path stringlengths 5 169 | owner stringlengths 2 34 | repo_id int64 1.49M 755M | is_fork bool 2
classes | languages_distribution stringlengths 16 1.68k ⌀ | content stringlengths 446 72k | issues float64 0 1.84k | main_language stringclasses 37
values | forks int64 0 5.77k | stars int64 0 46.8k | commit_sha stringlengths 40 40 | size int64 446 72.6k | name stringlengths 2 64 | license stringclasses 15
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/main/kotlin/day07/Day07.kt | mdenburger | 433,731,891 | false | {"Kotlin": 8573} | package day07
import java.io.File
import kotlin.math.abs
import kotlin.math.min
fun main() {
println("Answer 1: " + minimumFuel(::constantCost))
println("Answer 2: " + minimumFuel(::increasingCost))
}
fun minimumFuel(cost: (positions: List<Int>, position: Int) -> Int): Int {
val positions = File("src/main/kotlin/day07/day07-input.txt").readText().split(",").map { it.toInt() }
val min = positions.minOrNull()!!
val max = positions.maxOrNull()!!
return (min..max).fold(Int.MAX_VALUE) { minimum, position ->
min(cost(positions, position), minimum)
}
}
fun constantCost(positions: List<Int>, position: Int): Int =
positions.sumOf { abs(it - position) }
fun increasingCost(positions: List<Int>, position: Int): Int =
positions.sumOf {
val distance = abs(it - position)
(distance * (distance + 1)) shr 1 // sum of integers 1..N = N * (N - 1) / 2
}
| 0 | Kotlin | 0 | 0 | e890eec2acc2eea9c0432d092679aeb9de3f51b4 | 917 | aoc-2021 | MIT License |
src/com/aaron/helloalgorithm/algorithm/数组/_26_删除有序数组中的重复项.kt | aaronzzx | 431,740,908 | false | null | package com.aaron.helloalgorithm.algorithm.数组
import com.aaron.helloalgorithm.algorithm.LeetCode
import com.aaron.helloalgorithm.algorithm.Printer
/**
* # 26. 删除有序数组中的重复项
*
* 给你一个有序数组 nums ,请你 原地 删除重复出现的元素,使每个元素 只出现一次 ,返回删除后数组的新长度。
*
* 不要使用额外的数组空间,你必须在 原地 修改输入数组 并在使用 O(1) 额外空间的条件下完成。
*
* 示例 1:
*
* ```
* 输入:nums = [1,1,2]
* 输出:2, nums = [1,2]
* ```
*
* 解释:函数应该返回新的长度 2 ,并且原数组 nums 的前两个元素被修改为 1, 2 。不需要考虑数组中超出新长度后面的元素。
*
* 示例 2:
*
* ```
* 输入:nums = [0,0,1,1,1,2,2,3,3,4]
* 输出:5, nums = [0,1,2,3,4]
* ```
*
* 解释:函数应该返回新的长度 5 , 并且原数组 nums 的前五个元素被修改为 0, 1, 2, 3, 4 。不需要考虑数组中超出新长度后面的元素。
*
* 来源:力扣(LeetCode)
*
* 链接:[https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array]
*
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*
* @author <EMAIL>
* @since 2021/11/18
*/
class _26_删除有序数组中的重复项
private val NUMS = intArrayOf(0, 0, 1, 1, 1, 2, 2, 3, 3, 4)
fun LeetCode.数组.run_26_删除有序数组中的重复项_双指针(nums: IntArray = NUMS) {
val old = nums.contentToString()
val newSize = _26_删除有序数组中的重复项_双指针(nums)
Printer.print(
title = "删除有序数组中的重复项-双指针",
input = "nums = $old",
output = "$newSize, ${nums.copyOf(newSize).contentToString()}"
)
}
/**
* # 解法:双指针
*
* 当数组 nums 的长度大于 0 时,数组中至少包含一个元素,在删除重复元素之后也至少剩下一个元素,
* 因此下标 0 保持原状即可,从下标 1 开始删除重复元素。
*
* 通过 fast 指针遍历数组,每次都取当前 fast 索引和 fast - 1 索引进行比较,如果两个数不相等
* 则将当前 fast 值更新到 slow 位置,然后 slow 指针后移一位。
*
* 如果数组中没有重复元素,那么 slow 和 fast 一直都是相等的,只有当发现了重复元素后,slow 指针
* 原地踏步,这个时候的 slow 指针指向的值是重复值,需要通过 fast 指针寻找不同值将它替换掉,然后
* slow 指针后移,每次 slow 指针后移,它前面的值一定都是不重复的。
*
* T(n) = O(n); S(n) = O(1)
*/
fun LeetCode.数组._26_删除有序数组中的重复项_双指针(nums: IntArray): Int {
if (nums.isEmpty()) return 0
var slow = 1
var fast = 1
while (fast < nums.size) {
if (nums[fast] != nums[fast - 1]) {
nums[slow] = nums[fast]
++slow
}
++fast
}
return slow
} | 0 | Kotlin | 0 | 0 | 2d3d823b794fd0712990cbfef804ac2e138a9db3 | 3,022 | HelloAlgorithm | Apache License 2.0 |
archive/src/main/kotlin/com/grappenmaker/aoc/year20/Day14.kt | 770grappenmaker | 434,645,245 | false | {"Kotlin": 409647, "Python": 647} | package com.grappenmaker.aoc.year20
import com.grappenmaker.aoc.PuzzleSet
fun PuzzleSet.day14() = puzzle(day = 14) {
// Don't think I can generalize here
fun solve(solution: (memory: MutableMap<Long, Long>) -> Unit) =
mutableMapOf<Long, Long>().also(solution).values.sum().s()
fun solvePartOne() = solve { memory ->
var andMask = 0xFFFFFFFFFL
var orMask = 0L
inputLines.forEach { l ->
val (toSet, valuePart) = l.split(" = ")
if (toSet == "mask") {
andMask = 0xFFFFFFFFFL
orMask = 0L
valuePart.reversed().forEachIndexed { idx, c ->
when (c) {
'1' -> orMask = orMask or (1L shl idx)
'0' -> andMask = andMask xor (1L shl idx)
}
}
} else {
memory[toSet.drop(4).dropLast(1).toLong()] = valuePart.toLong() and andMask or orMask
}
}
}
fun solvePartTwo() = solve { memory ->
var orMask = 0L
val basicPerms = listOf(0xFFFFFFFFFL to 0L)
var permutations = basicPerms
inputLines.forEach { l ->
val (toSet, valuePart) = l.split(" = ")
if (toSet == "mask") {
orMask = 0L
permutations = basicPerms
valuePart.reversed().forEachIndexed { idx, c ->
val shifted = 1L shl idx
when (c) {
'1' -> orMask = orMask or shifted
'X' -> permutations = permutations
.flatMap { (a, o) -> listOf(a to (o or shifted), (a xor shifted) to o) }
}
}
} else {
val updated = toSet.drop(4).dropLast(1).toLong() or orMask
val value = valuePart.toLong()
permutations.forEach { (a, o) -> memory[updated and a or o] = value }
}
}
}
partOne = solvePartOne()
partTwo = solvePartTwo()
} | 0 | Kotlin | 0 | 7 | 92ef1b5ecc3cbe76d2ccd0303a73fddda82ba585 | 2,071 | advent-of-code | The Unlicense |
src/main/kotlin/day9/solver.kt | derekaspaulding | 317,756,568 | false | null | package day9
import java.io.File
fun solveFirstProblem(numbers: List<Long>, preambleLength: Int = 25): Long? = numbers
.subList(preambleLength, numbers.size)
.withIndex()
.find {
val (index, num) = it
val i2Start = index + 1
val end = index + preambleLength
for (i1 in index..end) {
for (i2 in i2Start..end) {
if (numbers[i1] + numbers[i2] == num) {
return@find false
}
}
}
true
}?.value
fun findSecondProblemSublist(numbers: List<Long>, target: Long): List<Long>? {
for (len in 2..numbers.size) {
for (i in 0..(numbers.size - len)) {
val subList = numbers.subList(i, i + len)
if (subList.reduce { acc, number -> acc + number} == target) {
return subList
}
}
}
return null
}
fun solveSecondProblem(numbers: List<Long>, preambleLength: Int = 25): Long? {
val target = solveFirstProblem(numbers, preambleLength) ?: return null
val subList = findSecondProblemSublist(numbers, target) ?: return null
val min = subList.minOrNull() ?: return null
val max = subList.maxOrNull() ?: return null
return min + max
}
fun main() {
val numbers = File("src/main/resources/day9/input.txt")
.useLines { it.toList() }
.map { it.toLong() }
val incorrectNumber = solveFirstProblem(numbers)
println("First number not following the rule: $incorrectNumber")
val weakness = solveSecondProblem(numbers)
println("XMAS-encryption weakness: $weakness")
} | 0 | Kotlin | 0 | 0 | 0e26fdbb3415fac413ea833bc7579c09561b49e5 | 1,613 | advent-of-code-2020 | MIT License |
src/day14/Day14.kt | GrzegorzBaczek93 | 572,128,118 | false | {"Kotlin": 44027} | package day14
import readInput
import utils.withStopwatch
fun main() {
val testInput = readInput("input14_test")
withStopwatch { println(part1(testInput)) }
withStopwatch { println(part2(testInput)) }
val input = readInput("input14")
withStopwatch { println(part1(input)) }
withStopwatch { println(part2(input)) }
}
private fun part1(input: List<String>) = solve1(input)
private fun part2(input: List<String>) = solve2(input)
private fun solve1(input: List<String>) {
val playground = Playground()
input.forEach { playground.addFromPath(it, Segment.Rock) }
var finished = false
var i = 0
while (!finished) {
finished = playground.generateSand(endYIndex = playground.getRanges().second.y)
i++
}
println("Number of sand: ${i - 1}")
}
private fun solve2(input: List<String>) {
val playground = Playground()
input.forEach { playground.addFromPath(it, Segment.Rock) }
var finished = false
var i = 0
while (!finished) {
finished = playground.generateSand()
i++
}
println("Number of sand: $i")
}
private fun print(playground: Playground) {
val (min, max) = playground.getRanges()
val map = playground.getMap()
(0..max.y + 2).forEach { y ->
(min.x - 2..max.x + 2).forEach { x ->
val current = Position(x, y)
when {
current == Position(500, 0) -> print(" + ")
map.containsKey(current) -> print(" ${map[current]!!.symbol} ")
else -> print(" . ")
}
}
println()
}
}
| 0 | Kotlin | 0 | 0 | 543e7cf0a2d706d23c3213d3737756b61ccbf94b | 1,601 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/test/kotlin/chapter5/solutions/ex7/listing.kt | DavidGomesh | 680,857,367 | false | {"Kotlin": 204685} | package chapter5.solutions.ex7
import chapter3.List
import chapter5.Stream
import chapter5.Stream.Companion.cons
import chapter5.Stream.Companion.empty
import chapter5.toList
import io.kotest.matchers.shouldBe
import io.kotest.core.spec.style.WordSpec
//tag::append[]
fun <A> Stream<A>.append(sa: () -> Stream<A>): Stream<A> =
foldRight(sa) { h, t -> cons({ h }, t) }
//end::append[]
class Solution7 : WordSpec({
//tag::map[]
fun <A, B> Stream<A>.map(f: (A) -> B): Stream<B> =
this.foldRight(
{ empty<B>() },
{ h, t -> cons({ f(h) }, t) })
//end::map[]
//tag::filter[]
fun <A> Stream<A>.filter(f: (A) -> Boolean): Stream<A> =
this.foldRight(
{ empty<A>() },
{ h, t -> if (f(h)) cons({ h }, t) else t() })
//end::filter[]
//tag::flatmap[]
fun <A, B> Stream<A>.flatMap(f: (A) -> Stream<B>): Stream<B> =
foldRight(
{ empty<B>() },
{ h, t -> f(h).append(t) })
//end::flatmap[]
"Stream.map" should {
"apply a function to each evaluated element in a stream" {
val s = Stream.of(1, 2, 3, 4, 5)
s.map { (it * 2).toString() }.toList() shouldBe
List.of("2", "4", "6", "8", "10")
}
"return an empty stream if no elements are found" {
empty<Int>().map { (it * 2).toString() } shouldBe empty()
}
}
"Stream.filter" should {
"""return all elements of a stream that conform
to a predicate""" {
val s = Stream.of(1, 2, 3, 4, 5)
s.filter { it % 2 == 0 }.toList() shouldBe
List.of(2, 4)
}
"return no elements of an empty stream" {
empty<Int>().filter { it % 2 == 0 }
.toList() shouldBe List.empty()
}
}
"Stream.append" should {
"append two streams to each other" {
val s1 = Stream.of(1, 2, 3)
val s2 = Stream.of(4, 5, 6)
s1.append { s2 }.toList() shouldBe
List.of(1, 2, 3, 4, 5, 6)
}
"append a stream to an empty stream" {
val s1 = empty<Int>()
val s2 = Stream.of(1, 2, 3)
s1.append { s2 }.toList() shouldBe List.of(1, 2, 3)
}
"append an empty stream to a stream" {
val s1 = Stream.of(1, 2, 3)
val s2 = empty<Int>()
s1.append { s2 }.toList() shouldBe List.of(1, 2, 3)
}
}
"Stream.flatMap" should {
"""apply a function that can fail to each evaluated
element in a stream""" {
val s = Stream.of(1, 2, 3, 4, 5)
s.flatMap { Stream.of("$it", "${it * 2}") }
.toList() shouldBe
List.of(
"1",
"2",
"2",
"4",
"3",
"6",
"4",
"8",
"5",
"10"
)
}
}
})
| 0 | Kotlin | 0 | 0 | 41fd131cd5049cbafce8efff044bc00d8acddebd | 3,064 | fp-kotlin | MIT License |
src/main/kotlin/io/dmitrijs/aoc2022/Day07.kt | lakiboy | 578,268,213 | false | {"Kotlin": 76651} | package io.dmitrijs.aoc2022
class Day07(input: List<String>) {
private val fs = readFs(input)
fun puzzle1() = fs
.flatten()
.map { it.size }
.filter { it <= 100_000 }
.sum()
fun puzzle2(): Int {
val taken = fs.size
val free = 70_000_000 - taken
val allocate = 30_000_000 - free
return fs
.flatten()
.map { it.size }
.sorted()
.first { it >= allocate }
}
private fun readFs(lines: List<String>): Dir {
val rootDir = Dir.root()
val pushd = mutableListOf<Dir>()
pushd.add(rootDir)
lines.drop(1).forEach { line ->
val workDir = pushd.last()
when {
line.startsWith("dir") -> workDir.addDir(line.substring(4))
line.startsWith("\$ ls") -> Unit
line.startsWith("\$ cd ..") -> pushd.removeLast()
line.startsWith("\$ cd") -> pushd.add(workDir.getDir(line.substring(5)))
else -> workDir.addFile(line.substringAfter(" "), line.substringBefore(" ").toInt())
}
}
return rootDir
}
private data class File(private val name: String, val size: Int)
private class Dir(
private val name: String,
private val dirs: MutableSet<Dir> = mutableSetOf(),
private val files: MutableSet<File> = mutableSetOf(),
) {
val size get(): Int = dirs.sumOf { it.size } + files.sumOf { it.size }
fun addDir(name: String) = dirs.add(Dir(name))
fun addFile(name: String, size: Int) = files.add(File(name, size))
fun getDir(name: String) = dirs.first { name == it.name }
fun flatten(): Sequence<Dir> {
val current = this
return sequence {
yield(current)
current.dirs.forEach { child -> yieldAll(child.flatten()) }
}
}
companion object {
fun root() = Dir("/")
}
}
}
| 0 | Kotlin | 0 | 1 | bfce0f4cb924834d44b3aae14686d1c834621456 | 2,023 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/Day12.kt | sushovan86 | 573,586,806 | false | {"Kotlin": 47064} | class HillClimbing private constructor(
private val areaElevationMap: MutableMap<Coordinate, Int>,
private val startCoordinate: Coordinate,
private val endCoordinate: Coordinate,
private val width: Int,
private val height: Int
) {
data class Coordinate(val x: Int = 0, val y: Int = 0)
private val visited = mutableSetOf<Coordinate>()
private val queue = ArrayDeque<Coordinate>()
private val parentCoordinateMap = mutableMapOf<Coordinate, Coordinate>()
private fun initialize(start: Coordinate) {
visited.clear()
parentCoordinateMap.clear()
queue.clear()
queue += start
visited += start
}
private fun getAdjacentCoordinates(coordinate: Coordinate) = buildList(4) {
if (coordinate.y > 0) {
add(coordinate.copy(y = coordinate.y - 1)) // UP
}
if (coordinate.y < height - 1) {
add(coordinate.copy(y = coordinate.y + 1)) // DOWN
}
if (coordinate.x > 0) {
add(coordinate.copy(x = coordinate.x - 1)) // LEFT
}
if (coordinate.x < width - 1) {
add(coordinate.copy(x = coordinate.x + 1)) // RIGHT
}
}
companion object {
fun load(inputList: List<String>): HillClimbing {
val yEnd = inputList.size
val xEnd = inputList[0].length
val areaElevationMap = mutableMapOf<Coordinate, Int>()
var startCoordinate = Coordinate()
var endCoordinate = Coordinate()
for ((yCoordinate, inputLine) in inputList.withIndex()) {
for ((xCoordinate, elevation) in inputLine.withIndex()) {
when (elevation) {
'S' -> {
startCoordinate = Coordinate(xCoordinate, yCoordinate)
areaElevationMap[startCoordinate] = 0
}
'E' -> {
endCoordinate = Coordinate(xCoordinate, yCoordinate)
areaElevationMap[endCoordinate] = 'z' - 'a'
}
else -> areaElevationMap[Coordinate(xCoordinate, yCoordinate)] = elevation - 'a'
}
}
}
return HillClimbing(areaElevationMap, startCoordinate, endCoordinate, xEnd, yEnd)
}
}
fun findShortestPath(start: Coordinate = startCoordinate): Int {
initialize(start)
while (queue.isNotEmpty()) {
val currentCoordinate = queue.removeFirst()
if (currentCoordinate == endCoordinate) {
return findDistanceToStart(currentCoordinate, start)
}
val currentElevation = areaElevationMap.getValue(currentCoordinate)
getAdjacentCoordinates(currentCoordinate)
.filter {
(it !in visited) &&
(areaElevationMap.getValue(it) - currentElevation <= 1)
}
.forEach {
queue += it
visited += it
parentCoordinateMap[it] = currentCoordinate
}
}
return Int.MAX_VALUE
}
private fun findDistanceToStart(currentCoordinate: Coordinate, start: Coordinate): Int {
var temp: Coordinate? = currentCoordinate
var distance = 0
while (temp != start) {
temp = parentCoordinateMap[temp]
distance++
}
return distance
}
fun findShortestPathForLowestStart() = areaElevationMap
.filter { it.value == 0 }
.map { findShortestPath(it.key) }
.min()
}
fun main() {
val testInput = readInput("Day12_test")
val testHillClimbing = HillClimbing.load(testInput)
check(testHillClimbing.findShortestPath() == 31)
check(testHillClimbing.findShortestPathForLowestStart() == 29)
val actualInput = readInput("Day12")
val actualHillClimbing = HillClimbing.load(actualInput)
println(actualHillClimbing.findShortestPath())
println(actualHillClimbing.findShortestPathForLowestStart())
} | 0 | Kotlin | 0 | 0 | d5f85b6a48e3505d06b4ae1027e734e66b324964 | 4,174 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/Day12.kt | jcornaz | 573,137,552 | false | {"Kotlin": 76776} | object Day12 {
@Suppress("UNUSED_PARAMETER")
fun part1(input: String): Long = TODO()
@Suppress("UNUSED_PARAMETER")
fun part2(input: String): Long = TODO()
private const val START_CHARACTER = 'S'
private const val GOAL_CHARACTER = 'E'
fun findPath(input: String): String {
val map = parseMap(input)
var currentState = findInitialState(map)
val maxY = map.size - 1
val maxX = map.first().size - 1
val outputMap: List<MutableList<Char>> = map.map { it.mapTo(mutableListOf()) { '.' } }
while (map[currentState.y][currentState.x] != GOAL_CHARACTER) {
print(map[currentState.y][currentState.x])
val (direction, nextState) = getSuccessors(currentState, maxX, maxY)
// .filter { (_, coordinate) ->
// map[coordinate.y][coordinate.x] == GOAL_CHARACTER || map[coordinate.y][coordinate.x] - map[currentState.y][currentState.x] <= 1
// }
.maxBy { (_, coordinate) ->
val value = map[coordinate.y][coordinate.x]
if (value == GOAL_CHARACTER) 'z' + 1 else value
}
outputMap[currentState.y][currentState.x] = direction.char
currentState = nextState
}
outputMap[currentState.y][currentState.x] = GOAL_CHARACTER
return outputMap.joinToString(separator = "\n") { it.joinToString(separator = "")}
}
private fun parseMap(input: String): List<List<Char>> = input.lines().map { it.toList() }
private fun findInitialState(map: List<List<Char>>) : Coordinate =
map.withIndex()
.map { (row, l) ->
Coordinate(l.withIndex().find { (_, c) -> c == START_CHARACTER }!!.index, row)
}
.first()
private fun getSuccessors(currentCoordinate: Coordinate, maxX: Int, maxY: Int) = Direction.values()
.map { it to it.getNextSquare(currentCoordinate) }
.filter { (_, target) -> target.x in (0 .. maxX) && target.y in (0 .. maxY) }
class Coordinate(val x: Int, val y: Int)
enum class Direction(val char: Char) {
UP('^') {
override fun getNextSquare(currentCoordinate: Coordinate) =
Coordinate(currentCoordinate.x, currentCoordinate.y - 1)
},
DOWN('v') {
override fun getNextSquare(currentCoordinate: Coordinate) =
Coordinate(currentCoordinate.x, currentCoordinate.y + 1)
},
LEFT('<') {
override fun getNextSquare(currentCoordinate: Coordinate): Coordinate =
Coordinate(currentCoordinate.x - 1, currentCoordinate.y)
},
RIGHT('>') {
override fun getNextSquare(currentCoordinate: Coordinate) =
Coordinate(currentCoordinate.x + 1, currentCoordinate.y)
};
abstract fun getNextSquare(currentCoordinate: Coordinate) : Coordinate
}
}
| 1 | Kotlin | 0 | 0 | 979c00c4a51567b341d6936761bd43c39d314510 | 2,963 | aoc-kotlin-2022 | The Unlicense |
src/me/bytebeats/algo/kt/Solution8.kt | bytebeats | 251,234,289 | false | null | package me.bytebeats.algo.kt
import me.bytebeats.algo.kt.design.CustomFunction
import me.bytebeats.algs.ds.ListNode
import me.bytebeats.algs.ds.TreeNode
class Solution8 {
fun pathSum(root: TreeNode?, sum: Int): Int {//面试题04.12
if (root == null) {
return 0
}
return pathSum(root, 0, sum) + pathSum(root?.left, sum) + pathSum(root?.right, sum)
}
private fun pathSum(root: TreeNode?, subSum: Int, sum: Int): Int {
if (root == null) {
return 0
}
var count = 0
val nextSum = subSum + root.`val`
if (nextSum == sum) {
count++
}
count += pathSum(root.left, nextSum, sum)
count += pathSum(root.right, nextSum, sum)
return count
}
fun twoCitySchedCost(costs: Array<IntArray>): Int {//1029
var ans = 0
val half = costs.size / 2
costs.sortBy { it[0] - it[1] }
for (i in costs.indices) {
if (i < half) {
ans += costs[i][0]
} else {
ans += costs[i][1]
}
}
return ans
}
fun reverseString(s: CharArray): Unit {//344
var left = 0
var right = s.lastIndex
var ch = ' '
while (left < right) {
ch = s[left]
s[left] = s[right]
s[right] = ch
left++
right--
}
}
fun reverseVowels(s: String): String {//557
val chArr = s.toCharArray()
var i = 0
var j = s.lastIndex
var ch = ' '
while (i < j) {
while (i < j && !isVowel(chArr[i])) {
i++
}
while (i < j && !isVowel(chArr[j])) {
j--
}
if (i < j) {
ch = chArr[i]
chArr[i] = chArr[j]
chArr[j] = ch
i++
j--
}
}
return String(chArr)
}
private fun isVowel(ch: Char): Boolean {
return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U'
}
fun removeVowels(S: String): String {//1119
val ans = StringBuilder()
for (c in S) {
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
continue
} else {
ans.append(c)
}
}
return ans.toString()
}
fun reverseStr(s: String, k: Int): String {//541
val ans = s.toCharArray()
var left = 0
while (left < s.length) {
if (s.length - left <= k) {
reverse(ans, left, s.length - 1)
} else {
reverse(ans, left, left + k - 1)
}
left += 2 * k
}
return String(ans)
}
private fun reverse(charArray: CharArray, left: Int, right: Int) {
var i = left
var j = right
var ch = ' '
while (i < j) {
ch = charArray[i]
charArray[i] = charArray[j]
charArray[j] = ch
i++
j--
}
}
fun countLetters(S: String): Int {//1180
var ans = 0
var i = 0
var j = 0
while (i < S.length) {
j = i
while (j < S.length && S[j] == S[i]) {
j++
}
ans += count(j - i)
i = j
}
return ans
}
private fun count(n: Int): Int = n * (n + 1) / 2
fun customSortString(S: String, T: String): String {//791
val map = mutableMapOf<Char, Int>()
for (i in S.indices) {
map[S[i]] = i
}
return String(T.toList().sortedBy { map[it] ?: -1 }.toCharArray())
}
fun complexNumberMultiply(a: String, b: String): String {//537
val ans = StringBuilder()
val cn1 = extract(a)
val cn2 = extract(b)
val r = cn1[0] * cn2[0] - cn1[1] * cn2[1]
val v = cn1[1] * cn2[0] + cn1[0] * cn2[1]
ans.append(r)
ans.append('+')
ans.append(v)
ans.append('i')
return ans.toString()
}
private fun extract(cn: String): List<Int> = cn.split("+").map {
if (it.endsWith('i')) {
it.substring(0, it.lastIndex)
} else {
it
}
}.map { it.toInt() }
fun maximumSwap(num: Int): Int {//670
val ans = num.toString().toCharArray()
var max = '0'
var tmp = '0'
for (i in 0 until ans.lastIndex) {
max = ans.drop(i + 1).maxOfOrNull { it } ?: '0'
if (ans[i] < max) {
for (j in ans.lastIndex downTo i + 1) {
if (ans[j] == max) {
tmp = ans[i]
ans[i] = ans[j]
ans[j] = tmp
return String(ans).toInt()
}
}
}
}
return num
}
fun longestConsecutive(nums: IntArray): Int {//128
val set = mutableSetOf<Int>()
for (num in nums) {
set.add(num)
}
var ans = 0
var curNum = 0
var curStreak = 0
for (num in set) {
if (!set.contains(num - 1)) {
curNum = num
curStreak = 1
while (set.contains(curNum + 1)) {
curNum++
curStreak++
}
ans = ans.coerceAtLeast(curStreak)
}
}
return ans
}
fun reconstructQueue(people: Array<IntArray>): Array<IntArray> {//406
val queue = people.sortedWith(Comparator { o1, o2 ->
if (o1[0] == o2[0])
o1[1] - o2[1]
else
o2[0] - o1[0]
})
val list = mutableListOf<IntArray>()
for (q in queue) {
list.add(q[1], q)
}
return list.toTypedArray()
}
fun findSolution(customfunction: CustomFunction, z: Int): List<List<Int>> {//1237
val ans = mutableListOf<List<Int>>()
var i = 1
var j = 1000
var res = 0
while (i <= z && j >= 1) {
res = customfunction.f(i, j)
if (res < z) {
i++
} else if (res > z) {
j--
} else {
ans.add(listOf(i, j))
i++
j++
}
}
return ans
}
fun shuffle(nums: IntArray, n: Int): IntArray {//5428, 1470
val list = mutableListOf<Int>()
for (i in 0 until n) {
list.add(nums[i])
list.add(nums[i + n])
}
return list.toIntArray()
}
fun getStrongest(arr: IntArray, k: Int): IntArray {//5429, 1471
val ans = IntArray(k)
arr.sort()
val median = arr[(arr.size - 1) / 2]
val sorted = arr.reversed().sortedByDescending { Math.abs(it - median) }
for (i in 0 until k) {
ans[i] = sorted[i]
}
return ans
}
fun change(amount: Int, coins: IntArray): Int {//512
val dp = IntArray(amount + 1)
dp[0] = 1
for (coin in coins) {
for (i in coin..amount) {
dp[i] += dp[i - coin]
}
}
return dp[amount]
}
fun equationsPossible(equations: Array<String>): Boolean {//990
val parent = IntArray(26) { it }
for (e in equations) {
if (e[1] == '=') {
union(parent, e[0] - 'a', e[3] - 'a')
}
}
for (e in equations) {
if (e[1] == '!') {
if (find(parent, e[0] - 'a') == find(parent, e[3] - 'a')) {
return false
}
}
}
return true
}
private fun union(parent: IntArray, index1: Int, index2: Int) {
parent[find(parent, index1)] = parent[find(parent, index2)]
}
private fun find(parent: IntArray, index: Int): Int {
var i = index
while (parent[i] != i) {
parent[i] = parent[parent[i]]
i = parent[i]
}
return i
}
fun isPowerOfTwo(n: Int): Boolean {//231
if (n < 1) {
return false
}
var num = n
var has1 = false
while (num > 1) {
if (has1) {
return false
}
if (num and 1 == 1) {
has1 = true
}
num = num shr 1
}
return true
}
fun translateNum(num: Int): Int {//面试题46
var ans = 1
val src = num.toString()
var p = 0
var q = 0
var pre = ""
for (i in src.indices) {
p = q
q = ans
ans = 0
ans += q
if (i == 0) {
continue
}
pre = src.substring(i - 1, i + 1)
if (pre <= "25" && pre >= "10") {
ans += p
}
}
return ans
}
fun isSubsequence(s: String, t: String): Boolean {//392
var count = 0
var i = 0
var j = 0
while (i < s.length && j < t.length) {
if (s[i] == t[j]) {
count++
i++
j++
} else {
j++
}
}
return count == s.length
}
fun getLonelyNodes(root: TreeNode?): List<Int> {//1469
val ans = mutableListOf<Int>()
dfs(root, ans)
return ans
}
fun dfs(node: TreeNode?, ans: MutableList<Int>) {
if (node == null || node.left == null && node.right == null) {
return
}
if (node.left != null && node.right == null) {
ans.add(node.left.`val`)
dfs(node.left, ans)
} else if (node.left == null && node.right != null) {
ans.add(node.right.`val`)
dfs(node.right, ans)
} else {
dfs(node.left, ans)
dfs(node.right, ans)
}
}
fun threeSum(nums: IntArray): List<List<Int>> {//15
val ans = mutableListOf<MutableList<Int>>()
nums.sort()
var i = 0
while (i < nums.size - 2) {
var left = i + 1
var right = nums.size - 1
var sum = 0
while (left < right) {
sum = nums[i] + nums[left] + nums[right]
if (sum < 0) {
left++
} else if (sum > 0) {
right--
} else {
val e = mutableListOf<Int>()
e.add(nums[i])
e.add(nums[left])
e.add(nums[right])
ans.add(e)
while (left < right && nums[left] == nums[left + 1]) {
left++
}
while (left < right && nums[right] == nums[right - 1]) {
right--
}
left++
right--
}
}
while (i < nums.size - 2 && nums[i] == nums[i + 1]) {
i++
}
i++
}
return ans
}
fun finalPrices(prices: IntArray): IntArray {//1475
var j = -1
for (i in prices.indices) {
j = -1
for (k in i + 1 until prices.size) {
if (prices[k] <= prices[i]) {
j = k
break
}
}
if (j != -1) {
prices[i] -= prices[j]
}
}
return prices
}
fun deleteNodes(head: ListNode?, m: Int, n: Int): ListNode? {//1474
var p = head
var k = 0
while (p != null) {
k = m - 1
while (p?.next != null && k > 0) {
p = p?.next
k--
}
k = n
while (p?.next != null && k > 0) {
p.next = p.next.next
k--
}
p = p?.next
}
return head
}
fun runningSum(nums: IntArray): IntArray {//1480
for (i in 1 until nums.size) {
nums[i] += nums[i - 1]
}
return nums
}
fun findLeastNumOfUniqueInts(arr: IntArray, k: Int): Int {
val map = mutableMapOf<Int, Int>()
arr.forEach { map.compute(it) { _, v -> if (v == null) 1 else v + 1 } }
val sorted = map.entries.sortedBy { it.value }
var kk = k
for (entry in sorted) {
if (kk >= entry.value) {
kk -= entry.value
map.remove(entry.key)
} else {
break
}
}
return map.size
}
fun findBestValue(arr: IntArray, target: Int): Int {//1300
arr.sort()
var sum = 0
for (i in arr.indices) {
val x = (target - sum) / (arr.size - i)
if (x < arr[i]) {
val t = (target - sum).toDouble() / (arr.size - i)
return if (t - x > .5) {
x + 1
} else {
x
}
}
sum += arr[i]
}
return arr.last()
}
fun longestCommonPrefix(strs: Array<String>): String {//14
var prefix = ""
val min = strs.map { it.length }.minOfOrNull { it } ?: 0
for (i in 1..min) {
var flag = true
for (j in 1 until strs.size) {
if (strs[j].substring(0, i) != strs[j - 1].substring(0, i)) {
flag = false
break
}
}
if (flag) {
prefix = strs[0].substring(0, i)
}
}
return prefix
}
var longest = 0
fun longestUnivaluePath(root: TreeNode?): Int {//687
longest = 0
pathLength(root)
return longest
}
private fun pathLength(root: TreeNode?): Int {
if (root == null) {
return 0
}
val left = pathLength(root.left)
val right = pathLength(root.right)
var pathLeft = 0
var pathRight = 0
if (root.left != null && root.left.`val` == root.`val`) {
pathLeft += (left + 1)
}
if (root.right != null && root.right.`val` == root.`val`) {
pathRight += (right + 1)
}
longest = longest.coerceAtLeast(pathLeft + pathRight)
return pathLeft.coerceAtLeast(pathRight)
}
fun licenseKeyFormatting(S: String, K: Int): String {//482
val ans = StringBuilder()
var kk = K
for (i in S.lastIndex downTo 0) {
if (S[i] != '-') {
if (kk == 0) {
kk = K
ans.append('-')
}
if (S[i].isDigit()) {
ans.append(S[i])
kk--
} else if (S[i].isLetter()) {
ans.append(S[i].toUpperCase())
kk--
}
}
}
return ans.reversed().toString()
}
fun constructRectangle(area: Int): IntArray {//492
var l = Math.ceil(Math.sqrt(area.toDouble())).toInt()
for (i in l..area) {
if (area % i == 0) {
return intArrayOf(i, area / i)
}
}
return intArrayOf()
}
fun validIPAddress(IP: String): String {//468
if (IP.contains(".") && isValidIpV4(IP)) {
return "IPv4"
} else if (IP.contains(":") && isValidIpV6(IP)) {
return "IPv6"
} else {
return "Neither"
}
}
private fun isValidIpV4(ip: String): Boolean {
val segs = ip.split(".")
if (segs.size != 4) {
return false
}
for (seg in segs) {
if (!isValidIPv4Seg(seg)) {
return false
}
}
return true
}
private fun isValidIPv4Seg(seg: String): Boolean {//468
if (seg.isEmpty() || seg.length > 3) {
return false
}
for (c in seg) {
if (!isValidIPv4Char(c)) {
return false
}
}
val num = seg.toInt()
if (num > 255) {
return false
}
if (seg.length == 2 && num < 10 || seg.length == 3 && num < 100) {
return false
}
return true
}
private fun isValidIPv4Char(ch: Char): Boolean = ch in '0'..'9'
private fun isValidIpV6(ip: String): Boolean {
val segs = ip.split(":")
if (segs.size != 8) {
return false
}
for (seg in segs) {
if (!isValidIPv6Seg(seg)) {
return false
}
}
return true
}
private fun isValidIPv6Seg(seg: String): Boolean {
if (seg.isEmpty() || seg.length > 4) {
return false
}
for (c in seg) {
if (!isValidIPv6Char(c)) {
return false
}
}
return true
}
private fun isValidIPv6Char(ch: Char): Boolean = ch in '0'..'9' || ch in 'a'..'f' || ch in 'A'..'F'
fun solve(board: Array<CharArray>): Unit {//130
if (board.isNotEmpty() && board[0].isNotEmpty()) {
val row = board.size
val column = board[0].size
var i = 0
for (j in 0 until column) {
if (board[i][j] == 'O') {
color(board, i, j)
}
}
for (j in 0 until row) {
if (board[j][i] == 'O') {
color(board, j, i)
}
}
i = board.lastIndex
for (j in 0 until column) {
if (board[i][j] == 'O') {
color(board, i, j)
}
}
i = board[0].lastIndex
for (j in 0 until row) {
if (board[j][i] == 'O') {
color(board, j, i)
}
}
for (i in 0 until row) {
for (j in 0 until column) {
if (board[i][j] == 'O') {
board[i][j] = 'X'
} else if (board[i][j] == '#') {
board[i][j] = 'O'
}
}
}
}
}
private fun color(board: Array<CharArray>, x: Int, y: Int) {
if (x < 0 || y < 0 || x >= board.size || y >= board[0].size) {
return
}
board[x][y] = '#'
if (x > 0 && board[x - 1][y] == 'O') {
color(board, x - 1, y)
}
if (x < board.size - 1 && board[x + 1][y] == 'O') {
color(board, x + 1, y)
}
if (y > 0 && board[x][y - 1] == 'O') {
color(board, x, y - 1)
}
if (y < board[0].size - 1 && board[x][y + 1] == 'O') {
color(board, x, y + 1)
}
}
fun recoverFromPreorder(S: String): TreeNode? {//1028
val path = mutableListOf<TreeNode>()
var pos = 0
while (pos < S.length) {
var level = 0
while (S[pos] == '-') {
level++
pos++
}
var value = 0
while (pos < S.length && S[pos].isDigit()) {
value *= 10
value += S[pos] - '0'
pos++
}
val node = TreeNode(value)
if (level == path.size) {
if (path.isNotEmpty()) {
path.last()?.left = node
}
} else {
while (level != path.size) {
path.removeAt(path.lastIndex)
}
path.last()?.right = node
}
path.add(node)
}
while (path.size > 1) {
path.removeAt(path.lastIndex)
}
return path.last()
}
fun hIndex(citations: IntArray): Int {//274
citations.sort()
// var ans = 0
// for (i in citations.indices) {
// if (citations.size - i <= citations[i]) {
// ans = ans.coerceAtLeast((citations.size - i).coerceAtMost(citations[i]))
// }
// }
// return ans
val s = citations.size
if (s == 0) {
return 0
}
var l = 0
var h = s - 1
var mid = 0
while (l < h) {
mid = l + (h - l) / 2
if (s - mid > citations[mid]) {
l = mid + 1
} else if (s - mid <= citations[mid]) {
h = mid
}
}
return citations[l].coerceAtMost(s - l)
}
fun hIndex1(citations: IntArray): Int {//275
var ans = 0
for (i in citations.indices) {
if (citations.size - i <= citations[i]) {
ans = ans.coerceAtLeast((citations.size - i).coerceAtMost(citations[i]))
}
}
return ans
}
fun hIndex2(citations: IntArray): Int {//275
val s = citations.size
if (s == 0) {
return 0
}
var l = 0
var h = s - 1
var mid = 0
while (l < h) {
mid = l + (h - l) / 2
if (s - mid > citations[mid]) {
l = mid + 1
} else if (s - mid <= citations[mid]) {
h = mid
}
}
return citations[l].coerceAtMost(s - l)
}
private val EMPTY = Int.MAX_VALUE
private val GATE = 0
private val directions = arrayOf(arrayOf(1, 0), arrayOf(-1, 0), arrayOf(0, 1), arrayOf(0, -1))
fun wallsAndGates(rooms: Array<IntArray>): Unit {//286
if (rooms.isNotEmpty() && rooms[0].isNotEmpty()) {
val row = rooms.size
val column = rooms[0].size
val q = mutableListOf<IntArray>()
for (i in 0 until row) {
for (j in 0 until column) {
if (rooms[i][j] == GATE) {
q.add(intArrayOf(i, j))
}
}
}
while (q.isNotEmpty()) {
val point = q.removeAt(0)
for (d in directions) {
val r = point[0] + d[0]
val c = point[1] + d[1]
if (r < 0 || c < 0 || r >= row || c >= column || rooms[r][c] != EMPTY) {
continue
}
rooms[r][c] = rooms[point[0]][point[1]] + 1
q.add(intArrayOf(r, c))
}
}
}
}
fun trimBST(root: TreeNode?, L: Int, R: Int): TreeNode? {//669
if (root == null) {
return null
}
if (root.`val` > R) {
return trimBST(root.left, L, R)
}
if (root.`val` < L) {
return trimBST(root.right, L, R)
}
root.left = trimBST(root.left, L, R)
root.right = trimBST(root.right, L, R)
return root
}
fun longestDupSubstring(S: String): String {//1044
val size = S.length
val nums = IntArray(size)
for (i in S.indices) {
nums[i] = S[i] - 'a'
}
val modulus = Math.pow(2.0, 32.0).toLong()
var left = 1
var right = size
var mid = 0
while (left < right) {
mid = left + (right - left) / 2
if (search(mid, modulus, nums) > -1) {
left = mid + 1
} else {
right = mid
}
}
val start = search(left - 1, modulus, nums)
if (start > -1) {
return S.substring(start, start + left - 1)
} else {
return ""
}
}
private fun search(length: Int, modulus: Long, nums: IntArray): Int {
var hash = 0L
for (i in 0 until length) {
hash = (hash * 26 + nums[i]) % modulus
}
val seen = mutableSetOf<Long>()
seen.add(hash)
var aL = 1L
for (i in 1..length) {
aL = (aL * 26L) % modulus
}
for (start in 1..nums.size - length) {
hash = (hash * 26 - nums[start - 1] * aL % modulus + modulus) % modulus
hash = (hash + nums[start + length - 1]) % modulus
if (seen.contains(hash)) return start
seen.add(hash)
}
return -1
}
fun isMatch(s: String, p: String): Boolean {//10
val m = s.length
val n = p.length
val f = Array(m + 1) { BooleanArray(n + 1) { false } }
f[0][0] = true
for (i in 0..m) {
for (j in 1..n) {
if (p[j - 1] == '*') {
f[i][j] = f[i][j - 2]
if (matches(s, p, i, j - 1)) {
f[i][j] = f[i][j] || f[i - 1][j]
}
} else {
if (matches(s, p, i, j)) {
f[i][j] = f[i - 1][j - 1]
}
}
}
}
return f[m][n]
}
private fun matches(s: String, p: String, i: Int, j: Int): Boolean {
if (i == 0) return false
if (p[j - 1] == '.') return true
return s[i - 1] == p[j - 1]
}
fun isMatch1(s: String, p: String): Boolean {//44
val m = s.length
val n = p.length
var sIdx = 0
var pIdx = 0
var startIdx = -1
var sTmpIdx = -1
while (sIdx < m) {
// If the pattern caracter = string character
// or pattern character = '?'
if (pIdx < n && (p[pIdx] == '?' || s[sIdx] == p[pIdx])) {
++sIdx
++pIdx
}// If pattern character = '*'
else if (pIdx < n && p[pIdx] == '*') {
// Check the situation
// when '*' matches no characters
startIdx = pIdx
sTmpIdx = sIdx
++pIdx
} // If pattern character != string character
// or pattern is used up
// and there was no '*' character in pattern
else if (startIdx == -1) {
return false
}
// If pattern character != string character
// or pattern is used up
// and there was '*' character in pattern before
else {
// Backtrack: check the situation
// when '*' matches one more character
pIdx = startIdx + 1
sIdx = sTmpIdx + 1
sTmpIdx = sIdx
}
}
// The remaining characters in the pattern should all be '*' characters
for (i in pIdx until n) {
if (p[i] != '*') return false
}
return true
}
fun getPermutation(n: Int, k: Int): String {//60
val factorials = IntArray(n)
val nums = mutableListOf<Int>()
factorials[0] = 1
nums.add(1)
for (i in 1 until n) {
factorials[i] = i * factorials[i - 1]
nums.add(i + 1)
}
var kk = k - 1
val ans = StringBuilder()
var idx = 0
for (i in n - 1 downTo 0) {
idx = kk / factorials[i]
kk -= idx * factorials[i]
ans.append(nums[idx])
nums.removeAt(idx)
}
return ans.toString()
}
fun calculateMinimumHP(dungeon: Array<IntArray>): Int {//174
if (dungeon.isNotEmpty() && dungeon[0].isNotEmpty()) {
val row = dungeon.size
val column = dungeon[0].size
val dp = Array(row) { IntArray(column) }
dp[row - 1][column - 1] = 0.coerceAtLeast(-dungeon[row - 1][column - 1])
for (i in row - 2 downTo 0) {
val needMin = dp[i + 1][column - 1] - dungeon[i][column - 1]
dp[i][column - 1] = 0.coerceAtLeast(needMin)
}
for (j in column - 2 downTo 0) {
val needMin = dp[row - 1][j + 1] - dungeon[row - 1][j]
dp[row - 1][j] = 0.coerceAtLeast(needMin)
}
for (i in row - 2 downTo 0) {
for (j in column - 2 downTo 0) {
val needMin = dp[i + 1][j].coerceAtMost(dp[i][j + 1]) - dungeon[i][j]
dp[i][j] = 0.coerceAtLeast(needMin)
}
}
return dp[0][0] + 1
}
return 0
}
fun patternMatching(pattern: String, value: String): Boolean {//面试题16.18
var countA = 0
var countB = 0
for (ch in pattern) {
if (ch == 'a') {
++countA
} else {
++countB
}
}
var ptn = pattern
if (countA < countB) {
val tmp = countA
countA = countB
countB = tmp
val chArr = pattern.toCharArray()
for (i in chArr.indices) {
chArr[i] = if (chArr[i] == 'a') 'b' else 'a'
}
ptn = String(chArr)
}
if (value.isEmpty()) {
return countA == 0
}
if (ptn.isEmpty()) {
return false
}
var lenA = 0
while (lenA * countA <= value.length) {
val left = value.length - lenA * countA
if (countB == 0 && left == 0 || countB != 0 && left % countB == 0) {
val len_b = if (countB == 0) 0 else left / countB
var pos = 0
var correct = true
var valA = ""
var valB = ""
for (ch in ptn) {
if (ch == 'a') {
val sub = value.substring(pos, pos + lenA)
if (valA.isEmpty()) {
valA = sub
} else if (valA != sub) {
correct = false
break
}
pos += lenA
} else {
val sub = value.substring(pos, pos + len_b)
if (valB.isEmpty()) {
valB = sub
} else if (valB != sub) {
correct = false
break
}
pos += len_b
}
}
if (correct && valA != valB) {
return true
}
}
++lenA
}
return false
}
fun singleNumber(nums: IntArray): Int {//137
var seen1 = 0
var seen2 = 0
for (n in nums) {
seen1 = seen2.inv() and (seen1 xor n)
seen2 = seen1.inv() and (seen2 xor n)
}
return seen1
}
fun findContentChildren(g: IntArray, s: IntArray): Int {//455
g.sort()
s.sort()
var i = 0
var j = 0
var ans = 0
while (i < g.size && j < s.size) {
if (g[i] > s[j]) {
while (j < s.size && g[i] > s[j]) {
++j
}
if (j < s.size) {
++i
++j
++ans
}
} else {
++i
++j
++ans
}
}
return ans
}
fun findRadius(houses: IntArray, heaters: IntArray): Int {//475
houses.sort()
heaters.sort()
var ans = 0
var k = 0
for (i in houses.indices) {
var radius = Int.MAX_VALUE
for (j in k until heaters.size) {
k = if (houses[i] >= heaters[j]) j else k
radius = radius.coerceAtMost(Math.abs(houses[i] - heaters[j]))
if (houses[i] < heaters[j]) break
}
ans = ans.coerceAtLeast(radius)
}
return ans
}
fun countNodes(root: TreeNode?): Int {//222
if (root == null) return 0
val depth = depthOfCompleteBT(root)
if (depth == 0) return 1
var left = 1
var right = Math.pow(2.0, depth.toDouble()).toInt() - 1
var pivot = 0
while (left <= right) {
pivot = left + (right - left) / 2
if (exists(pivot, depth, root)) left = pivot + 1
else right = pivot - 1
}
return Math.pow(2.0, depth.toDouble()).toInt() - 1 + left
}
private fun depthOfCompleteBT(root: TreeNode?): Int {
var depth = 0
var p = root?.left
while (p != null) {
++depth
p = p.left
}
return depth
}
private fun exists(idx: Int, depth: Int, node: TreeNode?): Boolean {
var left = 0
var right = Math.pow(2.0, depth.toDouble()).toInt() - 1
var pivot = 0
var p = node
for (i in 0 until depth) {
pivot = left + (right - left) / 2
if (idx <= pivot) {
p = p?.left
right = pivot
} else {
p = p?.right
left = pivot + 1
}
}
return p != null
}
fun xorOperation(n: Int, start: Int): Int {//1486
var xorval = 0
for (i in 0 until n) {
xorval = xorval xor (start + 2 * i)
}
return xorval
}
fun getFolderNames(names: Array<String>): Array<String> {
val map = mutableMapOf<String, Int>()
for (i in names.indices) {
if (map.containsKey(names[i])) {
map.compute(names[i]) { _, v -> if (v == null) 1 else v + 1 }
var j = map[names[i]]!! - 1
var tmp = "${names[i]}($j)"
while (map.containsKey(tmp)) {
++j
tmp = "${names[i]}($j)"
}
names[i] = tmp
} else {
map[names[i]] = 1
}
}
return names
}
} | 0 | Kotlin | 0 | 1 | 7cf372d9acb3274003bb782c51d608e5db6fa743 | 34,384 | Algorithms | MIT License |
src/commonMain/kotlin/AI.kt | bdm2505 | 403,340,025 | false | {"Kotlin": 33540, "Shell": 1493} | import kotlin.random.Random
fun Board.getBestCourse(mins:Boolean = true): Pair<Int, Board.Turn>? {
var bestScore = Int.MAX_VALUE
val courses = mutableListOf<Board.Turn>()
getAllCourse(colorCourse).forEach {
val nextBoard = copy()
nextBoard.move(it.start, it.end)
var sc = nextBoard.score()
if(!mins)
sc = -sc
if (sc == bestScore)
courses.add(it)
if (sc < bestScore){
bestScore = sc
courses.clear()
courses.add(it)
}
}
if (courses.isEmpty())
return null
return (if(mins) bestScore else -bestScore) to courses[Random.nextInt(courses.size)]
}
fun Board.calculateRec(gl:Int, me: Boolean = true): Pair<Int, Board.Turn>? {
if(gl == 0) return getBestCourse(me)
var bestScore = Int.MAX_VALUE
val courses = mutableListOf<Board.Turn>()
getAllCourse(colorCourse).map{
val nextBoard = copy()
nextBoard.move(it.start, it.end)
var sc1 = nextBoard.score()
if(!me)
sc1 = -sc1
if (sc1 == bestScore)
courses.add(it)
if (sc1 < bestScore){
bestScore = sc1
courses.clear()
courses.add(it)
}
val res = nextBoard.calculateRec(gl - 1, !me)
res?.let { pair ->
var sc = pair.first
if (!me)
sc = -sc
if (sc == bestScore)
courses.add(it)
if (sc < bestScore) {
bestScore = sc
courses.clear()
courses.add(it)
}
}
}
if (courses.isEmpty())
return null
return (if(me) bestScore else -bestScore) to courses[Random.nextInt(courses.size)]
}
fun Board.findBestTurn(count: Int, isMins: Boolean = true): Pair<Int, Board.Turn?> {
if (count == 0)
return currentBest(isMins)
val score = score()
//println("count=$count, score=${score}")
//dump()
//println()
val turns = getAllCourse(colorCourse).map {
val board = copy()
board.move(it.start, it.end)
val nscore = board.score()
if ((isMins && nscore > score) || (!isMins && nscore < score))
board.currentBest(!isMins).first to it
else
board.findBestTurn(count - 1, !isMins).first to it
}
val best = getMinOrMax(isMins, turns) ?: 0 to null
//println("best for $count, $best")
return best
}
private fun Board.currentBest(isMins: Boolean): Pair<Int, Board.Turn?> {
val turns = getAllCourse(colorCourse).map {
val board = copy()
board.move(it.start, it.end)
board.score() to it
}
return getMinOrMax(isMins, turns) ?: 0 to null
}
private fun getMinOrMax(isMins: Boolean, turns: List<Pair<Int, Board.Turn>>): Pair<Int, Board.Turn>? {
val elem = if (isMins) turns.minByOrNull { it.first } else turns.maxByOrNull { it.first }
return elem?.let { e ->
val list = turns.filter { it.first == e.first }
list[Random.nextInt(list.size)]
}
} | 0 | Kotlin | 1 | 1 | f10170daec6fa2df370799ce558ef846528d713f | 3,083 | kotlin-chess | MIT License |
kotlin/src/katas/kotlin/sort/mergesort/MergeSort3.kt | dkandalov | 2,517,870 | false | {"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221} | package katas.kotlin.sort.mergesort
import nonstdlib.listOfInts
import nonstdlib.printed
import datsok.shouldEqual
import org.junit.Test
import kotlin.random.Random
class MergeSortTests3 {
@Test fun `trivial examples`() {
emptyList<Int>().mergeSort() shouldEqual emptyList()
listOf(1).mergeSort() shouldEqual listOf(1)
}
@Test fun `basic examples`() {
listOf(1, 2).mergeSort() shouldEqual listOf(1, 2)
listOf(2, 1).mergeSort() shouldEqual listOf(1, 2)
listOf(1, 2, 3).mergeSort() shouldEqual listOf(1, 2, 3)
listOf(1, 3, 2).mergeSort() shouldEqual listOf(1, 2, 3)
listOf(2, 1, 3).mergeSort() shouldEqual listOf(1, 2, 3)
listOf(2, 3, 1).mergeSort() shouldEqual listOf(1, 2, 3)
listOf(3, 1, 2).mergeSort() shouldEqual listOf(1, 2, 3)
listOf(3, 2, 1).mergeSort() shouldEqual listOf(1, 2, 3)
}
@Test fun `sort random list`() {
fun List<Int>.isSorted() =
windowed(size = 2, step = 1).all { it[0] <= it[1] }
val randomList = Random.listOfInts(
sizeRange = IntRange(0, 100),
valuesRange = IntRange(0, 100)
)
randomList.mergeSort().isSorted().printed() shouldEqual true
}
}
private fun <E: Comparable<E>> List<E>.mergeSort(): List<E> {
if (size <= 1) return this
val midIndex = size / 2
return merge(
left = subList(0, midIndex).mergeSort(),
right = subList(midIndex, size).mergeSort()
)
}
private fun <E: Comparable<E>> merge(left: List<E>, right: List<E>): List<E> {
return when {
left.isEmpty() -> right
right.isEmpty() -> left
left[0] < right[0] -> listOf(left[0]) + merge(left.drop(1), right)
else -> listOf(right[0]) + merge(right.drop(1), left)
}
}
| 7 | Roff | 3 | 5 | 0f169804fae2984b1a78fc25da2d7157a8c7a7be | 1,822 | katas | The Unlicense |
src/Day22.kt | Flame239 | 570,094,570 | false | {"Kotlin": 60685} | private fun mm(): MonkeyMap {
val input = readInput("Day22")
val moves = input.takeLastWhile { it.isNotBlank() }[0]
val m = input.takeWhile { it.isNotBlank() }
val w = m.maxOf { it.length }
val map = Array(m.size) { IntArray(w) }
m.forEachIndexed { i, s ->
s.forEachIndexed { j, c ->
val num = when (c) {
' ' -> -1
'.' -> 0
else -> 1
}
map[i][j] = num
}
for (j in s.length until w) {
map[i][j] = -1
}
}
return MonkeyMap(map, Regex("\\d+|\\D+").findAll(moves).map(MatchResult::value))
}
private fun part1(mm: MonkeyMap): Int {
val map = mm.map
val h = map.size
val w = map[0].size
var j = map[0].indexOfFirst { it >= 0 }
var i = 0
val d = D.RIGHT()
mm.moves.forEach { move ->
if (move == "L") {
d.L()
} else if (move == "R") {
d.R()
} else {
for (s in 1..move.toInt()) {
var nI = i + d.I
var nJ = j + d.J
if (d.I != 0 && (nI < 0 || nI >= h || map[nI][nJ] == -1)) {
while ((nI - d.I in 0 until h) && map[nI - d.I][nJ] >= 0) nI -= d.I
}
if (d.J != 0 && (nJ < 0 || nJ >= w || map[nI][nJ] == -1)) {
while ((nJ - d.J in 0 until w) && map[nI][nJ - d.J] >= 0) nJ -= d.J
}
if (map[nI][nJ] == 0) {
i = nI
j = nJ
} else {
break
}
}
}
}
return (1000 * (i + 1) + 4 * (j + 1) + d.score)
}
private fun part2(mm: MonkeyMap): Int {
val map = mm.map
val h = map.size
val w = map[0].size
var j = map[0].indexOfFirst { it >= 0 }
var i = 0
var d = D(0, 1)
mm.moves.forEach { move ->
if (move == "L") {
d.L()
} else if (move == "R") {
d.R()
} else {
for (s in 1..move.toInt()) {
var nI = i + d.I
var nJ = j + d.J
var nD = d
val col = j / 50
val colRem = j % 50
val row = i / 50
val rowRem = i % 50
if (d.I != 0 && (nI < 0 || nI >= h || map[nI][nJ] == -1)) {
if (col == 0) {
if (d.I > 0) { // 7 -> 13
nD = D.DOWN()
nI = 0
nJ = 100 + colRem
} else { // 10 -> 11
nD = D.RIGHT()
nI = 50 + colRem
nJ = 50
}
}
if (col == 1) {
if (d.I > 0) { // 5 -> 6
nD = D.LEFT()
nI = 150 + colRem
nJ = 49
} else { // 2 -> 8
nD = D.RIGHT()
nI = 150 + colRem
nJ = 0
}
}
if (col == 2) {
if (d.I > 0) { // 14 -> 3
nD = D.LEFT()
nI = 50 + colRem
nJ = 99
} else { // 13 -> 7
nD = D.UP()
nI = 199
nJ = colRem
}
}
}
if (d.J != 0 && (nJ < 0 || nJ >= w || map[nI][nJ] == -1)) {
if (row == 0) {
if (d.J > 0) { // 1 -> 4 REV!
nD = D.LEFT()
nI = 149 - rowRem
nJ = 99
} else { // 12 -> 9 REV
nD = D.RIGHT()
nI = 149 - rowRem
nJ = 0
}
}
if (row == 1) {
if (d.J > 0) { // 3 -> 14
nD = D.UP()
nI = 49
nJ = 100 + rowRem
} else { // 11 -> 10
nD = D.DOWN()
nI = 100
nJ = rowRem
}
}
if (row == 2) {
if (d.J > 0) { //4 -> 1 rev
nD = D.LEFT()
nI = 49 - rowRem
nJ = 149
} else { // 9 -> 12 rev
nD = D.RIGHT()
nI = 49 - rowRem
nJ = 50
}
}
if (row == 3) {
if (d.J > 0) { // 6 -> 5
nD = D.UP()
nI = 149
nJ = 50 + rowRem
} else { // 8 -> 2
nD = D.DOWN()
nI = 0
nJ = 50 + rowRem
}
}
}
if (map[nI][nJ] == 0) {
i = nI
j = nJ
d = nD
} else {
break
}
}
}
}
return 1000 * (i + 1) + 4 * (j + 1) + d.score
}
fun main() {
measure { part1(mm()) }
measure { part2(mm()) }
}
private data class MonkeyMap(val map: Array<IntArray>, val moves: Sequence<String>)
private data class D(var I: Int, var J: Int) {
val score: Int
get() {
if (I == 1) return 1
if (I == -1) return 3
if (J == 1) return 0
if (J == -1) return 2
return -1
}
fun L() {
val newJ = if (J == 0) I else 0
val newI = if (I == 0) -J else 0
I = newI
J = newJ
}
fun R() {
val newJ = if (J == 0) -I else 0
val newI = if (I == 0) J else 0
I = newI
J = newJ
}
companion object {
fun UP() = D(-1, 0)
fun DOWN() = D(1, 0)
fun LEFT() = D(0, -1)
fun RIGHT() = D(0, 1)
}
}
| 0 | Kotlin | 0 | 0 | 27f3133e4cd24b33767e18777187f09e1ed3c214 | 6,566 | advent-of-code-2022 | Apache License 2.0 |
src/nativeMain/kotlin/com.qiaoyuang.algorithm/special/Questions9.kt | qiaoyuang | 100,944,213 | false | {"Kotlin": 338134} | package com.qiaoyuang.algorithm.special
fun test9() {
printlnResult(intArrayOf(10, 5, 2, 6), 100)
}
/**
* Questions 9: Given an IntArray and an integer k, find the count of all continues sub-array that product is less than k
*/
private infix fun IntArray.findCount(k: Int): Int {
require(isNotEmpty()) { "The IntArray can't be empty" }
var count = size
repeat(size) { i ->
var j = i + 1
while (j < size) {
val product = subProduct(i, j)
if (product < k) {
count++
j++
} else
break
}
}
return count
}
private fun IntArray.subProduct(i: Int, j: Int): Int {
var product = 1
for (index in i..j)
product *= this[index]
return product
}
private fun printlnResult(array: IntArray, k: Int) =
println("The count of all continues sub-array that product less than $k is (${array findCount k}) in array: ${array.toList()}")
| 0 | Kotlin | 3 | 6 | 66d94b4a8fa307020d515d4d5d54a77c0bab6c4f | 974 | Algorithm | Apache License 2.0 |
src/main/kotlin/com/tangledwebgames/tangledmath/rational/RationalExtensions.kt | l-e-webb | 432,786,844 | false | {"Kotlin": 18102} | package com.tangledwebgames.tangledmath.rational
import com.tangledwebgames.tangledmath.rational.Rational.Companion.rational
/* Rounding */
/**
* Returns the largest integer less than or equal to this [Rational]. Equivalent
* to [toInt].
*/
fun Rational.roundDown(): Int = toInt()
/**
* Returns the smallest integer greater than or equal to this [Rational].
*/
fun Rational.roundUp(): Int = if (isIntegral()) {
toInt()
} else {
roundDown() + 1
}
/**
* Returns the nearest integer to this [Rational]. If this [Rational] is
* exactly halfway between two integers (e.g. 1 / 2), rounds Down.
*/
fun Rational.round(): Int {
val partialFraction: Rational = this - roundDown()
return if (partialFraction > 1 over 2) {
roundUp()
} else {
roundDown()
}
}
/* Iteration */
/**
* Folds this sequence into a single [Rational]. Begins with [initial], then
* applies [rationalizer] to each element in the sequence and multiplies the
* result with the accumulated value.
*/
inline fun <T> Sequence<T>.rationalFold(
initial: Rational = Rational.ONE,
rationalizer: (T) -> Rational?
) = fold(initial) { ratio, item ->
rationalizer(item)?.let {
it * ratio
} ?: ratio
}
/**
* Folds this iterable into a single [Rational]. Begins with [initial], then
* applies [rationalizer] to each element in the iterable and multiplies the
* result with the accumulated value.
*/
inline fun <T> Iterable<T>.rationalFold(
initial: Rational = Rational.ONE,
rationalizer: (T) -> Rational?
) = asSequence().rationalFold(initial, rationalizer)
fun Sequence<Rational>.sum(): Rational = reduceOrNull { acc, rational ->
acc + rational
} ?: Rational.ZERO
fun Iterable<Rational>.sum(): Rational = reduceOrNull { acc, rational ->
acc + rational
} ?: Rational.ZERO
fun Sequence<Rational>.product(): Rational = reduceOrNull { acc, rational ->
acc * rational
} ?: Rational.ONE
fun Iterable<Rational>.product(): Rational = reduceOrNull { acc, rational ->
acc * rational
} ?: Rational.ONE
/* Integer operation extensions */
fun Int.toRational(): Rational = rational(this, 1)
/**
* Returns the integer approximation of this times [ratio].
*/
fun Int.ratioOf(ratio: Rational) = (ratio * this).toInt()
/**
* Infix fun for natural expression of rational values, e.g.
* val oneHalf = 1 over 2
*/
infix fun Int.over(other: Int) = rational(this, other)
/**
* Creates a [Rational] number equivalent to [percent] / 100. Note that the
* result will be in simplest form, so the denominator is not guaranteed to be
* 100.
*/
fun percentage(percent: Int): Rational = rational(percent, 100)
/**
* See [percentage].
*/
fun Int.percent(): Rational = percentage(this)
operator fun Int.plus(other: Rational) = other + this
operator fun Int.times(other: Rational) = other * this
operator fun Int.div(other: Rational) = other / this
| 0 | Kotlin | 0 | 0 | 70be827718019464ec3fd38a002273dc51389bc7 | 2,906 | tangledmath | Apache License 2.0 |
src/day10/Day10.kt | martin3398 | 572,166,179 | false | {"Kotlin": 76153} | package day10
import readInput
import java.lang.Math.abs
sealed interface Instruction
object Noop : Instruction
data class AddX(val count: Int) : Instruction
fun main() {
fun simulate(instructions: List<Instruction>, callback: (cycle: Int, registerValue: Int) -> Unit) {
var cycle = 1
var registerValue = 1
instructions.forEach {
when {
it is Noop -> callback(cycle, registerValue).also { cycle++ }
it is AddX -> {
callback(cycle, registerValue).also { cycle++ }
callback(cycle, registerValue).also { cycle++ }
registerValue += it.count
}
}
}
}
fun part1(input: List<Instruction>): Int {
var signalStrengthSum = 0
simulate(input) { cycle, registerValue ->
if ((cycle - 20) % 40 == 0)
signalStrengthSum += cycle * registerValue
}
return signalStrengthSum
}
fun part2(input: List<Instruction>): String {
val sb = StringBuilder()
simulate(input) { cycle, registerValue ->
val positionToDraw = (cycle - 1) % 40
if (positionToDraw == 0) {
sb.append("\n")
}
sb.append(if (abs(registerValue - positionToDraw) <= 1) "#" else " ")
}
return sb.toString()
}
fun preprocess(input: List<String>): List<Instruction> =
input.map { if (it == "noop") Noop else AddX(it.split(" ").last().toInt()) }
// test if implementation meets criteria from the description, like:
val testInput = readInput(10, true)
check(part1(preprocess(testInput)) == 13140)
val input = readInput(10)
println(part1(preprocess(input)))
check(part2(preprocess(testInput)) ==
"\n" +
"## ## ## ## ## ## ## ## ## ## \n" +
"### ### ### ### ### ### ### \n" +
"#### #### #### #### #### \n" +
"##### ##### ##### ##### \n" +
"###### ###### ###### ####\n" +
"####### ####### ####### "
)
println(part2(preprocess(input)))
}
| 0 | Kotlin | 0 | 0 | 4277dfc11212a997877329ac6df387c64be9529e | 2,243 | advent-of-code-2022 | Apache License 2.0 |
src/Day06.kt | monsterbrain | 572,819,542 | false | {"Kotlin": 42040} | import java.util.*
fun main() {
fun part1(input: String): Int {
var firstIndex = -1
input.forEachIndexed { index, char ->
if (index >= 4) {
// check last received 4 char
val last4 = input.substring(index-4, index)
if (firstIndex == -1 && last4.isUnique()) {
firstIndex = index
}
}
}
return firstIndex
}
fun part2(input: String): Int {
var firstIndex = -1
input.forEachIndexed { index, char ->
if (index >= 14) {
// check last received 4 char
val last14 = input.substring(index-14, index)
println("last14 = ${last14} when index=$index")
if (firstIndex == -1 && last14.isUnique()) {
firstIndex = index
}
}
}
return firstIndex
}
// test if implementation meets criteria from the description, like:
/*val testInput = readInput("Day05_test")
val part1Result = part1(testInput)
check(part1Result == "CMZ")*/
/*val input = readInput("Day05")
println(part1(input))*/
// test if implementation meets criteria from the description, like:
/*val testInput1 = "mjqjpqmgbljsphdztnvjfqwrcgsmlb"
val test1Result = part1(testInput1)
check(test1Result == 7)*/
val testInput2 = "mjqjpqmgbljsphdztnvjfqwrcgsmlb"
val test2Result = part2(testInput2)
check(test2Result == 19)
/*val input = readInput("Day06").take(1)[0]
println("input = ${input}")
println(part1(input))*/
val input = readInput("Day06").take(1)[0]
println("input = ${input}")
println(part2(input))
}
private fun String.isUnique(): Boolean {
return toSet().size == length
}
| 0 | Kotlin | 0 | 0 | 3a1e8615453dd54ca7c4312417afaa45379ecf6b | 1,819 | advent-of-code-kotlin-2022-Solutions | Apache License 2.0 |
src/day04/Code.kt | fcolasuonno | 572,734,674 | false | {"Kotlin": 63451, "Dockerfile": 1340} | package day04
import readInput
operator fun IntRange.contains(other: IntRange) = first in other && last in other
fun IntRange.overlaps(other: IntRange) = first <= other.last && last >= other.first
fun String.toIntRange(delimiter: Char = '-') = split(delimiter).map { it.toInt() }.let { it[0]..it[1] }
typealias Day04Type = Pair<IntRange, IntRange>
fun main() {
val format = """(\d+)-(\d+),(\d+)-(\d+)""".toRegex()
fun parse(input: List<String>) = input.map { line ->
format.matchEntire(line)!!.destructured
.toList().map(String::toInt)
.let { (x1, x2, y1, y2) ->
x1..x2 to y1..y2
}
}
fun part1(input: List<Day04Type>) = input.count { (first, second) ->
first in second || second in first
}
fun part2(input: List<Day04Type>) = input.count { (first, second) ->
first.overlaps(second)
}
val input = parse(readInput(::main.javaClass.packageName))
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 9cb653bd6a5abb214a9310f7cac3d0a5a478a71a | 1,014 | AOC2022 | Apache License 2.0 |
src/main/kotlin/com/anahoret/aoc2022/day07/main.kt | mikhalchenko-alexander | 584,735,440 | false | null | package com.anahoret.aoc2022.day07
import java.io.File as JavaIoFile
class FileTree {
enum class Command {
CD, LS;
companion object {
fun parse(str: String): Command {
return when {
str.startsWith("\$ cd") -> CD
str.startsWith("\$ ls") -> LS
else -> throw IllegalAccessException("Command does not exist: $str")
}
}
}
}
companion object {
fun buildTree(
input: List<String>,
tree: FileTree = FileTree()
): FileTree {
if (input.isEmpty()) return tree
val line = input.first()
return when (line.let(Command.Companion::parse)) {
Command.CD -> handleCd(line, tree, input)
Command.LS -> handleLs(input, tree)
}
}
private fun handleLs(input: List<String>, tree: FileTree): FileTree {
val nodes = input.drop(1).takeWhile { !isCommand(it) }
.map { toNode(it, tree.currentDir) }
tree.addAll(nodes)
return buildTree(input.drop(nodes.size + 1), tree)
}
private fun handleCd(command: String, tree: FileTree, input: List<String>): FileTree {
val path = command.split(" ")[2]
tree.goTo(path)
return buildTree(input.drop(1), tree)
}
private fun toNode(str: String, parent: Directory): FileTreeNode {
val parts = str.split(" ")
return if (str.startsWith("dir")) Directory(parts[1], parent)
else File(parts[1], parts[0].toInt())
}
private fun isCommand(strings: String): Boolean {
return strings.startsWith("$")
}
}
private var root = Directory("/", null)
var currentDir = root
private set
fun goTo(name: String): Directory {
currentDir = when (name) {
"/" -> root
".." -> currentDir.parent!!
else -> currentDir.getDir(name) ?: currentDir.add(Directory(name, currentDir))
}
return currentDir
}
fun addAll(nodes: List<FileTreeNode>) {
currentDir.addAll(nodes)
}
fun findAll(predicate: (FileTreeNode) -> Boolean): List<FileTreeNode> {
return root.findAll(predicate)
}
fun size(): Int {
return root.size()
}
}
interface FileTreeNode {
val name: String
fun size(): Int
}
open class Directory(override val name: String, val parent: Directory?) : FileTreeNode {
private val nodes = mutableListOf<FileTreeNode>()
fun <T : FileTreeNode> add(node: T): T {
nodes.add(node)
return node
}
override fun size(): Int {
return nodes.fold(0) { acc, node ->
acc + node.size()
}
}
fun getDir(name: String): Directory? {
return nodes.find { it is Directory && it.name == name } as Directory?
}
fun addAll(nodes: List<FileTreeNode>) {
this.nodes.addAll(nodes)
}
fun findAll(predicate: (FileTreeNode) -> Boolean): List<FileTreeNode> {
return nodes.fold(mutableListOf()) { acc, node ->
if (predicate(node)) acc.add(node)
if (node is Directory) acc.addAll(node.findAll(predicate))
acc
}
}
}
class File(override val name: String, val size: Int) : FileTreeNode {
override fun size(): Int {
return size
}
}
fun main() {
val fileTree = JavaIoFile("src/main/kotlin/com/anahoret/aoc2022/day07/input.txt")
.readText()
.trim()
.split("\n")
.let(FileTree.Companion::buildTree)
// Part 1
part1(fileTree)
// Part 2
part2(fileTree)
}
private fun part1(fileTree: FileTree) {
fileTree.findAll {
it is Directory && it.size() < 100000
}.sumOf(FileTreeNode::size)
.let(::println)
}
private fun part2(fileTree: FileTree) {
val totalSpace = 70000000
val needForUpdateSpace = 30000000
val usedSpace = fileTree.size()
val freeSpace = totalSpace - usedSpace
val needToFreeSpace = needForUpdateSpace - freeSpace
fileTree.findAll {
it is Directory && it.size() >= needToFreeSpace
}.minBy(FileTreeNode::size)
.size()
.let(::println)
}
| 0 | Kotlin | 0 | 0 | b8f30b055f8ca9360faf0baf854e4a3f31615081 | 4,323 | advent-of-code-2022 | Apache License 2.0 |
src/Day04.kt | diesieben07 | 572,879,498 | false | {"Kotlin": 44432} | private val file = "Day04"
private data class CleaningPair(val a: IntRange, val b: IntRange) {
fun oneFullyContainsTheOther(): Boolean {
return b.first in a && b.last in a || a.first in b && a.last in b
}
fun rangesOverlap(): Boolean {
return a.first <= b.last && b.first <= a.last
}
}
private fun String.parseIntRange(): IntRange {
val (first, last) = split('-')
return first.toInt()..last.toInt()
}
private fun Sequence<String>.parseInput(): Sequence<CleaningPair> {
return map {
val (a, b) = it.split(',')
CleaningPair(a.parseIntRange(), b.parseIntRange())
}
}
private fun part1() {
streamInput(file) { input ->
println(input.parseInput().count { it.oneFullyContainsTheOther() })
}
}
private fun part2() {
streamInput(file) { input ->
println(input.parseInput().count { it.rangesOverlap() })
}
}
fun main() {
part1()
part2()
}
| 0 | Kotlin | 0 | 0 | 0b9993ef2f96166b3d3e8a6653b1cbf9ef8e82e6 | 944 | aoc-2022 | Apache License 2.0 |
src/day1/Day01.kt | dinoolivo | 573,723,263 | false | null | package day1
import readInput
fun main() {
fun part1(input: List<Int>): Int {
return input.first()
}
fun part2(input: List<Int>): Int {
return input.take(3).sum()
}
fun clusterByCondition(input: List<String>): List<List<Int>> =
input.foldIndexed(arrayListOf(ArrayList<Int>())) { _, acc, item ->
if (item.isBlank()) {
acc.add(ArrayList())
}else{
acc.last().add(item.toInt())
}
acc
}
fun sortedCalories(input: List<List<Int>>) = input.map { calories -> calories.sum() }.sortedDescending()
val testInput = sortedCalories(clusterByCondition(readInput("inputs/Day01_test")))
println("Test Part 1: " + part1(testInput))
println("Test Part 2: " + part2(testInput))
//execute the two parts on the real input
val input = sortedCalories(clusterByCondition(readInput("inputs/Day01")))
println("Part1: " + part1(input))
println("Part2: " + part2(input))
}
| 0 | Kotlin | 0 | 0 | 6e75b42c9849cdda682ac18c5a76afe4950e0c9c | 1,016 | aoc2022-kotlin | Apache License 2.0 |
src/main/aoc2019/Day12.kt | nibarius | 154,152,607 | false | {"Kotlin": 963896} | package aoc2019
import MyMath
import kotlin.math.abs
class Day12(input: List<String>) {
data class Moon(val pos: MutableList<Int>, val vel: MutableList<Int>) {
fun applyGravity(other: Moon) {
(0..2).forEach {
vel[it] += if (pos[it] < other.pos[it]) 1 else if (pos[it] > other.pos[it]) -1 else 0
}
}
fun applyVelocity() {
(0..2).forEach { pos[it] += vel[it] }
}
private fun potentialEnergy() = pos.sumOf { abs(it) }
private fun kineticEnergy() = vel.sumOf { abs(it) }
fun energy() = potentialEnergy() * kineticEnergy()
}
private fun parseInput(input: List<String>): List<Moon> {
return input.map { line ->
Moon(mutableListOf(
line.substringAfter("x=").substringBefore(",").toInt(),
line.substringAfter("y=").substringBefore(",").toInt(),
line.substringAfter("z=").substringBefore(">").toInt()),
mutableListOf(0, 0, 0))
}
}
private val system = parseInput(input)
private fun doOneStep() {
system.forEach { first ->
system.forEach { second ->
if (first != second) {
first.applyGravity(second)
}
}
}
system.forEach { it.applyVelocity() }
}
fun solvePart1(steps: Int): Int {
repeat(steps) {
doOneStep()
}
return system.sumOf { it.energy() }
}
/*
(x1, y1, z1), (x1, x2, x3),
(x2, y2, z2), ==> (y1, y2, y3),
(x3, y3, z3) (z1, z2, z3)
*/
private fun transpose(input: List<List<Int>>): List<List<Int>> {
val out = List(3) { IntArray(3) { 0 } }
(0..2).forEach { y ->
(0..2).forEach { x ->
out[y][x] = input[x][y]
}
}
return out.map { it.toList() }
}
fun solvePart2(): Long {
// Due to the inherent math in the problem there are loops and the very first state
// will be the first state that repeats it self.
// https://www.reddit.com/r/adventofcode/comments/e9vfod/2019_day_12_i_see_everyone_solving_it_with_an/
// x, y, z axis are completely independent so search for the loop length of each one
// But important to look for loops for each axis as a whole system
// https://www.reddit.com/r/adventofcode/comments/e9ufz7/2019_day_12_part_2_intermediate_data_from_the/
val startPos = transpose(system.map { it.pos })
// start velocity is 0
// Map of Axis to Loop length
val loops = mutableMapOf<Int, Int>()
var iterations = 0
while (loops.size < 3) {
doOneStep()
iterations++
(0..2).forEach { axis ->
if (!loops.containsKey(axis) && // Loop already found for this axis
system.all { it.vel[axis] == 0 } && // Initial state for velocity
transpose(system.map { it.pos })[axis] == startPos[axis]) { // Initial state for position
loops[axis] = iterations
}
}
}
return MyMath.lcm(loops.values)
}
} | 0 | Kotlin | 0 | 6 | f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22 | 3,265 | aoc | MIT License |
src/kickstart2020/h/BoringNumbers.kt | vubogovich | 256,984,714 | false | null | package kickstart2020.h
import kotlin.math.max
private val power5 = Array(20) { 1L }
fun main() {
val inputFileName = "src/kickstart2020/h/BoringNumbers.in"
java.io.File(inputFileName).takeIf { it.exists() }?.also { System.setIn(it.inputStream()) }
for (i in 1 until power5.size) power5[i] = power5[i - 1] * 5
for (case in 1..readLine()!!.toInt()) {
val (l, r) = readLine()!!.split(' ').map { it.toLong() }
val res = boring(r) - boring(l - 1)
println("Case #$case: $res")
}
}
private fun boring(k: Long): Long {
val s = k.toString()
return calculate(s) + (1 until s.length).map { power5[it] }.sum()
}
private fun calculate(s: String): Long {
return when (s.length) {
1 -> (s.toLong() + 1) / 2
2 -> s.toLong() / 20 * 5 + if (s[0].toInt() % 2 > 0) (s.substring(1).toLong()) / 2 + 1 else 0
else -> max(0, s.take(2).toInt() - 1).toString().let { if (it.length == 2) calculate(it) * power5[s.length - 2] else 0 } +
if (s[0].toInt() % 2 > 0 && s[1].toInt() % 2 == 0) calculate(s.substring(2)) else 0
}
}
| 0 | Kotlin | 0 | 0 | fc694f84bd313cc9e8fcaa629bafa1d16ca570fb | 1,101 | kickstart | MIT License |
src/main/kotlin/Day4.kt | corentinnormand | 725,992,109 | false | {"Kotlin": 40576} | class Day4 : Aoc("day4.txt") {
private fun strToSet(string: String) =
string.split(" ")
.map { it.trim() }
.filter { it.isNotBlank() }
.map { it.toInt() }
.toSet()
override fun one() {
val input = readFile("day4.txt").lines()
val result = input.map { it.split(":")[1] }
.map { it.split("|") }
.map { Pair(strToSet(it[0]), strToSet(it[1])) }
.map { it.first.intersect(it.second).size }
.filter { it > 0 }
.map { 1 shl (it - 1) }
.sum()
println(result)
}
override fun two() {
val tmp = readFile("day4.txt").lines()
.filter { it.isNotBlank() }
.map { it.split(":") }
.map { Pair(it[0].split(" ").last(), it[1]) }
.map { Pair(it.first.trim().toInt(), it.second.split("|")) }
.map { Pair(it.first, strToSet(it.second[0]).intersect(strToSet(it.second[1])).size) }
.map { Pair(it.first, (it.first + 1..it.first + it.second).toSet()) }
.toMap()
var index = 0
val inputs = tmp.values.toMutableList()
while (inputs.isNotEmpty()) {
val line = inputs[0]
inputs.removeAt(0)
val elements = line.map { tmp[it]!! }
inputs.addAll(elements)
if (index % 10000 == 0) {
println(inputs.size)
}
index++
}
println(index)
}
}
| 0 | Kotlin | 0 | 0 | 2b177a98ab112850b0f985c5926d15493a9a1373 | 1,512 | aoc_2023 | Apache License 2.0 |
src/me/bytebeats/algo/kt/Solution9.kt | bytebeats | 251,234,289 | false | null | package me.bytebeats.algo.kt
import java.util.*
import me.bytebeats.algs.ds.ListNode
import me.bytebeats.algs.ds.TreeNode
class Solution9 {
fun avoidFlood(rains: IntArray): IntArray {//1488
val ans = IntArray(rains.size)
val lakes = mutableMapOf<Int, Int>()
val todo = sortedSetOf<Int>()
for (i in rains.indices) {
val rain = rains[i]
if (rain == 0) {
todo.add(i)
continue
} else {
ans[i] = -1
if (lakes.containsKey(rain)) {
val toPull = todo.higher(lakes[rain]) ?: return IntArray(0)
ans[toPull] = rain
todo.remove(toPull)
}
lakes[rain] = i
}
}
for (i in ans.indices) {
if (ans[i] == 0) ans[i] = 1
}
return ans
}
fun letterCasePermutation(S: String): List<String> {//784
var pow = 0
for (c in S) {
if (c.isLetter()) {
pow++
}
}
val ans = mutableListOf<String>()
for (i in 0 until Math.pow(2.0, pow.toDouble()).toInt()) {
var num = i
var pos = 0
val sb = StringBuilder()
while (num > 0) {
while (S[pos].isDigit()) {//find first character
sb.append(S[pos])
pos++
}
if (pos < S.length) {
if (num and 1 == 0) {
sb.append(S[pos].toLowerCase())
} else {
sb.append(S[pos].toUpperCase())
}
num = num shr 1
pos++
}
}
for (j in pos until S.length) {
if (S[j].isDigit()) {
sb.append(S[j])
} else {
sb.append(S[j].toLowerCase())
}
}
ans.add(sb.toString())
}
return ans
}
fun numTrees(n: Int): Int {//96, 卡特兰数
var catalan = 1L
for (i in 1..n) {
catalan = catalan * 2 * (2 * i - 1) / (i + 1)
}
return catalan.toInt()
}
fun numTrees1(n: Int): Int {//96
val dp = IntArray(n + 1)
dp[0] = 1
dp[1] = 1
for (i in 2..n) {
for (j in 1..i) {
dp[i] += dp[j - 1] * dp[i - j]
}
}
return dp[n]
}
fun generateTrees(n: Int): List<TreeNode?> {//95
return if (n == 0) listOf() else generateTrees(1, n)
}
private fun generateTrees(start: Int, end: Int): List<TreeNode?> {
val allTrees = mutableListOf<TreeNode?>()
if (start > end) {
allTrees.add(null)
return allTrees
}
for (i in start..end) {
val leftTrees = generateTrees(start, i - 1)
val rightTrees = generateTrees(i + 1, end)
for (leftTree in leftTrees) {
for (rightTree in rightTrees) {
val curTree = TreeNode(i)
curTree.left = leftTree
curTree.right = rightTree
allTrees.add(curTree)
}
}
}
return allTrees
}
fun removeDuplicateNodes(head: ListNode?): ListNode? {//面试题 02.01
if (head != null) {
val set = mutableSetOf<Int>()
var p = head
set.add(head.`val`)
while (p?.next != null) {
if (set.contains(p.next.`val`)) {
p.next = p.next.next
} else {
p = p.next
set.add(p.`val`)
}
}
}
return head
}
fun sumNumbers(root: TreeNode?): Int {//129
val ans = mutableListOf<String>()
dfs(root, "", ans)
return ans.map { it.toInt() }.sum()
}
private fun dfs(root: TreeNode?, str: String, list: MutableList<String>) {
if (root == null) return
val newStr = "$str${root.`val`}"
if (root.left == null && root.right == null) {
list.add(newStr)
} else {
if (root.left != null) {
dfs(root.left, newStr, list)
}
if (root.right != null) {
dfs(root.right, newStr, list)
}
}
}
fun largestTriangleArea(points: Array<IntArray>): Double {//812
var ans = 0.0
for (i in 0..points.size - 3) {
for (j in i + 1..points.size - 2) {
for (k in j + 1 until points.size) {
ans = ans.coerceAtLeast(areaOfTriangle(points[i], points[j], points[k]))
}
}
}
return ans
}
private fun areaOfTriangle(a: IntArray, b: IntArray, c: IntArray): Double {
return 0.5 * Math.abs(a[0] * b[1] + b[0] * c[1] + c[0] * a[1] - a[1] * b[0] - b[1] * c[0] - c[1] * a[0])
}
fun average(salary: IntArray): Double {//1491
var min = Int.MAX_VALUE
var max = Int.MIN_VALUE
var sum = 0
for (s in salary) {
min = min.coerceAtMost(s)
max = max.coerceAtLeast(s)
sum += s
}
return (sum - min - max) / (salary.size - 2).toDouble()
}
fun kthFactor(n: Int, k: Int): Int {
val sqrt = Math.sqrt(n.toDouble()).toInt()
val list = mutableListOf<Int>()
for (i in 1..sqrt) {
if (n % i == 0) {
if (i * i == n) {
list.add(i)
} else {
list.add(i)
list.add(n / i)
}
}
}
if (list.size < k) {
return -1
} else {
return list.sorted().drop(k - 1).first() ?: 0
}
}
fun longestSubarray(nums: IntArray): Int {
val idx = mutableListOf<Int>()
idx.add(-1)
for (n in nums.indices) {
if (nums[n] == 0) {
idx.add(n)
}
}
idx.add(nums.size)
if (idx.size == nums.size + 2) {
return 0
} else if (idx.size == 2) {
return nums.size - 1
} else {
var max = 0
for (i in 2..idx.lastIndex) {
max = max.coerceAtLeast(idx[i] - idx[i - 2] - 2)
}
return max
}
}
fun minNumberOfSemesters(n: Int, dependencies: Array<IntArray>, k: Int): Int {
val inDegrees = IntArray(n + 1)
inDegrees[0] = -1
val graph = mutableMapOf<Int, MutableList<Int>>()
for (d in dependencies) {
inDegrees[d[1]]++
if (graph.containsKey(d[0])) {
graph[d[0]]?.add(d[1])
} else {
val dependencies = mutableListOf<Int>()
dependencies.add(d[1])
graph[d[0]] = dependencies
}
}
val q = mutableListOf<Int>()
for (i in 1..n) {
if (inDegrees[i] == 0) q.add(i)
}
val replace = mutableListOf<Int>()
var ans = 0
while (q.isNotEmpty()) {
var kk = k
while (kk-- > 0 && q.isNotEmpty()) {
val cur = q.removeAt(0)
graph[cur]?.apply {
for (i in 0 until size) {
inDegrees[this[i]]--
if (inDegrees[this[i]] == 0) {
replace.add(this[i])
}
}
}
}
q.addAll(replace)
replace.clear()
ans += 1
}
return ans
}
fun isPathCrossing(path: String): Boolean {//1496
var x = 0
var y = 0
val set = mutableSetOf<String>()
set.add("$x,$y")
for (ch in path) {
if (ch == 'N') {
y++
} else if (ch == 'S') {
y--
} else if (ch == 'E') {
x++
} else {
x--
}
val point = "$x,$y"
if (set.contains(point)) {
return true
} else {
set.add(point)
}
}
return false
}
fun canArrange(arr: IntArray, k: Int): Boolean {//1497
val mod = IntArray(k)
for (i in arr) {
mod[(i % k + k) % k] += 1//(i % k + k) % k, 使余数为负的转为正
}
for (i in 1 until k) {
if (mod[i] != mod[k - i]) {
return false
}
}
return mod[0] % 2 == 0
}
fun numSubseq(nums: IntArray, target: Int): Int {
nums.sort()
return 0
}
fun findItinerary(tickets: List<List<String>>): List<String> {//332
val ans = mutableListOf<String>()
if (tickets.isNotEmpty()) {
val graph = mutableMapOf<String, PriorityQueue<String>>()
for (ticket in tickets) {
val queue = graph.computeIfAbsent(ticket[0]) {
PriorityQueue()//邻接顶点按字典顺序排序, 如果是使用 LinkedList 的话, 不要显式的进行排序
}
queue.add(ticket[1])
}
visit(graph, "JFK", ans)
}
return ans
}
/**
* DFS遍历图, 当不能再走时, 再将节点加入 ans
*/
private fun visit(graph: Map<String, PriorityQueue<String>>, src: String, ans: MutableList<String>) {
val neibour = graph[src]
while (neibour?.isNotEmpty() == true) {
val dst = neibour.poll()
visit(graph, dst, ans)
}
ans.add(0, src)
}
fun canMakeArithmeticProgression(arr: IntArray): Boolean {//1502
arr.sort()
val diff = arr[1] - arr[0]
for (i in 2 until arr.size) {
if (arr[i] - arr[i - 1] != diff) {
return false
}
}
return true
}
fun hasAlternatingBits(n: Int): Boolean {//693
var pre = n and 1
var nn = n shr 1
var cur = 0
while (nn > 0) {
cur = nn and 1
if (cur xor pre == 0) {
return false
}
nn = nn shr 1
pre = cur
}
return true
}
fun maxCount(m: Int, n: Int, ops: Array<IntArray>): Int {//598
var r = m
var c = n
for (op in ops) {
r = r.coerceAtMost(op[0])
c = c.coerceAtMost(op[1])
}
return r * c
}
fun findLUSlength(a: String, b: String): Int {//521
if (a == b) {
return -1
}
return a.length.coerceAtLeast(b.length)
}
fun findWords(words: Array<String>): Array<String> {//500
val fst = setOf('q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p')
val scnd = setOf('a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l')
val trd = setOf('z', 'x', 'c', 'v', 'b', 'n', 'm')
val ans = mutableListOf<String>()
for (word in words) {
if (word.isEmpty()) {
continue
}
val fstChar = word.first().toLowerCase()
val set = if (fst.contains(fstChar)) {
fst
} else if (scnd.contains(fstChar)) {
scnd
} else {
trd
}
var flag = true
for (i in 1 until word.length) {
if (!set.contains(word[i].toLowerCase())) {
flag = false
break
}
}
if (flag) {
ans.add(word)
}
}
return ans.toTypedArray()
}
fun findTilt(root: TreeNode?): Int {//563
if (root == null) {
return 0
}
return Math.abs(sumTree(root.left) - sumTree(root.right)) + findTilt(root.left) + findTilt(root.right)
}
fun sumTree(root: TreeNode?): Int {
if (root == null) return 0
else return root.`val` + sumTree(root.left) + sumTree(root.right)
}
fun numSpecialEquivGroups(A: Array<String>): Int {//893
val seen = mutableSetOf<String>()
for (s in A) {
val count = IntArray(52)
for (i in s.indices) {
count[s[i] - 'a' + 26 * (i and 1)] += 1
}
seen.add(count.contentToString())
}
return seen.size
}
fun widthOfBinaryTree(root: TreeNode?): Int {//662, wrong solution
if (root == null) return 0
val nodeQueue = mutableListOf<TreeNode>()
val idxQueue = mutableListOf<Int>()
nodeQueue.add(root)
idxQueue.add(0)
var countDown = 1
var count = 0
var minIdx = Int.MAX_VALUE
var maxIdx = Int.MIN_VALUE
var node: TreeNode? = null
var idx = 0
var ans = 0
var depth = 1
while (nodeQueue.isNotEmpty()) {
node = nodeQueue.removeAt(0)
idx = idxQueue.removeAt(0)
countDown--
minIdx = minIdx.coerceAtMost(idx)
maxIdx = maxIdx.coerceAtLeast(idx)
if (node?.left != null) {
nodeQueue.add(node?.left)
idxQueue.add(idx - 1)
count++
}
if (node?.right != null) {
nodeQueue.add(node?.right)
idxQueue.add(idx + 1)
count++
}
if (countDown == 0) {
depth++
ans = ans.coerceAtLeast(maxIdx - minIdx)
countDown = count
count = 0
minIdx = Int.MAX_VALUE
maxIdx = Int.MIN_VALUE
}
}
return ans
}
fun checkRecord(s: String): Boolean {//551
var countA = 0
var countL = 0
for (c in s) {
if (c == 'L') {
countL += 1
if (countL > 2) {
return false
}
} else {
if (countL != 0) {
countL = 0
}
if (c == 'A') {
countA += 1
}
if (countA > 1) {
return false
}
}
}
return true
}
fun isSameTree(p: TreeNode?, q: TreeNode?): Boolean {//100
if (p == null) return q == null
else if (p != null && q != null) {
return p.`val` == q.`val` && isSameTree(p.left, q.left) && isSameTree(p.right, q.right)
} else return false
}
fun findLHS(nums: IntArray): Int {//594
val map = mutableMapOf<Int, Int>()
var ans = 0
for (num in nums) {
map.compute(num) { _, v -> if (v == null) 1 else v + 1 }
if (map.containsKey(num - 1)) {
ans = ans.coerceAtLeast(map[num]!! + map[num - 1]!!)
}
if (map.containsKey(num + 1)) {
ans = ans.coerceAtLeast(map[num]!! + map[num + 1]!!)
}
}
return ans
}
fun numIdenticalPairs(nums: IntArray): Int {//1512
var ans = 0
val map = mutableMapOf<Int, MutableList<Int>>()
for (i in nums.indices) {
if (map.containsKey(nums[i])) {
ans += map[nums[i]]!!.size
}
map.compute(nums[i]) { _, v ->
if (v == null) {
val list = mutableListOf<Int>()
list.add(i)
list
} else {
v.add(i)
v
}
}
}
return ans
}
fun numberOfDays(Y: Int, M: Int): Int {//1184
val map = mapOf(
1 to 31,
2 to 28,
3 to 31,
4 to 30,
5 to 31,
6 to 30,
7 to 31,
8 to 31,
9 to 30,
10 to 31,
11 to 30,
12 to 31
)
if (M != 2) {
return map[M]!!
} else {
var days = map[2]!!
if (Y % 400 == 0 || Y % 4 == 0 && Y % 100 != 0) {
days += 1
}
return days
}
}
val UNCOLORED = 0
val RED = 1
val GREEN = 2
var valid = false
fun isBipartite(graph: Array<IntArray>): Boolean {//785, dfs
val n = graph.size
val colors = IntArray(n) { UNCOLORED }
valid = true
var node = 0
while (node < n && valid) {
if (colors[node] == UNCOLORED) {
dfs(node, RED, graph, colors)
}
node += 1
}
return valid
}
private fun dfs(node: Int, color: Int, graph: Array<IntArray>, colors: IntArray) {
colors[node] = color
val colorOfNeighbor = if (color == RED) GREEN else RED
for (neighber in graph[node]) {
if (colors[neighber] == UNCOLORED) {
dfs(neighber, colorOfNeighbor, graph, colors)
if (!valid) {
return
}
} else if (colors[neighber] != colorOfNeighbor) {
valid = false
return
}
}
}
fun isBipartite1(graph: Array<IntArray>): Boolean {//785, bfs
val n = graph.size
val colors = IntArray(n) { UNCOLORED }
for (i in 0 until n) {//node
if (colors[i] == UNCOLORED) {
val q = mutableListOf<Int>()
q.add(i)
colors[i] = RED
while (q.isNotEmpty()) {
val node = q.removeAt(0)
val colorOfNeighbor = if (colors[node] == RED) GREEN else RED
for (neighber in graph[node]) {
if (colors[neighber] == UNCOLORED) {
q.add(neighber)
colors[neighber] = colorOfNeighbor
} else if (colors[neighber] != colorOfNeighbor) {
return false
}
}
}
}
}
return true
}
fun destCity(paths: List<List<String>>): String {//1436, 计算每个点的出度
val graph = mutableMapOf<String, Int>()
for (path in paths) {
graph.compute(path[0]) { _, v -> if (v == null) 1 else v + 1 }
graph.compute(path[1]) { _, v -> v ?: 0 }
}
return graph.entries.filter { it.value == 0 }.map { it.key }.first()
}
fun minSubsequence(nums: IntArray): List<Int> {//1403
nums.sortDescending()
val ans = mutableListOf<Int>()
var sum = nums.sum()
var sub = 0
for (num in nums) {
sub += num
sum -= num
ans.add(num)
if (sub > sum) {
return ans
}
}
return ans
}
fun freqAlphabets(s: String): String {//1309
val map = mutableMapOf<String, Char>()
for (i in 1..26) {
if (i < 10) {
map[i.toString()] = 'a' + i - 1
} else {
map["$i#"] = 'a' + i - 1
}
}
val sb = StringBuilder()
val size = s.length
var i = size - 1
while (i >= 0) {
if (s[i] == '#') {
sb.append(map[s.substring(i - 2, i + 1)])
i -= 3
} else {
sb.append(map[s[i].toString()])
i--
}
}
return sb.reversed().toString()
}
fun calPoints(ops: Array<String>): Int {//682
val stack = mutableListOf<Int>()
for (op in ops) {
if (op == "+") {
val top = stack.removeAt(stack.lastIndex)
val newTop = top + stack.last()
stack.add(top)
stack.add(newTop)
} else if (op == "C") {
stack.removeAt(stack.lastIndex)
} else if (op == "D") {
stack.add(2 * stack.last())
} else {
stack.add(op.toInt())
}
}
return stack.sum()
}
fun repeatedStringMatch(A: String, B: String): Int {//686
var a = ""
val aL = A.length
val bL = B.length
for (i in 1..(bL / aL + 2)) {//reduced loop
a = "$a$A"
if (a.length >= B.length && a.contains(B)) {
return i
}
}
return -1
}
fun countBinarySubstrings(s: String): Int {//696
val size = s.length
val dp = IntArray(size)
dp[0] = 1
var t = 0
for (i in 1 until size) {
if (s[i - 1] != s[i]) {
dp[++t] = 1
} else {
dp[t] += 1
}
}
var ans = 0
for (i in 1..t) {
ans += dp[i - 1].coerceAtMost(dp[i])
}
return ans
}
fun allPathsSourceTarget(graph: Array<IntArray>): List<List<Int>> {//797
return solve(graph, 0)
}
private fun solve(graph: Array<IntArray>, node: Int): MutableList<MutableList<Int>> {
val n = graph.size
val ans = mutableListOf<MutableList<Int>>()
if (node == n - 1) {
val path = mutableListOf<Int>()
path.add(node)
ans.add(path)
return ans
}
for (nb in graph[node]) {
for (path in solve(graph, nb)) {
path.add(0, node)
ans.add(path)
}
}
return ans
}
fun splitArray(nums: IntArray, m: Int): Int {//410
val n = nums.size
val dp = Array(n + 1) { IntArray(m + 1) { Int.MAX_VALUE } }
val sub = IntArray(n + 1)
for (i in 0 until n) {
sub[i + 1] = sub[i] + nums[i]
}
dp[0][0] = 0
for (i in 1..n) {
for (j in 1..m.coerceAtMost(i)) {
for (k in 0 until i) {
dp[i][j] = dp[i][j].coerceAtMost(dp[k][j - 1].coerceAtLeast(sub[i] - sub[k]))
}
}
}
return dp[n][m]
}
} | 0 | Kotlin | 0 | 1 | 7cf372d9acb3274003bb782c51d608e5db6fa743 | 22,544 | Algorithms | MIT License |
src/Day03.kt | pmatsinopoulos | 730,162,975 | false | {"Kotlin": 10493} | import kotlin.io.path.Path
import kotlin.io.path.readLines
fun buildMatrix(inputFile: String): Array<CharArray> {
val fileLines = Path("src/$inputFile").readLines()
val numberOfColumns = fileLines.first().length
val matrix = Array(fileLines.size) { rowIndex ->
CharArray(numberOfColumns) { columnIndex ->
fileLines[rowIndex][columnIndex]
}
}
return matrix
}
fun numberHasNeighbouringSymbol(
matrix: Array<CharArray>,
startDigitPosition: Pair<Int, Int>,
endDigitPosition: Pair<Int, Int>
): Boolean {
val result = false
var startScan = startDigitPosition.second - 1
if (startScan < 0) {
startScan = 0
}
var endScan = endDigitPosition.second + 1
val numberOfColumns = matrix.first().size
val numberOfRows = matrix.size
if (endScan >= numberOfColumns) {
endScan = numberOfColumns - 1
}
val rowIndex = startDigitPosition.first
for (scanPosition in startScan..endScan) {
if (matrix[rowIndex][scanPosition].isSymbol()) {
return true
}
if (rowIndex > 0 && matrix[rowIndex - 1][scanPosition].isSymbol()) {
return true
}
if (rowIndex < numberOfRows - 1 && matrix[rowIndex + 1][scanPosition].isSymbol()) {
return true
}
}
return result
}
fun neighbouringGears(
matrix: Array<CharArray>,
number: NumberInMatrix
): MutableList<Pair<Int, Int>> {
// A number may have many Gear neighbours
val result = mutableListOf<GearPosition>()
val startDigitPosition = number.first
var startScan = startDigitPosition.second - 1
if (startScan < 0) {
startScan = 0
}
val endDigitPosition = number.second
var endScan = endDigitPosition.second + 1
val numberOfColumns = matrix.first().size
val numberOfRows = matrix.size
if (endScan >= numberOfColumns) {
endScan = numberOfColumns - 1
}
val rowIndex = startDigitPosition.first
for (scanPosition in startScan..endScan) {
if (matrix[rowIndex][scanPosition].isGear()) {
result.add(GearPosition(rowIndex, scanPosition))
}
if (rowIndex > 0 && matrix[rowIndex - 1][scanPosition].isGear()) {
result.add(GearPosition(rowIndex - 1, scanPosition))
}
if (rowIndex < numberOfRows - 1 && matrix[rowIndex + 1][scanPosition].isGear()) {
result.add(GearPosition(rowIndex + 1, scanPosition))
}
}
return result
}
fun digitsToNumber(
matrix: Array<CharArray>,
number: NumberInMatrix
): Int {
val startDigitPosition = number.first
val endDigitPosition = number.second
return matrix[startDigitPosition.first].slice(startDigitPosition.second..endDigitPosition.second).joinToString("")
.toInt()
}
typealias Position = Pair<Int, Int>
typealias GearPosition = Position
typealias DigitPosition = Position
typealias StartPosition = DigitPosition
typealias EndPosition = DigitPosition
typealias NumberInMatrix = Pair<StartPosition, EndPosition>
fun gearRatio(matrix: Array<CharArray>, numbers: MutableList<NumberInMatrix>): Int {
return numbers.fold(1) { acc, number ->
acc * digitsToNumber(matrix, number)
}
}
fun main() {
val inputs = listOf("Day03.txt")
for (input in inputs) {
val matrix = buildMatrix(input)
var sum = 0
val numbersForGears: MutableMap<
GearPosition, // Gear position
MutableList<NumberInMatrix> // numbers neighbouring with gear position
> = mutableMapOf()
matrix.forEachIndexed { rowIndex, chars ->
val digitPositions =
mutableListOf<DigitPosition>() // an even set of digit positions, each pair representing the start and end position of a number
var inDigit = false
chars.forEachIndexed { columnIndex, c ->
if (c.isDot()) {
if (inDigit) {
digitPositions.add(EndPosition(rowIndex, columnIndex - 1)) // adding the end digit position
inDigit = false
}
} else if (c.isDigit()) {
if (inDigit) {
if (columnIndex == chars.size - 1) {
// we are at the end of the row
digitPositions.add(EndPosition(rowIndex, columnIndex)) // adding the end digit position
inDigit = false
}
} else {
digitPositions.add(StartPosition(rowIndex, columnIndex)) // adding the start digit position
inDigit = true
}
} else if (c.isSymbol()) {
if (inDigit) {
digitPositions.add(EndPosition(rowIndex, columnIndex - 1)) // adding the end digit position
inDigit = false
}
}
}
// here, I have all the pairs of beginnings and endings of numbers
var i = 0
while (i < digitPositions.size) {
val numberInMatrix = NumberInMatrix(digitPositions[i], digitPositions[i + 1])
val neighbouringGearsForNumber = neighbouringGears(matrix, numberInMatrix)
neighbouringGearsForNumber.forEach { gearForNumber ->
if (numbersForGears[gearForNumber] == null) {
numbersForGears[gearForNumber] = mutableListOf()
}
numbersForGears[gearForNumber]?.add(numberInMatrix)
}
i += 2
}
}
sum = numbersForGears.filterValues { numbers -> numbers.size >= 2 }
.values.map { numbers ->
gearRatio(matrix, numbers)
}.sum()
println(sum)
}
}
| 0 | Kotlin | 0 | 0 | f913207842b2e6491540654f5011127d203706c6 | 5,931 | advent-of-code-kotlin-template | Apache License 2.0 |
src/Day03.kt | Sagolbah | 573,032,320 | false | {"Kotlin": 14528} | fun main() {
fun getPriority(symbol: Char) : Int {
return if (symbol in 'a'..'z') {
symbol - 'a' + 1
} else {
symbol - 'A' + 27
}
}
fun part1(input: List<String>): Int {
var ans = 0
for (line in input) {
val fst = line.substring(0, line.length / 2).toSet()
val snd = line.substring(line.length / 2).toSet()
val symbol = fst.intersect(snd).first()
ans += getPriority(symbol)
}
return ans
}
fun part2(input: List<String>): Int {
var ans = 0
for (i in input.indices step 3) {
val symbol = input[i].toSet().intersect(input[i+1].toSet()).intersect(input[i+2].toSet()).first()
ans += getPriority(symbol)
}
return ans
}
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 893c1797f3995c14e094b3baca66e23014e37d92 | 913 | advent-of-code-kt | Apache License 2.0 |
src/main/kotlin/day16.kt | gautemo | 572,204,209 | false | {"Kotlin": 78294} | import shared.getText
/*
This day was hard. This code is slow. This code is messy. But it works if you want to wait some hours.
Not sure if I want to spend more time on it, making it more readable or re-thinking the solution to be faster.
*/
fun main() {
val input = getText("day16.txt")
println(day16A(input))
println(day16B(input))
}
fun day16A(input: String): Int {
val valves = input.lines().map {
val name = it.split(" ")[1]
val rate = Regex("""(?<=rate=)\d+""").find(it)!!.value.toInt()
val tunnels = Regex("""(?<=tunnels? leads? to valves? ).*""").find(it)!!.value.split(",").map { v -> v.trim() }
Valve(name, rate, tunnels)
}
return search(valves.find { it.name == "AA" }!!, valves)
}
data class Valve(val name: String, val rate: Int, val tunnels: List<String>)
private fun search(start: Valve, valves: List<Valve>): Int {
val ignore = mutableListOf(Triple(0, "AA", setOf<String>()))
val queue = mutableListOf(Path(0, 0, listOf(start.name)))
var best = 0
var count = 0
while (queue.isNotEmpty()) {
val check = queue.removeAt(0)
if(check.been.size != count) {
if(queue.size > 1000){
val b = queue.maxOf { it.total }
queue.removeIf { it.total * 2 < b }
}
count = check.been.size
println(check.been.size)
println(ignore.size)
println(queue.size)
}
if(check.allOpened(valves)){
val end = check.wait(30 - check.been.size)
best = maxOf(best, end.res())
continue
}
if(check.been.size == 30) {
best = maxOf(best, check.res())
continue
}
val currentValve = valves.getByName(check.been.last())
if(currentValve.rate > 0 && !check.opened.contains(currentValve.name)){
val newPath = check.open(currentValve.rate)
if(ignore.none { newPath.total <= it.first && newPath.been.last() == it.second && newPath.opened == it.third }) {
queue.add(newPath)
ignore.removeIf {
it.second == newPath.been.last() && newPath.opened.containsAll(it.third) && newPath.total >= it.first
}
ignore.add(Triple(newPath.total, newPath.been.last(), newPath.opened))
}
}
for(move in currentValve.tunnels) {
val newPath = check.next(move)
if(ignore.none { newPath.total <= it.first && newPath.been.last() == it.second && newPath.opened == it.third }) {
queue.add(newPath)
ignore.removeIf {
it.second == newPath.been.last() && newPath.opened.containsAll(it.third) && newPath.total >= it.first
}
ignore.add(Triple(newPath.total, newPath.been.last(), newPath.opened))
}
}
}
println(best)
return best
}
private data class Path(val total: Int, var pressure: Int, val been: List<String>, val opened: Set<String> = setOf()){
fun open(addPressure: Int): Path {
return Path(total + pressure, pressure + addPressure, been.plus(been.last()), opened.plus(been.last()))
}
fun next(to: String): Path {
return Path(total + pressure, pressure, been.plus(to), opened)
}
fun allOpened(valves: List<Valve>) = valves.filter { it.rate > 0 }.all { opened.contains(it.name) }
fun wait(minutes: Int) = Path(total + (minutes * pressure), pressure, been, opened)
fun res() = total + pressure
}
private fun List<Valve>.getByName(name: String) = find { it.name == name}!!
private fun List<Valve>.getByName2(name: String) = find { it.name == name}
fun day16B(input: String): Int {
val valves = input.lines().map {
val name = it.split(" ")[1]
val rate = Regex("""(?<=rate=)\d+""").find(it)!!.value.toInt()
val tunnels = Regex("""(?<=tunnels? leads? to valves? ).*""").find(it)!!.value.split(",").map { v -> v.trim() }
Valve(name, rate, tunnels)
}
return search3(valves)
}
private fun search3(valves: List<Valve>): Int {
val ignore = mutableListOf(Triple(0, setOf("AA", "AA"), setOf<String>()))
val queue = mutableListOf(Approach("AA" to "AA"))
var best = 0
var count = 0
while (queue.isNotEmpty()) {
val check = queue.removeAt(0)
if(check.moves.first.length/2 != count) {
if(queue.size > 1000){
val b = queue.maxOf { it.total(valves) }
queue.removeIf { it.total(valves) * 1.3 < b }
}
count = check.moves.first.length/2
println(count)
println(ignore.size)
println(queue.size)
}
val on = check.on()
if(check.moves.first.length/2 == 26) {
best = maxOf(best, check.total(valves))
continue
}
if(check.allOpened(valves)){
if(check.total(valves) > best) {
best = check.total(valves)
queue.add(Approach("${check.moves.first}ww" to "${check.moves.second}ww"))
}
continue
}
val v1 = valves.getByName(on.first)
val v2 = valves.getByName(on.second)
val canOpenV1 = v1.rate > 0 && !check.hasOpened(v1.name)
val canOpenV2 = v2.rate > 0 && !check.hasOpened(v2.name)
val goTo = mutableSetOf<Approach>()
if(canOpenV1 && canOpenV2 && on.first != on.second) {
goTo.add(Approach("${check.moves.first}${on.first}" to "${check.moves.second}${on.second}"))
}
if(canOpenV1){
for(move in v2.tunnels) {
goTo.add(Approach("${check.moves.first}${on.first}" to "${check.moves.second}$move"))
}
}
if(canOpenV2) {
for(move in v1.tunnels) {
goTo.add(Approach("${check.moves.first}$move" to "${check.moves.second}${on.second}"))
}
}
for(move1 in v1.tunnels) {
for(move2 in v2.tunnels) {
goTo.add(Approach("${check.moves.first}$move1" to "${check.moves.second}$move2"))
}
}
val bestOpened = goTo.maxOf { it.hasOpened().size }
ignore.removeIf { it.third.size * 1.3 < bestOpened && bestOpened > 4 }
val canGoTo = goTo.fold(listOf<Approach>()) { acc, approach ->
if(acc.none { other -> other.moves.toList().toSet() == approach.moves.toList().toSet() }){
acc + listOf(approach)
} else{
acc
}
}.filter { !it.isBadMove() }
for(approach in canGoTo) {
val total = approach.total(valves)
val onSet = setOf(approach.on().first, approach.on().second)
val hasOpened = approach.hasOpened()
if(ignore.none { total <= it.first && onSet == it.second && it.third.containsAll(hasOpened)}) {
queue.add(approach)
val newIgnore = Triple(total, onSet, hasOpened)
ignore.removeIf {
newIgnore.first >= it.first && newIgnore.second == it.second && newIgnore.third == it.third
}
ignore.add(newIgnore)
}
}
}
println(best)
return best
}
private data class Approach(val moves: Pair<String, String>) {
fun on() = Pair(moves.first.takeLast(2), moves.second.takeLast(2))
fun total(valves: List<Valve>): Int {
if(moves.first.length <= 2) return 0
var total = 0
var pressure = 0
for (i in 2 until moves.first.length step 2) {
total += pressure
if(moves.first.substring(i, i+2) == moves.first.substring(i-2, i)){
val valve = valves.getByName2(moves.first.substring(i, i+2))
pressure += valve?.rate ?: 0
}
if(moves.second.substring(i, i+2) == moves.second.substring(i-2, i)){
val valve = valves.getByName2(moves.second.substring(i, i+2))
pressure += valve?.rate ?: 0
}
}
return total + pressure
}
fun allOpened(valves: List<Valve>) = valves.filter { it.rate > 0 }.all { hasOpened(it.name) }
fun hasOpened(name: String): Boolean {
return moves.first.windowed(4, 2).any { it == "$name$name" } ||
moves.second.windowed(4, 2).any { it == "$name$name" }
}
fun isBadMove(): Boolean {
if(moves.first.length >= 6 && moves.first.takeLast(6).let { it.substring(0,2) == it.substring(4,6) }){
return true
}
if(moves.second.length >= 6 && moves.second.takeLast(6).let { it.substring(0,2) == it.substring(4,6) }){
return true
}
return false
}
fun hasOpened(): Set<String> {
return setOf(
*moves.first.windowed(4, 2).filter { it.take(2) == it.takeLast(2) }.toTypedArray(),
*moves.second.windowed(4, 2).filter { it.take(2) == it.takeLast(2) }.toTypedArray(),
)
}
} | 0 | Kotlin | 0 | 0 | bce9feec3923a1bac1843a6e34598c7b81679726 | 9,055 | AdventOfCode2022 | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/StoneGame2.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import kotlin.math.max
import kotlin.math.min
/**
* 1140. Stone Game II
* @see <a href="https://leetcode.com/problems/stone-game-ii/">Source</a>
*/
fun interface StoneGame2 {
operator fun invoke(piles: IntArray): Int
}
/**
* Approach 1: Memoization
*/
class StoneGame2Memoization : StoneGame2 {
override operator fun invoke(piles: IntArray): Int {
val dp = Array(2) {
Array(piles.size + 1) { IntArray(piles.size + 1) }
}
for (p in 0..1) {
for (i in 0..piles.size) {
for (m in 0..piles.size) {
dp[p][i][m] = -1
}
}
}
return f(piles, dp, 0, 0, 1)
}
private fun f(piles: IntArray, dp: Array<Array<IntArray>>, p: Int, i: Int, m: Int): Int {
if (i == piles.size) {
return 0
}
if (dp[p][i][m] != -1) {
return dp[p][i][m]
}
var res = if (p == 1) LIM else -1
var s = 0
for (x in 1..min(2 * m, piles.size - i)) {
s += piles[i + x - 1]
res = if (p == 0) {
max(res, s + f(piles, dp, 1, i + x, max(m, x)))
} else {
min(res, f(piles, dp, 0, i + x, max(m, x)))
}
}
return res.also { dp[p][i][m] = it }
}
companion object {
private const val LIM = 1000000
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,036 | kotlab | Apache License 2.0 |
advent-of-code2015/src/main/kotlin/day24/Advent24.kt | REDNBLACK | 128,669,137 | false | null | package day24
import combinations
import mul
import parseInput
import splitToLines
/**
--- Day 24: It Hangs in the Balance ---
It's Christmas Eve, and Santa is loading up the sleigh for this year's deliveries. However, there's one small problem: he can't get the sleigh to balance. If it isn't balanced, he can't defy physics, and nobody gets presents this year.
No pressure.
Santa has provided you a list of the weights of every package he needs to fit on the sleigh. The packages need to be split into three groups of exactly the same weight, and every package has to fit. The first group goes in the passenger compartment of the sleigh, and the second and third go in containers on either side. Only when all three groups weigh exactly the same amount will the sleigh be able to fly. Defying physics has rules, you know!
Of course, that's not the only problem. The first group - the one going in the passenger compartment - needs as few packages as possible so that Santa has some legroom left over. It doesn't matter how many packages are in either of the other two groups, so long as all of the groups weigh the same.
Furthermore, Santa tells you, if there are multiple ways to arrange the packages such that the fewest possible are in the first group, you need to choose the way where the first group has the smallest quantum entanglement to reduce the chance of any "complications". The quantum entanglement of a group of packages is the product of their weights, that is, the value you get when you multiply their weights together. Only consider quantum entanglement if the first group has the fewest possible number of packages in it and all groups weigh the same amount.
For example, suppose you have ten packages with weights 1 through 5 and 7 through 11. For this situation, some of the unique first groups, their quantum entanglements, and a way to divide the remaining packages are as follows:
Group 1; Group 2; Group 3
11 9 (QE= 99); 10 8 2; 7 5 4 3 1
10 9 1 (QE= 90); 11 7 2; 8 5 4 3
10 8 2 (QE=160); 11 9; 7 5 4 3 1
10 7 3 (QE=210); 11 9; 8 5 4 2 1
10 5 4 1 (QE=200); 11 9; 8 7 3 2
10 5 3 2 (QE=300); 11 9; 8 7 4 1
10 4 3 2 1 (QE=240); 11 9; 8 7 5
9 8 3 (QE=216); 11 7 2; 10 5 4 1
9 7 4 (QE=252); 11 8 1; 10 5 3 2
9 5 4 2 (QE=360); 11 8 1; 10 7 3
8 7 5 (QE=280); 11 9; 10 4 3 2 1
8 5 4 3 (QE=480); 11 9; 10 7 2 1
7 5 4 3 1 (QE=420); 11 9; 10 8 2
Of these, although 10 9 1 has the smallest quantum entanglement (90), the configuration with only two packages, 11 9, in the passenger compartment gives Santa the most legroom and wins. In this situation, the quantum entanglement for the ideal configuration is therefore 99. Had there been two configurations with only two packages in the first group, the one with the smaller quantum entanglement would be chosen.
What is the quantum entanglement of the first group of packages in the ideal configuration?
--- Part Two ---
That's weird... the sleigh still isn't balancing.
"Ho ho ho", Santa muses to himself. "I forgot the trunk".
Balance the sleigh again, but this time, separate the packages into four groups instead of three. The other constraints still apply.
Given the example packages above, this would be some of the new unique first groups, their quantum entanglements, and one way to divide the remaining packages:
11 4 (QE=44); 10 5; 9 3 2 1; 8 7
10 5 (QE=50); 11 4; 9 3 2 1; 8 7
9 5 1 (QE=45); 11 4; 10 3 2; 8 7
9 4 2 (QE=72); 11 3 1; 10 5; 8 7
9 3 2 1 (QE=54); 11 4; 10 5; 8 7
8 7 (QE=56); 11 4; 10 5; 9 3 2 1
Of these, there are three arrangements that put the minimum (two) number of packages in the first group: 11 4, 10 5, and 8 7. Of these, 11 4 has the lowest quantum entanglement, and so it is selected.
Now, what is the quantum entanglement of the first group of packages in the ideal configuration?
*/
fun main(args: Array<String>) {
val test = """
|1
|2
|3
|4
|5
|7
|8
|9
|10
|11
""".trimMargin()
val input = parseInput("day24-input.txt")
println(findLowestQE(test, 3) == 2 to 99L)
println(findLowestQE(test, 4) == 2 to 44L)
println(findLowestQE(input, 3))
println(findLowestQE(input, 4))
}
fun findLowestQE(input: String, groupsSize: Int): Pair<Int, Long>? {
val data = input.splitToLines().map(String::toInt)
val maxSize = data.size / groupsSize + 2
val maxSum = data.sum() / groupsSize
return (1..maxSize - 1)
.asSequence()
.mapNotNull { i ->
data.combinations(i)
.filter { it.size <= maxSize && it.sum() == maxSum }
.map { it.size to it.map(Int::toLong).mul() }
.firstOrNull()
}
.first()
}
| 0 | Kotlin | 0 | 0 | e282d1f0fd0b973e4b701c8c2af1dbf4f4a149c7 | 4,965 | courses | MIT License |
src/Day01.kt | cgeesink | 573,018,348 | false | {"Kotlin": 10745} | fun main() {
fun part1(input: List<String>): Int {
var currentElve = 0
var maxElve = 0
for (line in input) {
if (line.isBlank()) {
if (currentElve > maxElve) {
maxElve = currentElve
}
currentElve = 0
} else {
currentElve += line.toInt()
}
}
return maxElve
}
fun pushValue(value: Int, array: Array<Int>) {
var current = value
var overflow = 0
for (i in 0..array.size - 1) {
if (current > array[i]) {
overflow = array[i]
array[i] = current
current = 0
}
if (overflow > array[i]) {
val tmp = array[i]
array[i] = overflow
overflow = tmp
}
}
}
fun part2(input: List<String>): Int {
var currentElve = 0
val maxElves = arrayOf(0, 0, 0)
for (line in input) {
if (line.isNotBlank()) {
currentElve += line.toInt()
} else {
pushValue(currentElve, maxElves)
currentElve = 0
}
}
if (currentElve > 0) {
pushValue(currentElve, maxElves)
}
return maxElves.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 137fb9a9561f5cbc358b7cfbdaf5562c20d6b10d | 1,648 | aoc-2022-in-kotlin | Apache License 2.0 |
src/main/kotlin/com/jaspervanmerle/aoc2021/day/Day22.kt | jmerle | 434,010,865 | false | {"Kotlin": 60581} | package com.jaspervanmerle.aoc2021.day
import kotlin.math.max
import kotlin.math.min
class Day22 : Day("655005", "1125649856443608") {
private data class Cuboid(val xRange: IntRange, val yRange: IntRange, val zRange: IntRange) {
val volume = xRange.size() * yRange.size() * zRange.size()
fun overlapsWith(other: Cuboid): Boolean {
return xRange.first <= other.xRange.last && xRange.last >= other.xRange.first
&& yRange.first <= other.yRange.last && yRange.last >= other.yRange.first
&& zRange.first <= other.zRange.last && zRange.last >= other.zRange.first
}
fun splitAround(other: Cuboid): List<Cuboid> {
val belowX = xRange.first until other.xRange.first
val middleX = max(xRange.first, other.xRange.first)..min(xRange.last, other.xRange.last)
val aboveX = other.xRange.last + 1..xRange.last
val belowY = yRange.first until other.yRange.first
val middleY = max(yRange.first, other.yRange.first)..min(yRange.last, other.yRange.last)
val aboveY = other.yRange.last + 1..yRange.last
val belowZ = zRange.first until other.zRange.first
val middleZ = max(zRange.first, other.zRange.first)..min(zRange.last, other.zRange.last)
val aboveZ = other.zRange.last + 1..zRange.last
val cuboids = mutableListOf<Cuboid>()
for (x in listOf(belowX, middleX, aboveX)) {
for (y in listOf(belowY, middleY, aboveY)) {
for (z in listOf(belowZ, middleZ, aboveZ)) {
val cuboid = Cuboid(x, y, z)
if (cuboid.volume > 0 && !cuboid.overlapsWith(other)) {
cuboids.add(cuboid)
}
}
}
}
return cuboids
}
private fun IntRange.size(): Long {
return max(0L, last.toLong() - first.toLong() + 1L)
}
}
private data class RebootStep(val on: Boolean, val xRange: IntRange, val yRange: IntRange, val zRange: IntRange)
private val rebootSteps = input.lines().map {
val on = it.startsWith("on")
val rangeMatches = "(-?\\d+)\\.\\.(-?\\d+)".toRegex().findAll(it).toList()
val xRange = rangeMatches[0].groups[1]!!.value.toInt()..rangeMatches[0].groups[2]!!.value.toInt()
val yRange = rangeMatches[1].groups[1]!!.value.toInt()..rangeMatches[1].groups[2]!!.value.toInt()
val zRange = rangeMatches[2].groups[1]!!.value.toInt()..rangeMatches[2].groups[2]!!.value.toInt()
RebootStep(on, xRange, yRange, zRange)
}
override fun solvePartOne(): Any {
return countOnCubes { max(it.first, -50)..min(it.last, 50) }
}
override fun solvePartTwo(): Any {
return countOnCubes { it }
}
private fun countOnCubes(rangeLimiter: (IntRange) -> IntRange): Long {
var onCuboids = emptyList<Cuboid>()
for (step in rebootSteps) {
val newOnCuboids = mutableListOf<Cuboid>()
val stepCuboid = Cuboid(rangeLimiter(step.xRange), rangeLimiter(step.yRange), rangeLimiter(step.zRange))
for (cuboid in onCuboids) {
if (cuboid.overlapsWith(stepCuboid)) {
newOnCuboids.addAll(cuboid.splitAround(stepCuboid))
} else {
newOnCuboids.add(cuboid)
}
}
if (step.on) {
newOnCuboids.add(stepCuboid)
}
onCuboids = newOnCuboids
}
return onCuboids.sumOf { it.volume }
}
}
| 0 | Kotlin | 0 | 0 | dcac2ac9121f9bfacf07b160e8bd03a7c6732e4e | 3,677 | advent-of-code-2021 | MIT License |
src/main/kotlin/com/kishor/kotlin/ds/BinaryTree.kt | kishorsutar | 276,212,164 | false | null | package com.kishor.kotlin.ds
import java.util.*
import kotlin.math.abs
import kotlin.math.max
open class BinaryTree(value: Int) {
var value = value
var left: BinaryTree? = null
var right: BinaryTree? = null
}
fun branchSums(root: BinaryTree): List<Int> {
val listOfSum = mutableListOf<Int>()
getBranchSum(root, listOfSum, 0)
return listOfSum
}
fun getBranchSum(node: BinaryTree, listOfSum: MutableList<Int>, runningSum: Int) {
var currentSum = runningSum
if (node.left == null && node.right == null) {
currentSum += node.value
listOfSum.add(currentSum)
return
} else {
currentSum += node.value
}
if (node.left != null) {
getBranchSum(node.left!!, listOfSum, currentSum)
}
if (node.right != null) {
getBranchSum(node.right!!, listOfSum, currentSum)
}
}
fun nodeDepthsRecursive(root: BinaryTree): Int {
var runningSum = 0
return depthSum(root, runningSum)
}
fun depthSum(node: BinaryTree?, runningSum: Int): Int {
if (node == null) return 0
return runningSum + depthSum(node.right, runningSum) + depthSum(node.left, runningSum)
}
class Level(tree: BinaryTree, depth: Int) {
var depth = depth
var tree = tree
}
fun nodeDepthIterative(root: BinaryTree): Int {
val stack = Stack<Level>()
var sumOfDepth = 0
stack.push(Level(root, 0))
while (stack.isNotEmpty()) {
val top = stack.pop()
val node = top.tree
val depth = top.depth
sumOfDepth += depth
if (node.left != null) {
stack.push(Level(node.left!!, depth + 1))
}
if (node.right != null) {
stack.push(Level(node.right!!, depth + 1))
}
}
return sumOfDepth
}
fun nodeDepthLevelIterative(root: BinaryTree): Int {
val queue = ArrayDeque<Level>()
var sumOfDepth = 0
queue.add(Level(root, 0))
while (queue.isNotEmpty()) {
val top = queue.poll()
val node = top.tree
val depth = top.depth
sumOfDepth += depth
if (node.left != null) {
queue.add(Level(node.left!!, depth + 1))
}
if (node.right != null) {
queue.add(Level(node.right!!, depth + 1))
}
}
return sumOfDepth
}
fun invertRecursiveBinaryTree(tree: BinaryTree?) {
if (tree == null) return
swapLeftAndRight(tree)
invertRecursiveBinaryTree(tree.left)
invertRecursiveBinaryTree(tree.right)
}
fun swapLeftAndRight(node1: BinaryTree) {
val left = node1.left
node1.left = node1.right
node1.right = left
}
fun invertIterativeBinaryTree(tree: BinaryTree) {
val queue = ArrayDeque<BinaryTree>()
queue.add(tree)
while (queue.isNotEmpty()) {
val current = queue.poll()
swapLeftAndRight(current)
if (current.left != null) queue.add(current.left)
if (current.right != null) queue.add(current.right)
}
}
data class TreeInfo(val diameter: Int, val height: Int)
fun binaryTreeDiameter(tree: BinaryTree): Int {
return getTreeInfo(tree).diameter
}
fun getTreeInfo(tree: BinaryTree?): TreeInfo {
if (tree == null) return TreeInfo(0, 0)
val leftTree = getTreeInfo(tree.left)
val rightTree = getTreeInfo(tree.right)
val longestPathThroughRoot = leftTree.height + rightTree.height
val maxDiameterSoFar = max(leftTree.diameter, rightTree.diameter)
val currentDiameter = max(longestPathThroughRoot, maxDiameterSoFar)
val currentHeight = 1 + max(leftTree.height, rightTree.height)
return TreeInfo(currentDiameter, currentHeight)
}
data class BinaryTreeWithParent(
val value: Int, val left: BinaryTreeWithParent?,
val right: BinaryTreeWithParent?,
val parent: BinaryTreeWithParent?
)
fun findSuccessor(tree: BinaryTreeWithParent, node: BinaryTreeWithParent): BinaryTreeWithParent {
if (node.right != null) return getLeftmostChild(node.right)
return getRightmostParent(node)
}
fun getLeftmostChild(node: BinaryTreeWithParent): BinaryTreeWithParent {
var currentNode = node
while (currentNode.left == null) {
currentNode = currentNode.left!!
}
return currentNode
}
fun getRightmostParent(node: BinaryTreeWithParent): BinaryTreeWithParent {
var currentNode = node
while (currentNode.parent != null && currentNode.parent!!.right == currentNode) {
currentNode = currentNode.parent!!
}
return currentNode.parent!!
}
fun heightBalancedTree(tree: BinaryTree): Boolean {
return getTreeBalanceInfo(tree).isBalanced
}
class TreeHeightInfo(height: Int, isBalanced: Boolean) {
var height = height
var isBalanced = isBalanced
}
fun getTreeBalanceInfo(node: BinaryTree?): TreeHeightInfo {
if (node == null) return TreeHeightInfo(-1, true)
val leftInfo = getTreeBalanceInfo(node.left)
val rightInfo = getTreeBalanceInfo(node.right)
val isBalanced = leftInfo.isBalanced && rightInfo.isBalanced && abs(leftInfo.height - rightInfo.height) <= 1
val height = 1 + max(leftInfo.height, rightInfo.height)
return TreeHeightInfo(height, isBalanced)
}
| 0 | Kotlin | 0 | 0 | 6672d7738b035202ece6f148fde05867f6d4d94c | 5,121 | DS_Algo_Kotlin | MIT License |
aoc-day4/src/Board.kt | rnicoll | 438,043,402 | false | {"Kotlin": 90620, "Rust": 1313} | import kotlin.collections.ArrayList
class Board(private val rows: Array<Row>) {
companion object {
fun read(input: Iterator<String>): Board {
val rows = ArrayList<Row>(Day4.BOARD_SIZE)
for (i in 0 until Day4.BOARD_SIZE) {
rows.add(Row.parse(input.next()))
}
return Board(rows.toTypedArray())
}
}
fun match(num: Int) = this.rows.forEach { it.match(num) }
fun isMatched(): Boolean {
val matchedRows = rows.filter { it.isRowMatched() }
if (matchedRows.isNotEmpty()) return true
for (col in 0 until Day4.BOARD_SIZE) {
var matchedCol = true
for (row in 0 until Day4.BOARD_SIZE) {
matchedCol = matchedCol && rows[row].isMatched(col)
}
if (matchedCol) {
return true
}
}
return false
}
fun score() = rows.sumOf { it.score() }
override fun toString() = rows.contentToString()
}
class Row(private val numbers: List<Int>) {
companion object {
fun parse(input: String): Row {
val numbers = ArrayList<Int>(Day4.BOARD_SIZE)
for (i in 0 until Day4.BOARD_SIZE) {
val start = 3 * i
val t = input.substring(start, start + 2).trim()
numbers.add(Day4.NUMBER_PARSER.parse(t).toInt())
}
return Row(numbers)
}
}
private val matched: MutableList<Boolean> = numbers.map { false }.toMutableList()
fun get(i: Int) = numbers[i]
fun match(num: Int) {
for (i in numbers.indices) {
if (numbers[i] == num) {
matched[i] = true
}
}
}
fun isRowMatched() = matched.all { it }
fun isMatched(col: Int) = matched[col]
fun score() = numbers.mapIndexed { index, i ->
if (!matched[index]) {
i
} else {
0
}
}.sum()
override fun toString(): String {
return numbers.toTypedArray().contentToString()
}
} | 0 | Kotlin | 0 | 0 | 8c3aa2a97cb7b71d76542f5aa7f81eedd4015661 | 2,073 | adventofcode2021 | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/FindArrayDifference.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
/**
* 2215. Find the Difference of Two Arrays
* @see <a href="https://leetcode.com/problems/find-the-difference-of-two-arrays/">Source</a>
*/
fun interface FindArrayDifference {
fun findDifference(nums1: IntArray, nums2: IntArray): List<List<Int>>
}
/**
* Approach 1: Brute Force
*/
class FindArrayDifferenceBF : FindArrayDifference {
override fun findDifference(nums1: IntArray, nums2: IntArray): List<List<Int>> {
return listOf(
getElementsOnlyInFirstList(nums1, nums2),
getElementsOnlyInFirstList(nums2, nums1),
)
}
// Returns the elements in the first arg nums1 that don't exist in the second arg nums2.
private fun getElementsOnlyInFirstList(nums1: IntArray, nums2: IntArray): List<Int> {
val onlyInNums1: MutableSet<Int> = HashSet()
// Iterate over each element in the list nums1.
for (num in nums1) {
var existInNums2 = false
// Check if num is present in the second arg nums2.
for (x in nums2) {
if (x == num) {
existInNums2 = true
break
}
}
if (!existInNums2) {
onlyInNums1.add(num)
}
}
// Convert to vector.
return ArrayList(onlyInNums1)
}
}
class FindArrayDifferenceHashSet : FindArrayDifference {
override fun findDifference(nums1: IntArray, nums2: IntArray): List<List<Int>> {
return listOf(
getElementsOnlyInFirstList(nums1, nums2),
getElementsOnlyInFirstList(nums2, nums1),
)
}
// Returns the elements in the first arg nums1 that don't exist in the second arg nums2.
private fun getElementsOnlyInFirstList(nums1: IntArray, nums2: IntArray): List<Int> {
val onlyInNums1: MutableSet<Int> = HashSet()
// Store nums2 elements in an unordered set.
val existsInNums2: MutableSet<Int> = HashSet()
for (num in nums2) {
existsInNums2.add(num)
}
// Iterate over each element in the list nums1.
for (num in nums1) {
if (!existsInNums2.contains(num)) {
onlyInNums1.add(num)
}
}
// Convert to vector.
return ArrayList(onlyInNums1)
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,957 | kotlab | Apache License 2.0 |
2023/src/day10/day10.kt | Bridouille | 433,940,923 | false | {"Kotlin": 171124, "Go": 37047} | package day10
import GREEN
import RESET
import printTimeMillis
import readInput
private fun findStart(table: Array<CharArray>): List<Int> {
for (y in table.indices) {
for (x in table[y].indices) {
if (table[y][x] == 'S') return listOf(x, y)
}
}
throw IllegalStateException("No S found")
}
fun printTable(table: Array<CharArray>) {
println("=".repeat(table[0].size * 2))
for (line in table) {
print("[")
for (c in line) {
print("$c,")
}
println("]")
}
}
enum class Possibles(val letters: Set<Char>) {
TOP(setOf('|', '7', 'F')),
BOTTOM(setOf('|', 'L', 'J')),
LEFT(setOf('-', 'L', 'F')),
RIGHT(setOf('-', '7', 'J'))
}
data class Point(val x: Int, val y: Int)
data class Visit(
val x: Int,
val y: Int,
val possibles: Set<Char>
)
// Traverses the map in a dfs and return the points contained in the loop
private fun dfs(
table: Array<CharArray>,
startX: Int,
startY: Int
): Set<Point> {
val stack = mutableListOf<Visit>()
val visited = mutableSetOf<Point>()
println("Start = ($startX, $startY)")
stack.add(Visit(startX, startY - 1, Possibles.TOP.letters))
stack.add(Visit(startX, startY + 1, Possibles.BOTTOM.letters))
stack.add(Visit(startX - 1, startY, Possibles.LEFT.letters))
stack.add(Visit(startX + 1, startY, Possibles.RIGHT.letters))
while (stack.isNotEmpty()) {
val visit = stack.removeLast()
if (visit.y < 0 || visit.y >= table.size) continue
if (visit.x < 0 || visit.x >= table[visit.y].size) continue
if (table[visit.y][visit.x] == 'S' && visited.size > 2) {
println("Found 'S' in ${visited.size + 1} steps")
visited.add(Point(visit.x, visit.y))
return visited
}
if (!visit.possibles.contains(table[visit.y][visit.x])) continue
if (visited.contains(Point(visit.x, visit.y))) continue
val x = visit.x
val y = visit.y
val tmp = table[y][x]
visited.add(Point(visit.x, visit.y))
when (tmp) {
'-' -> { // explore left + right
stack.add(Visit(x - 1, y, Possibles.LEFT.letters))
stack.add(Visit(x + 1, y, Possibles.RIGHT.letters))
}
'|' -> { // explore top + bottom
stack.add(Visit(x, y - 1, Possibles.TOP.letters))
stack.add(Visit(x, y + 1, Possibles.BOTTOM.letters))
}
'F' -> { // explore bottom + right
stack.add(Visit(x, y + 1, Possibles.BOTTOM.letters))
stack.add(Visit(x + 1, y, Possibles.RIGHT.letters))
}
'7' -> { // explore left + bottom
stack.add(Visit(x - 1, y, Possibles.LEFT.letters))
stack.add(Visit( x, y + 1, Possibles.BOTTOM.letters))
}
'J' -> { // explore top + left
stack.add(Visit(x, y - 1, Possibles.TOP.letters))
stack.add(Visit(x - 1, y, Possibles.LEFT.letters))
}
'L' -> { // explore top + right
stack.add(Visit(x, y - 1, Possibles.TOP.letters))
stack.add(Visit(x + 1, y, Possibles.RIGHT.letters))
}
else -> throw IllegalStateException("Invalid char -> $tmp")
}
}
throw IllegalStateException("No solution found")
}
fun part1(input: List<String>): Int {
val table = Array(input.size) { idx -> input[idx].toCharArray() }
val (startX, startY) = findStart(table)
return dfs(table, startX, startY).size / 2
}
fun part2(input: List<String>): Int {
val table = Array(input.size) { idx -> input[idx].toCharArray() }
val (startX, startY) = findStart(table)
val loopPoints = dfs(table, startX, startY)
// Clean the map from pipes not in the loop
for (y in table.indices) {
for (x in table[y].indices) {
if (!loopPoints.contains(Point(x, y))) {
table[y][x] = '.'
}
}
}
// Go through the map from left to right counting the number of points that are inside
// https://en.wikipedia.org/wiki/Point_in_polygon
var insideCount = 0
for (y in table.indices) {
var inside = false
for (x in table[y].indices) {
if (setOf('|', 'L', 'J').contains(table[y][x])) {
inside = !inside
} else if (table[y][x] == '.' && inside) {
insideCount += 1
}
}
}
return insideCount
}
fun main() {
val testInput = readInput("day10_example.txt")
printTimeMillis { print("part1 example = $GREEN" + part1(testInput) + RESET) }
printTimeMillis { print("part2 example = $GREEN" + part2(testInput) + RESET) }
val input = readInput("day10.txt")
printTimeMillis { print("part1 input = $GREEN" + part1(input) + RESET) }
printTimeMillis { print("part2 input = $GREEN" + part2(input) + RESET) }
}
| 0 | Kotlin | 0 | 2 | 8ccdcce24cecca6e1d90c500423607d411c9fee2 | 4,984 | advent-of-code | Apache License 2.0 |
src/main/kotlin/com/hj/leetcode/kotlin/problem2316/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem2316
/**
* LeetCode page: [2316. Count Unreachable Pairs of Nodes in an Undirected Graph](https://leetcode.com/problems/count-unreachable-pairs-of-nodes-in-an-undirected-graph/);
*/
class Solution {
/* Complexity:
* Time O(n+E) and Space O(n+E) where E is the size of edges;
*/
fun countPairs(n: Int, edges: Array<IntArray>): Long {
val nodeAdjacency = nodeToItsAdjacency(edges)
var remainingNodes = n.toLong()
var numPairs = 0L
dfs(n, nodeAdjacency) { componentSize ->
remainingNodes -= componentSize
numPairs += componentSize * remainingNodes
}
return numPairs
}
private fun nodeToItsAdjacency(edges: Array<IntArray>): Map<Int, List<Int>> {
val adjacent = hashMapOf<Int, MutableList<Int>>()
for ((u, v) in edges) {
adjacent.computeIfAbsent(u) { mutableListOf() }.add(v)
adjacent.computeIfAbsent(v) { mutableListOf() }.add(u)
}
return adjacent
}
private fun dfs(
numNodes: Int,
nodeAdjacency: Map<Int, List<Int>>,
visited: MutableSet<Int> = hashSetOf(),
sideEffect: (connectedComponentSize: Int) -> Unit
) {
val nodes = 0 until numNodes
for (node in nodes) {
if (node in visited) continue
val oldVisitedSize = visited.size
visitAllReachableNodes(node, nodeAdjacency, visited)
val newVisitedSize = visited.size
val componentSize = newVisitedSize - oldVisitedSize
sideEffect(componentSize)
}
}
private fun visitAllReachableNodes(
sourceNode: Int,
nodeAdjacency: Map<Int, List<Int>>,
visited: MutableSet<Int>
) {
visited.add(sourceNode)
val adjacent = nodeAdjacency[sourceNode] ?: emptyList()
for (node in adjacent) {
if (node in visited) continue
visitAllReachableNodes(node, nodeAdjacency, visited)
}
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 2,038 | hj-leetcode-kotlin | Apache License 2.0 |
src/cn/leetcode/codes/simple145/Simple145.kt | shishoufengwise1234 | 258,793,407 | false | {"Java": 771296, "Kotlin": 68641} | package cn.leetcode.codes.simple145
import cn.leetcode.codes.common.TreeNode
import cn.leetcode.codes.createTreeNode
import cn.leetcode.codes.out
import java.util.*
import kotlin.collections.ArrayList
fun main() {
val nums = arrayOf<Int?>(1,2,3)
val treeNode = createTreeNode(nums)
val re = postorderTraversal(treeNode)
val re2 = postorderTraversal2(treeNode)
out("re = $re")
out("re2 = $re2")
}
/*
145. 二叉树的后序遍历
给定一个二叉树,返回它的 后序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [3,2,1]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
*/
//递归解法 后序遍历 左子树 -> 右子树 -> 根节点
fun postorderTraversal(root: TreeNode?): List<Int> {
val list = ArrayList<Int>()
if (root == null) return list
postorder(root,list)
return list
}
fun postorder(node: TreeNode?,list: ArrayList<Int>){
if (node == null) return
postorder(node.left,list)
postorder(node.right,list)
list.add(node.`val`)
}
//迭代解法
fun postorderTraversal2(root: TreeNode?): List<Int> {
val list = ArrayList<Int>()
if (root == null) return list
//借助队列实现遍历
var node = root
var prev:TreeNode? = null
val deque = LinkedList<TreeNode>()
while (!deque.isEmpty() || node != null){
//持续遍历左子树
while (node != null){
deque.push(node)
node = node.left
}
node = deque.pop()
//持续遍历右子树
if (node.right == null || node.right == prev){
list.add(node.`val`)
prev = node
node = null
}else{
deque.push(node)
node = node.right
}
}
return list
}
| 0 | Java | 0 | 0 | f917a262bcfae8cd973be83c427944deb5352575 | 1,803 | LeetCodeSimple | Apache License 2.0 |
src/test/kotlin/be/brammeerten/y2022/Day16Test.kt | BramMeerten | 572,879,653 | false | {"Kotlin": 170522} | package be.brammeerten.y2022
import be.brammeerten.extractRegexGroups
import be.brammeerten.graphs.Dijkstra
import be.brammeerten.graphs.Graph
import be.brammeerten.graphs.Node
import be.brammeerten.graphs.Vertex
import be.brammeerten.readFile
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
class Day16Test {
private val START = "AA"
var TIME = 30
var HEURISTIC_MIN_VISITED = 0
var HEURISTIC_MIN_PRESSURE = 0
val dijkstraCache = HashMap<Pair<String, String>, List<Valve>?>()
@Test
fun `part 1a`() {
val graph = readGraph(readFile("2022/day16/exampleInput.txt"))
Assertions.assertEquals(1651, solve(graph))
}
@Test
fun `part 1b`() {
val graph = readGraph(readFile("2022/day16/input.txt"))
val solved = solve(graph)
Assertions.assertEquals(1647, solved)
}
@Test
fun `part 2a`() {
TIME = 26
val graph = readGraph(readFile("2022/day16/exampleInput.txt"))
Assertions.assertEquals(1707, solveWithElephant(graph))
}
@Test
fun `part 2b`() {
TIME = 26
HEURISTIC_MIN_VISITED = 6
HEURISTIC_MIN_PRESSURE = 600
val graph = readGraph(readFile("2022/day16/input.txt"))
Assertions.assertEquals(2169, solveWithElephant(graph))
}
fun solve(graph: CaveGraph): Int {
val state = State(graph.nodes[START]!!, 0, 0, 0)
val notVisited = HashMap(graph.nodes)
notVisited.remove(START)
val solutions = notVisited.values.flatMap { target -> trySolution(graph, state, target, notVisited, 1) }
return solutions.maxOf { it.pressure }
}
fun solveWithElephant(graph: CaveGraph): Int {
var state = State(graph.nodes[START]!!, 0, 0, 0)
var notVisited = HashMap(graph.nodes)
notVisited.remove(START)
val solutions1 = notVisited.values.flatMap { target -> trySolution(graph, state, target, notVisited, 1) }
println("Found possible solutions: ${solutions1.size}")
return solutions1
.flatMap { s1 -> solutions1.map { s2 -> s1 to s2 }
.filter { (s1, s2) -> s1.getVisitedSize(graph.nodes.size) + s2.getVisitedSize(graph.nodes.size) -1 <= graph.nodes.keys.size }
.filter { (s1, s2) -> s1.getVisited(graph.nodes.keys).none { v -> s2.getVisited(graph.nodes.keys).contains(v) }}}
.maxOf { (s1, s2) -> s1.pressure + s2.pressure }
}
fun trySolution(graph: CaveGraph, state: State, target: Valve, notVisited: Map<String, Valve>, count: Int): List<Result> {
// new state
val newState = openValve(graph, target, state)
if (newState.time == TIME) return listOf(Result(newState.pressure, HashMap(notVisited)))
// new targets
val newNotVisited = HashMap(notVisited)
newNotVisited.remove(target.key)
// no targets left, wait
if (newNotVisited.isEmpty())
return listOf(Result(newState.pressure + ((TIME-newState.time) * newState.pressurePerRound), HashMap(newNotVisited)))
// try all targets
val out = newNotVisited.values
.flatMap { trySolution(graph, newState, it, newNotVisited, count+1).filter { it.pressure > HEURISTIC_MIN_PRESSURE && it.getVisitedSize(graph.nodes.size) > HEURISTIC_MIN_VISITED } }
val wait = tryWaiting(newState, newNotVisited)
return if (wait.pressure > HEURISTIC_MIN_PRESSURE) out + tryWaiting(newState, newNotVisited) else out
}
fun tryWaiting(state: State, notVisited: Map<String, Valve>): Result {
return Result(state.pressure + ((TIME-state.time) * state.pressurePerRound), HashMap(notVisited))
}
data class Result(val pressure: Int, val notVisited: HashMap<String, Valve>) {
fun getVisited(allNodes: Set<String>): Set<String> {
return allNodes - notVisited.keys - "AA"
}
fun getVisitedSize(allNodesSize: Int): Int {
return allNodesSize - notVisited.size
}
}
fun openValve(graph: CaveGraph, to: Valve, state: State): State {
val path = Dijkstra.findShortestPath(graph, state.position.key, to.key, dijkstraCache)!!
val steps = path.windowed(2).sumOf { (from, to) -> from.vertices.find { it.to == to.key }!!.weight }
// Not enough time to reach valve and open it, just stay still
if (state.time + steps >= TIME) {
return State(state.position, TIME, state.pressure + ((TIME-state.time)*state.pressurePerRound), state.pressurePerRound)
}
// Run to valve and open it
val timePassed = steps + 1
val pressure = state.pressure + (timePassed * state.pressurePerRound)
return State(to, state.time + timePassed, pressure, state.pressurePerRound + to.value)
}
/**
* ====================== READING AND SIMPLIFYING THE GRAPH ====================
*/
fun readGraph(lines: List<String>): CaveGraph {
val graph = CaveGraph()
lines
.map { extractRegexGroups("^Valve (.+) has flow rate=(\\d+); tunnels? leads? to valves? (.+)$", it) }
.forEach { matches -> graph.addNode(matches[0], matches[1].toInt(), matches[2].split(", ").map { Vertex(it, 1) }) }
return graph.simplify()
}
fun CaveGraph.simplify(): CaveGraph {
while (true) {
val remove = nodes.values.firstOrNull { it.value == 0 && it.key != START } ?: break
remove(remove)
}
return this
}
fun CaveGraph.remove(node: Valve) {
val neighbours = node.vertices
neighbours.forEach { neighbour ->
neighbours
.filter { it != neighbour }
.forEach { newNeighbour ->
var curNode = nodes[neighbour.to]!!
val newLink = Vertex(newNeighbour.to, neighbour.weight + newNeighbour.weight)
val existingLink = curNode.vertices.firstOrNull { it.to == newLink.to }
if (existingLink != null && newLink.weight < existingLink.weight) {
curNode = curNode.removeVertex(existingLink)
}
nodes[neighbour.to] = curNode.removeVertexTo(node).addVertex(newLink)
}
}
nodes.remove(node.key)
}
fun <K, V> Node<K, V>.removeVertex(vertex: Vertex<K>): Node<K, V> {
return Node(key, value, vertices - vertex)
}
fun <K, V> Node<K, V>.removeVertexTo(node: Node<K, V>): Node<K, V> {
return Node(key, value, vertices.filter { it.to != node.key }.toList())
}
fun <K, V> Node<K, V>.addVertex(vertex: Vertex<K>): Node<K, V> {
return Node(key, value, vertices + vertex)
}
}
typealias CaveGraph = Graph<String, Int>
typealias Valve = Node<String, Int>
data class State(val position: Valve, val time: Int, val pressure: Int, val pressurePerRound: Int) | 0 | Kotlin | 0 | 0 | 1defe58b8cbaaca17e41b87979c3107c3cb76de0 | 6,917 | Advent-of-Code | MIT License |
src/main/Day13.kt | ssiegler | 572,678,606 | false | {"Kotlin": 76434} | package day13
import utils.readInput
import java.io.Reader
import java.io.StringReader
sealed interface Packet : Comparable<Packet> {
data class Number(val value: Int) : Packet {
override fun compareTo(other: Packet): Int =
when (other) {
is Number -> value.compareTo(other.value)
is PacketList -> PacketList(listOf(this)).compareTo(other)
}
}
data class PacketList(val items: List<Packet>) : Packet {
constructor(vararg values: Int) : this(values.map(::Number))
constructor(vararg values: Packet) : this(values.asList())
override fun compareTo(other: Packet): Int =
when (other) {
is Number -> compareTo(PacketList(listOf(other)))
is PacketList -> {
items
.zip(other.items)
.map { (left, right) -> left.compareTo(right) }
.dropWhile(0::equals)
.firstOrNull()
?: items.size.compareTo(other.items.size)
}
}
}
}
sealed interface Token {
object LeftBracket : Token
object RightBracket : Token
object Comma : Token
object EOF : Token
data class Number(val value: Int) : Token
}
class Scanner(private val input: Reader) {
private var code: Int = input.read()
lateinit var token: Token
fun advance() {
token =
when (code) {
in Int.MIN_VALUE until 0 -> {
Token.EOF
}
in '0'.code..'9'.code -> {
var number: Int = code - '0'.code
readNext()
while (code in '0'.code..'9'.code) {
number = 10 * number + (code - '0'.code)
readNext()
}
Token.Number(number)
}
'['.code -> {
readNext()
Token.LeftBracket
}
']'.code -> {
readNext()
Token.RightBracket
}
','.code -> {
readNext()
Token.Comma
}
else -> {
error("Unknown character: $code")
}
}
}
private fun readNext() {
code = input.read()
}
}
fun List<String>.readPairs(): List<Pair<Packet, Packet>> =
chunked(3).map { (first, second, _) -> first.readPacket() to second.readPacket() }
fun String.readPacket(): Packet = parse(Scanner(StringReader(this)).apply { advance() })
private fun parse(scanner: Scanner): Packet =
when (val token = scanner.token) {
is Token.Number -> Packet.Number(token.value)
Token.LeftBracket -> parseList(scanner)
Token.Comma,
Token.RightBracket,
Token.EOF -> error("Expected number or '[', got $token")
}.also { scanner.advance() }
private fun parseList(scanner: Scanner): Packet.PacketList {
scanner.advance()
val list = mutableListOf<Packet>()
if (scanner.token != Token.RightBracket) {
list.add(parse(scanner))
while (scanner.token == Token.Comma) {
scanner.advance()
list.add(parse(scanner))
}
}
require(scanner.token == Token.RightBracket) { "Expected ']', got ${scanner.token}" }
return Packet.PacketList(list)
}
fun List<String>.readPackets() = filter(String::isNotBlank).map(String::readPacket)
fun part1(filename: String) =
readInput(filename)
.readPairs()
.withIndex()
.filter { (_, value) -> value.first < value.second }
.sumOf { (index, _) -> index + 1 }
val dividers =
listOf(Packet.PacketList(Packet.PacketList(2)), Packet.PacketList(Packet.PacketList(6)))
fun part2(filename: String): Int {
val sorted = (readInput(filename).readPackets() + dividers).sorted()
return (sorted.findIndex(dividers[0])) * sorted.findIndex(dividers[1])
}
private fun List<Packet>.findIndex(divider: Packet.PacketList) = indexOf(divider) + 1
private const val filename = "Day13"
fun main() {
println(part1(filename))
println(part2(filename))
}
| 0 | Kotlin | 0 | 0 | 9133485ca742ec16ee4c7f7f2a78410e66f51d80 | 4,297 | aoc-2022 | Apache License 2.0 |
src/Day02.kt | StephenVinouze | 572,377,941 | false | {"Kotlin": 55719} | import java.lang.IllegalArgumentException
enum class Shape(
val value: Int
) {
Rock(1),
Paper(2),
Scissors(3),
}
enum class Result(val score: Int) {
Loss(0),
Draw(3),
Win(6),
}
fun main() {
fun roundScorePart1(round: String): Int {
val shapes = round.split(" ").take(2)
val opponentShape = when (shapes.first()) {
"A" -> Shape.Rock
"B" -> Shape.Paper
"C" -> Shape.Scissors
else -> throw IllegalArgumentException("Unknown opponent shape")
}
val myShape = when (shapes.last()) {
"X" -> Shape.Rock
"Y" -> Shape.Paper
"Z" -> Shape.Scissors
else -> throw IllegalArgumentException("Unknown shape for myself")
}
val result = when (opponentShape) {
Shape.Rock -> when (myShape) {
Shape.Rock -> Result.Draw
Shape.Paper -> Result.Win
Shape.Scissors -> Result.Loss
}
Shape.Paper -> when (myShape) {
Shape.Rock -> Result.Loss
Shape.Paper -> Result.Draw
Shape.Scissors -> Result.Win
}
Shape.Scissors -> when (myShape) {
Shape.Rock -> Result.Win
Shape.Paper -> Result.Loss
Shape.Scissors -> Result.Draw
}
}
return result.score + myShape.value
}
fun roundScorePart2(round: String): Int {
val shapes = round.split(" ").take(2)
val opponentShape = when (shapes.first()) {
"A" -> Shape.Rock
"B" -> Shape.Paper
"C" -> Shape.Scissors
else -> throw IllegalArgumentException("Unknown opponent shape")
}
val result = when (shapes.last()) {
"X" -> Result.Loss
"Y" -> Result.Draw
"Z" -> Result.Win
else -> throw IllegalArgumentException("Unknown result for myself")
}
val myShape = when (opponentShape) {
Shape.Rock -> when (result) {
Result.Loss -> Shape.Scissors
Result.Draw -> Shape.Rock
Result.Win -> Shape.Paper
}
Shape.Paper -> when (result) {
Result.Loss -> Shape.Rock
Result.Draw -> Shape.Paper
Result.Win -> Shape.Scissors
}
Shape.Scissors -> when (result) {
Result.Loss -> Shape.Paper
Result.Draw -> Shape.Scissors
Result.Win -> Shape.Rock
}
}
return result.score + myShape.value
}
fun part1(input: List<String>): Int =
input.sumOf { roundScorePart1(it) }
fun part2(input: List<String>): Int =
input.sumOf { roundScorePart2(it) }
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 | 11b9c8816ded366aed1a5282a0eb30af20fff0c5 | 3,048 | AdventOfCode2022 | Apache License 2.0 |
src/Day03.kt | konclave | 573,548,763 | false | {"Kotlin": 21601} | fun main() {
fun pointCount(code: Int): Int {
return code - if (code < 97) 38 else 96
}
fun solve1(input: List<String>): Int {
return input.sumOf {
val (cmp1, cmp2) = it.chunked(it.length / 2)
var res = 0
for (c in cmp1) {
if (cmp2.contains(c)) {
res = pointCount(c.code)
}
}
res
}
}
fun solve2(input: List<String>): Int {
return input.chunked(3).sumOf {
val (bp1, bp2, bp3) = it
var res = 0
for (c in bp1) {
if (bp2.contains(c) && bp3.contains(c)) {
res = pointCount(c.code)
break
}
}
res
}
}
val input = readInput("Day03")
println(solve1(input))
println(solve2(input))
}
| 0 | Kotlin | 0 | 0 | 337f8d60ed00007d3ace046eaed407df828dfc22 | 896 | advent-of-code-2022 | Apache License 2.0 |
src/Day24.kt | astrofyz | 572,802,282 | false | {"Kotlin": 124466} | fun main() {
class Blizzard(var pos: Pair<Int, Int>, var step: Pair<Int, Int>){}
fun parseBlizzards(input: List<String>): MutableList<Blizzard> {
var Blizzards = mutableListOf<Blizzard>()
for ((row, line) in input.withIndex()){
for ((col, elem) in line.withIndex()){
when (elem){
'>' -> Blizzards.add(Blizzard(Pair(row, col), Pair(0, 1)))
'<' -> Blizzards.add(Blizzard(Pair(row, col), Pair(0, -1)))
'^' -> Blizzards.add(Blizzard(Pair(row, col), Pair(-1, 0)))
'v' -> Blizzards.add(Blizzard(Pair(row, col), Pair(1, 0)))
else -> continue
}
}
}
return Blizzards
}
infix fun Int.cycle(size: Int): Int {
return when (this) {
0 -> size-1
size -> 1
else -> this
}
}
fun part1(input: List<String>){
val maxRow = input.size
val maxCol = input[0].length
println(maxCol)
var Blizzards = parseBlizzards(input)
var startPos = Pair(0, 1)
var endPos = Pair(maxRow-2, maxCol-2)
fun MutableList<Blizzard>.update(){
for (bliz in this){
// println("updating ${bliz.pos}")
bliz.pos = Pair((bliz.pos.first + bliz.step.first) cycle (maxRow - 1),
(bliz.pos.second + bliz.step.second) cycle (maxCol - 1))
// println("updated to ${bliz.pos}")
}
}
println("starting blizzards points ${Blizzards.map { it.pos }.toList().groupingBy { it }.eachCount()}")
var time = 0
var possibleMoves = mutableListOf<Pair<Int, Int>>()
possibleMoves.add(startPos)
while (true){
Blizzards.update()
// println("Blizzards: ${Blizzards.map { it.pos }.toList().groupingBy { it }.eachCount()}")
var closedPos = Blizzards.map { it.pos }.toSet()
var currentMoves = possibleMoves.map { it }.toMutableList()
for (pos in currentMoves){
for (step in listOf(Pair(1, 0), Pair(-1, 0), Pair(0, 1), Pair(0, -1))){
if ((pos.first+step.first in 1..maxRow-2)&&(pos.second+step.second in 1..maxCol-2)){
possibleMoves.add(Pair(pos.first+step.first, pos.second+step.second))
}
}
}
possibleMoves = possibleMoves.subtract(closedPos).toMutableList()
// println(possibleMoves)
if (endPos in possibleMoves) {println("found $time"); break}
time ++
}
time += 2
println("time to End first $time")
time = 0
startPos = Pair(maxRow-1, maxCol-2)
endPos = Pair(1, 1)
possibleMoves = mutableListOf<Pair<Int, Int>>()
possibleMoves.add(startPos)
while (true){
Blizzards.update()
// println("Blizzards: ${Blizzards.map { it.pos }.toList().groupingBy { it }.eachCount()}")
var closedPos = Blizzards.map { it.pos }.toSet()
var currentMoves = possibleMoves.map { it }.toMutableList()
for (pos in currentMoves){
for (step in listOf(Pair(1, 0), Pair(-1, 0), Pair(0, 1), Pair(0, -1))){
if ((pos.first+step.first in 1..maxRow-2)&&(pos.second+step.second in 1..maxCol-2)){
possibleMoves.add(Pair(pos.first+step.first, pos.second+step.second))
}
}
}
possibleMoves = possibleMoves.subtract(closedPos).toMutableList()
// println(possibleMoves)
if (endPos in possibleMoves) {println("found $time"); break}
time ++
}
time += 2
println("time to start first $time")
time = 0
startPos = Pair(0, 1)
endPos = Pair(maxRow - 2, maxCol - 2)
possibleMoves = mutableListOf<Pair<Int, Int>>()
possibleMoves.add(startPos)
while (true){
Blizzards.update()
// println("Blizzards: ${Blizzards.map { it.pos }.toList().groupingBy { it }.eachCount()}")
var closedPos = Blizzards.map { it.pos }.toSet()
var currentMoves = possibleMoves.map { it }.toMutableList()
for (pos in currentMoves){
for (step in listOf(Pair(1, 0), Pair(-1, 0), Pair(0, 1), Pair(0, -1))){
if ((pos.first+step.first in 1..maxRow-2)&&(pos.second+step.second in 1..maxCol-2)){
possibleMoves.add(Pair(pos.first+step.first, pos.second+step.second))
}
}
}
possibleMoves = possibleMoves.subtract(closedPos).toMutableList()
// println(possibleMoves)
if (endPos in possibleMoves) {println("found $time"); break}
time ++
}
time += 2
println("time to end second $time")
}
val testInput = readInput("Day24")
part1(testInput)
} | 0 | Kotlin | 0 | 0 | a0bc190b391585ce3bb6fe2ba092fa1f437491a6 | 5,072 | aoc22 | Apache License 2.0 |
src/main/kotlin/d7/D7_1.kt | MTender | 734,007,442 | false | {"Kotlin": 108628} | package d7
import input.Input
const val CARD_LABELS = "AKQJT98765432"
data class Hand(
val cards: String,
val bid: Int
) : Comparable<Hand> {
override fun compareTo(other: Hand): Int {
val typeDiff = this.getTypeStrength() - other.getTypeStrength()
if (typeDiff != 0) return typeDiff
for (i in 0..4) {
if (this.cards[i] != other.cards[i]) {
return CARD_LABELS.indexOf(other.cards[i]) - CARD_LABELS.indexOf(this.cards[i])
}
}
return 0
}
private fun getTypeStrength(): Int {
val charCounts = mutableMapOf<Char, Int>()
for (c in cards) {
charCounts[c] = (charCounts[c] ?: 0) + 1
}
return when (charCounts.size) {
5 -> 1 // high card
4 -> 2 // one pair
3 -> {
if (charCounts.values.toSet() == setOf(2, 2, 1)) {
return 3 // two pair
}
return 4 // three of a kind
}
2 -> {
if (charCounts.values.toSet() == setOf(3, 2)) {
return 5 // full house
}
return 6 // four of a kind
}
1 -> 7 // five of a kind
else -> throw RuntimeException("impossible")
}
}
}
fun parseInput(lines: List<String>): List<Hand> {
return lines
.map { it.split(" ") }
.map { Hand(it[0], it[1].toInt()) }
}
fun main() {
val lines = Input.read("input.txt")
val hands = parseInput(lines)
val sortedHands = hands.sorted()
println(sortedHands.mapIndexed { index, hand -> hand.bid * (index + 1) }.sum())
} | 0 | Kotlin | 0 | 0 | a6eec4168b4a98b73d4496c9d610854a0165dbeb | 1,700 | aoc2023-kotlin | MIT License |
src/Utils.kt | jorander | 571,715,475 | false | {"Kotlin": 28471} | import java.io.File
import java.math.BigInteger
import java.security.MessageDigest
/**
* Reads lines from the given input txt file.
*/
fun readInput(name: String) = File("src", "$name.txt").readLines()
/**
* Converts string to md5 hash.
*/
fun String.md5(): String = BigInteger(1, MessageDigest.getInstance("MD5").digest(toByteArray())).toString(16)
/**
* From Day 1 solution.
* Chunks a list by the entry that matches the given predicate.
*/
fun <E> List<E>.chunked(predicate: (E) -> Boolean): List<List<E>> {
tailrec fun <E> List<E>.accumulatedChunked(acc: List<List<E>>, predicate: (E) -> Boolean): List<List<E>> =
if (this.isEmpty()) {
acc
} else {
val firstList = this.takeWhile { !predicate(it) }
val rest = this.dropWhile { !predicate(it) }.dropWhile(predicate)
rest.accumulatedChunked(acc + listOf(firstList), predicate)
}
return this.accumulatedChunked(emptyList(), predicate)
}
/**
* Creates pairs with all combinations of elements in the two collections.
*/
infix fun <E> Collection<E>.cartesianProduct(r2: Collection<E>): List<Pair<E, E>> {
return flatMap { x -> r2.map { y -> x to y } }
}
/**
* Some classes and methods to handle positions and movements in a 2D-space.
*/
data class Position2D(val x: Int, val y: Int) {
infix operator fun plus(movement: Movement2D) = Position2D(this.x + movement.dx, this.y + movement.dy)
infix operator fun minus(other: Position2D) = Movement2D(this.x - other.x, this.y - other.y)
fun isOnOuterEdgeIn(grid: Grid2D<*>) =
(x == 0) || (x == grid.width - 1) || (y == 0) || (y == grid.height - 1)
companion object {
fun from(p: Pair<Int, Int>) = Position2D(p.first, p.second)
}
}
/**
* A zero-indexed 2D-space where (0,0) is in the top left corner.
*/
interface Grid2D<out E> {
val height: Int
val width: Int
val allPositions: List<Position2D>
companion object {
@JvmName("from1")
fun from(data: List<CharSequence>): Grid2D<Char> = ListCharSequenceGrid2D(data)
@JvmName("from2")
fun <E> from(data: List<List<E>>): Grid2D<E> = ListGrid2D(data)
}
operator fun get(position: Position2D): E
}
data class ListGrid2D<out E>(private val data: List<List<E>>) : Grid2D<E> {
override val height: Int
get() = data.size
override val width: Int
get() = data[0].size
override val allPositions: List<Position2D>
get() = ((data[0].indices).toList() cartesianProduct data.indices.toList()).map(Position2D::from)
override fun get(position: Position2D): E = data[position.y][position.x]
}
data class ListCharSequenceGrid2D(private val data: List<CharSequence>) : Grid2D<Char> {
override val height: Int
get() = data.size
override val width: Int
get() = data[0].length
override val allPositions: List<Position2D>
get() = ((0 until data[0].length).toList() cartesianProduct (data.indices.toList())).map(Position2D::from)
override fun get(position: Position2D) = data[position.y][position.x]
}
data class Movement2D(val dx: Int, val dy: Int)
| 0 | Kotlin | 0 | 0 | 1681218293cce611b2c0467924e4c0207f47e00c | 3,155 | advent-of-code-2022 | Apache License 2.0 |
advent/src/test/kotlin/org/elwaxoro/advent/y2022/Dec07.kt | elwaxoro | 328,044,882 | false | {"Kotlin": 376774} | package org.elwaxoro.advent.y2022
import org.elwaxoro.advent.PuzzleDayTester
/**
* Day 7: No Space Left On Device
*/
class Dec07 : PuzzleDayTester(7, 2022) {
/**
* Find directories with total size less than 100000 and add them up
*/
override fun part1(): Any = loader().findDirs().map { it.calcSize() }.filter { it <= 100000 }.sum()// == 1582412L
/**
* Find directories >= the space required for the upgrade file
* Pick the smallest one for deletion
*/
override fun part2(): Any = loader().let { root ->
maxOf(0, 30000000 - (70000000 - root.calcSize())).let { spaceRequired ->
root.findDirs().map { it.calcSize() }.filter { it >= spaceRequired }.min()
}
}// == 3696336L
/**
* every command starts with $ and is followed by 1 or more additional newlines before the next $, so it's the perfect delimiter for this
* start at the root, then run every command and consume any output
* at the end, return a single FSNode marking the root of the filesystem
*/
private fun loader(): FSNode = load(delimiter = "$").map { it.trim() }.filter { it.isNotEmpty() }.let { terminal ->
FSNode(name = "/", isDir = true, parent = null).also { root ->
terminal.fold(root) { dir, cmdAndOutput ->
val split = cmdAndOutput.split("\n")
val cmd = split.first()
val output = split.drop(1)
var workingDir = dir
if (cmd.startsWith("cd")) {
val target = cmd.replace("cd ", "")
workingDir = when (target) {
"/" -> root
".." -> workingDir.parent!!
else -> workingDir.children.first { it.name == target }
}
} else if (cmd.startsWith("ls")) {
output.forEach {
if (it.startsWith("dir")) {
workingDir.children.add(FSNode(name = it.replace("dir ", ""), isDir = true, parent = workingDir))
} else {
val (size, name) = it.split(" ")
workingDir.children.add(FSNode(name = name, isDir = false, size = size.toLong(), parent = workingDir))
}
}
}
workingDir
}
}
}
private data class FSNode(
val name: String,
val isDir: Boolean,
var size: Long = -1,
val parent: FSNode?,
val children: MutableList<FSNode> = mutableListOf(),
) {
/**
* Directory size is the sum of all files and subdirectories
*/
fun calcSize(): Long = if (size >= 0) {
size
} else {
children.sumOf { it.calcSize() }.also { size = it } // cache it
}
/**
* Recursively builds a list of all directories or subdirectories from this node
*/
fun findDirs(): List<FSNode> = if (isDir) {
listOf(this).plus(children.filter { it.isDir }.flatMap { it.findDirs() })
} else {
listOf()
}
}
}
| 0 | Kotlin | 4 | 0 | 1718f2d675f637b97c54631cb869165167bc713c | 3,214 | advent-of-code | MIT License |
src/main/kotlin/clockvapor/telegram/markov/Utils.kt | ClockVapor | 136,247,129 | false | {"Kotlin": 24060} | package clockvapor.telegram.markov
import clockvapor.markov.MarkovChain
val MarkovChain.wordCounts: Map<String, Int>
get() {
val map = hashMapOf<String, Int>()
for ((_, dataMap) in data) {
for ((word, count) in dataMap) {
val sanitized = word.sanitize()
if (sanitized.isNotBlank()) {
map.compute(sanitized.toLowerCase()) { _, n -> n?.plus(count) ?: count }
}
}
}
return map
}
fun scoreMostDistinguishingWords(user: Map<String, Int>, universe: Map<String, Int>): Map<String, Double> {
val scores = linkedMapOf<String, Double>()
val userTotal = user.values.sum()
val universeTotal = universe.values.sum()
for ((word, count) in user) {
scores[word] = Math.pow(count.toDouble(), 1.1) / userTotal / (universe.getValue(word).toDouble() / universeTotal)
}
return scores.toList().sortedWith(Comparator { a, b ->
val c = b.second.compareTo(a.second)
if (c == 0)
a.first.compareTo(b.first)
else
c
}).toMap()
}
fun computeUniverse(wordCountsCollection: Collection<Map<String, Int>>): Map<String, Int> {
val universe = hashMapOf<String, Int>()
for (wordCounts in wordCountsCollection) {
for ((word, count) in wordCounts) {
universe.compute(word) { _, n -> n?.plus(count) ?: count }
}
}
return universe
}
private const val punctuation = "[`~!@#$%^&*()\\-_=+\\[\\],<.>/?\\\\|;:\"]+"
private fun String.sanitize(): String =
replace("“", "\"").replace("”", "\"").replace("‘", "'").replace("’", "'")
.replace(Regex("^$punctuation"), "")
.replace(Regex("$punctuation$"), "")
| 1 | Kotlin | 4 | 5 | b72a68dd2cedd3c19f53fcdb5b3c89f7f1450cd7 | 1,751 | markov-telegram-bot | MIT License |
src/day05/Day05.kt | chskela | 574,228,146 | false | {"Kotlin": 9406} | package day05
import java.io.File
class Stack<T> {
private val mutableList = mutableListOf<T>()
fun push(vararg element: T) {
mutableList.addAll(element)
}
fun pop(): T? {
return if (mutableList.isNotEmpty()) {
mutableList.removeLast()
} else {
null
}
}
fun pop(n: Int): List<T> {
val result = mutableListOf<T>()
result.addAll(mutableList.takeLast(n))
repeat(n) {
mutableList.removeLast()
}
return result
}
override fun toString(): String {
return mutableList.toString()
}
}
fun main() {
fun <A, B, R, T> Pair<A, B>.map(transformA: (A) -> R, transformB: (B) -> T): Pair<R, T> {
return Pair(
transformA(first),
transformB(second)
)
}
fun parseMovements(s: String) = s
.lines()
.map { row ->
row.split(" ")
.filter { it.toIntOrNull() != null }
.map { it.toInt() }
}
fun parseStore(s: String) = s.lines().reversed()
.foldIndexed(mutableMapOf()) { index, acc: MutableMap<Int, Stack<Char>>, str ->
str.forEachIndexed { idx, char ->
if (index == 0 && char.isDigit()) {
val i = char.digitToInt()
acc[i] = Stack<Char>()
}
if (char.isLetter()) {
val i = idx / 4 + 1
val stack = acc[i]
stack?.let { st ->
st.push(char)
acc[i] = st
}
}
}
acc
}
fun parseInput(input: String) = input.split("\n\n")
.foldIndexed("" to "") { index: Int, acc: Pair<String, String>, s: String ->
if (index % 2 != 0) acc.copy(second = s) else acc.copy(first = s)
}.map(
transformA = ::parseStore,
transformB = ::parseMovements
)
fun part1(input: String): String {
val (storeData, movedData) = parseInput(input)
movedData.forEach { (move, from, to) ->
(1..move).forEach { _ ->
val el = storeData[from]?.pop()
el?.let {
storeData[to]?.push(it)
}
}
}
return storeData.values.map { it.pop() }.joinToString("")
}
fun part2(input: String): String {
val (storeData, movedData) = parseInput(input)
movedData.forEach { (move, from, to) ->
val el = storeData[from]?.pop(move)
el?.let {
storeData[to]?.push(*it.toTypedArray())
}
}
return storeData.values.map { it.pop() }.joinToString("")
}
val testInput = File("src/day05/Day05_test.txt").readText()
println(part1(testInput))
println(part2(testInput))
//
val input = File("src/day05/Day05.txt").readText()
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 951d38a894dcf0109fd0847eef9ff3ed3293fca0 | 3,049 | adventofcode-2022-kotlin | Apache License 2.0 |
2022/src/main/kotlin/org/suggs/adventofcode/Day11MonkeyInTheMiddle.kt | suggitpe | 321,028,552 | false | {"Kotlin": 156836} | package org.suggs.adventofcode
import org.slf4j.LoggerFactory
object Day11MonkeyInTheMiddle {
private val log = LoggerFactory.getLogger(this::class.java)
fun countMonkeyInspectionsFrom(data: List<String>, times: Int, worryAction: (Long) -> Long): Long {
val monkeys = data.map { buildMonkeyFrom(it.split("\n")) }
val commonDenominator = monkeys.map { it.testDivisible }.reduce { acc, it -> it * acc }
repeat(times) {
monkeys.forEach { it.redistributeTo(monkeys, commonDenominator, worryAction) }
}
monkeys.map { log.debug("${it.name} inspected items ${it.inspections} times.") }
return monkeys.map { it.inspections }.sortedDescending().take(2).reduce { acc, it -> it * acc }
}
private fun buildMonkeyFrom(monkeyJuice: List<String>) =
Monkey(
monkeyJuice[0].substringBefore(":"),
monkeyJuice[1].substringAfter(":").filterNot { it.isWhitespace() }.split(",").map { it.toLong() },
monkeyJuice[2].substringAfter("=").trim().split(" ").drop(1),
monkeyJuice[3].substringAfter(":").split(" ").last().trim().toLong(),
monkeyJuice[4].split(" ").last().trim().toInt(),
monkeyJuice[5].split(" ").last().trim().toInt()
)
}
data class Monkey(
val name: String,
var items: List<Long>,
val formula: List<String>,
val testDivisible: Long,
val trueMonkey: Int,
val falseMonkey: Int,
var inspections: Long = 0
) {
fun redistributeTo(monkeys: List<Monkey>, commonDenominator: Long, worryAction: (Long) -> Long) {
items.forEach {
val newWorry = worryValueOf(it, commonDenominator, worryAction)
monkeys[destinationMonkey(newWorry)].addNewItem(newWorry)
}
items = listOf()
}
private fun addNewItem(newItem: Long) {
items += newItem
}
private fun worryValueOf(item: Long, commonDenominator: Long, worryAction: (Long) -> Long): Long {
inspections++
val factor = if (formula[1] == "old") item else formula[1].toLong()
val worry = when (formula[0]) {
"*" -> item * factor
"+" -> item + factor
else -> throw IllegalStateException("oops no idea what to do with $formula")
}
return worryAction(worry) % commonDenominator
}
private fun destinationMonkey(item: Long) =
if (item % testDivisible == 0L) trueMonkey else falseMonkey
}
| 0 | Kotlin | 0 | 0 | 9485010cc0ca6e9dff447006d3414cf1709e279e | 2,472 | advent-of-code | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/LongestCycle.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import java.util.LinkedList
import java.util.Queue
import kotlin.math.max
/**
* 2360. Longest Cycle in a Graph
* @see <a href="https://leetcode.com/problems/longest-cycle-in-a-graph/">Source</a>
*/
fun interface LongestCycle {
operator fun invoke(edges: IntArray): Int
}
/**
* Approach 1: Depth First Search
*/
class LongestCycleDFS : LongestCycle {
private var answer = -1
override operator fun invoke(edges: IntArray): Int {
val n: Int = edges.size
val visit = BooleanArray(n)
for (i in 0 until n) {
if (!visit[i]) {
val dist: MutableMap<Int, Int> = HashMap()
dist[i] = 1
dfs(i, edges, dist, visit)
}
}
return answer
}
fun dfs(node: Int, edges: IntArray, dist: MutableMap<Int, Int>, visit: BooleanArray) {
visit[node] = true
val neighbor = edges[node]
if (neighbor != -1 && !visit[neighbor]) {
dist[neighbor] = dist.getOrDefault(node, 0) + 1
dfs(neighbor, edges, dist, visit)
} else if (neighbor != -1 && dist.containsKey(neighbor)) {
answer = max(answer, dist.getOrDefault(node, 0) - dist.getOrDefault(neighbor, 0) + 1)
}
}
}
/**
* Approach 2: Kahn's Algorithm
*/
class LongestCycleKahnsAlgorithm : LongestCycle {
override operator fun invoke(edges: IntArray): Int {
val n: Int = edges.size
val visit = BooleanArray(n)
val inDegree = IntArray(n)
// Count inDegree of each node.
for (edge in edges) {
if (edge != -1) {
inDegree[edge]++
}
}
// Kahn's algorithm starts.
val q: Queue<Int> = LinkedList()
for (i in 0 until n) {
if (inDegree[i] == 0) {
q.offer(i)
}
}
while (q.isNotEmpty()) {
val node: Int = q.poll()
visit[node] = true
val neighbor = edges[node]
if (neighbor != -1) {
inDegree[neighbor]--
if (inDegree[neighbor] == 0) {
q.offer(neighbor)
}
}
}
// Kahn's algorithm ends.
var answer = -1
for (i in 0 until n) {
if (!visit[i]) {
var neighbor = edges[i]
var count = 1
visit[i] = true
// Iterate in the cycle.
while (neighbor != i) {
visit[neighbor] = true
count++
neighbor = edges[neighbor]
}
answer = max(answer, count)
}
}
return answer
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 3,370 | kotlab | Apache License 2.0 |
src/Day01.kt | fex42 | 575,013,600 | false | {"Kotlin": 4342} | fun main() {
println(listOf(1, 5, 2, 4, 3).sortedDescending().take(3))
fun maxCals(input: String) =
input.split("\n\n").map { elf ->
elf.split("\n").map { it.toInt() }
}.map { it.sum() }
.max()
fun part1(input: String): Int {
return maxCals(input)
}
fun part2(input: String) =
input.split("\n\n").map { elf ->
elf.split("\n").map { it.toInt() }
}.map { it.sum() }
.sortedDescending().take(3)
.sum()
// test if implementation meets criteria from the description, like:
val testInput = readText("Day01_test")
check(part1(testInput) == 24000)
val input = readText("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | dd5d9ff58afc615bcac0fd76b86e737833eb7576 | 765 | AuC-2022 | Apache License 2.0 |
src/Day07.kt | lonskiTomasz | 573,032,074 | false | {"Kotlin": 22055} | fun main() {
fun dirs(input: List<String>): MutableMap<String, Long> {
var curr = "."
val dirs: MutableMap<String, Long> = mutableMapOf() // path - size
input.forEach { line ->
when {
"""\$ cd /""".toRegex().matches(line) -> curr = "."
"""\$ cd \.\.""".toRegex().matches(line) -> curr = curr.substringBeforeLast('/')
"""\$ cd (\w+)""".toRegex().matches(line) -> {
val dir = """\$ cd (\w+)""".toRegex()
.matchEntire(line)
?.groupValues?.get(1)
?: throw IllegalArgumentException("Incorrect input line $line")
curr = if (curr.isEmpty()) dir else "$curr/$dir"
}
"""(\d+) (.+)""".toRegex().matches(line) -> {
val (size, _) = """(\d+) (.+)""".toRegex()
.matchEntire(line)
?.destructured
?: throw IllegalArgumentException("Incorrect input line $line")
var dir = curr
while (true) {
dirs[dir] = dirs.getOrDefault(dir, 0) + size.toLong()
if (dir == ".") break
dir = dir.substringBeforeLast('/')
}
}
}
}
return dirs
}
fun part1(input: List<String>) {
val sum = dirs(input).values.sumOf { if (it <= 100000) it else 0 }
println(sum)
}
fun part2(input: List<String>) {
val totalSpace = 70000000
val requiredSpace = 30000000
val dirs = dirs(input)
val outermostDirSize = dirs.getValue(".")
println(dirs.values.filter { totalSpace - (outermostDirSize - it) >= requiredSpace }.min())
}
val inputTest = readInput("day07/input_test")
val input = readInput("day07/input")
part1(inputTest)
part1(input)
part2(inputTest)
part2(input)
} | 0 | Kotlin | 0 | 0 | 9e758788759515049df48fb4b0bced424fb87a30 | 2,021 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/test/kotlin/chapter3/solutions/ex12/listing.kt | DavidGomesh | 680,857,367 | false | {"Kotlin": 204685} | package chapter3.solutions.ex12
import chapter3.List
import chapter3.foldLeft
import chapter3.foldRight
import io.kotest.matchers.shouldBe
import io.kotest.core.spec.style.WordSpec
// tag::init[]
fun <A, B> foldLeftR(xs: List<A>, z: B, f: (B, A) -> B): B =
foldRight(xs, { b: B -> b }, { a, g -> { b -> g(f(b, a)) } })(z)
fun <A, B> foldRightL(xs: List<A>, z: B, f: (A, B) -> B): B =
foldLeft(xs,
{ b: B -> b }
) { g, a ->
{ b ->
g(f(a, b))
}
}(z)
//expanded example
typealias Identity<B> = (B) -> B
fun <A, B> foldLeftRDemystified(
ls: List<A>,
acc: B,
combiner: (B, A) -> B
): B {
val identity: Identity<B> = { b: B -> b }
val combinerDelayer: (A, Identity<B>) -> Identity<B> =
{ a: A, delayedExec: Identity<B> ->
{ b: B ->
delayedExec(combiner(b, a))
}
}
val chain: Identity<B> = foldRight(ls, identity, combinerDelayer)
return chain(acc)
}
// end::init[]
class Solution12 : WordSpec({
"list foldLeftR" should {
"implement foldLeft functionality using foldRight" {
foldLeftR(
List.of(1, 2, 3, 4, 5),
0,
{ x, y -> x + y }) shouldBe 15
foldLeftRDemystified(
List.of(1, 2, 3, 4, 5),
0,
{ x, y -> x + y }) shouldBe 15
}
}
"list foldRightL" should {
"implement foldRight functionality using foldLeft" {
foldRightL(
List.of(1, 2, 3, 4, 5),
0,
{ x, y -> x + y }) shouldBe 15
}
}
})
| 0 | Kotlin | 0 | 0 | 41fd131cd5049cbafce8efff044bc00d8acddebd | 1,653 | fp-kotlin | MIT License |
src/Day04.kt | theofarris27 | 574,591,163 | false | null | fun main() {
fun part1(input: List<String>): Int {
var sum = 0
for (lines in input) {
var half1 = lines.substring(0, lines.indexOf(","))
var half1num1 = half1.substring(0, half1.indexOf("-")).toInt()
var half1num2 = half1.substring(half1.indexOf("-") + 1).toInt()
var half2 = lines.substring(lines.indexOf(",") + 1)
var half2num1 = half2.substring(0, half2.indexOf("-")).toInt()
var half2num2 = half2.substring(half2.indexOf("-") + 1).toInt()
if (half1num1 <= half2num1 && half1num2 >= half2num2) {
sum++
} else if (half2num1 <= half1num1 && half2num2 >= half1num2) {
sum++
}
}
return sum
}
fun part2(input: List<String>): Int {
var sum = 0
for (lines in input) {
var half1 = lines.substring(0, lines.indexOf(","))
var half1num1 = half1.substring(0, half1.indexOf("-")).toInt()
var half1num2 = half1.substring(half1.indexOf("-") + 1).toInt()
var half2 = lines.substring(lines.indexOf(",") + 1)
var half2num1 = half2.substring(0, half2.indexOf("-")).toInt()
var half2num2 = half2.substring(half2.indexOf("-") + 1).toInt()
if (half1num1 <= half2num1 && half1num2 >= half2num2) {
sum++
} else if (half2num1 <= half1num1 && half2num2 >= half1num2) {
sum++
}
else if(half1num2 >= half2num1 && half1num2 <= half2num2){
sum++
}
else if(half1num1 >= half2num1 && half1num1 <= half2num2){
sum++
}
}
return sum
}
val input = readInput("Sections")
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | cf77115471a7f1caeedf13ae7a5cdcbdcec3eab7 | 2,026 | AdventOfCode | Apache License 2.0 |
solutions/src/LengthOfLongestFibSequence.kt | JustAnotherSoftwareDeveloper | 139,743,481 | false | {"Kotlin": 305071, "Java": 14982} | class LengthOfLongestFibSequence {
//https://leetcode.com/problems/length-of-longest-fibonacci-subsequence/description/
fun lenLongestFibSubseq(A: IntArray): Int {
var longest = 0
var index = 0
// O(n)
val valuesToIndex = A.mapIndexed { index, i -> Pair(i, index) }.associateBy({ it.first }, { it.second })
val max = A.last()
var sequences: Map<Int, List<List<Int>>> = mutableMapOf()
val init: MutableList<List<Int>> = mutableListOf()
//Prepopulate : O(n^2)
for (i in 0 until A.size) {
var j = i + 1
while (j < A.size) {
val fib = A[i]+A[j]
init.add(listOf(A[i], A[j]))
j++
}
}
sequences += 2 to init
longest = 2
// O(log(n))
while (sequences.getOrDefault(longest, listOf()).isNotEmpty()) {
var nextLevel: MutableList<List<Int>> = mutableListOf()
var currLongest = sequences[longest]!!
currLongest.forEach { it -> //O(n^2)
val previous = it[it.size-1]
val beforeThat = it[it.size - 2]
val fib = previous + beforeThat
if (valuesToIndex.containsKey(fib) && valuesToIndex.getOrDefault(fib, Int.MAX_VALUE) > valuesToIndex.getOrDefault(previous,Int.MAX_VALUE)) {
nextLevel.add(it + fib)
}
}
longest++
sequences += longest to nextLevel
}
return when {
longest - 1 < 3 -> 0
else -> longest - 1
}
}
} | 0 | Kotlin | 0 | 0 | fa4a9089be4af420a4ad51938a276657b2e4301f | 1,623 | leetcode-solutions | MIT License |
src/Day18.kt | tigerxy | 575,114,927 | false | {"Kotlin": 21255} | fun main() {
fun part1(input: List<String>): Int =
(0..2)
.flatMap { dimension ->
input
.parse()
.groupBy { it.filterIndexed { idx, _ -> idx != dimension }.toPair() }
.map { it.value.map { it[dimension] }.sorted() }
}
.sumOf {
if (it.size > 1) {
it.zipWithNext { a, b -> if (b - a > 1) 2 else 0 }.sum()
} else {
0
} + 2
}
fun part2(input: List<String>): Int = 0
val day = "18"
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day${day}_test")
val testOutput1 = part1(testInput)
println("part1_test=$testOutput1")
assert(testOutput1 == 13)
val testOutput2 = part2(testInput)
println("part2_test=$testOutput2")
assert(testOutput1 == 0)
val input = readInput("Day$day")
println("part1=${part1(input)}")
println("part2=${part2(input)}")
}
private fun <E> List<E>.toPair() =
Pair(first(), last())
private fun List<String>.parse(): List<List<Int>> =
map { it.split(',').mapToInt() } | 0 | Kotlin | 0 | 1 | d516a3b8516a37fbb261a551cffe44b939f81146 | 1,209 | aoc-2022-in-kotlin | Apache License 2.0 |
src/Day03.kt | gnuphobia | 578,967,785 | false | {"Kotlin": 17559} | fun main() {
fun part1(input: List<String>): Int {
var score: Int = 0
for (contents: String in input) {
var ruck: Rucksack = Rucksack(contents)
score += ruck.itemPriority
}
return score
}
fun part2(input: List<String>): Int {
var journey: MutableList<RuckGroup> = mutableListOf<RuckGroup>()
var count = 0
var ruckGroup = RuckGroup()
for(item in input) {
ruckGroup.addRucker(item)
count++
if (count > 2) {
journey.add(ruckGroup)
ruckGroup = RuckGroup()
count = 0
}
}
var priorityScore: Int = 0
val priority = PriorityScore()
for(group in journey) {
group.findCommonItem()
priorityScore += priority.itemPriority(group.commonItem)
}
return priorityScore
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
var priority1: Int = part1(testInput)
check(priority1 == 157)
var part2ExpectedAnswer = 70
var part2Answer = part2(testInput)
check(part2Answer == part2ExpectedAnswer)
val input = readInput("Day03")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | a1b348ec33f85642534c46af8c4a69e7b78234ab | 1,329 | aoc2022kt | Apache License 2.0 |
2020/src/main/kotlin/sh/weller/adventofcode/twentytwenty/Day21.kt | Guruth | 328,467,380 | false | {"Kotlin": 188298, "Rust": 13289, "Elixir": 1833} | package sh.weller.adventofcode.twentytwenty
fun List<String>.day21Part2(): String {
val allergenIngredientsPairs = this.parseInput()
val allergenSet = allergenIngredientsPairs.flatMap { it.first }.toSet()
// All possible ingredients that contain allergens
val ingredientsThatAppearForEveryAllergen = mutableMapOf<String, MutableList<String>>()
allergenSet
.forEach { allergen ->
val listsWithAllergen =
allergenIngredientsPairs
.filter { it.first.contains(allergen) }
.map { it.second }
val ingredientsThatAreInAllLists = listsWithAllergen.flatten().groupBy { it }
.filter { it.value.size == listsWithAllergen.size }
ingredientsThatAppearForEveryAllergen[allergen] =
ingredientsThatAreInAllLists.map { it.key }.toMutableList()
}
val foundAllergenIngredientPairs = mutableListOf<Pair<String, String>>()
do {
val notProcessedIngredients = ingredientsThatAppearForEveryAllergen
.filter { foo ->
foundAllergenIngredientPairs.map { it.first }.contains(foo.key).not()
}
.mapValues {
it.value.filter { possibleIngredient ->
foundAllergenIngredientPairs.map { foundIngredient -> foundIngredient.second }
.contains(possibleIngredient).not()
}
}
notProcessedIngredients
.filter { it.value.size == 1 }
.forEach {
foundAllergenIngredientPairs.add(Pair(it.key, it.value.single()))
}
} while (ingredientsThatAppearForEveryAllergen.size != foundAllergenIngredientPairs.size)
return foundAllergenIngredientPairs.sortedBy { it.first }.map { it.second }.joinToString(",")
}
fun List<String>.day21Part1(): Int {
val allergenIngredientsPairs = this.parseInput()
val allergenSet = allergenIngredientsPairs.flatMap { it.first }.toSet()
// All possible ingredients that contain allergens
val ingredientsThatAppearForEveryAllergen = mutableMapOf<String, MutableList<String>>()
allergenSet
.forEach { allergen ->
val listsWithAllergen =
allergenIngredientsPairs
.filter { it.first.contains(allergen) }
.map { it.second }
val ingredientsThatAreInAllLists = listsWithAllergen.flatten().groupBy { it }
.filter { it.value.size == listsWithAllergen.size }
ingredientsThatAppearForEveryAllergen[allergen] =
ingredientsThatAreInAllLists.map { it.key }.toMutableList()
}
val foundAllergenIngredientPairs = mutableListOf<Pair<String, String>>()
do {
val notProcessedIngredients = ingredientsThatAppearForEveryAllergen
.filter { foo ->
foundAllergenIngredientPairs.map { it.first }.contains(foo.key).not()
}
.mapValues {
it.value.filter { possibleIngredient ->
foundAllergenIngredientPairs.map { foundIngredient -> foundIngredient.second }
.contains(possibleIngredient).not()
}
}
notProcessedIngredients
.filter { it.value.size == 1 }
.forEach {
foundAllergenIngredientPairs.add(Pair(it.key, it.value.single()))
}
} while (ingredientsThatAppearForEveryAllergen.size != foundAllergenIngredientPairs.size)
return allergenIngredientsPairs.flatMap { it.second }
.filter { foundAllergenIngredientPairs.map { it.second }.contains(it).not() }
.size
}
private fun List<String>.parseInput(): List<Pair<List<String>, List<String>>> =
this
.map { line ->
val ingredients = line.split("(")[0].split(" ").filter { it.isNotBlank() }.map { it.trim() }
val allergens =
line.split("(")[1].dropLast(1).drop(8).split(",").filter { it.isNotBlank() }.map { it.trim() }
return@map allergens to ingredients
} | 0 | Kotlin | 0 | 0 | 69ac07025ce520cdf285b0faa5131ee5962bd69b | 4,123 | AdventOfCode | MIT License |
2021/src/day01/day1.kt | scrubskip | 160,313,272 | false | {"Kotlin": 198319, "Python": 114888, "Dart": 86314} | package day01
import java.io.File
fun main() {
// println(findIncreasesSlidingWindow(listOf(199, 200, 208, 210, 200, 207, 240, 269, 260, 263),
// 3))
println(findIncreasesFold(listOf(199, 200, 208, 210, 200, 207, 240, 269, 260, 263)))
val lineList = mutableListOf<Int>()
File("src/day01","day1.txt").useLines { lines -> lines.forEach { lineList.add(it.toInt()) } }
println(findIncreasesSlidingWindow(lineList, 3))
}
fun findIncreases(input: List<Int>): Int {
var increases: Int = 0
var prevValue: Int? = null
for (value in input) {
if (prevValue != null && value > prevValue) {
increases++
}
prevValue = value
}
return increases
}
fun findIncreasesFold(input: List<Int>): Int {
return input.foldIndexed(0) { index, increases, value ->
if (index > 0 && value > input[index - 1]) increases + 1 else increases
}
}
fun findIncreasesSlidingWindow(input: List<Int>, windowSize: Int): Int {
var increases: Int = 0
var index: Int = windowSize
var prevWindowValue: Int? = null
while (index <= input.size) {
var windowValue: Int = input.slice(index - windowSize..index - 1).sum()
// println("$index : $windowValue")
if (prevWindowValue != null && windowValue > prevWindowValue) {
increases++
}
prevWindowValue = windowValue
index++
}
return increases
}
| 0 | Kotlin | 0 | 0 | a5b7f69b43ad02b9356d19c15ce478866e6c38a1 | 1,431 | adventofcode | Apache License 2.0 |
advent-of-code-2023/src/Day14.kt | osipxd | 572,825,805 | false | {"Kotlin": 141640, "Shell": 4083, "Scala": 693} | import lib.matrix.*
private typealias Platform = Matrix<Char>
private typealias PlatformSnapshot = List<String>
private const val DAY = "Day14"
fun main() {
fun testInput() = readInput("${DAY}_test")
fun input() = readInput(DAY)
"Part 1" {
part1(testInput()) shouldBe 136
measureAnswer { part1(input()) }
}
"Part 2" {
part2(testInput()) shouldBe 64
measureAnswer { part2(input()) }
}
}
private fun part1(input: Platform): Int {
input.tilt(TiltDirection.NORTH)
return input.calculateNorthWeight()
}
private fun part2(input: Platform): Int {
val memory = mutableListOf<List<String>>()
val rotationsCount = 1_000_000_000
repeat(rotationsCount) { i ->
input.rotate()
val snapshot = input.snapshot()
val cycleStart = memory.indexOf(snapshot)
if (cycleStart != -1) {
val cycleSize = i - cycleStart
val positionInCycle = (rotationsCount - cycleStart - 1) % cycleSize
return memory[cycleStart + positionInCycle]
.calculateNorthWeight()
}
memory += snapshot
}
error("Where is the cycle?")
}
private fun Platform.rotate() {
TiltDirection.entries.forEach(::tilt)
}
private fun Platform.tilt(direction: TiltDirection) {
for (mainAxis in indices) {
var freePosition = 0
for (movingAxis in indices) {
val position = direction.derivePosition(mainAxis, movingAxis, lastIndex)
when (this[position]) {
'O' -> {
val positionToSet = direction.derivePosition(mainAxis, freePosition, lastIndex)
this[position] = '.'
this[positionToSet] = 'O'
freePosition++
}
'#' -> freePosition = movingAxis + 1
}
}
}
}
// Think about more lightweight snapshot here.
private fun Platform.snapshot(): PlatformSnapshot = rows().map { it.joinToString("") }
private fun Platform.calculateNorthWeight(): Int = snapshot().calculateNorthWeight()
@JvmName("calculateNorthWeightSnapshot")
private fun PlatformSnapshot.calculateNorthWeight(): Int {
var weight = 0
for (col in indices) {
for (row in indices) {
if (this[row][col] == 'O') weight += size - row
}
}
return weight
}
private fun readInput(name: String) = readMatrix(name)
.also { input -> check(input.rowCount == input.columnCount) }
private enum class TiltDirection(val horizontal: Boolean, val forward: Boolean) {
NORTH(horizontal = false, forward = true),
WEST(horizontal = true, forward = true),
SOUTH(horizontal = false, forward = false),
EAST(horizontal = true, forward = false);
val vertical: Boolean get() = !horizontal
val backward: Boolean get() = !forward
fun derivePosition(mainAxis: Int, movingAxis: Int, maximum: Int): Position {
fun deriveAxis(orientation: Boolean) = when {
orientation && forward -> movingAxis
orientation && backward -> maximum - movingAxis
else -> mainAxis
}
return Position(deriveAxis(vertical), deriveAxis(horizontal))
}
}
// Matrix is always square so slightly simplify API
private val Platform.indices get() = rowIndices
private val Platform.lastIndex get() = lastRowIndex
| 0 | Kotlin | 0 | 5 | 6a67946122abb759fddf33dae408db662213a072 | 3,373 | advent-of-code | Apache License 2.0 |
src/Day09.kt | cerberus97 | 579,910,396 | false | {"Kotlin": 11722} | import kotlin.math.abs
import kotlin.system.exitProcess
fun main() {
data class Point(val x: Int, val y: Int)
fun Point.move(dir: Char): Point = when (dir) {
'R' -> Point(x + 1, y)
'L' -> Point(x - 1, y)
'D' -> Point(x, y + 1)
'U' -> Point(x, y - 1)
else -> exitProcess(-1)
}
fun findTailPosition(headPosition: Point, tailPosition: Point): Point {
if (abs(headPosition.x - tailPosition.x) <= 1 && abs(headPosition.y - tailPosition.y) <= 1) return tailPosition
return Point(
listOf(tailPosition.x, tailPosition.x - 1, tailPosition.x + 1).minBy { x -> abs(x - headPosition.x) },
listOf(tailPosition.y, tailPosition.y - 1, tailPosition.y + 1).minBy { y -> abs(y - headPosition.y) },
)
}
fun part1(input: List<String>): Int {
var headPosition = Point(0, 0)
var tailPosition = Point(0, 0)
val visited = mutableSetOf(tailPosition)
input.forEach { row ->
val dir = row[0]
val cnt = row.substringAfter(' ').toInt()
repeat(cnt) {
headPosition = headPosition.move(dir)
tailPosition = findTailPosition(headPosition, tailPosition)
visited += tailPosition
}
}
return visited.size
}
fun part2(input: List<String>): Int {
val ropeLength = 10
val rope = MutableList(ropeLength) { Point(0, 0) }
val visited = mutableSetOf(rope.last())
input.forEach { row ->
val dir = row[0]
val cnt = row.substringAfter(' ').toInt()
repeat(cnt) {
rope[0] = rope[0].move(dir)
for (i in 1 until ropeLength) {
rope[i] = findTailPosition(rope[i - 1], rope[i])
}
visited += rope.last()
}
}
return visited.size
}
val input = readInput("in")
part1(input).println()
part2(input).println()
} | 0 | Kotlin | 0 | 0 | ed7b5bd7ad90bfa85e868fa2a2cdefead087d710 | 1,785 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/day02/Day02.kt | iliascholl | 572,982,464 | false | {"Kotlin": 8373} | package day02
import readInput
fun main() {
val left = "ABC"
val right = "XYZ"
val choices = left.length
fun part1(input: List<String>) = input.map { strategy ->
strategy.split(" ").let {
left.indexOf(it.first()) to right.indexOf(it.last())
}
}.sumOf { (first, second) ->
when (Math.floorMod(first - second, choices)) {
0 -> 3
1 -> 0
2 -> 6
else -> throw IllegalStateException()
} + second + 1
}
fun part2(input: List<String>) = input.map { strategy ->
strategy.split(" ").let {
left.indexOf(it.first()) to right.indexOf(it.last())
}
}.sumOf { (first, second) ->
second * 3 + Math.floorMod(first + second - 1, 3) + 1
}
val testInput = readInput("day02/test")
check(part1(testInput) == 3 * 1 + 3 * 2 + 3 * 3 + 3 * 3 + 3 * 6)
val input = readInput("day02/input")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 26db12ddf4731e4ee84f45e1dc4385707f9e1d05 | 997 | advent-of-code-kotlin | Apache License 2.0 |
kotlin/src/com/daily/algothrim/leetcode/FindTheDifference.kt | idisfkj | 291,855,545 | false | null | package com.daily.algothrim.leetcode
/**
* 389. 找不同
*
* 给定两个字符串 s 和 t,它们只包含小写字母。
*
* 字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。
*
* 请找出在 t 中被添加的字母。
*
* 示例 1:
*
* 输入:s = "abcd", t = "abcde"
* 输出:"e"
* 解释:'e' 是那个被添加的字母。
* 示例 2:
*
* 输入:s = "", t = "y"
* 输出:"y"
* 示例 3:
*
* 输入:s = "a", t = "aa"
* 输出:"a"
* 示例 4:
*
* 输入:s = "ae", t = "aea"
* 输出:"a"
*
* 提示:
*
* 0 <= s.length <= 1000
* t.length == s.length + 1
* s 和 t 只包含小写字母
* */
class FindTheDifference {
companion object {
@JvmStatic
fun main(args: Array<String>) {
println(FindTheDifference().solution("abcd", "abcde"))
println(FindTheDifference().solution("", "y"))
println(FindTheDifference().solution("a", "aa"))
println(FindTheDifference().solution("ae", "aea"))
println()
println(FindTheDifference().solution2("abcd", "abcde"))
println(FindTheDifference().solution2("", "y"))
println(FindTheDifference().solution2("a", "aa"))
println(FindTheDifference().solution2("ae", "aea"))
println()
println(FindTheDifference().solution3("abcd", "abcde"))
println(FindTheDifference().solution3("", "y"))
println(FindTheDifference().solution3("a", "aa"))
println(FindTheDifference().solution3("ae", "aea"))
println()
println(FindTheDifference().solution4("abcd", "abcde"))
println(FindTheDifference().solution4("", "y"))
println(FindTheDifference().solution4("a", "aa"))
println(FindTheDifference().solution4("ae", "aea"))
}
}
/**
* 哈希
* 时间:O(n)
* 空间:O(n)
*/
fun solution(s: String, t: String): Char {
val map = hashMapOf<Char, Int>()
s.forEach {
map[it] = map[it]?.plus(1) ?: 1
}
t.forEach {
if (map[it] == null || map[it] == 0) return it
map[it] = map[it]?.minus(1) ?: 0
}
return ' '
}
/**
* 计数
* 时间:O(n)
* 空间:O(n)
*/
fun solution2(s: String, t: String): Char {
val a = 'a'.toInt()
val bucket = IntArray(26)
s.forEach {
bucket[it.toInt() - a]++
}
t.forEach {
if (bucket[it.toInt() - a] == 0) return it
bucket[it.toInt() - a]--
}
return ' '
}
/**
* 求和
* 时间:O(n)
* 空间:O(1)
*/
fun solution3(s: String, t: String): Char {
var sSum = 0
var tSum = 0
s.forEach {
sSum += it.toInt()
}
t.forEach {
tSum += it.toInt()
}
return (tSum - sSum).toChar()
}
/**
* 位运算
* 时间:O(n)
* 空间:O(1)
*/
fun solution4(s: String, t: String): Char {
var r = 0
s.forEach {
r = r.xor(it.toInt())
}
t.forEach {
r = r.xor(it.toInt())
}
return r.toChar()
}
} | 0 | Kotlin | 9 | 59 | 9de2b21d3bcd41cd03f0f7dd19136db93824a0fa | 3,330 | daily_algorithm | Apache License 2.0 |
kotlin/src/main/kotlin/de/p58i/advent-02.kt | mspoeri | 573,120,274 | false | {"Kotlin": 31279} | package de.p58i
import java.io.File
import java.util.LinkedList
val permutations = setOf(
mapOf(
"X" to Move.ROCK,
"Y" to Move.PAPER,
"Z" to Move.SCISSORS,
),
mapOf(
"X" to Move.ROCK,
"Y" to Move.SCISSORS,
"Z" to Move.PAPER,
),
mapOf(
"X" to Move.SCISSORS,
"Y" to Move.PAPER,
"Z" to Move.ROCK,
),
mapOf(
"X" to Move.SCISSORS,
"Y" to Move.ROCK,
"Z" to Move.PAPER,
),
mapOf(
"X" to Move.PAPER,
"Y" to Move.SCISSORS,
"Z" to Move.ROCK,
),
mapOf(
"X" to Move.PAPER,
"Y" to Move.ROCK,
"Z" to Move.SCISSORS,
),
)
enum class Move(val value: Int) {
ROCK(1) {
override val beats: Move
get() = SCISSORS
override val beatenBy: Move
get() = PAPER
},
PAPER(2) {
override val beats: Move
get() = ROCK
override val beatenBy: Move
get() = SCISSORS
},
SCISSORS(3) {
override val beats: Move
get() = PAPER
override val beatenBy: Move
get() = ROCK
};
abstract val beats: Move
abstract val beatenBy: Move
fun beats(other: Move): Boolean = other == beats
fun draws(other: Move): Boolean = other == this
}
fun String.toMove(): Move = when (this) {
"A" -> Move.ROCK
"B" -> Move.PAPER
"C" -> Move.SCISSORS
else -> throw IllegalArgumentException()
}
class SeedRound(
val opponentMove: Move,
val ownMove: String,
)
class GameRound(
val opponentMove: Move,
val ownMove: Move,
) {
val score: Int
get() {
return if (win) {
6 + ownMove.value
} else if (draw) {
3 + ownMove.value
} else {
ownMove.value
}
}
val win = ownMove.beats(opponentMove)
val draw = ownMove.draws(opponentMove)
}
class Game(
val rounds: Collection<GameRound>,
val mappings: Map<String, Move>
) {
val xMapping = lazy { mappings["X"]!! }
val yMapping = lazy { mappings["Y"]!! }
val zMapping = lazy { mappings["Z"]!! }
val wins = rounds.count { it.win }
val draws = rounds.count { it.draw }
val score: Int
get() = rounds.sumOf { it.score }
}
fun createPermutationGames(seedGame: Collection<SeedRound>): List<Game> {
return permutations.map { mapping ->
Game(seedGame.map { seedRound -> GameRound(seedRound.opponentMove, mapping[seedRound.ownMove]!!) }, mapping)
}
}
fun String.toWinLoseDraw() = when (this) {
"X" -> "LOSE"
"Y" -> "DRAW"
"Z" -> "WIN"
else -> throw IllegalArgumentException()
}
fun calcCounterMove(opponentMove: Move, outcome: String): Move = when (outcome) {
"LOSE" -> opponentMove.beats
"DRAW" -> opponentMove
"WIN" -> opponentMove.beatenBy
else -> throw IllegalArgumentException()
}
fun createWinLoseStrategyGame(seedGame: Collection<SeedRound>) = Game(
seedGame.map {
SeedRound(it.opponentMove, it.ownMove.toWinLoseDraw())
}.map {
GameRound(it.opponentMove, calcCounterMove(it.opponentMove, it.ownMove))
}, emptyMap()
)
fun main() {
val seedGame = LinkedList<SeedRound>()
File("./task-inputs/advent-02.input").forEachLine {
val opponentMove = it.split(" ").first()
val ownMove = it.split(" ").last()
seedGame.add(SeedRound(opponentMove.toMove(), ownMove))
}
performPermutationStrategy(seedGame)
val winLoseGame = createWinLoseStrategyGame(seedGame)
println("""
Win Lose Game Scores ${winLoseGame.score}[${winLoseGame.rounds.size}/${winLoseGame.wins}/${winLoseGame.draws}]
""".trimIndent())
}
private fun performPermutationStrategy(seedGame: LinkedList<SeedRound>) {
val games = createPermutationGames(seedGame)
println(
games.joinToString(separator = "\n") {
"""
Game score: ${it.score}[${it.rounds.size}/${it.wins}/${it.draws}]
X = ${it.xMapping}
Y = ${it.yMapping}
Z = ${it.zMapping}
""".trimIndent()
}
)
val bestGame = games.maxBy { it.score }
println("""
Best Game Scores ${bestGame.score}
X = ${bestGame.xMapping}
Y = ${bestGame.yMapping}
Z = ${bestGame.zMapping}
""".trimIndent())
}
| 0 | Kotlin | 0 | 1 | 62d7f145702d9126a80dac6d820831eeb4104bd0 | 4,686 | Advent-of-Code-2022 | MIT License |
src/main/kotlin/day4.kt | gautemo | 433,582,833 | false | {"Kotlin": 91784} | import shared.getText
fun playBingo(input: String, looseMode: Boolean = false): Int{
val sections = input.trim().split("\n\n")
val numbers = sections.first().split(",").map { it.toInt() }
val boards = sections.drop(1).map { Board(it) }
for(number in numbers){
for(board in boards.filter { !it.bingo }){
board.playNumber(number)
if(board.bingo){
if(!looseMode || boards.all { it.bingo }){
return board.uncheckedSum() * number
}
}
}
}
throw Exception("Someone should have won by now")
}
class Board(input: String){
val lines = input.split("\n").map { line -> line.trim().split(Regex("\\s+")).map { number -> BingoNumber(number.toInt()) } }
var bingo = false
private set
fun playNumber(number: Int){
lines.forEach { line -> line.find { bingoNumber -> bingoNumber.number == number }?.checked = true }
bingo = horizontalWin() || verticalWin()
}
private fun horizontalWin() = lines.any { line -> line.all { bingoNumber -> bingoNumber.checked } }
private fun verticalWin(): Boolean{
val length = lines.first().size
for(i in 0 until length){
if(lines.all { line -> line[i].checked }) return true
}
return false
}
fun uncheckedSum(): Int{
return lines.sumOf { line -> line.filter { bingoNumber -> !bingoNumber.checked }.sumOf { bingoNumber -> bingoNumber.number } }
}
}
data class BingoNumber(val number: Int, var checked: Boolean = false)
fun main(){
val input = getText("day4.txt")
val result = playBingo(input)
println(result)
val resultLoosingBoard = playBingo(input, true)
println(resultLoosingBoard)
} | 0 | Kotlin | 0 | 0 | c50d872601ba52474fcf9451a78e3e1bcfa476f7 | 1,768 | AdventOfCode2021 | MIT License |
src/main/java/com/barneyb/aoc/aoc2022/day16/ProboscideaVolcanium.kt | barneyb | 553,291,150 | false | {"Kotlin": 184395, "Java": 104225, "HTML": 6307, "JavaScript": 5601, "Shell": 3219, "CSS": 1020} | package com.barneyb.aoc.aoc2022.day16
import com.barneyb.aoc.util.Solver
import com.barneyb.aoc.util.toSlice
import com.barneyb.util.HashMap
import com.barneyb.util.Queue
import com.barneyb.util.Stack
fun main() {
Solver.execute(
::parse,
::maximumPressureRelease, // 1880
::maximumPressureReleaseWithElephant, // 2520
)
}
internal data class Valve(
val name: String,
val rate: Int,
val tunnels: List<String>,
)
// Valve AA has flow rate=0; tunnels lead to valves DD, II, BB
private val lineMatcher =
Regex("Valve ([A-Z]+) has flow rate=(\\d+); tunnels? leads? to valves? ([A-Z]+(, [A-Z]+)*)")
internal fun parseValves(input: String) =
input.toSlice()
.trim()
.lines()
.map(lineMatcher::matchEntire)
.map { m ->
val (name, rate, tunnels) = m!!.groupValues.drop(1)
Valve(name, rate.toInt(), tunnels.split(',').map(String::trim))
}
internal fun parse(input: String) =
buildGraph(parseValves(input))
private const val START_VALVE = "AA"
private typealias Graph = HashMap<Valve, HashMap<Valve, Int>>
private val Graph.startValve
get() = keys.first { it.name == START_VALVE }
private fun buildGraph(valves: List<Valve>): Graph {
val index = HashMap<String, Valve>().apply {
for (v in valves)
put(v.name, v)
}
val adjacent = Graph().apply {
for (v in valves) {
put(v, HashMap<Valve, Int>().apply {
for (t in v.tunnels)
put(index[t], 1)
})
}
}
// printGraphviz(adjacent)
for (v in valves) {
if (v.rate > 0 || v.name == START_VALVE) continue
val adj = adjacent[v]
for ((a, ad) in adj) {
for ((b, bd) in adj) {
if (a == b) continue
val curr = if (adjacent[a].contains(b)) adjacent[a][b]
else Int.MAX_VALUE
val new = ad + bd
if (new < curr) {
adjacent[a][b] = new
adjacent[b][a] = new
}
}
adjacent[a].remove(v)
}
adjacent.remove(v)
}
// printGraphviz(adjacent)
val again = Graph()
for (v in adjacent.keys) {
val temp = HashMap<Valve, Int>()
val queue = Queue(Pair(v, 0))
while (queue.isNotEmpty()) {
val (s, d) = queue.remove()
if (!temp.contains(s) || temp[s] > d) {
temp[s] = d
s.tunnels.forEach {
queue.enqueue(Pair(index[it], d + 1))
}
}
}
again[v] = HashMap<Valve, Int>().apply {
temp.filter { (s, _) ->
s !== v && s.rate > 0
}.forEach(this::put)
}
}
// printGraphviz(again)
return again
}
@Suppress("unused")
private fun printGraphviz(adjacent: Graph) {
println(buildString {
append("digraph {\n")
for ((v, adj) in adjacent) {
append(" ${v.name} [label=\"${v.name} (${v.rate})\"${if (v.name == START_VALVE) ",style=filled,fillcolor=lightgreen" else ""}];")
for ((o, d) in adj) {
append("${v.name} -> ${o.name} [label=$d];")
}
append('\n')
}
append("}\n")
})
}
private fun walk(adjacent: Graph, start: Step): Int {
// printGraphviz(adjacent)
val queue = Stack(start)
val maxRate = adjacent.keys.sumOf(Valve::rate)
var best = Int.MIN_VALUE
val visited = HashMap<Set<Valve>, Int>()
while (queue.isNotEmpty()) {
val step = queue.remove()
val remaining = step.minutesLeft
if (remaining < 0) continue
if (step.projected > best)
best = step.projected
else if (visited.contains(step.open))
if (visited[step.open] >= step.projected)
continue
visited[step.open] = step.projected
if (step.rate == maxRate)
continue
else if (step.projected + remaining * (maxRate - step.rate) <= best)
continue
for ((v, d) in adjacent[step.valve])
if (remaining - 1 > d && !step.isOpen(v))
queue.add(step.moveAndOpen(v, d))
}
return best
}
internal fun maximumPressureRelease(graph: Graph) =
walk(graph, Solo(29, graph.startValve))
internal fun maximumPressureReleaseWithElephant(graph: Graph) =
walk(graph, Team(25, graph.startValve))
| 0 | Kotlin | 0 | 0 | 8b5956164ff0be79a27f68ef09a9e7171cc91995 | 4,498 | aoc-2022 | MIT License |
src/adventofcode/blueschu/y2017/day07/solution.kt | blueschu | 112,979,855 | false | null | package adventofcode.blueschu.y2017.day07
import java.io.File
import java.lang.RuntimeException
import kotlin.test.assertEquals
fun input(): List<String> =
File("resources/y2017/day07.txt").useLines { it.toList() }
fun runDemoAssertions() {
val demoTower = parseTower(
listOf(
"pbga (66)",
"xhth (57)",
"ebii (61)",
"havc (66)",
"ktlj (57)",
"fwft (72) -> ktlj, cntj, xhth",
"qoyq (66)",
"padx (45) -> pbga, havc, qoyq",
"tknk (41) -> ugml, padx, fwft",
"jptl (61)",
"ugml (68) -> gyxo, ebii, jptl",
"gyxo (61)",
"cntj (57)"
)
)
assertEquals("tknk", demoTower.name)
assertEquals(60, newWeightOfBadNode(demoTower))
}
fun main(args: Array<String>) {
runDemoAssertions()
val towerRoot = parseTower(input())
println("Part 1: ${towerRoot.name}")
println("Part 2: ${newWeightOfBadNode(towerRoot)}")
}
data class TowerNode(val name: String, val weight: Int) {
var parent: TowerNode? = null
private set
val children = mutableListOf<TowerNode>()
inline val isRoot get() = parent == null
inline val isLeaf get() = children.isEmpty()
fun addChild(node: TowerNode) {
if (node.parent != null) {
throw IllegalArgumentException("Node is already a member of a tree")
}
node.parent = this
children.add(node)
}
fun branchWeight(): Int =
weight + if (isLeaf) 0 else children.map { it.branchWeight() }.sum()
fun findRoot(): TowerNode = if (isRoot) this else parent!!.findRoot()
}
fun parseTower(structureList: List<String>): TowerNode {
val pattern = "^(\\w+)\\s\\((\\d+)\\)(?:\\s->\\s([\\w,\\s]+))?$".toRegex()
val parsedStructure = structureList.map {
pattern.matchEntire(it) ?: throw IllegalStateException("Tower structure contains malformed data")
}
// all nodes with name and weight
val nodes = parsedStructure.map {
val (name, weight) = it.destructured
name to TowerNode(name, weight.toInt())
}.toMap() // map faster than repetitive List#find { it.name == name }
// map node name to list of child names
val nonLeafNodes = parsedStructure
.filter { it.groups[3] != null }
.associateBy(
{ it.groups[1]!!.value },
{ it.groups[3]!!.value.split(",\\s+".toRegex()) }
)
nonLeafNodes.forEach {
val (name, children) = it
children.forEach {
nodes[name]!!.addChild(nodes[it]!!)
}
}
// return the root node
return nodes.values.first().findRoot()
}
class BranchAlreadyBalancedException : RuntimeException()
// Could be more time efficient by iterating over child indexes
// However, using groupBy allows for a more concise implementation
fun nextUnbalancedNode(node: TowerNode): TowerNode {
val nodes: List<TowerNode> = node.children
if (2 == nodes.size) {
return try {
nextUnbalancedNode(nodes[0])
} catch (e: BranchAlreadyBalancedException) {
nextUnbalancedNode(nodes[1])
}
}
return nodes.groupBy(TowerNode::branchWeight)
.values
.find { it.size == 1 }?.get(0) ?: throw BranchAlreadyBalancedException()
}
fun newWeightOfBadNode(tower: TowerNode): Int {
var badNode = tower
// Climb tower until branch is balanced
try {
while (true) {
badNode = nextUnbalancedNode(badNode)
}
} catch (e: BranchAlreadyBalancedException) {
// all of the node's children are balanced - the bad node has been found
}
// Ugly and rather inefficient, but its functional
val correctBranchWeight = badNode
.parent!!
.children
.groupBy(TowerNode::branchWeight)
.values
.find { it.size > 1 }!!
.get(0)
.branchWeight()
val delta = badNode.branchWeight() - correctBranchWeight
return badNode.weight - delta
}
| 0 | Kotlin | 0 | 0 | 9f2031b91cce4fe290d86d557ebef5a6efe109ed | 4,040 | Advent-Of-Code | MIT License |
src/main/kotlin/me/peckb/aoc/_2023/calendar/day19/Day19.kt | peckb1 | 433,943,215 | false | {"Kotlin": 956135} | package me.peckb.aoc._2023.calendar.day19
import me.peckb.aoc._2023.calendar.day19.Rule.*
import javax.inject.Inject
import me.peckb.aoc.generators.InputGenerator.InputGeneratorFactory
class Day19 @Inject constructor(
private val generatorFactory: InputGeneratorFactory,
) {
fun partOne(filename: String) = generatorFactory.forFile(filename).read { input ->
val (xmasData, workflowData) = input.toList().partition { it.startsWith('{') }
val workflows = workflowData.dropLast(1)
.map(::workflow)
.associateBy { it.name }
xmasData.map(::xmas)
.filter { workflows.accept(it) }
.sumOf { it.value }
}
fun partTwo(filename: String) = generatorFactory.forFile(filename).read { input ->
val (_, workflowData) = input.toList().partition { it.startsWith('{') }
val workflows = workflowData.dropLast(1)
.plus(listOf("A{}", "R{}"))
.map(::workflow)
.associateBy { it.name }
countAccepted(workflows, workflows["in"]!!)
}
private fun Map<String, Workflow>.accept(xmas: XMAS): Boolean {
var nextWorkflow = "in"
while (nextWorkflow != "A" && nextWorkflow != "R") {
nextWorkflow = get(nextWorkflow)?.rules?.firstNotNullOf { it.apply(xmas) } ?: "R"
}
return nextWorkflow == "A"
}
private fun countAccepted(
workflows: Map<String, Workflow>,
workflow: Workflow,
validXmas: ValidXmas = ValidXmas(),
): Long {
return when (workflow.name) {
"A" -> validXmas.allowed()
"R" -> 0
else -> {
var remainingXmas = validXmas
return workflow.rules.sumOf { rule ->
when (rule) {
is GreaterThan -> {
val limitedXmas = remainingXmas.adjustGreaterThan(rule.variableName, rule.value + 1)
remainingXmas = remainingXmas.adjustLessThan(rule.variableName, rule.value)
countAccepted(workflows, workflows[rule.ifTrue]!!, limitedXmas)
}
is LessThan -> {
val limitedXmas = remainingXmas.adjustLessThan(rule.variableName, rule.value - 1)
remainingXmas = remainingXmas.adjustGreaterThan(rule.variableName, rule.value)
countAccepted(workflows, workflows[rule.ifTrue]!!, limitedXmas)
}
is Static -> {
countAccepted(workflows, workflows[rule.result]!!, remainingXmas)
}
}
}
}
}
}
private fun workflow(line: String): Workflow {
// ex{x>10:one,m<20:two,a>30:R,A}
val name = line.takeWhile { it != '{' }
val rules = line.substring(name.length + 1, line.length - 1)
.split(",")
.map { ruleString ->
if (ruleString.contains(':')) {
// we have a condition then an "answer"
val (check, ifTrue) = ruleString.split(':')
when (val operation = check[1]) {
'>' -> GreaterThan(check[0], check.substring(2).toInt(), ifTrue)
'<' -> LessThan(check[0], check.substring(2).toInt(), ifTrue)
else -> throw IllegalArgumentException("Unknown operation $operation")
}
} else {
// we just have an answer
Static(ruleString)
}
}
return Workflow(name, rules)
}
private fun xmas(line: String): XMAS {
// {x=787,m=2655,a=1222,s=2876}
val (x, m, a, s) = line.substring(1, line.length - 1)
.split(',')
.map { it.drop(2).toInt() }
return XMAS(x, m, a, s)
}
}
| 0 | Kotlin | 1 | 3 | 2625719b657eb22c83af95abfb25eb275dbfee6a | 3,452 | advent-of-code | MIT License |
y2021/src/main/kotlin/adventofcode/y2021/Day17.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2021
import adventofcode.io.AdventSolution
import adventofcode.util.vector.Vec2
object Day17 : AdventSolution(2021, 17, "Trick Shot") {
override fun solvePartOne(input: String): Int {
val (_,yT) = parse(input)
return yT.first * (yT.first+1) / 2
}
override fun solvePartTwo(input: String): Int {
val (xT,yT) = parse(input)
val dx = 0..xT.last
val dy = yT.first until -yT.first
return dy.flatMap { y -> dx.map { x -> Vec2(x, y) } }
.count { velocity ->
generateSequence(Vec2(0, 0) to velocity) { (p, v) ->
(p + v) to Vec2(if (v.x > 0) v.x - 1 else v.x, v.y - 1)
}
.takeWhile { (p, _) -> p.x <= xT.last && p.y >= yT.first }
.any { (p, _) -> p.x in xT && p.y in yT }
}
}
fun parse(input: String): Pair<IntRange, IntRange> {
val (x0,x1,y0,y1) = """target area: x=(-?\d+)\.\.(-?\d+), y=(-?\d+)\.\.(-?\d+)""".toRegex().matchEntire(input)!!.destructured
return x0.toInt()..x1.toInt() to y0.toInt()..y1.toInt()
}
}
| 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 1,140 | advent-of-code | MIT License |
src/day03/Day03.kt | martindacos | 572,700,466 | false | {"Kotlin": 12412} | package day03
import readInput
fun main() {
fun calculatePriority(intersect: Set<Char>): Int {
val number = if (intersect.first().isUpperCase()) {
intersect.first().code - 38
} else {
intersect.first().code - 96
}
return number
}
fun part1(input: List<String>): Int {
var priority = 0
for (content in input) {
val chunkedContent: List<String> = content.chunked(content.length / 2)
val list1 = chunkedContent[0].toSet()
val list2 = chunkedContent[1].toSet()
val intersect = list1.intersect(list2)
val number = calculatePriority(intersect)
priority += number
}
return priority
}
fun part2(input: List<String>): Int {
var priority = 0
for (i in 3..input.size step 3) {
val elf1 = input[i-3].toSet()
val elf2 = input[i-2].toSet()
val elf3 = input[i-1].toSet()
val intersect = elf1.intersect(elf2).intersect(elf3)
val number = calculatePriority(intersect)
priority += number
}
return priority
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("/day03/Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("/day03/Day03")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | f288750fccf5fbc41e8ac03598aab6a2b2f6d58a | 1,475 | 2022-advent-of-code-kotlin | Apache License 2.0 |
src/Day01.kt | n0irx | 572,845,006 | false | {"Kotlin": 2392} | import java.util.PriorityQueue
fun main() {
// TC: O(n), only looping through the list of calories once
// TC: O(1), only need to hold tempSum, and maxSum variable
fun part1(input: List<String>): Int {
var tempSum = 0; var maxSum = 0
for (num in input) {
if (num != "") {
tempSum += Integer.parseInt(num)
maxSum = maxOf(tempSum, maxSum)
} else {
tempSum = 0
}
}
return maxSum
}
// TC: O(n), only looping through the list of calories once
// TC: O(1), need to store 3 of the max calories of elf
fun part2(input: List<String>): Int {
// maxHeap will hold the order of max elf's calories
val maxHeap = PriorityQueue<Int> { p1, p2 -> p1 - p2 }
var tempSum = 0; var maxSum = 0
for (num in input) {
// empty string indicate a separator for each elf's calories
if (num != "") {
tempSum += Integer.parseInt(num)
maxSum = maxOf(tempSum, maxSum)
} else {
// current elf's calories finished calculated
maxHeap.add(tempSum)
if (maxHeap.size > 3) {
maxHeap.poll()
}
tempSum = 0
}
}
// get the max three value
var maxThree = 0
for (i in 1..3) {
maxThree += maxHeap.poll()
}
return maxThree
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 1)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 7a7c2027c32419ad1f82c38a071699ad5bbbbb14 | 1,742 | advent-of-code-kotlin | Apache License 2.0 |
src/day01/solution.kt | bohdandan | 729,357,703 | false | {"Kotlin": 80367} | package day01
import println
import readInput
fun main() {
var spelledDigits = mapOf(
"one" to 1,
"two" to 2,
"three" to 3,
"four" to 4,
"five" to 5,
"six" to 6,
"seven" to 7,
"eight" to 8,
"nine" to 9
)
fun getFirstDigit(str: String, fromTheBeginning: Boolean = true): Int {
var input = if (fromTheBeginning) str else str.reversed()
for (index in str.indices) {
val char = input[index]
if (char.isDigit()) return Character.getNumericValue(char);
for ((key, value) in spelledDigits) {
var searchString = if (fromTheBeginning) key else key.reversed()
if (input.startsWith(searchString, index)) return value
}
}
return 0;
}
fun decode(input: List<String>): Int {
return input.stream()
.map {it ->
var first = getFirstDigit(it)
var last = getFirstDigit(it, false)
"$first$last".toInt()
}
.toList().sum()
}
check(decode(listOf("two1nine")) == 29)
val testInput1 = readInput("day01/test1")
check(decode(testInput1) == 142)
val testInput2 = readInput("day01/test2")
check(decode(testInput2) == 281)
val input = readInput("day01/input")
decode(input).println()
}
| 0 | Kotlin | 0 | 0 | 92735c19035b87af79aba57ce5fae5d96dde3788 | 1,400 | advent-of-code-2023 | Apache License 2.0 |
kotlin/src/com/daily/algothrim/leetcode/hard/FindMedianSortedArrays.kt | idisfkj | 291,855,545 | false | null | package com.daily.algothrim.leetcode.hard
/**
* 4. 寻找两个正序数组的中位数
*
* 给定两个大小分别为 m 和 n 的正序(从小到大)数组 nums1 和 nums2。请你找出并返回这两个正序数组的 中位数 。
*
*/
class FindMedianSortedArrays {
companion object {
@JvmStatic
fun main(args: Array<String>) {
println(FindMedianSortedArrays().findMedianSortedArrays(intArrayOf(1, 3), intArrayOf(2)))
println(FindMedianSortedArrays().findMedianSortedArrays(intArrayOf(1, 2), intArrayOf(3, 4)))
}
}
/**
* lg(n+m)
*/
fun findMedianSortedArrays(nums1: IntArray, nums2: IntArray): Double {
val size1 = nums1.size
val size2 = nums2.size
val totalSize = size1 + size2
return if (totalSize % 2 == 1) {
val k = totalSize / 2
getKthElement(nums1, nums2, k + 1)
} else {
val k1 = totalSize / 2
val k2 = totalSize / 2 - 1
(getKthElement(nums1, nums2, k1 + 1) + getKthElement(nums1, nums2, k2 + 1)) / 2.0
}
}
private fun getKthElement(nums1: IntArray, nums2: IntArray, k: Int): Double {
val size1 = nums1.size
val size2 = nums2.size
var index1 = 0
var index2 = 0
var kthElement = k
while (true) {
if (index1 == size1) {
return nums2[index2 + kthElement - 1].toDouble()
}
if (index2 == size2) {
return nums1[index1 + kthElement - 1].toDouble()
}
if (kthElement == 1) return Math.min(nums1[index1], nums2[index2]).toDouble()
val half = kthElement / 2
val currentIndex1 = Math.min(index1 + half, size1) - 1
val currentIndex2 = Math.min(index2 + half, size2) - 1
val node1 = nums1[currentIndex1]
val node2 = nums2[currentIndex2]
if (node1 <= node2) {
kthElement -= currentIndex1 - index1 + 1
index1 = currentIndex1 + 1
} else {
kthElement -= currentIndex2 - index2 + 1
index2 = currentIndex2 + 1
}
}
}
} | 0 | Kotlin | 9 | 59 | 9de2b21d3bcd41cd03f0f7dd19136db93824a0fa | 2,229 | daily_algorithm | Apache License 2.0 |
src/Day06.kt | timmiller17 | 577,546,596 | false | {"Kotlin": 44667} | fun main() {
fun part1(input: List<String>): Int {
val signal = input[0]
for (i in 0..signal.length - 4) {
if (signal[i] != signal[i + 1] &&
signal[i] != signal[i + 2] &&
signal[i] != signal[i + 3] &&
signal[i + 1] != signal[i + 2] &&
signal[i + 1] != signal[i + 3] &&
signal[i + 2] != signal[i + 3]
) {
return i + 4
}
}
return 0
}
fun part2(input: List<String>): Int {
val signal = input[0]
for (i in 0..signal.length - 14) {
val substring = signal.substring(i, i + 14)
if (substring.allUnique()) {
return i + 14
}
}
return 0
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day06_test")
check(part1(testInput) == 7)
check(part2(testInput) == 19)
val input = readInput("Day06")
part1(input).println()
part2(input).println()
}
fun String.allUnique(): Boolean {
for ((index, item) in this.withIndex()) {
if (this.substring(index + 1, this.length).contains(item)) {
return false
}
}
return true
} | 0 | Kotlin | 0 | 0 | b6d6b647c7bb0e6d9e5697c28d20e15bfa14406c | 1,283 | advent-of-code-2022 | Apache License 2.0 |
2022/src/day13/Day13.kt | scrubskip | 160,313,272 | false | {"Kotlin": 198319, "Python": 114888, "Dart": 86314} | package day13
import java.io.File
import java.util.*
fun main() {
runFileInput("src/day13/day13input.txt")
val input = mutableListOf<String>()
input.addAll(File("src/day13/day13input.txt").readLines())
input.add("[[2]]")
input.add("[[6]]")
println(getSortedIndexMultiplier(input.filter { it.isNotBlank() }.map { parseInput(it) }))
}
fun runFileInput(inputFile: String): Int {
val input = File(inputFile).readLines()
val indices = mutableListOf<Int>()
input.filter { it.isNotBlank() }.chunked(2).forEachIndexed { index, values ->
if (compareLists(parseInput(values[0]), parseInput(values[1])) == -1) {
indices.add(index + 1)
println("Found ${values[0]} < ${values[1]}")
}
}
val count = input.filter { it.isNotBlank() }.chunked(2).size
println("compared $count pairs and found ${indices.size} correct")
println(indices.sum())
return indices.sum()
}
fun getSortedIndexMultiplier(input: List<List<Any>>): Int {
val sortedList = input.sortedWith { left, right -> compareLists(left, right) }
val indexLow = sortedList.indexOf(listOf(listOf(2))) + 1
val indexHigh = sortedList.indexOf(listOf(listOf(6))) + 1
return indexLow * indexHigh
}
fun parseInput(input: String): List<Any> {
if (input.isEmpty() || !input.startsWith("[")) {
throw Exception("invalid input: $input")
}
val stack = Stack<MutableList<Any>>()
var currentList = stack.push(mutableListOf())
var index = 1
var valIndex = -1
while (index < input.length) {
when (val currentChar = input[index]) {
'[' -> {
val newList = mutableListOf<Any>()
currentList.add(newList)
stack.push(currentList)
currentList = newList
}
']', ',' -> {
if (valIndex >= 0) {
// Parse from valIndex to here
currentList?.add(input.substring(valIndex, index).toInt())
valIndex = -1
}
if (currentChar == ']') {
currentList = stack.pop()
}
}
else -> {
if (valIndex == -1 && currentChar.isDigit()) {
valIndex = index
}
}
}
index++
}
return currentList
}
/**
* @return -1 if left is lower, 1 if right is higher, 0 if equal
*/
@Suppress("UNCHECKED_CAST")
fun compareLists(left: List<Any>, right: List<Any>): Int {
if (left.isEmpty() && right.isNotEmpty()) {
// left ran out of items
return -1
}
var index = 0
while (index < left.size) {
var leftVal = left[index]
if (index > right.size - 1) {
// right ran out of items
return 1
}
var rightVal = right[index]
if (leftVal is Int && rightVal is Int) {
if (leftVal > rightVal) {
return 1
} else if (leftVal < rightVal) {
return -1
}
} else {
var listReturn = -2
if (leftVal is List<*> && rightVal is List<*>) {
listReturn = compareLists(leftVal as List<Any>, rightVal as List<Any>)
} else if (leftVal is Int && rightVal is List<*>) {
listReturn = compareLists(listOf(leftVal), rightVal as List<Any>)
} else if (leftVal is List<*> && rightVal is Int) {
listReturn = compareLists(leftVal as List<Any>, listOf(rightVal))
}
if (listReturn == -2) {
throw Exception("Invalid items in list.")
}
if (listReturn != 0) {
return listReturn
}
}
index++
}
// Ran out of left items. If the right is also out of items
return if (index > right.size) 1 else if (index < right.size) -1 else 0
} | 0 | Kotlin | 0 | 0 | a5b7f69b43ad02b9356d19c15ce478866e6c38a1 | 3,958 | adventofcode | Apache License 2.0 |
usvm-util/src/main/kotlin/org/usvm/algorithms/WeightedAaTree.kt | UnitTestBot | 586,907,774 | false | {"Kotlin": 2547205, "Java": 471958} | package org.usvm.algorithms
import java.util.*
import kotlin.math.min
data class AaTreeNode<T>(
/**
* Value attached to the node.
*/
val value: T,
/**
* Weight attached to the node.
*/
val weight: Double,
/**
* Sum of the children's weights.
*/
val weightSum: Double,
/**
* Node's depth in the tree. 1 for root node, 2 for its children etc.
*/
val level: Int,
/**
* Reference to the left child.
*/
val left: AaTreeNode<T>?,
/**
* Reference to the right child.
*/
val right: AaTreeNode<T>?
)
/**
* Balanced AA-tree of [AaTreeNode].
*
* @param comparator comparator to arrange elements in the tree. Doesn't affect the element's weights.
*/
class WeightedAaTree<T>(private val comparator: Comparator<T>) {
var count: Int = 0
private set
var root: AaTreeNode<T>? = null
private set
private fun AaTreeNode<T>.update(
value: T = this.value,
weight: Double = this.weight,
level: Int = this.level,
left: AaTreeNode<T>? = this.left,
right: AaTreeNode<T>? = this.right
): AaTreeNode<T> {
val leftWeightSum = left?.weightSum ?: 0.0
val rightWeightSum = right?.weightSum ?: 0.0
return AaTreeNode(value = value, weight = weight, weightSum = leftWeightSum + rightWeightSum + weight, level = level, left = left, right = right)
}
private fun AaTreeNode<T>.skew(): AaTreeNode<T> {
if (left?.level == level) {
return left.update(right = update(left = left.right))
}
return this
}
private fun AaTreeNode<T>.split(): AaTreeNode<T> {
if (level == right?.right?.level) {
return right.update(level = right.level + 1, left = update(right = right.left))
}
return this
}
private tailrec fun addRec(value: T, weight: Double, insertTo: AaTreeNode<T>?, k: (AaTreeNode<T>) -> AaTreeNode<T>): AaTreeNode<T> {
if (insertTo == null) {
count++
return k(AaTreeNode(value, weight, weight, 1, null, null))
}
val compareResult = comparator.compare(value, insertTo.value)
return when {
compareResult < 0 ->
addRec(value, weight, insertTo.left) { k(insertTo.update(left = it).skew().split()) }
compareResult > 0 ->
addRec(value, weight, insertTo.right) { k(insertTo.update(right = it).skew().split()) }
else -> insertTo
}
}
private fun AaTreeNode<T>.decreaseLevel(): AaTreeNode<T> {
val shouldBe = min(left?.level ?: 0, right?.level ?: 0) + 1
if (shouldBe >= level) {
return this
}
val updatedRight =
if (shouldBe >= (right?.level ?: 0)) {
right
} else {
checkNotNull(right)
right.update(level = shouldBe)
}
return update(level = shouldBe, right = updatedRight)
}
private fun AaTreeNode<T>.succ(): AaTreeNode<T>? {
var node = this.right
while (node?.left != null) {
node = node.left
}
return node
}
private fun AaTreeNode<T>.pred(): AaTreeNode<T>? {
var node = this.left
while (node?.right != null) {
node = node.right
}
return node
}
private fun AaTreeNode<T>.balanceAfterRemove(): AaTreeNode<T> {
return decreaseLevel().skew().run {
val skewedRight = right?.skew()
val skewedRightRight = skewedRight?.right?.skew()
update(right = skewedRight?.update(right = skewedRightRight))
.split()
.run { update(right = right?.split()) }
}
}
private tailrec fun removeRec(value: T, deleteFrom: AaTreeNode<T>?, k: (AaTreeNode<T>?) -> AaTreeNode<T>?): AaTreeNode<T>? {
if (deleteFrom == null) {
return null
}
val compareResult = comparator.compare(value, deleteFrom.value)
return when {
compareResult < 0 ->
removeRec(value, deleteFrom.left) { k(deleteFrom.update(left = it).balanceAfterRemove()) }
compareResult > 0 ->
removeRec(value, deleteFrom.right) { k(deleteFrom.update(right = it).balanceAfterRemove()) }
else -> {
when {
deleteFrom.right == null && deleteFrom.level == 1 -> {
count--
k(null)
}
deleteFrom.left == null -> {
val succ = deleteFrom.succ()
checkNotNull(succ)
removeRec(succ.value, deleteFrom.right) { k(deleteFrom.update(value = succ.value, right = it).balanceAfterRemove()) }
}
else -> {
val pred = deleteFrom.pred()
checkNotNull(pred)
removeRec(pred.value, deleteFrom.left) { k(deleteFrom.update(value = pred.value, left = it).balanceAfterRemove()) }
}
}
}
}
}
/**
* Adds an element with specified weight.
*
* @return True if the element didn't exist in the tree and was added.
*/
fun add(value: T, weight: Double): Boolean {
val prevCount = count
root = addRec(value, weight, root) { it }
return prevCount != count
}
/**
* Removes an element.
*
* @return True if the element existed in the tree and was removed.
*/
fun remove(value: T): Boolean {
val prevCount = count
root = removeRec(value, root) { it }
return prevCount != count
}
/**
* Returns the sequence of nodes in pre-order manner.
*/
fun preOrderTraversal(): Sequence<AaTreeNode<T>> {
val currentRoot = root ?: return emptySequence()
var node: AaTreeNode<T>
val stack = Stack<AaTreeNode<T>>()
stack.push(currentRoot)
return sequence {
while (stack.isNotEmpty()) {
node = stack.pop()
yield(node)
if (node.right != null) {
stack.push(node.right)
}
if (node.left != null) {
stack.push(node.left)
}
}
}
}
}
| 39 | Kotlin | 0 | 7 | 94c5a49a0812737024dee5be9d642f22baf991a2 | 6,467 | usvm | Apache License 2.0 |
src/Day02Part2.kt | RickShaa | 572,623,247 | false | {"Kotlin": 34294} | fun main() {
val fileName = "day02.txt"
val testFileName = "day02_test.txt"
val input:String = FileUtil.getTrimmedText(fileName);
val testInput:String = FileUtil.getTrimmedText(testFileName);
val WON = 6;
val DRAW =3;
//Create Lookup map to store
val choiceMap = mapOf<String, Choice>(
"A" to Choice.ROCK,
"B" to Choice.PAPER,
"C" to Choice.SCISSORS,
)
val outcomeMap = mapOf<String,Outcome>(
"Z" to Outcome.WIN,
"X" to Outcome.LOSS,
"Y" to Outcome.DRAW
)
val pointsMap = mapOf<Choice, Int>(
Choice.ROCK to 1,
Choice.PAPER to 2,
Choice.SCISSORS to 3
)
fun getPointsByChoice(choice: Choice):Int?{
return pointsMap[choice]
}
fun getChoice(key:String): Choice? {
return choiceMap[key]
}
fun getOutcome(key:String): Outcome?{
return outcomeMap[key]
}
fun calculateDrawOutCome(opponentChoice:Choice): Int {
//just return same choice as opponent
return getPointsByChoice(opponentChoice)!!
}
fun calculateWinOutCome(opponentChoice: Choice): Int? {
return if(opponentChoice == Choice.ROCK){
getPointsByChoice(Choice.PAPER)
}else if(opponentChoice == Choice.PAPER){
getPointsByChoice(Choice.SCISSORS)
}else{
getPointsByChoice(Choice.ROCK)
}
}
fun calculateLossOutCome(opponentChoice: Choice):Int?{
if(opponentChoice == Choice.ROCK){
return getPointsByChoice(Choice.SCISSORS)
}else if(opponentChoice == Choice.PAPER){
return getPointsByChoice(Choice.ROCK)
}
return getPointsByChoice(Choice.PAPER)
}
var finalScore = 0;
val matches = input.split("\n");
matches.forEach{
match->
val picks = match.split(" ")
//Translate A,B,X to ROCK, PAPER, SCISSORS and translate outcome
val preferredOutcome = getOutcome(picks[1])!!
val oppChoice = getChoice(picks[0])!!
//draw case
if(preferredOutcome == Outcome.DRAW){
finalScore+= DRAW + calculateDrawOutCome(oppChoice)
}else if(preferredOutcome == Outcome.WIN){
finalScore+= WON + calculateWinOutCome(oppChoice)!!
}else{
finalScore+= calculateLossOutCome(oppChoice)!!
}
}
println(finalScore)
}
enum class Outcome {
WIN,
DRAW,
LOSS
}
| 0 | Kotlin | 0 | 1 | 76257b971649e656c1be6436f8cb70b80d5c992b | 2,469 | aoc | Apache License 2.0 |
src/main/kotlin/Day24.kt | clechasseur | 318,029,920 | false | null | import org.clechasseur.adventofcode2020.Day24Data
import org.clechasseur.adventofcode2020.Pt
object Day24 {
private val input = Day24Data.input
fun part1(): Int {
val floor = Floor()
input.lines().map { it.toHexDirections() }.forEach { floor.followAndFlip(it) }
return floor.blackTilesCount
}
fun part2(): Int {
val floor = Floor()
input.lines().map { it.toHexDirections() }.forEach { floor.followAndFlip(it) }
repeat(100) { floor.sleepOnIt() }
return floor.blackTilesCount
}
private val hexDirectionRegex = """[ns]?[ew]""".toRegex()
private enum class HexDirection(val value: String, val displacement: Pt) {
NW("nw", Pt(-1, -1)),
NE("ne", Pt(1, -1)),
E("e", Pt(2, 0)),
SE("se", Pt(1, 1)),
SW("sw", Pt(-1, 1)),
W("w", Pt(-2, 0));
companion object {
fun withValue(value: String): HexDirection = values().find { it.value == value }!!
}
}
private fun Pt.move(hexDirection: HexDirection): Pt = this + hexDirection.displacement
private fun Pt.move(hexDirections: List<HexDirection>): Pt = hexDirections.fold(this) { pt, disp ->
pt.move(disp)
}
private fun String.toHexDirections(): List<HexDirection> = hexDirectionRegex.findAll(this).map {
HexDirection.withValue(it.value)
}.toList()
private class Floor {
private val blackTiles = mutableSetOf<Pt>()
val blackTilesCount: Int
get() = blackTiles.size
fun flip(pt: Pt) {
if (blackTiles.contains(pt)) {
blackTiles.remove(pt)
} else {
blackTiles.add(pt)
}
}
fun followAndFlip(hexDirections: List<HexDirection>) {
flip(Pt.ZERO.move(hexDirections))
}
fun sleepOnIt() {
(blackTiles.filter { blackTile ->
val neighbours = blackNeighbours(blackTile)
neighbours == 0 || neighbours > 2
} + whiteTiles.filter { whiteTile ->
blackNeighbours(whiteTile) == 2
}).forEach { tile ->
flip(tile)
}
}
private val whiteTiles: Set<Pt>
get() = blackTiles.flatMap { blackTile ->
HexDirection.values().map { blackTile.move(it) }
}.filter { tile ->
tile !in blackTiles
}.toSet()
private fun blackNeighbours(pt: Pt): Int = HexDirection.values().count { dir ->
blackTiles.contains(pt.move(dir))
}
}
}
| 0 | Kotlin | 0 | 0 | 6173c9da58e3118803ff6ec5b1f1fc1c134516cb | 2,613 | adventofcode2020 | MIT License |
AOC-2017/src/main/kotlin/Day14.kt | sagar-viradiya | 117,343,471 | false | {"Kotlin": 72737} | object Day14 {
fun part1(input: String) = (0..127).sumBy { getBinaryKnotHash(Day10.part2("$input-$it"), true).length }
fun part2(input: String): Int {
val disk = getDisk(input)
var regions = 0
for (i in 0 until disk.size) {
for (j in 0 until disk[i].size) {
if (disk[i][j]) {
disk[i][j] = false
regions++
clearRegions(i, j, disk)
}
}
}
return regions
}
private fun getBinaryKnotHash(input: String, reduced: Boolean = false): String {
val reducedBinaryKnotHash = StringBuffer()
input.forEach { reducedBinaryKnotHash.append(if (reduced) getReducedBinary(it) else getBinary(it)) }
return reducedBinaryKnotHash.toString()
}
private fun getDisk(input: String): List<MutableList<Boolean>> {
return (0..127).map { getBinaryKnotHash(Day10.part2("$input-$it")) }
.map { it.map { it == '1' }.toMutableList() }
}
private fun clearRegions(row: Int, column: Int, disk: List<MutableList<Boolean>>) {
if (row > 0 && disk[row - 1][column]) {
disk[row - 1][column] = false
clearRegions(row - 1, column, disk)
}
if (row < 127 && disk[row + 1][column]) {
disk[row + 1][column] = false
clearRegions(row + 1, column, disk)
}
if (column > 0 && disk[row][column - 1]) {
disk[row][column - 1] = false
clearRegions(row, column - 1, disk)
}
if (column < 127 && disk[row][column + 1]) {
disk[row][column + 1] = false
clearRegions(row, column + 1, disk)
}
}
private fun getReducedBinary(input: Char) = when(input) {
'0' -> ""
'1', '2', '4', '8' -> "1"
'3', '5', '6', '9', 'a', 'c' -> "11"
'7', 'b', 'd', 'e' -> "111"
'f' -> "1111"
else -> throw IllegalStateException("Illegal hex value")
}
private fun getBinary(input: Char) = when(input) {
'0' -> "0000"
'1' -> "0001"
'2' -> "0010"
'3' -> "0011"
'4' -> "0100"
'5' -> "0101"
'6' -> "0110"
'7' -> "0111"
'8' -> "1000"
'9' -> "1001"
'a' -> "1010"
'b' -> "1011"
'c' -> "1100"
'd' -> "1101"
'e' -> "1110"
'f' -> "1111"
else -> throw IllegalStateException("Illegal hex value")
}
} | 0 | Kotlin | 0 | 0 | 7f88418f4eb5bb59a69333595dffa19bee270064 | 2,519 | advent-of-code | MIT License |
src/main/aoc2020/Day22.kt | nibarius | 154,152,607 | false | {"Kotlin": 963896} | package aoc2020
class Day22(input: List<String>) {
private val players = input.map { player -> player.split("\n").drop(1).map { it.toInt() } }
private fun normalGame(players: List<MutableList<Int>>): Pair<Int, MutableList<Int>> {
while (players.all { it.isNotEmpty() }) {
val cards = List(2) { players[it].removeAt(0) }
val winner = cards.withIndex().maxByOrNull { it.value }!!.index
players[winner].addAll(List(2) { cards[(winner + it) % 2] })
}
return 0 to players.first { it.isNotEmpty() } // who wins is not important
}
// returns a winner index to deck pair
private fun recursiveGame(players: List<MutableList<Int>>): Pair<Int, MutableList<Int>> {
val previousRounds = mutableSetOf<Int>()
while (players.all { it.isNotEmpty() }) {
val configuration = players.hashCode()
if (previousRounds.contains(configuration)) {
// player 1 win the game
return 0 to players[0]
}
previousRounds.add(configuration)
val cards = List(2) { players[it].removeAt(0) }
val winner = if (cards.withIndex().all { (index, value) -> value <= players[index].size }) {
// the winner of this round is the winner of a new recursive game
val newCards = players.mapIndexed { playerIndex, cardList -> cardList.take(cards[playerIndex]).toMutableList() }
val subGame = recursiveGame(newCards)
subGame.first
} else {
cards.withIndex().maxByOrNull { it.value }!!.index
}
// add the cards to the winners deck, own card first, other players card later
players[winner].addAll(List(2) { cards[(winner + it) % 2] })
}
return players.mapIndexed { index, cardList -> index to cardList }.first { it.second.isNotEmpty() }
}
private fun normalGame(game: (List<MutableList<Int>>) -> Pair<Int, MutableList<Int>>): Int {
val p = players.map { it.toMutableList() }
val winner = game.invoke(p).second
return winner.mapIndexed { index, i -> (winner.size - index) * i }.sum()
}
fun solvePart1(): Int {
return normalGame(this::normalGame)
}
fun solvePart2(): Int {
return normalGame(this::recursiveGame)
}
} | 0 | Kotlin | 0 | 6 | f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22 | 2,376 | aoc | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/SearchInRotatedSortedArray.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
/**
* 33. Search in Rotated Sorted Array
* @see <a href="https://leetcode.com/problems/search-in-rotated-sorted-array/">Source</a>
*/
fun interface SearchInRotatedSortedArray {
fun search(nums: IntArray, target: Int): Int
}
class SearchInRotatedSortedArraySearch : SearchInRotatedSortedArray {
override fun search(nums: IntArray, target: Int): Int {
val minIdx = findMinIdx(nums)
if (target == nums[minIdx]) return minIdx
val m: Int = nums.size
var start = if (target <= nums[m - 1]) minIdx else 0
var end = if (target > nums[m - 1]) minIdx else m - 1
while (start <= end) {
val mid = start + (end - start) / 2
if (nums[mid] == target) {
return mid
} else if (target > nums[mid]) {
start = mid + 1
} else {
end = mid - 1
}
}
return -1
}
private fun findMinIdx(nums: IntArray): Int {
var start = 0
var end = nums.size - 1
while (start < end) {
val mid = start + (end - start) / 2
if (nums[mid] > nums[end]) start = mid + 1 else end = mid
}
return start
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,860 | kotlab | Apache License 2.0 |
facebook/y2020/round2/b.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package facebook.y2020.round2
private fun solve(): DoubleArray {
val s = readStrings()
val n = s[0].toInt()
val p = s[1].toDouble()
var a = DoubleArray(2) { 1.0 }
for (m in 3..n) {
val pairs = m * (m - 1L) / 2
val b = DoubleArray(m) { i ->
val smaller = a.getOrElse(i - 1) { 0.0 }
val same = a.getOrElse(i) { 0.0 }
val r = 1 + (
(i * (i - 1L) / 2) * smaller +
(i) * (p * smaller) +
(m - 1 - i) * ((1 - p) * same) +
(i * (m - 1L - i)) * (p * smaller + (1 - p) * same) +
(m - 1L - i) * (m - 2L - i) / 2 * same
) / pairs
r
}
a = b
}
return a
}
fun main() = repeat(readInt()) { println("Case #${it + 1}:\n${solve().joinToString("\n")}") }
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
| 0 | Java | 1 | 9 | 30953122834fcaee817fe21fb108a374946f8c7c | 820 | competitions | The Unlicense |
src/day13/Day13.kt | davidcurrie | 579,636,994 | false | {"Kotlin": 52697} | package day13
import java.io.File
fun main() {
val pairs = File("src/day13/input.txt").readText().split("\n\n")
.map { it.split("\n") }
.map { listOf(parse(it[0]), parse(it[1])) }
println(pairs.mapIndexed { index, pair -> if (check(pair[0], pair[1])!!) index + 1 else 0 }.sumOf { it })
val dividers = listOf(mutableListOf(mutableListOf(2)), mutableListOf(mutableListOf(6)))
val packets = pairs.flatten().toMutableList()
packets.addAll(dividers)
packets.sortWith { left, right -> if (check(left, right)!!) -1 else 1 }
println(packets.mapIndexed { i, p -> if (p in dividers) i + 1 else 1 }.fold(1, Int::times))
}
fun check(left: MutableList<*>, right: MutableList<*>): Boolean? {
for (i in left.indices) {
var l = left[i]
if (i == right.size) return false
var r = right[i]
if (l is Int && r is Int) {
if (l < r) {
return true
} else if (l > r) {
return false
}
} else {
if (l is Int) {
l = mutableListOf(l)
}
if (r is Int) {
r = mutableListOf(r)
}
if (l is MutableList<*> && r is MutableList<*>) {
val check = check(l, r)
if (check != null) return check
}
}
}
if (right.size > left.size) return true
return null
}
fun parse(s: String): MutableList<*> {
val stack = mutableListOf<MutableList<Any>>()
var n: Int? = null
var result: MutableList<Any>? = null
for (c in s) {
when (c) {
'[' -> {
val list = mutableListOf<Any>()
if (stack.isEmpty()) {
result = list
} else {
stack.last().add(list)
}
stack.add(list)
n = null
}
']' -> {
if (n != null) {
stack.last().add(n)
}
n = null
stack.removeLast()
}
',' -> {
if (n != null) {
stack.last().add(n)
}
n = null
}
else -> {
n = if (n != null) (10 * n) else 0
n += c.toString().toInt()
}
}
}
return result!!
}
| 0 | Kotlin | 0 | 0 | 0e0cae3b9a97c6019c219563621b43b0eb0fc9db | 2,427 | advent-of-code-2022 | MIT License |
src/Day17.kt | zfz7 | 573,100,794 | false | {"Kotlin": 53499} | fun main() {
println(day17A(readFile("Day17").trim(), 2200))
println(day17B(readFile("Day17").trim()))
}
//val shapes = listOf("1111", ".2.\n222\n.2.", "..3\n..3\n333", "3\n3\n3\n3", "33\n33")
val shapes = listOf("####", ".#.\n###\n.#.", "..#\n..#\n###", "#\n#\n#\n#", "##\n##")
fun day17A(input: String, blocks: Long): Int {
val grid = Array(7) { CharArray(5000) { '.' }.toMutableList() }.toMutableList()
var droppedRocks = 0
var windBlown = 0
var shape = 0
var pos = Pair(2, grid[0].size - 4) //3 from bottom
// var pos = Pair(2, grid[0].size - 4) //3 from bottom
while (droppedRocks < blocks) {
var stillFalling = true
drawShape(shape, grid, pos, false)
// printGrid(grid)
while (stillFalling) {
clearShape(grid)
val sidewaysPos: Pair<Int, Int> = pushShape(shape, grid, input[windBlown], pos)
windBlown = (windBlown + 1) % input.length
drawShape(shape, grid, sidewaysPos, false)
// printGrid(grid)
//drop
clearShape(grid)
val droppedPos: Pair<Int, Int> = dropShape(shape, grid, sidewaysPos)
stillFalling = sidewaysPos != droppedPos
drawShape(shape, grid, droppedPos, !stillFalling)
// printGrid(grid)
pos = droppedPos
}
pos = Pair(2, findHeight(grid) - 4)
// if(grid[0].size - pos.second - 3 - 1 >= 844){
// println(droppedRocks)
// break;
// }
// pos = Pair(2, pos.second - shapes[shape].split("\n").size - 3)
shape = (shape + 1) % shapes.size
droppedRocks++
}
printGrid(grid)
return grid[0].size - pos.second - 3 - 1
}
fun day17B(input: String): Long {
//1565517241411
//1514285714288
//1565517240376 < -LOW
//1565517242226 <- WRONG
//1565517241382 <- ?
//notice that blocks repeats after some time
//Block ~ height
//531 + 1740*a = 844 + 2724*a
val initialNonRepeatingBlocks = 531L
val repeatingBlocks = 1740L
val initialNonRepeatingHeight = 844L
val repeatingHeight = 2724L
val repeatingTimes: Long = (1000000000000L -initialNonRepeatingBlocks) / repeatingBlocks
val remainBlocks: Long = (1000000000000L -initialNonRepeatingBlocks) % repeatingBlocks
println(repeatingTimes)
println(remainBlocks)
val height = initialNonRepeatingHeight + repeatingTimes * repeatingHeight
return height + day17A(input, initialNonRepeatingBlocks+remainBlocks.toInt()) - initialNonRepeatingHeight
}
fun shiftGridDown(grid: MutableList<MutableList<Char>>, bottomLeft: Pair<Int, Int>, shape: Int): Int {
for (j in bottomLeft.second - shapes[shape].split("\n").size .. bottomLeft.second) {
if (grid[0][j] == '.' ||
grid[1][j] == '.' ||
grid[2][j] == '.' ||
grid[3][j] == '.' ||
grid[4][j] == '.' ||
grid[5][j] == '.' ||
grid[6][j] == '.'
)
continue
// printGrid(grid)
// println(j)
for (j1 in 0 until j) {
grid[0][grid[0].size - 1 - j1] = grid[0][j - j1]
grid[1][grid[0].size - 1 - j1] = grid[1][j - j1]
grid[2][grid[0].size - 1 - j1] = grid[2][j - j1]
grid[3][grid[0].size - 1 - j1] = grid[3][j - j1]
grid[4][grid[0].size - 1 - j1] = grid[4][j - j1]
grid[5][grid[0].size - 1 - j1] = grid[5][j - j1]
grid[6][grid[0].size - 1 - j1] = grid[6][j - j1]
grid[0][j - j1] = '.'
grid[1][j - j1] = '.'
grid[2][j - j1] = '.'
grid[3][j - j1] = '.'
grid[4][j - j1] = '.'
grid[5][j - j1] = '.'
grid[6][j - j1] = '.'
}
// printGrid(grid)
// println(j)
return grid[0].size - j -1
}
return -1
}
fun findHeight(grid: MutableList<MutableList<Char>>): Int {
for (j in 0 until grid[0].size) {
for (i in 0 until grid.size) {
if (grid[i][j] == '@' || grid[i][j] == '0' || grid[i][j] == '1' || grid[i][j] == '2' || grid[i][j] == '3' || grid[i][j] == '4') {
return j
}
}
}
throw Exception("help")
}
fun dropShape(shape: Int, grid: MutableList<MutableList<Char>>, bottomLeft: Pair<Int, Int>): Pair<Int, Int> {
shapes[shape].split("\n").reversed().forEachIndexed { idxY, line ->
line.forEachIndexed { idxX, char ->
if (isChar(char) && grid.getOrNull(bottomLeft.first + idxX)
?.getOrNull(bottomLeft.second - idxY + 1) != '.'
) {
// cant move
return bottomLeft
}
}
}
return Pair(bottomLeft.first, bottomLeft.second + 1)
}
fun clearShape(grid: MutableList<MutableList<Char>>) {
for (i in 0 until grid.size) {
for (j in 0 until grid[0].size) {
if (isChar(grid[i][j]))
grid[i][j] = '.'
}
}
}
fun pushShape(
shape: Int,
grid: MutableList<MutableList<Char>>,
direction: Char,
bottomLeft: Pair<Int, Int>
): Pair<Int, Int> {
val dir = when (direction) {
'>' -> 1
'<' -> -1
else -> throw Exception("help")
}
shapes[shape].split("\n").reversed().forEachIndexed { idxY, line ->
line.forEachIndexed { idxX, char ->
if (isChar(char) && grid.getOrNull(bottomLeft.first + idxX + dir)
?.getOrNull(bottomLeft.second - idxY) != '.'
) {
// cant move
return bottomLeft
}
}
}
return Pair(bottomLeft.first + dir, bottomLeft.second)
}
fun drawShape(shape: Int, grid: MutableList<MutableList<Char>>, bottomLeft: Pair<Int, Int>, atRest: Boolean) {
shapes[shape].split("\n").reversed().forEachIndexed { idxY, line ->
line.forEachIndexed { idxX, char ->
if (grid[bottomLeft.first + idxX][bottomLeft.second - idxY] == '.')
grid[bottomLeft.first + idxX][bottomLeft.second - idxY] =
if (atRest && isChar(char)) shape.toString()[0] else char
// if (atRest && isChar(char)) '@' else char
}
}
}
fun isChar(char: Char) =
when (char) {
// '#', '0', '1', '2', '3', '4' -> true
'#' -> true
else -> false
}
fun isRest(char: Char) =
when (char) {
'#', '0', '1', '2', '3', '4' -> true
else -> false
}
| 0 | Kotlin | 0 | 0 | c50a12b52127eba3f5706de775a350b1568127ae | 6,495 | AdventOfCode22 | Apache License 2.0 |
kotlin/misc/Sat2.kt | polydisc | 281,633,906 | true | {"Java": 540473, "Kotlin": 515759, "C++": 265630, "CMake": 571} | package misc
import java.util.stream.Stream
// https://en.wikipedia.org/wiki/2-satisfiability
object Sat2 {
fun dfs1(graph: Array<List<Integer>>, used: BooleanArray, order: List<Integer?>, u: Int) {
used[u] = true
for (v in graph[u]) if (!used[v]) dfs1(graph, used, order, v)
order.add(u)
}
fun dfs2(reverseGraph: Array<List<Integer>>, comp: IntArray, u: Int, color: Int) {
comp[u] = color
for (v in reverseGraph[u]) if (comp[v] == -1) dfs2(reverseGraph, comp, v, color)
}
fun solve2Sat(graph: Array<List<Integer>>): BooleanArray? {
val n = graph.size
val used = BooleanArray(n)
val order: List<Integer> = ArrayList()
for (i in 0 until n) if (!used[i]) dfs1(graph, used, order, i)
val reverseGraph: Array<List<Integer>> =
Stream.generate { ArrayList() }.limit(n).toArray { _Dummy_.__Array__() }
for (i in 0 until n) for (j in graph[i]) reverseGraph[j].add(i)
val comp = IntArray(n)
Arrays.fill(comp, -1)
run {
var i = 0
var color = 0
while (i < n) {
val u: Int = order[n - i - 1]
if (comp[u] == -1) dfs2(reverseGraph, comp, u, color++)
++i
}
}
for (i in 0 until n) if (comp[i] == comp[i xor 1]) return null
val res = BooleanArray(n / 2)
var i = 0
while (i < n) {
res[i / 2] = comp[i] > comp[i xor 1]
i += 2
}
return res
}
fun main(args: Array<String?>?) {
val n = 6
val g: Array<List<Integer>> = Stream.generate { ArrayList() }.limit(n).toArray { _Dummy_.__Array__() }
// (a || b) && (b || !c)
// !a => b
// !b => a
// !b => !c
// c => b
val a = 0
val na = 1
val b = 2
val nb = 3
val c = 4
val nc = 5
g[na].add(b)
g[nb].add(a)
g[nb].add(nc)
g[c].add(b)
val solution = solve2Sat(g)
System.out.println(Arrays.toString(solution))
}
}
| 1 | Java | 0 | 0 | 4566f3145be72827d72cb93abca8bfd93f1c58df | 2,120 | codelibrary | The Unlicense |
2019/src/main/kotlin/com/github/jrhenderson1988/adventofcode2019/day15/RepairDroid.kt | jrhenderson1988 | 289,786,400 | false | {"Kotlin": 216891, "Java": 166355, "Go": 158613, "Rust": 124111, "Scala": 113820, "Elixir": 112109, "Python": 91752, "Shell": 37} | package com.github.jrhenderson1988.adventofcode2019.day15
import com.github.jrhenderson1988.adventofcode2019.common.Direction
import com.github.jrhenderson1988.adventofcode2019.common.dijkstra
import java.util.Stack
class RepairDroid(private val intCodeComputer: IntCodeComputer) {
private val priorities = listOf(Direction.NORTH, Direction.EAST, Direction.SOUTH, Direction.WEST)
fun calculateFewestStepsToOxygenSystem(): Int {
val (position, oxygenSystemPosition, maze) = discover(Pair(0, 0))
val coordinates = maze.filter { it.value == Cell.PATH }.keys
val path = dijkstra(coordinates, position, oxygenSystemPosition)
?: error("The shortest path could not be calculated")
return path.size - 1
}
fun calculateTimeTakenToFillWithOxygen(): Int {
val (_, oxygenSystemPosition, maze) = discover(Pair(0, 0))
val filled = maze.toMutableMap()
filled[oxygenSystemPosition] = Cell.OXYGEN
var minutes = 0
while (filled.containsValue(Cell.PATH)) {
filled
.filter { it.value == Cell.OXYGEN }
.forEach { (position, _) ->
Direction.neighboursOf(position)
.filter { filled[it] == Cell.PATH }
.forEach { filled[it] = Cell.OXYGEN }
}
minutes++
}
return minutes
}
private fun discover(position: Pair<Int, Int>): Triple<Pair<Int, Int>, Pair<Int, Int>, Map<Pair<Int, Int>, Cell>> {
var pos = position
var oxygenSystemPosition: Pair<Int, Int>? = null
val maze = mutableMapOf(position to Cell.PATH)
val history = Stack<Direction>()
val cpu = intCodeComputer
while (!cpu.terminated) {
val (direction, backtracking) = nextDirection(pos, maze, history) ?: break
val response = cpu.execute(directionToCode(direction)) ?: break
val cell = codeToCell(response)
val target = Pair(pos.first + direction.delta.first, pos.second + direction.delta.second)
when (cell) {
Cell.WALL -> maze[target] = Cell.WALL
Cell.OXYGEN_SYSTEM, Cell.PATH -> {
maze[target] = Cell.PATH
pos = target
if (!backtracking) {
history.push(direction)
}
if (cell == Cell.OXYGEN_SYSTEM) {
oxygenSystemPosition = pos
}
}
else -> error("Unexpected cell $cell")
}
}
return Triple(pos, oxygenSystemPosition!!, maze.toMap())
}
private fun codeToCell(code: Long) =
when (code) {
0L -> Cell.WALL
1L -> Cell.PATH
2L -> Cell.OXYGEN_SYSTEM
else -> error("Invalid cell code [$code]")
}
private fun directionToCode(direction: Direction) =
when (direction) {
Direction.NORTH -> 1L
Direction.SOUTH -> 2L
Direction.WEST -> 3L
Direction.EAST -> 4L
}
private fun nextDirection(
position: Pair<Int, Int>,
maze: Map<Pair<Int, Int>, Cell>,
history: Stack<Direction>
): Pair<Direction, Boolean>? {
val unexplored = priorities.filter { maze[it.nextPoint(position)] == null }
return when {
unexplored.isNotEmpty() -> unexplored.first() to false
history.isNotEmpty() -> history.pop().opposite() to true
else -> null
}
}
enum class Cell {
WALL,
PATH,
OXYGEN_SYSTEM,
OXYGEN;
}
} | 0 | Kotlin | 0 | 0 | 7b56f99deccc3790c6c15a6fe98a57892bff9e51 | 3,720 | advent-of-code | Apache License 2.0 |
kotlin/src/main/kotlin/dev/mikeburgess/euler/problems/Problem021.kt | mddburgess | 261,028,925 | false | null | package dev.mikeburgess.euler.problems
import dev.mikeburgess.euler.common.properDivisors
/**
* Problem 21
*
* Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly
* into n).
*
* If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and each of a and b are
* called amicable numbers.
*
* For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110;
* therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220.
*
* Evaluate the sum of all the amicable numbers under 10000.
*/
class Problem021 : Problem {
override fun solve(): Long {
val sums = (1..9999).associateWith { it.properDivisors.sum() }
return sums.filter { (a, b) -> a != b }
.mapValues { (_, b) -> sums[b] }
.filter { (a, b) -> a == b }
.keys.sum().toLong()
}
}
| 0 | Kotlin | 0 | 0 | 86518be1ac8bde25afcaf82ba5984b81589b7bc9 | 924 | project-euler | MIT License |
src/main/kotlin/biz/koziolek/adventofcode/year2023/day20/day20.kt | pkoziol | 434,913,366 | false | {"Kotlin": 715025, "Shell": 1892} | package biz.koziolek.adventofcode.year2023.day20
import biz.koziolek.adventofcode.findInput
fun main() {
val inputFile = findInput(object {})
val modules = parseModules(inputFile.bufferedReader().readLines())
println("low pulses * high pulses: ${countPulses(modules, buttonPresses = 1000)}")
println("It takes ${findFewestButtonPresses(modules)} button presses to send low pulse to rx")
}
sealed interface Module {
val name: String
val destinations: List<String>
fun processPulse(pulse: Pulse): Pair<Module, Pulse.Level?>
}
data class BroadcasterModule(override val destinations: List<String>) : Module {
override val name = "broadcaster"
override fun processPulse(pulse: Pulse) = this to pulse.level
}
data class FlipFlopModule(override val name: String,
override val destinations: List<String>,
val isOn: Boolean = false) : Module {
private fun flip() = copy(isOn = !isOn)
override fun processPulse(pulse: Pulse): Pair<Module, Pulse.Level?> =
when (pulse.level) {
Pulse.Level.HIGH -> this to null
Pulse.Level.LOW -> this.flip() to if (isOn) Pulse.Level.LOW else Pulse.Level.HIGH
}
}
data class ConjunctionModule(override val name: String,
val inputs: Set<String>,
override val destinations: List<String>,
val recentPulses: Map<String, Pulse.Level> = inputs.associateWith { Pulse.Level.LOW }) : Module {
override fun processPulse(pulse: Pulse): Pair<Module, Pulse.Level?> {
val newModule = this.update(pulse.from, pulse.level)
return if (newModule.recentPulses.values.all { it == Pulse.Level.HIGH }) {
newModule to Pulse.Level.LOW
} else {
newModule to Pulse.Level.HIGH
}
}
private fun update(from: String, level: Pulse.Level): ConjunctionModule =
copy(recentPulses = recentPulses + mapOf(from to level))
}
data class UntypedModule(override val name: String,
override val destinations: List<String> = emptyList()) : Module {
override fun processPulse(pulse: Pulse) = this to pulse.level
}
data class Pulse(val from: String, val to: String, val level: Level) {
enum class Level { LOW, HIGH }
override fun toString() = "$from -${level.name.lowercase()}-> $to"
companion object {
val BUTTON_PRESS = Pulse(from = "button", to = "broadcaster", level = Level.LOW)
}
}
fun parseModules(lines: List<String>): Map<String, Module> {
val inputToOutputMap = lines.associate { line ->
val (namePart, destPart) = line.split("->")
val nameAndType = namePart.trim()
val destinations = destPart.split(',').map { it.trim() }
nameAndType to destinations
}
return inputToOutputMap.map { (nameAndType, destinations) ->
when {
nameAndType == "broadcaster" ->
BroadcasterModule(destinations)
nameAndType.startsWith('%') ->
FlipFlopModule(
name = getName(nameAndType),
destinations = destinations
)
nameAndType.startsWith('&') ->
ConjunctionModule(
name = getName(nameAndType),
inputs = inputToOutputMap
.filterValues { it.contains(getName(nameAndType)) }
.keys
.map { getName(it) }
.toSet(),
destinations = destinations
)
else ->
UntypedModule(nameAndType, destinations)
}
}.associateBy { it.name }
}
private fun getName(nameAndType: String): String =
when {
nameAndType.startsWith('%') -> nameAndType.drop(1)
nameAndType.startsWith('&') -> nameAndType.drop(1)
else -> nameAndType
}
fun generatePulses(modules: Map<String, Module>, initialPulse: Pulse): Sequence<Pair<Pulse, Map<String, Module>>> =
sequence {
val pulsesToProcess = mutableListOf(initialPulse)
var currentModules = modules
while (pulsesToProcess.isNotEmpty()) {
val pulse = pulsesToProcess.removeFirst()
val module = currentModules[pulse.to]
if (module != null) {
val (newModule, nextLevel) = module.processPulse(pulse)
currentModules = currentModules + (newModule.name to newModule)
if (nextLevel != null) {
pulsesToProcess.addAll(newModule.destinations.map {
Pulse(
from = newModule.name,
to = it,
level = nextLevel
)
})
}
}
yield(pulse to currentModules)
}
}
fun Sequence<Pair<Pulse, Map<String, Module>>>.getLatestModulesAndAllPulses(): Pair<Map<String, Module>, List<Pulse>> =
fold(Pair(emptyMap(), emptyList())) { (_, pulses), (pulse, newModules) ->
newModules to (pulses + pulse)
}
fun countPulses(modules: Map<String, Module>, buttonPresses: Int): Long {
var currentModules = modules
var lowCount = 0L
var highCount = 0L
for (i in 1..buttonPresses) {
for ((pulse, newModules) in generatePulses(currentModules, Pulse.BUTTON_PRESS)) {
currentModules = newModules
if (pulse.level == Pulse.Level.LOW) {
lowCount++
} else {
highCount++
}
}
}
return lowCount * highCount
}
fun findFewestButtonPresses(modules: Map<String, Module>): Long {
var currentModules = modules
val rxInputName = currentModules.values.single { it.destinations == listOf("rx") }.name
val firstHighs: MutableMap<String, Int?> =
(currentModules[rxInputName] as ConjunctionModule)
.inputs
.associateWith { null }
.toMutableMap()
var buttonPresses = 0
while (true) {
buttonPresses++
for ((pulse, newModules) in generatePulses(currentModules, Pulse.BUTTON_PRESS)) {
currentModules = newModules
if (pulse.to == rxInputName && pulse.level == Pulse.Level.HIGH) {
firstHighs.computeIfAbsent(pulse.from) { buttonPresses }
}
if (firstHighs.all { it.value != null }) {
return firstHighs.values.fold(1L) { acc, i -> acc * i!! }
}
}
}
}
fun toGraphvizString(modules: Map<String, Module>): String {
val allModules = modules.values
.flatMap { it.destinations }
.distinct()
.map { modules[it] ?: UntypedModule(it) }
return modules.values
.flatMap { module -> module.destinations.map { module.name to it } }
.joinToString(
prefix = """
digraph G {
rankdir=LR
""".trimIndent() + allModules.joinToString(
prefix = "\n ",
postfix = "\n",
separator = "\n "
) { "${it.name} [shape=${getGraphvizShape(it)}];" },
postfix = "\n}",
separator = "\n"
) { " ${it.first} -> ${it.second}" }
}
private fun getGraphvizShape(module: Module) =
when (module) {
is BroadcasterModule -> "hexagon"
is ConjunctionModule -> "box"
is FlipFlopModule -> "diamond"
is UntypedModule -> "oval"
}
| 0 | Kotlin | 0 | 0 | 1b1c6971bf45b89fd76bbcc503444d0d86617e95 | 7,608 | advent-of-code | MIT License |
year2021/day01/part2/src/main/kotlin/com/curtislb/adventofcode/year2021/day01/part2/Year2021Day01Part2.kt | curtislb | 226,797,689 | false | {"Kotlin": 2146738} | /*
--- Part Two ---
Considering every single measurement isn't as useful as you expected: there's just too much noise in
the data.
Instead, consider sums of a three-measurement sliding window. Again considering the above example:
```
199 A
200 A B
208 A B C
210 B C D
200 E C D
207 E F D
240 E F G
269 F G H
260 G H
263 H
```
Start by comparing the first and second three-measurement windows. The measurements in the first
window are marked A (199, 200, 208); their sum is 199 + 200 + 208 = 607. The second window is marked
B (200, 208, 210); its sum is 618. The sum of measurements in the second window is larger than the
sum of the first, so this first comparison increased.
Your goal now is to count the number of times the sum of measurements in this sliding window
increases from the previous sum. So, compare A with B, then compare B with C, then C with D, and so
on. Stop when there aren't enough measurements left to create a new three-measurement sum.
In the above example, the sum of each three-measurement window is as follows:
```
A: 607 (N/A - no previous sum)
B: 618 (increased)
C: 618 (no change)
D: 617 (decreased)
E: 647 (increased)
F: 716 (increased)
G: 769 (increased)
H: 792 (increased)
```
In this example, there are 5 sums that are larger than the previous sum.
Consider sums of a three-measurement sliding window. How many sums are larger than the previous sum?
*/
package com.curtislb.adventofcode.year2021.day01.part2
import com.curtislb.adventofcode.common.parse.parseInts
import java.nio.file.Path
import java.nio.file.Paths
/**
* Returns the solution to the puzzle for 2021, day 1, part 2.
*
* @param inputPath The path to the input file for this puzzle.
* @param windowSize The size of the measurement window to use when comparing sums.
*/
fun solve(inputPath: Path = Paths.get("..", "input", "input.txt"), windowSize: Int = 3): Int =
inputPath.toFile()
.readText()
.parseInts()
.windowed(windowSize + 1)
.count { it.first() < it.last() }
fun main() {
println(solve())
}
| 0 | Kotlin | 1 | 1 | 6b64c9eb181fab97bc518ac78e14cd586d64499e | 2,156 | AdventOfCode | MIT License |
src/Day02.kt | Longtainbin | 573,466,419 | false | {"Kotlin": 22711} | fun main() {
val input = readInput("inputDay02")
// store shape score
val SHAPE_SCORE = intArrayOf(1, 2, 3)
/**
* OUT_Part1 store result, 0 -> draw
* 1 -> win ,-1 -> lost
*/
val OUT_Part1 = arrayOf(intArrayOf(0, 1, -1), intArrayOf(-1, 0, 1), intArrayOf(1, -1, 0))
val OUT_Part2 = arrayOf(charArrayOf('C', 'A', 'B'), charArrayOf('A', 'B', 'C'), charArrayOf('B', 'C', 'A'))
fun part1(input: List<String>): Int {
var totalScore = 0
for (str in input) {
val opponentSymbol = str[0]
val yourSymbol = str[2]
val outcomeScore: Int = getOutcomeScore(OUT_Part1, opponentSymbol, yourSymbol)
val shapeScore: Int = getShapeScore(SHAPE_SCORE, yourSymbol)
totalScore += (shapeScore + outcomeScore)
}
return totalScore
}
fun part2(input: List<String>): Int {
var totalScore = 0
for (str in input) {
val opponentSymbol = str[0]
val yourSymbol = str[2]
val outcomeScore: Int = getOutcomeScore(OUT_Part2, yourSymbol)
val shapeScore: Int = getShapeScore(SHAPE_SCORE, OUT_Part2, opponentSymbol, yourSymbol)
totalScore += (shapeScore + outcomeScore)
}
return totalScore
}
println(part1(input))
println(part2(input))
}
private fun outcomeScore(outcome: Outcome): Int {
return if (outcome === Outcome.DRAW) {
3
} else if (outcome === Outcome.WIN) {
6
} else {
0
}
}
/*** For Part_1 ***/
private fun getShapeScore(SHAPE_SCORE: IntArray, yourSymbol: Char): Int {
return SHAPE_SCORE[yourSymbol - 'X']
}
private fun getOutcomeScore(OUT: Array<IntArray>, opponentSymbol: Char, yourSymbol: Char): Int {
val i = opponentSymbol - 'A'
val j = yourSymbol - 'X'
return if (OUT[i][j] == 0) {
outcomeScore(Outcome.DRAW)
} else if (OUT[i][j] == 1) {
outcomeScore(Outcome.WIN)
} else {
outcomeScore(Outcome.LOST)
}
}
/*** For Part_2 ***/
private fun getShapeScore(SHAPE_SCORE: IntArray, OUT: Array<CharArray>, opponentSymbol: Char, yourSymbol: Char): Int {
val i: Int = opponentSymbol - 'A'
val j = yourSymbol - 'X'
return SHAPE_SCORE[OUT[i][j] - 'A']
}
private fun getOutcomeScore(OUT: Array<CharArray>, yourSymbol: Char): Int {
return if (yourSymbol == 'Y') {
outcomeScore(Outcome.DRAW)
} else if (yourSymbol == 'Z') {
outcomeScore(Outcome.WIN)
} else {
outcomeScore(Outcome.LOST)
}
}
enum class Outcome {
WIN,
LOST,
DRAW
} | 0 | Kotlin | 0 | 0 | 48ef88b2e131ba2a5b17ab80a0bf6a641e46891b | 2,610 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/nl/jackploeg/aoc/_2022/calendar/day08/Day08.kt | jackploeg | 736,755,380 | false | {"Kotlin": 318734} | package nl.jackploeg.aoc._2022.calendar.day08
import javax.inject.Inject
import nl.jackploeg.aoc.generators.InputGenerator.InputGeneratorFactory
import nl.jackploeg.aoc.utilities.readStringFile
class Day08 @Inject constructor(
private val generatorFactory: InputGeneratorFactory,
) {
// count visible trees
fun partOne(fileName: String): Int {
val input = readStringFile(fileName)
val grid = initTreeGrid(input)
return countVisibleTrees(grid.first)
}
// get max scenic score
fun partTwo(fileName: String): Int {
val input = readStringFile(fileName)
val grid = initTreeGrid(input)
return grid.first.flatMap { it.trees }.maxOfOrNull { it.scenicScore() }!!
}
fun countVisibleTrees(rows: ArrayList<Row>): Int {
return rows.flatMap { it.trees }.filter { it.isVisible() }.count()
}
fun initTreeGrid(lines: List<String>): Pair<ArrayList<Row>, ArrayList<Column>> {
var i = 0
val rows: ArrayList<Row> = ArrayList()
val columns: ArrayList<Column> = ArrayList()
do {
val trees = lines[i].toCharArray()
if (i <= rows.size) {
rows.add(Row(i))
}
val row = rows[i]
var j = 0
do {
if (j <= columns.size) {
columns.add(Column(j))
}
val column = columns[j]
val tree = Tree(row, i, column, j, lines[i][j].digitToInt())
row.trees.add(tree)
column.trees.add(tree)
j++
} while (j < trees.size)
i++
} while (i < lines.size)
return Pair(rows, columns)
}
class Row(val number: Int, val trees: ArrayList<Tree> = ArrayList())
class Column(val number: Int, val trees: ArrayList<Tree> = ArrayList())
class Tree(private val row: Row, private val rowIndex: Int, private val column: Column, private val columnIndex: Int, private val height: Int) {
fun isVisible(): Boolean {
return rowIndex == 0
|| rowIndex == row.trees.size - 1
|| columnIndex == 0
|| columnIndex == column.trees.size - 1
|| allSmaller(row.trees, columnIndex)
|| allSmaller(column.trees, rowIndex)
}
fun scenicScore(): Int {
return scenicScore(row.trees, columnIndex) * scenicScore(column.trees, rowIndex)
}
private fun allSmaller(collection: ArrayList<Tree>, index: Int): Boolean {
val before = collection.subList(0, index)
val after = collection.subList(index + 1, collection.size)
return before.map { it.height }.filter { it >= this.height }.isEmpty()
|| after.map { it.height }.filter { it >= this.height }.isEmpty()
}
private fun scenicScore(collection: ArrayList<Tree>, index: Int): Int {
val before = collection.subList(0, index)
var score1 = 0
if (index > 0) {
for (i in index - 1 downTo 0) {
score1++
if (before[i].height >= height)
break
}
}
var score2 = 0
if (index < collection.size) {
for (i in index + 1 until collection.size) {
score2++
if (collection[i].height >= height)
break
}
}
return score1 * score2
}
}
}
| 0 | Kotlin | 0 | 0 | f2b873b6cf24bf95a4ba3d0e4f6e007b96423b76 | 3,618 | advent-of-code | MIT License |
src/main/kotlin/me/alejandrorm/klosure/sparql/algebra/operators/Project.kt | alejandrorm | 512,041,126 | false | {"Kotlin": 196720, "Ruby": 28544, "HTML": 25737} | package me.alejandrorm.klosure.sparql.algebra.operators
import me.alejandrorm.klosure.model.Graph
import me.alejandrorm.klosure.model.Graphs
import me.alejandrorm.klosure.sparql.SolutionMapping
data class ProjectArguments(val distinct: Boolean, val variables: List<ExpressionVariableBinding>)
class Project(
val args: ProjectArguments,
val sm: SolutionModifiers,
val op: AlgebraOperator
) : AlgebraOperator {
private val variablesSet = args.variables.map { it.variable }.toSet()
private val hasAggregates = args.variables.any { it.expression.isAggregate() }
private val allAggregates = args.variables.all { it.expression.isAggregate() }
private val hasGroups = sm.groupBy != null
init {
if (hasAggregates && !hasGroups && !allAggregates) {
throw IllegalArgumentException("Projection cannot have some aggregates without having a group by")
}
}
override fun toString(): String {
return "Project('${if (args.variables.isEmpty()) "*" else args.variables.joinToString(", ")}', $op)"
}
override fun eval(
solutions: Sequence<SolutionMapping>,
activeGraph: Graph,
graphs: Graphs
): Sequence<SolutionMapping> {
return if (args.variables.isEmpty()) {
sm.eval(op.eval(solutions, activeGraph, graphs), activeGraph, graphs).map {
if (it.groups.any()) {
throw IllegalArgumentException("Projecting variables not aggregated or grouped by")
} else {
SolutionMapping(emptySet(), it.boundVariables.boundVariables)
}
}
} else {
if (args.distinct) {
getMultisetSolutions(solutions, activeGraph, graphs).distinct()
} else {
getMultisetSolutions(solutions, activeGraph, graphs)
}
}
}
override fun hasFilter(): Boolean = false
private fun getMultisetSolutions(
solutions: Sequence<SolutionMapping>,
activeGraph: Graph,
graphs: Graphs
): Sequence<SolutionMapping> {
val results = sm.eval(op.eval(solutions, activeGraph, graphs), activeGraph, graphs)
if (allAggregates && !hasGroups) {
// FIXME: solution group is being iterated multiple times
val solutionGroup = results.map { it.boundVariables }
return sequenceOf(
SolutionMapping(
emptySet(),
args.variables.flatMap {
val expression = it.expression
// TODO report error if expression on variables not aggregated or grouped by
val value = expression.evalGroup(
SolutionMapping.EmptySolutionMapping,
solutionGroup,
activeGraph,
graphs
)
if (value == null) emptyList() else listOf(it.variable to value)
}.toMap()
)
)
} else {
return results.map { solution ->
SolutionMapping(
variablesSet,
args.variables.flatMap {
val expression = it.expression
// TODO report error if expression on variables not aggregated or grouped by
val value = expression.evalGroup(solution.boundVariables, solution.groups, activeGraph, graphs)
if (value == null) emptyList() else listOf(it.variable to value)
}.toMap()
)
}
}
}
}
| 0 | Kotlin | 0 | 0 | 14abf426f3cad162c021ffae750038e25b8cb271 | 3,716 | klosure | Apache License 2.0 |
src/2022/Day25.kt | ttypic | 572,859,357 | false | {"Kotlin": 94821} | package `2022`
import readInput
fun main() {
fun part1(input: List<String>): String {
return input.sumOf { it.fromSNAFU() }.toSNAFU()
}
fun part2(input: List<String>): Int {
return 0
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day25_test")
println(part1(testInput))
println(part2(testInput))
check(part1(testInput) == "2=-1=0")
check(part2(testInput) == 0)
val input = readInput("Day25")
println(part1(input))
println(part2(input))
}
fun String.fromSNAFU(): Long {
return this.fold(0L) { acc, c ->
when(c) {
'=' -> acc * 5 - 2
'-' -> acc * 5 - 1
else -> acc * 5 + c.toString().toInt()
}
}
}
fun Long.toSNAFU(): String {
val chars = mutableListOf<String>()
var number = this
do {
when(val digit = number % 5) {
in 0L..2L -> {
chars.add(digit.toString())
number /= 5
}
3L -> {
chars.add("=")
number = number / 5 + 1
}
4L -> {
chars.add("-")
number = number / 5 + 1
}
else -> error("Something wrong. Probably negative input")
}
} while (number != 0L)
return chars.reversed().joinToString(separator = "")
}
| 0 | Kotlin | 0 | 0 | b3e718d122e04a7322ed160b4c02029c33fbad78 | 1,410 | aoc-2022-in-kotlin | Apache License 2.0 |
src/main/kotlin/dayEight/DayEight.kt | janreppien | 573,041,132 | false | {"Kotlin": 26432} | package dayEight
import AocSolution
import java.io.File
class DayEight : AocSolution(8) {
private val input = readInput()
private fun readInput(): MutableList<MutableList<Int>> {
val file = File("src/main/resources/inputs/dayEight/input.txt")
val input = mutableListOf<MutableList<Int>>()
file.forEachLine { line ->
input.add(mutableListOf())
input.last().addAll(line.toList().map { char -> char.digitToInt() })
}
return input
}
override fun solvePartOne(): String {
var visibleTrees = 0
for (line in input.indices) {
for (pos in input[line].indices) {
if (isVisible(line, pos)) {
visibleTrees++
}
}
}
return visibleTrees.toString()
}
override fun solvePartTwo(): String {
var maxScore = 0
for (line in input.indices) {
for (pos in input[line].indices) {
if (isVisible(line, pos)) {
val newScore = calcScore(line,pos)
if(newScore> maxScore){
maxScore = newScore
}
}
}
}
return maxScore.toString()
}
private fun calcScore(x: Int, y: Int) : Int {
if(x in listOf(input.size-1,0) || y in listOf(input[x].size -1, 0)) {
return 0
}
val value = input[x][y]
val left = input[x].subList(0, y).reversed()
val right = input[x].subList(y + 1, input[x].size)
val above = input.map { it[y] }.subList(0, x).reversed()
val below = input.map { it[y] }.subList(x + 1, input.size)
val viewLeft = if(left.max() >= value) {
left.indexOfFirst { it >= value } + 1
} else {
y
}
val viewRight = if(right.max() >= value) {
right.indexOfFirst { it >= value } + 1
} else {
input[x].size - y -1
}
val viewAbove = if(above.max() >= value) {
above.indexOfFirst { it >= value } +1
} else {
x
}
val viewBelow = if(below.max() >= value) {
below.indexOfFirst { it >= value } +1
} else {
input.size - x - 1
}
return viewLeft * viewRight * viewAbove * viewBelow
}
private fun isVisible(x: Int, y: Int): Boolean {
val value = input[x][y]
val left = input[x].subList(0, y)
val right = input[x].subList(y + 1, input[x].size)
val above = input.map { it[y] }.subList(0, x)
val below = input.map { it[y] }.subList(x + 1, input.size)
return left.isEmpty() || left.max() < value || right.isEmpty() || right.max() < value || above.isEmpty() ||
above.max() < value || below.isEmpty() || below.max() < value
}
} | 0 | Kotlin | 0 | 0 | b53f6c253966536a3edc8897d1420a5ceed59aa9 | 2,901 | aoc2022 | MIT License |
src/Day07.kt | max-zhilin | 573,066,300 | false | {"Kotlin": 114003} | import java.util.*
class TreeNode(val size: Int, val name: String){
var parent: TreeNode? = null
var children: MutableMap<String, TreeNode> = mutableMapOf()
fun addChild(node:TreeNode){
children[node.name] = node
node.parent = this
}
fun calcSize(): Int {
var sum = size
if (children.isNotEmpty()) {
sum += children.values.sumOf { it.calcSize() }
}
return sum
}
fun sumDirSize(limit: Int, list: MutableList<Int>) {
val size = calcSize()
if (size <= limit && this.size == 0) list.add(size)
if (children.isNotEmpty()) {
children.forEach { it.value.sumDirSize(limit, list) }
}
}
fun minDirSize(limit: Int, list: MutableList<Int>) {
val size = calcSize()
if (size >= limit && this.size == 0) list.add(size)
// list.add(size)
if (children.isNotEmpty()) {
children.forEach { it.value.minDirSize(limit, list) }
}
}
override fun toString(): String {
var s = "$size $name"
if (children.isNotEmpty()) {
s += " {" + children.map { it.toString() } + " }"
}
return s
}
fun child(dirName: String): TreeNode {
return children[dirName]!!
}
}
fun main() {
fun part1(input: List<String>): Int {
val root = TreeNode(0, "/")
var currentNode = root
var readDirState = false
input.forEach() { line ->
val scanner = Scanner(line)
if (readDirState && line.first() != '$') {
val typeOrSize = scanner.next()
currentNode.addChild(
if (typeOrSize == "dir") TreeNode(0, scanner.next())
else TreeNode(typeOrSize.toInt(), scanner.next())
)
} else {
readDirState = false
when (scanner.next()) {
"$" -> {
when (scanner.next()) {
"cd" -> {
val dirName = scanner.next()
currentNode = when (dirName) {
".." -> currentNode.parent!!
"/" -> root
else -> currentNode.child(dirName)
}
}
"ls" -> readDirState = true
else -> error("wrong command $line")
}
}
else -> error("no $ sign in $line")
}
}
}
// println(root)
val list = mutableListOf<Int>()
root.sumDirSize(100_000, list)
// println(list)
return list.sum()
}
fun part2(input: List<String>): Int {
val root = TreeNode(0, "/")
var currentNode = root
var readDirState = false
input.forEach() { line ->
val scanner = Scanner(line)
if (readDirState && line.first() != '$') {
val typeOrSize = scanner.next()
currentNode.addChild(
if (typeOrSize == "dir") TreeNode(0, scanner.next())
else TreeNode(typeOrSize.toInt(), scanner.next())
)
} else {
readDirState = false
when (scanner.next()) {
"$" -> {
when (scanner.next()) {
"cd" -> {
val dirName = scanner.next()
currentNode = when (dirName) {
".." -> currentNode.parent!!
"/" -> root
else -> currentNode.child(dirName)
}
}
"ls" -> readDirState = true
else -> error("wrong command $line")
}
}
else -> error("no $ sign in $line")
}
}
}
// println(root)
val list = mutableListOf<Int>()
root.minDirSize(4_804_833, list)
// root.minDirSize(0, list)
println(list.sorted())
println(70_000_000 - root.calcSize() - 30_000_000)
return list.min()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day07_test")
// println(part1(testInput))
// check(part1(testInput) == 95437)
// println(part2(testInput))
// check(part2(testInput) == 24933642)
val input = readInput("Day07")
// println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | d9dd7a33b404dc0d43576dfddbc9d066036f7326 | 4,834 | AoC-2022 | Apache License 2.0 |
src/main/kotlin/eu/michalchomo/adventofcode/year2023/Day01.kt | MichalChomo | 572,214,942 | false | {"Kotlin": 56758} | package eu.michalchomo.adventofcode.year2023
import eu.michalchomo.adventofcode.Day
import eu.michalchomo.adventofcode.main
object Day01 : Day {
override val number = 1
private val stringDigitsToIntegers = mapOf(
"one" to 1,
"two" to 2,
"three" to 3,
"four" to 4,
"five" to 5,
"six" to 6,
"seven" to 7,
"eight" to 8,
"nine" to 9,
)
override fun part1(input: List<String>): String = input.filter { it.isNotEmpty() }
.sumOf { line ->
(line.dropWhile { !it.isDigit() }.first().toString() + line.reversed().dropWhile { !it.isDigit() }
.first().toString()).toInt()
}.toString()
override fun part2(input: List<String>): String = input.sumOf { line ->
line.foldIndexed("") { i, acc, c ->
if (c.isDigit()) {
acc + c
} else {
val num = stringDigitsToIntegers.keys.find { line.substring(i).startsWith(it) }
if (num != null) {
acc + stringDigitsToIntegers[num]
} else {
acc
}
}
}.let { it[0].digitToInt() * 10 + it.last().digitToInt() }
}.toString()
}
fun main() {
main(Day01)
}
| 0 | Kotlin | 0 | 0 | a95d478aee72034321fdf37930722c23b246dd6b | 1,293 | advent-of-code | Apache License 2.0 |
dataStructuresAndAlgorithms/src/main/java/dev/funkymuse/datastructuresandalgorithms/sort/MergeSortPlain.kt | FunkyMuse | 168,687,007 | false | {"Kotlin": 1728251} | package dev.funkymuse.datastructuresandalgorithms.sort
/**
* Merge sort is an efficient algorithm for sorting lists of data.
* Principle:
* Split the list in half until it is only 2 elements long, then sort those lists.
* After sorting those small lists, start merging them together.
* For instance, having 1 3 and 2 5, by merging we would get 1 2 3 5.
*
*
* Time complexity: O(n log n) in all cases.
* Due to that, quicksort usually performs better on average due to its best case
* O(n) time complexity.
*
* Space complexity: O(n) auxiliary.
*/
fun <T : Comparable<T>> mergeSortPlain(list: MutableList<T>) = mergeSortPlain(list, 0, list.size - 1)
private fun <T : Comparable<T>> mergeSortPlain(list: MutableList<T>, start: Int, end: Int) {
if (end > start) {
val mid = (end + start) / 2
mergeSortPlain(list, start, mid)
mergeSortPlain(list, mid + 1, end)
merge(list, start, mid, end)
}
}
private fun <T : Comparable<T>> merge(list: MutableList<T>, start: Int, mid: Int, end: Int) {
val numLeft = mid - start + 1
val numRight = end - mid
val leftList = ArrayList<T>(numLeft + 1)
val rightList = ArrayList<T>(numRight + 1)
for (i in 1..numLeft) {
leftList.add(list[start + i - 1])
}
for (i in 1..numRight) {
rightList.add(list[mid + i])
}
var i = 0
var j = 0
for (k in start..end) {
list[k] = if (leftList[i] < rightList[j]) leftList[i++] else rightList[j++]
if (i == numLeft) {
for (p in (k + 1)..end) {
list[p] = rightList[j++]
}
return
}
if (j == numRight) {
for (p in (k + 1)..end) {
list[p] = leftList[i++]
}
return
}
}
} | 0 | Kotlin | 92 | 771 | e2afb0cc98c92c80ddf2ec1c073d7ae4ecfcb6e1 | 1,818 | KAHelpers | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/FactorCombinations.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 java.util.LinkedList
import kotlin.math.sqrt
/**
* 254. Factor Combinations
*/
fun interface FactorCombinations {
fun getFactors(n: Int): List<List<Int>>
}
class FactorCombinationsImpl : FactorCombinations {
override fun getFactors(n: Int): List<List<Int>> {
val result: MutableList<List<Int>> = ArrayList()
helper(result, ArrayList(), n, 2)
return result
}
private fun helper(result: MutableList<List<Int>>, item: MutableList<Int>, n: Int, start: Int) {
if (n <= 1) {
if (item.size > 1) {
result.add(ArrayList(item))
}
return
}
for (i in start..n) {
if (n % i == 0) {
item.add(i)
helper(result, item, n / i, i)
item.removeAt(item.size - 1)
}
}
}
}
class FactorCombinationsImpl2 : FactorCombinations {
override fun getFactors(n: Int): List<List<Int>> {
val ret: MutableList<List<Int>> = LinkedList<List<Int>>()
if (n <= 3) return ret
val path: MutableList<Int> = LinkedList<Int>()
getFactors(2, n, path, ret)
return ret
}
private fun getFactors(start: Int, n: Int, path: MutableList<Int>, ret: MutableList<List<Int>>) {
var i = start
while (i <= sqrt(n.toDouble())) {
// The previous factor is no bigger than the next
if (n % i == 0 && n / i >= i) {
path.add(i)
path.add(n / i)
ret.add(LinkedList(path))
path.removeAt(path.size - 1)
getFactors(i, n / i, path, ret)
path.removeAt(path.size - 1)
}
i++
}
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,386 | kotlab | Apache License 2.0 |
src/main/kotlin/PalindromicSubstrings.kt | Codextor | 453,514,033 | false | {"Kotlin": 26975} | /**
* Given a string s, return the number of palindromic substrings in it.
*
* A string is a palindrome when it reads the same backward as forward.
*
* A substring is a contiguous sequence of characters within the string.
*
*
*
* Example 1:
*
* Input: s = "abc"
* Output: 3
* Explanation: Three palindromic strings: "a", "b", "c".
* Example 2:
*
* Input: s = "aaa"
* Output: 6
* Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".
*
*
* Constraints:
*
* 1 <= s.length <= 1000
* s consists of lowercase English letters.
* @see <a href="https://leetcode.com/problems/palindromic-substrings/">LeetCode</a>
*/
fun countSubstrings(s: String): Int {
var substringCount = 0
for (index in s.indices) {
substringCount += countSubstringsWithCenter(s, index, index)
substringCount += countSubstringsWithCenter(s, index, index + 1)
}
return substringCount
}
private fun countSubstringsWithCenter(s: String, start: Int, end: Int): Int {
var count = 0
var startIndex = start
var endIndex = end
while (startIndex >= 0 && endIndex < s.length && s[startIndex] == s[endIndex]) {
count++
startIndex--
endIndex++
}
return count
}
| 0 | Kotlin | 1 | 0 | 68b75a7ef8338c805824dfc24d666ac204c5931f | 1,237 | kotlin-codes | Apache License 2.0 |
src/day03/kotlin/aoc2023-03/src/main/kotlin/Main.kt | JoubaMety | 726,095,975 | false | {"Kotlin": 17724} | data class StringInSchematic(
val schematic: List<String>,
val index: Index,
val length: Int
)
data class Index(
val column: Int,
val row: Int
)
class PartNumberMaximumDimensions(
partNumber: StringInSchematic
) {
val top = getTopDimension(partNumber)
val bottom = getBottomDimension(partNumber)
val left = getLeftDimension(partNumber)
val right = getRightDimension(partNumber)
private fun getTopDimension(partNumber: StringInSchematic): Int {
var top: Int = partNumber.index.row
if (top - 1 >= 0)
top--
return top
}
private fun getBottomDimension(partNumber: StringInSchematic): Int {
var bottom: Int = partNumber.index.row
if (bottom + 1 < (partNumber.schematic.size))
bottom++
return bottom
}
private fun getLeftDimension(partNumber: StringInSchematic): Int {
var left: Int = partNumber.index.column
if (left - 1 >= 0)
left--
return left
}
private fun getRightDimension(partNumber: StringInSchematic): Int {
var right: Int = partNumber.index.column + (partNumber.length - 1)
if (right + 1 < (partNumber.schematic[partNumber.index.row].length - 1))
right++
return right
}
}
fun getSumOfPartNumbers(input: String): Int {
val inputList = convertStringToList(input)
var sumOfPartNumbers = 0
var partNumberIndex: Int
var partNumberLength: Int
var currentRow = 0
inputList.forEach { row ->
if (row.isNotEmpty()) {
partNumberIndex = -1
partNumberLength = 0
var characterIndex = 0
row.forEach { character ->
if (character.isDigit() && character != '.') {
if (partNumberIndex == -1) partNumberIndex = characterIndex
partNumberLength++
}
if (!character.isDigit() || characterIndex+1 == row.length) {
if (partNumberIndex != -1) {
if (findSymbolForPartNumber(
StringInSchematic(
inputList,
Index(partNumberIndex, currentRow),
partNumberLength
)
)
) {
val substring = inputList[currentRow]
.substring(partNumberIndex, partNumberIndex + partNumberLength)
val sum = substring.toIntOrNull()
if (sum != null)
sumOfPartNumbers += sum
}
partNumberIndex = -1
partNumberLength = 0
}
}
characterIndex++
}
}
currentRow++
}
return sumOfPartNumbers
}
fun findSymbolForPartNumber(partNumber: StringInSchematic): Boolean {
val maxDimensions = PartNumberMaximumDimensions(partNumber)
var foundSymbol = false
if (partNumber.schematic[partNumber.index.row].isNotBlank()) {
y@ for (y in maxDimensions.top..maxDimensions.bottom) {
x@ for (x in maxDimensions.left..maxDimensions.right) {
val character = partNumber.schematic[y][x]
if (!character.isDigit() && character != '.') {
foundSymbol = true
break@y
}
}
}
}
return foundSymbol
}
class GearRatio(
private val schematic: List<String>,
private val index: Index
) {
private var firstNumber: Int = 0
private var secondNumber: Int = 0
fun getNearbyNumbers() {
val maxDimensions = PartNumberMaximumDimensions(
StringInSchematic(schematic, index, 1)
)
var numbersCount = 0
val foundNumbersList : MutableList<StringInSchematic> = mutableListOf()
y@ for (y in maxDimensions.top..maxDimensions.bottom) {
x@ for (x in maxDimensions.left..maxDimensions.right) {
if (schematic[y][x].isDigit()) {
var foundNumberBool = false
foundNumbersList.forEach { foundNumber ->
if(foundNumber.index.row == y) {
val startIndex = foundNumber.index.column
val endIndex = foundNumber.index.column + foundNumber.length
if (x in startIndex..endIndex) {
foundNumberBool = true
}
}
}
if (!foundNumberBool) {
val wholeNumber = getWholeNumber(Index(x,y))
// duuuuuuudee,wtf
val number = wholeNumber.number
foundNumbersList.add(wholeNumber.stringInSchematic)
if (numbersCount == 0) {
firstNumber += number
} else if (numbersCount == 1) {
secondNumber += number
break@y
}
numbersCount++
}
}
}
}
}
private data class WholeNumber(
val stringInSchematic: StringInSchematic,
val number: Int
)
private fun getWholeNumber(index: Index) : WholeNumber {
var number = ""
var numberIndex = index.column
var numberLength = 0
for(i in (0..index.column).reversed()) {
val character = schematic[index.row][i]
if (character.isDigit()) {
number = "$character$number"
numberIndex = i
numberLength++
} else {
break
}
}
for(i in index.column+1..< schematic[index.row].length) {
val character = schematic[index.row][i]
if (schematic[index.row][i].isDigit()) {
number = "$number$character"
numberLength++
} else {
break
}
}
return WholeNumber(
StringInSchematic(
schematic,
Index(numberIndex, index.row),
numberLength
),
number.toInt()
)
}
fun getGearRatio() : Int {
return firstNumber * secondNumber
}
fun isValid() : Boolean {
return firstNumber > 0 && secondNumber > 0
}
}
fun getSumOfGearRatios(input: String) : Int {
val inputList = convertStringToList(input)
var sumOfGearRatios = 0
var currentRow = 0
inputList.forEach { row ->
var currentChar = 0
row.forEach { character ->
if (character == '*') {
val gearRatio = GearRatio(inputList, Index(currentChar, currentRow))
gearRatio.getNearbyNumbers()
if(gearRatio.isValid()) sumOfGearRatios += gearRatio.getGearRatio()
}
currentChar++
}
currentRow += 1
}
return sumOfGearRatios
}
fun getResourceAsText(path: String): String? =
object {}.javaClass.getResource(path)?.readText()
/**
* Splits String into elements, is put into a List
*/
fun convertStringToList(input: String): List<String> =
input.split(regex = "[\r\n]+".toRegex()).toList()
fun main() {
val input = getResourceAsText("adventofcode.com_2023_day_3_input.txt")
if (input != null) {
val sumOfPartNumbers = getSumOfPartNumbers(input)
val sumOfGearRatios = getSumOfGearRatios(input)
println("AOC 2023 | Day 03")
println("- Part 01: Sum of Part Numbers: $sumOfPartNumbers")
println("- Part 01: Sum of Gear Ratios: $sumOfGearRatios")
} else {
error("ERROR: Input text file couldn't be read.")
}
}
| 0 | Kotlin | 0 | 0 | 1f883bbbbed64f285b0d3cf7f51f6fb3a1a0e966 | 8,075 | AdventOfCode-2023 | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.