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/g0001_0100/s0085_maximal_rectangle/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g0001_0100.s0085_maximal_rectangle
// #Hard #Array #Dynamic_Programming #Matrix #Stack #Monotonic_Stack
// #2023_07_10_Time_209_ms_(100.00%)_Space_37.9_MB_(100.00%)
class Solution {
fun maximalRectangle(matrix: Array<CharArray>): Int {
/*
* idea: using [LC84 Largest Rectangle in Histogram]. For each row of the matrix, construct
* the histogram based on the current row and the previous histogram (up to the previous
* row), then compute the largest rectangle area using LC84.
*/
val m = matrix.size
var n = 0
if (m == 0 || matrix[0].size.also { n = it } == 0) {
return 0
}
var i: Int
var j: Int
var res = 0
val heights = IntArray(n)
i = 0
while (i < m) {
j = 0
while (j < n) {
if (matrix[i][j] == '0') {
heights[j] = 0
} else {
heights[j] += 1
}
j++
}
res = Math.max(res, largestRectangleArea(heights))
i++
}
return res
}
private fun largestRectangleArea(heights: IntArray): Int {
/*
* idea: scan and store if a[i-1]<=a[i] (increasing), then as long as a[i]<a[i-1], then we
* can compute the largest rectangle area with base a[j], for j<=i-1, and a[j]>a[i], which
* is a[j]*(i-j). And meanwhile, all these bars (a[j]'s) are already done, and thus are
* throwable (using pop() with a stack).
*
* <p>We can use an array nLeftGeq[] of size n to simulate a stack. nLeftGeq[i] = the number
* of elements to the left of [i] having value greater than or equal to a[i] (including a[i]
* itself). It is also the index difference between [i] and the next index on the top of the
* stack.
*/
val n = heights.size
if (n == 0) {
return 0
}
val nLeftGeq = IntArray(n)
// the number of elements to the left
// of [i] with value >= heights[i]
nLeftGeq[0] = 1
// preIdx=the index of stack.peek(), res=max area so far
var preIdx = 0
var res = 0
for (i in 1 until n) {
nLeftGeq[i] = 1
// notice that preIdx = i - 1 = peek()
while (preIdx >= 0 && heights[i] < heights[preIdx]) {
res = Math.max(res, heights[preIdx] * (nLeftGeq[preIdx] + i - preIdx - 1))
// pop()
nLeftGeq[i] += nLeftGeq[preIdx]
// peek() current top
preIdx = preIdx - nLeftGeq[preIdx]
}
if (preIdx >= 0 && heights[i] == heights[preIdx]) {
// pop()
nLeftGeq[i] += nLeftGeq[preIdx]
}
// otherwise nothing to do
preIdx = i
}
// compute the rest largest rectangle areas with (indices of) bases
// on stack
while (preIdx >= 0 && 0 < heights[preIdx]) {
res = Math.max(res, heights[preIdx] * (nLeftGeq[preIdx] + n - preIdx - 1))
// peek() current top
preIdx = preIdx - nLeftGeq[preIdx]
}
return res
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 3,278 | LeetCode-in-Kotlin | MIT License |
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[95]不同的二叉搜索树 II.kt | maoqitian | 175,940,000 | false | {"Kotlin": 354268, "Java": 297740, "C++": 634} | import javax.swing.tree.TreeNode
//给你一个整数 n ,请你生成并返回所有由 n 个节点组成且节点值从 1 到 n 互不相同的不同 二叉搜索树 。可以按 任意顺序 返回答案。
//
//
//
//
//
// 示例 1:
//
//
//输入:n = 3
//输出:[[1,null,2,null,3],[1,null,3,2],[2,1,3],[3,1,null,null,2],[3,2,null,1]]
//
//
// 示例 2:
//
//
//输入:n = 1
//输出:[[1]]
//
//
//
//
// 提示:
//
//
// 1 <= n <= 8
//
//
//
// Related Topics 树 二叉搜索树 动态规划 回溯 二叉树
// 👍 1027 👎 0
//leetcode submit region begin(Prohibit modification and deletion)
/**
* Example:
* var ti = TreeNode(5)
* var v = ti.`val`
* Definition for a binary tree node.
* class TreeNode(var `val`: Int) {
* var left: TreeNode? = null
* var right: TreeNode? = null
* }
*/
class Solution {
fun generateTrees(n: Int): List<TreeNode?> {
if(n == 0) return ArrayList<TreeNode?>()
return generateBinaryTrees(1,n)
}
private fun generateBinaryTrees(start: Int, end: Int): ArrayList<TreeNode?> {
var res = ArrayList<TreeNode?>()
//递归结束条件
if (start > end){
res.add(null)
return res
}
//逻辑处理 进入下层循环
//遍历可行根节点
for (i in start..end){
//左子树
var leftTree = generateBinaryTrees(start, i - 1)
//右子树
var rightTree = generateBinaryTrees(i+1,end)
//从左子树集合中选出一棵左子树,从右子树集合中选出一棵右子树,拼接到根节点上
leftTree.forEach { leftNode->
rightTree.forEach { rightNode->
var node = TreeNode(i)
node.left = leftNode
node.right = rightNode
res.add(node)
}
}
}
//数据 reverse
return res
}
}
//leetcode submit region end(Prohibit modification and deletion)
| 0 | Kotlin | 0 | 1 | 8a85996352a88bb9a8a6a2712dce3eac2e1c3463 | 2,059 | MyLeetCode | Apache License 2.0 |
src/main/kotlin/com/github/aoc/AOCD4P1.kt | frikit | 317,914,710 | false | null | package com.github.aoc
import com.github.aoc.utils.*
fun main() {
val input = InputParser.parseInput(InputDay4Problem1, "\n\n")
.map { it.replace("\n", " ") }
.map { it.replace("\r", " ") }
val map = input.map {
it.split(" ").map { elem ->
val key = elem.split(":")[0].trim()
val value = elem.split(":")[1].trim()
key to value
}
}.map {
val res = hashMapOf<String, String>()
it.forEach { pair ->
res[pair.first] = pair.second
}
res
}
val countValid = map.map { validatePassport(it) }.filter { it }.count()
Result.stopExecutionPrintResult(countValid)
}
/**
* byr (Birth Year)
* iyr (Issue Year)
* eyr (Expiration Year)
* hgt (Height)
* hcl (Hair Color)
* ecl (Eye Color)
* pid (Passport ID)
* cid (Country ID) - Optional
*/
private fun validatePassport(userMap: Map<String, String>): Boolean {
val requiredProps = listOf("byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid").sorted()
val keyWithValues = userMap.map { (key, _) -> key }.sorted()
return keyWithValues.containsAll(requiredProps)
}
| 0 | Kotlin | 0 | 0 | 2fca82225a19144bbbca39247ba57c42a30ef459 | 1,157 | aoc2020 | Apache License 2.0 |
src/main/kotlin/aoc2022/Day13.kt | lukellmann | 574,273,843 | false | {"Kotlin": 175166} | package aoc2022
import AoCDay
import util.illegalInput
// https://adventofcode.com/2022/day/13
object Day13 : AoCDay<Int>(
title = "Distress Signal",
part1ExampleAnswer = 13,
part1Answer = 6046,
part2ExampleAnswer = 140,
part2Answer = 21423,
) {
private sealed class PacketData : Comparable<PacketData> {
class Integer(val integer: Int) : PacketData()
class List(val list: kotlin.collections.List<PacketData>) : PacketData() {
constructor(element: PacketData) : this(listOf(element))
}
final override fun compareTo(other: PacketData): Int {
return when (this) {
is Integer -> when (other) {
is Integer -> this.integer.compareTo(other.integer)
is List -> List(this).compareTo(other)
}
is List -> when (other) {
is Integer -> this.compareTo(List(other))
is List -> {
val left = this.list.iterator()
val right = other.list.iterator()
while (left.hasNext() && right.hasNext()) {
val comparison = left.next().compareTo(right.next())
if (comparison != 0) return comparison
}
this.list.size.compareTo(other.list.size)
}
}
}
}
}
private fun parsePacket(input: String): PacketData.List {
fun parsePacketDataList(start: Int): IndexedValue<PacketData.List> {
var index = start
val list = PacketData.List(buildList {
var integer = ""
fun addInteger() {
if (integer.isNotEmpty()) {
add(PacketData.Integer(integer.toInt()))
integer = ""
}
}
while (true) {
when (val char = input[index++]) {
in '0'..'9' -> integer += char
',' -> addInteger()
'[' -> {
val (skipIndex, list) = parsePacketDataList(start = index)
add(list)
index = skipIndex
}
']' -> {
addInteger()
break
}
else -> illegalInput(input)
}
}
})
return IndexedValue(index, list)
}
require(input.length >= 2 && input.first() == '[')
val (index, packet) = parsePacketDataList(start = 1)
check(index == input.length) { "input wasn't fully consumed, stopped at $index for length ${input.length}" }
return packet
}
private fun parsePacketPairs(input: String) = input
.lineSequence()
.chunked(3) // third is just a blank line or missing -> ignore
.map { (first, second) -> Pair(parsePacket(first), parsePacket(second)) }
private fun parsePackets(input: String) = input
.lineSequence()
.filter { line -> line.isNotBlank() }
.map(::parsePacket)
override fun part1(input: String) = parsePacketPairs(input)
.withIndex()
.filter { (_, packetPair) -> packetPair.first < packetPair.second }
.sumOf { packetPair -> packetPair.index + 1 } // 1-based indexing
override fun part2(input: String): Int {
val dividerPacket1 = parsePacket("[[2]]")
val dividerPacket2 = parsePacket("[[6]]")
val (indexDivider1, indexDivider2) = (parsePackets(input) + dividerPacket1 + dividerPacket2)
.sorted()
.withIndex()
.filter { (_, packet) -> packet === dividerPacket1 || packet === dividerPacket2 }
.map { dividerPacket -> dividerPacket.index + 1 } // 1-based indexing
.toList()
.also { check(it.size == 2) { "Expected 2 divider packets but found ${it.size}" } }
return indexDivider1 * indexDivider2
}
}
| 0 | Kotlin | 0 | 1 | 344c3d97896575393022c17e216afe86685a9344 | 4,185 | advent-of-code-kotlin | MIT License |
src/main/kotlin/first/MarkingWay.kt | Kvest | 163,103,813 | false | null | package first
import java.util.*
import kotlin.math.pow
import kotlin.math.sqrt
private const val START = 'S'
private const val END = 'X'
private const val OBSTACLE = 'B'
private const val PATH = '*'
private const val STRAIGHT_STEP = 1f
private const val DIAGONAL_STEP = 1.5f
fun addPath(mapString: String): String {
val maze = Maze(mapString)
val frontier = Frontier()
frontier.add(maze.start, 0f)
val cameFrom = mutableMapOf<Cell, Cell>()
val costSoFar = mutableMapOf(maze.start to 0f)
while (frontier.isNotEmpty()) {
//next cell to consider
val current = frontier.poll()
if (current == maze.end) {
//path already found
break
}
val currentCost = costSoFar[current] ?: 0f
//examine all available neighbors
maze.forEachAvailableNeighbor(current) { neighbor, weight ->
val newCost = currentCost + weight
//add neighbor for the further consideration if it is new or the new cost is lower than the previous one
if (neighbor !in costSoFar || newCost < costSoFar.getOrDefault(neighbor, 0f)) {
costSoFar[neighbor] = newCost
val priority = newCost + heuristic(maze.end, neighbor)
frontier.add(neighbor, priority)
cameFrom[neighbor] = current
}
}
}
//build set of the all cells in the path
val path = mutableSetOf(maze.end)
var step = maze.end
while (step != maze.start) {
step = cameFrom[step]!!
path.add(step)
}
//mark path on the original string
return mapString.split("\n").mapIndexed { i, row ->
row.mapIndexed { j, ch ->
if (Cell(i, j) in path) {
PATH
} else {
ch
}
}.joinToString(separator = "")
}.joinToString(separator = "\n")
}
fun heuristic(first: Cell, second: Cell) = first.distanceTo(second)
fun Int.pow2() = this.toFloat().pow(2)
data class Cell private constructor(val i: Int, val j: Int) {
companion object {
private val cash = mutableMapOf<Int, MutableMap<Int, Cell>>()
//Avoid allocations of the huge amount of the Cell items
operator fun invoke(i: Int, j: Int): Cell {
val rowsCash = cash.getOrPut(i) { mutableMapOf() }
return rowsCash.getOrPut(j) { Cell(i, j) }
}
}
fun distanceTo(other: Cell) = sqrt((other.i - i).pow2() + (other.j - j).pow2())
}
class Frontier {
private val queue = PriorityQueue<Container>()
fun add(cell: Cell, priority: Float) {
queue.add(Container(cell, priority))
}
fun poll() = queue.poll().cell
fun isNotEmpty() = queue.isNotEmpty()
private class Container(val cell: Cell, val priority: Float) : Comparable<Container> {
override fun compareTo(other: Container): Int {
val delta = priority - other.priority
return when {
delta > 0 -> 1
delta < 0 -> -1
else -> 0
}
}
}
}
class Maze(mapString: String) {
companion object {
private class NeighborInfo(val dI: Int, val dJ: Int, val stepWeight: Float)
private val neighbors = arrayOf(
NeighborInfo(-1, -1, DIAGONAL_STEP),
NeighborInfo(-1, 0, STRAIGHT_STEP),
NeighborInfo(-1, 1, DIAGONAL_STEP),
NeighborInfo(0, 1, STRAIGHT_STEP),
NeighborInfo(1, 1, DIAGONAL_STEP),
NeighborInfo(1, 0, STRAIGHT_STEP),
NeighborInfo(1, -1, DIAGONAL_STEP),
NeighborInfo(0, -1, STRAIGHT_STEP))
}
private val rows = mapString.split("\n")
private val heightRange = 0 until rows.size
private val widthRange = 0 until rows[0].length
val start = findCell(START)
val end = findCell(END)
fun forEachAvailableNeighbor(cell: Cell, action: (neighbor: Cell, stepWeight: Float) -> Unit) {
neighbors.forEach {
val i = cell.i + it.dI
val j = cell.j + it.dJ
if (i in heightRange && j in widthRange && isCellAvailable(i, j)) {
action(Cell(i, j), it.stepWeight)
}
}
}
private fun isCellAvailable(i: Int, j: Int) = rows[i][j] != OBSTACLE
private fun findCell(target: Char): Cell {
rows.forEachIndexed { i, row ->
row.forEachIndexed { j, ch ->
if (ch == target) {
return Cell(i, j)
}
}
}
throw IllegalStateException("$target not found")
}
}
| 0 | Kotlin | 0 | 0 | d94b725575a8a5784b53e0f7eee6b7519ac59deb | 4,647 | aoc2018 | Apache License 2.0 |
src/main/kotlin/pl/mrugacz95/aoc/day23/day23.kt | mrugacz95 | 317,354,321 | false | null | package pl.mrugacz95.aoc.day23
fun <T> List<T>.cycle(): Sequence<T> {
var i = 0
if (isEmpty()) return emptySequence()
return generateSequence {
this[i++ % this.size]
}
}
const val cupsToPick = 3
fun makeMove(state: List<Int>): List<Int> {
val current = state.first()
var cups = state
val picked = cups.subList(1, cupsToPick + 1)
cups = listOf(current) + cups.subList(cupsToPick + 1, cups.size).toList()
var destination = current
do {
destination = if (destination - 1 > 0) {
destination - 1
} else {
cups.maxOrNull()!!
}
}while (destination in picked)
val destinationIdx = cups.indexOf(destination)
val newState = cups.subList(0, destinationIdx + 1) + picked + cups.subList(destinationIdx + 1, cups.size)
return newState.subList(1, newState.size) + listOf(newState.first())
}
fun part1(cups: List<Int>): String {
var state = cups
for (move in 1..100) {
state = makeMove(state)
}
return state.cycle().dropWhile { it != 1 }.drop(1).take(cups.size - 1).joinToString("")
}
fun printCups(nextCup: List<Int>, currentCup: Int){
println("Cups: ")
var current = 1
for(i in 1 until nextCup.size){
if (nextCup[current] == currentCup){
print("(${nextCup[current]}) ")
}
else {
print("${nextCup[current]} ")
}
current = nextCup[current]
}
println()
}
const val debug = false
const val numberOfMoves = 10000000
const val numberOfCups = 1000000
fun part2(cups: List<Int>): Long {
val numberOfCups = numberOfCups + 1
val nextCup = MutableList(numberOfCups){ it + 1 }
nextCup[0] = -1 // empty
for(i in 0 until cups.size - 1){
nextCup[cups[i]] = cups[i + 1]
}
nextCup[cups.last()] = cups.size + 1
nextCup[nextCup.lastIndex] = cups[0]
var current = cups[0]
for (move in 0..numberOfMoves) {
val picked = mutableListOf(nextCup[current])
for(pick in 0 until cupsToPick - 1){
picked.add(nextCup[picked.last()])
}
var destination = current - 1
while (destination in picked || destination <= 0){
destination -= 1
if(destination <= 0){
destination = numberOfCups - 1
}
}
if(debug) {
println("-- move $move --")
printCups(nextCup, current)
println("Picked: $picked")
println("destination: $destination\n")
}
nextCup[current] = nextCup[picked.last()] // skip picked
nextCup[picked.last()] = nextCup[destination] // insert tail
nextCup[destination] = picked.first() // insert head
current = nextCup[current]
}
val first = nextCup[1]
val second = nextCup[first]
return first.toLong() * second.toLong()
}
fun main() {
val cups = {}::class.java.getResource("/day23.in")
.readText()
.map { it.toString().toInt() }
println("Answer part 1: ${part1(cups)}")
println("Answer part 2: ${part2(cups)}")
} | 0 | Kotlin | 0 | 1 | a2f7674a8f81f16cd693854d9f564b52ce6aaaaf | 3,099 | advent-of-code-2020 | Do What The F*ck You Want To Public License |
src/Day03.kt | Fenfax | 573,898,130 | false | {"Kotlin": 30582} | fun main() {
val alphabet = ('a'..'z').joinToString("").plus(('A'..'Z').joinToString(""))
fun postionInAlphabet(char: Char): Int {
return alphabet.indexOfFirst { it == char } + 1
}
fun part1(input: List<String>): Int {
return input.map { it.chunked(it.length / 2) }
.map { element -> element[0].first { element[1].contains(it) } }
.sumOf { postionInAlphabet(it) }
}
fun part2(input: List<String>): Int {
return input.asSequence()
.map { it.toMutableList() }
.windowed(3, 3)
.map { groups -> groups.reduce { acc, chars -> acc.apply { retainAll(chars) } }.first() }
.sumOf {postionInAlphabet(it)}
}
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 28af8fc212c802c35264021ff25005c704c45699 | 817 | AdventOfCode2022 | Apache License 2.0 |
22/part_one.kt | ivanilos | 433,620,308 | false | {"Kotlin": 97993} | import java.io.File
fun readInput() : Reactor {
val input = File("input.txt")
.readLines()
.map { it.split(",") }
val opRegex = """(\w+)""".toRegex()
val cubeRegex = """(-?\d+)..(-?\d+)""".toRegex()
val steps = mutableListOf<Step>()
input.forEach {
val op = opRegex.find(it[0])?.groupValues?.get(0).toString()
val (xMin, xMax) = cubeRegex.find(it[0])?.destructured!!
val (yMin, yMax) = cubeRegex.find(it[1])?.destructured!!
val (zMin, zMax) = cubeRegex.find(it[2])?.destructured!!
val cube = Cuboid(xMin.toInt(), xMax.toInt(), yMin.toInt(), yMax.toInt(), zMin.toInt(), zMax.toInt())
steps.add(Step(op, cube))
}
return Reactor(steps)
}
data class Step(val op : String, val cuboid : Cuboid)
data class Cuboid (val xMin : Int, val xMax : Int,
val yMin : Int, val yMax : Int,
val zMin : Int, val zMax : Int)
data class Cube (val x : Int, val y : Int, val z : Int)
class Reactor(private val steps : List<Step>) {
companion object {
const val MIN_VALID_COORDINATE = -50
const val MAX_VALID_COORDINATE = 50
}
fun onCubesAfterSteps() : Int {
val onCubes = mutableSetOf<Cube>()
for (step in steps) {
if (!isValidCuboid(step.cuboid)) continue
for (x in step.cuboid.xMin..step.cuboid.xMax) {
for (y in step.cuboid.yMin..step.cuboid.yMax) {
for (z in step.cuboid.zMin..step.cuboid.zMax) {
val cube = Cube(x, y, z)
if (step.op == "on") {
onCubes.add(cube)
} else {
onCubes.remove(cube)
}
}
}
}
}
return onCubes.size
}
private fun isValidCuboid(cuboid : Cuboid) : Boolean {
return cuboid.xMin in MIN_VALID_COORDINATE..MAX_VALID_COORDINATE &&
cuboid.xMax in MIN_VALID_COORDINATE..MAX_VALID_COORDINATE &&
cuboid.yMin in MIN_VALID_COORDINATE..MAX_VALID_COORDINATE &&
cuboid.yMax in MIN_VALID_COORDINATE..MAX_VALID_COORDINATE &&
cuboid.zMin in MIN_VALID_COORDINATE..MAX_VALID_COORDINATE &&
cuboid.zMin in MIN_VALID_COORDINATE..MAX_VALID_COORDINATE
}
}
fun solve(reactor : Reactor) : Int {
return reactor.onCubesAfterSteps()
}
fun main() {
val reactor = readInput()
val ans = solve(reactor)
println(ans)
}
| 0 | Kotlin | 0 | 3 | a24b6f7e8968e513767dfd7e21b935f9fdfb6d72 | 2,576 | advent-of-code-2021 | MIT License |
src/main/day08/Part1.kt | ollehagner | 572,141,655 | false | {"Kotlin": 80353} | package day08
import common.Point
import readInput
typealias TreeRow = List<Tree>
typealias Column = List<Int>
fun main() {
// val input = readInput("day08/testinput.txt")
val input = readInput("day08/input.txt")
val inputRows = inputAsRows(input)
val inputRowsReversed = inputRows.map { it.reversed() }
val inputColumns = inputAsColumns(inputRows)
val inputColumnsReversed = inputColumns.map { it.reversed() }
val treesInSight = listOf(inputRows, inputRowsReversed, inputColumns, inputColumnsReversed).flatten()
.map { trees -> inSight(trees) }
.flatten()
.toSet()
.count();
println("Day 08 part 1, trees in sight: $treesInSight")
}
fun inSight(trees: TreeRow): Set<Tree> {
return trees
.drop(1)
.fold(listOf(trees.first())) { acc, tree ->
if(tree.height > acc.maxOf { it.height }) acc + tree else acc
}
.toSet()
}
fun inputAsRows(input: List<String>): List<TreeRow> {
return input
.mapIndexed { y, row ->
row.withIndex()
.map { indexedValue ->
Tree(indexedValue.value.digitToInt(), Point(indexedValue.index, y))
}
}
}
fun inputAsColumns(input: List<TreeRow>): List<TreeRow> {
return (0 until input.first().size).map { x ->
input.mapIndexed { y, trees ->
trees[x]
}
}
}
data class Tree(val height: Int, val position: Point) | 0 | Kotlin | 0 | 0 | 6e12af1ff2609f6ef5b1bfb2a970d0e1aec578a1 | 1,463 | aoc2022 | Apache License 2.0 |
src/main/kotlin/day19/solution.kt | bukajsytlos | 433,979,778 | false | {"Kotlin": 63913} | package day19
import java.io.File
import kotlin.math.abs
fun main() {
val unidentifiedScanners = mutableListOf<UnidentifiedScanner>()
File("src/main/kotlin/day19/input.txt").useLines { linesSeq ->
val linesIterator = linesSeq.iterator()
while (linesIterator.hasNext()) {
val scannerId = linesIterator.next().substringAfter("scanner ").substringBefore(" ---")
val scannerBeacons = mutableListOf<Vector3D>()
while (linesIterator.hasNext()) {
val line = linesIterator.next()
if (line.isEmpty()) break
val (x, y, z) = line.split(",")
scannerBeacons.add(Vector3D.from(end = Point3D(x.toInt(), y.toInt(), z.toInt())))
}
unidentifiedScanners.add(UnidentifiedScanner(scannerId, scannerBeacons))
}
}
val identifiedScanners = mutableSetOf<IdentifiedScanner>()
var baseScanner = unidentifiedScanners.removeAt(0).run { IdentifiedScanner(id, Point3D.CENTER, beaconVectors) }
identifiedScanners.add(baseScanner)
val testedScanners = mutableListOf(baseScanner)
while (unidentifiedScanners.isNotEmpty()) {
val baseScannerInterBeaconVectors = baseScanner.beaconVectors.eachVector()
val unidentifiedScannersIterator = unidentifiedScanners.iterator()
for (unidentifiedScanner in unidentifiedScannersIterator) {
val unidentifiedScannerInterBeaconsVectors = unidentifiedScanner.beaconVectors.eachVector()
val commonDistances = baseScannerInterBeaconVectors.keys
.map { it.squaredLength() }
.intersect(unidentifiedScannerInterBeaconsVectors.keys.map { it.squaredLength() }.toSet())
//scanner have at least 12 common beacons (12 inter beacon combinations == 66 (12 * 11 / 2))
if (commonDistances.size >= 66) {
val commonDistance = commonDistances.first()
val identifiedBeaconsForCommonDistance = baseScannerInterBeaconVectors
.filter { it.key.squaredLength() == commonDistance }
.entries.first()
val unidentifiedBeaconsForCommonDistance = unidentifiedScannerInterBeaconsVectors
.filter { it.key.squaredLength() == commonDistance }
val scannerTransformation = TRANSFORMATIONS.first { transformation ->
unidentifiedBeaconsForCommonDistance
.map { it.key.transform(transformation) }
.any { it == identifiedBeaconsForCommonDistance.key }
}
val unidentifiedBeaconVector = unidentifiedBeaconsForCommonDistance.entries.first {
it.key.transform(scannerTransformation) == identifiedBeaconsForCommonDistance.key
}.value.first
val identifiedBeaconVector = identifiedBeaconsForCommonDistance.value.first
val transformedBeaconVector = unidentifiedBeaconVector.transform(scannerTransformation)
val scannerPositionShift = identifiedBeaconVector - transformedBeaconVector
val identifiedScanner = IdentifiedScanner(
unidentifiedScanner.id,
baseScanner.position + scannerPositionShift,
unidentifiedScanner.beaconVectors.map { it.transform(scannerTransformation) }
)
identifiedScanners.add(identifiedScanner)
unidentifiedScannersIterator.remove()
}
}
testedScanners.add(baseScanner)
baseScanner = identifiedScanners.first { it !in testedScanners }
}
println(identifiedScanners.flatMap { scanner -> scanner.beaconVectors.map { scanner.position + it } }.toSet().size)
println(identifiedScanners.flatMap { identifiedScanner1 ->
identifiedScanners.map { identifiedScanner2 ->
identifiedScanner1.position.manhattanDistance(identifiedScanner2.position)
}
}.maxOrNull())
}
fun List<Vector3D>.eachVector(): Map<Vector3D, Pair<Vector3D, Vector3D>> = buildMap {
this@eachVector.forEach { v1 ->
this@eachVector.forEach { v2 ->
if (v1 != v2) {
put(v2 - v1, v1 to v2)
}
}
}
}
data class UnidentifiedScanner(val id: String, val beaconVectors: List<Vector3D>)
data class IdentifiedScanner(val id: String, val position: Point3D, val beaconVectors: List<Vector3D>)
data class Vector3D(val dx: Int, val dy: Int, val dz: Int) {
operator fun plus(other: Vector3D) = Vector3D(dx + other.dx, dy + other.dy, dz + other.dz)
operator fun minus(other: Vector3D) = Vector3D(dx - other.dx, dy - other.dy, dz - other.dz)
fun squaredLength(): Int = dx * dx + dy * dy + dz * dz
fun transform(matrix: Matrix3D): Vector3D = Vector3D(
dx * matrix.m00 + dy * matrix.m01 + dz * matrix.m02,
dx * matrix.m10 + dy * matrix.m11 + dz * matrix.m12,
dx * matrix.m20 + dy * matrix.m21 + dz * matrix.m22
)
companion object {
fun from(start: Point3D = Point3D.CENTER, end: Point3D): Vector3D = Vector3D(end.x - start.x, end.y - start.y, end.z - start.z)
}
}
data class Matrix3D(
val m00: Int, val m01: Int, val m02: Int,
val m10: Int, val m11: Int, val m12: Int,
val m20: Int, val m21: Int, val m22: Int
)
data class Point3D(val x: Int, val y: Int, val z: Int) {
operator fun plus(vector: Vector3D) = Point3D(x + vector.dx, y + vector.dy, z + vector.dz)
operator fun minus(vector: Vector3D) = Point3D(x - vector.dx, y - vector.dy, z - vector.dz)
fun manhattanDistance(other: Point3D) = abs(x - other.x) + abs(y - other.y) + abs(z - other.z)
companion object {
val CENTER = Point3D(0, 0, 0)
}
}
val TRANSFORMATIONS: List<Matrix3D> = listOf(
Matrix3D(
1, 0, 0,
0, 1, 0,
0, 0, 1
),
Matrix3D(
1, 0, 0,
0, 0, -1,
0, 1, 0
),
Matrix3D(
1, 0, 0,
0, -1, 0,
0, 0, -1
),
Matrix3D(
1, 0, 0,
0, 0, 1,
0, -1, 0
),
Matrix3D(
-1, 0, 0,
0, -1, 0,
0, 0, 1
),
Matrix3D(
-1, 0, 0,
0, 0, -1,
0, -1, 0
),
Matrix3D(
-1, 0, 0,
0, 1, 0,
0, 0, -1
),
Matrix3D(
-1, 0, 0,
0, 0, 1,
0, 1, 0
),
Matrix3D(
0, -1, 0,
1, 0, 0,
0, 0, 1
),
Matrix3D(
0, 0, 1,
1, 0, 0,
0, 1, 0
),
Matrix3D(
0, 1, 0,
1, 0, 0,
0, 0, -1
),
Matrix3D(
0, 0, -1,
1, 0, 0,
0, -1, 0
),
Matrix3D(
0, 1, 0,
-1, 0, 0,
0, 0, 1
),
Matrix3D(
0, 0, 1,
-1, 0, 0,
0, -1, 0
),
Matrix3D(
0, -1, 0,
-1, 0, 0,
0, 0, -1
),
Matrix3D(
0, 0, -1,
-1, 0, 0,
0, 1, 0
),
Matrix3D(
0, 0, -1,
0, 1, 0,
1, 0, 0
),
Matrix3D(
0, 1, 0,
0, 0, 1,
1, 0, 0
),
Matrix3D(
0, 0, 1,
0, -1, 0,
1, 0, 0
),
Matrix3D(
0, -1, 0,
0, 0, -1,
1, 0, 0
),
Matrix3D(
0, 0, -1,
0, -1, 0,
-1, 0, 0
),
Matrix3D(
0, -1, 0,
0, 0, 1,
-1, 0, 0
),
Matrix3D(
0, 0, 1,
0, 1, 0,
-1, 0, 0
),
Matrix3D(
0, 1, 0,
0, 0, -1,
-1, 0, 0
),
) | 0 | Kotlin | 0 | 0 | f47d092399c3e395381406b7a0048c0795d332b9 | 7,576 | aoc-2021 | MIT License |
AnalyticHierarchyProcess/app/src/main/java/com/emirhanaydin/analytichierarchyprocess/math.kt | emirhanaydin | 159,205,125 | false | null | package com.emirhanaydin.analytichierarchyprocess
fun getRandomIndex(n: Int): Float {
return when (n) {
1, 2 -> 0f
3 -> 0.58f
4 -> 0.90f
5 -> 1.12f
6 -> 1.24f
7 -> 1.32f
8 -> 1.41f
9 -> 1.45f
10 -> 1.49f
11 -> 1.51f
12 -> 1.48f
13 -> 1.56f
else -> -1f
}
}
fun multiplyVectors(v1: FloatArray, v2: FloatArray): Float {
val size = v1.size
var sum = 0f
for (i in 0 until size) {
sum += v1[i] * v2[i]
}
return sum
}
private fun getWeights(ratings: Array<FloatArray>): Pair<Array<FloatArray>, FloatArray> {
val size = ratings.size
val weights = Array(size) { FloatArray(size) }
val subtotals = FloatArray(size)
// Calculate the weights
for (i in 0 until size) {
val child = ratings[i]
for (j in 0 until child.size) {
val index = j + i + 1 // Plus i to make the calculations triangular, plus 1 to skip diagonal
weights[i][index] = child[j]
weights[index][i] = 1 / weights[i][index] // Reciprocal
// Add the values to subtotals by their column indexes
subtotals[index] += weights[i][index]
subtotals[i] += weights[index][i]
}
// The diagonal indicates the alternative itself, so its weight is 1
weights[i][i] = 1f
subtotals[i] += weights[i][i]
}
return Pair(weights, subtotals)
}
private fun getNormalizedWeights(weights: Array<FloatArray>, subtotals: FloatArray): Array<FloatArray> {
val size = weights.size
val normalizedWeights = Array(size) { FloatArray(size) }
// Normalize the weights
for (i in 0 until size) {
for (j in 0 until size) {
normalizedWeights[i][j] = weights[i][j] / subtotals[j]
}
}
return normalizedWeights
}
private fun getPriorities(normalizedWeights: Array<FloatArray>): FloatArray {
val size = normalizedWeights.size
val priorities = FloatArray(size)
// Calculate priorities with the normalized weights
for (i in 0 until size) {
var sum = 0f
for (j in 0 until size) {
sum += normalizedWeights[i][j]
}
priorities[i] = sum / size // Average of the row
}
return priorities
}
private fun getConsistencyRatio(priorities: FloatArray, subtotals: FloatArray): Pair<Float, Float> {
val size = priorities.size
// Calculate the consistency ratio
val eMax = multiplyVectors(priorities, subtotals)
val consistencyIndex = (eMax - size) / (size - 1)
return Pair(consistencyIndex, getRandomIndex(size))
}
fun performAhp(ratings: Array<FloatArray>): AhpResult {
val weights: Array<FloatArray>
val subtotals: FloatArray
getWeights(ratings).apply {
weights = first
subtotals = second
}
val normalizedWeights = getNormalizedWeights(weights, subtotals)
val priorities = getPriorities(normalizedWeights)
val randomIndex: Float
val consistencyIndex: Float
getConsistencyRatio(priorities, subtotals).apply {
consistencyIndex = first
randomIndex = second
}
return AhpResult(priorities, consistencyIndex, randomIndex, consistencyIndex / randomIndex)
}
class AhpResult(
val priorities: FloatArray,
val consistencyIndex: Float,
val randomIndex: Float,
val consistencyRatio: Float
) | 0 | Kotlin | 1 | 0 | 7a58319c4b90d027cb24afda6a6793eba807b410 | 3,411 | ahp-android | The Unlicense |
src/main/kotlin/mkuhn/aoc/Day08.kt | mtkuhn | 572,236,871 | false | {"Kotlin": 53161} | package mkuhn.aoc
import mkuhn.aoc.util.*
fun main() {
val input = readInput("Day08")
println(day08part1(input))
println(day08part2(input))
}
fun day08part1(input: List<String>): Int =
TreeGrid(input.map { l -> l.map { it.digitToInt() } }.transpose())
.findVisibleTrees()
.count()
fun day08part2(input: List<String>): Int =
TreeGrid(input.map { l -> l.map { it.digitToInt() } }.transpose())
.findHighestScenicScore()
class TreeGrid(grid: List<List<Int>>): Grid<Int>(grid) {
enum class Direction {NORTH, SOUTH, EAST, WEST}
fun findVisibleTrees() =
allPoints().filter { isTreeVisible(it) }
fun findHighestScenicScore() =
allPoints().maxOf { scenicScore(it) }
fun scenicScore(pos: Point) =
Direction.values().fold(1) { acc, direction ->
acc * viewingDistance(pos, direction)
}
fun viewingDistance(pos: Point, direction: Direction) =
when(direction) {
Direction.NORTH -> allNorth(pos)
Direction.SOUTH -> allSouth(pos)
Direction.EAST -> allEast(pos)
Direction.WEST -> allWest(pos)
}.takeWhileInclusive { valueAt(it) < valueAt(pos) }.count()
fun isTreeVisible(pos: Point) =
when {
!isInBounds(pos) -> error("invalid coordinates $pos")
isEdge(pos) -> true
allWest(pos).all { valueAt(it) < valueAt(pos) } -> true
allEast(pos).all { valueAt(it) < valueAt(pos) } -> true
allNorth(pos).all { valueAt(it) < valueAt(pos) } -> true
allSouth(pos).all { valueAt(it) < valueAt(pos) } -> true
else -> false
}
} | 0 | Kotlin | 0 | 1 | 89138e33bb269f8e0ef99a4be2c029065b69bc5c | 1,679 | advent-of-code-2022 | Apache License 2.0 |
src/Day04.kt | palex65 | 572,937,600 | false | {"Kotlin": 68582} |
private fun String.toRanges(): List<IntRange> = split(',').map { range ->
val (start, end) = range.split('-').map { it.toInt() }
start..end
}
private fun part1(lines: List<String>): Int =
lines.count { line ->
val(a, b) = line.toRanges()
a.all{ it in b } || b.all { it in a }
}
private fun part2(lines: List<String>): Int =
lines.count { line ->
val (a, b) = line.toRanges()
a.any { it in b }
}
fun main() {
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
println(part1(input)) // 588
println(part2(input)) // 911
}
| 0 | Kotlin | 0 | 2 | 35771fa36a8be9862f050496dba9ae89bea427c5 | 684 | aoc2022 | Apache License 2.0 |
src/main/kotlin/y2022/Day02.kt | jforatier | 432,712,749 | false | {"Kotlin": 44692} | package y2022
class Day02(private val data: List<String>) {
enum class Action(val char: Set<String>, val value:Int) {
UNKNOWN(setOf(),0),
ROCK(setOf("A","X"), 1),
PAPER(setOf("B","Y"), 2),
SCISSORS(setOf("C","Z"),3);
fun winAgainst() : Action {
return when(this) {
UNKNOWN -> UNKNOWN
ROCK -> SCISSORS
PAPER -> ROCK
SCISSORS -> PAPER
}
}
fun failAgainst() : Action {
return when(this) {
UNKNOWN -> UNKNOWN
ROCK -> PAPER
PAPER -> SCISSORS
SCISSORS -> ROCK
}
}
}
enum class ResultExpected(val char: String) {
UNKNOWN(""),
WIN("Z"),
DRAW("Y"),
LOSS("X");
}
private fun String.actionForResult(opponentChoose: Action): Day02.Action {
var resultExpected = ResultExpected.UNKNOWN
ResultExpected.values().forEach {
if(it.char.contains(this)){
resultExpected = it
}
}
return when(resultExpected){
ResultExpected.DRAW, ResultExpected.UNKNOWN -> opponentChoose
ResultExpected.LOSS -> opponentChoose.winAgainst()
ResultExpected.WIN -> opponentChoose.failAgainst()
}
}
private fun String.toAction(): Action {
Action.values().forEach {
if(it.char.contains(this)){
return it
}
}
return Action.UNKNOWN
}
data class Round(val opponentChoose: Action, val myChoice: Action) {
fun getScore() : Int {
return when(myChoice.winState(opponentChoose)){
true -> myChoice.value + 6
null -> myChoice.value + 3
false -> myChoice.value
}
}
}
fun part1(): Int {
return data
.map { line -> Round(line.split(" ")[0].toAction(),line.split(" ")[1].toAction() ) }
.sumOf { it.getScore() }
}
fun part2(): Int {
return data
.map { line -> Round(line.split(" ")[0].toAction(),line.split(" ")[1].actionForResult(line.split(" ")[0].toAction()) ) }
.sumOf { it.getScore() }
}
}
private fun Day02.Action.winState(opponentChoose: Day02.Action): Boolean? {
if(this == opponentChoose){
return null
}
if(this.failAgainst() == opponentChoose){
return false
}
return true
}
| 0 | Kotlin | 0 | 0 | 2a8c0b4ccb38c40034c6aefae2b0f7d4c486ffae | 2,534 | advent-of-code-kotlin | MIT License |
src/main/kotlin/days/Day03.kt | julia-kim | 569,976,303 | false | null | package days
import readInput
fun main() {
val lettersToNumber = (('a'..'z') + ('A'..'Z')).mapIndexed { i, c ->
c to (i + 1)
}.toMap()
fun part1(input: List<String>): Int {
var sum = 0
input.forEach { rucksack ->
val halfLength = rucksack.length / 2
val compartment1 = rucksack.take(halfLength).map { it }
val compartment2 = rucksack.takeLast(halfLength).map { it }
val common = compartment1.first { compartment2.contains(it) }
sum += lettersToNumber[common] ?: 0
}
return sum
}
fun part2(input: List<String>): Int {
var sum = 0
val allRucksacks = input.map { it.map { it } }
allRucksacks.chunked(3).forEach { group ->
val common = group[0].first { itemType ->
group[1].contains(itemType) && group[2].contains(itemType)
}
sum += lettersToNumber[common] ?: 0
}
return sum
}
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 65188040b3b37c7cb73ef5f2c7422587528d61a4 | 1,196 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/days/Day11.kt | felix-ebert | 317,592,241 | false | null | package days
import kotlin.math.max
import kotlin.math.min
class Day11 : Day(11) {
override fun partOne(): Any {
return simulateSeatModel(parseSeatModel(), ::findNeighbours, 4)
}
override fun partTwo(): Any {
return simulateSeatModel(parseSeatModel(), ::findFirstVisibleSeats, 5)
}
private fun parseSeatModel(): Array<Array<Char>> {
val seats = Array(inputList.first().length) { Array(inputList.size) { ' ' } }
inputList.forEachIndexed { x, row ->
row.forEachIndexed { y, c ->
seats[x][y] = c
}
}
return seats
}
private fun simulateSeatModel(seats: Array<Array<Char>>, seatChecker: (seats: Array<Array<Char>>, row: Int, col: Int) -> List<Char>, occupiedSeats: Int): Int {
// deep copy old model
val newModel = Array(inputList.first().length) { Array(inputList.size) { ' ' } }
seats.forEachIndexed { x, row ->
row.forEachIndexed { y, c ->
newModel[x][y] = c
}
}
// apply rules
seats.forEachIndexed { x, row ->
row.forEachIndexed { y, c ->
when (c) {
'L' -> if (!seatChecker(seats, x, y).contains('#')) newModel[x][y] = '#'
'#' -> if (seatChecker(seats, x, y).count { it == '#' } >= occupiedSeats) newModel[x][y] = 'L'
}
}
}
return if (seats.contentDeepEquals(newModel)) seats.sumOf { it.count { c -> c == '#' } }
else simulateSeatModel(newModel, seatChecker, occupiedSeats)
}
private fun findNeighbours(seats: Array<Array<Char>>, row: Int, col: Int): List<Char> {
// adapted from: https://stackoverflow.com/questions/652106/finding-neighbours-in-a-two-dimensional-array/19074651#19074651
val neighbourSeats = mutableListOf<Char>()
for (x in max(0, row - 1)..min(row + 1, seats.size - 1)) {
for (y in max(0, col - 1)..min(col + 1, seats[0].size - 1)) {
if (row != x || col != y) {
neighbourSeats.add(seats[x][y])
}
}
}
return neighbourSeats
}
private fun findFirstVisibleSeats(seats: Array<Array<Char>>, row: Int, col: Int): List<Char> {
// adapted from: https://www.geeksforgeeks.org/search-a-word-in-a-2d-grid-of-characters/
val firstVisibleSeats = mutableListOf<Char>()
val x = intArrayOf(-1, -1, -1, 0, 0, 1, 1, 1)
val y = intArrayOf(-1, 0, 1, -1, 1, -1, 0, 1)
for (dir in 0 until 8) {
var rd: Int = row + x[dir]
var cd: Int = col + y[dir]
for (i in 0..max(seats.size, seats[0].size)) {
if (rd >= seats.size || rd < 0 || cd >= seats[0].size || cd < 0)
break
if (seats[rd][cd] != '.') {
firstVisibleSeats.add(seats[rd][cd])
break
}
rd += x[dir]
cd += y[dir]
}
}
return firstVisibleSeats
}
} | 0 | Kotlin | 0 | 4 | dba66bc2aba639bdc34463ec4e3ad5d301266cb1 | 3,112 | advent-of-code-2020 | Creative Commons Zero v1.0 Universal |
src/main/kotlin/aoc2021/day8/SevenSegments.kt | arnab | 75,525,311 | false | null | package aoc2021.day8
object SevenSegments {
data class Observation(
val pattern: List<String>,
val output: List<String>
)
fun parse(data: String) = data.split("\n").map { line ->
val (pattern, output) = line.split(" | ")
Observation(
pattern.split(" ").map { it.toCharArray().sorted().joinToString("") },
output.split(" ").map { it.toCharArray().sorted().joinToString("") }
)
}
fun countDigitsWithUniqSegments(observations: List<Observation>) = observations.flatMap { it.output }
.count {
it.length == 2 || // -> 1
it.length == 4 || // -> 4
it.length == 3 || // -> 7
it.length == 7 // -> 8
}
fun decodeAllAndSum(observations: List<Observation>) = observations.sumBy { observation ->
val cipher = deduceCipher(observation.pattern)
calculateValue(observation.output, cipher)
}
private fun deduceCipher(pattern: List<String>): Map<String, Int> {
val cipher: MutableMap<String, Int> = mutableMapOf()
val remainingPatternsToIdentify = pattern.toMutableList()
val patternOne = remainingPatternsToIdentify.find { it.length == 2 }!!
cipher[patternOne] = 1
remainingPatternsToIdentify.remove(patternOne)
val patternFour = remainingPatternsToIdentify.find { it.length == 4 }!!
cipher[patternFour] = 4
remainingPatternsToIdentify.remove(patternFour)
val patternSeven = remainingPatternsToIdentify.find { it.length == 3 }!!
cipher[patternSeven] = 7
remainingPatternsToIdentify.remove(patternSeven)
val patternEight = remainingPatternsToIdentify.find { it.length == 7 }!!
cipher[patternEight] = 8
remainingPatternsToIdentify.remove(patternEight)
val patternNine = remainingPatternsToIdentify.find { it.length == 6 && it.containsPattern(patternFour) }!!
cipher[patternNine] = 9
remainingPatternsToIdentify.remove(patternNine)
val patternZero = remainingPatternsToIdentify.find { it.length == 6 && it.containsPattern(patternOne) }!!
cipher[patternZero] = 0
remainingPatternsToIdentify.remove(patternZero)
val patternSix = remainingPatternsToIdentify.find { it.length == 6 }!!
cipher[patternSix] = 6
remainingPatternsToIdentify.remove(patternSix)
val patternThree = remainingPatternsToIdentify.find { it.length == 5 && it.containsPattern(patternOne) }!!
cipher[patternThree] = 3
remainingPatternsToIdentify.remove(patternThree)
val patternFive = remainingPatternsToIdentify.find { it.length == 5 && patternSix.containsPattern(it) }!!
cipher[patternFive] = 5
remainingPatternsToIdentify.remove(patternFive)
if (remainingPatternsToIdentify.size > 1) {
throw NotImplementedError("Only one pattern (for #2) should have remained, found: $remainingPatternsToIdentify")
}
val patternTwo = remainingPatternsToIdentify[0]
cipher[patternTwo] = 2
remainingPatternsToIdentify.remove(patternTwo)
return cipher
}
private fun calculateValue(output: List<String>, cipher: Map<String, Int>) =
output.map { cipher[it] }.joinToString("").toInt()
private fun String.containsPattern(pattern: String) = pattern.all { this.contains(it) }
}
| 0 | Kotlin | 0 | 0 | 1d9f6bc569f361e37ccb461bd564efa3e1fccdbd | 3,421 | adventofcode | MIT License |
src/main/kotlin/days/Geometry.kt | andilau | 429,206,599 | false | {"Kotlin": 113274} | package days
import kotlin.math.absoluteValue
import kotlin.math.sign
data class Point(val x: Int, val y: Int) {
fun up() = copy(y = y - 1)
fun down() = copy(y = y + 1)
fun left() = copy(x = x - 1)
fun right() = copy(x = x + 1)
fun manhattanDistance(to: Point = ORIGIN) =
(x - to.x).absoluteValue + (y - to.y).absoluteValue
fun neighbors() = listOf(up(), left(), down(), right())
operator fun minus(other: Point): Point = Point(x - other.x, y - other.y)
operator fun plus(other: Point): Point = Point(x + other.x, y + other.y)
fun rotateLeft() = Point(y, -x)
fun rotateRight() = Point(-y, x)
companion object {
val ORIGIN = Point(0, 0)
}
}
data class Point3D(val x: Int, val y: Int, val z: Int) {
infix fun sign(other: Point3D) = Point3D(
(other.x - x).sign,
(other.y - y).sign,
(other.z - z).sign,
)
operator fun plus(other: Point3D) = Point3D(x + other.x, y + other.y, z + other.z)
fun manhattanDistance(to: Point3D = ORIGIN) =
(x - to.x).absoluteValue + (y - to.y).absoluteValue + (z - to.z).absoluteValue
companion object {
val ORIGIN = Point3D(0, 0, 0)
}
}
enum class Direction {
NORTH, EAST, SOUTH, WEST;
fun left() = when (this) {
NORTH -> WEST
WEST -> SOUTH
SOUTH -> EAST
EAST -> NORTH
}
fun right() = left().left().left()
companion object {
fun from(movement: Point) =
when (movement) {
Point.ORIGIN.up() -> NORTH
Point.ORIGIN.down() -> SOUTH
Point.ORIGIN.left() -> WEST
Point.ORIGIN.right() -> EAST
else -> throw IllegalArgumentException("Unknown direction: $movement")
}
}
}
fun <T> Map<Point, T>.mapAsString(default: T, mapping: (T) -> Char) =
buildString {
val map = this@mapAsString
val yRange = keys.minOf(Point::y)..keys.maxOf(Point::y)
val xRange = (keys.minOf(Point::x)..keys.maxOf(Point::x))
for (y in yRange) {
val line = xRange
.map { x -> map.getOrDefault(Point(x, y), default) }
.map { mapping(it) }
.joinToString("")
appendLine(line)
}
}
| 2 | Kotlin | 0 | 0 | f51493490f9a0f5650d46bd6083a50d701ed1eb1 | 2,296 | advent-of-code-2019 | Creative Commons Zero v1.0 Universal |
src/main/kotlin/io/undefined/TrappingRainWater.kt | jffiorillo | 138,075,067 | false | {"Kotlin": 434399, "Java": 14529, "Shell": 465} | package io.undefined
import io.utils.runTests
// https://leetcode.com/problems/trapping-rain-water/
class TrappingRainWater {
// https://leetcode.com/problems/trapping-rain-water/discuss/17391/Share-my-short-solution.
fun execute(heights: IntArray): Int {
var start = 0
var end = heights.lastIndex
var max = 0
var leftMax = 0
var rightMax = 0
while (start <= end) {
leftMax = maxOf(leftMax, heights[start])
rightMax = maxOf(rightMax, heights[end])
when {
leftMax < rightMax -> {
// leftMax is smaller than rightMax, so the (leftmax-A[a]) water can be stored
max += leftMax - heights[start]
start++
}
else -> {
max += rightMax - heights[end]
end--
}
}
}
return max
}
fun execute1(heights: IntArray): Int {
val result = mutableSetOf<Pair<Int, Int>>()
val towers = mutableListOf<Pair<Int, Int>>()
loop@ for (index in heights.indices) {
val value = heights[index]
if (index == 0) {
if (value > 0) towers.add(index to value)
continue
}
if (heights[index - 1] < value) {
if (towers.isNotEmpty()) {
addValues(heights, towers, value, index, result)
removeInvalidTowers(towers, value)
}
towers.add(index to value)
}
}
return result.size
}
private fun addValues(heights: IntArray, towers: MutableList<Pair<Int, Int>>, currentValue: Int, currentIndex: Int,
result: MutableSet<Pair<Int, Int>>) {
for (pair in towers.reversed()) {
generateAllValues(heights, pair.first, currentIndex, minOf(currentValue, pair.second), result)
if (pair.second >= currentValue) {
break
}
}
}
private fun generateAllValues(heights: IntArray, index0: Int, index1: Int, maxHeight: Int, result: MutableSet<Pair<Int, Int>>) {
(index0 + 1 until index1).forEach { row ->
val minHeight = heights[row]
(minHeight until maxHeight).forEach { col -> result.add(row to col) }
}
}
private fun removeInvalidTowers(towers: MutableList<Pair<Int, Int>>, value: Int) {
val indexToRemove = mutableListOf<Int>()
for (index in towers.lastIndex downTo 0) {
val pair = towers[index]
if (pair.second >= value) {
break
}
indexToRemove.add(index)
}
indexToRemove.forEach { towers.removeAt(it) }
}
}
fun main() {
runTests(listOf(
intArrayOf(0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1) to 6,
intArrayOf(2, 0, 2) to 2,
intArrayOf(0, 3, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1) to 12,
intArrayOf(4, 1, 3, 0, 1, 0, 2, 7) to 17
)) { (input, value) -> value to TrappingRainWater().execute(input) }
} | 0 | Kotlin | 0 | 0 | f093c2c19cd76c85fab87605ae4a3ea157325d43 | 2,748 | coding | MIT License |
src/Day02.kt | rinas-ink | 572,920,513 | false | {"Kotlin": 14483} | import java.lang.IllegalArgumentException
fun main() {
fun convertInput(c: Char): Int = if (c - 'A' < 3) (c - 'A')
else {
(c - 'X')
} + 1
fun less(x: Int) = when (x) {
1 -> 3
2 -> 1
3 -> 2
else -> throw IllegalArgumentException("Must be in range [1; 3]")
}
fun evalStep1(s: String): Int {
val opponent = convertInput(s[0])
val us = convertInput(s[2])
return us + 3 * (us == opponent).compareTo(false) + 6 * (less(us) == opponent).compareTo(
false
)
}
fun evalAllSteps(
input: List<String>,
func: (String) -> Int
): Int = input.fold(0) { sum, step -> sum + func(step) }
fun part1(input: List<String>): Int = evalAllSteps(input, ::evalStep1)
fun greater(x: Int) = when (x) {
3 -> 1
1 -> 2
2 -> 3
else -> throw IllegalArgumentException("Must be in range [1; 3]")
}
fun evalStep2(s: String): Int {
val other = convertInput(s[0])
when (s[2]) {
'X' -> return less(other)
'Y' -> return other + 3
'Z' -> return greater(other) + 6
else -> throw IllegalArgumentException("Must be X, Y or Z")
}
}
fun part2(input: List<String>) = evalAllSteps(input,::evalStep2)
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 462bcba7779f7bfc9a109d886af8f722ec14c485 | 1,600 | anvent-kotlin | Apache License 2.0 |
puzzles/src/main/kotlin/com/kotlinground/puzzles/hashmap/equalrowsandcolumns/equalPairs.kt | BrianLusina | 113,182,832 | false | {"Kotlin": 483489, "Shell": 7283, "Python": 1725} | package com.kotlinground.puzzles.hashmap.equalrowsandcolumns
fun equalPairsHashMap(grid: Array<IntArray>): Int {
var count = 0
val n = grid.size
val rowCounter = hashMapOf<String, Int>()
for (row in grid) {
val rowString = row.contentToString()
rowCounter[rowString] = 1 + rowCounter.getOrDefault(rowString, 0)
}
for (column in 0 until n) {
val col = arrayListOf<Int>()
for (i in 0 until n) {
col.add(grid[i][column])
}
count += rowCounter.getOrDefault(col.toString(), 0)
}
return count
}
fun equalPairsBruteForce(grid: Array<IntArray>): Int {
var count = 0
val n: Int = grid.size
// Check each row r against each column c.
for (r in 0 until n) {
for (c in 0 until n) {
var match = true
// Iterate over row r and column c.
for (i in 0 until n) {
if (grid[r][i] != grid[i][c]) {
match = false
break
}
}
// If row r equals column c, increment count by 1.
count += if (match) 1 else 0
}
}
return count
}
internal data class TrieNode(var count: Int = 0, val children: HashMap<Int, TrieNode> = hashMapOf())
internal class Trie {
private var rootTrieNode: TrieNode = TrieNode()
fun insert(array: IntArray) {
var trieNode = rootTrieNode
for (a in array) {
if (!trieNode.children.containsKey(a)) {
trieNode.children[a] = TrieNode()
}
trieNode = trieNode.children.getOrDefault(a, TrieNode())
}
trieNode.count += 1
}
fun search(array: IntArray): Int {
var trieNode = rootTrieNode
for (a in array) {
if (trieNode.children.containsKey(a)) {
trieNode = trieNode.children[a]!!
} else {
return 0
}
}
return trieNode.count
}
}
fun equalPairsTrieNode(grid: Array<IntArray>): Int {
val trie = Trie()
var count = 0
val n: Int = grid.size
for (row in grid) {
trie.insert(row)
}
for (c in 0 until n) {
val colArray = IntArray(n)
for (r in 0 until n) {
colArray[r] = grid[r][c]
}
count += trie.search(colArray)
}
return count
}
| 1 | Kotlin | 1 | 0 | 5e3e45b84176ea2d9eb36f4f625de89d8685e000 | 2,390 | KotlinGround | MIT License |
src/Day05.kt | maximilianproell | 574,109,359 | false | {"Kotlin": 17586} | import java.io.File
fun main() {
fun extractMoveActionsFromInput(input: String): List<Int> {
return input
.replaceFirst("move", "")
.replaceFirst("from", "")
.replaceFirst("to", "")
.chunked(3)
.map { it.trim().toInt() }
}
fun part1(input: String): String {
val (stacksString, moveActionString) = input.split("\n\n")
val supplyStack = SupplyStack.createSupplyStack(stacksString)
moveActionString.lines().forEach { moveAction ->
val (numberOfCrates, stackSource, stackDestination) = extractMoveActionsFromInput(moveAction)
supplyStack moveSingle numberOfCrates from (stackSource to stackDestination)
}
return supplyStack
.getStackMap()
.toSortedMap()
.values
.map { it.lastOrNull() ?: "" }
.reduce { acc, s -> acc + s }
}
fun part2(input: String): String {
val (stacksString, moveActionString) = input.split("\n\n")
val supplyStack = SupplyStack.createSupplyStack(stacksString)
moveActionString.lines().forEach { moveAction ->
val (numberOfCrates, stackSource, stackDestination) = extractMoveActionsFromInput(moveAction)
supplyStack moveAll numberOfCrates from (stackSource to stackDestination)
}
return supplyStack
.getStackMap()
.toSortedMap()
.values
.map { it.lastOrNull() ?: "" }
.reduce { acc, s -> acc + s }
}
val testInputString = """
[D]
[N] [C]
[Z] [M] [P]
1 2 3
move 1 from 2 to 1
move 3 from 1 to 3
move 2 from 2 to 1
move 1 from 1 to 2
""".trimIndent()
val input = File(("src/Day05.txt")).readText()
// val input = testInputString
println(part1(input))
println(part2(input))
}
data class SupplyStack(
private val stackMap: MutableMap<Int, ArrayList<String>>
) {
companion object {
fun createSupplyStack(input: String): SupplyStack {
val lines = input.lines()
val mStackMap = mutableMapOf<Int, ArrayList<String>>()
lines.forEachIndexed { lineIndex, lineString ->
if (lineIndex == lines.lastIndex) return@forEachIndexed
// every crate has the width of 4 (including the whitespace next to it)
val entries = lineString.chunked(4)
for ((index, element) in entries.withIndex()) {
if (element.isNotBlank()) {
val char = element
.replace("]", "")
.replace("[", "")
.trim()
// always add to the beginning
mStackMap.putIfAbsent(index + 1, arrayListOf(char))?.add(0, char)
}
}
}
return SupplyStack(mStackMap)
}
}
fun getStackMap() = stackMap.toMap()
inner class MoveAction(
private val numberOfCrates: Int,
private val moveSingle: Boolean,
) {
infix fun from(mPair: Pair<Int, Int>) {
val fromArray = stackMap.getOrElse(key = mPair.first) { null }
val toArray = stackMap.getOrElse(key = mPair.second) { null }
fromArray?.let { elementsFrom ->
if (elementsFrom.isEmpty()) return@let
if (moveSingle) {
repeat(numberOfCrates) {
val lastElement = elementsFrom.removeLast()
toArray?.add(lastElement)
}
} else {
val elementsToMove = elementsFrom.subList(
elementsFrom.size - numberOfCrates,
elementsFrom.size
)
toArray?.addAll(elementsToMove)
elementsToMove.clear()
}
}
}
}
infix fun moveSingle(numberOfCrates: Int): MoveAction = MoveAction(
numberOfCrates = numberOfCrates,
moveSingle = true
)
infix fun moveAll(numberOfCrates: Int): MoveAction = MoveAction(
numberOfCrates = numberOfCrates,
moveSingle = false
)
} | 0 | Kotlin | 0 | 0 | 371cbfc18808b494ed41152256d667c54601d94d | 4,376 | kotlin-advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/LongestCommonPrefix.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2021 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import dev.shtanko.algorithms.extensions.commonPrefix
/**
* Longest Common Prefix.
* @see <a href="https://leetcode.com/problems/longest-common-prefix/">Source</a>
*/
fun interface LongestCommonPrefix {
operator fun invoke(strs: Array<String>): String
}
/**
* Approach 1: Horizontal scanning
*/
class LCPHorizontalScanning : LongestCommonPrefix {
override operator fun invoke(strs: Array<String>): String {
if (strs.isEmpty()) return ""
var prefix: String = strs.first()
for (i in 1 until strs.size) {
while (strs[i].indexOf(prefix) != 0) {
prefix = prefix.substring(0, prefix.length - 1)
if (prefix.isEmpty()) return ""
}
}
return prefix
}
}
/**
* Approach 2: Vertical scanning
*/
class LCPVerticalScanning : LongestCommonPrefix {
override operator fun invoke(strs: Array<String>): String {
if (strs.isEmpty()) return ""
for (i in strs[0].indices) {
val c: Char = strs[0][i]
for (j in 1 until strs.size) {
if (i == strs[j].length || strs[j][i] != c) return strs[0].substring(0, i)
}
}
return strs[0]
}
}
/**
* Approach 3: Divide and conquer
*/
class LCPDivideAndConquer : LongestCommonPrefix {
override operator fun invoke(strs: Array<String>): String {
if (strs.isEmpty()) return ""
return longestCommonPrefix(strs, 0, strs.size - 1)
}
private fun longestCommonPrefix(strs: Array<String>, l: Int, r: Int): String {
return if (l == r) {
strs[l]
} else {
val mid = l.plus(r).div(2)
val lcpLeft = longestCommonPrefix(strs, l, mid)
val lcpRight = longestCommonPrefix(strs, mid + 1, r)
(lcpLeft to lcpRight).commonPrefix()
}
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,498 | kotlab | Apache License 2.0 |
src/Day03.kt | SpencerDamon | 573,244,838 | false | {"Kotlin": 6482} |
fun main() {
/*fun part1(input: List<String>): Int {
var subString1 = ""
var subString2 = ""
val points = mutableListOf<Int>()
for (i in input) {
val string = i.toString()
subString1 = string.substring(0, string.length / 2)
subString2 = string.substring(string.length / 2, string.length)
for (i in subString1) {
if (subString2.contains(i)) {
points.add( when(i) {
in 'a'..'z' -> i.code - 96
else -> i.code - 38
}
)
//println(points)
break
}
}
}
return points.sum()
}*/
fun part2(input: List<String>): Int {
val sums = mutableListOf<Int>()
for (i in 0 until input.size step 3) {
val line1 = input[i]
val line2 = input[i + 1]
val line3 = input[i + 2]
for (j in 0 until line1.length) {
if (line2.contains(line1[j]) && line3.contains(line1[j])) {
sums.add(when (line1[j]) {
in 'a'..'z' -> line1[j].code - 96
else -> line1[j].code - 38
}
)
break
}
}
}
return sums.sum()
}
// remove comment to test,
// test if implementation meets criteria from the description, like:
//val testInput = readInput("Day03_pt2_test")
//check(part1(testInput) == 157)
//check(part2(testInput) == 70)
val input = readInput("Day03_input")
// println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 659a9e9ae4687bd633bddfb924416c80a8a2db2e | 1,758 | aoc-2022-in-Kotlin | Apache License 2.0 |
src/aoc2017/kot/Day16.kt | Tandrial | 47,354,790 | false | null | package aoc2017.kot
import java.io.File
object Day16 {
fun solve(input: List<String>, times: Int = 1): String {
val sequence = mutableListOf<List<Char>>()
var curr = (0 until 16).map { 'a' + it }
repeat(times) {
if (curr in sequence) {
return sequence[times % sequence.size].joinToString(separator = "")
} else {
sequence.add(curr)
curr = dance(curr, input)
}
}
return curr.joinToString(separator = "")
}
private fun dance(curr: List<Char>, input: List<String>): List<Char> {
var next = curr.toMutableList()
for (move in input) {
when (move[0]) {
's' -> {
val pos = move.drop(1).toInt()
next = (next.drop(next.size - pos) + next.take(next.size - pos)).toMutableList()
}
'x' -> {
val (a, b) = move.drop(1).split("/").map { it.toInt() }
next[a] = next[b].also { next[b] = next[a] }
}
'p' -> {
val (a, b) = move.drop(1).split("/").map { next.indexOf(it[0]) }
next[a] = next[b].also { next[b] = next[a] }
}
}
}
return next
}
}
fun main(args: Array<String>) {
val input = File("./input/2017/Day16_input.txt").readText().split(",")
println("Part One = ${Day16.solve(input)}")
println("Part Two = ${Day16.solve(input, 1_000_000_000)}")
}
| 0 | Kotlin | 1 | 1 | 9294b2cbbb13944d586449f6a20d49f03391991e | 1,348 | Advent_of_Code | MIT License |
src/Day02.kt | Kbzinho-66 | 572,299,619 | false | {"Kotlin": 34500} | private const val WIN = 6
private const val DRAW = 3
private const val LOSS = 0
private const val ROCK = 1
private const val PAPER = 2
private const val SCISSORS = 3
fun main() {
operator fun String.component1() = this[0] - 'A'
operator fun String.component2() = this[1]
operator fun String.component3() = this[2] - 'X'
fun part1(games: List<String>): Int {
// Linhas representam o que o oponente jogou; colunas, o que eu joguei
val points = arrayOf(
intArrayOf(ROCK + DRAW, PAPER + WIN, SCISSORS + LOSS),
intArrayOf(ROCK + LOSS, PAPER + DRAW, SCISSORS + WIN),
intArrayOf(ROCK + WIN, PAPER + LOSS, SCISSORS + DRAW),
)
var total = 0
games.forEach { round ->
val (opponent, _, mine) = round
total += points[opponent][mine]
}
return total
}
fun part2(games: List<String>): Int {
// Linhas continuam representando o que o oponente jogou, mas as colunas passam a ser o resultado do jogo
val points = arrayOf(
intArrayOf(LOSS + SCISSORS, DRAW + ROCK , WIN + PAPER),
intArrayOf(LOSS + ROCK , DRAW + PAPER , WIN + SCISSORS),
intArrayOf(LOSS + PAPER , DRAW + SCISSORS, WIN + ROCK),
)
var total = 0
games.forEach { round ->
val (opponent, _ , outcome) = round
total += points[opponent][outcome]
}
return total
}
// Testar os casos básicos
val testInput = readInput("../inputs/Day02_test")
sanityCheck(part1(testInput), 15)
sanityCheck(part2(testInput), 12)
val input = readInput("../inputs/Day02")
println("Parte 1 = ${part1(input)}")
println("Parte 2 = ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | e7ce3ba9b56c44aa4404229b94a422fc62ca2a2b | 1,776 | advent_of_code_2022_kotlin | Apache License 2.0 |
src/Day04.kt | morris-j | 573,197,835 | false | {"Kotlin": 7085} | fun main() {
fun createRange(value: String): IntRange {
val split = value.split("-")
val first = split[0].toInt()
val second = split[1].toInt()
return IntRange(first, second)
}
fun processInput(input: List<String>): List<Pair<IntRange, IntRange>> {
return input.map {
val split = it.split(",")
val first = createRange(split[0])
val second = createRange(split[1])
Pair(first, second)
}
}
fun part1(input: List<String>): Int {
var sum = 0
val processedInput = processInput(input)
processedInput.forEach {
if(it.first.contains(it.second.first) && it.first.contains(it.second.last)
|| it.second.contains(it.first.first) && it.second.contains(it.first.last)) {
sum += 1
}
}
return sum
}
fun part2(input: List<String>): Int {
var sum = 0
val processedInput = processInput(input)
processedInput.forEach {
if(it.first.contains(it.second.first) || it.first.contains(it.second.last)
|| it.second.contains(it.first.first) || it.second.contains(it.first.last)) {
sum += 1
}
}
return sum
}
val input = readInput("Day04")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | e3f2d02dad432dbc1b15c9e0eefa7b35ace0e316 | 1,390 | kotlin-advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/com/hj/leetcode/kotlin/problem886/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem886
/**
* LeetCode page: [886. Possible Bipartition](https://leetcode.com/problems/possible-bipartition/);
*/
class Solution {
/* Complexity:
* Time O(n+|dislikes|) and Space O(n+|dislikes|);
*/
fun possibleBipartition(n: Int, dislikes: Array<IntArray>): Boolean {
/* We reduce the problem to a two-coloring graph problem:
* 1) each person is a vertex in the graph;
* 2) dislike between people means an undirected edge between corresponding vertices;
* 3) grouping people is coloring the graph and the color of each vertex can have values 0, 1 and -1,
* where 0 means unknown, 1 and -1 represent two different colors (i.e. groups);
* The goal is to determine whether the graph can be colored in a way that each edge incidents at
* different color vertices.
*/
val edges = constructEdges(dislikes)
val vertexColor = IntArray(n + 1)
for (vertex in 1..n) {
if (vertexColor[vertex] == 0) {
val canBeColored = colorConnectedComponent(vertex, vertexColor, edges)
if (!canBeColored) return false
}
}
return true
}
private fun constructEdges(dislikes: Array<IntArray>): Map<Int, List<Int>> {
val edges = hashMapOf<Int, MutableList<Int>>()
for ((u, v) in dislikes) {
edges.computeIfAbsent(u) { mutableListOf() }.add(v)
edges.computeIfAbsent(v) { mutableListOf() }.add(u)
}
return edges
}
private fun colorConnectedComponent(source: Int, vertexColor: IntArray, edges: Map<Int, List<Int>>): Boolean {
val verticesAtCurrDepth = ArrayDeque<Int>()
vertexColor[source] = 1
verticesAtCurrDepth.addLast(source)
while (verticesAtCurrDepth.isNotEmpty()) {
repeat(verticesAtCurrDepth.size) {
val u = verticesAtCurrDepth.removeFirst()
val color = vertexColor[u]
val anotherColor = -color
val adjacencies = edges[u] ?: emptyList()
for (v in adjacencies) {
if (vertexColor[v] == color) return false
if (vertexColor[v] == anotherColor) continue
vertexColor[v] = anotherColor
verticesAtCurrDepth.addLast(v)
}
}
}
return true
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 2,460 | hj-leetcode-kotlin | Apache License 2.0 |
src/Day05.kt | vlsolodilov | 573,277,339 | false | {"Kotlin": 19518} | fun main() {
val testCrates: List<Stack<Char>> = listOf<Stack<Char>>(
mutableListOf('Z', 'N'),
mutableListOf('M', 'C', 'D'),
mutableListOf('P'),
)
val crates: List<Stack<Char>> = listOf<Stack<Char>>(
mutableListOf('N', 'S', 'D', 'C', 'V', 'Q', 'T'),
mutableListOf('M', 'F', 'V'),
mutableListOf('F', 'Q', 'W', 'D', 'P', 'N', 'H', 'M'),
mutableListOf('D', 'Q', 'R', 'T', 'F'),
mutableListOf('R', 'F', 'M', 'N', 'Q', 'H', 'V', 'B'),
mutableListOf('C', 'F', 'G', 'N', 'P', 'W', 'Q'),
mutableListOf('W', 'F', 'R', 'L', 'C', 'T'),
mutableListOf('T', 'Z', 'N', 'S'),
mutableListOf('M', 'S', 'D', 'J', 'R', 'Q', 'H', 'N'),
)
fun getRearrangementProcedure(procedure: String): RearrangementProcedure {
val procedureInput = procedure.split(" ")
return RearrangementProcedure(
count = procedureInput[1].toInt(),
from = procedureInput[3].toInt() - 1,
to = procedureInput[5].toInt() - 1,
)
}
fun doRearrangement(crates: List<Stack<Char>>, procedure: RearrangementProcedure) =
repeat(procedure.count) {
crates[procedure.to].push(crates[procedure.from].pop()!!)
}
fun doRearrangement2(crates: List<Stack<Char>>, procedure: RearrangementProcedure) {
crates[procedure.to] += crates[procedure.from].takeLast(procedure.count)
repeat(procedure.count) {
crates[procedure.from].pop()
}
}
fun getTopCrates(crates: List<Stack<Char>>): String =
crates.map { it.peek() }.joinToString("")
fun part1(crates: List<Stack<Char>>, input: List<String>): String {
val cratesCopy = crates.map { it.toMutableList() }.toMutableList()
input.map(::getRearrangementProcedure).forEach {
doRearrangement(cratesCopy, it)
}
return getTopCrates(cratesCopy)
}
fun part2(crates: List<Stack<Char>>, input: List<String>): String {
val cratesCopy = crates.map { it.toMutableList() }.toMutableList()
input.map(::getRearrangementProcedure).forEach {
doRearrangement2(cratesCopy, it)
}
return getTopCrates(cratesCopy)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
check(part1(testCrates, testInput) == "CMZ")
check(part2(testCrates, testInput) == "MCD")
val input = readInput("Day05")
println(part1(crates, input))
println(part2(crates, input))
}
data class RearrangementProcedure(val count: Int, val from: Int, val to: Int)
/**
* Stack as type alias of Mutable List
*/
typealias Stack<T> = MutableList<T>
/**
* Pushes item to [Stack]
* @param item Item to be pushed
*/
fun <T> Stack<T>.push(item: T) = add(item)
/**
* Pops (removes and return) last item from [Stack]
* @return item Last item if [Stack] is not empty, null otherwise
*/
fun <T> Stack<T>.pop(): T? = if (isNotEmpty()) removeAt(lastIndex) else null
/**
* Peeks (return) last item from [Stack]
* @return item Last item if [Stack] is not empty, null otherwise
*/
fun <T> Stack<T>.peek(): T? = if (isNotEmpty()) this[lastIndex] else null
| 0 | Kotlin | 0 | 0 | b75427b90b64b21fcb72c16452c3683486b48d76 | 3,243 | aoc22 | Apache License 2.0 |
src/Day21.kt | illarionov | 572,508,428 | false | {"Kotlin": 108577} | fun main() {
val testInput = readInput("Day21_test")
.map(String::parseYellingMonkey)
val input = readInput("Day21")
.map(String::parseYellingMonkey)
part1(testInput).also {
println("Part 1, test input: $it")
check(it == 152L)
}
part1(input).also {
println("Part 1, real input: $it")
check(it == 72664227897438L)
}
part2(testInput).also {
println("Part 2, test input: $it")
check(it == 301L)
}
part2(input).also {
println("Part 2, real input: $it")
check(it == 3916491093817)
}
}
private sealed class MonkeyJob {
data class Number(val value: Long) : MonkeyJob()
data class MathOperation(
val left: String,
val right: String,
val opSymbol: Char,
val op: (left: Long, right: Long) -> Long
) : MonkeyJob()
}
private data class Monkey2(
val id: String,
val op: MonkeyJob
)
private fun part1(input: List<Monkey2>): Long {
val set = input.associateBy(Monkey2::id)
fun getResultOfMonkey(id: String): Long {
val m = set[id] ?: error("Cannot find monkey $id")
return when (m.op) {
is MonkeyJob.MathOperation -> {
m.op.op(
getResultOfMonkey(m.op.left),
getResultOfMonkey(m.op.right)
)
}
is MonkeyJob.Number -> m.op.value
}
}
return getResultOfMonkey("root")
}
private fun part2(input: List<Monkey2>): Long {
val set = input.associateBy(Monkey2::id)
fun getResultOfMonkey(id: String): Long? {
val m = set[id] ?: error("Cannot find monkey $id")
if (id == "humn") {
return null
}
return when (m.op) {
is MonkeyJob.MathOperation -> {
val left = getResultOfMonkey(m.op.left)
val right = getResultOfMonkey(m.op.right)
if (left == null || right == null) {
return null
}
m.op.op(left, right)
}
is MonkeyJob.Number -> m.op.value
}
}
fun getResultOfHumn(id: String, expectedResult: Long): Long? {
val monkey = set[id]!!
if (monkey.id == "humn") {
return expectedResult
}
if (monkey.op is MonkeyJob.Number) {
error("No yelling monkeys except for human")
}
val op = monkey.op as MonkeyJob.MathOperation
val left = getResultOfMonkey(monkey.op.left)
val right = getResultOfMonkey(monkey.op.right)
if (left == null && right != null) {
val expectedResultFromLeft = when (op.opSymbol) {
'-' -> expectedResult + right
'+' -> expectedResult - right
'*' -> expectedResult / right
'/' -> expectedResult * right
else -> {
error("Unknown operation `$op`")
}
}
return getResultOfHumn(op.left, expectedResultFromLeft)
} else if (left != null && right == null) {
val expectedResultFromRight = when (op.opSymbol) {
'-' -> left - expectedResult
'+' -> expectedResult - left
'*' -> expectedResult / left
'/' -> left / expectedResult
else -> {
error("Unknown operation `$op`")
}
}
return getResultOfHumn(op.right, expectedResultFromRight)
} else {
error("Unsupported combination. left: $left, right: $right")
}
}
val rootMonkey = set["root"]!!
val left: Long? = getResultOfMonkey(
(rootMonkey.op as MonkeyJob.MathOperation).left
)
val right: Long? = getResultOfMonkey(
rootMonkey.op.right
)
val result = if (left == null && right != null) {
getResultOfHumn(rootMonkey.op.left, right)
} else if (left != null && right == null) {
getResultOfHumn(rootMonkey.op.right, left)
} else {
error("Unsupported combination on root: left = $left, right = $right")
}
return result!!
}
private val numberRegex = Regex("""(\w{4}): (\d+)""")
private val opRegex = Regex("""(\w{4}): (\w{4}) ([+\-*/]) (\w{4})""")
private fun String.parseYellingMonkey(): Monkey2 {
numberRegex.matchEntire(this)?.groupValues?.let {
return Monkey2(it[1], MonkeyJob.Number(it[2].toLong()))
}
opRegex.matchEntire(this)?.groupValues?.let {
return Monkey2(
it[1],
MonkeyJob.MathOperation(
left = it[2],
right = it[4],
opSymbol = it[3][0],
op = when (it[3]) {
"-" -> Long::minus
"+" -> Long::plus
"*" -> Long::times
"/" -> Long::div
else -> error("Unknown operation `$this`, `${it[2]}`")
}
)
)
}
error("Cannot parse `$this`")
} | 0 | Kotlin | 0 | 0 | 3c6bffd9ac60729f7e26c50f504fb4e08a395a97 | 5,069 | aoc22-kotlin | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/RangeSumQuery.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
/**
* Range Sum Query - Immutable
* @see <a href="https://leetcode.com/problems/range-sum-query-immutable/">Source</a>
*/
fun interface RangeSumQuery {
operator fun invoke(i: Int, j: Int): Int
}
class RangeSumQueryBruteForce(val nums: IntArray) : RangeSumQuery {
override operator fun invoke(i: Int, j: Int): Int {
var sum = 0
for (k in i..j) {
sum += nums[k]
}
return sum
}
}
class RangeSumQueryCaching(val nums: IntArray) : RangeSumQuery {
private val map: MutableMap<Pair<Int, Int>, Int> = HashMap()
init {
for (i in nums.indices) {
var sum = 0
for (j in i until nums.size) {
sum += nums[j]
map[i to j] = sum
}
}
}
override operator fun invoke(i: Int, j: Int): Int {
return map[i to j] ?: 0
}
}
class RangeSumQueryCachingOptimized(val nums: IntArray) : RangeSumQuery {
private val sum: IntArray = IntArray(nums.size + 1)
init {
for (i in nums.indices) {
sum[i + 1] = sum[i] + nums[i]
}
}
override operator fun invoke(i: Int, j: Int): Int {
return sum[j + 1] - sum[i]
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,854 | kotlab | Apache License 2.0 |
src/Day03.kt | jfiorato | 573,233,200 | false | null | fun main() {
val items = ".abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
fun part1(input: List<String>): Int {
var totalPriority = 0
for (line in input) {
val contents = line.toList()
val compartment1 = contents.take(contents.size/2)
val compartment2 = contents.takeLast(contents.size/2)
val shared = compartment1.intersect(compartment2)
totalPriority += items.indexOf(shared.first())
}
return totalPriority
}
fun part2(input: List<String>): Int {
var totalPriority = 0
val contentsIterator = input.iterator()
while (contentsIterator.hasNext()) {
val elf1 = contentsIterator.next().toSet()
val elf2 = contentsIterator.next().toSet()
val elf3 = contentsIterator.next().toSet()
val s1 = elf1.intersect(elf2)
val shared = s1.intersect(elf3)
totalPriority += items.indexOf(shared.first())
}
return totalPriority
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
val testInputB = readInput("Day03_testb")
check(part2(testInputB) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 4455a5e9c15cd067d2661438c680b3d7b5879a56 | 1,370 | kotlin-aoc-2022 | Apache License 2.0 |
leetcode/src/linkedlist/Q234.kt | zhangweizhe | 387,808,774 | false | null | package linkedlist
import linkedlist.kt.ListNode
fun main() {
// 234. 回文链表
// https://leetcode-cn.com/problems/palindrome-linked-list/
val createList = LinkedListUtil.createList(intArrayOf(1, 2, 1))
println(isPalindrome1(createList))
}
/**
* 把原链表反转,构造一个新链表,对比新旧链表的每个节点的值是否一样
* 时间复杂度O(n)
* 空间复杂度O(n)
*/
private fun isPalindrome(head: ListNode?): Boolean {
var cur = head
var newHead: ListNode? = null
while (cur != null) {
var newNode = ListNode(cur.`val`)
newNode.next = newHead
newHead = newNode
cur = cur.next
}
var tmp = newHead
while (tmp != null) {
println(tmp.`val`)
tmp = tmp.next
}
cur = head
while (cur != null && newHead != null) {
if (cur.`val` != newHead.`val`) {
return false
}
cur = cur.next
newHead = newHead.next
}
return true
}
/**
* 先找到右半部分的链表,将其反转,然后对比左右两半的链表,每个值是否一致
* 时间复杂度O(n)
* 空间复杂度O(1),反转是在原链表反转的,不消耗额外的空间
*/
fun isPalindrome1(head: ListNode?): Boolean {
val rightHalf = LinkedListUtil.getRightHalf(head)
var rightP = rightHalf
var leftP = head
rightP = LinkedListUtil.reverseListLocal(rightP)
while (rightP != null && leftP != null) {
if (rightP.`val` != leftP.`val`) {
return false
}
rightP = rightP.next
leftP = leftP.next
}
return true
}
| 0 | Kotlin | 0 | 0 | 1d213b6162dd8b065d6ca06ac961c7873c65bcdc | 1,635 | kotlin-study | MIT License |
src/main/kotlin/d8_SevenSegmentSearch/SevenSegmentSearch.kt | aormsby | 425,644,961 | false | {"Kotlin": 68415} | package d8_SevenSegmentSearch
import util.Input
import util.Output
fun main() {
Output.day(8, "Seven Segment Search")
val startTime = Output.startTime()
/*
// Regex works for P1, but it's slooooooow.
val allDisplayText = Input.parseAllText(filename = "/input/d8_seven_segment_displays.txt")
val uniqueSizeSegmentCount =
Regex("""(?<=\|.{0,})(?:\b\w{2}\b|\b\w{3}\b|\b\w{4}\b|\b\w{7}\b)""")
.findAll(allDisplayText)
.count()
*/
// I sorted the strings by char to use them as map keys! :)
val displayPatterns = Input.parseLines("/input/d8_seven_segment_displays.txt")
.map { str ->
val x = str.split(" | ")
Pair(
x[0].trim(' ').split(" ")
.map { item -> item.toSortedSet().joinToString("") },
x[1].trim(' ').split(" ")
.map { item -> item.toSortedSet().joinToString("") }
)
}
// For Part and Part 2 outputs
var uniqueSegmentsFound = 0
var outputSum = 0
// loop over display patterns
displayPatterns.forEach { pat ->
val displayMap = mutableMapOf<Int, String>()
// map known combos for 1, 4, 7, 8 in each patter
pat.first.forEach {
when (it.length) {
2 -> displayMap[1] = it
3 -> displayMap[7] = it
4 -> displayMap[4] = it
7 -> displayMap[8] = it
}
}
// count number of known segments in each display output (Part 1)
pat.second.forEach {
if (it in displayMap.values) uniqueSegmentsFound++
}
// deduce remaining segments and map
val fiveSegs = pat.first.filter { it.length == 5 } as MutableList
val sixSegs = pat.first.filter { it.length == 6 } as MutableList
// 9 is the only 6-segment number to contain the segments of 7 and 4
displayMap[9] = sixSegs.first { displayMap[7]!!.isInside(it) && displayMap[4]!!.isInside(it) }
sixSegs.remove(displayMap[9]!!)
// 0 is the only remaining 6-segment number to contain the segments of 7
displayMap[0] = sixSegs.first { displayMap[7]!!.isInside(it) }
sixSegs.remove(displayMap[0]!!)
// 6 is the only 6-segment number remaining
displayMap[6] = sixSegs.first()
// 3 is the only 5-segment number to contain the segments of 7
displayMap[3] = fiveSegs.first() { displayMap[7]!!.isInside(it) }
fiveSegs.remove(displayMap[3]!!)
// To obtain five, I got the diffs of 3, 0, and 6
// The remaining segments are inside 5's segments (but not 2's)
val fiveCheck = displayMap[3]!!.diff(displayMap[0]!!).diff(displayMap[6]!!)
displayMap[5] = fiveSegs.first { fiveCheck.isInside(it) }
fiveSegs.remove(displayMap[5]!!)
// 2 is the only 5-segment number remaining
displayMap[2] = fiveSegs.first()
// determine output value and add to total sum
// flipped the map for easy pattern/number correlation
val flippedMap = displayMap.entries.associateBy({ it.value }) { it.key }
outputSum += pat.second.fold("") { acc, s -> acc + flippedMap[s] }.toInt()
}
Output.part(1, "Count of 1s, 4s, 7s, and 8s", uniqueSegmentsFound)
Output.part(2, "Sum of All Outputs", outputSum)
Output.executionTime(startTime)
}
/**
* Returns a String of all segments that are not shared
* between the two given strings.
*/
fun String.diff(s2: String): String {
val group = (this + s2).groupingBy { it }.eachCount()
val minValue = group.minOf { it.value }
return group.filter { it.value == minValue }.keys.joinToString("")
}
/**
* Checks if each segment is shared by a given pattern
*/
fun String.isInside(s: String): Boolean {
this.forEach {
if (!s.contains(it))
return false
}
return true
} | 0 | Kotlin | 1 | 1 | 193d7b47085c3e84a1f24b11177206e82110bfad | 3,932 | advent-of-code-2021 | MIT License |
src/day14/Day14.kt | HGilman | 572,891,570 | false | {"Kotlin": 109639, "C++": 5375, "Python": 400} | package day14
import lib.Path
import lib.Point2D
import readInput
fun main() {
val day = 14
val testInput = readInput("day$day/testInput")
// check(part1(testInput) == 1)
// check(part2(testInput) == 1)
val input = readInput("day$day/input")
// println(part1(input))
println(part2(input))
}
fun part1(input: List<String>): Int {
val paths: List<Path> = input.map {
Path(it.split(" -> ").map {
val (x, y) = it.split(",").map { it.toInt() }
Point2D(x, y)
})
}
val minX: Int = paths.minOf { it.points.minOf { it.x } }
val maxX = paths.maxOf { it.points.maxOf { it.x } }
val minY = 0
val maxY = paths.maxOf { it.points.maxOf { it.y } }
val field = List(maxY + 1) {
mutableListOf<PlayObject>()
}
for (y in 0 until maxY + 1) {
for (x in 0 until maxX - minX + 1) {
field[y].add(Air)
}
}
paths.forEach { path ->
path.getAllPoints().forEach { p ->
field[p.y][p.x - minX] = Rock
}
}
field[0][500 - minX] = Source
val startPosition = Point2D(500 - minX, 0)
var sand = startPosition
var shouldAddSand = true
var amountAdded = 0
while (shouldAddSand) {
if (field[sand.y + 1][sand.x] == Air) {
// down pos is not blocked, go down
sand = Point2D(sand.x, sand.y + 1)
// println("go down, newPos: $sand")
} else if (field[sand.y + 1][sand.x - 1] == Air) {
// left is not blocked go diagonally left
sand = Point2D(sand.x - 1, sand.y + 1)
// println("go left, newPos: $sand")
} else if (field[sand.y + 1][sand.x + 1] == Air) {
// right is not blocked to diagonally right
sand = Point2D(sand.x + 1, sand.y + 1)
// println("go right, newPos: $sand")
} else {
// all option tried
field[sand.y][sand.x] = Sand
// println("added sand, $sand")
sand = startPosition
amountAdded++
}
// sand is out
if (sand.x > maxX - minX || sand.x - 1 < 0 || sand.y + 1 > maxY) {
shouldAddSand = false
}
}
for (y in 0 until maxY + 1) {
var line = ""
for (x in minX until maxX + 1) {
line += field[y][x - minX].symbol
}
println(line)
}
println("added: $amountAdded")
return 1
}
fun part2(input: List<String>): Int {
val paths1: List<Path> = input.map {
Path(it.split(" -> ").map {
val (x, y) = it.split(",").map { it.toInt() }
Point2D(x, y)
})
}
val maxY1 = paths1.maxOf { it.points.maxOf { it.y } }
val floor = Path(
listOf(
Point2D(500 - (maxY1 + 2), maxY1 + 2),
Point2D(500 + maxY1 + 2, maxY1 + 2)
)
)
val maxY = maxY1 + 2
val paths = paths1 + floor
val minX = -maxY + 500
val maxX = maxY + 500
val field = List(maxY + 1) {
mutableListOf<PlayObject>()
}
for (y in 0 until maxY + 1) {
for (x in 0 until maxX - minX + 1) {
field[y].add(Air)
}
}
paths.forEach { path ->
path.getAllPoints().forEach { p ->
field[p.y][p.x - minX] = Rock
}
}
field[0][500 - minX] = Source
val startPosition = Point2D(500 - minX, 0)
var sand = startPosition
var shouldAddSand = true
var amountAdded = 0
for (y in 0 until maxY + 1) {
var line = ""
for (x in minX until maxX + 1) {
line += field[y][x - minX].symbol
}
println(line)
}
println()
println()
while (shouldAddSand) {
if (field[sand.y + 1][sand.x] == Air) {
// down pos is not blocked, go down
sand = Point2D(sand.x, sand.y + 1)
// println("go down, newPos: $sand")
} else if (field[sand.y + 1][sand.x - 1] == Air) {
// left is not blocked go diagonally left
sand = Point2D(sand.x - 1, sand.y + 1)
// println("go left, newPos: $sand")
} else if (field[sand.y + 1][sand.x + 1] == Air) {
// right is not blocked to diagonally right
sand = Point2D(sand.x + 1, sand.y + 1)
// println("go right, newPos: $sand")
} else {
// all option tried
field[sand.y][sand.x] = Sand
// println("added sand, $sand")
amountAdded++
if (sand == startPosition) {
break
}
sand = startPosition
}
// sand is out
if (sand.x + 1 > maxX - minX || sand.x - 1 < 0 || sand.y + 1 > maxY) {
shouldAddSand = false
}
}
for (y in 0 until maxY + 1) {
var line = ""
for (x in minX until maxX + 1) {
line += field[y][x - minX].symbol
}
println(line)
}
println("added: $amountAdded")
return 1
}
sealed class PlayObject(val symbol: Char)
object Sand : PlayObject('o')
object Source : PlayObject('+')
object Air : PlayObject('.')
object Rock : PlayObject('#') | 0 | Kotlin | 0 | 1 | d05a53f84cb74bbb6136f9baf3711af16004ed12 | 5,196 | advent-of-code-2022 | Apache License 2.0 |
src/Day16.kt | syncd010 | 324,790,559 | false | null | class Day16: Day {
private fun convert(input: List<String>) : List<Int> {
return input[0].map { it - '0' }
}
override fun solvePartOne(input: List<String>): Int {
var signal = convert(input)
val basePattern = listOf(0, 1, 0, -1)
val newSignal = MutableList(signal.size) { '0' }
for (phase in 1..100) {
for (i in signal.indices) {
val pattern = basePattern
.map { value -> List(i + 1) { value } }
.flatten()
val patternSeq = generateSequence(1) { (it + 1) % pattern.size }
.take(signal.size)
.map { pattern[it] }.toList()
newSignal[i] = signal.zip(patternSeq).sumBy { (a, b) -> a * b }.toString().last()
}
signal = newSignal.map { it - '0' }
}
return digitsToNum(signal.take(8))
}
override fun solvePartTwo(input: List<String>): Int {
val inputSignal = convert(input).toMutableList()
val startIdx = digitsToNum(inputSignal.take(7))
val repeatCount = 10000
// This solution doesn't work for small indexes...
if (startIdx < (inputSignal.size * repeatCount) / 2) return -1
val signal = List(repeatCount) { inputSignal }.flatten().drop(startIdx).toIntArray()
val signalSum = IntArray(signal.size) { 0 }
for (phase in 1..100) {
signalSum[0] = signal.sum()
for (idx in 1 until signal.size)
signalSum[idx] = signalSum[idx - 1] - signal[idx - 1]
for (idx in signal.indices) signal[idx] = signalSum[idx] % 10
}
return digitsToNum(signal.take(8))
}
} | 0 | Kotlin | 0 | 0 | 11c7c7d6ccd2488186dfc7841078d9db66beb01a | 1,787 | AoC2019 | Apache License 2.0 |
src/main/kotlin/_2023/Day11.kt | novikmisha | 572,840,526 | false | {"Kotlin": 145780} | package _2023
import Coordinate
import Day
import InputReader
import atCoordinates
import kotlin.math.abs
class Day11 : Day(2023, 11) {
override val firstTestAnswer = 374
override val secondTestAnswer = 0
override fun first(input: InputReader): Int {
val space = input.asLines().toMutableList()
val galaxies = space.flatMapIndexed { row: Int, line: String ->
line.mapIndexedNotNull { column, c ->
val coordinate = Coordinate(row, column)
if (space.atCoordinates(coordinate) == '#') {
coordinate
} else {
null
}
}
}
val emptyRows = space.mapIndexedNotNull { row, line ->
if (line.all { it == '.' }) {
row
} else {
null
}
}
val emptyColumns = mutableListOf<Int>()
for (column in space.first().indices) {
if (space.all { it[column] == '.' }) {
emptyColumns.add(column)
}
}
return galaxies.windowed(galaxies.size, partialWindows = true) {
val startingGalaxy = it.first()
val otherGalaxies = it.drop(1)
otherGalaxies.map { galaxy ->
var distance = abs(startingGalaxy.x - galaxy.x) + abs(startingGalaxy.y - galaxy.y)
val xRange = listOf(startingGalaxy.x, galaxy.x).sorted()
distance += emptyRows.count { it in xRange.first()..xRange.last() }
val yRange = listOf(startingGalaxy.y, galaxy.y).sorted()
distance += emptyColumns.count { it in yRange.first()..yRange.last() }
distance
}
}.flatten().sum()
}
override fun second(input: InputReader): Long {
val space = input.asLines().toMutableList()
val galaxies = space.flatMapIndexed { row: Int, line: String ->
line.mapIndexedNotNull { column, c ->
val coordinate = Coordinate(row, column)
if (space.atCoordinates(coordinate) == '#') {
coordinate
} else {
null
}
}
}
val emptyRows = space.mapIndexedNotNull { row, line ->
if (line.all { it == '.' }) {
row
} else {
null
}
}
val emptyColumns = mutableListOf<Int>()
for (column in space.first().indices) {
if (space.all { it[column] == '.' }) {
emptyColumns.add(column)
}
}
return galaxies.windowed(galaxies.size, partialWindows = true) {
val startingGalaxy = it.first()
val otherGalaxies = it.drop(1)
otherGalaxies.map { galaxy ->
var distance = (abs(startingGalaxy.x - galaxy.x) + abs(startingGalaxy.y - galaxy.y)).toLong()
val xRange = listOf(startingGalaxy.x, galaxy.x).sorted()
distance += (emptyRows.count { it in xRange.first()..xRange.last() } * 999999L)
val yRange = listOf(startingGalaxy.y, galaxy.y).sorted()
distance += (emptyColumns.count { it in yRange.first()..yRange.last() } * 999999L)
distance
}
}.flatten().sum()
}
}
fun main() {
Day11().solve(skipTest = true)
} | 0 | Kotlin | 0 | 0 | 0c78596d46f3a8bf977bf356019ea9940ee04c88 | 3,436 | advent-of-code | Apache License 2.0 |
dcp_kotlin/src/main/kotlin/dcp/day292/day292.kt | sraaphorst | 182,330,159 | false | {"C++": 577416, "Kotlin": 231559, "Python": 132573, "Scala": 50468, "Java": 34742, "CMake": 2332, "C": 315} | package dcp.day292
// day292.kt
// By <NAME>, 2020.
import java.util.*
typealias Vertex = Int
typealias AdjacencyList = List<Vertex>
typealias AdjacencyGraph = List<AdjacencyList>
typealias Partition = Set<Vertex>
data class Bipartition(val partition1: Partition, val partition2: Partition) {
init {
require(partition1.intersect(partition2).isEmpty())
require(partition1.isNotEmpty())
require(partition2.isNotEmpty())
}
}
/**
* The idea here is that a solution corresponds to a bipartite graph, with each partition representing a team.
* We can find out if a graph is bipartite by doing a DFS on it to see if it has a 2-colouring, i.e. has
* no cycles of odd length. The graph may not be connected, so we must take this into account.
*
* We assume for simplicity that the graph is over the vertices {0, ..., n-1}.
*
* This should have complexity O(V + E), but it may be higher because of our choice of use of data structures, i.e.
* immutable sets for partitions, which requires copying.
*/
fun AdjacencyGraph.findBipartition(): Bipartition? {
// If there are one or fewer vertices, clearly there is no bipartition.
if (size <= 1)
return null
// Make sure all values in the adjacency lists are in range [0,size).
require(all { (it.min() ?: 0) >= 0 })
require(all { (it.max() ?: 0) < size })
// Unfortunately, we're going to be using mutability here since graph algorithms don't lend themselves well to
// immutability.
val visited: MutableList<Boolean> = MutableList(size){false}
val stack: Stack<Vertex> = Stack()
stack.push(0)
// If colour is true, this corresponds to partition1; else, partition2.
tailrec
fun dfs(partition1: Partition = emptySet(), partition2: Partition = emptySet(), colour: Boolean = true): Bipartition? {
if (stack.isEmpty()) {
val firstUnvisited = visited.indexOfFirst { !it }
return when {
firstUnvisited == -1 && partition1.isNotEmpty() && partition2.isNotEmpty() -> Bipartition(partition1, partition2)
firstUnvisited == -1 -> null
else -> {
// Make sure to add the next vertex to the smaller partition so as to avoid cases like a
// completely disconnected graph putting all vertices in the same partition, which would be invalid.
stack.push(firstUnvisited)
dfs(partition1, partition2, partition1.size < partition2.size)
}
}
}
// Visit the top of the stack, make sure none of its neighbours will have the same colour as it.
val v = stack.peek()
// Add v to the appropriate partition.
val newPartition1 = if (!visited[v] && colour) partition1 + v else partition1
val newPartition2 = if (!visited[v] && !colour) partition2 + v else partition2
if (visited[v]) {
stack.pop()
} else {
visited[v] = true
if (colour && get(v).any{ it in partition1 }) return null
if (!colour && get(v).any{ it in partition2 }) return null
}
// Find the first unvisited neighbour of v, if it exists, and push it on the stack.
val uIdx = get(v).indexOfFirst { !visited[it] }
if (uIdx != -1) {
// Get the element from v's adjacency list.
val u = get(v)[uIdx]
stack.push(u)
}
return dfs(newPartition1, newPartition2, v in newPartition2)
}
return dfs()
}
| 0 | C++ | 1 | 0 | 5981e97106376186241f0fad81ee0e3a9b0270b5 | 3,572 | daily-coding-problem | MIT License |
src/aoc22/Day11_Simple.kt | mihassan | 575,356,150 | false | {"Kotlin": 123343} | @file:Suppress("PackageDirectoryMismatch")
package aoc22.day11_simple
import lib.Maths.divisibleBy
import lib.Solution
import lib.Strings.extractInts
import lib.Strings.extractLongs
import lib.Strings.words
data class Monkey(
val startingItems: List<Long>,
val operation: (Long) -> Long,
val divisor: Long,
val test: (Long) -> Int,
) {
companion object {
fun parse(str: String): Monkey {
val lines = str.lines()
val startingItems = lines[1].extractLongs()
val (_, op, operand) = lines[2].substringAfter("new = ").words()
val operation: (Long) -> Long = when (op) {
"*" -> { old -> old * (operand.toLongOrNull() ?: old) }
"+" -> { old -> old + (operand.toLongOrNull() ?: old) }
else -> error("Invalid input")
}
val (divisor, trueTarget, falseTarget) = lines.takeLast(3).joinToString().extractInts()
val test: (Long) -> Int = { worryLevel ->
if (worryLevel divisibleBy divisor.toLong()) trueTarget else falseTarget
}
return Monkey(startingItems, operation, divisor.toLong(), test)
}
}
}
typealias Input = List<Monkey>
typealias Output = Long
private val solution = object : Solution<Input, Output>(2022, "Day11") {
val ROUNDS = mapOf(Part.PART1 to 20, Part.PART2 to 10000)
override fun parse(input: String): Input = input.split("\n\n").map { Monkey.parse(it) }
override fun format(output: Output): String = "$output"
override fun solve(part: Part, input: Input): Output {
val modulus = input.map { it.divisor }.toSet().reduce(Long::times)
val inspections = LongArray(input.size)
val monkeysWithCurrentItems = input.map { it.startingItems.toMutableList() }
repeat(ROUNDS[part]!!) {
monkeysWithCurrentItems.forEachIndexed { idx, items ->
val monkey = input[idx]
items.forEach { item ->
val worryLevel = when(part) {
Part.PART1 -> monkey.operation(item) / 3L
Part.PART2 -> monkey.operation(item) % modulus
}
val nextMonkey = monkey.test(worryLevel)
monkeysWithCurrentItems[nextMonkey] += worryLevel
inspections[idx]++
}
items.clear()
}
}
return inspections.sortedDescending().take(2).reduce(Long::times)
}
}
fun main() = solution.run()
| 0 | Kotlin | 0 | 0 | 698316da8c38311366ee6990dd5b3e68b486b62d | 2,309 | aoc-kotlin | Apache License 2.0 |
src/day04/Day04.kt | barbulescu | 572,834,428 | false | {"Kotlin": 17042} | package day04
import readInput
fun main() {
val pairs = readInput("day04/Day04")
.map { it.split(",") }
.onEach { require(it.size == 2) { "expected 2 ranges" } }
.map { parseRange(it[0]) to parseRange(it[1]) }
val fullyOverlapped = pairs
.count(::isFullyOverlapped)
println("Fully included $fullyOverlapped")
val partiallyOverlapped = pairs
.count { it.first.intersect(it.second).isNotEmpty() }
println("Partially included $partiallyOverlapped")
}
fun parseRange(range: String): IntRange {
val parts = range.split("-")
val from = parts[0].toInt()
val to = parts[1].toInt()
return from.rangeTo(to)
}
fun isFullyOverlapped(ranges: Pair<IntRange, IntRange>) : Boolean {
val first = ranges.first.toSortedSet()
val second = ranges.second.toSortedSet()
val intersect = first.intersect(second)
return intersect == first || intersect == second
}
| 0 | Kotlin | 0 | 0 | 89bccafb91b4494bfe4d6563f190d1b789cde7a4 | 937 | aoc-2022-in-kotlin | Apache License 2.0 |
src/main/kotlin/day21.kt | gautemo | 572,204,209 | false | {"Kotlin": 78294} | import shared.getText
fun main() {
val input = getText("day21.txt")
println(day21A(input))
println(day21B(input))
}
fun day21A(input: String) = yellGame(input)
fun day21B(input: String) = yellGame(input, true)
private fun yellGame(input: String, withUnkown: Boolean = false): Long {
val monkeys = input.lines().associate {
it.split(":").let { (monkey, yell) -> monkey to yell.trim() }
}.toMutableMap()
if(withUnkown) monkeys["humn"] = "x"
fun replace(monkey: String): String {
if(monkeys[monkey]!!.toLongOrNull() != null || monkeys[monkey]!! == "x") return monkeys[monkey]!!
val (left, symbol, right) = monkeys[monkey]!!.split(" ")
val replaceLeft = replace(left)
val replaceRight = replace(right)
if(replaceLeft.toLongOrNull() != null && replaceRight.toLongOrNull() != null) {
return when(symbol) {
"+" -> (replaceLeft.toLong() + replaceRight.toLong()).toString()
"-" -> (replaceLeft.toLong() - replaceRight.toLong()).toString()
"*" -> (replaceLeft.toLong() * replaceRight.toLong()).toString()
else -> (replaceLeft.toLong() / replaceRight.toLong()).toString()
}
}
return "($replaceLeft$symbol$replaceRight)"
}
if(!withUnkown) return replace("root").toLong()
val (left, _, right) = monkeys["root"]!!.split(" ")
var equationLeft = replace(left)
var equationRight = replace(right).toLong()
while (equationLeft != "x") {
equationLeft = equationLeft.removePrefix("(").removeSuffix(")")
val symbolAt = equationLeft.rootSymbolAt()
val symbol = equationLeft[symbolAt]
val a = equationLeft.substring(0, symbolAt)
val b = equationLeft.substring(symbolAt+1, equationLeft.length)
if(a.toLongOrNull() == null) {
when(symbol) {
'+' -> equationRight -= b.toLong()
'-' -> equationRight += b.toLong()
'*' -> equationRight /= b.toLong()
'/' -> equationRight *= b.toLong()
}
equationLeft = a
} else {
when(symbol) {
'+' -> equationRight -= a.toLong()
'-' -> equationRight = a.toLong() - equationRight
'*' -> equationRight /= a.toLong()
'/' -> equationRight = a.toLong() / equationRight
}
equationLeft = b
}
}
return equationRight
}
private fun String.rootSymbolAt(): Int {
for((i,c) in withIndex()){
if(listOf('+', '-', '*', '/').contains(c) && take(i).count { it == '(' } == take(i).count { it == ')' }){
return i
}
}
throw Exception("should have root symbol")
} | 0 | Kotlin | 0 | 0 | bce9feec3923a1bac1843a6e34598c7b81679726 | 2,766 | AdventOfCode2022 | MIT License |
src/day-7.kt | drademacher | 160,820,401 | false | null | import java.io.File
fun main(args: Array<String>) {
println("part 1: " + partOne())
println("part 2: " + partTwo())
}
private fun partOne(): String {
var result = ""
val inDegreeGraph = parseFile()
do {
val verticesWithNoInDegree = getVerticesWithNoInDegree(inDegreeGraph)
val vertexWithSmallestLetter = verticesWithNoInDegree.min()!!
result += vertexWithSmallestLetter
removeFromGraph(inDegreeGraph, vertexWithSmallestLetter)
} while (inDegreeGraph.keys.isNotEmpty())
return result
}
private fun partTwo(): Int {
val NUMBER_OF_WORKER = 5
var ticks = 0
val inDegreeGraph = parseFile()
val workers = IntArray(NUMBER_OF_WORKER)
val processingVertexOfWorker = CharArray(NUMBER_OF_WORKER)
while(inDegreeGraph.isNotEmpty()) {
val verticesToBeProcess = getVerticesWithNoInDegree(inDegreeGraph)
.subtract(processingVertexOfWorker.toList())
.toMutableList()
val freeWorker = getFreeWorkerIndices(workers).take(verticesToBeProcess.size)
for ((vertexIndex, workerIndex) in freeWorker.withIndex()) {
val vertexToProcess = verticesToBeProcess[vertexIndex]
workers[workerIndex] = processingTime(vertexToProcess)
processingVertexOfWorker[workerIndex] = vertexToProcess
}
ticks += 1
for (workerIndex in 0 until NUMBER_OF_WORKER) {
workers[workerIndex] -= 1
if (workers[workerIndex] == 0) {
val finishedVertex = processingVertexOfWorker[workerIndex]
processingVertexOfWorker[workerIndex] = '-'
removeFromGraph(inDegreeGraph, finishedVertex)
}
}
}
return ticks
}
private fun parseFile(): HashMap<Char, MutableList<Char>> {
val rawFile = File("res/day-7.txt").readText()
.split("\n")
.filter { it != "" }
val inDegreeGraph = hashMapOf<Char, MutableList<Char>>()
('A'..'Z').forEach { c -> inDegreeGraph[c] = mutableListOf() }
for (line in rawFile) {
inDegreeGraph[line[36]]!!.add(line[5])
}
return inDegreeGraph
}
private fun getVerticesWithNoInDegree(inDegreeGraph: HashMap<Char, MutableList<Char>>): List<Char> {
return inDegreeGraph
.filter { it.value.isEmpty() }
.keys
.toList()
.sorted()
}
private fun removeFromGraph(graph: HashMap<Char, MutableList<Char>>, vertex: Char) {
graph.remove(vertex)
graph.forEach { key, value -> value.remove(vertex) }
}
private fun processingTime(vertex: Char): Int {
return 61 + ('A'..'Z').indexOf(vertex)
}
private fun getFreeWorkerIndices(workers: IntArray): List<Int> {
return workers.withIndex().filter { it.value <= 0 }.map { it.index }.sorted()
} | 0 | Kotlin | 0 | 0 | a7f04450406a08a5d9320271148e0ae226f34ac3 | 2,812 | advent-of-code-2018 | MIT License |
src/main/kotlin/nl/tiemenschut/aoc/y2023/day2.kt | tschut | 723,391,380 | false | {"Kotlin": 61206} | package nl.tiemenschut.aoc.y2023
import nl.tiemenschut.aoc.lib.dsl.aoc
import nl.tiemenschut.aoc.lib.dsl.day
import nl.tiemenschut.aoc.lib.dsl.parser.AsListOfStrings
fun main() {
aoc(AsListOfStrings) {
puzzle { 2023 day 2 }
data class Turn(val red: Int, val green: Int, val blue: Int)
data class Game(val id: Int, val turns: List<Turn>)
val gameIdRegex = "Game (.*):".toRegex()
val redRegex = "(\\d*) red".toRegex()
val greenRegex = "(\\d*) green".toRegex()
val blueRegex = "(\\d*) blue".toRegex()
fun String.toGame() = Game(
id = gameIdRegex.find(this)!!.groupValues[1].toInt(),
turns = split(":")[1].split(";").map { turn ->
Turn(
red = redRegex.find(turn)?.groupValues?.last()?.toInt() ?: 0,
green = greenRegex.find(turn)?.groupValues?.last()?.toInt() ?: 0,
blue = blueRegex.find(turn)?.groupValues?.last()?.toInt() ?: 0,
)
})
part1 { input ->
input
.map { it.toGame() }
.filter {
it.turns.all { turn ->
turn.red <= 12 && turn.green <= 13 && turn.blue <= 14
}
}
.sumOf { it.id }
}
part2 { input ->
input
.map { it.toGame() }
.sumOf { game ->
game.turns.maxOf { it.red } * game.turns.maxOf { it.green } * game.turns.maxOf { it.blue }
}
}
}
}
| 0 | Kotlin | 0 | 1 | a1ade43c29c7bbdbbf21ba7ddf163e9c4c9191b3 | 1,606 | aoc-2023 | The Unlicense |
src/Day02.kt | rk012 | 574,169,156 | false | {"Kotlin": 9389} | private const val ROCK = 0
private const val PAPER = 1
private const val SCISSORS = 2
fun main() {
fun Char.asItem() = when (this) {
in "AX" -> ROCK
in "BY" -> PAPER
in "CZ" -> SCISSORS
else -> fail()
}
fun itemBeats(item: Int) = when (item) {
ROCK -> SCISSORS
PAPER -> ROCK
SCISSORS -> PAPER
else -> fail()
}
fun itemLoses(item: Int) = when (item) {
ROCK -> PAPER
PAPER -> SCISSORS
SCISSORS -> ROCK
else -> fail()
}
fun itemScore(item: Int) = when (item) {
ROCK -> 1
PAPER -> 2
SCISSORS -> 3
else -> fail()
}
fun List<Pair<Int, Int>>.getScore() = fold(0) { acc, (opp, play) ->
acc + itemScore(play) + when (opp) {
itemBeats(play) -> 6
play -> 3
else -> 0
}
}
fun part1(input: List<String>) = input.map {
it[0].asItem() to it[2].asItem()
}.getScore()
fun part2(input: List<String>) = input.map {
it[0].asItem() to it[2]
}.map { (opp, result) ->
opp to when (result) {
'X' -> itemBeats(opp)
'Y' -> opp
'Z' -> itemLoses(opp)
else -> fail()
}
}.getScore()
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | bfb4c56c4d4c8153241fa6aa6ae0e829012e6679 | 1,556 | advent-of-code-2022 | Apache License 2.0 |
src/Day23.kt | wgolyakov | 572,463,468 | false | null | private enum class Direction {
NORTH, SOUTH, WEST, EAST
}
fun main() {
fun parse(input: List<String>): Set<Pair<Int, Int>> {
val elves = mutableSetOf<Pair<Int, Int>>()
for (y in input.indices)
for (x in input[y].indices)
if (input[y][x] == '#') elves.add(x to y)
return elves
}
val checkPositionsToStay = listOf(-1 to -1, 0 to -1, 1 to -1, -1 to 0, 1 to 0, -1 to 1, 0 to 1, 1 to 1)
val directionsOrder = mapOf(
Direction.NORTH to listOf(Direction.NORTH, Direction.SOUTH, Direction.WEST, Direction.EAST),
Direction.SOUTH to listOf(Direction.SOUTH, Direction.WEST, Direction.EAST, Direction.NORTH),
Direction.WEST to listOf(Direction.WEST, Direction.EAST, Direction.NORTH, Direction.SOUTH),
Direction.EAST to listOf(Direction.EAST, Direction.NORTH, Direction.SOUTH, Direction.WEST),
)
val checkPositionsToMove = mapOf(
Direction.NORTH to listOf(-1 to -1, 0 to -1, 1 to -1),
Direction.SOUTH to listOf(-1 to 1, 0 to 1, 1 to 1),
Direction.WEST to listOf(-1 to -1, -1 to 0, -1 to 1),
Direction.EAST to listOf(1 to -1, 1 to 0, 1 to 1),
)
val positionToMove = mapOf(
Direction.NORTH to (0 to -1),
Direction.SOUTH to (0 to 1),
Direction.WEST to (-1 to 0),
Direction.EAST to (1 to 0),
)
val nextDirection = mapOf(
Direction.NORTH to Direction.SOUTH,
Direction.SOUTH to Direction.WEST,
Direction.WEST to Direction.EAST,
Direction.EAST to Direction.NORTH,
)
fun round(elves: Set<Pair<Int, Int>>, firstDirection: MutableList<Direction>): Set<Pair<Int, Int>> {
// first half of round
val nextElves = mutableSetOf<Pair<Int, Int>>()
val propose = mutableMapOf<Pair<Int, Int>, MutableList<Pair<Int, Int>>>()
for ((x, y) in elves) {
if (checkPositionsToStay.all { (dx, dy) -> x + dx to y + dy !in elves }) {
nextElves.add(x to y)
} else {
var canMove = false
for (direction in directionsOrder[firstDirection[0]]!!) {
if (checkPositionsToMove[direction]!!.all { (dx, dy) -> x + dx to y + dy !in elves }) {
val (dx, dy) = positionToMove[direction]!!
propose.getOrPut(x + dx to y + dy) { mutableListOf() }.add(x to y)
canMove = true
break
}
}
if (!canMove) nextElves.add(x to y)
}
}
// second half of round
for ((tile, fromList) in propose) {
if (fromList.size == 1)
nextElves.add(tile)
else
nextElves.addAll(fromList)
}
firstDirection[0] = nextDirection[firstDirection[0]]!!
return nextElves
}
fun part1(input: List<String>): Int {
var elves = parse(input)
val firstDirection = mutableListOf(Direction.NORTH)
for (round in 0 until 10)
elves = round(elves, firstDirection)
val xMin = elves.minOf { it.first }
val xMax = elves.maxOf { it.first }
val yMin = elves.minOf { it.second }
val yMax = elves.maxOf { it.second }
var emptyCount = 0
for (x in xMin..xMax)
for (y in yMin..yMax)
if (x to y !in elves) emptyCount++
return emptyCount
}
fun part2(input: List<String>): Int {
var elves = parse(input)
val firstDirection = mutableListOf(Direction.NORTH)
var round = 0
do {
val nextElves = round(elves, firstDirection)
round++
val changed = nextElves != elves
elves = nextElves
} while (changed)
return round
}
val testInput = readInput("Day23_test")
check(part1(testInput) == 110)
check(part2(testInput) == 20)
val input = readInput("Day23")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 789a2a027ea57954301d7267a14e26e39bfbc3c7 | 3,395 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/dec24/Main.kt | dladukedev | 318,188,745 | false | null | package dec24
enum class Direction {
NORTHWEST,
NORTHEAST,
SOUTHWEST,
SOUTHEAST,
EAST,
WEST
}
fun parseInput(input: String): List<List<Direction>> {
return input.lines()
.map { it.toCharArray().toList() }
.map { line ->
line.foldIndexed(emptyList<Direction>()) { index, acc, direction ->
when (direction) {
'n' -> {
when (val foundChar = line.getOrNull(index + 1)) {
'e' -> acc + Direction.NORTHEAST
'w' -> acc + Direction.NORTHWEST
null -> throw IndexOutOfBoundsException(index + 1)
else -> throw Exception("Invalid Character $foundChar")
}
}
's' -> {
when (val foundChar = line.getOrNull(index + 1)) {
'e' -> acc + Direction.SOUTHEAST
'w' -> acc + Direction.SOUTHWEST
null -> throw IndexOutOfBoundsException(index + 1)
else -> throw Exception("Invalid Character $foundChar")
}
}
'e' -> {
if (index == 0 || (line[index - 1] != 'n' && line[index - 1] != 's')) {
acc + Direction.EAST
} else {
acc
}
}
'w' -> {
if (index == 0 || (line[index - 1] != 'n' && line[index - 1] != 's')) {
acc + Direction.WEST
} else {
acc
}
}
else -> throw Exception("Invalid Character $direction")
}
}
}
}
data class TileLocation(val x: Int, val y: Int) {
val neighbors by lazy {
listOf(
TileLocation(x - 1, y + 2),
TileLocation(x - 1, y - 2),
TileLocation(x + 1, y + 2),
TileLocation(x + 1, y - 2),
TileLocation(x + 2, y),
TileLocation(x - 2, y)
)
}
}
tailrec fun findTile(directions: List<Direction>, currentLocation: TileLocation = TileLocation(0,0)): TileLocation {
if(directions.isEmpty()) {
return currentLocation
}
val updatedLocation = when(directions.first()) {
Direction.NORTHWEST -> TileLocation(currentLocation.x - 1, currentLocation.y + 2)
Direction.NORTHEAST -> TileLocation(currentLocation.x + 1, currentLocation.y + 2)
Direction.SOUTHWEST -> TileLocation(currentLocation.x - 1, currentLocation.y - 2)
Direction.SOUTHEAST -> TileLocation(currentLocation.x + 1, currentLocation.y - 2)
Direction.EAST -> currentLocation.copy(x = currentLocation.x + 2)
Direction.WEST -> currentLocation.copy(x = currentLocation.x - 2)
}
return findTile(directions.drop(1), updatedLocation)
}
fun flipTile(directions: List<Direction>, blackTiles: HashSet<TileLocation>): HashSet<TileLocation>{
val tileLocation = findTile(directions)
if(blackTiles.contains(tileLocation)) {
blackTiles.remove(tileLocation)
} else {
blackTiles.add(tileLocation)
}
return blackTiles
}
fun getBlackTiles(tileLocations: List<List<Direction>>): HashSet<TileLocation> {
return tileLocations.fold(HashSet()) { acc, tileLocationDirections ->
flipTile(tileLocationDirections, acc)
}
}
fun countBlackTiles(tileLocations: List<List<Direction>>): Int {
return getBlackTiles(tileLocations).size
}
sealed class Tile(val location: TileLocation) {
data class Black(val tileLocation: TileLocation): Tile(tileLocation)
data class White(val tileLocation: TileLocation): Tile(tileLocation)
}
fun updateFloor(blackTiles: HashSet<TileLocation>): HashSet<TileLocation> {
return blackTiles.flatMap {
it.neighbors
}.map {
if(blackTiles.contains(it)) {
Tile.Black(it)
} else {
Tile.White(it)
}
}.fold(HashSet<TileLocation>()) { acc, tile ->
val blackNeighborsCount = tile.location.neighbors.count {
blackTiles.contains(it)
}
when(tile) {
is Tile.Black -> {
if(blackNeighborsCount in 1..2) {
acc.add(tile.location)
}
acc
}
is Tile.White -> {
if(blackNeighborsCount == 2) {
acc.add(tile.location)
}
acc
}
}
}
}
fun livingFloor(days: Int, blackTiles: HashSet<TileLocation>): HashSet<TileLocation> {
return (1..days).fold(blackTiles) {acc, i ->
updateFloor(acc)
}
}
fun main() {
val tileLocations = parseInput(input)
println("------------ PART 1 ------------")
val blackTilesCount = countBlackTiles(tileLocations)
println("result: $blackTilesCount")
println("------------ PART 2 ------------")
val livingFloorBlackTilesCount = livingFloor(100, getBlackTiles(tileLocations)).size
println("result: $livingFloorBlackTilesCount")
} | 0 | Kotlin | 0 | 0 | d4591312ddd1586dec6acecd285ac311db176f45 | 5,316 | advent-of-code-2020 | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/FrequencySort.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 java.util.PriorityQueue
/**
* 451. Sort Characters By Frequency
* @see <a href="https://leetcode.com/problems/sort-characters-by-frequency/">Source</a>
*/
fun interface FrequencySort {
operator fun invoke(str: String): String
}
class FrequencyBucketSort : FrequencySort {
override operator fun invoke(str: String): String {
val map: MutableMap<Char, Int> = HashMap()
for (character in str.toCharArray()) {
map[character] = map.getOrDefault(character, 0) + 1
}
val bucket: Array<MutableList<Char>> = Array(str.length + 1) {
mutableListOf()
}
for (key in map.keys) {
val frequency = map[key] ?: 0
bucket[frequency].add(key)
}
val sb = StringBuilder()
for (pos in bucket.indices.reversed()) {
for (character in bucket[pos]) {
for (i in 0 until pos) {
sb.append(character)
}
}
}
return sb.toString()
}
}
class FrequencySortPQ : FrequencySort {
override operator fun invoke(str: String): String {
val map: MutableMap<Char, Int> = HashMap()
for (character in str.toCharArray()) {
map[character] = map.getOrDefault(character, 0) + 1
}
val pq: PriorityQueue<Map.Entry<Char, Int>> = PriorityQueue { a, b -> b.value - a.value }
pq.addAll(map.entries)
val sb = StringBuilder()
while (pq.isNotEmpty()) {
val (key, value) = pq.poll()
for (i in 0 until value) sb.append(key)
}
return sb.toString()
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,287 | kotlab | Apache License 2.0 |
src/main/kotlin/com/github/solairerove/algs4/leprosorium/strings/MaxDistanceBetweenSameElements.kt | solairerove | 282,922,172 | false | {"Kotlin": 251919} | package com.github.solairerove.algs4.leprosorium.strings
import kotlin.math.max
/**
* We are given a string S consisting of N lowercase letters.
* A sequence of two adjacent letters inside a string is called a digram.
* The distance between two digrams is the distance between the first letter of the first digram
* and the first letter of the second digram.
*
* For example, in string S "akcmz" the distance between digrams "k" and "mz" is 2.
*
* We want to find the maximum distance between the furthest identical digrams inside string S.
*
* If there are no two identical digrams inside S, your function should S return -1.
*
* Examples:
*
* 1. Given S = "aakmaakmakda" your function should return 7.
* The furthest identical digrams are "ak's, starting in positions 2 and 9.
*
* 2. Given S = "aaa" your function should return 1.
* The furthest identical digrams are "aa's starting at positions 1 and 2.
*
* 3. Given S = "civic" your function should return -1.
* There are no two identical digrams in S.
*
* Write an efficient algorithm for the following assumptions:
* N is an integer within the range (2..300,000];
* string S is made only of lowercase letters (a-z).
*/
// O(n) time | O(n) space
fun maximumIdenticalAdjacentDistance(s: String): Int {
if (s.length == 2) return -1
val pairToFirstIdx = mutableMapOf<String, Int>()
var distance = -1
for (i in 0 until s.length - 1) {
val pair = "${s[i]}${s[i + 1]}"
if (pair in pairToFirstIdx) {
distance = max(distance, i - pairToFirstIdx[pair]!!)
} else {
pairToFirstIdx[pair] = i
}
}
return distance
}
| 1 | Kotlin | 0 | 3 | 64c1acb0c0d54b031e4b2e539b3bc70710137578 | 1,668 | algs4-leprosorium | MIT License |
src/twentytwentytwo/day13/Day13.kt | colinmarsch | 571,723,956 | false | {"Kotlin": 65403, "Python": 6148} | package twentytwentytwo.day13
import readInput
fun main() {
fun part1(input: List<String>): Int {
var total = 0
input.chunked(3).forEachIndexed { index, pair ->
val left = parse(pair[0])
val right = parse(pair[1])
if (inOrder(left, right)) {
total += index + 1
}
}
return total
}
fun part2(input: List<String>): Int {
var total = 0
val items = input.filter { it.isNotEmpty() }.map { parse(it) }.toMutableList()
val first = ListItem(mutableListOf(ListItem(mutableListOf(IntItem(2)))))
val second = ListItem(mutableListOf(ListItem(mutableListOf(IntItem(6)))))
items.add(first)
items.add(second)
items.sort()
return (items.indexOf(first) + 1) * (items.indexOf(second) + 1)
}
val input = readInput("day13", "Day13_input")
println(part1(input))
println(part2(input))
}
interface Item : Comparable<Item> {
override fun compareTo(other: Item): Int
}
class IntItem(val value: Int) : Item {
override fun compareTo(other: Item): Int {
return when (other) {
is IntItem -> this.value.compareTo(other.value)
is ListItem -> {
return ListItem(mutableListOf(this)).compareTo(other)
}
else -> throw IllegalStateException()
}
}
}
class ListItem(val list: MutableList<Item> = mutableListOf()) : Item {
override fun compareTo(other: Item): Int {
when (other) {
is IntItem -> {
return this.compareTo(ListItem(mutableListOf(other)))
}
is ListItem -> {
list.forEachIndexed { index, item ->
if (index >= other.list.size) return 1
val compare = item.compareTo(other.list[index])
if (compare != 0)
return compare
}
return if (list.size == other.list.size) 0 else -1
}
else -> throw IllegalStateException()
}
}
}
private fun inOrder(left: ListItem, right: ListItem): Boolean {
return left <= right
}
private fun parse(line: String): ListItem {
val stack = ArrayDeque<MutableList<Any>>()
var current = mutableListOf<Any>()
var number = -1
fun flushNumber() {
if (number != -1) {
current.add(number)
number = -1
}
}
line.forEach { char ->
when (char) {
'[' -> {
stack.addLast(current)
current = mutableListOf()
stack.last().add(current)
}
']' -> {
flushNumber()
current = stack.removeLast()
}
',' -> flushNumber()
else -> number = number.coerceAtLeast(0) * 10 + (char - '0')
}
}
return ListItem((current[0] as List<*>).toItem().toMutableList())
}
private fun List<*>.toItem(): List<Item> = map {
if (it is List<*>) {
ListItem(it.toItem().toMutableList())
} else {
IntItem(it as Int)
}
}
| 0 | Kotlin | 0 | 0 | bcd7a08494e6db8140478b5f0a5f26ac1585ad76 | 3,161 | advent-of-code | Apache License 2.0 |
src/main/aoc2023/Day2.kt | nibarius | 154,152,607 | false | {"Kotlin": 963896} | package aoc2023
class Day2(input: List<String>) {
private val gameData = input.associate { line ->
//line: "Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green"
val gameId = line.substringAfter(" ").substringBefore(":").toInt()
val sets = line.substringAfter(": ").split("; ")
//sets: "3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green"
val y = sets.map { set ->
// set: "3 blue, 4 red"
val colors = set.split(", ")
val x = colors.associate { color ->
val pairs = color.split(" ")
pairs.last() to pairs.first().toInt()
}
CubeSet(
x.getOrDefault("red", 0),
x.getOrDefault("blue", 0),
x.getOrDefault("green", 0)
)
}
gameId to Game(y)
}
private data class Game(val sets: List<CubeSet>) {
private fun minCubeSet() = CubeSet(
sets.maxOf { it.red },
sets.maxOf { it.blue },
sets.maxOf { it.green },
)
fun power() = minCubeSet().let { it.red * it.blue * it.green }
fun isPossible() = sets.all { it.red <= 12 && it.green <= 13 && it.blue <= 14 }
}
private data class CubeSet(val red: Int, val blue: Int, val green: Int)
fun solvePart1(): Int {
return gameData.filterValues { it.isPossible() }.keys.sum()
}
fun solvePart2(): Int {
return gameData.values.sumOf { it.power() }
}
} | 0 | Kotlin | 0 | 6 | f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22 | 1,502 | aoc | MIT License |
src/Day02.kt | ZiomaleQ | 573,349,910 | false | {"Kotlin": 49609} | fun main() {
fun part1(input: List<String>): Int {
var score = 0
for (line in input) {
val enemyMove = toEnum(line[0])
val myMove = toEnum(line[2])
score += (myMove.ordinal + 1) + isWin(enemyMove, myMove)
}
return score
}
fun part2(input: List<String>): Int {
var score = 0
for (line in input) {
val enemyMove = toEnum(line[0])
val outcome = toOutcome(line[2])
val myMove = getMove(enemyMove, outcome)
score += (myMove.ordinal + 1) + isWin(enemyMove, myMove)
}
return score
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
/* 6 for the win, 3 for the draw, 0 for lose */
fun isWin(left: Moves, right: Moves): Int {
if (left == right) return 3
if (left == Moves.SCISSORS && right == Moves.PAPER) return 0
if (left == Moves.SCISSORS && right == Moves.ROCK) return 6
if (left == Moves.ROCK && right == Moves.PAPER) return 6
if (left == Moves.ROCK && right == Moves.SCISSORS) return 0
if (left == Moves.PAPER && right == Moves.SCISSORS) return 6
if (left == Moves.PAPER && right == Moves.ROCK) return 0
return 0
}
fun getMove(left: Moves, outcome: Outcome): Moves {
if (outcome == Outcome.DRAW) return left
if (outcome == Outcome.LOSE) {
if (left == Moves.SCISSORS) return Moves.PAPER
if (left == Moves.ROCK) return Moves.SCISSORS
if (left == Moves.PAPER) return Moves.ROCK
}
if (outcome == Outcome.WIN) {
if (left == Moves.SCISSORS) return Moves.ROCK
if (left == Moves.ROCK) return Moves.PAPER
if (left == Moves.PAPER) return Moves.SCISSORS
}
return Moves.ROCK
}
//[A, B, C, X, Y, Z]
//[65, 66, 67, 88, 89, 90]
fun toEnum(char: Char): Moves = when (char.code - 65 - if (char.code > 88) 23 else 0) {
0 -> Moves.ROCK
1 -> Moves.PAPER
2 -> Moves.SCISSORS
//Impossible anyway
else -> Moves.ROCK
}
fun toOutcome(char: Char): Outcome = when (char.code - 88) {
0 -> Outcome.LOSE
1 -> Outcome.DRAW
2 -> Outcome.WIN
//Impossible anyway
else -> Outcome.LOSE
}
enum class Moves {
ROCK, PAPER, SCISSORS
}
enum class Outcome {
DRAW, LOSE, WIN
} | 0 | Kotlin | 0 | 0 | b8811a6a9c03e80224e4655013879ac8a90e69b5 | 2,466 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/Day05.kt | brigham | 573,127,412 | false | {"Kotlin": 59675} | import java.util.ArrayDeque
import java.util.Deque
import java.util.regex.Pattern
data class Instruction(val times: Int, val from: Int, val to: Int)
fun main() {
fun parse(input: List<String>): Pair<List<Deque<Char>>, List<Instruction>> {
val stacks = mutableListOf<Deque<Char>>()
fun ensureSize(n: Int) {
if (stacks.size < n) {
for (i in (stacks.size until n)) {
stacks.add(ArrayDeque())
}
}
}
val lines = input.iterator()
var line = lines.next()
while (line[1] != '1') {
for (i in (1..line.length step 4)) {
if (line[i].isWhitespace()) {
continue
}
val crate = line[i]
val which = (i - 1) / 4
ensureSize(which + 1)
stacks[which].addLast(crate)
}
line = lines.next()
}
val last = line[line.length - 1].digitToInt()
check(last == stacks.size)
val instructions = mutableListOf<Instruction>()
val pattern = Pattern.compile("move (\\d+) from (\\d+) to (\\d+)")
while (lines.hasNext()) {
line = lines.next()
if (line.isBlank()) {
continue
}
val match = pattern.matcher(line)
check(match.matches()) { "no match for $line" }
val times = match.group(1).toInt()
val from = match.group(2).toInt() - 1
val to = match.group(3).toInt() - 1
instructions.add(Instruction(times, from, to))
}
return stacks.toList() to instructions.toList()
}
fun part1(input: List<String>): String {
val (stacks, instructions) = parse(input)
for (instruction in instructions) {
for (i in 0 until instruction.times) {
stacks[instruction.to].push(checkNotNull(stacks[instruction.from].pop()))
}
}
return stacks.map { it.peek() }.joinToString("")
}
fun part2(input: List<String>): String {
val (stacks, instructions) = parse(input)
for (instruction in instructions) {
val holder = ArrayDeque<Char>(instruction.times)
for (i in 0 until instruction.times) {
holder.push(checkNotNull(stacks[instruction.from].pop()))
}
while (holder.isNotEmpty()) {
stacks[instruction.to].push(holder.pop())
}
}
return stacks.map { it.peek() }.joinToString("")
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | b87ffc772e5bd9fd721d552913cf79c575062f19 | 2,882 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/me/grison/aoc/y2020/Day17.kt | agrison | 315,292,447 | false | {"Kotlin": 267552} | package me.grison.aoc.y2020
import me.grison.aoc.*
class Day17 : Day(17, 2020) {
override fun title() = "Conway Cubes"
override fun partOne() = (0..5).fold(loadCubes()) { g, _ -> g.evolve() }.count()
override fun partTwo() = (0..5).fold(loadCubes(true)) { g, _ -> g.evolve() }.count()
private fun loadCubes(hyper: Boolean = false) = mutableSetOf<Position>().let {
inputList.forEachIndexed { x, line ->
line.forEachIndexed { y, state ->
if (state == '#') it.add(Position(x, y, 0))
}
}
Cubes(it, hyper)
}
}
data class Position(val x: Int, val y: Int, val z: Int, val w: Int = 0)
data class Cubes(val cubes: Set<Position>, val hyper: Boolean = false) {
fun count() = cubes.size
fun evolve(): Cubes {
val nextCubes = mutableSetOf<Position>()
val (xRange, yRange, zRange, wRange) = allRanges()
for (x in xRange)
for (y in yRange)
for (z in zRange)
for (w in wRange) {
val n = countLiveNeighbours(x, y, z, w)
val p = Position(x, y, z, w)
if (n == 3) nextCubes.add(p)
else if (p in cubes && (n == 2 || n == 3)) nextCubes.add(p)
}
return Cubes(nextCubes, hyper)
}
private fun countLiveNeighbours(x: Int, y: Int, z: Int, w: Int): Int {
var total = 0
for (xx in -1..1)
for (yy in -1..1)
for (zz in -1..1)
for (ww in (if (hyper) -1..1 else 0..0)) // iterate also on w when hyper
if (!(xx == 0 && yy == 0 && zz == 0 && ww == 0)) // avoid self!!
if (Position(xx + x, yy + y, zz + z, w + ww) in cubes)
total += 1
return total
}
private fun allRanges() = mutableListOf<IntRange>().let { ranges ->
ranges.add(cubes.minOf { it.x } - 1..cubes.maxOf { it.x } + 1)
ranges.add(cubes.minOf { it.y } - 1..cubes.maxOf { it.y } + 1)
ranges.add(cubes.minOf { it.z } - 1..cubes.maxOf { it.z } + 1)
// part2: if hyper then same as x,y,z, otherwise a range of 1
ranges.add(if (hyper) cubes.minOf { it.w } - 1..cubes.maxOf { it.w } + 1
else 0..0)
ranges
}
} | 0 | Kotlin | 3 | 18 | ea6899817458f7ee76d4ba24d36d33f8b58ce9e8 | 2,375 | advent-of-code | Creative Commons Zero v1.0 Universal |
src/leetcodeProblem/leetcode/editor/en/NextGreaterElementI.kt | faniabdullah | 382,893,751 | false | null | //The next greater element of some element x in an array is the first greater
//element that is to the right of x in the same array.
//
// You are given two distinct 0-indexed integer arrays nums1 and nums2, where
//nums1 is a subset of nums2.
//
// For each 0 <= i < nums1.length, find the index j such that nums1[i] == nums2[
//j] and determine the next greater element of nums2[j] in nums2. If there is no
//next greater element, then the answer for this query is -1.
//
// Return an array ans of length nums1.length such that ans[i] is the next
//greater element as described above.
//
//
// Example 1:
//
//
//Input: nums1 = [4,1,2], nums2 = [1,3,4,2]
//Output: [-1,3,-1]
//Explanation: The next greater element for each value of nums1 is as follows:
//- 4 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so
//the answer is -1.
//- 1 is underlined in nums2 = [1,3,4,2]. The next greater element is 3.
//- 2 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so
//the answer is -1.
//
//
// Example 2:
//
//
//Input: nums1 = [2,4], nums2 = [1,2,3,4]
//Output: [3,-1]
//Explanation: The next greater element for each value of nums1 is as follows:
//- 2 is underlined in nums2 = [1,2,3,4]. The next greater element is 3.
//- 4 is underlined in nums2 = [1,2,3,4]. There is no next greater element, so
//the answer is -1.
//
//
//
// Constraints:
//
//
// 1 <= nums1.length <= nums2.length <= 1000
// 0 <= nums1[i], nums2[i] <= 10⁴
// All integers in nums1 and nums2 are unique.
// All the integers of nums1 also appear in nums2.
//
//
//
//Follow up: Could you find an O(nums1.length + nums2.length) solution? Related
//Topics Array Hash Table Stack Monotonic Stack 👍 1005 👎 76
package leetcodeProblem.leetcode.editor.en
class NextGreaterElementI {
fun solution() {
}
//below code will be used for submission to leetcode (using plugin of course)
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
fun nextGreaterElement(nums1: IntArray, nums2: IntArray): IntArray {
for (i in nums1.indices) {
val valueSame = nums1[i]
var underLine = false
for (j in nums2.indices) {
if (underLine && nums2[j] > valueSame) {
nums1[i] = nums2[j]
break
}
if (nums2[j] == valueSame) {
underLine = true
}
if (underLine && j == nums2.lastIndex) {
nums1[i] = -1
}
}
}
return nums1
}
}
//leetcode submit region end(Prohibit modification and deletion)
}
fun main() {
}
| 0 | Kotlin | 0 | 6 | ecf14fe132824e944818fda1123f1c7796c30532 | 2,822 | dsa-kotlin | MIT License |
2023/src/main/kotlin/org/suggs/adventofcode/Day05SeedFertilizer.kt | suggitpe | 321,028,552 | false | {"Kotlin": 156836} | package org.suggs.adventofcode
import org.slf4j.LoggerFactory
import kotlin.time.measureTime
object Day05SeedFertilizer {
private val log = LoggerFactory.getLogger(this::class.java)
fun calculateLowestLocationNumber(data: List<String>): Long {
val seeds = extractSeedsFrom(data)
val ranges = extractDataRangesFrom(data)
return seeds.minOf { calculateLocationValueFor(it, ranges) }
.also { log.debug("Part 1: $it") }
}
fun calculateLowestLocationNumberFromRange(data: List<String>): Long {
val seeds = extractSeedRangesFrom(data)
val ranges = extractDataRangesFrom(data)
var min = Long.MAX_VALUE
seeds.forEach { it ->
val timeTaken = measureTime {
it.forEach { seedNum ->
min = minOf(calculateLocationValueFor(seedNum, ranges), min)
}
}
log.debug("Last range took $timeTaken min value $min")
}
return min
.also { log.debug("Part 2: $it") }
}
private fun extractSeedRangesFrom(data: List<String>) =
data.first().split(":").last().trim().split(" ").map { it.toLong() }.chunked(2).map { it.first()..<it.first() + it.last() }
private fun extractSeedsFrom(data: List<String>): List<Long> = data.first().split(":").last().trim().split(" ").map { it.toLong() }
private fun extractDataRangesFrom(data: List<String>) = data.drop(1).map { RangePairSet(it) }
private fun calculateLocationValueFor(seedValue: Long, ranges: List<RangePairSet>): Long {
if (ranges.isEmpty()) return seedValue
return calculateLocationValueFor(ranges.first().mapSrcToDest(seedValue), ranges.drop(1))
}
}
data class RangePairSet(val rangePairs: List<RangePair>) {
fun mapSrcToDest(num: Long): Long {
rangePairs.forEach {
if (it.src.contains(num))
return it.getDestValueFor(num)
}
return num
}
companion object {
operator fun invoke(rangeBlock: String): RangePairSet {
return RangePairSet(rangeBlock.split("\n").drop(1).fold(listOf<RangePair>()) { sum, elem -> sum + RangePair(elem) })
}
}
}
data class RangePair(val src: LongRange, val dest: LongRange) {
fun getDestValueFor(num: Long) = dest.first + (num - src.first)
companion object {
operator fun invoke(rangeCode: String): RangePair {
val data = rangeCode.trim().split(" ")
return RangePair(
data[1].toLong().rangeTo(data[1].toLong() + (data[2].toLong() - 1L)),
data[0].toLong().rangeTo(data[0].toLong() + (data[2].toLong() - 1L))
)
}
}
}
| 0 | Kotlin | 0 | 0 | 9485010cc0ca6e9dff447006d3414cf1709e279e | 2,716 | advent-of-code | Apache License 2.0 |
src/Day20.kt | nordberg | 573,769,081 | false | {"Kotlin": 47470} | import kotlin.math.abs
fun wrapAroundIndex(index: Int, indexWrapLimit: Int, movingUp: Boolean): Int {
if (index in 0..indexWrapLimit) {
return if (movingUp) {
if (index == indexWrapLimit) {
0
} else {
index
}
} else {
if (index == 0) {
indexWrapLimit
} else {
index
}
}
}
if (index > indexWrapLimit) {
return wrapAroundIndex(index - indexWrapLimit, indexWrapLimit, movingUp)
}
return wrapAroundIndex(index + indexWrapLimit, indexWrapLimit, movingUp)
}
fun wrapAroundIndex2(index: Int, indexWrapLimit: Int, movingUp: Boolean): Int {
val newIndex = if (index > 2 * indexWrapLimit) {
indexWrapLimit - (index % indexWrapLimit)
} else if (index < -indexWrapLimit) {
(indexWrapLimit - ((abs(index) % indexWrapLimit)))
} else if (index > indexWrapLimit) {
(index - indexWrapLimit)
} else if (index < 0) {
(indexWrapLimit + index)
} else {
index
}
if (newIndex == 0) {
return indexWrapLimit
}
check(newIndex in 0..indexWrapLimit) {
"0 <= $newIndex <= $indexWrapLimit"
}
if (movingUp) {
return newIndex - 1
}
return newIndex
}
fun main() {
data class CoordWithId(val value: Int, val id: Int)
fun part1(input: List<Int>): Int {
val coordinatesWithId = input.mapIndexed { index, i -> CoordWithId(i, index) }
val decryptedCoordinates = coordinatesWithId.toMutableList()
coordinatesWithId.forEach { coordinateWithId ->
val oldIndexForCoord = decryptedCoordinates.indexOfFirst { it.id == coordinateWithId.id }
val newIndexForCoord = wrapAroundIndex(
oldIndexForCoord + coordinateWithId.value,
coordinatesWithId.indices.max().toInt(),
coordinateWithId.value > 0
)
decryptedCoordinates.removeAt(oldIndexForCoord)
decryptedCoordinates.add(newIndexForCoord, coordinateWithId)
check(decryptedCoordinates[newIndexForCoord].id == coordinateWithId.id) {
"Expected $coordinateWithId at $newIndexForCoord but found ${decryptedCoordinates[newIndexForCoord]}"
}
}
val indexOfZero = decryptedCoordinates.indexOfFirst { it.value == 0 }
return listOf(1000, 2000, 3000).sumOf {
decryptedCoordinates[(indexOfZero + it) % decryptedCoordinates.size].value
}
}
fun part2(input: List<String>): Int {
return 5
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day20_test").map { it.toInt() }
val testAnswer = part1(testInput)
check(testAnswer == 3) {
"Expected 3, got $testAnswer"
}
val input = readInput("Day20").map { it.toInt() }
val answer = part1(input)
check(answer < 15733) {
"Expected $answer to be lower than 15733"
}
check(answer > 941) {
"Expected $answer to be higher than 15733"
}
check(answer != 7770) {
"Answer is not 7770"
}
check(answer != 4263) {
"Answer is not 4263"
}
check(answer != 8254) {
"Answer is not 8254"
}
println(answer)
//println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 3de1e2b0d54dcf34a35279ba47d848319e99ab6b | 3,383 | aoc-2022 | Apache License 2.0 |
grind-75-kotlin/src/main/kotlin/TwoSum.kt | Codextor | 484,602,390 | false | {"Kotlin": 27206} | /**
* Given an array of integers nums and an integer target,
* return indices of the two numbers such that they add up to target.
*
* You may assume that each input would have exactly one solution, and you may not use the same element twice.
*
* You can return the answer in any order.
*
*
*
* Example 1:
*
* Input: nums = [2,7,11,15], target = 9
* Output: [0,1]
* Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
* Example 2:
*
* Input: nums = [3,2,4], target = 6
* Output: [1,2]
* Example 3:
*
* Input: nums = [3,3], target = 6
* Output: [0,1]
*
*
* Constraints:
*
* 2 <= nums.length <= 10^4
* -10^9 <= nums[i] <= 10^9
* -10^9 <= target <= 10^9
* Only one valid answer exists.
*
*
* Follow-up: Can you come up with an algorithm that is less than O(n2) time complexity?
* @see <a href="https://leetcode.com/problems/two-sum/">LeetCode</a>
*/
fun twoSum(nums: IntArray, target: Int): IntArray {
val map = HashMap<Int, Int>()
/*
* Based on the assumption that each input would have exactly one solution, we can safely override the values of
* repeated keys, knowing they won't be part of the solution
*/
for (index in nums.indices) {
map[nums[index]] = index
}
for (index in nums.indices) {
val targetComplementIndex = map.get(target - nums[index])
/*
* Since we're not allowed to use the same element twice, we need to ensure that the index of the current
* element is not the same as the index of the element we're looking for
*/
if (targetComplementIndex != null && targetComplementIndex != index) {
return intArrayOf(index, targetComplementIndex)
}
}
return intArrayOf()
}
| 0 | Kotlin | 0 | 0 | 87aa60c2bf5f6a672de5a9e6800452321172b289 | 1,748 | grind-75 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/NumSubmatrixSumTarget.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
/**
* 1074. Number of Submatrices That Sum to Target
* @see <a href="https://leetcode.com/problems/number-of-submatrices-that-sum-to-target/">Source</a>
*/
fun interface NumSubmatrixSumTarget {
operator fun invoke(matrix: Array<IntArray>, target: Int): Int
}
class NumSubmatrixSumTargetSolution : NumSubmatrixSumTarget {
override operator fun invoke(matrix: Array<IntArray>, target: Int): Int {
var res = 0
val m = matrix.size
val n = matrix[0].size
// Compute prefix sum for each row
for (i in 0 until m) {
for (j in 1 until n) {
matrix[i][j] += matrix[i][j - 1]
}
}
// Iterate over all pairs of columns and count submatrices with sum equal to target
val counter = HashMap<Int, Int>()
for (i in 0 until n) {
for (j in i until n) {
counter.clear()
counter[0] = 1
var cur = 0
for (k in 0 until m) {
cur += matrix[k][j] - if (i > 0) matrix[k][i - 1] else 0
res += counter.getOrDefault(cur - target, 0)
counter[cur] = counter.getOrDefault(cur, 0) + 1
}
}
}
return res
}
}
class NumSubmatrixSumTargetSolution2 : NumSubmatrixSumTarget {
override fun invoke(matrix: Array<IntArray>, target: Int): Int {
val prefixSumMatrix = calculatePrefixSum(matrix)
return countSubmatrixSums(prefixSumMatrix, target)
}
private fun calculatePrefixSum(matrix: Array<IntArray>): Array<IntArray> {
val m = matrix.size
val n = matrix[0].size
val prefixSumMatrix = Array(m) { IntArray(n) }
for (row in 0 until m) {
for (col in 0 until n) {
prefixSumMatrix[row][col] = matrix[row][col] + if (col > 0) prefixSumMatrix[row][col - 1] else 0
}
}
return prefixSumMatrix
}
private fun countSubmatrixSums(prefixSumMatrix: Array<IntArray>, target: Int): Int {
val m = prefixSumMatrix.size
val n = prefixSumMatrix[0].size
var count = 0
for (colStart in 0 until n) {
for (colEnd in colStart until n) {
for (rowStart in 0 until m) {
var sum = 0
for (rowEnd in rowStart until m) {
sum += prefixSumMatrix[rowEnd][colEnd] - if (colStart > 0) {
prefixSumMatrix[rowEnd][colStart - 1]
} else {
0
}
if (sum == target) {
count++
}
}
}
}
}
return count
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 3,463 | kotlab | Apache License 2.0 |
src/main/kotlin/solutions/day16/Day16.kt | Dr-Horv | 112,381,975 | false | null |
package solutions.day16
import solutions.Solver
class TwoWayMap<K, V> {
private val keyMap = mutableMapOf<K, V>()
private val valueMap = mutableMapOf<V, K>()
fun put(key: K, value: V) {
keyMap.put(key, value)
valueMap.put(value, key)
}
fun putAll(map: TwoWayMap<K, V>) {
map.entries().forEach {
put(it.key, it.value)
}
}
fun entries(): MutableSet<MutableMap.MutableEntry<K, V>> {
return keyMap.entries
}
fun size(): Int {
return keyMap.size
}
fun getValue(key: K): V {
return keyMap.getValue(key)
}
fun getKey(value: V): K {
return valueMap.getValue(value)
}
fun copy(): TwoWayMap<K, V> {
val newMap = TwoWayMap<K, V>()
keyMap.forEach { k, v -> newMap.put(k, v) }
return newMap
}
}
class Day16: Solver {
override fun solve(input: List<String>, partTwo: Boolean): String {
val symbolTransforms: TwoWayMap<String, String> = TwoWayMap()
val indexTransforms: TwoWayMap<Int, Int> = TwoWayMap()
val a = 'a'.toInt()
(0 until 16).forEach {
val strChar = (a + it).toChar().toString()
symbolTransforms.put(strChar, strChar)
indexTransforms.put(it, it)
}
input.first()
.split(",")
.forEach {
val type = it[0]
val rest = it.substring(1)
when(type) {
's' -> addSpinTransform(indexTransforms, rest.toInt())
'x' -> swapValues(indexTransforms, rest.split("/").map(String::toInt))
'p' -> swapValues(symbolTransforms, rest.split("/"))
}
}
if(!partTwo) {
return computeFinalString(a, indexTransforms, symbolTransforms)
}
val (newIndex, newSymbols) = do1000Iterations(indexTransforms, symbolTransforms)
val (secondIndex, secondSymbols) = do1000Iterations(newIndex, newSymbols)
val (finalIndex, finalSymbols) = do1000Iterations(secondIndex, secondSymbols)
return computeFinalString(a, finalIndex, finalSymbols)
}
private fun do1000Iterations(indexTransforms: TwoWayMap<Int, Int>, symbolTransforms: TwoWayMap<String, String>): Pair<TwoWayMap<Int, Int>, TwoWayMap<String, String>> {
val indexTransformsOverTime = mutableListOf<TwoWayMap<Int, Int>>(indexTransforms)
val symbolTransformsOverTime = mutableListOf<TwoWayMap<String, String>>(symbolTransforms)
for (i in 1 until 1000) {
indexTransformsOverTime.add(indexTransforms.copy())
symbolTransformsOverTime.add(symbolTransforms.copy())
}
val newIndex = combine(indexTransformsOverTime)
val newSymbols = combine(symbolTransformsOverTime)
return Pair(newIndex, newSymbols)
}
private fun <K> combine(transforms: MutableList<TwoWayMap<K, K>>): TwoWayMap<K, K> {
val newMap = transforms.removeAt(0)
transforms.forEach { t ->
newMap.entries().forEach {
val newValue= t.getValue(it.value)
newMap.put(it.key, newValue)
}
}
return newMap
}
private fun computeFinalString(a: Int, indexTransforms: TwoWayMap<Int, Int>, symbolTransforms: TwoWayMap<String, String>): String {
val res: Array<String> = Array(16, { "" })
(0 until 16).forEach {
val strChar = (a + it).toChar().toString()
val newIndex = indexTransforms.getValue(it)
val newChar = symbolTransforms.getValue(strChar)
res[newIndex] = newChar
}
return res.joinToString("")
}
private fun <K, V> swapValues(twoWayMap: TwoWayMap<K, V>, pair: List<V>) {
val (i1, i2) = pair
val i1Key = twoWayMap.getKey(i1)
val i2Key = twoWayMap.getKey(i2)
val i1Val = twoWayMap.getValue(i1Key)
val i2Val = twoWayMap.getValue(i2Key)
twoWayMap.put(i1Key, i2Val)
twoWayMap.put(i2Key, i1Val)
}
private fun addSpinTransform(indexTransforms: TwoWayMap<Int, Int>, spinSize: Int) {
val newMap = TwoWayMap<Int, Int>()
indexTransforms.entries()
.forEach {
val newIndex = (it.value + spinSize) % indexTransforms.size()
newMap.put(it.key, newIndex)
}
indexTransforms.putAll(newMap)
}
}
| 0 | Kotlin | 0 | 2 | 975695cc49f19a42c0407f41355abbfe0cb3cc59 | 4,515 | Advent-of-Code-2017 | MIT License |
src/main/kotlin/com/nibado/projects/advent/y2020/Day07.kt | nielsutrecht | 47,550,570 | false | null | package com.nibado.projects.advent.y2020
import com.nibado.projects.advent.*
object Day07 : Day {
private val REGEX_LINES = "([a-z ]+) bags contain ([0-9a-z, ]+)\\.".toRegex()
private val REGEX_BAG = "([0-9]+) ([a-z ]+) (bag|bags)".toRegex()
private val bags = resourceRegex(2020, 7, REGEX_LINES).map { (_, a, b) -> parseBag(a, b) }
override fun part1() = recurseUp("shiny gold").size
override fun part2() : Int = recurseDown("shiny gold") - 1
private fun recurseUp(color: String) : List<Bag> = bags.filter { bag -> bag.bags.any { it.second.color == color} }
.let { list -> list + list.flatMap { recurseUp(it.color) } }.distinct()
private fun recurseDown(color: String) : Int = 1 + bags.first { it.color == color }.bags
.map { (c, bag) -> c * recurseDown(bag.color) }.sum()
private fun parseBag(first: String, second: String) : Bag {
val list = if(second == "no other bags") { emptyList() } else {
second.split(", ").map { REGEX_BAG.matchEntire(it)!!.groupValues
.let { (_, a, b) -> a.toInt() to Bag(b, emptyList()) } }
}
return Bag(first, list)
}
data class Bag(val color: String, val bags: List<Pair<Int, Bag>>)
}
| 1 | Kotlin | 0 | 15 | b4221cdd75e07b2860abf6cdc27c165b979aa1c7 | 1,243 | adventofcode | MIT License |
src/Day23.kt | dizney | 572,581,781 | false | {"Kotlin": 105380} | import Day23.draw
import Day23.proposeMoves
object Day23 {
const val EXPECTED_PART1_CHECK_ANSWER = 110
const val EXPECTED_PART2_CHECK_ANSWER = 20
sealed interface GridCell
object Empty : GridCell
object Elf : GridCell
class Grid {
private val rows = mutableListOf<List<GridCell>>()
var width: Int = 0
private set
var height: Int = 0
private set
fun addRow(cells: List<Day23.GridCell>) {
rows += cells
width = rows.maxOf { it.size }
height = rows.size
}
fun doStep() {
}
}
fun Array<Coordinates>.draw() {
val fromX = minOf { it.x }
val toX = maxOf { it.x }
val fromY = minOf { it.y }
val toY = maxOf { it.y }
for (y in fromY..toY) {
for (x in fromX..toX) {
if (Coordinates(x, y) in this) {
print('#')
} else {
print('.')
}
}
println()
}
}
fun Array<Coordinates>.proposeMoves(
directions: Array<Direction>,
directionStartIdx: Int
): List<Pair<Coordinates, Coordinates>> = mapNotNull { elf ->
if (intersect(elf.adjacentPositions().toSet()).isNotEmpty()) {
var proposedMove: Pair<Coordinates, Coordinates>? = null
var directionIdx = directionStartIdx
var directionsDoneCount = 0
while (proposedMove == null && directionIdx < directions.size && directionsDoneCount++ <= directions.size) {
if (intersect(elf.adjacentPositions(directions[directionIdx])).isEmpty()) {
proposedMove = Pair(elf, elf + directions[directionIdx].move)
}
directionIdx = (directionIdx + 1) % directions.size
}
proposedMove
} else {
null
}
}
}
fun main() {
fun List<String>.parseElfsMap(): Array<Coordinates> = flatMapIndexed { row, line ->
line.mapIndexedNotNull { col, cell ->
when (cell) {
'.' -> null
'#' -> Coordinates(col, row)
else -> error("Unknown cell content $cell")
}
}
}.toTypedArray()
fun part1(input: List<String>, doDraw: Boolean): Int {
val elfs = input.parseElfsMap()
if (doDraw) {
elfs.draw()
println()
}
val directions = arrayOf(Direction.NORTH, Direction.SOUTH, Direction.WEST, Direction.EAST)
var directionStartIdx = 0
repeat(10) {
val proposedMoves = elfs.proposeMoves(directions, directionStartIdx)
val allNewPositions = proposedMoves.map { it.second }
proposedMoves.forEach { (currentPosition, proposedPosition) ->
if (allNewPositions.count { it == proposedPosition } == 1) {
elfs[elfs.indexOf(currentPosition)] = proposedPosition
}
}
directionStartIdx = (directionStartIdx + 1) % directions.size
if (doDraw) {
elfs.draw()
println()
}
}
val fromX = elfs.minOf { it.x }
val toX = elfs.maxOf { it.x }
val fromY = elfs.minOf { it.y }
val toY = elfs.maxOf { it.y }
return (fromY..toY).sumOf { y -> (fromX..toX).count { x -> !elfs.contains(Coordinates(x, y)) } }
}
fun part2(input: List<String>): Int {
val elfs = input.parseElfsMap()
val directions = arrayOf(Direction.NORTH, Direction.SOUTH, Direction.WEST, Direction.EAST)
var directionStartIdx = 0
var round = 0
var atLeastOneElfMoved: Boolean
do {
atLeastOneElfMoved = false
val proposedMoves = elfs.proposeMoves(directions, directionStartIdx)
val allNewPositions = proposedMoves.map { it.second }
proposedMoves.forEach { (currentPosition, proposedPosition) ->
if (allNewPositions.count { it == proposedPosition } == 1) {
elfs[elfs.indexOf(currentPosition)] = proposedPosition
atLeastOneElfMoved = true
}
}
directionStartIdx = (directionStartIdx + 1) % directions.size
round++
} while (atLeastOneElfMoved)
return round
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day23_test")
check(part1(testInput, true) == Day23.EXPECTED_PART1_CHECK_ANSWER) { "Part 1 failed" }
check(part2(testInput) == Day23.EXPECTED_PART2_CHECK_ANSWER) { "Part 2 failed" }
val input = readInput("Day23")
println(part1(input, false))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f684a4e78adf77514717d64b2a0e22e9bea56b98 | 4,853 | aoc-2022-in-kotlin | Apache License 2.0 |
aoc-day3/src/Day3.kt | rnicoll | 438,043,402 | false | {"Kotlin": 90620, "Rust": 1313} | import java.io.File
import java.util.*
import kotlin.collections.ArrayList
import kotlin.math.pow
fun main() {
val filename = File("input");
val contents = parse(filename);
part1(contents);
part2(contents);
}
fun parse(path: File): ArrayList<ArrayList<Int>> {
val bits = ArrayList<ArrayList<Int>>();
path.forEachLine {
if (it.isEmpty()) {
return@forEachLine;
}
val current = ArrayList<Int>();
for (i in it.indices) {
if (it[i] == '1') {
current.add(1);
} else {
current.add(0);
}
}
bits.add(current);
}
return bits;
}
fun countBits(contents: List<List<Int>>, value: Int): Array<Int> {
val counts = Array(contents.first().size) { _ -> 0 }
contents.forEach { row ->
row.forEachIndexed { idx, col ->
if (col == value) {
counts[idx]++;
}
}
}
return counts;
}
fun part2(contents: ArrayList<ArrayList<Int>>) {
val oxygen = filter(contents, OxygenGenerator())?.toTypedArray()
val cO2Scrubber = filter(contents, CO2Scrubber())?.toTypedArray()
println("Oxygen: $oxygen")
println("CO2Scrubber: $cO2Scrubber")
println(binToDec(oxygen!!) * binToDec(cO2Scrubber!!));
}
fun filter(contents: ArrayList<ArrayList<Int>>, filter: Filter): List<Int>? {
var current: List<List<Int>> = contents
for (bitIdx in 0..contents.size) {
current = filter.filter(current, bitIdx)
if (current.size < 2) {
break
}
}
return current.singleOrNull()
}
fun part1(contents: ArrayList<ArrayList<Int>>) {
val ones = countBits(contents, 1)
val gamma = Array(ones.size) { _ -> 0 }
val epsilon = Array(ones.size) { _ -> 0 }
for (i in ones.indices) {
val oneCount = ones[i];
val zeroCount = contents.size - ones[i];
if (oneCount > zeroCount) {
gamma[i] = 1;
epsilon[i] = 0;
} else {
gamma[i] = 0;
epsilon[i] = 1;
}
}
println("Gamma: ${Arrays.toString(gamma)}")
println("Epsilon: ${Arrays.toString(epsilon)}")
val gammaDec = binToDec(gamma);
val epsilonDec = binToDec(epsilon);
println(gammaDec * epsilonDec);
}
fun binToDec(bin: Array<Int>): Int {
var total = 0;
for (i in bin.indices) {
val multiplier = 2.toDouble().pow(i.toDouble());
val current = bin[bin.size - 1 - i];
total += (current * multiplier).toInt();
}
return total;
} | 0 | Kotlin | 0 | 0 | 8c3aa2a97cb7b71d76542f5aa7f81eedd4015661 | 2,567 | adventofcode2021 | MIT License |
src/main/kotlin/com/hj/leetcode/kotlin/problem210/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem210
/**
* LeetCode page: [210. Course Schedule II](https://leetcode.com/problems/course-schedule-ii/);
*/
class Solution {
/* Complexity:
* Time O(V+E) and Space O(V+E) where V is numCourses and E is size of prerequisites;
*/
fun findOrder(numCourses: Int, prerequisites: Array<IntArray>): IntArray {
val coursesByPrerequisite = groupCoursesByPrerequisite(numCourses, prerequisites)
val pendingCount = getNumPendingPrerequisitePerCourse(numCourses, prerequisites)
return findPathToFinishAllCourses(numCourses, pendingCount, coursesByPrerequisite)
}
private fun groupCoursesByPrerequisite(
numCourses: Int,
prerequisites: Array<IntArray>
): List<List<Int>> {
val graph = List(numCourses) { mutableListOf<Int>() }
for (dependency in prerequisites) {
val course = dependency[0]
val prerequisite = dependency[1]
graph[prerequisite].add(course)
}
return graph
}
private fun getNumPendingPrerequisitePerCourse(
numCourses: Int,
prerequisites: Array<IntArray>
): IntArray {
val count = IntArray(numCourses)
for (dependency in prerequisites) {
val course = dependency[0]
count[course]++
}
return count
}
private fun findPathToFinishAllCourses(
numCourses: Int,
numPendingPrerequisitePerCourse: IntArray,
coursesByPrerequisite: List<List<Int>>
): IntArray {
val pendingCount = numPendingPrerequisitePerCourse
val path = IntArray(numCourses)
var indexNextCourse = 0
for (course in pendingCount.indices) {
val noPrerequisite = pendingCount[course] == 0
if (noPrerequisite) {
path[indexNextCourse] = course
indexNextCourse++
}
}
var indexPrevCourse = 0
while (indexPrevCourse < indexNextCourse) {
val completedCourse = path[indexPrevCourse]
val coursesRequiringIt = coursesByPrerequisite[completedCourse]
for (course in coursesRequiringIt) {
pendingCount[course]--
val canBeCompleted = pendingCount[course] == 0
if (canBeCompleted) {
path[indexNextCourse] = course
indexNextCourse++
}
}
indexPrevCourse++
}
val pathFound = indexNextCourse == path.size
return if (pathFound) path else intArrayOf()
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 2,610 | hj-leetcode-kotlin | Apache License 2.0 |
src/main/kotlin/com/mckernant1/advent2023/Day1.kt | mckernant1 | 494,952,749 | false | {"Kotlin": 33093} | package com.mckernant1.advent2023
import com.mckernant1.commons.extensions.collections.SortedMaps.firstEntry
import com.mckernant1.commons.extensions.collections.SortedMaps.lastEntry
fun main() {
val cords1 = """
1abc2
pqr3stu8vwx
a1b2c3d4e5f
treb7uchet
""".trimIndent()
println(
cords1.split("\n").sumOf { trebuchetPart1(it) }
)
val cords2 = """
two1nine
eightwothree
abcone2threexyz
xtwone3four
4nineeightseven2
zoneight234
7pqrstsixteen
""".trimIndent()
println(
cords2.split("\n").sumOf {
trebuchetPart2(it).also { println(it) }
}
)
}
fun trebuchetPart1(s: String): Int {
val first = s.dropWhile { !it.isDigit() }.first()
val last = s.dropLastWhile { !it.isDigit() }.last()
return "$first$last".toInt()
}
fun trebuchetPart2(s: String): Int {
val minMap = numberMap.keys.associate {
s.indexOf(it) to numberMap[it]!!
}.toSortedMap()
val maxMap = numberMap.keys.associate {
s.lastIndexOf(it) to numberMap[it]!!
}.toSortedMap()
minMap.remove(-1)
maxMap.remove(-1)
return "${minMap.firstEntry().value}${maxMap.lastEntry().value}".toInt()
}
val numberMap = mapOf(
"one" to 1,
"two" to 2,
"three" to 3,
"four" to 4,
"five" to 5,
"six" to 6,
"seven" to 7,
"eight" to 8,
"nine" to 9,
"1" to 1,
"2" to 2,
"3" to 3,
"4" to 4,
"5" to 5,
"6" to 6,
"7" to 7,
"8" to 8,
"9" to 9
)
| 0 | Kotlin | 0 | 0 | 5aaa96588925b1b8d77d7dd98dd54738deeab7f1 | 1,523 | kotlin-random | Apache License 2.0 |
src/main/kotlin/day17.kt | gautemo | 433,582,833 | false | {"Kotlin": 91784} | import shared.getText
import kotlin.math.max
import kotlin.math.min
fun highestPosTrajectory(input: String) = hittingProbes(input).maxOf { it.maxY }
fun nrHitTrajectories(input: String) = hittingProbes(input).size
private fun hittingProbes(input: String): List<Probe> {
val target = findTarget(input)
val onTarget = mutableListOf<Probe>()
for(x in 0..300){
for(y in -100..200){
val probe = tryTrajectory(x, y, target)
if(probe != null) onTarget.add(probe)
}
}
return onTarget
}
private fun findTarget(input: String): Target{
fun findRange(XorY: String): IntProgression {
val a = Regex("""(?<=$XorY=)-?\d+""").find(input)!!.value.toInt()
val b = Regex("""(?<=$XorY=-?\d\d?\d?\.\.)-?\d+""").find(input)!!.value.toInt()
return if(a <= b) a..b else a downTo b
}
return Target(findRange("x"), findRange("y"))
}
private fun tryTrajectory(x: Int, y: Int, target: Target): Probe?{
val probe = Probe(x, y)
while (!probe.toFar(target)){
probe.move()
if(probe.onTarget(target)) return probe
}
return null
}
data class Target(val xRange: IntProgression, val yRange: IntProgression)
class Probe(var xVelocity: Int, var yVelocity: Int){
private var x = 0
private var y = 0
var maxY = 0
fun move(){
x += xVelocity
y += yVelocity
maxY = max(y, maxY)
when{
xVelocity > 0 -> xVelocity--
xVelocity < 0 -> xVelocity++
}
yVelocity--
}
fun toFar(target: Target): Boolean{
return when{
x < min(target.xRange.first, target.xRange.last) && xVelocity <= 0 -> true
x > max(target.xRange.first, target.xRange.last) && xVelocity <= 0 -> true
y < min(target.yRange.first, target.yRange.last) -> true
else -> false
}
}
fun onTarget(target: Target) = target.xRange.contains(x) && target.yRange.contains(y)
}
fun main(){
val input = getText("day17.txt")
val task1 = highestPosTrajectory(input)
println(task1)
val task2 = nrHitTrajectories(input)
println(task2)
} | 0 | Kotlin | 0 | 0 | c50d872601ba52474fcf9451a78e3e1bcfa476f7 | 2,155 | AdventOfCode2021 | MIT License |
src/main/kotlin/g2601_2700/s2602_minimum_operations_to_make_all_array_elements_equal/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g2601_2700.s2602_minimum_operations_to_make_all_array_elements_equal
// #Medium #Array #Sorting #Binary_Search #Prefix_Sum
// #2023_07_13_Time_790_ms_(100.00%)_Space_63.8_MB_(100.00%)
class Solution {
fun minOperations(nums: IntArray, queries: IntArray): List<Long> {
nums.sort()
val sum = LongArray(nums.size)
sum[0] = nums[0].toLong()
for (i in 1 until nums.size) {
sum[i] = sum[i - 1] + nums[i].toLong()
}
val res: MutableList<Long> = ArrayList()
for (query in queries) {
res.add(getOperations(sum, nums, query))
}
return res
}
private fun getOperations(sum: LongArray, nums: IntArray, target: Int): Long {
var res: Long = 0
val index = getIndex(nums, target)
val rightCounts = nums.size - 1 - index
if (index > 0) {
res += index.toLong() * target - sum[index - 1]
}
if (rightCounts > 0) {
res += sum[nums.size - 1] - sum[index] - rightCounts.toLong() * target
}
res += kotlin.math.abs(target - nums[index]).toLong()
return res
}
private fun getIndex(nums: IntArray, target: Int): Int {
var index = nums.binarySearch(target)
if (index < 0) index = -(index + 1)
if (index == nums.size) --index
return index
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,373 | LeetCode-in-Kotlin | MIT License |
src/2021/Day14.kt | nagyjani | 572,361,168 | false | {"Kotlin": 369497} | package `2021`
import java.io.File
import java.math.BigInteger
import java.util.*
fun main() {
Day14().solve()
}
class Day14 {
val input = """
NNCB
CH -> B
HH -> N
CB -> H
NH -> C
HB -> C
HC -> B
HN -> C
NN -> C
BH -> H
NC -> B
NB -> B
BN -> B
BB -> N
BC -> B
CC -> N
CN -> C
""".trimIndent()
fun<T> MutableMap<T, BigInteger>.incMap(key: T, num: BigInteger): MutableMap<T, BigInteger> {
this[key] = getOrDefault(key, BigInteger.ZERO).add(num)
return this
}
fun Map<String, BigInteger>.freqs(first: Char, last:Char): Map<Char, BigInteger> {
val r = mutableMapOf<Char, BigInteger>()
this.forEach { it.key.forEach { itc -> r.incMap(itc, it.value) } }
return r.incMap(first, BigInteger.ONE).incMap(last, BigInteger.ONE).mapValues { it.value.divide(BigInteger("2")) }
}
fun Map<String, List<String>>.split(nums: Map<String, BigInteger>): MutableMap<String, BigInteger> {
val newNums = mutableMapOf<String, BigInteger>()
nums.forEach { this[it.key]!!.forEach{new2 -> newNums.incMap(new2, it.value) }}
return newNums
}
fun solve() {
val f = File("src/2021/inputs/day14.in")
val s = Scanner(f)
// val s = Scanner(input)
val init = s.nextLine().trim()
var nums = mutableMapOf<String, BigInteger>()
init.windowed(2){it.toString()}.forEach { nums.incMap(it, BigInteger.ONE) }
val t = mutableMapOf<String, List<String>>()
while (s.hasNextLine()) {
val line = s.nextLine().trim()
if (line.isNotEmpty()) {
val lineTokens = line.split(" ")
val left = lineTokens[0]
val right = lineTokens[2]
t.set(left, listOf(left.slice(0..0)+right, right+left.slice(1..1)))
}
}
for (i in 0..40) {
val freqs = nums.freqs(init.first(), init.last())
val minFreq = freqs.minOf { it.value }
val maxFreq = freqs.maxOf { it.value }
println("${minFreq} ${maxFreq} ${maxFreq.subtract(minFreq)}")
nums = t.split(nums)
}
// var counts = mutableMapOf<String, Int>()
// init.windowed(2){val s = it.toString(); counts[s] = counts.getOrDefault(s, 0)}
// for (i in 1..4) {
// var nextCounts = mutableMapOf<String, Int>()
// counts.keys) {
// for (n in t.split(k))
// }
// }
}
} | 0 | Kotlin | 0 | 0 | f0c61c787e4f0b83b69ed0cde3117aed3ae918a5 | 2,468 | advent-of-code | Apache License 2.0 |
src/Day10.kt | mcrispim | 573,449,109 | false | {"Kotlin": 46488} | fun main() {
fun part1(input: List<String>): Int {
var nextCommand = 0
val measures = listOf(20, 60, 100, 140, 180, 220)
val strength = mutableListOf<Int>()
var nextMeasure = 0
var cycle = 1
var registerX = 1
while (nextCommand <= input.lastIndex) {
val initialRegisterX = registerX
when (val command = input[nextCommand]) {
"noop" -> {
cycle++
}
else -> {
cycle += 2
registerX += command.substringAfter(" ").toInt()
}
}
nextCommand++
if (cycle > measures[nextMeasure]) {
strength.add(measures[nextMeasure] * initialRegisterX)
} else if (cycle == measures[nextMeasure]) {
strength.add(measures[nextMeasure] * registerX)
}
if (cycle >= measures[nextMeasure]) {
nextMeasure++
}
if (strength.size == measures.size)
break
}
return strength.sum()
}
fun part2(input: List<String>): Int {
var registerX = 1
var instruction = 0
var duration = 0
var increment = 0
for (line in 0..5) {
for (pixel in 0..39) {
if (duration == 0) {
val command = input[instruction++]
if (command == "noop") {
duration = 1
increment = 0
} else {
duration = 2
increment = command.substringAfter(" ").toInt()
}
}
duration--
val sprite = registerX - 1.. registerX + 1
print(if (pixel in sprite) "#" else ".")
if (duration == 0) {
registerX += increment
}
}
println()
}
return input.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day10_test")
check(part1(testInput) == 13140)
check(part2(testInput) == 146)
val input = readInput("Day10")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 5fcacc6316e1576a172a46ba5fc9f70bcb41f532 | 2,335 | AoC2022 | Apache License 2.0 |
src/main/kotlin/g0801_0900/s0840_magic_squares_in_grid/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g0801_0900.s0840_magic_squares_in_grid
// #Medium #Array #Math #Matrix #2023_03_28_Time_149_ms_(100.00%)_Space_34.2_MB_(100.00%)
class Solution {
fun numMagicSquaresInside(grid: Array<IntArray>): Int {
val m = grid.size
val n = grid[0].size
var count = 0
for (i in 0 until m - 2) {
for (j in 0 until n - 2) {
val set: MutableSet<Int> = HashSet()
val sum = grid[i][j] + grid[i][j + 1] + grid[i][j + 2]
if (sum == grid[i + 1][j] + grid[i + 1][j + 1] + grid[i + 1][j + 2] && sum == grid[i + 2][j] +
grid[i + 2][j + 1] + grid[i + 2][j + 2] && sum == grid[i][j] + grid[i + 1][j] + grid[i + 2][j] &&
sum == grid[i][j + 1] + grid[i + 1][j + 1] + grid[i + 2][j + 1] && sum == grid[i][j + 2] +
grid[i + 1][j + 2] + grid[i + 2][j + 2] && sum == grid[i][j] + grid[i + 1][j + 1] +
grid[i + 2][j + 2] && sum == grid[i][j + 2] + grid[i + 1][j + 1] + grid[i + 2][j] && set.add(
grid[i][j]
) &&
isLegit(grid[i][j]) &&
set.add(grid[i][j + 1]) &&
isLegit(grid[i][j + 1]) &&
set.add(grid[i][j + 2]) &&
isLegit(grid[i][j + 2]) &&
set.add(grid[i + 1][j]) &&
isLegit(grid[i + 1][j]) &&
set.add(grid[i + 1][j + 1]) &&
isLegit(grid[i + 1][j + 1]) &&
set.add(grid[i + 1][j + 2]) &&
isLegit(grid[i + 1][j + 2]) &&
set.add(grid[i + 2][j]) &&
isLegit(grid[i + 2][j]) &&
set.add(grid[i + 2][j + 1]) &&
isLegit(grid[i + 2][j + 1]) &&
set.add(grid[i + 2][j + 2]) &&
isLegit(grid[i + 2][j + 2])
) {
count++
}
}
}
return count
}
private fun isLegit(num: Int): Boolean {
return num in 1..9
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 2,139 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/adventofcode/y2021/Day05.kt | Tasaio | 433,879,637 | false | {"Kotlin": 117806} | import adventofcode.*
fun main() {
val day = Day05()
println(day.part1())
day.reset()
println(day.part2())
}
class Day05 : Y2021Day(5) {
private val input = fetchInput()
private val points: List<Pair<Coordinate, Coordinate>> = input.map {
val a = it.split("->")
val res1= a[0].split(",")
val res2 = a[1].split(",")
Pair(
Coordinate(res1[0].parseNumbersToSingleInt(), res1[1].parseNumbersToSingleInt()),
Coordinate(res2[0].parseNumbersToSingleInt(), res2[1].parseNumbersToSingleInt())
)
}
private val minMax = points.flatMap { it.toList() }.getMinMaxValues()
override fun part1(): Number? {
val lines = arrayListOf<LineSegment>()
points.forEach {
if (it.first.x == it.second.x || it.first.y == it.second.y) {
lines.add(LineSegment(it.first, it.second))
}
}
val g = Grid(minMax.maxX, minMax.maxY, '.')
g.forEach { p ->
lines.forEach { l ->
if (p.posX == l.from.x.toInt() || p.posY == l.from.y.toInt()) {
if (l.pointIsOnLine(p.coordinate())) {
if (p.content.isDigit()) {
p.content = (p.content.toIntValue() + 1).digitToChar()
} else {
p.content = '1'
}
}
}
}
}
return g.count {
it.content.isDigit() && it.content.toIntValue() > 1
}
}
override fun part2(): Number? {
val lines = arrayListOf<LineSegment>()
val diag = arrayListOf<LineSegment>()
points.forEach {
if (it.first.x == it.second.x || it.first.y == it.second.y) {
lines.add(LineSegment(it.first, it.second))
} else {
diag.add(LineSegment(it.first, it.second))
}
}
val g = Grid(minMax.maxX, minMax.maxY, '.')
var c = 0
g.forEach { p ->
if (c++ % 10000 == 0) println(c)
lines.forEach { l ->
if (p.posX == l.from.x.toInt() || p.posY == l.from.y.toInt()) {
if (l.pointIsOnLine(p.coordinate())) {
if (p.content.isDigit()) {
p.content = (p.content.toIntValue() + 1).digitToChar()
} else {
p.content = '1'
}
}
}
}
diag.forEach {
if (it.pointIsOnLine(p.coordinate())) {
if (p.content.isDigit()) {
p.content = (p.content.toIntValue() + 1).digitToChar()
} else {
p.content = '1'
}
}
}
}
g.printDebug()
return g.count {
it.content.isDigit() && it.content.toIntValue() > 1
}
}
}
| 0 | Kotlin | 0 | 0 | cc72684e862a782fad78b8ef0d1929b21300ced8 | 3,065 | adventofcode2021 | The Unlicense |
src/main/kotlin/g2001_2100/s2045_second_minimum_time_to_reach_destination/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g2001_2100.s2045_second_minimum_time_to_reach_destination
// #Hard #Breadth_First_Search #Graph #Shortest_Path
// #2023_06_23_Time_862_ms_(100.00%)_Space_57.2_MB_(100.00%)
import java.util.LinkedList
import java.util.Queue
class Solution {
fun secondMinimum(n: Int, edges: Array<IntArray>, time: Int, change: Int): Int {
val adj: Array<MutableList<Int>?> = arrayOfNulls(n)
for (i in adj.indices) {
adj[i] = ArrayList()
}
for (edge in edges) {
val p = edge[0] - 1
val q = edge[1] - 1
adj[p]?.add(q)
adj[q]?.add(p)
}
val dis1 = IntArray(n)
val dis2 = IntArray(n)
dis1.fill(Int.MAX_VALUE)
dis2.fill(Int.MAX_VALUE)
dis1[0] = 0
val queue: Queue<IntArray> = LinkedList()
queue.offer(intArrayOf(0, 0))
while (queue.isNotEmpty()) {
val temp = queue.poll()
val cur = temp[0]
val path = temp[1]
for (node in adj[cur]!!) {
val newPath = path + 1
if (newPath < dis1[node]) {
dis2[node] = dis1[node]
dis1[node] = newPath
queue.offer(intArrayOf(node, newPath))
} else if (newPath > dis1[node] && newPath < dis2[node]) {
dis2[node] = newPath
queue.offer(intArrayOf(node, newPath))
}
}
}
return helper(dis2[n - 1], time, change)
}
private fun helper(pathValue: Int, time: Int, change: Int): Int {
var sum = 0
for (i in 0 until pathValue) {
sum += time
if (i == pathValue - 1) {
break
}
if (sum / change % 2 != 0) {
sum = (sum / change + 1) * change
}
}
return sum
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,908 | LeetCode-in-Kotlin | MIT License |
src/Day19.kt | andrikeev | 574,393,673 | false | {"Kotlin": 70541, "Python": 18310, "HTML": 5558} | fun main() {
fun part1(input: List<String>): Int {
val blueprints = input.map(Blueprint::parse)
return blueprints.sumOf { blueprint ->
(blueprint.id * blueprint.simulate(24)).also { println("${blueprint.id}: $it") }
}
}
fun part2(input: List<String>): Int {
val blueprints = input.map(Blueprint::parse).take(3)
return blueprints
.map { blueprint -> blueprint.simulate(32) }
.reduceRight { left, right -> left * right }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day19_test")
check(part1(testInput).also { println("part1 test: $it") } == 33)
check(part2(testInput).also { println("part2 test: $it") } == 56 * 62)
val input = readInput("Day19")
println(part1(input))
println(part2(input))
}
private fun Blueprint.simulate(minutes: Int): Int {
var states = listOf(FabricState(minutesLeft = minutes))
fun FabricState.canBuildGeodeRobot() = geodeRobotPrice.first <= ore && geodeRobotPrice.second <= obsidian
fun FabricState.canBuildObsidianRobot() = obsidianRobotPrice.first <= ore && obsidianRobotPrice.second <= clay
fun FabricState.canBuildClayRobot() = clayRobotPrice <= ore
fun FabricState.canBuildOreRobot() = oreRobotPrice <= ore
fun FabricState.shouldBuildRobots() = minutesLeft > 1
fun FabricState.shouldBuildObsidianRobot() = shouldBuildRobots() && !canBuildGeodeRobot() && minutesLeft > 2
fun FabricState.shouldBuildClayRobot(): Boolean {
return shouldBuildRobots() &&
!canBuildGeodeRobot() &&
!canBuildObsidianRobot() &&
(clayRobots < obsidianRobotPrice.second) &&
minutesLeft > 3
}
fun FabricState.newState(
ore: Int = this.ore + this.oreRobots,
clay: Int = this.clay + this.clayRobots,
obsidian: Int = this.obsidian + this.obsidianRobots,
geode: Int = this.geode + this.geodeRobots,
oreRobots: Int = this.oreRobots,
clayRobots: Int = this.clayRobots,
obsidianRobots: Int = this.obsidianRobots,
geodeRobots: Int = this.geodeRobots,
): FabricState = copy(
minutesLeft = minutesLeft - 1,
ore = ore,
clay = clay,
obsidian = obsidian,
geode = geode,
oreRobots = oreRobots,
clayRobots = clayRobots,
obsidianRobots = obsidianRobots,
geodeRobots = geodeRobots,
)
fun FabricState.shouldBuildOreRobot(): Boolean {
return shouldBuildRobots() &&
!canBuildGeodeRobot() &&
!canBuildObsidianRobot() &&
(oreRobots < maxOf(clayRobotPrice, obsidianRobotPrice.first, geodeRobotPrice.first))
}
repeat(minutes) {
val newStates = mutableListOf<FabricState>()
states.forEach { state ->
with(state) {
if (canBuildGeodeRobot()) {
newStates.add(
newState(
ore = ore + oreRobots - geodeRobotPrice.first,
obsidian = obsidian + obsidianRobots - geodeRobotPrice.second,
geodeRobots = geodeRobots + 1,
)
)
}
if (shouldBuildObsidianRobot() && canBuildObsidianRobot()) {
newStates.add(
newState(
ore = ore + oreRobots - obsidianRobotPrice.first,
clay = clay + clayRobots - obsidianRobotPrice.second,
obsidianRobots = obsidianRobots + 1,
)
)
}
if (shouldBuildClayRobot() && canBuildClayRobot()) {
newStates.add(
newState(
ore = ore + oreRobots - clayRobotPrice,
clayRobots = clayRobots + 1,
)
)
}
if (shouldBuildOreRobot() && canBuildOreRobot()) {
newStates.add(
newState(
ore = ore + oreRobots - oreRobotPrice,
oreRobots = oreRobots + 1,
)
)
}
newStates.add(
newState()
)
}
}
states = newStates.sortedByDescending(FabricState::geode).take(10000000)
}
return states.maxOf(FabricState::geode)
}
private data class FabricState(
val minutesLeft: 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,
)
private class Blueprint(
val id: Int,
val oreRobotPrice: Int,
val clayRobotPrice: Int,
val obsidianRobotPrice: Pair<Int, Int>,
val geodeRobotPrice: Pair<Int, Int>,
) {
companion object {
fun parse(input: String): Blueprint {
val id = input.substringAfter("Blueprint ").substringBefore(":").toInt()
val (ore, clay, obsidian, geode) = input.substringAfter(":").split(".")
val (oreRobotPrice) = ore.split(" ").mapNotNull(String::toIntOrNull)
val (clayRobotPrice) = clay.split(" ").mapNotNull(String::toIntOrNull)
val (obsidianRobotPriceOre, obsidianRobotPriceClay) = obsidian.split(" ").mapNotNull(String::toIntOrNull)
val (geodeRobotPriceOre, geodeRobotPriceObsidian) = geode.split(" ").mapNotNull(String::toIntOrNull)
return Blueprint(
id = id,
oreRobotPrice = oreRobotPrice,
clayRobotPrice = clayRobotPrice,
obsidianRobotPrice = Pair(obsidianRobotPriceOre, obsidianRobotPriceClay),
geodeRobotPrice = Pair(geodeRobotPriceOre, geodeRobotPriceObsidian),
)
}
}
}
| 0 | Kotlin | 0 | 1 | 1aedc6c61407a28e0abcad86e2fdfe0b41add139 | 6,117 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/com/ginsberg/advent2017/Day19.kt | tginsberg | 112,672,087 | false | null | /*
* Copyright (c) 2017 by <NAME>
*/
package com.ginsberg.advent2017
/**
* AoC 2017, Day 19
*
* Problem Description: http://adventofcode.com/2017/day/19
* Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2017/day19/
*/
class Day19(private val input: List<String>) {
private val grid = input.map { it.toCharArray() }
private val directions = listOf(
Coordinate(0, 1),
Coordinate(0, -1),
Coordinate(1, 0),
Coordinate(-1, 0)
)
fun solvePart1(): String =
traverse(Coordinate(input[0].indexOf("|"), 0), Coordinate(0, 1)).second
fun solvePart2(): Int =
traverse(Coordinate(input[0].indexOf("|"), 0), Coordinate(0, 1)).first
private tailrec fun traverse(location: Coordinate,
direction: Coordinate,
seen: List<Char> = emptyList(),
steps: Int = 0): Pair<Int, String> =
if (grid.at(location) == ' ') Pair(steps, seen.joinToString(""))
else {
when (grid.at(location)) {
in 'A'..'Z' -> traverse(location + direction, direction, seen + grid.at(location), steps.inc())
'+' -> {
val turn = turn(location, direction)
traverse(location + turn, turn, seen, steps.inc())
}
else -> traverse(location + direction, direction, seen, steps.inc())
}
}
private fun turn(location: Coordinate, direction: Coordinate) =
directions
.filter { it != direction }
.filter { it != !direction }
.first { grid.at(location + it) != ' ' }
private fun List<CharArray>.at(coordinate: Coordinate): Char =
this[coordinate.y][coordinate.x]
data class Coordinate(val x: Int, val y: Int) {
operator fun plus(that: Coordinate) = Coordinate(x + that.x, y + that.y)
operator fun not() = Coordinate(-x, -y)
}
}
| 0 | Kotlin | 0 | 15 | a57219e75ff9412292319b71827b35023f709036 | 2,013 | advent-2017-kotlin | MIT License |
src/org/aoc2021/Day13.kt | jsgroth | 439,763,933 | false | {"Kotlin": 86732} | package org.aoc2021
import java.nio.file.Files
import java.nio.file.Path
object Day13 {
data class Point(val x: Int, val y: Int)
data class Fold(val direction: String, val coordinate: Int)
private fun solvePart1(lines: List<String>): Int {
val (points, folds) = parseLines(lines)
val (cols, rows) = determineGridSize(folds)
val grid = generateGrid(points, rows, cols)
val folded = applyFold(grid, folds[0])
return folded.sumOf { column -> column.count { it } }
}
private fun solvePart2(lines: List<String>) {
val (points, folds) = parseLines(lines)
val (cols, rows) = determineGridSize(folds)
val grid = generateGrid(points, rows, cols)
val folded = folds.fold(grid) { newGrid, fold -> applyFold(newGrid, fold) }
printGrid(folded)
}
private fun parseLines(lines: List<String>): Pair<List<Point>, List<Fold>> {
val points = mutableListOf<Point>()
val folds = mutableListOf<Fold>()
lines.filter(String::isNotBlank).forEach { line ->
if (line.startsWith("fold along ")) {
val (direction, coordinate) = line.substringAfter("fold along ")
.split("=")
.let { it[0] to it[1].toInt() }
folds.add(Fold(direction, coordinate))
} else {
val (x, y) = line.split(",").map(String::toInt)
points.add(Point(x, y))
}
}
return points.toList() to folds.toList()
}
private fun generateGrid(points: List<Point>, rows: Int, cols: Int): Array<Array<Boolean>> {
val grid = Array(cols) { Array(rows) { false } }
points.forEach { (x, y) -> grid[x][y] = true }
return grid
}
private fun determineGridSize(folds: List<Fold>): Pair<Int, Int> {
val firstHorizontalFold = folds.first { it.direction == "x" }
val firstVerticalFold = folds.first { it.direction == "y" }
return (2 * firstHorizontalFold.coordinate + 1) to (2 * firstVerticalFold.coordinate + 1)
}
private fun applyFold(grid: Array<Array<Boolean>>, fold: Fold) = when (fold.direction) {
"x" -> applyHorizontalFold(grid, fold.coordinate)
"y" -> applyVerticalFold(grid, fold.coordinate)
else -> throw IllegalArgumentException(fold.direction)
}
private fun applyHorizontalFold(grid: Array<Array<Boolean>>, x: Int): Array<Array<Boolean>> {
if (x != (grid.size - 1) / 2) throw IllegalArgumentException("$x ${grid.size}")
val newGrid = Array(x) { Array(grid[0].size) { false } }
for (i in 0 until x) {
for (j in grid[0].indices) {
newGrid[i][j] = grid[i][j]
}
}
for (i in x+1 until grid.size) {
for (j in grid[0].indices) {
if (grid[i][j]) {
newGrid[grid.size - 1 - i][j] = true
}
}
}
return newGrid
}
private fun applyVerticalFold(grid: Array<Array<Boolean>>, y: Int): Array<Array<Boolean>> {
if (y != (grid[0].size - 1) / 2) throw IllegalArgumentException("$y ${grid[0].size}")
val newGrid = Array(grid.size) { Array(y) { false } }
for (i in grid.indices) {
for (j in 0 until y) {
newGrid[i][j] = grid[i][j]
}
}
for (i in grid.indices) {
for (j in y+1 until grid[0].size) {
if (grid[i][j]) {
newGrid[i][grid[0].size - 1 - j] = true
}
}
}
return newGrid
}
private fun printGrid(grid: Array<Array<Boolean>>) {
for (j in grid[0].indices) {
for (i in grid.indices) {
print(if (grid[i][j]) "#" else " ")
}
println()
}
}
@JvmStatic
fun main(args: Array<String>) {
val lines = Files.readAllLines(Path.of("input13.txt"), Charsets.UTF_8)
val solution1 = solvePart1(lines)
println(solution1)
solvePart2(lines)
}
} | 0 | Kotlin | 0 | 0 | ba81fadf2a8106fae3e16ed825cc25bbb7a95409 | 4,131 | advent-of-code-2021 | The Unlicense |
src/kotlin/_2022/Task05.kt | MuhammadSaadSiddique | 567,431,330 | false | {"Kotlin": 20410} | package _2022
import Task
import readInput
import java.util.*
object Task05 : Task {
override fun partA() = parseInput().let { (stacks, instructions) ->
instructions.forEach { (move, from, to) ->
repeat(move) { stacks[to]?.push(stacks[from]?.pop()) }
}
findTopCrates(stacks)
}
override fun partB() = parseInput().let { (stacks, instructions) ->
instructions.forEach { (move, from, to) ->
val temp = LinkedList<String>()
repeat(move) { temp.push(stacks[from]?.pop()) }
repeat(move) { stacks[to]?.push(temp.pop()) }
}
findTopCrates(stacks)
}
private fun findTopCrates(stacks: Map<Int, LinkedList<String>>): String =
stacks.entries.sortedBy { it.key }.joinToString("") { it.value.peek() }
private fun parseInput() = readInput("_2022/05")
.split("\n\n")
.let { (stacks, instructions) -> parseStacks(stacks) to parseInstructions(instructions) }
private fun parseStacks(input: String): Map<Int, LinkedList<String>> = input
.split('\n')
.map {
it
.chunked(4)
.mapIndexed { index, it ->
val position = index + 1
val (_, crane) = it.toCharArray()
position to crane
}
.filter { (_, char) -> char.isLetter() }
}
.flatten()
.groupBy { (index) -> index }
.map { (index, list) -> index to LinkedList(list.map { (_, char) -> char.toString() }) }
.toMap()
private fun parseInstructions(input: String): List<List<Int>> = input
.split('\n')
.map { it.split(' ').mapNotNull { it.toIntOrNull() } }
}
| 0 | Kotlin | 0 | 0 | 3893ae1ac096c56e224e798d08d7fee60e299a84 | 1,750 | AdventCode-Kotlin | Apache License 2.0 |
src/Day02.kt | razvn | 573,166,955 | false | {"Kotlin": 27208} | import java.lang.Exception
fun main() {
val day = "Day02"
fun part1(input: List<String>): Int = input.fold(0) { acc, line ->
val player1 = calcPlayer(line[0])
val player2 = calcPlayer(line[2])
val result = calcResult(player1, player2)
acc + result.value + player2.value
}
fun part2(input: List<String>): Int = input.fold(0) { acc, line ->
val player1 = calcPlayer(line[0])
val result = calcResult(line[2])
val player2 = calcPlayerFromResult(player1, result)
acc + result.value + player2.value
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("${day}_test")
println(part1(testInput))
println(part2(testInput))
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput(day)
println(part1(input))
println(part2(input))
}
private enum class RPS(val value: Int) {
Rock(1),
Paper(2),
Scissors(3),
}
enum class Result(val value: Int) {
DRAW(3),
WIN(6),
LOSE(0)
}
private fun calcResult(p1: RPS, p2: RPS): Result {
return when (p2) {
RPS.Paper -> when (p1) {
RPS.Paper -> Result.DRAW
RPS.Rock -> Result.WIN
RPS.Scissors -> Result.LOSE
}
RPS.Scissors -> when (p1) {
RPS.Scissors -> Result.DRAW
RPS.Rock -> Result.LOSE
RPS.Paper -> Result.WIN
}
RPS.Rock -> when (p1) {
RPS.Rock -> Result.DRAW
RPS.Paper -> Result.LOSE
RPS.Scissors -> Result.WIN
}
}
}
private fun calcPlayer(char: Char): RPS = when (char) {
'A', 'X' -> RPS.Rock
'B', 'Y' -> RPS.Paper
'C', 'Z' -> RPS.Scissors
else -> throw Exception("Unknown value $char")
}
private fun calcPlayerFromResult(p1: RPS, result: Result): RPS {
return when (p1) {
RPS.Rock -> when (result) {
Result.DRAW -> RPS.Rock
Result.WIN -> RPS.Paper
Result.LOSE -> RPS.Scissors
}
RPS.Paper -> when (result) {
Result.DRAW -> RPS.Paper
Result.WIN -> RPS.Scissors
Result.LOSE -> RPS.Rock
}
RPS.Scissors -> when (result) {
Result.DRAW -> RPS.Scissors
Result.WIN -> RPS.Rock
Result.LOSE -> RPS.Paper
}
}
}
private fun calcResult(char: Char): Result = when (char) {
'X' -> Result.LOSE
'Y' -> Result.DRAW
'Z' -> Result.WIN
else -> throw Exception("Unknown value $char")
}
| 0 | Kotlin | 0 | 0 | 73d1117b49111e5044273767a120142b5797a67b | 2,579 | aoc-2022-kotlin | Apache License 2.0 |
src/day5/Day05.kt | JoeSkedulo | 573,328,678 | false | {"Kotlin": 69788} | package day5
import Runner
fun main() {
Day5Runner().solve()
}
class Day5Runner : Runner<String>(
day = 5,
expectedPartOneTestAnswer = "CMZ",
expectedPartTwoTestAnswer = "MCD"
) {
override fun partOne(input: List<String>, test: Boolean): String {
val moves = input.filter { line -> line.contains("move") }
val stacks = buildStacks(input)
moves.forEach { line ->
val move = line.toMove()
val startStack = stacks[move.startStack]
val endStack = stacks[move.endStack]
repeat(move.count) {
endStack.add(startStack.last())
startStack.removeLast()
}
}
return stacks.toAnswer()
}
override fun partTwo(input: List<String>, test: Boolean): String {
val moves = input.filter { line -> line.contains("move") }
val stacks = buildStacks(input)
moves.forEach { line ->
val move = line.toMove()
val startStack = stacks[move.startStack]
val endStack = stacks[move.endStack]
val removed = buildList {
repeat(move.count) {
add(0, startStack.removeLast())
}
}
endStack.addAll(removed)
}
return stacks.toAnswer()
}
private fun buildStacks(input: List<String>) : List<MutableList<String>> {
val stackLines = input.filter { line -> line != "" && !line.contains("move") }.toMutableList()
val lastStackLine = stackLines.removeLast()
val reveredStackLines = stackLines.reversed()
val stackCount = lastStackLine.filter { it.isDigit() }.map { it.intValue() }.max()
return buildList {
repeat(stackCount) {
add(mutableListOf())
}
reveredStackLines.forEach { line ->
line.windowed(4, 4, partialWindows = true).forEachIndexed { index, crates ->
crates
.filter { it.isLetter() }
.forEach { char ->
this[index].add(char.toString())
}
}
}
}
}
private fun Char.intValue() = this.toString().toInt()
private fun List<MutableList<String>>.toAnswer() = let { stacks ->
buildString {
stacks.forEach { stack ->
append(stack.last())
}
}
}
private fun String.toMove() : Move {
val filteredLine = filter { it.isDigit() || it.isWhitespace() }
.split(" ")
.mapNotNull { it.toIntOrNull() }
return Move(
count = filteredLine[0],
startStack = filteredLine[1] - 1,
endStack = filteredLine[2] - 1
)
}
}
data class Move(
val count: Int,
val startStack: Int,
val endStack: Int
) | 0 | Kotlin | 0 | 0 | bd8f4058cef195804c7a057473998bf80b88b781 | 2,914 | advent-of-code | Apache License 2.0 |
src/main/kotlin/com/hj/leetcode/kotlin/problem904/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem904
/**
* LeetCode page: [904. Fruit Into Baskets](https://leetcode.com/problems/fruit-into-baskets/);
*/
class Solution {
/* Complexity:
* Time O(|fruits|) and Space O(1);
*/
fun totalFruit(fruits: IntArray): Int {
// an emptyBasket that match algorithm logic
val basket1 = SingleTypeBasket(-1, 0, -1)
// a basket with one fruits[0]
val basket2 = SingleTypeBasket(fruits[0], 1, 0)
var maxFruits = 0
for (index in 1 until fruits.size) {
when (val type = fruits[index]) {
basket1.fruitType -> basket1.putOne(type, index)
basket2.fruitType -> basket2.putOne(type, index)
else -> {
maxFruits = maxOf(maxFruits, basket1.numFruits + basket2.numFruits)
val isBasket1MoreRecent = basket1.lastPickIndex > basket2.lastPickIndex
val (moreRecent, lessRecent) =
if (isBasket1MoreRecent) basket1 to basket2 else basket2 to basket1
// require emptyBasket set lastPickIndex to -1
moreRecent.numFruits = moreRecent.lastPickIndex - lessRecent.lastPickIndex
lessRecent.putOne(type, index)
}
}
}
maxFruits = maxOf(maxFruits, basket1.numFruits + basket2.numFruits)
return maxFruits
}
private class SingleTypeBasket(var fruitType: Int, var numFruits: Int, var lastPickIndex: Int) {
fun putOne(type: Int, pickIndex: Int) {
val isExistingType = type == fruitType
if (isExistingType) {
numFruits++
} else {
fruitType = type
numFruits = 1
}
lastPickIndex = pickIndex
}
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 1,852 | hj-leetcode-kotlin | Apache License 2.0 |
2021/src/test/kotlin/Day19.kt | jp7677 | 318,523,414 | false | {"Kotlin": 171284, "C++": 87930, "Rust": 59366, "C#": 1731, "Shell": 354, "CMake": 338} | import Util.splitWhen
import kotlin.math.abs
import kotlin.test.Test
import kotlin.test.assertEquals
class Day19 {
data class Position(val x: Int, val y: Int, val z: Int)
data class Scanner(val index: Int, val beacons: Set<Position>)
enum class Turn { NONE, RIGHT, LEFT, UP, DOWN, BACKWARDS }
enum class Rotate { NONE, CLOCKWISE, COUNTERCLOCKWISE, UPSIDE_DOWN }
data class Correction(val turn: Turn, val rotation: Rotate, val x: Int, val y: Int, val z: Int)
private val turns = listOf(Turn.NONE, Turn.RIGHT, Turn.LEFT, Turn.UP, Turn.DOWN, Turn.BACKWARDS)
private val rotations = listOf(Rotate.NONE, Rotate.CLOCKWISE, Rotate.COUNTERCLOCKWISE, Rotate.UPSIDE_DOWN)
@Test
fun `run part 01`() {
val scanners = getScanners()
val count = getOceanMap(scanners)
.count { (_, isScanner) -> !isScanner }
assertEquals(451, count)
}
@Test
fun `run part 02`() {
val scanners = getScanners()
val detectedScanners = getOceanMap(scanners)
.filter { (_, isScanner) -> isScanner }
.map { (position, _) -> position }
val maxDistance = detectedScanners
.flatMap { position ->
detectedScanners
.filterNot { other -> position == other }
.map { other ->
position.distance(other)
}
}
.maxOrNull()
assertEquals(13184, maxDistance)
}
private fun getOceanMap(scanners: List<Scanner>): Set<Pair<Position, Boolean>> {
val detectedScanners = mutableListOf(scanners.first().index to Position(0, 0, 0))
val detectedBeacons = scanners.first().beacons.toMutableSet()
while (detectedScanners.size != scanners.size) {
val trianglesFromDetectedBeacons = detectedBeacons.getTrianglesWithBeacons()
scanners
.filterNot { detectedScanners.map { scanner -> scanner.first }.contains(it.index) }
.map {
it to it.beacons
.getTrianglesWithBeacons()
.filter { (triangles, _) ->
triangles.sorted() in trianglesFromDetectedBeacons
.map { (triangle, _) -> triangle.sorted() }
}
}
.filter { (_, triangles) -> triangles.count() * 3 >= 12 }
.forEach { (scanner, triangles) ->
val correction = calcCorrection(triangles, trianglesFromDetectedBeacons)
detectedScanners.add(scanner.index to Position(correction.x, correction.y, correction.z))
scanner.beacons
.map { it.face(correction.turn, correction.rotation) }
.map { Position(it.x - correction.x, it.y - correction.y, it.z - correction.z) }
.forEach { detectedBeacons.add(it) }
}
}
return detectedScanners.map { it.second to true }.toSet() + detectedBeacons.map { it to false }
}
/** Build distinct triangles for all positions with closest two neighbours.
* Also maintain position order for each triangle. */
private fun Set<Position>.getTrianglesWithBeacons() =
this.map {
this
.filterNot { beacon -> beacon == it }
.sortedBy { beacon -> beacon.distance(it) }
.take(2)
.let { beacons ->
listOf(
it.distance(beacons.first()),
it.distance(beacons.last()),
beacons.first().distance(beacons.last())
) to listOf(it, beacons.first(), beacons.last())
}
}
.sortedWith(
compareBy<Pair<List<Int>, List<Position>>> { (triangle, _) -> triangle[0] }
.thenBy { (triangle, _) -> triangle[1] }
)
.distinctBy { (triangle, _) -> triangle.sorted() }
/** Determine correction (direction and position offset) by turning and rotating matching triangles.
* Direction matches when the distances between all matching positions for matching triangles are equal.
* Compare all triangles to avoid edge case where more than one direction fits. */
private fun calcCorrection(
trianglesWithBeacons: List<Pair<List<Int>, List<Position>>>,
trianglesFromDetectedBeacons: List<Pair<List<Int>, List<Position>>>
) = trianglesWithBeacons
.map { (triangle, beacons) ->
val (_, matchingDetectedBeacons) = trianglesFromDetectedBeacons
.single { (detectedTriangle, _) -> triangle == detectedTriangle }
turns.flatMap { turn ->
rotations.mapNotNull { rotation ->
val match = matchingDetectedBeacons[0]
val faced = beacons[0].face(turn, rotation)
val distance1 = match.distance(faced)
val distance2 = matchingDetectedBeacons[1].distance(beacons[1].face(turn, rotation))
val distance3 = matchingDetectedBeacons[2].distance(beacons[2].face(turn, rotation))
if (distance1 == distance2 && distance1 == distance3)
Correction(turn, rotation, faced.x - match.x, faced.y - match.y, faced.z - match.z)
else null
}
}.toSet()
}
.filterNot { corrections -> corrections.isEmpty() }
.reduce { acc, corrections -> acc intersect corrections }
.let { corrections ->
if (corrections.size == 1) corrections.first() else throw IllegalStateException()
}
private fun Position.face(turn: Turn, rotation: Rotate) = when (turn to rotation) {
Turn.NONE to Rotate.NONE -> this
Turn.NONE to Rotate.CLOCKWISE -> Position(this.y, -this.x, this.z)
Turn.NONE to Rotate.COUNTERCLOCKWISE -> Position(-this.y, this.x, this.z)
Turn.NONE to Rotate.UPSIDE_DOWN -> Position(-this.x, -this.y, this.z)
Turn.RIGHT to Rotate.NONE -> Position(this.z, this.y, -this.x)
Turn.RIGHT to Rotate.CLOCKWISE -> Position(this.z, -this.x, -this.y)
Turn.RIGHT to Rotate.COUNTERCLOCKWISE -> Position(this.z, this.x, this.y)
Turn.RIGHT to Rotate.UPSIDE_DOWN -> Position(this.z, -this.y, this.x)
Turn.LEFT to Rotate.NONE -> Position(-this.z, this.y, this.x)
Turn.LEFT to Rotate.CLOCKWISE -> Position(-this.z, -this.x, this.y)
Turn.LEFT to Rotate.COUNTERCLOCKWISE -> Position(-this.z, this.x, -this.y)
Turn.LEFT to Rotate.UPSIDE_DOWN -> Position(-this.z, -this.y, -this.x)
Turn.UP to Rotate.NONE -> Position(this.x, this.z, -this.y)
Turn.UP to Rotate.CLOCKWISE -> Position(this.y, this.z, this.x)
Turn.UP to Rotate.COUNTERCLOCKWISE -> Position(-this.y, this.z, -this.x)
Turn.UP to Rotate.UPSIDE_DOWN -> Position(-this.x, this.z, this.y)
Turn.DOWN to Rotate.NONE -> Position(this.x, -this.z, this.y)
Turn.DOWN to Rotate.CLOCKWISE -> Position(-this.y, -this.z, this.x)
Turn.DOWN to Rotate.COUNTERCLOCKWISE -> Position(this.y, -this.z, -this.x)
Turn.DOWN to Rotate.UPSIDE_DOWN -> Position(-this.x, -this.z, -this.y)
Turn.BACKWARDS to Rotate.NONE -> Position(-this.x, this.y, -this.z)
Turn.BACKWARDS to Rotate.CLOCKWISE -> Position(this.y, this.x, -this.z)
Turn.BACKWARDS to Rotate.COUNTERCLOCKWISE -> Position(-this.y, -this.x, -this.z)
Turn.BACKWARDS to Rotate.UPSIDE_DOWN -> Position(this.x, -this.y, -this.z)
else -> throw IllegalStateException()
}
private fun Position.distance(element: Position = Position(0, 0, 0)) =
abs(this.x - element.x) + abs(this.y - element.y) + abs(this.z - element.z)
private fun getScanners() = Util.getInputAsListOfString("day19-input.txt")
.map {
if (it.contains(','))
it.split(',').let { s -> Position(s[0].toInt(), s[1].toInt(), s[2].toInt()) }
else null
}
.splitWhen { it == null }
.mapIndexed { index, it -> Scanner(index, it.filterNotNull().toSet()) }
@Test
fun `face Tests`() {
assertEquals(Position(1, 2, 3), Position(1, 2, 3).face(Turn.NONE, Rotate.NONE))
assertEquals(Position(2, -1, 3), Position(1, 2, 3).face(Turn.NONE, Rotate.CLOCKWISE))
assertEquals(Position(-2, 1, 3), Position(1, 2, 3).face(Turn.NONE, Rotate.COUNTERCLOCKWISE))
assertEquals(Position(-1, -2, 3), Position(1, 2, 3).face(Turn.NONE, Rotate.UPSIDE_DOWN))
assertEquals(Position(3, 2, -1), Position(1, 2, 3).face(Turn.RIGHT, Rotate.NONE))
assertEquals(Position(3, -1, -2), Position(1, 2, 3).face(Turn.RIGHT, Rotate.CLOCKWISE))
assertEquals(Position(3, 1, 2), Position(1, 2, 3).face(Turn.RIGHT, Rotate.COUNTERCLOCKWISE))
assertEquals(Position(3, -2, 1), Position(1, 2, 3).face(Turn.RIGHT, Rotate.UPSIDE_DOWN))
assertEquals(Position(-3, 2, 1), Position(1, 2, 3).face(Turn.LEFT, Rotate.NONE))
assertEquals(Position(-3, -1, 2), Position(1, 2, 3).face(Turn.LEFT, Rotate.CLOCKWISE))
assertEquals(Position(-3, 1, -2), Position(1, 2, 3).face(Turn.LEFT, Rotate.COUNTERCLOCKWISE))
assertEquals(Position(-3, -2, -1), Position(1, 2, 3).face(Turn.LEFT, Rotate.UPSIDE_DOWN))
assertEquals(Position(1, 3, -2), Position(1, 2, 3).face(Turn.UP, Rotate.NONE))
assertEquals(Position(2, 3, 1), Position(1, 2, 3).face(Turn.UP, Rotate.CLOCKWISE))
assertEquals(Position(-2, 3, -1), Position(1, 2, 3).face(Turn.UP, Rotate.COUNTERCLOCKWISE))
assertEquals(Position(-1, 3, 2), Position(1, 2, 3).face(Turn.UP, Rotate.UPSIDE_DOWN))
assertEquals(Position(1, -3, 2), Position(1, 2, 3).face(Turn.DOWN, Rotate.NONE))
assertEquals(Position(-2, -3, 1), Position(1, 2, 3).face(Turn.DOWN, Rotate.CLOCKWISE))
assertEquals(Position(2, -3, -1), Position(1, 2, 3).face(Turn.DOWN, Rotate.COUNTERCLOCKWISE))
assertEquals(Position(-1, -3, -2), Position(1, 2, 3).face(Turn.DOWN, Rotate.UPSIDE_DOWN))
assertEquals(Position(-1, 2, -3), Position(1, 2, 3).face(Turn.BACKWARDS, Rotate.NONE))
assertEquals(Position(2, 1, -3), Position(1, 2, 3).face(Turn.BACKWARDS, Rotate.CLOCKWISE))
assertEquals(Position(-2, -1, -3), Position(1, 2, 3).face(Turn.BACKWARDS, Rotate.COUNTERCLOCKWISE))
assertEquals(Position(1, -2, -3), Position(1, 2, 3).face(Turn.BACKWARDS, Rotate.UPSIDE_DOWN))
assertEquals(Position(1, -1, 1), Position(-1, -1, 1).face(Turn.DOWN, Rotate.UPSIDE_DOWN))
assertEquals(Position(2, -2, 2), Position(-2, -2, 2).face(Turn.DOWN, Rotate.UPSIDE_DOWN))
assertEquals(Position(3, -3, 3), Position(-3, -3, 3).face(Turn.DOWN, Rotate.UPSIDE_DOWN))
assertEquals(Position(2, -1, 3), Position(-2, -3, 1).face(Turn.DOWN, Rotate.UPSIDE_DOWN))
assertEquals(Position(-5, 4, -6), Position(5, 6, -4).face(Turn.DOWN, Rotate.UPSIDE_DOWN))
assertEquals(Position(-8, -7, 0), Position(8, 0, 7).face(Turn.DOWN, Rotate.UPSIDE_DOWN))
assertEquals(Position(-1, -1, -1), Position(-1, -1, 1).face(Turn.LEFT, Rotate.NONE))
assertEquals(Position(-2, -2, -2), Position(-2, -2, 2).face(Turn.LEFT, Rotate.NONE))
assertEquals(Position(-3, -3, -3), Position(-3, -3, 3).face(Turn.LEFT, Rotate.NONE))
assertEquals(Position(-1, -3, -2), Position(-2, -3, 1).face(Turn.LEFT, Rotate.NONE))
assertEquals(Position(4, 6, 5), Position(5, 6, -4).face(Turn.LEFT, Rotate.NONE))
assertEquals(Position(-7, 0, 8), Position(8, 0, 7).face(Turn.LEFT, Rotate.NONE))
assertEquals(Position(1, 1, -1), Position(-1, -1, 1).face(Turn.RIGHT, Rotate.UPSIDE_DOWN))
assertEquals(Position(2, 2, -2), Position(-2, -2, 2).face(Turn.RIGHT, Rotate.UPSIDE_DOWN))
assertEquals(Position(3, 3, -3), Position(-3, -3, 3).face(Turn.RIGHT, Rotate.UPSIDE_DOWN))
assertEquals(Position(1, 3, -2), Position(-2, -3, 1).face(Turn.RIGHT, Rotate.UPSIDE_DOWN))
assertEquals(Position(-4, -6, 5), Position(5, 6, -4).face(Turn.RIGHT, Rotate.UPSIDE_DOWN))
assertEquals(Position(7, 0, 8), Position(8, 0, 7).face(Turn.RIGHT, Rotate.UPSIDE_DOWN))
assertEquals(Position(1, 1, 1), Position(-1, -1, 1).face(Turn.UP, Rotate.COUNTERCLOCKWISE))
assertEquals(Position(2, 2, 2), Position(-2, -2, 2).face(Turn.UP, Rotate.COUNTERCLOCKWISE))
assertEquals(Position(3, 3, 3), Position(-3, -3, 3).face(Turn.UP, Rotate.COUNTERCLOCKWISE))
assertEquals(Position(3, 1, 2), Position(-2, -3, 1).face(Turn.UP, Rotate.COUNTERCLOCKWISE))
assertEquals(Position(-6, -4, -5), Position(5, 6, -4).face(Turn.UP, Rotate.COUNTERCLOCKWISE))
assertEquals(Position(0, 7, -8), Position(8, 0, 7).face(Turn.UP, Rotate.COUNTERCLOCKWISE))
}
@Test
fun `distance Tests`() {
assertEquals(6, Position(0, 0, 0).distance(Position(1, 2, 3)))
assertEquals(6, Position(1, 2, 3).distance())
assertEquals(12, Position(-1, -2, -3).distance(Position(1, 2, 3)))
}
}
| 0 | Kotlin | 1 | 2 | 8bc5e92ce961440e011688319e07ca9a4a86d9c9 | 13,218 | adventofcode | MIT License |
src/main/kotlin/Day09.kt | arosenf | 726,114,493 | false | {"Kotlin": 40487} | import kotlin.system.exitProcess
fun main(args: Array<String>) {
if (args.isEmpty() or (args.size < 2)) {
println("Input not specified")
exitProcess(1)
}
val fileName = args.first()
println("Reading $fileName")
val lines = readLines(fileName)
val result =
if (args[1] == "part1") {
Day09().predict(lines)
} else {
Day09().predictBackwards(lines)
}
println("Result: $result")
}
class Day09 {
fun predict(lines: Sequence<String>): Long {
val sequences = reduceErrors(lines)
// Extrapolate next value
return sequences.sumOf { sequence -> sequence.sumOf { it.last() } }
}
fun predictBackwards(lines: Sequence<String>): Long {
val sequences = reduceErrors(lines)
return sequences.sumOf { sequence ->
val pairs = sequence.map { line -> Pair(0L, line.first()) }
.reversed()
.toMutableList()
// Cannot modify list in-place with zipWithNext
for (i in 0..<pairs.size - 1) {
val current = pairs[i]
val next = pairs[i + 1]
pairs[i + 1] = Pair(next.second - current.first, next.second)
}
pairs.last().first
}
}
}
private fun reduceErrors(lines: Sequence<String>): List<List<List<Long>>> {
val sequences = mutableListOf<List<List<Long>>>()
lines.forEach { l ->
val sequence = mutableListOf<List<Long>>()
var current = l.split(' ').map { s -> s.toLong() }
sequence.add(current)
while (current.any { it != 0L }) {
current = current.zipWithNext { x: Long, y: Long -> y - x }
sequence.add(current)
}
sequences.add(sequence)
}
return sequences
}
| 0 | Kotlin | 0 | 0 | d9ce83ee89db7081cf7c14bcad09e1348d9059cb | 1,823 | adventofcode2023 | MIT License |
src/main/kotlin/y2022/day07/Day07.kt | TimWestmark | 571,510,211 | false | {"Kotlin": 97942, "Shell": 1067} | package y2022.day07
fun main() {
AoCGenerics.printAndMeasureResults(
part1 = { part1() },
part2 = { part2() }
)
}
data class Directory(
val name: String,
val subDirs: MutableList<Directory>,
val parentDir: Directory?,
var size: Int
)
fun input(): Directory {
val root = Directory("/", mutableListOf(), null, 0)
var currentDir = root
AoCGenerics.getInputLines("/y2022/day07/input.txt")
.forEach { line ->
when {
line.startsWith("$ cd /") || line == "$ ls" -> {}
line.startsWith("$ cd ..") -> currentDir = currentDir.parentDir!!
line.startsWith("$ cd ") -> currentDir = currentDir.subDirs.find { dir -> dir.name == line.split(" ")[2] }!!
line.startsWith("dir") -> currentDir.subDirs.add(
Directory(
line.split(" ")[1],
mutableListOf(),
currentDir,
0
)
)
else -> currentDir.addFilesize(line.split(" ")[0].toInt())
}
}
return root
}
fun Directory.addFilesize(size: Int) {
this.size += size
if (parentDir != null) {
this.parentDir.addFilesize(size)
}
}
fun getDirSizes(dir: Directory, resultList: MutableList<Int>) {
resultList.add(dir.size)
dir.subDirs.forEach {
getDirSizes(it, resultList)
}
}
fun part1(): Int {
val root = input()
val flatDirSizes = mutableListOf<Int>()
getDirSizes(root, flatDirSizes)
return flatDirSizes.filter { dirSize -> dirSize <= 100000 }.sum()
}
fun part2(): Int {
val root = input()
val totalSpace = 70_000_000
val freeSpaceNeeded = 30_000_000
val unusedSpace = totalSpace - root.size
val spaceToBeDeleted = freeSpaceNeeded - unusedSpace
val flatDirSizes = mutableListOf<Int>()
getDirSizes(root, flatDirSizes)
return flatDirSizes.filter { dirSize -> dirSize >= spaceToBeDeleted }.minOf{ it }
} | 0 | Kotlin | 0 | 0 | 23b3edf887e31bef5eed3f00c1826261b9a4bd30 | 2,046 | AdventOfCode | MIT License |
src/2021-Day02.kt | frozbiz | 573,457,870 | false | {"Kotlin": 124645} | fun main() {
// coords = [0,0,0]
// for line in input:
// (cmd, distance) = line.split(" ")
// distance = int(distance)
// if cmd == "forward":
// coords[0] += distance
// coords[1] += distance * coords[2]
// elif cmd == "up":
// coords[2] -= distance
// else:
// coords[2] += distance
// return coords
//
// coords = solution2(test_input)
// print(f"{coords}, {coords[0] * coords[1]}")
//
// with file_path.open() as file:
// coords = solution2(file)
// print(f"{coords}, {coords[0] * coords[1]}")
//
fun part1(input: List<String>): List<Int> {
val coords = mutableListOf(0, 0)
for (line in input) {
val (cmd, distance) = line.split(' ', '\n')
var dist = distance.toInt()
when (cmd) {
"forward" -> coords[0] += dist
"up" -> coords[1] -= dist
else -> coords[1] += dist
}
}
return coords
}
fun part2(input: List<String>): List<Int> {
val coords = mutableListOf(0, 0, 0)
for (line in input) {
val (cmd, distance) = line.split(' ', '\n')
var dist = distance.toInt()
when (cmd) {
"forward" -> {
coords[0] += dist
coords[1] += dist * coords[2]
}
"up" -> coords[2] -= dist
else -> coords[2] += dist
}
}
return coords
}
// test if implementation meets criteria from the description, like:
val testInput = listOf(
"forward 5\n",
"down 5\n",
"forward 8\n",
"up 3\n",
"down 8\n",
"forward 2\n"
)
var coords = part1(testInput)
println("${coords}, ${coords[1] * coords[0]}")
check(coords[0]*coords[1] == 150)
coords = part2(testInput)
println("${coords}, ${coords[1] * coords[0]}")
check(coords[0]*coords[1] == 900)
val input = readInput("2021-day2")
coords = part1(input)
println("${coords}, ${coords[1] * coords[0]}")
coords = part2(input)
println("${coords}, ${coords[1] * coords[0]}")
}
| 0 | Kotlin | 0 | 0 | 4feef3fa7cd5f3cea1957bed1d1ab5d1eb2bc388 | 2,171 | 2022-aoc-kotlin | Apache License 2.0 |
src/main/kotlin/puzzle10/SyntaxScorer.kt | tpoujol | 436,532,129 | false | {"Kotlin": 47470} | package puzzle10
import java.lang.IllegalStateException
import kotlin.system.measureTimeMillis
fun main() {
val syntaxScorer = SyntaxScorer()
val time = measureTimeMillis {
println("Bad line scoring: ${syntaxScorer.fixBrokenLines()}")
println("Incomplete line scoring: ${syntaxScorer.fixIncompleteLines()}")
}
println("time: $time")
}
sealed interface SyntaxCharacter{
fun produceMatchingCharacter(): SyntaxCharacter
}
enum class OpeningSyntaxCharacter: SyntaxCharacter {
Parenthesis,
CurlyBracket,
AngleBracket,
SquareBracket;
override fun produceMatchingCharacter(): ClosingSyntaxCharacter = when(this) {
Parenthesis -> ClosingSyntaxCharacter.Parenthesis
CurlyBracket -> ClosingSyntaxCharacter.CurlyBracket
AngleBracket -> ClosingSyntaxCharacter.AngleBracket
SquareBracket -> ClosingSyntaxCharacter.SquareBracket
}
}
enum class ClosingSyntaxCharacter: SyntaxCharacter {
Parenthesis,
CurlyBracket,
AngleBracket,
SquareBracket;
override fun produceMatchingCharacter(): OpeningSyntaxCharacter = when(this) {
Parenthesis -> OpeningSyntaxCharacter.Parenthesis
CurlyBracket -> OpeningSyntaxCharacter.CurlyBracket
AngleBracket -> OpeningSyntaxCharacter.AngleBracket
SquareBracket -> OpeningSyntaxCharacter.SquareBracket
}
fun toSyntaxErrorScore(): Int = when(this) {
Parenthesis -> 3
CurlyBracket -> 1197
AngleBracket -> 25137
SquareBracket -> 57
}
fun toAutocompleteScore(): Int = when(this) {
Parenthesis -> 1
CurlyBracket -> 3
AngleBracket -> 4
SquareBracket -> 2
}
}
fun Char.toSyntaxCharacter():SyntaxCharacter = when(this){
'(' -> OpeningSyntaxCharacter.Parenthesis
'{' -> OpeningSyntaxCharacter.CurlyBracket
'<' -> OpeningSyntaxCharacter.AngleBracket
'[' -> OpeningSyntaxCharacter.SquareBracket
')' -> ClosingSyntaxCharacter.Parenthesis
'}' -> ClosingSyntaxCharacter.CurlyBracket
'>' -> ClosingSyntaxCharacter.AngleBracket
']' -> ClosingSyntaxCharacter.SquareBracket
else -> { throw IllegalArgumentException("unknown opening Character") }
}
class SyntaxScorer {
private val input = SyntaxScorer::class.java.getResource("/input/puzzle10.txt")
?.readText()
?.split("\n")
?.map {
it.fold(mutableListOf()) { acc: MutableList<SyntaxCharacter>, c: Char ->
acc.apply { add(c.toSyntaxCharacter()) }
}.toList()
}
?: listOf()
fun fixBrokenLines(): Int {
return input.fold(mutableListOf()) { acc: MutableList<LineProblem.SyntaxErrorProblem>, line: List<SyntaxCharacter> ->
acc.apply {
findProblemInLine(line)
.takeIf { it is LineProblem.SyntaxErrorProblem }
?.also { add(it as LineProblem.SyntaxErrorProblem) }
}
}
.sumOf { it.illegalClosingCharacter.toSyntaxErrorScore() }
}
fun fixIncompleteLines(): Long {
val lineProblems = input.fold(mutableListOf()) { acc: MutableList<LineProblem.IncompleteLineProblem>, line: List<SyntaxCharacter> ->
acc.apply {
findProblemInLine(line)
.takeIf { it is LineProblem.IncompleteLineProblem }
?.also { add(it as LineProblem.IncompleteLineProblem) }
}
}.toList()
val result = lineProblems.map {
it.orphanedOpeningCharacterList
.reversed()
.fold(0L) { acc: Long, openingSyntaxCharacter: OpeningSyntaxCharacter ->
acc * 5 + openingSyntaxCharacter.produceMatchingCharacter().toAutocompleteScore()
}
}
.sortedBy { it }
return result[result.size.floorDiv(2)]
}
private companion object {
sealed class LineProblem{
data class SyntaxErrorProblem(val illegalClosingCharacter: ClosingSyntaxCharacter): LineProblem()
data class IncompleteLineProblem(val orphanedOpeningCharacterList: List<OpeningSyntaxCharacter>): LineProblem()
}
private fun findProblemInLine(line: List<SyntaxCharacter>): LineProblem {
val openingCharacters = mutableListOf<OpeningSyntaxCharacter>()
for (character in line){
if (character is ClosingSyntaxCharacter) {
if (openingCharacters.isEmpty()){
return LineProblem.SyntaxErrorProblem(character)
} else if (openingCharacters.last().produceMatchingCharacter() != character) {
return LineProblem.SyntaxErrorProblem(character)
} else {
openingCharacters.removeLast()
}
}
else if (character is OpeningSyntaxCharacter) {
openingCharacters.add(character)
}
else {
throw IllegalStateException("character: $character is neither an opening nor a closing syntax char")
}
}
return LineProblem.IncompleteLineProblem(openingCharacters.toList())
}
}
} | 0 | Kotlin | 0 | 1 | 6d474b30e5204d3bd9c86b50ed657f756a638b2b | 5,283 | aoc-2021 | Apache License 2.0 |
src/day10/Day10.kt | kerchen | 573,125,453 | false | {"Kotlin": 137233} | package day10
import readInput
data class Instruction(val duration: Int, val delta: Int)
fun main() {
fun part1(input: List<String>): Int {
var signalStrengthSum = 0
var x = 1
var counter = 0
var cycle = 0
var instruction: Instruction
val signalSampleCycles = listOf(20, 60, 100, 140, 180, 220)
val signalSampleCycleIt = signalSampleCycles.iterator()
var nextSampleCycle = signalSampleCycleIt.next()
for (instructionString in input) {
counter += 1
instruction = if (instructionString.startsWith("noop")) {
Instruction(1, 0)
} else {
Instruction(2, instructionString.split(" ")[1].toInt())
}
val instructionEndCycle = cycle + instruction.duration
if (nextSampleCycle in cycle..instructionEndCycle){
// day10.Instruction will complete after the end of a sample cycle, so use
// pre-instruction value of x for signal strength.
signalStrengthSum += x * nextSampleCycle
x += instruction.delta
if (!signalSampleCycleIt.hasNext()) break
nextSampleCycle = signalSampleCycleIt.next()
} else {
x += instruction.delta
}
cycle += instruction.duration
}
return signalStrengthSum
}
fun part2(input: List<String>): List<CharArray> {
val columnCount = 40
val rowCount = 6
val image = List(rowCount) { CharArray(columnCount) { '.' } }
var x = 1
var counter = 0
var cycle = 0
var imageRow = 0
var imageColumn = 0
var instruction: Instruction
for (instructionString in input) {
counter += 1
instruction = if (instructionString.startsWith("noop")) {
Instruction(1, 0)
} else {
Instruction(2, instructionString.split(" ")[1].toInt())
}
for (crtCycle in IntRange(cycle, cycle+instruction.duration-1)) {
if (imageColumn >= x - 1 && imageColumn <= x + 1) {
image[imageRow][imageColumn] = '#'
}
imageColumn += 1
if (imageColumn == columnCount)
{
imageColumn = 0
imageRow += 1
}
}
x += instruction.delta
cycle += instruction.duration
}
return image
}
val testInput = readInput("Day10_test")
check(part1(testInput) == 13140)
val testImage = part2(testInput)
val expectedImage = listOf(
"##..##..##..##..##..##..##..##..##..##..",
"###...###...###...###...###...###...###.",
"####....####....####....####....####....",
"#####.....#####.....#####.....#####.....",
"######......######......######......####",
"#######.......#######.......#######.....")
for (row in IntRange(0, 5)) {
check(String(testImage[row]) == expectedImage[row])
}
val input = readInput("Day10")
println(part1(input))
val image = part2(input)
for (row in image) {
println(row)
}
}
| 0 | Kotlin | 0 | 0 | dc15640ff29ec5f9dceb4046adaf860af892c1a9 | 3,275 | AdventOfCode2022 | Apache License 2.0 |
src/main/kotlin/days/Day2.kt | jgrgt | 433,952,606 | false | {"Kotlin": 113705} | package days
class Day2 : Day(2) {
override fun partOne(): Any {
val commands = inputList.map { Command.from(it) }
val position = commands.fold(Position(0, 0)) { position, command ->
move(position, command)
}
return position.horizontal * position.depth
}
override fun partTwo(): Any {
val commands = inputList.map { Command.from(it) }
val position = commands.fold(Submarine(0, 0, 0)) { submarine, command ->
moveWithAim(submarine, command)
}
return position.horizontal * position.depth
}
}
fun move(p: Position, c: Command): Position {
return when (c) {
is Forward -> p.forward(c.steps)
is Down -> p.down(c.steps)
is Up -> p.up(c.steps)
}
}
fun moveWithAim(s: Submarine, c: Command): Submarine {
return when (c) {
is Forward -> s.forward(c.steps)
is Down -> s.down(c.steps)
is Up -> s.up(c.steps)
}
}
data class Position(val horizontal: Int, val depth: Int) {
fun forward(steps: Int): Position {
return copy(horizontal = horizontal + steps)
}
fun down(steps: Int): Position {
return copy(depth = depth + steps)
}
fun up(steps: Int): Position {
return copy(depth = depth - steps)
}
}
data class Submarine(val horizontal: Int, val depth: Int, val aim: Int) {
fun forward(steps: Int): Submarine {
return copy(horizontal = horizontal + steps, depth = depth + aim * steps)
}
fun down(steps: Int): Submarine {
return copy(aim = aim + steps)
}
fun up(steps: Int): Submarine {
return copy(aim = aim - steps)
}
}
sealed class Command {
companion object {
fun from(s: String): Command {
val parts = s.split(" ")
if (parts.size != 2) {
error("Command should have 2 parts split by a space")
}
val (type, value) = parts
return when (type) {
"forward" -> Forward(value.toInt())
"down" -> Down(value.toInt())
"up" -> Up(value.toInt())
else -> error("Unknown command ${type}")
}
}
}
}
class Forward(val steps: Int) : Command()
class Up(val steps: Int) : Command()
class Down(val steps: Int) : Command()
| 0 | Kotlin | 0 | 0 | 6231e2092314ece3f993d5acf862965ba67db44f | 2,341 | aoc2021 | Creative Commons Zero v1.0 Universal |
src/Day05.kt | rk012 | 574,169,156 | false | {"Kotlin": 9389} | fun main() {
fun List<String>.parseLayout() = ((last().length + 2) / 4).let { size ->
dropLast(1).map { line ->
("$line ").chunked(4).let { items ->
List(size) {
items.getOrNull(it)?.ifBlank { null }?.get(1)
}
}
}
}
fun List<String>.layoutColumns() = parseLayout().let { layout ->
List(layout.last().size) { n ->
layout.map { it.getOrNull(n) }.asReversed().filterNotNull()
}
}
fun List<List<Char>>.performMove(amount: Int, from: Int, to: Int) = mapIndexed { i, items ->
when (i) {
from-1 -> items.dropLast(amount)
to-1 -> items + get(from-1).takeLast(amount).asReversed()
else -> items
}
}
fun List<List<Char>>.performGroupMove(amount: Int, from: Int, to: Int) = mapIndexed { i, items ->
when (i) {
from-1 -> items.dropLast(amount)
to-1 -> items + get(from-1).takeLast(amount)
else -> items
}
}
fun List<String>.runMoves(useChunked: Boolean) = let { lines ->
lines.takeWhile { it.isNotBlank() }.layoutColumns() to lines.takeLastWhile { it.isNotBlank() }
}.let { (columns, directions) ->
directions.map { s ->
s.split(" ").let { chunks ->
listOf(chunks[1], chunks[3], chunks[5]).map {
it.toInt()
}
}
}.fold(columns) { acc, (amount, from, to) ->
if (useChunked) acc.performGroupMove(amount, from, to)
else acc.performMove(amount, from, to)
}.map {
it.last()
}.joinToString("")
}
fun part1(input: List<String>) = input.runMoves(false)
fun part2(input: List<String>) = input.runMoves(true)
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | bfb4c56c4d4c8153241fa6aa6ae0e829012e6679 | 2,103 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/com/github/michaelbull/advent2021/day4/BingoBoard.kt | michaelbull | 433,565,311 | false | {"Kotlin": 162839} | package com.github.michaelbull.advent2021.day4
import com.github.michaelbull.advent2021.math.Vector2
private val ROW_REGEX = "(\\d+)+".toRegex()
fun Iterator<String>.toBingoBoard(size: Int): BingoBoard {
val cells = buildMap {
repeat(size) { rowIndex ->
val row = this@toBingoBoard.next()
val values = ROW_REGEX.findAll(row).map { it.value.toInt() }
values.forEachIndexed { columnIndex, value ->
set(Vector2(columnIndex, rowIndex), value)
}
}
}
return BingoBoard(cells)
}
data class BingoBoard(
val cells: Map<Vector2, Int>
) {
private val columnIndices: Set<Int>
get() = cells.map { it.key.x }.toSet()
private val rowIndices: Set<Int>
get() = cells.map { it.key.y }.toSet()
fun solvedBy(draw: List<Int>): Boolean {
return columnsSolved(draw) || rowsSolved(draw)
}
fun score(draw: List<Int>): Int {
val unmarkedSum = cells.filterValues { it !in draw }.values.sum()
return unmarkedSum * draw.last()
}
private fun columnsSolved(draw: List<Int>): Boolean {
return columnIndices.any { columnSolved(it, draw) }
}
private fun rowsSolved(draw: List<Int>): Boolean {
return rowIndices.any { rowSolved(it, draw) }
}
private fun columnSolved(column: Int, draw: List<Int>): Boolean {
return columnValues(column).all(draw::contains)
}
private fun rowSolved(row: Int, draw: List<Int>): Boolean {
return rowValues(row).all(draw::contains)
}
private fun columnValues(index: Int): List<Int> {
return cells
.filterKeys { it.x == index }
.map(Map.Entry<Vector2, Int>::value)
}
private fun rowValues(index: Int): List<Int> {
return cells
.filterKeys { it.y == index }
.map(Map.Entry<Vector2, Int>::value)
}
}
| 0 | Kotlin | 0 | 4 | 7cec2ac03705da007f227306ceb0e87f302e2e54 | 1,910 | advent-2021 | ISC License |
src/Day05.kt | chasebleyl | 573,058,526 | false | {"Kotlin": 15274} |
data class Stack(
val id: Int,
val crates: ArrayDeque<String> = ArrayDeque(),
)
fun ArrayDeque<String>.removeLastN(n: Int): ArrayDeque<String> {
val elements = ArrayDeque<String>()
for (i in 1..n) {
elements.addFirst(this.removeLast())
}
return elements
}
fun ArrayDeque<String>.addLastN(elements: ArrayDeque<String>) {
for (i in 1..elements.size) {
this.addLast(elements.removeFirst())
}
}
data class StackAction(
val number: Int,
val from: Int,
val to: Int,
) {
companion object {
operator fun invoke(matchResult: MatchResult) = StackAction(
matchResult.groupValues[1].toInt(),
matchResult.groupValues[2].toInt(),
matchResult.groupValues[3].toInt(),
)
}
}
fun buildEmptyStacks(input: String): List<Stack> =
mutableListOf<Stack>().let { stackList ->
input.chunked(4).forEachIndexed { index, _ ->
stackList.add(Stack(index + 1))
}
stackList
}
fun buildStacks(input: List<String>): List<Stack> {
val stackAccumulators = buildEmptyStacks(input[0])
drawing@ for(line in input) {
if (line.isEmpty()) break@drawing
val rawCrates = line.chunked(4)
for (i in rawCrates.indices) {
val supply = rawCrates[i].replace("[","").replace("]","").replace(" ","")
if (supply.isNotEmpty() && !supply.all { char -> char.isDigit() }) {
stackAccumulators[i].crates.addFirst(supply)
}
}
}
return stackAccumulators
}
fun main() {
fun part1(input: List<String>): String {
val stacks = buildStacks(input)
input.forEach { line ->
if (line.contains("move")) {
"""move\s(\d+)\sfrom\s(\d+)\sto\s(\d+)""".toRegex().find(line)?.let { matchResult ->
val stackAction = StackAction(matchResult)
stacks.find { it.id == stackAction.to }?.let { destination ->
stacks.find { it.id == stackAction.from }?.let { origin ->
for (i in 1..stackAction.number) {
destination.crates.addLast(origin.crates.removeLast())
}
}
}
}
}
}
var topSupplies = ""
stacks.forEach { stack ->
topSupplies += stack.crates.last()
}
return topSupplies
}
fun part2(input: List<String>): String {
val stacks = buildStacks(input)
input.forEach { line ->
if (line.contains("move")) {
"""move\s(\d+)\sfrom\s(\d+)\sto\s(\d+)""".toRegex().find(line)?.let { matchResult ->
val stackAction = StackAction(matchResult)
stacks.find { it.id == stackAction.to }?.let { destination ->
stacks.find { it.id == stackAction.from }?.let { origin ->
destination.crates.addLastN(origin.crates.removeLastN(stackAction.number))
}
}
}
}
}
var topSupplies = ""
stacks.forEach { stack ->
topSupplies += stack.crates.last()
}
return topSupplies
}
val input = readInput("Day05")
val testInput = readInput("Day05_test")
// PART 1
check(part1(testInput) == "CMZ")
println(part1(input))
// PART 2
check(part2(testInput) == "MCD")
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | f2f5cb5fd50fb3e7fb9deeab2ae637d2e3605ea3 | 3,564 | aoc-2022 | Apache License 2.0 |
kotlin/src/2022/Day07_2022.kt | regob | 575,917,627 | false | {"Kotlin": 50757, "Python": 46520, "Shell": 430} |
private data class Elem(val parent: Elem?, val children: MutableMap<String, Elem> = mutableMapOf(), var size: Int = 0)
private fun calcTotalSize(node: Elem, acc: MutableList<Int>): Int {
var total = node.children.values.sumOf {
calcTotalSize(it, acc)
}
total += node.size
acc.add(total)
return total
}
fun main() {
val input = readInput(7).trim()
val cmds = input.split("$").asSequence()
.filter {it.isNotBlank()}
.map {
it.lines()
.map(String::trim)
.filter {x -> x.isNotBlank() }
}
val root = Elem(null)
var cur = root
for (cmdLines in cmds) {
val cmd = cmdLines[0]
when (cmd) {
"ls" -> cmdLines.subList(1, cmdLines.size).forEach {
val (x, y) = it.split(" ")
if (x == "dir") cur.children[y] = Elem(cur)
else cur.size += x.toInt()
}
else -> when(val tar = cmd.split(" ")[1]) {
"/" -> cur = root
".." -> cur = cur.parent!!
else -> cur = cur.children[tar]!!
}
}
}
val totals = mutableListOf<Int>()
val total = calcTotalSize(root, totals)
// part1
println(totals.filter {it <= 100000}.sum())
// part2
val minSize = 30000000 - (70000000 - total)
val res = totals.asSequence()
.filter {it >= minSize}
.min()
println(res)
} | 0 | Kotlin | 0 | 0 | cf49abe24c1242e23e96719cc71ed471e77b3154 | 1,463 | adventofcode | Apache License 2.0 |
src/day08/Day08.kt | TheJosean | 573,113,380 | false | {"Kotlin": 20611} | package day08
import readInput
fun main() {
fun List<List<Char>>.visibleLeft(i: Int, j: Int): Boolean {
val base = this[i][j]
for (x in j - 1 downTo 0) {
if (this[i][x] >= base) return false
}
return true
}
fun List<List<Char>>.visibleRight(i: Int, j: Int): Boolean {
val base = this[i][j]
for (x in j + 1 until this[i].size) {
if (this[i][x] >= base) return false
}
return true
}
fun List<List<Char>>.visibleTop(i: Int, j: Int): Boolean {
val base = this[i][j]
for (x in i - 1 downTo 0) {
if (this[x][j] >= base) return false
}
return true
}
fun List<List<Char>>.visibleBottom(i: Int, j: Int): Boolean {
val base = this[i][j]
for (x in i + 1 until size) {
if (this[x][j] >= base) return false
}
return true
}
fun List<List<Char>>.countLeft(i: Int, j: Int): Int {
val base = this[i][j]
var count = 0
for (x in j - 1 downTo 0) {
if (base > this[i][x]) count++
else return ++count
}
return count
}
fun List<List<Char>>.countRight(i: Int, j: Int): Int {
val base = this[i][j]
var count = 0
for (x in j + 1 until this[i].size) {
if (base > this[i][x]) count++
else return ++count
}
return count
}
fun List<List<Char>>.countTop(i: Int, j: Int): Int {
val base = this[i][j]
var count = 0
for (x in i - 1 downTo 0) {
if (base > this[x][j]) count++
else return ++count
}
return count
}
fun List<List<Char>>.countBottom(i: Int, j: Int): Int {
val base = this[i][j]
var count = 0
for (x in i + 1 until size) {
if (base > this[x][j]) count++
else return ++count
}
return count
}
fun List<List<Char>>.count(i: Int, j: Int): Int {
if (i == 0 || j == 0 || i == size || j == this[i].size) return 0
return countLeft(i, j) * countRight(i, j) * countTop(i, j) * countBottom(i, j)
}
fun List<List<Char>>.visible(i: Int, j: Int) =
i == 0 || j == 0 ||
visibleLeft(i, j) || visibleRight(i, j) || visibleTop(i, j) || visibleBottom(i, j)
fun part1(input: List<List<Char>>) =
input.mapIndexed { i, row ->
row.mapIndexed { j, _ -> input.visible(i, j) }.count { it }
}.sum()
fun part2(input: List<List<Char>>) =
input.mapIndexed { i, row ->
row.mapIndexed { j, _ -> input.count(i, j) }.max()
}.max()
// test if implementation meets criteria from the description, like:
val testInput = readInput("/day08/Day08_test")
check(part1(testInput.map { it.toList() }) == 21)
check(part2(testInput.map { it.toList() }) == 8)
val input = readInput("/day08/Day08")
println(part1(input.map { it.toList() }))
println(part2(input.map { it.toList() }))
}
| 0 | Kotlin | 0 | 0 | 798d5e9b1ce446ba3bac86f70b7888335e1a242b | 3,068 | advent-of-code | Apache License 2.0 |
src/Day02.kt | JonahBreslow | 578,314,149 | false | {"Kotlin": 6978} | import java.io.File
fun main(){
fun read_file(file_path: String) : List<String> {
val text = File(file_path).readLines()
return text
}
val fix = mapOf("A" to "X", "B" to "Y", "C" to "Z")
fun part1(x: String) : Int {
val me: String = x[2].toString()
val opp: String = fix.getValue(x[0].toString())
var score: Int = 0
// draw
if (opp == me) score += 3
// Win
if (opp == "X" && me == "Y") score +=6
if (opp == "Y" && me == "Z") score +=6
if (opp == "Z" && me == "X") score +=6
score += mapOf("X" to 1, "Y" to 2, "Z" to 3).getValue(me)
return score
}
fun part2(x: String): Int {
val result: String = x[2].toString()
val opp: String = x[0].toString()
var me: String = "A"
var score: Int = 0
// draw
if (result == "Y"){
score += 3
me = opp
}
// lose
if (result == "X"){
if (opp == "A") me = "C"
if (opp == "B") me = "A"
if (opp == "C") me = "B"
}
// win
if (result == "Z"){
score += 6
if (opp == "A") me = "B"
if (opp == "B") me = "C"
if (opp == "C") me = "A"
}
score += mapOf("A" to 1, "B" to 2, "C" to 3).getValue(me)
return score
}
val testFile = read_file("data/day2_test.txt")
check(testFile.map { part1(it)}.sum() == 15)
check(testFile.map { part2(it)}.sum() == 12)
val file = read_file("data/day2.txt")
println(file.map { part1(it)} .sum())
println(file.map { part2(it)} .sum())
}
| 0 | Kotlin | 0 | 1 | c307ff29616f613473768168cc831a7a3fa346c2 | 1,727 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/day04/Day04.kt | Volifter | 572,720,551 | false | {"Kotlin": 65483} | package day04
import utils.*
fun getRanges(input: List<String>): List<Pair<IntRange, IntRange>> {
val regex = """^(\d+)-(\d+),(\d+)-(\d+)$""".toRegex()
return input.map { line ->
val (a, b, c, d) = regex.find(line)!!.groupValues
.drop(1)
.map(String::toInt)
Pair(a..b, c..d)
}
}
fun part1(input: List<String>): Int = getRanges(input).count { (a, b) ->
a.first in b && a.last in b
|| b.first in a && b.last in a
}
fun part2(input: List<String>): Int = getRanges(input).count { (a, b) ->
maxOf(a.first, b.first) <= minOf(a.last, b.last)
}
fun main() {
val testInput = readInput("Day04_test")
expect(part1(testInput), 2)
expect(part2(testInput), 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | c2c386844c09087c3eac4b66ee675d0a95bc8ccc | 823 | AOC-2022-Kotlin | Apache License 2.0 |
src/main/kotlin/days_2021/Day9.kt | BasKiers | 434,124,805 | false | {"Kotlin": 40804} | package days_2021
import util.Day
class Day9 : Day(9) {
val input = inputList.map { row -> row.toCharArray().map(Char::digitToInt) }
fun getPosition(seaFloor: List<List<Int>>, position: Pair<Int, Int>) =
seaFloor.getOrNull(position.second)?.getOrNull(position.first)
val directions = listOf(1 to 0, 0 to 1, -1 to 0, 0 to -1)
fun getAdjacentHeights(seaFloor: List<List<Int>>, position: Pair<Int, Int>): List<Pair<Pair<Int, Int>, Int>> {
return directions.mapNotNull { (xDir, yDir) ->
val dirPos = xDir + position.first to yDir + position.second
val adjacentHeight = getPosition(seaFloor, dirPos)
if (adjacentHeight != null) {
dirPos to adjacentHeight
} else {
null
}
}
}
fun getBasin(seaFloor: List<List<Int>>, position: Pair<Int, Int>): List<Pair<Pair<Int, Int>, Int>>? {
val height = getPosition(seaFloor, position)
if (height == null || height == 9) {
return null
}
val discoveredPositions: MutableSet<Pair<Int, Int>> = mutableSetOf()
val heightsInBasin: MutableMap<Pair<Int, Int>, Int> = mutableMapOf(position to height)
while (discoveredPositions.size != heightsInBasin.size) {
val (positionToSearch) = heightsInBasin.asSequence().first { (pos) -> !discoveredPositions.contains(pos) }
val newHeights = getAdjacentHeights(seaFloor, positionToSearch)
.filterNot { (pos, height) -> height == 9 || heightsInBasin.any { (p) -> p == pos } }
for ((newPos, newHeight) in newHeights) {
heightsInBasin[newPos] = newHeight
}
discoveredPositions.add(positionToSearch)
}
return heightsInBasin.toList()
}
override fun partOne(): Any {
return input.flatMapIndexed { y, row ->
row.filterIndexed { x, height ->
getAdjacentHeights(
input,
x to y
).all { (_, adjacentHeight) -> adjacentHeight > height }
}.map { lowPoint -> lowPoint + 1 }
}.sum()
}
override fun partTwo(): Any {
var positions = input.flatMapIndexed { y, row -> row.mapIndexed { x, _ -> x to y } }
val basins: MutableList<List<Pair<Pair<Int, Int>, Int>>> = mutableListOf()
while (positions.isNotEmpty()) {
val (position, positionsLeft) = positions.first() to positions.drop(1)
val basin = getBasin(input, position)
if (basin != null) {
basins.add(basin)
positions = positionsLeft.filterNot { pos ->
basin.any { (basinPos) -> basinPos == pos }
}
} else {
positions = positionsLeft
}
}
return basins.map { basin -> basin.size }.sorted().takeLast(3).reduce { acc, size -> acc * size }
}
} | 0 | Kotlin | 0 | 0 | 870715c172f595b731ee6de275687c2d77caf2f3 | 2,969 | advent-of-code-2021 | Creative Commons Zero v1.0 Universal |
src/main/kotlin/com/groundsfam/advent/y2023/d13/Day13.kt | agrounds | 573,140,808 | false | {"Kotlin": 281620, "Shell": 742} | package com.groundsfam.advent.y2023.d13
import com.groundsfam.advent.DATAPATH
import com.groundsfam.advent.grids.Grid
import com.groundsfam.advent.timed
import kotlin.io.path.div
import kotlin.io.path.useLines
sealed interface Reflection
@JvmInline
value class Column(val n: Int) : Reflection
@JvmInline
value class Row(val n: Int) : Reflection
// count of differing characters between two lists
fun diffs(s1: List<Char>, s2: List<Char>): Int =
s1.zip(s2).count { (c1, c2) -> c1 != c2 }
fun findReflection(pattern: Grid<Char>, smudged: Boolean): Reflection? {
fun line(n: Int, byRows: Boolean): List<Char> =
if (byRows) {
pattern.getRow(n)
} else {
pattern.getCol(n)
}
fun find(byRows: Boolean): Int? {
val numLines = if (byRows) pattern.numRows else pattern.numCols
return (1 until numLines).firstOrNull { a ->
var smudgesRemaining = if (smudged) 1 else 0
val linesMatch = (0 until a).all { a1 ->
// line number of the reflection of a1 across a
val a2 = 2 * a - 1 - a1
// allows us to call diffs() even if a2 is too big
val diff = if (a2 >= numLines) null else diffs(line(a1, byRows), line(a2, byRows))
when (diff) {
// a2 is too big -- there's nothing to compare this line to
null -> true
// lines are identical
0 -> true
// lines are identical up to a smudge
1 -> {
smudgesRemaining--
true
}
// lines are different
else -> false
}
}
linesMatch && smudgesRemaining == 0
}
}
find(byRows = true)
?.also { return Row(it) }
find(byRows = false)
?.also { return Column(it) }
return null
}
fun main() = timed {
// list of patterns
// each pattern is a list of rows
// each row is a list of characters, a list-ified string
val patterns: List<Grid<Char>> = (DATAPATH / "2023/day13.txt").useLines { lines ->
val parsedPatterns = mutableListOf<Grid<Char>>()
var currPattern = Grid<Char>()
lines.forEach { line ->
if (line.isBlank()) {
parsedPatterns.add(currPattern)
currPattern = Grid()
} else {
currPattern.add(line.toMutableList())
}
}
if (currPattern.isNotEmpty()) {
parsedPatterns.add(currPattern)
}
parsedPatterns
}
fun List<Grid<Char>>.sumReflections(smudged: Boolean): Long =
this.sumOf { pattern ->
when (val r = findReflection(pattern, smudged)) {
is Row -> r.n * 100L
is Column -> r.n.toLong()
null -> throw RuntimeException("No${if (smudged) " smudged" else ""} reflection found for pattern $pattern")
}
}
patterns
.sumReflections(smudged = false)
.also { println("Part one: $it") }
patterns
.sumReflections(smudged = true)
.also { println("Part two: $it") }
}
| 0 | Kotlin | 0 | 1 | c20e339e887b20ae6c209ab8360f24fb8d38bd2c | 3,273 | advent-of-code | MIT License |
day16/src/Day16.kt | simonrules | 491,302,880 | false | {"Kotlin": 68645} | import java.io.File
class Day16(path: String) {
var binary = ""
var versionTotal = 0
init {
val text = File(path).readText()
text.forEach {
binary = binary.plus(when(it) {
'0' -> "0000"
'1' -> "0001"
'2' -> "0010"
'3' -> "0011"
'4' -> "0100"
'5' -> "0101"
'6' -> "0110"
'7' -> "0111"
'8' -> "1000"
'9' -> "1001"
'A' -> "1010"
'B' -> "1011"
'C' -> "1100"
'D' -> "1101"
'E' -> "1110"
'F' -> "1111"
else -> ""
})
}
}
private fun parsePacket(pos: Int): Pair<Int, Long> {
val version = getValue(binary.substring(pos, pos + 3))
versionTotal += version
val type = getValue(binary.substring(pos + 3, pos + 6))
return if (type == 4) {
parseLiteral(pos + 6)
} else {
parseOperator(pos + 6, type)
}
}
private fun parseLiteral(pos: Int): Pair<Int, Long> {
var cur = pos
var value = 0L
var lastOne = false
while (!lastOne) {
lastOne = binary[cur] == '0'
value *= 16 // number is in chunks of 4 bits
value += getValue(binary.substring(cur + 1, cur + 5))
cur += 5
}
//println("literal=$value")
return Pair(cur, value)
}
private fun operation(type: Int, values: List<Long>): Long {
return when(type) {
0 -> values.sum()
1 -> values.reduce { acc, i -> acc * i }
2 -> values.minOrNull()!!
3 -> values.maxOrNull()!!
5 -> if (values[0] > values[1]) 1 else 0
6 -> if (values[0] < values[1]) 1 else 0
7 -> if (values[0] == values[1]) 1 else 0
else -> 0
}
}
private fun parseOperator(pos: Int, type: Int): Pair<Int, Long> {
var cur = pos
val values = mutableListOf<Long>()
if (binary[cur] == '0') {
var length = getValue(binary.substring(cur + 1, cur + 16))
cur += 16
//println("length=$length")
while (length > 0) {
val (newCur, value) = parsePacket(cur)
length -= (newCur - cur)
cur = newCur
values.add(value)
}
} else {
var number = getValue(binary.substring(cur + 1, cur + 12))
cur += 12
//println("number=$number")
while (number > 0) {
val (newCur, value) = parsePacket(cur)
number--
cur = newCur
values.add(value)
}
}
return Pair(cur, operation(type, values))
}
private fun getValue(bits: String): Int {
var value = 0
for (i in 0..bits.lastIndex) {
value *= 2
value += if (bits[i] == '1') 1 else 0
}
return value
}
fun part1(): Int {
parsePacket(0)
return versionTotal
}
fun part2(): Long {
val (_, value) = parsePacket(0)
return value
}
}
fun main() {
val aoc = Day16("day16/input.txt")
println(aoc.part1())
println(aoc.part2())
}
| 0 | Kotlin | 0 | 0 | d9e4ae66e546f174bcf66b8bf3e7145bfab2f498 | 3,411 | aoc2021 | Apache License 2.0 |
src/main/kotlin/io/github/clechasseur/adventofcode/y2022/Day11.kt | clechasseur | 567,968,171 | false | {"Kotlin": 493887} | package io.github.clechasseur.adventofcode.y2022
object Day11 {
private val input = listOf(
Monkey(
id = 0,
items = listOf(63L, 84L, 80L, 83L, 84L, 53L, 88L, 72L),
op = { it * 11L },
test = { if (it % 13L == 0L) 4 else 7 }
),
Monkey(
id = 1,
items = listOf(67L, 56L, 92L, 88L, 84L),
op = { it + 4L },
test = { if (it % 11L == 0L) 5 else 3 }
),
Monkey(
id = 2,
items = listOf(52L),
op = { it * it },
test = { if (it % 2L == 0L) 3 else 1 }
),
Monkey(
id = 3,
items = listOf(59L, 53L, 60L, 92L, 69L, 72L),
op = { it + 2L },
test = { if (it % 5L == 0L) 5 else 6 }
),
Monkey(
id = 4,
items = listOf(61L, 52L, 55L, 61L),
op = { it + 3L },
test = { if (it % 7L == 0L) 7 else 2 }
),
Monkey(
id = 5,
items = listOf(79L, 53L),
op = { it + 1L },
test = { if (it % 3L == 0L) 0 else 6 }
),
Monkey(
id = 6,
items = listOf(59L, 86L, 67L, 95L, 92L, 77L, 91L),
op = { it + 5L },
test = { if (it % 19L == 0L) 4 else 0 }
),
Monkey(
id = 7,
items = listOf(58L, 83L, 89L),
op = { it * 19L },
test = { if (it % 17L == 0L) 2 else 1 }
)
)
private const val clonazepam = 9_699_690L // product of all X in "divisible by X"
fun part1(): Long = generateSequence(input) {
it.playOneRound(boredMonkeys = true)
}.drop(20).first().sortedByDescending {
it.business
}.take(2).fold(1L) { acc, monkey ->
acc * monkey.business
}
fun part2(): Long = generateSequence(input) {
it.playOneRound(boredMonkeys = false)
}.drop(10_000).first().sortedByDescending {
it.business
}.take(2).fold(1L) { acc, monkey ->
acc * monkey.business
}
private data class Monkey(
val id: Int,
val items: List<Long>,
val op: (Long) -> Long,
val test: (Long) -> Int,
val business: Long = 0L
) {
fun proceed(bored: Boolean): Pair<Monkey, Map<Int, List<Long>>> = copy(
items = listOf(),
business = business + items.size
) to items.map { worry ->
val newWorry = (op(worry) / if (bored) 3L else 1L) % clonazepam
test(newWorry) to newWorry
}.fold(mutableMapOf()) { m, (destMonkey, item) ->
m[destMonkey] = (m[destMonkey] ?: listOf()) + item
m
}
fun add(newItems: List<Long>): Monkey = copy(items = items + newItems)
}
private fun List<Monkey>.playOneTurn(boredMonkeys: Boolean): List<Monkey> {
val (newLast, result) = first().proceed(boredMonkeys)
return drop(1).map { it.add(result[it.id] ?: listOf()) } + newLast
}
private fun List<Monkey>.playOneRound(boredMonkeys: Boolean): List<Monkey> = generateSequence(this) {
it.playOneTurn(boredMonkeys)
}.drop(size).first()
}
| 0 | Kotlin | 0 | 0 | 7ead7db6491d6fba2479cd604f684f0f8c1e450f | 3,218 | adventofcode2022 | MIT License |
src/day01/Day01.kt | schrami8 | 572,631,109 | false | {"Kotlin": 18696} | fun <E> List<E>.splitBy(predicate: (E) -> Boolean): List<List<E>> =
this.fold(mutableListOf(mutableListOf<E>())) { acc, element ->
if (predicate.invoke(element)) {
acc += mutableListOf<E>()
} else {
acc.last() += element
}
acc
}
fun main() {
fun part1(input: List<String>): Int {
var mostCalories = 0
var tmpCalories = 0
input.forEach {
if (it.isNotEmpty()) {
tmpCalories += it.toInt()
if (tmpCalories > mostCalories)
mostCalories = tmpCalories
}
else
tmpCalories = 0
}
return mostCalories
}
fun part2(input: List<String>): Int {
val elves = mutableListOf<Int>()
var tmpCalories = 0
input.forEach {
if (it.isNotEmpty())
tmpCalories += it.toInt()
else {
elves.add(tmpCalories)
tmpCalories = 0
}
}
println(elves.sortedDescending())
return elves.sortedDescending().take(3).sum()
}
// test if implementation meets criteria from the description, like:
//val testInput = readInput("Day01_test")
//check(part1(testInput) == 1)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 215f89d7cd894ce58244f27e8f756af28420fc94 | 1,382 | advent-of-code-kotlin | Apache License 2.0 |
src/y2022/day01.kt | sapuglha | 573,238,440 | false | {"Kotlin": 33695} | package y2022
import readFileAsLines
import readFileAsText
fun main() {
val fileName = "y2022/data/day01"
fun sumElves(input: List<String>): List<Int> {
val response: MutableList<Int> = mutableListOf()
val sublist: MutableList<Int> = mutableListOf()
input.forEach {
if (it.isNotBlank()) {
sublist.add(it.toInt())
} else {
response.add(
sublist.sumOf { it }
)
sublist.clear()
}
}
return response
}
fun sumElves(input: String): List<Int> =
input
.trim()
.split("\n\n")
.map { elf ->
elf.split("\n")
.map { it.toInt() }
.sumOf { it }
}
fun solutionPart1(input: String): Int =
sumElves(input)
.maxOf { it }
fun solutionPart2(input: String): Int =
sumElves(input)
.sortedDescending()
.take(3)
.sumOf { it }
fun solutionPart1(input: List<String>): Int =
sumElves(input)
.maxOf { it }
fun solutionPart2(input: List<String>): Int =
sumElves(input)
.sortedDescending()
.take(3)
.sumOf { it }
val inputAsText = fileName.readFileAsText()
println("part1 from text: ${solutionPart1(inputAsText)}")
println("part2 from text: ${solutionPart2(inputAsText)}")
val inputAsLines = fileName.readFileAsLines()
println("part1 from lines: ${solutionPart1(inputAsLines)}")
println("part2 from lines: ${solutionPart2(inputAsLines)}")
}
| 0 | Kotlin | 0 | 0 | 82a96ccc8dcf38ae4974e6726e27ddcc164e4b54 | 1,678 | adventOfCode2022 | Apache License 2.0 |
src/day-12.kt | drademacher | 160,820,401 | false | null | import java.io.File
fun main(args: Array<String>) {
println("part 1: " + simulateFast(20))
println("part 2: " + simulateFast(50000000000))
}
// REMARK: the cycle becomes stable after around 200 generations, then adding 34 plants each cycle
private fun simulateFast(generations: Long): Long {
if (generations <= 200) {
return simulateExactNumber(generations.toInt())
}
val firstTwoHundredGenerations = simulateExactNumber(200)
return firstTwoHundredGenerations + (generations - 200) * 34
}
private fun simulateExactNumber(n: Int): Long {
val offsetOfEmptyPlants = 2 * n
val rawFile = File("res/day-12.txt").readText()
.split("\n")
.filter { it != "" }
var (plants, rules) = parseFile(rawFile, offsetOfEmptyPlants)
for (generation in 0 until n) {
var nextGeneration = ".."
for (i in 0..plants.length - 5) {
nextGeneration += when {
plants.slice(i..i + 4) in rules -> "#"
else -> "."
}
}
nextGeneration += ".."
plants = nextGeneration
}
return calcNumberOfLivingsPlants(plants, offsetOfEmptyPlants)
}
private fun calcNumberOfLivingsPlants(plants: String, offsetOfEmptyPlants: Int) =
plants
.withIndex()
.filter { it.value == '#' }
.map { it.index - offsetOfEmptyPlants }
.map(Int::toLong)
.sum()
private fun parseFile(rawFile: List<String>, offsetOfEmptyPlants: Int): Pair<String, Set<String>> {
val plants = ".".repeat(offsetOfEmptyPlants) + rawFile[0].drop(15) + ".".repeat(offsetOfEmptyPlants)
val rules = rawFile
.drop(1)
.filter { it.last() == '#' }
.map { it.take(5) }
.toSet()
return Pair(plants, rules)
}
| 0 | Kotlin | 0 | 0 | a7f04450406a08a5d9320271148e0ae226f34ac3 | 1,843 | advent-of-code-2018 | MIT License |
src/main/kotlin/net/wrony/aoc2023/a15/15.kt | kopernic-pl | 727,133,267 | false | {"Kotlin": 52043} | package net.wrony.aoc2023.a15
import kotlin.io.path.Path
import kotlin.io.path.readText
fun String.hASH(): Int {
return this.fold(0) { acc, c ->
((acc + c.code) * 17) % 256
}
}
sealed class Operation(val element: String) {
class INSERT(element: String, val focal: Int) : Operation(element) {
fun toLens() = Lens(element, focal)
}
class REMOVE(element: String) : Operation(element)
fun hASH() = element.hASH()
}
typealias Lens = Pair<String, Int>
fun initMap(cap: Int): Map<Int, MutableList<Lens>> {
return buildMap(cap) {
(0..255).forEach {
put(it, mutableListOf())
}
}
}
fun main() {
Path("src/main/resources/15.txt").readText().split(",").also {
println(it.sumOf(String::hASH))
}.let { commands ->
commands.map { c ->
when {
c.contains('-') -> Operation.REMOVE(c.dropLast(1))
c.contains('=') -> c.split("=")
.let { (element, focal) -> Operation.INSERT(element, focal.toInt()) }
else -> throw Exception("Unknown command $c")
}
}.fold(initMap(commands.size)) { acc, operation ->
when (operation) {
is Operation.REMOVE -> acc[operation.hASH()]!!.removeIf { l -> l.first == operation.element }
.let { acc }
is Operation.INSERT -> acc[operation.hASH()]!!.let { lenses ->
if (lenses.any { l -> l.first == operation.element }) {
lenses.replaceAll { l ->
if (l.first == operation.element) {
operation.toLens()
} else {
l
}
}
} else {
lenses.add(operation.toLens())
}
acc
}
}
}.filter { (_, lenses) -> lenses.isNotEmpty() }
.let {
m -> m.keys.fold(0) { acc, boxKey ->
acc + m[boxKey]!!.foldIndexed(0) {
idx, boxAcc, lens -> boxAcc + (boxKey+1) * (idx+1) * lens.second
}
}
}.let { println("Second answer: $it") }
}
} | 0 | Kotlin | 0 | 0 | 1719de979ac3e8862264ac105eb038a51aa0ddfb | 2,315 | aoc-2023-kotlin | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.