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/Day22.kt | gijs-pennings | 573,023,936 | false | {"Kotlin": 20319} | private lateinit var nodes: List<List<Node>>
private val w get() = nodes.size
private val h get() = nodes[0].size
fun main() {
val lines = readInput(22)
val map = lines.dropLast(2)
val path = lines.last()
nodes = List(map.maxOf { it.length }) { x ->
List(map.size) { y ->
Node(FullPos.fromGlobal(x, y), map[y].getOrNull(x) ?: ' ')
}
}
for (u in nodes.flatten())
if (u.repr != ' ')
for (f in Facing.VALS) {
val pair = next(u, f)
if (pair.first.repr == '.') u.adj[f.ordinal] = pair // keep self-loop if neighbor is wall
}
var i = 0
var f = Facing.RIGHT
var u = nodes.map { it[0] }.first { it.repr == '.' }
while (i < path.length)
if (path[i].isDigit()) {
val s = path.drop(i).takeWhile { it.isDigit() }
i += s.length
repeat(s.toInt()) {
val pair = u.adj[f.ordinal]
u = pair.first
f = pair.second
}
} else {
f = f.turn(path[i] == 'R')
i++
}
println(1000 * (u.pos.global.y + 1) + 4 * (u.pos.global.x + 1) + f.ordinal)
}
private fun next(u: Node, f: Facing): Pair<Node, Facing> {
val global = u.pos.global + f.d
if (global.isWithin(w, h)) {
val v = nodes[global]
if (v.repr != ' ') return Pair(v, f)
}
val local = u.pos.local
return when (u.pos.side) {
0 -> {
if (f == Facing.LEFT)
Pair(nodes[FullPos.fromLocal(0, 49 - local.y, 3)], Facing.RIGHT)
else // up
Pair(nodes[FullPos.fromLocal(0, local.x, 5)], Facing.RIGHT)
}
1 -> when (f) {
Facing.RIGHT -> Pair(nodes[FullPos.fromLocal(49, 49 - local.y, 4)], Facing.LEFT)
Facing.DOWN -> Pair(nodes[FullPos.fromLocal(49, local.x, 2)], Facing.LEFT)
Facing.UP -> Pair(nodes[FullPos.fromLocal(local.x, 49, 5)], Facing.UP)
else -> throw IllegalStateException()
}
2 -> {
if (f == Facing.RIGHT)
Pair(nodes[FullPos.fromLocal(local.y, 49, 1)], Facing.UP)
else // left
Pair(nodes[FullPos.fromLocal(local.y, 0, 3)], Facing.DOWN)
}
3 -> {
if (f == Facing.LEFT)
Pair(nodes[FullPos.fromLocal(0, 49 - local.y, 0)], Facing.RIGHT)
else // up
Pair(nodes[FullPos.fromLocal(0, local.x, 2)], Facing.RIGHT)
}
4 -> {
if (f == Facing.RIGHT)
Pair(nodes[FullPos.fromLocal(49, 49 - local.y, 1)], Facing.LEFT)
else // down
Pair(nodes[FullPos.fromLocal(49, local.x, 5)], Facing.LEFT)
}
5 -> when (f) {
Facing.RIGHT -> Pair(nodes[FullPos.fromLocal(local.y, 49, 4)], Facing.UP)
Facing.DOWN -> Pair(nodes[FullPos.fromLocal(local.x, 0, 1)], Facing.DOWN)
Facing.LEFT -> Pair(nodes[FullPos.fromLocal(local.y, 0, 0)], Facing.DOWN)
else -> throw IllegalStateException()
}
else -> throw IllegalStateException("Illegal side: " + u.pos.side)
}
}
private operator fun <T> List<List<T>>.get(p: FullPos) = get(p.global)
private enum class Facing(x: Int = 0, y: Int = 0) {
RIGHT(x = 1),
DOWN (y = 1),
LEFT (x = -1),
UP (y = -1);
val d = Pos(x, y)
fun turn(right: Boolean) = VALS[Math.floorMod(ordinal + if (right) 1 else -1, NUM)]
companion object {
val VALS = values().toList()
val NUM = VALS.size
}
}
private class FullPos private constructor(
val global: Pos,
val local: Pos,
val side: Int,
) {
companion object {
fun fromGlobal(p: Pos) = FullPos(p, p.floorMod(50, 50), getSide(p))
fun fromGlobal(x: Int, y: Int) = fromGlobal(Pos(x, y))
fun fromLocal(p: Pos, s: Int) = FullPos(getGlobal(p, s), p, s)
fun fromLocal(x: Int, y: Int, s: Int) = fromLocal(Pos(x, y), s)
private fun getSide(p: Pos): Int {
val sx = p.x / 50
val sy = p.y / 50
return when (sy) {
0 -> sx - 1
1 -> 2
2 -> sx + 3
3 -> 5
else -> throw IllegalStateException()
}
}
private fun getGlobal(local: Pos, side: Int) = local + 50 * when (side) {
0 -> Pos(1, 0)
1 -> Pos(2, 0)
2 -> Pos(1, 1)
3 -> Pos(0, 2)
4 -> Pos(1, 2)
5 -> Pos(0, 3)
else -> throw IllegalStateException()
}
}
}
private class Node(
val pos: FullPos,
val repr: Char
) {
val adj = Facing.VALS.map { Pair(this, it) }.toTypedArray()
}
| 0 | Kotlin | 0 | 0 | 8ffbcae744b62e36150af7ea9115e351f10e71c1 | 4,779 | aoc-2022 | ISC License |
src/main/kotlin/year2022/Day09.kt | simpor | 572,200,851 | false | {"Kotlin": 80923} | import kotlin.math.absoluteValue
class Day09 {
fun parse(input: String): List<Pair<String, Int>> = input.lines().map { l ->
val s = l.split(" ")
Pair(s[0], s[1].toInt())
}
fun moveFunction(move: String): (Point) -> Point = when (move) {
"U" -> { pos: Point -> pos.copy(y = pos.y + 1) }
"D" -> { pos: Point -> pos.copy(y = pos.y - 1) }
"R" -> { pos: Point -> pos.copy(x = pos.x + 1) }
"L" -> { pos: Point -> pos.copy(x = pos.x - 1) }
else -> throw Exception("Unknown move: $move")
}
fun Point.isAround(other: Point): Boolean =
if ((this.x - other.x).absoluteValue >= 2) false else (this.y - other.y).absoluteValue < 2
fun printSnake(moveCommand: Pair<String, Int>, snake: MutableMap<Int, Point>) {
val xMax = snake.values.maxOfOrNull { it.x }!!
val xMin = snake.values.minOfOrNull { it.x }!!
val yMax = snake.values.maxOfOrNull { it.y }!!
val yMin = snake.values.minOfOrNull { it.y }!!
val points = snake.map { Pair(it.value, it.key) }.toMap()
println("Move command: ${moveCommand.first} ${moveCommand.second}")
for (y in yMax downTo yMin) {
for (x in xMin..xMax) {
if (x == 0 && y == 0) print("s")
else if (points.contains(Point(x, y))) print(points[Point(x, y)])
else print(".")
}
println()
}
println()
}
fun printMap(map: MutableMap<Point, Boolean>) {
val xMax = map.keys.maxOfOrNull { it.x }!!
val xMin = map.keys.minOfOrNull { it.x }!!
val yMax = map.keys.maxOfOrNull { it.y }!!
val yMin = map.keys.minOfOrNull { it.y }!!
val points = map.map { it.key }.toSet()
println("Map")
for (y in yMax downTo yMin) {
for (x in xMin..xMax) {
if (points.contains(Point(x, y))) print("#")
else print(".")
}
println()
}
println()
}
fun moveSnake(snake: MutableMap<Int, Point>, i: Int, move: (Point) -> Point): Pair<Int, Point> {
val current = snake[i]!!
val pair = if (i == 0) {
Pair(0, move.invoke(current))
} else {
val prev = snake[i - 1]!!
if (prev.isAround(current)) {
Pair(i, current)
} else {
var x = if (current.x == prev.x) current.x else if (current.x < prev.x) current.x + 1 else current.x - 1
var y = if (current.y == prev.y) current.y else if (current.y < prev.y) current.y + 1 else current.y - 1
Pair(i, Point(x, y))
}
}
return pair
}
fun part1(input: String, debug: Boolean = false): Long {
val moves = parse(input)
val range = 0..1
val snake = range.associateWith { Point(0, 0) }.toMutableMap()
val map = logic(moves, range, snake, debug)
if (debug) printMap(map)
return map.values.count { it }.toLong()
}
fun part2(input: String, debug: Boolean = false): Long {
val moves = parse(input)
val range = 0..9
val snake = range.associateWith { Point(0, 0) }.toMutableMap()
val map = logic(moves, range, snake, debug)
if (debug) printMap(map)
return map.values.count { it }.toLong()
}
fun logic(
moves: List<Pair<String, Int>>,
range: IntRange,
snake: MutableMap<Int, Point>,
debug: Boolean
): MutableMap<Point, Boolean> {
val map = mutableMapOf<Point, Boolean>()
moves.forEach { move ->
val updatePos = moveFunction(move.first)
repeat(move.second) {
range.forEach { key ->
snake[key] = moveSnake(snake, key, updatePos).second
}
map[snake[range.max()]!!] = true
if (debug) printSnake(move, snake)
}
}
return map
}
fun testInput() =
"R 4\n" +
"U 4\n" +
"L 3\n" +
"D 1\n" +
"R 4\n" +
"D 1\n" +
"L 5\n" +
"R 2"
fun input() = AoCUtils.readText("year2022/day09.txt")
}
| 0 | Kotlin | 0 | 0 | 631cbd22ca7bdfc8a5218c306402c19efd65330b | 4,297 | aoc-2022-kotlin | Apache License 2.0 |
src/main/kotlin/io/undefined/AccountMerge.kt | jffiorillo | 138,075,067 | false | {"Kotlin": 434399, "Java": 14529, "Shell": 465} | package io.undefined
import io.utils.runTests
// https://leetcode.com/problems/accounts-merge/
class AccountMerge {
fun execute(input: List<List<String>>): List<List<String>> {
val information = input.mapIndexed { index, list -> index to (list.first() to list.subList(1, list.size).toMutableSet()) }.toMap().toMutableMap()
val map = mutableListOf<Pair<MutableSet<String>, Int>>()
val groups = information.map { (key, value) -> value.second to key }
for ((set, index) in groups) {
val keys = map.filter { (key, _) -> key.any { set.contains(it) } }
when {
keys.isEmpty() -> map.add(set to index)
else -> {
val newKey = keys.first()
newKey.first.addAll(set)
(1 until keys.size).map { keys[it] }.forEach { (values, index) ->
newKey.first.addAll(values)
information.remove(index)
}
information.remove(index)
}
}
}
return information.values.map { (name, emails) -> mutableListOf(name).apply { addAll(emails.sorted()) } }
}
private data class Node(val name: String, val value: Set<String>, val children: MutableList<Node> = mutableListOf())
}
fun main() {
runTests(listOf(
listOf(
listOf("David", "<EMAIL>", "<EMAIL>"),
listOf("David", "<EMAIL>", "<EMAIL>"),
listOf("David", "<EMAIL>", "<EMAIL>"),
listOf("David", "<EMAIL>", "<EMAIL>"),
listOf("David", "<EMAIL>", "<EMAIL>"))
to listOf(listOf("David", "<EMAIL>", "<EMAIL>", "<EMAIL>", "<EMAIL>", "<EMAIL>", "<EMAIL>"))
)) { (input, value) -> value to AccountMerge().execute(input) }
} | 0 | Kotlin | 0 | 0 | f093c2c19cd76c85fab87605ae4a3ea157325d43 | 1,714 | coding | MIT License |
stepik/sportprogramming/ScheduleGreedyAlgorithm.kt | grine4ka | 183,575,046 | false | {"Kotlin": 98723, "Java": 28857, "C++": 4529} | package stepik.sportprogramming
private const val MAX_DAYS = 5000
private val used: BooleanArray = BooleanArray(MAX_DAYS) { false }
private val orders = mutableListOf<Order>()
fun main() {
val n = readInt()
repeat(n) {
orders.add(readOrder())
}
val sortedByDeadlineOrders = orders.sortedDescending()
var sum: Long = 0
for (i in 0 until sortedByDeadlineOrders.size) {
val order = sortedByDeadlineOrders[i]
var k = order.deadline
while (k >= 1 && used[k]) {
k--
}
if (k == 0) {
continue
}
used[k] = true
sum += order.cost
}
println("Maximum sum of all orders will be $sum")
}
private class Order(val deadline: Int, val cost: Int) : Comparable<Order> {
override fun compareTo(other: Order): Int {
return cost - other.cost
}
}
private fun readInt() = readLine()!!.toInt()
private fun readOrder(): Order {
val pairOfInts = readLine()!!.split(" ").map(String::toInt).toIntArray()
return Order(pairOfInts[0], pairOfInts[1])
}
| 0 | Kotlin | 0 | 0 | c967e89058772ee2322cb05fb0d892bd39047f47 | 1,078 | samokatas | MIT License |
codeforces/round901/d_ok_but_should_be_wa.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package codeforces.round901
private fun solve(): Double {
val (n, m) = readInts()
val d = List(n + 1) { DoubleArray(m - n + 1) }
for (i in 1..n) {
var kBest = 0
for (s in d[i].indices) {
val range = maxOf(kBest - 5, 0)..minOf(kBest + 11, s)
var best = Double.MAX_VALUE
for (k in range) {
val new = (i + s - 1.0 - k) / (1 + k) + d[i - 1][s - k]
if (new < best) {
best = new
kBest = k
}
}
d[i][s] = best
}
}
return d[n][m - n] * 2 + n
}
fun main() = repeat(1) { println(solve()) }
private fun readStrings() = readln().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| 0 | Java | 1 | 9 | 30953122834fcaee817fe21fb108a374946f8c7c | 636 | competitions | The Unlicense |
src/aoc2022/Day11.kt | FluxCapacitor2 | 573,641,929 | false | {"Kotlin": 56956} | package aoc2022
import Day
import splitOn
object Day11 : Day(2022, 11) {
private val monkeys = mutableListOf<Monkey>()
data class Monkey(
val items: MutableList<Long>,
val operation: (Long) -> Long,
val test: (Long) -> Boolean,
val ifTrue: Int,
val ifFalse: Int,
var inspected: Int = 0
) {
fun process(divideByThree: Boolean = true) {
items.removeAll { item ->
inspected++
val newLevel = if (divideByThree) {
operation(item) / 3
} else {
operation(item)
}
val result = test(newLevel)
if (result) {
monkeys[ifTrue].items.add(newLevel)
} else {
monkeys[ifFalse].items.add(newLevel)
}
return@removeAll true
}
}
}
fun readInput(useModuloTrick: Boolean) {
monkeys.clear()
// This number keeps track of the product of all divisors that are tested
// (see later comment)
var totalModulus = 1
for (lineGroup in lines.splitOn { it.isEmpty() }) {
val group = lineGroup.map { it.trim() }
val eq = group[2].substringAfter("new = ").split(' ') // The full equation, e.g. ["old", "*", "5"]
val factor = group[3].substringAfter("divisible by ")
.toInt() // The required divisor for the condition to return true
val monkey = Monkey(
items = group[1].substringAfter("Starting items: ")
.split(", ") // Split the string by comma into a list of substrings
.map { it.toLong() }.toMutableList(), // Convert the strings to numbers
operation = { num ->
val input1 = eq[0].toLongOrNull() ?: num
val input2 = eq[2].toLongOrNull() ?: num
val newValue = when (val op = eq[1]) {
// addExact and multiplyExact throw exceptions when numbers overflow.
"+" -> Math.addExact(input1, input2)
"*" -> Math.multiplyExact(input1, input2)
else -> error("Invalid operation: $op")
}
// The value returned after the operation must be reduced to a smaller number
// for the program to run in a reasonable amount of time. Because we are only using
// the worry-values to check if they are divisible, applying a modulus operation
// with the product of all divisors that we check will keep the numbers at a relatively
// small size (under 2^63 - 1) while preserving the results of divisibility checks.
if (useModuloTrick) newValue % totalModulus
// Note: This trick does not apply when the worry-values are divided by 3 after every
// inspection, because that alters divisibility of the numbers.
else newValue
},
test = { num ->
num % factor == 0L
},
ifTrue = group[4].substringAfter("throw to monkey ").toInt(),
ifFalse = group[5].substringAfter("throw to monkey ").toInt()
)
monkeys.add(monkey)
totalModulus *= factor
}
}
override fun part1() {
readInput(useModuloTrick = false)
// Process 20 rounds, where worry levels are divided by three every time they're processed.
repeat(20) {
monkeys.forEach {
it.process(divideByThree = true)
}
}
println("Part 1 result: ${getMonkeyBusinessLevel()}")
}
override fun part2() {
readInput(useModuloTrick = true)
// Process 10,000 rounds, where worry levels are not divided by three every time.
// A modulus trick is needed to keep the numbers at a reasonable (< Long.MAX_VALUE) size.
repeat(10000) {
monkeys.forEach {
it.process(divideByThree = false)
}
}
println("Part 2 result: ${getMonkeyBusinessLevel()}")
}
/**
* Finds the top two monkeys based on their amount of items
* inspected, and returns the product of these two numbers.
*/
private fun getMonkeyBusinessLevel(): Long {
return monkeys
.sortedByDescending { it.inspected } // Sort the monkeys by their amounts of items inspected (with the highest first)
.take(2) // Take the top two
.map { it.inspected.toLong() } // Multiply them together
.reduce { acc, i -> acc * i }
}
} | 0 | Kotlin | 0 | 0 | a48d13763db7684ee9f9129ee84cb2f2f02a6ce4 | 4,824 | advent-of-code-2022 | Apache License 2.0 |
src/day17/Day17.kt | Volifter | 572,720,551 | false | {"Kotlin": 65483} | package day17
import utils.*
const val WIDTH = 7
val ROCKS = listOf(
Rock(
Coords(0, 0),
Coords(1, 0),
Coords(2, 0),
Coords(3, 0)
),
Rock(
Coords(1, 0),
Coords(0, -1),
Coords(1, -1),
Coords(2, -1),
Coords(1, -2)
),
Rock(
Coords(0, 0),
Coords(1, 0),
Coords(2, 0),
Coords(2, -1),
Coords(2, -2)
),
Rock(
Coords(0, 0),
Coords(0, -1),
Coords(0, -2),
Coords(0, -3)
),
Rock(
Coords(0, 0),
Coords(1, 0),
Coords(0, -1),
Coords(1, -1)
)
)
val FILL_DIRECTIONS = listOf(
Coords(0, 1),
Coords(-1, 0),
Coords(1, 0)
)
data class Coords(var x: Int, var y: Int) {
operator fun plus(other: Coords): Coords = Coords(x + other.x, y + other.y)
operator fun minus(other: Coords): Coords = Coords(x - other.x, y - other.y)
override operator fun equals(other: Any?): Boolean =
other is Coords
&& other.x == x
&& other.y == y
override fun hashCode(): Int = x * 31 + y
fun collidesWithMap(map: Set<Coords>): Boolean =
x !in (0 until WIDTH) || y > 0 || this in map
}
class Rock(private vararg val offsets: Coords) {
val minY: Int get() = offsets.minOf { it.y }
operator fun plus(delta: Coords): Rock = Rock(
*offsets
.map { it + delta }
.toTypedArray()
)
fun collidesWithMap(map: Set<Coords>): Boolean =
offsets.any { it.collidesWithMap(map) }
fun addToMap(map: MutableSet<Coords>) = map.addAll(offsets)
override fun toString(): String = "Rock(${offsets.toList()})"
}
class InfiniteCollection<T>(private val items: List<T>) {
var index = 0
fun next(): T = items[index].also { index = (index + 1) % items.size }
}
data class State(val gaps: Set<Coords>, val windIdx: Int, val rockIdx: Int)
fun dropRock(
map: MutableSet<Coords>,
droppedRock: Rock,
winds: InfiniteCollection<Coords>
): Rock =
generateSequence(droppedRock) { prevRock ->
(prevRock + Coords(0, 1))
.takeUnless { it.collidesWithMap(map) }
?.let { rock ->
(rock + winds.next())
.takeUnless { it.collidesWithMap(map) }
?: rock
}
}.last()
fun getGaps(map: Set<Coords>, minY: Int): Set<Coords> {
val visited = (0 until WIDTH).mapNotNull { x ->
Coords(x, 0).takeUnless {
Coords(x, minY).collidesWithMap(map)
}
}.toMutableSet()
generateSequence(visited.toList()) { stack ->
stack
.flatMap { coords ->
FILL_DIRECTIONS.mapNotNull { delta ->
(coords + delta)
.takeUnless { newCoords ->
Coords(
newCoords.x,
newCoords.y + minY
).collidesWithMap(map)
|| newCoords in visited
}
?.also { visited.add(it) }
}
}
.takeIf { it.isNotEmpty() }
}.count()
return visited
}
fun solve(input: String, cycleCount: Long): Long {
val winds = InfiniteCollection(
input.map { Coords(if (it == '>') 1 else -1, 0) }
)
val rocks = InfiniteCollection(ROCKS)
val map = mutableSetOf<Coords>()
var minY = 1
var cyclesRemaining = cycleCount
val cache = mutableMapOf<State, Pair<Long, Int>>()
var extraY: Long? = null
while (cyclesRemaining > 0) {
val rockIdx = rocks.index
val windIdx = winds.index
val rock = dropRock(map, rocks.next() + Coords(2, minY - 5), winds)
rock.addToMap(map)
minY = minOf(minY, rock.minY)
if (extraY == null) {
val state = State(getGaps(map, minY), windIdx, rockIdx)
cache[state]?.let { (prevCycle, prevHeight) ->
val deltaHeight = prevHeight - minY
val deltaCycles = prevCycle - cyclesRemaining
val n = cyclesRemaining / deltaCycles - 1
extraY = deltaHeight.toLong() * n
cyclesRemaining -= deltaCycles * n
}
cache[state] = Pair(cyclesRemaining, minY)
}
cyclesRemaining--
}
return 1 - minY.toLong() + (extraY ?: 0)
}
fun part1(input: String): Long = solve(input, 2022)
fun part2(input: String): Long = solve(input, 1_000_000_000_000)
fun main() {
val testInput = readInput("Day17_test")[0]
expect(part1(testInput), 3068)
expect(part2(testInput), 1514285714288)
val input = readInput("Day17")[0]
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | c2c386844c09087c3eac4b66ee675d0a95bc8ccc | 4,818 | AOC-2022-Kotlin | Apache License 2.0 |
Array/cuijilin/Array.kt | JessonYue | 268,215,243 | false | null | package luge
/*167. 两数之和 II - 输入有序数组*/
/*给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数。
函数应该返回这两个下标值 index1 和 index2,其中 index1 必须小于 index2。
说明:
返回的下标值(index1 和 index2)不是从零开始的。
你可以假设每个输入只对应唯一的答案,而且你不可以重复使用相同的元素。
示例:
输入: numbers = [2, 7, 11, 15], target = 9
输出: [1,2]
解释: 2 与 7 之和等于目标数 9 。因此 index1 = 1, index2 = 2 。*/
private val nums = intArrayOf(1, 2, 5, 8, -88)
private val target = 7
fun main() {
val index1 = getIndex1(nums, target)
println("the index is : ${+index1[0]},${+index1[1]}")
val index2 = getIndex2(nums, target)
println("the index is : ${+index2[0]},${+index2[1]}")
val index3 = getIndex3(nums, target)
println("the index is : ${+index3[0]},${+index3[1]}")
println(200 * 300 * 400 * 500)
}
// 时间复杂度: O(nˆ2)
fun getIndex1(nums: IntArray, target: Int): IntArray {
var start = 0
for (i in nums.indices) {
start = i
for (j in i + 1 until nums.size) {
if (target - nums[start] == nums[j]) {
return intArrayOf(start, j)
}
}
}
return intArrayOf(-1, -1)
}
// 2遍哈希表
fun getIndex2(nums: IntArray, target: Int): IntArray {
var map: HashMap<Int, Int> = HashMap()
nums.forEachIndexed { index, value ->
map[value] = index
}
nums.forEachIndexed { index, value ->
if (map.containsKey(target - value) && index != target - value) {
return intArrayOf(index,map[target - value]!!)
}
}
return intArrayOf(-1, -1)
}
// 1遍哈希表
fun getIndex3(nums: IntArray, target: Int): IntArray {
var map: HashMap<Int, Int> = HashMap()
nums.forEachIndexed { index, value ->
var complement = target - value
if (map.containsKey(complement)) {
return intArrayOf(map[complement]!!, index)
}
map[value] = index
}
return intArrayOf(-1, -1)
}
/*2020.06.11
70. 爬楼梯
假设你正在爬楼梯。需要 n 阶你才能到达楼顶。
每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?
注意:给定 n 是一个正整数。
示例 1:
输入: 2
输出: 2
解释: 有两种方法可以爬到楼顶。
1. 1 阶 + 1 阶
2. 2 阶
示例 2:
输入: 3
输出: 3
解释: 有三种方法可以爬到楼顶。
1. 1 阶 + 1 阶 + 1 阶
2. 1 阶 + 2 阶
3. 2 阶 + 1 阶*/
| 0 | C | 19 | 39 | 3c22a4fcdfe8b47f9f64b939c8b27742c4e30b79 | 2,729 | LeetCodeLearning | MIT License |
app/src/main/java/com/betulnecanli/kotlindatastructuresalgorithms/CodingPatterns/CyclicSort.kt | betulnecanli | 568,477,911 | false | {"Kotlin": 167849} | /*
The Cyclic Sort pattern is used to solve problems where the goal is to sort an array of numbers in a specific range
or find the missing or duplicate number in a range. Let's tackle a simple problem:
"Find the Missing Number in a Consecutive Array." I'll provide a Kotlin implementation for it.
Usage: Use this technique to solve array problems where the input data lies within a fixed range.
*/
//1.Find the Missing Number in a Consecutive Array
fun findMissingNumber(nums: IntArray): Int {
var i = 0
while (i < nums.size) {
if (nums[i] < nums.size && nums[i] != i) {
// Swap the number to its correct position
val temp = nums[i]
nums[i] = nums[temp]
nums[temp] = temp
} else {
i++
}
}
// Find the first missing number
for (j in nums.indices) {
if (nums[j] != j) {
return j
}
}
// If no missing number found, return the next number in the sequence
return nums.size
}
fun main() {
val nums = intArrayOf(3, 0, 1)
val missingNumber = findMissingNumber(nums)
println("Missing Number: $missingNumber")
}
/*
In this example:
The findMissingNumber function takes an array of integers and finds the missing number in a consecutive array starting from 0.
We use the Cyclic Sort pattern to iterate through the array and swap numbers to their correct positions.
After the Cyclic Sort, we find the first index where the number is not equal to the index, and that is the missing number.
You can modify the nums array in the main function to test different scenarios.
This problem demonstrates how Cyclic Sort can be applied to efficiently find a missing number in a consecutive array.
*/
//2.Find All Duplicate Numbers
fun findDuplicates(nums: IntArray): List<Int> {
val duplicates = mutableListOf<Int>()
var i = 0
while (i < nums.size) {
if (nums[i] != i + 1 && nums[i] != nums[nums[i] - 1]) {
// Swap the number to its correct position
val temp = nums[i]
nums[i] = nums[temp - 1]
nums[temp - 1] = temp
} else {
i++
}
}
for (j in nums.indices) {
if (nums[j] != j + 1) {
duplicates.add(nums[j])
}
}
return duplicates
}
fun main() {
val nums = intArrayOf(4, 3, 2, 7, 8, 2, 1, 1)
val duplicates = findDuplicates(nums)
println("Duplicate Numbers: ${duplicates.joinToString(", ")}")
}
//3.Find the First K Missing Positive Numbers
fun findKMissingPositive(nums: IntArray, k: Int): List<Int> {
val missingNumbers = mutableListOf<Int>()
var i = 0
var count = 0
while (count < k) {
if (nums[i] > 0 && nums[i] <= nums.size && nums[i] != nums[nums[i] - 1]) {
// Swap the number to its correct position
val temp = nums[i]
nums[i] = nums[temp - 1]
nums[temp - 1] = temp
} else {
i++
}
count++
}
var j = 0
while (missingNumbers.size < k) {
if (nums[j] != j + 1) {
missingNumbers.add(j + 1)
}
j++
}
return missingNumbers
}
fun main() {
val nums = intArrayOf(2, 3, 4, 7, 11)
val k = 5
val missingNumbers = findKMissingPositive(nums, k)
println("First $k Missing Positive Numbers: ${missingNumbers.joinToString(", ")}")
}
/*
Find All Duplicate Numbers:
The findDuplicates function finds all duplicate numbers in an array using the Cyclic Sort pattern.
After the Cyclic Sort, we iterate through the array and identify the duplicate numbers.
Find the First K Missing Positive Numbers:
The findKMissingPositive function finds the first K missing positive numbers in an array using the Cyclic Sort pattern.
After the Cyclic Sort, we iterate through the array and identify the missing positive numbers until we find K of them.
*/
| 2 | Kotlin | 2 | 40 | 70a4a311f0c57928a32d7b4d795f98db3bdbeb02 | 3,915 | Kotlin-Data-Structures-Algorithms | Apache License 2.0 |
src/main/kotlin/day15_chiton_risk/ChitonRisk.kt | barneyb | 425,532,798 | false | {"Kotlin": 238776, "Shell": 3825, "Java": 567} | package day15_chiton_risk
import geom2d.Point
import geom2d.Rect
import geom2d.asLinearOffset
import java.util.*
/**
* 2D plane again. "You start... your destination" means a graph walk. "Lowest
* total risk" means an optimization problem. The wrinkle is that the
* optimization needs to be integrated into the walk, as the search space is
* infinite, since there's no rules about returning to an already-visited
* location. Such reentrance cannot yield an optimal route, of course, but we
* can do better. As soon as we have _any_ total risk (minimal or not), any
* partial routes which have already exceeded that threshold can be immediately
* ignored.
*
* Part two's search space is _massive_ compared to part one. Generalizing the
* pruning from part one to apply to each point (not just complete routes)
* trades some memory for a lot of CPU, so well worth it. Using a priority queue
* to always extend the lowest-risk routes as quickly as possible maximizes the
* effectiveness of that pruning.
*
* The 5x5 map is also interesting. It's not a simple tiling, but each non-first
* tile is still wholly determined by the first tile. So no need to actually
* materialize the full map. If part one's map has a nice interface,
* a decorator can be used to "project" it to five times its size (in each
* direction), including the requisite increase in risk.
*/
fun main() {
util.solve(589, ::partOne)
util.solve(2885, ::partTwo)
}
private abstract class Grid {
abstract val width: Int
abstract val height: Int
val bounds by lazy {
Rect(width.toLong(), height.toLong())
}
val bottomRight: Point get() = bounds.bottomRight
abstract fun getRiskAt(p: Point): Int
}
private class SimpleGrid(input: String) : Grid() {
override val width = input.indexOf('\n')
var grid = input
.filter { it != '\n' }
.map(Char::digitToInt)
override val height = grid.size / width
override fun getRiskAt(p: Point) =
grid[p.asLinearOffset(bounds).toInt()]
}
data class Path(
val at: Point,
val totalRisk: Int,
val visited: List<Point>?,
) : Comparable<Path> {
constructor(at: Point, track: Boolean = false) : this(
at,
0,
if (track) listOf(at) else null,
)
fun then(pos: Point, risk: Int) =
Path(
pos,
totalRisk + risk,
visited?.plus(pos)
)
override fun compareTo(other: Path) =
totalRisk - other.totalRisk
}
fun partOne(input: String): Int =
riskOfBestPath(SimpleGrid(input))
private fun riskOfBestPath(grid: Grid, sink: ((Path) -> Unit)? = null): Int {
val queue: Queue<Path> = PriorityQueue()
queue.add(Path(Point.ORIGIN, sink != null))
val allRisks = HashMap<Point, Int>()
val goal = grid.bottomRight
while (queue.isNotEmpty()) {
val p = queue.remove()
if (p.at == goal) {
sink?.invoke(p)
return p.totalRisk
}
if (p.totalRisk >= allRisks.getOrDefault(p.at, Int.MAX_VALUE)) {
continue
}
allRisks[p.at] = p.totalRisk
sink?.invoke(p)
p.at
.orthogonalNeighbors(grid.bounds)
.map { p.then(it, grid.getRiskAt(it)) }
.forEach(queue::add)
}
throw IllegalStateException("found no path to the bottom corner?!")
}
private class TiledGrid(
val base: Grid,
n: Int,
override val width: Int = base.width * n,
override val height: Int = base.height * n
) : Grid() {
override fun getRiskAt(p: Point): Int {
val raw = base.getRiskAt(
Point(
p.x % base.width,
p.y % base.height
)
)
return ((raw + p.x / base.width + p.y / base.height - 1) % 9 + 1).toInt()
}
}
fun partTwo(input: String) =
riskOfBestPath(TiledGrid(SimpleGrid(input), 5))
| 0 | Kotlin | 0 | 0 | a8d52412772750c5e7d2e2e018f3a82354e8b1c3 | 3,900 | aoc-2021 | MIT License |
src/main/kotlin/net/dinkla/raytracerchallenge/math/Tuple.kt | jdinkla | 325,043,782 | false | {"Kotlin": 127433, "Gherkin": 74260} | package net.dinkla.raytracerchallenge.math
import net.dinkla.raytracerchallenge.math.Approx.isDifferenceSmall
import java.util.Objects
import kotlin.math.sqrt
typealias Vector = Tuple
typealias Point = Tuple
data class Tuple(val x: Double, val y: Double, val z: Double, val w: Double) {
fun isPoint(): Boolean = w == 1.0
fun isVector(): Boolean = w == 0.0
operator fun plus(t: Tuple): Tuple {
assert(w + t.w <= 1.0)
return Tuple(x + t.x, y + t.y, z + t.z,w + t.w)
}
operator fun minus(t: Tuple): Tuple {
assert(w - t.w >= 0.0)
return Tuple(x - t.x, y - t.y, z - t.z,w - t.w)
}
operator fun unaryMinus() = Tuple(-x, -y, -z, -w)
operator fun times(s: Double) = Tuple(x * s, y * s, z * s, w * s)
operator fun div(s: Double) = Tuple(x / s, y / s, z / s, w / s)
infix fun dot(v: Vector): Double {
assert(isVector())
assert(v.isVector())
return x * v.x + y * v.y + z * v.z // + w * t.w
}
infix fun cross(v: Vector): Vector {
assert(isVector())
assert(v.isVector())
return vector(y * v.z - z * v.y, z * v.x - x * v.z, x * v.y - y * v.x)
}
fun magnitude(): Double {
assert(isVector())
fun sqrLength(): Double = x * x + y * y + z * z // + w * w w is 0.0 for vector
return sqrt(sqrLength())
}
fun normalize(): Vector {
val l = magnitude()
return vector(x / l, y / l, z / l)
}
override fun equals(other: Any?): Boolean {
val p: Tuple = other as? Tuple ?: return false
return isDifferenceSmall(x, p.x) && isDifferenceSmall(y, p.y) && isDifferenceSmall(z, p.z) && w == p.w
}
override fun hashCode(): Int = Objects.hash(x, y, z, w)
fun reflect(normal: Vector): Vector = this - (normal * 2.0 * (this dot normal))
fun toVector(): Vector = Tuple(x, y, z, 0.0)
companion object {
val ORIGIN = point(0, 0, 0)
val UP = vector(0, 1, 0)
}
}
fun tuple(x: Int, y: Int, z: Int, w: Int) = Tuple(x.toDouble(), y.toDouble(), z.toDouble(), w.toDouble())
fun point(x: Int, y: Int, z: Int) = Tuple(x.toDouble(), y.toDouble(), z.toDouble(), 1.0)
fun point(x: Double, y: Double, z: Double) = Tuple(x, y, z, 1.0)
fun vector(x: Int, y: Int, z: Int) = Tuple(x.toDouble(), y.toDouble(), z.toDouble(), 0.0)
fun vector(x: Double, y: Double, z: Double) = Tuple(x, y, z, 0.0)
| 0 | Kotlin | 0 | 1 | 0cf1a977250e6ea9e725fab005623e7a627ad29e | 2,406 | ray-tracer-challenge | MIT License |
kotlin/0743-network-delay-time.kt | neetcode-gh | 331,360,188 | false | {"JavaScript": 473974, "Kotlin": 418778, "Java": 372274, "C++": 353616, "C": 254169, "Python": 207536, "C#": 188620, "Rust": 155910, "TypeScript": 144641, "Go": 131749, "Swift": 111061, "Ruby": 44099, "Scala": 26287, "Dart": 9750} | class Solution {
//times[i] == [source, target, weight]
fun networkDelayTime(times: Array<IntArray>, n: Int, k: Int): Int {
val adjList = ArrayList<ArrayList<Pair<Int,Int>>>(times.size)
for(i in 0..n)
adjList.add(ArrayList<Pair<Int,Int>>())
for(time in times){
val (source, target, weight) = time
adjList.get(source).add(Pair(target, weight))
}
//minheap stores [node, weight]
val minHeap = PriorityQueue<IntArray>{ edge1: IntArray, edge2: IntArray ->
edge1[1] - edge2[1]
}
val visited = HashSet<Int>()
minHeap.add(intArrayOf(k,0))
var time = 0 //the max of all the shortest paths
while(!minHeap.isEmpty()){
val (node, weight) = minHeap.poll()
if(visited.contains(node))
continue
visited.add(node)
time = maxOf(time, weight)
val listofnodes = adjList.get(node)
for(adjacent in listofnodes){
val (adjNode, adjWeight) = adjacent
if(!visited.contains(adjNode))
minHeap.add(intArrayOf(adjNode, adjWeight+weight)) // total path to each adjNode
}
}
return if(visited.size == n) time else -1
}
}
| 337 | JavaScript | 2,004 | 4,367 | 0cf38f0d05cd76f9e96f08da22e063353af86224 | 1,305 | leetcode | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/SubarraysDivByK.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
/**
* 974. Subarray Sums Divisible by K
* @see <a href="https://leetcode.com/problems/subarray-sums-divisible-by-k/">Source</a>
*/
fun interface SubarraysDivByK {
operator fun invoke(nums: IntArray, k: Int): Int
}
class SubarraysDivByKMap : SubarraysDivByK {
override operator fun invoke(nums: IntArray, k: Int): Int {
val map: MutableMap<Int, Int> = HashMap()
map[0] = 1
var count = 0
var sum = 0
for (a in nums) {
sum = (sum + a) % k
if (sum < 0) sum += k // Because -1 % 5 = -1, but we need the positive mod 4
count += map.getOrDefault(sum, 0)
map[sum] = map.getOrDefault(sum, 0) + 1
}
return count
}
}
class SubarraysDivByKPrefixSum : SubarraysDivByK {
override operator fun invoke(nums: IntArray, k: Int): Int {
val map = IntArray(k)
map[0] = 1
var count = 0
var sum = 0
for (a in nums) {
sum = (sum + a) % k
if (sum < 0) sum += k // Because -1 % 5 = -1, but we need the positive mod 4
count += map[sum]
map[sum]++
}
return count
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,814 | kotlab | Apache License 2.0 |
src/main/kotlin/coursework/sorting/MergeSort.kt | Whitedrawn | 674,729,151 | false | null | package coursework.sorting
import coursework.database.BOOK
object MergeSort {
var tick = 0
fun sort(scrambled: ArrayList<BOOK>): Pair<ArrayList<BOOK>, Int> {
tick = 0
val res = ArrayList(scrambled)
if (scrambled.size <= 1)
return Pair(res, tick)
else {
val h = scrambled.size / 2
val leftScrambled = ArrayList(scrambled.slice(0 until h))
val rightScrambled = ArrayList(scrambled.slice(h until scrambled.size))
val (leftSorted, _) = sort(leftScrambled)
val (rightSorted, _)= sort(rightScrambled)
merge_rec(leftSorted, rightSorted, res)
return Pair(res, tick)
}
}
fun merge_rec(
leftSorted: ArrayList<BOOK>,
rightSorted: ArrayList<BOOK>,
res: ArrayList<BOOK>,
) {
fun merge_rec_g(
leftSorted: ArrayList<BOOK>, l: Int,
rightSorted: ArrayList<BOOK>, r: Int,
res: ArrayList<BOOK>, t: Int,
) {
if (!((l < leftSorted.size) || (r < rightSorted.size))) {
assert((l == leftSorted.size) && (r == rightSorted.size))
} else {
assert(t < res.size)
tick += 1
if (l == leftSorted.size) {
res[t] = rightSorted[r]
merge_rec_g(leftSorted, l, rightSorted, r + 1, res, t + 1)
} else if (r == rightSorted.size) {
res[t] = leftSorted[l]
merge_rec_g(leftSorted, l + 1, rightSorted, r, res, t + 1)
} else {
if (leftSorted[l].YEAR_OF_PUBLICATION < rightSorted[r].YEAR_OF_PUBLICATION) {
res[t] = leftSorted[l]
merge_rec_g(leftSorted, l + 1, rightSorted, r, res, t + 1)
} else {
res[t] = rightSorted[r]
merge_rec_g(leftSorted, l, rightSorted, r + 1, res, t + 1)
}
}
}
}
// Inmmersion call.
var (l, r, t) = Triple(0, 0, 0)
merge_rec_g(leftSorted, l, rightSorted, r, res, t) // not B
}
}
//fun main() {
// val (left, right, res) =Triple(
// ArrayList(arrayListOf(-1,2,3)),
// ArrayList(arrayListOf(1,12,13)),
// ArrayList(arrayListOf(1,32,13,4,15,6)))
// MergeSort.merge_R(left,right,res)
// res.forEach { i ->
// print("${i} ")
// }
//}
//fun main() {
// val left = ArrayList(arrayListOf(-1, 20, 3))
// val (a,i) = MergeSort.sort(left)
// println(i)
// a.forEach({ println(it)}
// )
//
//}
| 0 | Kotlin | 0 | 0 | 502e68f30238331152fa4950f2003bcf93080bac | 2,788 | JavaLibrary | MIT License |
src/main/kotlin/Day22.kt | dlew | 75,886,947 | false | null | import java.util.*
import java.util.regex.Pattern
class Day22 {
data class Coord(val x: Int, val y: Int)
data class Node(val x: Int, val y: Int, val size: Int, val used: Int, val avail: Int)
companion object {
private val NODE_PATTERN =
Pattern.compile("/dev/grid/node-x(\\d+)-y(\\d+)\\s+(\\d+)T\\s+(\\d+)T\\s+(\\d+)T\\s+(\\d+)%")
fun parseNodes(input: String) = input.split("\n").map { parseNode(it) }
fun parseNode(input: String): Node {
val matcher = NODE_PATTERN.matcher(input)
matcher.matches()
return Node(
matcher.group(1).toInt(),
matcher.group(2).toInt(),
matcher.group(3).toInt(),
matcher.group(4).toInt(),
matcher.group(5).toInt()
)
}
fun nodesToGrid(nodes: List<Node>, transform: (Node) -> Int): List<List<Int>> {
val result = ArrayList<MutableList<Int>>()
nodes.forEach { node ->
if (result.size < node.y + 1) {
result.add(ArrayList<Int>())
}
result[node.y].add(transform.invoke(node))
}
return result
}
fun viable(a: Node, b: Node): Boolean {
return a.used != 0
&& (a.x != b.x || a.y != b.y)
&& a.used <= b.avail
}
fun countViablePairs(nodes: List<Node>): Int {
var count = 0
nodes.forEach { a ->
nodes.forEach { b ->
if (viable(a, b)) {
count++
}
}
}
return count
}
// Key observation: Besides a few nodes which have a huge used
// area, all nodes can move into/out of the empty node. So we just
// convert this into a maze with a few walls
private fun convertToMaze(nodes: List<Node>): List<List<Boolean>> {
val result = ArrayList<MutableList<Boolean>>()
nodes.forEach { node ->
if (result.size < node.y + 1) {
result.add(ArrayList<Boolean>())
}
result[node.y].add(node.used > 100)
}
return result
}
fun finalSolution(nodes: List<Node>): Int {
val maze = convertToMaze(nodes)
val width = maze[0].size
val emptyNode = findEmpty(nodes)
var empty = Coord(emptyNode.x, emptyNode.y)
var steps = 0
(1..width - 1).reversed().forEach { dataIndex ->
val mazeWithDataBlocked = maze.map { it.toMutableList() }
mazeWithDataBlocked[0][dataIndex] = true
steps += fastestPath(mazeWithDataBlocked, empty, Coord(dataIndex - 1, 0)) + 1
empty = Coord(dataIndex, 0)
}
return steps
}
fun fastestPath(maze: List<List<Boolean>>, start: Coord, end: Coord): Int {
val visited = HashSet<Coord>()
visited.add(start)
var lastVisited = listOf(start)
var count = 1
while (lastVisited.isNotEmpty()) {
val possibilities = lastVisited
.flatMap { legalAdjacent(maze, it) }
.toSet()
.filter { !visited.contains(it) }
if (possibilities.contains(end)) {
return count
}
lastVisited = possibilities
visited.addAll(lastVisited)
count++
}
throw IllegalStateException("Should have found a solution!")
}
fun legalAdjacent(maze: List<List<Boolean>>, point: Coord): List<Coord> {
val possibilities = ArrayList<Coord>()
// Up
if (point.y != 0 && !maze[point.y - 1][point.x]) {
possibilities.add(Coord(point.x, point.y - 1))
}
// Down
if (point.y != maze.size - 1 && !maze[point.y + 1][point.x]) {
possibilities.add(Coord(point.x, point.y + 1))
}
// Left
if (point.x != 0 && !maze[point.y][point.x - 1]) {
possibilities.add(Coord(point.x - 1, point.y))
}
// Right
if (point.x != maze[0].size - 1 && !maze[point.y][point.x + 1]) {
possibilities.add(Coord(point.x + 1, point.y))
}
return possibilities
}
fun findEmpty(nodes: List<Node>) = nodes.first { it.used == 0 }
}
} | 0 | Kotlin | 2 | 12 | 527e6f509e677520d7a8b8ee99f2ae74fc2e3ecd | 3,988 | aoc-2016 | MIT License |
2023/src/day04/Day04.kt | scrubskip | 160,313,272 | false | {"Kotlin": 198319, "Python": 114888, "Dart": 86314} | package day04
import java.io.File
import kotlin.math.pow
fun main() {
val input = File("src/day04/Day04.txt").readLines()
val scratchers = Pile(input)
println(scratchers.getPointValue())
println(scratchers.getCardCount())
}
val SPACE = Regex("\\s+")
class Pile(input: List<String>) {
private val cards: Map<Int, Scratcher>
init {
cards = buildMap {
input.forEach {
val scratcher = Scratcher(it)
put(scratcher.id, scratcher)
}
}
}
fun getCardCount(): Int {
val countMap = mutableMapOf<Int, Int>()
cards.values.forEach {
addScratcher(it, countMap)
}
return countMap.values.sum()
}
fun getPointValue(): Long {
return cards.values.sumOf { it.getPointValue() }
}
private fun addScratcher(scratcher: Scratcher, countMap: MutableMap<Int, Int>) {
val id = scratcher.id
// Add to map
// println("adding $id")
countMap.putIfAbsent(id, 0)
countMap[id] = countMap[id]!! + 1
(id + 1).rangeTo(id + scratcher.getWinCount()).forEach {
cards[it]?.let { newScratcher ->
addScratcher(newScratcher, countMap)
}
}
}
}
class Scratcher(input: String) {
private val winningNumbers: MutableSet<Long> = mutableSetOf()
private val numbers: MutableSet<Long> = mutableSetOf()
private var pointValue: Long? = null
val id: Int
init {
id = input.substring(0, input.indexOf(":")).split(SPACE)[1].toInt()
val numberStrings = input.substring(input.indexOf(":") + 1).split("|").map { it.trim() }
winningNumbers.addAll(numberStrings[0].split(SPACE).map { it.toLong() })
numbers.addAll(numberStrings[1].split(SPACE).map { it.toLong() })
}
fun getWinCount(): Int {
return numbers.count { winningNumbers.contains(it) }
}
fun getPointValue(): Long {
if (pointValue == null) {
val count = getWinCount()
pointValue = if (count == 0) {
0L
} else {
2.0.pow(count - 1).toLong()
}
}
return pointValue as Long
}
} | 0 | Kotlin | 0 | 0 | a5b7f69b43ad02b9356d19c15ce478866e6c38a1 | 2,237 | adventofcode | Apache License 2.0 |
aoc-2018/src/main/kotlin/nl/jstege/adventofcode/aoc2018/days/Day04.kt | JStege1206 | 92,714,900 | false | null | package nl.jstege.adventofcode.aoc2018.days
import nl.jstege.adventofcode.aoccommon.days.Day
import nl.jstege.adventofcode.aoccommon.utils.extensions.extractValues
class Day04 : Day(title = "Repose Record") {
companion object Configuration {
private const val INPUT_PATTERN_STRING =
"""\[(\d{4}-\d{2}-\d{2} \d{2}:(\d{2}))] """ +
"""(Guard #(\d+) begins shift|falls asleep|wakes up)"""
private val INPUT_REGEX = INPUT_PATTERN_STRING.toRegex()
}
override fun first(input: Sequence<String>): Any = input
.parse()
.maxBy { (_, sleepSessions) -> sleepSessions.sumBy { it.size } }
?.let { (guardId, sleepSessions) ->
sleepSessions.findMinuteMostAsleep()?.key?.let { guardId * it }
} ?: throw IllegalStateException()
override fun second(input: Sequence<String>): Any = input
.parse()
.mapNotNull { (guardId, sleepSessions) ->
sleepSessions
.findMinuteMostAsleep()
?.let { (minute, amount) -> Triple(guardId, minute, amount) }
}
.maxBy { (_, _, minuteAmount) -> minuteAmount }
?.let { (guardId, minute) ->
guardId * minute
} ?: throw IllegalStateException()
private fun Sequence<String>.parse(): Map<Int, List<List<Int>>> =
mutableMapOf<Int, MutableList<List<Int>>>().apply {
this@parse
.sorted()
.map { it.extractValues(INPUT_REGEX, 2, 3, 4) }
.fold(-1 to mutableListOf<List<Int>>()) { (start, sessions), (minute, op, id) ->
when (op) {
"falls asleep" -> minute.toInt() to sessions
"wakes up" -> -1 to sessions.apply { add(start.minutesTo(minute.toInt())) }
else -> -1 to computeIfAbsent(id.toInt()) { mutableListOf() }
}
}
}
private fun Int.minutesTo(other: Int): List<Int> =
if (this >= other) (this until (other + 60)).map { it % 60 }
else (this until other).toList()
private fun List<List<Int>>.findMinuteMostAsleep(): Map.Entry<Int, Int>? = this
.flatten()
.groupBy { it }
.mapValues { (_, value) -> value.size }
.maxBy { it.value }
}
| 0 | Kotlin | 0 | 0 | d48f7f98c4c5c59e2a2dfff42a68ac2a78b1e025 | 2,316 | AdventOfCode | MIT License |
src/Day06.kt | Advice-Dog | 436,116,275 | true | {"Kotlin": 25836} | fun main() {
fun getLanternfishCount(input: List<String>, days: Int): Long {
val fishCount = mutableListOf<Long>()
for (i in 0 until 9) {
fishCount.add(0)
}
val list = input.first().split(",").map { it.toInt() }
list.forEach {
fishCount[it]++
}
println("Initial state: (${fishCount.sum()}) ${fishCount.joinToString { it.toString() }}")
for (day in 1..days) {
val children = fishCount[0]
// add this amount of new fish to the end
fishCount.add(children)
// move this amount to 6 days from now
fishCount[7] += children
// clear the current day
fishCount.removeAt(0)
println("After day $day: (${fishCount.sum()}) ${fishCount.joinToString { it.toString() }}")
}
return fishCount.sum()
}
fun part1(input: List<String>): Long {
return getLanternfishCount(input, days = 80)
}
fun part2(input: List<String>): Long {
return getLanternfishCount(input, days = 256)
}
// test if implementation meets criteria from the description, like:
val testInput = getTestData("Day06")
check(part1(testInput) == 5934L)
check(part2(testInput) == 26_984_457_539)
val input = getData("Day06")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 2a2a4767e7f0976dba548d039be148074dce85ce | 1,388 | advent-of-code-kotlin-template | Apache License 2.0 |
src/main/kotlin/com/ginsberg/advent2017/Day25.kt | tginsberg | 112,672,087 | false | null | /*
* Copyright (c) 2017 by <NAME>
*/
package com.ginsberg.advent2017
/**
* AoC 2017, Day 25
*
* Problem Description: http://adventofcode.com/2017/day/25
* Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2017/day25/
*/
class Day25(input: List<String>) {
private val machine = parseInput(input)
fun solvePart1(): Int =
machine.run()
class Action(val write: Boolean, val move: Int, val nextState: Char)
class MachineState(val zero: Action, val one: Action)
class TuringMachine(private val states: Map<Char, MachineState>, private val steps: Int, startState: Char) {
private val tape = mutableSetOf<Int>()
private var state = states.getValue(startState)
private var cursor = 0
fun run(): Int {
repeat(steps) {
execute()
}
return tape.size
}
private fun execute() {
if (cursor in tape) handleAction(state.one)
else handleAction(state.zero)
}
private fun handleAction(action: Action) {
if (action.write) tape.add(cursor) else tape.remove(cursor)
cursor += action.move
state = states.getValue(action.nextState)
}
}
private fun parseInput(input: List<String>): TuringMachine {
val initialState = input.first()[15]
val steps = input[1].split(" ")[5].toInt()
val stateMap = input
.filter { it.isNotBlank() }
.drop(2)
.map { it.split(" ").last().dropLast(1) }
.chunked(9)
.map {
it[0].first() to MachineState(
Action(it[2] == "1", if (it[3] == "right") 1 else -1, it[4].first()),
Action(it[6] == "1", if (it[7] == "right") 1 else -1, it[8].first())
)
}.toMap()
return TuringMachine(stateMap, steps, initialState)
}
}
| 0 | Kotlin | 0 | 15 | a57219e75ff9412292319b71827b35023f709036 | 1,951 | advent-2017-kotlin | MIT License |
src/Day10.kt | brunojensen | 572,665,994 | false | {"Kotlin": 13161} | private val strings = readInput("Day10.test")
fun main() {
fun sumSixSignalStrengths(cycle : Int, register : Int) =
if(cycle % 40 == 20) cycle * register else 0
fun part1(input: List<String>): Long {
var cycle = 0
var sumSixSignalStrengths = 0L
var register = 1
input.forEach {
sumSixSignalStrengths += sumSixSignalStrengths(++cycle, register)
if("noop" != it) {
sumSixSignalStrengths += sumSixSignalStrengths(++cycle, register)
register += it.split(" ")[1].toInt()
}
}
return sumSixSignalStrengths
}
fun part2(input: List<String>): Long {
return 0
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day10.test")
check(part1(testInput) == 13140L)
check(part2(testInput) == 0L)
val input = readInput("Day10")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 2707e76f5abd96c9d59c782e7122427fc6fdaad1 | 898 | advent-of-code-kotlin-1 | Apache License 2.0 |
leetcode2/src/leetcode/RotateArray.kt | hewking | 68,515,222 | false | null | package leetcode
/**
* 189. 旋转数组
* https://leetcode-cn.com/problems/rotate-array/
* Created by test
* Date 2019/6/7 1:29
* Description
* 给定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数。
示例 1:
输入: [1,2,3,4,5,6,7] 和 k = 3
输出: [5,6,7,1,2,3,4]
解释:
向右旋转 1 步: [7,1,2,3,4,5,6]
向右旋转 2 步: [6,7,1,2,3,4,5]
向右旋转 3 步: [5,6,7,1,2,3,4]
示例 2:
输入: [-1,-100,3,99] 和 k = 2
输出: [3,99,-1,-100]
解释:
向右旋转 1 步: [99,-1,-100,3]
向右旋转 2 步: [3,99,-1,-100]
说明:
尽可能想出更多的解决方案,至少有三种不同的方法可以解决这个问题。
要求使用空间复杂度为 O(1) 的原地算法。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/rotate-array
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
object RotateArray {
class Solution {
/**
* 思路:
* 第一种解法: 错误的解法,还未完成
*/
fun rotate(nums: IntArray, k: Int): Unit {
val len = nums.size
for (i in nums.indices) {
if (i + k >= len) {
nums[i + k - len] = nums[i]
} else {
nums[i + k] = nums[i]
}
}
}
/**
* 第二种解法 ,最容易想到可是效率太低
* O(n * k)
*/
fun rotate2(nums: IntArray, k: Int): Unit {
for (i in 0 until k) {
val tmp = nums.last()
var i = nums.size - 1
while (i > 0) {
nums[i] = nums[i - 1]
i--
}
nums[0] = tmp
}
}
}
} | 0 | Kotlin | 0 | 0 | a00a7aeff74e6beb67483d9a8ece9c1deae0267d | 1,848 | leetcode | MIT License |
src/test/kotlin/ch/ranil/aoc/aoc2023/Day15.kt | stravag | 572,872,641 | false | {"Kotlin": 234222} | package ch.ranil.aoc.aoc2023
import ch.ranil.aoc.AbstractDay
import org.junit.jupiter.api.Test
import kotlin.test.assertEquals
class Day15 : AbstractDay() {
@Test
fun part1TestHash() {
assertEquals(52, hash("HASH"))
}
@Test
fun part1Test() {
assertEquals(1320, compute1(testInput))
}
@Test
fun part1Puzzle() {
assertEquals(516804, compute1(puzzleInput))
}
@Test
fun part2Test() {
assertEquals(145, compute2(testInput))
}
@Test
fun part2Puzzle() {
assertEquals(231844, compute2(puzzleInput))
}
private fun compute1(input: List<String>): Int {
return input
.joinToString("")
.split(",")
.sumOf {
hash(it)
}
}
private fun compute2(input: List<String>): Int {
val boxes = mutableMapOf<Int, MutableMap<String, Int>>()
input
.joinToString("")
.split(",")
.forEach { data ->
val (_, label, operation, focalLength) = Regex("([a-zA-Z]+)([-=])([0-9])*").find(data)?.groupValues.orEmpty()
val boxNumber = hash(label)
when (operation) {
"-" -> boxes[boxNumber]?.remove(label)
"=" -> addEntry(boxes, boxNumber, label, focalLength)
}
}
return boxes.entries.sumOf { (boxNumber, entries) ->
var sumOfBox = 0
entries.entries.forEachIndexed { index, entry ->
sumOfBox += (boxNumber + 1) * (index + 1) * entry.value
}
sumOfBox
}
}
private fun addEntry(
boxes: MutableMap<Int, MutableMap<String, Int>>,
boxNumber: Int,
label: String,
focalLength: String
) {
boxes.compute(boxNumber) { _, entries ->
entries?.also { it[label] = focalLength.toInt() }
?: mutableMapOf(label to focalLength.toInt())
}
}
private fun hash(s: String): Int {
return s.fold(0) { acc, c ->
var newAcc = acc + c.code
newAcc *= 17
newAcc %= 256
newAcc
}
}
}
| 0 | Kotlin | 1 | 0 | dbd25877071cbb015f8da161afb30cf1968249a8 | 2,218 | aoc | Apache License 2.0 |
2023/2/solve-2.kts | gugod | 48,180,404 | false | {"Raku": 170466, "Perl": 121272, "Kotlin": 58674, "Rust": 3189, "C": 2934, "Zig": 850, "Clojure": 734, "Janet": 703, "Go": 595} | import kotlin.text.Regex
import java.io.File
data class Round(
val reds: Int = 0,
val greens: Int = 0,
val blues: Int = 0,
)
data class Game(
val id: Int,
val rounds: List<Round>,
)
val games = File("input").readLines().map { line ->
val matchedGameId = Regex("Game ([0-9]+):").matchAt(line, 0)!!
val gameId = matchedGameId.groups[1]!!.value.toInt()
val rounds = Regex("; ")
.split(line.substring(matchedGameId.range.endInclusive + 2))
.map {
var colors = mutableMapOf<String,Int>()
Regex("([0-9]+) (red|green|blue),?").findAll(it).forEach {
val n = it.groups[1]!!.value.toInt()
val color = it.groups[2]!!.value.toString()
colors.put(color, n)
}
Round(
reds = colors.getOrDefault("red", 0),
greens = colors.getOrDefault("green", 0),
blues = colors.getOrDefault("blue", 0),
)
}
Game(
id = gameId,
rounds = rounds
)
}
val ans = games.map { game ->
game.rounds.map { it.reds }.max() * game.rounds.map { it.greens }.max() * game.rounds.map { it.blues }.max()
}.sum()
println(ans)
| 0 | Raku | 1 | 5 | ca0555efc60176938a857990b4d95a298e32f48a | 1,222 | advent-of-code | Creative Commons Zero v1.0 Universal |
src/main/kotlin/endredeak/aoc2022/Day05.kt | edeak | 571,891,076 | false | {"Kotlin": 44975} | package endredeak.aoc2022
fun main() {
solve("Supply Stacks") {
val regex = Regex("move (\\d+) from (\\d+) to (\\d+)")
data class Move(val size: Int, val from: Int, val to: Int)
fun input() = run {
val stackLines = lines.filter { it.contains("[") }
val ops = lines.filter { it.contains("move") }
val stacks = mutableMapOf<Int, MutableList<Char>>()
stackLines
.forEach {
it.chunked(4)
.mapIndexed { i, r -> i to r }
.filterNot { (_, r) -> r.isBlank() }
.forEach { (i, r) -> stacks[i + 1]?.add(r[1]) ?: run { stacks[i + 1] = mutableListOf(r[1]) } }
}
val moves = ops
.map {
regex.find(it)!!
.destructured
.let { (s, f, t) -> Move(s.toInt(), f.toInt(), t.toInt()) }
}
stacks.map { (k, v) -> k to v.reversed().toMutableList() }.toMap().toMutableMap() to moves
}
fun runMoving(reversed: Boolean) =
input()
.let { (stacks, moves) ->
moves.forEach { (s, f, t) ->
val toMove = stacks[f]!!.takeLast(s).let { if (reversed) it.reversed() else it }
val remaining = stacks[f]!!.dropLast(s)
val new = stacks[t]!!.apply { addAll(toMove) }
stacks[f] = remaining.toMutableList()
stacks[t] = new.toMutableList()
}
stacks
}
.toSortedMap()
.map { it.value.last() }
.joinToString("")
part1("GRTSWNJHH") { runMoving(true) }
part2("QLFQDBBHM") { runMoving(false) }
}
} | 0 | Kotlin | 0 | 0 | e0b95e35c98b15d2b479b28f8548d8c8ac457e3a | 1,888 | AdventOfCode2022 | Do What The F*ck You Want To Public License |
app/src/main/java/pt/eandrade/leetcodedaily/problems/LowestCommonAncestorBinarySearchTree.kt | eandrade-dev | 513,632,885 | false | {"Kotlin": 27612} | package pt.eandrade.leetcodedaily.problems
import pt.eandrade.leetcodedaily.misc.IsProblem
import pt.eandrade.leetcodedaily.misc.Utils.Companion.TreeNode
import pt.eandrade.leetcodedaily.misc.Utils.Companion.printTree
class LowestCommonAncestorBinarySearchTree : IsProblem {
override fun run() : String {
val root: TreeNode
val p: TreeNode
val q: TreeNode
when((1..3).random()){
1 -> {
root = TreeNode(6,
TreeNode(2, TreeNode(0), TreeNode(4, TreeNode(3), TreeNode(5))),
TreeNode(8, TreeNode(7), TreeNode(9)))
p = TreeNode(2)
q = TreeNode(8)
}
2 -> {
root = TreeNode(6,
TreeNode(2, TreeNode(0), TreeNode(4, TreeNode(3), TreeNode(5))),
TreeNode(8, TreeNode(7), TreeNode(9)))
p = TreeNode(2)
q = TreeNode(4)
}
3 -> {
root = TreeNode(2, TreeNode(1))
p = TreeNode(2)
q = TreeNode(1)
}
else -> {
root = TreeNode(2, TreeNode(1), null)
p = TreeNode(2)
q = TreeNode(1)
}
}
var resultStr = "Tree: ${printTree(root)}"
resultStr += "\np: ${p.`val`}, q: ${q.`val`}"
val result = lowestCommonAncestor(root, p, q)
resultStr += "\nResult: ${result?.`val`}"
return resultStr
}
private fun lowestCommonAncestor(root: TreeNode?, p: TreeNode?, q: TreeNode?): TreeNode? {
if(root == null){
return null
}
val pval = p?.`val` ?: Int.MAX_VALUE
val qval = q?.`val` ?: Int.MAX_VALUE
if(pval > qval) {
return lowestCommonAncestor(root, q, p)
}
if(root.`val` in pval..qval){
return root
}
return if(root.`val` < pval && root.`val` < qval){
lowestCommonAncestor(root.right, p, q)
} else{
lowestCommonAncestor(root.left, p, q)
}
}
} | 0 | Kotlin | 0 | 0 | a60190869baf120db377359de89a15531e77749c | 2,124 | leetcode-daily | Apache License 2.0 |
leetcode/src/offer/Offer42.kt | zhangweizhe | 387,808,774 | false | null | package offer
fun main() {
// https://leetcode-cn.com/problems/lian-xu-zi-shu-zu-de-zui-da-he-lcof/
// 剑指 Offer 42. 连续子数组的最大和
println(maxSubArray2(intArrayOf(1,2,3,-2,3,4)))
}
private fun maxSubArray(nums: IntArray): Int {
val tmp = IntArray(nums.size)
tmp[0] = nums[0]
var max = nums[0]
for (i in 1 until nums.size) {
val t = tmp[i-1] + nums[i]
tmp[i] = Math.max(t, nums[i])
max = Math.max(tmp[i], max)
}
return max
}
private fun maxSubArray1(nums: IntArray): Int {
var pre = nums[0]
var max = nums[0]
var index = 1
while (index < nums.size) {
val i = nums[index]
if (pre < 0) {
pre = i;
}else {
pre += i;
}
// pre = Math.max(i, pre + i)
max = Math.max(max, pre)
index++
}
return max
}
private fun maxSubArray2(nums: IntArray): Int {
var pre = nums[0]
var max = nums[0]
for (i in 1 until nums.size) {
if (pre < 0) {
// 前面的和是负数,负增益,直接取当前的数
pre = nums[i]
}else {
// 前面的最大和是非负数,累加到当前这个数上
pre += nums[i]
}
max = Math.max(pre, max)
}
return max
} | 0 | Kotlin | 0 | 0 | 1d213b6162dd8b065d6ca06ac961c7873c65bcdc | 1,318 | kotlin-study | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/SortVowels.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 dev.shtanko.algorithms.extensions.isVowel
/**
* 2785. Sort Vowels in a String
* @see <a href="https://leetcode.com/problems/sort-vowels-in-a-string">Source</a>
*/
fun interface SortVowels {
operator fun invoke(s: String): String
}
sealed interface SortVowelsStrategy {
/**
* Approach 1: Sorting
*/
data object Sorting : SortVowels, SortVowelsStrategy {
override fun invoke(s: String): String {
val temp = ArrayList<Char>()
// Store the vowels in the temporary string.
for (c in s.toCharArray()) {
if (c.isVowel()) {
temp.add(c)
}
}
// Sort the temporary string characters in ascending order.
temp.sort()
val ans = StringBuilder()
var j = 0
for (i in s.indices) {
// If the character is a vowel, replace it with the character in the string temp.
if (s[i].isVowel()) {
ans.append(temp[j])
j++
} else {
ans.append(s[i])
}
}
return ans.toString()
}
}
/**
* Approach 2: Counting Sort
*/
data object CountingSort : SortVowels, SortVowelsStrategy {
override fun invoke(s: String): String {
val count = IntArray(LIMIT)
// Store the frequencies for each character.
for (c in s.toCharArray()) {
if (c.isVowel()) {
count[c.code - 'A'.code]++
}
}
// Sorted string having all the vowels.
val sortedVowel = "AEIOUaeiou"
val ans = java.lang.StringBuilder()
var j = 0
for (i in s.indices) {
if (!s[i].isVowel()) {
ans.append(s[i])
} else {
// Skip to the character which is having remaining count.
while (count[sortedVowel[j].code - 'A'.code] == 0) {
j++
}
ans.append(sortedVowel[j])
count[sortedVowel[j].code - 'A'.code]--
}
}
return ans.toString()
}
}
companion object {
private const val LIMIT = 1000
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 3,035 | kotlab | Apache License 2.0 |
src/Day01.kt | hrach | 572,585,537 | false | {"Kotlin": 32838} | fun main() {
fun part1(input: List<String>): Int {
val groups = mutableListOf<List<Int>>()
var group = mutableListOf<Int>()
input.forEach {
if (it.isBlank()) group = mutableListOf<Int>().also { groups.add(it) }
else group.add(it.toInt())
}
return groups.maxOf { it.sum() }
}
fun part2(input: List<String>): Int {
val groups = mutableListOf<List<Int>>()
var group = mutableListOf<Int>()
input.forEach {
if (it.isBlank()) group = mutableListOf<Int>().also { groups.add(it) }
else group.add(it.toInt())
}
return groups.map { it.sum() }.sortedDescending().take(3).sum()
}
val testInput = readInput("Day01_test")
check(part1(testInput), 24000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 40b341a527060c23ff44ebfe9a7e5443f76eadf3 | 760 | aoc-2022 | Apache License 2.0 |
src/Day03.kt | eo | 574,058,285 | false | {"Kotlin": 45178} | // https://adventofcode.com/2022/day/3
fun main() {
fun itemPriority(item: Char) = if (item.isLowerCase()) {
item - 'a' + 1
} else {
item - 'A' + 27
}
fun part1(input: List<String>): Int {
return input
.map { it.chunked(it.length / 2).map(String::toSet) }
.map { (items1, items2) -> (items1 intersect items2).single() }
.sumOf(::itemPriority)
}
fun part2(input: List<String>): Int {
return input
.chunked(3)
.map { rucksack ->
rucksack
.map(String::toSet)
.reduce { acc, items -> acc intersect items }
.single()
}
.sumOf(::itemPriority)
}
val input = readLines("Input03")
println("Part 1: " + part1(input))
println("Part 2: " + part2(input))
}
| 0 | Kotlin | 0 | 0 | 8661e4c380b45c19e6ecd590d657c9c396f72a05 | 880 | aoc-2022-in-kotlin | Apache License 2.0 |
advent-of-code-2020/src/main/kotlin/eu/janvdb/aoc2020/day20/Day20.kt | janvdbergh | 318,992,922 | false | {"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335} | package eu.janvdb.aoc2020.day20
import eu.janvdb.aocutil.kotlin.readGroupedLines
val MONSTER = Picture(
listOf(
" # ",
"# ## ## ###",
" # # # # # # "
)
)
fun main() {
val tiles = readGroupedLines(2020, "input20.txt").map(::MapTile)
val topLeftCorner = getTopLeftCorner(tiles)
val fullPicture = buildPictureFromCornerDown(tiles, topLeftCorner)
val occurrences = fullPicture.findImageOccurrences(MONSTER)
val pictureWithoutMonsters = occurrences.fold(fullPicture) { picture, occurrence ->
picture.removeImageOccurrence(occurrence.first, occurrence.second)
}
println(pictureWithoutMonsters.numberOfPixelsSet())
}
private fun getTopLeftCorner(tiles: List<MapTile>): MapTile {
// Corners only attach to two other tiles.
// This means that of their eight border checksums, four will not be found in other tiles
val borderValues = tiles.flatMap { it.borderValues }
val borderValuesOccurringOnce = borderValues.groupBy { it }.filterValues { it.size == 1 }.map { it.key }.toSet()
val corners = tiles.filter { borderValuesOccurringOnce.intersect(it.borderValues).size == 4 }
// Result of part 1: multiply id of corners
val cornerProduct = corners.fold(1L) { temp, corner -> temp * corner.id }
println(cornerProduct)
// Take the first corner and orient it so that its top and left edge don't match any other
return corners[0].getAllTransformations()
.first { it.borderLeft in borderValuesOccurringOnce && it.borderTop in borderValuesOccurringOnce }
}
private fun buildPictureFromCornerDown(allTiles: List<MapTile>, topLeft: MapTile): Picture {
fun findTileMatchingRight(tileToMatch: MapTile): MapTile? {
val tile = allTiles.filter { it.id != tileToMatch.id }.singleOrNull { tileToMatch.borderRight in it.borderValues }
?: return null
return tile.getAllTransformations().single { it.borderLeftFlipped == tileToMatch.borderRight }
}
fun getTileMatchingBottom(tileToMatch: MapTile): MapTile? {
val tile = allTiles.filter { it.id != tileToMatch.id }.singleOrNull { tileToMatch.borderBottom in it.borderValues }
?: return null
return tile.getAllTransformations().single { it.borderTopFlipped == tileToMatch.borderBottom }
}
val tilesOrdered = mutableListOf<MutableList<MapTile>>()
var currentLeft: MapTile? = topLeft
while (currentLeft != null) {
val currentLine = mutableListOf(currentLeft)
tilesOrdered.add(currentLine)
var current = findTileMatchingRight(currentLeft)
while (current != null) {
currentLine.add(current)
current = findTileMatchingRight(current)
}
currentLeft = getTileMatchingBottom(currentLeft)
}
return tilesOrdered.combine()
} | 0 | Java | 0 | 0 | 78ce266dbc41d1821342edca484768167f261752 | 2,650 | advent-of-code | Apache License 2.0 |
src/main/kotlin/day7.kt | gautemo | 572,204,209 | false | {"Kotlin": 78294} | import shared.getText
fun main() {
val input = getText("day7.txt")
println(day7A(input))
println(day7B(input))
}
fun day7A(input: String): Int {
val rootDir = getRootDir(input)
return rootDir.allDirs().sumOf {
if(it.getSize() <= 100000) it.getSize() else 0
}
}
fun day7B(input: String): Int {
val rootDir = getRootDir(input)
val unusedSpace = 70000000 - rootDir.getSize()
val toDelete = 30000000 - unusedSpace
return rootDir.allDirs().minOf {
if(it.getSize() > toDelete) it.getSize() else Int.MAX_VALUE
}
}
private fun getRootDir(input: String): Dir {
val rootDir = Dir("/", null)
var currentDir = rootDir
input.lines().forEach {
when {
it == "$ cd /" -> currentDir = rootDir
it.contains("dir") -> {
currentDir.dirs.add(Dir(it.split(" ")[1], currentDir))
}
it =="$ cd .." -> {
currentDir = currentDir.parent ?: throw Exception("too far out")
}
Regex("""\$ cd .+""").matches(it) -> {
currentDir = currentDir.dirs.find { dir -> dir.name == it.split(" ")[2] } ?: throw Exception("dir not found")
}
Regex("""\d+ .+""").matches(it) -> {
currentDir.files.add(it.split(" ")[0].toInt())
}
}
}
return rootDir
}
private class Dir(val name: String, val parent: Dir?, val files: MutableList<Int> = mutableListOf(), val dirs: MutableList<Dir> = mutableListOf()) {
fun getSize(): Int {
return files.sum() + dirs.sumOf { it.getSize() }
}
fun allDirs(): List<Dir> {
return listOf(this) + dirs.flatMap { it.allDirs() }
}
} | 0 | Kotlin | 0 | 0 | bce9feec3923a1bac1843a6e34598c7b81679726 | 1,712 | AdventOfCode2022 | MIT License |
src/main/kotlin/me/consuegra/algorithms/KSymmetricBinaryTree.kt | aconsuegra | 91,884,046 | false | {"Java": 113554, "Kotlin": 79568} | package me.consuegra.algorithms
import me.consuegra.datastructure.KBinaryTreeNode
/**
* Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
* Example :
*
* 1
* / \
* 2 2
* / \ / \
* 3 4 4 3
*
* The above binary tree is symmetric.
* But the following is not:
*
* 1
* / \
* 2 2
* \ \
* 3 3
*
*/
class KSymmetricBinaryTree {
fun isSymmetric(treeNode: KBinaryTreeNode<Int>): Boolean {
val preOrder = preOrder(treeNode)
val postOrder = postOrder(treeNode)
if (preOrder.length != postOrder.length) {
return false
}
var j = postOrder.length - 1
for (c in preOrder) {
if (c != postOrder[j]) {
return false
}
j--
}
return true
}
private fun preOrder(treeNode: KBinaryTreeNode<Int>?): String = preOrder(treeNode, StringBuilder()).toString()
private fun preOrder(treeNode: KBinaryTreeNode<Int>?, acc: StringBuilder): StringBuilder {
treeNode?.let {
acc.append(treeNode.data)
preOrder(treeNode.left, acc)
preOrder(treeNode.right, acc)
}
return acc
}
private fun postOrder(treeNode: KBinaryTreeNode<Int>?): String = postOrder(treeNode, StringBuilder()).toString()
private fun postOrder(treeNode: KBinaryTreeNode<Int>?, acc: StringBuilder): StringBuilder {
treeNode?.let {
postOrder(treeNode.left, acc)
postOrder(treeNode.right, acc)
acc.append(treeNode.data)
}
return acc
}
}
| 0 | Java | 0 | 7 | 7be2cbb64fe52c9990b209cae21859e54f16171b | 1,649 | algorithms-playground | MIT License |
src/Day14/Day14.kt | AllePilli | 572,859,920 | false | {"Kotlin": 47397} | package Day14
import TerminalUtils
import checkAndPrint
import measureAndPrintTimeMillis
import minMaxRange
import readInput
import kotlin.math.max
import kotlin.math.min
fun main() {
val showAnimationInTerminal = false
val startPosition = 500 to 0
fun List<String>.prepareInput() = flatMap { line ->
line.split(" -> ")
.map { pair ->
pair.split(",")
.let { (first, second) ->
first.toInt() to second.toInt()
}
}
.zipWithNext { first, second ->
buildList {
if (first.first == second.first) {
for (y in min(first.second, second.second)..max(first.second, second.second)) {
add(first.first to y)
}
} else {
for (x in min(first.first, second.first)..max(first.first, second.first)) {
add(x to first.second)
}
}
}
}
.flatten()
}.toSet()
fun part1(input: Set<Pair<Int, Int>>): Int {
val sandAtRest: MutableList<Pair<Int, Int>> = mutableListOf()
var currSand = startPosition.copy()
val maxRocksY = input.maxOf { (_, y) -> y }
fun positionFree(position: Pair<Int, Int>): Boolean = position !in input && position !in sandAtRest
while (true) {
val down = currSand.copy(second = currSand.second + 1)
if (positionFree(down)) {
if (down.second > maxRocksY) break
currSand = down
continue
}
val diagLeft = down.copy(first = down.first - 1)
if (positionFree(diagLeft)) {
currSand = diagLeft
continue
}
val diagRight = down.copy(first = down.first + 1)
if (positionFree(diagRight)) {
currSand = diagRight
continue
}
sandAtRest += currSand.copy()
currSand = startPosition.copy()
}
return sandAtRest.size
}
fun part2(input: Set<Pair<Int, Int>>): Int {
val xMap = hashMapOf<Int, MutableList<Pair<Int, Int>>>()
val yMap = hashMapOf<Int, MutableList<Pair<Int, Int>>>()
input.forEach { position ->
xMap.computeIfAbsent(position.first) { mutableListOf() }
.add(position)
yMap.computeIfAbsent(position.second) { mutableListOf() }
.add(position)
}
val sandAtRest: MutableList<Pair<Int, Int>> = mutableListOf()
var currSand = startPosition.copy()
val maxRocksY = input.maxOf { (_, y) -> y }
val rocksXRange = input.minMaxRange { (x, _) -> x }
val floor = ((rocksXRange.first - maxRocksY / 2)..(rocksXRange.last + maxRocksY / 2))
.map { floorX -> floorX to (maxRocksY + 2) }
.toMutableList()
fun positionFree(position: Pair<Int, Int>): Boolean =
position.second < maxRocksY + 2 && position !in input && position !in sandAtRest
if (showAnimationInTerminal) TerminalUtils.hideTerminalCursor()
while (sandAtRest.lastOrNull() != startPosition) {
if (showAnimationInTerminal) {
TerminalUtils.clearTerminal()
for (x in 0..11) {
for (y in 488..512) {
when (y to x) {
in sandAtRest -> print("o")
in input, in floor -> print("#")
currSand -> print("+")
else -> print(".")
}
}
println()
}
Thread.sleep(500)
}
// Try to go down
val newY = xMap.getOrPut(currSand.first) { mutableListOf(currSand) }
.minOfOrNull { it.second }
?.let { it - 1 }
?: (maxRocksY + 1)
currSand = currSand.copy(second = newY)
val diagLeft = currSand.first - 1 to newY
if (positionFree(diagLeft)) {
currSand = diagLeft
continue
}
val diagRight = currSand.first + 1 to newY
if (positionFree(diagRight)) {
currSand = diagRight
continue
}
sandAtRest += currSand.copy()
xMap.computeIfAbsent(currSand.first) { mutableListOf() }
.add(currSand)
yMap.computeIfAbsent(currSand.second) { mutableListOf() }
.add(currSand)
currSand = startPosition.copy()
}
if (showAnimationInTerminal) TerminalUtils.restoreTerminalCursor()
return sandAtRest.size
}
val testInput = readInput("Day14_test").prepareInput()
check(part1(testInput) == 24)
check(part2(testInput) == 93)
val input = readInput("Day14").prepareInput()
measureAndPrintTimeMillis {
checkAndPrint(part1(input), 964)
}
measureAndPrintTimeMillis {
checkAndPrint(part2(input), 32041)
}
} | 0 | Kotlin | 0 | 0 | 614d0ca9cc925cf1f6cfba21bf7dc80ba24e6643 | 5,282 | AdventOfCode2022 | Apache License 2.0 |
y2016/src/main/kotlin/adventofcode/y2016/Day07.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2016
import adventofcode.io.AdventSolution
object Day07 : AdventSolution(2016, 7, "Internet Protocol Version 7") {
override fun solvePartOne(input: String) = input.lineSequence().count(::isValidTLS).toString()
override fun solvePartTwo(input: String) = input.lineSequence().count(::isValidSSL).toString()
private fun isValidTLS(s: String): Boolean = splitHypernet(s).let { (main, hypernet) ->
main.any { containsAbba(it.value) }
&& hypernet.none { containsAbba(it.value) }
}
private fun isValidSSL(s: String): Boolean = splitHypernet(s).let { (main, hypernet) ->
val babs = main.flatMap { getAbas(it.value) }
val abas = hypernet.flatMap { getAbas(it.value) }
return babs.any { bab ->
abas.any { aba ->
bab[0] == aba[1] && aba[0] == bab[1]
}
}
}
private fun splitHypernet(s: String): Pair<List<IndexedValue<String>>, List<IndexedValue<String>>> {
return s.split('[', ']')
.withIndex()
.partition { it.index % 2 == 0 }
}
private fun containsAbba(s: String): Boolean = s
.windowed(4)
.any { it[0] == it[3] && it[1] == it[2] && it[0] != it[1] }
private fun getAbas(s: String): List<String> = s
.windowed(3)
.filter { it[0] == it[2] && it[0] != it[1] }
} | 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 1,238 | advent-of-code | MIT License |
kotlin/problems/src/solution/DFSPrograms.kt | lunabox | 86,097,633 | false | {"Kotlin": 146671, "Python": 38767, "JavaScript": 19188, "Java": 13966} | package solution
import com.sun.org.apache.xpath.internal.operations.Bool
class DFSPrograms {
/**
* https://leetcode-cn.com/problems/number-of-islands/
*/
fun numIslands(grid: Array<CharArray>): Int {
var ans = 0
grid.forEachIndexed { i, chars ->
chars.forEachIndexed { j, c ->
if (c == '1') {
ans++
dfsIslands(grid, i, j)
}
}
}
return ans
}
private fun dfsIslands(grid: Array<CharArray>, x: Int, y: Int) {
if (x < 0 || y < 0 || x >= grid.size || y >= grid[0].size || grid[x][y] == '0') {
return
}
grid[x][y] = '0'
dfsIslands(grid, x + 1, y)
dfsIslands(grid, x - 1, y)
dfsIslands(grid, x, y + 1)
dfsIslands(grid, x, y - 1)
}
/**
* https://leetcode-cn.com/problems/partition-equal-subset-sum/
*/
fun canPartition(nums: IntArray): Boolean {
val sum = nums.sum()
if (sum % 2 == 1) {
return false
}
val half = sum / 2
nums.sortDescending()
if (nums[0] > half) {
return false
}
return partitionDfs(nums, 0, half)
}
private fun partitionDfs(nums: IntArray, index: Int, sum: Int): Boolean {
if (sum == 0) {
return true
}
if (sum < 0) {
return false
}
for (i in index until nums.size) {
if (partitionDfs(nums, i + 1, sum - nums[i])) {
return true
}
}
return false
}
} | 0 | Kotlin | 0 | 0 | cbb2e3ad8f2d05d7cc54a865265561a0e391a9b9 | 1,628 | leetcode | Apache License 2.0 |
src/main/kotlin/com/groundsfam/advent/y2023/d16/Day16.kt | agrounds | 573,140,808 | false | {"Kotlin": 281620, "Shell": 742} | package com.groundsfam.advent.y2023.d16
import com.groundsfam.advent.DATAPATH
import com.groundsfam.advent.Direction
import com.groundsfam.advent.Direction.DOWN
import com.groundsfam.advent.Direction.LEFT
import com.groundsfam.advent.Direction.RIGHT
import com.groundsfam.advent.Direction.UP
import com.groundsfam.advent.grids.Grid
import com.groundsfam.advent.grids.containsPoint
import com.groundsfam.advent.grids.count
import com.groundsfam.advent.grids.readGrid
import com.groundsfam.advent.points.Point
import com.groundsfam.advent.points.go
import com.groundsfam.advent.timed
import kotlin.io.path.div
private data class LightBeam(val position: Point, val direction: Direction)
private fun nextDirections(tile: Char, direction: Direction): List<Direction> =
when (tile) {
'.' -> listOf(direction)
'/' ->
when (direction) {
UP -> listOf(RIGHT)
RIGHT -> listOf(UP)
DOWN -> listOf(LEFT)
LEFT -> listOf(DOWN)
}
'\\' ->
when (direction) {
UP -> listOf(LEFT)
LEFT -> listOf(UP)
DOWN -> listOf(RIGHT)
RIGHT -> listOf(DOWN)
}
'|' ->
if (direction.isHorizontal()) listOf(UP, DOWN)
else listOf(direction)
'-' ->
if (direction.isVertical()) listOf(LEFT, RIGHT)
else listOf(direction)
else -> throw RuntimeException("Invalid tile $tile")
}
private fun findEnergizedTiles(grid: Grid<Char>, start: LightBeam): Int {
val energized: Grid<MutableSet<Direction>> = Grid(grid.numRows, grid.numCols) { mutableSetOf() }
val queue = ArrayDeque<LightBeam>()
queue.add(start)
while (queue.isNotEmpty()) {
var (position, direction) = queue.removeFirst()
while (grid.containsPoint(position) && energized[position].add(direction)) {
val nextDirs = nextDirections(grid[position], direction)
if (nextDirs.size == 1) {
val dir = nextDirs[0]
position = position.go(dir)
direction = dir
} else {
// must be a splitter with two directions
// add opposite direction to same tile because result
// will be the same for either direction
energized[position].add(-direction)
val (dir1, dir2) = nextDirs
position = position.go(dir1)
direction = dir1
queue.add(LightBeam(position.go(dir2), dir2))
}
}
}
return energized.count { it.isNotEmpty() }
}
private fun maximizeEnergizedTiles(grid: Grid<Char>): Int =
listOf(
(0 until grid.numCols).maxOf { x ->
findEnergizedTiles(grid, LightBeam(Point(x, 0), DOWN))
},
(0 until grid.numCols).maxOf { x ->
findEnergizedTiles(grid, LightBeam(Point(x, grid.numRows - 1), UP))
},
(0 until grid.numRows).maxOf { y ->
findEnergizedTiles(grid, LightBeam(Point(0, y), RIGHT))
},
(0 until grid.numRows).maxOf { y ->
findEnergizedTiles(grid, LightBeam(Point(grid.numCols - 1, y), LEFT))
},
).max()
fun main() = timed {
val grid = (DATAPATH / "2023/day16.txt")
.readGrid()
println("Part one: ${findEnergizedTiles(grid, LightBeam(Point(0, 0), RIGHT))}")
println("Part two: ${maximizeEnergizedTiles(grid)}")
}
| 0 | Kotlin | 0 | 1 | c20e339e887b20ae6c209ab8360f24fb8d38bd2c | 3,507 | advent-of-code | MIT License |
src/main/kotlin/day15/RecursivePathfinder.kt | Ostkontentitan | 434,500,914 | false | {"Kotlin": 73563} | package day15
class RecursivePathfinder : Pathfinder {
override fun searchOptimalPath(
map: Array<Array<Int>>
): Int {
val destination = CavePosition(map.lastIndex, map.first().lastIndex, map.last().last())
val start = CavePosition(0, 0, map[0][0])
val bestForPosition: Array<Array<Int?>> = (1..map.size).map {
arrayOfNulls<Int?>(map.size)
}.toTypedArray()
val knownDeadEnds = mutableSetOf<Int>()
val runs = map.size * map.size * map.size
var bestRisk: Int = Integer.MAX_VALUE
var counter = 0
while (counter < runs) {
val better = tryFindBetterPath(
current = start,
destination = destination,
map = map,
bestForPosition = bestForPosition,
visited = emptyList(),
currentRisk = 0,
knownDeadEnds = knownDeadEnds,
bestRisk
)
val newRisk = better?.sumOf { it.risk } ?: Integer.MAX_VALUE
if (newRisk < bestRisk) {
bestRisk = newRisk
println("better way found with risk ${newRisk - start.risk}")
}
counter++
}
return bestRisk - start.risk
}
private tailrec fun tryFindBetterPath(
current: CavePosition,
destination: CavePosition,
map: Array<Array<Int>>,
bestForPosition: Array<Array<Int?>>,
visited: List<CavePosition>,
currentRisk: Int,
knownDeadEnds: MutableSet<Int>,
bestTotalRisk: Int
): List<CavePosition>? {
val updatedVisits = visited + current
val updatedRisk = currentRisk + current.risk
if (current == destination) {
return updatedVisits
}
val visitable = visitablePositionsFrom(current, map).filterNot { candidate ->
isCandidateUnworthy(candidate, updatedVisits, updatedRisk, knownDeadEnds, bestForPosition, bestTotalRisk)
}
if (visitable.isEmpty()) {
knownDeadEnds.add(updatedVisits.hashCode())
return null
}
return tryFindBetterPath(
visitable.random(),
destination,
map,
bestForPosition,
updatedVisits,
updatedRisk,
knownDeadEnds,
bestTotalRisk
)
}
private fun isCandidateUnworthy(
candidate: CavePosition,
visited: List<CavePosition>,
currentRisk: Int,
knownDeadEnds: MutableSet<Int>,
bestForPosition: Array<Array<Int?>>,
bestTotalRisk: Int
): Boolean {
val candidatePathRisk = currentRisk + candidate.risk
if (candidatePathRisk > bestTotalRisk) {
return true
}
val knownBest = bestForPosition[candidate.y][candidate.x]
val hasBetterRouteTo = knownBest != null && candidatePathRisk > knownBest
if (!hasBetterRouteTo) {
bestForPosition[candidate.y][candidate.x] = candidatePathRisk
} else {
return true
}
if (visited.contains(candidate)) {
return true
}
if (visited.count { candidate.inProximityTo(it) } > 1) {
return true
}
if (knownDeadEnds.contains((visited + candidate).hashCode())) {
return true
}
return false
}
fun visitablePositionsFrom(
current: CavePosition,
map: Array<Array<Int>>
): List<CavePosition> {
val x = current.x
val y = current.y
val pool = listOf(
y + 1 to x,
y to x + 1,
y to x - 1,
y - 1 to x
)
return pool.mapNotNull { (y, x) ->
val risk = map.getOrNull(y)?.getOrNull(x)
if (risk == null) {
null
} else {
CavePosition(y, x, risk)
}
}
}
} | 0 | Kotlin | 0 | 0 | e0e5022238747e4b934cac0f6235b92831ca8ac7 | 3,996 | advent-of-kotlin-2021 | Apache License 2.0 |
codeforces/vk2022/round1/f.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package codeforces.vk2022.round1
fun main() {
val (n, qIn) = readInts()
val pOpenClose = qIn / 10_000.toModular()
val one = 1.toModular()
val pCloseOpen = one - pOpenClose
val cnk = List(n + 1) { i -> Array(i + 1) { one } }
for (i in cnk.indices) {
for (j in 1 until i) {
cnk[i][j] = cnk[i - 1][j - 1] + cnk[i - 1][j]
}
}
val fact2 = Array(n + 1) { one }
fun fact2(i: Int) = fact2[i]
for (i in 1..n) {
fact2[i] = ((2 * i - 1) * fact2(i - 1))
}
val pPaired = List(n + 1) { i -> Array(i) { one } }
for (i in 0..n) {
for (k in 0 until i) {
val kk = i - 1 - k
pPaired[i][k] = ((cnk[i][k + 1] * fact2(k) * fact2(kk)) / fact2(i))
}
}
val pAtLeast = List(n + 1) { i -> Array(i) { one } }
fun pAtLeast(i: Int, j: Int): Modular {
if (j >= i) return one
return pAtLeast[i][j]
}
for (i in 0..n) {
for (j in 0 until i) {
if (i + j > n) continue
var pij = 0.toModular()
for (k in 0 until i) {
val kk = i - 1 - k
var pBalance = pAtLeast(k, j + 1) * pOpenClose
if (j >= 1) {
pBalance = (pAtLeast(k, j - 1) * pCloseOpen) + pBalance
}
pij = pPaired[i][k] * pAtLeast(kk, j) * pBalance + pij
}
pAtLeast[i][j] = pij
}
}
println(pAtLeast(n, 0))
}
//private fun Int.toModular() = toDouble(); typealias Modular = Double
private fun Int.toModular() = Modular(this)//toDouble()
private class Modular {
companion object {
const val M = 998244353
}
val x: Int
@Suppress("ConvertSecondaryConstructorToPrimary")
constructor(value: Int) { x = (value % M).let { if (it < 0) it + M else it } }
operator fun plus(that: Modular) = Modular((x + that.x) % M)
operator fun minus(that: Modular) = Modular((x + M - that.x) % M)
operator fun times(that: Modular) = (x.toLong() * that.x % M).toInt().toModular()
private fun modInverse() = Modular(x.toBigInteger().modInverse(M.toBigInteger()).toInt())
operator fun div(that: Modular) = times(that.modInverse())
override fun toString() = x.toString()
}
private operator fun Int.plus(that: Modular) = Modular(this) + that
private operator fun Int.minus(that: Modular) = Modular(this) - that
private operator fun Int.times(that: Modular) = Modular(this) * that
private operator fun Int.div(that: Modular) = Modular(this) / that
private fun readStrings() = readln().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| 0 | Java | 1 | 9 | 30953122834fcaee817fe21fb108a374946f8c7c | 2,347 | competitions | The Unlicense |
src/main/kotlin/com/hj/leetcode/kotlin/problem1406/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem1406
/**
* LeetCode page: [1406. Stone Game III](https://leetcode.com/problems/stone-game-iii/);
*/
class Solution {
/* Complexity:
* Time O(N) and Space O(1) where N is the size of stoneValue;
*/
fun stoneGameIII(stoneValue: IntArray): String {
val (aliceScore, bobScore) = playerScores(stoneValue)
return gameResult(aliceScore, bobScore)
}
private fun playerScores(stoneValue: IntArray): Pair<Int, Int> {
/* (By dynamic programming)
* Define the sub problem as the score of the first player when playing game with
* the suffix arrays of stoneValue.
*
* Only the three most recent sub results are stored, which is sufficient to solve
* the original problem.
*/
val subProblemResults = ArrayDeque<Int>()
/* Add base cases that 0 score for suffix arrays stoneValue[size:], stoneValue[size+1:]
* and stoneValue[size+2:].
*/
subProblemResults.apply {
addLast(0)
addLast(0)
addLast(0)
}
// Solve the sub problem in descending order of the suffix array start index
var suffixSum = 0
for (start in stoneValue.lastIndex downTo 0) {
suffixSum += stoneValue[start]
val currentResult = suffixSum - subProblemResults.min()!!
subProblemResults.addFirst(currentResult)
subProblemResults.removeLast()
}
// Compute and return the play scores
val firstPlayerScore = subProblemResults.first()
val secondPlayerScore = suffixSum - firstPlayerScore
return Pair(firstPlayerScore, secondPlayerScore)
}
private fun gameResult(aliceScore: Int, bobScore: Int): String = when {
aliceScore > bobScore -> "Alice"
aliceScore < bobScore -> "Bob"
else -> "Tie"
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 1,917 | hj-leetcode-kotlin | Apache License 2.0 |
src/Day01/Day01.kt | emillourens | 572,599,575 | false | {"Kotlin": 32933} | fun main() {
fun part1(input: List<String>): Int {
var calories = 0
var counter = 1
var elfWithTheLargestCal = 0
var prevLargest = 0
for (item in input)
{
if(item == "")
{
counter++
calories = 0
continue
}
calories += item.toInt()
if(prevLargest < calories)
{
prevLargest = calories
elfWithTheLargestCal = calories
}
}
return elfWithTheLargestCal
}
fun part2(input: List<String>): Int {
var calories = 0
val total: Int
val num = mutableListOf<Int>()
for (item in input)
{
if(input.last() == item)
{
num.add(item.toInt())
}
if(item == "")
{
num.add(calories)
calories = 0
continue
}
calories += item.toInt()
}
num.sort()
total = num.takeLast(3).sum()
return total
}
// 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 | 1f9739b73ef080b012e505e0a4dfe88f928e893d | 1,412 | AoC2022 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/Allocator.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.TreeMap
/**
* 2502. Design Memory Allocator
* @see <a href="https://leetcode.com/problems/design-memory-allocator">Source</a>
*/
interface Malloc {
fun allocate(size: Int, mID: Int): Int
fun free(mID: Int): Int
}
class Allocator(n: Int) : Malloc {
data class Node(val l: Int, val r: Int)
// certain area of memory is allocated or not
private var a: BooleanArray = BooleanArray(n)
// Track all allocations for each mID
private val mIds: Array<MutableList<Node>?> = arrayOfNulls(LIMIT)
override fun allocate(size: Int, mID: Int): Int {
val l = findFirstAvailable(size)
if (l == -1) return -1
// find the list of memories allocated for this mID
if (mIds[mID] == null) mIds[mID] = ArrayList() // if new, create the empty memList for this mID
mIds[mID]?.add(Node(l, l + size)) // append to memList allocated to this mID
// allocate memory
var i = l
val r = l + size
while (i < r) {
a[i] = true
i++
}
return l
}
override fun free(mID: Int): Int {
var size = 0
// free all memory allocated to this mID
for ((l, r) in mIds[mID] ?: return 0) {
size += r - l
for (i in l until r) a[i] = false // free memory
}
mIds[mID]?.clear() // this mID is gone
return size
}
private fun findFirstAvailable(size: Int): Int {
var i = 0
while (i <= a.size - size) {
var j = i
val r = i + size
while (j < r) {
if (a[j]) {
i = -1
break
} // true is allocated, so can't be used, we go to next section
j++
}
i = if (i == -1) j + 1 else return i
}
return -1
}
companion object {
private const val LIMIT = 1001
}
}
class TAllocator(n: Int) : Malloc {
private val memory: MutableMap<Int, TreeMap<Int, Int>> = HashMap()
private val ranges = TreeMap<Int, Int>()
init {
ranges[0] = n - 1 // address start from 0
memory[0] = ranges // 0 means free block
}
class Range(val start: Int, val end: Int)
override fun allocate(size: Int, mID: Int): Int {
val emptyRange = Range(start = -1, end = -1)
val foundRange = findSuitableMemoryRange(size) ?: emptyRange
if (foundRange.start != -1) {
allocateMemoryRange(mID, size, foundRange)
}
mergeRanges(mID)
return foundRange.start
}
private fun findSuitableMemoryRange(size: Int): Range? {
return memory[0]?.entries?.find { it.value - it.key + 1 >= size }?.let { Range(it.key, it.value) }
}
private fun allocateMemoryRange(mID: Int, size: Int, foundRange: Range) {
memory.computeIfAbsent(mID) { TreeMap() }[foundRange.start] = foundRange.start + size - 1
memory[0]?.remove(foundRange.start)
val remainingSize = foundRange.end - foundRange.start + 1
if (remainingSize > size) {
memory.getOrDefault(0, TreeMap())[foundRange.start + size] = foundRange.end
}
}
override fun free(mID: Int): Int {
var cnt = 0
val freeRanges = memory[mID]
if (freeRanges != null) {
for ((startAdd, endAdd) in freeRanges) {
cnt += endAdd - startAdd + 1
memory.getOrDefault(0, TreeMap())[startAdd] = endAdd
}
}
memory.remove(mID)
mergeRanges(0)
return cnt
}
private fun mergeRanges(mID: Int) {
val curRanges = memory[mID]
val mergedRanges = TreeMap<Int, Int>()
val lastRange = intArrayOf(Int.MIN_VALUE, Int.MIN_VALUE)
if (curRanges != null) {
for ((startAdd, endAdd) in curRanges) {
if (startAdd - 1 == lastRange[1]) {
lastRange[1] = endAdd
} else {
if (lastRange[0] != Int.MIN_VALUE) {
mergedRanges[lastRange[0]] = lastRange[1]
}
lastRange[0] = startAdd
lastRange[1] = endAdd
}
}
}
if (lastRange[0] != Int.MIN_VALUE) {
mergedRanges[lastRange[0]] = lastRange[1]
}
memory[mID] = mergedRanges
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 5,066 | kotlab | Apache License 2.0 |
src/main/kotlin/at/mpichler/aoc/solutions/year2022/Day15.kt | mpichler94 | 656,873,940 | false | {"Kotlin": 196457} | package at.mpichler.aoc.solutions.year2022
import at.mpichler.aoc.lib.Day
import at.mpichler.aoc.lib.Order
import at.mpichler.aoc.lib.PartSolution
import at.mpichler.aoc.lib.Vector2i
import java.lang.IllegalStateException
import kotlin.math.absoluteValue
open class Part15A : PartSolution() {
lateinit var sensors: MutableList<Sensor>
override fun parseInput(text: String) {
sensors = mutableListOf()
val pattern = Regex("Sensor at x=(-?\\d+), y=(-?\\d+): closest beacon is at x=(-?\\d+), y=(-?\\d+)")
for (line in text.trim().split("\n")) {
val result = pattern.find(line)
checkNotNull(result)
val pos = Vector2i(result.groupValues[1].toInt(), result.groupValues[2].toInt())
val beacon = Vector2i(result.groupValues[3].toInt(), result.groupValues[4].toInt())
val distance = (pos - beacon).norm(Order.L1)
sensors.add(Sensor(pos, distance, beacon))
}
}
override fun compute(): Any {
val targetRow = if (sensors.size != 14) 2_000_000 else 10
return coveredTiles(targetRow).size
}
private fun coveredTiles(targetRow: Int): Set<Int> {
val row = mutableSetOf<Int>()
val beacons = mutableSetOf<Int>()
for (sensor in sensors) {
if (sensor.beacon.y == targetRow) {
beacons.add(sensor.beacon.x)
}
val yDistance = (targetRow - sensor.pos.y).absoluteValue
val xDistance = sensor.distance - yDistance
if (xDistance < 0) {
continue
}
val xMin = sensor.pos.x - xDistance
val xMax = sensor.pos.x + xDistance
for (x in xMin..xMax) {
row.add(x)
}
}
for (beacon in beacons) {
row.remove(beacon)
}
return row
}
override fun getExampleAnswer(): Int {
return 26
}
data class Sensor(val pos: Vector2i, val distance: Int, val beacon: Vector2i)
}
class Part15B : Part15A() {
override fun compute(): Long {
val (x, y) = freeTile()
return x * 4_000_000L + y
}
private fun freeTile(): Vector2i {
for (sensor in sensors) {
for (pos in getSensorBorder(sensor)) {
var found = true
for (sensor2 in sensors) {
val distance = (sensor2.pos - pos).norm(Order.L1)
if (distance <= sensor2.distance) {
found = false
break
}
}
if (found) {
return pos
}
}
}
throw IllegalStateException("Should not be reached")
}
/**
* Get border of sensor area, within which no beacon can be
*/
private fun getSensorBorder(sensor: Sensor): Sequence<Vector2i> {
val max = 4_000_000
val beacons = sensors.map { it.beacon }
return sequence {
val topY = sensor.pos.y + sensor.distance - 1
val bottomY = sensor.pos.y - sensor.distance - 1
for (i in 0..<sensor.distance) {
for ((x, y) in listOf(
Vector2i(sensor.pos.x + i, topY - i),
Vector2i(sensor.pos.x - i, topY - i),
Vector2i(sensor.pos.x + i, bottomY + i),
Vector2i(sensor.pos.x - i, bottomY + i)
)) {
if (x < 0 || y < 0 || x > max || y > max || Vector2i(x, y) in beacons) {
continue
}
yield(Vector2i(x, y))
}
}
}
}
override fun getExampleAnswer(): Int {
return 56_000_011
}
}
fun main() {
Day(2022, 15, Part15A(), Part15B())
} | 0 | Kotlin | 0 | 0 | 69a0748ed640cf80301d8d93f25fb23cc367819c | 3,867 | advent-of-code-kotlin | MIT License |
src/Day06.kt | KliminV | 573,758,839 | false | {"Kotlin": 19586} | fun main() {
fun part1(input: String): Int {
return firstOccurrenceNDistinctChars(input, 4)
}
fun part2(input: String): Int {
return firstOccurrenceNDistinctChars(input, 14)
}
// test if implementation meets criteria from the description, like:
val testInput = read("Day06_test")
check(part1(testInput) == 7)
check(part2(testInput) == 19)
val input = read("Day06")
println(part1(input))
println(part2(input))
}
fun firstOccurrenceNDistinctChars(input: String, numOfElements: Int): Int {
val result = input.windowed(numOfElements, 1, false)
.indexOfFirst { sequence ->
val set = mutableSetOf<Char>()
for (i in 0 until numOfElements)
set.add(sequence[i])
set.size == numOfElements
}
return if (result == -1) result else result + numOfElements
}
| 0 | Kotlin | 0 | 0 | 542991741cf37481515900894480304d52a989ae | 880 | AOC-2022-in-kotlin | Apache License 2.0 |
src/Day01.kt | graesj | 572,651,121 | false | {"Kotlin": 10264} | fun main() {
fun part1(input: List<String>): Int {
return input
.map { it.toIntOrNull() }
.runningFold(0) { acc, calories ->
calories?.let {
acc + it
} ?: 0
}.max()
}
fun part2(input: List<String>): Int {
return input
.asSequence()
.map { it.toIntOrNull() }
.runningFold(0) { acc, calories ->
calories?.let {
acc + it
} ?: 0
}.sortedDescending()
.take(3)
.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readLines("Day01_test")
check(part1(testInput) == 24000)
val input = readLines("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | df7f855a14c532f3af7a8dc86bd159e349cf59a6 | 854 | aoc-2022 | Apache License 2.0 |
src/Day05.kt | EdoFanuel | 575,561,680 | false | {"Kotlin": 80963} | import java.util.*
fun main() {
val stacks = Array<Stack<Char>>(9) { Stack() }
stacks[0] += "TDWZVP".toList()
stacks[1] += "LSWVFJD".toList()
stacks[2] += "ZMLSVTBH".toList()
stacks[3] += "RSJ".toList()
stacks[4] += "CZBGFMLW".toList()
stacks[5] += "QVWHZRGB".toList()
stacks[6] += "VJPCBDN".toList()
stacks[7] += "PTBQ".toList()
stacks[8] += "HGZRC".toList()
fun part1(input: List<String>): String {
for (line in input) {
val tokens = line.split(" ")
val count = tokens[1].toInt()
val source = tokens[3].toInt() - 1
val target = tokens[5].toInt() - 1
for (i in 0 until count) {
stacks[target].push(stacks[source].pop())
}
}
return stacks.map { it.peek() }.joinToString("")
}
fun part2(input: List<String>): String {
for (line in input) {
val tokens = line.split(" ")
val count = tokens[1].toInt()
val source = tokens[3].toInt() - 1
val target = tokens[5].toInt() - 1
val move = mutableListOf<Char>()
for (i in 0 until count) {
move += stacks[source].pop()
}
for (c in move.reversed()) {
stacks[target].push(c)
}
}
return stacks.map { it.peek() }.joinToString("")
}
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 46a776181e5c9ade0b5e88aa3c918f29b1659b4c | 1,492 | Advent-Of-Code-2022 | Apache License 2.0 |
src/main/kotlin/year2023/day01/Problem.kt | Ddxcv98 | 573,823,241 | false | {"Kotlin": 154634} | package year2023.day01
import IProblem
import java.util.NoSuchElementException
class Problem : IProblem {
private val map = mapOf(
"1" to 1,
"2" to 2,
"3" to 3,
"4" to 4,
"5" to 5,
"6" to 6,
"7" to 7,
"8" to 8,
"9" to 9,
"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
)
private val lines = javaClass
.getResource("/2023/01.txt")!!
.readText()
.lines()
.filter(String::isNotBlank)
private fun firstMatch(keys: Iterable<String>, s: String): Int {
for (i in s.indices) {
for (key in keys) {
if (s.regionMatches(i, key, 0, key.length)) {
return map[key]!!
}
}
}
throw NoSuchElementException("no key found in $s")
}
private fun lastMatch(keys: Iterable<String>, s: String): Int {
for (i in s.indices.reversed()) {
for (key in keys) {
if (s.regionMatches(i, key, 0, key.length)) {
return map[key]!!
}
}
}
throw NoSuchElementException("no key found in $s")
}
private fun calculate(keys: Iterable<String>): Int {
var sum = 0
for (line in lines) {
val x = firstMatch(keys, line)
val y = lastMatch(keys, line)
sum += x * 10 + y
}
return sum
}
override fun part1(): Int {
val keys = map.keys.filter { it.length == 1 }
return calculate(keys)
}
override fun part2(): Int {
val keys = map.keys
return calculate(keys)
}
}
| 0 | Kotlin | 0 | 0 | 455bc8a69527c6c2f20362945b73bdee496ace41 | 1,816 | advent-of-code | The Unlicense |
src/main/kotlin/days/Day13Data.kt | yigitozgumus | 572,855,908 | false | {"Kotlin": 26037} | package days
import utils.SolutionData
import utils.Utils
fun main() = with(Day13Data()) {
println(" --- Part 1 --- ")
solvePart1()
println(" --- Part 2 --- ")
solvePart2()
}
class Day13Data: SolutionData(inputFile = "inputs/day13.txt") {
val pairs = rawData
.windowed(size = 2, step=3)
.map { (left, right) -> Utils.List.from(left) to Utils.List.from(right) }
}
fun Day13Data.solvePart1() {
pairs.mapIndexed { i, (left, right) -> if (left compareTo right < 0) i + 1 else 0 }.sum().also { println(it) }
}
fun Day13Data.solvePart2() {
val first = Utils.List.from("[[2]]")
val second = Utils.List.from("[[6]]")
val sorted = (pairs.flatMap { it.toList() } + listOf(first, second)).sortedWith(Utils.List::compareTo)
((sorted.indexOf(first) + 1) * (sorted.indexOf(second) + 1)).also { println(it) }
}
| 0 | Kotlin | 0 | 0 | 9a3654b6d1d455aed49d018d9aa02d37c57c8946 | 829 | AdventOfCode2022 | MIT License |
src/main/kotlin/g1001_1100/s1020_number_of_enclaves/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g1001_1100.s1020_number_of_enclaves
// #Medium #Array #Depth_First_Search #Breadth_First_Search #Matrix #Union_Find
// #Graph_Theory_I_Day_3_Matrix_Related_Problems
// #2023_05_21_Time_369_ms_(76.26%)_Space_90.3_MB_(16.91%)
class Solution {
fun numEnclaves(grid: Array<IntArray>): Int {
val visited = Array(grid.size) {
BooleanArray(
grid[0].size
)
}
for (i in grid.indices) {
for (j in grid[0].indices) {
if (grid[i][j] == 1 && (i == 0 || j == 0 || i == grid.size - 1 || j == grid[0].size - 1)) {
move(grid, i, j, visited)
}
}
}
var count = 0
for (i in 1 until visited.size - 1) {
for (j in 1 until visited[0].size - 1) {
if (!visited[i][j] && grid[i][j] == 1) count++
}
}
return count
}
companion object {
fun move(g: Array<IntArray>, i: Int, j: Int, b: Array<BooleanArray>) {
if (i < 0 || j < 0 || i == g.size || j == g[0].size || g[i][j] == 0 || b[i][j]) return
b[i][j] = true
move(g, i + 1, j, b)
move(g, i - 1, j, b)
move(g, i, j - 1, b)
move(g, i, j + 1, b)
}
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,306 | LeetCode-in-Kotlin | MIT License |
src/day4/main.kt | rafagalan | 573,145,902 | false | {"Kotlin": 5674} | package day4
import readInput
fun parseInput(input: String) =
input
.split(",", "-")
.windowed(2, 2) {(lowerBound, upperBound) ->
IntArray(upperBound.toInt() - lowerBound.toInt() + 1) { it + lowerBound.toInt() }.toSet()
}
fun main() {
fun part1(input: List<String>) =
input
.map{
parseInput(it).let {
it.reduce { acc, ints -> ints.union((acc)) } == it.maxBy { it.size }
}
}.count { it }
fun part2(input: List<String>) =
input
.map{
parseInput(it).let {
it.reduce { acc, ints -> ints.intersect((acc)) }.isNotEmpty()
}
}.count{ it }
val testInput = readInput("day4/test_input")
check(part1(testInput) == 2)
val realInput = readInput("day4/input")
println(part1(realInput))
val testInput2 = readInput("day4/test_input")
check(part2(testInput2) == 4)
val realInput2 = readInput("day4/input")
println(part2(realInput2))
} | 0 | Kotlin | 0 | 0 | 8e7d3f25fe52a4153479adb56c5924b50f6c0be9 | 1,071 | AdventOfCode2022 | Apache License 2.0 |
src/Day15_2.kt | jrmacgill | 573,065,109 | false | {"Kotlin": 76362} | import utils.*
class Day15_2 {
val ranges = mutableMapOf<Point, Int>()
fun contained(min : Point, max : Point) : Boolean {
ranges.forEach{
val dist = it.value
if (it.key.manhattanDistanceTo(min) <= dist && it.key.manhattanDistanceTo(max) <=dist && it.key.manhattanDistanceTo(Point(min.x, max.y)) <= dist && it.key.manhattanDistanceTo(Point(max.x, min.y)) <= dist) {
return true
}
}
return false;
}
fun doChunk(min : Point, max : Point) {
if (contained(min, max)) {
} else {
if (min.x == max.x || min.y == max.y) {
} else {
if (min.manhattanDistanceTo(max) < 3) {
for (x in min.x .. max.x) {
for (y in min.y .. max.y) {
if (!contained(Point(x,y),Point(x,y))) {
println("FOUND!!" + Point(x,y))
}
}
}
} else {
var mid = Point((min.x + max.x) / 2, (min.y + max.y) / 2)
doChunk(Point(min.x, min.y), Point(mid.x, mid.y))
doChunk(Point(mid.x, min.y), Point(max.x, mid.y))
doChunk(Point(min.x, mid.y), Point(mid.x, max.y))
doChunk(Point(mid.x, mid.y), Point(max.x, max.y))
}
}
}
}
fun go() {
// var size = 20
// var lines =readInput("day15_test")
var lines =readInput("day15")
val size = 4000000
val data = mutableListOf<List<Int>>()
val sensors = mutableMapOf<Point, Point>()
println("sizing")
lines.forEach{
var values = it.extractAllIntegers()
data.add(values)
var s = Point(values[0], values[1])
var b = Point(values[2], values[3])
sensors[s] = b
ranges[s] = s.manhattanDistanceTo(b)
}
doChunk(Point(0,0), Point(size,size))
}
}
fun main() {
Day15_2().go()
} | 0 | Kotlin | 0 | 1 | 3dcd590f971b6e9c064b444139d6442df034355b | 2,135 | aoc-2022-kotlin | Apache License 2.0 |
Kotlin for Java Developers. Week 4/Rationals/Task/src/rationals/Rational.kt | binout | 159,054,839 | false | null | package rationals
import java.math.BigInteger
class Rational(private val numerator: BigInteger,
private val denominator: BigInteger = BigInteger.ONE)
: Comparable<Rational> {
init {
require(denominator != BigInteger.ZERO)
}
operator fun unaryMinus(): Rational = Rational(-numerator, denominator)
operator fun minus(other: Rational): Rational = Rational(
numerator * other.denominator - other.numerator * denominator,
denominator * other.denominator)
operator fun plus(other: Rational): Rational = Rational(
numerator * other.denominator + other.numerator * denominator,
denominator * other.denominator)
operator fun times(other: Rational): Rational = Rational(
numerator * other.numerator,
denominator * other.denominator)
operator fun div(other: Rational): Rational = times(other.inv())
override fun compareTo(other: Rational): Int =
(numerator * other.denominator).compareTo(other.numerator * denominator)
fun inv(): Rational = Rational(denominator, numerator)
fun opposite(): Rational = Rational(-numerator, - denominator)
fun normalize(): Rational {
val gcd = this.numerator.gcd(this.denominator)
if (this.denominator < BigInteger.ZERO) {
return Rational(this.numerator / gcd, this.denominator / gcd).opposite()
} else {
return Rational(this.numerator / gcd, this.denominator / gcd)
}
}
override fun equals(other: Any?): Boolean {
if (other !is Rational) {
return false
} else {
val normalize = this.normalize()
val otherNormalize = other.normalize()
return normalize.numerator == otherNormalize.numerator
&& normalize.denominator == otherNormalize.denominator
}
}
override fun toString(): String {
val normalize = this.normalize()
if (normalize.denominator == BigInteger.ONE) {
return normalize.numerator.toString()
}
return "${normalize.numerator}/${normalize.denominator}"
}
}
infix fun BigInteger.divBy(other: BigInteger): Rational = Rational(this, other)
infix fun Int.divBy(other: Int): Rational = Rational(this.toBigInteger(), other.toBigInteger())
infix fun Long.divBy(other: Long): Rational = Rational(this.toBigInteger(), other.toBigInteger())
fun String.toRational(): Rational {
if (this.contains("/")) {
val splitted = this.split("/", limit = 2)
return splitted[0].toBigInteger() divBy splitted[1].toBigInteger()
} else {
return Rational(this.toBigInteger())
}
}
fun main(args: Array<String>) {
val r1 = 1 divBy 2
val r2 = 2000000000L divBy 4000000000L
println(r1 == r2)
println((2 divBy 1).toString() == "2")
println((-2 divBy 4).toString() == "-1/2")
println("117/1098".toRational().toString() == "13/122")
println("1/2".toRational() - "1/3".toRational() == "1/6".toRational())
println("1/2".toRational() + "1/3".toRational() == "5/6".toRational())
println(-(1 divBy 2) == (-1 divBy 2))
println((1 divBy 2) * (1 divBy 3) == "1/6".toRational())
println((1 divBy 2) / (1 divBy 4) == "2".toRational())
println((1 divBy 2) < (2 divBy 3))
println((1 divBy 2) in (1 divBy 3)..(2 divBy 3))
println("912016490186296920119201192141970416029".toBigInteger() divBy
"1824032980372593840238402384283940832058".toBigInteger() == 1 divBy 2)
}
| 0 | Kotlin | 1 | 5 | 40ff182f63d29443fa3c29730560d37e2325501a | 3,540 | coursera-kotlin | Apache License 2.0 |
src/main/kotlin/dec6/Main.kt | dladukedev | 318,188,745 | false | null | package dec6
fun chunkInput(input: String): List<String> {
return input.split(Regex("\\n\\n"))
}
fun getCharactersFromChunk(chunk: String): List<List<Char>> {
return chunk.lines()
.map { it.trim() }
.map { it.toCharArray().toTypedArray().toList() }
.filter { it.isNotEmpty() }
}
fun getCharactersInAllPartsOfChunk(charList: List<List<Char>>): List<Char> {
if(charList.isEmpty()) return emptyList()
return charList[0].filter { searchChar ->
charList.all {
it.contains(searchChar)
}
}
}
fun getUniqueCharactersFromChunk(chunk: String): List<Char> {
return getCharactersFromChunk(chunk)
.flatten()
.filter { it.toString().matches(Regex("[a-z]")) }
.distinct()
}
fun getTotalCharacterCountForInput(input: String): Int {
return chunkInput(input)
.map { getUniqueCharactersFromChunk(it) }
.map { it.count() }
.sum()
}
fun getCharacterCountInAllGroups(input: String): Int {
return chunkInput(input)
.map { getCharactersFromChunk(it) }
.map { getCharactersInAllPartsOfChunk(it) }
.map { it.count() }
.sum()
}
fun main() {
println("------------ PART 1 ------------")
val result = getTotalCharacterCountForInput(input)
println("result: $result")
println("------------ PART 2 ------------")
val result2 = getCharacterCountInAllGroups(input)
println("result: $result2")
} | 0 | Kotlin | 0 | 0 | d4591312ddd1586dec6acecd285ac311db176f45 | 1,457 | advent-of-code-2020 | MIT License |
solutions/aockt/y2015/Y2015D19.kt | Jadarma | 624,153,848 | false | {"Kotlin": 435090} | package aockt.y2015
import io.github.jadarma.aockt.core.Solution
object Y2015D19 : Solution {
/** Returns all the possible transformations the machine can do. */
private fun parseInput(input: List<String>): List<Pair<String, String>> =
input.dropLast(2).map {
val (first, second) = it.split(" => ")
first to second
}
override fun partOne(input: String): Int {
val lines = input.lines()
val molecule = lines.last()
return parseInput(lines)
.flatMap { (original, transformed) ->
Regex(original)
.findAll(molecule)
.map { molecule.replaceRange(it.range, transformed) }
.toList()
}
.toSet()
.size
}
override fun partTwo(input: String): Int {
val lines = input.lines()
val molecule = lines.last()
val transformations = parseInput(lines).toMutableList()
var iterations = 0
var target = molecule
while (target != "e") {
val last = target
transformations.forEach { (original, transformed) ->
if (target.contains(transformed)) {
target = target.replaceFirst(transformed, original)
iterations++
}
}
if (last == target) {
transformations.shuffle()
target = molecule
iterations = 0
}
}
return iterations
}
/**
* This is too cool not to show: you can solve this only by using the medicine molecule if you can figure out that
* the transformation rules follow an unambiguous grammar. Unfortunately, it won't pass the test on the trivial
* HOH example since it doesn't use the same grammar, but it works for real input data in linear time! Yay math!
*
* Discovered by Reddit user `/u/askalski`.
* Original explanation: [https://www.reddit.com/r/adventofcode/comments/3xflz8/day_19_solutions/cy4etju].
*/
@Suppress("unused")
private fun partTwoByMagic(input: String): Int {
val molecule = input.lineSequence().last()
val elements = molecule.count { it in 'A'..'Z' }
val parens = molecule.windowed(2).count { it == "Rn" || it == "Ar" }
val commas = molecule.count { it == 'Y' }
return elements - parens - commas * 2 - 1
}
}
| 0 | Kotlin | 0 | 3 | 19773317d665dcb29c84e44fa1b35a6f6122a5fa | 2,466 | advent-of-code-kotlin-solutions | The Unlicense |
kotlin/src/com/daily/algothrim/leetcode/medium/FourSum.kt | idisfkj | 291,855,545 | false | null | package com.daily.algothrim.leetcode.medium
/**
* 18. 四数之和
*/
class FourSum {
companion object {
@JvmStatic
fun main(args: Array<String>) {
FourSum().fourSum(intArrayOf(1, 0, -1, 0, -2, 2), 0).forEach {
it.forEach { i ->
print(i)
}
println()
}
FourSum().fourSum(intArrayOf(2,2,2,2,2), 8).forEach {
it.forEach { i ->
print(i)
}
println()
}
FourSum().fourSum(intArrayOf(0,0,0,1000000000,1000000000,1000000000,1000000000), 1000000000).forEach {
it.forEach { i ->
print(i)
}
println()
}
}
}
fun fourSum(nums: IntArray, target: Int): List<List<Int>> {
val result = arrayListOf<List<Int>>()
val size = nums.size
if (size < 4) return result
nums.sort()
for (i in 0 until size - 3) {
if (i > 0 && nums[i] == nums[i - 1]) continue
if (nums[i].toLong() + nums[i + 1] + nums[i + 2] + nums[i + 3] > target) break
if (nums[i].toLong() + nums[size - 3] + nums[size - 2] + nums[size - 1] < target) continue
for (j in i + 1 until size - 2) {
if (j > i + 1 && nums[j] == nums[j - 1]) continue
if (nums[i].toLong() + nums[j] + nums[j + 1] + nums[j + 2] > target) break
if (nums[i].toLong() + nums[j] + nums[size - 2] + nums[size - 1] < target) continue
var l = j + 1
var r = size - 1
while (l < r) {
val sum = nums[i].toLong() + nums[j] + nums[l] + nums[r]
if (sum == target.toLong()) {
result.add(arrayListOf(nums[i], nums[j], nums[l], nums[r]))
while (l < r && nums[l] == nums[l + 1]) {
l++
}
l++
while (l < r && nums[r] == nums[r - 1]) {
r--
}
r--
} else if (sum < target) {
l++
} else {
r--
}
}
}
}
return result
}
} | 0 | Kotlin | 9 | 59 | 9de2b21d3bcd41cd03f0f7dd19136db93824a0fa | 2,438 | daily_algorithm | Apache License 2.0 |
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[32]最长有效括号.kt | maoqitian | 175,940,000 | false | {"Kotlin": 354268, "Java": 297740, "C++": 634} | import java.util.*
//给你一个只包含 '(' 和 ')' 的字符串,找出最长有效(格式正确且连续)括号子串的长度。
//
//
//
//
//
// 示例 1:
//
//
//输入:s = "(()"
//输出:2
//解释:最长有效括号子串是 "()"
//
//
// 示例 2:
//
//
//输入:s = ")()())"
//输出:4
//解释:最长有效括号子串是 "()()"
//
//
// 示例 3:
//
//
//输入:s = ""
//输出:0
//
//
//
//
// 提示:
//
//
// 0 <= s.length <= 3 * 104
// s[i] 为 '(' 或 ')'
//
//
//
// Related Topics 字符串 动态规划
// 👍 1334 👎 0
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
fun longestValidParentheses(s: String): Int {
//单调栈 时间复杂度 O(n)
//栈中记录字符 index
var stack = LinkedList<Int>()
//保证栈中有元素
stack.addFirst(-1)
var maxRes = 0
for (i in s.indices){
if(s[i] == '('){
stack.addFirst(i)
}else{
//s[i] == ')'
//出栈
stack.removeFirst()
if(stack.isEmpty()){
stack.addFirst(i)
}else{
//计算最大长度
maxRes = Math.max(maxRes,i - stack.peek())
}
}
}
return maxRes
}
}
//leetcode submit region end(Prohibit modification and deletion)
| 0 | Kotlin | 0 | 1 | 8a85996352a88bb9a8a6a2712dce3eac2e1c3463 | 1,476 | MyLeetCode | Apache License 2.0 |
src/main/kotlin/us/jwf/aoc2021/Day18Snailfish.kt | jasonwyatt | 433,743,675 | false | {"Kotlin": 49932} |
fun main() {
val data = readInputFile("day18")
fun part1(): Int {
val sum = data
.map { Snailfish.parse(it).populateParents() }
.reduce { accumulator, value -> accumulator + value }
return sum.magnitude
}
fun part2(): Int {
val numbers = data.toList()
var maxMagnitude = Int.MIN_VALUE
numbers.forEach { a ->
numbers.forEach inner@{ b ->
if (a === b) return@inner
val sfA = Snailfish.parse(a).populateParents()
val sfB = Snailfish.parse(b).populateParents()
val mag = (sfA + sfB).magnitude
maxMagnitude = maxOf(maxMagnitude, mag)
}
}
return maxMagnitude }
println("Result part1: ${part1()}")
println("Result part2: ${part2()}")
}
sealed class Snailfish(open var parent: Compound? = null) {
val magnitude: Int
get() {
return when (this) {
is Compound -> 3 * left.magnitude + 2 * right.magnitude
is Regular -> value
}
}
val isLeft: Boolean
get() = parent?.left === this
val isRight: Boolean
get() = parent?.right === this
operator fun plus(rhs: Snailfish): Snailfish {
val combined = Compound(this, rhs)
this.parent = combined
rhs.parent = combined
combined.reduce()
return combined
}
fun reduce(): Snailfish {
do {
var didSomething = false
val exploder = findExploder()
val splitter = findSplitter()
if (exploder != null) {
didSomething = true
exploder.explode()
} else if (splitter != null) {
didSomething = true
splitter.split()
}
} while (didSomething)
return this
}
fun populateParents(): Snailfish {
if (this !is Compound) return this
left.parent = this
right.parent = this
left.populateParents()
right.populateParents()
return this
}
private fun findExploder(depth: Int = 0): Compound? {
if (this !is Compound) return null
if (depth == 4) return this
return left.findExploder(depth + 1) ?: right.findExploder(depth + 1)
}
private fun findSplitter(): Regular? {
if (this is Regular) {
if (this.value >= 10) return this
return null
}
this as Compound
return left.findSplitter() ?: right.findSplitter()
}
data class Compound(
var left: Snailfish,
var right: Snailfish,
) : Snailfish() {
fun explode() {
val leftRegular = left as Regular
val rightRegular = right as Regular
findNextLeft()?.let { it.value += leftRegular.value }
findNextRight()?.let { it.value += rightRegular.value }
val replacement = Regular(0)
replacement.parent = parent
if (isLeft) parent?.left = replacement
if (isRight) parent?.right = replacement
}
private fun findNextLeft(): Regular? {
return if (isRight) {
val parentLeft = parent?.left ?: return null
when (parentLeft) {
is Regular -> parentLeft
is Compound -> parentLeft.deepestRight()
}
} else {
var parentAsRight: Compound = parent ?: return null
while (!parentAsRight.isRight) {
parentAsRight = parentAsRight.parent ?: return null
}
parentAsRight.findNextLeft()
}
}
private fun findNextRight(): Regular? {
return if (isLeft) {
val parentRight = parent?.right ?: return null
when (parentRight) {
is Regular -> parentRight
is Compound -> parentRight.deepestLeft()
}
} else {
var parentAsLeft: Compound = parent ?: return null
while (!parentAsLeft.isLeft) {
parentAsLeft = parentAsLeft.parent ?: return null
}
parentAsLeft.findNextRight()
}
}
fun deepestRight(): Regular? {
(right as? Regular)?.let { return it }
return (right as Compound).deepestRight()
}
fun deepestLeft(): Regular? {
(left as? Regular)?.let { return it }
return (left as Compound).deepestLeft()
}
override fun toString(): String = "[$left, $right]"
}
data class Regular(var value: Int) : Snailfish() {
fun split() {
if (this.value < 10) return
val replacement =
Compound(
Regular(value / 2),
Regular(value / 2 + (if (value % 2 == 0) 0 else 1))
)
replacement.left.parent = replacement
replacement.right.parent = replacement
replacement.parent = parent
if (isLeft) parent?.left = replacement
if (isRight) parent?.right = replacement
}
override fun toString(): String = "$value"
}
companion object {
fun parse(raw: String): Snailfish {
if (raw[0] != '[') return Regular(raw.toInt())
var counter = 0
var i = 1
while (counter != 0 || raw[i] != ',') {
if (raw[i] == '[') counter++
if (raw[i] == ']') counter--
i++
}
val left = parse(raw.substring(1, i))
val right = parse(raw.substring(i + 1, raw.length - 1))
return Compound(left, right)
}
}
} | 0 | Kotlin | 0 | 0 | 6d4f19df3b7cb1906052b80a4058fa394a12740f | 5,876 | AdventOfCode-Kotlin | Apache License 2.0 |
src/main/kotlin/algorithms/StringAlgorithms.kt | AgentKnopf | 240,955,745 | false | null | package algorithms
/**
* Two strings are an anagram of each other, if they contain the same letters, the same number of times,
* possibly in a different order.
* @return true if the given strings are anagrams of each other, ignoring capitalization; false otherwise.
*/
internal fun isAnagram(left: String, right: String): Boolean {
if (left.length != right.length) {
//Not the same length so not an anagram
return false
}
//To lowercase both values
val leftString = left.toLowerCase()
val rightString = right.toLowerCase()
//Sort and compare
return leftString.sort() == rightString.sort()
}
/**
* @return the given string, with it's letters sorted in alphabetical order.
*/
internal fun String.sort(): String = toCharArray().sorted().joinToString("")
/**
* @return true if all characters in the given String are unique; false otherwise
*/
internal fun String?.hasUniqueCharacters(withDataStructure: Boolean = true): Boolean = if (this == null) {
false
} else {
if (withDataStructure) hasUniqueCharactersUsingDataStructure(this) else hasUniqueCharactersUsingNoDataStructure(this)
}
/**
* Implements [hasUniqueCharacters] using no additional data structure.
*/
private fun hasUniqueCharactersUsingNoDataStructure(value: String): Boolean {
//We'll go through each character and compare it to the rest of the characters, resulting in O(n)
val characters = value.toLowerCase().toCharArray()
for ((outerIndex, outerCharacter) in characters.withIndex()) {
for ((innerIndex, innerCharacter) in characters.withIndex()) {
if (innerIndex != outerIndex && outerCharacter == innerCharacter) {
return false
}
}
}
return true
}
/**
* Implements [hasUniqueCharacters] with additional data structure.
*/
private fun hasUniqueCharactersUsingDataStructure(value: String): Boolean {
var set = mutableSetOf<Char>()
value.toCharArray().forEach { character -> set = set.plus(character.toLowerCase()).toMutableSet() }
return set.size == value.length
}
internal fun stringToInteger(value: String): Int {
//Check if the first non-whitespace character is a digit or +/- - otherwise we'll return 0
val valueTrimmed = value.trimStart()
if (valueTrimmed.isEmpty()) {
return 0
}
val isNotDigit = !valueTrimmed[0].isDigit()
val isPlus = valueTrimmed[0] == '+'
val isMinus = valueTrimmed[0] == '-'
if ((valueTrimmed.length == 1 && (isPlus || isMinus)) ||
(isNotDigit && !isPlus && !isMinus)
) {
return 0
}
//First check if there is a plus symbol
var numberAsString = value.replace("[^\\d-.]".toRegex(), "")
println(numberAsString)
return try {
//If the resulting string contains a dot we remove everything after the dot
val indexOfDot = numberAsString.indexOf('.', 0)
if (indexOfDot >= 0) {
//We got a dot, cut it off and everything after it
numberAsString = numberAsString.substring(0, indexOfDot)
}
numberAsString.toInt()
} catch (e: NumberFormatException) {
//We know its a valid number, so it must be out of range, return [Int.MIN_VALUE]
Int.MIN_VALUE
}
}
/**
* Given two strings s and t, determine if they are isomorphic.
* Two strings are isomorphic if the characters in s can be replaced to get t.
* All occurrences of a character must be replaced with another character while preserving the order of characters.
* No two characters may map to the same character but a character may map to itself.
*/
internal fun isIsomorphicString(left: String, right: String): Boolean {
val mapLeftToRight = mutableMapOf<Char, Char>()
left.forEachIndexed { index, value ->
if (mapLeftToRight.containsKey(value)) {
//We already have a mapping, check if it's correct
if (right[index] != mapLeftToRight[value]) {
return false
}
} else {
val characterRight = right[index]
//Make sure the character in the right string hasn't been mapped to any other character yet
if (mapLeftToRight.values.contains(characterRight)) {
return false
}
//Add a mapping
mapLeftToRight[value] = characterRight
}
}
return true
}
/**
* Given a string, find the length of the longest substring without repeating characters.
*
* This falls into the "sliding window" category. We have two pointers and we'll keep advancing the right-hand
* pointer until we hit a duplicate. Once we do, we advance the left-hand pointer until we no longer have duplicates, then
* we continue with the right pointer.
*/
internal fun longestSubStringWithoutRepeatingCharacters(input: String): Int {
val lastIndex = mutableMapOf<Char, Int>()
var max = 0
var startIndex = -1
for ((index, character) in input.withIndex()) {
val lastIndex = lastIndex.put(character, index)
if (lastIndex != null && lastIndex > startIndex) {
startIndex = lastIndex
}
if (index - startIndex > max) {
max = index - startIndex
}
}
return max
} | 0 | Kotlin | 1 | 0 | 5367ce67e54633e53b2b951c2534bf7b2315c2d8 | 5,236 | technical-interview | MIT License |
src/AOC2022/Day10/Day10.kt | kfbower | 573,519,224 | false | {"Kotlin": 44562} | package AOC2022.Day10
import AOC2022.readInput
fun main(){
/* addx V takes two cycles to complete. After two cycles, the X register is increased by the value V. (V can be negative.)
noop takes one cycle to complete. It has no other effect.*/
/*signal strength (the cycle number multiplied by the value of the X register) */
fun part1(input: List<String>): Int {
val ssList = mutableListOf<Pair<Int,Int>>()
var cycleCount = 1
var Xreg = 1
input.forEachIndexed { _, s ->
if (s=="noop"){
cycleCount++
val ledgerEntry:Pair<Int,Int> = Pair(cycleCount, Xreg)
ssList+=ledgerEntry
}
else if (s.contains("addx")){
val newS = s.replace("addx ","")
cycleCount++
val ledgerEntry:Pair<Int,Int> = Pair(cycleCount, Xreg)
ssList+=ledgerEntry
cycleCount++
Xreg+=(newS.toInt())
val ledgerEntry2:Pair<Int,Int> = Pair(cycleCount, Xreg)
ssList+=ledgerEntry2
}
}
//Find the signal strength during the 20th, 60th, 100th, 140th, 180th, and 220th cycles. What is the sum of these six signal strengths?
val ssTotal: MutableList<Int> = mutableListOf()
val ssTargetList= listOf<Int>(20,60,100,140,180,220)
ssTargetList.forEachIndexed { _, i ->
val cycleLookup = ssList.find{it.first == i}
val sizeLookup = cycleLookup?.second
ssTotal+=(sizeLookup!!*i)
}
return ssTotal.sum()
}
fun part2(input: List<String>){
val lit = "#"
val unlit = "."
val ssList = mutableListOf<Pair<Int,Int>>()
var cycleCount = 0
var Xreg = 1
input.forEachIndexed { i, s ->
if (s=="noop"){
val ledgerEntry:Pair<Int,Int> = Pair(cycleCount, Xreg)
ssList+=ledgerEntry
cycleCount++
}
else if (s.contains("addx")){
val newS = s.replace("addx ","")
val ledgerEntry:Pair<Int,Int> = Pair(cycleCount, Xreg)
ssList+=ledgerEntry
cycleCount++
val ledgerEntry2:Pair<Int,Int> = Pair(cycleCount, Xreg)
ssList+=ledgerEntry2
cycleCount++
Xreg+=(newS.toInt())
}
}
val drawList1 = mutableListOf<String>()
val drawList2 = mutableListOf<String>()
val drawList3 = mutableListOf<String>()
val drawList4 = mutableListOf<String>()
val drawList5 = mutableListOf<String>()
val drawList6 = mutableListOf<String>()
println(ssList)
ssList.forEachIndexed { index, pair ->
if (index in 0..39) {
if (pair.first == pair.second|| pair.first == ((pair.second+1)) || pair.first == ((pair.second-1))) {
drawList1 += lit
} else {
drawList1 += unlit
}
}
else if (index in 40..79) {
if ((pair.first - 40) == pair.second|| pair.first-40 == (pair.second+1) || pair.first-40 == (pair.second-1)) {
drawList2 += lit
} else {
drawList2 += unlit
}
}
else if (index in 80..119) {
if ((pair.first - 80) == pair.second|| pair.first-80 == (pair.second+1) || pair.first-80 == (pair.second-1)) {
drawList3 += lit
} else {
drawList3 += unlit
}
}
else if (index in 120..159) {
if ((pair.first - 120) == pair.second|| pair.first-120 == (pair.second+1) || pair.first-120 == (pair.second-1)) {
drawList4 += lit
} else {
drawList4 += unlit
}
}
else if (index in 160..199) {
if ((pair.first -160) == pair.second|| pair.first-160 == (pair.second+1) || pair.first-160 == (pair.second-1)) {
drawList5 += lit
} else {
drawList5 += unlit
}
}
else if (index in 200..239) {
if ((pair.first-200) == pair.second|| pair.first-200 == (pair.second+1) || pair.first-200 == (pair.second-1)) {
drawList6 += lit
} else {
drawList6 += unlit
}
}
else{
println("nothing")
}
}
println(drawList1)
println(drawList2)
println(drawList3)
println(drawList4)
println(drawList5)
println(drawList6)
}
val input = readInput("Day10")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 48a7c563ebee77e44685569d356a05e8695ae36c | 4,947 | advent-of-code-2022 | Apache License 2.0 |
app/src/test/java/online/vapcom/codewars/algorithms/SkyScraperTests.kt | vapcomm | 503,057,535 | false | {"Kotlin": 142486} | package online.vapcom.codewars.algorithms
import online.vapcom.codewars.algorithms.Skyscrapers.getVisibleFromEnd
import online.vapcom.codewars.algorithms.Skyscrapers.getVisibleFromStart
import online.vapcom.codewars.algorithms.Skyscrapers.packPermutationToInt
import online.vapcom.codewars.algorithms.Skyscrapers.permutations
import kotlin.test.Test
import kotlin.test.assertEquals
class SkyScraperTests {
@Test
fun permutationsFour() {
val four = listOf(1, 2, 3, 4)
val perms = four.permutations()
assertEquals(24, perms.size)
assertEquals("1, 2, 3, 4\n" +
"2, 1, 3, 4\n" +
"3, 1, 2, 4\n" +
"1, 3, 2, 4\n" +
"2, 3, 1, 4\n" +
"3, 2, 1, 4\n" +
"4, 2, 3, 1\n" +
"2, 4, 3, 1\n" +
"3, 4, 2, 1\n" +
"4, 3, 2, 1\n" +
"2, 3, 4, 1\n" +
"3, 2, 4, 1\n" +
"4, 1, 3, 2\n" +
"1, 4, 3, 2\n" +
"3, 4, 1, 2\n" +
"4, 3, 1, 2\n" +
"1, 3, 4, 2\n" +
"3, 1, 4, 2\n" +
"4, 1, 2, 3\n" +
"1, 4, 2, 3\n" +
"2, 4, 1, 3\n" +
"4, 2, 1, 3\n" +
"1, 2, 4, 3\n" +
"2, 1, 4, 3", perms.joinToString("\n") { it.joinToString() })
// check arithmetic progression sum: (1+4)*4/2 = 10
perms.forEachIndexed { index, p ->
assertEquals(10, p.sum(), "Sum of permutation #$index should be 10")
}
// check all permutations really differ
val set = perms.map { it.joinToString() }.toSet()
assertEquals(24, set.size)
}
@Test
fun permutationsSeven() {
val seven = listOf(1, 2, 3, 4, 5, 6, 7)
val perms = seven.permutations()
assertEquals(5040, perms.size)
// check arithmetic progression sum: (1+7)*7/2 = 28
perms.forEachIndexed { index, p ->
assertEquals(28, p.sum(), "Sum of permutation #$index should be 28")
}
// check all differ
val set = perms.map { it.joinToString() }.toSet()
assertEquals(5040, set.size)
}
@Test
fun packToIntTest() {
assertEquals(0, packPermutationToInt(emptyList()))
assertEquals(0x1, packPermutationToInt(listOf(1)))
assertEquals(0x12, packPermutationToInt(listOf(1, 2)))
assertEquals(0x1234, packPermutationToInt(listOf(1, 2, 3, 4)))
assertEquals(0x123456, packPermutationToInt(listOf(1, 2, 3, 4, 5, 6)))
assertEquals(0x1234567, packPermutationToInt(listOf(1, 2, 3, 4, 5, 6, 7)))
}
@Test
fun visibleFrom() {
val permutations = listOf(
packPermutationToInt(listOf(1, 2, 3, 4)),
packPermutationToInt(listOf(4, 3, 2, 1)),
packPermutationToInt(listOf(4, 2, 3, 1)),
packPermutationToInt(listOf(4, 1, 3, 2)),
packPermutationToInt(listOf(3, 2, 1, 4)),
packPermutationToInt(listOf(2, 1, 4, 3)),
packPermutationToInt(listOf(2, 3, 1, 4))
)
assertEquals("4, 1, 1, 1, 2, 2, 3", getVisibleFromStart(permutations).joinToString())
assertEquals("1, 4, 3, 3, 1, 2, 1", getVisibleFromEnd(permutations).joinToString())
}
}
| 0 | Kotlin | 0 | 0 | 97b50e8e25211f43ccd49bcee2395c4bc942a37a | 3,352 | codewars | MIT License |
src/automaton/FiniteStateMachine.kt | q-lang | 128,704,097 | false | null | package automaton
import graph.NonDeterministicGraph
import graph.SimpleGraph
data class FiniteStateMachine<STATE, SYMBOL>(
val nfaStart: STATE,
val nfa: NonDeterministicGraph<STATE, SYMBOL?>,
val groups: Map<String, Group<STATE>>
) : Automaton<STATE, SYMBOL> {
// Deterministic Finite Automaton
val dfaStart: Set<STATE>
val dfa: SimpleGraph<Set<STATE>, SYMBOL>
init {
val newDfa = SimpleGraph.New<Set<STATE>, SYMBOL>()
dfaStart = nfa.epsilonClosure(setOf(nfaStart))
val queue = mutableListOf(dfaStart)
while (queue.isNotEmpty()) {
val starts = queue.removeAt(0)
if (starts in newDfa.vertices)
continue
val reachable: MutableMap<SYMBOL, Set<STATE>> = mutableMapOf()
for (path in nfa.paths(nfa.epsilonClosure(starts), { p -> p.edge != null }))
reachable[path.edge!!] = reachable[path.edge].orEmpty() union nfa.epsilonClosure(setOf(path.end))
for (ends in reachable.values)
queue.add(ends)
newDfa[starts] = reachable
}
dfa = newDfa.build()
}
override fun transitionFunction(state: Set<STATE>, inputs: InputTape<SYMBOL>): Set<STATE>? {
val input = inputs.next() ?: return null
return dfa.vertices[state]?.get(input)
}
fun evaluate(inputs: Sequence<SYMBOL>): Map<String, Match>? {
return evaluate(dfaStart, InputTape(inputs), groups)
}
fun evaluateAll(inputs: Sequence<SYMBOL>): Sequence<Map<String, Match>> {
return evaluateAll(dfaStart, InputTape(inputs), groups)
}
data class New<STATE, SYMBOL>(val initialState: STATE) {
val nfa = NonDeterministicGraph.New<STATE, SYMBOL?>()
val groups: MutableMap<String, Group<STATE>> = mutableMapOf()
init {
nfa.graph.vertices[initialState] = mapOf()
}
fun transition(start: STATE, input: SYMBOL?, end: STATE) = apply {
nfa.path(start, input, end)
}
fun group(name: String, start: STATE, end: STATE) = apply {
groups[name] = Group(start, end)
}
fun build() = FiniteStateMachine(initialState, nfa.build(), groups)
}
}
| 0 | Kotlin | 1 | 0 | 2d8a8b4d32ae8ec5b8ed9cce099bd58f37838833 | 2,074 | q-lang | MIT License |
src/Day10.kt | lonskiTomasz | 573,032,074 | false | {"Kotlin": 22055} | fun main() {
fun part1(input: List<String>): Int {
var cycle = 0
var x = 1
var sum = 0
fun cycle() {
cycle += 1
if (cycle in listOf(20, 60, 100, 140, 180, 220)) sum += x * cycle
}
input.forEach { line ->
when {
line == "noop" -> cycle()
line.startsWith("addx") -> {
repeat(2) { cycle() }
x += line.removePrefix("addx ").toInt()
}
}
}
return sum
}
fun part2(input: List<String>): String {
var cycle = 0
var x = 1
var CRT = ""
fun cycle() {
cycle += 1
CRT += if (cycle in x..x+2) "#" else "."
if (cycle == 40) {
cycle = 0
CRT += "\n"
}
}
input.forEach { line ->
when {
line == "noop" -> cycle()
line.startsWith("addx") -> {
repeat(2) { cycle() }
x += line.removePrefix("addx ").toInt()
}
}
}
return CRT
}
val inputTest = readInput("day10/input_test")
val input = readInput("day10/input")
println(part1(inputTest))
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 9e758788759515049df48fb4b0bced424fb87a30 | 1,358 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/tools/manhattan.kt | verwoerd | 224,986,977 | false | null | package tools
import kotlin.math.abs
/**
* @author verwoerd
* @since 3-12-2019
*/
data class Coordinate(val x: Int, val y: Int) : Comparable<Coordinate> {
override fun compareTo(other: Coordinate): Int = when (val result = y.compareTo(other.y)) {
0 -> x.compareTo(other.x)
else -> result
}
operator fun minus(other: Coordinate): Coordinate = Coordinate(x - other.x, y - other.y)
operator fun plus(other: Coordinate): Coordinate = Coordinate(x + other.x, y + other.y)
operator fun plus(i: Number): Coordinate = plus(Coordinate(i.toInt(), i.toInt()))
operator fun times(i: Number): Coordinate = this * Coordinate(i.toInt(), i.toInt())
operator fun times(other: Coordinate): Coordinate = Coordinate(x * other.x, y * other.y)
operator fun div(other: Coordinate): Coordinate = Coordinate(x / other.x, y / other.y)
infix fun plusY(i: Number): Coordinate = plus(Coordinate(0, i.toInt()))
infix fun plusX(i: Number): Coordinate = plus(Coordinate(i.toInt(), 0))
}
val xIncrement = Coordinate(1, 0)
val yIncrement = Coordinate(0, 1)
fun manhattanDistance(a: Coordinate, b: Coordinate) = abs(a.x - b.x) + abs(a.y - b.y)
val origin = Coordinate(0, 0)
val manhattanOriginComparator = Comparator { a: Coordinate, b: Coordinate ->
manhattanDistance(origin, a) - manhattanDistance(
origin, b
)
}
fun <V> Map<Coordinate, V>.yRange() = keys.minBy { it.y }!!.y to keys.maxBy { it.y }!!.y
fun <V> Map<Coordinate, V>.xRange() = keys.minBy { it.x }!!.x to keys.maxBy { it.x }!!.x
fun adjacentCoordinates(origin: Coordinate) = sequenceOf(
Coordinate(origin.x + 1, origin.y),
Coordinate(origin.x - 1, origin.y),
Coordinate(origin.x, origin.y + 1),
Coordinate(origin.x, origin.y - 1)
)
| 0 | Kotlin | 0 | 0 | 554377cc4cf56cdb770ba0b49ddcf2c991d5d0b7 | 1,822 | AoC2019 | MIT License |
advent2022/src/main/kotlin/year2022/Day21.kt | bulldog98 | 572,838,866 | false | {"Kotlin": 132847} | package year2022
import AdventDay
typealias ValueNumber = Long
private fun String.toValueNumber(): ValueNumber = toLong()
class Day21 : AdventDay(2022, 21) {
enum class HumanPosition {
NONE,
LEFT,
RIGHT
}
enum class MathOperation(
val separator: String,
val computation: (ValueNumber, ValueNumber) -> ValueNumber,
// how to compute first for x = left `op` right, x first param, right is second
val leftReverse: (ValueNumber, ValueNumber) -> ValueNumber,
// how to compute second for x = left `op` right, x first param, left is second
val rightReverse: (ValueNumber, ValueNumber) -> ValueNumber = leftReverse
) {
PLUS(" + ", ValueNumber::plus, ValueNumber::minus),
MINUS(" - ", ValueNumber::minus, ValueNumber::plus, { result, left -> left - result }),
MULTIPLICATION(" * ", ValueNumber::times, ValueNumber::div),
DIVISION(" / ", ValueNumber::div, ValueNumber::times, { result, left -> left / result }),
}
sealed interface MonkeyEquation {
val name: String
fun value(lookup: (String) -> MonkeyEquation): ValueNumber
fun containsHumanValue(lookup: (String) -> MonkeyEquation): HumanPosition
companion object {
private fun fromEquation(name: String, equation: String, op: MathOperation): Operation =
equation.split(op.separator).let { (a, b) ->
Operation(name, a, b, op)
}
fun from(input: String): MonkeyEquation {
val (name, rest) = input.split(": ")
return when {
MathOperation.PLUS.separator in rest -> fromEquation(name, rest, MathOperation.PLUS)
MathOperation.MINUS.separator in rest -> fromEquation(name, rest, MathOperation.MINUS)
MathOperation.MULTIPLICATION.separator in rest -> fromEquation(name, rest, MathOperation.MULTIPLICATION)
MathOperation.DIVISION.separator in rest -> fromEquation(name, rest, MathOperation.DIVISION)
else -> Number(name, rest.toValueNumber())
}
}
}
}
data object Unknown : MonkeyEquation {
override val name: String = "humn"
override fun containsHumanValue(lookup: (String) -> MonkeyEquation): HumanPosition = HumanPosition.LEFT
override fun value(lookup: (String) -> MonkeyEquation): ValueNumber = ValueNumber.MAX_VALUE
}
data class Number(override val name: String, val value: ValueNumber) : MonkeyEquation {
override fun toString(): String = "$name = $value"
override fun value(lookup: (String) -> MonkeyEquation): ValueNumber = value
override fun containsHumanValue(lookup: (String) -> MonkeyEquation): HumanPosition = HumanPosition.NONE
}
data class Operation(
override val name: String,
val a: String,
val b: String,
val op: MathOperation
): MonkeyEquation {
override fun toString(): String = "$name = $a${op.separator}$b"
override fun value(lookup: (String) -> MonkeyEquation): ValueNumber =
op.computation(lookup(a).value(lookup), lookup(b).value(lookup))
override fun containsHumanValue(lookup: (String) -> MonkeyEquation): HumanPosition = when {
a == "humn" -> HumanPosition.LEFT
b == "humn" -> HumanPosition.RIGHT
else -> {
val (left, right) = listOf(lookup(a), lookup(b)).map { it.containsHumanValue(lookup) }
when {
left != HumanPosition.NONE -> HumanPosition.LEFT
right != HumanPosition.NONE -> HumanPosition.RIGHT
else -> HumanPosition.NONE
}
}
}
}
private fun computeOperationMap(input: List<String>): Map<String, MonkeyEquation> {
val ops = input.map { MonkeyEquation.from(it) }
return buildMap {
ops.forEach {
this[it.name] = it
}
val operationsToSimplify = this.values.filterIsInstance<Operation>().filter {
isComputable(it.a, this) && isComputable(it.b, this)
}.toMutableSet()
while (operationsToSimplify.isNotEmpty()) {
val toSimplify = operationsToSimplify.first()
operationsToSimplify.remove(toSimplify)
this[toSimplify.name] = Number(toSimplify.name, this[toSimplify.name]!!.value(this::getValue))
operationsToSimplify.addAll(this.values.filterIsInstance<Operation>().filter {
isComputable(it.a, this) && isComputable(it.b, this)
})
}
}
}
private fun isComputable(variable: String, lookupMonkeyEquation: Map<String, MonkeyEquation>): Boolean =
when (val equation = lookupMonkeyEquation[variable]) {
null -> false
is Unknown -> false
is Number -> true
is Operation -> isComputable(equation.a, lookupMonkeyEquation) && isComputable(equation.b, lookupMonkeyEquation)
}
private tailrec fun MonkeyEquation.solve(
expectedValue: ValueNumber,
lookup: (String) -> MonkeyEquation
): ValueNumber = when {
this is Unknown -> expectedValue
this is Number -> if (value == expectedValue) value else error("did not match")
this !is Operation -> error("unable to solve $this")
lookup(a) is Number -> {
val left = lookup(a)
val right = lookup(b)
val computed = op.rightReverse(expectedValue, left.value(lookup))
right.solve(computed, lookup)
}
lookup(b) is Number -> {
val left = lookup(a)
val right = lookup(b)
val computed = op.leftReverse(expectedValue, right.value(lookup))
left.solve(computed, lookup)
}
else -> error("unable to evaluate")
}
override fun part1(input: List<String>): ValueNumber {
val lookupOperation = computeOperationMap(input)
return lookupOperation["root"]!!.value(lookupOperation::getValue)
}
override fun part2(input: List<String>): ValueNumber {
val (a, b) = input.find { it.startsWith("root: ") }!!.drop(6).split(" + ")
val lookupEquation = computeOperationMap(input.filter { "root: " !in it && "humn: " !in it }) +
mapOf("humn" to Unknown)
val rootEquation = Operation("root", a, b, MathOperation.MINUS)
return rootEquation.solve(0L, lookupEquation::getValue)
}
}
fun main() = Day21().run() | 0 | Kotlin | 0 | 0 | 02ce17f15aa78e953a480f1de7aa4821b55b8977 | 6,656 | advent-of-code | Apache License 2.0 |
jvm/src/main/kotlin/io/prfxn/aoc2021/day17.kt | prfxn | 435,386,161 | false | {"Kotlin": 72820, "Python": 362} | // Trick Shot (https://adventofcode.com/2021/day/17)
package io.prfxn.aoc2021
import kotlin.math.max
fun main() {
val (targetXRange, targetYRange) =
"-?\\d+".toRegex().findAll(textResourceReader("input/17.txt").readText())
.map { it.value.toInt() }
.let {
val (x1, x2, y1, y2) = it.toList()
(x1..x2) to (y1..y2)
}
fun bullseye(x: Int, y: Int): Boolean = x in targetXRange && y in targetYRange
fun missed(x: Int, y: Int) = x > targetXRange.last || y < targetYRange.first
fun stepSequence(xv0: Int, yv0: Int) =
generateSequence((0 to 0) to (xv0 to yv0)) { (pos, vel) ->
val (x, y) = pos
val (xv, yv) = vel
(x + xv to y + yv) to
(max(xv - 1, 0) to yv - 1)
}
fun getMaxY(xv0: Int, yv0: Int): Int? =
with (stepSequence(xv0, yv0)) {
var maxY = 0
find { (pos, vel) ->
val (x, y) = pos
maxY = max(maxY, y)
if (missed(x, y)) return@with null
bullseye(x, y)
}
maxY
}
// judgement call on those ranges
println( // answer 1
(0..1000).flatMap { x -> (-1000..1000).map { y -> x to y } }
.mapNotNull { (x, y) -> getMaxY(x, y) }
.maxOf { it }
)
println( // answer 2
(0..1000).flatMap { x -> (-1000..1000).map { y -> x to y } }
.mapNotNull { (x, y) -> getMaxY(x, y) }
.count()
)
}
| 0 | Kotlin | 0 | 0 | 148938cab8656d3fbfdfe6c68256fa5ba3b47b90 | 1,553 | aoc2021 | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/Nqueens2.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2020 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
/**
* 52. N-Queens II
* @see <a href="https://leetcode.com/problems/n-queens-ii/">Source</a>
*/
fun interface TotalNQueensStrategy {
operator fun invoke(n: Int): Int
}
/**
* Approach: Backtracking
* Time complexity: O(N!)
* Space complexity: O(N)
*/
class TotalNQueensStraightForward : TotalNQueensStrategy {
private val occupiedCols = hashSetOf<Int>()
private val occupiedDiag1s = hashSetOf<Int>()
private val occupiedDiag2s = hashSetOf<Int>()
override operator fun invoke(n: Int): Int {
return n.totalNQueensHelper(0, 0)
}
private fun Int.totalNQueensHelper(row: Int, c: Int): Int {
var count = c
for (col in 0 until this) {
if (occupiedCols.contains(col)) {
continue
}
val diag1 = row - col
if (occupiedDiag1s.contains(diag1)) {
continue
}
val diag2 = row + col
if (occupiedDiag2s.contains(diag2)) {
continue
}
// we can now place a queen here
if (row == this - 1) {
count++
} else {
occupiedCols.add(col)
occupiedDiag1s.add(diag1)
occupiedDiag2s.add(diag2)
count = this.totalNQueensHelper(row + 1, count)
// recover
occupiedCols.remove(col)
occupiedDiag1s.remove(diag1)
occupiedDiag2s.remove(diag2)
}
}
return count
}
}
class TotalNQueensRecursive : TotalNQueensStrategy {
private var count = 0
override operator fun invoke(n: Int): Int {
val cols = BooleanArray(n)
val d1 = BooleanArray(2 * n)
val d2 = BooleanArray(2 * n)
n.backtracking(0, cols, d1, d2)
return count
}
private fun Int.backtracking(row: Int, cols: BooleanArray, d1: BooleanArray, d2: BooleanArray) {
if (row == this) count++
for (col in 0 until this) {
val id1 = col - row + this
val id2 = col + row
if (cols[col] || d1[id1] || d2[id2]) {
continue
}
cols[col] = true
d1[id1] = true
d2[id2] = true
this.backtracking(row + 1, cols, d1, d2)
cols[col] = false
d1[id1] = false
d2[id2] = false
}
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 3,062 | kotlab | Apache License 2.0 |
src/com/kingsleyadio/adventofcode/y2021/day07/Alternative.kt | kingsleyadio | 435,430,807 | false | {"Kotlin": 134666, "JavaScript": 5423} | package com.kingsleyadio.adventofcode.y2021.day07
import com.kingsleyadio.adventofcode.util.readInput
fun part1(input: List<Int>): Int {
val min = input.minOrNull()!!
val max = input.maxOrNull()!!
val plane = IntArray(max - min + 1)
for (value in input) plane[value - min]++
val aligningForward = IntArray(plane.size)
var subs = plane[0]
for (i in 1..plane.lastIndex) {
aligningForward[i] = aligningForward[i - 1] + subs
subs += plane[i]
}
val aligningBackward = IntArray(plane.size)
subs = plane.last()
for (i in plane.lastIndex - 1 downTo 0) {
aligningBackward[i] = aligningBackward[i + 1] + subs
subs += plane[i]
}
for (i in aligningBackward.indices) aligningForward[i] += aligningBackward[i]
return aligningForward.minOrNull()!!
}
fun main() {
val input = readInput(2021, 7).useLines { lines ->
lines.first().split(",").map { it.toInt() }
}
println(part1(input))
}
| 0 | Kotlin | 0 | 1 | 9abda490a7b4e3d9e6113a0d99d4695fcfb36422 | 981 | adventofcode | Apache License 2.0 |
src/Day01.kt | jsebasct | 572,954,137 | false | {"Kotlin": 29119} | fun main() {
fun part1(input: List<String>): Int {
val caloriesElf = mutableListOf<Int>()
var sum = 0
for (calorie in input) {
if (calorie != "") {
sum += calorie.toInt()
} else {
caloriesElf.add(sum)
sum = 0
}
}
return caloriesElf.maxOrNull() ?: 0
}
fun part2(input: List<String>): Int {
val caloriesElf = mutableListOf<Int>()
var sum = 0
for (calorie in input) {
if (calorie != "") {
sum += calorie.toInt()
} else {
caloriesElf.add(sum)
sum = 0
}
}
caloriesElf.add(sum)
caloriesElf.sortDescending()
return caloriesElf.take(3).sum()
}
val input = readInput("Day01_test")
println(part1(input))
println("Part two")
println(part2(input))
// test if implementation meets criteria from the description, like:
// val testInput = readInput("Day01_test")
// check(part2(testInput) == 45000)
}
| 0 | Kotlin | 0 | 0 | c4a587d9d98d02b9520a9697d6fc269509b32220 | 1,099 | aoc2022 | Apache License 2.0 |
year2023/day11/part2/src/main/kotlin/com/curtislb/adventofcode/year2023/day11/part2/Year2023Day11Part2.kt | curtislb | 226,797,689 | false | {"Kotlin": 2146738} | /*
--- Part Two ---
The galaxies are much older (and thus much farther apart) than the researcher initially estimated.
Now, instead of the expansion you did before, make each empty row or column one million times
larger. That is, each empty row should be replaced with 1000000 empty rows, and each empty column
should be replaced with 1000000 empty columns.
(In the example above, if each empty row or column were merely 10 times larger, the sum of the
shortest paths between every pair of galaxies would be 1030. If each empty row or column were merely
100 times larger, the sum of the shortest paths between every pair of galaxies would be 8410.
However, your universe will need to expand far beyond these values.)
Starting with the same initial image, expand the universe according to these new rules, then find
the length of the shortest path between every pair of galaxies. What is the sum of these lengths?
*/
package com.curtislb.adventofcode.year2023.day11.part2
import com.curtislb.adventofcode.year2023.day11.expansion.ExpandedUniverse
import java.nio.file.Path
import java.nio.file.Paths
/**
* Returns the solution to the puzzle for 2023, day 11, part 2.
*
* @param inputPath The path to the input file for this puzzle.
* @param expansionFactor The actual size, after expansion, of each row or column with no galaxies.
*/
fun solve(
inputPath: Path = Paths.get("..", "input", "input.txt"),
expansionFactor: Long = 1_000_000L
): Long {
val universe = ExpandedUniverse.fromFile(inputPath.toFile(), expansionFactor)
return universe.sumGalaxyDistances()
}
fun main() {
println(solve())
}
| 0 | Kotlin | 1 | 1 | 6b64c9eb181fab97bc518ac78e14cd586d64499e | 1,628 | AdventOfCode | MIT License |
src/main/kotlin/at/mpichler/aoc/solutions/year2022/Day02.kt | mpichler94 | 656,873,940 | false | {"Kotlin": 196457} | package at.mpichler.aoc.solutions.year2022
import at.mpichler.aoc.lib.Day
import at.mpichler.aoc.lib.PartSolution
open class Part2A : PartSolution() {
private lateinit var rounds: List<String>
internal open val table = mapOf(
"AX" to 4,
"AY" to 8,
"AZ" to 3,
"BX" to 1,
"BY" to 5,
"BZ" to 9,
"CX" to 7,
"CY" to 2,
"CZ" to 6
)
override fun parseInput(text: String) {
rounds = text.trim().split("\n").map { it.replace(" ", "") }.toList()
}
override fun compute(): Int {
return rounds.sumOf { table[it] ?: 0 }
}
override fun getExampleAnswer(): Int {
return 15
}
}
class Part2B : Part2A() {
override val table = mapOf(
"AX" to 3,
"AY" to 4,
"AZ" to 8,
"BX" to 1,
"BY" to 5,
"BZ" to 9,
"CX" to 2,
"CY" to 6,
"CZ" to 7
)
override fun getExampleAnswer(): Int {
return 12
}
}
fun main() {
Day(2022, 2, Part2A(), Part2B())
}
| 0 | Kotlin | 0 | 0 | 69a0748ed640cf80301d8d93f25fb23cc367819c | 1,058 | advent-of-code-kotlin | MIT License |
advent-of-code-2019/src/test/java/Day3CrossedWired.kt | yuriykulikov | 159,951,728 | false | {"Kotlin": 1666784, "Rust": 33275} | import org.assertj.core.api.Assertions.assertThat
import org.junit.Ignore
import org.junit.Test
import kotlin.math.absoluteValue
class Day3CrossedWired {
val testInput = listOf(
Triple(
"R8,U5,L5,D3",
"U7,R6,D4,L4", 6
),
Triple(
"R75,D30,R83,U83,L12,D49,R71,U7,L72",
"U62,R66,U55,R34,D71,R55,D58,R83", 159
),
Triple(
"R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51",
"U98,R91,D20,R16,D67,R40,U7,R15,U6,R7", 135
)
)
val testInput2 = listOf(
Triple(
"R8,U5,L5,D3",
"U7,R6,D4,L4", 30
),
Triple(
"R75,D30,R83,U83,L12,D49,R71,U7,L72",
"U62,R66,U55,R34,D71,R55,D58,R83", 610
),
Triple(
"R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51",
"U98,R91,D20,R16,D67,R40,U7,R15,U6,R7", 410
)
)
@Test
fun verifyTestInput() {
testInput.forEach { (first, second, distance) ->
assertThat(firstCrossing(first, second)).isEqualTo(distance)
}
}
@Ignore
@Test
fun silverStar() {
assertThat(firstCrossing(first, second)).isEqualTo(1084)
}
@Test
fun verifyTestInput2() {
testInput2.forEach { (first, second, steps) ->
assertThat(optimalCrossing(first, second)).isEqualTo(steps)
}
}
@Ignore
@Test
fun goldStar() {
assertThat(optimalCrossing(first, second)).isEqualTo(9240)
}
data class Point(val x: Int, val y: Int)
private fun Point.left() = copy(x = x - 1)
private fun Point.right() = copy(x = x + 1)
private fun Point.up() = copy(y = y + 1)
private fun Point.down() = copy(y = y - 1)
private fun firstCrossing(first: String, second: String): Int {
return points(first).intersect(points(second))
.minus(Point(0, 0))
.map { it.x.absoluteValue + it.y.absoluteValue }
.min() ?: 0
}
private fun optimalCrossing(first: String, second: String): Int {
val firstPoints = points(first)
val secondPoints = points(second)
return firstPoints.intersect(secondPoints)
.minus(Point(0, 0))
.onEach { println(it) }
.map { firstPoints.indexOf(it) + secondPoints.indexOf(it) }
.min() ?: 0
}
private fun points(desc: String): List<Point> {
return desc.split(",")
.fold(listOf(Point(0, 0))) { acc, next ->
val steps = next.substring(1).toInt()
acc.plus(when (next.first()) {
'R' -> (0 until steps).fold(listOf(acc.last())) { localAcc, _ ->
localAcc.plus(localAcc.last().right())
}
'U' -> (0 until steps).fold(listOf(acc.last())) { localAcc, _ ->
localAcc.plus(localAcc.last().up())
}
'L' -> (0 until steps).fold(listOf(acc.last())) { localAcc, _ ->
localAcc.plus(localAcc.last().left())
}
'D' -> (0 until steps).fold(listOf(acc.last())) { localAcc, _ ->
localAcc.plus(localAcc.last().down())
}
else -> throw Exception()
}.drop(1))
}
}
private val first =
"R1003,U741,L919,U341,L204,U723,L113,D340,L810,D238,R750,U409,L104,U65,R119,U58,R94,D738,L543,U702,R612,D998,L580,U887,R664,D988,R232,D575,R462,U130,L386,U386,L217,U155,L68,U798,R792,U149,L573,D448,R76,U896,L745,D640,L783,D19,R567,D271,R618,U677,L449,D651,L843,D117,L636,U329,R484,U853,L523,U815,L765,U834,L500,U321,R874,U90,R473,U31,R846,U549,L70,U848,R677,D557,L702,U90,R78,U234,R282,D289,L952,D514,R308,U255,R752,D338,L134,D335,L207,U167,R746,U328,L65,D579,R894,U716,R510,D932,L396,U766,L981,D115,L668,U197,R773,U898,L22,U294,L548,D634,L31,U626,R596,U442,L103,U448,R826,U511,R732,U680,L279,D693,R292,U641,R253,U977,R699,U861,R534,D482,L481,U929,L244,U863,L951,D744,R775,U198,L658,U700,L740,U725,R286,D105,L629,D117,L991,D778,L627,D389,R942,D17,L791,D515,R231,U418,L497,D421,L508,U91,R841,D823,L88,U265,L223,D393,L399,D390,L431,D553,R40,U724,L566,U121,L436,U797,L42,U13,R19,D858,R912,D571,L207,D5,L981,D996,R814,D918,L16,U872,L5,U281,R706,U596,R827,D19,R976,D664,L930,U56,R168,D892,R661,D751,R219,U343,R120,U21,L659,U976,R498,U282,R1,U721,R475,D798,L5,U396,R268,D454,R118,U260,L709,D369,R96,D232,L320,D763,R548,U670,R102,D253,L947,U845,R888,D645,L734,D734,L459,D638,L82,U933,L485,U235,R181,D51,L45,D979,L74,D186,L513,U974,R283,D493,R128,U909,L96,D861,L291,U640,R793,D712,R421,D315,L152,U220,L252,U642,R126,D417,R137,D73,R1,D711,R880,U718,R104,U444,L36,D974,L360,U12,L890,D337,R184,D745,R164,D931,R915,D999,R452,U221,L399,D761,L987,U562,R25,D642,R411,D605,R964"
private val second =
"L1010,U302,L697,D105,R618,U591,R185,U931,R595,D881,L50,D744,L320,D342,L221,D201,L862,D959,R553,D135,L238,U719,L418,U798,R861,U80,L571,U774,L896,U772,L960,U368,R415,D560,R276,U33,L532,U957,R621,D137,R373,U53,L842,U118,L299,U203,L352,D531,R118,U816,R355,U678,L983,D175,R652,U230,R190,D402,R111,D842,R756,D961,L82,U206,L576,U910,R622,D494,R630,D893,L200,U943,L696,D573,L143,D640,L885,D184,L52,D96,L580,U204,L793,D806,R477,D651,L348,D318,L924,D700,R675,D689,L723,D418,L156,D215,L943,D397,L301,U350,R922,D721,R14,U399,L774,U326,L14,D465,L65,U697,R564,D4,L40,D250,R914,U901,R316,U366,R877,D222,L672,D329,L560,U882,R321,D169,R161,U891,L552,U86,L194,D274,L567,D669,L682,U60,L985,U401,R587,U569,L1,D325,L73,U814,L338,U618,L49,U67,L258,D596,R493,D249,L310,D603,R810,D735,L829,D378,R65,U85,L765,D854,L863,U989,L595,U564,L373,U76,R923,U760,L965,U458,L610,U461,R900,U151,L650,D437,L1,U464,L65,D349,R256,D376,L686,U183,L403,D354,R867,U993,R819,D333,L249,U466,L39,D878,R855,U166,L254,D532,L909,U48,L980,U652,R393,D291,L502,U230,L738,U681,L393,U935,L333,D139,L499,D813,R302,D415,L693,D404,L308,D603,R968,U753,L510,D356,L356,U620,R386,D205,R587,U212,R715,U360,L603,U792,R58,U619,R73,D958,L53,D666,L756,U71,L621,D576,L174,U779,L382,U977,R890,D830,R822,U312,R716,U767,R36,U340,R322,D175,L417,U710,L313,D526,L573,D90,L493,D257,L918,U425,R93,D552,L691,U792,R189,U43,L633,U934,L953,U817,L404,D904,L384,D15,L670,D889,L648,U751,L928,D744,L932,U761,R879,D229,R491,U902,R134,D219,L634,U423,L241"
} | 0 | Kotlin | 0 | 1 | f5efe2f0b6b09b0e41045dc7fda3a7565cb21db3 | 6,515 | advent-of-code | MIT License |
src/main/kotlin/com/ginsberg/advent2016/Day15.kt | tginsberg | 74,924,040 | false | null | /*
* Copyright (c) 2016 by <NAME>
*/
package com.ginsberg.advent2016
/**
* Advent of Code - Day 15: December 15, 2016
*
* From http://adventofcode.com/2016/day/15
*
*/
class Day15(input: List<String>) {
companion object {
val DISC_REGEX = Regex("""Disc #(\d+) has (\d+) positions; at time=0, it is at position (\d+).""")
}
val discs: List<Disc> = parseInput(input)
fun solvePart1(): Int = solve()
fun solvePart2(): Int = solve(discs + Disc(11, 0, discs.size+1))
private fun solve(state: List<Disc> = discs): Int =
generateSequence(0, Int::inc)
.filter { time -> state.all { it.openAtDropTime(time) } }
.first()
data class Disc(val positions: Int, val start: Int, val depth: Int) {
fun openAtDropTime(time: Int): Boolean =
(time + depth + start) % positions == 0
}
private fun parseInput(input: List<String>): List<Disc> =
input
.map { DISC_REGEX.matchEntire(it) }
.filterNotNull()
.map { it.destructured }
.map { Disc(it.component2().toInt(), it.component3().toInt(), it.component1().toInt())}
.sortedBy { it.depth }
}
| 0 | Kotlin | 0 | 3 | a486b60e1c0f76242b95dd37b51dfa1d50e6b321 | 1,206 | advent-2016-kotlin | MIT License |
dataStructuresAndAlgorithms/src/main/java/com/crazylegend/datastructuresandalgorithms/graphs/djikstra/Dijkstra.kt | ch8n | 379,267,678 | true | {"Kotlin": 1841146} | package com.crazylegend.datastructuresandalgorithms.graphs.djikstra
import com.crazylegend.datastructuresandalgorithms.graphs.Edge
import com.crazylegend.datastructuresandalgorithms.graphs.Vertex
import com.crazylegend.datastructuresandalgorithms.graphs.adjacency.AdjacencyList
import com.crazylegend.datastructuresandalgorithms.queue.priority.comparator.ComparatorPriorityQueue
/**
* Created by crazy on 9/7/20 to long live and prosper !
*/
class Dijkstra<T>(private val graph: AdjacencyList<T>) {
private fun route(destination: Vertex<T>, paths: HashMap<Vertex<T>, Visit<T>>): ArrayList<Edge<T>> {
var vertex = destination
val path = arrayListOf<Edge<T>>()
loop@ while (true) {
val visit = paths[vertex] ?: break
when (visit.type) {
VisitType.START -> break@loop
VisitType.EDGE -> visit.edge?.let {
path.add(it)
vertex = it.source
}
}
}
return path
}
private fun distance(destination: Vertex<T>, paths: HashMap<Vertex<T>, Visit<T>>): Double {
val path = route(destination, paths)
return path.sumByDouble { it.weight ?: 0.0 }
}
fun shortestPath(start: Vertex<T>): HashMap<Vertex<T>, Visit<T>> {
val paths: HashMap<Vertex<T>, Visit<T>> = HashMap()
paths[start] = Visit(VisitType.START)
val distanceComparator = Comparator<Vertex<T>> { first, second ->
(distance(second, paths) - distance(first, paths)).toInt()
}
val priorityQueue = ComparatorPriorityQueue(distanceComparator)
priorityQueue.enqueue(start)
while (true) {
val vertex = priorityQueue.dequeue() ?: break
val edges = graph.edges(vertex)
edges.forEach {
val weight = it.weight ?: return@forEach
if (paths[it.destination] == null
|| distance(vertex, paths) + weight < distance(it.destination, paths)) {
paths[it.destination] = Visit(VisitType.EDGE, it)
priorityQueue.enqueue(it.destination)
}
}
}
return paths
}
fun shortestPath(destination: Vertex<T>, paths: HashMap<Vertex<T>, Visit<T>>): ArrayList<Edge<T>> {
return route(destination, paths)
}
fun getAllShortestPath(source: Vertex<T>): HashMap<Vertex<T>, ArrayList<Edge<T>>> {
val paths = HashMap<Vertex<T>, ArrayList<Edge<T>>>()
val pathsFromSource = shortestPath(source)
graph.allVertices.forEach {
val path = shortestPath(it, pathsFromSource)
paths[it] = path
}
return paths
}
}
| 0 | Kotlin | 0 | 1 | 815cc480758a6119d60d5e0b5ccd78ee03fdb73e | 2,754 | Set-Of-Useful-Kotlin-Extensions-and-Helpers | MIT License |
src/Day01.kt | kenyee | 573,186,108 | false | {"Kotlin": 57550} |
fun main() { // ktlint-disable filename
fun getTopCalories(input: List<String>): List<Int> {
var elfCal = 0
val calorieSubtotals = mutableListOf<Int>()
for (line in input) {
if (line.isEmpty()) {
calorieSubtotals.add(elfCal)
elfCal = 0
} else {
elfCal += line.toInt()
}
}
// check last elf
if (elfCal > 0) {
calorieSubtotals.add(elfCal)
}
return calorieSubtotals.sortedDescending()
}
fun part1(input: List<String>): Int {
val topCalories = getTopCalories(input)
return topCalories.first()
}
fun part2(input: List<String>): Int {
val topCalories = getTopCalories(input)
return topCalories.take(3).sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
println("test result most calories is: ${part1(testInput)}")
check(part1(testInput) == 24000)
println("test result 3 max calories total is: ${part2(testInput)}")
check(part2(testInput) == 45000)
val input = readInput("Day01_input")
println("Input data max calories is: ${part1(input)}")
println("Input data 3 max calories total is: ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 814f08b314ae0cbf8e5ae842a8ba82ca2171809d | 1,324 | KotlinAdventOfCode2022 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/KnightProbability.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
/**
* 688. Knight Probability in Chessboard
* @see <a href="https://leetcode.com/problems/knight-probability-in-chessboard/">Source</a>
*/
fun interface KnightProbability {
operator fun invoke(n: Int, k: Int, row: Int, column: Int): Double
}
/**
* Approach #1: Dynamic Programming
*/
class KnightProbabilityDP : KnightProbability {
override operator fun invoke(n: Int, k: Int, row: Int, column: Int): Double {
var dp = Array(n) { DoubleArray(n) }
val dr = intArrayOf(2, 2, 1, 1, -1, -1, -2, -2)
val dc = intArrayOf(1, -1, 2, -2, 2, -2, 1, -1)
var k0 = k
dp[row][column] = 1.0
while (k0 > 0) {
val dp2 = Array(n) { DoubleArray(n) }
for (r in 0 until n) {
for (c in 0 until n) {
for (j in 0..7) {
val cr = r + dr[j]
val cc = c + dc[j]
if (cr in 0 until n && 0 <= cc && cc < n) {
dp2[cr][cc] += dp[r][c] / 8.0
}
}
}
}
dp = dp2
k0--
}
var ans = 0.0
for (row0 in dp) {
for (x in row0) {
ans += x
}
}
return ans
}
}
/**
* Approach #2: Matrix Exponentiation
*/
class KnightProbabilityMatrixExpo : KnightProbability {
override operator fun invoke(n: Int, k: Int, row: Int, column: Int): Double {
val dr = intArrayOf(-1, -1, 1, 1, -2, -2, 2, 2)
val dc = intArrayOf(2, -2, 2, -2, 1, -1, 1, -1)
val index = IntArray(n * n)
var t = 0
for (r in 0 until n) {
for (c in 0 until n) {
if (r * n + c == canonical(r, c, n)) {
index[r * n + c] = t
t++
} else {
index[r * n + c] = index[canonical(r, c, n)]
}
}
}
val tArr = Array(t) { DoubleArray(t) }
var curRow = 0
for (r in 0 until n) {
for (c in 0 until n) {
if (r * n + c == canonical(r, c, n)) {
for (j in 0..7) {
val cr = r + dr[j]
val cc = c + dc[j]
if (cr in 0 until n && 0 <= cc && cc < n) {
tArr[curRow][index[canonical(cr, cc, n)]] += FRACTION
}
}
curRow++
}
}
}
val row0 = matrixExpo(tArr, k)[index[row * n + column]]
var ans = 0.0
for (x in row0) {
ans += x
}
return ans
}
private fun canonical(r: Int, c: Int, n: Int): Int {
var r0 = r
var c0 = c
if (2 * r0 > n) {
r0 = n - 1 - r0
}
if (2 * c0 > n) {
c0 = n - 1 - c0
}
if (r0 > c0) {
val t = r0
r0 = c0
c0 = t
}
return r0 * n + c0
}
private fun matrixMult(a: Array<DoubleArray>, b: Array<DoubleArray>): Array<DoubleArray> {
val ans = Array(a.size) { DoubleArray(a.size) }
for (i in a.indices) {
for (j in b.first().indices) {
for (k in b.indices) {
ans[i][j] += a[i][k] * b[k][j]
}
}
}
return ans
}
private fun matrixExpo(a: Array<DoubleArray>, pow: Int): Array<DoubleArray> {
val ans = Array(a.size) { DoubleArray(a.size) }
for (i in a.indices) {
ans[i][i] = 1.0
}
if (pow == 0) return ans
if (pow == 1) return a
if (pow % 2 == 1) {
return matrixMult(matrixExpo(a, pow - 1), a)
}
val b = matrixExpo(a, pow / 2)
return matrixMult(b, b)
}
companion object {
private const val FRACTION = 0.125
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 4,633 | kotlab | Apache License 2.0 |
src/main/kotlin/g0401_0500/s0403_frog_jump/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g0401_0500.s0403_frog_jump
// #Hard #Array #Dynamic_Programming #2022_11_30_Time_240_ms_(100.00%)_Space_37.1_MB_(100.00%)
import java.util.HashMap
import java.util.HashSet
class Solution {
// global hashmap to store visited index -> set of jump lengths from that index
private val visited: HashMap<Int, HashSet<Int>> = HashMap()
fun canCross(stones: IntArray): Boolean {
// a mathematical check before going in the recursion
for (i in 3 until stones.size) {
if (stones[i] > stones[i - 1] * 2) {
return false
}
}
// map of values -> index to make sure we get the next index quickly
val rocks: HashMap<Int, Int> = HashMap()
for (i in stones.indices) {
rocks.put(stones[i], i)
}
return jump(stones, 0, 1, 0, rocks)
}
private fun jump(
stones: IntArray,
index: Int,
jumpLength: Int,
expectedVal: Int,
rocks: Map<Int, Int>
): Boolean {
// overshoot and going backwards not allowed
if (index >= stones.size || jumpLength <= 0) {
return false
}
// reached the last index
if (index == stones.size - 1) {
return expectedVal == stones[index]
}
// check if this index -> jumpLength pair was seen before, otherwise record it
val rememberJumps: HashSet<Int> = visited.getOrDefault(index, HashSet())
if (stones[index] > expectedVal || rememberJumps.contains(jumpLength)) {
return false
}
rememberJumps.add(jumpLength)
visited.put(index, rememberJumps)
// check for jumpLength-1, jumpLength, jumpLength+1 for a new expected value
return (
jump(
stones,
rocks[stones[index] + jumpLength] ?: stones.size,
jumpLength + 1,
stones[index] + jumpLength,
rocks
) ||
jump(
stones,
rocks[stones[index] + jumpLength] ?: stones.size,
jumpLength,
stones[index] + jumpLength,
rocks
) ||
jump(
stones,
rocks[stones[index] + jumpLength] ?: stones.size,
jumpLength - 1,
stones[index] + jumpLength,
rocks
)
)
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 2,504 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/aoc2022/Day25.kt | w8mr | 572,700,604 | false | {"Kotlin": 140954} | package aoc2022
import aoc.parser.followedBy
import aoc.parser.map
import aoc.parser.oneOrMore
import aoc.parser.regex
class Day25 {
val SnafuDigits = "=-012"
data class Snafu(val number: String) {
val SnafuDigits = "=-012"
init {
require(number.all { it in SnafuDigits}) { "number is not valid SNAFU" }
}
fun toLong() =
this.number.reversed().fold(Pair(0L, 1L)) { (acc, m), c ->
Pair(acc + m * (SnafuDigits.indexOf(c) - 2), m * 5)
}.first
}
fun Long.toSnafu() = Snafu(sequence {
var number = this@toSnafu
while (number > 0) {
val digit = number % 5
when {
digit > 2 -> {
number += 5
number /= 5
yield(SnafuDigits[digit.toInt() - 3])
}
else -> {
number /= 5
yield(SnafuDigits[digit.toInt() + 2])
}
}
}
}.joinToString("").reversed())
fun part1(input: String): String {
val parser = oneOrMore(regex("[012=-]+") map (::Snafu) followedBy "\n")
val parsed = parser.parse(input)
val sum = parsed.map(Snafu::toLong).sum()
return sum.toSnafu().number
}
}
| 0 | Kotlin | 0 | 0 | e9bd07770ccf8949f718a02db8d09daf5804273d | 1,327 | aoc-kotlin | Apache License 2.0 |
src/chapter2/section4/ex23_MultiwayHeaps.kt | w1374720640 | 265,536,015 | false | {"Kotlin": 1373556} | package chapter2.section4
import chapter2.getCompareTimes
import chapter2.getDoubleArray
import chapter2.less
import chapter2.section1.cornerCases
import chapter2.section2.getMergeSortComparisonTimes
import chapter2.swap
/**
* 基于完全多叉树的堆排序(区别于完全二叉树)
* 索引从0开始,设多叉树的父节点为k,分叉为t,则子节点为 t*k+1 t*k+2 ... t*k+t
* 设多叉树的子节点为m,则父节点为(m-1)/t
* 设数组大小为N,则最后一个有子节点的父节点为(N-2)/t
*/
fun <T : Comparable<T>> multiwayHeapSort(array: Array<T>, way: Int) {
require(way > 1)
//构造大顶堆
for (i in (array.size - 2) / way downTo 0) {
array.sink(i, array.size - 1, way)
}
//将堆顶数据交换到数组末尾,并对堆顶执行下沉操作
for (i in array.size - 1 downTo 1) {
array.swap(0, i)
array.sink(0, i - 1, way)
}
}
/**
* 指定数组大小的下沉操作
*/
private fun <T : Comparable<T>> Array<T>.sink(k: Int, end: Int, way: Int) {
var i = k
while (i * way + 1 <= end) {
val j = maxIndex(i * way + 1, minOf(end, i * way + way))
if (less(i, j)) {
swap(i, j)
i = j
} else {
break
}
}
}
private fun <T : Comparable<T>> Array<T>.maxIndex(start: Int, end: Int): Int {
var maxIndex = start
for (i in start + 1..end) {
if (less(maxIndex, i)) {
maxIndex = i
}
}
return maxIndex
}
/**
* 在堆排序中使用t向堆的情况下找出使比较次数NlgN的系数最小的t值
*/
fun main() {
//使用7向堆测试排序算法是否正确
cornerCases { multiwayHeapSort(it, 7) }
val size = 10000
repeat(10) {
val way = it + 2
val times = getCompareTimes(getDoubleArray(size)) { array ->
multiwayHeapSort(array, way)
}
println("way=$way times=$times")
}
} | 0 | Kotlin | 1 | 6 | 879885b82ef51d58efe578c9391f04bc54c2531d | 1,955 | Algorithms-4th-Edition-in-Kotlin | MIT License |
2022/src/Day10.kt | Saydemr | 573,086,273 | false | {"Kotlin": 35583, "Python": 3913} | package src
fun main() {
var part2vals = mutableListOf<Int>()
fun part1(input: List<String>): Int {
var register = 1
var registerNext = 0
val values = mutableListOf<Int>()
input.map { it.trim().split(" ") }
.forEach {
register += registerNext
values.add(register)
registerNext = if (it[0].trim() == "addx") it[1].toInt() else 0
if (it[0].trim() == "addx") values.add(register)
}
register += registerNext
values.add(register)
part2vals = values
val sequence = (0..220)
.map { if ((it - 19) % 40 == 0) it+1 else 0 }
return sequence.zip(values)
.sumOf { it.first * it.second }
}
fun part2(input: List<Int>): String {
var resString = ""
var CRTPosition = 0
input.forEach {
if (CRTPosition % 40 == 0) CRTPosition = 0
resString += if (CRTPosition in it-1 until it+2)
"#"
else
"."
CRTPosition++
}
return resString
}
val input = readInput("input10")
println(part1(input))
println(part2(part2vals).chunked(40).joinToString("\n"))
}
| 0 | Kotlin | 0 | 1 | 25b287d90d70951093391e7dcd148ab5174a6fbc | 1,278 | AoC | Apache License 2.0 |
src/Day02.kt | cgeesink | 573,018,348 | false | {"Kotlin": 10745} | fun main() {
fun calculateChoiceScore(myChoice: Char): Int {
val choiceScore = when (myChoice) {
'X' -> 1
'Y' -> 2
'Z' -> 3
else -> 0
}
return choiceScore
}
fun calculateGameScore(opponentChoice: Char, myChoice: Char): Int {
val gameScore = when (opponentChoice) {
'A' -> when (myChoice) {
'X' -> 3
'Y' -> 6
else -> 0
}
'B' -> when (myChoice) {
'Y' -> 3
'Z' -> 6
else -> 0
}
'C' -> when (myChoice) {
'Z' -> 3
'X' -> 6
else -> 0
}
else -> throw NotImplementedError()
}
return gameScore
}
fun part1(input: List<String>): Int {
var score = 0
for (line in input) {
val opponentChoice = line[0]
val myChoice = line[2]
val choiceScore = calculateChoiceScore(myChoice)
val gameScore = calculateGameScore(opponentChoice, myChoice)
score += choiceScore + gameScore
}
return score
}
fun part2(input: List<String>): Int {
var score = 0
for (line in input) {
val opponentChoice = line[0]
val strategyChoice = line[2]
val myChoice = when (strategyChoice) {
'X' -> when (opponentChoice) {
'A' -> 'Z'
'B' -> 'X'
'C' -> 'Y'
else -> throw NotImplementedError()
}
'Y' -> when (opponentChoice) {
'A' -> 'X'
'B' -> 'Y'
'C' -> 'Z'
else -> throw NotImplementedError()
}
'Z' -> when (opponentChoice) {
'A' -> 'Y'
'B' -> 'Z'
'C' -> 'X'
else -> throw NotImplementedError()
}
else -> throw NotImplementedError()
}
val choiceScore = calculateChoiceScore(myChoice)
val gameScore = calculateGameScore(opponentChoice, myChoice)
score += choiceScore + gameScore
}
return score
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 137fb9a9561f5cbc358b7cfbdaf5562c20d6b10d | 2,658 | aoc-2022-in-kotlin | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/SortedSquares.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2020 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import kotlin.math.abs
/**
* 977. Squares of a Sorted Array
* @see <a href="https://leetcode.com/problems/squares-of-a-sorted-array">Source</a>
* Given an array of integers A sorted in non-decreasing order, return an array of the squares of each number,
* also in sorted non-decreasing order.
*/
fun interface SortedSquares {
operator fun invoke(nums: IntArray): IntArray
}
class SortedSquaresTwoPointers : SortedSquares {
override operator fun invoke(nums: IntArray): IntArray {
val n = nums.size
val result = IntArray(n)
var i = 0
var j = n - 1
for (p in n - 1 downTo 0) {
if (abs(nums[i]) > abs(nums[j])) {
result[p] = nums[i] * nums[i]
i++
} else {
result[p] = nums[j] * nums[j]
j--
}
}
return result
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,528 | kotlab | Apache License 2.0 |
solutions/src/Day20.kt | khouari1 | 573,893,634 | false | {"Kotlin": 132605, "HTML": 175} | import java.util.*
fun main() {
fun part1(input: List<String>): Long = mix(input)
fun part2(input: List<String>): Long = mix(input, timesToMix = 10, decryptionKey = 811589153)
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day20_test")
check(part1(testInput) == 3L)
check(part2(testInput) == 1623178306L)
val input = readInput("Day20")
println(part1(input))
println(part2(input))
}
private fun mix(input: List<String>, timesToMix: Int = 1, decryptionKey: Int = 1): Long {
val numbers = input.map { line -> line.toLong() * decryptionKey }
val indexMap = mutableMapOf<Int, Int>()
val numbersCopy = LinkedList<Long>()
numbers.forEachIndexed { index, number ->
indexMap[index] = index
numbersCopy.add(number)
}
for (i in 1..timesToMix) {
numbers.forEachIndexed { index, number ->
val oldIndex = indexMap[index]!!
if (number == 0L) return@forEachIndexed
val tempNewIndex = (oldIndex + number) % (numbers.size - 1)
val newIndex = if (tempNewIndex < 0) {
numbers.size + tempNewIndex - 1
} else {
tempNewIndex
}
if (newIndex.toInt() == oldIndex) return@forEachIndexed
numbersCopy.removeAt(oldIndex)
numbersCopy.add(newIndex.toInt(), number)
// find out which numbers' index has been affected by the move
// update their index
if (newIndex > oldIndex) {
// moved right
// everything before has been shifted to the left
for (i in 0 until indexMap.size) {
val currentIndex = indexMap[i]!!
if (currentIndex in oldIndex + 1..newIndex) {
indexMap[i] = indexMap[i]!! - 1
}
}
} else {
// moved left
// everything after has been shifted to the right
for (i in 0 until indexMap.size) {
val currentIndex = indexMap[i]!!
if (currentIndex in newIndex until oldIndex) {
indexMap[i] = indexMap[i]!! + 1
}
}
}
indexMap[index] = newIndex.toInt()
}
}
val offsetIndex = numbersCopy.indexOf(0)
val oneThousandth = numbersCopy[(1000 + offsetIndex) % numbers.size]
val twoThousandth = numbersCopy[(2000 + offsetIndex) % numbers.size]
val threeThousandth = numbersCopy[(3000 + offsetIndex) % numbers.size]
return oneThousandth + twoThousandth + threeThousandth
}
| 0 | Kotlin | 0 | 1 | b00ece4a569561eb7c3ca55edee2496505c0e465 | 2,711 | advent-of-code-22 | Apache License 2.0 |
src/main/kotlin/me/peckb/aoc/_2015/calendar/day15/Day15.kt | peckb1 | 433,943,215 | false | {"Kotlin": 956135} | package me.peckb.aoc._2015.calendar.day15
import me.peckb.aoc.generators.InputGenerator.InputGeneratorFactory
import javax.inject.Inject
import kotlin.math.max
typealias Counts = List<Int>
class Day15 @Inject constructor(private val generatorFactory: InputGeneratorFactory) {
fun partOne(filename: String) = generatorFactory.forFile(filename).readAs(::ingredient) { input ->
val ingredients = input.toList()
findHighestTotal(ingredients).first
}
fun partTwo(filename: String) = generatorFactory.forFile(filename).readAs(::ingredient) { input ->
val ingredients = input.toList()
val lowestCalorieIngredient = ingredients.minByOrNull { it.calories }!!
val perfectCookieOptions: MutableList<Pair<Long, Counts>> = mutableListOf()
var counts = findHighestTotal(ingredients).second
var calorieCount = calculateCalories(counts, ingredients)
// there is a VERY GOOD chance that our bes cost cookie has more calories than our wanted calories
// the problem is actually setup just in such a way
// so while we have not found the perfect cookie yet, keep lower the cost until we do
while (calorieCount != WANTED_CALORIES) {
findPerfectCookieCount(counts, ingredients)?.let {
perfectCookieOptions.add(calculateTotal(it, ingredients) to it)
}
counts = if (calorieCount > WANTED_CALORIES) {
// our calorie count is too high, so we need to swap out a high calorie count item
// with an ingredient that has lower calories, but we only want to swap one at a time
// finding the highest total cost each time we have to lower our calories
lowerCalorieCount(counts, ingredients, lowestCalorieIngredient).value.second
} else {
// once we've gone under our wanted calories, we can look at all of the perfect cookie
// options we found, and the perfect cookie option with the highest total is the winner
perfectCookieOptions.maxByOrNull { it.first }!!.second
}
calorieCount = calculateCalories(counts, ingredients)
}
calculateTotal(counts, ingredients)
}
private fun findHighestTotal(ingredients: List<Ingredient>) : Pair<Long, Counts> {
var counts = ingredients.map { 1 }
while (counts.sum() < INGREDIENT_TOTAL) {
val nextIncrements = counts.indices.map {
counts.mapIndexed { i, c -> if (i == it) c + 1 else c }
}
counts = nextIncrements.maxByOrNull { max(calculateTotal(it, ingredients), 0) }!!
}
return calculateTotal(counts, ingredients) to counts
}
private fun calculateTotal(counts: Counts, ingredients: List<Ingredient>): Long {
val totals = counts.zip(ingredients).map { (count, ingredient) ->
CookieTotal(
ingredient.capacity * count,
ingredient.durability * count,
ingredient.flavor * count,
ingredient.texture * count,
)
}
val cookieTotal = totals.fold(CookieTotal(0, 0, 0, 0)) { acc, next -> acc + next }
return cookieTotal.capacity * cookieTotal.durability * cookieTotal.flavor * cookieTotal.texture
}
private fun calculateCalories(counts: Counts, ingredients: List<Ingredient>): Long {
return counts.zip(ingredients).sumOf { (count, ingredient) ->
ingredient.calories * count
}
}
private fun findPerfectCookieCount(counts: Counts, ingredients: List<Ingredient>): Counts? {
val possiblePerfectCookieCounts = counts.indices.flatMap { indexToSwapOut ->
counts.indices.mapNotNull { indexToSwapIn ->
if (indexToSwapOut != indexToSwapIn) {
counts.mapIndexed { i, c ->
when (i) {
indexToSwapOut -> c - 1
indexToSwapIn -> c + 1
else -> c
}
}
} else {
null
}
}
}
return possiblePerfectCookieCounts.firstOrNull { calculateCalories(it, ingredients) == WANTED_CALORIES }
}
private fun lowerCalorieCount(counts: Counts, ingredients: List<Ingredient>, lowestCalorieIngredient: Ingredient): IndexedValue<Pair<Int, Counts>> {
// find the x highest calorie counts
val highestCalorieIndex = ingredients.indices.filterNot { ingredients[it] == lowestCalorieIngredient }
val possibleRemovals = highestCalorieIndex.map { index ->
index to counts.mapIndexed { i, c -> if (i == index) c - 1 else c }
}
// find out which removal has the highest total cost
// remove one from that count
val afterRemovals = possibleRemovals.maxByOrNull {
max(calculateTotal(it.second, ingredients), 0)
}!!
val ingredientRemoved = ingredients[afterRemovals.first]
// find calorie counts less than the one we just removed
val addBackIngredientIndices = ingredients.indices.filterNot { index ->
ingredients[index].calories >= ingredientRemoved.calories
}
val possibleAddBacks = addBackIngredientIndices.map { index ->
index to afterRemovals.second.mapIndexed { i, c -> if (i == index) c + 1 else c }
}
// find out which addition has the highest total cost
// add that one back in
return possibleAddBacks.withIndex().maxByOrNull {
max(calculateTotal(it.value.second, ingredients), 0)
}!!
}
private fun ingredient(line: String): Ingredient {
// Butterscotch: capacity -1, durability -2, flavor 6, texture 3, calories 8
val (name, data) = line.split(": ")
val (cap, dur, fla, tex, cal) = data.split(", ").map { it.split(" ").last() }
return Ingredient(name, cap.toLong(), dur.toLong(), fla.toLong(), tex.toLong(), cal.toLong())
}
data class Ingredient(val name: String, val capacity: Long, val durability: Long, val flavor: Long, val texture: Long, val calories: Long)
data class CookieTotal(val capacity: Long, val durability: Long, val flavor: Long, val texture: Long) {
infix operator fun plus(other: CookieTotal) = CookieTotal(
capacity + other.capacity,
durability + other.durability,
flavor + other.flavor,
texture + other.texture,
)
}
companion object {
const val INGREDIENT_TOTAL = 100
const val WANTED_CALORIES = 500L
}
}
| 0 | Kotlin | 1 | 3 | 2625719b657eb22c83af95abfb25eb275dbfee6a | 6,111 | advent-of-code | MIT License |
2021/src/day18/day18.kt | scrubskip | 160,313,272 | false | {"Kotlin": 198319, "Python": 114888, "Dart": 86314} | package day18
import java.io.File
import kotlin.math.ceil
fun main() {
val input = File("src/day18", "day18input.txt").readLines().map { Snailfish.parseFish(it) }
val sum = input.reduce { acc: Snailfish, snailfish: Snailfish -> acc + snailfish }
println(sum.getMagnitude())
println(findGreatestMagnitudePair(input))
}
fun findGreatestMagnitudePair(input: List<Snailfish>): Long {
var greatestMag: Long = 0
for (fish in input) {
for (otherFish in input) {
if (fish != otherFish) {
val mag = (fish + otherFish).getMagnitude()
if (mag > greatestMag) {
// println("found max $fish $otherFish $mag")
greatestMag = mag
}
}
}
}
return greatestMag
}
open class Snailfish() {
var left: Snailfish? = null
var right: Snailfish? = null
var parent: Snailfish? = null
override fun toString(): String {
return "[$left,$right]"
}
operator fun plus(other: Snailfish): Snailfish {
val newFish = Snailfish()
newFish.left = this.copy()
newFish.left?.parent = newFish
newFish.right = other.copy()
newFish.right?.parent = newFish
newFish.reduce()
return newFish
}
fun reduce() {
var explode = getFirstDepthGreaterThan(4)
var split = getFirstChildGreaterThanEqualTo(10)
do {
explode?.parent?.explodeChild(explode)
explode = getFirstDepthGreaterThan(4)
if (explode != null) {
continue
}
split = getFirstChildGreaterThanEqualTo(10)
if (split != null) split?.parent?.splitChild(split)
explode = getFirstDepthGreaterThan(4)
} while (explode != null || split != null)
}
private fun splitChild(split: SnailfishValue) {
//println("splitting $split")
val newFish = Snailfish()
newFish.left = SnailfishValue(split.number / 2)
newFish.left?.parent = newFish
newFish.right = SnailfishValue(ceil(split.number.toDouble() / 2).toLong())
newFish.right?.parent = newFish
newFish.parent = this
if (split == left) {
left = newFish
} else {
right = newFish
}
}
private fun explodeChild(snailfish: Snailfish) {
//println("exploding $snailfish")
val leftValue = (snailfish.left as SnailfishValue).number
val rightValue = (snailfish.right as SnailfishValue).number
val isLeft = snailfish == left
// find leftmost value
val firstLeftValue = snailfish.getFirstLeft()
firstLeftValue?.let {
it.number = it.number + leftValue
}
val firstRightValue = snailfish.getFirstRight()
firstRightValue?.let {
it.number = it.number + rightValue
}
val newValue = SnailfishValue(0)
newValue.parent = this
if (isLeft) {
left = newValue
} else {
right = newValue
}
}
fun getFirstLeft(): SnailfishValue? {
var node = parent
var currentChild = this
while (node != null && node.left == currentChild) {
currentChild = node
node = node.parent
}
if (node != null) {
return node.left?.getRightmostValue()
}
return null
}
fun getFirstRight(): SnailfishValue? {
var node = parent
var currentChild = this
while (node != null && node.right == currentChild) {
currentChild = node
node = node.parent
}
if (node != null) {
return node.right?.getLeftmostValue()
}
return null
}
fun getRightmostValue(): SnailfishValue? {
if (this is SnailfishValue) {
return this
} else if (right != null) {
return right?.getRightmostValue()
}
return null
}
fun getLeftmostValue(): SnailfishValue? {
if (this is SnailfishValue) {
return this
} else if (left != null) {
return left?.getLeftmostValue()
}
return null
}
fun getFirstDepthGreaterThan(maxDepth: Int, currentDepth: Int = 0): Snailfish? {
if (left is SnailfishValue && right is SnailfishValue) {
if (currentDepth >= maxDepth) {
return this
}
}
if (left != null) {
val foundLeft = left?.getFirstDepthGreaterThan(maxDepth, currentDepth + 1)
if (foundLeft != null) {
return foundLeft
}
}
if (right != null) {
val foundRight = right?.getFirstDepthGreaterThan(maxDepth, currentDepth + 1)
if (foundRight != null) {
return foundRight
}
}
return null
}
fun getFirstChildGreaterThanEqualTo(value: Int): SnailfishValue? {
if (this is SnailfishValue && this.number >= value) {
return this
}
if (left != null) {
val foundLeft = left?.getFirstChildGreaterThanEqualTo(value)
if (foundLeft != null) {
return foundLeft
}
}
if (right != null) {
val foundRight = right?.getFirstChildGreaterThanEqualTo(value)
if (foundRight != null) {
return foundRight
}
}
return null
}
open fun getMagnitude(): Long {
return (left?.getMagnitude() ?: 0).times(3) + (right?.getMagnitude() ?: 0).times(2)
}
private fun copy(): Snailfish {
return parseFish(toString())
}
companion object {
fun parseFish(input: String): Snailfish {
return parseFishInner(input, 0).first
}
private fun parseFishInner(input: String, startIndex: Int): Pair<Snailfish, Int> {
var index = startIndex
var currentFish = Snailfish()
while (index < input.length) {
if (input[index] == '[') {
with(parseFishInner(input, index + 1)) {
currentFish.left = first
first.parent = currentFish
index = second
}
} else if (input[index] == ',') {
with(parseFishInner(input, index + 1)) {
currentFish.right = first
first.parent = currentFish
index = second
}
} else if (input[index].isDigit()) {
// find next non digit
val nextIndex = input.indexOfAny(listOf(",", "]"), index)
require(nextIndex != -1)
val valueFish = SnailfishValue(input.substring(index, nextIndex).toLong())
return Pair(valueFish, nextIndex)
} else if (input[index] == ']') {
return Pair(currentFish, index + 1)
} else {
throw Exception("invalid character ${input[index]}")
}
}
return Pair(currentFish, index)
}
}
}
class SnailfishValue(var number: Long) : Snailfish() {
override fun toString(): String {
return number.toString()
}
override fun getMagnitude(): Long {
return number
}
} | 0 | Kotlin | 0 | 0 | a5b7f69b43ad02b9356d19c15ce478866e6c38a1 | 7,507 | adventofcode | Apache License 2.0 |
kotlin/2022/day02/Day02.kt | nathanjent | 48,783,324 | false | {"Rust": 147170, "Go": 52936, "Kotlin": 49570, "Shell": 966} | class Day02 {
enum class Result(val score: Int) {
Win(6),
Lose(0),
Draw(3),
}
enum class Shape(val score: Int) {
Rock(1),
Paper(2),
Scissors(3),
}
fun part1(input: Iterable<String>): Int {
return input
.asSequence()
.filter { it.isNotBlank() }
.map { it.split(" ") }
.map { getRoundPart1(getShape(it[0]), getShape(it[1])) }
.map { it.first.score + it.second.score }
.sum()
}
fun part2(input: Iterable<String>): Int {
return input
.asSequence()
.filter { it.isNotBlank() }
.map { it.split(" ") }
.map { getRoundPart2(getShape(it[0]), getResult(it[1])) }
.map { it.first.score + it.second.score }
.sum()
}
private fun getRoundPart1(opponentShape: Shape, myShape: Shape): Pair<Result, Shape> {
return when {
opponentShape == Shape.Rock && myShape == Shape.Paper -> Pair(Result.Win, myShape)
opponentShape == Shape.Paper && myShape == Shape.Scissors -> Pair(Result.Win, myShape)
opponentShape == Shape.Scissors && myShape == Shape.Rock -> Pair(Result.Win, myShape)
opponentShape == Shape.Rock && myShape == Shape.Rock -> Pair(Result.Draw, myShape)
opponentShape == Shape.Paper && myShape == Shape.Paper -> Pair(Result.Draw, myShape)
opponentShape == Shape.Scissors && myShape == Shape.Scissors -> Pair(Result.Draw, myShape)
else -> Pair(Result.Lose, myShape)
}
}
private fun getRoundPart2(opponentShape: Shape, result: Result): Pair<Result, Shape> {
return when {
opponentShape == Shape.Rock && result == Result.Win -> Pair(result, Shape.Paper)
opponentShape == Shape.Paper && result == Result.Win -> Pair(result, Shape.Scissors)
opponentShape == Shape.Scissors && result == Result.Win -> Pair(result, Shape.Rock)
opponentShape == Shape.Rock && result == Result.Lose -> Pair(result, Shape.Scissors)
opponentShape == Shape.Paper && result == Result.Lose -> Pair(result, Shape.Rock)
opponentShape == Shape.Scissors && result == Result.Lose -> Pair(result, Shape.Paper)
opponentShape == Shape.Rock && result == Result.Draw -> Pair(result, Shape.Rock)
opponentShape == Shape.Paper && result == Result.Draw -> Pair(result, Shape.Paper)
opponentShape == Shape.Scissors && result == Result.Draw -> Pair(result, Shape.Scissors)
else -> throw RuntimeException("Unknown round result")
}
}
private fun getShape(shape: String): Shape {
return when (shape.trim()) {
"A", "X" -> Shape.Rock
"B", "Y" -> Shape.Paper
"C", "Z" -> Shape.Scissors
else -> throw RuntimeException("Unknown shape input $shape")
}
}
private fun getResult(result: String): Result {
return when (result.trim()) {
"X" -> Result.Lose
"Y" -> Result.Draw
"Z" -> Result.Win
else -> throw RuntimeException("Unknown result input $result")
}
}
} | 0 | Rust | 0 | 0 | 7e1d66d2176beeecaac5c3dde94dccdb6cfeddcf | 2,956 | adventofcode | MIT License |
kotlin/src/katas/kotlin/leetcode/bst_vertical_traversal/VerticalTraversal.kt | dkandalov | 2,517,870 | false | {"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221} | package katas.kotlin.leetcode.bst_vertical_traversal
import org.junit.Test
import java.util.*
import kotlin.collections.ArrayList
class VerticalTraversalTests {
@Test fun `vertical order traversal`() {
require(verticalTraversal(Node(1)) == listOf(listOf(1)))
val tree = Node(3,
Node(9),
Node(20, Node(15), Node(7))
)
require(
verticalTraversal(tree) == listOf(
listOf(9), listOf(3, 15), listOf(20), listOf(7))
)
val tree2 = Node(1,
Node(2, Node(4), Node(5)),
Node(3, Node(6), Node(7))
)
require(
verticalTraversal(tree2) == listOf(
listOf(4), listOf(2), listOf(1, 5, 6), listOf(3), listOf(7))
)
}
}
private fun verticalTraversal(root: Node): List<List<Int>> {
val valuesByColumn = TreeMap<Int, ArrayList<Int>>()
root.traverse { node, column ->
val values = valuesByColumn.getOrPut(column, { ArrayList() })
values.add(node.value)
}
return valuesByColumn.values.toList()
}
private fun Node.traverse(column: Int = 0, f: (Node, Int) -> Unit) {
f(this, column)
left?.traverse(column - 1, f)
right?.traverse(column + 1, f)
}
private data class Node(
val value: Int,
val left: Node? = null,
val right: Node? = null
)
| 7 | Roff | 3 | 5 | 0f169804fae2984b1a78fc25da2d7157a8c7a7be | 1,357 | katas | The Unlicense |
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[43]字符串相乘.kt | maoqitian | 175,940,000 | false | {"Kotlin": 354268, "Java": 297740, "C++": 634} | import java.lang.StringBuilder
//给定两个以字符串形式表示的非负整数 num1 和 num2,返回 num1 和 num2 的乘积,它们的乘积也表示为字符串形式。
//
// 示例 1:
//
// 输入: num1 = "2", num2 = "3"
//输出: "6"
//
// 示例 2:
//
// 输入: num1 = "123", num2 = "456"
//输出: "56088"
//
// 说明:
//
//
// num1 和 num2 的长度小于110。
// num1 和 num2 只包含数字 0-9。
// num1 和 num2 均不以零开头,除非是数字 0 本身。
// 不能使用任何标准库的大数类型(比如 BigInteger)或直接将输入转换为整数来处理。
//
// Related Topics 数学 字符串
// 👍 653 👎 0
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
fun multiply(num1: String, num2: String): String {
//使用数组保存字符串每一位 最后拼接
// 时间复杂度 O(n*m) n m 为两个数组的长度
var res = IntArray(num1.length + num2.length)
for (i in num1.length-1 downTo 0){
for (j in num2.length-1 downTo 0){
//计算乘积
var currMult = (num1[i] -'0') * (num2[j] - '0')
//当前所在位置
var p1 = i+j
var p2 = i+j+1
var sum = currMult + res[p2]
//放置对应元素
res[p1] += sum / 10
res[p2] = sum % 10
}
}
//拼接结果
var stringBuilder = StringBuilder()
res.forEach {
if(!(stringBuilder.isEmpty() && it == 0)){
stringBuilder.append(it)
}
}
return if (stringBuilder.isEmpty()) "0" else stringBuilder.toString()
}
}
//leetcode submit region end(Prohibit modification and deletion)
| 0 | Kotlin | 0 | 1 | 8a85996352a88bb9a8a6a2712dce3eac2e1c3463 | 1,815 | MyLeetCode | Apache License 2.0 |
solutions/src/Day19.kt | khouari1 | 573,893,634 | false | {"Kotlin": 132605, "HTML": 175} | import java.util.*
fun main() {
fun part1(input: List<String>): Int =
getBlueprintsFrom(input)
.sumOf { blueprint ->
val robots = listOf(Robot.OreRobot)
val geodes = getHighestGeodeCount(blueprint, robots, 24)
blueprint.id * geodes
}
fun part2(input: List<String>): Int =
getBlueprintsFrom(input)
.take(3)
.map { blueprint ->
val robots = listOf(Robot.OreRobot)
val geodes = getHighestGeodeCount(blueprint, robots, 32)
geodes
}.reduce { acc, i -> acc * i }
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day19_test")
check(part1(testInput) == 33)
check(part2(testInput) == 3472)
val input = readInput("Day19")
println(part1(input))
println(part2(input))
}
private fun getHighestGeodeCount(blueprint: Blueprint, robots: List<Robot>, totalMinutes: Int): Int {
val stack = Stack<State>()
stack.add(State(RobotFactory(blueprint), robots, 1))
val maxOreRequiredPerTurn = maxOf(
blueprint.oreRobotCost.ore,
blueprint.clayRobotCost.ore,
blueprint.obsidianRobotCost.ore,
blueprint.geodeRobotCost.ore,
)
val maxClayRequiredPerTurn = maxOf(
blueprint.oreRobotCost.clay,
blueprint.clayRobotCost.clay,
blueprint.obsidianRobotCost.clay,
blueprint.geodeRobotCost.clay,
)
val maxObsidianRequiredPerTurn = maxOf(
blueprint.oreRobotCost.obsidian,
blueprint.clayRobotCost.obsidian,
blueprint.obsidianRobotCost.obsidian,
blueprint.geodeRobotCost.obsidian,
)
var highestGeodes = 0
// DFS to find highest geode count
while (stack.isNotEmpty()) {
val (robotFactory, robots, minute, skippedOre, skippedClay, skippedObsidian) = stack.pop()
val oreRobotsCount = robots.filterIsInstance<Robot.OreRobot>().count()
val clayRobotsCount = robots.filterIsInstance<Robot.ClayRobot>().count()
val obsidianRobotsCount = robots.filterIsInstance<Robot.ObsidianRobot>().count()
if (minute > totalMinutes) {
if (robotFactory.materials.geodes > highestGeodes) {
highestGeodes = robotFactory.materials.geodes
}
continue
}
val newMaterials = perTurnMaterialsCollected(robots)
// If can create geode robot then just do that
if (robotFactory.canCreateRobot(Robot.GeodeRobot)) {
val newFactory = robotFactory.copy()
newFactory.createRobot(Robot.GeodeRobot)
stack.add(State(newFactory, robots + Robot.GeodeRobot, minute + 1))
newFactory.addMaterials(newMaterials)
} else {
// If a robot could have been built but was skipped then don't build it until a different robot has been built
// Also if the number of a certain robot means the max required material is available each turn then no need to build more
val canCreateObsidian =
robotFactory.canCreateRobot(Robot.ObsidianRobot) && obsidianRobotsCount < maxObsidianRequiredPerTurn
if (canCreateObsidian && !skippedObsidian) {
val newFactory = robotFactory.copy()
newFactory.createRobot(Robot.ObsidianRobot)
stack.add(State(newFactory, robots + Robot.ObsidianRobot, minute + 1))
newFactory.addMaterials(newMaterials)
}
val canCreateClay =
robotFactory.canCreateRobot(Robot.ClayRobot) && clayRobotsCount < maxClayRequiredPerTurn
if (canCreateClay && !skippedClay) {
val newFactory = robotFactory.copy()
newFactory.createRobot(Robot.ClayRobot)
stack.add(State(newFactory, robots + Robot.ClayRobot, minute + 1))
newFactory.addMaterials(newMaterials)
}
val canCreateOre = robotFactory.canCreateRobot(Robot.OreRobot) && oreRobotsCount < maxOreRequiredPerTurn
if (canCreateOre && !skippedOre) {
val newFactory = robotFactory.copy()
newFactory.createRobot(Robot.OreRobot)
stack.add(State(newFactory, robots + Robot.OreRobot, minute + 1))
newFactory.addMaterials(newMaterials)
}
val newFactory = robotFactory.copy()
stack.add(State(newFactory, robots, minute + 1, canCreateOre, canCreateClay, canCreateObsidian))
newFactory.addMaterials(newMaterials)
}
}
return highestGeodes
}
private fun perTurnMaterialsCollected(robots: List<Robot>): Materials {
return if (robots.isEmpty()) {
Materials()
} else {
robots.map {
when (it) {
is Robot.ClayRobot -> Materials(clay = 1)
is Robot.GeodeRobot -> Materials(geodes = 1)
is Robot.ObsidianRobot -> Materials(obsidian = 1)
is Robot.OreRobot -> Materials(ore = 1)
}
}.reduce { acc, materials -> acc + materials }
}
}
data class State(
val robotFactory: RobotFactory,
val robots: List<Robot>,
val minute: Int,
val skippedOre: Boolean = false,
val skippedClay: Boolean = false,
val skippedObsidian: Boolean = false,
)
data class RobotFactory(
private val blueprint: Blueprint,
var materials: Materials = Materials(),
) {
fun addMaterials(materials: Materials) {
this.materials = this.materials + materials
}
fun canCreateRobot(robot: Robot): Boolean {
val (ore, clay, obsidian) = when (robot) {
Robot.ClayRobot -> blueprint.clayRobotCost
Robot.GeodeRobot -> blueprint.geodeRobotCost
Robot.ObsidianRobot -> blueprint.obsidianRobotCost
Robot.OreRobot -> blueprint.oreRobotCost
}
return materials.clay >= clay &&
materials.ore >= ore &&
materials.obsidian >= obsidian
}
fun createRobot(robot: Robot) {
materials -= when (robot) {
Robot.ClayRobot -> blueprint.clayRobotCost
Robot.GeodeRobot -> blueprint.geodeRobotCost
Robot.ObsidianRobot -> blueprint.obsidianRobotCost
Robot.OreRobot -> blueprint.oreRobotCost
}
}
}
data class Blueprint(
val id: Int,
val oreRobotCost: MaterialCost,
val clayRobotCost: MaterialCost,
val obsidianRobotCost: MaterialCost,
val geodeRobotCost: MaterialCost,
)
data class MaterialCost(
val ore: Int,
val clay: Int = 0,
val obsidian: Int = 0,
)
data class Materials(
val ore: Int = 0,
val clay: Int = 0,
val obsidian: Int = 0,
val geodes: Int = 0,
) {
operator fun plus(materials: Materials): Materials {
return Materials(
ore = this.ore + materials.ore,
clay = this.clay + materials.clay,
obsidian = this.obsidian + materials.obsidian,
geodes = this.geodes + materials.geodes,
)
}
operator fun minus(materials: MaterialCost): Materials {
return Materials(
ore = this.ore - materials.ore,
clay = this.clay - materials.clay,
obsidian = this.obsidian - materials.obsidian,
geodes = geodes,
)
}
}
sealed class Robot {
object OreRobot : Robot()
object ClayRobot : Robot()
object ObsidianRobot : Robot()
object GeodeRobot : Robot()
}
private fun getBlueprintsFrom(input: List<String>): List<Blueprint> {
return input.map { line ->
val split = line.split(" ")
val blueprintId = split[1].dropLast(1).toInt()
val oreRobotCost = MaterialCost(ore = split[6].toInt())
val clayRobotCost = MaterialCost(ore = split[12].toInt())
val obsidianRobotCost = MaterialCost(ore = split[18].toInt(), clay = split[21].toInt())
val geodeRobotCost = MaterialCost(ore = split[27].toInt(), obsidian = split[30].toInt())
Blueprint(
id = blueprintId,
oreRobotCost = oreRobotCost,
clayRobotCost = clayRobotCost,
obsidianRobotCost = obsidianRobotCost,
geodeRobotCost = geodeRobotCost,
)
}
} | 0 | Kotlin | 0 | 1 | b00ece4a569561eb7c3ca55edee2496505c0e465 | 8,314 | advent-of-code-22 | Apache License 2.0 |
src/main/kotlin/nl/kelpin/fleur/advent2018/Day17.kt | fdlk | 159,925,533 | false | null | package nl.kelpin.fleur.advent2018
import kotlin.math.max
import kotlin.math.min
sealed class Soil {
abstract fun contains(point: Point): Boolean
}
data class Vertical(val x: Int, val yRange: IntRange) : Soil() {
companion object {
private val re = Regex("""x=(\d+), y=(\d+)\.\.(\d+)""")
fun of(line: String): Vertical? {
val (x, yFrom, yTo) = re.matchEntire(line)?.destructured ?: return null
return Vertical(x.toInt(), yFrom.toInt()..yTo.toInt())
}
}
override fun contains(point: Point): Boolean = x == point.x && yRange.contains(point.y)
}
data class Horizontal(val xRange: IntRange, val y: Int) : Soil() {
companion object {
private val re = Regex("""y=(\d+), x=(\d+)\.\.(\d+)""")
fun of(line: String): Horizontal? {
val (y, xFrom, xTo) = re.matchEntire(line)?.destructured ?: return null
return Horizontal(xFrom.toInt()..xTo.toInt(), y.toInt())
}
}
override fun contains(point: Point): Boolean = y == point.y && xRange.contains(point.x)
}
class Day17(input: List<String>) {
val horizontals: List<Horizontal> = input.mapNotNull { Horizontal.of(it) }.sortedBy { it.y }
private val verticals: List<Vertical> = input.mapNotNull { Vertical.of(it) }.sortedBy { it.x }
private val clays: Set<Soil> = horizontals.union(verticals)
private val waters = mutableSetOf<Horizontal>()
private val flowingWaters = mutableSetOf<Horizontal>()
private val taps = mutableSetOf(Point(500, 0))
private val inactiveTaps = mutableSetOf<Point>()
private val spouts = mutableSetOf<Vertical>()
private val xRange = horizontals.map { it.xRange.start }.min()!! - 1..horizontals.map { it.xRange.endInclusive }.max()!! + 1
private val yRange = verticals.map { it.yRange.start }.min()!!..verticals.map { it.yRange.endInclusive }.max()!!
fun charFor(point: Point): Char = when {
taps.contains(point) -> '*'
clays.any { it.contains(point) } -> '#'
spouts.any { it.contains(point) } -> '|'
waters.any { it.contains(point) } -> '~'
flowingWaters.any { it.contains(point) } -> '-'
else -> ' '
}
fun map(): String = yRange.joinToString("\n") { y -> xRange.map { x -> Point(x, y) }.map(::charFor).joinToString("") }
private fun isSupported(point: Point): Boolean = clays.union(waters).any { it.contains(point.move(Down)) }
private fun isClay(point: Point): Boolean = clays.any { it.contains(point) }
// the point where a tap hits a supporting surface
data class Pok(val point: Point, val leftUnsupported: Int, val leftNoClay: Int, val rightUnsupported: Int, val rightNoClay: Int) {
fun supportedWater(): Horizontal? {
if (leftNoClay > leftUnsupported && rightNoClay < rightUnsupported) {
return Horizontal(leftNoClay + 1 until rightNoClay, point.y)
}
return null
}
fun flowingWater(): Horizontal = Horizontal(max(leftUnsupported, leftNoClay + 1)..min(rightUnsupported, rightNoClay - 1), point.y)
fun taps(): List<Point> {
val result = mutableListOf<Point>()
if (leftNoClay <= leftUnsupported) {
result.add(Point(leftUnsupported, point.y))
}
if (rightNoClay >= rightUnsupported) {
result.add(Point(rightUnsupported, point.y))
}
return result
}
}
private fun pok(tap: Point): Pok? {
val pok = (tap.y..yRange.endInclusive)
.map { tap.copy(y = it) }
.find(::isSupported) ?: return null
val toTheLeft = (pok.x downTo xRange.start).map { pok.copy(x = it) }
val leftUnsupported = toTheLeft.find { !isSupported(it) }!!.x
val leftNoClay = toTheLeft.find { isClay(it) }?.x ?: xRange.start
val toTheRight = (pok.x..xRange.endInclusive).map { pok.copy(x = it) }
val rightUnsupported = toTheRight.find { !isSupported(it) }!!.x
val rightNoClay = toTheRight.find { isClay(it) }?.x ?: xRange.endInclusive
return Pok(pok, leftUnsupported, leftNoClay, rightUnsupported, rightNoClay)
}
fun next() {
taps.toList().forEach { tap ->
val pok = pok(tap)
if (pok == null) {
taps.remove(tap)
inactiveTaps.add(tap)
return
}
val supportedWater = pok.supportedWater()
if (supportedWater != null) {
waters.add(supportedWater)
taps.removeAll { supportedWater.contains(it) }
inactiveTaps.removeAll { supportedWater.contains(it) }
// reactivate the inactive taps above
taps.addAll(inactiveTaps.filter { supportedWater.contains(it.copy(y = supportedWater.y)) })
} else {
taps.addAll(pok.taps())
taps.remove(tap)
inactiveTaps.add(tap)
}
}
}
private fun addFlowingWaters() {
for (tap in inactiveTaps) {
val pok = pok(tap)
spouts.add(Vertical(tap.x, tap.y until (pok?.point?.y ?: yRange.endInclusive+1)))
if (pok != null) {
flowingWaters.add(pok.flowingWater())
}
}
}
fun bothParts(): Pair<Int, Int> {
repeat(10_000) {
next()
}
addFlowingWaters()
val map = map()
println(map)
return map.count { "~*|-".contains(it) } to map.count { it == '~' }
}
} | 0 | Kotlin | 0 | 3 | a089dbae93ee520bf7a8861c9f90731eabd6eba3 | 5,581 | advent-2018 | MIT License |
src/Day09.kt | robinpokorny | 572,434,148 | false | {"Kotlin": 38009} | import kotlin.math.sign
private fun parse(input: List<String>): List<Char> = input
.flatMap {
val (dir, steps) = it.split(" ")
List(steps.toInt()) { dir.single() }
}
private fun moveHead(head: Point, move: Char): Point = when (move) {
'R' -> head.copy(x = head.x + 1)
'L' -> head.copy(x = head.x - 1)
'U' -> head.copy(y = head.y - 1)
'D' -> head.copy(y = head.y + 1)
else -> head // Never
}
private fun moveTail(tail: Point, head: Point): Point {
val dx = head.x - tail.x
val dy = head.y - tail.y
val touching = dx in -1..1 && dy in -1..1
if (touching) return tail
return Point(tail.x + dx.sign, tail.y + dy.sign)
}
private fun countTailPositions(motions: List<Char>): Int = motions
.scan(Point(0, 0), ::moveHead)
.scan(Point(0, 0), ::moveTail)
.toSet()
.size
private fun count10TailPositions(motions: List<Char>): Int = motions
.scan(Point(0, 0), ::moveHead)
.scan(Point(0, 0), ::moveTail)
.scan(Point(0, 0), ::moveTail)
.scan(Point(0, 0), ::moveTail)
.scan(Point(0, 0), ::moveTail)
.scan(Point(0, 0), ::moveTail)
.scan(Point(0, 0), ::moveTail)
.scan(Point(0, 0), ::moveTail)
.scan(Point(0, 0), ::moveTail)
.scan(Point(0, 0), ::moveTail)
.toSet()
.size
fun main() {
val input = parse(readDayInput(9))
val testInput = parse(rawTestInput)
val testInput2 = parse(rawTestInput2)
// PART 1
assertEquals(countTailPositions(testInput), 13)
println("Part1: ${countTailPositions(input)}")
// PART 2
assertEquals(count10TailPositions(testInput2), 36)
println("Part2: ${count10TailPositions(input)}")
}
private val rawTestInput = """
R 4
U 4
L 3
D 1
R 4
D 1
L 5
R 2
""".trimIndent().lines()
private val rawTestInput2 = """
R 5
U 8
L 8
D 3
R 17
D 10
L 25
U 20
""".trimIndent().lines() | 0 | Kotlin | 0 | 2 | 56a108aaf90b98030a7d7165d55d74d2aff22ecc | 1,914 | advent-of-code-2022 | MIT License |
lib/src/main/kotlin/de/linkel/aoc/utils/rangeset/LongRangeSet.kt | norganos | 726,350,504 | false | {"Kotlin": 162220} | package de.linkel.aoc.utils.rangeset
import de.linkel.aoc.utils.iterables.intersect
import de.linkel.aoc.utils.iterables.intersects
class LongRangeSetFactory: RangeFactory<Long, LongRange, Long> {
companion object {
val INSTANCE = LongRangeSetFactory()
}
override fun build(start: Long, endInclusive: Long) = LongRange(start, endInclusive)
override fun incr(a: Long) = a +1
override fun add(a: Long, b: Long) = a + b
override fun subtract(a: Long, b: Long) = a - b
override fun count(range: LongRange) = range.last - range.first + 1
override fun sumCounts(counts: Iterable<Long>) = counts.sum()
override fun without(a: LongRange, b: LongRange): Collection<LongRange> {
return if (a.first >= b.first && a.last <= b.last) emptyList() // a completely inside b -> nothing left
else if (a.first < b.first && a.last > b.last) listOf(LongRange(a.first, b.first - 1), LongRange(b.last + 1, a.last)) // b completely inside a -> b cuts a in 2 parts
else if (a.first < b.first && a.last > b.first) listOf(LongRange(a.first, b.first - 1)) // b cuts a upper end
else if (a.last > b.last && a.first < b.last) listOf(LongRange(b.last + 1, a.last)) // b cuts a lower end
else listOf(a) // no intersection -> a stays the same
}
override fun intersects(a: LongRange, b: LongRange): Boolean {
return a.intersects(b)
}
override fun intersect(a: LongRange, b: LongRange): LongRange {
return a.intersect(b)
}
override val maxValue = Long.MAX_VALUE
override val minValue = Long.MIN_VALUE
}
class LongRangeSet(
ranges: Iterable<LongRange>
): AbstractNumberRangeSet<LongRangeSet, Long, LongRange, Long>(
ranges,
LongRangeSetFactory.INSTANCE
) {
override fun copy(ranges: Iterable<LongRange>) = LongRangeSet(ranges)
}
fun LongRange.toRangeSet(): LongRangeSet {
return LongRangeSet(listOf(this))
}
| 0 | Kotlin | 0 | 0 | 3a1ea4b967d2d0774944c2ed4d96111259c26d01 | 1,933 | aoc-utils | Apache License 2.0 |
src/day08/Main.kt | nikwotton | 572,814,041 | false | {"Kotlin": 77320} | package day08
import java.io.File
const val workingDir = "src/day08"
fun main() {
val sample = File("$workingDir/sample.txt")
val input1 = File("$workingDir/input_1.txt")
println("Step 1a: ${runStep1(sample)}") // 21
println("Step 1b: ${runStep1(input1)}")
println("Step 2a: ${runStep2(sample)}") // 8
println("Step 2b: ${runStep2(input1)}")
}
fun runStep1(input: File): String {
val rows = mutableListOf<MutableList<Int>>()
input.readLines().forEach {
rows.add(it.map { it.digitToInt() }.toMutableList())
}
return rows.mapIndexed outer@{ y, row ->
row.mapIndexed inner@{ x, i ->
if (y == 0 || y == rows.size - 1) return@inner true
if (x == 0 || x == row.size - 1) return@inner true
if (row.take(x).none { it >= i }) return@inner true
if (row.takeLast(row.size - x - 1).none { it >= i }) return@inner true
if (rows.take(y).none { it[x] >= i }) return@inner true
if (rows.takeLast(rows.size - y - 1).none { it[x] >= i }) return@inner true
false
}
}.sumOf { it.count { it } }.toString()
}
fun runStep2(input: File): String {
val rows = mutableListOf<MutableList<Int>>()
input.readLines().forEach {
rows.add(it.map { it.digitToInt() }.toMutableList())
}
return rows.mapIndexed outer@{ y, row ->
row.mapIndexed inner@{ x, i ->
var up = 0
var foundUp = false
var down = 0
var foundDown = false
var left = 0
var foundLeft = false
var right = 0
var foundRight = false
(y-1 downTo 0).forEach {
if (foundUp) return@forEach
if (rows[it][x] >= i) foundUp = true
up++
}
(y+1 until rows.size).forEach {
if (foundDown) return@forEach
if (rows[it][x] >= i) foundDown = true
down++
}
(x-1 downTo 0).forEach {
if (foundLeft) return@forEach
if (row[it] >= i) foundLeft = true
left++
}
(x+1 until rows.size).forEach {
if (foundRight) return@forEach
if (row[it] >= i) foundRight = true
right++
}
up * down * left * right
}
}.maxOf { it.max() }.toString()
}
| 0 | Kotlin | 0 | 0 | dee6a1c34bfe3530ae6a8417db85ac590af16909 | 2,436 | advent-of-code-2022 | Apache License 2.0 |
leetcode/kotlin/search-in-rotated-sorted-array.kt | PaiZuZe | 629,690,446 | false | null | class Solution {
fun search(nums: IntArray, target: Int): Int {
val pivot = findPivot(nums, 0, nums.size, nums.last())
return binSearchWithPivot(nums, target, 0, nums.size, pivot)
}
private fun binSearchWithPivot(nums: IntArray, target: Int, start: Int, end: Int, pivot: Int): Int {
if (end <= start) {
return -1
}
val middle = (((end - start) / 2) + start)
if (nums[(middle + pivot) % nums.size] == target) {
return (middle + pivot) % nums.size
} else if (nums[(middle + pivot) % nums.size] < target) {
return binSearchWithPivot(nums, target, middle + 1, end, pivot)
} else {
return binSearchWithPivot(nums, target, start, middle, pivot)
}
}
private fun findPivot(nums: IntArray, start: Int, end: Int, comp: Int): Int {
if (start == end) {
return start
}
val middle = ((end - start) / 2) + start
return if (nums[middle] <= comp) {
findPivot(nums, start, middle, nums[middle])
} else {
findPivot(nums, middle + 1, end, comp)
}
}
}
| 0 | Kotlin | 0 | 0 | 175a5cd88959a34bcb4703d8dfe4d895e37463f0 | 1,165 | interprep | MIT License |
src/medium/_5LongestPalindromicSubstring.kt | ilinqh | 390,190,883 | false | {"Kotlin": 382147, "Java": 32712} | package medium
class _5LongestPalindromicSubstring {
class Solution {
fun longestPalindrome(s: String): String {
if (s.length < 2) {
return s
}
val sb = StringBuffer().append('#')
for (char in s) {
sb.append("${char}#")
}
val str = sb.toString()
var maxLeft = 0
var maxCount = 1
var left: Int
var right: Int
var count: Int
for (index in str.indices) {
count = 1
left = index
right = index
while ((left - 1) >= 0 && (right + 1) < str.length && (str[left - 1] == str[right + 1])) {
left--
right++
count += 2
}
if (count > maxCount) {
maxLeft = left
maxCount = count
}
}
return s.substring(maxLeft / 2, (maxLeft + maxCount) / 2)
}
}
// Best
class BestSolution {
fun longestPalindrome(s: String): String {
var start = 0
var maxLength = 0
if (s.length < 2) {
return s
}
val chars = s.toCharArray()
val length = chars.size
var i = 0
while (i < length) {
// 如果剩余长度和小于等于最长子串,就没必要再比较了
if ((length - i) <= maxLength / 2) {
break
}
var left = i
var right = i
// 第一步 向右寻找相同的字符串
while (right < length - 1 && chars[right] == chars[right + 1]) {
// 继续向右寻找
right++
}
var goNext = false
while (right < length - 1 && left > 0 && chars[right + 1] == chars[left - 1]) {
right++
left--
goNext = true
}
if (right - left + 1 > maxLength) {
maxLength = right - left + 1
start = left
}
if (!goNext) {
i = right + 1
} else {
i++
}
}
return s.substring(start, start + maxLength)
}
}
} | 0 | Kotlin | 0 | 0 | 8d2060888123915d2ef2ade293e5b12c66fb3a3f | 2,508 | AlgorithmsProject | Apache License 2.0 |
kotlin/src/main/kotlin/com/pbh/soft/day5/Day5Solver.kt | phansen314 | 579,463,173 | false | {"Kotlin": 105902} | package com.pbh.soft.day5
import cc.ekblad.konbini.*
import com.pbh.soft.common.Solver
import com.pbh.soft.common.parsing.ParsingUtils.onSuccess
import com.pbh.soft.day5.RangeKind.LOCATION
import com.pbh.soft.day5.RangeKind.SEED
import mu.KLogging
object Day5Solver : Solver, KLogging() {
override fun solveP1(text: String): String = Parsing.almanacP.parse(text).onSuccess { almanac ->
val answer = almanac.seeds
.mapIndexed { index, seed ->
var current = SEED to seed
do {
val dest = almanac.follow(current)
current = dest
} while (dest.first != LOCATION)
current.second
}
.min()
return answer.toString()
}
override fun solveP2(text: String): String = Parsing.almanacP.parse(text).onSuccess { almanac ->
val answer = almanac.seeds.asSequence().chunked(2).flatMap { (start, length) -> start ..< start + length }
.map { seed ->
var current = seed
for ((_, mapping) in almanac.mappings) {
val dest = mapping.follow(current)
current = dest
}
// if (current % 100000L == 0L) logger.debug { current.toString() }
current
}
.minOrNull()
return answer.toString()
// val seedRanges = almanac.seeds.chunked(2).map { (start, length) -> start..<start + length }
// println("number of seeds: ${almanac.seeds.chunked(2).map { it[1] }.sum()}")
//
// val reversedMappings = almanac.mappings.map { (_, existing) ->
// val swappedRanges = existing.ranges.map { it.copy(srcRange = it.destRange, destRange = it.srcRange) }.sortedBy { it.srcRange.first }
// existing.to to existing.copy(from = existing.to, to = existing.from, ranges = swappedRanges)
// }.reversed().toMap(linkedMapOf())
//
// for (location in 0..<Long.MAX_VALUE) {
// var current = LOCATION to location
// do {
// val dest = reversedMappings.follow(current)
// current = dest
// } while (dest.first != SEED)
// if (seedRanges.search(current.second) != null) {
// return current.second.toString()
// } else if (location % 100000 == 0L) {
// logger.debug { "$location" }
// }
// }
//
// return "todo"
}
// list must be sorted!
private fun List<Ranges>.search(value: Long): Ranges? {
var (l, r) = 0 to size - 1
while (l <= r) {
val m = (l + r).ushr(1)
val rangesSpec = this[m]
if (value in rangesSpec.srcRange) return rangesSpec
if (value > rangesSpec.srcRange.last) l = m + 1
else r = m - 1
}
return null
}
private fun List<LongRange>.search(value: Long): LongRange? {
var (l, r) = 0 to size - 1
while (l <= r) {
val m = (l + r).ushr(1)
val rangesSpec = this[m]
if (value in rangesSpec) return rangesSpec
if (value > rangesSpec.last) l = m + 1
else r = m - 1
}
return null
}
private fun Almanac.follow(location: Pair<RangeKind, Long>): Pair<RangeKind, Long> {
return mappings.follow(location)
// val (inKind, inValue) = location
// val mapping = this.mappings[inKind] ?: throw IllegalStateException("no mappings defined for $inKind!!")
// val outValue = mapping.ranges.search(inValue)?.let { inValue - it.srcRange.first + it.destRange.first } ?: inValue
// return mapping.to to outValue
}
private fun Map<RangeKind, Mapping>.follow(location: Pair<RangeKind, Long>): Pair<RangeKind, Long> {
val (inKind, inValue) = location
val mapping = this[inKind] ?: throw IllegalStateException("no mappings defined for $inKind!!")
val outValue = mapping.ranges.search(inValue)?.let { inValue - it.srcRange.first + it.destRange.first } ?: inValue
return mapping.to to outValue
}
private fun Mapping.follow(inValue: Long): Long {
return ranges.search(inValue)?.let { inValue - it.srcRange.first + it.destRange.first } ?: inValue
}
}
object Parsing {
val newlineP = string("\r\n")
val rangeSpecP = parser {
val destinationStart = integer(); whitespace1()
val sourceStart = integer(); whitespace1()
val length = integer()
val destinationEnd: Long = destinationStart + length
val sourceEnd: Long = sourceStart + length
Ranges(sourceStart..<sourceEnd, destinationStart..<destinationEnd, length)
}
val rangeKindP = oneOf(*RangeKind.entries.map { e -> string(e.textName).map { e } }.toTypedArray<Parser<RangeKind>>())
val mappingP = parser {
val from = rangeKindP(); string("-to-");
val to = rangeKindP(); string(" map:\r\n")
val rangesSpecs = chain(rangeSpecP, newlineP).terms.sortedBy { it.srcRange.first }
Mapping(from, to, rangesSpecs)
}
val almanacP = parser {
string("seeds:"); whitespace1()
val seeds = chain(integer, whitespace1).terms; many(newlineP)
val mappings = chain(mappingP, cc.ekblad.konbini.many(newlineP)).terms.associateByTo(linkedMapOf()) { it.from }
Almanac(seeds, mappings)
}
}
typealias Seed = Long
enum class RangeKind(val textName: String) {
SEED("seed"),
SOIL("soil"),
FERTILIZER("fertilizer"),
WATER("water"),
LIGHT("light"),
TEMPERATURE("temperature"),
HUMIDITY("humidity"),
LOCATION("location"),
}
data class Ranges(val srcRange: LongRange, val destRange: LongRange, val length: Long) : ClosedRange<Long> by srcRange
data class Mapping(val from: RangeKind, val to: RangeKind, val ranges: List<Ranges>)
data class Almanac(
val seeds: List<Seed>,
val mappings: Map<RangeKind, Mapping>,
// val seedToSoil: Mapping,
// val soilToFertilizer: Mapping,
// val fertilizerToWater: Mapping,
// val waterToLight: Mapping,
// val lightToTemperature: Mapping,
// val temperatureToHumidity: Mapping,
// val humidityToLocation: Mapping,
) | 0 | Kotlin | 0 | 0 | 7fcc18f453145d10aa2603c64ace18df25e0bb1a | 5,701 | advent-of-code | MIT License |
src/main/kotlin/net/codetreats/aoc/common/Dijkstra.kt | codetreats | 725,535,998 | false | {"Kotlin": 45007, "Shell": 1060} | package net.codetreats.aoc.common
class Dijkstra {
/**
* Calculate the minimum distance between startNode and endNode.
* The algorithm expects, that there are exactly [nodeCount] nodes with names from 0 to [nodeCount - 1]
* @param: nodeCount the total number of nodes
* @param: startNOde the name of the start node
* @param: endNode the name of the end node
* @param: edges defines all edges. An edge starts at the key of the map and ends in 0 .. n other nodes.
* A target node is of type [EdgeDistance],
* which contains the name of the target node and the distance between the key and the target
*/
fun shortestPath(nodeCount: Int, startNode: Int, endNode: Int, edges: Map<Int, Set<EdgeDistance>>) : DijkstraResult {
val distances = IntArray(nodeCount) { Integer.MAX_VALUE}
val preds = IntArray(nodeCount) { -1 }
distances[startNode] = 0
val queue : MutableList<Int> = mutableListOf(0)
val added = mutableSetOf<Int>(0)
while(queue.isNotEmpty()) {
val u : Int = queue.minBy { distances[it] }!!
queue.remove(u)
if (u == endNode) {
return DijkstraResult(preds, distances[u])
}
edges[u]!!.forEach { v ->
if (v.node !in queue && v.node !in added) {
queue.add(v.node)
added.add(v.node)
}
if (v.node in queue) {
val newDistance = distances[u] + v.weight
if (newDistance < distances[v.node]) {
distances[v.node] = newDistance
preds[v.node] = u
}
}
}
}
throw IllegalStateException("Algorithm finished without result")
}
}
data class EdgeDistance(val node: Int, val weight: Int)
data class DijkstraResult(val preds: IntArray, val length: Int) {
fun shortestPath(from: Int, to: Int) : List<Int> {
val path = mutableListOf(to)
while (path.last() != from) {
path.add(preds[path.last()])
}
return path.reversed()
}
} | 0 | Kotlin | 1 | 1 | 3cd4aa53093b5f95328cf478e63fe2a7a4e90961 | 2,197 | aoc2023 | MIT License |
src/main/aoc2016/Day13.kt | nibarius | 154,152,607 | false | {"Kotlin": 963896} | package aoc2016
class Day13(private val favoriteNumber: Int, private val target: Pair<Int, Int>) {
private fun numOneBits(number: Int): Int = number.toString(2).count { it == '1' }
private fun Pair<Int, Int>.isWall(): Boolean {
val x = first
val y = second
val value = x * x + 3 * x + 2 * x * y + y + y * y + favoriteNumber
return numOneBits(value) % 2 != 0
}
fun getMap(): String {
var ret = " 0123456789\n"
for (y in 0..6) {
ret += "$y "
for (x in 0..9) {
ret += when (Pair(x, y).isWall()) {
true -> "#"
false -> "."
}
}
ret += "\n"
}
return ret
}
private val visited = mutableListOf<Pair<Int, Int>>()
private data class Step(val location: Pair<Int, Int>, val steps: Int)
private fun enqueueAllPossibleSteps(currentStep: Step, toCheck: MutableList<Step>) {
val movesToCheck = listOf(
Pair(currentStep.location.first - 1, currentStep.location.second),
Pair(currentStep.location.first + 1, currentStep.location.second),
Pair(currentStep.location.first, currentStep.location.second - 1),
Pair(currentStep.location.first, currentStep.location.second + 1))
for (next in movesToCheck) {
if (next.first >= 0 && next.second >= 0 &&
!next.isWall() &&
toCheck.none { it.location == next } &&
visited.none { it == next }) {
toCheck.add(Step(next, currentStep.steps + 1))
}
}
}
private fun walk(maxSteps: Int): Int {
val toCheck = mutableListOf(Step(Pair(1, 1), 0))
while (toCheck.size > 0) {
val step = toCheck.removeAt(0)
if (step.steps > maxSteps) {
continue
}
visited.add(step.location)
if (step.location == target) {
return step.steps
}
enqueueAllPossibleSteps(step, toCheck)
}
return -1
}
fun solvePart1(): Int {
return walk(999)
}
fun solvePart2(): Int {
walk(50)
return visited.size
}
}
| 0 | Kotlin | 0 | 6 | f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22 | 2,300 | aoc | MIT License |
dcp_kotlin/src/main/kotlin/dcp/day267/day267.kt | sraaphorst | 182,330,159 | false | {"C++": 577416, "Kotlin": 231559, "Python": 132573, "Scala": 50468, "Java": 34742, "CMake": 2332, "C": 315} | package dcp.day267
// day267.kt
// By <NAME>, 2019.
import java.lang.IllegalArgumentException
// Represent the board as an 8x8 grid with (0,0) being in the upper left corner, the first coordinate representing
// the x-axis, and the second coordinate representing the y-axis.
enum class Direction {
VERTICAL_N,
VERTICAL_S,
HORIZONTAL_E,
HORIZONTAL_W,
DIAGONAL_NE,
DIAGONAL_NW,
DIAGONAL_SE,
DIAGONAL_SW
}
// Position of a piece
typealias Position = Pair<Int, Int>
// Generic filter to filter only legal moves.
fun List<Position>.filterLegal(): List<Position> =
filter { it.first in 0..7 && it.second in 0..7 }
sealed class ChessPiece(val name: String, private val symbol: Char, val position: Position) {
// Given a starting position, determine the list of valid positions to which a piece can move.
abstract fun moves(otherPieces: List<Position>): List<Position>
override fun toString(): String =
"$symbol(${position.first},${position.second})"
companion object {
// Calculate moves for pieces that move in straight lines.
// This takes a direction to calculate the legal moves along that direction, and the position of other pieces that
// can block it from continuing in that direction.
private fun lineMoves(start: Position, dx: Int, dy: Int, direction: Direction, otherPieces: List<Position>): List<Position> {
val newPos = Position(start.first + dx, start.second + dy)
// If we are out of bounds, stop. This voids us from having to filter legal moves.
return if (newPos.first !in 0..7 || newPos.second !in 0..7)
emptyList()
// If a piece other than the black king blocks us, then stop.
else if (newPos in otherPieces)
emptyList()
else listOf(newPos) + when(direction) {
Direction.HORIZONTAL_E -> lineMoves(start,dx + 1, dy, direction, otherPieces)
Direction.HORIZONTAL_W -> lineMoves(start, dx - 1, dy, direction, otherPieces)
Direction.VERTICAL_N -> lineMoves(start, dx, dy - 1, direction, otherPieces)
Direction.VERTICAL_S -> lineMoves(start, dx, dy + 1, direction, otherPieces)
Direction.DIAGONAL_NE -> lineMoves(start, dx + 1, dy - 1, direction, otherPieces)
Direction.DIAGONAL_NW -> lineMoves(start, dx - 1, dy - 1, direction, otherPieces)
Direction.DIAGONAL_SE -> lineMoves(start, dx + 1, dy + 1, direction, otherPieces)
Direction.DIAGONAL_SW -> lineMoves(start, dx - 1, dy + 1, direction, otherPieces)
}
}
// Given a list of allowable directions, calculate all the line moves (i.e. moves along lines) that a piece can
// make. The result is only allowable moves, i.e. moves that maintain position on the board and are not blocked
// by another piece, with the exception of the black king.
fun allLineMoves(start: Position, directions: List<Direction>, otherPieces: List<Position>): List<Position> =
directions.flatMap { lineMoves(start, 0, 0, it, otherPieces) }
}
}
class Pawn(position: Position): ChessPiece("pawn", 'P', position) {
// For our intents and purposes, as we are looking to see if the black king is in check, we only allow diagonal
// moves away from the x axis.
override fun moves(otherPieces: List<Position>): List<Position> =
listOf(-1, 1).map { Pair(position.first - 1, position.second + it) }.filterLegal()
}
// White king, so we use W instead of K, which is reserved for the black king.
// While in a real chess game, the kings can never place each other in check, we allow including the white king as
// he can block the movement of other pieces.
class King(position: Position): ChessPiece("king", 'W', position) {
override fun moves(otherPieces: List<Position>): List<Position> =
listOf(-1, 0, 1).flatMap { dx -> listOf(-1, 0, 1).filterNot { dx == 0 && it == 0 }.
map { dy -> Pair(position.first + dx, position.second + dy) } }.filterLegal()
}
// A knight can move all 8 Ls (1x2), and can move through other pieces.
class Knight(position: Position): ChessPiece("knight", 'N', position) {
override fun moves(otherPieces: List<Position>): List<Position> =
listOf(Pair(1, 2), Pair(2, 1), Pair(-1, 2), Pair(-2, 1), Pair(1, -2), Pair(2, -1), Pair(-1, -2), Pair(-2, -1)).
map { (dx, dy) -> Pair(position.first + dx, position.second + dy) }.filterLegal()
}
// With all subsequent pieces, they can be blocked by other pieces, so we have to restrict their movement based on
// the position of the other pieces.
// Rooks can move along horizontal and vertical lines.
class Rook(position: Position): ChessPiece("rook", 'R', position) {
override fun moves(otherPieces: List<Position>): List<Position> =
allLineMoves(position, listOf(Direction.HORIZONTAL_W, Direction.HORIZONTAL_E, Direction.VERTICAL_N, Direction.VERTICAL_S), otherPieces)
}
// Bishops can move along diagonal lines.
class Bishop(position: Position): ChessPiece("bishop", 'B', position) {
override fun moves(otherPieces: List<Position>): List<Position> =
allLineMoves(position, listOf(Direction.DIAGONAL_NE, Direction.DIAGONAL_NW, Direction.DIAGONAL_SE, Direction.DIAGONAL_SW), otherPieces)
}
// Queens can move along all lines.
class Queen(position: Position): ChessPiece("queen", 'Q', position) {
override fun moves(otherPieces: List<Position>): List<Position> =
allLineMoves(position, listOf(
Direction.HORIZONTAL_W, Direction.HORIZONTAL_E, Direction.VERTICAL_N, Direction.VERTICAL_S,
Direction.DIAGONAL_NE, Direction.DIAGONAL_NW, Direction.DIAGONAL_SE, Direction.DIAGONAL_SW
), otherPieces)
}
// The board is represented by an 8x8 matrix of rows, for example, of the form:
// ...K....
// ........
// .B......
// ......P.
// .......R
// ..N.....
// ........
// .....Q..
class Board(matrix: List<String>) {
private val blackKing: Position
private val whitePieces: List<ChessPiece>
init {
require(matrix.size == 8)
matrix.forEach { require(it.length == 8) }
// Auxiliary function to read in the white pieces.
fun aux(x: Int, y: Int): List<ChessPiece> {
// Stopping condition: we reach one row past the end of the board.
return when {
x == 8 -> emptyList()
y == 8 -> aux(x + 1, 0)
else -> when(val s = matrix[x][y]) {
'P' -> listOf(Pawn(Position(x, y)))
'N' -> listOf(Knight(Position(x, y)))
'W' -> listOf(King(Position(x, y)))
'R' -> listOf(Rook(Position(x, y)))
'B' -> listOf(Bishop(Position(x, y)))
'Q' -> listOf(Queen(Position(x, y)))
'K' -> emptyList()
'.' -> emptyList()
else -> throw IllegalArgumentException("Board contains invalid symbol: $s")
} + aux(x, y + 1)
}
}
whitePieces = aux(0, 0)
// Find the black king.
val blackKingRow = matrix.withIndex().find { (_, row) -> 'K' in row }
val blackKingX = blackKingRow?.index
val blackKingY = blackKingRow?.value?.indexOf('K')
blackKing = blackKingX?.let { x -> blackKingY?.let { y -> Position(x, y) }} ?:
throw IllegalArgumentException("Black king not found on board.")
}
// Check if the black king is in check by calculating all of the moves of the other pieces to see if they can
// move onto the black king.
fun isBlackKingInCheck(): Boolean {
val positions = whitePieces.map(ChessPiece::position)
return blackKing in whitePieces.flatMap { it.moves(positions - it.position) }
}
companion object {
// Convenience function to create a board from a single string of length 64 instead of a list of eight
// strings of length 8.
fun stringToBoard(str: String): Board {
require(str.length == 64)
val matrix = (0..7).map{ idx -> str.drop(idx * 8).take(8) }
return Board(matrix)
}
}
}
| 0 | C++ | 1 | 0 | 5981e97106376186241f0fad81ee0e3a9b0270b5 | 8,312 | daily-coding-problem | MIT License |
src/main/kotlin/y2015/day05/Day05.kt | TimWestmark | 571,510,211 | false | {"Kotlin": 97942, "Shell": 1067} | package y2015.day05
fun main() {
AoCGenerics.printAndMeasureResults(
part1 = { part1() },
part2 = { part2() }
)
}
fun input(): List<String> {
return AoCGenerics.getInputLines("/y2015/day05/input.txt")
}
fun String.hasDoubleChar(): Boolean {
var prevChar: Char? = null
this.forEach { char ->
if (prevChar == char) {
return true
}
prevChar = char
}
return false
}
fun String.hasCleanDoublePair(): Boolean {
val pairs = mutableListOf<String>()
for (i in 0 until this.length-1) {
pairs.add(this.substring(i, i+2))
}
if (pairs.toSet().size == pairs.size) {
return false
}
for (i in 0 until pairs.size-1) {
if (pairs[i] == pairs[i+1]) {
return false
}
}
return true
}
fun String.hasRepeatingCharWithOneSpace(): Boolean {
var prevChar: Char? = null
var twoPrev: Char? = null
this.forEach { char ->
if (char == twoPrev) {
return true
}
twoPrev = prevChar
prevChar = char
}
return false
}
fun part1(): Int {
val vowels = listOf('a', 'e', 'i', 'o', 'u')
val denyList = listOf("ab", "cd", "pq", "xy")
return input().map {line ->
when {
line.count { char -> vowels.contains(char) } < 3 -> false
!line.hasDoubleChar() -> false
denyList.any {deny -> line.contains(deny)} -> false
else -> true
}
}.count { it }
}
fun part2(): Int {
return input().map { line ->
when {
!line.hasCleanDoublePair() -> false
!line.hasRepeatingCharWithOneSpace() -> false
else -> true
}
}.count { it }
}
| 0 | Kotlin | 0 | 0 | 23b3edf887e31bef5eed3f00c1826261b9a4bd30 | 1,742 | AdventOfCode | MIT License |
src/main/kotlin/io/jadon/election/voting.kt | phase | 277,456,271 | false | null | package io.jadon.election
/**
* A voter's vote in an election
*/
data class Vote(
val voter: Voter,
val preferences: MutableList<Party>
) {
fun first(): Party? = preferences.firstOrNull()
fun copy(): Vote = Vote(voter, ArrayList(preferences))
}
fun List<Vote>.copy(): List<Vote> = this.map { it.copy() }
/**
* Normalize a list of double into 0 -> 1
*/
fun <T> Map<T, Double>.normalize(): Map<T, Double> {
if (this.keys.isEmpty()) return this
val ratio = 1 / this.maxBy { it.value }!!.value
return this.mapValues { it.value * ratio }
}
/**
* Results of an election. The support percentage map shows how close each party was to winning.
*/
data class ElectionResults(val winner: Party, val supportPercentage: Map<Party, Double>)
abstract class VotingSystem(
val name: String,
val model: ElectionModel
) {
fun cycle(): Pair<ElectionResults, List<Vote>> {
val votes = getVotes()
val results = chooseWinner(votes)
model.voters.forEach { it.remember(results) }
return Pair(results, votes)
}
private fun getVotes(): List<Vote> =
model.voters.map { it.vote(model.parties) }
fun getPartyPreference(party: Party, votes: List<Vote>): List<Pair<Int, Int>> {
val voteRanks = mutableMapOf<Int, Int>()
votes.forEach {
it.preferences.forEachIndexed { index, other ->
if (party == other) {
voteRanks.compute(index + 1) { _, old -> (old ?: 0) + 1 }
}
}
}
return voteRanks.toList().sortedBy { it.first }
}
protected abstract fun chooseWinner(votes: List<Vote>): ElectionResults
override fun toString(): String = name
}
class FirstPastThePost(model: ElectionModel) : VotingSystem("First Past The Post", model) {
override fun chooseWinner(votes: List<Vote>): ElectionResults {
val partyVotes = mutableMapOf<Party, Int>()
votes.forEach { vote ->
vote.first()?.let {
partyVotes.compute(it) { _, old -> (old ?: 0) + 1 }
}
}
// closeness = how many votes the party got / how many voters their were
val closeness = partyVotes.mapValues { it.value.toDouble() / votes.size }.normalize()
// debug stats of votes for each party
// println(partyVotes.toList().sortedBy { -it.second })
val winner = partyVotes.maxBy { it.value }!!.key
return ElectionResults(winner, closeness)
}
}
class AlternativeVote(model: ElectionModel) : VotingSystem("Alternative Vote", model) {
override fun chooseWinner(originalVotes: List<Vote>): ElectionResults {
// closeness = how many people preferred the party
val closeness = model.parties.map {
it to (getPartyPreference(it, originalVotes)
// collect eac
.map { (it.second.toDouble() / originalVotes.size) / (it.first * 0.75) }.sum())
}.toMap().normalize()
val votes = originalVotes.copy()
val voteAmount = votes.size
val discardedParties = mutableListOf<Party>()
while (discardedParties.size < model.parties.size - 1) {
val partyVotes = mutableMapOf<Party, Int>()
votes.forEach { vote ->
vote.first()?.let {
partyVotes.compute(it) { _, old -> (old ?: 0) + 1 }
}
}
val highestParty = partyVotes.maxBy { it.value }!!.key
val lowestParty = partyVotes.minBy { it.value }!!.key
val votesForHighestParty = getPartyPreference(highestParty, votes)[0].second
// need >= 50% to win
if (votesForHighestParty >= voteAmount / 2) {
return ElectionResults(highestParty, closeness)
}
// debug stats for the lowest & highest parties
// println(" > " + highestParty + " had " + votesForHighestParty + "/" + voteAmount + " votes")
// println(" > " + highestParty + " had " + (Math.floor(100.0 * (votesForHighestParty.toDouble() / voteAmount.toDouble()))) + "% of the vote")
// println(" > Removing lowest party " + lowestParty + " with " + partyVotes.minBy { it.value }!!.value + " votes")
// remove the votes for the lowest party
votes.forEach { vote ->
// find the vote preference indexes for the lowest party
val preferencesToRemove = mutableListOf<Int>()
vote.preferences.forEachIndexed { index, party ->
if (party == lowestParty) {
preferencesToRemove.add(index)
}
}
// reverse the list and remove the indexes that match the party
preferencesToRemove.sort()
preferencesToRemove.reverse()
preferencesToRemove.forEach { vote.preferences.removeAt(it) }
}
discardedParties.add(lowestParty)
}
val remainingParties = model.parties.toMutableList()
remainingParties.removeAll(discardedParties)
val winner = if (remainingParties.isNotEmpty()) {
remainingParties.first()
} else {
model.parties.first()
}
return ElectionResults(winner, closeness)
}
}
| 0 | Kotlin | 0 | 7 | 3002e4a2082a35fb9735f4bd5574ca51b9dff1a5 | 5,340 | electoral-systems | The Unlicense |
src/datastructure/graphs/Graphs.kt | minielectron | 332,678,510 | false | {"Java": 127791, "Kotlin": 48336} | package datastructure.graphs
import java.util.LinkedList
import java.util.PriorityQueue
data class Edge(val source: Int, val destination: Int, val weight: Int)
class Graphs(private val nodes: Int) {
private val graph = Array(nodes) { ArrayList<Edge>() } // Fixed array size to 'nodes'
fun createGraph() {
graph[0].add(Edge(0, 2, 2))
graph[0].add(Edge(0, 3, 4))
graph[1].add(Edge(1, 0, 7))
graph[2].add(Edge(2, 1, 3))
graph[3].add(Edge(3, 4, 1))
}
fun bfs() {
if (graph.isEmpty()) {
return
}
val queue = LinkedList<Int>()
val visited = BooleanArray(nodes)
// Initialize the queue with the first vertex (you can choose any starting vertex)
queue.add(graph[0].first().source) // Starting vertex with source and destination as 0
while (queue.isNotEmpty()) {
val curr = queue.poll()
if (!visited[curr]) {
visited[curr] = true
println(curr)
// Find neighbors of the current edge's destination
val neighbours = findNeighbours(curr)
// Enqueue unvisited neighbors
for (neighbor in neighbours) {
if (!visited[neighbor]) {
queue.add(neighbor)
}
}
}
}
}
fun dfs(inputGraph: Array<ArrayList<Edge>>, curr: Int, visited: BooleanArray) { // O(V+E)
// Step - 1 - Print the node
print("$curr ")
//Step 2- Mark visited true
visited[curr] = true
// Step 3 - Explore neighbour nodes
val neighbours = findNeighbours(curr)
for (n in neighbours) {
if (!visited[n]) {
dfs(inputGraph, n, visited)
println()
}
}
}
fun size(): Int {
return graph.size
}
private fun findNeighbours(vertex: Int): List<Int> {
val neighbours = mutableListOf<Int>()
// Implement your logic to find neighbors of 'vertex' here
// You can iterate through 'graph' and identify edges connected to 'vertex'
graph[vertex].forEach {
neighbours.add(it.destination)
}
return neighbours
}
fun detectCycle(curr: Int, visited: BooleanArray, recurStack: BooleanArray): Boolean { // Works for directed nodes
visited[curr] = true
recurStack[curr] = true
val neighbours = findNeighbours(curr)
for (n in neighbours) {
if (recurStack[n]) {
return true // There is a cycle
} else if (!visited[n]) {
if (detectCycle(n, visited, recurStack)) {
return true
}
}
}
recurStack[curr] = false
return false
}
fun cycleDetectionInUndirectedGraph(curr: Int, visited: BooleanArray, parent: Int): Boolean {
visited[curr] = true
val neighbours = findNeighbours(curr)
for (n in neighbours) {
if (visited[n] && parent != n) {
return true
} else if (!visited[n]) {
if (cycleDetectionInUndirectedGraph(n, visited, curr)) {
return true
}
}
}
return false
}
fun printAllPaths(curr: Int, visited: BooleanArray, target: Int, path: String) { // O(V^V)
// Base condition
if (curr == target) {
println(path)
return
}
val neighbours = findNeighbours(curr)
for (n in neighbours) {
if (!visited[n]) {
visited[curr] = true
printAllPaths(n, visited, target, path.plus(n))
visited[curr] = false // Important
}
}
}
fun dijkstraAlgorithm(src: Int) {
val pq = PriorityQueue<VertexPair>()
val visited = BooleanArray(graph.size) { false }
// Here we are tricking which will work in case starting node is zero but won't work for others.
pq.add(VertexPair(src, 0))
val distance = IntArray(graph.size)
for (i in distance.indices) {
if (i != src) {
distance[i] = Int.MAX_VALUE
}
}
while (pq.isNotEmpty()) {
val curr: VertexPair = pq.remove()
if (!visited[curr.node]) {
visited[curr.node] = true
}
for (i in graph[curr.node].indices) {
val edge: Edge = graph[curr.node][i]
val u = edge.source
val v = edge.destination
// Relaxation step
if (distance[u] + edge.weight < distance[v]) {
distance[v] = distance[u] + edge.weight
pq.add(VertexPair(v, distance[v]))
}
}
}
for (d in distance) {
print("$d ->")
}
}
fun bellmanfordAlgo(src: Int) {
val V = graph.size
val dist = IntArray(V)
for (i in graph.indices) {
if (src != i) {
dist[i] = Int.MAX_VALUE
}
}
for (k in 0 until V - 1) {
for (i in 0 until V) {
for (j in graph[i].indices) {
val edge = graph[i][j]
val u = edge.source
val v = edge.destination
if (dist[u] != Int.MAX_VALUE && dist[u] + edge.weight < dist[v]) {
dist[v] = dist[u] + edge.weight
}
}
}
}
for (d in dist) {
print("$d ->")
}
}
fun primsMst(src: Int) {
val pq = PriorityQueue<VertexPair>()
pq.add(VertexPair(0, 0)) // Non mst
val visited = BooleanArray(graph.size) { false }
var cost = 0
while (pq.isNotEmpty()) {
val curr = pq.poll()
if (!visited[curr.node]) {
visited[curr.node] = true
cost += curr.distance
for (i in graph[curr.node].indices) {
val edge = graph[curr.node][i]
if (!visited[edge.destination]) {
pq.add(VertexPair(edge.destination, edge.weight))
}
}
}
}
println("\nTotal path cost = $cost")
}
fun topSort(): LinkedList<Int> {
val visited = BooleanArray(6) { false }
val stack = LinkedList<Int>()
for (node in graph.indices) {
if (!visited[node]) {
topologicalSort(node, visited, stack)
}
}
return stack
}
private fun topologicalSort(curr: Int, visited: BooleanArray, stack: LinkedList<Int>) {
visited[curr] = true
val neighbours = findNeighbours(curr)
for (n in neighbours) {
if (!visited[n]) {
topologicalSort(n, visited, stack)
}
}
stack.push(curr) // DFS + push to stack
}
/**
* This algorithm is used to find the strongly connected components inside a graph.
* A graph is called strongly connected if all the nodes can be reached from each of the nodes.
*
* There are three steps to find the SCC.
*
* 1. Get nodes in stack(Topological sort)
* 2. Transpose the graph
* 3. Do DFS according to stack nodes on the transpose graph.
* */
fun kosarajuAlgorithm() {
val visited = BooleanArray(graph.size) { false }
// Step 1
val stack = topSort()
// Step 2 -- Transpose the graph
val transposeGraph = Array(graph.size) { ArrayList<Edge>() }
for (i in graph.indices) {
for (j in graph[i].indices) {
val edge = graph[i][j]
transposeGraph[edge.destination].add(
Edge(
source = edge.destination,
destination = edge.source,
weight = edge.weight
)
)
}
}
println("Graph")
graph.forEach {
println(it)
}
println("Transpose")
transposeGraph.forEach {
println(it)
}
// Step 3 -- Do DFS on stack nodes
println("Stack")
println(stack)
while (stack.isNotEmpty()) {
val node = stack.pop()
if (!visited[node]) {
dfs(transposeGraph, node, visited)
println()
}
}
}
}
class VertexPair(val node: Int, val distance: Int) : Comparable<VertexPair> {
override fun compareTo(other: VertexPair): Int {
return distance - other.distance
}
override fun toString(): String {
return "[$node, $distance]"
}
}
fun main() {
val graph = Graphs(5)
graph.createGraph()
// graph.bfs()
// val visited = BooleanArray(graph.size()) { false }
// visited.forEachIndexed { index, value ->
// if (!value) {
// graph.dfs(index, visited)
// }
// }
// val visitedCycles = BooleanArray(graph.size()) { false }
// val recurStack = BooleanArray(graph.size()) { false }
// println(graph.detectCycle(0, visitedCycles, recurStack))
// val startNode = 0
// val pathVisited = BooleanArray(graph.size())
// println("\nAll paths are : ")
// graph.printAllPaths(startNode, pathVisited, 4, "$startNode")
// println("Topological sort ")
// topSort(graph)
// println("Cycle detection in undirected graph")
// val visited = BooleanArray(4){false}
// println(graph.cycleDetectionInUndirectedGraph(0, visited, -1))
// graph.bellmanfordAlgo(0)
// graph.primsMst(0)
graph.kosarajuAlgorithm()
}
| 0 | Java | 0 | 0 | f2aaff0a995071d6e188ee19f72b78d07688a672 | 9,927 | data-structure-and-coding-problems | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.