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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
kotlin/src/katas/kotlin/leetcode/regex_matching/v3/RegexMatching.kt | dkandalov | 2,517,870 | false | {"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221} | package katas.kotlin.leetcode.regex_matching.v3
import datsok.shouldEqual
import org.junit.jupiter.api.Test
class RegexMatching {
@Test fun `some examples`() {
"".matchesRegex("") shouldEqual true
"".matchesRegex("a") shouldEqual false
"a".matchesRegex("") shouldEqual false
"a".matchesRegex("a") shouldEqual true
"a".matchesRegex(".") shouldEqual true
"a".matchesRegex("..") shouldEqual false
"ab".matchesRegex("..") shouldEqual true
"ab".matchesRegex("a.") shouldEqual true
"ab".matchesRegex(".b") shouldEqual true
"a".matchesRegex("a?") shouldEqual true
"a".matchesRegex("a?b?") shouldEqual true
"b".matchesRegex("a?b?") shouldEqual true
"c".matchesRegex("a?b?") shouldEqual false
"".matchesRegex("a*") shouldEqual true
"a".matchesRegex("a*") shouldEqual true
"b".matchesRegex("a*") shouldEqual false
"aa".matchesRegex("a*") shouldEqual true
"aab".matchesRegex("a*") shouldEqual false
"aab".matchesRegex("a*b") shouldEqual true
"baa".matchesRegex("ba*") shouldEqual true
"abc".matchesRegex(".*") shouldEqual true
}
}
typealias Matcher = (String) -> List<String>
fun char(c: Char): Matcher = { input ->
if (input.firstOrNull() == c) listOf(input.drop(1)) else emptyList()
}
fun anyChar(): Matcher = { input ->
if (input.isNotEmpty()) listOf(input.drop(1)) else emptyList()
}
fun optional(matcher: Matcher): Matcher = { input ->
listOf(input) + matcher(input)
}
fun zeroOrMore(matcher: Matcher): Matcher = { input ->
listOf(input) + matcher(input).flatMap(zeroOrMore(matcher))
}
private fun String.matchesRegex(regex: String): Boolean {
val matchers = regex.fold(emptyList<Matcher>()) { matchers, c ->
when (c) {
'.' -> matchers + anyChar()
'?' -> matchers.dropLast(1) + optional(matchers.last())
'*' -> matchers.dropLast(1) + zeroOrMore(matchers.last())
else -> matchers + char(c)
}
}
return matchers
.fold(listOf(this)) { inputs, matcher -> inputs.flatMap(matcher) }
.any { it.isEmpty() }
}
| 7 | Roff | 3 | 5 | 0f169804fae2984b1a78fc25da2d7157a8c7a7be | 2,194 | katas | The Unlicense |
src/main/kotlin/se/saidaspen/aoc/aoc2022/Day23.kt | saidaspen | 354,930,478 | false | {"Kotlin": 301372, "CSS": 530} | package se.saidaspen.aoc.aoc2022
import se.saidaspen.aoc.util.*
import se.saidaspen.aoc.util.COMPASS.*
import kotlin.math.absoluteValue
fun main() = Day23.run()
object Day23 : Day(2022, 23) {
class World(val map: MutableMap<P<Int, Int>, Char>, var hasMoved: Boolean = false) {
private var considerDir = listOf(listOf(N, NE, NW), listOf(S, SE, SW), listOf(W, NW, SW), listOf(E, NE, SE))
private var plan = 0
val elvesCount : Int by lazy { map.entries.count { it.value == '#' }}
fun step() {
val elves = map.entries.filter { it.value == '#' }.map { it.key }.toList()
val planElves = elves.filter { neighbors(it).any { n -> map[n] == '#' } }
val plannedMoves = mutableMapOf<Point, Point>()
for (elf in planElves) {
var isValid = false
var toTest = plan
var tested = 0
while (!isValid && tested < 4) {
if (!considerDir[toTest].any { map[elf + it] == '#' }) {
isValid = true
plannedMoves[elf] = elf + considerDir[toTest][0]
}
tested += 1
toTest = (toTest + 1) % 4
}
}
// Filter
val positionsDoublePlanned = plannedMoves.map { it.value }.histo().filter { it.value > 1 }.map { it.key }
val movesToExec = plannedMoves.entries.filter { !positionsDoublePlanned.contains(it.value) }
// Move
for (move in movesToExec) {
map[move.key] = '.'
map[move.value] = '#'
}
hasMoved = movesToExec.isNotEmpty()
plan = (plan + 1) % 4
}
}
override fun part1(): Any {
val world = World(toMap(input))
repeat(10) { world.step() }
val elves = world.map.filter { it.value == '#' }
val width = (elves.maxOf { it.key.first } - elves.minOf { it.key.first }).absoluteValue + 1
val height = (elves.maxOf { it.key.second } - elves.minOf { it.key.second }).absoluteValue + 1
return width * height - world.elvesCount
}
override fun part2(): Any {
val world = World(toMap(input))
var round = 1
while (true) {
world.step()
if (!world.hasMoved) return round
round += 1
}
}
}
| 0 | Kotlin | 0 | 1 | be120257fbce5eda9b51d3d7b63b121824c6e877 | 2,418 | adventofkotlin | MIT License |
src/Day03.kt | Totwart123 | 573,119,178 | false | null | fun main() {
fun Char.getValueOfItem() = if(this.isUpperCase()) this.code - 38 else this.code - 96
fun part1(input: List<String>): Int {
var sum = 0
input.forEach {items ->
val compartment1 = items.substring(0, items.length / 2)
val compartment2 = items.substring(items.length/2, items.length)
val double = compartment1.first { compartment2.contains(it) }
sum += double.getValueOfItem()
}
return sum
}
fun part2(input: List<String>): Int {
var sum = 0
input.chunked(3).forEach { group ->
val itemType = group[0].first { group[1].contains(it) && group[2].contains(it) }
sum += itemType.getValueOfItem()
}
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 | 33e912156d3dd4244c0a3dc9c328c26f1455b6fb | 988 | AoC | Apache License 2.0 |
calendar/day07/Day7.kt | polarene | 572,886,399 | false | {"Kotlin": 17947} | package day07
import Day
import Lines
class Day7 : Day() {
override fun part1(input: Lines): Any {
val fs = Filesystem.init(input)
return fs.findDirsBySize { it <= 100_000 }.sum()
}
override fun part2(input: Lines): Any {
val totalSpace = 70_000_000
val updateSpace = 30_000_000
val fs = Filesystem.init(input)
val unused = totalSpace - fs.size()
val needed = updateSpace - unused
return fs.findDirsBySize { it >= needed }.min()
}
}
class Node(
private val name: String,
private val size: Int = 0,
val children: MutableList<Node> = mutableListOf(),
var parent: Node? = null
) {
val isDir: Boolean get() = children.isNotEmpty()
fun size(): Int =
if (isDir)
children.sumOf { it.size() }
else
size
operator fun plusAssign(other: Node) {
other.parent = this
children.add(other)
}
operator fun get(name: String): Node {
return children.first { it.name == name }
}
override fun toString() = "- $name ($size)"
}
class Filesystem(private val root: Node) {
companion object {
fun init(lines: Lines): Filesystem {
val root = Node("/")
var current = root
lines.drop(1).forEach { line ->
current = when {
line.startsWith("$") -> cmd(current, line.substring(2))
else -> create(current, line)
}
}
return Filesystem(root)
}
const val INDENTATION = 2
}
fun findDirsBySize(condition: (Int) -> Boolean): List<Int> {
return findDirs(root).asSequence()
.map { it.size() }
.filter(condition)
.toList()
}
private fun findDirs(current: Node): List<Node> {
return if (current.isDir)
listOf(current) + current.children.flatMap { findDirs(it) }
else
emptyList()
}
fun size(): Int {
return root.size()
}
override fun toString() = toString(0, root)
private fun toString(level: Int, node: Node): String {
return "${level.ind(INDENTATION)}$node\n" + buildString {
node.children.forEach {
append(toString(level + 1, it))
}
}
}
private fun Int.ind(indentation: Int) = " ".repeat(this * indentation)
}
// ----------------------------------------------------------------
// parsing
// ----------------------------------------------------------------
fun cmd(current: Node, line: String): Node {
val args = line.split(" ")
return when (args[0]) {
"cd" -> if (args[1] == "..") {
current.parent!!
} else {
current[args[1]]
}
"ls" -> current
else -> error("Unknown command")
}
}
fun create(current: Node, line: String): Node {
val (typeOrSize, name) = line.split(" ")
current += when (typeOrSize) {
"dir" -> Node(name)
else -> Node(name, typeOrSize.toInt())
}
return current
} | 0 | Kotlin | 0 | 0 | 0b2c769174601b185227efbd5c0d47f3f78e95e7 | 3,105 | advent-of-code-2022 | Apache License 2.0 |
src/Day07.kt | weberchu | 573,107,187 | false | {"Kotlin": 91366} | private interface FileDescriptor {
val name: String
}
private data class Directory(
override val name: String,
val parent: Directory?,
val children: MutableMap<String, FileDescriptor>
): FileDescriptor
private data class File(
override val name: String,
val size: Long
): FileDescriptor
private class FileSystem {
private val root = Directory("/", null, mutableMapOf())
private var currentDir = root
val currentPath = mutableListOf("/")
fun cd(dir: String) {
currentDir = when (dir) {
"/" -> {
currentPath.clear()
currentPath.add("/")
root
}
".." -> {
currentPath.removeLast()
currentDir.parent!!
}
else -> {
currentPath.add(dir)
currentDir.children[dir]!! as Directory
}
}
}
fun createDir(name: String) {
if (currentDir.children[name] == null) {
currentDir.children[name] = Directory(name, currentDir, mutableMapOf())
}
}
fun createFile(name: String, size: Long) {
currentDir.children[name] = File(name, size)
}
fun get(path: List<String>): FileDescriptor {
if (path[0] != "/") {
throw IllegalArgumentException("Path must start with /")
}
var dir: FileDescriptor = root
for (i in 1 until path.size) {
dir = (dir as Directory).children[path[i]]!!
}
return dir
}
fun allDirSize(): Map<List<String>, Long> {
val dirSize = mutableMapOf<List<String>, Long>()
val pendingDir = mutableListOf(listOf("/"))
while (pendingDir.isNotEmpty()) {
val pathToProcess = pendingDir.removeLast()
val dirToProcess = get(pathToProcess)
if (dirToProcess is Directory) {
val subDir = dirToProcess.children.values.filter {
it is Directory && !dirSize.containsKey(pathToProcess + it.name)
}
if (subDir.isEmpty()) {
// all children are either files or sub dir with known size
dirSize[pathToProcess] = dirToProcess.children.values.sumOf {
if (it is File) {
it.size
} else {
dirSize[pathToProcess + it.name]!!
}
}
} else {
pendingDir.add(pathToProcess)
subDir.forEach {
pendingDir.add(pathToProcess + it.name)
}
}
}
}
return dirSize
}
}
private fun createFileSystem(input: List<String>): FileSystem {
val fs = FileSystem()
for (line in input) {
if (line.startsWith('$')) {
val cmd = line.substring(2).split(" ")
when (cmd[0]) {
"cd" -> {
fs.cd(cmd[1])
}
"ls" -> {} // do nothing, will parse next line as list output
else -> throw IllegalArgumentException("Unknown command $cmd")
}
} else {
val list = line.split(" ")
if (list[0] == "dir") {
fs.createDir(list[1])
} else {
fs.createFile(list[1], list[0].toLong())
}
}
}
return fs
}
fun main() {
val input = readInput("Day07")
// val input = readInput("Test")
val fs = createFileSystem(input)
val allDirSize = fs.allDirSize()
val part1 = allDirSize.values.filter { it <= 100000 }.sum()
val currentFreeSpace = 70000000 - allDirSize[listOf("/")]!!
val minSizeToFreeUp = 30000000 - currentFreeSpace
var toBeDeletedDirSize = Long.MAX_VALUE
allDirSize.forEach { (path, size) ->
if (size > minSizeToFreeUp && size < toBeDeletedDirSize) {
toBeDeletedDirSize = size
}
}
println("Part 1: " + part1)
println("Part 2: " + toBeDeletedDirSize)
}
| 0 | Kotlin | 0 | 0 | 903ff33037e8dd6dd5504638a281cb4813763873 | 4,136 | advent-of-code-2022 | Apache License 2.0 |
src/day02/Day02.kt | iammohdzaki | 573,280,588 | false | {"Kotlin": 2028} | package day02
import readInput
fun main() {
val part1Scores: Map<String, Int> =
mapOf(
"A X" to 1 + 3,
"A Y" to 2 + 6,
"A Z" to 3 + 0,
"B X" to 1 + 0,
"B Y" to 2 + 3,
"B Z" to 3 + 6,
"C X" to 1 + 6,
"C Y" to 2 + 0,
"C Z" to 3 + 3,
)
val part2Scores: Map<String, Int> =
mapOf(
"A X" to 3 + 0,
"A Y" to 1 + 3,
"A Z" to 2 + 6,
"B X" to 1 + 0,
"B Y" to 2 + 3,
"B Z" to 3 + 6,
"C X" to 2 + 0,
"C Y" to 3 + 3,
"C Z" to 1 + 6,
)
val testInput = readInput("day02", "Day02_test").split("\n")
check(testInput.sumOf {
part1Scores[it] ?: 0
} == 15)
val input = readInput("day02", "Day02").split("\n")
println(input.sumOf {
part2Scores[it] ?: 0
})
}
| 0 | Kotlin | 0 | 0 | 70fae2770ae91467b5663fdc69135da0baa3e352 | 939 | aoc-2022-kotlin | Apache License 2.0 |
src/main/kotlin/com/hopkins/aoc/day22/main.kt | edenrox | 726,934,488 | false | {"Kotlin": 88215} | package com.hopkins.aoc.day22
import java.io.File
import java.lang.IllegalStateException
const val debug = true
const val part = 1
/** Advent of Code 2023: Day 22 */
fun main() {
// Step 1: Read the file input
val lines: List<String> = File("input/input22.txt").readLines()
if (debug) {
println("Step 1: Read file")
println("=======")
println(" num lines: ${lines.size}")
}
// Step 2: Parse the input into cubes
val cubes: List<Cube> = lines.mapIndexed { index, line -> parseCube(index, line) }
if (debug) {
println("Step 2: Parse cubes")
println("=======")
cubes.forEach { cube -> println(" $cube") }
}
// Step 3: Sort the cubes by descending z position
val sortedCubes = cubes.sortedBy { it.origin.z }
// Step 4: Drop the cubes to the bottom
var droppedCubes = mutableListOf<Cube>()
for (cube in sortedCubes) {
val droppedCube = dropCube(cube, droppedCubes)
droppedCubes.add(droppedCube)
}
if (debug) {
println("Step 5: Drop cubes")
println("=======")
//printCubeStack(droppedCubes.toList())
}
// Step 5: Find the disintegratable cubes
val sortedAfterDrop = droppedCubes.sortedBy { it.origin.z }
val cubeMap = droppedCubes.flatMap { cube -> cube.getPoints().map {point -> point to cube } }.toMap()
var count = 0
for (cube in sortedAfterDrop) {
val cubesAbove = cube.getPoints().map { point -> cubeMap[point.add(Point3d.DIRECTION_ZUP)] }.distinct()
if (cubesAbove.isEmpty()) {
count++
} else {
val cubesBelow = cubeMap.filter { key, value -> key.z < cube.origin.z}
}
if (others.all { other -> other == dropCube(other, others.filterNot { it == other }) }) {
println("Can remove: ${'A' + cube.label}")
count++
}
}
println("Num: $count") // 395
}
fun printCubeStack(cubes: List<Cube>) {
val maxX = cubes.maxOf { it.origin.x + it.vector.x }
val maxY = cubes.maxOf { it.origin.y + it.vector.y }
val maxZ = cubes.maxOf { it.origin.z + it.vector.z }
println("size: [$maxX,$maxY,$maxZ]")
val pointToCube: Map<Point3d, Cube> = cubes.flatMap { cube -> cube.getPoints().map { point -> point to cube } }.toMap()
for (z in maxZ downTo 1) {
println("Z: $z")
for (y in 0 .. maxY) {
for (x in 0 .. maxX) {
val current = Point3d(x, y, z)
val cube = pointToCube[current]
if (cube == null) {
print(".")
} else {
val value: Char = 'A' + cube.label
print(value)
}
print("|")
}
println("")
}
println("-".repeat((maxX + 1) * 2))
}
}
fun dropCube(cube: Cube, droppedCubes: Collection<Cube>): Cube {
var newOrigin = cube.origin
val droppedPoints = droppedCubes.flatMap { it.getPoints() }.toSet()
while (newOrigin.z > 1) {
val newCube = cube.withOrigin(newOrigin)
val points = newCube.getPoints()
val newPoints = points.map { it.add(Point3d.DIRECTION_ZDOWN)}
if (newPoints.any { droppedPoints.contains(it) }) {
break
} else {
newOrigin = newOrigin.add(Point3d.DIRECTION_ZDOWN)
}
}
return Cube(cube.label, newOrigin, cube.vector)
}
fun parseCube(index: Int, line: String): Cube {
val (left, right) = line.split("~")
val origin = parsePoint3d(left)
val extent = parsePoint3d(right)
return Cube(index, origin, extent.subtract(origin))
}
fun parsePoint3d(pointStr: String): Point3d {
val (x, y, z) = pointStr.split(",")
return Point3d(x.toInt(), y.toInt(), z.toInt())
}
data class Cube(val label: Int, val origin: Point3d, val vector: Point3d) {
fun withOrigin(newOrigin: Point3d): Cube =
Cube(label, newOrigin, vector)
fun getPoints(): List<Point3d> {
if (vector == Point3d.ORIGIN) {
return listOf(origin)
}
val magnitude = vector.getDirectionMagnitude()
val direction = vector.toDirection()
var acc = Point3d.ORIGIN
return (0 .. magnitude).map {
origin.add(acc).also { acc = acc.add(direction)}
}
}
override fun toString(): String = "origin=$origin, vector=$vector"
}
data class Point3d(val x: Int, val y: Int, val z: Int) {
fun isDirectional(): Boolean {
return if (x != 0) {
y == 0 && z == 0
} else if (y != 0) {
z == 0 // x == 0 is implied
} else {
z != 0 // x == 0 && y == 0 are implied
}
}
fun toDirection(): Point3d {
require(isDirectional())
return if (x != 0) {
Point3d(x/x, 0, 0)
} else if (y != 0) {
Point3d(0, y/y, 0)
} else {
require(z != 0)
Point3d(0, 0, z/z)
}
}
fun getDirectionMagnitude(): Int {
require(isDirectional())
return if (x != 0) {
x
} else if (y != 0) {
y
} else {
z
}
}
fun add(other: Point3d): Point3d = Point3d(x + other.x, y + other.y, z + other.z)
fun subtract(other: Point3d): Point3d = Point3d(x - other.x, y - other.y,z - other.z)
override fun toString(): String = "[$x,$y,$z]"
companion object {
val ORIGIN = Point3d(0, 0, 0)
val DIRECTION_ZUP = Point3d(0, 0, 1)
val DIRECTION_ZDOWN = Point3d(0, 0, -1)
}
}
| 0 | Kotlin | 0 | 0 | 45dce3d76bf3bf140d7336c4767e74971e827c35 | 5,593 | aoc2023 | MIT License |
src/main/kotlin/com/github/michaelbull/advent2023/day10/PipeMap.kt | michaelbull | 726,012,340 | false | {"Kotlin": 195941} | package com.github.michaelbull.advent2023.day10
import com.github.michaelbull.advent2023.math.Vector2
import com.github.michaelbull.advent2023.math.Vector2CharMap
import com.github.michaelbull.advent2023.math.toVector2CharMap
fun Sequence<String>.toPipeMap(): PipeMap {
val tiles = this.toVector2CharMap()
val (startTile) = tiles.first { (_, char) -> char == 'S' }
tiles[startTile] = tiles.directionsConnectedTo(startTile).pipe()
return PipeMap(tiles, startTile)
}
data class PipeMap(
val tiles: Vector2CharMap,
val startTile: Vector2,
) {
fun farthestStepCount(): Int {
return path().count() / 2
}
fun enclosedTileCount(): Int {
val path = path().toSet()
var count = 0
for (y in tiles.yRange) {
var enclosed = false
for (x in tiles.xRange) {
val tile = Vector2(x, y)
if (tile in path) {
val pipe = tiles[tile]
val north = pipe.directions().any { it == NORTH }
if (north) {
enclosed = !enclosed
}
} else if (enclosed) {
count++
}
}
}
return count
}
private fun path() = sequence {
val visited = mutableSetOf<Vector2>()
var tile = startTile
while (true) {
visited += tile
val adjacentTiles = tile.adjacentTiles()
val unvisitedTile = adjacentTiles.firstOrNull { it !in visited }
if (unvisitedTile != null) {
yield(unvisitedTile)
tile = unvisitedTile
} else if (startTile in adjacentTiles) {
yield(startTile)
break
}
}
}
private fun Vector2.adjacentTiles(): List<Vector2> {
return tiles[this].directions().map(::plus)
}
}
private val NORTH = Vector2(0, -1)
private val EAST = Vector2(1, 0)
private val SOUTH = Vector2(0, 1)
private val WEST = Vector2(-1, 0)
private val CARDINAL_DIRECTIONS = setOf(
NORTH,
EAST,
SOUTH,
WEST
)
private val DIRECTIONS_BY_PIPE = mapOf(
'|' to setOf(NORTH, SOUTH),
'-' to setOf(EAST, WEST),
'L' to setOf(NORTH, EAST),
'J' to setOf(NORTH, WEST),
'7' to setOf(SOUTH, WEST),
'F' to setOf(SOUTH, EAST),
'.' to emptySet()
)
private val PIPE_BY_DIRECTIONS = DIRECTIONS_BY_PIPE
.map { (key, value) -> value to key }
.toMap()
private fun Char.directions(): Set<Vector2> {
return DIRECTIONS_BY_PIPE.getValue(this)
}
private fun Set<Vector2>.pipe(): Char {
return PIPE_BY_DIRECTIONS.getValue(this)
}
private fun Vector2CharMap.isConnected(tile: Vector2, direction: Vector2): Boolean {
val adjacentTile = tile + direction
val adjacentPipe = getOrNull(adjacentTile) ?: return false
val adjacentDirections = adjacentPipe.directions()
val oppositeDirection = -direction
return oppositeDirection in adjacentDirections
}
private fun Vector2CharMap.directionsConnectedTo(tile: Vector2): Set<Vector2> {
return CARDINAL_DIRECTIONS
.filter { direction -> isConnected(tile, direction) }
.toSet()
}
| 0 | Kotlin | 0 | 1 | ea0b10a9c6528d82ddb481b9cf627841f44184dd | 3,232 | advent-2023 | ISC License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/DistributeCookies.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import kotlin.math.max
import kotlin.math.min
/**
* 2305. Fair Distribution of Cookies
* @see <a href="https://leetcode.com/problems/fair-distribution-of-cookies/">Source</a>
*/
fun interface DistributeCookies {
operator fun invoke(cookies: IntArray, k: Int): Int
}
class DistributeCookiesBacktracking : DistributeCookies {
override operator fun invoke(cookies: IntArray, k: Int): Int {
val distribute = IntArray(k)
return dfs(0, distribute, cookies, k, k)
}
private fun dfs(i: Int, distribute: IntArray, cookies: IntArray, k: Int, zeroCount: Int): Int {
// If there are not enough cookies remaining, return Integer.MAX_VALUE
// as it leads to an invalid distribution.
var count = zeroCount
if (cookies.size - i < count) {
return Int.MAX_VALUE
}
// After distributing all cookies, return the unfairness of this
// distribution.
if (i == cookies.size) {
var unfairness = Int.MIN_VALUE
for (value in distribute) {
unfairness = max(unfairness, value)
}
return unfairness
}
// Try to distribute the i-th cookie to each child, and update answer
// as the minimum unfairness in these distributions.
var answer = Int.MAX_VALUE
for (j in 0 until k) {
count -= if (distribute[j] == 0) 1 else 0
distribute[j] += cookies[i]
// Recursively distribute the next cookie.
answer = min(answer, dfs(i + 1, distribute, cookies, k, count))
distribute[j] -= cookies[i]
count += if (distribute[j] == 0) 1 else 0
}
return answer
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,365 | kotlab | Apache License 2.0 |
kotlin/src/com/daily/algothrim/leetcode/Search.kt | idisfkj | 291,855,545 | false | null | package com.daily.algothrim.leetcode
/**
* 81. 搜索旋转排序数组 II
* 已知存在一个按非降序排列的整数数组 nums ,数组中的值不必互不相同。
*
* 在传递给函数之前,nums 在预先未知的某个下标 k(0 <= k < nums.length)上进行了 旋转 ,使数组变为 [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]](下标 从 0 开始 计数)。例如, [0,1,2,4,4,4,5,6,6,7] 在下标 5 处经旋转后可能变为 [4,5,6,6,7,0,1,2,4,4] 。
* 给你 旋转后 的数组 nums 和一个整数 target ,请你编写一个函数来判断给定的目标值是否存在于数组中。如果 nums 中存在这个目标值 target ,则返回 true ,否则返回 false 。
*/
class Search {
companion object {
@JvmStatic
fun main(args: Array<String>) {
println(Search().search(intArrayOf(2,5,6,0,0,1,2), 0))
println(Search().search(intArrayOf(2,5,6,0,0,1,2), 3))
println(Search().search(intArrayOf(1,0,1,1,1), 0))
}
}
fun search(nums: IntArray, target: Int): Boolean {
if (nums.isEmpty()) return false
var start = 0
var end = nums.size - 1
var mid: Int
while (start <= end) {
mid = start + (end - start).shr(1)
if (nums[mid] == target) return true
// 1. 无法分清左右是否有序,向后挪一位将重复的去除,重新比较
if (nums[start] == nums[mid]) {
start++
continue
}
if (nums[start] < nums[mid]) { // 2. 前半部分有序
if (nums[mid] > target && nums[start] <= target) { // 在前半部分
end = mid - 1
} else { // 在后半部分
start = mid + 1
}
} else { // 3. 后半部分有序
if (nums[mid] < target && nums[end] >= target) { // 在后半部分
start = mid + 1
} else { // 在前半部分
end = mid - 1
}
}
}
return false
}
} | 0 | Kotlin | 9 | 59 | 9de2b21d3bcd41cd03f0f7dd19136db93824a0fa | 2,168 | daily_algorithm | Apache License 2.0 |
src/main/kotlin/com/jacobhyphenated/advent2023/day12/Day12.kt | jacobhyphenated | 725,928,124 | false | {"Kotlin": 121644} | package com.jacobhyphenated.advent2023.day12
import com.jacobhyphenated.advent2023.Day
import com.jacobhyphenated.advent2023.product
class Day12: Day<List<Pair<List<Char>, List<Int>>>> {
override fun getInput(): List<Pair<List<Char>, List<Int>>> {
return parseInput(readInputFile("12"))
}
override fun part1(input: List<Pair<List<Char>, List<Int>>>): Int {
return input.sumOf { (arrangement, groupSize) -> countValidArrangements(arrangement, groupSize) }
}
override fun part2(input: List<Pair<List<Char>, List<Int>>>): Long {
// expand input
return input.sumOf { (arrangement, groupSize) ->
val expandedArrangement = List(5) { arrangement.joinToString("") }.joinToString("?")
val expandedSizes = List(5) { groupSize }.flatten()
// this solves the test input relatively fast, but it's not good enough for the puzzle input
countValidArrangements(expandedArrangement.toCharArray().toList(), expandedSizes).toLong().also { println(it) }
}
// go through characters in arrangement one at a time
// track contiguous possible
// track contiguous working
// firstPivot = first non # char where continuousPossible >= groupSize[0]
// lastPivot
// max is arrangement.size - groupSize[1:].sum() - 1
// first . character where contiguousWorking > 0
// if firstPivot == null || lastPivot == null, return 0
// loop firstPivot .. lastPivot
// if arrangment[it] == '#' continue
// calc(arrangement[0:it], groupSize[0]) * recurse(arrangement[it+1:], groupSize[1:])
// memo recurse function inputs
// can this result in duplicate combos around pivot points?
}
private fun countValidArrangements(arrangement: List<Char>, groupSizes: List<Int>): Int {
if (isArrangementInvalid(arrangement, groupSizes)) {
return 0
}
val unknownIndex = arrangement.indexOfFirst { it == '?' }
if (unknownIndex == -1) {
return 1
}
val a1 = arrangement.mapIndexed { i, c -> if (i == unknownIndex) { '#' } else { c } }
val a2 = arrangement.mapIndexed { i, c -> if (i == unknownIndex) { '.' } else { c } }
return countValidArrangements(a1, groupSizes) + countValidArrangements(a2, groupSizes)
}
fun isArrangementInvalid(arrangement: List<Char>, groupSizes: List<Int>): Boolean {
val buffer = mutableListOf<Char>()
var groupIndex = 0
for (i in arrangement.indices) {
if (groupIndex > groupSizes.size) {
return true
}
if (groupIndex == groupSizes.size && arrangement.subList(i, arrangement.size).any { it == '#' }) {
return true
}
if (arrangement[i] == '?') {
return false
}
else if (arrangement[i] == '#') {
buffer.add(arrangement[i])
}
else if (arrangement[i] == '.') {
if (buffer.isNotEmpty()) {
if (groupIndex >= groupSizes.size || buffer.size != groupSizes[groupIndex]) {
return true
}
else {
groupIndex++
buffer.clear()
}
}
}
}
if (buffer.isNotEmpty()) {
if (groupIndex >= groupSizes.size || buffer.size != groupSizes[groupIndex]) {
return true
}
else {
groupIndex++
buffer.clear()
}
}
if (groupIndex != groupSizes.size) {
return true
}
return false
}
fun allCombinations(prefix: List<Int>, rest: List<Int>, num: Int): List<List<Int>> {
if (prefix.size == num) {
return listOf(prefix)
}
val remainder = num - prefix.size
return (0 .. rest.size - remainder).map {
val combo = prefix + rest[it]
allCombinations(combo, rest.subList(it+1), num)
}.flatten()
}
private fun isReadyForCombos(groups: List<String>, sizes: List<Int>): Boolean {
return groups.size == sizes.size && groups.indices.all { groups[it].length >= sizes[it] }
}
fun parseInput(input: String): List<Pair<List<Char>, List<Int>>> {
return input.lines().map {line ->
val (arrangementString, groupString) = line.split(" ").map { it.trim() }
val groups = groupString.split(",").map { it.toInt() }
val arrangement = arrangementString.toCharArray().toList()
Pair(arrangement, groups)
}
}
}
fun<T> List<T>.subList(fromIndex: Int): List<T> {
if (fromIndex >= size) {
return listOf()
}
return subList(fromIndex, this.size)
} | 0 | Kotlin | 0 | 0 | 90d8a95bf35cae5a88e8daf2cfc062a104fe08c1 | 4,394 | advent2023 | The Unlicense |
src/Day23.kt | Kvest | 573,621,595 | false | {"Kotlin": 87988} | import kotlin.math.max
import kotlin.math.min
fun main() {
val testInput = readInput("Day23_test")
check(part1(testInput) == 110)
check(part2(testInput) == 20)
val input = readInput("Day23")
println(part1(input))
println(part2(input))
}
private val DIRECTIONS = listOf(
//N, NE, NW
listOf(
intArrayOf(-1, 0),
intArrayOf(-1, 1),
intArrayOf(-1, -1)
),
//S, SE, SW
listOf(
intArrayOf(1, 0),
intArrayOf(1, 1),
intArrayOf(1, -1)
),
//W, NW, SW
listOf(
intArrayOf(0, -1),
intArrayOf(-1, -1),
intArrayOf(1, -1)
),
//E, NE, SE
listOf(
intArrayOf(0, 1),
intArrayOf(-1, 1),
intArrayOf(1, 1)
),
)
private val ALL_ADJACENT = listOf(
intArrayOf(-1, -1),
intArrayOf(-1, 0),
intArrayOf(-1, 1),
intArrayOf(0, 1),
intArrayOf(1, 1),
intArrayOf(1, 0),
intArrayOf(1, -1),
intArrayOf(0, -1),
)
private fun part1(input: List<String>): Int {
var elves = input.toElves()
val moveMap = mutableMapOf<IJ, IJ>()
val counts = mutableMapOf<IJ, Int>()
repeat(10) { iterationNumber ->
moveMap.clear()
counts.clear()
elves.calculateMoves(iterationNumber, moveMap, counts)
elves = elves.applyMoves(moveMap, counts)
}
var iFrom = elves.first().i
var jFrom = elves.first().j
var iTo = iFrom
var jTo = jFrom
elves.forEach {
iFrom = min(iFrom, it.i)
jFrom = min(jFrom, it.j)
iTo = max(iTo, it.i)
jTo = max(jTo, it.j)
}
var count = 0
for (i in iFrom..iTo) {
for (j in jFrom..jTo) {
if (IJ(i, j) !in elves) {
++count
}
}
}
return count
}
private fun part2(input: List<String>): Int {
var elves = input.toElves()
var iterationNumber = 0
val moveMap = mutableMapOf<IJ, IJ>()
val counts = mutableMapOf<IJ, Int>()
while (true) {
moveMap.clear()
counts.clear()
elves.calculateMoves(iterationNumber, moveMap, counts)
if (moveMap.isEmpty()) {
break
}
elves = elves.applyMoves(moveMap, counts)
++iterationNumber
}
return iterationNumber + 1
}
private fun List<String>.toElves(): Set<IJ> {
return this.flatMapIndexed { i, row ->
row.mapIndexedNotNull { j, ch ->
if (ch == '#') {
IJ(i, j)
} else {
null
}
}
}.toSet()
}
private fun Set<IJ>.calculateMoves(
iterationNumber: Int,
moveMap: MutableMap<IJ, IJ>,
counts: MutableMap<IJ, Int>
) {
this.forEach { elf ->
val shouldMove = ALL_ADJACENT.any { delta ->
IJ(elf.i + delta[0], elf.j + delta[1]) in this
}
if (shouldMove) {
val moveDirection = DIRECTIONS.indices.firstNotNullOfOrNull { i ->
DIRECTIONS[(i + iterationNumber) % DIRECTIONS.size].takeIf { dir ->
dir.all { delta -> IJ(elf.i + delta[0], elf.j + delta[1]) !in this }
}
}
if (moveDirection != null) {
val newLocation = IJ(elf.i + moveDirection[0][0], elf.j + moveDirection[0][1])
moveMap[elf] = newLocation
counts[newLocation] = counts.getOrDefault(newLocation, 0) + 1
}
}
}
}
private fun Set<IJ>.applyMoves(
moveMap: MutableMap<IJ, IJ>,
counts: MutableMap<IJ, Int>
): Set<IJ> {
return this.map { elf ->
moveMap[elf]?.takeIf { counts[it] == 1 } ?: elf
}.toSet()
} | 0 | Kotlin | 0 | 0 | 6409e65c452edd9dd20145766d1e0ea6f07b569a | 3,648 | AOC2022 | Apache License 2.0 |
src/main/kotlin/days/Day2.kt | mstar95 | 317,305,289 | false | null | package days
class Day2 : Day(2) {
override fun partOne(): Any {
val input = inputList.map { splitFirst(it) }
return input.filter { run(it) }.size
}
override fun partTwo(): Any {
val input = inputList.map { splitSecond(it) }
return input.filter { runSecond(it) }.size
}
fun splitFirst(r: String): Triple<Times, String, String> {
val splits = r.split(' ')
val first = splits[0].split("-")
val times = Times(first[0].toInt(), first[1].toInt())
val value = splits[1].dropLast(1)
val rest = splits[2]
return Triple(times, value, rest)
}
fun splitSecond(r: String): Triple<Positions, String, String> {
val splits = r.split(' ')
val first = splits[0].split("-")
val times = Positions(first[0].toInt(), first[1].toInt())
val value = splits[1].dropLast(1)
val rest = splits[2]
return Triple(times, value, rest)
}
fun run( triple: Triple<Times, String, String>): Boolean {
val( times, value, rest )= triple
val filter = rest.toList()
.filter { it.toString() == value }
val length = filter
.size
return times.from <= length && times.to >= length
}
private fun runSecond(triple: Triple<Positions, String, String>): Boolean {
val (pos, value, rest) = triple
return (rest[pos.first- 1].toString() == value).xor(rest[pos.second -1 ].toString() == value)
}
}
data class Times(val from: Int, val to: Int)
data class Positions(val first: Int, val second: Int)
| 0 | Kotlin | 0 | 0 | ca0bdd7f3c5aba282a7aa55a4f6cc76078253c81 | 1,611 | aoc-2020 | Creative Commons Zero v1.0 Universal |
advent-of-code/src/main/kotlin/DayEight.kt | pauliancu97 | 518,083,754 | false | {"Kotlin": 36950} | class DayEight {
private fun getNumMemoryCharacters(string: String): Int {
var currentString = string
var result = 0
while (currentString.isNotEmpty()) {
val firstChar = currentString.first()
if (firstChar != '"') {
result++
}
if (firstChar == '\\') {
if (currentString.length < 2) {
currentString = ""
} else {
when (currentString[1]) {
'\\' -> currentString = currentString.drop(2)
'"' -> currentString = currentString.drop(2)
'x' -> currentString = currentString.drop(4)
}
}
} else {
currentString = currentString.drop(1)
}
}
return result
}
fun getNumEncodedCharacters(string: String): Int =
string.sumOf { char ->
when (char) {
'\\', '"' -> 2 as Int
else -> 1 as Int
}
} + 2
private fun readStrings(path: String) =
readLines(path)
.map { string -> string.filterNot { it.isWhitespace() } }
fun solvePartOne() {
val strings = readStrings("day_eight.txt")
val totalCodeLength = strings.sumOf { it.length }
val totalMemoryLength = strings.sumOf { getNumMemoryCharacters(it) }
val diff = totalCodeLength - totalMemoryLength
println(diff)
}
fun solvePartTwo() {
val strings = readStrings("day_eight.txt")
val totalCodeLength = strings.sumOf { it.length }
val totalEncodedLength = strings.sumOf { getNumEncodedCharacters(it) }
val diff = totalEncodedLength - totalCodeLength
println(diff)
}
}
fun main() {
DayEight().solvePartTwo()
} | 0 | Kotlin | 0 | 0 | 3ba05bc0d3e27d9cbfd99ca37ca0db0775bb72d6 | 1,868 | advent-of-code-2015 | MIT License |
src/Day11.kt | HylkeB | 573,815,567 | false | {"Kotlin": 83982} | fun main() {
class Operation(
val leftValue: String,
val operator: String,
val rightValue: String,
) {
fun execute(oldValue: Long): Long {
val left = if (leftValue == "old") oldValue else leftValue.toLong()
val right = if (rightValue == "old") oldValue else rightValue.toLong()
return when (operator) {
"*" -> left * right
"+" -> left + right
else -> throw IllegalStateException("Unknown operator: $operator")
}
}
}
class Monkey {
val items = ArrayDeque<Long>()
lateinit var operation: Operation
var testModulo = -1L
var testTrue = -1
var testFalse = -1
var inspectCounter = 0L
}
fun parseMonkeys(input: List<String>): List<Monkey> {
val monkeys = mutableListOf<Monkey>()
input.map { it.trim() }.forEach { line ->
when {
line.startsWith("Monkey") -> {
monkeys.add(Monkey())
}
line.startsWith("Starting items") -> {
line.substringAfter("Starting items: ").split(", ").map { it.toLong() }
.forEach {
monkeys.last().items.addLast(it)
}
}
line.startsWith("Operation") -> {
val operationData = line.substringAfter("Operation: new = ").split(" ")
monkeys.last().operation = Operation(operationData[0], operationData[1], operationData[2])
}
line.startsWith("Test") -> {
monkeys.last().testModulo = line.substringAfter("Test: divisible by ").toLong()
}
line.startsWith("If true") -> {
monkeys.last().testTrue = line.substringAfter("If true: throw to monkey ").toInt()
}
line.startsWith("If false") -> {
monkeys.last().testFalse = line.substringAfter("If false: throw to monkey ").toInt()
}
}
}
return monkeys
}
fun part1(input: List<String>): Long {
val monkeys = parseMonkeys(input)
repeat(20) {
monkeys.forEach { monkey ->
while (monkey.items.isNotEmpty()) {
val startWorryScore = monkey.items.removeFirst()
val inspectWorryScore = monkey.operation.execute(startWorryScore)
monkey.inspectCounter++
val boredomWorryScore = inspectWorryScore / 3
val test = boredomWorryScore % monkey.testModulo
if (test == 0L) {
monkeys[monkey.testTrue].items.addLast(boredomWorryScore)
} else {
monkeys[monkey.testFalse].items.addLast(boredomWorryScore)
}
}
}
}
val busiestMonkeys = monkeys.sortedByDescending { it.inspectCounter }
.take(2)
return busiestMonkeys[0].inspectCounter * busiestMonkeys[1].inspectCounter
}
fun part2(input: List<String>): Long {
val monkeys = parseMonkeys(input)
val biggestCommonDenominator = monkeys.fold(1L) { acc, monkey ->
acc * monkey.testModulo
}
repeat(10000) {
monkeys.forEachIndexed { index, monkey ->
while (monkey.items.isNotEmpty()) {
val startWorryScore = monkey.items.removeFirst()
val inspectWorryScore = monkey.operation.execute(startWorryScore)
val normalizedInspectorWorryScore = inspectWorryScore % biggestCommonDenominator
monkey.inspectCounter++
val test = normalizedInspectorWorryScore % monkey.testModulo
val newMonkey = if (test == 0L) {
monkey.testTrue
} else {
monkey.testFalse
}
monkeys[newMonkey].items.addLast(normalizedInspectorWorryScore)
}
}
}
val busiestMonkeys = monkeys.sortedByDescending { it.inspectCounter }
return busiestMonkeys[0].inspectCounter * busiestMonkeys[1].inspectCounter
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day11_test")
check(part1(testInput) == 10605L)
check(part2(testInput) == 2713310158L)
val input = readInput("Day11")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 8649209f4b1264f51b07212ef08fa8ca5c7d465b | 4,701 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/main/aoc2019/Day7.kt | nibarius | 154,152,607 | false | {"Kotlin": 963896} | package aoc2019
class Day7(input: List<String>) {
private val parsedInput = input.map { it.toLong() }.toList()
data class Amplifier(val program: List<Long>, val setting: Long) {
private val computer = Intcode(program, mutableListOf(setting))
fun isDone() = computer.computerState == Intcode.ComputerState.Terminated
// Provide input to the computer, run until it halts and return the output
fun input(value: Long) = computer.apply {
input.add(value)
run()
}.output.removeAt(0)
}
private fun runAmplifiers(settings: List<Long>): Long {
val amps = settings.map { Amplifier(parsedInput, it) }
var i = 0
// Sequence of amplifier runs each feeds it's output as input to the next one until all has terminated
return generateSequence(0L) { amps[i++ % amps.size].input(it) }
.first { amps.all { it.isDone() } }
}
private fun highestSignal(sequences: List<List<Long>>) = sequences.maxOf { runAmplifiers(it) }
fun solvePart1(): Long {
return highestSignal(allPermutationsOf(0..4))
}
fun solvePart2(): Long {
return highestSignal(allPermutationsOf(5..9))
}
fun allPermutationsOf(input: IntRange) = mutableListOf<List<Long>>().apply {
permutations(input.map { it.toLong() }, listOf(), this)
}
private fun permutations(remaining: List<Long>, soFar: List<Long>, result: MutableList<List<Long>>) {
if (remaining.isEmpty()) {
result.add(soFar)
return
}
for (i in remaining.indices) {
permutations(
remaining.toMutableList().apply { removeAt(i) },
soFar.toMutableList().apply { add(remaining[i]) },
result
)
}
}
} | 0 | Kotlin | 0 | 6 | f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22 | 1,838 | aoc | MIT License |
src/main/kotlin/se/saidaspen/aoc/aoc2022/Day19.kt | saidaspen | 354,930,478 | false | {"Kotlin": 301372, "CSS": 530} | package se.saidaspen.aoc.aoc2022
import se.saidaspen.aoc.util.*
import java.lang.Integer.max
import kotlin.math.min
fun main() = Day19.run()
object Day19 : Day(2022, 19) {
private val bps = input.lines().map { ints(it) }.map {
Pair(
it[0], // id of blueprint
listOf(listOf(it[1], 0, 0, 0), // ore robot
listOf(it[2], 0, 0, 0), // clay robot
listOf(it[3], it[4], 0, 0), // obsidian robot
listOf(it[5], 0, it[6], 0) // geode robot
)
)
}
override fun part1() = bps.sumOf { it.first * solve(it.second, 24)}
override fun part2()= bps.subList(0, 3).map { solve(it.second, 32) }.reduce { acc, next -> acc * next}
private fun solve(bps: List<List<Int>>, initialTime: Int): Int {
fun canAfford(bp: List<Int>, inv: List<Int>) = inv.withIndex().all { it.value >= bp[it.index] }
// First four are resources, next four are robots, last one is the time left.
val start = listOf(0, 0, 0, 0, 1, 0, 0, 0, initialTime)
val queue = listOf(start).toArrayDeque()
val seen = mutableSetOf<List<Int>>()
var best = 0
// Maximum cost of any resource to be used in any one round
val maxCosts = listOf(
bps.map { it[0] }.max(), // The price of most expensive ore consumption
bps.map { it[1] }.max(), // The price of most expensive clay consumption
bps[3][2], // The price of most expensive obsidian consumption (only geode robots cost obsidian!)
)
main@while (queue.isNotEmpty()) {
val curr = queue.pop()!!
if (seen.contains(curr)) continue // We have already checked this one
val timeLeft = curr[8]
if (timeLeft == 0) { // Time's up. Tally up.
best = max(best, curr[3])
continue
}
// If we have no chance to make it to best, give up.
if ((timeLeft * timeLeft + timeLeft) / 2 + curr[7] * timeLeft <= best - curr[3]) continue
val currentInv = curr.subList(0, 4).toMutableList()
val currentFactory = curr.subList(4)
// Throw away excess inventory. Makes for more cache-hits of seen, makes it faster.
currentInv[0] = min(currentInv[0], (timeLeft * maxCosts[0]) - (curr[4] * (timeLeft - 1)))
currentInv[1] = min(currentInv[1], (timeLeft * maxCosts[1]) - (curr[5] * (timeLeft - 1)))
currentInv[2] = min(currentInv[2], (timeLeft * maxCosts[2]) - (curr[6] * (timeLeft - 1)))
val nextInventory = currentInv.elemAdd(currentFactory)
val nextTime = timeLeft - 1
// If we can afford a geo-cracking robot, build it and move on!
if (canAfford(bps[3], currentInv)) {
queue.push(nextInventory.elemSubtract(bps[3]) + currentFactory.elemAdd(0, 0, 0, 1) + nextTime)
continue@main
}
// We can only build one robot at a time, so, build any robot that we can afford to build.
for (i in 0..2) {
// Don't build more robots than what can produce resources to be consumed in one round.
// it's a waste of time. Except for geode-cracking robots!
if (currentFactory[i] <= maxCosts[i] && canAfford(bps[i], currentInv)) {
val nextFactory = currentFactory.toMutableList()
nextFactory[i] += 1
queue.push(nextInventory.elemSubtract(bps[i]) + nextFactory + nextTime)
}
}
// We always have the possibility of not building any robots at all
queue.push(nextInventory + currentFactory + nextTime)
seen.add(curr)
}
return best
}
} | 0 | Kotlin | 0 | 1 | be120257fbce5eda9b51d3d7b63b121824c6e877 | 3,817 | adventofkotlin | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/PathsWithMaxScore.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import dev.shtanko.algorithms.MOD
/**
* 1301. Number of Paths with Max Score
* @see <a href="https://leetcode.com/problems/number-of-paths-with-max-score/">Source</a>
*/
fun interface PathsWithMaxScore {
operator fun invoke(board: List<String>): IntArray
}
class PathsWithMaxScoreDP : PathsWithMaxScore {
private val dirs = arrayOf(intArrayOf(0, -1), intArrayOf(-1, 0), intArrayOf(-1, -1))
override operator fun invoke(board: List<String>): IntArray {
val m: Int = board.size
val n: Int = board[0].length
val dpSum = Array(m) { IntArray(n) }
val dpCnt = Array(m) { IntArray(n) }
dpCnt[m - 1][n - 1] = 1 // start at the bottom right square
for (r in m - 1 downTo 0) {
for (c in n - 1 downTo 0) {
if (dpCnt[r][c] == 0) {
continue
}
for (dir in dirs) {
val nr = r + dir[0]
val nc = c + dir[1]
if (nr >= 0 && nc >= 0 && board[nr][nc] != 'X') {
var nsum = dpSum[r][c]
if (board[nr][nc] != 'E') nsum += board[nr][nc] - '0'
if (nsum > dpSum[nr][nc]) {
dpCnt[nr][nc] = dpCnt[r][c]
dpSum[nr][nc] = nsum
} else if (nsum == dpSum[nr][nc]) {
dpCnt[nr][nc] = (dpCnt[nr][nc] + dpCnt[r][c]) % MOD
}
}
}
}
}
return intArrayOf(dpSum[0][0], dpCnt[0][0])
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,261 | kotlab | Apache License 2.0 |
app/src/main/kotlin/advent_of_code/year_2022/day3/RucsackReorganization.kt | mavomo | 574,441,138 | false | {"Kotlin": 56468} | package advent_of_code.year_2022.day3
import com.google.common.collect.ImmutableList
class RucsackReorganization {
private val alphabetsInLowerCase = ('a'..'z').toSet()
private val alphabetsInUpperCase = ('A'..'Z').toSet()
fun computeSumOfAllPriorities(sample: List<String>): Any {
var totalPriorities = 0
val itemsByPriorities = itemsTypeByPriorities()
for (it in sample) {
val commonItem = findCommonItems(it).first()
totalPriorities += if (commonItem.isLowerCase()) {
itemsByPriorities.first.get(commonItem)!!
}else {
itemsByPriorities.second.get(commonItem)!!
}
}
return totalPriorities
}
fun findCommonItems(content: String): Set<Char> {
val contentByCompartiment: List<String> = content.chunked(content.length / 2)
val contentOfFirstCompartiment = contentByCompartiment.first().toCharArray()
val contentOfSecondCompartiment = contentByCompartiment.last().toCharArray()
return contentOfFirstCompartiment.intersect(contentOfSecondCompartiment.toList())
}
fun itemsTypeByPriorities(): Pair<Map<Char, Int>, Map<Char, Int>> {
val lowercaseWithPriorities: Map<Char, Int> = alphabetsInLowerCase.mapIndexed { index, currentItem ->
Pair(currentItem, index + 1)
}.toMap()
var initialIdx = 26
val uppercaseWithPriorities: Map<Char, Int> = alphabetsInUpperCase.map { currrentItem ->
initialIdx++
Pair(currrentItem, initialIdx)
}.toMap()
return Pair(lowercaseWithPriorities, uppercaseWithPriorities)
}
fun findCommonItemsInGroupOf3(items: List<String>): ImmutableList<Char> {
val nbGroups = items.chunked(3)
val commonItems: MutableList<Char> = mutableListOf()
nbGroups.forEach { itemsOfGroup ->
val firstGroup = itemsOfGroup.first().toCharArray()
val secondGroup = itemsOfGroup.get(1).toCharArray()
val thirdGroup = itemsOfGroup.last().toCharArray()
val common = firstGroup.intersect(secondGroup.toList()).intersect(thirdGroup.toList())
commonItems.add(common.first())
}
return ImmutableList.copyOf(commonItems)
}
fun computeSumOfPrioritiesForAllGroups(commonItems: ImmutableList<Char>): Any {
val typesByPriority = itemsTypeByPriorities()
var totalPriorities = 0
commonItems.forEach{
totalPriorities += if(it.isLowerCase()){
typesByPriority.first.get(it)!!
}else {
typesByPriority.second.get(it)!!
}
}
return totalPriorities
}
}
| 0 | Kotlin | 0 | 0 | b7fec100ea3ac63f48046852617f7f65e9136112 | 2,726 | advent-of-code | MIT License |
src/main/java/Day9.kt | mattyb678 | 319,195,903 | false | null | class Day9 : Day {
override fun asInt(): Int = 9
override fun part1InputName(): String = "day9"
override fun part1(input: List<String>): String {
val preamble = 25
return firstNonMatch(preamble, input).toString()
}
private fun List<Long>.sums(): Sequence<Long> {
val result = mutableListOf<Long>()
this.forEachIndexed { i, x ->
this.forEachIndexed { j, y ->
if (i != j) {
result.add(x + y)
}
}
}
return result.asSequence()
}
override fun part2InputName(): String = "day9"
override fun part2(input: List<String>): String {
val preamble = 25
val invalidNumber = firstNonMatch(preamble, input)
val values = input.map(String::toLong)
val prefixSums = values.prefixSum()
for (i in 0 until prefixSums.size) {
for (j in 1 until prefixSums.size) {
val begin = prefixSums[i]
val end = prefixSums[j]
if (end - begin == invalidNumber) {
val inner = values.subList(i, j)
val min = inner.minOrNull() ?: Long.MIN_VALUE
val max = inner.maxOrNull() ?: Long.MAX_VALUE
return (min + max).toString()
}
}
}
return "-1"
}
private fun List<Long>.prefixSum(): List<Long> {
return this.fold(listOf()) { resultList, el ->
if (resultList.isEmpty()) {
resultList + el
} else {
resultList + (resultList.last() + el)
}
}
}
private fun firstNonMatch(preambleCount: Int, input: List<String>): Long {
val numberList = input.map(String::toLong).windowed(preambleCount + 1, 1)
var firstNonMatch = 0L
for (numbers in numberList) {
val last = numbers.last()
val toCheck = numbers.dropLast(1)
val match = toCheck.sums().any { it == last }
if (!match) {
firstNonMatch = last
break
}
}
return firstNonMatch
}
} | 0 | Kotlin | 0 | 1 | f677d61cfd88e18710aafe6038d8d59640448fb3 | 2,194 | aoc-2020 | MIT License |
src/Day05.kt | nordberg | 573,769,081 | false | {"Kotlin": 47470} | fun main() {
fun part1(input: List<String>): String {
// [P] [L] [T]
// [L] [M] [G] [G] [S]
// [M] [Q] [W] [H] [R] [G]
// [N] [F] [M] [D] [V] [R] [N]
// [W] [G] [Q] [P] [J] [F] [M] [C]
// [V] [H] [B] [F] [H] [M] [B] [H] [B]
// [B] [Q] [D] [T] [T] [B] [N] [L] [D]
// [H] [M] [N] [Z] [M] [C] [M] [P] [P]
// 1 2 3 4 5 6 7 8 9
val piles = mutableListOf(
mutableListOf('H', 'B', 'V', 'W', 'N', 'M', 'L', 'P'),
mutableListOf('M', 'Q', 'H'),
mutableListOf('N', 'D', 'B', 'G', 'F', 'Q', 'M', 'L'),
mutableListOf('Z', 'T', 'F', 'Q', 'M', 'W', 'G'),
mutableListOf('M', 'T', 'H', 'P'),
mutableListOf('C', 'B', 'M', 'J', 'D', 'H', 'G', 'T'),
mutableListOf('M', 'N', 'B', 'F', 'V', 'R'),
mutableListOf('P', 'L', 'H', 'M', 'R', 'G', 'S'),
mutableListOf('P', 'D', 'B', 'C', 'N')
)
input.forEach {
val (numToMove, fromPile, toPile) = it.split(";").map { z -> z.toInt() }
for (i in 1..numToMove) {
piles[toPile - 1].add(piles[fromPile - 1].removeLast())
}
}
return piles.map { it.last() }.joinToString("")
}
fun part2(input: List<String>): String {
val piles = mutableListOf(
listOf('H', 'B', 'V', 'W', 'N', 'M', 'L', 'P'),
listOf('M', 'Q', 'H'),
listOf('N', 'D', 'B', 'G', 'F', 'Q', 'M', 'L'),
listOf('Z', 'T', 'F', 'Q', 'M', 'W', 'G'),
listOf('M', 'T', 'H', 'P'),
listOf('C', 'B', 'M', 'J', 'D', 'H', 'G', 'T'),
listOf('M', 'N', 'B', 'F', 'V', 'R'),
listOf('P', 'L', 'H', 'M', 'R', 'G', 'S'),
listOf('P', 'D', 'B', 'C', 'N')
)
input.forEach {
val (numToMove, fromPile, toPile) = it.split(";").map { z -> z.toInt() }
val fromThis = piles[fromPile - 1]
piles[toPile - 1] += fromThis.takeLast(numToMove)
piles[fromPile - 1] = fromThis.dropLast(numToMove)
}
return piles.map { it.last() }.joinToString("")
}
// test if implementation meets criteria from the description, like:
// val testInput = readInput("Day01_test")
//check(part1(testInput) == 1)
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 3de1e2b0d54dcf34a35279ba47d848319e99ab6b | 2,476 | aoc-2022 | Apache License 2.0 |
solutions/src/CherryPickup.kt | JustAnotherSoftwareDeveloper | 139,743,481 | false | {"Kotlin": 305071, "Java": 14982} | import java.util.*
/**
* https://leetcode.com/problems/cherry-pickup/
*/
class CherryPickup {
fun cherryPickup(grid: Array<IntArray>): Int {
val n = grid.size
val dp = Array(n + 1) { Array(n + 1) { IntArray(n + 1) } }
for (i in 0..n) {
for (j in 0..n) {
Arrays.fill(dp[i][j], Int.MIN_VALUE)
}
}
dp[1][1][1] = grid[0][0]
for (x1 in 1..n) {
for (y1 in 1..n) {
for (x2 in 1..n) {
val y2 = x1 + y1 - x2
if (dp[x1][y1][x2] > 0 || y2 < 1 || y2 > n || grid[x1 - 1][y1 - 1] == -1 || grid[x2 - 1][y2 - 1] == -1) {
continue
// have already detected || out of boundary || cannot access
}
val cur = Math.max(Math.max(dp[x1 - 1][y1][x2], dp[x1 - 1][y1][x2 - 1]), Math.max(dp[x1][y1 - 1][x2], dp[x1][y1 - 1][x2 - 1]))
if (cur < 0) {
continue
}
dp[x1][y1][x2] = cur + grid[x1 - 1][y1 - 1]
if (x1 != x2) {
dp[x1][y1][x2] += grid[x2 - 1][y2 - 1]
}
}
}
}
return if (dp[n][n][n] < 0) 0 else dp[n][n][n]
}
}
| 0 | Kotlin | 0 | 0 | fa4a9089be4af420a4ad51938a276657b2e4301f | 1,338 | leetcode-solutions | MIT License |
src/Day04.kt | PascalHonegger | 573,052,507 | false | {"Kotlin": 66208} | fun main() {
fun String.toCleaningRange() = split('-').let { (from, to) -> from.toInt()..to.toInt() }
fun String.toCleaningRanges() = split(',').map { it.toCleaningRange() }
operator fun IntRange.contains(other: IntRange) = first <= other.first && last >= other.last
fun part1(input: List<String>): Int {
return input.count { group ->
val (elf1, elf2) = group.toCleaningRanges()
elf1 in elf2 || elf2 in elf1
}
}
fun part2(input: List<String>): Int {
return input.count { group ->
val (elf1, elf2) = group.toCleaningRanges()
elf1.intersect(elf2).isNotEmpty()
}
}
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 2215ea22a87912012cf2b3e2da600a65b2ad55fc | 875 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/g1701_1800/s1722_minimize_hamming_distance_after_swap_operations/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g1701_1800.s1722_minimize_hamming_distance_after_swap_operations
// #Medium #Array #Depth_First_Search #Union_Find
// #2023_06_16_Time_843_ms_(100.00%)_Space_87.9_MB_(100.00%)
class Solution {
fun minimumHammingDistance(source: IntArray, target: IntArray, allowedSwaps: Array<IntArray>): Int {
var i: Int
val n = source.size
var weight = 0
val parent = IntArray(n)
i = 0
while (i < n) {
parent[i] = i
i++
}
for (swap in allowedSwaps) {
union(swap[0], swap[1], parent)
}
val components = HashMap<Int, MutableList<Int>>()
i = 0
while (i < n) {
find(i, parent)
val list = components.getOrDefault(parent[i], ArrayList())
list.add(i)
components[parent[i]] = list
i++
}
for ((_, value) in components) {
weight += getHammingDistance(source, target, value)
}
return weight
}
private fun getHammingDistance(source: IntArray, target: IntArray, indices: List<Int>): Int {
val list1 = HashMap<Int, Int>()
val list2 = HashMap<Int, Int>()
for (i in indices) {
list1[target[i]] = 1 + list1.getOrDefault(target[i], 0)
list2[source[i]] = 1 + list2.getOrDefault(source[i], 0)
}
var size = indices.size
for ((key, value) in list1) {
size -= Math.min(value, list2.getOrDefault(key, 0))
}
return size
}
private fun union(x: Int, y: Int, parent: IntArray) {
if (x != y) {
val a = find(x, parent)
val b = find(y, parent)
if (a != b) {
parent[a] = b
}
}
}
private fun find(x: Int, parent: IntArray): Int {
var y = x
while (y != parent[y]) {
y = parent[y]
}
parent[x] = y
return y
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,973 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/g2801_2900/s2809_minimum_time_to_make_array_sum_at_most_x/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g2801_2900.s2809_minimum_time_to_make_array_sum_at_most_x
// #Hard #Array #Dynamic_Programming #Sorting
// #2023_12_06_Time_325_ms_(100.00%)_Space_42.6_MB_(100.00%)
import kotlin.math.max
class Solution {
fun minimumTime(nums1: List<Int?>, nums2: List<Int?>, x: Int): Int {
val n = nums1.size
val nums = Array(n) { IntArray(2) }
for (i in 0 until n) {
nums[i] = intArrayOf(nums1[i]!!, nums2[i]!!)
}
nums.sortWith { a: IntArray, b: IntArray -> a[1] - b[1] }
val dp = IntArray(n + 1)
var sum1: Long = 0
var sum2: Long = 0
for (i in 0 until n) {
sum1 += nums[i][0].toLong()
sum2 += nums[i][1].toLong()
}
if (sum1 <= x) {
return 0
}
for (j in 0 until n) {
for (i in j + 1 downTo 1) {
dp[i] = max(dp[i].toDouble(), (nums[j][0] + nums[j][1] * i + dp[i - 1]).toDouble())
.toInt()
}
}
for (i in 1..n) {
if (sum1 + sum2 * i - dp[i] <= x) {
return i
}
}
return -1
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,161 | LeetCode-in-Kotlin | MIT License |
src/Day02.kt | NunoPontes | 572,963,410 | false | {"Kotlin": 7416} | fun main() {
val rock = 1
val paper = 2
val scissors = 3
val win = 6
val draw = 3
val lost = 0
fun part1(input: List<String>): Int {
return input.sumOf {
when (it) {
"A X" -> rock + draw
"A Y" -> paper + win
"A Z" -> scissors + lost
"B X" -> rock + lost
"B Y" -> paper + draw
"B Z" -> scissors + win
"C X" -> rock + win
"C Y" -> paper + lost
"C Z" -> scissors + draw
else -> lost.toInt()
}
}
}
fun part2(input: List<String>): Int {
return input.sumOf {
when (it) {
"A X" -> scissors + lost
"A Y" -> rock + draw
"A Z" -> paper + win
"B X" -> rock + lost
"B Y" -> paper + draw
"B Z" -> scissors + win
"C X" -> paper + lost
"C Y" -> scissors + draw
"C Z" -> rock + win
else -> lost.toInt()
}
}
}
val inputPart1 = readInput("Day02_part1")
val inputPart2 = readInput("Day02_part2")
println(part1(inputPart1))
println(part2(inputPart2))
}
| 0 | Kotlin | 0 | 0 | 78b67b952e0bb51acf952a7b4b056040bab8b05f | 1,293 | advent-of-code-2022 | Apache License 2.0 |
2023/10/solve-1.kts | gugod | 48,180,404 | false | {"Raku": 170466, "Perl": 121272, "Kotlin": 58674, "Rust": 3189, "C": 2934, "Zig": 850, "Clojure": 734, "Janet": 703, "Go": 595} | import java.io.File
enum class Dir { NORTH, EAST, SOUTH, WEST }
data class Coord (val y: Int, val x: Int)
class PipeNetwork (val sketch: List<String>) {
val rows = sketch.indices
val cols = sketch[0].indices
private val dirsOfPipe = mapOf<Char,List<Dir>>(
'|' to listOf(Dir.NORTH, Dir.SOUTH),
'-' to listOf(Dir.EAST, Dir.WEST),
'L' to listOf(Dir.NORTH, Dir.EAST),
'J' to listOf(Dir.NORTH, Dir.WEST),
'7' to listOf(Dir.WEST, Dir.SOUTH),
'F' to listOf(Dir.EAST, Dir.SOUTH),
);
fun lookupSketch (p: Coord) = sketch[p.y][p.x]
fun locateAnimal () : Coord {
rows.forEach { y ->
cols.forEach { x ->
if (sketch[y][x] == 'S')
return Coord(y,x)
}
}
throw IllegalStateException("No Animal?")
}
fun neswOf (p: Coord): Map<Dir,Coord> =
mapOf(
Dir.NORTH to Coord(p.y-1, p.x),
Dir.EAST to Coord(p.y, p.x+1),
Dir.SOUTH to Coord(p.y+1, p.x),
Dir.WEST to Coord(p.y, p.x-1),
)
.filterValues { rows.contains(it.y) && cols.contains(it.x) }
fun connectionOfAnimal (p: Coord) =
neswOf(p).filter { (dir,p) ->
val c = lookupSketch(p)
when (dir) {
Dir.NORTH -> (listOf('|', '7', 'F').any { c == it })
Dir.EAST -> (listOf('-', '7', 'J').any { c == it })
Dir.SOUTH -> (listOf('|', 'L', 'J').any { c == it })
Dir.WEST -> (listOf('-', 'L', 'F').any { c == it })
}
}
fun connectionOfPipe (p: Coord) =
dirsOfPipe
.get(lookupSketch(p))!!
.let { conns ->
neswOf(p).filterKeys { dir -> conns.any { it == dir } }
}
fun mainLoop () {
var s = locateAnimal()
val visited = hashSetOf<Coord>(s)
var current = connectionOfAnimal(s).values
var steps = 0
while (current.count() != 0) {
steps++
current = current.flatMap {
visited.add(it)
connectionOfPipe(it).values
}.filter { !visited.contains(it) }
}
println(steps)
}
}
val nw = PipeNetwork(File(args.getOrNull(0) ?: "input").readLines())
val s = nw.locateAnimal()
println(s)
val t = nw.connectionOfAnimal(s)
println(t)
nw.mainLoop()
| 0 | Raku | 1 | 5 | ca0555efc60176938a857990b4d95a298e32f48a | 2,398 | advent-of-code | Creative Commons Zero v1.0 Universal |
dcp_kotlin/src/main/kotlin/dcp/day231/day231.kt | sraaphorst | 182,330,159 | false | {"C++": 577416, "Kotlin": 231559, "Python": 132573, "Scala": 50468, "Java": 34742, "CMake": 2332, "C": 315} | package dcp.day231
// day231.kt
// By <NAME>, 2019.
import kotlin.math.ceil
/**
* Interleave letters of s if possible in a way that no two adjacent letters are the same.
* Returns null if cannot be done, and otherwise one method of doing so.
*/
fun interleave(s: String): String? {
// Check if feasible.
if (s.isEmpty())
return ""
// Sort letters by frequency, and get the letter with the highest count.
// If the letter with the highest count appears too many times, we cannot perform any rearranging and fail.
val lettersByFrequency = s.toSet().map { c -> c to s.count { c == it }}.toList().sortedBy { it.second }.reversed()
val maxSymbols = lettersByFrequency.firstOrNull()?.second
if (maxSymbols == null || maxSymbols > ceil(s.length.toDouble() / 2).toInt())
return null
// Now form the string. We want to interleave characters from the first half with the chracters from the second
// half using zip, so we have to work with character arrays instead of strings.
val preprocessed = lettersByFrequency.map { (c, num) -> c.toString().repeat(num) }.joinToString(separator = ""){it}.toList()
val splitPoint = s.length / 2 + s.length % 2
val firstHalf = preprocessed.take(splitPoint)
val secondHalf = preprocessed.drop(splitPoint)
// If there is an odd number of characters, we have to append the last character from firstHalf or it will get
// devoured by zip due to the discrepancy of sizes of firstHalf and secondHalf, so we have a special case for it.
return firstHalf.zip(secondHalf).joinToString(separator = "") { "${it.first}${it.second}" } +
if (firstHalf.size > secondHalf.size) firstHalf.last().toString() else ""
}
/**
* Check if a string produced by interleave is valid, i.e. the string passed into this function has no two
* adjacent letters that are the same.
*/
fun checkIfValid(s: String): Boolean =
s.zipWithNext().none { it.first == it.second }
| 0 | C++ | 1 | 0 | 5981e97106376186241f0fad81ee0e3a9b0270b5 | 1,984 | daily-coding-problem | MIT License |
src/Day02.kt | RickShaa | 572,623,247 | false | {"Kotlin": 34294} | fun main() {
val fileName = "day02.txt"
val testFileName = "day02_test.txt"
val input:String = FileUtil.getTrimmedText(fileName);
val testInput:String = FileUtil.getTrimmedText(testFileName);
val WON = 6;
val DRAW =3;
val LOSS = 0;
//Create Lookup map to store
val choiceMap = mapOf<String, Choice>(
"A" to Choice.ROCK,
"B" to Choice.PAPER,
"C" to Choice.SCISSORS,
"Y" to Choice.PAPER,
"X" to Choice.ROCK,
"Z" to Choice.SCISSORS
)
val pointsMap = mapOf<Choice, Int>(
Choice.ROCK to 1,
Choice.PAPER to 2,
Choice.SCISSORS to 3
)
fun getPointsByChoice(choice: Choice):Int?{
return pointsMap[choice]
}
fun getChoice(key:String): Choice? {
return choiceMap[key]
}
var finalScore = 0;
val matches = input.split("\n");
matches.forEach{
match->
val picks = match.split(" ")
//Translate A,B,X to ROCK, PAPER, SCISSORS
val choice = getChoice(picks[1])!!
val oppChoice = getChoice(picks[0])!!
//draw case
if(
choice == Choice.ROCK && oppChoice == Choice.ROCK ||
choice == Choice.PAPER && oppChoice == Choice.PAPER ||
choice == Choice.SCISSORS && oppChoice == Choice.SCISSORS){
//win case
finalScore+= DRAW + getPointsByChoice(choice)!!
}else if(
choice == Choice.ROCK && oppChoice == Choice.SCISSORS ||
choice == Choice.PAPER && oppChoice == Choice.ROCK ||
choice == Choice.SCISSORS && oppChoice == Choice.PAPER
){
finalScore+= WON + getPointsByChoice(choice)!!
}else{
finalScore+= getPointsByChoice(choice)!!
}
}
println(finalScore)
}
enum class Choice{
ROCK,
PAPER,
SCISSORS
}
| 0 | Kotlin | 0 | 1 | 76257b971649e656c1be6436f8cb70b80d5c992b | 1,877 | aoc | Apache License 2.0 |
2020/src/year2021/day10/code.kt | eburke56 | 436,742,568 | false | {"Kotlin": 61133} | package year2021.day10
import util.readAllLines
import java.util.*
fun main() {
part1()
part2()
}
private val OPENERS = setOf('(', '{', '[', '<')
private val CLOSERS = setOf(')', '}', ']', '>')
private val OPENTOCLOSE = mapOf(
'(' to ')',
'{' to '}',
'[' to ']',
'<' to '>'
)
private fun part1() {
val SCORES = mapOf(
')' to 3,
']' to 57,
'}' to 1197,
'>' to 25137
)
val sum = readAllLines("input.txt").sumOf { line ->
val stack = Stack<Char>()
var score = 0
for (it in line) {
when (it) {
in OPENERS -> stack.push(it)
in CLOSERS -> if (!checkClose(stack, it)) { score = SCORES[it]!!; break }
else -> error("Illegal character in processing")
}
}
score
}
println(sum)
}
private fun part2() {
val SCORES = mapOf(
')' to 1,
']' to 2,
'}' to 3,
'>' to 4
)
val scores = mutableListOf<Long>()
readAllLines("input.txt").forEach { line ->
var corrupt = false
val stack = Stack<Char>()
for (it in line) {
when (it) {
in OPENERS -> stack.push(it)
in CLOSERS -> if (!checkClose(stack, it)) { corrupt = true; break }
else -> error("Illegal character in processing")
}
}
if (!corrupt) {
var score = 0L
while (stack.isNotEmpty()) {
score = 5 * score + SCORES[OPENTOCLOSE[stack.pop()]]!!
}
scores.add(score)
}
}
scores.sorted().also {
println(it[it.size / 2])
}
}
private fun checkClose(stack: Stack<Char>, it: Char): Boolean =
when (it) {
in OPENERS -> true
in CLOSERS -> {
if (it == OPENTOCLOSE[stack.lastElement()]) {
stack.pop()
true
} else {
false
}
}
else -> error("Illegal character in checkClose")
}
| 0 | Kotlin | 0 | 0 | 24ae0848d3ede32c9c4d8a4bf643bf67325a718e | 2,072 | adventofcode | MIT License |
src/main/kotlin/eu/michalchomo/adventofcode/Utils.kt | MichalChomo | 572,214,942 | false | {"Kotlin": 56758} | package eu.michalchomo.adventofcode
import java.io.File
private const val ROOT_PATH = "src/main/kotlin/eu/michalchomo/adventofcode/year"
fun readInput(year: Int, name: String) =
File("$ROOT_PATH$year", "$name.txt").readText()
/**
* Reads lines from the given input txt file.
*/
fun readInputLines(year: Int, name: String) =
File("$ROOT_PATH$year", "$name.txt").readLines()
fun linesAsInts(lines: List<String>) = lines.map { l -> l.toInt() }
fun Boolean.toInt() = if (this) 1 else 0
fun <T> List<T>.split(includeEmpty: Boolean = false, isDelimiter: (T) -> Boolean) =
this.fold(mutableListOf<List<T>>() to mutableListOf<T>()) { (allParts, currentPart), element ->
if (isDelimiter(element) || this.lastOrNull() == element) {
if (includeEmpty || currentPart.isNotEmpty()) {
if (this.lastOrNull() == element) currentPart.add(element)
allParts.add(currentPart.toList())
}
currentPart.clear()
} else {
currentPart.add(element)
}
allParts to currentPart
}.first.toList()
fun LongRange.intersect(other: LongRange): LongRange? {
val start = maxOf(this.first, other.first)
val endInclusive = minOf(this.last, other.last)
return if (start <= endInclusive) start..endInclusive else null
}
fun LongRange.removeIntersectWith(other: LongRange): List<LongRange> = this.intersect(other)?.let { intersect ->
if (intersect.first == this.first && intersect.last == this.last) {
emptyList()
} else if (intersect.first > this.first && intersect.last < this.last) {
listOf(
this.first..<intersect.first,
intersect.last + 1..this.last
)
} else {
if (intersect.first > this.first) {
listOf(this.first..<intersect.first)
} else {
listOf(intersect.last+1..this.last)
}
}
} ?: listOf(this)
fun List<String>.toCharMatrix() = this.map { it.toCharArray() }.toTypedArray()
fun main(day: Day) {
val testInput = eu.michalchomo.adventofcode.year2023.readInputLines("${day.name()}_test")
println(day.part1(testInput))
println(day.part2(testInput))
val input = eu.michalchomo.adventofcode.year2023.readInputLines(day.name())
println(day.part1(input))
println(day.part2(input))
}
| 0 | Kotlin | 0 | 0 | a95d478aee72034321fdf37930722c23b246dd6b | 2,331 | advent-of-code | Apache License 2.0 |
2022/src/day21/day21.kt | Bridouille | 433,940,923 | false | {"Kotlin": 171124, "Go": 37047} | package day21
import GREEN
import RESET
import printTimeMillis
import readInput
sealed class Job {
data class Number(val nb: Long): Job()
data class Operation(val left: String, val right: String, val operation: Ope): Job()
}
interface Ope {
fun doOp(a: Long, b: Long): Long
fun fromResult(result: Long, a: Long?, b: Long?): Long // either a or b is null, but not both
}
class Mul : Ope {
override fun doOp(a: Long, b: Long) = a * b
// 15 * X = 150 -> X = 150/15
// X * 15 = 150 -> X = 150/15
override fun fromResult(result: Long, a: Long?, b: Long?) = result / (a ?: b!!)
}
class Plus : Ope {
override fun doOp(a: Long, b: Long) = a + b
// 15 + X = 150 -> X = 150 - 15
// X + -15 = 150 -> X = 150 - -15
override fun fromResult(result: Long, a: Long?, b: Long?) = result - (a ?: b!!)
}
class Minus : Ope {
override fun doOp(a: Long, b: Long) = a - b
// 15 - X = 150 -> X = -150 + 15 = -135 (-result + b)
// 15 - X = -40 -> X = 40 + 15 = 55 (-result + b)
// X - 15 = 150 -> X = 150 + 15 = 165 (result + b)
// X - 15 = -40 -> X = -40 + 15 = -25 (result + b)
override fun fromResult(result: Long, a: Long?, b: Long?): Long {
return if (a != null) -result + a else result + b!!
}
}
class Div : Ope {
override fun doOp(a: Long, b: Long) = a / b
// 150 / X = 15 -> X = 150 / 15 = 10
// X / 15 = 10 -> X = 10 * 15 = 150
override fun fromResult(result: Long, a: Long?, b: Long?): Long {
return if (a != null) a / result else result * b!!
}
}
val OPE = mapOf("*" to Mul(), "+" to Plus(), "-" to Minus(), "/" to Div())
const val END_NODE = "humn"
const val ROOT_NODE = "root"
fun monkeyMap(input: List<String>): MutableMap<String, Job> {
val ret = mutableMapOf<String, Job>()
for (l in input) {
val name = l.split(": ")[0]
val inst = l.split(": ")[1]
val job = if (inst.toIntOrNull() != null) {
Job.Number(inst.toLong())
} else {
val ope = inst.split(" ")
Job.Operation(ope[0], ope[2], OPE[ope[1]]!!)
}
ret[name] = job
}
return ret
}
fun resolve(monkeys: MutableMap<String, Job>, start: String): Long {
if (monkeys[start] is Job.Number) return (monkeys[start] as Job.Number).nb
val ope = monkeys[start] as Job.Operation
val result = ope.operation.doOp(resolve(monkeys, ope.left), resolve(monkeys, ope.right))
monkeys[start] = Job.Number(result)
return result
}
fun part1(input: List<String>) = resolve(monkeyMap(input), ROOT_NODE)
fun hasEndNode(monkeys: MutableMap<String, Job>, start: String): Boolean {
if (start == END_NODE) return true
if (monkeys[start] is Job.Number) return false
val ope = monkeys[start] as Job.Operation
return hasEndNode(monkeys, ope.left) || hasEndNode(monkeys, ope.right)
}
fun resolveEquation(monkeys: MutableMap<String, Job>, start: String, wanted: Long): Long {
if (start == END_NODE) return wanted
val ope = monkeys[start] as Job.Operation
val unknownIsLeft = hasEndNode(monkeys, ope.left)
val knownValue = resolve(monkeys, if (unknownIsLeft) ope.right else ope.left)
// Compute the new number we're looking for from the result + one operand
val newWanted = if (start == ROOT_NODE) {
knownValue
} else {
ope.operation.fromResult(
wanted,
if (unknownIsLeft) null else knownValue,
if (unknownIsLeft) knownValue else null
)
}
return resolveEquation(monkeys, if (unknownIsLeft) ope.left else ope.right, newWanted)
}
fun part2(input: List<String>) = resolveEquation(monkeyMap(input), ROOT_NODE, -1)
fun main() {
val testInput = readInput("day21_example.txt")
printTimeMillis { print("part1 example = $GREEN" + part1(testInput) + RESET) }
printTimeMillis { print("part2 example = $GREEN" + part2(testInput) + RESET) }
val input = readInput("day21.txt")
printTimeMillis { print("part1 input = $GREEN" + part1(input) + RESET) }
printTimeMillis { print("part2 input = $GREEN" + part2(input) + RESET) }
}
| 0 | Kotlin | 0 | 2 | 8ccdcce24cecca6e1d90c500423607d411c9fee2 | 4,106 | advent-of-code | Apache License 2.0 |
src/Day06.kt | iartemiev | 573,038,071 | false | {"Kotlin": 21075} | fun findUnique(line: String, sequenceLength: Int): Int {
var startIdx = 0
var found = false
while (!found) {
val countSet = line.subSequence(startIdx, startIdx + sequenceLength).toSet()
if (countSet.size == sequenceLength) {
found = true
} else {
startIdx++
}
}
return startIdx + sequenceLength
}
//Cathrin's solution - saving for future ref
fun processWindowOfX(input: String, x: Int) : Int{
return input.windowed(x,1) {
window -> window.toSet().size == x
}.indexOf(true) + x
}
fun main() {
fun part1(input: List<String>): Int {
val (line) = input
return findUnique(line, 4)
}
fun part2(input: List<String>): Int {
val (line) = input
return findUnique(line, 14)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day06_test")
check(part1(testInput) == 11)
check(part2(testInput) == 26)
val input = readInput("Day06")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 8d2b7a974c2736903a9def65282be91fbb104ffd | 1,008 | advent-of-code | Apache License 2.0 |
murdle_solver.main.kts | dfings | 739,242,704 | false | {"Kotlin": 1574} | #!/usr/bin/env kotlin
@file:Repository("https://repo1.maven.org/maven2/")
@file:DependsOn("com.google.guava:guava:33.0.0-jre")
import com.google.common.collect.Collections2.permutations
typealias Combo = List<Int>
typealias Solution = List<Combo>
class Constraint(val values: Combo) {
val isNegative = values.any { it < 0 }
fun isCompatibleWith(solution: Solution): Boolean =
if (isNegative) solution.none(this::matches) else solution.any(this::matches)
fun matches(combo: Combo): Boolean {
for (i in combo.indices) {
if (values[i] > 0 && values[i] != combo[i]) return false
if (values[i] < 0 && -values[i] != combo[i]) return false
}
return true
}
}
fun <T> cartesianProduct(iterables: Iterable<Iterable<T>>): Sequence<List<T>> =
iterables.asSequence().fold(sequenceOf(listOf<T>())) { acc, input ->
acc.flatMap { output -> input.map { output + it } }
}
fun generateValidSolutions(size: Int): Sequence<Solution> {
val permutations = permutations((1..size).toList())
val products = cartesianProduct(List(size - 1) { permutations })
val prefixes = (1..size).map { listOf(it) }
return products.map { product -> (0..size-1).map { i -> prefixes[i] + product.map { it[i] } } }
}
val lines = java.io.File(args[0]).readLines()
val constraints = lines.map { Constraint(it.split(',').map { it.toInt() }) }
val size = constraints[0].values.size
generateValidSolutions(size).filter { solution -> constraints.all { it.isCompatibleWith(solution) } }.forEach { println(it) }
| 0 | Kotlin | 0 | 0 | c4e727bb71437ffa7d785688b84bdc5b76420685 | 1,574 | murdle | The Unlicense |
src/Day03.kt | fmborghino | 573,233,162 | false | {"Kotlin": 60805} | // as an extension property, note ext props can't be local
val Char.scoreProp: Int
get() = if (this.isLowerCase()) {
this.code - 96
} else {
this.code - 64 + 26
}
fun main() {
fun log(message: Any?) {
// println(message)
}
fun Char.score(): Int {
return if (this.isLowerCase()) {
this.code - 96
} else {
this.code - 64 + 26
}
}
fun part1(input: List<String>): Int {
return input.sumOf {
val half = it.length / 2
// kind of prefer the non infix for this (see part2)
(it.substring(0, half).toSet() intersect it.substring(half).toSet()).first().score()// infix
}
}
fun part2(input: List<String>): Int {
return input
.chunked(3)
.sumOf {
it[0].toSet().intersect(it[1].toSet()).intersect(it[2].toSet()).first().scoreProp // not infix :-)
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test.txt")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03.txt")
println(part1(input))
check(part1(input) == 8243)
println(part2(input))
check(part2(input) == 2631)
}
| 0 | Kotlin | 0 | 0 | 893cab0651ca0bb3bc8108ec31974654600d2bf1 | 1,326 | aoc2022 | Apache License 2.0 |
src/main/kotlin/net/voldrich/aoc2021/Day20.kt | MavoCz | 434,703,997 | false | {"Kotlin": 119158} | package net.voldrich.aoc2021
import net.voldrich.BaseDay
// link to task
fun main() {
Day20().run()
}
class Day20 : BaseDay() {
override fun task1() : Int {
val image = ImageEnhancement()
image.print()
val enhanced = image.enhance()
enhanced.print()
val twiceEnhanced = enhanced.enhance()
twiceEnhanced.print()
return twiceEnhanced.totalBrightPoints()
}
override fun task2() : Int {
val image = ImageEnhancement()
val enhanced = (1..50).fold(image) { img, _ -> img.enhance() }
return enhanced.totalBrightPoints()
}
inner class ImageEnhancement {
val enhancementLine: String
val image: List<String>
val expandChar: Char
constructor() {
expandChar = '0'
enhancementLine = input.lines()[0]
image = expandImage(input.lines().subList(2, input.lines().size)
.map { it
.replace('#', '1')
.replace('.', '0') })
}
constructor(enhancementLine: String, image: List<String>, prevExpandChar : Char) {
this.enhancementLine = enhancementLine
// if the transformation of 000 000 000 translates to # this means that all infinity off screen . will became #
// if the transformation of 111 111 111 translates to . this means that all infinity off screen # will became .
this.expandChar = if (enhancementLine[0] == '.') '0' else if (prevExpandChar == '0') '1' else '0'
this.image = expandImage(image)
}
fun expandImage(img: List<String>): List<String> {
val map = img.map { expandChar + it + expandChar }.toMutableList()
map.add(0, getEmptyLine(img[0].length + 2))
map.add(getEmptyLine(img[0].length + 2))
return map
}
fun enhance(): ImageEnhancement {
return ImageEnhancement(enhancementLine, image.mapIndexed { y, line ->
line.mapIndexed{ x, _ ->
enhanceItem(y, x)
}.joinToString("")
}, expandChar)
}
private fun enhanceItem(y: Int, x: Int) : Char {
val num = getData(y-1, x) + getData(y, x) + getData(y+1, x)
val index = num.toInt(2)
return if (enhancementLine[index] == '#') '1' else '0'
}
fun getEmptyLine(size: Int) : String {
return (0 until size).map { expandChar }.joinToString("")
}
private fun getData(y: Int, x: Int): String {
val row = if (y in image.indices) image[y] else getEmptyLine(image[0].length)
return when (x) {
0 -> expandChar + row.substring(0, 2)
row.length - 1 -> row.substring(x-1, row.length) + expandChar
else -> row.substring(x-1, x+2)
}
}
fun totalBrightPoints(): Int {
return image.sumOf { it.count { char -> char == '1' } }
}
fun print() {
image.forEach { println(it) }
println()
}
}
}
| 0 | Kotlin | 0 | 0 | 0cedad1d393d9040c4cc9b50b120647884ea99d9 | 3,137 | advent-of-code | Apache License 2.0 |
src/Day16Part1.kt | underwindfall | 573,471,357 | false | {"Kotlin": 42718} | fun main() {
val dayId = "16"
val input = readInput("Day${dayId}")
class VD(val id: Int, val r: Int, val us: List<String>)
var cnt = 0
val vs = HashMap<String, VD>()
for (s in input) {
val (v, r, t) = Regex("Valve ([A-Z][A-Z]) has flow rate=(\\d+); tunnel[s]? lead[s]? to valve[s]? ([A-Z, ]+)")
.matchEntire(s)!!.groupValues.drop(1)
check(vs.put(v, VD(cnt++, r.toInt(), t.split(", "))) == null)
}
val tl = 30
data class ST(val m: Long, val c: String)
val dp = Array(tl + 1) { HashMap<ST, Int>() }
fun put(t: Int, m: Long, c: String, p: Int) {
val st = ST(m, c)
val cur = dp[t][st]
if (cur == null || p > cur) dp[t][st] = p
}
put(0, 0, "AA", 0)
for (t in 0 until tl) {
println("$t ${dp[t].size}")
for ((st, p) in dp[t]) {
val (m, c) = st
val v = vs[c]!!
val mask = 1L shl v.id
if (v.r > 0 && (mask and m) == 0L) {
put(t + 1, m or mask, c, p + (tl - t - 1) * v.r)
}
for (u in v.us) {
put(t + 1, m, u, p)
}
}
}
val ans = dp[tl].map { it.value }.max()
println(ans)
}
| 0 | Kotlin | 0 | 0 | 0e7caf00319ce99c6772add017c6dd3c933b96f0 | 1,223 | aoc-2022 | Apache License 2.0 |
advent2021/src/main/kotlin/year2021/Day02.kt | bulldog98 | 572,838,866 | false | {"Kotlin": 132847} | package year2021
import AdventDay
private typealias Direction = Pair<String, Int>
private fun List<String>.toDirections() = map {
val (a, b) = it.split(' ')
a to b.toInt()
}
private fun Direction.toMovement() = when (first) {
"forward" -> 0 to second
"up" -> -second to 0
"down" -> second to 0
else -> throw IllegalArgumentException("did not expect $first")
}
object Day02 : AdventDay(2021, 2) {
override fun part1(input: List<String>): Int {
val (depth, hPos) = input.toDirections()
.map { it.toMovement() }
.fold(0 to 0) { (oldDepth, oldHPos), (depthGain, hPosGain) ->
(oldDepth + depthGain) to (oldHPos + hPosGain)
}
return hPos * depth
}
override fun part2(input: List<String>): Int {
val (depth, hPos) = input.toDirections()
.map { it.toMovement() }
.fold(Triple(0, 0, 0)) { (oldDepth, oldHPos, oldAim), (depthGain, hPosGain) ->
Triple(
oldDepth + hPosGain * oldAim,
oldHPos + hPosGain,
oldAim + depthGain
)
}
return hPos * depth
}
}
fun main() = Day02.run()
| 0 | Kotlin | 0 | 0 | 02ce17f15aa78e953a480f1de7aa4821b55b8977 | 1,223 | advent-of-code | Apache License 2.0 |
src/main/kotlin/shortestpath/개선된_다익스트라_알고리즘.kt | CokeLee777 | 614,704,937 | false | null | package shortestpath
import java.util.*
import kotlin.Comparator
import kotlin.math.*
private const val INF = 1e9.toInt()
fun main(){
val sc = Scanner(System.`in`)
//노드의 개수와 간선의 개수 입력받기
val n = sc.nextInt()
val m = sc.nextInt()
//시작노드 번호 입력받기
val start = sc.nextInt()
//최단거리 테이블 초기화
val distances = IntArray(n + 1) { INF }
//그래프 입력받기
val graph = mutableListOf<MutableList<Node>>()
for(i in 0 .. n){
graph.add(mutableListOf())
}
for(i in 0 until m){
val a = sc.nextInt()
val b = sc.nextInt()
val cost = sc.nextInt()
graph[a].add(Node(b, cost))
}
fun dijkstra(start: Int){
val pq = PriorityQueue<Node>()
//시작 노드는 최단 경로를 0으로 설정
pq.add(Node(start, 0))
distances[start] = 0
//큐가 빌 때까지 반복
while(!pq.isEmpty()){
val node = pq.poll()
val now = node.index
val distance = node.distance
//현재 노드가 이미 처리된 적이 있다면 무시
if(distances[now] < distance) continue
//현재 노드와 연결된 다른 인접한 노드들을 확인
for(i in 0 until graph[now].size){
val cost = distance + graph[now][i].distance
//비용이 더 적게 든다면
if(cost < distances[graph[now][i].index]){
distances[graph[now][i].index] = cost
pq.offer(Node(graph[now][i].index, cost))
}
}
}
}
dijkstra(start)
for(i in 1 .. n){
when(distances[i]){
INF -> println("INFINITY")
else -> println(distances[i])
}
}
}
data class Node(val index: Int, val distance: Int): Comparable<Node> {
override fun compareTo(other: Node): Int = this.distance - other.distance
} | 0 | Kotlin | 0 | 0 | 919d6231c87fe4ee7fda6c700099e212e8da833f | 2,000 | algorithm | MIT License |
src/Day05.kt | fmborghino | 573,233,162 | false | {"Kotlin": 60805} | fun main() {
fun log(message: Any?) {
// println(message)
}
// ugly-ish "matrix rotate" of the stacks, removing the junk columns and "leading" spaces
// so the test stacks come back looking like...
// NZ
// DCM
// P
// TODO switch this to return Array<ArrayDeque<Char>>, but for now, jammin' with String < shrug >
fun parseStacks(rawStacks: List<String>): Array<String> {
// cuz of the pattern of the column counters (only works for single digit!)
val stackCount = (rawStacks.last().length + 2) / 4
log("# stacks $stackCount")
val stacks = Array<String>(stackCount) { "" }
rawStacks.take(rawStacks.size - 1).forEachIndexed() { index, row ->
log("row $index: [$row]")
for (i in 1 .. rawStacks.last().length step 4) {
val stackNumber = (i - 1) / 4
val content = row.getOrElse(i) { ' ' }
log("row $index at $i: [$content] stackNumber: $stackNumber")
if (content != ' ') {
stacks[stackNumber] = stacks[stackNumber] + content
}
}
}
return stacks
}
// doing this with strings is dumb as fuck but also a hoot!
fun moveStacks(stacks: Array<String>, instructions: List<String>, is9001: Boolean = false) {
instructions.forEach { instruction ->
// move 1 from 2 to 1
val (_, countStr, fromStr, toStr) = instruction.split("move ", " from ", " to ")
val (count, from, to) = listOf(countStr.toInt(), fromStr.toInt() - 1, toStr.toInt() - 1)
// what are we moving?
val moving = if (is9001) {
// this is for part2
stacks[from].substring(0, count)
} else {
// lolz because "move one by one" (this is for part1)
stacks[from].substring(0, count).reversed()
}
log("instructions [$instruction] -> $count $from $to (moving $moving)")
// remove from the source
stacks[from] = stacks[from].substring(count)
// add to the destination
stacks[to] = moving + stacks[to]
log("*** stacks\n${stacks.joinToString("\n")}")
}
}
fun stackTops(stacks: Array<String>): String {
return stacks.map {
it.getOrElse(0) { ' ' }
}.joinToString("")
}
fun part1(input: List<String>, is9001: Boolean = false): String {
// split up the stacks and the instructions, they are separated by an empty line
val separator = input.indexOfFirst { it.isEmpty() }
val rawStacks = input.slice(0 until separator)
val instructions = input.slice(separator + 1 until input.size)
log("*** rawStacks\n$rawStacks")
log("*** instructions\n$instructions")
val stacks: Array<String> = parseStacks(rawStacks)
log("*** stacks\n${stacks.joinToString("\n")}")
moveStacks(stacks, instructions, is9001 = is9001)
log("*** moved stacks\n${stacks.joinToString("\n")}")
return stackTops(stacks)
}
fun part2(input: List<String>): String {
return part1(input, is9001 = true)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test.txt")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("Day05.txt")
println(part1(input))
// check(part1(input) == 9999)
println(part2(input))
// check(part2(input) == 99999)
}
// NOODLING BELOW FOR IMPROVEMENTS
private fun day05() {
val input = """
[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
"""
val numberStacks = numberStacks(input)
log("*** $numberStacks")
log("*** regex ${buildRegex(3).pattern}")
val stacks = parseStacks(input, numberStacks)
log("*** dumpStacks\n${stacks.joinToString("\n")}")
}
private fun parseStacks(input: String, numberStacks: Int): Array<ArrayDeque<Char>> {
val r = buildRegex(numberStacks)
val stacks: Array<ArrayDeque<Char>> = Array(numberStacks) { ArrayDeque() }
input.split("\n")
.drop(1)
.takeWhile { ! it.startsWith(" 1") }
.forEachIndexed() { index, line ->
val padded = line.padEnd((numberStacks * 4) - 1, ' ') // makes the regex easier
log("parsing padded line $index -> [$padded]")
val matches = r.find(padded)
for (i in 1.. numberStacks) {
val item = matches?.groups?.get(i)?.value
log("matched group $i as [$item]")
if(item != " ") {
stacks[i - 1].add(item?.get(0) ?: '*')
}
}
}
return stacks
}
private fun numberStacks(input: String): Int {
return input.split("\n")
// .dropWhile { it.contains("[") }
// .first()
.first() { it.startsWith(" 1")}
.split(" ")
.filter { it.isNotBlank() }
.max()
.toInt()
}
private fun buildRegex(numberStacks: Int): Regex {
return ("." + """([A-Z ])...""".repeat(numberStacks - 1) + "([A-Z ]).").toRegex()
}
| 0 | Kotlin | 0 | 0 | 893cab0651ca0bb3bc8108ec31974654600d2bf1 | 5,260 | aoc2022 | Apache License 2.0 |
src/main/kotlin/days/y22/Day05.kt | kezz | 572,635,766 | false | {"Kotlin": 20772} | package days.y22
import util.Day
import util.mapInner
import util.splitAroundBlankStrings
public fun main() {
Day5().run()
}
public class Day5 : Day(22, 5) {
override fun part1(input: List<String>): Any = input
.splitAroundBlankStrings()
.toList()
.let { (startState, instructions) -> startState to instructions.map { line -> line.split(' ').mapNotNull(String::toIntOrNull) } }
.let { (startState, instructions) ->
Triple(
startState.slice(0 until startState.lastIndex).map(String::toCharArray),
startState.last().toList().mapNotNull(Char::digitToIntOrNull).max(),
instructions
)
}
.let { (startState, maxCount, instructions) ->
Pair(
Array(maxCount) { index -> startState.mapNotNullTo(mutableListOf()) { chars -> chars.getOrNull((index * 4) + 1)?.takeIf(Char::isLetter) } }.toList(),
instructions.mapInner { oneIndexedElement -> oneIndexedElement - 1 }
)
}
.let { (state, instructions) ->
state.apply { instructions.forEach { (amount, from, to) -> repeat(amount + 1) { state[to].add(0, state[from].removeFirst()) } } }
}
.map(MutableList<Char>::first)
.joinToString(separator = "")
override fun part2(input: List<String>): Any = input
.splitAroundBlankStrings()
.toList()
.let { (startState, instructions) -> startState to instructions.map { line -> line.split(' ').mapNotNull(String::toIntOrNull) } }
.let { (startState, instructions) ->
Triple(
startState.slice(0 until startState.lastIndex).map(String::toCharArray),
startState.last().toList().mapNotNull(Char::digitToIntOrNull).max(),
instructions
)
}
.let { (startState, maxCount, instructions) ->
Pair(
Array(maxCount) { index -> startState.mapNotNullTo(mutableListOf()) { chars -> chars.getOrNull((index * 4) + 1)?.takeIf(Char::isLetter) } },
instructions.mapInner { oneIndexedElement -> oneIndexedElement - 1 }
)
}
.let { (state, instructions) ->
state.apply {
instructions.forEach { (amount, from, to) ->
state[to].addAll(0, state[from].take(amount + 1).also { state[from] = state[from].drop(amount + 1).toMutableList() })
}
}
}
.map(MutableList<Char>::first)
.joinToString(separator = "")
}
| 0 | Kotlin | 0 | 0 | 1cef7fe0f72f77a3a409915baac3c674cc058228 | 2,588 | aoc | Apache License 2.0 |
src/day13/Day13.kt | kerchen | 573,125,453 | false | {"Kotlin": 137233} | package day13
import readInput
fun findClosingBracket(input: String, start: Int): Int {
var i = start
var nestLevel = 1
while (nestLevel != 0) {
when(input[i]) {
'[' -> nestLevel += 1
']' -> nestLevel -= 1
}
i += 1
}
return i
}
abstract class SequenceItem {
abstract fun isAtomic(): Boolean
abstract fun convertToList(): SequenceList
}
class SequenceNumber(val number: Int) : SequenceItem() {
override fun isAtomic(): Boolean {
return true
}
override fun convertToList(): SequenceList {
return SequenceList("$number")
}
}
class SequenceList(input: String) : SequenceItem() {
var items = mutableListOf<SequenceItem>()
override fun isAtomic(): Boolean {
return false
}
override fun convertToList(): SequenceList {
return this
}
init {
var start = 0
while ( start < input.length ) {
when(input[start]) {
'[' -> {
var end = findClosingBracket(input, start + 1)
items.add(SequenceList(input.substring(start+1, end-1)))
start = end
}
',' -> {
start += 1
}
else -> {
var number = 0
while(start < input.length && input[start].isDigit()) {
number = number * 10 + input[start].digitToInt()
start += 1
}
items.add(SequenceNumber(number))
}
}
}
}
}
class Packet(input: String, val isDivider: Boolean = false) {
val sequence = SequenceList(input)
}
enum class Ordered {
PUNT,
YES,
NO
}
fun isWellOrdered(leftList: SequenceList, rightList: SequenceList): Ordered
{
val leftIterator = leftList.items.iterator()
val rightIterator = rightList.items.iterator()
while (leftIterator.hasNext() && rightIterator.hasNext())
{
val leftVal = leftIterator.next()
val rightVal = rightIterator.next()
if (leftVal.isAtomic() && rightVal.isAtomic()) {
val leftNumber = (leftVal as SequenceNumber).number
val rightNumber = (rightVal as SequenceNumber).number
if (leftNumber < rightNumber) return Ordered.YES
if (leftNumber > rightNumber) return Ordered.NO
} else if (!leftVal.isAtomic() && !rightVal.isAtomic()) {
val subResult = isWellOrdered(leftVal.convertToList(), rightVal.convertToList())
if (subResult != Ordered.PUNT)
return subResult
} else if (!leftVal.isAtomic()) {
val subResult = isWellOrdered(leftVal as SequenceList, rightVal.convertToList())
if (subResult != Ordered.PUNT)
return subResult
} else {
val subResult = isWellOrdered(leftVal.convertToList(), rightVal.convertToList())
if (subResult != Ordered.PUNT)
return subResult
}
}
if (!leftIterator.hasNext()) {
if (rightIterator.hasNext()) {
return Ordered.YES
}
}
if (!rightIterator.hasNext()) {
if (leftIterator.hasNext()) {
return Ordered.NO
}
}
return Ordered.PUNT
}
fun isWellOrdered(leftSide: Packet, rightSide: Packet): Boolean {
return isWellOrdered(leftSide.sequence, rightSide.sequence) == Ordered.YES
}
class PacketComparator {
companion object : Comparator<Packet> {
override fun compare(a: Packet, b: Packet): Int {
val lessThan = isWellOrdered(a, b)
if (lessThan)
return -1
return 1
}
}
}
fun main() {
fun part1(input: List<String>): Int {
val inputIterator = input.iterator()
var packetIndex = 1
val wellOrderedPackets = mutableSetOf<Int>()
while(inputIterator.hasNext()) {
val leftString = inputIterator.next()
var leftPacket = Packet(leftString.substring(1, leftString.length - 1))
val rightString = inputIterator.next()
var rightPacket = Packet(rightString.substring(1, rightString.length - 1))
if (isWellOrdered(leftPacket, rightPacket)) {
wellOrderedPackets.add(packetIndex)
}
packetIndex += 1
// Skip blank separator line if present
if (inputIterator.hasNext()) {
inputIterator.next()
}
}
return wellOrderedPackets.sum()
}
fun part2(input: List<String>): Int {
val inputIterator = input.iterator()
val packets = mutableListOf<Packet>()
packets.add(Packet("[2]", true))
packets.add(Packet("[6]", true))
while(inputIterator.hasNext()) {
val packetString = inputIterator.next()
packets.add(Packet(packetString.substring(1, packetString.length - 1)))
val packetString2 = inputIterator.next()
packets.add(Packet(packetString2.substring(1, packetString2.length - 1)))
if (inputIterator.hasNext()) {
inputIterator.next()
}
}
var decoderKey = 1
var index = 1
for (p in packets.sortedWith(PacketComparator)) {
if (p.isDivider) {
decoderKey *= index
}
index += 1
}
return decoderKey
}
val testInput = readInput("Day13_test")
check(part1(testInput) == 13)
check(part2(testInput) == 140)
val input = readInput("Day13")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | dc15640ff29ec5f9dceb4046adaf860af892c1a9 | 5,916 | AdventOfCode2022 | Apache License 2.0 |
src/nativeMain/kotlin/com.qiaoyuang.algorithm/special/Questions10.kt | qiaoyuang | 100,944,213 | false | {"Kotlin": 338134} | package com.qiaoyuang.algorithm.special
fun test10() {
printlnResult(intArrayOf(1, 1, 1), 2)
printlnResult(intArrayOf(1, 3, 5, 4, -2, 2, 7), 9)
}
/**
* Questions 10: Give an IntArray and an integer k, find the count of consistent sub-arrays in the IntArray that sum equals k
*/
private infix fun IntArray.findCount(k: Int): Int {
require(isNotEmpty()) { "The IntArray can't be empty" }
var count = 0
repeat(size) { i ->
var j = i
while (j < size)
if (subSum(i, j++) == k)
count++
}
return count
}
private fun IntArray.subSum(i: Int, j: Int): Int {
var sum = 0
for (index in i..j)
sum += this[index]
return sum
}
private fun printlnResult(array: IntArray, k: Int) =
println("The count of consistent sub-arrays that sum equals $k is (${array findCount k}) in array: ${array.toList()}")
| 0 | Kotlin | 3 | 6 | 66d94b4a8fa307020d515d4d5d54a77c0bab6c4f | 886 | Algorithm | Apache License 2.0 |
kotlin/src/main/kotlin/com/github/jntakpe/aoc2022/days/Day18.kt | jntakpe | 572,853,785 | false | {"Kotlin": 72329, "Rust": 15876} | package com.github.jntakpe.aoc2022.days
import com.github.jntakpe.aoc2022.shared.Day
import com.github.jntakpe.aoc2022.shared.readInputLines
object Day18 : Day {
override val input = readInputLines(18)
.map { l -> l.split(',').map { it.toInt() }.let { (x, y, z) -> Position(x, y, z) } }
override fun part1() = input.sumOf { c -> c.adjacent().count { it !in input } }
override fun part2(): Int {
val min = input.run { Position(minOf { it.x } - 1, minOf { it.y } - 1, minOf { it.z } - 1) }
val max = input.run { Position(maxOf { it.x } + 1, maxOf { it.y } + 1, maxOf { it.z } + 1) }
val visited = mutableSetOf<Position>()
val queue = mutableListOf(min)
while (queue.isNotEmpty()) {
val p = queue.removeLast()
if (p in input) continue
if (p.x !in min.x..max.x || p.y !in min.y..max.y || p.z !in min.z..max.z) continue
if (visited.add(p)) queue.addAll(p.adjacent())
}
return input.sumOf { p -> p.adjacent().count { it in visited } }
}
data class Position(val x: Int, val y: Int, val z: Int) {
companion object {
private val ADJACENT = listOf(
Position(1, 0, 0),
Position(-1, 0, 0),
Position(0, 1, 0),
Position(0, -1, 0),
Position(0, 0, 1),
Position(0, 0, -1)
)
}
operator fun plus(other: Position) = copy(x = x + other.x, y = y + other.y, z = z + other.z)
fun adjacent() = ADJACENT.map { this + it }
}
} | 1 | Kotlin | 0 | 0 | 63f48d4790f17104311b3873f321368934060e06 | 1,597 | aoc2022 | MIT License |
src/main/kotlin/branchandbound/examples/ContinuousKnapsackSolver.kt | sujeevraja | 196,775,908 | false | null | package branchandbound.examples
import branchandbound.api.INode
import branchandbound.api.ISolver
import kotlin.math.min
/**
* Implementation of greedy algorithm to solve continuous knapsack problems to optimality. Given
* [profits] (item utilities) and [weights] (item weights) and the knapsack [capacity], the
* algorithm will find the combination of items with maximum value to place in the knapsack without
* exceeding its capacity. It is assumed that the proportion of each selected item can vary
* continuously in [0,1].
*/
class ContinuousKnapsackSolver(
private val profits: List<Double>,
private val weights: List<Double>,
private val capacity: Double
) : ISolver {
private val eps = 1e-6
override fun solve(unsolvedNode: INode): INode {
(unsolvedNode as KnapsackNode)
val restrictions = unsolvedNode.restrictions
val node = applyRestrictions(unsolvedNode)
return if (node.remainingCapacity < 0.0) node.copy(lpSolved = true, lpFeasible = false)
else runGreedyAlgorithm(node, getIndicesSortedByUtility(restrictions.keys.toSet()))
}
private fun applyRestrictions(node: KnapsackNode): KnapsackNode =
node.restrictions.entries.fold(node.copy(remainingCapacity = capacity, lpIntegral = true))
{ n, entry ->
if (entry.value == 0) n
else n.copy(
remainingCapacity = n.remainingCapacity - weights[entry.key],
lpObjective = n.lpObjective + profits[entry.key]
)
}
private fun getIndicesSortedByUtility(fixed: Set<Int>) =
profits.indices.asSequence().filter { it !in fixed }.map { i ->
Pair(i, profits[i] / weights[i])
}.sortedByDescending { it.second }.asSequence().map { it.first }.toList()
private fun runGreedyAlgorithm(initialNode: KnapsackNode, sortedIndices: List<Int>): KnapsackNode =
sortedIndices.fold(initialNode) { node, i ->
val w = weights[i]
val proportion = min(node.remainingCapacity, w) / w
if (proportion <= eps) node
else node.copy(
remainingCapacity = node.remainingCapacity - (w * proportion),
lpObjective = node.lpObjective + (profits[i] * proportion),
lpSolution = node.lpSolution.plus(Pair(i, proportion)),
lpIntegral = node.lpIntegral && proportion >= 1 - eps
)
}.copy(lpSolved = true, lpFeasible = true)
}
| 2 | Kotlin | 1 | 1 | 6a2b0899aa216d2697082ceb62004b7676f26b75 | 2,479 | fixed-wing-drone-orienteering | MIT License |
src/Day05.kt | rosyish | 573,297,490 | false | {"Kotlin": 51693} | fun simulatePart1(stacks: List<MutableList<Char>>, n: Int, from: Int, to: Int): Unit {
for (i in 1..n) {
if (!stacks[from - 1].isEmpty()) stacks[to - 1].add(stacks[from - 1].removeLast())
}
}
fun simulatePart2(stacks: List<MutableList<Char>>, n: Int, from: Int, to: Int): Unit {
stacks[to - 1].addAll(stacks[from - 1].takeLast(n))
for (i in 1..n) {
stacks[from - 1].removeLast()
}
}
fun main() {
val allLines = readInput("Day05_input")
val (inputStacks, moves) = allLines.partition {
it.contains('[')
}
val numOfStacks = moves[0].trim().split(" ").last().toInt()
val stacks = inputStacks.foldRight(List(numOfStacks) { mutableListOf<Char>() }) { str, acc ->
str.forEachIndexed { index, ch ->
if (ch.isLetter()) {
acc[moves[0][index].toString().toInt() - 1].add(ch);
}
}
acc
}
val pat = Regex("^move (\\d+) from (\\d+) to (\\d+)$")
moves
.drop(2)
.forEach {
val (n, from, to) = pat
.matchEntire(it)!!
.groupValues
.drop(1)
.map { it.toInt() }
simulatePart2(stacks, n, from, to)
}
println(stacks.map { it.last() }.joinToString(separator = ""))
} | 0 | Kotlin | 0 | 2 | 43560f3e6a814bfd52ebadb939594290cd43549f | 1,301 | aoc-2022 | Apache License 2.0 |
src/Day11.kt | Kbzinho-66 | 572,299,619 | false | {"Kotlin": 34500} | import java.lang.Exception
private data class WorryOperation(val operator: String, val value: String) {
fun apply(starting: Long): Long {
val actualValue = if (value == "old") starting else value.toLong()
val result = when (operator) {
"*" -> starting * actualValue
"+" -> starting + actualValue
else -> throw Exception("Invalid operator")
}
return result
}
}
private data class Monkey(
val items: ArrayDeque<Long>,
val operation: WorryOperation,
val divisor: Long,
val recipientWhenTrue: Int,
val recipientWhenFalse: Int,
var inspections: Int = 0
) {
fun next(worryLevel: Long): Int =
if ( worryLevel % divisor == 0L) recipientWhenTrue else recipientWhenFalse
}
fun main() {
fun studyMonkeys(input: List<String>): ArrayList<Monkey> {
val monkeys = arrayListOf<Monkey>()
val operatorPosition = " Operation: new = old ".length
var items: ArrayDeque<Long> = ArrayDeque()
var operation: WorryOperation? = null
var divisor: Long? = null
var recipientWhenTrue: Int? = null
var recipientWhenFalse: Int? = null
for (line in input) {
val trimmedLine = line.trim()
when {
trimmedLine.startsWith("Monkey") -> continue
trimmedLine.startsWith("Starting items: ") -> {
line
.substringAfter(": ")
.split(", ")
.map { items.add(it.toLong()) }
}
trimmedLine.startsWith("Operation: ") -> {
val operator = line.substring(operatorPosition, operatorPosition + 1)
val value = line.substringAfter("$operator ")
operation = WorryOperation(operator, value)
}
trimmedLine.startsWith("Test: ") -> {
divisor = line.substringAfter("divisible by ").toLong()
}
trimmedLine.startsWith("If true: ") -> {
recipientWhenTrue = line.substringAfter("monkey ").toInt()
}
trimmedLine.startsWith("If false: ") -> {
recipientWhenFalse = line.substringAfter("monkey ").toInt()
}
else -> {
val newMonkey = Monkey(
items,
operation!!,
divisor!!,
recipientWhenTrue!!,
recipientWhenFalse!!
)
monkeys.add(newMonkey)
items = ArrayDeque()
operation = null
divisor = null
recipientWhenTrue = null
recipientWhenFalse = null
}
}
}
return monkeys
}
fun part1(monkeys: List<Monkey>): Int {
for (round in 1..20) {
monkeys.forEach { monkey ->
while (monkey.items.isNotEmpty()) {
monkey.inspections++
val item = monkey.items.removeFirst()
val op = monkey.operation
val newWorryLevel = op.apply(item) / 3
val next = monkey.next(newWorryLevel)
monkeys[next].items.addLast(newWorryLevel)
}
}
}
val (top, second) = monkeys
.map { monkey -> monkey.inspections }
.sortedDescending()
.take(2)
return top * second
}
fun part2(monkeys: List<Monkey>): ULong {
// The product of all divisors can drastically reduce the actual number while
// keeping its remainder the same for each divisor.
val modulus: Long = monkeys
.map { monkey -> monkey.divisor }
.fold(1) { total, curr -> total * curr }
for (round in 1..10000) {
monkeys.forEach { monkey ->
while (monkey.items.isNotEmpty()) {
monkey.inspections++
val item = monkey.items.removeFirst()
val op = monkey.operation
val newWorryLevel = op.apply(item) % modulus
val next = monkey.next(newWorryLevel)
monkeys[next].items.addLast(newWorryLevel)
}
}
}
val (top, second) = monkeys
.map { monkey -> monkey.inspections }
.sortedDescending()
.take(2)
.map { it.toULong() }
return top * second
}
// Testar os casos básicos
val testInput = readInput("../inputs/Day11_test")
var testMonkeys = studyMonkeys(testInput)
sanityCheck(part1(testMonkeys), 10605)
// Since Monkeys are stateful, it's safer to completely wipe them
testMonkeys = studyMonkeys(testInput)
sanityCheck(part2(testMonkeys), 2713310158UL)
val input = readInput("../inputs/Day11")
val monkeys = studyMonkeys(input)
println("Parte 1 = ${part1(monkeys)}")
println("Parte 2 = ${part2(monkeys)}")
} | 0 | Kotlin | 0 | 0 | e7ce3ba9b56c44aa4404229b94a422fc62ca2a2b | 5,195 | advent_of_code_2022_kotlin | Apache License 2.0 |
LeetCode/Kotlin/src/main/kotlin/org/redquark/tutorials/leetcode/LongestPalindromeSubstring.kt | ani03sha | 297,402,125 | false | null | package org.redquark.tutorials.leetcode
fun longestPalindrome(s: String): String {
// Update the string to put hash "#" at the beginning, end and in between each character
val updatedString = getUpdatedString(s)
// Length of the array that will store the window of palindromic substring
val length = 2 * s.length + 1
// Array to store the length of each palindrome centered at each element
val p = IntArray(length)
// Current center of the longest palindromic string
var c = 0
// Right boundary of the longest palindromic string
var r = 0
// Maximum length of the substring
var maxLength = 0
// Position index
var position = -1
for (i in 0 until length) {
// Mirror of the current index
val mirror = 2 * c - i
// Check if the mirror is outside the left boundary of current longest palindrome
if (i < r) {
p[i] = (r - i).coerceAtMost(p[mirror])
}
// Indices of the characters to be compared
var a = i + (1 + p[i])
var b = i - (1 + p[i])
// Expand the window
while (a < length && b >= 0 && updatedString[a] == updatedString[b]) {
p[i]++
a++
b--
}
// If the expanded palindrome is expanding beyond the right boundary of
// the current longest palindrome, then update c and r
if (i + p[i] > r) {
c = i
r = i + p[i]
}
if (maxLength < p[i]) {
maxLength = p[i]
position = i
}
}
val offset = p[position]
val result = StringBuilder()
for (i in position - offset + 1 until position + offset) {
if (updatedString[i] != '#') {
result.append(updatedString[i])
}
}
return result.toString()
}
fun getUpdatedString(s: String): String {
val sb = StringBuilder()
for (element in s) {
sb.append("#").append(element)
}
sb.append("#")
return sb.toString()
}
fun main() {
println(longestPalindrome("babad"))
println(longestPalindrome("cbbd"))
println(longestPalindrome("a"))
println(longestPalindrome("ac"))
println(longestPalindrome("abb"))
} | 2 | Java | 40 | 64 | 67b6ebaf56ec1878289f22a0324c28b077bcd59c | 2,216 | RedQuarkTutorials | MIT License |
src/main/kotlin/ru/timakden/aoc/year2016/Day07.kt | timakden | 76,895,831 | false | {"Kotlin": 321649} | package ru.timakden.aoc.year2016
import ru.timakden.aoc.util.measure
import ru.timakden.aoc.util.readInput
/**
* [Day 7: Internet Protocol Version 7](https://adventofcode.com/2016/day/7).
*/
object Day07 {
@JvmStatic
fun main(args: Array<String>) {
measure {
val input = readInput("year2016/Day07")
println("Part One: ${part1(input)}")
println("Part Two: ${part2(input)}")
}
}
fun part1(input: List<String>) = input.count { isSupportTls(it) }
fun part2(input: List<String>) = input.count { isSupportSsl(it) }
private fun isSupportTls(ip: String): Boolean {
val firstRequirement = "(\\w)(?!\\1)(\\w)\\2\\1".toRegex().containsMatchIn(ip)
val secondRequirement = !"\\[\\w*(\\w)(?!\\1)(\\w)\\2\\1\\w*]".toRegex().containsMatchIn(ip)
return firstRequirement && secondRequirement
}
private fun isSupportSsl(ip: String): Boolean {
val bracketRanges = getBracketRanges(ip)
var result = false
(0..ip.lastIndex - 2).forEach { outer ->
if (ip[outer] == ip[outer + 2] && ip[outer] != ip[outer + 1]) {
val aba = ip.substring(outer, outer + 3)
val expectedBab = aba[1].toString() + aba[0].toString() + aba[1].toString()
if (expectedBab in ip) {
(0..ip.lastIndex - 2).forEach { inner ->
val bab = ip.substring(inner, inner + 3)
if (bab == expectedBab) {
var abaNotInBrackets = true
var babInBrackets = false
bracketRanges.forEach { range ->
if (outer in range) abaNotInBrackets = false
if (inner in range) babInBrackets = true
}
result = result || abaNotInBrackets && babInBrackets
}
}
}
}
}
return result
}
private fun getBracketRanges(ip: String): List<IntRange> {
val openingBrackets = mutableListOf<Int>()
val closingBrackets = mutableListOf<Int>()
ip.forEachIndexed { index, c ->
if (c == '[') openingBrackets += index
if (c == ']') closingBrackets += index
}
return openingBrackets.mapIndexed { index, i -> i..closingBrackets[index] }
}
}
| 0 | Kotlin | 0 | 3 | acc4dceb69350c04f6ae42fc50315745f728cce1 | 2,473 | advent-of-code | MIT License |
src/nativeMain/kotlin/Day11.kt | rubengees | 576,436,006 | false | {"Kotlin": 67428} | class Day11 : Day {
private data class Monkey(
val items: List<Long>,
val operation: (Long) -> Long,
val divisor: Long,
val trueTarget: Int,
val falseTarget: Int
) {
fun targetFor(value: Long): Int {
return if (value.mod(divisor) == 0L) trueTarget else falseTarget
}
}
private fun parse(input: String): List<Monkey> {
val groups = input.split("\n\n")
val monkeys = groups.map { group ->
val items = group.lines()[1].substring(18).split(", ").map { it.toLong() }
val operation = parseOperation(group.lines()[2])
val divisor = group.lines()[3].substring(21).toLong()
val trueTarget = group.lines()[4].substring(29).toInt()
val falseTarget = group.lines()[5].substring(30).toInt()
Monkey(items, operation, divisor, trueTarget, falseTarget)
}
return monkeys
}
private fun parseOperation(line: String): (Long) -> Long {
val operationSubject = line.substring(25)
val operator = when (line[23]) {
'*' -> { a: Long, b: Long -> a * b }
'+' -> { a: Long, b: Long -> a + b }
else -> error("Unknown operator ${line[23]}")
}
return { operator(it, if (operationSubject == "old") it else operationSubject.toLong()) }
}
private fun simulate(monkeys: List<Monkey>, rounds: Int, relief: (Long) -> Long): List<Long> {
val mutableMonkeys = monkeys.toMutableList()
val inspections = mutableMapOf<Int, Long>()
repeat(rounds) {
mutableMonkeys.forEachIndexed { index, monkey ->
inspections[index] = inspections.getOrElse(index) { 0 } + monkey.items.size
for (item in monkey.items) {
val inspectedItem = relief(monkey.operation(item))
val nextMonkeyIndex = monkey.targetFor(inspectedItem)
val nextMonkey = mutableMonkeys[nextMonkeyIndex]
mutableMonkeys[nextMonkeyIndex] = nextMonkey.copy(items = nextMonkey.items + inspectedItem)
mutableMonkeys[index] = monkey.copy(items = emptyList())
}
}
}
return inspections.values.toList()
}
override suspend fun part1(input: String): String {
val result = simulate(parse(input), rounds = 20) { it / 3 }
return result.sortedDescending().take(2).reduce { acc, curr -> acc * curr }.toString()
}
override suspend fun part2(input: String): String {
val monkeys = parse(input)
val safeReliefModulo = monkeys.fold(1L) { acc, curr -> acc * curr.divisor }
val result = simulate(parse(input), rounds = 10_000) { it.mod(safeReliefModulo) }
return result.sortedDescending().take(2).reduce { acc, curr -> acc * curr }.toString()
}
}
| 0 | Kotlin | 0 | 0 | 21f03a1c70d4273739d001dd5434f68e2cc2e6e6 | 2,902 | advent-of-code-2022 | MIT License |
src/year2020/day3/Solution.kt | Niallfitzy1 | 319,123,397 | false | null | package year2020.day3
import java.io.File
import java.nio.charset.Charset
fun main() {
val mapData: List<String> =
File("src/year2020/day3/input").readLines(Charset.defaultCharset())
val map = Map(mapData)
val productOfSlopes = listOf<Long>(
findNumberOfTreesForDirection(map, Vector(1, 1)),
findNumberOfTreesForDirection(map, Vector(3, 1)),
findNumberOfTreesForDirection(map, Vector(5, 1)),
findNumberOfTreesForDirection(map, Vector(7, 1)),
findNumberOfTreesForDirection(map, Vector(1, 2))
).reduce(Long::times)
println(productOfSlopes)
}
fun findNumberOfTreesForDirection(map: Map, direction: Vector): Long {
var currentLocation = Coordinate( direction.x,direction.y)
var numberOfTrees = 0L
do {
val isTree = isTree(map, currentLocation)
print("\rAt $currentLocation. It ${if (isTree) "is" else "is not"} a tree")
if (isTree) numberOfTrees++
currentLocation = traverse(direction, currentLocation)
}while (inbounds(map, currentLocation))
println("\rReached $currentLocation & escaped the trees. Encountered: $numberOfTrees trees on slope $direction")
return numberOfTrees
}
fun traverse(direction: Vector, location: Coordinate): Coordinate {
return Coordinate(location.x + direction.x, location.y + direction.y)
}
fun isTree(map: Map, newLocation: Coordinate): Boolean {
val row = map.map[newLocation.y]
val locationWithinRepeatedMap = newLocation.x % map.boundaryOnXAxis()
return row[locationWithinRepeatedMap] == '#'
}
fun inbounds(map: Map, newLocation: Coordinate): Boolean {
return map.boundaryOnYAxis() > newLocation.y
}
data class Map(val map: List<String>) {
fun boundaryOnXAxis(): Int {
return map.first().length
}
fun boundaryOnYAxis(): Int {
return map.size
}
}
data class Vector(val x: Int, val y: Int)
data class Coordinate(val x: Int, val y: Int) | 0 | Kotlin | 0 | 0 | 67a69b89f22b7198995d5abc19c4840ab2099e96 | 1,949 | AdventOfCode | The Unlicense |
src/main/kotlin/aoc/year2022/Day05.kt | SackCastellon | 573,157,155 | false | {"Kotlin": 62581} | package aoc.year2022
import aoc.Puzzle
import java.util.*
import kotlin.collections.ArrayDeque
private typealias Rearrange = (stacks: Map<Int, ArrayDeque<Char>>, amount: Int, from: Int, to: Int) -> Unit
/**
* [Day 5 - Advent of Code 2022](https://adventofcode.com/2022/day/5)
*/
object Day05 : Puzzle<String, String> {
private val procedureRegex = Regex("move (\\d+) from (\\d+) to (\\d+)")
override fun solvePartOne(input: String): String = solve(input, ::rearrangeOneByOne)
override fun solvePartTwo(input: String): String = solve(input, ::rearrangeAllAtOnce)
private fun solve(input: String, rearrange: Rearrange): String {
val lines = input.lines()
val index = lines.indexOfFirst { it.isEmpty() }
val stackNames = lines[index - 1].windowed(3, 4).map { it.trim().toInt() }
val stacks: Map<Int, ArrayDeque<Char>> = stackNames.associateWith { ArrayDeque() }
lines.slice(0 until index - 1).forEach { line ->
line.windowed(3, 4)
.map { it.removeSurrounding("[", "]").singleOrNull() }
.mapIndexed { index, crate -> if (crate != null) stacks.getValue(stackNames[index]).add(crate) }
}
lines.slice((index + 1)..lines.lastIndex)
.mapNotNull(procedureRegex::matchEntire)
.map { it.destructured.toList().map(String::toInt) }
.forEach { (amount, from, to) -> rearrange(stacks, amount, from, to) }
return stacks.values.map(ArrayDeque<Char>::first).joinToString("")
}
private fun rearrangeOneByOne(map: Map<Int, ArrayDeque<Char>>, amount: Int, from: Int, to: Int) {
val toStack = map.getValue(to)
val fromStack = map.getValue(from)
repeat(amount) { toStack.addFirst(fromStack.removeFirst()) }
}
private fun rearrangeAllAtOnce(map: Map<Int, ArrayDeque<Char>>, amount: Int, from: Int, to: Int) {
val tmpStack = ArrayDeque<Char>(amount)
val toStack = map.getValue(to)
val fromStack = map.getValue(from)
repeat(amount) { tmpStack.addFirst(fromStack.removeFirst()) }
tmpStack.forEach(toStack::addFirst)
}
}
| 0 | Kotlin | 0 | 0 | 75b0430f14d62bb99c7251a642db61f3c6874a9e | 2,149 | advent-of-code | Apache License 2.0 |
year2023/src/cz/veleto/aoc/year2023/Day16.kt | haluzpav | 573,073,312 | false | {"Kotlin": 164348} | package cz.veleto.aoc.year2023
import cz.veleto.aoc.core.AocDay
import cz.veleto.aoc.core.Pos
import cz.veleto.aoc.core.get
import cz.veleto.aoc.core.plus
class Day16(config: Config) : AocDay(config) {
override fun part1(): String = countEnergizedTiles(startBeam = Pos(0, 0) to Direction.Right).toString()
override fun part2(): String {
val lineIndices = cachedInput.indices
val columnIndices = cachedInput[0].indices
val startBeams = columnIndices.map { Pos(0, it) to Direction.Down } +
lineIndices.map { Pos(it, columnIndices.last) to Direction.Left } +
columnIndices.map { Pos(lineIndices.first, it) to Direction.Up } +
lineIndices.map { Pos(it, 0) to Direction.Right }
return startBeams
.maxOf { startBeam ->
if (config.log) println("Energizing tiles from $startBeam")
countEnergizedTiles(startBeam = startBeam)
}
.toString()
}
private fun countEnergizedTiles(startBeam: Pair<Pos, Direction>): Int = generateSequence { }
.runningFold(State(beams = setOf(startBeam))) { state, _ ->
val newBeams = state.beams.flatMap { step(it, cachedInput) }
State(
beams = newBeams.toSet(),
energized = state.energized + newBeams,
)
}
.zipWithNext()
.first { (old, new) -> old.energized == new.energized }
.first
.energized
.map { it.first }
.toSet()
.size
private fun step(beam: Pair<Pos, Direction>, map: List<String>): List<Pair<Pos, Direction>> {
val (beamPos, beamDirection) = beam
val tile = map[beamPos]
val right = beamPos + Pos(0, 1) to Direction.Right
val down = beamPos + Pos(1, 0) to Direction.Down
val left = beamPos + Pos(0, -1) to Direction.Left
val up = beamPos + Pos(-1, 0) to Direction.Up
val newBeams = when {
tile == '\\' -> listOf(
when (beamDirection) {
Direction.Right -> down
Direction.Down -> right
Direction.Left -> up
Direction.Up -> left
}
)
tile == '/' -> listOf(
when (beamDirection) {
Direction.Right -> up
Direction.Down -> left
Direction.Left -> down
Direction.Up -> right
}
)
tile == '|' && (beamDirection == Direction.Right || beamDirection == Direction.Left) -> listOf(
up,
down,
)
tile == '-' && (beamDirection == Direction.Down || beamDirection == Direction.Up) -> listOf(
right,
left,
)
else -> listOf(
when (beamDirection) {
Direction.Right -> right
Direction.Down -> down
Direction.Left -> left
Direction.Up -> up
}
)
}
return newBeams.filter { (pos, _) ->
val (lineIndex, columnIndex) = pos
lineIndex in map.indices && columnIndex in map[0].indices
}
}
enum class Direction {
Right, Down, Left, Up
}
data class State(
val beams: Set<Pair<Pos, Direction>>,
val energized: Set<Pair<Pos, Direction>> = beams,
)
}
| 0 | Kotlin | 0 | 1 | 32003edb726f7736f881edc263a85a404be6a5f0 | 3,516 | advent-of-pavel | Apache License 2.0 |
src/Lesson8Leader/Dominator.kt | slobodanantonijevic | 557,942,075 | false | {"Kotlin": 50634} |
import java.util.HashMap
/**
* 100/100
* @param A
* @return
*/
fun solution(A: IntArray): Int {
if (A.size == 0) return -1
val count: HashMap<Int, Int> = HashMap<Int, Int>()
for (i in A.indices) {
if (count.containsKey(A[i])) {
count[A[i]] = (count[A[i]] ?: 0) + 1
} else {
count.put(A[i], 1)
}
if ((count[A[i]] ?: 0) > A.size / 2) {
return i
}
}
return -1
}
/**
* An array A consisting of N integers is given. The dominator of array A is the value that occurs in more than half of the elements of A.
*
* For example, consider array A such that
*
* A[0] = 3 A[1] = 4 A[2] = 3
* A[3] = 2 A[4] = 3 A[5] = -1
* A[6] = 3 A[7] = 3
* The dominator of A is 3 because it occurs in 5 out of 8 elements of A (namely in those with indices 0, 2, 4, 6 and 7) and 5 is more than a half of 8.
*
* Write a function
*
* class Solution { public int solution(int[] A); }
*
* that, given an array A consisting of N integers, returns index of any element of array A in which the dominator of A occurs. The function should return −1 if array A does not have a dominator.
*
* For example, given array A such that
*
* A[0] = 3 A[1] = 4 A[2] = 3
* A[3] = 2 A[4] = 3 A[5] = -1
* A[6] = 3 A[7] = 3
* the function may return 0, 2, 4, 6 or 7, as explained above.
*
* Write an efficient algorithm for the following assumptions:
*
* N is an integer within the range [0..100,000];
* each element of array A is an integer within the range [−2,147,483,648..2,147,483,647].
*/ | 0 | Kotlin | 0 | 0 | 155cf983b1f06550e99c8e13c5e6015a7e7ffb0f | 1,614 | Codility-Kotlin | Apache License 2.0 |
src/questions/SingleElementInSortedArray.kt | realpacific | 234,499,820 | false | null | package questions
import _utils.UseCommentAsDocumentation
import utils.shouldBe
/**
* You are given a sorted array consisting of only integers where every element appears exactly twice,
* except for one element which appears exactly once.
* Return the single element that appears only once.
* Your solution must run in `O(log n)` time and `O(1)` space.
*
* [Source](https://leetcode.com/problems/single-element-in-a-sorted-array/)
*/
@UseCommentAsDocumentation
private fun singleNonDuplicate(nums: IntArray): Int {
/**
* Theorem:
*
* If no single element exists till index i such that nums[i] == nums[i + 1], then i must be even.
* i.e. starting index must always be even.
*
* 0 1 2 3 4 5 6 7 8
* _________________________________
* 1 1 2 2 3 3 4 4 (5)
* (1) 2 2 3 3 4 4 5 5
*
* Using this fact, do binary search
*/
fun findSingleNonDuplicate(low: Int, high: Int): Int {
if (high == low && high > nums.lastIndex) {
return nums.last()
}
if (low < 0) {
return nums.first()
}
val midIndex = (low + high) / 2
val rightElemIndex = midIndex + 1
val leftElemIndex = midIndex - 1
if (nums[midIndex] == nums.getOrNull(rightElemIndex)) { // is mid == right element?
val startingIndex = midIndex // if yes, mid is the starting element
if (startingIndex % 2 == 0) { // if mid is even, then single element is at its right
return findSingleNonDuplicate(startingIndex + 2, high)
} else {
return findSingleNonDuplicate(low, startingIndex - 1) // else at its left
}
} else if (nums.getOrNull(leftElemIndex) == nums[midIndex]) { // if left is the starting index
val startingIndex = leftElemIndex
if (startingIndex % 2 == 0) { // is starting index even?
return findSingleNonDuplicate(startingIndex + 2, high) // if yes, then no single element at left
} else {
return findSingleNonDuplicate(low, startingIndex - 1) // single element must exists at left
}
} else {
return nums[midIndex] // found the single element
}
}
return findSingleNonDuplicate(0, nums.size)
}
fun main() {
singleNonDuplicate(nums = intArrayOf(1, 1, 2, 2, 3, 3, 4, 4, 5)) shouldBe 5
singleNonDuplicate(nums = intArrayOf(3, 3, 7, 7, 10, 11, 11)) shouldBe 10
singleNonDuplicate(nums = intArrayOf(1, 1, 2, 3, 3, 4, 4, 8, 8)) shouldBe 2
singleNonDuplicate(nums = intArrayOf(3, 3, 7, 10, 10, 11, 11)) shouldBe 7
singleNonDuplicate(nums = intArrayOf(3, 3, 7, 7, 10, 10, 11, 11, 12)) shouldBe 12
singleNonDuplicate(nums = intArrayOf(1, 3, 3, 7, 7, 10, 10, 11, 11)) shouldBe 1
} | 4 | Kotlin | 5 | 93 | 22eef528ef1bea9b9831178b64ff2f5b1f61a51f | 2,864 | algorithms | MIT License |
src/main/kotlin/nl/tiemenschut/aoc/y2023/day11.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.util.grid.CharGridParser
import nl.tiemenschut.aoc.lib.util.grid.Grid
import nl.tiemenschut.aoc.lib.util.points.by
import kotlin.math.max
import kotlin.math.min
fun main() {
aoc(CharGridParser) {
puzzle { 2023 day 11 }
fun Grid<Char>.findEmptyRowsAndColumns() {
for (x in 0 until width()) {
val col = (0 until height()).map { x by it }
if (col.all { get(it) in listOf('.', '2') }) col.forEach { set(it, '2') }
}
for (y in 0 until height()) {
val row = (0 until width()).map { it by y }
if (row.all { get(it) in listOf('.', '2') }) row.forEach { set(it, '2') }
}
}
fun calculateAllDistances(input: Grid<Char>, scale: Int): Long {
val galaxies = input.allIndexOff('#')
var totalDistance = 0L
galaxies.mapIndexed { fromIndex, from ->
for (toIndex in fromIndex + 1..<galaxies.size) {
val to = galaxies[toIndex]
var distance = 0L
for (x in min(from.x, to.x)..<max(from.x, to.x)) {
distance += if (input[x by from.y] == '2') scale else 1
}
for (y in min(from.y, to.y)..<max(from.y, to.y)) {
distance += if (input[to.x by y] == '2') scale else 1
}
totalDistance += distance
}
}
return totalDistance
}
part1 { input ->
input.findEmptyRowsAndColumns()
calculateAllDistances(input, 2)
}
part2 { input ->
input.findEmptyRowsAndColumns()
calculateAllDistances(input, 1_000_000)
}
}
}
| 0 | Kotlin | 0 | 1 | a1ade43c29c7bbdbbf21ba7ddf163e9c4c9191b3 | 1,943 | aoc-2023 | The Unlicense |
src/main/kotlin/Day09.kt | SimonMarquis | 570,868,366 | false | {"Kotlin": 50263} | import kotlin.math.absoluteValue
import kotlin.math.sign
class Day09(input: List<String>) {
private val operations = input.asSequence()
.map { it.split(" ") }
.flatMap { (direction, number) -> List(number.toInt()) { direction } }
fun part1(): Int {
var head = origin
var tail = head
val visited = mutableSetOf(tail)
operations.forEach { direction ->
head = head.step(direction)
tail = tail.follow(head)
visited += tail
}
return visited.size
}
fun part2(): Int {
val knots = MutableList(10) { origin }
val visited = mutableSetOf(knots.last())
operations.forEach { direction ->
knots.forEachIndexed { index, knot ->
knots[index] = when (index) {
0 -> knot.step(direction)
else -> knot.follow(knots[index - 1])
}
}
visited += knots.last()
}
return visited.size
}
private fun Point.step(direction: String) = when (direction) {
"U" -> x to y + 1
"R" -> x + 1 to y
"D" -> x to y - 1
"L" -> x - 1 to y
else -> error(direction)
}
private fun Point.follow(other: Point): Point {
val dx = other.x - x
val dy = other.y - y
if (dx.absoluteValue <= 1 && dy.absoluteValue <= 1) return this
return x + dx.sign to y + dy.sign
}
}
private typealias Point = Pair<Int, Int>
private val Point.x: Int get() = first
private val Point.y: Int get() = second
private val origin = 0 to 0
| 0 | Kotlin | 0 | 0 | a2129cc558c610dfe338594d9f05df6501dff5e6 | 1,627 | advent-of-code-2022 | Apache License 2.0 |
src/Day05.kt | catcutecat | 572,816,768 | false | {"Kotlin": 53001} | import java.util.*
import kotlin.system.measureTimeMillis
fun main() {
measureTimeMillis {
Day05.run {
solve1("CMZ") // "CWMTGHBDW"
solve2("MCD") // "SSCGWJCRB"
}
}.let { println("Total: $it ms") }
}
object Day05 : Day.RowInput<Day05.SupplyStacks, String>("05") {
data class SupplyStacks(val rawStacks: String, val steps: List<Step>) {
fun moveOneAtATime(): String = Stacks(rawStacks).apply { steps.forEach(::moveOneAtATime) }.status
fun moveMultipleAtOnce(): String = Stacks(rawStacks).apply { steps.forEach(::moveMultipleAtOnce) }.status
}
class Stacks(s: String) {
private val stacks: Array<Stack<Char>>
private val tmpStack = Stack<Char>()
init {
val lines = s.split(System.lineSeparator())
val size = lines.last().split(" ").filter { it.isNotEmpty() }.size
stacks = Array(size) { Stack() }
for (i in lines.lastIndex - 1 downTo 0) {
val line = lines[i]
for (j in 1..line.lastIndex step 4) { // 1, 5, 9
if (line[j].isLetter()) stacks[j / 4].push(line[j])
}
}
}
val status: String get() = stacks.joinToString("") { it.last().toString() }
fun moveOneAtATime(step: Step) {
val (move, from, to) = step
repeat(move) { stacks[to].push(stacks[from].pop()) }
}
fun moveMultipleAtOnce(step: Step) {
val (move, from, to) = step
repeat(move) { tmpStack.push(stacks[from].pop()) }
repeat(move) { stacks[to].push(tmpStack.pop()) }
}
}
data class Step(val move: Int, val from: Int, val to: Int) {
companion object {
fun fromString(s: String) = s.split(" ").let {
Step(it[1].toInt(), it[3].toInt() - 1, it[5].toInt() - 1)
}
}
}
override fun parse(input: String): SupplyStacks = input
.split(System.lineSeparator() + System.lineSeparator())
.let { (a, b) ->
SupplyStacks(a, b.split(System.lineSeparator()).map(Step::fromString))
}
override fun part1(data: SupplyStacks) = data.moveOneAtATime()
override fun part2(data: SupplyStacks) = data.moveMultipleAtOnce()
} | 0 | Kotlin | 0 | 2 | fd771ff0fddeb9dcd1f04611559c7f87ac048721 | 2,315 | AdventOfCode2022 | Apache License 2.0 |
src/main/kotlin/com/nibado/projects/advent/y2020/Day18.kt | nielsutrecht | 47,550,570 | false | null | package com.nibado.projects.advent.y2020
import com.nibado.projects.advent.*
import com.nibado.projects.advent.collect.Stack
object Day18 : Day {
private val values = resourceLines(2020, 18).map {
it.replace(" ", "").split("").filterNot(String::isBlank)
}
override fun part1() = values.map { eval(shunt(it) { 1 } )}.sum()
override fun part2() = values.map { eval(shunt(it) { t -> if (t == "+") 2 else 1 } )}.sum()
private fun shunt(tokens: List<String>, precedence: (String) -> Int) : List<String> =
tokens.fold(mutableListOf<String>() to Stack<String>()) { (output, operators), token ->
if(token.isInt()) {
output += token
} else if(token == "+" || token == "*") {
while(operators.peekOrNull() in setOf("*", "+")
&& precedence(token) <= precedence(operators.peek())
&& operators.peek() != "(") {
output += operators.pop()
}
operators += token
} else if(token == "(") {
operators += token
} else if(token == ")") {
while(operators.peekOrNull() != "(") {
output += operators.pop()
}
if(operators.peek() == "(") {
operators.pop()
}
}
output to operators
}.let { (output,operators) -> output + operators }
private fun eval(expr: List<String>) : Long = expr.fold(Stack<Long>()) { s, e ->
s += when(e) {
"+" -> s.pop() + s.pop()
"*" -> s.pop() * s.pop()
else -> e.toLong()
}
s
}.pop()
}
| 1 | Kotlin | 0 | 15 | b4221cdd75e07b2860abf6cdc27c165b979aa1c7 | 1,772 | adventofcode | MIT License |
src/Day20.kt | AlaricLightin | 572,897,551 | false | {"Kotlin": 87366} | fun main() {
fun mixList(list: MutableList<ListElement>) {
val listSizeMinus1 = list.size - 1
for (i in 0..list.lastIndex) {
val currentIndex: Int = list.indexOfFirst { it.initialOrder == i }
if (currentIndex < 0)
throw IllegalArgumentException()
val element = list[currentIndex]
list.removeAt(currentIndex)
val newIndex: Int = (currentIndex.toLong() + element.v).mod(listSizeMinus1)
if (newIndex > 0)
list.add(newIndex, element)
else
list.add(element)
}
}
fun calculateResult(list: MutableList<ListElement>): Long {
val zeroIndex = list.indexOfFirst { it.v == 0L }
if (zeroIndex < 0)
throw IllegalArgumentException()
return (1..3).sumOf {
val index = (zeroIndex + it * 1000).mod(list.size)
list[index].v
}
}
fun part1(input: List<String>): Long {
val list: MutableList<ListElement> = input
.mapIndexed { index, s ->
ListElement(s.toLong(), index)
}
.toMutableList()
mixList(list)
return calculateResult(list)
}
fun part2(input: List<String>): Long {
val list: MutableList<ListElement> = input
.mapIndexed { index, s ->
ListElement(s.toLong() * 811589153, index)
}
.toMutableList()
repeat(10) { mixList(list) }
return calculateResult(list)
}
val testInput = readInput("Day20_test")
check(part1(testInput) == 3L)
check(part2(testInput) == 1623178306L)
val input = readInput("Day20")
println(part1(input))
println(part2(input))
}
private data class ListElement(
val v: Long,
val initialOrder: Int
) | 0 | Kotlin | 0 | 0 | ee991f6932b038ce5e96739855df7807c6e06258 | 1,847 | AdventOfCode2022 | Apache License 2.0 |
module-tool/src/main/kotlin/de/twomartens/adventofcode/day17/graph/GraphWalker.kt | 2martens | 729,312,999 | false | {"Kotlin": 89431} | package de.twomartens.adventofcode.day17.graph
import mu.KotlinLogging
import java.util.*
data class VisitedNode(val row: Int, val column: Int, var direction: Direction?, var directionCount: Int = 0)
data class PathNode(val visitedNode: VisitedNode, val distanceToStart: Int) : Comparable<PathNode> {
override fun compareTo(other: PathNode): Int {
return distanceToStart - other.distanceToStart
}
}
class GraphWalker {
fun findMinimalHeatLoss(graph: Graph, minPerDirection: Int, maxPerDirection: Int): Int {
log.debug { "Find minimal heat loss" }
val lastColumnIndex = graph.rows[0].lastIndex
val lastRowIndex = graph.rows.lastIndex
val visitedNodes: MutableMap<VisitedNode, Boolean> = HashMap()
val firstVisitedNode = VisitedNode(0, 0, null, 0)
val queue: Queue<PathNode> = PriorityQueue()
queue.add(PathNode(firstVisitedNode, 0))
var lastNode: PathNode? = null
while (queue.isNotEmpty()) {
lastNode = queue.poll()
if (lastNode.visitedNode.row == lastRowIndex
&& lastNode.visitedNode.column == lastColumnIndex
&& lastNode.visitedNode.directionCount >= minPerDirection
&& lastNode.visitedNode.directionCount <= maxPerDirection) {
break
}
log.debug { "Currently at tile $lastNode with heat loss ${lastNode.distanceToStart}" }
val neighbours = findNeighbours(lastNode, minPerDirection)
val validNeighbours = neighbours
.filter {
isWithinRowBounds(it, graph) && isWithinColumnBounds(it, graph)
}
.filter { !visitedNodes.containsKey(it) }
.filter { it.directionCount <= maxPerDirection }
for (neighbour in validNeighbours) {
val neighbourTile = graph.rows[neighbour.row][neighbour.column]
val newDistance = lastNode.distanceToStart + neighbourTile.heatLossOnEnter
val pathNode = PathNode(neighbour, newDistance)
queue.add(pathNode)
visitedNodes[neighbour] = true
}
}
return lastNode?.distanceToStart ?: 0
}
fun findNeighbours(currentNode: PathNode, minPerDirection: Int): List<VisitedNode> {
val direction = currentNode.visitedNode.direction
val visitedNode = currentNode.visitedNode
val sameDirectionCount = currentNode.visitedNode.directionCount
val belowMinDirectionCount = sameDirectionCount < minPerDirection
val leftNeighbour = findNeighbour(visitedNode, Direction.LEFT)
val rightNeighbour = findNeighbour(visitedNode, Direction.RIGHT)
val downNeighbour = findNeighbour(visitedNode, Direction.DOWN)
val upNeighbour = findNeighbour(visitedNode, Direction.UP)
return when (direction) {
Direction.LEFT -> if (belowMinDirectionCount) listOf(leftNeighbour) else listOf(
downNeighbour, leftNeighbour, rightNeighbour)
Direction.UP -> if (belowMinDirectionCount) listOf(upNeighbour) else listOf(
leftNeighbour, upNeighbour, rightNeighbour)
Direction.RIGHT -> if (belowMinDirectionCount) listOf(rightNeighbour) else listOf(
upNeighbour, rightNeighbour, downNeighbour)
Direction.DOWN -> if (belowMinDirectionCount) listOf(downNeighbour) else listOf(
rightNeighbour, downNeighbour, leftNeighbour)
null -> listOf(rightNeighbour,
downNeighbour,
leftNeighbour,
upNeighbour)
}
}
fun findNeighbour(currentNode: VisitedNode, direction: Direction): VisitedNode {
val sameDirectionCount = if (currentNode.direction == direction) currentNode.directionCount + 1 else 1
return when (direction) {
Direction.LEFT -> VisitedNode(currentNode.row, currentNode.column - 1, direction, sameDirectionCount)
Direction.UP -> VisitedNode(currentNode.row - 1, currentNode.column, direction, sameDirectionCount)
Direction.RIGHT -> VisitedNode(currentNode.row, currentNode.column + 1, direction, sameDirectionCount)
Direction.DOWN -> VisitedNode(currentNode.row + 1, currentNode.column, direction, sameDirectionCount)
}
}
private fun isWithinRowBounds(
it: VisitedNode,
graph: Graph
) = it.row >= 0 && it.row <= graph.rows.lastIndex
private fun isWithinColumnBounds(
it: VisitedNode,
graph: Graph
) = it.column >= 0 && it.column <= graph.rows[0].lastIndex
companion object {
private val log = KotlinLogging.logger {}
}
} | 0 | Kotlin | 0 | 0 | 03a9f7a6c4e0bdf73f0c663ff54e01daf12a9762 | 4,822 | advent-of-code | Apache License 2.0 |
src/Day03.kt | thelmstedt | 572,818,960 | false | {"Kotlin": 30245} | import java.io.File
fun main() {
fun part1(file: File): Int {
val priorities = "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
val priorityMap = priorities.mapIndexed { index, c -> c to index + 1 }.toMap()
return file
.readText()
.lineSequence()
.filter { it.isNotBlank() }
.map { it.chunked(it.length / 2) }
.map { (l, r) -> l.toCharArray().toSet().intersect(r.toCharArray().toSet()) }
.map { it.map { priorityMap[it]!! } }
.flatMap { it }
.sum()
}
fun part2(file: File): Int {
val priorities = "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
val priorityMap = priorities.mapIndexed { index, c -> c to index + 1 }.toMap()
return file
.readText()
.lineSequence()
.filter { it.isNotBlank() }
.chunked(3)
.map { (l, m, r) ->
val ls = l.toCharArray().toSet()
val rs = r.toCharArray().toSet()
val ms = m.toCharArray().toSet()
ls.intersect(rs).intersect(ms)
}
.map { it.map { priorityMap[it]!! } }
.flatMap { it }
.sum()
}
println(part1(File("src", "Day03_test.txt")))
println(part1(File("src", "Day03.txt")))
println(part2(File("src", "Day03_test.txt")))
println(part2(File("src", "Day03.txt")))
}
| 0 | Kotlin | 0 | 0 | e98cd2054c1fe5891494d8a042cf5504014078d3 | 1,478 | advent2022 | Apache License 2.0 |
kotlin/src/main/kotlin/com/github/fstaudt/aoc2021/day2/Day2.kt | fstaudt | 433,733,254 | true | {"Kotlin": 9482, "Rust": 1574} | package com.github.fstaudt.aoc2021.day2
import com.github.fstaudt.aoc2021.day2.Day2.Step.Companion.toCommand
import com.github.fstaudt.aoc2021.shared.Day
import com.github.fstaudt.aoc2021.shared.readInputLines
fun main() {
Day2().run()
}
class Day2 : Day {
override val input: List<String> = readInputLines(2)
override fun part1() = input.map { it.toCommand() }.fold(Position()) { p, c -> p.applyPart1(c) }.run { horizontal * depth }
override fun part2() = input.map { it.toCommand() }.fold(Position()) { p, c -> p.applyPart2(c) }.run { horizontal * depth }
data class Position(var horizontal: Int = 0, var depth: Int = 0, var aim: Int = 0) {
fun applyPart1(step: Step): Position {
return when (step.action) {
"forward" -> Position(horizontal + step.units, depth)
"down" -> Position(horizontal, depth + step.units)
"up" -> Position(horizontal, depth - step.units)
else -> error(step.action)
}
}
fun applyPart2(step: Step): Position {
return when (step.action) {
"forward" -> Position(horizontal + step.units, depth + (aim * step.units), aim)
"down" -> Position(horizontal, depth, aim + step.units)
"up" -> Position(horizontal, depth, aim - step.units)
else -> error(step.action)
}
}
}
data class Step(val action: String, val units: Int) {
companion object {
fun String.toCommand() = Step(split(" ")[0], split(" ")[1].toInt())
}
}
}
| 0 | Kotlin | 0 | 0 | f2ee9bca82711bc9aae115400ecff6db5d683c9e | 1,608 | aoc2021 | MIT License |
src/Day10.kt | mjossdev | 574,439,750 | false | {"Kotlin": 81859} | private sealed interface Instruction {
val cycles: Int
}
private class Addx(val value: Int) : Instruction {
override val cycles
get() = 2
}
private object Noop : Instruction {
override val cycles: Int
get() = 1
}
private const val ROW_WIDTH = 40
fun main() {
class Cpu {
private val valuesOfX = mutableListOf(1)
val cycles
get() = valuesOfX.size - 1
fun getXDuring(cycle: Int): Int = valuesOfX[cycle - 1]
fun execute(instruction: Instruction) {
valuesOfX.apply {
val x = last()
repeat(instruction.cycles - 1) {
add(x)
}
add(when (instruction) {
Noop -> x
is Addx -> x + instruction.value
})
}
}
fun draw(): List<String> = valuesOfX.windowed(ROW_WIDTH, ROW_WIDTH).map {
it.mapIndexed { cycle, spritePos ->
if (cycle in spritePos - 1..spritePos + 1) '#' else '.'
}.joinToString("")
}
}
fun readInstructions(input: List<String>) = input.map { when (it) {
"noop" -> Noop
else -> it.split(' ').let { (inst, value) ->
check(inst == "addx")
Addx(value.toInt())
}
} }
fun part1(input: List<String>): Int {
val cpu = Cpu()
readInstructions(input).forEach {
cpu.execute(it)
}
return (20..cpu.cycles step 40).sumOf { it * cpu.getXDuring(it) }
}
fun part2(input: List<String>): String {
val cpu = Cpu()
readInstructions(input).forEach {
cpu.execute(it)
}
return cpu.draw().joinToString("\n")
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day10_test")
check(part1(testInput) == 13140)
check(part2(testInput) == """
##..##..##..##..##..##..##..##..##..##..
###...###...###...###...###...###...###.
####....####....####....####....####....
#####.....#####.....#####.....#####.....
######......######......######......####
#######.......#######.......#######.....
""".trimIndent())
val input = readInput("Day10")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | afbcec6a05b8df34ebd8543ac04394baa10216f0 | 2,355 | advent-of-code-22 | Apache License 2.0 |
src/day11/Day11.kt | pocmo | 433,766,909 | false | {"Kotlin": 134886} | package day11
import java.io.File
data class Position(
val x: Int,
val y: Int
)
data class Octopus(
var energy: Int,
var flashed: Boolean = false
) {
fun canFlash(): Boolean = energy > 9 && !flashed
fun flash() {
energy = 0
flashed = true
}
fun reset() {
if (flashed) {
flashed = false
energy = 0
}
}
}
fun List<List<Octopus>>.dump(): String {
val octopuses = this
return buildString {
octopuses.forEach { row ->
row.forEach { octopus ->
append(octopus.energy)
}
appendLine()
}
}.trim()
}
fun List<List<Octopus>>.increase() {
forEach { row ->
row.forEach { octopus ->
octopus.energy++
}
}
}
fun List<List<Octopus>>.increase(neighbors: List<Position>) {
neighbors.forEach { neighbor ->
get(neighbor.y)[neighbor.x].energy++
}
}
fun List<List<Octopus>>.neighborsOf(x: Int, y: Int): List<Position> {
val candidates = listOf(
Position(x - 1, y - 1),
Position(x, y - 1),
Position(x + 1, y - 1),
Position(x - 1, y),
Position(x + 1, y),
Position(x - 1, y + 1),
Position(x, y + 1),
Position(x + 1, y + 1),
)
return candidates.filter { candidate ->
candidate.y in indices &&
candidate.x in get(0).indices
}
}
fun List<List<Octopus>>.flash(): Pair<Int, List<Position>> {
val neighbors = mutableListOf<Position>()
var flashes = 0
indices.forEach { y ->
get(y).indices.forEach { x ->
val octopus = get(y)[x]
if (octopus.canFlash()) {
octopus.flash()
flashes++
neighbors.addAll(neighborsOf(x, y))
}
}
}
return Pair(flashes, neighbors)
}
fun List<List<Octopus>>.simulate(): Int {
increase()
var (flashes, neighbors) = flash()
while (neighbors.isNotEmpty()) {
increase(neighbors)
val (additionalFlashes, newNeighbors) = flash()
neighbors = newNeighbors
flashes += additionalFlashes
}
reset()
return flashes
}
fun List<List<Octopus>>.simulate(times: Int): Int {
var flashes = 0
repeat(times) {
flashes += simulate()
}
return flashes
}
fun List<List<Octopus>>.reset() {
forEach { row ->
row.forEach { octopus ->
octopus.reset()
}
}
}
fun List<List<Octopus>>.allFlashed(): Boolean {
return all { row ->
row.all { octopus -> octopus.energy == 0 }
}
}
fun List<List<Octopus>>.simulateUntilAllFlashed(): Int {
var step = 0
while (!allFlashed()) {
simulate()
step++
}
return step
}
fun readOctopuses(fileName: String): List<List<Octopus>> {
return readOctopusesFromString(File(fileName)
.readText())
}
fun readOctopusesFromString(input: String): List<List<Octopus>> {
return input
.lines()
.map { line ->
line.toCharArray().map { value -> Octopus(value.digitToInt()) }
}
}
fun part1() {
val octopuses = readOctopuses("day11.txt")
val flashes = octopuses.simulate(100)
println("Flashes = $flashes")
}
fun part2() {
val octopuses = readOctopuses("day11.txt")
val steps = octopuses.simulateUntilAllFlashed()
println("Steps = $steps")
}
fun main() {
part2()
}
| 0 | Kotlin | 1 | 2 | 73bbb6a41229e5863e52388a19108041339a864e | 3,451 | AdventOfCode2021 | Apache License 2.0 |
src/main/kotlin/aoc2020/CrabCombat.kt | komu | 113,825,414 | false | {"Kotlin": 395919} | package komu.adventofcode.aoc2020
import komu.adventofcode.utils.nonEmptyLines
fun crabCombat1(s: String): Int {
val (deck1, deck2) = parseDecks(s)
while (deck1.isNotEmpty() && deck2.isNotEmpty()) {
val top1 = deck1.removeAt(0)
val top2 = deck2.removeAt(0)
if (top1 > top2) {
deck1.add(top1)
deck1.add(top2)
} else {
deck2.add(top2)
deck2.add(top1)
}
}
val winner = deck1.takeIf { it.isNotEmpty() } ?: deck2
return score(winner)
}
fun crabCombat2(s: String): Int {
val (deck1, deck2) = parseDecks(s)
return score(recursiveCombat(deck1, deck2).winningDeck)
}
private fun recursiveCombat(d1: List<Int>, d2: List<Int>): GameResult {
val seen = mutableSetOf<Pair<List<Int>, List<Int>>>()
val deck1 = d1.toMutableList()
val deck2 = d2.toMutableList()
while (deck1.isNotEmpty() && deck2.isNotEmpty()) {
if (!seen.add(Pair(deck1.toList(), deck2.toList())))
return GameResult(true, deck1)
val top1 = deck1.removeAt(0)
val top2 = deck2.removeAt(0)
val winner1 = if (deck1.size >= top1 && deck2.size >= top2)
recursiveCombat(deck1.take(top1), deck2.take(top2)).winner1
else
top1 > top2
if (winner1) {
deck1.add(top1)
deck1.add(top2)
} else {
deck2.add(top2)
deck2.add(top1)
}
}
val winner1 = deck1.isNotEmpty()
return GameResult(winner1, if (winner1) deck1 else deck2)
}
private class GameResult(val winner1: Boolean, val winningDeck: List<Int>)
private fun score(winner: List<Int>) =
winner.asReversed().mapIndexed { i, n -> (i + 1) * n }.sum()
private fun parseDecks(s: String): Pair<MutableList<Int>, MutableList<Int>> {
val (d1, d2) = s.split("\n\n").map { p -> p.nonEmptyLines().drop(1).map { it.toInt() }.toMutableList() }
return Pair(d1, d2)
}
| 0 | Kotlin | 0 | 0 | 8e135f80d65d15dbbee5d2749cccbe098a1bc5d8 | 1,962 | advent-of-code | MIT License |
src/day8/Day8.kt | blundell | 572,916,256 | false | {"Kotlin": 38491} | package day8
import readInput
data class Height(
val value: Int,
val westHeights: List<Int>,
val eastHeights: List<Int>,
val northHeights: List<Int>,
val southHeights: List<Int>,
) {
val visible by lazy {
return@lazy listOf(
northHeights,
southHeights,
eastHeights,
westHeights,
).any { heights -> heights.none { it >= value } }
}
val scenicScore by lazy {
northHeights.reversed().countBelow(value) *
southHeights.countBelow(value) *
eastHeights.countBelow(value) *
westHeights.reversed().countBelow(value)
}
private fun List<Int>.countBelow(target: Int): Int {
var runningTotal = 0
for (n in this) {
if (n < target) {
runningTotal += 1
}
if (n >= target) {
runningTotal += 1
break
}
}
return runningTotal
}
}
private fun List<Int>.subListFrom(fromIndex: Int): List<Int> {
if (fromIndex >= this.size) {
return emptyList()
}
return this.subList(fromIndex, this.size)
}
private fun List<Int>.subListTo(toIndex: Int): List<Int> {
return this.subList(0, toIndex)
}
fun main() {
fun getAsInts(input: List<String>): MutableList<MutableList<Int>> {
val ints = mutableListOf<MutableList<Int>>()
for (line in input) {
val currentLineInts = mutableListOf<Int>()
for (c in line) {
currentLineInts.add(c.code - '0'.code)
}
ints.add(currentLineInts)
}
return ints
}
fun storeHeights(rows: MutableList<MutableList<Int>>): MutableList<MutableList<Height>> {
val heights = mutableListOf<MutableList<Height>>()
for ((y, row) in rows.withIndex()) {
val currentRowHeights = mutableListOf<Height>()
for ((x, h) in row.withIndex()) {
val northHeights = mutableListOf<Int>()
for (n in 0 until y) {
// Get the height in the same column of the previous rows
northHeights.add(rows[n][x])
}
val southHeights = mutableListOf<Int>()
for (n in y + 1 until row.size) {
// Get the height in the same column of the previous rows
southHeights.add(rows[n][x])
}
currentRowHeights.add(
Height(
value = h,
eastHeights = row.subListFrom(x + 1),
westHeights = row.subListTo(x),
northHeights = northHeights,
southHeights = southHeights,
)
)
}
heights.add(currentRowHeights)
}
return heights
}
fun part1(input: List<String>): Int {
val rows = getAsInts(input)
val heights = storeHeights(rows)
var runningTotal = 0
for ((y, row) in heights.withIndex()) {
for ((x, height) in row.withIndex()) {
if (height.visible) {
print("${height.value}")
runningTotal += 1
} else {
print("-")
}
}
println("")
}
return runningTotal
}
fun part2(input: List<String>): Int {
val rows = getAsInts(input)
val heights = storeHeights(rows)
return heights.map {
it.map { h ->
h.scenicScore
}
}
.flatten()
.max()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("day8/Day8_test")
val part1Result = part1(testInput)
check(part1Result == 21) { "Expected 21 but got [$part1Result]" }
val part2Result = part2(testInput)
check(part2Result == 8) { "Expected 8 but got [$part2Result]" }
val input = readInput("day8/Day8")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f41982912e3eb10b270061db1f7fe3dcc1931902 | 4,177 | kotlin-advent-of-code-2022 | Apache License 2.0 |
src/Day13.kt | Riari | 574,587,661 | false | {"Kotlin": 83546, "Python": 1054} | private abstract class Packet {
fun compareTo(other: Packet): Int {
if (this is IntPacket && other is IntPacket) return this.compareTo(other)
if (this is IntPacket && other is ListPacket) return this.compareTo(other)
if (this is ListPacket && other is ListPacket) return this.compareTo(other)
if (this is ListPacket && other is IntPacket) return this.compareTo(other)
return 0
}
}
private class IntPacket(val value: Int) : Packet() {
fun toListPacket(): ListPacket {
return ListPacket(mutableListOf(this))
}
fun compareTo(other: ListPacket): Int {
return toListPacket().compareTo(other)
}
fun compareTo(other: IntPacket): Int {
return other.value.compareTo(this.value)
}
override fun toString(): String {
return "$value"
}
}
private class ListPacket(val value: MutableList<Packet> = mutableListOf()) : Packet() {
fun compareTo(other: ListPacket): Int {
for (i in 0 until maxOf(value.size, other.value.size)) {
val left = value.getOrNull(i)
val right = other.value.getOrNull(i)
if (left == null) return 1
if (right == null) return -1
val result = left.compareTo(right)
if (result != 0) return result
}
return 0
}
fun compareTo(other: IntPacket): Int {
return compareTo(other.toListPacket())
}
override fun toString(): String {
var string = "["
for ((index, packet) in value.withIndex()) {
string += packet.toString()
if (index < value.size - 1) string += ","
}
return "$string]"
}
}
fun main() {
fun String.findClosingBracket(opensAt: Int): Int {
var endsAt: Int = opensAt
var counter = 1
while (counter > 0) {
val c: Char = this[++endsAt]
if (c == '[') counter++
else if (c == ']') counter--
}
return endsAt
}
fun parse(string: String): Packet {
val packet = ListPacket()
var i = 0
while (i < string.length) {
when (string[i]) {
'[' -> {
val endsAt = string.findClosingBracket(i)
val nested = string.substring(i + 1 until endsAt)
packet.value.add(parse(nested))
i = endsAt
continue
}
',', ']' -> {}
else -> {
var number: String = string[i].toString()
if (i + 1 < string.length && string[i + 1].isDigit()) number += string[++i]
packet.value.add(IntPacket(number.toInt()))
}
}
i++
}
return packet
}
fun processInput(input: List<String>): List<Pair<Packet, Packet>> {
val packets = mutableListOf<Pair<Packet, Packet>>()
input.chunked(3).forEach {
packets.add(Pair(
parse(it[0].substring(1 until it[0].length)),
parse(it[1].substring(1 until it[1].length))
))
}
return packets
}
fun part1(packets: List<Pair<Packet, Packet>>): Int {
return packets.withIndex().filter { it.value.first.compareTo(it.value.second) == 1 }.sumOf { it.index + 1 }
}
fun part2(packets: List<Pair<Packet, Packet>>): Int {
val flattened: MutableList<Packet> = packets.flatten()
val dividers = listOf(parse("[[2]]"), parse("[[6]]"))
dividers.forEach { flattened.add(it) }
val sorted = flattened.sortedWith { left, right -> right.compareTo(left) }
return sorted.withIndex().filter { dividers.contains(it.value) }.map { it.index + 1 }.reduce { acc, i -> acc * i }
}
val testInput = processInput(readInput("Day13_test"))
check(part1(testInput) == 13)
check(part2(testInput) == 140)
val input = processInput(readInput("Day13"))
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 8eecfb5c0c160e26f3ef0e277e48cb7fe86c903d | 4,049 | aoc-2022 | Apache License 2.0 |
src/Day03.kt | roxanapirlea | 572,665,040 | false | {"Kotlin": 27613} | fun main() {
fun Char.getPriority(): Long {
return if (this.isUpperCase()) {
code - 'A'.code + 27L
} else {
code - 'a'.code + 1L
}
}
fun part1(input: List<String>): Long {
return input.map { backpack ->
val (compartment1, compartment2) =
backpack.chunked(backpack.length / 2).map { it.toCharArray().toSet() }
val common = compartment1.intersect(compartment2).single()
common.getPriority()
}.reduce { total, priority -> total + priority }
}
fun part2(input: List<String>): Long {
return input.chunked(3)
.map { group -> group.map { backpack -> backpack.toCharArray().toSet() } }
.map { group ->
val common = group.reduce { common, backpack -> common intersect backpack }.single()
common.getPriority()
}.reduce { total, priority -> total + priority }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157L)
check(part2(testInput) == 70L)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 6c4ae6a70678ca361404edabd1e7d1ed11accf32 | 1,247 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/com/ginsberg/advent2017/grid/FractalGrid.kt | tginsberg | 112,672,087 | false | null | package com.ginsberg.advent2017.grid
import kotlin.math.sqrt
fun List<FractalGrid>.join(): FractalGrid {
val rows = sqrt(this.size.toFloat()).toInt()
return this.chunked(rows).map {
it.reduce { a, b -> a nextTo b }
}.reduce { a, b -> a over b }
}
data class FractalGrid(val grid: List<List<Char>>) {
constructor(input: String) : this(
input.split("/").map { it.toList() }
)
val size = grid.size
infix fun nextTo(that: FractalGrid): FractalGrid =
FractalGrid(
grid.mapIndexed { idx, row -> row + that.grid[idx] }
)
infix fun over(that: FractalGrid): FractalGrid =
FractalGrid(
this.grid + that.grid
)
infix fun rowsOfSize(n: Int): List<FractalGrid> =
this.grid.chunked(n).map { FractalGrid(it) }
infix fun columnsOfSize(n: Int): List<FractalGrid> {
val chunked = this.grid.map { row ->
row.chunked(n)
}
return (0 until (grid[0].size) / n).map { x ->
(0 until n).map { y ->
chunked[y][x]
}
}.map { FractalGrid(it) }
}
fun split(): List<FractalGrid> {
val splitSize = if (size % 2 == 0) 2 else 3
val splits = size / splitSize
if (splits == 1) {
return listOf(this)
}
return (this rowsOfSize splitSize).map { it columnsOfSize splitSize }.flatten()
}
fun rotate(): FractalGrid =
FractalGrid(
(0 until grid.size).map { r ->
(0 until grid.size).map { c ->
grid[c][(grid.size) - 1 - r]
}
}
)
fun flip(): FractalGrid =
FractalGrid(grid.map { it.reversed() })
fun combinations(): List<FractalGrid> {
val rotations = (0 until 3).fold(listOf(this)) { rots, _ -> rots + rots.last().rotate() }
val flips = rotations.map { it.flip() }
return rotations + flips
}
override fun toString(): String =
grid.joinToString("/") { it.joinToString("") }
} | 0 | Kotlin | 0 | 15 | a57219e75ff9412292319b71827b35023f709036 | 2,063 | advent-2017-kotlin | MIT License |
src/Day02.kt | kecolk | 572,819,860 | false | {"Kotlin": 22071} | fun main() {
fun evalRound(input: String): Int {
return when (input) {
"A X" -> 4
"A Y" -> 8
"A Z" -> 3
"B X" -> 1
"B Y" -> 5
"B Z" -> 9
"C X" -> 7
"C Y" -> 2
"C Z" -> 6
else -> 0
}
}
fun part1(input: List<String>): Int = input.sumOf { evalRound(it) }
fun evalRound2(it: String): Int {
return when (it) {
"A X" -> 3
"A Y" -> 4
"A Z" -> 8
"B X" -> 1
"B Y" -> 5
"B Z" -> 9
"C X" -> 2
"C Y" -> 6
"C Z" -> 7
else -> 0
}
}
fun part2(input: List<String>): Int = input.sumOf { evalRound2(it) }
val testInput = readTextInput("Day02_test")
val input = readTextInput("Day02")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 72b3680a146d9d05be4ee209d5ba93ae46a5cb13 | 998 | kotlin_aoc_22 | Apache License 2.0 |
src/main/java/com/booknara/problem/union/EarliestMomentWhenEveryoneBecomeFriendsKt.kt | booknara | 226,968,158 | false | {"Java": 1128390, "Kotlin": 177761} | package com.booknara.problem.union
/**
* 1101. The Earliest Moment When Everyone Become Friends (Medium)
* https://leetcode.com/problems/the-earliest-moment-when-everyone-become-friends/
*/
class EarliestMomentWhenEveryoneBecomeFriendsKt {
// T:O(nlogn), S:O(n)
fun earliestAcq(logs: Array<IntArray>, n: Int): Int {
val root = IntArray(n) { i -> i }
val rank = IntArray(n) { 1 }
var groups = n
// timestamp should be sorted
logs.sortBy { i -> i[0] }
for (i in logs.indices) {
val time = logs[i][0]
val root1 = find(root, logs[i][1])
val root2 = find(root, logs[i][2])
if (root1 != root2) {
if (rank[root1] < rank[root2]) {
root[root1] = root2
} else if (rank[root1] > rank[root2]) {
root[root2] = root1
} else {
root[root2] = root1
rank[root1]++
}
groups--
if (groups == 1) {
return time
}
}
}
return -1
}
fun find(root: IntArray, index: Int): Int {
if (index == root[index]) {
return index
}
root[index] = find(root, root[index])
return root[index]
}
}
| 0 | Java | 1 | 1 | 04dcf500ee9789cf10c488a25647f25359b37a53 | 1,163 | playground | MIT License |
src/main/kotlin/day9.kt | Arch-vile | 572,557,390 | false | {"Kotlin": 132454} | package day9
import aoc.utils.Cursor
import aoc.utils.firstPart
import aoc.utils.readInput
import aoc.utils.secondPart
import kotlin.math.abs
fun part1(): Int {
var head = Cursor(0, 0)
val directions = readInput("day9-input.txt")
.map { Pair(it.firstPart(), it.secondPart().toInt()) }
val headLocations = positions(head, directions)
val knotMoves = runSimulation(head, headLocations)
// tailHistory.forEach { println(it) }
return knotMoves.toSet().size;
}
fun part2(): Int {
var head = Cursor(0, 0)
val directions = readInput("day9-input.txt")
.map { Pair(it.firstPart(), it.secondPart().toInt()) }
val headPositions = positions(head, directions)
var knotPositions = runSimulation(head, headPositions)
repeat(8){
knotPositions = runSimulation(head, knotPositions)
}
return knotPositions.toSet().size
}
fun positions(start: Cursor, directions: List<Pair<String, Int>>): MutableList<Cursor> {
var current = start
val positions = mutableListOf(start)
directions.forEach { direction ->
current = move(direction, current)
positions.add(current)
}
return positions
}
fun runSimulation(start: Cursor, headLocations: MutableList<Cursor>): MutableList<Cursor> {
var tail = start
val tailHistory = mutableListOf(tail)
headLocations.forEach { head ->
// If needs diagonal move
while (
head.x != tail.x && head.y != tail.y && isNotAdjecant(tail, head)
) {
if (head.x > tail.x && head.y > tail.y) {
tail = tail.copy(x = tail.x + 1, y = tail.y + 1)
} else if (head.x > tail.x && head.y < tail.y) {
tail = tail.copy(x = tail.x + 1, y = tail.y - 1)
} else if (head.x < tail.x && head.y > tail.y) {
tail = tail.copy(x = tail.x - 1, y = tail.y + 1)
} else if (head.x < tail.x && head.y < tail.y) {
tail = tail.copy(x = tail.x - 1, y = tail.y - 1)
}
tailHistory.add(tail)
}
// Now they are in same row or column
// Same row
while (head.x != tail.x && isNotAdjecant(tail, head)) {
if (head.x > tail.x)
tail = tail.copy(x = tail.x + 1)
else if (head.x < tail.x)
tail = tail.copy(x = tail.x - 1)
tailHistory.add(tail)
}
// Same column
while (head.y != tail.y && isNotAdjecant(tail, head)) {
if (head.y > tail.y)
tail = tail.copy(y = tail.y + 1)
else if (head.y < tail.y)
tail = tail.copy(y = tail.y - 1)
tailHistory.add(tail)
}
}
return tailHistory
}
fun isNotAdjecant(tail: Cursor, head: Cursor): Boolean {
return !(abs(tail.x - head.x) <= 1 && abs(tail.y - head.y) <= 1)
}
private fun move(it: Pair<String, Int>, point: Cursor): Cursor {
return when (it.first) {
"U" -> point.copy(y = point.y + it.second)
"D" -> point.copy(y = point.y - it.second)
"R" -> point.copy(x = point.x + it.second)
"L" -> point.copy(x = point.x - it.second)
else -> throw Error("unhandled")
}
}
| 0 | Kotlin | 0 | 0 | e737bf3112e97b2221403fef6f77e994f331b7e9 | 3,227 | adventOfCode2022 | Apache License 2.0 |
leetcode/snakes-and-ladders/main.kt | seirion | 17,619,607 | false | {"C++": 801740, "HTML": 42242, "Kotlin": 37689, "Python": 21759, "C": 3798, "JavaScript": 294} | // https://leetcode.com/problems/snakes-and-ladders
import java.util.*
class Solution {
data class Data(val cost: Int, val index: Int)
fun snakesAndLadders(board: Array<IntArray>): Int {
val size = board.size * board.size
val jump = board.reversed()
.mapIndexed { i, b -> if (i % 2 == 0) b.toList() else b.reversed() }
.flatten()
.mapIndexed { i, v -> if (v == -1) i else v - 1 } // zero-based indexing
val q: Queue<Data> = LinkedList()
val visit = BooleanArray(size) { false }
q.add(Data(0, 0))
visit[0] = true
while (q.isNotEmpty()) {
val from = q.poll()
if (from.index == size - 1) return from.cost
(1..6).map { from.index + it }
.filter { it in 0 until size }
.map { jump[it] }
.filterNot { visit[it] }
.forEach { to ->
visit[to] = true
q.add(Data(from.cost + 1, to))
}
}
return -1
}
}
fun main(args: Array<String>) {
val input = arrayOf(
intArrayOf(-1, -1, -1, -1, -1, -1),
intArrayOf(-1, -1, -1, -1, -1, -1),
intArrayOf(1, -1, -1, -1, -1, -1),
intArrayOf(1, 35, -1, -1, 13, -1),
intArrayOf(1, -1, -1, -1, -1, -1),
intArrayOf(1, 15, -1, -1, -1, -1)
)
println(Solution().snakesAndLadders(input))
val input2 = arrayOf(
intArrayOf(-1, -1, -1, -1, 48, 5, -1),
intArrayOf(12, 29, 13, 9, -1, 2, 32),
intArrayOf(-1, -1, 21, 7, -1, 12, 49),
intArrayOf(2, 37, 21, 40, -1, 22, 12),
intArrayOf(2, -1, 2, -1, -1, -1, 6),
intArrayOf(9, -1, 35, -1, -1, 39, -1),
intArrayOf(1, 36, -1, -1, -1, -1, 5)
)
println(Solution().snakesAndLadders(input2))
}
| 0 | C++ | 4 | 4 | a59df98712c7eeceabc98f6535f7814d3a1c2c9f | 1,941 | code | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/ClosestDessertCost.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 kotlin.math.abs
/**
* 1774. Closest Dessert Cost
* @see <a href="https://leetcode.com/problems/closest-dessert-cost/">Source</a>
*/
fun interface ClosestDessertCost {
operator fun invoke(baseCosts: IntArray, toppingCosts: IntArray, target: Int): Int
}
class ClosestDessertCostBacktracking : ClosestDessertCost {
private var result = 0
override operator fun invoke(baseCosts: IntArray, toppingCosts: IntArray, target: Int): Int {
if (baseCosts.isEmpty()) return 0
result = baseCosts[0]
for (base in baseCosts) closestCost(base, toppingCosts, 0, target)
return result
}
private fun closestCost(current: Int, toppingCosts: IntArray, index: Int, target: Int) {
val local = abs(target - current) < abs(target - result)
if (local || abs(target - current) == abs(target - result) && current < result) {
result = current
}
if (index == toppingCosts.size) {
return
}
closestCost(current, toppingCosts, index + 1, target)
// when current < target, one toppingCosts is acceptable
if (current < target) {
closestCost(current + toppingCosts[index], toppingCosts, index + 1, target)
}
// when current + toppingCosts < target, another toppingCosts is acceptable
if (current + toppingCosts[index] < target) {
closestCost(current + toppingCosts[index] * 2, toppingCosts, index + 1, target)
}
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,136 | kotlab | Apache License 2.0 |
src/main/kotlin/year_2022/Day06.kt | krllus | 572,617,904 | false | {"Kotlin": 97314} | package year_2022
import utils.readInput
fun main() {
fun processLine(line: String): Int {
for (index in 4..line.length - 4) {
val a = line[index - 4]
val b = line[index - 3]
val c = line[index - 2]
val d = line[index - 1]
if (a != b && a != c && a != d && b != c && b != d && c != d) {
return index
}
}
error("index not found")
}
fun processLine(line: String, messageLength: Int): Int {
for (index in messageLength until line.length) {
val windowStart = 0 + index - messageLength
val windowEnd = index
val window = line.subSequence(windowStart, windowEnd)
var repeatChar = false
for (windowIndex in window.indices) {
val char = window[windowIndex]
for (searchIndex in windowIndex + 1 until window.length) {
val searchChar = window[searchIndex]
if (char == searchChar) {
repeatChar = true
continue
}
}
}
if (!repeatChar)
return index
}
error("index not found")
}
fun isUnique(window : Array<Char>) = setOf(*window).size == window.size
fun part1(input: List<String>): Int {
return input.map { line ->
processLine(line, 4)
}.sumOf { it }
}
fun part2(input: List<String>): Int {
return input.map { line ->
processLine(line, 14)
}.sumOf { it }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day06_test")
// check(part1(testInput) == 39)
// check(part2(testInput) == 0)
val input = readInput("Day06")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | b5280f3592ba3a0fbe04da72d4b77fcc9754597e | 1,913 | advent-of-code | Apache License 2.0 |
src/main/java/challenges/leetcode/MergeSortedArray.kt | ShabanKamell | 342,007,920 | false | null | package challenges.leetcode
/**
You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively.
Merge nums1 and nums2 into a single array sorted in non-decreasing order.
The final sorted array should not be returned by the function, but instead be stored inside the array nums1. To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n.
Example 1:
Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
Output: [1,2,2,3,5,6]
Explanation: The arrays we are merging are [1,2,3] and [2,5,6].
The result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1.
Example 2:
Input: nums1 = [1], m = 1, nums2 = [], n = 0
Output: [1]
Explanation: The arrays we are merging are [1] and [].
The result of the merge is [1].
Example 3:
Input: nums1 = [0], m = 0, nums2 = [1], n = 1
Output: [1]
Explanation: The arrays we are merging are [] and [1].
The result of the merge is [1].
Note that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1.
Constraints:
nums1.length == m + n
nums2.length == n
0 <= m, n <= 200
1 <= m + n <= 200
-109 <= nums1[i], nums2[j] <= 109
Follow up: Can you come up with an algorithm that runs in O(m + n) time?
*/
object MergeSortedArray {
private fun merge(a: IntArray, m: Int, b: IntArray, n: Int) {
var insertIndex = m + n - 1
var indexA = m - 1
var indexB = n - 1
while (indexB >= 0) {
if (indexA < 0) {
a[insertIndex--] = b[indexB--]
continue
}
if (b[indexB] >= a[indexA]) {
a[insertIndex--] = b[indexB--]
continue
}
a[insertIndex--] = a[indexA--]
}
}
@JvmStatic
fun main(args: Array<String>) {
val a = intArrayOf(1, 2, 3, 0, 0, 0)
merge(a, 3, intArrayOf(2, 5, 6), 3)
println(a.joinToString())
}
} | 0 | Kotlin | 0 | 0 | ee06bebe0d3a7cd411d9ec7b7e317b48fe8c6d70 | 2,183 | CodingChallenges | Apache License 2.0 |
src/Day10.kt | wlghdu97 | 573,333,153 | false | {"Kotlin": 50633} | import java.util.*
private class CPU constructor(private val instructions: List<Instruction>) {
fun run(onCycle: (cycle: Int, x: Int) -> Unit) {
val instQueue: Queue<Instruction> = LinkedList()
instructions.forEach {
instQueue.add(it)
}
var x = 1
var cycle = 1
var currentInst: Instruction? = instQueue.poll()
while (currentInst != null) {
val inst = currentInst
repeat(inst.cycleToFinish) {
onCycle(cycle, x)
if (it == inst.cycleToFinish - 1) {
x = inst.onFinishInstruction(x)
}
cycle += 1
}
currentInst = instQueue.poll()
}
}
sealed class Instruction {
abstract val cycleToFinish: Int
abstract fun onFinishInstruction(register: Int): Int
object Noop : Instruction() {
override val cycleToFinish: Int = 1
override fun onFinishInstruction(register: Int): Int {
return register // do nothing
}
}
class Addx(val argument: Int) : Instruction() {
override val cycleToFinish: Int = 2
override fun onFinishInstruction(register: Int): Int {
return register + argument
}
}
}
}
private fun parseInstructions(input: List<String>): List<CPU.Instruction> {
return input.map {
val parts = it.split(" ")
when (parts[0]) {
"addx" -> {
CPU.Instruction.Addx(parts[1].toInt())
}
"noop" -> {
CPU.Instruction.Noop
}
else -> {
throw IllegalArgumentException()
}
}
}
}
private fun CPU.sumOfSpecificCycleStrengths(vararg cycles: Int): Int {
var sum = 0
run { cycle, x ->
if (cycles.contains(cycle)) {
sum += (cycle * x)
}
}
return sum
}
private fun CPU.printPixels(width: Int) {
val monitor = StringBuilder()
run { cycle, x ->
val range = (x - 1)..(x + 1)
val inRange = ((cycle - 1) % width) in range
if (inRange) {
monitor.append("#")
} else {
monitor.append(".")
}
}
println(monitor.chunked(width).joinToString("\n"))
}
fun main() {
fun test1(input: List<String>): Int {
return CPU(parseInstructions(input)).sumOfSpecificCycleStrengths(20, 60, 100, 140, 180, 220)
}
fun part1(input: List<String>): Int {
return CPU(parseInstructions(input)).sumOfSpecificCycleStrengths(20, 60, 100, 140, 180, 220)
}
fun test2(input: List<String>) {
CPU(parseInstructions(input)).printPixels(40)
}
fun part2(input: List<String>) {
CPU(parseInstructions(input)).printPixels(40)
}
val testInput = readInput("Day10-Test01")
val input = readInput("Day10")
println(test1(testInput))
println(part1(input))
test2(testInput)
part2(input)
}
| 0 | Kotlin | 0 | 0 | 2b95aaaa9075986fa5023d1bf0331db23cf2822b | 3,051 | aoc-2022 | Apache License 2.0 |
src/chapter3/section2/ex32_Certification.kt | w1374720640 | 265,536,015 | false | {"Kotlin": 1373556} | package chapter3.section2
/**
* 验证
* 编写一个方法isBST(),接受一个结点Node为参数,若该结点是一个二叉查找树的根节点则返回true,否则返回false
* 提示:这个任务比看起来要困难,它和你调用前三题中各个方法的顺序有关
*
* 解:isBinaryTree必须第一个判断,否则有环的数据结构会导致后面的死循环
* 在我的实现中isOrdered()和hasNoDuplicates()方法的顺序并不重要
* hasNoDuplicates()不通过则isOrdered()也无法通过
*/
fun <K : Comparable<K>> isBST(node: BinarySearchTree.Node<K, *>): Boolean {
if (!isBinaryTree(node)) return false
if (!isOrdered(node, minNode(node).key, maxNode(node).key)) return false
if (!hasNoDuplicates(node)) return false
return true
}
fun <K : Comparable<K>> minNode(node: BinarySearchTree.Node<K, *>): BinarySearchTree.Node<K, *> {
return if (node.left == null) node else minNode(node.left!!)
}
fun <K : Comparable<K>> maxNode(node: BinarySearchTree.Node<K, *>): BinarySearchTree.Node<K, *> {
return if (node.right == null) node else maxNode(node.right!!)
}
fun main() {
val charArray = "EASYQUESTION".toCharArray()
val bst = BinarySearchTree<Char, Int>()
for (i in charArray.indices) {
bst.put(charArray[i], i)
}
println(isBST(bst.root!!))
val node = BinarySearchTree.Node(5, 0)
node.left = BinarySearchTree.Node(2, 0)
node.left!!.left = BinarySearchTree.Node(1, 0)
node.left!!.right = BinarySearchTree.Node(4, 0)
node.right = BinarySearchTree.Node(8, 0)
node.right!!.left = BinarySearchTree.Node(7, 0)
node.right!!.right = BinarySearchTree.Node(9, 0)
println(isBST(node))
}
| 0 | Kotlin | 1 | 6 | 879885b82ef51d58efe578c9391f04bc54c2531d | 1,709 | Algorithms-4th-Edition-in-Kotlin | MIT License |
src/Day03.kt | sd2000usr | 573,123,353 | false | {"Kotlin": 21846} |
val abc = "abcdefghijklmnopqrstuvwxyz"
val alphabet = "$abc${abc.uppercase()}"
fun main()
{
fun part1(input: List<String>)
{
var scoreAcc = 0
input.forEach ()
{ string ->
val map0 = mutableMapOf<Char, Int>() // char, times appear
val map1 = mutableMapOf<Char, Int>() // char, times appear
val half = string.length / 2
val slot0 = string.substring(0, half)
val slot1 = string.substring(half, string.length)
slot0.forEach()
{ char ->
val target = map0[char]
if (target == null)
map0[char] = 1
else
map0[char] = map0[char]!! + 1
}
slot1.forEach()
{ char ->
val target = map1[char]
if (target == null)
map1[char] = 1
else
map1[char] = map1[char]!! + 1
}
var mustAppearChar = Pair(' ', 0) // char, times appear
map0.forEach()
{ (char, timesAppear) ->
val timesAppearInMap1 = map1[char]
if (timesAppearInMap1 != null)
{
val timesAppearTogether = timesAppear + timesAppearInMap1
if (timesAppearTogether > mustAppearChar.second)
mustAppearChar = Pair(char, timesAppearTogether)
}
}
val score = alphabet.indexOf(mustAppearChar.first) + 1
scoreAcc += score
println("must appear char: ${mustAppearChar.first}, times: ${mustAppearChar.second}, score: $score")
//println(it)
}
println("scoreAcc: $scoreAcc")
}
fun part2(input: List<String>)
{
fun mapOfCharAndTimesAppears(string: String): Map<Char, Int>
{
val map = mutableMapOf<Char, Int>() // char, times appear
string.forEach ()
{ char ->
val target = map[char]
if (target == null)
map[char] = 1
else
map[char] = target + 1
}
return map
}
val cacheListCharTimesAppear = mutableListOf<Map<Char, Int>>()
fun timesCharAppearsInLisOfMap(charTarget: Char, list: List<Map<Char, Int>>): Int?
{
var accTimes = 0
for (map in list)
{
val timesAppears = map[charTarget]
if (timesAppears != null)
accTimes += timesAppears
else
return null
}
return accTimes
}
fun mustCommonCharAppearInCacheScore(): Int // must char appears score
{
///fun otherContains
val result = mutableMapOf<Char, Int>()
//timesCharAppearsInLisOfMap()
cacheListCharTimesAppear.forEach ()
{ map ->
map.forEach ()
{ (char, times) ->
if (!result.containsKey(char))
{
val totalTimes = timesCharAppearsInLisOfMap(char, cacheListCharTimesAppear)
if (totalTimes != null)
result[char] = totalTimes
}
}
}
val finalList = result.toList().sortedByDescending { (char, times) -> times }
val score = alphabet.indexOf(finalList.first().first) + 1
println("finalList: ${finalList.first()}, score: $score")
return score
}
var totalScore = 0
var index = 0
while (index < input.size)
{
val string = input[index]
val newMap = mapOfCharAndTimesAppears(string)
if ((index + 1) % 3 == 0)
{
cacheListCharTimesAppear.add(newMap)
totalScore += mustCommonCharAppearInCacheScore()
cacheListCharTimesAppear.clear()
}
else
cacheListCharTimesAppear.add(newMap)
index ++
}
println("total score: $totalScore")
}
val input = readInput("Day03")
//val input = readInput("testDay03")
//part1(input)
part2(input)
} | 0 | Kotlin | 0 | 0 | fe5307af5dd8620ae8dee0ad5244466b5332e535 | 4,434 | cfgtvsizedxr8jubhy | Apache License 2.0 |
src/main/kotlin/adventofcode/year2020/Day22CrabCombat.kt | pfolta | 573,956,675 | false | {"Kotlin": 199554, "Dockerfile": 227} | package adventofcode.year2020
import adventofcode.Puzzle
import adventofcode.PuzzleInput
class Day22CrabCombat(customInput: PuzzleInput? = null) : Puzzle(customInput) {
private val player1 by lazy { input.split("\n\n").first().lines().drop(1).map(String::toInt) }
private val player2 by lazy { input.split("\n\n").last().lines().drop(1).map(String::toInt) }
override fun partOne() = CrabCombatGame(player1.toMutableList(), player2.toMutableList()).playRegularGame()
override fun partTwo() = CrabCombatGame(player1.toMutableList(), player2.toMutableList()).playRecursiveGame(true)
companion object {
private data class CrabCombatGame(
val player1: MutableList<Int>,
val player2: MutableList<Int>
) {
private fun computeScore() = (player1 + player2).reversed().mapIndexed { position, card -> card * (position + 1) }.sum()
fun playRegularGame(): Int {
while (player1.isNotEmpty() && player2.isNotEmpty()) {
val card1 = player1.removeAt(0)
val card2 = player2.removeAt(0)
if (card1 > card2) {
player1.addAll(listOf(card1, card2))
} else {
player2.addAll(listOf(card2, card1))
}
}
return computeScore()
}
fun playRecursiveGame(startingGame: Boolean): Int {
val previousConfigurations = hashSetOf<CrabCombatGame>()
while (player1.isNotEmpty() && player2.isNotEmpty()) {
if (previousConfigurations.contains(this)) {
return 1
}
previousConfigurations.add(this)
val card1 = player1.removeAt(0)
val card2 = player2.removeAt(0)
val winningPlayer = when {
player1.size >= card1 && player2.size >= card2 ->
CrabCombatGame(
player1.take(card1).toMutableList(),
player2.take(card2).toMutableList()
).playRecursiveGame(false)
card1 > card2 -> 1
else -> 2
}
if (winningPlayer == 1) {
player1.addAll(listOf(card1, card2))
} else {
player2.addAll(listOf(card2, card1))
}
}
return when (startingGame) {
true -> computeScore()
false -> if (player1.size > player2.size) 1 else 2
}
}
}
}
}
| 0 | Kotlin | 0 | 0 | 72492c6a7d0c939b2388e13ffdcbf12b5a1cb838 | 2,794 | AdventOfCode | MIT License |
src/main/kotlin/year_2022/Day05.kt | krllus | 572,617,904 | false | {"Kotlin": 97314} | package year_2022
import utils.readInputAsText
fun main() {
fun createStorage(cargos: List<String>): MutableMap<Int, ElfStack> {
val storage: MutableMap<Int, ElfStack> = HashMap()
for (index in 0..cargos.size - 2) {
val row = cargos[index]
val elements = row.toCharArray()
.filterIndexed { elementIndex, _ ->
elementIndex % 4 == 1
}
elements.forEachIndexed { elementIndex, element ->
var elfStack = storage[elementIndex]
if (elfStack == null)
elfStack = ElfStack()
elfStack.addElement(element, true)
storage[elementIndex] = elfStack
}
}
return storage
}
fun part1(text: String): String {
val input = text.split("\n\n")
val first = input[0]
val cargos = first.split("\n")
val storage: MutableMap<Int, ElfStack> = createStorage(cargos)
val second = input[1]
val commands = second.split("\n").toCommandList()
for (command in commands) {
repeat(command.quantity) {
val shelfOrigin = storage[command.origin - 1] ?: error("shelf [${command.origin}] not found")
val shelfDestination = storage[command.destiny - 1] ?: error("shelf [${command.destiny}] not found")
val element = shelfOrigin.removeElement()
shelfDestination.addElement(element)
}
}
val result = storage.values.map { it.topElement() }.joinToString(separator = "")
println(result)
return result
}
fun part2(text: String): String {
val input = text.split("\n\n")
val first = input[0]
val cargos = first.split("\n")
val storage: MutableMap<Int, ElfStack> = createStorage(cargos)
val second = input[1]
val commands = second.split("\n").toCommandList()
for (command in commands) {
val shelfOrigin = storage[command.origin - 1] ?: error("shelf [${command.origin}] not found")
val shelfDestination = storage[command.destiny - 1] ?: error("shelf [${command.destiny}] not found")
val elements = arrayListOf<Char>()
repeat(command.quantity) {
elements.add(shelfOrigin.removeElement())
}
elements.reverse()
for (element in elements) {
shelfDestination.addElement(element)
}
}
val result = storage.values.map { it.topElement() }.joinToString(separator = "")
println(result)
return result
}
// test if implementation meets criteria from the description, like:
val testInput = readInputAsText("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInputAsText("Day05")
println(part1(input))
println(part2(input))
}
class ElfStack() {
private val elements = ArrayDeque<Char>()
fun addElement(element: Char, first: Boolean = false) {
if (element == ' ')
return
if (first) {
elements.addFirst(element)
} else {
elements.addLast(element)
}
}
fun removeElement(): Char {
return elements.removeLast()
}
fun topElement(): Char {
return elements.lastOrNull() ?: ' '
}
}
fun List<String>.toCommandList(): List<Command> {
return this.map { it.toCommand() }
}
fun String.toCommand(): Command {
val inputs = this.split(" ")
return Command(
quantity = inputs[1].toInt(),
origin = inputs[3].toInt(),
destiny = inputs[5].toInt(),
)
}
data class Command(
val quantity: Int,
val origin: Int,
val destiny: Int
) | 0 | Kotlin | 0 | 0 | b5280f3592ba3a0fbe04da72d4b77fcc9754597e | 3,830 | advent-of-code | Apache License 2.0 |
src/algorithmdesignmanualbook/datastructures/MultiplicativeArray.kt | realpacific | 234,499,820 | false | null | package algorithmdesignmanualbook.datastructures
import _utils.UseCommentAsDocumentation
import algorithmdesignmanualbook.print
import algorithmdesignmanualbook.withPrint
import utils.assertArraysSame
/**
* You have an unordered array X of n integers. Find the array M containing
* n elements where Mi is the product of all integers in X except for Xi. You may not use division.
*/
@UseCommentAsDocumentation
private interface MultiplicativeArray {
fun getMultiplicativeArray(array: Array<Int>): Array<Int>
}
/**
*
* Given array A, maintain two arrays
* * X: holds product of `A[0]..A[i]` at index i
* * Y: holds product of `A[lastIndex]..A[i]` at index i
*
* So now the item of result at index i is `X[i-1] * Y[i+1]`
* [Solution here](https://www.geeksforgeeks.org/a-product-array-puzzle/)
*/
class MultiplicativeArrayWithDoubleArrayApproach : MultiplicativeArray {
override fun getMultiplicativeArray(array: Array<Int>): Array<Int> {
val fromFrontProduct = Array(array.size) { 1 }
val fromBackProduct = Array(array.size) { 1 }
for (i in 0..array.lastIndex) {
fromFrontProduct[i] = fromFrontProduct.getOrElse(i - 1) { 1 } * array[i]
}
for (i in array.lastIndex downTo 0) {
fromBackProduct[i] = fromBackProduct.getOrElse(i + 1) { 1 } * array[i]
}
val result = Array(array.size) { 0 }
for (i in 0..array.lastIndex) {
result[i] = fromFrontProduct.getOrElse(i - 1) { 1 } * fromBackProduct.getOrElse(i + 1) { 1 }
}
return result.print()
}
}
/**
* Find total product and at index `i`, divide the total product by the value `A[i]`
*
* *Note:* What if one of the element is 0 or multiple elements are 0
*/
class MultiplicativeArrayWithDivision : MultiplicativeArray {
override fun getMultiplicativeArray(array: Array<Int>): Array<Int> {
val zeroIndexFirst = array.indexOf(0)
// Or traverse once and find all positions of 0
val zeroIndexLast = array.lastIndexOf(0)
// there are multiple zeros, then all elements are zero
if (zeroIndexFirst != zeroIndexLast) {
return Array(array.size) { 0 }.print()
} else if (zeroIndexFirst > -1) {
// there is only one index so only the index where 0 is will have total product
val result = Array(array.size) { 0 }
var totalProduct = 1
array.forEachIndexed { index, i ->
if (index != zeroIndexFirst) {
totalProduct *= i
}
}
result[zeroIndexFirst] = totalProduct
return result.print()
}
val result = Array(array.size) { 1 }
var totalProduct = 1
array.forEach { totalProduct *= it }
for (i in 0..result.lastIndex) {
result[i] = totalProduct / array[i]
}
return result.print()
}
}
fun main() {
val solutionWithDivision = MultiplicativeArrayWithDivision()
val solutionWithDoubleArrayApproach = MultiplicativeArrayWithDoubleArrayApproach()
listOf(solutionWithDivision, solutionWithDoubleArrayApproach)
.forEach {
withPrint(it.javaClass.simpleName) { it }
assertArraysSame(
expected = arrayOf(120, 40, 60, 30, 24),
actual = it.getMultiplicativeArray(arrayOf(1, 3, 2, 4, 5))
)
assertArraysSame(
expected = arrayOf(0, 0, 0, 0, 0, 120),
actual = it.getMultiplicativeArray(arrayOf(1, 3, 2, 4, 5, 0))
)
assertArraysSame(
expected = arrayOf(0, 0, 0, 0, 0, 0),
actual = it.getMultiplicativeArray(arrayOf(0, 3, 2, 4, 5, 0))
)
}
} | 4 | Kotlin | 5 | 93 | 22eef528ef1bea9b9831178b64ff2f5b1f61a51f | 3,860 | algorithms | MIT License |
src/Day20.kt | LauwiMeara | 572,498,129 | false | {"Kotlin": 109923} | import kotlin.math.abs
const val DECRYPTION_KEY = 811589153
fun main() {
fun createSequence(input: List<Int>, isPart2: Boolean = false): MutableList<Pair<Int, Long>> {
val sequence = mutableListOf<Pair<Int, Long>>()
for (i in input.indices) {
if (isPart2) {
sequence.add(Pair(i, input[i].toLong() * DECRYPTION_KEY))
} else {
sequence.add(Pair(i, input[i].toLong()))
}
}
return sequence
}
fun moveNumbers(sequence: MutableList<Pair<Int, Long>>): MutableList<Pair<Int, Long>> {
val sequenceSize = sequence.size
for (i in sequence.indices) {
val currentIndex = sequence.indexOfFirst{it.first == i}
val numberPair = sequence.removeAt(currentIndex)
var newIndex = currentIndex + numberPair.second
if (newIndex < 0) {
newIndex = (-(abs(newIndex) % (sequenceSize - 1)) + sequenceSize - 1) % (sequenceSize - 1)
} else if (newIndex >= sequenceSize) {
newIndex %= (sequenceSize - 1)
}
sequence.add(newIndex.toInt(), numberPair)
}
return sequence
}
fun getResult(sequence: List<Pair<Int, Long>>): Long {
val index0 = sequence.indexOfFirst{it.second == 0L}
val n1000 = sequence[(index0 + 1000) % sequence.size].second
val n2000 = sequence[(index0 + 2000) % sequence.size].second
val n3000 = sequence[(index0 + 3000) % sequence.size].second
return n1000 + n2000 + n3000
}
fun part1(input: List<Int>): Long {
var sequence = createSequence(input)
sequence = moveNumbers(sequence)
return getResult(sequence)
}
fun part2(input: List<Int>): Long {
var sequence = createSequence(input, true)
for (round in 0 until 10) {
sequence = moveNumbers(sequence)
}
return getResult(sequence)
}
val input = readInputAsInts("Day20")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 34b4d4fa7e562551cb892c272fe7ad406a28fb69 | 2,064 | AoC2022 | Apache License 2.0 |
src/Day01.kt | kecolk | 572,819,860 | false | {"Kotlin": 22071} | fun main() {
fun elvesCalories(input: List<Int?>): Collection<Int> {
return input
.scan(
Pair<Int, Int?>(
0,
0
)
) { acc, value -> Pair(if (value == null) acc.first + 1 else acc.first, value) }
.groupingBy { it.first }
.fold(0) { acc, element -> element.second?.let { acc + it } ?: acc }
.values
}
fun part1(input: List<Int?>): Int = elvesCalories(input).max()
fun part2(input: List<Int?>): Int =
elvesCalories(input).sorted().takeLast(3).sum()
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 72b3680a146d9d05be4ee209d5ba93ae46a5cb13 | 893 | kotlin_aoc_22 | Apache License 2.0 |
src/main/kotlin/util/Dijkstra.kt | Flame239 | 433,046,232 | false | {"Kotlin": 64209} | import java.util.*
class Edge(val v1: String, val v2: String, val dist: Int)
class Vertex(val name: String) : Comparable<Vertex> {
var dist = Int.MAX_VALUE // MAX_VALUE assumed to be infinity
var previous: Vertex? = null
val neighbours = HashMap<Vertex, Int>()
fun printPath() {
when (previous) {
this -> {
print(name)
}
null -> {
print("$name(unreached)")
}
else -> {
previous!!.printPath()
print(" -> $name($dist)")
}
}
}
override fun compareTo(other: Vertex): Int {
if (dist == other.dist) return name.compareTo(other.name)
return dist.compareTo(other.dist)
}
override fun toString() = "($name, $dist)"
}
class Graph(
val edges: List<Edge>,
val directed: Boolean,
val showAllPaths: Boolean = false
) {
private val graph = HashMap<String, Vertex>(edges.size)
init {
for (e in edges) {
if (!graph.containsKey(e.v1)) graph[e.v1] = Vertex(e.v1)
if (!graph.containsKey(e.v2)) graph[e.v2] = Vertex(e.v2)
}
for (e in edges) {
graph[e.v1]!!.neighbours[graph[e.v2]!!] = e.dist
if (!directed) graph[e.v2]!!.neighbours[graph[e.v1]!!] = e.dist
}
}
fun dijkstra(startName: String) {
if (!graph.containsKey(startName)) {
println("Graph doesn't contain start vertex '$startName'")
return
}
val source = graph[startName]
val q = TreeSet<Vertex>()
for (v in graph.values) {
v.previous = if (v == source) source else null
v.dist = if (v == source) 0 else Int.MAX_VALUE
q.add(v)
}
dijkstra(q)
}
private fun dijkstra(q: TreeSet<Vertex>) {
while (!q.isEmpty()) {
// vertex with shortest distance (first iteration will return source)
val u = q.pollFirst()!!
// if distance is infinite we can ignore 'u' (and any other remaining vertices)
// since they are unreachable
if (u.dist == Int.MAX_VALUE) break
//look at distances to each neighbour
for (a in u.neighbours) {
val v = a.key // the neighbour in this iteration
val alternateDist = u.dist + a.value
if (alternateDist < v.dist) { // shorter path to neighbour found
q.remove(v)
v.dist = alternateDist
v.previous = u
q.add(v)
}
}
}
}
fun getDistanceTo(endName: String) = graph[endName]!!.dist
fun printPath(endName: String) {
if (!graph.containsKey(endName)) {
println("Graph doesn't contain end vertex '$endName'")
return
}
print(if (directed) "Directed : " else "Undirected : ")
graph[endName]!!.printPath()
println()
if (showAllPaths) printAllPaths() else println()
}
private fun printAllPaths() {
for (v in graph.values) {
v.printPath()
println()
}
println()
}
}
| 0 | Kotlin | 0 | 0 | ef4b05d39d70a204be2433d203e11c7ebed04cec | 3,251 | advent-of-code-2021 | Apache License 2.0 |
src/nativeMain/kotlin/com.qiaoyuang.algorithm/round0/Questions60.kt | qiaoyuang | 100,944,213 | false | {"Kotlin": 338134} | package com.qiaoyuang.algorithm.round0
import kotlin.math.*
/**
* 求 n 个骰子的和的所有可能值出现的概率
*/
fun test60() {
printProbability1(6)
printProbability2(6)
}
const val MAX_VALUE = 6
// 基于递归
fun printProbability1(number: Int) {
if (number < 1) return
val array = IntArray(number) { 1 }
val sumArray = IntArray(MAX_VALUE * number - number + 1)
fun sum(): Int {
var sum = 0
array.forEach { sum += it }
return sum
}
fun printProbability(index: Int) {
if (index >= number) {
val sum = sum()
sumArray[sum - number]++
return
}
while (array[index] <= MAX_VALUE) {
printProbability(index + 1)
array[index]++
}
array[index] = 1
}
printProbability(0)
var sum = 0
sumArray.forEach { sum += it }
for (i in sumArray.indices)
println("和为:${i + number},概率为:${sumArray[i]}/$sum")
}
// 基于循环
fun printProbability2(number: Int) {
if (number < 1) return
val length = MAX_VALUE * number + 1
val probabilities = Array(2) { IntArray(length) }
var flag = 0
for (i in 1..MAX_VALUE)
probabilities[flag][i] = 1
for (k in 2..number) {
for (i in 0 until k)
probabilities[1 - flag][i] = 0
for (i in k until length) {
probabilities[1 - flag][i] = 0
var j = 1
while (j <= i && j <= MAX_VALUE) {
probabilities[1 - flag][i] += probabilities[flag][i - j]
j++
}
}
flag = 1 - flag
}
val total = MAX_VALUE.toFloat().pow(number.toFloat()).toInt()
for (i in number until length)
println("和为:$i,概率为:${probabilities[flag][i]}/$total")
}
| 0 | Kotlin | 3 | 6 | 66d94b4a8fa307020d515d4d5d54a77c0bab6c4f | 1,571 | Algorithm | Apache License 2.0 |
src/main/kotlin/adventofcode2022/solution/day_5.kt | dangerground | 579,293,233 | false | {"Kotlin": 51472} | package adventofcode2022.solution
import adventofcode2022.util.readDay
private const val DAY_NUM = 5
fun main() {
val stacks = mapOf(
1 to "DBJV",
2 to "PVBWRDF",
3 to "RGFLDCWQ",
4 to "WJPMLNDB",
5 to "HNBPCSQ",
6 to "RDBSNG",
7 to "ZBPMQFSH",
8 to "WLF",
9 to "SVFMR",
)
Day5(DAY_NUM.toString(), stacks, 10).solve()
}
class Day5(
private val num: String,
stacks: Map<Int, String>,
private val skipInput: Int,
) {
private val inputText = readDay(num)
private val stack = stacks.mapValues { ArrayDeque(it.value.asSequence().toList()) }
fun solve() {
println("Day $num Solution")
//println("* Part 1: ${solution1()}")
println("* Part 2: ${solution2()}")
}
fun solution1(): String {
inputText.lines().drop(skipInput).forEach {
val (move, from, to) = movements(it)
repeat(move) {
stack[from]!!.removeLast().let { pulled ->
stack[to]!!.addLast(pulled)
}
}
}
return stack.values.map { it.last() }.joinToString(separator = "") { it.toString() }
}
private fun movements(it: String): Triple<Int, Int, Int> {
val move = it.replace(Regex("^move (\\d+) from.*$"), "\$1").toInt()
val from = it.replace(Regex("^.*from (\\d+) to.*$"), "\$1").toInt()
val to = it.replace(Regex("^.* to (\\d+)$"), "\$1").toInt()
return Triple(move, from, to)
}
fun solution2(): String {
inputText.lines().drop(skipInput).forEach {
val (move, from, to) = movements(it)
IntRange(1, move)
.mapNotNull {
stack[from]!!.removeLast()
}
.reversed()
.forEach {
stack[to]!!.addLast(it)
}
}
return stack.values.map { it.last() }.joinToString(separator = "") { it.toString() }
}
} | 0 | Kotlin | 0 | 0 | f1094ba3ead165adaadce6cffd5f3e78d6505724 | 2,017 | adventofcode-2022 | MIT License |
src/Day20.kt | asm0dey | 572,860,747 | false | {"Kotlin": 61384} | fun main() {
class Container<T : Number>(val value: T)
fun <T : Number> ArrayDeque<Container<T>>.mix(containers: List<Container<T>>) {
for (cont in containers) {
val oldIndex = indexOf(cont)
removeAt(oldIndex)
val newIndex = oldIndex.toLong() + cont.value.toLong()
val newIndexWrapped =
if (newIndex > size) newIndex % size
else if (newIndex < 0) (newIndex % size + size) % size
else newIndex
add(newIndexWrapped.toInt(), cont)
}
}
fun part1(strings: List<String>): Int {
val all = strings.filterNot(String::isBlank).map(String::toInt).map(::Container)
val buf = ArrayDeque(all)
buf.mix(all)
val indexOf0 =
buf.mapIndexed(Int::to).single { (_, b) -> b.value == 0 }.first
val i1 = buf[(1000 + indexOf0) % buf.size].value
val i2 = buf[(2000 + indexOf0) % buf.size].value
val i3 = buf[(3000 + indexOf0) % buf.size].value
return i1 + i2 + i3
}
fun part2(strings: List<String>): Long {
val all = strings.filterNot(String::isBlank).map(String::toLong).map { it * 811589153 }.map(::Container)
val buf = ArrayDeque(all)
repeat(10) {
buf.mix(all)
}
val indexOf0 =
buf.mapIndexed(Int::to).single { (_, b) -> b.value == 0L }.first
val i1 = buf[(1000 + indexOf0) % buf.size].value
val i2 = buf[(2000 + indexOf0) % buf.size].value
val i3 = buf[(3000 + indexOf0) % buf.size].value
return i1 + i2 + i3
}
println(part1(readInput("Day20_test")))
println(part1(readInput("Day20")))
println(part2(readInput("Day20_test")))
println(part2(readInput("Day20")))
}
| 1 | Kotlin | 0 | 1 | f49aea1755c8b2d479d730d9653603421c355b60 | 1,789 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/endredeak/aoc2022/Day18.kt | edeak | 571,891,076 | false | {"Kotlin": 44975} | package endredeak.aoc2022
fun main() {
solve("Boiling Boulders") {
fun Triple<Int, Int, Int>.neighbours() = run {
val (x, y, z) = this
setOf(
Triple(0, 0, 1),
Triple(0, 1, 0),
Triple(1, 0, 0),
Triple(0, 0, -1),
Triple(0, -1, 0),
Triple(-1, 0, 0),
).map { (dx, dy, dz) ->
Triple(x + dx, y + dy, z + dz)
}.toSet()
}
val input = lines
.map { it.split(",") }
.map { Triple(it[0].toInt(), it[1].toInt(), it[2].toInt()) }
.toSet()
part1(4504) { (input.size * 6) - input.sumOf { it.neighbours().intersect(input.minus(it)).size } }
part2(2556) {
val (xRange, yRange, zRange) =
Triple(
input.minOf { it.first } - 1..input.maxOf { it.first } + 1,
input.minOf { it.second } - 1..input.maxOf { it.second } + 1,
input.minOf { it.third } - 1..input.maxOf { it.third } + 1
)
val queue = ArrayDeque<Triple<Int, Int, Int>>()
queue.add(Triple(xRange.first, yRange.first, zRange.first))
val seen = mutableSetOf<Triple<Int, Int, Int>>()
var found = 0
queue.forEach { next ->
if (next !in seen) {
next.neighbours()
.filter { it.first in xRange && it.second in yRange && it.third in zRange }
.forEach { neighbor ->
seen += next
if (neighbor in input) {
found++
} else {
queue.add(neighbor)
}
}
}
}
found
}
}
} | 0 | Kotlin | 0 | 0 | e0b95e35c98b15d2b479b28f8548d8c8ac457e3a | 1,936 | AdventOfCode2022 | Do What The F*ck You Want To Public License |
src/main/kotlin/aoc/year2023/Day16.kt | SackCastellon | 573,157,155 | false | {"Kotlin": 62581} | package aoc.year2023
import aoc.Puzzle
/**
* [Day 16 - Advent of Code 2023](https://adventofcode.com/2023/day/16)
*/
object Day16 : Puzzle<Int, Int> {
override fun solvePartOne(input: String): Int {
val layout = input.toLayout()
val beam = Beam(Point(0, 0), Direction.RIGHT)
return getEnergizedTiles(layout, beam)
}
override fun solvePartTwo(input: String): Int {
val layout = input.toLayout()
val (lastX, lastY) = input.lines().let { it.first().lastIndex to it.lastIndex }
return sequence {
// Top row
yieldAll((0..lastX).asSequence().map { x -> Beam(Point(x = x, y = 0), Direction.DOWN) })
// Bottom row
yieldAll((0..lastX).asSequence().map { x -> Beam(Point(x = x, y = lastY), Direction.UP) })
// Left-most column
yieldAll((0..lastY).asSequence().map { y -> Beam(Point(x = 0, y = y), Direction.RIGHT) })
// Right-most column
yieldAll((0..lastY).asSequence().map { y -> Beam(Point(x = lastX, y = y), Direction.LEFT) })
}.maxOf { beam -> getEnergizedTiles(layout, beam) }
}
private fun getEnergizedTiles(layout: Map<Point, Component>, start: Beam): Int {
val existingBeams = hashSetOf<Beam>()
fun doBounce(beam: Beam) {
if (beam in existingBeams) return
val component = layout[beam.point] ?: return
existingBeams.add(beam)
component.bounce(beam).forEach(::doBounce)
}
doBounce(start)
return existingBeams.map(Beam::point).distinct().count()
}
private fun String.toLayout(): Map<Point, Component> {
val lines = lines()
val components = hashMapOf<Point, Component>()
lines.forEachIndexed { y, line ->
line.forEachIndexed { x, symbol ->
val point = Point(x, y)
components[point] = Component.fromSymbol(symbol)
}
}
return components
}
private data class Point(val x: Int, val y: Int)
private enum class Direction {
UP, DOWN, LEFT, RIGHT,
}
private data class Beam(val point: Point, val direction: Direction)
private enum class Component(private val symbol: Char) {
EMPTY_SPACE('.') {
override fun bounce(beam: Beam): List<Beam> {
val direction = beam.direction
val point = beam.point
val nextPoint = when (direction) {
Direction.UP -> point.copy(y = point.y - 1)
Direction.DOWN -> point.copy(y = point.y + 1)
Direction.LEFT -> point.copy(x = point.x - 1)
Direction.RIGHT -> point.copy(x = point.x + 1)
}
return listOf(beam.copy(point = nextPoint))
}
},
MIRROR_UP('/') {
override fun bounce(beam: Beam): List<Beam> {
val direction = beam.direction
val point = beam.point
val nextBeam = when (direction) {
Direction.UP -> Beam(point.copy(x = point.x + 1), Direction.RIGHT)
Direction.DOWN -> Beam(point.copy(x = point.x - 1), Direction.LEFT)
Direction.LEFT -> Beam(point.copy(y = point.y + 1), Direction.DOWN)
Direction.RIGHT -> Beam(point.copy(y = point.y - 1), Direction.UP)
}
return listOf(nextBeam)
}
},
MIRROR_DOWN('\\') {
override fun bounce(beam: Beam): List<Beam> {
val direction = beam.direction
val point = beam.point
val nextBeam = when (direction) {
Direction.UP -> Beam(point.copy(x = point.x - 1), Direction.LEFT)
Direction.DOWN -> Beam(point.copy(x = point.x + 1), Direction.RIGHT)
Direction.LEFT -> Beam(point.copy(y = point.y - 1), Direction.UP)
Direction.RIGHT -> Beam(point.copy(y = point.y + 1), Direction.DOWN)
}
return listOf(nextBeam)
}
},
SPLITTER_VERTICAL('|') {
override fun bounce(beam: Beam): List<Beam> {
val direction = beam.direction
val point = beam.point
return when (direction) {
Direction.UP -> listOf(beam.copy(point = point.copy(y = point.y - 1)))
Direction.DOWN -> listOf(beam.copy(point = point.copy(y = point.y + 1)))
Direction.LEFT, Direction.RIGHT -> listOf(
Beam(point.copy(y = point.y - 1), Direction.UP),
Beam(point.copy(y = point.y + 1), Direction.DOWN)
)
}
}
},
SPLITTER_HORIZONTAL('-') {
override fun bounce(beam: Beam): List<Beam> {
val direction = beam.direction
val point = beam.point
return when (direction) {
Direction.LEFT -> listOf(beam.copy(point = point.copy(x = point.x - 1)))
Direction.RIGHT -> listOf(beam.copy(point = point.copy(x = point.x + 1)))
Direction.UP, Direction.DOWN -> listOf(
Beam(point.copy(x = point.x - 1), Direction.LEFT),
Beam(point.copy(x = point.x + 1), Direction.RIGHT)
)
}
}
};
abstract fun bounce(beam: Beam): List<Beam>
companion object {
private val cache = entries.associateBy { it.symbol }
fun fromSymbol(symbol: Char): Component = cache.getValue(symbol)
}
}
}
| 0 | Kotlin | 0 | 0 | 75b0430f14d62bb99c7251a642db61f3c6874a9e | 5,775 | advent-of-code | Apache License 2.0 |
src/day10/Solution.kt | abhabongse | 576,594,038 | false | {"Kotlin": 63915} | /* Solution to Day 10: Cathode-Ray Tube
* https://adventofcode.com/2022/day/10
*/
package day10
import utils.accumulate
import java.io.File
import kotlin.math.absoluteValue
fun main() {
val fileName =
// "day10_sample_a.txt"
// "day10_sample_b.txt"
"day10_input.txt"
val cpuInstructions = readInput(fileName)
// Part 1: signal strength during the 20th, 60th, 100th, 140th, 180th, and 220th cycles
val signalStrengthsByCycle = cpuInstructions
.asSequence()
.flatMap {
when (it) {
is CpuInstruction.Noop -> listOf(0)
is CpuInstruction.AddX -> listOf(0, it.value)
}
}
.accumulate(1, includeInitial = true) { acc, gradient -> acc + gradient }
.toList()
val p1SumSignalStrengths = listOf(20, 60, 100, 140, 180, 220).sumOf { it * signalStrengthsByCycle[it - 1] }
println("Part 1: $p1SumSignalStrengths")
// Part 2:
println("Part 2: (see below)")
signalStrengthsByCycle
.subList(0, 240)
.asSequence()
.chunked(40)
.forEach { list ->
list.withIndex()
.forEach { (pixelColumn, regX) ->
val char = if ((regX - pixelColumn).absoluteValue <= 1) {
'#'
} else {
'.'
}
print(char)
}
println()
}
}
/**
* Reads and parses input data according to the problem statement.
*/
fun readInput(fileName: String): List<CpuInstruction> {
return File("inputs", fileName)
.readLines()
.map { CpuInstruction from it }
}
| 0 | Kotlin | 0 | 0 | 8a0aaa3b3c8974f7dab1e0ad4874cd3c38fe12eb | 1,697 | aoc2022-kotlin | Apache License 2.0 |
solutions/aockt/y2015/Y2015D13.kt | Jadarma | 624,153,848 | false | {"Kotlin": 435090} | package aockt.y2015
import aockt.util.generatePermutations
import io.github.jadarma.aockt.core.Solution
object Y2015D13 : Solution {
private val inputRegex = Regex("""^(\w+) would (lose|gain) (\d+) happiness units by sitting next to (\w+).$""")
/**
* Parses a single line of input and returns a triple containing two people and the happiness difference applied if
* the first person stands next to the second.
*/
private fun parseInput(input: String): Triple<String, String, Int> {
val (personA, sign, amount, personB) = inputRegex.matchEntire(input)!!.destructured
val happiness = amount.toInt() * if (sign == "gain") 1 else -1
return Triple(personA, personB, happiness)
}
/**
* Given a list of happiness modifiers between all pairs of guests, returns all possible table arrangements and
* their total happiness modifier.
* If [includeApatheticSelf], includes an extra neutral person in the list.
*/
private fun bruteForceArrangement(
guestData: List<Triple<String, String, Int>>,
includeApatheticSelf: Boolean = false,
): Sequence<Pair<List<String>, Int>> {
val guests = mutableSetOf<String>()
val happinessScores = mutableMapOf<String, MutableMap<String, Int>>()
@Suppress("ReplacePutWithAssignment")
guestData.forEach { (guest, other, happiness) ->
guests.add(guest)
guests.add(other)
happinessScores
.getOrPut(guest) { mutableMapOf() }
.put(other, happiness)
}
if (includeApatheticSelf) {
happinessScores["Self"] = mutableMapOf()
guests.forEach { guest ->
happinessScores[guest]!!["Self"] = 0
happinessScores["Self"]!![guest] = 0
}
guests.add("Self")
}
return guests
.toList()
.generatePermutations()
.map { arrangement ->
arrangement to arrangement
.plusElement(arrangement.first())
.windowed(2)
.sumOf { happinessScores[it[0]]!![it[1]]!! + happinessScores[it[1]]!![it[0]]!! }
}
}
override fun partOne(input: String) =
input
.lines()
.map(this::parseInput)
.let(this::bruteForceArrangement)
.maxOf { it.second }
override fun partTwo(input: String) =
input
.lines()
.map(this::parseInput)
.let { this.bruteForceArrangement(it, includeApatheticSelf = true) }
.maxOf { it.second }
}
| 0 | Kotlin | 0 | 3 | 19773317d665dcb29c84e44fa1b35a6f6122a5fa | 2,659 | advent-of-code-kotlin-solutions | The Unlicense |
src/Day13.kt | MartinsCode | 572,817,581 | false | {"Kotlin": 77324} | enum class CompareResults {
LESS,
EQUAL,
GREATER
}
fun main() {
fun decompose(a: String): MutableList<String> {
val aList = mutableListOf<String>()
// parse the string
// since it's ment to be an array, remove outer brackets:
check(a[0] == '[')
check(a[a.lastIndex] == ']')
val text = a.substring(1, a.lastIndex)
// now: PARSE!
// can be [ or number
// if [ search for ] and add whole [...] to aList
// if number, parse to comma or end of string and add number to aList
var i = 0
println("Decomposing $a")
while (i < text.length) {
if (text[i] == '[') {
// beware of multiple layers!
var bracketLevel = 1
var j = i + 1
while (bracketLevel > 0) {
if (text[j] == '[')
bracketLevel++
if (text[j] == ']')
bracketLevel--
j++
}
aList.add(text.substring(i, j))
i = j
} else {
// parse until comma
var j = i + 1
while (j < text.length && text[j] != ',') {
j++
}
aList.add(text.substring(i, j))
i = j
}
i++
}
return aList
}
fun rightOrder(a: String, b: String): CompareResults {
// basic assumption
var rightOrder = CompareResults.EQUAL
// decompose strings to elements
val aList = decompose(a)
val bList = decompose(b)
val length = minOf(aList.size, bList.size)
var current = 0
while (rightOrder == CompareResults.EQUAL && current < length) {
// then compare sizes and iterate the shorter one
if (aList[current][0] == '[' || bList[current][0] == '[') {
var aStr = aList[current]
var bStr = bList[current]
if (aStr[0] != '[') {
aStr = "[$aStr]"
}
if (bStr[0] != '[') {
bStr = "[$bStr]"
}
rightOrder = rightOrder(aStr, bStr)
} else {
if (aList[current].toInt() > bList[current].toInt()) {
rightOrder = CompareResults.GREATER
} else if (aList[current].toInt() < bList[current].toInt()) {
rightOrder = CompareResults.LESS
}
}
current++
// compare each element according to rules
// if any element is in wrong order, break and return false
}
// so we compared 'em all and still are undecided. And now?
if (rightOrder == CompareResults.EQUAL) {
println("Decision because of length!")
// length decides. a has to be shorter than b for being true
rightOrder = when {
a.length < b.length -> CompareResults.LESS
a.length > b.length -> CompareResults.GREATER
else -> CompareResults.EQUAL
}
}
println("Compared $a to $b - rightOrder: $rightOrder")
return rightOrder
}
fun part1(input: List<String>): Int {
var counter = 0
var a = ""
var b = ""
var checksum = 0
var actPair = 1
input.forEach {
when {
it == "" -> {
println("Comparing $a and $b: rightOrder is ${rightOrder(a, b)}")
if (rightOrder(a, b) in listOf(CompareResults.LESS, CompareResults.EQUAL)) {
checksum += actPair
}
actPair++
}
counter == 0 -> a = it
counter == 1 -> b = it
}
counter = (counter + 1) % 3
}
// last pair has no empty line beneath, so trigge comparison manually
if (rightOrder(a, b) in listOf(CompareResults.LESS, CompareResults.EQUAL)) {
checksum += actPair
}
println(checksum)
return checksum
}
fun part2(input_: List<String>): Int {
// Sort lines according to above way of sorting
// For being a small set, we ignore all better sorting algorithms
val input = mutableListOf<String>("[[2]]", "[[6]]")
input_.forEach {
if (it != "") {
input.add(it)
}
}
val sorted = mutableListOf<String>()
while (input.size > 0) {
var min = input[0]
input.forEach {
if (rightOrder(min, it) == CompareResults.GREATER) {
min = it
}
}
input.remove(min)
sorted.add(min)
}
var index1 = 0
var index2 = 0
sorted.forEachIndexed { index, s ->
if (s == "[[2]]")
index1 = index + 1
if (s == "[[6]]")
index2 = index + 1
}
println(sorted.joinToString("\n"))
return index1 * index2
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day13-TestInput")
check(part1(testInput) == 13)
check(part2(testInput) == 140)
val input = readInput("Day13-Input")
check(part1(input) > 660)
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 1aedb69d80ae13553b913635fbf1df49c5ad58bd | 5,564 | AoC-2022-12-01 | Apache License 2.0 |
src/main/aoc2022/Day2.kt | nibarius | 154,152,607 | false | {"Kotlin": 963896} | package aoc2022
class Day2(input: List<String>) {
// Represent the shapes (and desired outcomes) as the numbers 0-2.
// rock -> paper -> scissors -> rock
// 0 -> 1 -> 2 -> 0
val parsedInput = input.map { line ->
line.split(" ").let { it.first().first() - 'A' to it.last().first() - 'X' }
}
/**
* Score one game given the opponent's and my shape.
*/
private fun scoreGame(opponent: Int, me: Int): Int {
return when {
opponent == me -> 3 // draw
(opponent + 1) % 3 == me -> 6 // one step ahead of opponent is a win
(opponent + 2) % 3 == me -> 0 // two steps ahead of opponent is a loss
else -> error("Impossible state")
}
}
/**
* Get the score for the given shape
*/
private fun Int.getShapeScore() = this + 1
/**
* Get the shape that results with the desired outcome given the opponents shape
*/
private fun getDesiredShape(opponent: Int, desiredOutcome: Int): Int {
return when (desiredOutcome) {
0 -> (opponent + 2) % 3 // two steps ahead of opponent is a loss
1 -> opponent
2 -> (opponent + 1) % 3 // one step ahead of opponent is a win
else -> error("Impossible state")
}
}
private fun calculateTotalScore(getOwnShape: (Int, Int) -> Int): Int {
return parsedInput.sumOf {
val myShape = getOwnShape(it.first, it.second)
scoreGame(it.first, myShape) + myShape.getShapeScore()
}
}
fun solvePart1(): Int {
// X, Y, Z represent the shape I should use
return calculateTotalScore { _, myShape -> myShape }
}
fun solvePart2(): Int {
// X, Y, Z represents the desired outcome
return calculateTotalScore { opponent, desiredResult -> getDesiredShape(opponent, desiredResult) }
}
} | 0 | Kotlin | 0 | 6 | f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22 | 1,908 | aoc | MIT License |
src/twentytwentytwo/day8/Day08.kt | colinmarsch | 571,723,956 | false | {"Kotlin": 65403, "Python": 6148} | package twentytwentytwo.day8
import readInput
fun main() {
fun part1(input: List<String>): Int {
val trees = mutableListOf<List<Int>>()
input.forEach { trees.add(it.chunked(1).map { it.toInt() }) }
var visibleTrees = trees.size * 4 - 4
for (i in 1 until trees.size - 1) {
for (j in 1 until trees[0].size - 1) {
if (isVisible(i, j, trees)) visibleTrees++
}
}
return visibleTrees
}
fun part2(input: List<String>): Int {
val trees = mutableListOf<List<Int>>()
input.forEach { trees.add(it.chunked(1).map { it.toInt() }) }
var maxScenicScore = 0
for (i in 1 until trees.size - 1) {
for (j in 1 until trees[0].size - 1) {
val currScore = scenicScore(i, j, trees)
if (currScore > maxScenicScore) {
maxScenicScore = currScore
}
}
}
return maxScenicScore
}
val input = readInput("day8", "Day08_input")
println(part1(input))
println(part2(input))
}
private fun isVisible(i: Int, j: Int, trees: List<List<Int>>): Boolean {
val height = trees[i][j]
var visible = true
for (q in 0 until i) {
if (trees[q][j] >= height) {
visible = false
break
}
}
if (visible) return true
visible = true
for (w in i + 1 until trees.size) {
if (trees[w][j] >= height) {
visible = false
break
}
}
if (visible) return true
visible = true
for (e in 0 until j) {
if (trees[i][e] >= height) {
visible = false
break
}
}
if (visible) return true
visible = true
for (r in j + 1 until trees.size) {
if (trees[i][r] >= height) {
visible = false
break
}
}
return visible
}
private fun scenicScore(i: Int, j: Int, trees: List<List<Int>>): Int {
val height = trees[i][j]
var totalScore = 1
var distance = 0
for (q in i - 1 downTo 0) {
distance++
if (trees[q][j] >= height) {
break
}
}
totalScore *= distance
distance = 0
for (w in i + 1 until trees.size) {
distance++
if (trees[w][j] >= height) {
break
}
}
totalScore *= distance
distance = 0
for (e in j - 1 downTo 0) {
distance++
if (trees[i][e] >= height) {
break
}
}
totalScore *= distance
distance = 0
for (r in j + 1 until trees.size) {
distance++
if (trees[i][r] >= height) {
break
}
}
totalScore *= distance
return totalScore
}
| 0 | Kotlin | 0 | 0 | bcd7a08494e6db8140478b5f0a5f26ac1585ad76 | 2,765 | advent-of-code | Apache License 2.0 |
puzzles/src/main/kotlin/com/kotlinground/puzzles/graph/reorderroutes/reorderRoutes.kt | BrianLusina | 113,182,832 | false | {"Kotlin": 483489, "Shell": 7283, "Python": 1725} | package com.kotlinground.puzzles.graph.reorderroutes
/**
* Reorders the edges of the directed graph represented as an adjacency list in connections such that each vertex
* is connected and has a path to the first vertex marked with 0. n represents the number of vertices.
*
* Complexity:
* n is the number of vertices/nodes
*
* Time Complexity: O(n)
* O(n) to initialize the adjacency list
* The dfs function visits each node once, which takes O(n) time in total. Because we have undirected edges,
* each edge can only be iterated twice (by nodes at the end), resulting in O(e) operations total while
* visiting all nodes, where e is the number of edges. Because the given graph is a tree, there are n−1
* undirected edges, so O(n+e)=O(n).
*
* Space Complexity: O(n)
* Building the adjacency list takes O(n) space.
* The recursion call stack used by dfs can have no more than n elements in the worst-case scenario.
* It would take up O(n) space in that case.
* @param n [Int] number of vertices or in this case, number of cities
* @param connections [Array] adjacency matrix for a directed graph or in this case, representation of cities
* @return [Int] minimum number of edges to re-arrange to ensure that each vertex is directly or indirectly connected to
* the initial vertex
*/
fun minReorder(n: Int, connections: Array<IntArray>): Int {
var count = 0
// Adjacency list that contains list of pairs of nodes such that adj[node] contains all the neighbours of node in the
// form of [neighbour, sign] where neighbour is the neighbouring node and sign is the direction of the edge. If the
// sign is 0, it's an 'artificial' edge, meaning it was added by the algorithm in order to get to this vertex, and 1
// denotes that it's an 'original' edge, meaning that it's the original edge and no need to re-order that connection
val adj = HashMap<Int, MutableList<List<Int>>>()
for (connection in connections) {
adj.computeIfAbsent(connection[0]) { ArrayList() }.add(listOf(connection[1], 1))
adj.computeIfAbsent(connection[1]) { ArrayList() }.add(listOf(connection[0], 0))
}
fun dfs(node: Int, parent: Int, adj: Map<Int, MutableList<List<Int>>>) {
if (!adj.containsKey(node)) {
return
}
// iterate over all children of node(nodes that share an edge)
// for every child, sign, check if child is equal to parent. if child is equal to parent, we will not visit it
// again
// if child is not equal to parent, we perform count+=sign and recursively call the dfs with node = child and
// parent = node
for (nei in adj[node]!!) {
val child = nei[0]
val sign = nei[1]
if (child != parent) {
count += sign
dfs(child, node, adj)
}
}
}
dfs(0, -1, adj)
return count
}
| 1 | Kotlin | 1 | 0 | 5e3e45b84176ea2d9eb36f4f625de89d8685e000 | 2,945 | KotlinGround | MIT License |
src/Day08.kt | fouksf | 572,530,146 | false | {"Kotlin": 43124} | import java.io.File
import java.util.Arrays
import java.util.Deque
fun main() {
fun generateTallnessMapLeft(forest: List<List<Int>>): List<List<Int>> {
val tallnessMap = ArrayList<MutableList<Int>>()
for (i in forest.indices) {
tallnessMap.add(mutableListOf())
for (j in forest[i].indices) {
tallnessMap[i].add(j, if (j > 0) forest[i].subList(0, j).max() else 0)
}
}
return tallnessMap
}
fun generateTallnessMapRight(forest: List<List<Int>>): List<List<Int>> {
val tallnessMap = ArrayList<MutableList<Int>>()
for (i in forest.indices) {
tallnessMap.add(mutableListOf())
for (j in forest[i].indices) {
tallnessMap[i].add(j, if (j < forest[i].size - 1) forest[i].subList(j + 1, forest[i].size).max() else 0)
}
}
return tallnessMap
}
fun generateTallnessMapDown(forest: List<List<Int>>): List<List<Int>> {
val tallnessMap = ArrayList<MutableList<Int>>()
for (i in forest.indices) {
tallnessMap.add(mutableListOf())
for (j in forest[i].indices) {
tallnessMap[i].add(j, if (i > 0) forest.map { it[j] }.subList(0, i).max() else 0)
}
}
return tallnessMap
}
fun generateTallnessMapUp(forest: List<List<Int>>): List<List<Int>> {
val tallnessMap = ArrayList<MutableList<Int>>()
for (i in forest.indices) {
tallnessMap.add(mutableListOf())
for (j in forest[i].indices) {
tallnessMap[i].add(j, if (i < forest.size - 1) forest.map { it[j] }.subList(i + 1, forest[i].size).max() else 0)
}
}
return tallnessMap
}
fun part1(input: List<String>): Int {
val forest = input.map { line -> line.split("").filter { it.isNotBlank() }.map { it.toInt() }}
val tallnessMapLeft = generateTallnessMapLeft(forest)
val tallnessMapRight = generateTallnessMapRight(forest)
val tallnessMapUp = generateTallnessMapUp(forest)
val tallnessMapDown = generateTallnessMapDown(forest)
var count = 0
for (i in 1 until forest.size - 1) {
for (j in 1 until forest[i].size - 1) {
if (forest[i][j] > tallnessMapDown[i][j] ||
forest[i][j] > tallnessMapUp[i][j] ||
forest[i][j] > tallnessMapRight[i][j] ||
forest[i][j] > tallnessMapLeft[i][j] ) {
count++
print("y")
} else {
print(" ")
}
}
println()
}
return count + forest.size * 2 + forest[0].size * 2 - 4
}
fun calculateScenicScore(x: Int, y: Int, forest: List<List<Int>>): Int {
var score = 1
var currentCount = 0
//up
for (i in x - 1 downTo 0) {
if (forest[x][y] > forest[i][y]) {
currentCount++
} else {
currentCount++
break
}
}
score *= currentCount
//down
currentCount = 0
for (i in x + 1 until forest.size) {
if (forest[x][y] > forest[i][y]) {
currentCount++
} else {
currentCount++
break
}
}
score *= currentCount
//left
currentCount = 0
for (j in y - 1 downTo 0) {
if (forest[x][y] > forest[x][j]) {
currentCount++
} else {
currentCount++
break
}
}
score *= currentCount
//right
currentCount = 0
for (j in y + 1 until forest[0].size) {
if (forest[x][y] > forest[x][j]) {
currentCount++
} else {
currentCount++
break
}
}
score *= currentCount
return score
}
fun part2(input: List<String>): Int {
val forest = input.map { line -> line.split("").filter { it.isNotBlank() }.map { it.toInt() }}
println(calculateScenicScore(3, 2, forest))
var max = 0
for (i in 1 until forest.size - 1) {
for (j in 1 until forest[i].size - 1) {
val score = calculateScenicScore(i, j , forest)
max = if (score > max) score else max
}
}
return max
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day08_test")
// println(part1(testInput))
println(part2(testInput))
val input = readInput("Day08")
// println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 701bae4d350353e2c49845adcd5087f8f5409307 | 4,809 | advent-of-code-2022 | Apache License 2.0 |
src/y2022/day10.kt | sapuglha | 573,238,440 | false | {"Kotlin": 33695} | package y2022
import readFileAsLines
import kotlin.text.StringBuilder
fun main() {
fun part1(input: List<String>): Int {
val cycleOfInterest = listOf(20, 60, 100, 140, 180, 220)
var cycle = 0
var signal = 1
val collectedSignals = mutableListOf<Int>()
fun computeCycle() {
cycle++
if (cycle in cycleOfInterest) {
collectedSignals.add(signal * cycle)
}
}
input.forEach { line ->
val command = if (line.length > 4) line.substringBefore(" ") else "noop"
val amount = if (line.length > 4) line.substringAfter(" ").toInt() else 0
if (command == "noop") {
computeCycle()
}
if (command == "addx") {
computeCycle()
computeCycle()
signal += amount
}
}
return collectedSignals.sumOf { it }
}
fun part2(input: List<String>): Int {
val cycleOfInterest = listOf(40, 80, 120, 160, 200, 240)
var cycle = 0
var drawingLine = StringBuilder()
var spritePosition = 1
fun getDrawingChar(): String =
if (drawingLine.length - 1 == spritePosition || drawingLine.length == spritePosition || drawingLine.length + 1 == spritePosition) "#" else "."
fun computeCycle() {
drawingLine.append(getDrawingChar())
cycle++
if (cycle in cycleOfInterest) {
println(drawingLine)
drawingLine = StringBuilder()
}
}
input.forEach { line ->
val command = if (line.length > 4) line.substringBefore(" ") else "noop"
val amount = if (line.length > 4) line.substringAfter(" ").toInt() else 0
if (command == "noop") {
computeCycle()
}
if (command == "addx") {
computeCycle()
computeCycle()
spritePosition += amount
}
}
return 1
}
"y2022/data/day10_test".readFileAsLines().let {
check(part1(it) == 13140)
check(part2(it) == 1)
}
"y2022/data/day10".readFileAsLines().let { input ->
println("part1: ${part1(input)}")
println("part2: ${part2(input)}")
}
}
| 0 | Kotlin | 0 | 0 | 82a96ccc8dcf38ae4974e6726e27ddcc164e4b54 | 2,352 | adventOfCode2022 | Apache License 2.0 |
src/main/kotlin/com/sk/set16/1685. Sum of Absolute Differences in a Sorted Array.kt | sandeep549 | 262,513,267 | false | {"Kotlin": 530613} | package com.sk.set16
class Solution1685 {
/**
* res[i] = (nums[i] - nums[0]) + (nums[i] - nums[1]) + ... + (nums[i] - nums[i - 1]) <--- absolute difference of nums[i] with first i numbers
* + (nums[i] - nums[i]) + (nums[i + 1] - nums[i]) + (nums[i + 2] - nums[i]) + ... + (nums[n - 1] - nums[i]) <--- absolute difference of nums[i] with last n - i numbers
*
* after simplification:
*
* res[i] = i * nums[i] - (nums[0] + ... + nums[i - 1]) <--- absolute difference of nums[i] with first i numbers
* + (nums[i + 1] + ... + nums[n]) - (n - i) * nums[i] <--- absolute difference of nums[i] with last n - i numbers
*
*after simplification:
*
* res[i] = i * nums[i] - prefixSum[i]
* + prefixSum[n] - prefixSum[i] - (n - i) * nums[i]
*/
fun getSumAbsoluteDifferences(nums: IntArray): IntArray {
val n = nums.size
val prefixSum = IntArray(n + 1)
for (i in 0 until n) {
prefixSum[i + 1] = prefixSum[i] + nums[i]
}
val res = IntArray(n)
for (i in 0 until n) {
res[i] = i * nums[i] - prefixSum[i] + (prefixSum[n] - prefixSum[i] - (n - i) * nums[i])
}
return res
}
fun getSumAbsoluteDifferences2(nums: IntArray): IntArray {
val n = nums.size
var leftSum = 0
var rightSum = nums.sum()
val res = IntArray(n)
for (i in 0 until n) {
res[i] = i * nums[i] - leftSum + rightSum - (n - i) * nums[i]
leftSum += nums[i]
rightSum -= nums[i]
}
return res
}
} | 1 | Kotlin | 0 | 0 | cf357cdaaab2609de64a0e8ee9d9b5168c69ac12 | 1,636 | leetcode-kotlin | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.