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/com/hj/leetcode/kotlin/problem653/Solution2.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem653
import com.hj.leetcode.kotlin.common.model.TreeNode
/**
* LeetCode page: [653. Two Sum IV - Input is a BST](https://leetcode.com/problems/two-sum-iv-input-is-a-bst/);
*/
class Solution2 {
/* Complexity:
* Time O(N) and Space O(H) where N and H are the number of nodes and height of root;
*/
fun findTarget(root: TreeNode?, k: Int): Boolean {
if (root == null || root.isLeaf()) return false
val inOrderIterator = BstIterator.inOrder(root)
val reverseOrderIterator = BstIterator.reverseOrder(root)
var left = inOrderIterator.next()
var right = reverseOrderIterator.next()
while (left != right) {
val currSum = left.`val` + right.`val`
when {
currSum < k -> left = inOrderIterator.next()
currSum > k -> right = reverseOrderIterator.next()
else -> return true
}
}
return false
}
private fun TreeNode.isLeaf() = left == null && right == null
private class BstIterator private constructor(root: TreeNode, private val reverse: Boolean) {
private val nodeStack = ArrayDeque<TreeNode>()
private val getChildCorrespondingToOrder: (parentNode: TreeNode) -> TreeNode? =
if (reverse) { parentNode -> parentNode.right } else { parentNode -> parentNode.left }
init {
updateNodeStack(root)
}
private fun updateNodeStack(parentNode: TreeNode?) {
var currParentNode = parentNode
while (currParentNode != null) {
nodeStack.addFirst(currParentNode)
currParentNode = getChildCorrespondingToOrder(currParentNode)
}
}
fun hasNext() = nodeStack.isNotEmpty()
fun next(): TreeNode {
val popped = nodeStack.removeFirst()
val newParentNode = if (reverse) popped.left else popped.right
updateNodeStack(newParentNode)
return popped
}
companion object {
fun inOrder(bstRoot: TreeNode) = BstIterator(bstRoot, false)
fun reverseOrder(bstRoot: TreeNode) = BstIterator(bstRoot, true)
}
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 2,251 | hj-leetcode-kotlin | Apache License 2.0 |
src/main/kotlin/day14.kt | bfrengley | 318,716,410 | false | null | package aoc2020.day14
import aoc2020.util.loadTextResource
val toBinaryString = java.lang.Long::toBinaryString
fun main(args: Array<String>) {
val instrs = loadTextResource("/day14.txt").lines().map(Instr::parse)
part1(instrs)
part2(instrs)
}
fun part1(instrs: List<Instr>) {
var mask = Bitmask.parse("")
val mem = mutableMapOf<Long, Long>()
for (instr in instrs) {
when (instr) {
is Instr.Mask -> mask = instr.mask
is Instr.Set -> {
mem[instr.addr] = mask(instr.value)
}
}
}
println("Part 1: ${mem.values.sum()}")
}
fun part2(instrs: List<Instr>) {
var mask = Bitmask.parse("")
val mem = mutableMapOf<Long, Long>()
for (instr in instrs) {
when (instr) {
is Instr.Mask -> mask = instr.mask
is Instr.Set -> {
for (addr in mask.maskAddress(instr.addr)) {
mem[addr] = instr.value
}
}
}
}
println("Part 2: ${mem.values.sum()}")
}
sealed class Instr {
class Mask(val mask: Bitmask) : Instr()
class Set(val addr: Long, val value: Long) : Instr()
companion object {
fun parse(str: String): Instr {
val (l, r) = str.split('=')
return if (l.startsWith("mask")) {
Mask(Bitmask.parse(r.trim()))
} else if (l.startsWith("mem")) {
val addr = l.substring(l.indexOf('[') + 1, l.indexOf(']')).toLong()
val value = r.trim().toLong()
Set(addr, value)
} else {
throw IllegalArgumentException()
}
}
}
}
data class Bitmask(val setmask: Long, val clearmask: Long, val floatmask: Long) {
private val floatmaskBits = toBinaryString(floatmask).reversed()
operator fun invoke(n: Long) = (n or setmask) and clearmask
fun maskAddress(addr: Long) = ((addr or setmask) and floatmask.inv()).let { baseAddr ->
floatmaskBits.foldIndexed(listOf(baseAddr)) { i, masks, b ->
if (b == '1') masks + masks.map { it or (1L shl i) } else masks
}
}
override fun toString(): String {
return "Bitmask(setmask=${
toBinaryString(setmask)
}, clearmask=${
toBinaryString(clearmask.inv())
}, floatmask=${
toBinaryString(floatmask)
})"
}
companion object {
fun parse(str: String): Bitmask {
var setmask = 0L
var clearmask = 0L.inv()
var floatmask = 0L
for ((i, c) in str.reversed().withIndex()) {
when (c) {
'1' -> setmask = setmask or (1L shl i)
'0' -> clearmask = clearmask xor (1L shl i)
else -> floatmask = floatmask or (1L shl i)
}
}
return Bitmask(setmask, clearmask, floatmask)
}
}
}
| 0 | Kotlin | 0 | 0 | 088628f585dc3315e51e6a671a7e662d4cb81af6 | 2,964 | aoc2020 | ISC License |
kotlin/src/com/s13g/aoc/aoc2022/Day22.kt | shaeberling | 50,704,971 | false | {"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245} | package com.s13g.aoc.aoc2022
import com.s13g.aoc.Result
import com.s13g.aoc.Solver
import com.s13g.aoc.XY
import com.s13g.aoc.add
import com.s13g.aoc.addTo
import com.s13g.aoc.aocRange
import com.s13g.aoc.resultFrom
/**
* --- Day 22: Monkey Map ---
* https://adventofcode.com/2022/day/22
*/
class Day22 : Solver {
private val deltas = listOf(XY(1, 0), XY(0, 1), XY(-1, 0), XY(0, -1))
private enum class Dir { LEFT, RIGHT, NOTHING }
private enum class Tile { WALL, NONE }
private val mappings = genMappings()
private fun genMappings(): Set<AreaMapping> {
// Dir: 0=RIGHT, 1=DOWN, 2=LEFT, 3=UP
val forward = setOf(
AreaMapping( // A
Area(XY(100, 50), XY(100, 99)),
Area(XY(100, 50), XY(199, 50)), 0, 3
),
AreaMapping( // B
Area(XY(150, 0), XY(150, 49)),
Area(XY(100, 149), XY(100, 100)), 0, 2
),
AreaMapping( // C
Area(XY(50, 150), XY(99, 150)),
Area(XY(50, 150), XY(50, 199)), 1, 2
),
AreaMapping( // D
Area(XY(100, -1), XY(149, -1)),
Area(XY(0, 200), XY(49, 200)), 3, 3
),
AreaMapping( // E
Area(XY(50, -1), XY(99, -1)),
Area(XY(-1, 150), XY(-1, 199)), 3, 0
),
AreaMapping( // F
Area(XY(49, 0), XY(49, 49)),
Area(XY(-1, 149), XY(-1, 100)), 2, 0
),
AreaMapping( // G
Area(XY(49, 50), XY(49, 99)),
Area(XY(0, 99), XY(49, 99)), 2, 1
)
)
return forward.plus(forward.map { it.inverse() })
}
override fun solve(lines: List<String>): Result {
val map = parseMap(lines.subList(0, lines.size - 2))
val steps = parseDirections(lines.last())
val start = map.keys.filter { it.y == 0 }.minBy { it.x }
return resultFrom(
solveB(start, map, steps, true),
solveB(start, map, steps, false)
)
}
private fun solveB(
start: XY, map: Map<XY, Tile>, steps: List<Step>, partA: Boolean
): Int {
var pos = start
val maxX = map.keys.maxOf { it.x }
val maxY = map.keys.maxOf { it.y }
var currentDir = 0 // 0=RIGHT, 1=DOWN, 2=LEFT, 3=UP
for (step in steps) {
for (mov in 1..step.num) {
var newPos = pos.add(deltas[currentDir])
var newDir = currentDir
// We have fallen off the map! Figure out how to wrap around the cube.
if (newPos !in map) {
if (partA) { // Part A: Just wrap around the edge
while (newPos !in map) {
newPos.addTo(deltas[currentDir])
if (newPos.x < 0) newPos = XY(maxX, newPos.y)
if (newPos.x > maxX) newPos = XY(0, newPos.y)
if (newPos.y < 0) newPos = XY(newPos.x, maxY)
if (newPos.y > maxY) newPos = XY(newPos.x, 0)
}
} else {
// Make sure that there is an area mapping!
val transportResult = transportB(newPos, currentDir)
newPos = transportResult.first
newDir = transportResult.second
// Make sure to always take one step after transport to new
// location to step ONTO the cube surface again.
newPos = newPos.add(deltas[newDir])
}
}
if (map[newPos] != Tile.WALL) {
pos = newPos
currentDir = newDir
} else {
break // It's not a wall AND on the surface. Step complete!
}
}
if (step.dir == Dir.LEFT) currentDir-- else if (step.dir == Dir.RIGHT) currentDir++
if (currentDir < 0) currentDir += 4
if (currentDir > 3) currentDir -= 4
}
return 1000 * (pos.y + 1) + 4 * (pos.x + 1) + currentDir
}
private fun transportB(pos: XY, dir: Int): Pair<XY, Int> {
for (am in mappings) {
if (am.dirFrom == dir && am.from.isInside(pos)) {
val fromXs = aocRange(am.from.from.x, am.from.to.x).toList()
val fromYs = aocRange(am.from.from.y, am.from.to.y).toList()
val toXs = aocRange(am.to.from.x, am.to.to.x).toList()
val toYs = aocRange(am.to.from.y, am.to.to.y).toList()
val fromXIdx = fromXs.indexOf(pos.x)
val fromYIdx = fromYs.indexOf(pos.y)
// Check if X get mapped to X, or to Y.
return if (fromXs.size == toXs.size) {
Pair(XY(toXs[fromXIdx], toYs[fromYIdx]), am.dirTo)
} else {
Pair(XY(toXs[fromYIdx], toYs[fromXIdx]), am.dirTo)
}
}
}
throw RuntimeException("Mapping not found for pos=$pos")
}
private fun parseMap(lines: List<String>): Map<XY, Tile> {
val result = mutableMapOf<XY, Tile>()
for ((y, line) in lines.withIndex()) {
for ((x, ch) in line.withIndex()) {
if (ch == ' ') continue
result[XY(x, y)] = if (ch == '#') Tile.WALL else Tile.NONE
}
}
return result
}
private fun parseDirections(line: String): List<Step> {
val result = mutableListOf<Step>()
var num = ""
for (ch in line) {
if (ch.isDigit()) num += ch
else {
result.add(Step(num.toInt(), if (ch == 'L') Dir.LEFT else Dir.RIGHT))
num = ""
}
}
result.add(Step(num.toInt(), Dir.NOTHING))
return result
}
private data class Step(val num: Int, val dir: Dir)
private data class Area(val from: XY, val to: XY) {
fun isInside(pos: XY) =
pos.x in aocRange(from.x, to.x) && pos.y in aocRange(from.y, to.y)
}
private data class AreaMapping(
val from: Area,
val to: Area,
val dirFrom: Int,
val dirTo: Int,
) {
fun inverse() = AreaMapping(to, from, (dirTo + 2) % 4, (dirFrom + 2) % 4)
}
} | 0 | Kotlin | 1 | 2 | 7e5806f288e87d26cd22eca44e5c695faf62a0d7 | 5,555 | euler | Apache License 2.0 |
src/main/kotlin/tree/Trim.kt | yx-z | 106,589,674 | false | null | package tree
import java.util.*
// given a tree that can have any number of child nodes
// trim the tree up to a given level
// the trimmed level nodes now have the sum of all their child nodes
fun main(args: Array<String>) {
// 1. 5
// / | | \
// 2. 1 2 3 4
// / \ | / | \
// 3. 6 7 9 1 2 3
val testRoot = TreeNode(5)
(1..4).forEach { testRoot.children.add(TreeNode(it)) }
testRoot.children[0].children.add(TreeNode(6))
testRoot.children[0].children.add(TreeNode(7))
testRoot.children[1].children.add(TreeNode(9))
testRoot.children[3].children.add(TreeNode(1))
testRoot.children[3].children.add(TreeNode(2))
testRoot.children[3].children.add(TreeNode(3))
testRoot.trim(2)
// 1. 5
// / | | \
// 2. 6+7 9 0 1+2+3
// || || || ||
// 13 9 0 6
println(testRoot)
}
fun TreeNode.trim(level: Int) {
val queue: Queue<Pair<TreeNode, Int>> = LinkedList<Pair<TreeNode, Int>>()
queue.add(this to 1)
while (queue.isNotEmpty()) {
val (currNode, currLv) = queue.remove()
if (currLv < level) {
currNode.children.forEach { queue.add(it to currLv + 1) }
} else {
// currLv >= level
// stop pushing to queue, i.e. stop main level order traversal
// update self value to sum of children and remove children
currNode.data = if (currNode.children.isEmpty()) {
0
} else {
currNode.sumChildren()
}
currNode.children.clear()
}
}
}
fun TreeNode.sumChildren(): Int {
if (this.children.isEmpty()) {
return data
}
return this.children.map { it.sumChildren() }.sum()
}
| 0 | Kotlin | 0 | 1 | 15494d3dba5e5aa825ffa760107d60c297fb5206 | 1,589 | AlgoKt | MIT License |
src/chapter4/section1/ex3.kt | w1374720640 | 265,536,015 | false | {"Kotlin": 1373556} | package chapter4.section1
import chapter3.section5.LinearProbingHashSET
import chapter3.section5.SET
import edu.princeton.cs.algs4.In
/**
* 为Graph添加一个赋值构造函数,它接受一副图G然后创建并初始化这幅图的一个副本
* G的用例对它作出的任何改动都不应该影响它的副本
*
* 解:因为通过扩展函数实现,不能直接访问adj变量
* 遍历图所有顶点对应的边,再将边依次加入新创建的图中
* 因为一条边会被遍历两次,所以用一个新的数据结构对边去重
*/
fun Graph.copy(): Graph {
val set = getEdgeSet()
val graph = Graph(V)
set.forEach {
graph.addEdge(it.small, it.large)
}
return graph
}
fun Graph.getEdgeSet(): SET<Edge> {
val set = LinearProbingHashSET<Edge>()
for (v in 0 until V) {
adj(v).forEach {
set.add(Edge(v, it))
}
}
return set
}
/**
* 无向图的一条边,0-1和1-0相等,无法描述平行边
*/
class Edge(v: Int, w: Int) {
val small = if (v > w) w else v
val large = if (v > w) v else w
override fun hashCode(): Int {
return small * 31 + large
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (other === this) return true
if (other !is Edge) return false
return other.small == small && other.large == large
}
}
fun main() {
val path = "./data/tinyG.txt"
println("before change:")
val graph = Graph(In(path))
println("graph: $graph")
val copyGraph = graph.copy()
println("copy: $copyGraph")
graph.addEdge(0, 7)
graph.addEdge(8, 11)
println("after change:")
println("graph: $graph")
println("copy: $copyGraph")
} | 0 | Kotlin | 1 | 6 | 879885b82ef51d58efe578c9391f04bc54c2531d | 1,762 | Algorithms-4th-Edition-in-Kotlin | MIT License |
src/day12/Terrain.kt | g0dzill3r | 576,012,003 | false | {"Kotlin": 172121} | package day12
open class Terrain (val input: String) {
private val rows: List<String> = input.trim().split("\n")
private val raw: String = input.replace("\n", "")
val xs: Int = rows[0].length
val ys: Int = rows.size
val dimensions: Pair<Int, Int> = Pair(xs, ys)
private val grid: Array<Int> = Array<Int>(xs * ys) { 0 }
val start: Int = raw.indexOf('S')
val startPoint: Point = toPoint(start)
val end: Int = raw.indexOf('E')
val endPoint: Point = toPoint(end)
// fun toIndex(x: Int, y: Int) = y * rows.size + x
fun toIndex(x: Int, y: Int) = y * xs + x
fun toCoord(i: Int) = Pair(i % xs, i / xs)
fun toPoint(i: Int) = Point(i % xs, i / xs)
fun fromPoint(point: Point) = point.y * xs + point.x
fun get(point: Point): Int = grid[fromPoint(point)]
fun get(x: Int, y: Int): Int = grid[toIndex(x, y)]
fun set(x: Int, y: Int, v: Int) {
grid[toIndex(x, y)] = v
}
fun contains(point: Point): Boolean {
val (x, y) = point
return x in 0 until xs && y in 0 until ys
}
fun gradient(from: Point, to: Point): Int {
return get(to) - get(from)
}
init {
raw.forEachIndexed { i, c ->
if (c in 'a'..'z') {
grid[i] = c - 'a'
} else if (c == 'S') {
grid[i] = 'a' - 'a'
} else if (c == 'E') {
grid[i] = 'z' - 'a'
} else {
throw IllegalArgumentException("Unrecognized terrain height: $c")
}
}
}
/**
* Test to see if we can move from the specified point in
* the specified direction. This is only possible if we don't move
* off of the grid and no more than 1 elevation higher
*/
protected fun canMove(point: Point, direction: Direction): Boolean {
val move = point.move(direction)
return contains(move) && gradient(point, move) <= 1
}
fun find(height: Int): List<Point> {
val list = mutableListOf<Point>()
visit { p, i ->
if (i == height) {
list.add(p)
}
}
return list
}
fun visit(lambda: (Point, Int) -> Unit) {
for (x in 0 until xs) {
for (y in 0 until ys) {
val point = Point(x, y)
lambda(point, get(point))
}
}
}
fun dump() {
val buf = StringBuffer()
grid.forEachIndexed { i, v ->
if (i > 0 && i % xs == 0) {
buf.append("\n")
}
buf.append('a'.plus(v))
}
buf.append("\nstart=${toCoord(start)}")
buf.append("\nend=${toCoord(end)}")
buf.append("\nsize=($xs, $ys)")
println(buf.toString())
}
}
fun main (args: Array<String>) {
val example = true
val terrain = readTerrain (example)
terrain.dump ()
return
}
// EOF | 0 | Kotlin | 0 | 0 | 6ec11a5120e4eb180ab6aff3463a2563400cc0c3 | 2,915 | advent_of_code_2022 | Apache License 2.0 |
src/main/kotlin/leetcode/problem0052/NQueens2.kt | ayukatawago | 456,312,186 | false | {"Kotlin": 266300, "Python": 1842} | package leetcode.problem0052
class NQueens2 {
fun totalNQueens(n: Int): Int {
val board = Array(n) { BooleanArray(n) { false } }
return solve(board, 0)
}
private fun solve(board: Array<BooleanArray>, row: Int): Int {
if (row == board.size) {
return 1
}
var count = 0
board[row].indices.forEach { column ->
if (canPlace(board, row, column)) {
board[row][column] = true
count += solve(board, row + 1)
board[row][column] = false
}
}
return count
}
private fun canPlace(board: Array<BooleanArray>, row: Int, column: Int): Boolean {
if (board[row].any { it }) {
return false
}
if (board.map { it[column] }.any { it }) {
return false
}
val leftDiagonal = (0 until row).mapNotNull {
val diff = column - row
if (it + diff >= 0 && it + diff <= board.lastIndex) board[it][it + diff] else null
}
if (leftDiagonal.any { it }) {
return false
}
val rightDiagonal = (0 until row).mapNotNull {
val sum = row + column
if (it <= sum && sum - it <= board.lastIndex) board[it][sum - it] else null
}
if (rightDiagonal.any { it }) {
return false
}
return true
}
}
| 0 | Kotlin | 0 | 0 | f9602f2560a6c9102728ccbc5c1ff8fa421341b8 | 1,419 | leetcode-kotlin | MIT License |
src/main/java/Day7.kt | mattyb678 | 319,195,903 | false | null | class Day7 : Day {
companion object {
private val parentRegex = "([a-z]+\\s[a-z]+)".toRegex()
private val contentRegex = "((\\d)\\s([a-z]+\\s[a-z]+))+".toRegex()
}
override fun asInt(): Int = 7
override fun part1InputName(): String = "day7"
override fun part1(input: List<String>): String {
val bagMap = input.toBagMap()
fun containsTarget(target: String, current: String): Boolean {
val contents = bagMap[current] ?: emptyList()
return when {
contents.isEmpty() -> false
contents.map { it.color }.any { it == target } -> true
else -> {
contents.map { containsTarget(target, it.color) }.any { it }
}
}
}
return bagMap.keys.filter { containsTarget("shiny gold", it) }
.count()
.toString()
}
override fun part2InputName(): String = "day7"
override fun part2(input: List<String>): String {
val bagMap = input.toBagMap()
fun bagsContainedIn(target: String):Int = bagMap[target]!!.sumBy { bag ->
bag.count + (bag.count * bagsContainedIn(bag.color))
}
return bagsContainedIn("shiny gold").toString()
}
private fun List<String>.toBagMap(): Map<String, List<BagContent>> {
return this.associate {
val parts = it.split("contain")
val parent = parentRegex.find(parts[0])?.groupValues?.get(0) ?: ""
val contents = contentRegex.findAll(parts[1])
.map { content -> content.destructured }
.map { (_, count, color) -> BagContent(color, count.toInt()) }
.toList()
parent to contents
}
}
}
data class BagContent(val color: String, val count: Int) | 0 | Kotlin | 0 | 1 | f677d61cfd88e18710aafe6038d8d59640448fb3 | 1,835 | aoc-2020 | MIT License |
src/main/kotlin/endredeak/aoc2023/Day06.kt | edeak | 725,919,562 | false | {"Kotlin": 26575} | package endredeak.aoc2023
import endredeak.aoc2023.lib.utils.productOf
import endredeak.aoc2023.lib.utils.transpose
import kotlin.math.ceil
import kotlin.math.floor
import kotlin.math.sqrt
fun main() {
solve("Wait For It") {
val input = lines.map { it.substringAfter(":") }
part1(138915) {
input
.map { it.split(" ").filter(String::isNotBlank).map(String::toLong) }
.transpose()
.productOf { solve(it[0], it[1]) }
}
part2(27340847) {
input
.map { it.filter(Char::isDigit).toLong() }
.let { solve(it[0], it[1]) }
}
}
}
// solve x^2 - tx - d = 0
private fun solve(t: Long, r: Long) =
(t / 2.0).let { b -> sqrt(b * b - r).let { d -> (ceil(b + d - 1) - floor(b - d + 1) + 1) } }.toLong()
// (1..<t).count { (t - it) * it > r }.toLong() // brute-force solution (around 700ms)
| 0 | Kotlin | 0 | 0 | 92c684c42c8934e83ded7881da340222ff11e338 | 936 | AdventOfCode2023 | Do What The F*ck You Want To Public License |
src/Day14.kt | spaikmos | 573,196,976 | false | {"Kotlin": 83036} | fun main() {
fun parseInput(input: List<String>): MutableSet<Pair<Int, Int>> {
// Parse the input into a set of points
val m = mutableSetOf<Pair<Int, Int>>()
for (i in input) {
val parts = i.split(" -> ")
val it = parts.iterator()
var tmp = (it.next().split(',').map{it -> it.toInt()})
var prev = Pair(tmp[0], tmp[1])
while (it.hasNext()) {
tmp = it.next().split(',').map{it -> it.toInt()}
var cur = Pair(tmp[0], tmp[1])
if (cur.first == prev.first) {
// this is a vertical wall
if (cur.second < prev.second) {
for (y in cur.second..prev.second) {
m.add(Pair(cur.first, y))
}
} else {
for (y in cur.second downTo prev.second) {
m.add(Pair(cur.first, y))
}
}
} else if (cur.second == prev.second) {
// this is a horizontal wall
if (cur.first < prev.first) {
for (x in cur.first..prev.first) {
m.add(Pair(x, cur.second))
}
} else {
for (x in cur.first downTo prev.first) {
m.add(Pair(x, cur.second))
}
}
}
prev = cur
}
}
return m
}
fun part1(m: MutableSet<Pair<Int, Int>>): Int {
//var m = parseInput(input)
// run the simulation:
val maxY = m.maxBy { it.second }.second
val numRock = m.size
do {
var cur = Pair(500, 0)
var stop = false
while ((stop == false) && (cur.second < maxY)) {
// check area directly below
if (m.contains(Pair(cur.first, cur.second+1)) == false) {
cur = Pair(cur.first, cur.second+1)
} else if (m.contains(Pair(cur.first-1, cur.second+1)) == false) {
cur = Pair(cur.first-1, cur.second+1)
} else if (m.contains(Pair(cur.first+1, cur.second+1)) == false) {
cur = Pair(cur.first+1, cur.second+1)
} else {
// Sand stopped moving
stop = true
m.add(cur)
}
}
} while (cur.second < maxY)
return m.size - numRock
}
fun part2(m: MutableSet<Pair<Int, Int>>): Int {
val minX = m.minBy { it.first }.first
val maxX = m.maxBy { it.first }.first
val maxY = m.maxBy { it.second }.second
// Add floor to map
for (x in (minX - 200)..(maxX + 200)) {
m.add(Pair(x, maxY+2))
}
// Run simulation
val numRock = m.size
do {
var cur = Pair(500, 0)
var stop = false
while (stop == false) {
// check area directly below
if (m.contains(Pair(cur.first, cur.second+1)) == false) {
cur = Pair(cur.first, cur.second+1)
} else if (m.contains(Pair(cur.first-1, cur.second+1)) == false) {
cur = Pair(cur.first-1, cur.second+1)
} else if (m.contains(Pair(cur.first+1, cur.second+1)) == false) {
cur = Pair(cur.first+1, cur.second+1)
} else {
// Sand stopped moving
stop = true
m.add(cur)
}
}
} while (cur != Pair(500, 0)) // Stop when sand doesn't move
return m.size - numRock
}
val input = readInput("../input/Day14")
println(part1(parseInput(input))) // 728
println(part2(parseInput(input))) // 27623
} | 0 | Kotlin | 0 | 0 | 6fee01bbab667f004c86024164c2acbb11566460 | 3,993 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/Day04.kt | alex859 | 573,174,372 | false | {"Kotlin": 80552} | fun main() {
val testInput = readInput("Day04_test.txt")
check(testInput.countFullyOverlappingAssignments() == 2)
check(testInput.countPartialOverlappingAssignments() == 4)
val input = readInput("Day04.txt")
println(input.countFullyOverlappingAssignments())
println(input.countPartialOverlappingAssignments())
}
internal fun String.countFullyOverlappingAssignments() =
lines().map { it.toAssignmentPair() }.count { it.oneFullyContainsOther() }
internal fun String.countPartialOverlappingAssignments() =
lines().map { it.toAssignmentPair() }.count { it.onePartiallyContainsOther() }
internal fun String.toAssignmentPair(): AssignmentPair {
val (first, second) = split(",")
return first.toIntRange() to second.toIntRange()
}
private fun String.toIntRange(): IntRange {
val (lower, upper) = split("-")
return lower.toInt()..upper.toInt()
}
internal fun AssignmentPair.oneFullyContainsOther() = (first in second) or (second in first)
internal fun AssignmentPair.onePartiallyContainsOther() = (first.overlaps(second)) or (second.overlaps(first))
internal typealias AssignmentPair = Pair<IntRange, IntRange>
internal infix operator fun IntRange.contains(that: IntRange) = this.toSet().containsAll(that.toSet())
internal fun IntRange.overlaps(that: IntRange) = this.toSet().intersect(that.toSet()).isNotEmpty() | 0 | Kotlin | 0 | 0 | fbbd1543b5c5d57885e620ede296b9103477f61d | 1,361 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/CountPairs.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
import dev.shtanko.algorithms.MOD
/**
* 1711. Count Good Meals
* @see <a href="https://leetcode.com/problems/count-good-meals/">Source</a>
*/
fun interface CountPairs {
operator fun invoke(deliciousness: IntArray): Int
}
class CountPairsTwoSum : CountPairs {
override operator fun invoke(deliciousness: IntArray): Int {
val map: MutableMap<Int, Int> = HashMap()
var res: Long = 0
for (e in deliciousness) {
for (i in 0..LIMIT) {
res += map.getOrDefault((1 shl i) - e, 0).toLong()
}
map.merge(e, 1) { a: Int, b: Int ->
Integer.sum(a, b)
}
}
return (res % MOD).toInt()
}
companion object {
private const val LIMIT = 21
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,418 | kotlab | Apache License 2.0 |
src/main/kotlin/dev/paulshields/aoc/day11/SeatPredictor.kt | Pkshields | 318,658,287 | false | null | package dev.paulshields.aoc.day11
abstract class SeatPredictor(input: String, private val occupiedSeatTolerance: Int) {
private var seatingLayout = input
.lines()
.filter { it.isNotEmpty() }
.map { it.map(Seat::parseChar).toList() }
.toList()
protected val adjacentSeats = listOf(-1 to -1, -1 to 0, -1 to 1,
0 to -1, 0 to 1,
1 to -1, 1 to 0, 1 to 1)
fun iterateUntilNoMoreSeatsChange(): Int {
val seatCounts = mutableListOf(countOccupiedSeats())
do {
nextRound()
seatCounts.add(countOccupiedSeats())
} while (seatCounts.last() != seatCounts[seatCounts.size - 2])
return seatCounts.last()
}
private fun nextRound() {
seatingLayout = seatingLayout.mapIndexed { y, row ->
row.mapIndexed { x, seat -> updateSeat(x, y, seat) }
}
}
private fun updateSeat(x: Int, y: Int, seat: Seat) = when(seat) {
Seat.EMPTY -> if (countOccupiedAdjacentSeats(x, y) == 0) Seat.OCCUPIED else Seat.EMPTY
Seat.OCCUPIED -> if (countOccupiedAdjacentSeats(x, y) >= occupiedSeatTolerance) Seat.EMPTY else Seat.OCCUPIED
else -> Seat.FLOOR
}
private fun countOccupiedAdjacentSeats(x: Int, y: Int) =
calculateSeatsToCheck(x, y)
.mapNotNull(::getSeat)
.filter { seat -> seat == Seat.OCCUPIED }
.count()
protected abstract fun calculateSeatsToCheck(x: Int, y: Int): List<Pair<Int, Int>>
protected fun getSeat(position: Pair<Int, Int>) =
position.let { (x, y) -> seatingLayout.getOrNull(y)?.getOrNull(x) }
private fun countOccupiedSeats() = seatingLayout.sumBy { row -> row.filter { it == Seat.OCCUPIED }.count() }
} | 0 | Kotlin | 0 | 0 | a7bd42ee17fed44766cfdeb04d41459becd95803 | 1,825 | AdventOfCode2020 | MIT License |
src/main/kotlin/Dijkstra.kt | MatteoMartinelli97 | 403,882,570 | false | {"Kotlin": 39512} | import java.util.*
import kotlin.collections.ArrayDeque
object Dijkstra {
fun shortestPath(g: Graph<Int>, source: Int): Map<Int, Float> { //Pair<List<Int>, Float> {
if (source !in g.V) {
throw RuntimeException("Source is not in graph vertices, cannot compute path!")
}
val dist = mutableMapOf<Int, Float>()
dist[source] = 0f
val Q = PriorityQueue<Pair<Int, Float>>(
g.V.size,
compareBy { it.second }
)
g.neighbours[source]?.forEach { dist[it.first] = it.second }
//Initialize priority queues with distances from source
for (v in g.V) {
if (v != source) {
dist[v] = Float.POSITIVE_INFINITY
}
Q.add(Pair(v, dist[v]!!))
}
while (!Q.isEmpty()) {
//Choose min distance vertex
val u = Q.poll()
//For each neighbour still in Q
// re-evaluate distance from source with intermediate step 'u'
g.neighbours[u.first]?.forEach {
if (Pair(it.first, dist[it.first]!!) in Q) {
val newDist = u.second + it.second
//If lesser than before, change the queue order, and update distance
if (newDist < dist[it.first]!!) {
Q.remove(it)
dist[it.first] = newDist
Q.add(Pair(it.first, newDist))
}
}
}
}
return dist
}
fun targetShortestPath(g: Graph<Int>, source: Int, target: Int): ArrayDeque<Int> {
if (source !in g.V) {
throw RuntimeException("Source ($source) is not in graph vertices, cannot compute path!")
}
if (target !in g.V) {
throw RuntimeException("Target ($target) is not in graph vertices, cannot compute path!")
}
if (target == source) return ArrayDeque(target)
val prev = mutableMapOf<Int, Int>()
val dist = mutableMapOf<Int, Float>()
dist[source] = 0f
val Q = PriorityQueue<Pair<Int, Float>>(
g.V.size,
compareBy { it.second }
)
g.neighbours[source]?.forEach {
dist[it.first] = it.second
prev[it.first] = source
}
//Initialize priority queues with distances from source
for (v in g.V) {
if (v != source) {
dist[v] = Float.POSITIVE_INFINITY
}
Q.add(Pair(v, dist[v]!!))
}
while (!Q.isEmpty()) {
//Choose min distance vertex
val u = Q.poll()
if (u.first == target) {
break
}
//For each neighbour still in Q
// re-evaluate distance from source with intermediate step 'u'
g.neighbours[u.first]?.forEach {
if (Pair(it.first, dist[it.first]!!) in Q) {
val newDist = u.second + it.second
//If lesser than before, change the queue order, and update distance
if (newDist < dist[it.first]!!) {
// Q.remove(it)
dist[it.first] = newDist
Q.add(Pair(it.first, newDist))
prev[it.first] = u.first
}
}
}
}
return buildPath(source, target, prev)
}
fun targetShortestPath(g: Grid2D, source: Int, target: Int): ArrayDeque<Int> {
if (g.getCoordinates(source) in g.blocks) throw java.lang.RuntimeException(
"Given source is a block." +
" Cannot start finding shortest path"
)
if (g.getCoordinates(target) in g.blocks) println("Target is a block. No path will exist")
return targetShortestPath(g.graph, source, target)
}
fun visualTargetShortestPath(g: Graph<Int>, source: Int, target: Int): Pair<ArrayDeque<Int>, MutableList<Int>> {
if (source !in g.V) {
throw RuntimeException("Source ($source) is not in graph vertices, cannot compute path!")
}
if (target !in g.V) {
throw RuntimeException("Target ($target) is not in graph vertices, cannot compute path!")
}
val visitedNodes = mutableListOf(source)
if (target == source) return Pair(ArrayDeque(target), visitedNodes)
val prev = mutableMapOf<Int, Int>()
val dist = mutableMapOf<Int, Float>()
dist[source] = 0f
val Q = PriorityQueue<Pair<Int, Float>>(
g.V.size,
compareBy { it.second }
)
g.neighbours[source]?.forEach {
dist[it.first] = it.second
prev[it.first] = source
}
//Initialize priority queues with distances from source
for (v in g.V) {
if (v != source) {
dist[v] = Float.POSITIVE_INFINITY
}
Q.add(Pair(v, dist[v]!!))
}
while (!Q.isEmpty()) {
//Choose min distance vertex
val u = Q.poll()
visitedNodes.add(u.first)
if (u.first == target) {
break
}
//For each neighbour still in Q
// re-evaluate distance from source with intermediate step 'u'
g.neighbours[u.first]?.forEach {
if (Pair(it.first, dist[it.first]!!) in Q) {
val newDist = u.second + it.second
//If lesser than before, change the queue order, and update distance
if (newDist < dist[it.first]!!) {
// Q.remove(it)
dist[it.first] = newDist
Q.add(Pair(it.first, newDist))
prev[it.first] = u.first
}
}
}
}
return Pair(buildPath(source, target, prev), visitedNodes)
}
fun visualTargetShortestPath(g: Grid2D, source: Int, target: Int): Pair<ArrayDeque<Int>, MutableList<Int>> {
if (g.getCoordinates(source) in g.blocks) throw java.lang.RuntimeException(
"Given source is a block." +
" Cannot start finding shortest path"
)
if (g.getCoordinates(target) in g.blocks) println("Target is a block. No path will exist")
return visualTargetShortestPath(g.graph, source, target)
}
private fun buildPath(source: Int, target: Int, prev: MutableMap<Int, Int>): ArrayDeque<Int> {
val path = ArrayDeque<Int>()
var u = target
path.add(u)
while (prev[u] != null && prev[u] != source) {
path.addFirst(prev[u]!!)
u = prev[u]!!
}
path.addFirst(source)
return path
}
} | 0 | Kotlin | 0 | 0 | f14d4ba7058be629b407e06eebe09fae63aa35c1 | 6,850 | Dijkstra-and-AStar | Apache License 2.0 |
aoc-2022/src/main/kotlin/nerok/aoc/aoc2022/day02/Day02.kt | nerok | 572,862,875 | false | {"Kotlin": 113337} | package nerok.aoc.aoc2022.day02
import nerok.aoc.utils.Input
import kotlin.time.DurationUnit
import kotlin.time.measureTime
enum class RockPaperScissor {
ROCK, PAPER, SCISSOR
}
enum class Result {
WIN, DRAW, LOSS
}
fun main() {
val opponentAction = mapOf(
"A" to RockPaperScissor.ROCK,
"B" to RockPaperScissor.PAPER,
"C" to RockPaperScissor.SCISSOR
)
val playerAction = mapOf(
"X" to RockPaperScissor.ROCK,
"Y" to RockPaperScissor.PAPER,
"Z" to RockPaperScissor.SCISSOR
)
val actionScoring = mapOf(
RockPaperScissor.ROCK to 1,
RockPaperScissor.PAPER to 2,
RockPaperScissor.SCISSOR to 3
)
val resultScoring = mapOf(
-1L to 0L,
0L to 3L,
1L to 6L
)
val resultMap = mapOf(
"X" to Result.LOSS,
"Y" to Result.DRAW,
"Z" to Result.WIN
)
val mappedResultScore = mapOf(
Result.LOSS to 0L,
Result.DRAW to 3L,
Result.WIN to 6L
)
fun score(opponent: RockPaperScissor, player: RockPaperScissor): Long {
if (opponent == player) return 0L
if (opponent == RockPaperScissor.ROCK) {
if (player == RockPaperScissor.PAPER) {
return 1L
}
if (player == RockPaperScissor.SCISSOR) {
return -1L
}
return 0L
}
if (opponent == RockPaperScissor.PAPER) {
if (player == RockPaperScissor.SCISSOR) {
return 1L
}
if (player == RockPaperScissor.ROCK) {
return -1L
}
return 0L
}
if (opponent == RockPaperScissor.SCISSOR) {
if (player == RockPaperScissor.ROCK) {
return 1L
}
if (player == RockPaperScissor.PAPER) {
return -1L
}
return 0L
}
return 0L
}
fun part1(input: List<String>): Long {
var totalScore = 0L
for (line in input) {
val (opponent, player) = line.split(" ")
val roundOpponentAction = opponentAction[opponent]
val roundPlayerAction = playerAction[player]
val result = score(roundOpponentAction!!, roundPlayerAction!!)
totalScore += resultScoring[result]!! + actionScoring[roundPlayerAction]!!
}
return totalScore
}
fun findAction(roundOpponentAction: RockPaperScissor, result: Result): RockPaperScissor {
when (result) {
Result.DRAW -> return roundOpponentAction
Result.WIN -> {
if (roundOpponentAction == RockPaperScissor.ROCK) return RockPaperScissor.PAPER
if (roundOpponentAction == RockPaperScissor.PAPER) return RockPaperScissor.SCISSOR
return RockPaperScissor.ROCK
}
Result.LOSS -> {
if (roundOpponentAction == RockPaperScissor.ROCK) return RockPaperScissor.SCISSOR
if (roundOpponentAction == RockPaperScissor.PAPER) return RockPaperScissor.ROCK
return RockPaperScissor.PAPER
}
}
}
fun part2(input: List<String>): Long {
var totalScore = 0L
for (line in input) {
val (opponent, result) = line.split(" ")
val roundOpponentAction = opponentAction[opponent]
val parsedResult = resultMap[result]
val identifiedPlayerAction = findAction(roundOpponentAction!!, parsedResult!!)
totalScore += mappedResultScore[parsedResult]!! + actionScoring[identifiedPlayerAction]!!
}
return totalScore
}
// test if implementation meets criteria from the description, like:
val testInput = Input.readInput("Day02_test")
check(part1(testInput) == 15L)
check(part2(testInput) == 12L)
val input = Input.readInput("Day02")
println(measureTime { println(part1(input)) }.toString(DurationUnit.SECONDS, 3))
println(measureTime { println(part2(input)) }.toString(DurationUnit.SECONDS, 3))
}
| 0 | Kotlin | 0 | 0 | 7553c28ac9053a70706c6af98b954fbdda6fb5d2 | 4,117 | AOC | Apache License 2.0 |
src/main/kotlin/Day07.kt | AlmazKo | 576,500,782 | false | {"Kotlin": 26733} | object Day07 : Task {
@JvmStatic
fun main(args: Array<String>) = execute()
override fun part1(input: Iterable<String>): Any {
val fs = initFileSystem(input)
return calculatePhase1(fs.root, 100_000)
}
override fun part2(input: Iterable<String>): Long {
val fs = initFileSystem(input)
val freeSpace = 70_000_000 - fs.root.size
val needToFree = 30_000_000 - freeSpace
return calculatePhase2(fs.root, needToFree, fs.root.size)
}
private fun initFileSystem(input: Iterable<String>): FileSystem {
val fs = FileSystem()
input.forEach(fs::interpret)
fs.calculateSizes()
return fs
}
private fun calculatePhase1(dir: Dir, threshold: Long): Long {
return dir.dirs()
.sumOf {
(if (it.size <= threshold) it.size else 0) + calculatePhase1(it, threshold)
}
}
private fun calculatePhase2(dir: Dir, threshold: Long, smallest: Long): Long {
val children = dir.dirs()
.filter { it.size >= threshold }
.minOfOrNull { calculatePhase2(it, threshold, smallest) } ?: smallest
return if (dir.size >= threshold) {
minOf(children, smallest, dir.size)
} else {
minOf(children, smallest)
}
}
sealed class Command
object Ls : Command()
object CdTop : Command()
object CdUp : Command()
class CdTo(val dirname: String) : Command()
sealed class Node
class File(val name: String, val size: Long) : Node()
class Dir(val name: String, val parent: Dir?) : Node() {
val nodes: ArrayList<Node> = ArrayList()
var size: Long = 0L
fun dirs() = nodes.filterIsInstance<Dir>()
}
class FileSystem {
val root = Dir("/", null)
private var cursor: Dir = root
fun interpret(input: String) {
if (input.startsWith('$')) {
val cmd = onInput(input.substringAfter(' '))
execute(cmd)
} else {
onOutput(input)
}
}
private fun onInput(raw: String): Command {
val name = raw.substringBefore(' ')
val argument = raw.substringAfter(' ')
return if (name == "cd") {
when (argument) {
"/" -> CdTop
".." -> CdUp
else -> CdTo(argument)
}
} else Ls
}
private fun execute(cmd: Command) {
cursor = when (cmd) {
is CdTo -> cursor.dirs().first { it.name == cmd.dirname } as Dir
CdTop -> root
CdUp -> cursor.parent ?: root
Ls -> cursor
}
}
private fun onOutput(output: String) {
val node = if (output.startsWith("dir")) {
Dir(output.substringAfter(' '), cursor)
} else {
File(
name = output.substringAfter(' '),
size = output.substringBefore(' ').toLong()
)
}
cursor.nodes.add(node)
}
fun calculateSizes(dir: Dir = root): Long {
dir.size = dir.nodes.sumOf {
when (it) {
is File -> it.size
is Dir -> calculateSizes(it)
}
}
return dir.size
}
}
} | 0 | Kotlin | 0 | 1 | 109cb10927328ce296a6b0a3600edbc6e7f0dc9f | 3,470 | advent2022 | MIT License |
src/main/kotlin/ru/glukhov/aoc/Day4.kt | cobaku | 576,736,856 | false | {"Kotlin": 25268} | package ru.glukhov.aoc
import java.io.BufferedReader
fun main() {
Problem.forDay("day4").use { solveFirst(it) }.let { println("Result of the first problem is $it") }
Problem.forDay("day4").use { solveSecond(it) }.let { println("Result of the first problem is $it") }
}
private fun solveFirst(reader: BufferedReader): Int = reader.lines()
.filter() { it.hasFullIntersection() }
.count()
.toInt()
private fun solveSecond(reader: BufferedReader): Int = reader.lines()
.filter() { it.hasOverlap() }
.count()
.toInt()
private fun String.pairs(): Pair<Pair<Int, Int>, Pair<Int, Int>> = this.split(",")
.let { Pair(it[0].asRange(), it[1].asRange()) }
private fun String.asRange(): Pair<Int, Int> = this.split("-")
.let { Pair(Integer.valueOf(it[0]), Integer.valueOf(it[1])) }
private fun String.hasFullIntersection(): Boolean = pairs().let {
(it.first.first <= it.second.first && it.first.second >= it.second.second)
.or(it.second.first <= it.first.first && it.second.second >= it.first.second)
}
private fun String.hasOverlap(): Boolean = if (hasFullIntersection()) true else
pairs().let { (it.first.second >= it.second.first).and(it.first.first <= it.second.second) } | 0 | Kotlin | 0 | 0 | a40975c1852db83a193c173067aba36b6fe11e7b | 1,226 | aoc2022 | MIT License |
kotlin/src/x2022/day10/day10.kt | freeformz | 573,924,591 | false | {"Kotlin": 43093, "Go": 7781} | package day10
import readInput
enum class Instruction(val cycles: Int) {
NOOP(1),
ADDX(2);
}
data class Op(val instruction: Instruction, val data: Any?) {
var cc: Int = 0
fun cycle(cpu: CPU, data: Any?): Boolean {
if (cc < instruction.cycles) cc++
when (instruction) {
Instruction.NOOP -> {}
Instruction.ADDX -> {
if (cc == instruction.cycles) {
//println("before x: ${cpu.registers["X"]}")
cpu.registers["X"] = cpu.registers["X"]!! + data as Int
//println("after x: ${cpu.registers["X"]}")
}
}
}
return cc == instruction.cycles
}
}
class CPU {
lateinit var registers: MutableMap<String, Int>
var cycle: Int = 1
var programCounter: Int = 0
var cOp: Op? = null
private var program = listOf<Op>()
init {
reset()
}
fun load(program: List<Op>) {
this.program = program
}
fun executeUntil(endCycle: Int, crt: CRTRow?) {
while (cycle < endCycle) {
//println("start cycle: $cycle")
if (programCounter > program.count() - 1) {
break
}
if (cOp == null) {
cOp = program[programCounter]
}
crt?.drawPixel(cycle - 1, regX())
val done = cOp!!.cycle(this, cOp!!.data)
cycle++
if (done) {
cOp = null
programCounter++
}
}
}
fun regX(): Int {
return registers["X"]!!
}
fun reset() {
registers = mutableMapOf(Pair("X", 1))
cycle = 1
programCounter = 0
cOp = null
}
}
class CRTRow(val offset: Int = 0) {
var row: String = ""
fun drawPixel(pos: Int, spritePos: Int) {
row += if (pos - offset in spritePos - 1..spritePos + 1) "#" else "."
}
}
fun main() {
fun parseInput(input: List<String>): List<Op> {
return input.map {
val parts = it.split(" ")
when (parts.first()) {
"noop" -> Op(Instruction.NOOP, null)
"addx" -> Op(Instruction.ADDX, parts.last().toInt())
else -> throw Exception("Unknown program instruction: ${parts.first()}")
}
}
}
fun partOne(input: List<String>) {
val program = parseInput(input)
val puter = CPU()
puter.load(program)
var sum = 0
for (i in 20 until 221 step 40) {
puter.executeUntil(i, null)
val css = puter.regX() * i
println("cycle $i: x=${puter.regX()} signal strength= ${css}")
sum += css
}
println("signal strength sum: $sum")
}
fun partTwo(input: List<String>) {
val program = parseInput(input)
val puter = CPU()
puter.load(program)
for (offset in 1 until 241 step 40) {
val crtRow = CRTRow(offset - 1)
for (i in 0..40) {
puter.executeUntil(offset + i, crtRow)
}
println(crtRow.row)
}
}
println("partOne test")
partOne(readInput("day10.test"))
println()
println("partOne")
partOne(readInput("day10"))
println()
println("partTwo with test input")
partTwo(readInput("day10.test"))
println()
println("partTwo")
partTwo(readInput("day10"))
} | 0 | Kotlin | 0 | 0 | 5110fe86387d9323eeb40abd6798ae98e65ab240 | 3,463 | adventOfCode | Apache License 2.0 |
src/main/kotlin/g2101_2200/s2134_minimum_swaps_to_group_all_1s_together_ii/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g2101_2200.s2134_minimum_swaps_to_group_all_1s_together_ii
// #Medium #Array #Sliding_Window #2023_06_25_Time_465_ms_(33.33%)_Space_51.3_MB_(100.00%)
class Solution {
fun minSwaps(nums: IntArray): Int {
val l = nums.size
val ones = IntArray(l)
ones[0] = if (nums[0] == 1) 1 else 0
for (i in 1 until l) {
if (nums[i] == 1) {
ones[i] = ones[i - 1] + 1
} else {
ones[i] = ones[i - 1]
}
}
if (ones[l - 1] == l || ones[l - 1] == 0) {
return 0
}
val ws = ones[l - 1]
var minSwaps = Int.MAX_VALUE
var si = 0
var ei: Int
while (si < nums.size) {
ei = (si + ws - 1) % l
var totalones: Int
totalones = if (ei >= si) {
ones[ei] - if (si == 0) 0 else ones[si - 1]
} else {
ones[ei] + (ones[l - 1] - ones[si - 1])
}
val swapsreq = ws - totalones
if (swapsreq < minSwaps) {
minSwaps = swapsreq
}
si++
}
return minSwaps
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,175 | LeetCode-in-Kotlin | MIT License |
src/Day01.kt | samo1 | 573,449,853 | false | {"Kotlin": 4045} | import java.util.PriorityQueue
fun main() {
fun inputToCaloriesPerElf(input: List<String>): List<Int> {
val calories = mutableListOf<Int>()
var value = 0
input.forEach { line ->
if (line.trim() != "") {
value += line.toInt()
} else {
calories.add(value)
value = 0
}
}
if (value != 0) {
calories.add(value)
}
return calories
}
fun part1(input: List<String>): Int {
val calories = inputToCaloriesPerElf(input)
return calories.max()
}
fun part2(input: List<String>): Int {
val calories = inputToCaloriesPerElf(input)
val priorityQueue = PriorityQueue<Int>(calories.size, Comparator.reverseOrder())
priorityQueue.addAll(calories)
val elf1 = priorityQueue.poll()
val elf2 = priorityQueue.poll()
val elf3 = priorityQueue.poll()
return elf1 + elf2 + elf3
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 7)
check(part2(testInput) == 18)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 77e32453ba45bd4f9088f34be91939b94161cf13 | 1,276 | adventofcode2022 | Apache License 2.0 |
src/Day08.kt | dakr0013 | 572,861,855 | false | {"Kotlin": 105418} | import kotlin.test.assertEquals
fun main() {
fun part1(input: List<String>): Int {
var visibleTreeCount = (input.size - 1) * 4
for (row in 1 until input.size - 1) {
for (col in 1 until input.first().length - 1) {
val currentTree = input[row][col].digitToInt()
var isVisibleFromLeft = true
for (k in 0 until col) {
val aLeftTree = input[row][k]
if (aLeftTree.digitToInt() >= currentTree) {
isVisibleFromLeft = false
break
}
}
var isVisibleFromRight = true
for (k in col + 1 until input.first().length) {
val aRightTree = input[row][k]
if (aRightTree.digitToInt() >= currentTree) {
isVisibleFromRight = false
break
}
}
var isVisibleFromTop = true
for (k in 0 until row) {
val aTopTree = input[k][col]
if (aTopTree.digitToInt() >= currentTree) {
isVisibleFromTop = false
break
}
}
var isVisibleFromBottom = true
for (k in row + 1 until input.size) {
val aBottomTree = input[k][col]
if (aBottomTree.digitToInt() >= currentTree) {
isVisibleFromBottom = false
break
}
}
if (isVisibleFromLeft || isVisibleFromRight || isVisibleFromTop || isVisibleFromBottom)
visibleTreeCount++
}
}
return visibleTreeCount
}
fun part2(input: List<String>): Int {
val scenicScores = mutableListOf<Int>()
for (row in 1 until input.size - 1) {
for (col in 1 until input.first().length - 1) {
val currentTree = input[row][col].digitToInt()
var leftViewDistance = 0
for (k in col - 1 downTo 0) {
leftViewDistance++
val aLeftTree = input[row][k]
if (aLeftTree.digitToInt() >= currentTree) {
break
}
}
var rightViewDistance = 0
for (k in col + 1 until input.first().length) {
rightViewDistance++
val aRightTree = input[row][k]
if (aRightTree.digitToInt() >= currentTree) {
break
}
}
var topViewDistance = 0
for (k in row - 1 downTo 0) {
topViewDistance++
val aTopTree = input[k][col]
if (aTopTree.digitToInt() >= currentTree) {
break
}
}
var bottomViewDistance = 0
for (k in row + 1 until input.size) {
bottomViewDistance++
val aBottomTree = input[k][col]
if (aBottomTree.digitToInt() >= currentTree) {
break
}
}
val scenicScore =
leftViewDistance * rightViewDistance * topViewDistance * bottomViewDistance
scenicScores.add(scenicScore)
}
}
return scenicScores.max()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day08_test")
assertEquals(21, part1(testInput))
assertEquals(8, part2(testInput))
val input = readInput("Day08")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 6b3adb09f10f10baae36284ac19c29896d9993d9 | 3,157 | aoc2022 | Apache License 2.0 |
src/main/kotlin/com/exsilicium/scripture/shared/model/Location.kt | Ex-Silicium | 103,700,839 | false | null | package com.exsilicium.scripture.shared.model
import com.exsilicium.scripture.shared.extensions.compareChapterRanges
import com.exsilicium.scripture.shared.extensions.compareVerseRanges
import com.exsilicium.scripture.shared.extensions.createJoinedString
import com.exsilicium.scripture.shared.extensions.joinString
import java.util.SortedSet
/**
* A location in a [Book].
*
* A [Location] makes no guarantee that it is valid for any [Book].
*/
sealed class Location : Comparable<Location> {
internal abstract fun isValid(book: Book): Boolean
abstract override fun toString(): String
}
/**
* A sorted set of inclusive ranges of chapters.
*
* E.g. 1-2, 3-5, 7
*/
data class ChapterRanges(
val chapterRanges: SortedSet<ClosedRange<Int>>
) : Location() {
constructor(vararg ranges: ClosedRange<Int>) : this(ranges.toSortedSet(ChapterRangeComparator()))
init {
require(chapterRanges.isNotEmpty())
require(chapterRanges.first().start >= 1)
}
override fun isValid(book: Book) = chapterRanges.all { book.isValidChapterRange(it) }
override fun compareTo(other: Location) = when (other) {
is VerseRanges -> {
val startComparison = chapterRanges.first().start.compareTo(other.verseRanges.first().start.chapter)
when (startComparison) {
0 -> if (other.verseRanges.first().start.verseNumber == 1) 0 else -1
else -> startComparison
}
}
is ChapterRanges -> compareChapterRanges(other)
}
override fun toString() = chapterRanges.createJoinedString()
}
/**
* A sorted set of inclusive ranges of verses.
*
* E.g. 1:1-2:3b, 2:5
*/
data class VerseRanges(
val verseRanges: SortedSet<ClosedRange<Verse>>
) : Location() {
constructor(vararg ranges: ClosedRange<Verse>) : this(ranges.toSortedSet(VerseRangeComparator()))
init {
require(verseRanges.isNotEmpty())
}
override fun isValid(book: Book) = verseRanges.all { book.isValid(it.endInclusive) }
override fun compareTo(other: Location) = when (other) {
is ChapterRanges -> {
val startComparison = verseRanges.first().start.chapter.compareTo(other.chapterRanges.first().start)
when (startComparison) {
0 -> if (verseRanges.first().start.verseNumber == 1) 0 else 1
else -> startComparison
}
}
is VerseRanges -> compareVerseRanges(other)
}
override fun toString() = verseRanges.joinString()
}
| 14 | Kotlin | 1 | 1 | 4815f70f5736080d7533e0d1316f0aa2c31aa85a | 2,533 | scripture-core | Apache License 2.0 |
src/main/kotlin/com/pandarin/aoc2022/Day2.kt | PandarinDev | 578,619,167 | false | {"Kotlin": 6586} | package com.pandarin.aoc2022
import java.lang.IllegalArgumentException
enum class Outcome(val score: Int, val shapeToChoose: (Shape) -> Shape) {
LOSE(0, shapeToChoose = {
when (it) {
Shape.ROCK -> Shape.SCISSOR
Shape.PAPER -> Shape.ROCK
Shape.SCISSOR -> Shape.PAPER
}
}),
DRAW(3, shapeToChoose = { it }),
WIN(6, shapeToChoose = {
when (it) {
Shape.ROCK -> Shape.PAPER
Shape.PAPER -> Shape.SCISSOR
Shape.SCISSOR -> Shape.ROCK
}
});
companion object {
fun decrypt(encryptedOutcome: String) = when (encryptedOutcome) {
"X" -> LOSE
"Y" -> DRAW
"Z" -> WIN
else -> throw IllegalArgumentException()
}
}
}
enum class Shape(val score: Int, val outcomeAgainst: (Shape) -> Outcome) {
ROCK(1, outcomeAgainst = {
when (it) {
ROCK -> Outcome.DRAW
PAPER -> Outcome.LOSE
SCISSOR -> Outcome.WIN
}
}),
PAPER(2, outcomeAgainst = {
when (it) {
ROCK -> Outcome.WIN
PAPER -> Outcome.DRAW
SCISSOR -> Outcome.LOSE
}
}),
SCISSOR(3, outcomeAgainst = {
when (it) {
ROCK -> Outcome.LOSE
PAPER -> Outcome.WIN
SCISSOR -> Outcome.DRAW
}
});
companion object {
fun decrypt(encryptedShape: String) = when (encryptedShape) {
"A", "X" -> ROCK
"B", "Y" -> PAPER
"C", "Z" -> SCISSOR
else -> throw IllegalArgumentException()
}
}
}
fun main() {
val inputLines = Common.readInput("/day2.txt").split("\n").filter { it.isNotEmpty() }
var part1Score = 0
var part2Score = 0
for (line in inputLines) {
val (enemyShapeEncrypted, myActionEncrypted) = line.split(" ")
val enemyShape = Shape.decrypt(enemyShapeEncrypted)
val myShapePart1 = Shape.decrypt(myActionEncrypted)
val outcomePart1 = myShapePart1.outcomeAgainst.invoke(enemyShape)
val outcomePart2 = Outcome.decrypt(myActionEncrypted)
val myShapePart2 = outcomePart2.shapeToChoose.invoke(enemyShape)
part1Score += myShapePart1.score + outcomePart1.score
part2Score += myShapePart2.score + outcomePart2.score
}
println("Part1: $part1Score")
println("Part2: $part2Score")
} | 0 | Kotlin | 0 | 0 | 42c35d23129cc9f827db5b29dd10342939da7c99 | 2,433 | aoc2022 | MIT License |
2021/src/test/kotlin/Day02.kt | jp7677 | 318,523,414 | false | {"Kotlin": 171284, "C++": 87930, "Rust": 59366, "C#": 1731, "Shell": 354, "CMake": 338} | import kotlin.test.Test
import kotlin.test.assertEquals
class Day02 {
enum class Instruction { FORWARD, UP, DOWN }
data class Command(val instruction: Instruction, val units: Int)
data class Position(val position: Int, val depth: Int, val aim: Int)
@Test
fun `run part 01`() {
val positionTimesDepth = getCourse()
.groupingBy { it.instruction }
.fold(0) { acc, it -> acc + it.units }
.let { it.getValue(Instruction.FORWARD) * (it.getValue(Instruction.DOWN) - it.getValue(Instruction.UP)) }
assertEquals(1635930, positionTimesDepth)
}
@Test
fun `run part 02`() {
val positionTimesDepth = getCourse()
.fold(Position(0, 0, 0)) { acc, it ->
Position(
if (it.instruction == Instruction.FORWARD) acc.position + it.units else acc.position,
if (it.instruction == Instruction.FORWARD) acc.depth + acc.aim * it.units else acc.depth,
when (it.instruction) {
Instruction.DOWN -> acc.aim + it.units
Instruction.UP -> acc.aim - it.units
else -> acc.aim
}
)
}
.let { it.position * it.depth }
assertEquals(1781819478, positionTimesDepth)
}
private fun getCourse() = Util.getInputAsListOfString("day02-input.txt")
.map {
it
.split("\\s".toRegex())
.let { s -> Command(Instruction.valueOf(s.first().uppercase()), s.last().toInt()) }
}
}
| 0 | Kotlin | 1 | 2 | 8bc5e92ce961440e011688319e07ca9a4a86d9c9 | 1,613 | adventofcode | MIT License |
src/main/kotlin/solutions/Day20GrovePositioningSystem.kt | aormsby | 571,002,889 | false | {"Kotlin": 80084} | package solutions
import utils.Input
import utils.Solution
// run only this day
fun main() {
Day20GrovePositioningSystem()
}
class Day20GrovePositioningSystem : Solution() {
init {
begin("Day 20 - Grove Positioning System")
val input = Input.parseLines(filename = "/d20_encrypted_file.txt")
.mapIndexed { i, n -> Pair(i, n.toLong()) }
val sol1 = findGroveCoordinateSum(input)
output("Sum of Grove Coordinates", sol1)
val sol2 = findGroveCoordinateSum(input.map { Pair(it.first, it.second * 811_589_153) }, cycles = 10)
output("Sum of Decrypted Grove Coordinates", sol2)
}
private fun findGroveCoordinateSum(input: List<Pair<Int, Long>>, cycles: Int = 1): Long {
val switchList = input.toMutableList()
val size = switchList.size
for( c in 0 until cycles) {
input.forEachIndexed { i, pair ->
val oldI = switchList.indexOf(switchList.find { it.first == i })
var newI = (oldI + pair.second) % (size - 1)
if (newI <= 0) {
newI += size - 1
}
switchList.removeAt(oldI)
switchList.add(newI.toInt(), pair)
}
}
val z = switchList.indexOf(switchList.find { it.second == 0L })
val a = switchList[(z + 1000) % size].second
val b = switchList[(z + 2000) % size].second
val c = switchList[(z + 3000) % size].second
return a + b + c
}
} | 0 | Kotlin | 0 | 0 | 1bef4812a65396c5768f12c442d73160c9cfa189 | 1,524 | advent-of-code-2022 | MIT License |
src/Day10.kt | inssein | 573,116,957 | false | {"Kotlin": 47333} | fun main() {
fun buildSignal(input: List<String>): List<Int> {
return input.fold(listOf(1)) { acc, it ->
val register = acc.last()
when (it.take(4)) {
"noop" -> acc.plus(register)
"addx" -> acc.plus(listOf(register, register + it.substring(5).toInt()))
else -> acc
}
}
}
fun part1(input: List<String>): Int {
val signal = buildSignal(input)
return (20..signal.size step 40).sumOf {
it * signal[it - 1]
}
}
fun part2(input: List<String>): String {
return buildSignal(input)
.mapIndexed { index, signal ->
if (index % 40 in signal - 1..signal + 1) {
"#"
} else {
"."
}
}
.windowed(40, 40, false)
.joinToString("\n") {
it.joinToString("")
}
}
val testInput = readInput("Day10_test")
check(part1(testInput) == 13140)
check(
part2(testInput) == """
##..##..##..##..##..##..##..##..##..##..
###...###...###...###...###...###...###.
####....####....####....####....####....
#####.....#####.....#####.....#####.....
######......######......######......####
#######.......#######.......#######.....
""".trimIndent()
)
val input = readInput("Day10")
println(part1(input)) // 14160
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 095d8f8e06230ab713d9ffba4cd13b87469f5cd5 | 1,473 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/tr/emreone/adventofcode/Day19Github.kt | EmRe-One | 568,569,073 | false | {"Kotlin": 166986} | package tr.emreone.adventofcode
import tr.emreone.kotlin_utils.product
import kotlin.math.min
class Day19Github : Day(19, 2022, "Not Enough Minerals") {
val bps = input.map { it.extractAllIntegers() }.show()
val id = 0
val ORE_ROBOT_COST_ORE = 1
val CLAY_ROBOT_COST_ORE = 2
val OBSIDIAN_ROBOT_COST_ORE = 3
val OBSIDIAN_ROBOT_COST_CLAY = 4
val GEODE_ROBOT_COST_ORE = 5
val GEODE_ROBOT_COST_OBSIDIAN = 6
data class State(
val remainingTime: Int,
val ore: Int = 0,
val clay: Int = 0,
val obsidian: Int = 0,
val geode: Int = 0,
val oreRobots: Int = 1,
val clayRobots: Int = 0,
val obsidianRobots: Int = 0,
val geodeRobots: Int = 0,
)
override fun part1() = bps.sumOf { bp ->
log { "Checking $bp" }
val max = maxGeodeOpened(bp, 24).also { log { "this yields $it geodes" } }
max * bp[id]
}
override fun part2() = bps.take(3).map { bp ->
log { "Checking $bp" }
val max = maxGeodeOpened(bp, 32).also { log { "this yields $it geodes" } }
max
}.product()
private fun maxGeodeOpened(bp: List<Int>, time: Int): Int {
val maxSpendOre = listOf(
ORE_ROBOT_COST_ORE,
CLAY_ROBOT_COST_ORE,
OBSIDIAN_ROBOT_COST_ORE,
GEODE_ROBOT_COST_ORE
).maxOf { bp[it] }
val maxSpendClay = bp[OBSIDIAN_ROBOT_COST_CLAY]
val maxSpendObsidian = bp[GEODE_ROBOT_COST_OBSIDIAN]
var best = 0
val queue = ArrayDeque<State>()
queue.add(State(time))
val seen = HashSet<Any>()
while (queue.isNotEmpty()) {
val state = queue.removeFirst()
best = best.coerceAtLeast(state.geode)
if (state.remainingTime == 0) continue
val stateId = with(state) {
val o = ore.coerceAtMost(remainingTime * maxSpendOre - oreRobots * (remainingTime - 1))
val c = clay.coerceAtMost(remainingTime * maxSpendClay - clayRobots * (remainingTime - 1))
val ob = obsidian.coerceAtMost(remainingTime * maxSpendObsidian - obsidianRobots * (remainingTime - 1))
listOf(o, c, ob, geode, oreRobots, clayRobots, obsidianRobots, geodeRobots)
}
seen.add(stateId) || continue
if (seen.size % 1000000 == 0)
log { "${state.remainingTime} $best ${seen.size}" }
with(state) {
queue += copy(
remainingTime = remainingTime - 1,
ore = ore + oreRobots,
clay = clay + clayRobots,
obsidian = obsidian + obsidianRobots,
geode = geode + geodeRobots,
)
if (oreRobots < maxSpendOre && ore < maxSpendOre * remainingTime &&
ore >= bp[ORE_ROBOT_COST_ORE])
queue += copy(
remainingTime = remainingTime - 1,
ore = ore + oreRobots - bp[ORE_ROBOT_COST_ORE],
clay = clay + clayRobots,
obsidian = obsidian + obsidianRobots,
geode = geode + geodeRobots,
oreRobots = oreRobots + 1,
)
if (clayRobots < maxSpendClay && clay < maxSpendClay * remainingTime &&
ore >= bp[CLAY_ROBOT_COST_ORE])
queue += copy(
remainingTime = remainingTime - 1,
ore = ore + oreRobots - bp[CLAY_ROBOT_COST_ORE],
clay = clay + clayRobots,
obsidian = obsidian + obsidianRobots,
geode = geode + geodeRobots,
clayRobots = clayRobots + 1,
)
if (obsidianRobots < maxSpendObsidian && obsidian < maxSpendObsidian &&
ore >= bp[OBSIDIAN_ROBOT_COST_ORE] && clay >= bp[OBSIDIAN_ROBOT_COST_CLAY])
queue += copy(
remainingTime = remainingTime - 1,
ore = ore + oreRobots - bp[OBSIDIAN_ROBOT_COST_ORE],
clay = clay + clayRobots - bp[OBSIDIAN_ROBOT_COST_CLAY],
obsidian = obsidian + obsidianRobots,
geode = geode + geodeRobots,
obsidianRobots = obsidianRobots + 1,
)
if (ore >= bp[GEODE_ROBOT_COST_ORE] && obsidian >= bp[GEODE_ROBOT_COST_OBSIDIAN])
queue += copy(
remainingTime = remainingTime - 1,
ore = ore + oreRobots - bp[GEODE_ROBOT_COST_ORE],
clay = clay + clayRobots,
obsidian = obsidian + obsidianRobots - bp[GEODE_ROBOT_COST_OBSIDIAN],
geode = geode + geodeRobots,
geodeRobots = geodeRobots + 1,
)
}
}
return best
}
val dp = mutableMapOf<Any, Int>()
fun opt(
bp: List<Int>,
time: Int,
ore: Int = 0,
clay: Int = 0,
obsidian: Int = 0,
geode: Int = 0,
oreRobots: Int = 1,
clayRobots: Int = 0,
obsidianRobots: Int = 0,
geodeRobots: Int = 0,
): Int {
if (time == 0) return geode
val maxSpendOre = listOf(
ORE_ROBOT_COST_ORE,
CLAY_ROBOT_COST_ORE,
OBSIDIAN_ROBOT_COST_ORE,
GEODE_ROBOT_COST_ORE
).maxOf { bp[it] }
val t = time
val key = listOf(
time,
ore.coerceAtMost(t + maxSpendOre - oreRobots * (t - 1)),
clay.coerceAtMost(t * bp[OBSIDIAN_ROBOT_COST_CLAY] - clayRobots * (t - 1)),
obsidian.coerceAtMost(t * bp[GEODE_ROBOT_COST_OBSIDIAN] - obsidianRobots * (t - 1)),
geode,
oreRobots,
clayRobots,
obsidianRobots,
geodeRobots
)
dp[key]?.let { return it }
val nOre = ore + oreRobots
val nClay = clay + clayRobots
val nObsidian = obsidian + obsidianRobots
val nGeode = geode + geodeRobots
val maxOre = ore / bp[ORE_ROBOT_COST_ORE]
val maxClay = ore / bp[CLAY_ROBOT_COST_ORE]
val maxObsidian = min(ore / bp[OBSIDIAN_ROBOT_COST_ORE], clay / bp[OBSIDIAN_ROBOT_COST_CLAY])
val maxGeode = min(ore / bp[GEODE_ROBOT_COST_ORE], obsidian / bp[GEODE_ROBOT_COST_OBSIDIAN])
val max = listOfNotNull(
opt(bp, time - 1, nOre, nClay, nObsidian, nGeode, oreRobots, clayRobots, obsidianRobots, geodeRobots),
if (maxOre > 0 && oreRobots < maxSpendOre) opt(
bp,
time - 1,
nOre - bp[ORE_ROBOT_COST_ORE],
nClay,
nObsidian,
nGeode,
oreRobots + 1,
clayRobots,
obsidianRobots,
geodeRobots
) else null,
if (maxClay > 0 && clayRobots < bp[OBSIDIAN_ROBOT_COST_CLAY]) opt(
bp,
time - 1,
nOre - bp[CLAY_ROBOT_COST_ORE],
nClay,
nObsidian,
nGeode,
oreRobots,
clayRobots + 1,
obsidianRobots,
geodeRobots
) else null,
if (maxObsidian > 0 && obsidianRobots < bp[GEODE_ROBOT_COST_OBSIDIAN]) opt(
bp,
time - 1,
nOre - bp[OBSIDIAN_ROBOT_COST_ORE],
nClay - bp[OBSIDIAN_ROBOT_COST_CLAY],
nObsidian,
nGeode,
oreRobots,
clayRobots,
obsidianRobots + 1,
geodeRobots
) else null,
if (maxGeode > 0) opt(
bp,
time - 1,
nOre - bp[GEODE_ROBOT_COST_ORE],
nClay,
nObsidian - bp[GEODE_ROBOT_COST_OBSIDIAN],
nGeode,
oreRobots,
clayRobots,
obsidianRobots,
geodeRobots + 1
) else null,
).maxOf { it }
dp[key] = max
return max
}
fun part1A(): Any? {
return bps.sumOf { bp ->
println("Checking $bp")
dp.clear()
val max = opt(bp, 24)
(max.also { println("Yields $it") } * bp[id]).also { println("QL is $it") }
}
}
}
fun main() {
solve<Day19Github> {
"""
Blueprint 1: Each ore robot costs 4 ore. Each clay robot costs 2 ore. Each obsidian robot costs 3 ore and 14 clay. Each geode robot costs 2 ore and 7 obsidian.
Blueprint 2: Each ore robot costs 2 ore. Each clay robot costs 3 ore. Each obsidian robot costs 3 ore and 8 clay. Each geode robot costs 3 ore and 12 obsidian.
""".trimIndent() part1 33
}
} | 0 | Kotlin | 0 | 0 | a951d2660145d3bf52db5cd6d6a07998dbfcb316 | 9,091 | advent-of-code-2022 | Apache License 2.0 |
year2023/src/main/kotlin/net/olegg/aoc/year2023/day22/Day22.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.year2023.day22
import net.olegg.aoc.someday.SomeDay
import net.olegg.aoc.utils.Vector3D
import net.olegg.aoc.utils.parseInts
import net.olegg.aoc.utils.toPair
import net.olegg.aoc.year2023.DayOf2023
/**
* See [Year 2023, Day 22](https://adventofcode.com/2023/day/22)
*/
object Day22 : DayOf2023(22) {
private val Z_STEP = Vector3D(0, 0, 1)
override fun first(): Any? {
val start = lines
.map { line ->
line.split("~")
.map { it.parseInts(",") }
.map { Vector3D(it[0], it[1], it[2]) }
.toPair()
}
.sortedBy { minOf(it.first.z, it.second.z) }
val filled = mutableSetOf<Vector3D>()
val end = buildList {
start.forEach { brick ->
generateSequence(brick) { it.first - Z_STEP to it.second - Z_STEP }
.takeWhile { it.first.z > 0 && it.second.z > 0 }
.map {
val delta = it.second - it.first
val dir = delta.dir()
List(delta.manhattan() + 1) { i -> it.first + dir * i }
}
.takeWhile { blocks -> blocks.none { it in filled } }
.last()
.let {
add(it)
filled.addAll(it)
}
}
}
val supports = end.mapIndexed { a, blocksA ->
end.mapIndexedNotNull { b, blocksB ->
if (a != b && blocksA.any { it + Z_STEP in blocksB }) {
b
} else {
null
}
}
}
val revSupports = end.mapIndexed { a, blocksA ->
end.mapIndexedNotNull { b, blocksB ->
if (a != b && blocksB.any { it + Z_STEP in blocksA }) {
b
} else {
null
}
}
}
return supports.count { support ->
support.all { block -> revSupports[block].size > 1 }
}
}
override fun second(): Any? {
val start = lines
.map { line ->
line.split("~")
.map { it.parseInts(",") }
.map { Vector3D(it[0], it[1], it[2]) }
.toPair()
}
.sortedBy { minOf(it.first.z, it.second.z) }
val filled = mutableSetOf<Vector3D>()
val end = buildList {
start.forEach { brick ->
generateSequence(brick) { it.first - Z_STEP to it.second - Z_STEP }
.takeWhile { it.first.z > 0 && it.second.z > 0 }
.map {
val delta = it.second - it.first
val dir = delta.dir()
List(delta.manhattan() + 1) { i -> it.first + dir * i }
}
.takeWhile { blocks -> blocks.none { it in filled } }
.last()
.let {
add(it)
filled.addAll(it)
}
}
}
val supports = end.mapIndexed { a, blocksA ->
end.mapIndexedNotNull { b, blocksB ->
if (a != b && blocksA.any { it + Z_STEP in blocksB }) {
b
} else {
null
}
}
}
val revSupports = end.mapIndexed { a, blocksA ->
end.mapIndexedNotNull { b, blocksB ->
if (a != b && blocksB.any { it + Z_STEP in blocksA }) {
b
} else {
null
}
}
}
return List(supports.size) { i ->
val queue = ArrayDeque(listOf(i))
val fall = mutableSetOf<Int>()
while (queue.isNotEmpty()) {
val curr = queue.removeFirst()
if (curr !in fall) {
fall += curr
queue += supports[curr].filter { next ->
revSupports[next].all { it in fall }
}
}
}
fall.size - 1
}.sum()
}
}
fun main() = SomeDay.mainify(Day22)
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 3,542 | adventofcode | MIT License |
src/Day07.kt | ExpiredMinotaur | 572,572,449 | false | {"Kotlin": 11216} | fun main() {
val pattern = "\\\$ cd (.*)|(\\d+).*".toRegex()
var fs = emptyMap<String, Int>().toMutableMap()
fun loadFileSystem(input: List<String>){
fs = emptyMap<String, Int>().toMutableMap()
var dir = ""
for(line in input)
{
val match = pattern.matchEntire(line)?: continue
match.groups[1]?.value?.let {
dir = when(it)
{
"/" -> ""
".." -> dir.substringBeforeLast("/","")
else -> if(it.isEmpty()) dir else "$dir/$it"
}
}?: match.groups[2]?.value?.toIntOrNull()?.let {
var cd = dir
while(true)
{
fs[cd] = fs.getOrElse(cd){0}+it
if(cd.isEmpty()) break
cd= cd.substringBeforeLast("/","")
}
}
}
}
fun part1(): Int {
return fs.filter { (a,b)-> b <= 100000}.values.sum()
}
fun part2(): Int {
val total = fs.getValue("")
return fs.values.sorted().first { 70000000 - (total-it) >= 30000000 }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day07_test")
loadFileSystem(testInput)
check(part1() == 95437)
check(part2() == 24933642)
val input = readInput("Day07")
loadFileSystem(input)
println("Part 1: " + part1())
println("Part 2: " + part2())
} | 0 | Kotlin | 0 | 0 | 7ded818577737b0d6aa93cccf28f07bcf60a9e8f | 1,506 | AOC2022 | Apache License 2.0 |
src/main/kotlin/tr/emreone/adventofcode/days/Day04.kt | EmRe-One | 726,902,443 | false | {"Kotlin": 95869, "Python": 18319} | package tr.emreone.adventofcode.days
import tr.emreone.kotlin_utils.automation.Day
import kotlin.math.pow
class Day04 : Day(4, 2023, "Scratchcards") {
private fun parseMatches(input: List<String>): Map<Int, Int> {
return input.associate { line ->
val (card, game) = line.split(":")
val cardId = card.split("\\s+".toRegex())[1].toInt()
val (winningNumbers, yourNumbers) = game.split("|")
val winningNumberList = winningNumbers.trim().split("\\s+".toRegex())
val yourNumberList = yourNumbers.trim().split("\\s+".toRegex())
val matches = yourNumberList.count { it in winningNumberList }
cardId to matches
}
}
override fun part1(): Int {
return parseMatches(inputAsList)
.map { (_, matches) ->
if (matches == 0) {
0
} else {
2.0.pow(matches.toDouble() - 1).toInt()
}
}
.sum()
}
override fun part2(): Int {
val cards = parseMatches(inputAsList)
val scratchcards = MutableList(cards.size) {
0
}
cards.forEach { (id, score) ->
val currentIndex = id - 1
scratchcards[currentIndex]++
for (i in 1..score) {
if (currentIndex + i in scratchcards.indices) {
scratchcards[currentIndex + i] += scratchcards[currentIndex]
}
}
}
return scratchcards.sum()
}
}
| 0 | Kotlin | 0 | 0 | c75d17635baffea50b6401dc653cc24f5c594a2b | 1,569 | advent-of-code-2023 | Apache License 2.0 |
test/leetcode/RomanNumerals.kt | andrej-dyck | 340,964,799 | false | null | package leetcode
import lib.*
import net.jqwik.api.*
import org.assertj.core.api.Assertions.*
import org.junit.jupiter.api.*
import org.junit.jupiter.params.*
import org.junit.jupiter.params.provider.*
import java.util.regex.*
import kotlin.system.*
import kotlin.time.*
/**
* https://leetcode.com/problems/integer-to-roman/
*
* 12. Integer to Roman
* [Medium]
*
* Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
*
* Symbol Value
* I 1
* V 5
* X 10
* L 50
* C 100
* D 500
* M 1000
*
* For example, 2 is written as II in Roman numeral, just two one's added together.
* 12 is written as XII, which is simply X + II.
* The number 27 is written as XXVII, which is XX + V + II.
*
* Roman numerals are usually written largest to smallest from left to right.
* However, the numeral for four is not IIII. Instead, the number four is written as IV.
* Because the one is before the five we subtract it making four.
* The same principle applies to the number nine, which is written as IX.
* There are six instances where subtraction is used:
*
* - I can be placed before V (5) and X (10) to make 4 and 9.
* - X can be placed before L (50) and C (100) to make 40 and 90.
* - C can be placed before D (500) and M (1000) to make 400 and 900.
*
* Given an integer, convert it to a roman numeral.
*
* Constraints:
* - 1 <= num <= 3999
*/
fun Int.toRoman(): String {
require(this in (1..3999))
tailrec fun reverseRN(rn: String, n: Int): String = when {
n >= 1000 -> reverseRN("M$rn", n - 1000)
n >= 900 -> reverseRN("MC$rn", n - 900)
n >= 500 -> reverseRN("D$rn", n - 500)
n >= 400 -> reverseRN("DC$rn", n - 400)
n >= 100 -> reverseRN("C$rn", n - 100)
n >= 90 -> reverseRN("CX$rn", n - 90)
n >= 50 -> reverseRN("L$rn", n - 50)
n >= 40 -> reverseRN("LX$rn", n - 40)
n >= 10 -> reverseRN("X$rn", n - 10)
n >= 9 -> reverseRN("XI$rn", n - 9)
n >= 5 -> reverseRN("V$rn", n - 5)
n >= 4 -> reverseRN("VI$rn", n - 4)
n >= 1 -> reverseRN("I$rn", n - 1)
else -> rn
}
return reverseRN("", this).reversed()
}
/**
* Unit tests
*/
class RomanNumeralsTest {
@ParameterizedTest
@CsvSource(
"1, I",
"2, II",
"3, III",
"4, IV",
"5, V",
"8, VIII",
"9, IX",
"10, X",
"12, XII",
"27, XXVII",
"49, XLIX",
"50, L",
"169, CLXIX",
"3999, MMMCMXCIX",
)
fun `quick check typical roman numerals`(n: Int, expectedRomanNumeral: String) {
assertThat(
n.toRoman()
).isEqualTo(
expectedRomanNumeral
)
}
@ParameterizedTest
@CsvSource("1, I", "5, V", "10, X", "50, L", "100, C", "500, D", "1000, M")
fun `roman digits correspond to correct values`(n: Int, expectedRomanNumeral: String) {
assertThat(
n.toRoman()
).isEqualTo(
expectedRomanNumeral
)
}
@ParameterizedTest
@CsvSource("4, IV", "9, IX", "40, XL", "90, XC", "400, CD", "900, CM")
fun `valid subtractions correspond to correct values`(n: Int, expectedRomanNumeral: String) {
assertThat(
n.toRoman()
).isEqualTo(
expectedRomanNumeral
)
}
@ParameterizedTest
@ValueSource(ints = [0, -1, -17])
fun `roman numerals do not support 0 and negative integers`(nonPositiveInteger: Int) {
assertThrows<IllegalArgumentException> {
nonPositiveInteger.toRoman()
}
}
@ParameterizedTest
@ValueSource(ints = [4000, 4001, 17358])
fun `roman numerals do not support integers larger than 3999`(largeInteger: Int) {
assertThrows<IllegalArgumentException> {
largeInteger.toRoman()
}
}
}
class RomanNumeralsPropertiesTest {
private val romanSymbols1s = mapOf("I" to 1, "X" to 10, "C" to 100, "M" to 1000)
private val romanSymbols5s = mapOf("V" to 5, "L" to 50, "D" to 500)
private val romanSymbols = romanSymbols1s.plus(romanSymbols5s)
@Property
fun `comprises only roman symbols`(@ForAll("1 to 3999") n: Int) {
val romanNumeral = n.toRoman()
assertThat(romanNumeral)
.`as`("$n as $romanNumeral must comprises only roman symbols")
.matches(nonEmptyRomanSymbolsPattern)
}
private val nonEmptyRomanSymbolsPattern by lazy {
romanSymbols.keys.joinToString(separator = "|", prefix = "(", postfix = ")+").toPattern()
}
@Property
fun `comprises at most 3 of 'I', 'X', 'C', and 'M' in a row`(@ForAll("1 to 3999") n: Int) {
val romanNumeral = n.toRoman()
assertThat(romanNumeral.count(romanSymbols1s.keys.map { it.repeat(4) }))
.`as`("$n as $romanNumeral must comprise %s most 3 times", romanSymbols1s.keys)
.allMatch { it == 0 }
}
@Property
fun `comprises at most 4 of 'I', 'X', 'C', and 'M'`(@ForAll("1 to 3999") n: Int) {
val romanNumeral = n.toRoman()
assertThat(romanNumeral.count(romanSymbols1s.keys))
.`as`("$n as $romanNumeral must comprise %s most 3 times", romanSymbols1s.keys)
.allMatch { it <= 4 }
}
@Property
fun `comprises at most 1 of 'V', 'L', and 'D'`(@ForAll("1 to 3999") n: Int) {
val romanNumeral = n.toRoman()
assertThat(romanNumeral.count(romanSymbols5s.keys))
.`as`("$n as $romanNumeral must comprise %s most 1 time", romanSymbols5s.keys)
.allMatch { it <= 1 }
}
@Property
fun `has no illegal subtractions like 'VX' or 'IL'`(@ForAll("1 to 3999") n: Int) {
val romanNumeral = n.toRoman()
assertThat(romanNumeral.count(illegalSubtractions))
.`as`(
"$n as $romanNumeral must not comprise any of illegal subtractions %s",
illegalSubtractions
)
.allMatch { it == 0 }
}
private val illegalSubtractions = listOf("IL", "IC", "ID", "IM", "XD", "XM")
@Property
fun `has no ambiguous sequences like 'IVI' or 'CDC'`(@ForAll("1 to 3999") n: Int) {
val romanNumeral = n.toRoman()
assertThat(romanNumeral.count(ambiguousSequences))
.`as`(
"$n as $romanNumeral must not comprise any ambiguities; i.e. %s",
ambiguousSequences
)
.allMatch { it == 0 }
}
private val ambiguousSequences = listOf("IVI", "IXI", "XLX", "XCX", "CDC")
@Property
fun `symbol values decrease monotonically`(@ForAll("1 to 3999") n: Int) {
val romanNumeral = n.toRoman()
val simplifiedRomanNumeral = simplified(romanNumeral)
assertThat(simplifiedRomanNumeral.pairs())
.`as`(
"$n as $romanNumeral (as simplified $simplifiedRomanNumeral)" +
" must comprise of monotonically decreasing symbol values"
)
.allMatch { (d1, d2) -> romanSymbols.getValue(d1) >= romanSymbols.getValue(d2) }
}
@Property
fun `converted back yields number`(@ForAll("1 to 3999") n: Int) {
val romanNumeral = n.toRoman()
assertThat(romanNumeralToInt(romanNumeral))
.`as`("$n as $romanNumeral must convert back to $n")
.isEqualTo(n)
}
private fun romanNumeralToInt(romanNumeral: String) =
simplified(romanNumeral).map { romanSymbols.getValue(it.toString()) }.sum()
private fun simplified(romanNumeral: String) =
romanNumeral
.replace("IV", "IIII")
.replace("IX", "VIIII")
.replace("XL", "XXXX")
.replace("XC", "LXXXX")
.replace("CD", "CCCC")
.replace("CM", "DCCCC")
@Provide("1 to 3999")
@Suppress("unused")
private fun numbers(): Arbitrary<Int> = Arbitraries.integers().between(1, 3999)
}
private fun String.count(string: String) = this.split(string).size - 1
private fun String.count(strings: Iterable<String>) = strings.map { count(it) }
private fun String.pairs() = windowed(2).map { it.take(1) to it.drop(1).take(1) } | 0 | Kotlin | 0 | 0 | 3e3baf8454c34793d9771f05f330e2668fda7e9d | 8,211 | coding-challenges | MIT License |
src/Day09.kt | fercarcedo | 573,142,185 | false | {"Kotlin": 60181} | import kotlin.math.abs
enum class MotionDirection {
UP, DOWN, RIGHT, LEFT
}
data class Motion(val direction: MotionDirection, val numberOfSteps: Int)
private val LINE_REGEX = "(?<direction>[UDRL])\\s+(?<steps>\\d+)".toRegex()
private const val NUM_TAILS = 9
fun main() {
fun isAdjacent(headPosition: Pair<Int, Int>, tailPosition: Pair<Int, Int>) =
abs(headPosition.first - tailPosition.first) <= 1 && abs(headPosition.second - tailPosition.second) <= 1
fun parseMotions(input: List<String>) = input.map {
val match = LINE_REGEX.matchEntire(it)
val direction = when(match!!.groups["direction"]!!.value) {
"U" -> MotionDirection.UP
"D" -> MotionDirection.DOWN
"R" -> MotionDirection.RIGHT
else -> MotionDirection.LEFT
}
Motion(direction, match.groups["steps"]!!.value.toInt())
}
fun moveHead(headPosition: Pair<Int, Int>, motion: Motion) = when (motion.direction) {
MotionDirection.UP -> {
headPosition.copy(second = headPosition.second + 1)
}
MotionDirection.DOWN -> {
headPosition.copy(second = headPosition.second - 1)
}
MotionDirection.RIGHT -> {
headPosition.copy(first = headPosition.first + 1)
}
else -> {
headPosition.copy(first = headPosition.first - 1)
}
}
fun moveKnot(headPosition: Pair<Int, Int>, tails: List<Pair<Int, Int>>, tailIndex: Int): Pair<Int, Int> {
val previousKnotPos = if (tailIndex == 0) headPosition else tails[tailIndex - 1]
var tailPosition = tails[tailIndex]
if (!isAdjacent(previousKnotPos, tailPosition)) {
if (previousKnotPos.second == tailPosition.second && abs(previousKnotPos.first - tailPosition.first) == 2) {
tailPosition = tailPosition.copy(first = if (previousKnotPos.first > tailPosition.first) tailPosition.first + 1 else tailPosition.first - 1)
} else if (previousKnotPos.first == tailPosition.first && abs(previousKnotPos.second - tailPosition.second) == 2) {
tailPosition = tailPosition.copy(second = if (previousKnotPos.second > tailPosition.second) tailPosition.second + 1 else tailPosition.second - 1)
} else if (abs(previousKnotPos.first - tailPosition.first) >= 1 && abs(previousKnotPos.second - tailPosition.second) >= 1) {
tailPosition = tailPosition.copy(
first = if (previousKnotPos.first > tailPosition.first) tailPosition.first + 1 else tailPosition.first - 1,
second = if (previousKnotPos.second > tailPosition.second) tailPosition.second + 1 else tailPosition.second - 1
)
}
}
return tailPosition
}
fun executeMotions(motions: List<Motion>): List<Set<Pair<Int, Int>>> {
var headPosition: Pair<Int, Int> = 0 to 0
val tails: MutableList<Pair<Int, Int>> = mutableListOf()
val tailsPositions: MutableList<MutableSet<Pair<Int, Int>>> = mutableListOf()
repeat(NUM_TAILS) {
tails.add(0 to 0)
tailsPositions.add(mutableSetOf())
}
for (motion in motions) {
for (i in 0 until motion.numberOfSteps) {
headPosition = moveHead(headPosition, motion)
for (i in 0 until tails.size) {
tails[i] = moveKnot(headPosition, tails, i)
tailsPositions[i].add(tails[i])
}
}
}
return tailsPositions
}
fun play(input: List<String>): List<Set<Pair<Int, Int>>> {
val motions = parseMotions(input)
return executeMotions(motions)
}
fun part1(input: List<String>) = play(input).first().size
fun part2(input: List<String>) = play(input).last().size
val testInput = readInput("Day09_test")
check(part1(testInput) == 13)
check(part2(testInput) == 1)
val testInput2 = readInput("Day09_test2")
check(part2(testInput2) == 36)
val input = readInput("Day09")
println(part1(input)) // 6271
println(part2(input)) // 2458
}
| 0 | Kotlin | 0 | 0 | e34bc66389cd8f261ef4f1e2b7f7b664fa13f778 | 4,153 | Advent-of-Code-2022-Kotlin | Apache License 2.0 |
src/main/kotlin/Main.kt | nschulzke | 571,330,516 | false | {"Kotlin": 5085} | package com.nschulzke
enum class Stars {
One, Two, Three;
}
private val mancalaIndices = setOf(6, 13)
data class Puzzle(
private val board: List<Int>,
private val turns: Int,
private val targets: List<Pair<Stars, Int>>,
val steps: List<Int> = emptyList(),
) {
fun onBottom(pit: Int): Boolean =
pit in 0..5
fun onTop(pit: Int): Boolean =
pit in 7..12
fun opposite(pit: Int): Int =
when (pit) {
0 -> 12
1 -> 11
2 -> 10
3 -> 9
4 -> 8
5 -> 7
7 -> 5
8 -> 4
9 -> 3
10 -> 2
11 -> 1
12 -> 0
else -> throw IllegalArgumentException("Pit $pit has no opposite")
}
fun move(pit: Int): Puzzle {
if (board[pit] == 0) {
throw Error("Cannot move empty pit")
}
if (pit in mancalaIndices) {
throw Error("Cannot move mancala")
}
val mutableBoard = board.toMutableList()
val stones = mutableBoard[pit]
mutableBoard[pit] = 0
var index = pit
for (i in 1..stones) {
index = (index + 1) % mutableBoard.size
mutableBoard[index]++
}
// If the final pit is opposite of another pit that is not empty, capture all pieces
if (index !in mancalaIndices) {
val oppositeIndex = opposite(index)
val mancala = if (onBottom(index)) {
6
} else {
13
}
if (mutableBoard[index] == 1 && mutableBoard[oppositeIndex] > 0) {
mutableBoard[mancala] += mutableBoard[oppositeIndex] + 1
mutableBoard[index] = 0
mutableBoard[oppositeIndex] = 0
}
}
return this.copy(
board = mutableBoard,
turns = if (index !in mancalaIndices) {
turns - 1
} else {
turns
},
steps = steps + pit
)
}
private fun pitToString(index: Int): String =
board[index].toString().padStart(2, ' ')
fun score(): Int =
board[6] + board[13]
fun starRating(): Stars? =
targets.lastOrNull { score() >= it.second }?.first
fun isComplete(): Boolean =
turns <= 0 || starRating() == Stars.Three
fun nonEmptyPitIndices(): Iterable<Int> =
board.indices.filter { board[it] > 0 && !mancalaIndices.contains(it) }
override fun toString(): String {
return """
| ${pitToString(12)} ${pitToString(11)} ${pitToString(10)} ${pitToString(9)} ${pitToString(8)} ${pitToString(7)}
|${pitToString(13)} ${pitToString(6)}
| ${pitToString(0)} ${pitToString(1)} ${pitToString(2)} ${pitToString(3)} ${pitToString(4)} ${pitToString(5)}
|${turns} turns left
""".trimMargin()
}
}
class Solver {
// Use a search tree to find the minimum number of moves to get 3 stars' worth of stones in the mancalas.
fun solve(startingPuzzle: Puzzle): Puzzle? {
val queue = mutableListOf(startingPuzzle)
val visited = mutableSetOf(startingPuzzle)
while (queue.isNotEmpty()) {
val puzzle = queue.removeAt(0)
if (puzzle.isComplete()) {
if (puzzle.starRating() == Stars.Three) {
return puzzle
}
} else {
for (pit in puzzle.nonEmptyPitIndices()) {
val nextGame = puzzle.move(pit)
if (nextGame !in visited) {
queue.add(nextGame)
visited.add(nextGame)
}
}
}
}
return null
}
companion object {
@JvmStatic
fun main(args: Array<String>) {
val puzzle = Puzzle(
board = mutableListOf(
1, 0, 3, 0, 4, 0, 0,
1, 0, 0, 0, 2, 0, 0,
),
turns = 3,
targets = listOf(
Stars.One to 8,
Stars.Two to 9,
Stars.Three to 10,
),
)
println(puzzle)
val solver = Solver()
val solution = solver.solve(puzzle)
if (solution == null) {
println("No solution found.")
} else {
solution.steps.fold(puzzle) { acc, next ->
acc.move(next).also { println("\nAfter moving $next:\n$it") }
}
}
}
}
}
| 0 | Kotlin | 0 | 0 | b130d3b1521b0a8cc9442b7afc97a951a01ced69 | 4,700 | mancala-puzzle-solver | MIT License |
src/Day22.kt | max-zhilin | 573,066,300 | false | {"Kotlin": 114003} | import java.util.*
const val RIGHT = 0
const val DOWN = 1
const val LEFT = 2
const val UP = 3
const val VOID = ' '
const val OPEN = '.'
const val WALL = '#'
fun transpose(side: Array<CharArray>): Array<CharArray> {
for (i in 1..side.lastIndex) for (j in 0..i) {
side[i][j] = side[j][i].also { side[j][i] = side[i][j] }
}
return side
}
fun rotateClockwise(side: Array<CharArray>): Array<CharArray> {
return transpose(side.reversed().toTypedArray())
}
fun main() {
fun part1(input: List<String>): Int {
val maxRow = input.size - 3
val maxCol = input.takeWhile { it.isNotBlank() }.maxOf { it.length } - 1
val board = Array(maxRow + 3) { Array(maxCol + 3) { VOID } } // leave void border
input.takeWhile { it.isNotBlank() }.forEachIndexed { row, line ->
line.forEachIndexed { col, c ->
if (c == OPEN || c == WALL) board[row + 1][col + 1] = c
}
}
val path = """(\d+|[LR])""".toRegex().findAll(input.last()) // 10R5L5R10L4R5L5
var (row, col) = listOf(1, board[1].indexOf(OPEN))
var facing = RIGHT
fun moveToWall(steps: Int, rowDiff: Int, colDiff: Int) {
repeat(steps) {
var rowNew = row + rowDiff
var colNew = col + colDiff
// skip void
while (board[rowNew][colNew] == VOID) {
rowNew = (board.size + rowNew + rowDiff) % board.size
colNew = (board[0].size + colNew + colDiff) % board[0].size
}
if (board[rowNew][colNew] == WALL) return
else {
row = rowNew
col = colNew
}
}
}
fun move(steps: Int) {
when(facing) {
RIGHT -> moveToWall(steps, 0, 1)
DOWN -> moveToWall(steps, 1, 0)
LEFT -> moveToWall(steps, 0, -1)
UP -> moveToWall(steps, -1, 0)
}
}
path.forEach { turn ->
when(turn.value) {
"L" -> facing = (4 + facing - 1) % 4
"R" -> facing = (4 + facing + 1) % 4
else -> move(turn.value.toInt())
}
}
return 1000 * (row) + 4 * (col) + facing
}
fun part2(input: List<String>, size: Int, inputNet: List<String>): Int {
val cube = Array(6) { Array(size) { CharArray(size) { OPEN } } }
val rotation = IntArray(6)
val maxPos = size - 1
inputNet.forEach { chunk ->
val side = chunk[0] - 'A'
val rowFactor = chunk[1].digitToInt()
val colFactor = chunk[2].digitToInt()
val rotationOfSide = chunk[3].digitToInt()
for (row in 0 until size) for (col in 0 until size)
cube[side][row][col] = input[row + rowFactor * size][col + colFactor * size]
repeat(4 - rotationOfSide) {
cube[side] = rotateClockwise(cube[side])
}
rotation[side] = rotationOfSide
}
val path = """(\d+|[LR])""".toRegex().findAll(input.last()) // 10R5L5R10L4R5L5
var row = 0; var col = 0
var side = 0
var facing = RIGHT
fun move(steps: Int) {
repeat(steps) {
var (rowNew, colNew) = when(facing) {
RIGHT -> listOf(row, col + 1)
DOWN -> listOf(row + 1, col)
LEFT -> listOf(row, col - 1)
UP -> listOf(row - 1, col)
else -> error("facing $facing")
}
var sideNew = side
var facingNew = facing
if (rowNew == -1) {
sideNew = (6 + side - 1) % 6
if (sideNew % 2 == 0) {
rowNew = maxPos - colNew
colNew = maxPos
facingNew = LEFT
} else {
rowNew = colNew
colNew = 0
facingNew = RIGHT
}
}
if (rowNew == maxPos + 1) {
sideNew = (6 + side + 2) % 6
if (sideNew % 2 == 0) {
rowNew = maxPos - colNew
colNew = 0
facingNew = RIGHT
} else {
rowNew = colNew
colNew = maxPos
facingNew = LEFT
}
}
if (colNew == -1)
if (side % 2 == 0) {
sideNew = (6 + side - 2) % 6
colNew = maxPos - rowNew
rowNew = maxPos
facingNew = UP
} else {
sideNew = (6 + side + 1) % 6
colNew = rowNew
rowNew = 0
facingNew = DOWN
}
if (colNew == maxPos + 1)
if (side % 2 == 0) {
sideNew = (6 + side + 1) % 6
colNew = maxPos - rowNew
rowNew = 0
facingNew = DOWN
} else {
sideNew = (6 + side - 2) % 6
colNew = rowNew
rowNew = maxPos
facingNew = UP
}
if (cube[sideNew][rowNew][colNew] == WALL) return
else {
row = rowNew
col = colNew
side = sideNew
facing = facingNew
}
}
}
fun net(): Array<CharArray> {
val maxRow = input.size - 3
val maxCol = input.takeWhile { it.isNotBlank() }.maxOf { it.length } - 1
val board = Array(maxRow + 1) { CharArray(maxCol + 1) { VOID } }
for ((i, cubeFace) in cube.withIndex()) {
var face = cubeFace.map { it.clone() }.toTypedArray()
if (i == side) face[row][col] = 'O'
val chunk = inputNet.first { it.first() == 'A' + i }
val rowFactor = chunk[1].digitToInt()
val colFactor = chunk[2].digitToInt()
val rotationOfSide = chunk[3].digitToInt()
repeat(rotationOfSide) {
face = rotateClockwise(face)
}
for (r in 0 until size) for (c in 0 until size)
board[r + rowFactor * size][c + colFactor * size] = face[r][c]
}
return board
}
fun printBoard() {
val board = net()
val r = board.indexOfFirst { it.contains('O') }
val c = board[r].indexOf('O')
board[r][c] = ">v<^"[(facing + rotation[side]) % 4]
println(board.joinToString("\n") { it.joinToString("") })
println()
}
printBoard()
path.forEach { turn ->
when(turn.value) {
"L" -> facing = (4 + facing - 1) % 4
"R" -> facing = (4 + facing + 1) % 4
else -> move(turn.value.toInt())
}
printBoard()
}
val board = net()
val r = board.indexOfFirst { it.contains('O') }
val c = board[r].indexOf('O')
return 1000 * (r + 1) + 4 * (c + 1) + (facing + rotation[side]) % 4
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day22_test")
// val testInput2 = readInput("Day22_test2")
// println(part1(testInput))
// check(part1(testInput2) == 33)
// check(part1(testInput) == 6032)
// println(part2(testInput, 4, "A020 F101 E112 C121 D220 B231 ".chunked(5))) // cube row col rot
check(part2(testInput, 4, "A020 F101 E112 C121 D220 B231 ".chunked(5)) == 5031)
@Suppress("UNUSED_VARIABLE")
val input = readInput("Day22")
// check(part1(input)) ==
// check(part2(input)) == 53324
// println(part1(input))
println(part2(input, 50, "A010 B023 C111 E201 D210 F300 ".chunked(5)))
}
| 0 | Kotlin | 0 | 0 | d9dd7a33b404dc0d43576dfddbc9d066036f7326 | 8,313 | AoC-2022 | Apache License 2.0 |
src/main/kotlin/aoc2015/Day22.kt | lukellmann | 574,273,843 | false | {"Kotlin": 175166} | package aoc2015
import AoCDay
import util.match
// https://adventofcode.com/2015/day/22
object Day22 : AoCDay<Int>(
title = "Wizard Simulator 20XX",
part1Answer = 1824,
part2Answer = 1937,
) {
private class Spell(val mana: Int, val effect: Effect? = null, val damage: Int = 0, val heal: Int = 0)
private class Effect(val duration: Int, val armor: Int = 0, val damage: Int = 0, val mana: Int = 0)
private val SPELLS = listOf(
Spell(mana = 53, damage = 4),
Spell(mana = 73, damage = 2, heal = 2),
Spell(mana = 113, Effect(duration = 6, armor = 7)),
Spell(mana = 173, Effect(duration = 6, damage = 3)),
Spell(mana = 229, Effect(duration = 5, mana = 101)),
)
private val BOSS_REGEX = """
Hit Points: (\d+)
Damage: (\d+)
""".trimIndent().toRegex()
private fun parseBoss(input: String): Boss {
val (hp, damage) = BOSS_REGEX.match(input).toList().map(String::toInt)
return Boss(hp, damage)
}
private data class Boss(val hp: Int, val damage: Int) {
init {
require(damage >= 0)
}
}
private data class Player(
val hp: Int,
val armor: Int,
val mana: Int,
val manaSpent: Int,
val effects: Map<Effect, Int>,
)
private sealed interface State {
object Lost : State
class Won(val manaSpent: Int) : State
class Undecided(val player: Player, val boss: Boss, private val hard: Boolean) : State {
fun copy(player: Player = this.player, boss: Boss = this.boss) = when {
player.hp <= 0 -> Lost
boss.hp <= 0 -> Won(manaSpent = player.manaSpent)
else -> Undecided(player, boss, hard)
}
fun lose1HpIfHard() = if (hard) copy(player = player.copy(hp = player.hp - 1)) else this
}
fun applyEffects(): State {
if (this !is Undecided) return this
val effects = player.effects.keys
val armor = effects.sumOf { it.armor }
val damage = effects.sumOf { it.damage }
val mana = effects.sumOf { it.mana }
return copy(
player = player.copy(
armor = armor,
mana = player.mana + mana,
effects = player.effects.filterValues { it > 1 }.mapValues { (_, d) -> d - 1 },
),
boss = boss.copy(hp = boss.hp - damage),
)
}
fun castSpell(spell: Spell) = if (this !is Undecided) this else copy(
player = player.copy(
hp = player.hp + spell.heal,
mana = player.mana - spell.mana,
manaSpent = player.manaSpent + spell.mana,
effects = spell.effect?.let { e -> player.effects + (e to e.duration) } ?: player.effects,
),
boss = boss.copy(hp = boss.hp - spell.damage),
)
fun bossAttack(): State {
if (this !is Undecided) return this
val dmg = (boss.damage - player.armor).coerceAtLeast(1)
return copy(player = player.copy(hp = player.hp - dmg))
}
}
private inline fun State.ifUndecided(action: State.Undecided.() -> Int?) = when (this) {
State.Lost -> null
is State.Won -> manaSpent
is State.Undecided -> action()
}
private fun bossTurn(state: State.Undecided): Int? = state
.applyEffects()
.bossAttack()
.ifUndecided(::playerTurn)
private fun playerTurn(state: State.Undecided): Int? = state
.lose1HpIfHard()
.applyEffects()
.ifUndecided {
SPELLS.filter { it.mana <= player.mana && it.effect !in player.effects }
.minOfWithOrNull(nullsLast()) { castSpell(it).ifUndecided(::bossTurn) }
}
private val INITIAL_PLAYER = Player(hp = 50, armor = 0, mana = 500, manaSpent = 0, effects = emptyMap())
private fun leastManaSpentToWin(input: String, hard: Boolean) =
playerTurn(State.Undecided(player = INITIAL_PLAYER, boss = parseBoss(input), hard)) ?: error("can't win")
override fun part1(input: String) = leastManaSpentToWin(input, hard = false)
override fun part2(input: String) = leastManaSpentToWin(input, hard = true)
}
| 0 | Kotlin | 0 | 1 | 344c3d97896575393022c17e216afe86685a9344 | 4,326 | advent-of-code-kotlin | MIT License |
src/main/kotlin/com/hj/leetcode/kotlin/problem1296/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem1296
import java.util.*
/**
* LeetCode page: [1296. Divide Array in Sets of K Consecutive Numbers](https://leetcode.com/problems/divide-array-in-sets-of-k-consecutive-numbers/);
*/
class Solution {
/* Complexity:
* Time O(NLogN) and Space O(N) where N is the size of nums;
*/
fun isPossibleDivide(nums: IntArray, k: Int): Boolean {
val countPerSortedNum = getCountPerNumSortedByNum(nums)
return isPossibleDivide(countPerSortedNum, k)
}
private fun getCountPerNumSortedByNum(nums: IntArray): SortedMap<Int, Int> {
val counts = sortedMapOf<Int, Int>()
for (num in nums) {
val currCount = counts[num] ?: 0
counts[num] = currCount + 1
}
return counts
}
private fun isPossibleDivide(countPerSortedNum: SortedMap<Int, Int>, k: Int): Boolean {
for (start in countPerSortedNum.keys) {
val countOfStart = checkNotNull(countPerSortedNum[start])
if (countOfStart == 0) continue
val end = start + k - 1
for (num in start..end) {
val countOfNum = countPerSortedNum[num] ?: 0
if (countOfNum < countOfStart) return false
countPerSortedNum[num] = countOfNum - countOfStart
}
}
return true
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 1,366 | hj-leetcode-kotlin | Apache License 2.0 |
src/Day16.kt | MarkTheHopeful | 572,552,660 | false | {"Kotlin": 75535} | import kotlin.math.max
import kotlin.math.min
private class Valve(val flowRate: Int, val totalIndex: Int) {
var open = false
val tunnelsIndices = mutableListOf<Int>()
var indexInNonZero = -1
}
private var SHIFT = 58
fun calculateHorribleKey(currentValveInd: Int, elephantValveInd: Int, mask: Int): Int {
return min(currentValveInd, elephantValveInd) + SHIFT * max(
currentValveInd,
elephantValveInd
) + SHIFT * SHIFT * mask
}
fun main() {
val lastParsed = mutableListOf<Valve>()
fun parseValves(input: List<String>): Pair<Valve, Int> {
lastParsed.clear()
val nameToValve = mutableMapOf<String, Valve>()
input.withIndex().forEach {
val (_, name, _, _, withFlow) = it.value.split(" ")
lastParsed.add(Valve(withFlow.split("=", ";")[1].toInt(), it.index))
nameToValve[name] = lastParsed.last()
}
input.forEach {
val (_, name) = it.split(" ")
val leadsTo = it.split(", ").map { it2 -> it2.takeLast(2) }
nameToValve[name]?.tunnelsIndices?.addAll(leadsTo.mapNotNull { it2 -> nameToValve[it2]?.totalIndex })
?: error("Valve disappeared?")
}
var nonZeroAmount = 0
nameToValve.forEach {
if (it.value.flowRate != 0) {
it.value.indexInNonZero = nonZeroAmount++
}
}
SHIFT = (input.size + 1)
return (nameToValve["AA"] ?: error("No starting valve?")) to nonZeroAmount
}
val memory: MutableMap<Pair<Pair<Int, Int>, Int>, Int> = mutableMapOf()
fun walkExponentially(
currentValve: Valve, mask: Int, currentFlow: Int = 0, timeLeft: Int = 30
): Int {
if (timeLeft == 0) return 0
if ((currentValve.totalIndex to timeLeft) to mask in memory) {
return memory[(currentValve.totalIndex to timeLeft) to mask]!! + currentFlow // We have just checked it
}
var maxAchievedAnswerAfterUs = currentFlow * (timeLeft - 1) // To stay here
if (!currentValve.open && currentValve.flowRate != 0) {
currentValve.open = true
maxAchievedAnswerAfterUs = max(
maxAchievedAnswerAfterUs, walkExponentially(
currentValve, (mask or (1 shl currentValve.indexInNonZero)), /*currentPressure + currentFlow,*/
currentFlow + currentValve.flowRate, timeLeft - 1
)
)
currentValve.open = false
}
currentValve.tunnelsIndices.forEach {
maxAchievedAnswerAfterUs = max(
maxAchievedAnswerAfterUs, walkExponentially(
lastParsed[it], mask, /*currentPressure + currentFlow, */
currentFlow, timeLeft - 1
)
)
}
// println("${currentValve.totalIndex to mask} with flow $currentFlow and $timeLeft time left with value $maxAchievedAnswerAfterUs")
memory[(currentValve.totalIndex to timeLeft) to mask] =
max(maxAchievedAnswerAfterUs, memory[(currentValve.totalIndex to timeLeft) to mask] ?: 0)
return maxAchievedAnswerAfterUs + currentFlow
}
val memoryTimed: MutableList<MutableList<Int>> = mutableListOf(mutableListOf(), mutableListOf()) // XD XD XD
fun calculateMaskFlows(nonZeroAmount: Int): List<Int> {
val nonZeroIndices = lastParsed.filter { it.flowRate != 0 }.map { it.totalIndex }
val answer = MutableList(1 shl nonZeroAmount) { 0 }
for (mask in 0 until (1 shl nonZeroAmount)) {
var sum = 0
for (i in 0 until nonZeroAmount) {
if (((1 shl i) and mask) != 0) sum += lastParsed[nonZeroIndices[i]].flowRate
}
answer[mask] = sum
}
return answer
}
fun solveThatProblem(startInd: Int, nonZeroAmount: Int): Int {
memoryTimed[0].clear()
memoryTimed[0] = MutableList(SHIFT * SHIFT * (1 shl nonZeroAmount)) { 0 }
memoryTimed[1].clear()
memoryTimed[1] = MutableList(SHIFT * SHIFT * (1 shl nonZeroAmount)) { 0 }
val masksValues = calculateMaskFlows(nonZeroAmount)
for (timeLeft in 0..26) {
for (mask in 0 until (1 shl nonZeroAmount)) {
for (currentValveInd in 0 until lastParsed.size) {
for (elephantValveInd in 0 until lastParsed.size) {
val horribleKey = calculateHorribleKey(currentValveInd, elephantValveInd, mask)
if (timeLeft == 0) {
memoryTimed[0][horribleKey] = 0
continue
}
val currentFlow = masksValues[mask]
var maxAchievedAnswerAfterUs = currentFlow * (timeLeft - 1) // To stay here
if (!lastParsed[currentValveInd].open && lastParsed[currentValveInd].flowRate != 0) {
if (!lastParsed[elephantValveInd].open && lastParsed[elephantValveInd].flowRate != 0 && lastParsed[elephantValveInd].totalIndex != lastParsed[currentValveInd].totalIndex) {
maxAchievedAnswerAfterUs = max(
maxAchievedAnswerAfterUs,
currentFlow + memoryTimed[(timeLeft - 1) % 2][calculateHorribleKey(
currentValveInd,
elephantValveInd,
mask or (1 shl lastParsed[currentValveInd].indexInNonZero) or (1 shl lastParsed[elephantValveInd].indexInNonZero)
)]
)
}
lastParsed[elephantValveInd].tunnelsIndices.forEach {
maxAchievedAnswerAfterUs = max(
maxAchievedAnswerAfterUs,
currentFlow + memoryTimed[(timeLeft - 1) % 2][calculateHorribleKey(
currentValveInd, it, mask or (1 shl lastParsed[currentValveInd].indexInNonZero)
)]
)
}
}
lastParsed[currentValveInd].tunnelsIndices.forEach {
if (!lastParsed[elephantValveInd].open && lastParsed[elephantValveInd].flowRate != 0) {
maxAchievedAnswerAfterUs = max(
maxAchievedAnswerAfterUs,
currentFlow + memoryTimed[(timeLeft - 1) % 2][calculateHorribleKey(
it,
elephantValveInd,
mask or (1 shl lastParsed[elephantValveInd].indexInNonZero)
)]
)
}
lastParsed[elephantValveInd].tunnelsIndices.forEach { it2 ->
maxAchievedAnswerAfterUs = max(
maxAchievedAnswerAfterUs,
currentFlow + memoryTimed[(timeLeft - 1) % 2][calculateHorribleKey(
it, it2, mask
)]
)
}
}
memoryTimed[timeLeft % 2][horribleKey] = maxAchievedAnswerAfterUs
}
}
}
println(timeLeft)
}
return memoryTimed[26 % 2][calculateHorribleKey(startInd, startInd, 0)]
}
fun part1(input: List<String>): Int {
return walkExponentially(parseValves(input).first, 0)
}
fun part2(input: List<String>): Int {
val (start, nonZero) = parseValves(input)
return solveThatProblem(start.totalIndex, nonZero)
// return walkExponentiallyWithElephant(start.totalIndex, start.totalIndex, 0)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day16_test")
check(part1(testInput) == 1651)
check(part2(testInput) == 1707)
val input = readInput("Day16")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 8218c60c141ea2d39984792fddd1e98d5775b418 | 8,448 | advent-of-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/days/Day3.kt | butnotstupid | 433,717,137 | false | {"Kotlin": 55124} | package days
import kotlin.math.pow
class Day3 : Day(3) {
override fun partOne(): Any {
val a = inputList.map { it.map { Character.getNumericValue(it) }.toTypedArray() }.toTypedArray()
val bitLen = inputList.first().length
val n = inputList.size
var gammaRate = 0
var epsilonRate = 0
var twoPowered = 1
for (bitNumber in bitLen-1 downTo 0) {
var sum = 0
for (i in a.indices) sum+=a[i][bitNumber]
if (sum > n / 2) {
gammaRate += twoPowered
} else {
epsilonRate += twoPowered
}
twoPowered *= 2
}
return gammaRate * epsilonRate
}
override fun partTwo(): Any {
val a = inputList.map { it.map { Character.getNumericValue(it) }.toTypedArray() }.toTypedArray()
val bitLen = inputList.first().length
val n = inputList.size
val inForOxygen = Array(n) { true }
val inForCO = Array(n) { true }
for (bitNumber in 0 until bitLen) {
val filteredOxygen = a.filterIndexed { index, _ -> inForOxygen[index] }
if (filteredOxygen.size > 1) {
val countOxygen = filteredOxygen.count { it[bitNumber] == 1 }
val toDiscard = if (2 * countOxygen >= filteredOxygen.size) 0 else 1
for (i in a.indices) {
if (a[i][bitNumber] == toDiscard) inForOxygen[i] = false
}
}
val filteredCO = a.filterIndexed { index, _ -> inForCO[index] }
if (filteredCO.size > 1) {
val countCO = filteredCO.count { it[bitNumber] == 1 }
val toDiscard = if (2 * countCO >= filteredCO.size) 1 else 0
for (i in a.indices) {
if (a[i][bitNumber] == toDiscard) inForCO[i] = false
}
}
}
val oxygenArray = inForOxygen.indexOf(true).let { a[it] }
val coArray = inForCO.indexOf(true).let { a[it] }
var oxygen = 0
var co = 0
var twoPowered = (2.0).pow(bitLen-1).toInt()
for (i in 0 until bitLen) {
oxygen += if (oxygenArray[i] == 1) twoPowered else 0
co += if (coArray[i] == 1) twoPowered else 0
twoPowered /= 2
}
return oxygen * co
}
}
| 0 | Kotlin | 0 | 0 | a06eaaff7e7c33df58157d8f29236675f9aa7b64 | 2,373 | aoc-2021 | Creative Commons Zero v1.0 Universal |
src/main/kotlin/day2/Day2.kt | tomaszobac | 726,163,227 | false | {"Kotlin": 15292} | package day2
import java.io.File
fun part1(file: File) {
var correctGames: Array<Int> = arrayOf()
lineLoop@
for ((currentGame, line) in file.readLines().withIndex()) {
val sets = (line.split(": ")[1]).split("; ")
for (set in sets) {
val cubes = set.split(", ")
for (colorAmount in cubes) {
val amount = colorAmount.split(' ')[0].toInt()
val color = colorAmount.split(' ')[1]
if (amount > 14) continue@lineLoop
if (amount > 13 && (color == "red" || color == "green")) continue@lineLoop
if (amount > 12 && color == "red") continue@lineLoop
}
}
correctGames += currentGame + 1
}
println(correctGames.sum())
}
fun part2(file: File) {
var gamePower: Array<Int> = arrayOf()
for (line in file.readLines()) {
val sets = (line.split(": ")[1]).split("; ")
val fewest = mutableMapOf(Pair("red", 1), Pair("green", 1), Pair("blue", 1))
var power = 1
for (set in sets) {
val cubes = set.split(", ")
for (colorAmount in cubes) {
val amount = colorAmount.split(' ')[0].toInt()
val color = colorAmount.split(' ')[1]
if (amount > fewest[color]!!) fewest[color] = amount
}
}
fewest.values.forEach { power *= it }
gamePower += power
}
println(gamePower.sum())
}
fun main() {
val file = File("src/main/kotlin/day2/input.txt")
part1(file)
part2(file)
} | 0 | Kotlin | 0 | 0 | e0ce68fcf11e126c4680cff75ba959e46c5863aa | 1,583 | aoc2023 | MIT License |
src/main/kotlin/year2023/day02/Problem.kt | Ddxcv98 | 573,823,241 | false | {"Kotlin": 154634} | package year2023.day02
import IProblem
class Problem : IProblem {
private val games = mutableListOf<Game>()
init {
javaClass
.getResourceAsStream("/2023/02.txt")!!
.bufferedReader()
.forEachLine(::parseGame)
}
private fun parseGame(s: String) {
val split = s.split(": ")
val id = split[0]
.filter { it.isDigit() }
.toInt()
val game = Game(id)
parseSets(game, split[1])
games.add(game)
}
private fun parseSets(game: Game, s: String) {
val split = s.split("; ")
for (t in split) {
val set = mutableListOf<Pair<String, Int>>()
parseCubes(set, t)
game.sets.add(set)
}
}
private fun parseCubes(set: MutableCollection<Pair<String, Int>>, s: String) {
val split = s.split(", ")
for (t in split) {
val (n, color) = t.split(' ')
set.add(color to n.toInt())
}
}
private fun isValid(game: Game, max: Map<String, Int>): Boolean {
for (set in game.sets) {
for (cube in set) {
if (cube.second > max[cube.first]!!) {
return false
}
}
}
return true
}
override fun part1(): Int {
val max = mutableMapOf(
"red" to 12,
"green" to 13,
"blue" to 14
)
var sum = 0
for (game in games) {
if (isValid(game, max)) {
sum += game.id
}
}
return sum
}
override fun part2(): Int {
var sum = 0
for (game in games) {
val max = mutableMapOf(
"red" to 0,
"green" to 0,
"blue" to 0
)
for (set in game.sets) {
for (cube in set) {
if (cube.second > max[cube.first]!!) {
max[cube.first] = cube.second
}
}
}
sum += max.values.fold(1) { acc, x -> acc * x }
}
return sum
}
}
| 0 | Kotlin | 0 | 0 | 455bc8a69527c6c2f20362945b73bdee496ace41 | 2,190 | advent-of-code | The Unlicense |
src/Utils.kt | rod41732 | 572,917,438 | false | {"Kotlin": 85344} | import java.io.File
import java.math.BigInteger
import java.security.MessageDigest
import kotlin.system.measureNanoTime
typealias Coord = Pair<Int, Int>
/**
* Reads lines from the given input txt file.
*/
fun readInput(name: String) = File("src", "$name.txt")
.readLines()
fun readInputRaw(name: String) = File("src", "$name.txt").readText()
/**
* Converts string to md5 hash.
*/
fun String.md5() = BigInteger(1, MessageDigest.getInstance("MD5").digest(toByteArray()))
.toString(16)
.padStart(32, '0')
fun <T> Collection<T>.sumOfIndexed(apply: (index: Int, T) -> Int): Int {
return withIndex().sumOf { (i, v) -> apply(i, v) }
}
fun <T> Collection<T>.countIndexed(pred: (index: Int, T) -> Boolean): Int {
return withIndex().count { (i, v) -> pred(i, v) }
}
fun <T> Collection<T>.maxOfIndexed(apply: (index: Int, T) -> Int): Int {
return withIndex().maxOf { (i, v) -> apply(i, v) }
}
fun <T> List<List<T>>.transpose(): List<List<T>> {
return List(this[0].size) { colId ->
map { row -> row[colId] }
}
}
// for benchmarking, print avg time used for specified sample sizes
fun measureAvgTime(sampleSizes: List<Int> = listOf(1, 10, 100, 1000), block: () -> Unit): List<Pair<Int, Double>> {
return sampleSizes.zip(sampleSizes.map { count ->
measureNanoTime {
repeat(count) { block() }
} / 1e6 / count
})
}
inline fun repeat(n: Long, block: (idx: Long) -> Unit) {
val m = n.mod(Int.MAX_VALUE).toLong()
val full = n - m
repeat((n / Int.MAX_VALUE.toLong()).toInt()) { high ->
repeat(Int.MAX_VALUE) { low ->
block(high.toLong() * Int.MAX_VALUE + low)
}
}
repeat(m.toInt()) {
block(full + it)
}
}
fun <T> List<T>.chunkBy(pred: (T) -> Boolean): List<List<T>> {
return fold(mutableListOf(mutableListOf<T>())) { acc, it ->
if (pred(it)) acc.last().add(it)
else acc.add(mutableListOf<T>())
acc
}.filter { it.isNotEmpty() }
}
enum class Direction {
UP, DOWN, LEFT, RIGHT
}
| 0 | Kotlin | 0 | 0 | 1d2d3d00e90b222085e0989d2b19e6164dfdb1ce | 2,046 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/days/Day15.kt | TheMrMilchmann | 571,779,671 | false | {"Kotlin": 56525} | /*
* Copyright (c) 2022 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package days
import utils.*
import kotlin.math.*
fun main() {
data class Point(val x: Long, val y: Long) {
infix fun distanceTo(other: Point): Long = (abs(x - other.x) + abs(y - other.y))
}
data class Line(val a: Point, val b: Point) {
infix fun intersect(other: Line): Point? {
val abX = a.x - b.x
val abY = a.y - b.y
val acX = a.x - other.a.x
val acY = a.y - other.a.y
val cdX = other.a.x - other.b.x
val cdY = other.a.y - other.b.y
val t = (acX.toDouble() * cdY - acY * cdX) / (abX * cdY - abY * cdX)
val u = (acX.toDouble() * abY - acY * abX) / (abX * cdY - abY * cdX)
if (t < 0 || 1 < t || u < 0 || 1 < u) return null
return Point(
x = (a.x + t * (b.x - a.x)).toLong(),
y = (a.y + t * (b.y - a.y)).toLong()
)
}
}
data class ScanArea(
val center: Point,
val beacon: Point,
val range: Long = center distanceTo beacon
) {
fun getScansOnRow(row: Long): LongRange {
val verticalDistance = abs(center.y - row)
if (verticalDistance > range) return LongRange.EMPTY
val horizontalDistance = range - verticalDistance
return (center.x - horizontalDistance)..(center.x + horizontalDistance)
}
}
val data = readInput().map {
val (sX, sY, bX, bY) = """(-)?\d+""".toRegex().findAll(it).take(4).toList()
Point(sX.value.toLong(), sY.value.toLong()) to Point(bX.value.toLong(), bY.value.toLong())
}
val scanAreas = data.map { (sensor, beacon) -> ScanArea(sensor, beacon) }
fun part1(): Int {
val row = 2_000_000L
val beacons = scanAreas.mapNotNull { if (it.beacon.y == row) it.beacon.x else null }.toSet()
return scanAreas.flatMap { it.getScansOnRow(row) }.filter { it !in beacons }.toSet().size
}
fun part2(): Long {
val space = 4_000_000L
val lines = sequence {
yield(Line(Point(0, 0), Point(space, 0)))
yield(Line(Point(0, 0), Point(0, space)))
yield(Line(Point(space, 0), Point(space, space)))
yield(Line(Point(0, space), Point(space, space)))
scanAreas.forEach {
val t = it.center.copy(y = it.center.y - it.range - 1)
val b = it.center.copy(y = it.center.y + it.range + 1)
val l = it.center.copy(x = it.center.x - it.range - 1)
val r = it.center.copy(x = it.center.x + it.range + 1)
yield(Line(t, r))
yield(Line(r, b))
yield(Line(b, l))
yield(Line(l, t))
}
}
val (x, y) = lines.flatMap { a -> lines.mapNotNull { b -> a intersect b } }
.filter { (x, y) -> x in 0..space && y in 0..space }
.first { p -> scanAreas.none { it.center distanceTo p <= it.range } }
return (x * space) + y
}
println("Part 1: ${part1()}")
println("Part 2: ${part2()}")
} | 0 | Kotlin | 0 | 1 | 2e01ab62e44d965a626198127699720563ed934b | 4,219 | AdventOfCode2022 | MIT License |
dcp_kotlin/src/main/kotlin/dcp/day279/day279.kt | sraaphorst | 182,330,159 | false | {"C++": 577416, "Kotlin": 231559, "Python": 132573, "Scala": 50468, "Java": 34742, "CMake": 2332, "C": 315} | package dcp.day279
// day279.kt
// By <NAME>, 2020.
typealias Vertex = Int
typealias AdjacencyList = Set<Vertex>
typealias AdjacencyGraph = Map<Vertex, AdjacencyList>
typealias TransitiveClosure = Set<Vertex>
typealias TransitiveClosures = Set<TransitiveClosure>
/**
* Calculate the transitive closure groups of a directed graph represented by adjacency lists.
* @param graph the graph represented as adjacency lists
*/
fun findTransitiveClosures(graph: AdjacencyGraph): TransitiveClosures {
if (graph.isEmpty())
return emptySet()
// All vertices should appear as keys in the adjacency graph, but in case there are vertices with no outbound
// edges that are not listed, make sure they appear in the set of vertices all the same.
val vertices: Set<Vertex> = graph.keys + graph.values.flatten()
/**
* Given a partial transitive closure, recursively completes it by looking for adjacency lists that intersect
* it and adding them to the partial transitive closure. When stability is maintained, i.e. there are no new
* vertices added to the partial transitive closure, the transitive closure is complete and returned.
*/
tailrec
fun findTransitiveClosure(partialClosure: TransitiveClosure, remainingVertices: Set<Vertex>): TransitiveClosure {
val partialClosureAddition = partialClosure.flatMap { graph[it]?.intersect(remainingVertices) ?: emptySet() }
return if (partialClosureAddition.isEmpty())
partialClosure
else
findTransitiveClosure(partialClosure + partialClosureAddition, remainingVertices - partialClosureAddition)
}
/**
* Auxiliary tail recursive function to find the transitive closures.
* It processes the set of remaining vertices, taking one at a time, calculating its transitive closure, and then
* recursing by removing the transitive closure from the remaining vertices and adding it to the list of
* transitive closures.
*/
tailrec
fun aux(remainingVertices: Set<Vertex>, transitiveClosures: TransitiveClosures = emptySet()): TransitiveClosures =
if (remainingVertices.isEmpty())
transitiveClosures
else {
// Peel off the first remaining vertex and find its transitive closure.
val vertexSet = setOf(remainingVertices.first())
val newTransitiveClosure = findTransitiveClosure(vertexSet, remainingVertices - vertexSet)
aux(remainingVertices - newTransitiveClosure, transitiveClosures + setOf(newTransitiveClosure))
}
return aux(vertices)
}
| 0 | C++ | 1 | 0 | 5981e97106376186241f0fad81ee0e3a9b0270b5 | 2,611 | daily-coding-problem | MIT License |
src/test/kotlin/ch/ranil/aoc/aoc2022/Day21.kt | stravag | 572,872,641 | false | {"Kotlin": 234222} | package ch.ranil.aoc.aoc2022
import ch.ranil.aoc.AbstractDay
import org.junit.jupiter.api.Test
import kotlin.test.assertEquals
class Day21 : AbstractDay() {
@Test
fun part1Test() {
assertEquals(152, compute1(testInput))
}
@Test
fun part1Puzzle() {
assertEquals(331319379445180, compute1(puzzleInput))
}
@Test
fun part2Test() {
assertEquals(301, compute2(testInput))
}
@Test
fun part2Puzzle() {
assertEquals(3715799488132, compute2(puzzleInput))
}
private fun compute1(input: List<String>): Long {
val monkeys = parse1(input)
return getAnswer("root", monkeys)
}
private fun getAnswer(monkeyName: String, monkeys: Map<String, Monkey>): Long {
return when (val monkey = monkeys.getValue(monkeyName)) {
is NumberMonkey -> monkey.number
is OperationMonkey -> {
val a = getAnswer(monkey.a, monkeys)
val b = getAnswer(monkey.b, monkeys)
monkey.operation(a, b)
}
else -> throw IllegalArgumentException()
}
}
private fun compute2(input: List<String>): Long {
val (monkeys, monkeyParents) = parse2(input)
// bubble up
val operationWithHumn = monkeyParents.getValue("humn")
val operationStack = mutableListOf("humn" to operationWithHumn)
var lastOperation = operationWithHumn
while (lastOperation.name != "root") {
lastOperation = monkeyParents.getValue(lastOperation.name)
operationStack.add(operationStack.last().second.name to lastOperation)
}
// bubble down
val (unknownRootPart, rootOperation) = operationStack.removeLast()
val equalityCheck = rootOperation.getKnownPart(unknownRootPart, monkeys)
return operationStack.reversed().fold(equalityCheck) { desiredAnswer, (unknownPart, operation) ->
operation.getUnknownPart(desiredAnswer, unknownPart, monkeys)
}
}
private fun OperationMonkey.getKnownPart(unknownPart: String, monkeys: Map<String, Monkey>): Long {
return when {
a == unknownPart -> getAnswer(b, monkeys)
b == unknownPart -> getAnswer(a, monkeys)
else -> throw IllegalArgumentException()
}
}
private fun OperationMonkey.getUnknownPart(
desiredAnswer: Long,
unknownPart: String,
monkeys: Map<String, Monkey>
): Long {
val knownPart = getKnownPart(unknownPart, monkeys)
return when (operator) {
'+' -> desiredAnswer - knownPart
'-' -> {
if (a == unknownPart) {
desiredAnswer + knownPart
} else {
knownPart - desiredAnswer
}
}
'*' -> desiredAnswer / getKnownPart(unknownPart, monkeys)
'/' -> {
if (a == unknownPart) {
desiredAnswer * knownPart
} else {
knownPart / desiredAnswer
}
}
else -> throw IllegalArgumentException("unexpected operator $operator")
}
}
private fun parse1(input: List<String>): Map<String, Monkey> {
val monkeys = input.map {
val (name, operationString) = it.split(": ")
if (operationString.toLongOrNull() == null) {
val (a, operator, b) = operationString.split(" ")
val operation: (Long, Long) -> Long = when (operator) {
"+" -> Long::plus
"-" -> Long::minus
"*" -> Long::times
"/" -> Long::div
else -> throw IllegalArgumentException("unexpected operator $operator")
}
OperationMonkey(name, a, b, operator[0], operation)
} else {
NumberMonkey(name, operationString.toLong())
}
}
return monkeys.associateBy { it.name }
}
private fun parse2(input: List<String>): Pair<Map<String, Monkey>, Map<String, OperationMonkey>> {
val lookup = parse1(input)
val parentLookup = lookup.values
.filterIsInstance<OperationMonkey>()
.flatMap {
listOf(
it.a to it,
it.b to it,
)
}.toMap()
return lookup to parentLookup
}
sealed interface Monkey {
val name: String
}
data class NumberMonkey(
override val name: String,
val number: Long
) : Monkey
data class OperationMonkey(
override val name: String,
val a: String,
val b: String,
val operator: Char,
val operation: (Long, Long) -> Long,
) : Monkey
}
| 0 | Kotlin | 1 | 0 | dbd25877071cbb015f8da161afb30cf1968249a8 | 4,863 | aoc | Apache License 2.0 |
2016/src/main/kotlin/com/koenv/adventofcode/Day13.kt | koesie10 | 47,333,954 | false | null | package com.koenv.adventofcode
import java.util.*
object Day13 {
fun getDistance(input: String, destination: Pair<Int, Int>): Int {
val favoriteNumber = input.toInt()
var currentState = State(null, 1 to 1)
val moves: Queue<State> = ArrayDeque<State>()
moves.add(currentState)
val seen = hashSetOf<Pair<Int, Int>>()
while (moves.isNotEmpty()) {
currentState = moves.poll()
if (isFinalMove(currentState, destination)) {
return currentState.depth
} else {
// add all states to possible moves
getAdjacentStates(currentState, favoriteNumber).forEach {
if (!seen.contains(it.position)) {
moves.offer(it)
seen.add(it.position)
}
}
}
}
throw IllegalStateException("No final move found")
}
fun findUniqueLocations(input: String, maxSteps: Int): Int {
val favoriteNumber = input.toInt()
var currentState = State(null, 1 to 1)
val moves: Queue<State> = ArrayDeque<State>()
moves.add(currentState)
val seen = hashSetOf<Pair<Int, Int>>()
while (moves.isNotEmpty()) {
currentState = moves.poll()
getAdjacentStates(currentState, favoriteNumber).forEach {
if (!seen.contains(it.position) && it.depth <= maxSteps) {
moves.offer(it)
seen.add(it.position)
}
}
}
return seen.size
}
private fun getAdjacentStates(currentState: State, favoriteNumber: Int): List<State> {
val possibleMoves = arrayListOf<State>()
possibleMoves.add(State(currentState, currentState.position.first + 1 to currentState.position.second))
possibleMoves.add(State(currentState, currentState.position.first - 1 to currentState.position.second))
possibleMoves.add(State(currentState, currentState.position.first to currentState.position.second + 1))
possibleMoves.add(State(currentState, currentState.position.first to currentState.position.second - 1))
return possibleMoves.filter { isValid(it, favoriteNumber) }
}
fun isFinalMove(state: State, destination: Pair<Int, Int>): Boolean {
return state.position == destination
}
fun isValid(state: State, favoriteNumber: Int): Boolean {
val x = state.position.first
val y = state.position.second
if (x < 0 || y < 0) {
return false
}
val result = x * x + 3 * x + 2 * x * y + y + y * y + favoriteNumber
return Integer.bitCount(result).mod(2) == 0
}
fun printMap() {
print(" ")
for (x in 0..9) {
print(x)
}
println()
for (y in 0..9) {
print(y)
print(" ")
for (x in 0..9) {
if (isValid(State(null, x to y), 10)) {
print('.')
} else {
print('#')
}
}
println()
}
}
data class State(
val parent: State?,
val position: Pair<Int, Int>
) {
val depth: Int
get() {
var currentParent = parent
var i = 0
while (currentParent != null) {
i++
currentParent = currentParent.parent
}
return i
}
}
} | 0 | Kotlin | 0 | 0 | 29f3d426cfceaa131371df09785fa6598405a55f | 3,603 | AdventOfCode-Solutions-Kotlin | MIT License |
src/main/kotlin/de/tek/adventofcode/y2022/day11/MonkeyInTheMiddle.kt | Thumas | 576,671,911 | false | {"Kotlin": 192328} | package de.tek.adventofcode.y2022.day11
import de.tek.adventofcode.y2022.util.readInputLines
import de.tek.adventofcode.y2022.util.splitByBlankLines
import java.math.BigInteger
open class Item(initialWorryLevel: Int, modulus: Int) {
private var worryLevel = initialWorryLevel.toBigInteger()
private val modulus = modulus.toBigInteger()
fun applyOperation(operation: Operation) {
worryLevel = operation.apply(worryLevel).mod(modulus)
}
open fun reduceWorry() {
worryLevel = worryLevel.divide(3.toBigInteger())
}
fun test(divisor: Int) = worryLevel.mod(divisor.toBigInteger()) == BigInteger.ZERO
override fun toString(): String {
return "Item(worryLevel=$worryLevel)"
}
}
class FragileItem(initialWorryLevel: Int, modulus: Int) : Item(initialWorryLevel, modulus) {
override fun reduceWorry() {}
}
class Operation(firstOperand: Operand, secondOperand: Operand, private val operator: Operator) {
private val operands = listOf(firstOperand, secondOperand)
fun apply(oldValue: BigInteger): BigInteger {
val toTypedArray = operands.map { it.evaluate(oldValue) }.toTypedArray()
with(operator) {
return toTypedArray[0] op toTypedArray[1]
}
}
companion object {
fun parseFrom(string: String): Operation {
val splitString = string.split(" ")
val firstOperand = Operand.parseFrom(splitString[2])
val operator = Operator.parseFrom(splitString[3][0])
val secondOperand = Operand.parseFrom(splitString[4])
return Operation(firstOperand, secondOperand, operator)
}
}
}
sealed class Operand {
class FixedValue(private val value: BigInteger) : Operand() {
override fun evaluate(value: BigInteger) = this.value
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is FixedValue) return false
if (value != other.value) return false
return true
}
override fun hashCode(): Int {
return value.hashCode()
}
}
object OldValue : Operand() {
override fun evaluate(value: BigInteger) = value
}
abstract fun evaluate(value: BigInteger): BigInteger
companion object {
fun parseFrom(string: String) = when (string) {
"old" -> OldValue
else -> {
val value = BigInteger(string)
FixedValue(value)
}
}
}
}
enum class Operator(private val char: Char, private val biFunction: (BigInteger, BigInteger) -> BigInteger) {
PLUS('+', BigInteger::plus), TIMES('*', BigInteger::times), DIV('/', BigInteger::divide);
infix fun BigInteger.op(other: BigInteger): BigInteger = biFunction(this, other)
companion object {
fun parseFrom(char: Char): Operator {
return Operator.values().find { char == it.char }
?: throw IllegalArgumentException("Unknown operator $char.")
}
}
}
class Monkey(
private val name: String,
initialItems: List<Item>,
private val operation: Operation,
private val divisor: Int
) {
private val currentItems = initialItems.toMutableList()
private lateinit var firstMonkeyFriend: Monkey
private lateinit var secondMonkeyFriend: Monkey
private var inspectionCounter = BigInteger.ZERO
fun makeFriends(firstMonkey: Monkey, secondMonkey: Monkey) {
if (firstMonkey === this || secondMonkey === this) {
throw IllegalArgumentException("A monkey cannot be friends with itself!")
}
firstMonkeyFriend = firstMonkey
secondMonkeyFriend = secondMonkey
}
fun handleItems() {
while (currentItems.isNotEmpty()) {
val item = currentItems.removeFirst()
handleItem(item)
}
}
private fun handleItem(item: Item) {
inspect(item)
getBoredWith(item)
val nextMonkey = determineNextMonkey(item)
item throwTo nextMonkey
}
private fun inspect(item: Item) {
inspectionCounter = inspectionCounter.inc()
item.applyOperation(operation)
}
private fun getBoredWith(item: Item) {
item.reduceWorry()
}
private fun determineNextMonkey(item: Item) = if (item.test(divisor)) firstMonkeyFriend else secondMonkeyFriend
private infix fun Item.throwTo(friend: Monkey) = friend.catch(this)
private fun catch(item: Item) = currentItems.add(item)
fun getInspectionCount(): BigInteger = inspectionCounter
override fun toString(): String {
return "Monkey(name=$name, operation=$operation, divisor=$divisor, currentItems=$currentItems, firstMonkeyFriend=${firstMonkeyFriend.name}, secondMonkeyFriend=${secondMonkeyFriend.name}, inspectionCounter=$inspectionCounter)"
}
}
class MonkeyBusiness private constructor(private val monkeys: Map<Int, Monkey>) {
fun playRounds(rounds: Int): BigInteger {
repeat(rounds) {
for (monkey in monkeys.values) {
monkey.handleItems()
}
//println("After round $it: ${monkeys.values}")
}
return monkeys.values.map { it.getInspectionCount() }.sorted().takeLast(2).reduce(BigInteger::times)
}
companion object {
var worryReductionEnabled = true
private val regexPerLine = arrayOf(
Regex("""Monkey (\d+):"""),
Regex("""\s*Starting items: (.*)"""),
Regex("""\s*Operation: (.*)"""),
Regex("""\s*Test: divisible by (\d+)"""),
Regex("""\s*If true: throw to monkey (\d+)"""),
Regex("""\s*If false: throw to monkey (\d+)""")
)
fun parseFrom(input: List<String>): MonkeyBusiness {
val monkeyDescriptions = splitByBlankLines(input).map { parseLines(it) }
val monkeyParser = createMonkeyParser(monkeyDescriptions)
val splitDescriptions = monkeyDescriptions.associate(::splitMonkeyDescription).toPairOfMaps()
val monkeys = splitDescriptions.first.mapValues { monkeyParser.parse(it.key, it.value) }
associateFriends(splitDescriptions.second, monkeys)
return MonkeyBusiness(monkeys)
}
private fun parseLines(monkeyDescription: List<String>): List<String> =
regexPerLine.zip(monkeyDescription) { regex, line ->
val match = regex.matchEntire(line)
match?.destructured?.component1()
?: throw IllegalArgumentException("Cannot parse line of monkey description against \"$regex\": $line")
}
private fun createMonkeyParser(monkeyDescriptions: List<List<String>>): MonkeyParser {
val divisors = monkeyDescriptions.map { it[3].toInt() }
val modulus = divisors.reduce(Int::times)
return MonkeyParser { worryLevel ->
if (worryReductionEnabled) Item(worryLevel, modulus) else FragileItem(worryLevel, modulus)
}
}
class MonkeyParser(private val itemCreator: (Int) -> Item) {
fun parse(number: Int, parseResults: List<String>): Monkey {
val name = number.toString()
val items = parseItems(parseResults[1])
val operation = Operation.parseFrom(parseResults[2])
val divisor = parseResults[3].toInt()
return Monkey(name, items, operation, divisor)
}
private fun parseItems(itemString: String): List<Item> =
itemString.split(",").map(String::trim).map(String::toInt).map(itemCreator)
}
private fun splitMonkeyDescription(parsedLines: List<String>): Pair<Int, Pair<List<String>, List<String>>> {
val monkeyNumber = parsedLines[0].toInt()
val monkeySelfDescription = parsedLines.subList(0, 4)
val monkeyFriendDescription = parsedLines.subList(4, 6)
return Pair(monkeyNumber, Pair(monkeySelfDescription, monkeyFriendDescription))
}
private fun <K, V, W> Map<K, Pair<V, W>>.toPairOfMaps(): Pair<Map<K, V>, Map<K, W>> {
val result = Pair(mutableMapOf<K, V>(), mutableMapOf<K, W>())
for (entry in this.entries) {
result.first[entry.key] = entry.value.first
result.second[entry.key] = entry.value.second
}
return result
}
private fun associateFriends(friendDescriptions: Map<Int, List<String>>, monkeys: Map<Int, Monkey>) {
friendDescriptions
.mapValues { parseFriends(it.value, monkeys) }
.mapKeys { monkeys[it.key]!! }
.forEach { monkeyAndFriends ->
makeFriends(monkeyAndFriends)
}
}
private fun parseFriends(friendDescription: List<String>, monkeys: Map<Int, Monkey>) =
parseFriendNumbers(friendDescription).map { slot ->
monkeys[slot] ?: throw IllegalArgumentException("There is no monkey ${slot}.")
}
private fun parseFriendNumbers(friendDescription: List<String>): Pair<Int, Int> {
val firstMonkeyFriendNumber = friendDescription[0].toInt()
val secondMonkeyFriendNumber = friendDescription[1].toInt()
return Pair(firstMonkeyFriendNumber, secondMonkeyFriendNumber)
}
private fun <T, S> Pair<T, T>.map(transform: (T) -> S): Pair<S, S> = Pair(transform(first), transform(second))
private fun makeFriends(monkeyAndFriends: Map.Entry<Monkey, Pair<Monkey, Monkey>>) {
val thisMonkey = monkeyAndFriends.key
val firstFriend = monkeyAndFriends.value.first
val secondMonkey = monkeyAndFriends.value.second
thisMonkey.makeFriends(firstFriend, secondMonkey)
}
}
}
fun main() {
val input = readInputLines(MonkeyBusiness::class)
fun part1(input: List<String>): BigInteger {
MonkeyBusiness.worryReductionEnabled = true
return MonkeyBusiness.parseFrom(input).playRounds(20)
}
fun part2(input: List<String>): BigInteger {
MonkeyBusiness.worryReductionEnabled = false
return MonkeyBusiness.parseFrom(input).playRounds(10000)
}
println("The level of monkey business after 20 rounds of stuff-slinging simian shenanigans is ${part1(input)}.")
println(
"Without worry reduction, " +
"the level of monkey business after 10000 rounds of stuff-slinging simian shenanigans is ${part2(input)}."
)
} | 0 | Kotlin | 0 | 0 | 551069a21a45690c80c8d96bce3bb095b5982bf0 | 10,630 | advent-of-code-2022 | Apache License 2.0 |
NiceString_TaxiPark/Taxi Park/Task/src/taxipark/TaxiParkTask.kt | EdmundoSanchezM | 354,481,310 | false | null | package taxipark
/*
* Task #1. Find all the drivers who performed no trips.
*/
fun TaxiPark.findFakeDrivers(): Set<Driver> =
this.allDrivers - this.trips.map { it.driver }.toSet()
/*
* Task #2. Find all the clients who completed at least the given number of trips.
*/
fun TaxiPark.findFaithfulPassengers(minTrips: Int): Set<Passenger> =
if (minTrips == 0) this.allPassengers else
this.trips.flatMap { it.passengers }.groupingBy { it }.eachCount().filter {
it.value >= minTrips
}.keys
/*
* Task #3. Find all the passengers, who were taken by a given driver more than once.
*/
fun TaxiPark.findFrequentPassengers(driver: Driver): Set<Passenger> =
this.trips.filter { it.driver == driver }.flatMap { it.passengers }.groupingBy { it }.eachCount().filter { it.value > 1 }.keys
/*
* Task #4. Find the passengers who had a discount for majority of their trips.
*/
fun TaxiPark.findSmartPassengers(): Set<Passenger> = this.trips.flatMap {
it.passengers.map { passenger -> Pair(passenger, it) }
}.groupBy { it.first }.filter {
it.value.count { (_, trip) -> trip.discount != null } >
it.value.count { (_, trip) -> trip.discount == null }
}.keys
/*
* Task #5. Find the most frequent trip duration among minute periods 0..9, 10..19, 20..29, and so on.
* Return any period if many are the most frequent, return `null` if there're no trips.
*/
fun TaxiPark.findTheMostFrequentTripDurationPeriod(): IntRange? = this.trips.map {
(it.duration - (it.duration % 10))..(it.duration + 9 - (it.duration % 10))
}.groupingBy { it }.eachCount().maxBy { it.value }?.key
/*
* Task #6.
* Check whether 20% of the drivers contribute 80% of the income.
*/
fun TaxiPark.checkParetoPrinciple(): Boolean {
val driversByIncome = this.trips.groupBy { it.driver }.mapValues {
it.value.sumByDouble { trip -> trip.cost }
}
val pct80totalIncome = driversByIncome.values.sum() * 0.8
val pct20totalDrivers = this.allDrivers.size * 0.2
var currentIncome = 0.0
print("\n------\ntrips=$driversByIncome\n\n")
driversByIncome.toList().sortedByDescending { it.second }.forEachIndexed { index, it ->
if (index >= pct20totalDrivers) return (currentIncome >= pct80totalIncome) && (currentIncome != 0.0)
currentIncome += it.second
print("currentIncome = $currentIncome index=$index pct80totalIncome=$pct80totalIncome pct20totalDrivers=$pct20totalDrivers\n")
}
return false
} | 0 | Kotlin | 0 | 0 | a671a9b35eeae1f56ee1ad448347d9df5e583c9d | 2,469 | Kotlin-for-Java-Developers | MIT License |
leetcode/src/offer/middle/Offer66.kt | zhangweizhe | 387,808,774 | false | null | package offer.middle
fun main() {
// 剑指 Offer 66. 构建乘积数组
// https://leetcode.cn/problems/gou-jian-cheng-ji-shu-zu-lcof/
println(constructArr1(intArrayOf(1,2,3,4,5)).contentToString())
}
fun constructArr(a: IntArray): IntArray {
if (a.isEmpty()) {
return IntArray(0)
}
// 对于一个索引i,可以用 i 左侧数字的乘积,乘以 i 右侧数字的乘积,即可得到结果
// 定义两个数组 L R,L[i] 表示 i 左侧数字的乘积,R[i] 表示 i 右侧数字的乘积
// 可知 L[0] = 1,因为 0 号元素左边没有数字,且 L[i] = L[i-1] * a[i-1]
// R[a.size - 1] = 1,因为最后一个元素右边没有数字,且 R[i] = R[i+1] * R[i]
// 可以根据上面的递推公式,填充 L 和 R
val L = IntArray(a.size)
L[0] = 1
val R = IntArray(a.size)
R[a.size - 1] = 1
// 填充L数组
for (i in 1 until a.size) {
L[i] = L[i-1] * a[i-1]
}
// 填充R数组
for (i in a.size-2 downTo 0) {
R[i] = R[i+1] * a[i+1]
}
// 使用 L 作为结果集合返回
for (i in L.indices) {
L[i] *= R[i]
}
return L
}
// 优化空间复杂度,只有一个辅助数组,也作为结果数组返回
fun constructArr1(a: IntArray): IntArray {
if (a.isEmpty()) {
return IntArray(0)
}
// 对于一个索引i,可以用 i 左侧数字的乘积,乘以 i 右侧数字的乘积,即可得到结果
// 定义两个数组 L R,L[i] 表示 i 左侧数字的乘积,R[i] 表示 i 右侧数字的乘积
// 可知 L[0] = 1,因为 0 号元素左边没有数字,且 L[i] = L[i-1] * a[i-1]
// R[a.size - 1] = 1,因为最后一个元素右边没有数字,且 R[i] = R[i+1] * R[i]
// 可以根据上面的递推公式,填充 L 和 R
val L = IntArray(a.size)
L[0] = 1
var R = 1
// 填充L数组
for (i in 1 until a.size) {
L[i] = L[i-1] * a[i-1]
}
// 填充R数组
for (i in a.size-1 downTo 0) {
L[i] *= R
R *= a[i]
}
return L
} | 0 | Kotlin | 0 | 0 | 1d213b6162dd8b065d6ca06ac961c7873c65bcdc | 2,078 | kotlin-study | MIT License |
src/main/kotlin/com/marcdenning/adventofcode/day12/Day12a.kt | marcdenning | 317,730,735 | false | {"Kotlin": 87536} | package com.marcdenning.adventofcode.day12
import java.io.File
import java.util.regex.Pattern
import kotlin.math.abs
const val FORWARD = 'F'
const val NORTH = 'N'
const val SOUTH = 'S'
const val EAST = 'E'
const val WEST = 'W'
const val RIGHT = 'R'
const val LEFT = 'L'
fun main(args: Array<String>) {
var currentCoordinates = Coordinates(0, 0, 90)
File(args[0]).readLines().map { parseInstruction(it) }
.forEach { currentCoordinates = moveShipScalar(currentCoordinates, it) }
println("Manhattan distance: ${abs(currentCoordinates.x) + abs(currentCoordinates.y)}")
}
fun parseInstruction(instruction: String): Pair<Char, Int> {
val matcher = Pattern.compile("(\\w){1}(\\d+)").matcher(instruction)
matcher.matches()
return Pair(matcher.group(1)[0], matcher.group(2).toInt())
}
fun moveShipScalar(startingCoordinates: Coordinates, instruction: Pair<Char, Int>): Coordinates {
return when (instruction.first) {
FORWARD -> {
return when (startingCoordinates.orientation) {
0 -> Coordinates(startingCoordinates.x, startingCoordinates.y + instruction.second, startingCoordinates.orientation)
90 -> Coordinates(startingCoordinates.x + instruction.second, startingCoordinates.y, startingCoordinates.orientation)
180 -> Coordinates(startingCoordinates.x, startingCoordinates.y - instruction.second, startingCoordinates.orientation)
270 -> Coordinates(startingCoordinates.x - instruction.second, startingCoordinates.y, startingCoordinates.orientation)
else -> throw Exception()
}
}
NORTH -> Coordinates(startingCoordinates.x, startingCoordinates.y + instruction.second, startingCoordinates.orientation)
SOUTH -> Coordinates(startingCoordinates.x, startingCoordinates.y - instruction.second, startingCoordinates.orientation)
EAST -> Coordinates(startingCoordinates.x + instruction.second, startingCoordinates.y, startingCoordinates.orientation)
WEST -> Coordinates(startingCoordinates.x - instruction.second, startingCoordinates.y, startingCoordinates.orientation)
RIGHT -> Coordinates(startingCoordinates.x, startingCoordinates.y, (startingCoordinates.orientation + instruction.second) % 360)
LEFT -> {
var newOrientation = startingCoordinates.orientation - instruction.second
if (newOrientation < 0) {
newOrientation += 360
}
Coordinates(startingCoordinates.x, startingCoordinates.y, newOrientation)
}
else -> throw Exception()
}
}
data class Coordinates(
val x: Long,
val y: Long,
val orientation: Int
)
| 0 | Kotlin | 0 | 0 | b227acb3876726e5eed3dcdbf6c73475cc86cbc1 | 2,705 | advent-of-code-2020 | MIT License |
hangman-service/src/main/kotlin/dulcinea/hangman/local/wordstore/WordStore.kt | wpitt3 | 167,178,716 | false | null | package dulcinea.hangman.local.wordstore
class WordCache(words: List<String>) {
private val minBeforeDoubles = 40
private val minBeforeTriples = 20
private val allWords: List<Word> = words.map { Word(it) }
fun allMatchingWords(with: List<Char?>, without: Set<Char>): List<Word> {
val unique: Set<Char> = with.filterNotNull().toSet()
val single = unique.filter{ l -> with.count { it == l } == 1}.toSet()
val double = unique.filter{ l -> with.count { it == l } == 2}.toSet()
val triple = unique.filter{ l -> with.count { it == l } == 3}.toSet()
return allWords.filter{ it.matches(with, without, single, double, triple) }
}
fun makeGuess(letter: Char, with: List<Char?>, without: Set<Char>): Map<SearchKey, List<Word>> {
val unique: Set<Char> = with.filterNotNull().toSet()
val single = unique.filter{ l -> with.count { it == l } == 1}.toSet()
val double = unique.filter{ l -> with.count { it == l } == 2}.toSet()
val triple = unique.filter{ l -> with.count { it == l } == 3}.toSet()
val words = allWords.filter{ it.matches(with, without, single, double, triple) }
return makeGuess(letter, with, without, words)
}
fun makeGuess(letter: Char, with: List<Char?>, without: Set<Char>, words: List<Word>): Map<SearchKey, List<Word>> {
val guesses = mutableMapOf<SearchKey, List<Word>>()
val withoutWords = words.filterWithout(with, without, letter)
if (withoutWords.size > 0) {
guesses[SearchKey(with, without + letter)] = withoutWords
}
guesses.putAll(with.indices.filter{with[it] == null}.map{
val newWith = with.addLetters(letter, it)
SearchKey(newWith.toList(), without) to words.filterSingle(newWith, without, letter)
}.filter{ it.second.isNotEmpty()}.toMap())
if (words.size < minBeforeDoubles) {
guesses.putAll(combinationPairs(with).map { combo ->
val newWith = with.addLetters(letter, combo[0], combo[1])
SearchKey(newWith.toList(), without) to words.filterDouble(newWith, without, letter)
}.filter{ it.second.isNotEmpty() })
}
if (words.size < minBeforeTriples) {
guesses.putAll(combinationTriples(with).map { combo ->
val newWith = with.addLetters(letter, combo[0], combo[1], combo[2])
SearchKey(newWith.toList(), without) to words.filterTriple(newWith, without, letter)
}.filter{ it.second.isNotEmpty()})
}
return guesses
}
private fun List<Char?>.addLetters(letter: Char, vararg indices: Int) : List<Char?> {
return indices.fold(this.toMutableList(), {acc, i -> acc[i] = letter; acc})
}
private fun List<Word>.filterWithout(with: List<Char?>, without: Set<Char>, letter: Char): List<Word> {
return this.filter{ it.matches(with, without + letter) }
}
private fun List<Word>.filterSingle(with: List<Char?>, without: Set<Char>, letter: Char): List<Word> {
return this.filter{ it.matches(with, without, setOf(letter), setOf(), setOf()) }
}
private fun List<Word>.filterDouble(with: List<Char?>, without: Set<Char>, letter: Char): List<Word> {
return this.filter { it.matches(with, without, setOf(), setOf(letter), setOf()) }
}
private fun List<Word>.filterTriple(with: List<Char?>, without: Set<Char>, letter: Char): List<Word> {
return this.filter { it.matches(with, without, setOf(), setOf(), setOf(letter)) }
}
private fun combinationPairs(with: List<Char?>): List<List<Int>> {
val remaining = with.indices.filter{with[it] == null}
return remaining.indices.map{ index ->
((index+1)..(remaining.size-1)).map{
listOf(remaining[index], remaining[it])
}
}.flatten()
}
private fun combinationTriples(with: List<Char?>): List<List<Int>> {
val remaining = with.indices.filter{with[it] == null}
return remaining.indices.map{ indexA ->
((indexA+1)..(remaining.size-1)).map{ indexB ->
((indexB+1)..(remaining.size-1)).map { indexC ->
listOf(remaining[indexA], remaining[indexB], remaining[indexC])
}
}.flatten()
}.flatten()
}
}
data class SearchKey(val with: List<Char?>, val without: Set<Char>)
data class Word(var input: String) {
private val aCharIndex: Int = 'A'.toInt()
private val word: String = input.toUpperCase()
private val with: List<Char>
private val without: Set<Char>
private val single: Set<Char>
private val double: Set<Char>
private val triple: Set<Char>
init {
val letters = word.map{it}
val unique = letters.toSet()
single = unique.filter{ letter -> letters.count { it == letter } == 1}.toSet()
double = unique.filter{ letter -> letters.count { it == letter } == 2}.toSet()
triple = unique.filter{ letter -> letters.count { it == letter } == 3}.toSet()
with = letters.map{ it }
without = (0..25).map{ (it + aCharIndex).toChar() }
.filter{ !with.contains(it) }
.toSet()
}
fun matches(with: List<Char?>, without: Set<Char>): Boolean {
return this.with.indices.all{ with[it] == null || (with[it] == this.with[it]) } && this.without intersect without == without
}
fun matches(with: List<Char?>, without: Set<Char>, singleLetters: Set<Char>, doubleLetters: Set<Char>, tripleLetters: Set<Char>): Boolean {
return this.single intersect singleLetters == singleLetters &&
this.double intersect doubleLetters == doubleLetters &&
this.triple intersect tripleLetters == tripleLetters &&
this.without intersect without == without &&
this.with.indices.all{ with[it] == null || with[it] == this.with[it] } &&
doubleLetters.all { letter -> val count = with.count{ it == letter }; count == 0 || count == 2 } &&
tripleLetters.all { letter -> val count = with.count{ it == letter }; count == 0 || count == 3 }
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Word
if (word != other.word) return false
return true
}
override fun hashCode(): Int {
return word.hashCode()
}
override fun toString(): String {
return word
}
} | 10 | Kotlin | 0 | 0 | 34332d06830b4ff6ca2ad200e2785650a32d3f78 | 6,581 | hangman | Apache License 2.0 |
src/Day04.kt | psy667 | 571,468,780 | false | {"Kotlin": 23245} | fun main() {
val id = "04"
fun part1(input: List<String>): Int {
return input.count {
val (a,b,x,y) = it.replace(',', '-').split('-').map(String::toInt)
a in x..y && b in x..y || x in a..b && y in a..b
}
}
fun part2(input: List<String>): Int {
return input.count {
val (a,b,x,y) = it.replace(',', '-').split('-').map(String::toInt)
a in x..y || b in x..y || x in a..b || y in a..b
}
}
val testInput = readInput("Day${id}_test")
check(part1(testInput) == 2)
val input = readInput("Day${id}")
println("==== DAY $id ====")
println("Part 1: ${part1(input)}")
println("Part 2: ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 73a795ed5e25bf99593c577cb77f3fcc31883d71 | 721 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/com/lucaszeta/adventofcode2020/day22/day22.kt | LucasZeta | 317,600,635 | false | null | package com.lucaszeta.adventofcode2020.day22
import com.lucaszeta.adventofcode2020.ext.getResourceAsText
fun main() {
val decks = getResourceAsText("/day22/decks.txt")
.split("\n\n")
.map(::parseDeck)
val winnerDeck = playCombat(decks[0], decks[1])
println("Combat")
println("Winner deck: $winnerDeck")
println("Score: ${calculateScore(winnerDeck)}")
val (_, recursiveWinnerDeck) = playRecursiveCombat(decks[0], decks[1])
println("Recursive Combat")
println("Winner deck: $recursiveWinnerDeck")
println("Score: ${calculateScore(recursiveWinnerDeck)}")
}
fun calculateScore(winnerDeck: List<Int>): Int {
var multiplier = 2
return winnerDeck
.reversed()
.reduce { acc, card ->
acc + card * multiplier++
}
}
fun parseDeck(input: String): List<Int> {
val onlyNumbers = "(\\d+)".toRegex()
return input
.split("\n")
.filter { onlyNumbers.matches(it) }
.map { it.toInt() }
}
| 0 | Kotlin | 0 | 1 | 9c19513814da34e623f2bec63024af8324388025 | 1,006 | advent-of-code-2020 | MIT License |
src/main/kotlin/net/voldrich/aoc2021/Day15.kt | MavoCz | 434,703,997 | false | {"Kotlin": 119158} | package net.voldrich.aoc2021
import net.voldrich.BaseDay
import org.jheaps.AddressableHeap
import org.jheaps.tree.FibonacciHeap
import java.util.*
import kotlin.collections.ArrayList
import kotlin.collections.HashSet
import kotlin.system.measureTimeMillis
// https://adventofcode.com/2021/day/15
fun main() {
Day15().run()
}
class Day15 : BaseDay() {
override fun task1() : Int {
val graph = Graph()
graph.calculateShortestPath()
return graph.getEndNode().getTotalDistance()
}
override fun task2() : Int {
val graph = Graph()
val graphExpanded = Graph(graph, 5)
graphExpanded.calculateShortestPathOptimized()
return graphExpanded.getEndNode().getTotalDistance()
}
fun performanceTest(iterationCount : Int) {
val graph = Graph()
val graphExpanded = Graph(graph, 5)
val averageNonOptimized = (0..iterationCount).map {
graphExpanded.reset()
graphExpanded.calculateShortestPath()
}.average()
val averageOptimized = (0..iterationCount).map {
graphExpanded.reset()
graphExpanded.calculateShortestPathOptimized()
}.average()
println("Average time non optimized: $averageNonOptimized")
println("Average time optimized: $averageOptimized")
}
inner class Graph {
private val nodes : List<List<Node>>
constructor(graph: Graph, expand: Int) {
val sourceSizeY = graph.nodes.size
val sourceSizeX = graph.nodes[0].size
val expandedNodes = ArrayList<List<Node>>(sourceSizeY * expand)
for (y in 0 until sourceSizeY * expand) {
val row = ArrayList<Node>(sourceSizeX * expand)
for (x in 0 until sourceSizeX * expand) {
if (y < sourceSizeY && x < sourceSizeX) {
row.add(graph.nodes[y][x].clone(y, x, 0))
} else {
row.add(graph.nodes[y % sourceSizeY][x % sourceSizeX].clone(y, x,(y / sourceSizeY) + (x / sourceSizeX)))
}
}
expandedNodes.add(row)
}
nodes = expandedNodes
println("Total nodes: ${nodes.size * nodes[0].size}")
}
constructor() {
nodes = input.lines().mapIndexed { y, line ->
line.toCharArray().mapIndexed { x, char -> Node(y, x, char.digitToInt()) }
}
println("Total nodes: ${nodes.size * nodes[0].size}")
}
// Dijkstra algorithm implementation
fun calculateShortestPath(): Long {
return measureTimeMillis {
val startNode = nodes[0][0]
startNode.distance = 0
val settledNodes = HashSet<Node>()
val unsettledNodes = PriorityQueue<Node> { node1, node2 -> node1.distance - node2.distance }
unsettledNodes.add(startNode)
while (unsettledNodes.isNotEmpty()) {
val currentNode: Node = unsettledNodes.remove()
for (nextNode in getAdjacentNodes(currentNode)) {
if (!settledNodes.contains(nextNode)) {
nextNode.considerNode(currentNode)
if (!unsettledNodes.contains(nextNode)) {
unsettledNodes.add(nextNode)
}
}
}
settledNodes.add(currentNode)
}
}
}
// Dijkstra algorithm implementation using Fibonacci heap
fun calculateShortestPathOptimized(): Long {
return measureTimeMillis {
val startNode = nodes[0][0]
startNode.distance = 0
val settledNodes = HashSet<Node>()
val heap = FibonacciHeap<Node, Unit> { node1, node2 -> node1.distance - node2.distance }
heap.insert(startNode)
while (!heap.isEmpty) {
val currentNode = heap.deleteMin().key
for (nextNode in getAdjacentNodes(currentNode)) {
if (!settledNodes.contains(nextNode)) {
if (nextNode.considerNode(currentNode)) {
nextNode.addOrDecreaseHeap(heap)
}
}
}
settledNodes.add(currentNode)
}
}
}
private val adjacentNodeIndexes = listOf(Pair(0, -1), Pair(0, 1), Pair(1, 0), Pair(-1, 0))
private fun getAdjacentNodes(node: Node): List<Node> {
return adjacentNodeIndexes.mapNotNull {
if (node.posy + it.first >= 0 && node.posy + it.first < nodes.size) {
if (node.posx + it.second >= 0 && node.posx + it.second < nodes[node.posy].size) {
return@mapNotNull nodes[node.posy + it.first][node.posx + it.second]
}
}
null
}
}
fun reset() {
nodes.forEach { it.forEach { node -> node.reset() } }
}
fun getEndNode(): Node {
return nodes[nodes.size-1][nodes[0].size -1]
}
}
class Node(val posy: Int, val posx: Int, val riskLevel: Int) {
var previousNode : Node? = null
var distance = Int.MAX_VALUE
var handle : AddressableHeap.Handle<Node, Unit>? = null
fun considerNode(prevNodeCandidate: Node) : Boolean {
if (prevNodeCandidate.distance + riskLevel < distance) {
previousNode = prevNodeCandidate
distance = prevNodeCandidate.distance + riskLevel
return true
}
return false
}
fun addOrDecreaseHeap(heap: FibonacciHeap<Node, Unit>) {
if (handle == null) {
handle = heap.insert(this)
} else {
handle!!.decreaseKey(this)
}
}
fun getTotalDistance() : Int {
if (previousNode != null) {
return previousNode!!.getTotalDistance() + riskLevel
}
return 0
}
fun reset() {
previousNode = null
distance = Int.MAX_VALUE
handle = null
}
override fun toString(): String {
return "Node(posy=$posy, posx=$posx, riskLevel=$riskLevel, distance=$distance)"
}
fun clone(posy: Int, posx: Int, valueIncrease: Int): Node {
var newRiskLevel = riskLevel + valueIncrease
if (newRiskLevel > 9) {
newRiskLevel -= 9
}
return Node(posy, posx, newRiskLevel)
}
}
}
| 0 | Kotlin | 0 | 0 | 0cedad1d393d9040c4cc9b50b120647884ea99d9 | 6,887 | advent-of-code | Apache License 2.0 |
src/main/kotlin/de/havemann/transformer/domain/sortkey/SortKey.kt | LukasHavemann | 362,340,388 | false | null | package de.havemann.transformer.domain.sortkey
import java.util.*
import java.util.Comparator.comparing
import kotlin.reflect.KProperty1
/**
* Sorting is determined through the use of the ‘sort’ query string parameter. The value of this parameter is a
* comma-separated list of sort keys. Sort directions can optionally be appended to each sort key, separated by the ‘:’
* character.
*
* The supported sort directions are either ‘asc’ for ascending or ‘desc’ for descending.
*
* The caller may (but is not required to) specify a sort direction for each key. If a sort direction is not specified
* for a key, then a default is set by the server.
*/
data class SortKey(val key: String, val ordering: Ordering) {
companion object {
/**
* Transforms a list of {@link SortKey} to a {@link Comparator}
*/
fun <Entity, Value : Comparable<Value>> toComparator(
sortKeys: List<SortKey>,
sortKeyToProperty: Map<String, KProperty1<Entity, Value?>>
): Comparator<Entity> {
return sortKeys
.stream()
.filter { sortKeyToProperty[it.key] != null }
.map { sortKey ->
val property = sortKeyToProperty[sortKey.key]
val sortingFunction: (t: Entity) -> Value = { property?.call(it)!! }
sortKey.ordering.adjust(comparing(sortingFunction))
}
.reduce { a, b -> a.thenComparing(b) }
.orElseThrow { IllegalArgumentException("list shouldn't be empty") }
}
}
}
enum class Ordering(val key: String) {
ASCENDING("asc"),
DESCENDING("desc");
/**
* reverses the given comparator if ordering is descending
*/
fun <T> adjust(comparator: Comparator<T>): Comparator<T> {
return if (this == DESCENDING) comparator.reversed() else comparator
}
companion object {
/**
* determines Ordering form given string
*/
fun detect(token: String): Ordering {
return values().asSequence()
.filter { it.key == token }
.firstOrNull()
?: throw IllegalArgumentException(token)
}
}
}
| 0 | Kotlin | 0 | 0 | 8638fe7c4037c93708cdaf05b9a8c23954e7d866 | 2,259 | microservice-transformer | MIT License |
src/main/kotlin/com/hj/leetcode/kotlin/problem211/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem211
/**
* LeetCode page: [211. Design Add and Search Words Data Structure](https://leetcode.com/problems/design-add-and-search-words-data-structure/);
*/
class WordDictionary() {
private val root = Trie(wildcards = '.')
fun addWord(word: String) {
root.addWord(word)
}
fun search(word: String): Boolean {
return root.search(word)
}
private class Trie(private val wildcards: Char) {
private var isEndOfWord = false
private val children = hashMapOf<Char, Trie>()
/* Complexity:
* Time O(L) and Space O(L) where L is the length of word;
*/
fun addWord(word: String) {
var currNode = this
for (char in word) {
currNode = currNode.children.computeIfAbsent(char) { Trie(wildcards) }
}
currNode.setEndOfWord()
}
private fun setEndOfWord() {
isEndOfWord = true
}
private fun isEndOfWord() = isEndOfWord
/* Complexity:
* Time O(A^N * L) and Space O(L) where A and N are the number of possible char and the
* maximum number of wildcards in word, L is the length of word;
*/
fun search(word: String): Boolean {
return search(word, 0)
}
private fun search(word: String, fromIndex: Int): Boolean {
if (fromIndex == word.length) {
return this.isEndOfWord()
}
val currChar = word[fromIndex]
return if (currChar == wildcards) {
children.values.any { it.search(word, fromIndex + 1) }
} else {
children[currChar]?.search(word, fromIndex + 1) ?: false
}
}
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 1,794 | hj-leetcode-kotlin | Apache License 2.0 |
2023/15/Solution.kt | AdrianMiozga | 588,519,359 | false | {"Kotlin": 110785, "Python": 11275, "Assembly": 3369, "C": 2378, "Pawn": 1390, "Dart": 732} | import java.io.File
private const val FILENAME = "2023/15/input.txt"
fun main() {
partOne()
partTwo()
}
private fun partOne() {
val file = File(FILENAME).readLines().map { it.split(",") }.first()
var result = 0
for (element in file) {
result += hash(element)
}
println(result)
}
private fun partTwo() {
val file = File(FILENAME).readLines().map { it.split(",") }.first()
val boxes = HashMap<Int, MutableList<Pair<String, Int>>>()
for (label in file) {
if (label.contains("-")) {
val lens = label.replace("-", "")
val currentValue = hash(lens)
if (boxes[currentValue] == null) {
continue
}
var removeIndex = -1
for ((index, pair) in boxes[currentValue]!!.withIndex()) {
if (pair.first == lens) {
removeIndex = index
}
}
if (removeIndex != -1) {
boxes[currentValue]!!.removeAt(removeIndex)
}
} else {
val (lens, value) = Regex("""(\w+)=(\d+)""").matchEntire(label)!!.destructured
val currentValue = hash(lens)
val list = boxes[currentValue]
if (list == null) {
boxes[currentValue] = mutableListOf(Pair(lens, value.toInt()))
} else {
var removeIndex = -1
for ((index, pair) in boxes[currentValue]!!.withIndex()) {
if (pair.first == lens) {
removeIndex = index
}
}
if (removeIndex != -1) {
boxes[currentValue]!!.removeAt(removeIndex)
boxes[currentValue]!!.add(removeIndex, Pair(lens, value.toInt()))
} else {
boxes[currentValue]!!.add(Pair(lens, value.toInt()))
}
}
}
}
var result = 0
for (box in boxes) {
for ((slot, values) in box.value.withIndex()) {
var temp = box.key + 1
temp *= slot + 1
temp *= values.second
result += temp
}
}
println(result)
}
private fun hash(lens: String): Int {
var currentValue = 0
for (character in lens) {
currentValue += character.code
currentValue *= 17
currentValue %= 256
}
return currentValue
}
| 0 | Kotlin | 0 | 0 | c9cba875089d8d4fb145932c45c2d487ccc7e8e5 | 2,449 | Advent-of-Code | MIT License |
src/Day04.kt | rossilor95 | 573,177,479 | false | {"Kotlin": 8837} | fun main() {
fun String.toIntRange(): IntRange = this.substringBefore('-').toInt()..this.substringAfter('-').toInt()
fun String.toIntRangePair(): Pair<IntRange, IntRange> =
this.substringBefore(',').toIntRange() to this.substringAfter(',').toIntRange()
infix fun IntRange.enclose(other: IntRange): Boolean = this.first <= other.first && this.last >= other.last
infix fun IntRange.overlap(other: IntRange): Boolean = (this intersect other).isNotEmpty()
fun part1(input: List<String>): Int = input.map { it.toIntRangePair() }.count { (assignments1, assignments2) ->
(assignments1 enclose assignments2) || (assignments2 enclose assignments1)
}
fun part2(input: List<String>): Int = input.map { it.toIntRangePair() }.count { (assignments1, assignments2) ->
assignments1 overlap assignments2
}
val testInput = readInput("Day04_test")
val input = readInput("Day04")
check(part1(testInput) == 2)
println("Part 1 Answer: ${part1(input)}")
check(part2(testInput) == 4)
println("Part 2 Answer: ${part2(input)}")
} | 0 | Kotlin | 0 | 0 | 0ed98d0ab5f44b2ccfc625ef091e736c5c748ff0 | 1,091 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/main/kotlin/com/askrepps/advent2022/day03/Day03.kt | askrepps | 726,566,200 | false | {"Kotlin": 302802} | /*
* MIT License
*
* Copyright (c) 2022-2023 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.askrepps.advent.advent2022.day03
import com.askrepps.advent.util.getInputLines
import java.io.File
data class Rucksack(val items: String) {
val firstCompartment = items.take(items.length / 2)
val secondCompartment = items.takeLast(items.length / 2)
}
fun String.toRucksack() = Rucksack(this)
val Char.priority: Int
get() = when (this) {
in 'a'..'z' -> this - 'a' + 1
in 'A'..'Z' -> this - 'A' + 27
else -> error("Invalid character $this")
}
val ALL_TYPES = ('a'..'z').toSet() + ('A'..'Z').toSet()
val List<Rucksack>.commonPriority: Int
get() {
val commonType = fold(ALL_TYPES) { acc, rucksack ->
acc.intersect(rucksack.items.toSet())
}
check(commonType.size == 1)
return commonType.first().priority
}
fun getPart1Answer(rucksacks: List<Rucksack>) =
rucksacks.sumOf { rucksack ->
rucksack.firstCompartment.toSet()
.intersect(rucksack.secondCompartment.toSet())
.sumOf { it.priority }
}
fun getPart2Answer(rucksacks: List<Rucksack>) =
rucksacks.chunked(3)
.sumOf { it.commonPriority }
fun main() {
val rucksacks = File("src/main/resources/2022/input-2022-day03.txt")
.getInputLines().map { it.toRucksack() }
println("The answer to part 1 is ${getPart1Answer(rucksacks)}")
println("The answer to part 2 is ${getPart2Answer(rucksacks)}")
}
| 0 | Kotlin | 0 | 0 | 5ce2228b0951db49a5cf2a6d974112f57e70030c | 2,564 | advent-of-code-kotlin | MIT License |
src/Day01.kt | maciekbartczak | 573,160,363 | false | {"Kotlin": 41932} | fun main() {
fun part1(input: String): Int {
return input
.split("\n\n")
.maxOf { calories ->
calories
.split("\n")
.sumOf { it.toInt() }
}
}
fun part2(input: String): Int {
return input
.split("\n\n")
.map { calories ->
calories
.split("\n")
.sumOf { it.toInt() }
}
.sortedDescending()
.take(3)
.sum()
}
val testInput = readInputAsString("Day01_test")
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
val input = readInputAsString("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 53c83d9eb49d126e91f3768140476a52ba4cd4f8 | 783 | advent-of-code-2022 | Apache License 2.0 |
Kotlin/src/LetterCombinationsOfAPhoneNumber.kt | TonnyL | 106,459,115 | false | null | /**
* Given a digit string, return all possible letter combinations that the number could represent.
*
* A mapping of digit to letters (just like on the telephone buttons) is given below.
*
* Input:Digit string "23"
* Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
* Note:
* Although the above answer is in lexicographical order, your answer could be in any order you want.
*
* Accepted.
*/
class LetterCombinationsOfAPhoneNumber {
fun letterCombinations(digits: String): List<String> {
val dict = arrayOf(" ", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz")
val results = mutableListOf<String>()
if (digits.isEmpty()) {
return emptyList()
}
if (digits.length == 1) {
dict[Integer.valueOf(digits)].toCharArray()
.mapTo(results) {
it.toString()
}
return results
}
val list = letterCombinations(digits.substring(1, digits.length))
val sb = StringBuilder()
for (c in dict[Integer.valueOf(digits.substring(0, 1))].toCharArray()) {
for (s in list) {
sb.append(c.toString()).append(s)
results.add(sb.toString())
sb.setLength(0)
}
}
return results
}
}
| 1 | Swift | 22 | 189 | 39f85cdedaaf5b85f7ce842ecef975301fc974cf | 1,362 | Windary | MIT License |
kotlin/720.Longest Word in Dictionary(词典中最长的单词).kt | learningtheory | 141,790,045 | false | {"Python": 4025652, "C++": 1999023, "Java": 1995266, "JavaScript": 1990554, "C": 1979022, "Ruby": 1970980, "Scala": 1925110, "Kotlin": 1917691, "Go": 1898079, "Swift": 1827809, "HTML": 124958, "Shell": 7944} | /**
<p>Given a list of strings <code>words</code> representing an English Dictionary, find the longest word in <code>words</code> that can be built one character at a time by other words in <code>words</code>. If there is more than one possible answer, return the longest word with the smallest lexicographical order.</p> If there is no answer, return the empty string.
<p><b>Example 1:</b><br />
<pre>
<b>Input:</b>
words = ["w","wo","wor","worl", "world"]
<b>Output:</b> "world"
<b>Explanation:</b>
The word "world" can be built one character at a time by "w", "wo", "wor", and "worl".
</pre>
</p>
<p><b>Example 2:</b><br />
<pre>
<b>Input:</b>
words = ["a", "banana", "app", "appl", "ap", "apply", "apple"]
<b>Output:</b> "apple"
<b>Explanation:</b>
Both "apply" and "apple" can be built from other words in the dictionary. However, "apple" is lexicographically smaller than "apply".
</pre>
</p>
<p><b>Note:</b>
<li>All the strings in the input will only contain lowercase letters.</li>
<li>The length of <code>words</code> will be in the range <code>[1, 1000]</code>.</li>
<li>The length of <code>words[i]</code> will be in the range <code>[1, 30]</code>.</li>
</p><p>给出一个字符串数组<code>words</code>组成的一本英语词典。从中找出最长的一个单词,该单词是由<code>words</code>词典中其他单词逐步添加一个字母组成。若其中有多个可行的答案,则返回答案中字典序最小的单词。</p>
<p>若无答案,则返回空字符串。</p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong>
words = ["w","wo","wor","worl", "world"]
<strong>输出:</strong> "world"
<strong>解释:</strong>
单词"world"可由"w", "wo", "wor", 和 "worl"添加一个字母组成。
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>
words = ["a", "banana", "app", "appl", "ap", "apply", "apple"]
<strong>输出:</strong> "apple"
<strong>解释:</strong>
"apply"和"apple"都能由词典中的单词组成。但是"apple"得字典序小于"apply"。
</pre>
<p><strong>注意:</strong></p>
<ul>
<li>所有输入的字符串都只包含小写字母。</li>
<li><code>words</code>数组长度范围为<code>[1,1000]</code>。</li>
<li><code>words[i]</code>的长度范围为<code>[1,30]</code>。</li>
</ul>
<p>给出一个字符串数组<code>words</code>组成的一本英语词典。从中找出最长的一个单词,该单词是由<code>words</code>词典中其他单词逐步添加一个字母组成。若其中有多个可行的答案,则返回答案中字典序最小的单词。</p>
<p>若无答案,则返回空字符串。</p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong>
words = ["w","wo","wor","worl", "world"]
<strong>输出:</strong> "world"
<strong>解释:</strong>
单词"world"可由"w", "wo", "wor", 和 "worl"添加一个字母组成。
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>
words = ["a", "banana", "app", "appl", "ap", "apply", "apple"]
<strong>输出:</strong> "apple"
<strong>解释:</strong>
"apply"和"apple"都能由词典中的单词组成。但是"apple"得字典序小于"apply"。
</pre>
<p><strong>注意:</strong></p>
<ul>
<li>所有输入的字符串都只包含小写字母。</li>
<li><code>words</code>数组长度范围为<code>[1,1000]</code>。</li>
<li><code>words[i]</code>的长度范围为<code>[1,30]</code>。</li>
</ul>
**/
class Solution {
fun longestWord(words: Array<String>): String {
}
} | 0 | Python | 1 | 3 | 6731e128be0fd3c0bdfe885c1a409ac54b929597 | 3,989 | leetcode | MIT License |
src/main/kotlin/days/Day7.kt | hughjdavey | 572,954,098 | false | {"Kotlin": 61752} | package days
import xyz.hughjd.aocutils.Collections.indicesOf
class Day7 : Day(7) {
private val commandIndices = inputList.indicesOf { it.startsWith("$") }
private val commands = commandIndices.plus(inputList.size).windowed(2).map { inputList.subList(it[0], it[1]) }
private val root = getFilesystem().findRoot()
override fun partOne(): Any {
return root.findAllDirectories().filter { it.totalSize() <= 100000 }.sumOf { it.totalSize() }
}
override fun partTwo(): Any {
val totalSpace = 70000000
val neededSpace = 30000000
val unusedSpace = totalSpace - root.totalSize()
val spaceToFree = neededSpace - unusedSpace
return root.findAllDirectories().filter { it.totalSize() > spaceToFree }.minBy { it.totalSize() }.totalSize()
}
private fun getFilesystem(): Directory {
return commands.drop(1).fold(Directory("/", null)) { cwd, command ->
val (cmd, output) = command[0].replace("$ ", "") to command.drop(1)
if (cmd.startsWith("cd")) {
val name = cmd.replace("cd ", "")
if (name == "..") cwd.parent!! else cwd.findDirectory(name) ?: Directory(name, cwd)
}
else {
val children = output.map {
if (it.startsWith("dir")) Directory(it.replace("dir ", ""), cwd) else {
val (size, name) = Regex("(\\d+) (.+)").matchEntire(it)!!.destructured;
File(name, size.toInt(), cwd)
}
}
cwd.children.addAll(children)
cwd
}
}
}
abstract class FilesystemObject(val name: String, val size: Int, val parent: Directory?, val children: MutableList<FilesystemObject> = mutableListOf()) {
override fun toString(): String {
return "FilesystemObject(name='$name', size=$size, parent=$parent)"
}
}
class File(name: String, size: Int, parent: Directory) : FilesystemObject(name, size, parent)
class Directory(name: String, parent: Directory?) : FilesystemObject(name, 0, parent) {
fun totalSize(): Int {
return if (children.isEmpty()) 0 else children.sumOf { child ->
if (child is File) child.size else (child as Directory).totalSize()
}
}
fun findDirectory(name: String): Directory? {
return if (children.isEmpty()) null else {
val childDirs = children.filterIsInstance<Directory>()
childDirs.find { it.name == name } ?: childDirs.map { it.findDirectory(name) }.find { it != null }
}
}
fun findRoot(): Directory {
return parent?.findRoot() ?: this
}
fun findAllDirectories(dirs: Set<Directory> = emptySet()): Set<Directory> {
return if (children.isEmpty()) emptySet() else {
val childDirs = children.filterIsInstance<Directory>()
dirs.plus(this).plus(childDirs).plus(childDirs.flatMap { it.findAllDirectories() })
}
}
}
}
| 0 | Kotlin | 0 | 2 | 65014f2872e5eb84a15df8e80284e43795e4c700 | 3,124 | aoc-2022 | Creative Commons Zero v1.0 Universal |
src/Day22.kt | janbina | 112,736,606 | false | null | package Day22
import getInput
import kotlin.test.assertEquals
fun main(args: Array<String>) {
val input = getInput(22).readLines()
val gridSize = 1000
val grid = Array(gridSize) { CharArray(gridSize) { '.' } }
val i = (gridSize - input.size) / 2
val j = (gridSize - input[0].length) / 2
val centerI = i + input.size/2
val centerJ = j + input[0].length/2
input.forEachIndexed { i2, line ->
line.forEachIndexed { j2, c ->
grid[i + i2][j + j2] = c
}
}
assertEquals(5460, part1(grid.copy(), centerI to centerJ, -1 to 0))
assertEquals(2511702, part2(grid.copy(), centerI to centerJ, -1 to 0))
}
fun part1(grid: Array<CharArray>, startPosition: Pair<Int, Int>, startDirection: Pair<Int, Int>): Int {
var position = startPosition
var direction = startDirection
var burstsCausingInfection = 0
repeat(10_000) {
when (grid[position]) {
'#' -> {
grid[position] = '.'
direction = direction.turnRight()
}
'.' -> {
grid[position] = '#'
direction = direction.turnLeft()
burstsCausingInfection++
}
}
position = position.move(direction)
}
return burstsCausingInfection
}
fun part2(grid: Array<CharArray>, startPosition: Pair<Int, Int>, startDirection: Pair<Int, Int>): Long {
var position = startPosition
var direction = startDirection
var burstsCausingInfection = 0L
repeat(10_000_000) {
when (grid[position]) {
'#' -> {
grid[position] = 'F'
direction = direction.turnRight()
}
'W' -> {
grid[position] = '#'
burstsCausingInfection++
}
'F' -> {
grid[position] = '.'
direction = direction.reverse()
}
'.' -> {
grid[position] = 'W'
direction = direction.turnLeft()
}
}
position = position.move(direction)
}
return burstsCausingInfection
}
fun Pair<Int, Int>.turnRight() = second to -first
fun Pair<Int, Int>.turnLeft() = -second to first
fun Pair<Int, Int>.reverse() = -first to -second
fun Pair<Int, Int>.move(direction: Pair<Int, Int>) = (first + direction.first) to (second + direction.second)
fun Array<CharArray>.copy() = Array(size) { get(it).clone() }
operator fun Array<CharArray>.get(indices: Pair<Int, Int>) = this[indices.first][indices.second]
operator fun Array<CharArray>.set(indices: Pair<Int, Int>, value: Char) {
this[indices.first][indices.second] = value
} | 0 | Kotlin | 0 | 0 | 71b34484825e1ec3f1b3174325c16fee33a13a65 | 2,694 | advent-of-code-2017 | MIT License |
src/net/sheltem/aoc/y2022/Day21.kt | jtheegarten | 572,901,679 | false | {"Kotlin": 178521} | package net.sheltem.aoc.y2022
import net.sheltem.common.MathOperation
import net.sheltem.common.MathOperation.ADD
import net.sheltem.common.MathOperation.Companion.fromSign
import net.sheltem.common.MathOperation.DIVIDE
import net.sheltem.common.MathOperation.MULTIPLY
import net.sheltem.common.MathOperation.SUBSTRACT
import kotlin.math.absoluteValue
suspend fun main() {
Day21().run()
}
class Day21 : Day<Long>(152, 301) {
override suspend fun part1(input: List<String>): Long = input.toMonkey().value.toLong()
override suspend fun part2(input: List<String>): Long = input.humanNumber()
}
private fun List<String>.toMonkey(): MonkeyNode = this
.map { it.split(": ") }
.associate { it.first() to it[1] }
.let { MathMonkey.from(it["root"]!!, it) }
private fun List<String>.humanNumber(): Long {
val inputMap = this.map { it.split(": ") }.associate { it.first() to it[1] }
var max = Long.MAX_VALUE
var min = 1L
while (true) {
val halfDiff = max - (max - min) / 2
// println("$min | $halfDiff | $max")
val tests = listOf(min, halfDiff, max)
.map { checkValue ->
val checkMap = inputMap.toMutableMap()
checkMap["humn"] = checkValue.toString()
(MathMonkey.from(checkMap["root"]!!, checkMap) as MathMonkey)
.let { checkValue to (it.left diff it.right) }
}.sortedBy { it.second }.take(2)
val result = tests.firstOrNull { it.second == 0.0 }
if (result != null) {
return result.first
} else {
min = tests.minOf { it.first }
max = tests.maxOf { it.first }
}
}
}
private data class MathMonkey(val op: MathOperation, val left: MonkeyNode, val right: MonkeyNode) : MonkeyNode {
override val value = op.execute(left, right)
companion object {
fun from(instruction: String, instructionsMap: Map<String, String>): MonkeyNode =
if (instruction.toLongOrNull() != null) ValueMonkey(instruction.toDouble())
else instruction.split(" ")
.let { MathMonkey(fromSign(it[1]), from(instructionsMap[it[0]]!!, instructionsMap), from(instructionsMap[it[2]]!!, instructionsMap)) }
}
}
private data class ValueMonkey(override val value: Double) : MonkeyNode
private interface MonkeyNode {
val value: Double
infix operator fun plus(other: MonkeyNode) = value + other.value
infix operator fun minus(other: MonkeyNode) = value - other.value
infix operator fun div(other: MonkeyNode) = value / other.value
infix operator fun times(other: MonkeyNode) = value * other.value
infix fun diff(other: MonkeyNode) = (value - other.value).absoluteValue
}
private fun MathOperation.execute(left: MonkeyNode, right: MonkeyNode) =
when (this) {
ADD -> left + right
SUBSTRACT -> left - right
MULTIPLY -> left * right
DIVIDE -> left / right
}
| 0 | Kotlin | 0 | 0 | ac280f156c284c23565fba5810483dd1cd8a931f | 2,967 | aoc | Apache License 2.0 |
src/Day24.kt | ech0matrix | 572,692,409 | false | {"Kotlin": 116274} | import java.util.PriorityQueue
fun main() {
fun part1(input: List<String>): Long {
// Set border
val borderMin = Coordinates(0, 0)
val borderMax = Coordinates(input.size-1, input[0].length-1)
// Set start/end
val start = borderMin.add(Coordinates(0, 1))
val end = borderMax.add(Coordinates(0, -1))
val startNext = start.add(Coordinates(1, 0))
val endPrecursor = end.add(Coordinates(-1, 0))
// Parse blizzards
val blizzards = mutableListOf<Blizzard>()
for(row in borderMin.row+1 .. borderMax.row-1) {
for(col in borderMin.col+1 .. borderMax.col-1) {
if (input[row][col] != '.') {
val orientation = when(input[row][col]) {
'>' -> 0
'v' -> 1
'<' -> 2
'^' -> 3
else -> throw IllegalArgumentException("Unexpected orientation symbol: ${input[row][col]}")
}
blizzards.add(Blizzard(
Coordinates(row, col),
orientation,
borderMin,
borderMax
))
}
}
}
val blizzardManager = BlizzardStateManager(blizzards)
var quickestTime = Long.MAX_VALUE
val visited = mutableSetOf<ValleyTile>()
val active = PriorityQueue<ValleyTile>(compareBy { it.costDistance })
active.offer(ValleyTile(start, 0, start.manhattanDistance(end).toLong()))
while(!active.isEmpty()) {
// Get next tile
val current = active.poll()!!
//println(current)
if (current.position == end) {
// Found the end
quickestTime = minOf(current.time, quickestTime)
}
visited.add(current)
// Update blizzards
val time = current.time + 1
val blizzardState = blizzardManager.get(time)
if (time < quickestTime) {
// Find possible moves
val possibleMoves = mutableListOf<ValleyTile>()
if (!blizzardState.contains(current.position)) {
// Standing still
possibleMoves.add(current.copy(time = time))
}
if (current.position == start && !blizzardState.contains(startNext)) {
// Move out of start
possibleMoves.add(ValleyTile(startNext, time, startNext.manhattanDistance(end).toLong()))
} else if (current.position == endPrecursor) {
// Move to end
quickestTime = minOf(time, quickestTime)
} else {
// All cardinal directions
val directionalMoves = listOf(
current.position.add(Coordinates(0, 1)),
current.position.add(Coordinates(0, -1)),
current.position.add(Coordinates(1, 0)),
current.position.add(Coordinates(-1, 0))
)
for (move in directionalMoves) {
// Use moves within border and no blizzards
if (move.row > borderMin.row && move.row < borderMax.row
&& move.col > borderMin.col && move.col < borderMax.col
&& !blizzardState.contains(move)
) {
possibleMoves.add(ValleyTile(move, time, move.manhattanDistance(end).toLong()))
}
}
}
// Check for repeated moves
possibleMoves.filter { !visited.contains(it) && !active.contains(it) }.forEach { active.offer(it) }
}
}
return quickestTime
}
fun part2(input: List<String>): Long {
// Set border
val borderMin = Coordinates(0, 0)
val borderMax = Coordinates(input.size-1, input[0].length-1)
// Set start/end
val start = borderMin.add(Coordinates(0, 1))
val end = borderMax.add(Coordinates(0, -1))
val startNext = start.add(Coordinates(1, 0))
val endPrecursor = end.add(Coordinates(-1, 0))
val lapDistance = start.manhattanDistance(end).toLong()
// Parse blizzards
val blizzards = mutableListOf<Blizzard>()
for(row in borderMin.row+1 .. borderMax.row-1) {
for(col in borderMin.col+1 .. borderMax.col-1) {
if (input[row][col] != '.') {
val orientation = when(input[row][col]) {
'>' -> 0
'v' -> 1
'<' -> 2
'^' -> 3
else -> throw IllegalArgumentException("Unexpected orientation symbol: ${input[row][col]}")
}
blizzards.add(Blizzard(
Coordinates(row, col),
orientation,
borderMin,
borderMax
))
}
}
}
val blizzardManager = BlizzardStateManager(blizzards)
var quickestTime = Long.MAX_VALUE
val visited = mutableSetOf<ValleyTile2>()
val active = PriorityQueue<ValleyTile2>(compareBy { it.costDistance })
active.offer(ValleyTile2(start, 0, lapDistance*3L))
while(!active.isEmpty()) {
// Get next tile
val current = active.poll()!!
//println(current)
if (current.position == end && current.reachedStart) {
// Found the end
quickestTime = minOf(current.time, quickestTime)
//return quickestTime // -- For debugging only
}
visited.add(current)
// Update blizzards
val time = current.time + 1
val blizzardState = blizzardManager.get(time)
if (time < quickestTime) {
// Find possible moves
val possibleMoves = mutableListOf<ValleyTile2>()
if (!blizzardState.contains(current.position)) {
// Standing still
possibleMoves.add(current.copy(time = time))
}
if (current.position == start && !blizzardState.contains(startNext)) {
// Move out of start
possibleMoves.add(ValleyTile2(startNext, time, startNext.manhattanDistance(end).toLong() + if (current.reachedEnd) 0 else lapDistance*2L, current.reachedEnd, current.reachedStart))
} else if (current.position == startNext && current.reachedEnd && !current.reachedStart) {
val nextMove = ValleyTile2(start, time, lapDistance, reachedEnd = true, reachedStart = true)
possibleMoves.add(nextMove)
// active.clear() // -- For debugging only
// println("Reached start again, second lap")
// println(" Current: $current")
// println(" Next: $nextMove")
} else if (current.position == endPrecursor && !current.reachedEnd) {
val nextMove = ValleyTile2(end, time, lapDistance*2L, reachedEnd = true, reachedStart = false)
possibleMoves.add(nextMove)
// active.clear() // -- For debugging only
// println("Reached end, first lap")
// println(" Current: $current")
// println(" Next: $nextMove")
} else if (current.position == endPrecursor && current.reachedStart) {
quickestTime = minOf(time, quickestTime)
//return quickestTime // -- For debugging only
} else if (current.position == end && !blizzardState.contains(endPrecursor)) {
possibleMoves.add(ValleyTile2(endPrecursor, time, endPrecursor.manhattanDistance(start).toLong() + lapDistance, current.reachedEnd, current.reachedStart))
} else {
// All cardinal directions
val directionalMoves = listOf(
current.position.add(Coordinates(0, 1)),
current.position.add(Coordinates(0, -1)),
current.position.add(Coordinates(1, 0)),
current.position.add(Coordinates(-1, 0))
)
for (move in directionalMoves) {
// Use moves within border and no blizzards
if (move.row > borderMin.row && move.row < borderMax.row
&& move.col > borderMin.col && move.col < borderMax.col
&& !blizzardState.contains(move)
) {
val distance = when {
current.reachedEnd -> move.manhattanDistance(start).toLong() + lapDistance
current.reachedStart -> move.manhattanDistance(end).toLong()
else -> move.manhattanDistance(end).toLong() + lapDistance*2L
}
possibleMoves.add(ValleyTile2(move, time, distance, current.reachedEnd, current.reachedStart))
}
}
}
// Check for repeated moves
possibleMoves.filter { !visited.contains(it) && !active.contains(it) }.forEach { active.offer(it) }
}
}
return quickestTime
}
val testInput = readInput("Day24_test")
check(part1(testInput) == 18L)
check(part2(testInput) == 54L)
val input = readInput("Day24")
val startTime1 = java.util.Date().time
val part1Answer = part1(input)
val endTime1 = java.util.Date().time
println("Part 1 (${endTime1-startTime1}ms): $part1Answer")
val startTime2 = java.util.Date().time
val part2Answer = part2(input)
val endTime2 = java.util.Date().time
println("Part 2 (${endTime2-startTime2}ms): $part2Answer")
}
data class ValleyTile(
val position: Coordinates,
val time: Long,
val distance: Long
) {
val costDistance = time * distance
}
data class ValleyTile2(
val position: Coordinates,
val time: Long,
val distance: Long,
val reachedEnd: Boolean = false,
val reachedStart: Boolean = false
) {
val costDistance = time * distance
}
class BlizzardStateManager(
initialState: List<Blizzard>
) {
private var currentTime = 0L
private var currentState = initialState
private val stateCache = mutableMapOf<Long, Set<Coordinates>>()
fun get(time: Long): Set<Coordinates> {
val cachedState = stateCache[time]
if (cachedState != null) {
return cachedState
}
for(t in currentTime+1 .. time) {
currentState = currentState.map { it.move() }
val newCachedState = currentState.map{it.position}.toSet()
stateCache[t] = newCachedState
}
currentTime = time
return stateCache[time]!!
}
}
data class Blizzard(
val position: Coordinates,
val orientation: Int,
val borderMin: Coordinates,
val borderMax: Coordinates
) {
companion object {
private val vectors = listOf(
Coordinates(0, 1), // Right
Coordinates(1, 0), // Down
Coordinates(0, -1), // Left
Coordinates(-1, 0) // Up
)
}
fun move(): Blizzard {
var next = position.add(vectors[orientation])
if (next.col == borderMin.col && orientation == 2) {
// Left border
next = Coordinates(next.row, borderMax.col-1)
} else if (next.col == borderMax.col && orientation == 0) {
// Right border
next = Coordinates(next.row, borderMin.col+1)
} else if (next.row == borderMin.row && orientation == 3) {
// Top border
next = Coordinates(borderMax.row-1, next.col)
} else if (next.row == borderMax.row && orientation == 1) {
next = Coordinates(borderMin.row+1, next.col)
}
return this.copy(position = next)
}
} | 0 | Kotlin | 0 | 0 | 50885e12813002be09fb6186ecdaa3cc83b6a5ea | 12,455 | aoc2022 | Apache License 2.0 |
utils/common/src/main/kotlin/Utils.kt | oss-review-toolkit | 107,540,288 | false | {"Kotlin": 4800742, "JavaScript": 307822, "Shell": 124731, "HTML": 81058, "Haskell": 30438, "CSS": 26585, "FreeMarker": 26475, "Python": 19161, "Dockerfile": 18312, "Swift": 11625, "Ruby": 9720, "Roff": 7665, "Vim Snippet": 7361, "Scala": 6656, "Go": 2816, "ANTLR": 1953, "Java": 559, "Rust": 280, "Emacs Lisp": 191} | /*
* Copyright (C) 2017 The ORT Project Authors (see <https://github.com/oss-review-toolkit/ort/blob/main/NOTICE>)
*
* 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
*
* https://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.
*
* SPDX-License-Identifier: Apache-2.0
* License-Filename: LICENSE
*/
package org.ossreviewtoolkit.utils.common
import java.io.File
import java.io.InputStream
import java.security.MessageDigest
import java.util.EnumSet
/**
* A comparator that sorts parent paths before child paths.
*/
val PATH_STRING_COMPARATOR = compareBy<String>({ path -> path.count { it == '/' } }, { it })
/**
* A set of directories used by version control systems to store metadata. The list covers also version control systems
* not supported by ORT, because such directories should never be considered.
*/
val VCS_DIRECTORIES = setOf(
".bzr",
".git",
".hg",
".repo",
".svn",
"CVS",
"CVSROOT"
)
/**
* Calculate the [digest] on the data from the given [file].
*/
fun calculateHash(file: File, digest: MessageDigest = MessageDigest.getInstance("SHA-1")): ByteArray =
file.inputStream().use { calculateHash(it, digest) }
/**
* Calculate the [digest] on the data from the given [string].
*/
fun calculateHash(string: String, digest: MessageDigest = MessageDigest.getInstance("SHA-1")): ByteArray =
string.byteInputStream().use { calculateHash(it, digest) }
/**
* Calculate the [digest] on the data from the given [inputStream]. The caller is responsible for closing the stream.
*/
fun calculateHash(inputStream: InputStream, digest: MessageDigest = MessageDigest.getInstance("SHA-1")): ByteArray {
// 4MB has been chosen rather arbitrarily, hoping that it provides good performance while not consuming a
// lot of memory at the same time, also considering that this function could potentially be run on multiple
// threads in parallel.
val buffer = ByteArray(4.mebibytes.toInt())
var length: Int
while (inputStream.read(buffer).also { length = it } > 0) {
digest.update(buffer, 0, length)
}
return digest.digest()
}
/**
* A Kotlin-style convenience function to replace EnumSet.of() and EnumSet.noneOf().
*/
inline fun <reified T : Enum<T>> enumSetOf(vararg elems: T): EnumSet<T> =
EnumSet.noneOf(T::class.java).apply { addAll(elems) }
/**
* Return recursively all ancestor directories of the given absolute [file], ordered along the path from
* the parent of [file] to the root.
*/
fun getAllAncestorDirectories(file: String): List<String> {
val result = mutableListOf<String>()
var ancestorDir = File(file).parentFile
while (ancestorDir != null) {
result += ancestorDir.invariantSeparatorsPath
ancestorDir = ancestorDir.parentFile
}
return result
}
/**
* Return the longest parent file that all [files] have in common, or a [File] with an empty path if they have no common
* parent file.
*/
fun getCommonParentFile(files: Collection<File>): File =
files.map {
it.normalize().parent
}.reduceOrNull { prefix, path ->
prefix?.commonPrefixWith(path.orEmpty(), ignoreCase = Os.isWindows)
}.orEmpty().let {
File(it)
}
/**
* Return the concatenated [strings] separated by [separator] whereas blank strings are omitted.
*/
fun joinNonBlank(vararg strings: String, separator: String = " - ") =
strings.filter { it.isNotBlank() }.joinToString(separator)
/**
* Temporarily set the specified system [properties] while executing [block]. Afterwards, previously set properties have
* their original values restored and previously unset properties are cleared.
*/
fun <R> temporaryProperties(vararg properties: Pair<String, String?>, block: () -> R): R {
val originalProperties = mutableListOf<Pair<String, String?>>()
properties.forEach { (key, value) ->
originalProperties += key to System.getProperty(key)
value?.also { System.setProperty(key, it) } ?: System.clearProperty(key)
}
return try {
block()
} finally {
originalProperties.forEach { (key, value) ->
value?.also { System.setProperty(key, it) } ?: System.clearProperty(key)
}
}
}
| 346 | Kotlin | 284 | 1,419 | 5c5eae44a5bd4934c4600a56ee08b79cb074f072 | 4,655 | ort | Apache License 2.0 |
src/main/kotlin/day1.kt | danielfreer | 297,196,924 | false | null | import kotlin.time.ExperimentalTime
@ExperimentalTime
fun day1(input: List<String>): List<Solution> {
val modulesMass = input.map(String::toInt)
return listOf(
solve(1, 1) { sumFuelRequired(modulesMass) },
solve(1, 2) { sumAllFuelRequired(modulesMass) }
)
}
fun fuelRequired(mass: Int) = mass / 3 - 2
fun sumFuelRequired(modulesMass: List<Int>) = modulesMass.sumBy(::fuelRequired)
tailrec fun allFuelRequired(mass: Int, totalFuel: Int = 0): Int {
if (mass < 9) return totalFuel
val fuel = fuelRequired(mass)
return allFuelRequired(fuel, totalFuel + fuel)
}
fun sumAllFuelRequired(modulesMass: List<Int>) = modulesMass.sumBy(::allFuelRequired)
| 0 | Kotlin | 0 | 0 | 74371d15f95492dee1ac434f0bfab3f1160c5d3b | 689 | advent2019 | The Unlicense |
kotlin/src/katas/kotlin/leetcode/phone_number/PhoneNumber.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.phone_number
import datsok.shouldEqual
import org.junit.Test
/**
* https://leetcode.com/problems/letter-combinations-of-a-phone-number/
*/
class PhoneNumberTests {
@Test fun `find all possible letter combinations that a number could represent`() {
"".letterCombinations() shouldEqual emptyList()
"1".letterCombinations() shouldEqual emptyList()
"2".letterCombinations() shouldEqual listOf("a", "b", "c")
"3".letterCombinations() shouldEqual listOf("d", "e", "f")
"23".letterCombinations() shouldEqual listOf("ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf")
}
}
private fun String.letterCombinations(): List<String> {
if (isEmpty()) return emptyList()
val lettersByNumber = mapOf(
'1' to emptyList(),
'2' to listOf("a", "b", "c"),
'3' to listOf("d", "e", "f")
)
val letters = lettersByNumber[first()] ?: error("")
val combinations = drop(1).letterCombinations()
return if (combinations.isEmpty()) letters
else letters.flatMap { letter -> combinations.map { letter + it } }
}
| 7 | Roff | 3 | 5 | 0f169804fae2984b1a78fc25da2d7157a8c7a7be | 1,114 | katas | The Unlicense |
src/main/kotlin/year2022/day15/Problem.kt | Ddxcv98 | 573,823,241 | false | {"Kotlin": 154634} | package year2022.day15
import IProblem
import java.util.regex.Pattern
import kotlin.math.abs
class Problem(private val y: Int, private val bounds: Int) : IProblem {
private val beacons = mutableSetOf<Point>()
private val distances = mutableMapOf<Point, Int>()
init {
val pattern = Pattern.compile("-?\\d+")
javaClass
.getResourceAsStream("/2022/15.txt")!!
.bufferedReader()
.forEachLine { line ->
val matches = pattern
.matcher(line)
.results()
.map { it.group().toInt() }
.toList()
val sensor = Point(matches[0], matches[1])
val beacon = Point(matches[2], matches[3])
beacons.add(beacon)
distances[sensor] = sensor.taxicabDistance(beacon)
}
}
private fun isCovered(point: Point): Boolean {
for ((sensor, distance) in distances) {
if (point.taxicabDistance(sensor) <= distance) {
return true
}
}
return false
}
private fun findNonCovered(): Point? {
for ((sensor, distance) in distances.mapValues { it.value + 1 }) {
for (i in -distance..distance) {
for (j in arrayOf(-distance + abs(i), distance - abs(i))) {
val y = sensor.y + j
val x = sensor.x + i
if (x < 0 || x > bounds || y < 0 || y > bounds) {
continue
}
val point = Point(x, y)
if (!isCovered(point)) {
return point
}
}
}
}
return null
}
override fun part1(): Int {
val l = distances.minOf { it.key.x - it.value }
val r = distances.maxOf { it.key.x + it.value }
var count = 0
for (x in l..r) {
val point = Point(x, y)
if (!beacons.contains(point) && isCovered(point)) {
count++
}
}
return count
}
override fun part2(): ULong {
val point = findNonCovered()!!
return point.x.toULong() * 4000000UL + point.y.toULong()
}
}
| 0 | Kotlin | 0 | 0 | 455bc8a69527c6c2f20362945b73bdee496ace41 | 2,316 | advent-of-code | The Unlicense |
src/main/kotlin/extensions/Tuple.kt | swantescholz | 102,711,230 | false | null | package extensions
import java.util.*
fun <A, B> fst(pair: Pair<A, B>): A = pair.first
fun <A, B> snd(pair: Pair<A, B>): B = pair.second
//fun <A,B,C> fst(triple: Triple<A,B,C>) : A = triple.first
//fun <A,B,C> snd(triple: Triple<A,B,C>) : B = triple.second
//fun <A,B,C> trd(triple: Triple<A,B,C>) : C = triple.third
fun <A, T> Pair<A, A>.map(function: (A) -> T) = Pair(function(first), function(second))
operator fun <A : Comparable<A>, B : Comparable<B>> Pair<A, B>.compareTo(other: Pair<A, B>): Int {
first.compareTo(other.first).let {
if (it != 0)
return it
}
return second.compareTo(other.second)
}
operator fun <A : Comparable<A>, B : Comparable<B>, C : Comparable<C>> Triple<A, B, C>.compareTo(other: Triple<A, B, C>): Int {
first.compareTo(other.first).let {
if (it != 0)
return it
}
second.compareTo(other.second).let {
if (it != 0)
return it
}
return third.compareTo(other.third)
}
fun <A : Comparable<A>> Pair<A, A>.sorted(): Pair<A, A> {
if (first <= second)
return this
return Pair(second, first)
}
val <A, B> Pair<A, B>.a: A
get() = this.first
val <A, B> Pair<A, B>.b: B
get() = this.second
val <A, B, C> Triple<A, B, C>.a: A
get() = this.first
val <A, B, C> Triple<A, B, C>.b: B
get() = this.second
val <A, B, C> Triple<A, B, C>.c: C
get() = this.third
data class MutablePair<A, B>(var first: A, var second: B) {}
data class MutableTriple<A, B, C>(var first: A, var second: B, var third: C) {}
fun Triple<Long, Long, Long>.sum(): Long {
return this.first + this.second + this.third
}
fun Triple<Long, Long, Long>.product(): Long {
return this.first * this.second * this.third
}
class PriorityPair<T>(val priority: Double, val value: T) : Comparable<PriorityPair<T>> {
override fun compareTo(other: PriorityPair<T>): Int {
return (this.priority - other.priority).sign()
}
operator fun component1(): Double = priority
operator fun component2(): T = value
}
data class Complexl(val a: Long, val b: Long) : Comparable<Complexl> {
override fun compareTo(other: Complexl): Int {
if (a < other.a)
return -1
if (a > other.a)
return 1
if (b < other.b)
return -1
if (b > other.b)
return 1
return 0
}
fun sorted() = if (a < b) this else Complexl(b, a)
}
data class Tuple3l(val a: Long, val b: Long, val c: Long) : Comparable<Tuple3l> {
constructor(a: Int, b: Int, c: Int) : this(a.toLong(), b.toLong(), c.toLong())
override fun compareTo(other: Tuple3l): Int {
if (a < other.a)
return -1
if (a > other.a)
return 1
if (b < other.b)
return -1
if (b > other.b)
return 1
if (c < other.c)
return -1
if (c > other.c)
return 1
return 0
}
}
data class Tuple4<A, B, C, D>(val a: A, val b: B, val c: C, val d: D)
operator fun <A : Comparable<A>, B : Comparable<B>, C : Comparable<C>,
D : Comparable<D>> Tuple4<A, B, C, D>.compareTo(other: Tuple4<A, B, C, D>): Int {
if (a < other.a)
return -1
if (a > other.a)
return 1
if (b < other.b)
return -1
if (b > other.b)
return 1
if (c < other.c)
return -1
if (c > other.c)
return 1
return 0
}
data class Tuple4l(val a: Long, val b: Long, val c: Long, val d: Long) : Comparable<Tuple4l> {
override operator fun compareTo(other: Tuple4l): Int {
if (a < other.a)
return -1
if (a > other.a)
return 1
if (b < other.b)
return -1
if (b > other.b)
return 1
if (c < other.c)
return -1
if (c > other.c)
return 1
if (d < other.d)
return -1
if (d > other.d)
return 1
return 0
}
}
data class Tuple5<A, B, C, D, E>(val a: A, val b: B, val c: C, val d: D, val e: E)
data class Tuple5l(val a: Long, val b: Long, val c: Long, val d: Long, val e: Long) : Comparable<Tuple5l> {
override operator fun compareTo(other: Tuple5l): Int {
if (a < other.a)
return -1
if (a > other.a)
return 1
if (b < other.b)
return -1
if (b > other.b)
return 1
if (c < other.c)
return -1
if (c > other.c)
return 1
if (d < other.d)
return -1
if (d > other.d)
return 1
if (e < other.e)
return -1
if (e > other.e)
return 1
return 0
}
}
data class Tuple6<A, B, C, D, E, F>(val a: A, val b: B, val c: C, val d: D, val e: E, val f: F)
data class Tuple6l(val a: Long, val b: Long, val c: Long, val d: Long, val e: Long, val f: Long)
class Tuple<T>(vararg args: T) : ArrayList<T>(args.toCollection(arrayListOf<T>())) {
val a: T get() = this[0]!!
val b: T get() = this[1]!!
val c: T get() = this[2]!!
val d: T get() = this[3]!!
val e: T get() = this[4]!!
val f: T get() = this[5]!!
val g: T get() = this[6]!!
val h: T get() = this[7]!!
val i: T get() = this[8]!!
val j: T get() = this[9]!!
val k: T get() = this[10]!!
val l: T get() = this[11]!!
val m: T get() = this[12]!!
val n: T get() = this[13]!!
val o: T get() = this[14]!!
val p: T get() = this[15]!!
val q: T get() = this[16]!!
val r: T get() = this[17]!!
val s: T get() = this[18]!!
val t: T get() = this[19]!!
operator fun component1() = this[0]!!
operator fun component2() = this[1]!!
operator fun component3() = this[2]!!
operator fun component4() = this[3]!!
operator fun component5() = this[4]!!
operator fun component6() = this[5]!!
operator fun component7() = this[6]!!
operator fun component8() = this[7]!!
operator fun component9() = this[8]!!
operator fun component10() = this[9]!!
operator fun component11() = this[10]!!
operator fun component12() = this[11]!!
operator fun component13() = this[12]!!
operator fun component14() = this[13]!!
operator fun component15() = this[14]!!
operator fun component16() = this[15]!!
operator fun component17() = this[16]!!
operator fun component18() = this[17]!!
operator fun component19() = this[18]!!
operator fun component20() = this[19]!!
} | 0 | Kotlin | 0 | 0 | 20736acc7e6a004c29c328a923d058f85d29de91 | 5,727 | ai | Do What The F*ck You Want To Public License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/PowerfulIntegers.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2021 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import kotlin.math.ln
import kotlin.math.pow
/**
* 970. Powerful Integers
* @see <a href="https://leetcode.com/problems/powerful-integers/">Source</a>
*/
fun interface PowerfulIntegers {
operator fun invoke(x: Int, y: Int, bound: Int): List<Int>
}
/**
* Approach: Logarithmic Bounds
*/
class LogarithmicBounds : PowerfulIntegers {
override operator fun invoke(x: Int, y: Int, bound: Int): List<Int> {
val a = if (x == 1) bound else (ln(bound.toDouble()) / ln(x.toDouble())).toInt()
val b = if (y == 1) bound else (ln(bound.toDouble()) / ln(y.toDouble())).toInt()
val powerfulIntegers = HashSet<Int>()
for (i in 0..a) {
for (j in 0..b) {
val value = x.toDouble().pow(i.toDouble()).toInt() + y.toDouble().pow(j.toDouble())
.toInt()
if (value <= bound) {
powerfulIntegers.add(value)
}
// No point in considering other powers of "1".
if (y == 1) {
break
}
}
if (x == 1) {
break
}
}
return powerfulIntegers.toList()
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,847 | kotlab | Apache License 2.0 |
day3/src/main/kotlin/com/nohex/aoc/day3/SubmarineMetrics.kt | mnohe | 433,396,563 | false | {"Kotlin": 105740} | package com.nohex.aoc.day3
internal class SubmarineMetrics {
fun getPowerConsumption(diagnostics: Sequence<String>): Int {
val iterator = diagnostics.iterator()
if (!iterator.hasNext()) {
return 0
}
// Obtain the record size from the first record.
val record = iterator.next()
val recordSize = record.length
// Set up counters that tally the occurrences of each character
// in each of the positions of the record.
val counter = CharCounter(recordSize)
// Parse the first record.
counter.parse(record)
// Parse the rest of the records.
while (iterator.hasNext()) {
counter.parse(iterator.next())
}
// Add a 0 in front of the counter to avoid the 2's complement nature
// of inv() from miscalculating the epsilon rate.
val mostCommonCharacters = "0" + counter.getMostCommonCharacters()
// Convert binary to integer.
val gammaRate = mostCommonCharacters.toInt(2)
val epsilonRate = (1 shl recordSize) + gammaRate.inv()
return gammaRate * epsilonRate
}
fun getLifeSupportRating(diagnostics: Sequence<String>): Int {
val iterator = diagnostics.iterator()
if (!iterator.hasNext()) {
return 0
}
// Set up the initial run.
var position = 0
val counts = getCounts(iterator, position)
val top = counts.maxByOrNull { it.value.size }!!.value
val bottom = counts.minByOrNull { it.value.size }!!.value
// Increase the position.
position++
// Reduce most used.
val oxygenGeneratorRating =
reduce(top, position, '1') { c -> c.maxByOrNull { it.value.size }!!.value }
// Reduce least used.
val co2ScrubberRating =
reduce(bottom, position, '0') { c -> c.minByOrNull { it.value.size }!!.value }
return oxygenGeneratorRating * co2ScrubberRating
}
private fun getCounts(
recordIterator: Iterator<String>,
position: Int
): Map<Char, List<String>> {
val counts = mutableMapOf<Char, MutableList<String>>()
while (recordIterator.hasNext()) {
// Classify the records according to the character
// in the specified position.
val record = recordIterator.next()
val value = record[position]
if (!counts.containsKey(value))
counts[value] = mutableListOf()
counts[value]!! += record
}
return counts
}
private fun reduce(
records: List<String>,
position: Int,
tieBreaker: Char,
listSupplier: (Map<Char, List<String>>) -> List<String>
): Int {
if (records.size == 1)
return records[0].toInt(2)
val counts = getCounts(records.iterator(), position)
// Favour the highest character
val next = if (allSameSize(counts)) counts[tieBreaker]!! else listSupplier.invoke(counts)
return reduce(next, position + 1, tieBreaker, listSupplier)
}
private fun allSameSize(counts: Map<Char, List<String>>): Boolean {
return counts.values.map { a -> a.size }.distinct().size == 1
}
}
| 0 | Kotlin | 0 | 0 | 4d7363c00252b5668c7e3002bb5d75145af91c23 | 3,272 | advent_of_code_2021 | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/MaximalRectangle.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 java.util.Stack
/**
* Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.
*/
fun Array<CharArray>.maximalRectangle(): Int {
if (isEmpty()) return 0
val row = size
val col = this[0].size
val heights = IntArray(col)
for (i in 0 until col) {
if (this[0][i] == '1') {
heights[i] = 1
}
}
var maxSquare = -1
for (i in 1 until row) {
maxSquare = kotlin.math.max(maxSquare, heights.maxArea())
for (j in 0 until col) {
if (this[i][j] == '1') {
heights[j] = heights[j] + 1
} else {
heights[j] = 0
}
}
}
maxSquare = kotlin.math.max(maxSquare, heights.maxArea())
return maxSquare
}
private fun IntArray.maxArea(): Int {
var max = -1
val stack = Stack<Int>()
val len = this.size
var i = 0
while (i < len) {
if (stack.isEmpty() || this[i] >= this[stack.peek()]) {
stack.push(i++)
} else {
val top = stack.pop()
val currentArea = this[top] * if (stack.isEmpty()) i else i - stack.peek() - 1
max = kotlin.math.max(max, currentArea)
}
}
while (stack.isNotEmpty()) {
val top = stack.pop()
val current = this[top] * if (stack.isEmpty()) i else i - stack.peek() - 1
max = kotlin.math.max(max, current)
}
return max
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,120 | kotlab | Apache License 2.0 |
src/main/kotlin/pub/edholm/aoc2017/day4/Passphrases.kt | Edholm | 112,762,269 | false | null | package pub.edholm.aoc2017.day4
import pub.edholm.aoc2017.utils.getInputForDay
fun main(args: Array<String>) {
val formattedInput = formatInput(getInputForDay(4))
val passphrases = Passphrases()
println("Day 4:")
println(" Part I: ${passphrases.countValid(formattedInput)}")
println(" Part II: ${passphrases.countValidWithoutAnagrams(formattedInput)}")
}
private fun formatInput(inputForDay: String): List<List<String>> {
return inputForDay.split("\n")
.map { it.split(" ") }
}
fun String.isAnagramOf(other: String): Boolean {
if (this.length != other.length) {
return false
}
return this.toList().sorted() == other.toList().sorted()
}
class Passphrases {
fun countValid(formattedInput: List<List<String>>): Int {
return formattedInput.filter { isValid(it) }.size
}
fun countValidWithoutAnagrams(allPhrases: List<List<String>>): Int {
return allPhrases.filter { isValid(it) && !containsAnagrams(it) }.size
}
fun containsAnagrams(phrase: List<String>): Boolean {
phrase.forEachIndexed { index, value ->
phrase.subList(index + 1, phrase.size).forEach { other ->
if (value.isAnagramOf(other)) {
return true
}
}
}
return false
}
fun isValid(phrase: List<String>) = phrase.distinct().size == phrase.size
} | 0 | Kotlin | 0 | 3 | 1a087fa3dff79f7da293852a59b9a3daec38a6fb | 1,311 | aoc2017 | The Unlicense |
src/main/kotlin/dev/shtanko/algorithms/leetcode/CatAndMouse.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2021 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import java.util.LinkedList
import java.util.Queue
/**
* 913. Cat and Mouse
* @see <a href="https://leetcode.com/problems/cat-and-mouse/">Source</a>
*/
fun interface CatAndMouse {
fun catMouseGame(graph: Array<IntArray>): Int
}
class CatAndMouseMinimax : CatAndMouse {
override fun catMouseGame(graph: Array<IntArray>): Int {
val n: Int = graph.size
val status = Array(SIZE) { Array(SIZE) { IntArray(CHUNK_SIZE) } }
val childrenNum = Array(SIZE) { Array(SIZE) { IntArray(CHUNK_SIZE) } }
// mouse location
for (m in 0 until n) {
// cat location
for (c in 0 until n) {
childrenNum[m][c][MOUSE_TURN] = graph[m].size
childrenNum[m][c][CAT_TURN] = graph[c].size
for (x in graph[c]) {
// The cat can not stay at the hole (position 0).
if (x == 0) {
childrenNum[m][c][CAT_TURN]--
break
}
}
}
}
// enqueued : all nodes that we know who wins in the end. Nodes with DRAW status is not in this queue.
val queue = enqueuedAllNodes(n, status)
// percolate nodes that we know who wins in the end
while (queue.isNotEmpty()) {
val node: IntArray = queue.remove()
val m = node[0]
val c = node[1]
val t = node[2]
val s = node[3] // mouse_location, cat_location, turn, status
// for every parent of this node (m, c, t) :
for (parent in parents(graph, m, c, t)) {
val m2 = parent[0]
val c2 = parent[1]
val t2 = parent[2] // mouse_location2, cat_location2, turn2
// if we do not know who wins in this parent node
if (status[m2][c2][t2] == DRAW) {
if (t2 == MOUSE_TURN && s == MOUSE_WIN || t2 == CAT_TURN && s == CAT_WIN) {
// if the parent can make a winning move (mouse to MOUSE_WIN, or cat to CAT_WIN)
status[m2][c2][t2] = s
queue.add(intArrayOf(m2, c2, t2, s))
} else {
// else, this parent has neutral children_num[parent]--.
// Enqueue if all children of this parent are colored as losing moves.
childrenNum[m2][c2][t2]--
if (childrenNum[m2][c2][t2] == 0) {
status[m2][c2][t2] = if (t2 == MOUSE_TURN) CAT_WIN else MOUSE_WIN
queue.add(intArrayOf(m2, c2, t2, status[m2][c2][t2]))
}
}
}
}
}
return status[1][2][MOUSE_TURN] // The mouse is at location 1. The cat is at location 2. The mouse moves first.
}
private fun enqueuedAllNodes(n: Int, status: Array<Array<IntArray>>): Queue<IntArray> {
// enqueued : all nodes that we know who wins in the end. Nodes with DRAW status is not in this queue.
val queue: Queue<IntArray> = LinkedList()
for (i in 0 until n) {
// turn
for (t in 1..2) {
status[0][i][t] = MOUSE_WIN // The mouse wins if it is at the hole (position 0).
queue.add(intArrayOf(0, i, t, MOUSE_WIN))
if (i > 0) {
status[i][i][t] = CAT_WIN // The cat wins if mouse and cat are at the same location.
queue.add(intArrayOf(i, i, t, CAT_WIN))
}
}
}
return queue
}
// What nodes could play their turn to arrive at node (m, c, t) ?
private fun parents(graph: Array<IntArray>, m: Int, c: Int, t: Int): List<IntArray> {
val ans: MutableList<IntArray> = ArrayList()
if (t == CAT_TURN) {
for (m2 in graph[m]) {
ans.add(intArrayOf(m2, c, MOUSE_TURN))
}
} else {
for (c2 in graph[c]) {
// The cat can not stay at the hole (position 0).
if (c2 > 0) {
ans.add(intArrayOf(m, c2, CAT_TURN))
}
}
}
return ans
}
companion object {
private const val SIZE = 50
private const val CHUNK_SIZE = 3
private const val DRAW = 0
private const val MOUSE_WIN = 1
private const val CAT_WIN = 2
private const val MOUSE_TURN = 1
private const val CAT_TURN = 2
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 5,228 | kotlab | Apache License 2.0 |
Kotlin/problems/0015_koko_eating_bananas.kt | oxone-999 | 243,366,951 | true | {"C++": 961697, "Kotlin": 99948, "Java": 17927, "Python": 9476, "Shell": 999, "Makefile": 187} | //Problem Statement
// Koko loves to eat bananas.
// There are N piles of bananas, the i-th pile has piles[i] bananas.
// The guards have gone and will come back in H hours.
//
// Koko can decide her bananas-per-hour eating speed of K.
// Each hour, she chooses some pile of bananas, and eats K bananas from that pile.
// If the pile has less than K bananas, she eats all of them instead, and won't
// eat any more bananas during this hour.
//
// Koko likes to eat slowly, but still wants to finish eating all the bananas before
// the guards come back.
//
// Return the minimum integer K such that she can eat all the bananas within H hours.
class Solution {
private fun hoursToEat(piles:IntArray, eatSpeed:Int): Int{
var hours:Int = 0;
for(pile in piles){
hours+=pile/eatSpeed;
if(pile%eatSpeed>0){
hours++;
}
}
return hours;
}
fun minEatingSpeed(piles: IntArray, H: Int): Int {
var minBananas:Int = 1;
var maxBananas:Int = 0;
for(pile in piles){
maxBananas = maxOf(maxBananas,pile);
}
while(minBananas<maxBananas){
var midBananas:Int = minBananas+(maxBananas-minBananas)/2;
if(hoursToEat(piles,midBananas)<=H){
maxBananas = midBananas;
}else{
minBananas = midBananas + 1;
}
}
return minBananas;
}
}
fun main(args:Array<String>){
var piles:IntArray = intArrayOf(30,11,23,4,20);
var H:Int = 6;
var sol:Solution = Solution();
println(sol.minEatingSpeed(piles,H));
}
| 0 | null | 0 | 0 | 52dc527111e7422923a0e25684d8f4837e81a09b | 1,633 | algorithms | MIT License |
src/Day11.kt | mandoway | 573,027,658 | false | {"Kotlin": 22353} | import kotlin.properties.Delegates
class Monkey(specification: List<String>) {
private lateinit var items: MutableList<Int>
private lateinit var operation: (old: Int) -> Int
private var divisibleBy by Delegates.notNull<Int>()
private var idIfTestIsTrue by Delegates.notNull<Int>()
private var idIfTestIsFalse by Delegates.notNull<Int>()
var inspections = 0
init {
specification.forEach {
when {
it.startsWith("Monkey") -> {
/* noop */
}
"Starting items" in it -> {
items = mutableListOf(
*it.substringAfterLast(":")
.trim()
.split(", ")
.map { el -> el.toInt() }
.toTypedArray()
)
}
"Operation" in it -> {
val operation = it.substringAfterLast("= ")
val (_, operator, parameter) = operation.split(" ")
val operatorFunction: Int.(Int) -> Int = when (operator) {
"+" -> Int::plus
"*" -> Int::times
else -> error("unsupported operator $operator")
}
val isParameterANumber = parameter.toIntOrNull() != null
this.operation = { old ->
if (isParameterANumber) {
old.operatorFunction(parameter.toInt())
} else {
old.operatorFunction(old)
}
}
}
"Test" in it -> divisibleBy = it.substringAfterLast(" ").toInt()
"If true" in it -> idIfTestIsTrue = it.substringAfterLast(" ").toInt()
"If false" in it -> idIfTestIsFalse = it.substringAfterLast(" ").toInt()
}
}
}
fun inspectItems(otherMonkeys: List<Monkey>) {
items.forEach {
val worryLevel = operation(it) / 3
val destinationMonkeyId = if (worryLevel % divisibleBy == 0) {
idIfTestIsTrue
} else {
idIfTestIsFalse
}
otherMonkeys[destinationMonkeyId].items.add(worryLevel)
inspections++
}
items.clear()
}
}
fun evaluateMonkeyBusiness(input: List<String>): Int {
val monkeys = input.chunked(7).map { Monkey(it) }
repeat(20) {
monkeys.forEach { monkey ->
monkey.inspectItems(monkeys)
}
}
return monkeys
.map { it.inspections }
.sortedDescending()
.take(2)
.reduce(Int::times)
}
fun main() {
fun part1(input: List<String>): Int {
return evaluateMonkeyBusiness(input)
}
fun part2(input: List<String>): Int {
return input.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day11_test")
check(part1(testInput) == 10605)
val input = readInput("Day11")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 0393a4a25ae4bbdb3a2e968e2b1a13795a31bfe2 | 3,221 | advent-of-code-22 | Apache License 2.0 |
src/main/kotlin/me/grison/aoc/y2020/Day16.kt | agrison | 315,292,447 | false | {"Kotlin": 267552} | package me.grison.aoc.y2020
import arrow.core.extensions.list.foldable.exists
import me.grison.aoc.*
import java.lang.System.lineSeparator
class Day16 : Day(16, 2020) {
override fun title() = "Ticket Translation"
override fun partOne(): Int {
val validRanges = flattenedValidRanges()
return nearbyTickets().map { it.allInts() }.flatten()
.filter { !validRanges.exists { v -> v.contains(it) } }.sum()
}
override fun partTwo(): Long {
val flattenedValidRanges = flattenedValidRanges()
val validRanges = validRanges()
val nearby = nearbyTickets()
// find all invalid lines
val invalidTickets = nearby.mapIndexed { i, ticket ->
if (ticket.allInts().exists { it !in flattenedValidRanges.flatten() }) i else null
}.filterNotNull()
// find all lines
val validTickets = mutableMapOf<Int, Set<Int>>().withDefault { mutableSetOf() }
nearby.mapIndexed { i, ticket -> p(i, ticket) }
.filter { it.first !in invalidTickets } // keep valid
.forEach {
// for each int in this nearby ticket
it.second.allInts().forEachIndexed { i, int ->
validRanges.forEachIndexed { j, v ->
// if none of the 2 ranges matches
if (!v[0].contains(int) && !v[1].contains(int)) {
validTickets[i] = validTickets.getValue(i) + j
}
}
}
}
// keep track of all the scanning errors
val scanningErrors = mutableMapOf<Int, Int>()
// these are the spec we need to find each int is what
val rangesToFind = validRanges.indices.toMutableList()
// while there are some valid tickets to find which int is what
while (validTickets.isNotEmpty()) {
// strategy is to get the largest int
val largestInvalidTicket = validTickets.entries.maxByOrNull { it.value.size }!!
// and try to find the first range from the spec where the largest int is valid
val validInt = rangesToFind.first { it !in largestInvalidTicket.value }
// we don't need to find that class of range anymore
rangesToFind.remove(validInt)
// nor do we need to find something for this ticket
validTickets.remove(largestInvalidTicket.key)
scanningErrors[largestInvalidTicket.key] = validInt
}
return myTickets()
// "departure" are specified in the first 6 lines in my input
.filterIndexed { index, _ -> scanningErrors[index] in 0..5 }
.multiply()
}
private fun flattenedValidRanges(): List<IntRange> {
return validRanges().flatten()
}
private fun validRanges(): MutableList<List<IntRange>> {
val (spec, _, _) = inputString.split(lineSeparator() * 2)
return mutableListOf<List<IntRange>>().let {
spec.split(lineSeparator()).forEach { line ->
val ints = line.allInts(includeNegative = false)
it.add(listOf(IntRange(ints[0], ints[1]), IntRange(ints[2], ints[3])))
}
it
}
}
private fun nearbyTickets(): List<String> {
val (_, _, _nearby) = inputGroups
return _nearby.lines().tail()
}
private fun myTickets(): List<Long> {
val (_, my, _) = inputGroups
return my.lines().last().allLongs()
}
} | 0 | Kotlin | 3 | 18 | ea6899817458f7ee76d4ba24d36d33f8b58ce9e8 | 3,599 | advent-of-code | Creative Commons Zero v1.0 Universal |
src/main/kotlin/tools/graph/FloydWarshall.kt | wrabot | 739,807,905 | false | {"Kotlin": 19706} | package tools.graph
class FloydWarshall(size: Int, weights: Map<Pair<Int, Int>, Double>) {
val indices = 0 until size
val dist = Array(size) { DoubleArray(size) { Double.POSITIVE_INFINITY } }
val prev = Array(size) { Array<Int?>(size) { null } }
override fun toString() = dist.toList().map { it.toList() }.toString()
init {
weights.forEach { (u, v), w ->
dist[u][v] = w
prev[u][v] = u
}
for (v in indices) {
dist[v][v] = 0.0
prev[v][v] = v
}
for (k in indices)
for (i in indices)
for (j in indices) {
val d = dist[i][k] + dist[k][j]
if (dist[i][j] > d) {
dist[i][j] = d
prev[i][j] = prev[k][j]
}
}
}
fun path(u: Int, v: Int) = path(u, v, emptyList())
private tailrec fun path(u: Int, v: Int?, path: List<Int>): List<Int> = when {
v == null -> emptyList()
u == v -> path
else -> path(u, prev[u][v], listOf(v) + path)
}
}
| 0 | Kotlin | 0 | 0 | fd2da26c0259349fbc9719e694d58549e7f040a0 | 1,125 | competitive-tools | Apache License 2.0 |
src/Day06.kt | melo0187 | 576,962,981 | false | {"Kotlin": 15984} | fun main() {
fun String.charsToProcessUntilFirstMarkerDetected(markerSize: Int): Int =
toCharArray()
.toList()
.windowed(markerSize)
.indexOfFirst { markerSizedCharSequence ->
markerSizedCharSequence.distinct().size == markerSize
} + markerSize
fun part1(input: List<String>): List<Int> =
input.map { datastreamBuffer -> datastreamBuffer.charsToProcessUntilFirstMarkerDetected(4) }
fun part2(input: List<String>): List<Int> =
input.map { datastreamBuffer -> datastreamBuffer.charsToProcessUntilFirstMarkerDetected(14) }
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day06_test")
check(part1(testInput) == listOf(7, 5, 6, 10, 11))
check(part2(testInput) == listOf(19, 23, 23, 29, 26))
val input = readInput("Day06")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | 97d47b84e5a2f97304a078c3ab76bea6672691c5 | 945 | kotlin-aoc-2022 | Apache License 2.0 |
src/main/kotlin/com/leetcode/P79.kt | antop-dev | 229,558,170 | false | {"Kotlin": 695315, "Java": 213000} | package com.leetcode
// https://github.com/antop-dev/algorithm/issues/316
class P79 {
fun exist(board: Array<CharArray>, word: String): Boolean {
for (i in board.indices) {
for (j in board[i].indices) {
if (dfs(board, i, j, word, 0)) {
return true
}
}
}
return false
}
private fun dfs(board: Array<CharArray>, i: Int, j: Int, word: String, k: Int): Boolean {
if (k == word.length) return true
// 행의 인덱스가 벗어난 경우
if (i !in board.indices) return false
// 열의 인덱스가 벗어난 경우
if (j !in board[0].indices) return false
// 단어가 틀린 경우
if (board[i][j] != word[k]) return false
// 방문 체크
board[i][j] = ' '
return if (dfs(board, i - 1, j, word, k + 1) // ↑
|| dfs(board, i + 1, j, word, k + 1) // ↓
|| dfs(board, i, j - 1, word, k + 1) // ←
|| dfs(board, i, j + 1, word, k + 1) // →
) {
true
} else {
// 지나갔던 경로들이 답이 아니었다면 다시 복구한다.
board[i][j] = word[k]
false
}
}
}
| 1 | Kotlin | 0 | 0 | 9a3e762af93b078a2abd0d97543123a06e327164 | 1,272 | algorithm | MIT License |
kotlin/rail-fence-cipher/src/main/kotlin/RailFenceCipher.kt | fredyw | 523,079,058 | false | null | class RailFenceCipher(private val n: Int) {
fun getEncryptedData(input: String): String {
val matrix = Array(n) { Array(input.length) { '.' } }
val zigZag = zigZag(n, input.length)
input.toList().zip(zigZag).forEach { (char, rowCol) ->
val (row, col) = rowCol
matrix[row][col] = char
}
return matrix.flatMap { list -> list.filter { it != '.' } }.joinToString("")
}
fun getDecryptedData(input: String): String {
val matrix = Array(n) { Array(input.length) { '.' } }
val zigZag = zigZag(n, input.length)
input.toList().zip(zigZag.groupBy { (row, _) -> row }.entries.sortedBy { it.key }
.flatMap { it.value })
.forEach { (char, rowCol) ->
val (row, col) = rowCol
matrix[row][col] = char
}
return zigZag.map { (row, col) -> matrix[row][col] }.joinToString("")
}
data class ZigZag(val row: Int, val col: Int, val down: Boolean)
private fun zigZag(maxRows: Int, maxCols: Int): List<Pair<Int, Int>> {
return generateSequence(ZigZag(0, 0, true)) {
if (it.down) {
if (it.row < maxRows - 1) {
ZigZag(it.row + 1, it.col + 1, true)
} else {
ZigZag(it.row - 1, it.col + 1, false)
}
} else {
if (it.row - 1 >= 0) {
ZigZag(it.row - 1, it.col + 1, false)
} else {
ZigZag(it.row + 1, it.col + 1, true)
}
}
}.takeWhile { it.col < maxCols }
.map { Pair(it.row, it.col) }
.toList()
}
}
| 0 | Kotlin | 0 | 0 | 101a0c849678ebb7d2e15b896cfd9e5d82c56275 | 1,714 | exercism | MIT License |
src/Day01.kt | olezhabobrov | 572,687,414 | false | {"Kotlin": 27363} | fun main() {
fun part1(input: List<String>): Int {
var result = 0
var current = 0
input.map {
if (it.isEmpty())
null
else
it.toInt()
}.forEach {
if (it == null) {
result = maxOf(result, current)
current = 0
} else {
current += it
}
}
return result
}
fun part2(input: List<String>): Int {
val result = mutableListOf<Int>()
var current = 0
input.map {
if (it.isEmpty())
null
else
it.toInt()
}.forEach {
if (it == null) {
result.add(current)
current = 0
} else {
current += it
}
}
result.sortDescending()
return result[0] + result[1] + result[2]
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 31f2419230c42f72137c6cd2c9a627492313d8fb | 1,191 | AdventOfCode | Apache License 2.0 |
src/Day10.kt | weberchu | 573,107,187 | false | {"Kotlin": 91366} | private fun part1(input: List<String>): Int {
var x = 1
var currentCycle = 0
val measureCycle = ArrayDeque(listOf(20, 60, 100, 140, 180, 220))
var signalStrength = 0
for (line in input) {
val instruction = line.split(" ")
when (instruction[0]) {
"noop" -> currentCycle++
"addx" -> currentCycle += 2
else -> throw IllegalArgumentException("Unknown instruction $line")
}
if (currentCycle >= measureCycle.first()) {
signalStrength += measureCycle.first() * x
measureCycle.removeFirst()
if (measureCycle.isEmpty()) {
break
}
}
if (instruction[0] == "addx") {
x += instruction[1].toInt()
}
}
return signalStrength
}
private class CRT {
var cycle = 0
var lines = mutableListOf<String>()
fun draw(spritePosition: Int) {
val row = cycle / 40
val column = cycle % 40
if (column == 0) {
lines.add("")
}
val pixel = if (column >= spritePosition - 1 && column <= spritePosition + 1) '#' else '.'
lines[row] = lines[row] + pixel
cycle++
}
fun print() {
for (line in lines) {
println(line)
}
}
}
private fun part2(input: List<String>) {
var x = 1
val crt = CRT()
for (line in input) {
val instruction = line.split(" ")
when (instruction[0]) {
"noop" -> crt.draw(x)
"addx" -> {
crt.draw(x)
crt.draw(x)
}
else -> throw IllegalArgumentException("Unknown instruction $line")
}
if (instruction[0] == "addx") {
x += instruction[1].toInt()
}
}
crt.print()
}
fun main() {
val input = readInput("Day10")
// val input = readInput("Test")
println("Part 1: " + part1(input))
println("Part 2: ")
part2(input)
}
| 0 | Kotlin | 0 | 0 | 903ff33037e8dd6dd5504638a281cb4813763873 | 1,991 | advent-of-code-2022 | Apache License 2.0 |
src/Day06.kt | Tiebe | 579,377,778 | false | {"Kotlin": 17146} | fun main() {
fun part1(input: String): Int {
input.forEachIndexed { index, _ ->
if (index > 3) {
val letterList = listOf(input[index-3], input[index-2], input[index-1], input[index])
if (letterList.groupingBy { it }.eachCount().filter { it.value > 1 }.isEmpty()) return index + 1
}
}
return 0
}
fun part2(input: String): Int {
input.forEachIndexed { index, _ ->
if (index > 13) {
val letterList = mutableListOf<Char>()
repeat(14) {
letterList.add(input[index-it-1])
}
if (letterList.groupingBy { it }.eachCount().filter { it.value > 1 }.isEmpty()) return index
}
}
return 0
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day06_test")[0]
check(part1(testInput) == 7)
check(part2(testInput) == 19)
val input = readInput("Day06")[0]
part1(input).println()
part2(input).println()
} | 1 | Kotlin | 0 | 0 | afe9ac46b38e45bd400e66d6afd4314f435793b3 | 1,092 | advent-of-code | Apache License 2.0 |
Kotlin/EdmundKarp.kt | lprimeroo | 41,106,663 | false | null | import java.util.*
import java.io.*
class EdmundKarp {
private val MAX_V = 40 // enough for sample graph in Figure 4.24/4.25/4.26
private val INF = 1000000000
// we need these global variables
private val res = arrayOfNulls<IntArray>(MAX_V) // define MAX_V appropriately
private var mf: Int = 0
private var f: Int = 0
private var s: Int = 0
private var t: Int = 0
private val p = Vector<Integer>()
private fun augment(v: Int, minEdge: Int) { // traverse the BFS spanning tree as in print_path (section 4.3)
if (v == s) {
f = minEdge
return
} // reach the source, record minEdge in a global variable `f'
else if (p.get(v) !== -1) {
augment(p.get(v), Math.min(minEdge, res[p.get(v)][v])) // recursive call
res[p.get(v)][v] -= f
res[v][p.get(v)] += f
} // alter residual capacities
}
@Throws(Exception::class)
fun main(args: Array<String>) {
val V: Int
var k: Int
var vertex: Int
var weight: Int
val sc = Scanner(System.`in`)
V = sc.nextInt()
s = sc.nextInt()
t = sc.nextInt()
for (i in 0 until V) {
res[i] = IntArray(MAX_V)
k = sc.nextInt()
for (j in 0 until k) {
vertex = sc.nextInt()
weight = sc.nextInt()
res[i][vertex] = weight
}
}
mf = 0
while (true) { // run O(VE^2) Edmonds Karp to solve the Max Flow problem
f = 0
// run BFS, please examine parts of the BFS code that is different than in Section 4.3
val q = LinkedList<Integer>()
val dist = Vector<Integer>()
dist.addAll(Collections.nCopies(V, INF)) // #define INF 2000000000
q.offer(s)
dist.set(s, 0)
p.clear()
p.addAll(Collections.nCopies(V, -1)) // (we have to record the BFS spanning tree)
while (!q.isEmpty()) { // (we need the shortest path from s to t!)
val u = q.poll()
if (u == t) break // immediately stop BFS if we already reach sink t
for (v in 0 until MAX_V)
// note: enumerating neighbors with AdjMatrix is `slow'
if (res[u][v] > 0 && dist.get(v) === INF) { // res[u][v] can change!
dist.set(v, dist.get(u) + 1)
q.offer(v)
p.set(v, u) // parent of vertex v is vertex u
}
}
augment(t, INF) // find the min edge weight `f' along this path, if any
if (f == 0) break // if we cannot send any more flow (`f' = 0), terminate the loop
mf += f // we can still send a flow, increase the max flow!
}
System.out.printf("%d\n", mf) // this is the max flow value of this flow graph
}
}
| 56 | C++ | 186 | 99 | 16367eb9796b6d4681c5ddf45248e2bcda72de80 | 2,970 | DSA | MIT License |
src/2021/Day16_1.kts | Ozsie | 318,802,874 | false | {"Kotlin": 99344, "Python": 1723, "Shell": 975} | import java.io.File
import kotlin.math.min
val hexMap = mapOf(
'0' to "0000",
'1' to "0001",
'2' to "0010",
'3' to "0011",
'4' to "0100",
'5' to "0101",
'6' to "0110",
'7' to "0111",
'8' to "1000",
'9' to "1001",
'A' to "1010",
'B' to "1011",
'C' to "1100",
'D' to "1101",
'E' to "1110",
'F' to "1111"
)
fun String.decode() = map { hexMap.get(it) }.joinToString("")
fun String.extract(): String {
val version = substring(0..2).toInt(2)
totalVersion += version
val type = substring(3..5).toInt(2)
print("V$version T$type: ")
return when(type) {
4 -> substring(6).extractLiteral().second
else -> substring(6).extractOperator()
}
}
fun String.extractLiteral(): Pair<Long,String> {
println("LIT> $this ")
var literal = ""
var remainder = this
for (i in 0..length-1 step 5) {
val chunk = substring(i,i+5)
println(" CHK> ${chunk[0]} ${chunk.substring(1)}")
literal = "$literal${chunk.substring(1)}"
remainder = remainder.substring(min(i+5, remainder.length-1))
if (chunk[0] == '0') break
}
println(" VAL> ${literal.toLong(2)}")
return Pair(literal.toLong(2), remainder)
}
fun String.extractOperator(): String {
val lengthType = if (first() == '0') 15 else 11
println("OPR> ${first()} ${substring(1,lengthType+1)} ${substring(lengthType+1)}")
println(" LT> $lengthType")
if (lengthType == 15) {
val subPacketLength = substring(1,lengthType+1).toInt(2)
val subPackets = substring(lengthType+1).substring(0, subPacketLength)
println(" 15> $subPacketLength $subPackets")
return subPackets.extract()
} else {
val packetCount = substring(1,lengthType+1).toInt(2)
val subPackets = substring(lengthType+1)
var remainder = subPackets
val packetLength = 11
println(" 11> $packetCount $subPackets")
print(" > ")
var packetsRead = 0
for (i in 0..subPackets.length-1 step packetLength) {
print(" ${subPackets.substring(i,i+packetLength)}")
if (++packetsRead == packetCount) break
}
println()
packetsRead = 0
for (i in 0..subPackets.length-1 step packetLength) {
subPackets.substring(i,i+packetLength).extract()
if (++packetsRead == packetCount) {
remainder = subPackets.substring(i+packetLength)
break
}
}
return remainder
}
}
println()
var totalVersion = 0
File("input/2021/day16").forEachLine { line ->
totalVersion = 0
var remainder = line.decode()
while (remainder.length > 6 && remainder.any { it == '1' }) {
println(" TOP> $remainder")
remainder = remainder.extract()
}
println(totalVersion)
}
//"0011111010010000".extract() | 0 | Kotlin | 0 | 0 | d938da57785d35fdaba62269cffc7487de67ac0a | 2,927 | adventofcode | MIT License |
src/day03/Day03_Part1.kt | m-jaekel | 570,582,194 | false | {"Kotlin": 13764} | package day03
import readInput
fun main() {
fun part1(input: List<String>): Int {
val incorrectItems = input.map {
getIncorrectItem(it)
}
return calculatePriorityScore(incorrectItems)
}
val testInput = readInput("day03/test_input")
check(part1(testInput) == 157)
val input = readInput("day03/input")
println(part1(input))
}
private fun getIncorrectItem(backpackItems: String): Char {
val items = backpackItems.chunked(backpackItems.length / 2)
val compartmentOne = items[0]
val compartmentTwo = items[1]
compartmentOne.forEach { item1 ->
compartmentTwo.forEach { item2 ->
if (item1 == item2) {
return item1
}
}
}
throw Exception("no incorrect item found!")
}
fun calculatePriorityScore(incorrectItems: List<Char>): Int {
// https://www.cs.cmu.edu/~pattis/15-1XX/common/handouts/ascii.html
val score = incorrectItems.map { item ->
when (item.code) {
// score 27 - 52 for upper case
in 65..90 -> item.code - 38
// score 1 - 26 for lower case
in 97..122 -> item.code - 96
else -> throw Exception("unusual item found")
}
}
return score.sumOf { it }
} | 0 | Kotlin | 0 | 1 | 07e015c2680b5623a16121e5314017ddcb40c06c | 1,287 | AOC-2022 | Apache License 2.0 |
2020/kotlin/src/main/kotlin/io/franmosteiro/aoc2020/Day09.kt | franmosteiro | 433,734,642 | false | {"Kotlin": 27170, "Ruby": 16611, "Shell": 389} | package io.franmosteiro.aoc2020
/**
* Advent of Code 2020 - Day 9: Encoding Error -
* Problem Description: http://adventofcode.com/2020/day/9
*/
class Day09(input: List<String>) {
private val seriesOfNumbers = input.map{ it.toLong() }
private var invalidNumber = -1
private val requiredSum: Long = 1398413738
fun resolvePartOne(preambleBatchSize: Int = 5): Int =
seriesOfNumbers.windowed(preambleBatchSize + 1, 1)
.first { !it.isValid() }
.last()
.also { invalidNumber = it.toInt() }.toInt()
fun resolvePartTwo(): Int {
val slice = contiguousRangeSlice(seriesOfNumbers)
return (slice.minOrNull()!! + slice.maxOrNull()!!).toInt()
}
private fun List<Long>.isValid(): Boolean =
any { itNumber -> ((last() - itNumber) in this) && (last() != itNumber) && ((last() - itNumber) != itNumber) }
private fun contiguousRangeSlice(seriesOfNumbers: List<Long>): List<Long> {
var acc = 0L
var first = 0
var second = 0
while( second < seriesOfNumbers.size) {
if(acc == requiredSum) {
return seriesOfNumbers.slice(first..second)
}
if(acc > requiredSum) {
acc -= seriesOfNumbers[first++]
continue
}
acc += seriesOfNumbers[second++]
}
error("No slice equal to $requiredSum")
}
}
| 0 | Kotlin | 0 | 0 | dad555d9cd0c3060c4b1353c7c6f170aa340c285 | 1,451 | advent-of-code | MIT License |
src/main/kotlin/leetcode/uber/NumberofIslandsII.kt | Magdi | 390,731,717 | false | null | package leetcode.uber
class NumberofIslandsII {
private val di = listOf(1, -1, 0, 0)
private val dj = listOf(0, 0, -1, 1)
// o ( k * lon ( n*m ) )
fun numIslands2(m: Int, n: Int, positions: Array<IntArray>): List<Int> {
val unionFind = UnionFind()
val grid = MutableList(m) { MutableList(n) { 0 } }
val result = mutableListOf<Int>()
positions.forEach { (row, col) ->
if (grid[row][col] != 1) {
val ind = getIndex(row, col, n)
grid[row][col] = 1
unionFind.addTree(ind)
for (d in 0 until 4) {
val nRow = row + di[d]
val nCol = col + dj[d]
if (nRow >= 0 && nCol >= 0 && nRow < m && nCol < n && grid[nRow][nCol] == 1) {
unionFind.union(ind, getIndex(nRow, nCol, n))
}
}
}
result.add(unionFind.forests)
}
return result
}
private fun getIndex(row: Int, col: Int, m: Int): Int {
return row * m + col
}
private class UnionFind {
val rank = hashMapOf<Int, Int>()
val parent = hashMapOf<Int, Int>()
var forests = 0
fun addTree(node: Int) {
rank[node] = 1
parent[node] = node
forests++
}
fun find(node: Int): Int {
if (node == parent[node]) return node
return find(parent[node]!!).also { parent[node] = it }
}
fun link(node1: Int, node2: Int) {
var x = node1
var y = node2
if (rank[x]!! > rank[y]!!) x = y.also { y = x } // swap
parent[x] = y
if (rank[x] == rank[y]) rank[y] = rank.getOrDefault(y, 1) + 1
}
fun union(node1: Int, node2: Int) {
val p1 = find(node1)
val p2 = find(node2)
if (p1 != p2) {
link(p1, p2)
forests--
}
}
}
}
| 0 | Kotlin | 0 | 0 | 63bc711dc8756735f210a71454144dd033e8927d | 2,031 | ProblemSolving | Apache License 2.0 |
src/main/kotlin/com/ginsberg/advent2020/Day12.kt | tginsberg | 315,060,137 | false | null | /*
* Copyright (c) 2020 by <NAME>
*/
/**
* Advent of Code 2020, Day 12 - Rain Risk
* Problem Description: http://adventofcode.com/2020/day/12
* Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2020/day12/
*/
package com.ginsberg.advent2020
class Day12(private val input: List<String>) {
fun solvePart1(): Int =
input.fold(Ship(Point2D.ORIGIN, Direction.East)) { ship, instruction ->
val command = instruction.first()
val amount = instruction.substring(1).toInt()
when (command) {
'N' -> ship.move(Direction.North, amount)
'S' -> ship.move(Direction.South, amount)
'E' -> ship.move(Direction.East, amount)
'W' -> ship.move(Direction.West, amount)
'F' -> ship.forward(amount)
'L' -> ship.turnLeft(amount / 90)
'R' -> ship.turnRight(amount / 90)
else -> throw IllegalArgumentException("Unknown instruction: $instruction")
}
}.at distanceTo Point2D.ORIGIN
fun solvePart2(): Int {
var waypoint = Waypoint()
var ship = Ship()
input.forEach { instruction ->
val command = instruction.first()
val amount = instruction.substring(1).toInt()
when (command) {
'N' -> waypoint = waypoint.move(Direction.North, amount)
'S' -> waypoint = waypoint.move(Direction.South, amount)
'E' -> waypoint = waypoint.move(Direction.East, amount)
'W' -> waypoint = waypoint.move(Direction.West, amount)
'F' -> ship = ship.copy(at = ship.at + (waypoint.at * amount))
'L' -> waypoint = waypoint.turnLeft(amount / 90)
'R' -> waypoint = waypoint.turnRight(amount / 90)
else -> throw IllegalArgumentException("Unknown instruction: $instruction")
}
}
return Point2D.ORIGIN distanceTo ship.at
}
data class Waypoint(val at: Point2D = Point2D(-1, 10)) {
fun move(dir: Direction, amount: Int): Waypoint =
Waypoint(at + (dir.offset * amount))
fun turnLeft(amount: Int): Waypoint =
(0 until amount).fold(this) { carry, _ ->
Waypoint(carry.at.rotateLeft())
}
fun turnRight(amount: Int): Waypoint =
(0 until amount).fold(this) { carry, _ ->
Waypoint(carry.at.rotateRight())
}
}
data class Ship(val at: Point2D = Point2D.ORIGIN, val facing: Direction = Direction.East) {
fun forward(amount: Int): Ship =
copy(at = at + (facing.offset * amount))
fun move(dir: Direction, amount: Int): Ship =
copy(at = at + (dir.offset * amount))
fun turnLeft(times: Int): Ship =
(0 until times).fold(this) { carry, _ ->
carry.copy(facing = carry.facing.turnLeft)
}
fun turnRight(times: Int): Ship =
(0 until times).fold(this) { carry, _ ->
carry.copy(facing = carry.facing.turnRight)
}
}
} | 0 | Kotlin | 2 | 38 | 75766e961f3c18c5e392b4c32bc9a935c3e6862b | 3,161 | advent-2020-kotlin | Apache License 2.0 |
src/Day07.kt | paulbonugli | 574,065,510 | false | {"Kotlin": 13681} | fun main() {
val inputLines = readInput("Day07")
val root = ElfDir("/")
// keep track of where we are with traversal
val traversalPath = ArrayDeque<ElfDir>()
inputLines.forEach { line ->
if(line.startsWith("$")) {
if(line != "$ ls") {
val (name) = "\\$ cd (/|[a-z]+|..)?".toRegex().matchEntire(line)?.destructured
?: throw IllegalStateException("unparseable command: $line")
when (name) {
"/" -> traversalPath.run { clear(); add(root) }
".." -> traversalPath.removeLast()
else -> traversalPath.add(
traversalPath.last().getChildDir(name)
?: throw IllegalStateException("navigating to directory $name which doesn't exist ($line)")
)
}
}
} else {
val (start, name) = "(dir|[0-9]+) ([a-z.]+)".toRegex().matchEntire(line)?.destructured ?: throw IllegalStateException("Unparseable listing: $line")
val newItem = if(start == "dir") ElfDir(name) else ElfFile(name, start.toInt())
traversalPath.last().add(newItem)
}
}
println("Inferred filesystem contents:")
println(root)
println()
val nestedDirs = getNestedDirs(root)
println("""Part 1: ${nestedDirs.map(ElfDir::size).filter { it <= 100000 }.sum()}""")
val freeSpace = 70000000 - root.size()
val needToFree = 30000000 - freeSpace
println("""Part 2: ${nestedDirs.map(ElfDir::size).filter { it >= needToFree }.minOf { it }}""")
}
fun getNestedDirs(vararg startDir : ElfDir) : List<ElfDir>{
return startDir.flatMap {
val childDirs = it.getChildDirs()
childDirs + getNestedDirs(*childDirs.toTypedArray())
}
}
sealed class ElfFileSystemObject(val name : String) {
abstract fun size() : Int
}
class ElfFile(name : String, private val size : Int) : ElfFileSystemObject(name) {
override fun size() : Int{
return this.size
}
override fun toString(): String {
return "- $name (file, $size)"
}
}
class ElfDir(name : String, private val contents: MutableSet<ElfFileSystemObject> = mutableSetOf()) : ElfFileSystemObject(name) {
fun add(item : ElfFileSystemObject) {
contents.add(item)
}
fun getChildDirs(): List<ElfDir> {
return contents.filterIsInstance<ElfDir>()
}
fun getChildDir(subDirName : String): ElfDir? {
return getChildDirs().find { it.name == subDirName }
}
override fun size(): Int {
return contents.map(ElfFileSystemObject::size).sum()
}
override fun toString(): String {
return "- $name (dir)\n " + contents.flatMap { it.toString().lines() }.joinToString("\n ")
}
} | 0 | Kotlin | 0 | 0 | d2d7952c75001632da6fd95b8463a1d8e5c34880 | 2,829 | aoc-2022-kotlin | Apache License 2.0 |
src/day01/Day01.kt | TimberBro | 567,240,136 | false | {"Kotlin": 11186} | package day01
import utils.readInput
fun main() {
fun part1(input: List<String>, desiredSum: Int): Int {
val foundNumbers = HashSet<Int>()
for (number in input) {
val currentNumber = number.toInt()
val numberToFind = desiredSum - currentNumber
if (foundNumbers.contains(numberToFind)) {
return currentNumber * numberToFind
} else {
foundNumbers.add(currentNumber)
}
}
throw RuntimeException("Could not found any pair")
}
// Does not work
fun part2(input: List<String>): Int {
// this is ugly, but I don't want to change the method signature
val sortedInput = input.map { it.toInt() }.sorted().map { it.toString() }.toList()
for ((index, number) in sortedInput.withIndex()) {
try {
val part1 = part1(
sortedInput.subList(index, sortedInput.lastIndex),
2020 - number.toInt()
)
return number.toInt() * part1
} catch (e: RuntimeException) {
continue
}
}
throw RuntimeException("Could not found any pair")
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("day01/Day01_test")
check(part1(testInput, 2020) == 514579)
check(part2(testInput) == 241861950)
val input = readInput("day01/Day01")
println(part1(input, 2020))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 1959383d2f422cc565560eefb1ed4f05bb87a386 | 1,593 | aoc2020 | Apache License 2.0 |
src/day15/Code.kt | fcolasuonno | 221,697,249 | false | null | package day15
import java.io.File
fun main() {
val name = if (false) "test.txt" else "input.txt"
val dir = ::main::class.java.`package`.name
val input = File("src/$dir/$name").readLines()
val parsed = parse(input)
println("Part 1 = ${part1(parsed)}")
println("Part 2 = ${part2(parsed)}")
}
data class Disc(val delay: Int, val positions: Int, var currentPos: Int) {
fun positionAt(time: Long) = ((time + delay + currentPos) % positions).toInt()
}
private val lineStructure = """Disc #(\d+) has (\d+) positions; at time=0, it is at position (\d+).""".toRegex()
fun parse(input: List<String>) = input.map {
lineStructure.matchEntire(it)?.destructured?.let {
val (disc, positions, currentPos) = it.toList()
Disc(disc.toInt(), positions.toInt(), currentPos.toInt())
}
}.requireNoNulls()
fun part1(input: List<Disc>): Any? = generateSequence(0L) { it + 1 }.first { time -> input.all { it.positionAt(time) == 0 } }
fun part2(input: List<Disc>) = (input + Disc(input.size + 1, 11, 0)).let { newInput -> generateSequence(0L) { it + 1 }.first { time -> newInput.all { it.positionAt(time) == 0 } } }
| 0 | Kotlin | 0 | 0 | 73110eb4b40f474e91e53a1569b9a24455984900 | 1,148 | AOC2016 | MIT License |
day06/src/main/kotlin/Main.kt | ickybodclay | 159,694,344 | false | null | import java.io.File
import java.util.*
import kotlin.math.abs
import kotlin.math.tan
data class Point(val x: Int, val y: Int)
fun main() {
val input = File(ClassLoader.getSystemResource("input.txt").file)
// Write solution here!
val points = ArrayList<Point>()
input.readLines().map { line ->
val tmpStrArray = line.split(",")
val p = Point(tmpStrArray[0].trim().toInt(), tmpStrArray[1].trim().toInt())
points.add(p)
}
// find boundary points
// plot points on grid
// figure out manhattan distance for each point of grid, which position closest to which point, if tie ignore
// figure out point with highest count, ignoring boundary points
}
fun getManhattanDistance(a: Point, b: Point) : Int {
return abs(a.x - b.x) + abs(a.y - b.y)
}
// use graham scan to find boundary points
fun getBoundaryPoints(allPoints: List<Point>) : List<Point> {
/*
let N be number of points
let points[N] be the array of points
swap points[0] with the point with the lowest y-coordinate
sort points by polar angle with points[0]
let stack = empty_stack()
push points[0] to stack
push points[1] to stack
for i = 2 to N-1:
while count stack >= 2 and ccw(next_to_top(stack), top(stack), points[i]) <= 0:
pop stack
push points[i] to stack
end
*/
val points = ArrayList(allPoints)
val lowestYPoint = points.minBy { it -> it.y }
val stack = Stack<Point>()
return emptyList()
}
fun polarAngle(origin: Point, p: Point) : Float {
return tan((p.y - origin.y).toFloat() / (p.x - origin.x).toFloat())
}
fun ccw(p1: Point, p2: Point, p3: Point) : Boolean {
return ((p2.x - p1.x) * (p3.y - p1.y) - (p2.y - p1.y) * (p3.x - p1.x)) > 0
} | 0 | Kotlin | 0 | 0 | 9a055c79d261235cec3093f19f6828997b7a5fba | 1,777 | aoc2018 | Apache License 2.0 |
2023/day04-25/src/main/kotlin/Day10.kt | CakeOrRiot | 317,423,901 | false | {"Kotlin": 62169, "Python": 56994, "C#": 20675, "Rust": 10417} | import java.io.File
import java.util.LinkedList
import java.util.Queue
class Day10 {
fun solve1() {
val grid = File("inputs/10.txt").inputStream().bufferedReader().lineSequence().map { it.toMutableList() }
.toMutableList()
var start = Pair(0, 0)
grid.forEachIndexed { i, line -> val j = line.indexOf('S'); if (j != -1) start = Pair(i, j) else null }
grid[start.first][start.second] = '|'
val dist = bfs(grid, start, ::getNeighboursShape, emptySet())
println(dist.values.max())
}
fun solve2() {
val grid = File("inputs/10.txt").inputStream().bufferedReader().lineSequence().map { it.toMutableList() }
.toMutableList()
var start = Pair(0, 0)
grid.forEachIndexed { i, line -> val j = line.indexOf('S'); if (j != -1) start = Pair(i, j) else null }
grid[start.first][start.second] = '|'
val dist = bfs(grid, start, ::getNeighboursShape, emptySet())
val loop = dist.keys.toSet()
var res = 0
for (i in 0..<grid.size) {
var pos = Position.OUTSIDE
for (j in 0..<grid[0].size) {
if (loop.contains(Pair(i, j))) {
pos = when (pos) {
Position.OUTSIDE -> when (grid[i][j]) {
'|' -> Position.INSIDE
'F' -> Position.TOP_BORDER
'L' -> Position.BOT_BORDER
else -> pos
}
Position.TOP_BORDER -> when (grid[i][j]) {
'J' -> Position.INSIDE
'7' -> Position.OUTSIDE
else -> pos
}
Position.BOT_BORDER -> when (grid[i][j]) {
'7' -> Position.INSIDE
'J' -> Position.OUTSIDE
else -> pos
}
Position.INSIDE -> when (grid[i][j]) {
'|' -> Position.OUTSIDE
'F' -> Position.BOT_BORDER
'L' -> Position.TOP_BORDER
else -> pos
}
}
} else {
if (pos == Position.INSIDE) res++
}
}
}
println(res)
}
enum class Position {
INSIDE, TOP_BORDER, BOT_BORDER, OUTSIDE
}
private fun getNeighboursShape(grid: List<List<Char>>, pos: Pair<Int, Int>): List<Pair<Int, Int>> {
val neighbours = emptyList<Pair<Int, Int>>().toMutableList()
val shape = grid[pos.first][pos.second]
when (shape) {
'|' -> {
neighbours.add(Pair(pos.first - 1, pos.second))
neighbours.add(Pair(pos.first + 1, pos.second))
}
'-' -> {
neighbours.add(Pair(pos.first, pos.second + 1))
neighbours.add(Pair(pos.first, pos.second - 1))
}
'L' -> {
neighbours.add(Pair(pos.first - 1, pos.second))
neighbours.add(Pair(pos.first, pos.second + 1))
}
'J' -> {
neighbours.add(Pair(pos.first - 1, pos.second))
neighbours.add(Pair(pos.first, pos.second - 1))
}
'7' -> {
neighbours.add(Pair(pos.first + 1, pos.second))
neighbours.add(Pair(pos.first, pos.second - 1))
}
'F' -> {
neighbours.add(Pair(pos.first + 1, pos.second))
neighbours.add(Pair(pos.first, pos.second + 1))
}
}
return neighbours.filter { it.first >= 0 && it.second >= 0 && it.first < grid.size && it.second < grid[0].size }
}
private fun bfs(
grid: List<List<Char>>,
start: Pair<Int, Int>,
getNeighbours: (List<List<Char>>, Pair<Int, Int>) -> List<Pair<Int, Int>>,
skip: Set<Pair<Int, Int>>
): MutableMap<Pair<Int, Int>, Int> {
val q: Queue<Pair<Int, Int>> = LinkedList()
q.add(start)
val dist = emptyMap<Pair<Int, Int>, Int>().toMutableMap()
dist[start] = 0
while (!q.isEmpty()) {
val cur = q.poll()
val neighbours = getNeighbours(grid, cur)
for (next in neighbours) {
if (next == start || dist.containsKey(next) || skip.contains(next)) continue
dist[next] = dist.getValue(cur) + 1
q.add(next)
}
}
return dist
}
} | 0 | Kotlin | 0 | 0 | 8fda713192b6278b69816cd413de062bb2d0e400 | 4,691 | AdventOfCode | MIT License |
_7Function/src/main/kotlin/practice/81 Letter Grade Printout.kt | Meus-Livros-Lidos | 690,208,771 | false | {"Kotlin": 166470} | package practice
/**
* Let's write a method to print a set of letter grades based on numeric scores. Create a method named printLetterGrades that accepts a DoubleArray.
* If the array is empty, don't print anything.
*
* Otherwise, for each value in the array, print a line to the console in the following format:
*
* Student 1,B,3.3
* The first value is in the format "Student N", where N is the index in the array but starting at 1.
* So the first student is "Student 1", the second "Student 2", and so on. (0-based indexing tends to confuse people who aren't computer scientists.)
*
* The second value is the student's letter grade based on the following scale:
*
* >= 4.0: A
* > 3.0 && <= 4.0: B
* > 2.0 && <= 3.0: C
* > 1.0 && <= 2.0: D
* otherwise, F
* You can assume that values in the array will be between 0.0 and 5.0, inclusive.
*
* The third value is the student's raw score.
*
* You should also print "--- GRADES START ---" at the beginning and "--- GRADES END ---" at the end, each on their own line.
*/
fun main() {
println("Letter Grade Printout")
println("Enter with the size of array:")
var sizeArray = readlnOrNull()?.toIntOrNull() ?: 1
while (!correctSizeArray7(sizeArray)) {
println("The size array must be int the range 1 .. 3")
println("Enter with the size of array again:")
sizeArray = readlnOrNull()?.toIntOrNull() ?: 1
correctSizeArray7(sizeArray)
}
val studentsGrade = DoubleArray(sizeArray)
for (i in studentsGrade.indices) {
println("Enter with the number:")
var inputNumber = readlnOrNull()?.toDoubleOrNull() ?: 0.0
if (checkNote2(inputNumber)) {
studentsGrade[i] = inputNumber
} else {
println("The number is not in range >= 0 and <= 100:")
while (!checkNote2(inputNumber)) {
inputNumber = readlnOrNull()?.toDoubleOrNull() ?: 0.0
checkNote2(inputNumber)
}
}
}
if (studentsGrade.isNotEmpty()) {
for (i in studentsGrade.indices) {
println("Student ${i + 1}, ${letterGrade(studentsGrade[i])} , ${studentsGrade[i]}")
}
}
}
fun correctSizeArray7(sizeArray: Int): Boolean {
return sizeArray > 0
}
fun checkNote2(inputNumber: Double): Boolean {
return inputNumber in 0.0..5.0
}
fun letterGrade(studentsGrade: Double): Char {
return when (studentsGrade) {
in 4.1..5.0 -> 'A'
in 3.1..4.0 -> 'B'
in 2.1..3.0 -> 'C'
in 1.1..2.0 -> 'D'
else -> 'F'
}
} | 0 | Kotlin | 0 | 1 | 2d05e5528b9dd2cf9ed8799bce47444246be6b42 | 2,575 | LearnCsOnline-Kotlin | MIT License |
src/main/kotlin/dev/bogwalk/batch6/Problem61.kt | bog-walk | 381,459,475 | false | null | package dev.bogwalk.batch6
import kotlin.math.floor
import kotlin.math.sqrt
import dev.bogwalk.util.maths.isHexagonalNumber
import dev.bogwalk.util.maths.isTriangularNumber
import dev.bogwalk.util.maths.isPentagonalNumber
/**
* Problem 61: Cyclical Figurate Numbers
*
* https://projecteuler.net/problem=61
*
* Goal: Given a set of N numbers representing a polygonal, find the sum of a set of N 4-digit
* numbers that respect the cyclical properties described below. If multiple such sets exist,
* return all their sums in sorted order.
*
* Constraints: 3 <= N <= 6, from {3,4,5,6,7,8}
*
* Cyclic Set: In this context, this means the last 2 digits of each number is the first 2 digits
* of the next number (including the last number with the first).
*
* Figurate/Polygonal numbers are generated by the formulae ->
*
* Triangle: P_3n = n(n + 1)/2 -> 1, 3, 6, 10, 15, ...
* Square: P_4n = n^2 -> 1, 4, 9, 16, 25, ...
* Pentagonal: P_5n = n(3n - 1)/2 -> 1, 5, 12, 22, 35, ...
* Hexagonal: P_6n = n(2n - 1) -> 1,6, 15, 28, 45, ...
* Heptagonal: P_7n = n(5n - 3)/2 -> 1, 7, 18, 34, 55, ...
* Octagonal: P_8n = n(3n - 2) -> 1, 8, 21, 40, 65, ...
*
* e.g. {8128, 2882, 8281} is the only cyclical set of 3 4-digit numbers to represent
* polygonal types -> {P_3-127, P_5-44, P_4-91}.
*
* e.g.: N = {3, 4, 5}
* cyclical set = {8128, 2882, 8281}
* sum = 19291
*/
class CyclicalFigurateNumbers {
/**
* Solution uses recursion to search for cyclic chains using the smallest polygonal set
* numbers as starters (e.g. there will be fewer octagonal numbers that triangle numbers to
* start chains).
*
* A separate stack of the remaining polygon numbers to find is cached so the search can
* continue if a chain that cannot close its first and last elements is reached. This is done
* by remembering the last polygon added to the chain & adding it back to the stack it was
* just popped from if the chain becomes invalid.
*
* Rather than searching for a final figurate that closes the chain, the expected number is
* checked to see if it is in the generated polygon list.
*
* @return list of all cyclic lists that represent the polygons requested.
*/
fun cyclicalFigurates(polygons: Set<Int>): List<List<Int>> {
val cycles = mutableListOf<List<Int>>()
var notFound = polygons.toMutableList()
val allPolygons = getPolygons(polygons)
fun nextCyclical(prefix: Int, lastFound: Int, chain: MutableList<Int>): MutableList<Int> {
if (notFound.size == 1) {
val expected = chain.last() % 100 * 100 + chain.first() / 100
if (expected in allPolygons[notFound.first()]) {
notFound.removeLast()
chain.add(expected)
} else {
chain.removeLast()
notFound.add(lastFound)
}
} else {
for (p in polygons) {
if (p in notFound) {
for (number in allPolygons[p]) {
if (number in chain) continue
if (prefix < number / 100) break
if (prefix == number / 100) {
chain.add(number)
notFound.remove(p)
val ans = nextCyclical(number % 100, p, chain)
if (notFound.isEmpty()) return ans
}
}
}
}
chain.removeLast()
notFound.add(lastFound)
}
return chain
}
val smallest = notFound.maxOrNull()!!
for (starter in allPolygons[smallest]) {
notFound.remove(smallest)
val cycle = nextCyclical(starter % 100, smallest, mutableListOf(starter))
if (cycle.size == polygons.size) {
cycles.add(cycle)
notFound = polygons.toMutableList()
}
}
return cycles
}
/**
* Generates all 4-digit figurate/polygonal numbers for the polygons specified.
*
* N.B. Numbers with a 0 in the 3rd position are filtered out as these will not allow the
* cyclic property to occur. e.g. 2701 (P_6_37) -> 01xx, which is not a 4-digit number.
*
* @param [polygons] set of Integers in [3, 8] representing triangle,...octagonal polygons.
* @return nested lists of all requested 4-digit figurate numbers, found at the index
* matching their polygonal value. e.g. All triangle numbers between 1000 and 9999 stored at
* index 3.
*/
private fun getPolygons(polygons: Set<Int>): List<List<Int>> {
val formulae = listOf(
Long::isTriangularNumber, ::isSquareNumber, Long::isPentagonalNumber,
Long::isHexagonalNumber, ::isHeptagonalNumber, ::isOctagonalNumber
)
val allPolygons = List(9) { p ->
if (p in polygons) {
(1010 until 10_000).filter { num ->
num.toString()[2] != '0' && formulae[p-3](num.toLong()) != null
}
} else emptyList()
}
return allPolygons
}
/**
* Returns the corresponding term of the number if square, or null.
*
* Derivation solution is based on the formula:
*
* n^2 = sN, in quadratic form becomes:
*
* 0 = n^2 + 0 - sN, with a, b, c = 1, 0, -sN
*
* putting these values in the quadratic formula becomes:
*
* n = (0 +/- sqrt(0 + 4sN))/2
*
* so the inverse function, positive solution becomes:
*
* n = sqrt(sN)
*/
private fun isSquareNumber(sN: Long): Int? {
val n = sqrt(1.0 * sN)
return if (n == floor(n)) n.toInt() else null
}
/**
* Returns the corresponding term of the number if heptagonal, or null.
*
* Derivation solution is based on the formula:
*
* n(5n - 3)/2 = hN, in quadratic form becomes:
*
* 0 = 5n^2 - 3n - 2hN, with a, b, c = 5, -3, (-2hN)
*
* putting these values in the quadratic formula becomes:
*
* n = (3 +/- sqrt(9 + 40hN))/10
*
* so the inverse function, positive solution becomes:
*
* n = 0.1 * (3 + sqrt(9 + 40hN))
*/
private fun isHeptagonalNumber(hN: Long): Int? {
val n = 0.1 * (3 + sqrt(9 + 40.0 * hN))
return if (n == floor(n)) n.toInt() else null
}
/**
* Returns the corresponding term of the number if octagonal, or null.
*
* Derivation solution is based on the formula:
*
* n(3n - 2) = oN, in quadratic form becomes:
*
* 0 = 3n^2 - 2n - oN, with a, b, c = 3, -2, -oN
*
* putting these values in the quadratic formula becomes:
*
* n = (2 +/- sqrt(4 + 12oN))/6
*
* so the inverse function, positive solution becomes:
*
* n = (1 + sqrt(1 + 3oN))/3
*/
private fun isOctagonalNumber(oN: Long): Int? {
val n = (1 + sqrt(1 + 3.0 * oN)) / 3.0
return if (n == floor(n)) n.toInt() else null
}
} | 0 | Kotlin | 0 | 0 | 62b33367e3d1e15f7ea872d151c3512f8c606ce7 | 7,332 | project-euler-kotlin | MIT License |
src/net/sheltem/aoc/y2022/Day14.kt | jtheegarten | 572,901,679 | false | {"Kotlin": 178521} | package net.sheltem.aoc.y2022
suspend fun main() {
Day14().run()
}
class Day14 : Day<Int>(24, 93) {
override suspend fun part1(input: List<String>): Int = input.toCave().countMaxSandDrops()
override suspend fun part2(input: List<String>): Int = input.toCave().addFloor().countMaxSandDrops()
}
private fun Array<CharArray>.addFloor(): Array<CharArray> = apply { this[this.size - 1] = "#".repeat(1000).toCharArray() }
private fun Array<CharArray>.countMaxSandDrops() = generateSequence { this.dropSand(500, 0) }.takeWhile { it }.count()
private tailrec fun Array<CharArray>.dropSand(right: Int, down: Int): Boolean {
return when {
this[down][right] == 'o' -> false
this.size == down + 1 -> false
this[down + 1][right] == '.' -> dropSand(right, down + 1)
this[down + 1][right - 1] == '.' -> dropSand(right - 1, down + 1)
this[down + 1][right + 1] == '.' -> dropSand(right + 1, down + 1)
else -> {
this[down][right] = 'o'
true
}
}
}
private fun List<String>.toCave(): Array<CharArray> {
val wallInstructions = this.map { it.toWallInstructions() }
return Array(wallInstructions.flatten().maxOf { it.second } + 3) { CharArray(1000) { '.' } }.apply { wallInstructions.forEach(this::addWall) }
}
private fun Array<CharArray>.addWall(instructions: List<Pair<Int, Int>>) = instructions.zipWithNext().forEach { this.drawBetween(it.first, it.second) }
private fun Array<CharArray>.drawBetween(start: Pair<Int, Int>, end: Pair<Int, Int>) {
if (start.first == end.first) {
(start.second to end.second).toRange().forEach { this[it][start.first] = '#' }
} else {
(start.first to end.first).toRange().forEach{ this[start.second][it] = '#' }
}
}
private fun Pair<Int, Int>.toRange() = if (first <= second) first..second else second..first
private fun String.toWallInstructions() = split(" -> ").map { it.split(",").let { position -> position[0].toInt() to position[1].toInt() } }
| 0 | Kotlin | 0 | 0 | ac280f156c284c23565fba5810483dd1cd8a931f | 2,012 | aoc | Apache License 2.0 |
src/aoc2022/Day12.kt | FluxCapacitor2 | 573,641,929 | false | {"Kotlin": 56956} | package aoc2022
import Day
object Day12 : Day(2022, 12) {
private const val printGrids = false // Set to true for a visualization of the final paths.
override fun part1() {
val grid = lines.map { it.split("").filter { line -> line.isNotBlank() } }.filter { it.isNotEmpty() }
val start = findGridItems(grid, 'S').single()
val distance = route(grid, start)
println("Part 1 result: $distance")
}
override fun part2() {
val grid = lines.map { it.split("").filter { line -> line.isNotBlank() } }.filter { it.isNotEmpty() }
val starts = findGridItems(grid, 'a') + findGridItems(grid, 'S').single()
val result = starts.minOf { loc ->
route(grid, loc) ?: Integer.MAX_VALUE
}
println("Part 2 result: $result")
}
private fun printGrid(grid: List<List<String>>, visited: List<Pair<Int, Int>>) {
var str = ""
grid.forEachIndexed { r, row ->
row.forEachIndexed { c, col ->
str += if (visited.any { it.first == r && it.second == c }) col
else "."
}
str += "\n"
}
println(str)
}
private data class Move(val steps: Int, val x: Int, val y: Int)
private fun route(
grid: List<List<String>>,
start: Pair<Int, Int>
): Int? {
val queue = mutableListOf<Move>()
val visited = mutableListOf<Pair<Int, Int>>()
val traceBack = mutableMapOf<Pair<Int, Int>, Pair<Int, Int>>()
queue.add(Move(0, start.first, start.second))
visited.add(start)
while (queue.isNotEmpty()) {
val (steps, row, col) = queue.first()
queue.removeFirst()
visited.add(row to col)
for (move in getSurrounding(grid, row to col, visited)) {
if (!visited.contains(move)) {
// Make sure the move is valid
val nextItem = grid[move.first][move.second][0]
val currentItem = grid[row][col][0]
if (nextItem == 'E') {
if (currentItem == 'z' || currentItem == 'y') { // 'E' is the same elevation as 'z'
if (printGrids) {
// print trace-back
var currentTrace = traceBack[row to col]
val traced = mutableListOf<Pair<Int, Int>>()
traced.add(row to col)
while (true) {
if (currentTrace != null) {
traced.add(currentTrace)
} else break
currentTrace = traceBack[currentTrace]
}
printGrid(grid, traced)
}
return steps + 1
} else continue
}
if (currentItem == 'S' && nextItem != 'a') continue
if (nextItem - currentItem > 1 && currentItem != 'S') continue
queue.add(Move(steps + 1, move.first, move.second))
visited.add(move)
traceBack[move] = row to col
}
}
}
return null // No route was found after searching every possible combination.
}
private fun getSurrounding(
grid: List<List<String>>,
point: Pair<Int, Int>,
visited: List<Pair<Int, Int>>,
): List<Pair<Int, Int>> {
return listOf(
point.first + 1 to point.second, // down
point.first - 1 to point.second, // up
point.first to point.second + 1, // right
point.first to point.second - 1, // left
).filter {
!visited.contains(it) && grid.getOrNull(it.first)?.getOrNull(it.second) != null
}
}
private fun findGridItems(grid: List<List<String>>, char: Char): List<Pair<Int, Int>> {
val items = mutableListOf<Pair<Int, Int>>()
for ((rowIndex, row) in grid.withIndex()) {
for ((columnIndex, col) in row.withIndex()) {
if (col[0] == char) items.add(rowIndex to columnIndex)
}
}
if (items.isEmpty()) {
error("Grid item '$char' not found!")
}
return items
}
} | 0 | Kotlin | 0 | 0 | a48d13763db7684ee9f9129ee84cb2f2f02a6ce4 | 4,482 | advent-of-code-2022 | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.