path
stringlengths
5
169
owner
stringlengths
2
34
repo_id
int64
1.49M
755M
is_fork
bool
2 classes
languages_distribution
stringlengths
16
1.68k
content
stringlengths
446
72k
issues
float64
0
1.84k
main_language
stringclasses
37 values
forks
int64
0
5.77k
stars
int64
0
46.8k
commit_sha
stringlengths
40
40
size
int64
446
72.6k
name
stringlengths
2
64
license
stringclasses
15 values
src/Day10.kt
jstapels
572,982,488
false
{"Kotlin": 74335}
sealed class Instruction(private val cycles: Int) { abstract fun apply(reg: Int): Int fun expanded(): List<Instruction> = ((1 until cycles).map { NoOp() }) + this } class NoOp: Instruction(1) { override fun apply(reg: Int) = reg } class AddX(private val arg: Int): Instruction(2) { override fun apply(reg: Int) = reg + arg } fun main() { fun execute(cmds: List<Instruction>, reg: Int = 1) = cmds.scan(reg) { r, c -> c.apply(r) } .toList() fun parseCmd(line: String) = when { line.startsWith("noop") -> NoOp() line.startsWith("addx") -> AddX(line.split(" ")[1].toInt()) else -> throw IllegalArgumentException("unexpected: $line") }.expanded() fun parseInput(input: List<String>) = input.flatMap { parseCmd(it) } fun part1(input: List<String>): Int { return execute(parseInput(input)) .withIndex() .fold(0) { sum, (i, v) -> if ((i + 21) % 40 == 0) sum + ((i + 1) * v) else sum } } fun printLcd(sprite: List<Int>) { sprite.withIndex() .forEach { (cycle, s) -> val pixel = cycle % 40 print(if ((pixel - s) in (-1..1)) "#" else ".") if (pixel == 39) println() } println() } fun part2(input: List<String>): Int { val out = execute(parseInput(input)) printLcd(out) return 1 } // test if implementation meets criteria from the description, like: val testInput = readInput("Day10_test") checkThat(part1(testInput), 13140) checkThat(part2(testInput), 1) val input = readInput("Day10") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
0d71521039231c996e2c4e2d410960d34270e876
1,724
aoc22
Apache License 2.0
src/main/kotlin/day05/day05.kt
corneil
572,437,852
false
{"Kotlin": 93311, "Shell": 595}
package day05 import main.utils.Stack import utils.readFileGroup import utils.readLinesGroup data class Instruction(val count: Int, val from: Int, val to: Int) fun main() { fun readStack(lines: List<String>, stack: Int): Stack<Char> { val result = mutableListOf<Char>() val offset = stack * 4 + 1 for (line in lines) { if (line.length > offset) { val crate = line[offset] if (crate in 'A'..'Z') { result.add(crate) } } } result.reverse() println("Stack[${stack + 1}]=${result.joinToString("")}") return Stack(result) } fun loadStacks(input: List<String>): List<Stack<Char>> { val lines = input.toMutableList() val numbers = lines.last().split(" ").mapNotNull { if(it.isNotBlank()) it.toInt() else null } lines.removeAt(lines.lastIndex) val stacks = mutableListOf<Stack<Char>>() for (stack in numbers.indices) { stacks.add(readStack(lines, stack)) } return stacks.toList() } fun loadInstructions(input: List<String>): List<Instruction> { val regex = """move (\d+) from (\d+) to (\d+)""".toRegex() return input.mapNotNull { line -> regex.find(line)?.let { val (count, from, to) = it.destructured Instruction(count.toInt(), from.toInt(), to.toInt()) } } } fun perform(stacks: List<Stack<Char>>, instruction: Instruction) { for (i in 1..instruction.count) { val crate = stacks[instruction.from - 1].pop() stacks[instruction.to - 1].push(crate) } } fun perform9001(stacks: List<Stack<Char>>, instruction: Instruction) { val tmp = Stack<Char>() for (i in 1..instruction.count) { val crate = stacks[instruction.from - 1].pop() tmp.push(crate) } while (!tmp.empty()) { stacks[instruction.to - 1].push(tmp.pop()) } } fun performAndFindTops(stacks: List<Stack<Char>>, instructions: List<Instruction>): String { instructions.forEach { perform(stacks, it) } stacks.forEach { stack -> println("[${stack.items().joinToString("")}]") } return stacks.joinToString("") { it.peek().toString() } } fun performAndFindTops9001(stacks: List<Stack<Char>>, instructions: List<Instruction>): String { instructions.forEach { perform9001(stacks, it) } stacks.forEach { stack -> println("[${stack.items().joinToString("")}]") } return stacks.joinToString("") { it.peek().toString() } } val test = """ [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 testInputs = readLinesGroup(test) val input = readFileGroup("day05") fun part1() { val testTops = performAndFindTops(loadStacks(testInputs[0]), loadInstructions(testInputs[1])) println("Part 1 Test Tops = $testTops") check(testTops == "CMZ") val tops = performAndFindTops(loadStacks(input[0]), loadInstructions(input[1])) println("Part 1 Tops = $tops") check(tops == "PTWLTDSJV") } fun part2() { val testTops = performAndFindTops9001(loadStacks(testInputs[0]), loadInstructions(testInputs[1])) println("Part 2 Test Tops = $testTops") check(testTops == "MCD") val tops = performAndFindTops9001(loadStacks(input[0]), loadInstructions(input[1])) println("Part 2 Tops = $tops") check(tops == "WZMFVGGZP") } println("Day - 05") part1() part2() }
0
Kotlin
0
0
dd79aed1ecc65654cdaa9bc419d44043aee244b2
3,396
aoc-2022-in-kotlin
Apache License 2.0
src/Day07.kt
Advice-Dog
436,116,275
true
{"Kotlin": 25836}
import kotlin.math.abs fun main() { fun part1(input: List<String>): Int { val positions = input.first().split(",").map { it.toInt() } val min = positions.minOf { it } val max = positions.maxOf { it } var best = -1 for (target in min..max) { val sum = positions.sumOf { abs(target - it) } if (sum < best || best == -1) best = sum } return best } fun part2(input: List<String>): Int { val positions = input.first().split(",").map { it.toInt() } val min = positions.minOf { it } val max = positions.maxOf { it } var best = -1 for (target in min..max) { val sum = positions.sumOf { getFuelCost(abs(target - it)) } if (sum < best || best == -1) best = sum } return best } // test if implementation meets criteria from the description, like: val testInput = getTestData("Day07") check(part1(testInput) == 37) check(part2(testInput) == 168) val input = getData("Day07") println(part1(input)) println(part2(input)) } fun getFuelCost(distance: Int): Int { var temp = 0 for (index in 1..distance) { temp += index } return temp }
0
Kotlin
0
0
2a2a4767e7f0976dba548d039be148074dce85ce
1,291
advent-of-code-kotlin-template
Apache License 2.0
src/main/kotlin/dev/bogwalk/batch2/Problem24.kt
bog-walk
381,459,475
false
null
package dev.bogwalk.batch2 import dev.bogwalk.util.maths.factorial /** * Problem 24: Lexicographic Permutations * * https://projecteuler.net/problem=24 * * Goal: Return the Nth lexicographic permutation of "abcdefghijklm". * * Constraints: 1 <= N <= 13! * * Lexicographic Permutation: The alphabetically/numerically ordered arrangements of an object. * e.g. "abc" -> {"abc", "acb", "bac", "bca", "cab", "cba"} * * e.g.: N = 1 -> "abcdefghijklm" * N = 2 -> "abcdefghijkml" */ class LexicographicPermutations { /** * Recursive solution uses factorial (permutations without repetition) to calculate the next * character in the permutation based on batch position. * * e.g. "abcd" has 4! = 24 permutations & each letter will have 6 permutations in which that * letter will be the 1st in the order. If n = 13, this permutation will be in batch 2 * (starts with "c") at position 1 (both 0-indexed). So "c" is removed and n = 1 is used with * the new string "abd". This continues until n = 0 and "cabd" is returned by the base case. * * SPEED (EQUAL) 5.5e5ns for 10-digit string * * @param [n] the nth permutation requested should be zero-indexed. * @param [input] the object to generate permutations of should be already sorted in * ascending order. */ fun lexicographicPerm( n: Long, input: String, permutation: String = "" ): String { return if (n == 0L) { permutation + input } else { val batchSize = (input.length).factorial().toLong() / input.length val i = (n / batchSize).toInt() lexicographicPerm( n % batchSize, input.removeRange(i..i), permutation + input[i] ) } } /** * Recursive solution above is altered by removing the unnecessary creation of a storage * string to pass into every recursive call, as well as reducing the factorial call, since * x! / x = (x - 1)! * * SPEED (EQUAL) 7.7e5ns for 10-digit string * * @param [n] the nth permutation requested should be zero-indexed. * @param [input] the object to generate permutations of should be already sorted in * ascending order. */ fun lexicographicPermImproved(n: Long, input: String): String { return if (input.length == 1) { input } else { val batchSize = (input.length - 1).factorial().toLong() val i = (n / batchSize).toInt() input[i] + lexicographicPermImproved( n % batchSize, input.removeRange(i..i) ) } } }
0
Kotlin
0
0
62b33367e3d1e15f7ea872d151c3512f8c606ce7
2,703
project-euler-kotlin
MIT License
src/aoc2017/kot/Day20.kt
Tandrial
47,354,790
false
null
package aoc2017.kot import getNumbers import java.io.File object Day20 { data class Vec3d(var x: Int, var y: Int, var z: Int) { operator fun plus(other: Vec3d) = Vec3d(this.x + other.x, this.y + other.y, this.z + other.z) } class Particle(val id: Int, s: String) { val values = s.getNumbers() var pos = Vec3d(values[0], values[1], values[2]) var vel = Vec3d(values[3], values[4], values[5]) val acc = Vec3d(values[6], values[7], values[8]) } fun partOne(input: List<String>): Int { val particles = input.mapIndexed { index, s -> Particle(index, s) } repeat(1000) { particles.forEach { it.vel += it.acc it.pos += it.vel } } return particles.sortedBy { Math.abs(it.pos.x) + Math.abs(it.pos.y) + Math.abs(it.pos.z) }.first().id } fun partTwo(input: List<String>): Int { val particles = input.mapIndexed { index, s -> Particle(index, s) }.toMutableList() repeat(1000) { particles.forEach { it.vel += it.acc it.pos += it.vel } // We're grouping by position, and remove everything in groups with size > 1 particles.groupBy { it.pos }.values.filter { it.size > 1 }.forEach { particles.removeAll(it) } } return particles.size } } fun main(args: Array<String>) { val input = File("./input/2017/Day20_input.txt").readLines() println("Part One = ${Day20.partOne(input)}") println("Part Two = ${Day20.partTwo(input)}") }
0
Kotlin
1
1
9294b2cbbb13944d586449f6a20d49f03391991e
1,457
Advent_of_Code
MIT License
src/main/kotlin/be/swsb/aoc2021/day10/Day10.kt
Sch3lp
433,542,959
false
{"Kotlin": 90751}
package be.swsb.aoc2021.day10 import be.swsb.aoc2021.day10.SyntaxError.AutoCompletion import be.swsb.aoc2021.day10.SyntaxError.Corruption object Day10 { fun solve1(input: List<String>): Int { return input.mapNotNull { it.compile() }.filterIsInstance<Corruption>() .sumOf { corruption -> corruption.penaltyPoints } } fun solve2(input: List<String>): Long { val autoCompletionPoints = input.mapNotNull { it.compile() } .filterIsInstance<AutoCompletion>() .map { it.points } .sorted() return autoCompletionPoints[autoCompletionPoints.size / 2] } } fun String.compile(): SyntaxError? { val openings = "({[<" val closings = ")}]>" val expected = mutableListOf<Char>() forEach { c -> if (c in openings) { expected += closings[openings.indexOf(c)] } else { if (c != expected.last()) { return Corruption(expected.last(), c) } else { expected.removeLast() } } } return if (expected.isNotEmpty()) { AutoCompletion(expected.joinToString("").reversed()) } else { null } } sealed class SyntaxError { data class Corruption(val expected: Char, val actual: Char) : SyntaxError() { val penaltyPoints: Int get() = when (actual) { ')' -> 3 ']' -> 57 '}' -> 1197 '>' -> 25137 else -> 0 } } data class AutoCompletion(val missingClosings: String) : SyntaxError() { val points: Long get() = missingClosings.fold(0) { acc, c -> (acc * 5) + pointsTable[c]!! } private val pointsTable = mapOf( ')' to 1, ']' to 2, '}' to 3, '>' to 4, ) } }
0
Kotlin
0
0
7662b3861ca53214e3e3a77c1af7b7c049f81f44
1,874
Advent-of-Code-2021
MIT License
y2016/src/main/kotlin/adventofcode/y2016/Day02.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2016 import adventofcode.io.AdventSolution import adventofcode.util.vector.Direction import adventofcode.util.vector.Vec2 import java.lang.IllegalArgumentException object Day02 : AdventSolution(2016, 2, "Bathroom Security") { override fun solvePartOne(input: String): String { val squarePad = """ 123 456 789 """ val map = convertToPad(squarePad) val initial = map.firstNotNullOf { (p, ch) -> p.takeIf { ch == "5" } } return solve(input, map, initial) } override fun solvePartTwo(input: String): String { val diamondPad = """ 1 234 56789 ABC D """ val map = convertToPad(diamondPad) val initial = map.firstNotNullOf { (p, ch) -> p.takeIf { ch == "5" } } return solve(input, map, initial) } } private fun solve(input: String, pad: Map<Vec2, String>, initial: Vec2) = input .lineSequence() .scan(initial) { startingButton, instructionLine -> instructionLine.map(Char::toDirection).fold(startingButton) { pos, instr -> (pos + instr).takeIf { it in pad.keys } ?: pos } } .drop(1) .joinToString("", transform = pad::getValue) private fun Char.toDirection(): Vec2 = when (this) { 'U' -> Direction.UP 'D' -> Direction.DOWN 'L' -> Direction.LEFT 'R' -> Direction.RIGHT else -> throw IllegalArgumentException() }.vector private fun convertToPad(input: String) = buildMap { input.lines().forEachIndexed { y, line -> line.forEachIndexed { x, ch -> if (ch.isLetterOrDigit()) put(Vec2(x, y), ch.toString()) } } }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
1,666
advent-of-code
MIT License
src/Day07.kt
Kietyo
573,293,671
false
{"Kotlin": 147083}
import kotlin.math.min sealed class Node { data class DirectoryNode( val parentDirectoryNode: DirectoryNode?, val directoryName: String, // Directory Name -> Directory Node val folderNodes: MutableMap<String, DirectoryNode> = mutableMapOf(), // File Name -> File Node val fileNodes: MutableMap<String, FileNode> = mutableMapOf() ) : Node() { fun calculatePart1(): Long { val myTotalSize = totalSize() val childTotalSizes = folderNodes.asSequence().sumOf { it.value.calculatePart1() } return childTotalSizes + if (myTotalSize <= 100000) myTotalSize else 0 } fun totalSize(): Long { return fileNodes.asSequence().sumOf { it.value.fileSize } + folderNodes.asSequence().sumOf { it.value.totalSize() } } fun print(currLevel: Int) { val indentationStr = "\t".repeat(currLevel) val fileIndentationStr = "\t".repeat(currLevel + 1) println("$indentationStr- Folder: $directoryName (totalSize=${totalSize()})") folderNodes.forEach { it.value.print(currLevel + 1) } fileNodes.forEach { println("$fileIndentationStr- File: ${it.value}") } } val totalSpaceAvailable = 70000000 val wantedUnusedSpace = 30000000 fun calculatePart2(totalUsed: Long, minDirectorySizeToRemove: Long): Long { var newMin = minDirectorySizeToRemove val thisTotalSize = totalSize() val availableSpaceIfRemoved = (totalSpaceAvailable - (totalUsed - thisTotalSize)) if (availableSpaceIfRemoved >= wantedUnusedSpace) { newMin = min(thisTotalSize, minDirectorySizeToRemove) } if (folderNodes.isEmpty()) return newMin return folderNodes.asSequence().minOf { it.value.calculatePart2(totalUsed, newMin) } } } data class FileNode( val fileName: String, val fileSize: Long ) : Node() { } } fun main() { fun parseRootNode(lines: List<String>): Node.DirectoryNode { val rootNode = Node.DirectoryNode(null, "root") var currNode = rootNode val itr = lines.listIterator() while (itr.hasNext()) { val it = itr.next() println(it) when { it.startsWith("$") -> { val split = it.split(" ") val cmd = split[1] when (cmd) { "cd" -> { val input = split[2] if (input == "/") { currNode = rootNode } else if (input == "..") { currNode = currNode.parentDirectoryNode!! } else { currNode = currNode.folderNodes[input]!! } } "ls" -> { while (itr.hasNext()) { val line = itr.next() when { line.startsWith("$") -> { itr.previous() break } line.startsWith("dir") -> { val (_, dirName) = line.split(" ") require(!currNode.folderNodes.containsKey(dirName)) currNode.folderNodes.putIfAbsent( dirName, Node.DirectoryNode(currNode, dirName) ) } else -> { // This is a file node val (fileSize, fileName) = line.split(" ") require(!currNode.fileNodes.containsKey(fileName)) currNode.fileNodes.putIfAbsent(fileName, Node.FileNode(fileName, fileSize.toLong())) } } if (line.startsWith("$")) { itr.previous() break } } } else -> TODO("Unsupported cmd: $cmd") } } else -> TODO() } } rootNode.print(0) return rootNode } fun part1(lines: List<String>): Unit { val rootNode = parseRootNode(lines) println(rootNode.calculatePart1()) } fun part2(lines: List<String>): Unit { val rootNode = parseRootNode(lines) val totalSize = rootNode.totalSize() println(rootNode.calculatePart2(totalSize, totalSize)) } val dayString = "day7" // test if implementation meets criteria from the description, like: val testInput = readInput("${dayString}_test") // part1(testInput) // part2(testInput) val input = readInput("${dayString}_input") // part1(input) part2(input) }
0
Kotlin
0
0
dd5deef8fa48011aeb3834efec9a0a1826328f2e
5,627
advent-of-code-2022-kietyo
Apache License 2.0
src/day6/Code.kt
fcolasuonno
162,470,286
false
null
package day6 import java.io.File import kotlin.math.max fun main(args: Array<String>) { val name = if (false) "test.txt" else "input.txt" val dir = ::main::class.java.`package`.name val input = File("src/$dir/$name").readLines() val parsed = parse(input) println("Part 1 = ${part1(parsed)}") println("Part 2 = ${part2(parsed)}") } enum class Action { ON, TOGGLE, OFF } data class Instruction(val action: Action, val x1: Int, val y1: Int, val x2: Int, val y2: Int) private val lineStructure = """(.*) (\d+),(\d+) through (\d+),(\d+)""".toRegex() fun parse(input: List<String>) = input.map { lineStructure.matchEntire(it)?.destructured?.let { val (action, x1, y1, x2, y2) = it Instruction( when (action) { "turn on" -> Action.ON "toggle" -> Action.TOGGLE "turn off" -> Action.OFF else -> throw IllegalStateException() }, x1.toInt(), y1.toInt(), x2.toInt(), y2.toInt() ) } }.requireNoNulls() fun part1(input: List<Instruction>): Int { val grid = List(1000) { MutableList(1000) { false } } input.forEach { for (y in it.y1..it.y2) { for (x in it.x1..it.x2) { grid[x][y] = when (it.action) { Action.ON -> true Action.TOGGLE -> !grid[x][y] Action.OFF -> false } } } } return grid.sumBy { it.count { it == true } } } fun part2(input: List<Instruction>): Int { val grid = List(1000) { MutableList(1000) { 0 } } input.forEach { for (y in it.y1..it.y2) { for (x in it.x1..it.x2) { val currentVal = grid[x][y] grid[x][y] = when (it.action) { Action.ON -> currentVal + 1 Action.TOGGLE -> currentVal + 2 Action.OFF -> max(currentVal - 1, 0) } } } } return grid.sumBy { it.sum() } }
0
Kotlin
0
0
24f54bf7be4b5d2a91a82a6998f633f353b2afb6
2,067
AOC2015
MIT License
day-02-kotlin/src/Main.kt
jakoberzar
159,959,049
false
{"JavaScript": 23733, "TypeScript": 11163, "Scala": 8193, "Rust": 7557, "Kotlin": 4451, "C#": 4250, "HTML": 2059}
import java.io.File fun main(args: Array<String>) { val input = getInput() star1(input) star2(input) } fun star1(input: List<String>) { val frequencies = input.map { countLetters(it) } val have2 = frequencies.filter { it.contains(2) }.count() val have3 = frequencies.filter { it.contains(3) }.count() println(have2 * have3) } fun getInput(): List<String> { return File("input.txt").readLines() } fun countLetters(word: String): Collection<Int> { val map = HashMap<Char, Int>() for (char in word) { val current = map.getOrElse(char) { 0 } map.put(char, current + 1) } return map.values } fun star2(input: List<String>) { val pair = getPair(input) val sameLetters = getSameLetters(pair.first, pair.second) println(sameLetters) } fun compareWords(first: String, second: String): Boolean { return first.zip(second) .filter { it.first != it.second } .count() == 1 } fun getPair(input: List<String>): Pair<String, String> { for ((idx, line) in input.withIndex()) { input.subList(idx + 1, input.lastIndex) .filter { compareWords(line, it) } .forEach { return Pair(line, it) } } throw Exception("No pair found") } fun getSameLetters(first: String, second: String): String { return first.zip(second) .filter { it.first == it.second } .map { it.first } .joinToString("") }
0
JavaScript
0
1
8779f71cebff6711e8b6613705bcba9714b4e33f
1,470
advent-of-code-2018
MIT License
src/main/kotlin/day07/Code.kt
fcolasuonno
317,324,330
false
null
package day07 import isDebug import java.io.File fun main() { val name = if (isDebug()) "test.txt" else "input.txt" System.err.println(name) val dir = ::main::class.java.`package`.name val input = File("src/main/kotlin/$dir/$name").readLines() val parsed = parse(input) part1(parsed) part2(parsed) } private val lineStructure = """(.+) bags contain (no other bags|((\d+) (.+) bags?, )*((\d+) (.+) bags?)).""".toRegex() private val bagsStructure = """(\d+) (.+) bags?""".toRegex() data class Bag(val num: Int, val type: String) fun parse(input: List<String>) = input.map { lineStructure.matchEntire(it)?.destructured?.let { val (bagType, bags) = it.toList() bagType to if (bags == "no other bags") emptyList() else bags.split(", ").map { bagsStructure.matchEntire(it)?.destructured?.let { val (num, type) = it.toList() Bag(num.toInt(), type) } }.requireNoNulls() } }.requireNoNulls().toMap() fun part1(input: Map<String, List<Bag>>) { val invert = input.flatMap { (type, bagList) -> bagList.map { it.type to type } }.groupBy { it.first }.mapValues { it.value.map { it.second }.toSet() } val check = mutableSetOf("shiny gold") val seen = mutableSetOf<String>() while (check.isNotEmpty()) { seen.addAll(check) check.addAll(check.flatMap { invert.getOrDefault(it, emptySet()) }) check.removeAll(seen) } println("Part 1 = ${seen.size - 1}") } fun part2(input: Map<String, List<Bag>>) { val res = generateSequence(listOf(Bag(1, "shiny gold"))) { list: List<Bag> -> list.flatMap { bag -> input.getValue(bag.type).map { Bag(it.num * bag.num, it.type) } }.takeIf { it.isNotEmpty() } }.sumBy { it.sumBy { it.num } } - 1 println("Part 2 = $res") }
0
Kotlin
0
0
e7408e9d513315ea3b48dbcd31209d3dc068462d
1,827
AOC2020
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/NumberOfGoodPaths.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import java.util.TreeMap /** * 2421. Number of Good Paths * @see <a href="https://leetcode.com/problems/number-of-good-paths/">Source</a> */ fun interface NumberOfGoodPaths { operator fun invoke(vals: IntArray, edges: Array<IntArray>): Int } class NumberOfGoodPathsUnionFind : NumberOfGoodPaths { override operator fun invoke(vals: IntArray, edges: Array<IntArray>): Int { val n = vals.size val adj: Array<MutableList<Int>> = Array(n) { ArrayList() } val sameValues = TreeMap<Int, ArrayList<Int>>() var ans = 0 for (i in 0 until n) { adj[i] = ArrayList() if (!sameValues.containsKey(vals[i])) { sameValues[vals[i]] = ArrayList() } sameValues[vals[i]]?.add(i) } for (e in edges) { val u = e[0] val v = e[1] if (vals[u] >= vals[v]) { adj[u].add(v) } else { adj[v].add(u) } } val uf = UF(n) for (sameValue in sameValues.keys) { val ints = sameValues[sameValue] ?: arrayListOf() for (u in ints) { for (v in adj[u]) { uf.union(u, v) } } val group: HashMap<Int, Int> = HashMap() for (u in ints) { group[uf.find(u)] = group.getOrDefault(uf.find(u), 0) + 1 } ans += ints.size for (key in group.keys) { val size = group[key] ?: 0 ans += size * (size - 1) / 2 } } return ans } class UF(len: Int) { private val parent: IntArray = IntArray(len) { -1 } fun find(a: Int): Int { return if (parent[a] >= 0) { find(parent[a]).also { parent[a] = it } } else { a } } fun union(a: Int, b: Int): Boolean { val pa = find(a) val pb = find(b) if (pa == pb) return false if (parent[pa] <= parent[pb]) { parent[pa] += parent[pb] parent[pb] = pa } else { parent[pb] += parent[pa] parent[pa] = pb } return true } } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,975
kotlab
Apache License 2.0
src/main/kotlin/com/github/dangerground/Day3.kt
dangerground
226,153,955
false
null
package com.github.dangerground import java.lang.Integer.max import java.lang.Integer.min import kotlin.math.absoluteValue class Day3(line1input: Array<String>, line2input: Array<String>) { val line1 = ArrayList<Line>() val line2 = ArrayList<Line>() init { convertToLine(line1input, line1) convertToLine(line2input, line2) } private fun convertToLine(inputs: Array<String>, lines: ArrayList<Line>) { var x = 0 var y = 0 for (input in inputs) { val p1 = Point(x, y) val num = input.substring(1).toInt() when (input[0]) { 'R' -> x += num 'L' -> x -= num 'U' -> y += num 'D' -> y -= num } val p2 = Point(x, y) lines.add(Line(p1, p2)) } } fun findNearestIntersection(): Int { var nearestDistance = Int.MAX_VALUE findIntersections().forEach { val distance = it.x.absoluteValue + it.y.absoluteValue if (distance < nearestDistance) { nearestDistance = distance } } return nearestDistance } fun findIntersections(): ArrayList<Point> { val intersections = ArrayList<Point>() for (section1 in line1) { for (section2 in line2) { val intersection = intersection(section1, section2) if (intersection != null && (intersection.x != 0 || intersection.y != 0)) { intersections.add(intersection) } } } return intersections } fun intersection(l1: Line, l2: Line) : Point? { val intersection = findHorizontalIntersection(l1, l2) if (intersection != null) { return intersection } return findHorizontalIntersection(l2, l1) } private fun findHorizontalIntersection(l1: Line, l2: Line): Point? { if (l1.p1.x == l1.p2.x && l2.p1.y == l2.p2.y) { val y1range = lineToYRange(l1) val x2range = lineToXRange(l2) val x = l1.p1.x val y = l2.p1.y if (x == 0 && y == 0) { return null; } if (x2range.contains(x) && y1range.contains(y)) { return Point(l1.p1.x, l2.p1.y) } } return null } private fun lineToXRange(l: Line) = IntRange(min(l.p1.x, l.p2.x), max(l.p1.x, l.p2.x)) private fun lineToYRange(l: Line) = IntRange(min(l.p1.y, l.p2.y), max(l.p1.y, l.p2.y)) fun findShortestStepCount() : Int { var shortestCount = Int.MAX_VALUE findIntersections().forEach {point -> var stepCount = 0 stepCount += countStepsToPoint(point, line1) stepCount += countStepsToPoint(point, line2) if (stepCount < shortestCount) { shortestCount = stepCount } } return shortestCount } private fun countStepsToPoint(p: Point, l: ArrayList<Line>) : Int { var steps = 0 l.forEach { val xRange = lineToXRange(it) val yRange = lineToYRange(it) if (xRange.contains(p.x) && yRange.contains(p.y)) { if (xRange.count() == 1) { steps += (it.p1.y - p.y).absoluteValue } else { steps += (it.p1.x - p.x).absoluteValue } return steps } else { if (xRange.count() == 1) { steps += yRange.count() - 1 } else { steps += xRange.count() - 1 } } } return -1 } class Point(val x: Int, val y: Int) class Line(val p1: Point, val p2: Point) { override fun toString(): String { return "(${p1.x},${p1.y})-(${p2.x},${p2.y})" } } }
0
Kotlin
0
1
125d57d20f1fa26a0791ab196d2b94ba45480e41
3,971
adventofcode
MIT License
src/day04/Day04.kt
Harvindsokhal
572,911,840
false
{"Kotlin": 11823}
package day04 import readInput fun main() { val data = readInput("day04/day04_data") fun pairFullOverlap(list: List<String>): Int { var count = 0 list.forEach { pair -> val pairOne = pair.split(',')[0].split('-') val pairTwo = pair.split(',')[1].split('-') val firstRange = pairOne[0].toInt()..pairOne[1].toInt() val secondRange = pairTwo[0].toInt()..pairTwo[1].toInt() if (firstRange.all { secondRange.contains(it)} || secondRange.all { firstRange.contains(it)}) { count +=1 } } return count } fun pairPartOverlap(list: List<String>): Int { var count = 0 list.forEach { pair -> val pairOne = pair.split(',')[0].split('-') val pairTwo = pair.split(',')[1].split('-') val firstRange = pairOne[0].toInt()..pairOne[1].toInt() val secondRange = pairTwo[0].toInt()..pairTwo[1].toInt() if (firstRange.any { secondRange.contains(it)} || secondRange.any { firstRange.contains(it)}) { count +=1 } } return count } fun part1 (list:List<String>) = pairFullOverlap(list) fun part2 (list:List<String>) = pairPartOverlap(list) println(part1(data)) println(part2(data)) }
0
Kotlin
0
0
7ebaee4887ea41aca4663390d4eadff9dc604f69
1,349
aoc-2022-kotlin
Apache License 2.0
2022/src/test/kotlin/Day09.kt
jp7677
318,523,414
false
{"Kotlin": 171284, "C++": 87930, "Rust": 59366, "C#": 1731, "Shell": 354, "CMake": 338}
import io.kotest.core.spec.style.StringSpec import io.kotest.matchers.shouldBe import kotlin.math.absoluteValue private data class Position9(val x: Int, val y: Int) class Day09 : StringSpec({ "puzzle part 01" { val countOfPositions = getHeadPositions() .runningReduce { acc, head -> acc.follow(head) } .toSet().count() countOfPositions shouldBe 5619 } "puzzle part 02" { val knots = buildList { repeat(9) { add(listOf(Position9(0, 0))) } } val countOfPositions = getHeadPositions() .fold(knots) { rope, head -> rope .map { it.last() } .scan(head) { knots, it -> it.follow(knots) } .drop(1) .mapIndexed { index, it -> if (index == rope.size - 1) rope[index] + it else listOf(it) } } .last() .toSet().count() countOfPositions shouldBe 2376 } }) private fun getHeadPositions() = getPuzzleInput("day09-input.txt") .map { it.split(" ") } .map { it.first() to it.last().toInt() } .flatMap { (move, times) -> buildList { repeat(times) { add(move) } } } .scan(Position9(0, 0)) { acc, it -> acc.move(it) } private fun Position9.move(direction: String) = when (direction) { "R" -> Position9(this.x + 1, this.y) "L" -> Position9(this.x - 1, this.y) "U" -> Position9(this.x, this.y + 1) "D" -> Position9(this.x, this.y - 1) else -> throw IllegalArgumentException() } private fun Position9.follow(other: Position9) = if ((this.x - other.x).absoluteValue <= 1 && (this.y - other.y).absoluteValue <= 1) this else when { other.x > x && other.y == y -> Position9(x + 1, y) other.x < x && other.y == y -> Position9(x - 1, y) other.x == x && other.y > y -> Position9(x, y + 1) other.x == x && other.y < y -> Position9(x, y - 1) other.x > x && other.y > y -> Position9(x + 1, y + 1) other.x < x && other.y > y -> Position9(x - 1, y + 1) other.x > x -> Position9(x + 1, y - 1) other.x < x -> Position9(x - 1, y - 1) else -> throw IllegalArgumentException() }
0
Kotlin
1
2
8bc5e92ce961440e011688319e07ca9a4a86d9c9
2,254
adventofcode
MIT License
src/main/kotlin/ru/timakden/aoc/year2015/Day19.kt
timakden
76,895,831
false
{"Kotlin": 321649}
package ru.timakden.aoc.year2015 import ru.timakden.aoc.util.measure import ru.timakden.aoc.util.readInput import java.util.* /** * [Day 19: Medicine for Rudolph](https://adventofcode.com/2015/day/19). */ object Day19 { @JvmStatic fun main(args: Array<String>) { measure { val input = readInput("year2015/Day19") val replacements = input.dropLast(2) val molecule = input.last() println("Part One: ${part1(replacements, molecule)}") println("Part Two: ${part2(replacements, molecule)}") } } fun part1(replacements: List<String>, molecule: String): Int { val regex = "\\s=>\\s".toRegex() val distinctMolecules = mutableSetOf<String>() val reversedReplacements = replacements.associateBy({ it.split(regex)[1] }, { it.split(regex)[0] }) reversedReplacements.forEach { (key, value) -> var index = -1 do { index = molecule.indexOf(value, index + 1) if (index != -1) distinctMolecules.add(molecule.replaceRange(index, index + value.length, key)) } while (index != -1) } return distinctMolecules.size } fun part2(replacements: List<String>, molecule: String): Int { var count: Int val regex = "\\s=>\\s".toRegex() val reversedReplacements = replacements.associateBy({ it.split(regex)[1] }, { it.split(regex)[0] }) do { count = findMolecule(0, molecule, reversedReplacements) } while (count == -1) return count } private tailrec fun findMolecule(depth: Int, molecule: String, reversedReplacements: Map<String, String>): Int { if (molecule == "e") return depth else { var originalMolecule = molecule val keys = reversedReplacements.keys.toMutableList() var replaced = false while (!replaced) { val toReplace = keys.removeAt(Random().nextInt(keys.size)) if (toReplace in molecule) { val before = originalMolecule.substringBefore(toReplace) val after = originalMolecule.substringAfter(toReplace) originalMolecule = before + reversedReplacements[toReplace] + after replaced = true } if (keys.isEmpty()) return -1 } return findMolecule(depth + 1, originalMolecule, reversedReplacements) } } }
0
Kotlin
0
3
acc4dceb69350c04f6ae42fc50315745f728cce1
2,520
advent-of-code
MIT License
src/Day02.kt
bunjix
573,915,819
false
{"Kotlin": 9977}
import java.io.File fun main() { val input = File("src/Day02_input.txt").readLines() val fomattedInput = input.map { line -> line.split(" ").let { players -> players.first().first() to players.last().first() } } println(part1(fomattedInput)) println(part2(fomattedInput)) } private fun part1(input: List<Pair<Char, Char>>): Int { return input.sumOf { (other, me) -> me.shapeScore() + me.roundOutcome(other) } } private fun part2(input: List<Pair<Char, Char>>): Int { /* return input.sumOf { (other, outcome) -> val me = outcome.shapeOutcome(other) me.shapeScore() + me.roundOutcome(other) } */ return part1(input.map { (other, outcome) -> other to outcome.shapeOutcome(other) }) } fun Char.shapeScore(): Int { return when (this) { 'X', 'A' -> 1 'Y', 'B' -> 2 'Z', 'C' -> 3 else -> throw IllegalStateException("Wrong shape $this") } } fun Char.shapeOutcome(other: Char): Char { return when { this == 'X' && other == 'A' -> 'C' this == 'X' && other == 'B' -> 'A' this == 'X' && other == 'C' -> 'B' this == 'Y' -> other this == 'Z' && other == 'A' -> 'B' this == 'Z' && other == 'B' -> 'C' this == 'Z' && other == 'C' -> 'A' else -> throw IllegalStateException("Wrong hand ($this, $other)") } } fun Char.mapShape(): Char { return when (this) { 'X' -> 'A' 'Y' -> 'B' 'Z' -> 'C' else -> this } } fun Char.roundOutcome(other: Char): Int { val myShape = this.mapShape() return when { myShape == 'A' && other == 'A' -> 3 myShape == 'A' && other == 'B' -> 0 myShape == 'A' && other == 'C' -> 6 myShape == 'B' && other == 'A' -> 6 myShape == 'B' && other == 'B' -> 3 myShape == 'B' && other == 'C' -> 0 myShape == 'C' && other == 'A' -> 0 myShape == 'C' && other == 'B' -> 6 myShape == 'C' && other == 'C' -> 3 else -> throw IllegalStateException("Wrong hand ($this, $other)") } }
0
Kotlin
0
0
ee2a344f6c0bb2563cdb828485e9a56f2ff08fcc
2,081
aoc-2022-kotlin
Apache License 2.0
src/main/kotlin/aoc23/Day17.kt
tom-power
573,330,992
false
{"Kotlin": 254717, "Shell": 1026}
package aoc23 import aoc23.Day17Domain.City import aoc23.Day17Domain.City.BlockNode import aoc23.Day17Parser.toCity import aoc23.Day17Solution.fourToTenStepsDirectionPredicate import aoc23.Day17Solution.threeStepsDirectionPredicate import common.Monitoring import common.Space2D import common.Space2D.Direction import common.Space2D.Direction.East import common.Space2D.Parser.toPointToChars import common.Space2D.Point import common.Space2D.bottomRight import common.Space2D.opposite import common.Space2D.topLeft import common.Year23 import common.graph.Dijkstra import common.graph.Edge import common.graph.Node object Day17 : Year23 { fun List<String>.part1(): Int = toCity() .leastHeatLoss(threeStepsDirectionPredicate) fun List<String>.part2(): Int = toCity() .leastHeatLoss(fourToTenStepsDirectionPredicate) } typealias DirectionPredicate = (BlockNode, Direction) -> Boolean object Day17Solution { val threeStepsDirectionPredicate: DirectionPredicate = { node, nextDirection -> when { node.directionCount > 2 -> nextDirection != node.direction else -> true } } val fourToTenStepsDirectionPredicate: DirectionPredicate = { node, nextDirection -> when { node.directionCount < 4 -> nextDirection == node.direction node.directionCount > 9 -> nextDirection != node.direction else -> true } } } object Day17Domain { data class City( val blockMap: Map<Point, Int>, val monitor: Monitoring.PointCharMonitor? = null ) { fun leastHeatLoss(directionPredicate: DirectionPredicate): Int = BlockDijkstra(directionPredicate).run { shortestPath() .also { monitor?.invoke(shortestPaths.last().first.map { it.value }.toSet()) } } data class BlockNode( override val value: Point, val directionCount: Int, val direction: Direction, ) : Node<Point> inner class BlockDijkstra( private val directionPredicate: DirectionPredicate ) : Dijkstra<Point, BlockNode>(monitoring = monitor != null) { private val topLeft = blockMap.keys.topLeft private val bottomRight = blockMap.keys.bottomRight override val start: () -> BlockNode = { BlockNode( value = topLeft, directionCount = 0, direction = East ) } override val isEnd: (BlockNode) -> Boolean = { it.value == bottomRight } override fun next(node: BlockNode): List<Edge<Point, BlockNode>> = with(node) { Space2D.Direction.entries .filter { nextDirection -> nextDirection != direction.opposite() } .filter { nextDirection -> directionPredicate(node, nextDirection) } .map { value.move(it) to it } .mapNotNull { (nextPoint, nextDirection) -> blockMap[nextPoint]?.let { nextCost -> Edge( node = BlockNode( value = nextPoint, directionCount = when { nextDirection == direction -> directionCount + 1 else -> 1 }, direction = nextDirection, ), cost = nextCost ) } } } } } } object Day17Parser { fun List<String>.toCity(monitor: Monitoring.PointCharMonitor? = null): City = City( blockMap = this.toPointToChars().associate { it.first to it.second.digitToInt() }, monitor = monitor, ) }
0
Kotlin
0
0
baccc7ff572540fc7d5551eaa59d6a1466a08f56
4,278
aoc
Apache License 2.0
src/main/kotlin/days/Common.kt
andilau
573,139,461
false
{"Kotlin": 65955}
package days import kotlin.math.sign fun lcm(x: Long, y: Long, vararg ints: Long): Long = ints.fold(x * y / gcd(x, y)) { acc, z -> lcm(acc, z) } fun lcm(x: Long, y: Long, ints: List<Long>): Long = ints.fold(x * y / gcd(x, y)) { acc, z -> lcm(acc, z) } fun gcd(a: Long, b: Long): Long { if (b == 0L) return a return gcd(b, a % b) } fun pairs(intRange: IntRange): List<Pair<Int, Int>> = intRange.flatMap { dy -> intRange.map { dx -> Pair(dx, dy) } } data class Point(val x: Int, val y: Int) { val north: Point get() = this.copy(y = y - 1) val northwest: Point get() = this + Point(-1, -1) val northeast: Point get() = this + Point(1, -1) val south: Point get() = this + Point(0, 1) val southwest: Point get() = this + Point(-1, 1) val southeast: Point get() = this + Point(1, 1) val west: Point get() = this + Point(-1, 0) val east: Point get() = this + Point(1, 0) fun neighboursAndSelf(): Set<Point> = setOf( copy(x = x + 1), copy(y = y + 1), copy(x = x - 1), copy(y = y - 1), copy(), ) fun neighbours() = setOf( copy(x = x + 1), copy(y = y + 1), copy(x = x - 1), copy(y = y - 1), ) fun neighboursAll() = setOf( copy(x = x + 1), copy(x = x - 1), copy(x = x + 1, y = y - 1), copy(x = x + 1, y = y + 1), copy(y = y + 1), copy(y = y - 1), copy(x = x - 1, y = y - 1), copy(x = x - 1, y = y + 1), ) fun lineto(to: Point): Sequence<Point> { val dx = (to.x - x).sign val dy = (to.y - y).sign return generateSequence(this) { if (it == to) null else it + Point(dx, dy) } } operator fun plus(other: Point) = Point(x + other.x, y + other.y) operator fun minus(other: Point) = Point(x - other.x, y - other.y) operator fun times(value: Int) = Point(x * value, y * value) override fun toString(): String { return "P($x,$y)" } companion object { val WEST = Point(-1, 0) val EAST = Point(1, 0) val NORTH = Point(0, -1) val SOUTH = Point(0, 1) fun from(line: String) = line .split(",") .map(String::toInt) .let { (x, y) -> Point(x, y) } } } operator fun Int.times(vector: Point) = vector.times(this) fun List<String>.extract(char: Char): Set<Point> { return this.flatMapIndexed() { y, row -> row.mapIndexedNotNull { x, c -> if (c == char) Point(x, y) else null } } .toSet() } fun Set<Point>.draw() { (minOf { it.y }..maxOf { it.y }).forEach { y -> (minOf { it.x }..maxOf { it.x }).map { x -> if (Point(x, y) in this) '#' else '.' }.joinToString("") .also { println(it) } } }
0
Kotlin
0
0
da824f8c562d72387940844aff306b22f605db40
2,837
advent-of-code-2022
Creative Commons Zero v1.0 Universal
src/d19.main.kts
cjfuller
317,725,797
false
null
import java.io.File sealed class Rule { abstract fun match(s: String): List<Pair<Boolean, Int>> data class Literal(val c: Char) : Rule() { override fun match(s: String) = if (s.firstOrNull() == c) { listOf(true to 1) } else { listOf(false to 0) } } data class Or(val sub: List<Rule>) : Rule() { override fun match(s: String) = sub .flatMap { it.match(s) } .filter { (matched, _) -> matched } .let { if (it.isEmpty()) listOf(false to 0) else it } } data class RuleRef(val ref: Int) : Rule() { override fun match(s: String) = rules[ref]!!.match(s) } data class RefSeq(val refs: List<RuleRef>) : Rule() { override fun match(s: String) = refs .fold(listOf(true to 0)) { acc, currRef -> acc.flatMap { (matchSoFar, lengthSoFar) -> if (matchSoFar) { currRef .match(s.drop(lengthSoFar)) .filter { (matched, _) -> matched } .map { (matched, nextLen) -> matched to lengthSoFar + nextLen } } else { listOf(matchSoFar to lengthSoFar) } } } .let { if (it.isEmpty()) listOf(false to 0) else it } } companion object { var rules: MutableMap<Int, Rule> = mutableMapOf() } } fun parseRule(text: String): Rule = when { text.contains('"') -> Rule.Literal( Regex(""""(\w)"""").find(text)!!.groupValues[1][0] ) text.contains('|') -> Rule.Or(text.split('|').map(::parseRule)) else -> { val parts = text.trim().split(" ") if (parts.size == 1) { Rule.RuleRef(parts[0].toInt()) } else { Rule.RefSeq(parts.map { Rule.RuleRef(it.toInt()) }) } } } Rule.rules = File("./data/d19.rules.txt").readLines().map { val (num, ruleText) = it.split(":") num.toInt() to parseRule(ruleText) }.toMap().toMutableMap() val messages = File("./data/d19.messages.txt").readLines().map(String::trim) fun completeMatch(rule: Rule, s: String): Boolean { val matches = rule.match(s) return matches.any { (matched, matchLen) -> matched && matchLen == s.length } } println("Part 1:") println(messages.count { m -> completeMatch(Rule.rules[0]!!, m) }) println("Part 2:") Rule.rules[8] = Rule.Or( listOf( Rule.RuleRef(42), Rule.RefSeq(listOf(Rule.RuleRef(42), Rule.RuleRef(8))) ) ) Rule.rules[11] = Rule.Or( listOf( Rule.RefSeq( listOf(Rule.RuleRef(42), Rule.RuleRef(31)) ), Rule.RefSeq(listOf(Rule.RuleRef(42), Rule.RuleRef(11), Rule.RuleRef(31))) ) ) println(messages.count { m -> completeMatch(Rule.rules[0]!!, m) })
0
Kotlin
0
0
c3812868da97838653048e63b4d9cb076af58a3b
3,108
adventofcode2020
MIT License
src/day22/Day22.kt
EndzeitBegins
573,569,126
false
{"Kotlin": 111428}
package day22 import day22.Direction.* import readInput import readTestInput import kotlin.math.sqrt private sealed interface Instruction { data class Move(val steps: Int) : Instruction object TurnLeft : Instruction object TurnRight : Instruction } private typealias Instructions = Sequence<Instruction> private fun String.toInstructions(): Instructions { val rawInstructions = this return sequence { var digitBuffer = "" for (rawInstruction in rawInstructions) { if (rawInstruction in '0'..'9') { digitBuffer += rawInstruction } else { if (digitBuffer.isNotEmpty()) { yield( Instruction.Move(steps = digitBuffer.toInt()) ) digitBuffer = "" } val instruction = if (rawInstruction == 'L') Instruction.TurnLeft else Instruction.TurnRight yield(instruction) } } if (digitBuffer.isNotEmpty()) { yield( Instruction.Move(steps = digitBuffer.toInt()) ) } } } private sealed interface Position { val x: Int val y: Int } data class PositionOnPlane(override val x: Int, override val y: Int) : Position data class PositionOnCube(override val x: Int, override val y: Int, val cubeFace: Int) : Position private data class Block<Pos : Position>(val position: Pos, val isWall: Boolean) private data class Row<Pos : Position>(val blocks: List<Block<Pos>>) private data class Column<Pos : Position>(val blocks: List<Block<Pos>>) private data class PlaneCryptoMap( val rows: List<Row<PositionOnPlane>>, val columns: List<Column<PositionOnPlane>>, ) private data class CubeFace( val rows: List<Row<PositionOnCube>>, val columns: List<Column<PositionOnCube>>, val neighbors: Map<Direction, Pair<Int, Direction>> ) private data class CubeCryptoMap( val faces: List<CubeFace>, ) private fun List<String>.toPlaneCryptoMap(): PlaneCryptoMap { val rawMapData = this val rows: MutableList<MutableList<Block<PositionOnPlane>>> = mutableListOf() val columns: MutableList<MutableList<Block<PositionOnPlane>>> = mutableListOf() rawMapData.forEachIndexed { y, rawRow -> rawRow.forEachIndexed rowLoop@{ x, cell -> val isWall = when (cell) { '.' -> false '#' -> true else -> return@rowLoop } val block = Block(position = PositionOnPlane(x = x, y = y), isWall = isWall) repeat(y - rows.lastIndex) { rows.add(mutableListOf()) } rows[y] += block repeat(x - columns.lastIndex) { columns.add(mutableListOf()) } columns[x] += block } } return PlaneCryptoMap( rows = rows.map { rowBlocks -> Row(rowBlocks) }, columns = columns.map { columnBlocks -> Column(columnBlocks) } ) } private fun List<String>.toCubeCryptoMap(isTestSet: Boolean): CubeCryptoMap { val area = this.sumOf { line -> line.count { cell -> cell in setOf('.', '#') } } val faceLength = sqrt(1.0 * area / 6).toInt() val faces = if (isTestSet) { listOf( extractCubeFace( faceLength = faceLength, horizontalOffset = 2, verticalOffset = 0, cubeFace = 0, neighbors = mapOf(LEFT to (2 to DOWN), RIGHT to (5 to LEFT), UP to (1 to DOWN), DOWN to (3 to DOWN)), ), extractCubeFace( faceLength = faceLength, horizontalOffset = 0, verticalOffset = 1, cubeFace = 1, neighbors = mapOf(LEFT to (5 to UP), RIGHT to (2 to RIGHT), UP to (0 to DOWN), DOWN to (4 to UP)), ), extractCubeFace( faceLength = faceLength, horizontalOffset = 1, verticalOffset = 1, cubeFace = 2, neighbors = mapOf(LEFT to (1 to LEFT), RIGHT to (3 to RIGHT), UP to (0 to RIGHT), DOWN to (4 to RIGHT)), ), extractCubeFace( faceLength = faceLength, horizontalOffset = 2, verticalOffset = 1, cubeFace = 3, neighbors = mapOf(LEFT to (2 to LEFT), RIGHT to (5 to DOWN), UP to (0 to UP), DOWN to (4 to DOWN)), ), extractCubeFace( faceLength = faceLength, horizontalOffset = 2, verticalOffset = 2, cubeFace = 4, neighbors = mapOf(LEFT to (2 to UP), RIGHT to (5 to RIGHT), UP to (3 to UP), DOWN to (1 to UP)), ), extractCubeFace( faceLength = faceLength, horizontalOffset = 3, verticalOffset = 2, cubeFace = 5, neighbors = mapOf(LEFT to (4 to LEFT), RIGHT to (0 to LEFT), UP to (3 to LEFT), DOWN to (1 to RIGHT)), ), ) } else { listOf( extractCubeFace( faceLength = faceLength, horizontalOffset = 1, verticalOffset = 0, cubeFace = 0, neighbors = mapOf(LEFT to (3 to RIGHT), RIGHT to (1 to RIGHT), UP to (5 to RIGHT), DOWN to (2 to DOWN)), ), extractCubeFace( faceLength = faceLength, horizontalOffset = 2, verticalOffset = 0, cubeFace = 1, neighbors = mapOf(LEFT to (0 to LEFT), RIGHT to (4 to LEFT), UP to (5 to UP), DOWN to (2 to LEFT)), ), extractCubeFace( faceLength = faceLength, horizontalOffset = 1, verticalOffset = 1, cubeFace = 2, neighbors = mapOf(LEFT to (3 to DOWN), RIGHT to (1 to UP), UP to (0 to UP), DOWN to (4 to DOWN)), ), extractCubeFace( faceLength = faceLength, horizontalOffset = 0, verticalOffset = 2, cubeFace = 3, neighbors = mapOf(LEFT to (0 to RIGHT), RIGHT to (4 to RIGHT), UP to (2 to RIGHT), DOWN to (5 to DOWN)), ), extractCubeFace( faceLength = faceLength, horizontalOffset = 1, verticalOffset = 2, cubeFace = 4, neighbors = mapOf(LEFT to (3 to LEFT), RIGHT to (1 to LEFT), UP to (2 to UP), DOWN to (5 to LEFT)), ), extractCubeFace( faceLength = faceLength, horizontalOffset = 0, verticalOffset = 3, cubeFace = 5, neighbors = mapOf(LEFT to (0 to DOWN), RIGHT to (4 to UP), UP to (3 to UP), DOWN to (1 to DOWN)), ), ) } return CubeCryptoMap(faces) } private fun List<String>.extractCubeFace( cubeFace: Int, faceLength: Int, horizontalOffset: Int, verticalOffset: Int, neighbors: Map<Direction, Pair<Int, Direction>>, ): CubeFace { val rawMapData = this val rawFaceData = rawMapData .drop(verticalOffset * faceLength) .take(faceLength) .map { mapRow -> mapRow.drop(horizontalOffset * faceLength).take(faceLength) } val rows: MutableList<MutableList<Block<PositionOnCube>>> = mutableListOf() val columns: MutableList<MutableList<Block<PositionOnCube>>> = mutableListOf() rawFaceData.forEachIndexed { y, rawRow -> rawRow.forEachIndexed rowLoop@{ x, cell -> val isWall = when (cell) { '.' -> false '#' -> true else -> return@rowLoop } val position = PositionOnCube( x = x + horizontalOffset * faceLength, y = y + verticalOffset * faceLength, cubeFace = cubeFace ) val block = Block(position = position, isWall = isWall) repeat(y - rows.lastIndex) { rows.add(mutableListOf()) } rows[y] += block repeat(x - columns.lastIndex) { columns.add(mutableListOf()) } columns[x] += block } } return CubeFace( rows = rows.map { rowBlocks -> Row(rowBlocks) }, columns = columns.map { columnBlocks -> Column(columnBlocks) }, neighbors = neighbors, ) } private fun PlaneCryptoMap.findStartPosition(): Position { val topRow = rows.first() val startingBlock = topRow.blocks.first() return startingBlock.position } private fun CubeCryptoMap.findStartPosition(): Position { val firstFace = faces.first() val topRow = firstFace.rows.first() val startingBlock = topRow.blocks.first() return startingBlock.position } private enum class Direction { LEFT, RIGHT, UP, DOWN } private data class Actor(val position: Position, val direction: Direction) private fun Actor.execute(instruction: Instruction, on: PlaneCryptoMap): Actor { return when (instruction) { is Instruction.Move -> { val updatedPosition = when (direction) { LEFT -> { val row = on.rows[position.y] moveBackward(steps = instruction.steps, blocks = row.blocks) } RIGHT -> { val row = on.rows[position.y] moveForward(steps = instruction.steps, blocks = row.blocks) } UP -> { val column = on.columns[position.x] moveBackward(steps = instruction.steps, blocks = column.blocks) } DOWN -> { val column = on.columns[position.x] moveForward(steps = instruction.steps, blocks = column.blocks) } } copy(position = updatedPosition) } Instruction.TurnLeft -> { val updatedDirection = when (direction) { LEFT -> DOWN RIGHT -> UP UP -> LEFT DOWN -> RIGHT } copy(direction = updatedDirection) } Instruction.TurnRight -> { val updatedDirection = when (direction) { LEFT -> UP RIGHT -> DOWN UP -> RIGHT DOWN -> LEFT } copy(direction = updatedDirection) } } } private fun Actor.moveForward(steps: Int, blocks: List<Block<PositionOnPlane>>): Position { val startIndex = blocks.indexOfFirst { it.position == position } var targetPosition = position for (index in (startIndex + 1)..(startIndex + steps)) { val sanitizedIndex = index.mod(blocks.size) val potentialTargetPosition = blocks[sanitizedIndex] if (!potentialTargetPosition.isWall) { targetPosition = potentialTargetPosition.position } else { break } } return targetPosition } private fun Actor.moveBackward(steps: Int, blocks: List<Block<PositionOnPlane>>): Position { val startIndex = blocks.indexOfFirst { it.position == position } var targetPosition = position for (index in (startIndex - 1) downTo (startIndex - steps)) { val sanitizedIndex = index.mod(blocks.size) val potentialTargetPosition = blocks[sanitizedIndex] if (!potentialTargetPosition.isWall) { targetPosition = potentialTargetPosition.position } else { break } } return targetPosition } private fun Actor.execute(instruction: Instruction, on: CubeCryptoMap): Actor { return when (instruction) { is Instruction.Move -> { move(steps = instruction.steps, on = on) } Instruction.TurnLeft -> { val updatedDirection = when (direction) { LEFT -> DOWN RIGHT -> UP UP -> LEFT DOWN -> RIGHT } copy(direction = updatedDirection) } Instruction.TurnRight -> { val updatedDirection = when (direction) { LEFT -> UP RIGHT -> DOWN UP -> RIGHT DOWN -> LEFT } copy(direction = updatedDirection) } } } private fun Actor.move(steps: Int, on: CubeCryptoMap): Actor { var stepsRemaining = steps var position = position as PositionOnCube var direction = direction while (stepsRemaining > 0) { val (nextBlock, nextDirection) = when (direction) { LEFT -> moveLeft(on = on, from = position, into = direction) RIGHT -> moveRight(on = on, from = position, into = direction) UP -> moveUp(on = on, from = position, into = direction) DOWN -> moveDown(on = on, from = position, into = direction) } if (nextBlock.isWall) { break } position = nextBlock.position direction = nextDirection stepsRemaining -= 1 } return Actor(position, direction) } private fun moveLeft( on: CubeCryptoMap, from: PositionOnCube, into: Direction ): Pair<Block<PositionOnCube>, Direction> { val faceLength = on.faces.first().rows.size val faceRow = on.faces[from.cubeFace].rows[from.y % faceLength] val nextX = (from.x % faceLength) - 1 return if (nextX in faceRow.blocks.indices) { faceRow.blocks[nextX] to into } else { val sourceCubeFace = on.faces[from.cubeFace] val (targetCubeFaceNumber, targetDirection) = sourceCubeFace.neighbors.getValue(LEFT) val targetCubeFace = on.faces[targetCubeFaceNumber] val targetPosition = when(targetDirection) { LEFT -> targetCubeFace.columns.last().blocks[from.y % faceLength] RIGHT -> targetCubeFace.columns.first().blocks.asReversed()[from.y % faceLength] UP -> targetCubeFace.rows.last().blocks.asReversed()[from.y % faceLength] DOWN -> targetCubeFace.rows.first().blocks[from.y % faceLength] } targetPosition to targetDirection } } private fun moveRight( on: CubeCryptoMap, from: PositionOnCube, into: Direction ): Pair<Block<PositionOnCube>, Direction> { val faceLength = on.faces.first().rows.size val faceRow = on.faces[from.cubeFace].rows[from.y % faceLength] val nextX = (from.x % faceLength) + 1 return if (nextX in faceRow.blocks.indices) { faceRow.blocks[nextX] to into } else { val sourceCubeFace = on.faces[from.cubeFace] val (targetCubeFaceNumber, targetDirection) = sourceCubeFace.neighbors.getValue(RIGHT) val targetCubeFace = on.faces[targetCubeFaceNumber] val targetPosition = when(targetDirection) { LEFT -> targetCubeFace.columns.last().blocks.asReversed()[from.y % faceLength] RIGHT -> targetCubeFace.columns.first().blocks[from.y % faceLength] UP -> targetCubeFace.rows.last().blocks[from.y % faceLength] DOWN -> targetCubeFace.rows.first().blocks.asReversed()[from.y % faceLength] } targetPosition to targetDirection } } private fun moveUp( on: CubeCryptoMap, from: PositionOnCube, into: Direction ): Pair<Block<PositionOnCube>, Direction> { val faceLength = on.faces.first().columns.size val faceColumn = on.faces[from.cubeFace].columns[from.x % faceLength] val nextY = (from.y % faceLength) - 1 return if (nextY in faceColumn.blocks.indices) { faceColumn.blocks[nextY] to into } else { val sourceCubeFace = on.faces[from.cubeFace] val (targetCubeFaceNumber, targetDirection) = sourceCubeFace.neighbors.getValue(UP) val targetCubeFace = on.faces[targetCubeFaceNumber] val targetPosition = when(targetDirection) { LEFT -> targetCubeFace.columns.last().blocks.asReversed()[from.x % faceLength] RIGHT -> targetCubeFace.columns.first().blocks[from.x % faceLength] UP -> targetCubeFace.rows.last().blocks[from.x % faceLength] DOWN -> targetCubeFace.rows.first().blocks.asReversed()[from.x % faceLength] } targetPosition to targetDirection } } private fun moveDown( on: CubeCryptoMap, from: PositionOnCube, into: Direction ): Pair<Block<PositionOnCube>, Direction> { val faceLength = on.faces.first().columns.size val faceColumn = on.faces[from.cubeFace].columns[from.x % faceLength] val nextY = (from.y % faceLength) + 1 return if (nextY in faceColumn.blocks.indices) { faceColumn.blocks[nextY] to into } else { val sourceCubeFace = on.faces[from.cubeFace] val (targetCubeFaceNumber, targetDirection) = sourceCubeFace.neighbors.getValue(DOWN) val targetCubeFace = on.faces[targetCubeFaceNumber] val targetPosition = when(targetDirection) { LEFT -> targetCubeFace.columns.last().blocks[from.x % faceLength] RIGHT -> targetCubeFace.columns.first().blocks.asReversed()[from.x % faceLength] UP -> targetCubeFace.rows.last().blocks.asReversed()[from.x % faceLength] DOWN -> targetCubeFace.rows.first().blocks[from.x % faceLength] } targetPosition to targetDirection } } private fun Actor.calculatePassword(): Int { val row = position.y + 1 val column = position.x + 1 val facing = when (direction) { LEFT -> 2 RIGHT -> 0 UP -> 3 DOWN -> 1 } return 1_000 * row + 4 * column + facing } private fun List<String>.parseAsPlainMap(): Pair<PlaneCryptoMap, Instructions> { val rawInput = this val cryptoMap = rawInput.dropLast(2).toPlaneCryptoMap() val instructions = rawInput.last().toInstructions() return cryptoMap to instructions } private fun List<String>.parseAsCubeMap(isTestSet: Boolean): Pair<CubeCryptoMap, Instructions> { val rawInput = this val cryptoMap = rawInput.dropLast(2).toCubeCryptoMap(isTestSet) val instructions = rawInput.last().toInstructions() return cryptoMap to instructions } private fun part1(input: List<String>): Int { val (cryptoMap, instructions) = input.parseAsPlainMap() val startPosition = cryptoMap.findStartPosition() var actor = Actor(startPosition, RIGHT) for (instruction in instructions) { actor = actor.execute(instruction = instruction, on = cryptoMap) } return actor.calculatePassword() } private fun part2(input: List<String>, isTestSet: Boolean): Int { val (cryptoMap, instructions) = input.parseAsCubeMap(isTestSet = isTestSet) val startPosition = cryptoMap.findStartPosition() var actor = Actor(startPosition, RIGHT) for (instruction in instructions) { actor = actor.execute(instruction = instruction, on = cryptoMap) } return actor.calculatePassword() } fun main() { // test if implementation meets criteria from the description, like: val testInput = readTestInput("Day22") check(part1(testInput) == 6032) check(part2(testInput, isTestSet = true) == 5031) val input = readInput("Day22") println(part1(input)) println(part2(input, isTestSet = false)) }
0
Kotlin
0
0
ebebdf13cfe58ae3e01c52686f2a715ace069dab
18,973
advent-of-code-kotlin-2022
Apache License 2.0
src/Day20.kt
sitamshrijal
574,036,004
false
{"Kotlin": 34366}
fun main() { fun parse(input: List<String>, decryptionKey: Long = 1L): MutableList<Number> = input.mapIndexed { index, s -> Number(s.toLong() * decryptionKey, index) }.toMutableList() fun part1(input: List<String>): Long { val numbers = parse(input) numbers.indices.forEach { originalIndex -> val index = numbers.indexOfFirst { it.index == originalIndex } val toMove = numbers.removeAt(index) numbers.addWrapped(index + toMove.value, toMove) } val index = numbers.indexOfFirst { it.value == 0L } return listOf(1000, 2000, 3000).sumOf { numbers.getWrapped(index + it).value } } fun part2(input: List<String>): Long { val numbers = parse(input, 811_589_153L) repeat(10) { numbers.indices.forEach { originalIndex -> val index = numbers.indexOfFirst { it.index == originalIndex } val toMove = numbers.removeAt(index) numbers.addWrapped(index + toMove.value, toMove) } } val index = numbers.indexOfFirst { it.value == 0L } return listOf(1000, 2000, 3000).sumOf { numbers.getWrapped(index + it).value } } val input = readInput("input20") println(part1(input)) println(part2(input)) } data class Number(val value: Long, val index: Int) fun <T> MutableList<T>.getWrapped(index: Int): T = this[index % size] fun <T> MutableList<T>.addWrapped(index: Long, value: T) { add(index.mod(size), value) }
0
Kotlin
0
0
fd55a6aa31ba5e3340be3ea0c9ef57d3fe9fd72d
1,530
advent-of-code-2022
Apache License 2.0
src/main/kotlin/advent/day13/TransparentOrigami.kt
hofiisek
434,171,205
false
{"Kotlin": 51627}
package advent.day13 import advent.Matrix import advent.Position import advent.loadInput import java.io.File /** * @author <NAME> */ typealias Paper = Matrix<PaperPosition> fun Paper.foldUp(foldRowIdx: Int): Paper { return (0 until foldRowIdx).map { row -> (0 until cols).map { col -> val position = Position(row, col) val bottomPosition = Position(foldRowIdx * 2 - row, col) if (get(position) is Dot || get(bottomPosition) is Dot) Dot(position) else Empty(position) } }.let(::Paper) } fun Paper.foldLeft(foldColIdx: Int): Paper { return (0 until rows).map { row -> (0 until foldColIdx).map { col -> val position = Position(row, col) val rightPosition = Position(row, foldColIdx * 2 - col) if (get(position) is Dot || get(rightPosition) is Dot) Dot(position) else Empty(position) } }.let(::Matrix) } fun Paper.print() = joinToString(separator = "\n") { row -> row.joinToString("") { position -> if (position is Dot) "#" else "." } }.also(::println) sealed class PaperPosition(open val position: Position) data class Dot(override val position: Position) : PaperPosition(position) data class Empty(override val position: Position) : PaperPosition(position) sealed class FoldInstruction(open val foldIdx: Int) data class FoldUp(override val foldIdx: Int) : FoldInstruction(foldIdx) data class FoldLeft(override val foldIdx: Int) : FoldInstruction(foldIdx) fun part1(input: File) = input.readLines() .let { lines -> val initialPaper = parseInitialPaper(lines) val foldInstructions = parseFoldInstructions(lines) foldInstructions.take(1).fold(initialPaper) { paper, instruction -> when (instruction) { is FoldUp -> paper.foldUp(instruction.foldIdx) is FoldLeft -> paper.foldLeft(instruction.foldIdx) } } } .also(Paper::print) .sumOf { row -> row.count { it is Dot } } fun part2(input: File) = input.readLines() .let { lines -> val initialPaper = parseInitialPaper(lines) val foldInstructions = parseFoldInstructions(lines) foldInstructions.fold(initialPaper) { paper, instruction -> when (instruction) { is FoldUp -> paper.foldUp(instruction.foldIdx) is FoldLeft -> paper.foldLeft(instruction.foldIdx) } } } .also(Paper::print) .sumOf { row -> row.count { it is Dot } } .also(::println) fun parseInitialPaper(lines: List<String>): Paper = lines .filterNot { it.isBlank() } .filterNot { it.startsWith("fold") } .map { it.split(",").map { it.toInt() } } .map { (col, row) -> Position(row, col) } .let { dotPositions -> val maxRow = dotPositions.maxOf { it.row } val maxCol = dotPositions.maxOf { it.col } (0..maxRow).map { row -> (0..maxCol).map { col -> val position = Position(row, col) if (position in dotPositions) Dot(position) else Empty(position) } } } .let(::Paper) fun parseFoldInstructions(lines: List<String>) = lines .filter { it.startsWith("fold") } .map { it.removePrefix("fold along ").split("=") } .map { (axis, idx) -> when (axis) { "x" -> FoldLeft(idx.toInt()) "y" -> FoldUp(idx.toInt()) else -> throw IllegalArgumentException("Invalid axis to fold along: $axis") } } fun main() { with(loadInput(day = 13)) { // with(loadInput(day = 13, filename = "input_example.txt")) { println(part1(this)) part2(this) } }
0
Kotlin
0
2
3bd543ea98646ddb689dcd52ec5ffd8ed926cbbb
3,836
Advent-of-code-2021
MIT License
src/day02/Day02.kt
cmargonis
573,161,233
false
{"Kotlin": 15730}
package day02 import readInput private const val DIRECTORY = "./day02" fun main() { fun calculateScoreForRound(elfPlay: ElfHand, playerResponse: PlayerResponse): Int { val outcome = playerResponse.playAgainst(elfPlay) return outcome.score + playerResponse.score } fun toPair(it: String) = it.split(" ", ignoreCase = true).zipWithNext().first() fun part1(input: List<String>): Int = input .map { toPair(it) } .sumOf { calculateScoreForRound(ElfHand(it.first), PlayerResponse(it.second)) } fun getMissingPlayerResponse(elfHand: ElfHand, outcome: Outcome): ElfHand = when { elfHand.play == "A" && outcome == Outcome.DEFEAT -> ElfHand("C") elfHand.play == "A" && outcome == Outcome.DRAW -> ElfHand("A") elfHand.play == "A" && outcome == Outcome.VICTORY -> ElfHand("B") elfHand.play == "B" && outcome == Outcome.DEFEAT -> ElfHand("A") elfHand.play == "B" && outcome == Outcome.DRAW -> ElfHand("B") elfHand.play == "B" && outcome == Outcome.VICTORY -> ElfHand("C") elfHand.play == "C" && outcome == Outcome.DEFEAT -> ElfHand("B") elfHand.play == "C" && outcome == Outcome.DRAW -> ElfHand("C") elfHand.play == "C" && outcome == Outcome.VICTORY -> ElfHand("A") else -> error("Unknown match!") } fun calculateScoreForSecondRound(elfPlay: ElfHand, outcome: Outcome): Int = getMissingPlayerResponse(elfPlay, outcome).score + outcome.score fun part2(input: List<String>): Int = input .map { toPair(it) } .sumOf { calculateScoreForSecondRound(ElfHand(it.first), Outcome.fromEncryptedMessage(it.second)) } val input = readInput("${DIRECTORY}/Day02") println(part1(input)) println(part2(input)) } private enum class Outcome(val score: Int) { DEFEAT(0), DRAW(3), VICTORY(6) ; companion object { fun fromEncryptedMessage(s: String) = when (s) { "X" -> DEFEAT "Y" -> DRAW "Z" -> VICTORY else -> error("Unknown encrypted outcome!") } } } private data class ElfHand(val play: String) { val score: Int = when (play) { "A" -> 1 "B" -> 2 "C" -> 3 else -> 0 } } private data class PlayerResponse(val play: String) { val score: Int = when (play) { "X" -> 1 "Y" -> 2 "Z" -> 3 else -> 0 } fun playAgainst(elfHand: ElfHand): Outcome = when { elfHand.play == "A" && play == "X" -> Outcome.DRAW elfHand.play == "A" && play == "Y" -> Outcome.VICTORY elfHand.play == "A" && play == "Z" -> Outcome.DEFEAT elfHand.play == "B" && play == "X" -> Outcome.DEFEAT elfHand.play == "B" && play == "Y" -> Outcome.DRAW elfHand.play == "B" && play == "Z" -> Outcome.VICTORY elfHand.play == "C" && play == "X" -> Outcome.VICTORY elfHand.play == "C" && play == "Y" -> Outcome.DEFEAT elfHand.play == "C" && play == "Z" -> Outcome.DRAW else -> error("Unknown match.") } }
0
Kotlin
0
0
bd243c61bf8aae81daf9e50b2117450c4f39e18c
3,078
kotlin-advent-2022
Apache License 2.0
src/main/kotlin/net/voldrich/aoc2021/Day18.kt
MavoCz
434,703,997
false
{"Kotlin": 119158}
package net.voldrich.aoc2021 import net.voldrich.BaseDay import kotlin.math.max // https://adventofcode.com/2021/day/18 fun main() { Day18().run() } class Day18 : BaseDay() { override fun task1() : Int { val finalSnailNumber = input.lines().map(::SnailNumber).reduce { a, b -> a.add(b) } return finalSnailNumber.calculateValue() } override fun task2() : Int { val numberList = input.lines().map(::SnailNumber).toList() var maxValue = Int.MIN_VALUE for (i in numberList) { for (j in numberList) { if (i != j) { maxValue = max(i.add(j).calculateValue(), maxValue) maxValue = max(j.add(i).calculateValue(), maxValue) } } } return maxValue } fun parseSnailNumber(numStr : String) : SnailNumber { return SnailNumber(numStr) } class SnailNumber { val rootPair : NumPair constructor(numStr : String) { rootPair = readSnailNumber(numStr.iterator()) as NumPair println(rootPair.toString()) } constructor(rootPair : NumPair) { this.rootPair = rootPair } private fun readSnailNumber(iterator: CharIterator): NumBase { val char = iterator.nextChar() if (char == '[') { val pair = NumPair() pair.left = readSnailNumber(iterator) assert(iterator.nextChar() == ',') pair.right = readSnailNumber(iterator) assert(iterator.nextChar() == ']') return pair } else if (char.isDigit()) { return NumValue(char.digitToInt()) } else throw Exception("Unexpected character $char") } fun add(other: SnailNumber) : SnailNumber { val pair = NumPair() pair.left = this.rootPair.clone() pair.right = other.rootPair.clone() val snailNumber = SnailNumber(pair) snailNumber.reduce() println("$this + $other = $snailNumber") return snailNumber } fun reduce() { //println("reduce $this") do { analyze() if (pairsToExplode.isNotEmpty()) { val explodeCandidate = pairsToExplode.first() val exPair = explodeCandidate.pair explodeCandidate.closestLeft?.add(exPair.left as NumValue) explodeCandidate.closestRight?.add(exPair.right as NumValue) exPair.parent.replace(exPair, NumValue(0)) //println("explode $explodeCandidate $this") continue } if (valuesToSplit.isNotEmpty()) { val splitValue = valuesToSplit.first() val pair = NumPair() val halfFloor = splitValue.value / 2 pair.left = NumValue(halfFloor) pair.right = NumValue(splitValue.value - halfFloor) splitValue.parent.replace(splitValue, pair) //println("split $splitValue $this") continue } } while (pairsToExplode.isNotEmpty() || valuesToSplit.isNotEmpty()) } val pairsToExplode = ArrayList<ExplodeCandidate>() val valuesToSplit = ArrayList<NumValue>() fun analyze() { pairsToExplode.clear() valuesToSplit.clear() analyze(rootPair, 1, null, null) } fun analyze(pair: NumPair, depth: Int, closestLeft: NumValue?, closestRight: NumValue?) { val left = pair.left val right = pair.right if (left is NumValue && left.value > 9) { valuesToSplit.add(left) } if (left is NumPair) { analyze(left, depth + 1, closestLeft, findClosesRight(pair)) } if (left is NumValue && right is NumValue && depth > 4) { pairsToExplode.add(ExplodeCandidate(pair, closestLeft, closestRight)) } if (right is NumPair) { analyze(right, depth + 1, findClosesLeft(pair), closestRight) } if (right is NumValue && right.value > 9) { valuesToSplit.add(right) } } data class ExplodeCandidate(val pair: NumPair, val closestLeft: NumValue?, val closestRight: NumValue?) private fun findClosesRight(pair: NumPair): NumValue { if (pair.right is NumValue) { return pair.right as NumValue } var leftMost = pair.right while (leftMost is NumPair) { leftMost = leftMost.left } if (leftMost is NumValue) { return leftMost } throw Exception("Right value not found") } private fun findClosesLeft(pair: NumPair): NumValue { if (pair.left is NumValue) { return pair.left as NumValue } var rightMost = pair.left while (rightMost is NumPair) { rightMost = rightMost.right } if (rightMost is NumValue) { return rightMost } throw Exception("Left value not found") } fun calculateValue() : Int { return rootPair.calculateValue() } override fun toString(): String { return rootPair.toString() } } class NumPair : NumBase() { var left: NumBase = NumValue(0) set(value) { value.parent = this field = value } var right: NumBase = NumValue(0) set(value) { value.parent = this field = value } override fun toString(builder: StringBuilder) { builder.append('[') left.toString(builder) builder.append(',') right.toString(builder) builder.append(']') } fun replace(oldPair: NumBase, newPair: NumBase) { if (left == oldPair) left = newPair if (right == oldPair) right = newPair newPair.parent = this } override fun calculateValue(): Int { return 3 * left.calculateValue() + 2 * right.calculateValue() } override fun clone(): NumBase { val clone = NumPair() clone.left = left.clone() clone.right = right.clone() return clone } } class NumValue(var value: Int = 0) : NumBase() { override fun toString(builder: StringBuilder) { builder.append(value) } override fun calculateValue(): Int { return value } override fun clone(): NumBase { return NumValue(value) } fun add(other: NumValue) { this.value += other.value } } abstract class NumBase { lateinit var parent: NumPair abstract fun toString(builder: StringBuilder) override fun toString(): String { val sb = StringBuilder() toString(sb) return sb.toString() } abstract fun calculateValue(): Int abstract fun clone(): NumBase } }
0
Kotlin
0
0
0cedad1d393d9040c4cc9b50b120647884ea99d9
7,528
advent-of-code
Apache License 2.0
13/part_one.kt
ivanilos
433,620,308
false
{"Kotlin": 97993}
import java.io.File fun readInput() : Paper { val lines = File("input.txt") .readLines() val dots = mutableListOf<Pair<Int, Int>>() val instructions = mutableListOf<Pair<Char, Int>>() parseInput(lines, dots, instructions) return Paper(dots, instructions) } fun parseInput(inputLines : List<String>, dots : MutableList<Pair<Int, Int>>, instructions: MutableList<Pair<Char, Int>>) { var readingInstructions = false for (line in inputLines) { if (line.isEmpty()) { readingInstructions = true } else if (readingInstructions) { instructions.add(parseInstruction(line)) } else { dots.add(parseDot(line)) } } } fun parseDot(line : String) : Pair<Int, Int> { val (x, y) = line.split(",").map { it.toInt() } return Pair(x, y) } fun parseInstruction(line : String) : Pair<Char, Int> { val regex = """fold along ([x|y])=(\d+)""".toRegex() val (axis, pos) = regex.find(line)?.destructured!! return Pair(axis[0], pos.toInt()) } class Paper(dots : MutableList<Pair<Int, Int>>, instructions : MutableList<Pair<Char, Int>>) { var dots : MutableSet<Pair<Int, Int>> private var instructions : List<Pair<Char,Int>> init { this.dots = dots.toMutableSet() this.instructions = instructions } fun foldOnce() { val updatedDots = mutableSetOf<Pair<Int, Int>>() for (dot in dots) { if (instructions[0].first == 'x') { val newX = if (dot.first < instructions[0].second) dot.first else 2 * instructions[0].second - dot.first val newY = dot.second updatedDots.add(Pair(newX, newY)) } else { val newX = dot.first val newY = if (dot.second < instructions[0].second) dot.second else 2 * instructions[0].second - dot.second updatedDots.add(Pair(newX, newY)) } } dots = updatedDots } } fun solve(paper: Paper): Int { paper.foldOnce() return paper.dots.size } fun main() { val paper = readInput() val ans = solve(paper) println(ans) }
0
Kotlin
0
3
a24b6f7e8968e513767dfd7e21b935f9fdfb6d72
2,201
advent-of-code-2021
MIT License
src/main/kotlin/aoc2022/Day08.kt
w8mr
572,700,604
false
{"Kotlin": 140954}
package aoc2022 import aoc.* import aoc.parser.digit import aoc.parser.followedBy import aoc.parser.oneOrMore class Day08 { val row = oneOrMore(digit()) followedBy "\n" val parser = oneOrMore(row) fun part1(input: String): Int { val grid = parser.parse(input) val height = grid.size val width = grid[0].size val visible = mutableSetOf<Coord>() fun checkTrees( main: IntProgression, sub: IntProgression, toCoord: (a: Int, b: Int) -> Coord ) { for (a in main) { var highest = -1 for (b in sub) { val c = toCoord(a, b) val v = grid[c.y][c.x] if (v > highest) { visible.add(c) highest = v } } } } checkTrees(0..height-1, 0..width-1) { y, x -> Coord(x,y) } checkTrees(0..height-1, width-1 downTo 0) { y, x -> Coord(x,y) } checkTrees(0..width-1, 0..height-1) { x, y -> Coord(x,y) } checkTrees(0..width-1, height-1 downTo 0) { x, y -> Coord(x,y) } return visible.size } fun part2(input: String): Int { val grid = parser.parse(input) val height = grid.size val width = grid[0].size var high = -1 fun check(c: Coord, range: IntProgression, toCoord: (c: Coord, i: Int) -> Coord): Int { val v = grid[c.y][c.x] var count = 0 for (i in range) { count++ val c2 = toCoord(c, i) if (grid[c2.y][c2.x] >= v) break } return count } for (y in 1..height-2) { for (x in 1..width-2) { val up = check(Coord(x,y), 1.. y) { c, i -> Coord(c.x, c.y - i) } val down = check(Coord(x,y), 1.. height-1-y) { c, i -> Coord(c.x, c.y + i)} val left = check(Coord(x,y), 1.. x) { c, i -> Coord(c.x - i, c.y) } val right = check(Coord(x,y), 1.. width-1-x) { c, i -> Coord(c.x + i, c.y) } val score = up * down * left * right if (score>high) { high = score } } } return high } }
0
Kotlin
0
0
e9bd07770ccf8949f718a02db8d09daf5804273d
2,343
aoc-kotlin
Apache License 2.0
src/Day10.kt
akijowski
574,262,746
false
{"Kotlin": 56887, "Shell": 101}
data class Signal(var cycle: Int = 1, var x: Int = 1) { var sum = 0 val screen = MutableList(6) { MutableList(40) { "." } } fun process() { if (isComputeTime()) { sum += cycle * x } cycle++ } fun processDraw() { val hPos = (cycle - 1) % 40 val vPos = (cycle - 1) / 40 if (hPos in (x - 1)..(x + 1)) { screen[vPos][hPos] = "#" } cycle++ } private fun isComputeTime() = cycle % 40 == 20 } fun main() { fun part1(input: List<String>): Int { return input.fold(Signal()) { sig, ins -> if (ins == "noop") sig.process() else { repeat(2) { sig.process() } sig.x += ins.split(" ").last().toInt() } sig }.sum } fun part2(input: List<String>) { println("Display:") input.fold(Signal()) { sig, ins -> if (ins == "noop") sig.processDraw() else { repeat(2) { sig.processDraw() } sig.x += ins.split(" ").last().toInt() } sig }.screen .forEach { println(it.joinToString(separator = " ")) } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day10_test") check(part1(testInput) == 13140) val input = readInput("Day10") println(part1(input)) part2(input) }
0
Kotlin
1
0
84d86a4bbaee40de72243c25b57e8eaf1d88e6d1
1,460
advent-of-code-2022
Apache License 2.0
Kotlin/src/main/kotlin/org/algorithm/structures/SegTree.kt
raulhsant
213,479,201
true
{"C++": 1035543, "Kotlin": 114509, "Java": 27177, "Python": 16568, "Shell": 999, "Makefile": 187}
package org.algorithm.structures class SegTree(val array: IntArray) { private var treeArray: MutableList<Int> private var arrSize: Int init { treeArray = MutableList<Int>(4 * array.size) { 0 } initSegTree(array, 0, 0, array.size - 1) arrSize = array.size println(treeArray) } private fun initSegTree(array: IntArray, treeIndex: Int, start: Int, end: Int): Int { if (start == end) { treeArray[treeIndex] = array[start] } else { val mid: Int = start + (end - start) / 2 treeArray[treeIndex] = initSegTree(array, 2 * treeIndex + 1, start, mid) + initSegTree(array, 2 * treeIndex + 2, mid + 1, end) } return treeArray[treeIndex] } private fun queryHelper(treeIndex: Int, currStart: Int, currEnd: Int, start: Int, end: Int): Int { return if (currStart > end || currEnd < start) { return 0 } else if (currStart == currEnd) { treeArray[treeIndex] } else if (currStart >= start && currEnd <= end) { treeArray[treeIndex] } else { val mid = currStart + (currEnd - currStart) / 2 queryHelper(2 * treeIndex + 1, currStart, mid, start, end) + queryHelper(2 * treeIndex + 2, mid + 1, currEnd, start, end) } } private fun updateHelper(treeIndex: Int, currStart: Int, currEnd: Int, start: Int, end: Int, value: Int): Int { if (currStart > end || currEnd < start) { return treeArray[treeIndex] } if (currStart == currEnd) { treeArray[treeIndex] += value } else { val mid: Int = currStart + (currEnd - currStart) / 2 treeArray[treeIndex] = updateHelper(2 * treeIndex + 1, currStart, mid, start, end, value) + updateHelper(2 * treeIndex + 2, mid + 1, currEnd, start, end, value) } return treeArray[treeIndex] } fun queryInterval(start: Int, end: Int): Int { return queryHelper(0, 0, arrSize - 1, start, end) } fun updateInterval(start: Int, end: Int, value: Int) { updateHelper(0, 0, arrSize - 1, start, end, value) } fun printSegTree() { println(treeArray) } } //fun main(args: Array<String>) { // val input = intArrayOf(1,2,3,1,3,5,6,4,1,2) // val segTree = SegTree(input) // println(segTree.queryInterval(3,7)) // segTree.updateInterval(0,3,2) // segTree.printSegTree() //}
0
C++
0
0
1578a0dc0a34d63c74c28dd87b0873e0b725a0bd
2,489
algorithms
MIT License
kotlin/src/x2022/day12/day12.kt
freeformz
573,924,591
false
{"Kotlin": 43093, "Go": 7781}
package day12 import readInput typealias Point = Pair<Int, Int> fun Point.neighbours() = sequenceOf( first - 1 to second, first to second + 1, first + 1 to second, first to second - 1 ) fun main() { fun parseInput(input: List<String>): Triple<Point, Point, Map<Point, Char>> { lateinit var start: Point lateinit var end: Point val parsed = input.withIndex().flatMap { (y, line) -> line.withIndex().map { (x, char) -> val point = y to x when (char) { 'S' -> point to 'a'.also { start = point } 'E' -> point to 'z'.also { end = point } else -> point to char } } }.toMap() return Triple(start, end, parsed) } fun countPaths(end: Point, parsed: Map<Point, Char>): Map<Point, Int> { return buildMap { var count = 0 var candidates = setOf(end) while (candidates.isNotEmpty()) { candidates = buildSet { for (candidate in candidates) { if (putIfAbsent(candidate, count) != null) continue val value = parsed.getValue(candidate) for (neighbour in candidate.neighbours()) { parsed[neighbour]?.also { if (value - it <= 1) { add(neighbour) } } } } } count++ } } } fun partOne(input: List<String>) { val (start, end, parsed) = parseInput(input) val countPaths = countPaths(end, parsed) println(countPaths[start]) } fun partTwo(input: List<String>) { val (_, end, parsed) = parseInput(input) val countPaths = countPaths(end, parsed) println(parsed.filterValues('a'::equals).filterKeys(countPaths::containsKey).keys.minOf(countPaths::getValue)) } println("partOne test") partOne(readInput("day12.test")) println() println("partOne") partOne(readInput("day12")) println() println("partTwo with test input") partTwo(readInput("day12.test")) println() println("partTwo") partTwo(readInput("day12")) }
0
Kotlin
0
0
5110fe86387d9323eeb40abd6798ae98e65ab240
2,412
adventOfCode
Apache License 2.0
advent-of-code-2020/src/test/java/aoc/Day16TicketTranslation.kt
yuriykulikov
159,951,728
false
{"Kotlin": 1666784, "Rust": 33275}
package aoc import org.assertj.core.api.Assertions.assertThat import org.junit.Test class Day16TicketTranslation { @Test fun silverTest() { assertThat(ticketScanningErrorRate(testInput)).isEqualTo(71) } data class Rule( val name: String, val ranges: List<IntRange> ) { fun test(number: Int): Boolean { return ranges.any { number in it } } } private fun ticketScanningErrorRate(input: String): Int { val rules: List<Rule> = parseRules(input) return parseNearbyTickets(input) .flatten() .filter { number -> rules.none { rule -> rule.test(number) } } .sum() } private fun parseNearbyTickets(input: String) = input.substringAfter("nearby tickets:") .lines() .filter { it.isNotEmpty() } .map { line -> line.split(",").map { it.toInt() } } private fun parseRules(input: String) = input.substringBefore("\n\n").lines() .map { line -> val ranges = line.substringAfter(": ").split(" or ").map { range -> range.substringBefore("-").toInt()..range.substringAfter("-").toInt() } Rule(line.substringBefore(":"), ranges) } @Test fun testYourTicket() { assertThat(parseYourTicket(testInput)).isEqualTo(listOf(7, 1, 14)) } private fun parseYourTicket(input: String): List<Int> { return input.substringAfter("your ticket:") .substringBefore("nearby tickets:") .trim() .split(",") .mapNotNull { it.toIntOrNull() } } @Test fun gold() { assertThat(findDepartures(taskInput)).isEqualTo(1439429522627) } /** * Once you work out which field is which, look for the six fields on your ticket that start with the word departure. * What do you get if you multiply those six values together? */ private fun findDepartures(input: String): Long { val rules = parseRules(input) val myTicket = parseYourTicket(input) val valid = parseNearbyTickets(input).filter { ticketFields -> ticketFields.all { field -> rules.any { rule -> rule.test(field) } } } val columns: List<List<Int>> = (0..myTicket.lastIndex).map { i -> valid.map { it[i] } } val hypothesis = columns.mapIndexed { index, values -> index to rules.filter { rule -> values.all { rule.test(it) } } .map { it.name } .sorted() } .sortedBy { (key, values) -> values.size } val ruleToIndex = hypothesis .fold(setOf()) { confirmed: Set<Pair<String, Int>>, (index, rules) -> val nextRule: String = rules.minus(confirmed.map { it.first }).apply { require(size == 1) }.first() confirmed.plus(nextRule to index) } return ruleToIndex.filter { (rule, index) -> rule.startsWith("departure") } .map { (rule, index) -> myTicket[index].toLong() } .reduce(Long::times) } private val testInput = """ class: 1-3 or 5-7 row: 6-11 or 33-44 seat: 13-40 or 45-50 your ticket: 7,1,14 nearby tickets: 7,3,47 40,4,50 55,2,20 38,6,12 """.trimIndent() private val taskInput = """ departure location: 29-766 or 786-950 departure station: 40-480 or 491-949 departure platform: 46-373 or 397-957 departure track: 33-657 or 673-970 departure date: 31-433 or 445-961 departure time: 33-231 or 250-966 arrival location: 48-533 or 556-974 arrival station: 42-597 or 620-957 arrival platform: 32-119 or 140-967 arrival track: 28-750 or 762-973 class: 26-88 or 101-950 duration: 30-271 or 293-974 price: 33-712 or 718-966 route: 49-153 or 159-953 row: 36-842 or 851-972 seat: 43-181 or 194-955 train: 29-500 or 513-964 type: 32-59 or 73-974 wagon: 47-809 or 816-957 zone: 44-451 or 464-955 your ticket: 151,103,173,199,211,107,167,59,113,179,53,197,83,163,101,149,109,79,181,73 nearby tickets: 339,870,872,222,255,276,706,890,583,718,924,118,201,141,59,581,931,143,221,919 400,418,807,726,84,142,820,112,228,687,335,855,761,740,627,532,369,313,147,620 474,926,741,424,632,982,876,926,738,936,300,726,400,321,348,160,421,464,78,258 337,683,885,368,214,215,620,650,321,311,200,696,838,880,526,812,821,891,829,204 678,69,480,939,219,736,628,948,178,296,204,890,199,526,736,210,170,923,228,726 574,55,871,945,347,207,840,707,442,791,159,216,427,312,947,326,738,801,264,54 811,259,417,932,870,634,945,408,706,766,303,402,942,50,415,150,839,674,904,836 670,358,701,172,231,914,875,205,586,517,576,206,796,400,363,303,295,932,73,308 319,949,312,803,217,6,719,870,202,883,111,532,467,801,83,202,331,637,930,412 580,262,196,529,401,806,446,104,326,657,589,789,876,817,470,653,167,191,634,678 720,217,118,422,190,115,684,827,317,228,524,569,531,471,322,408,896,566,875,302 678,683,218,820,896,303,296,316,229,758,114,261,825,750,901,428,479,556,373,404 502,259,577,77,260,588,340,199,626,575,171,422,372,83,111,902,300,863,800,886 577,216,195,804,298,948,83,807,878,656,740,743,854,740,219,331,714,176,683,199 492,187,259,528,853,80,808,887,149,723,324,922,170,323,884,825,710,562,416,471 702,55,141,261,743,256,632,693,787,581,363,851,578,74,164,146,413,224,829,282 370,161,470,207,876,57,564,103,195,216,468,632,161,734,487,150,570,251,311,196 242,430,115,575,806,258,109,85,433,794,85,258,647,596,84,339,215,879,203,74 912,449,174,371,857,556,743,537,521,643,903,745,764,207,295,896,431,901,592,332 687,361,855,683,298,828,421,894,163,214,308,110,643,495,106,198,613,205,322,582 318,578,83,318,150,182,298,740,424,306,411,895,50,265,887,465,912,262,294,428 320,948,74,114,643,801,928,280,868,930,822,140,620,696,627,520,692,820,526,764 622,477,314,253,419,73,333,924,750,432,705,894,114,827,364,946,577,269,789,463 639,742,840,541,656,787,222,637,728,734,558,744,173,801,80,629,634,572,151,326 830,468,597,75,259,762,331,315,151,369,308,419,447,207,523,268,118,719,501,839 496,312,525,343,559,77,114,404,362,595,656,301,622,337,741,818,816,352,1,449 432,512,627,739,729,627,218,829,595,471,641,447,639,350,220,718,573,319,859,363 646,368,258,320,916,520,328,327,180,357,646,620,530,208,269,84,264,53,184,163 904,657,329,897,327,339,674,803,110,327,308,78,883,353,150,446,296,645,539,932 472,726,685,676,406,419,594,419,699,364,416,868,106,53,662,856,859,571,674,571 301,741,900,869,259,727,557,975,334,913,496,948,929,79,165,680,838,465,591,902 939,201,586,897,948,725,625,224,923,801,910,723,361,338,55,217,721,300,674,777 362,211,592,573,711,831,170,949,171,408,647,578,228,349,629,780,582,567,84,349 317,874,623,704,934,526,898,797,447,485,400,589,679,109,827,107,353,807,859,513 519,108,304,162,888,88,742,637,789,923,749,404,171,175,708,432,559,200,557,444 787,589,518,397,762,200,734,222,468,252,306,560,558,701,905,656,155,689,51,258 354,159,938,734,932,636,478,162,562,718,315,712,933,862,530,877,118,535,366,797 189,338,517,302,414,401,167,905,947,500,895,940,405,222,864,706,835,352,269,825 757,404,212,426,628,113,945,480,398,271,353,364,225,804,643,84,416,728,936,223 337,529,631,589,909,314,174,820,257,199,822,359,344,445,929,20,513,450,212,928 254,927,865,202,851,733,897,329,433,224,319,674,857,722,837,207,419,84,728,375 416,464,822,368,920,175,0,213,799,200,648,529,398,889,678,407,180,870,496,786 712,335,80,824,826,416,261,400,904,630,255,691,259,723,344,354,786,857,774,195 945,257,57,260,642,817,934,909,574,358,269,683,764,176,365,427,549,878,500,791 807,140,308,885,866,623,80,111,648,848,572,643,853,854,560,934,699,52,580,164 895,590,647,730,540,874,255,115,304,117,224,399,168,819,420,525,306,160,580,595 594,265,401,920,855,62,352,706,908,835,925,908,829,620,476,51,251,73,875,696 261,748,411,706,409,53,470,202,227,918,653,398,516,518,416,187,917,836,649,222 288,690,877,468,620,451,147,919,251,408,836,584,319,729,640,445,673,87,650,856 308,806,477,875,329,928,948,800,417,574,220,991,355,51,693,838,747,794,498,913 706,582,499,834,887,109,677,857,280,407,651,517,468,407,403,303,515,881,656,523 256,597,344,577,636,702,561,738,683,884,268,858,73,201,421,721,646,739,424,992 903,211,920,623,160,152,567,786,852,423,179,258,690,493,110,505,823,303,721,373 397,893,747,819,729,88,651,893,699,229,744,948,712,104,741,643,511,854,876,706 929,880,820,532,259,621,307,480,900,59,915,188,863,624,119,252,928,935,451,885 335,893,475,733,787,850,629,839,530,231,451,942,260,718,654,473,255,495,406,464 451,822,629,745,226,595,295,862,408,592,498,474,77,110,845,354,906,424,913,936 75,891,446,347,468,521,312,320,346,579,900,205,528,307,370,890,8,269,826,566 566,353,58,360,629,793,649,567,259,736,261,531,118,880,244,145,581,172,885,471 107,371,947,936,250,468,624,888,334,622,947,327,837,941,360,521,754,199,688,905 313,163,370,367,8,174,341,792,153,736,725,581,313,203,872,225,590,720,841,475 210,823,329,556,763,691,371,202,807,902,741,413,303,832,651,802,473,358,990,897 718,652,891,367,702,640,645,883,817,231,590,842,350,820,291,681,422,859,691,338 349,408,890,915,116,719,872,589,586,620,116,206,683,353,317,81,319,86,849,797 84,520,856,641,254,206,209,356,178,476,728,114,559,802,579,377,298,112,941,853 518,741,500,466,796,676,833,235,330,854,494,762,58,923,908,228,335,433,85,565 418,697,943,513,854,907,824,872,479,81,372,324,688,216,299,407,621,492,63,685 559,652,645,107,685,577,870,370,509,58,371,85,445,800,174,255,412,475,640,837 85,366,789,597,625,701,275,166,632,82,854,422,628,863,855,213,448,213,517,263 447,373,853,469,912,545,712,695,749,673,299,647,744,826,893,367,865,448,116,943 570,520,859,919,742,221,577,316,946,358,82,910,892,595,584,559,644,593,665,879 645,345,399,430,697,86,641,642,239,764,325,253,728,82,891,372,402,270,400,153 144,533,735,296,806,648,521,747,115,194,405,764,188,861,838,584,872,373,738,744 446,180,652,85,429,330,172,517,629,566,167,922,177,884,751,868,919,102,494,930 306,946,257,637,886,231,836,566,108,210,357,720,791,819,826,489,346,159,420,883 360,622,764,398,398,82,323,165,403,185,557,447,635,171,493,211,736,570,766,79 840,174,102,911,424,821,878,311,498,785,798,572,211,268,59,177,732,853,475,165 109,228,693,210,300,882,184,419,872,939,706,693,596,635,625,905,566,351,202,727 686,414,806,638,869,737,407,506,912,465,448,738,913,118,514,321,363,180,905,345 928,348,305,110,916,827,222,681,197,313,827,903,148,761,498,523,643,297,430,897 317,816,623,799,152,518,491,801,934,762,694,708,583,257,818,400,931,358,899,755 418,943,493,888,559,252,826,222,680,726,426,639,104,579,886,732,844,111,856,817 478,728,865,930,591,340,734,401,900,399,116,839,78,106,315,111,667,631,302,478 744,691,703,984,901,301,75,432,687,336,630,421,527,116,944,111,930,641,497,729 529,930,589,712,588,59,817,76,566,704,319,253,935,423,692,753,626,217,299,142 911,403,257,196,179,178,55,627,468,546,684,327,255,923,912,252,646,266,206,207 889,638,475,473,866,227,789,148,72,57,50,366,269,743,878,901,627,227,586,199 833,976,570,51,335,212,173,110,652,424,446,858,677,73,787,107,877,159,587,165 333,831,361,52,165,59,145,528,935,57,262,366,884,198,354,223,985,808,170,521 928,301,762,573,572,832,728,708,933,150,689,308,680,579,603,313,354,582,368,477 437,686,400,937,162,594,878,414,170,209,259,886,432,208,348,228,399,519,708,574 85,633,54,353,886,917,161,499,496,78,804,119,652,496,511,919,476,306,728,51 451,718,399,578,639,651,293,940,364,75,450,364,799,341,851,295,465,335,754,266 371,268,852,750,706,735,113,752,863,795,467,572,794,497,838,310,160,367,251,471 883,269,624,268,268,557,68,197,590,330,678,316,429,266,877,414,896,733,899,746 991,521,595,300,422,471,686,620,159,341,448,730,694,513,342,575,743,213,790,684 178,252,643,595,697,59,703,328,424,76,567,173,254,880,805,728,519,798,332,157 297,373,312,687,566,491,571,109,448,581,720,873,552,695,806,446,351,854,594,150 260,216,58,789,676,180,708,785,115,252,331,344,498,334,570,935,200,105,208,687 207,484,171,323,466,722,794,833,323,50,763,347,729,252,710,176,910,328,74,649 938,293,838,840,341,429,702,483,259,852,900,112,143,180,881,526,519,58,466,750 700,172,253,365,871,563,643,520,945,587,253,852,492,731,493,281,310,112,573,220 425,941,103,586,871,801,807,918,843,898,522,251,799,177,763,144,195,228,408,84 149,256,792,82,711,419,533,946,835,271,76,681,172,141,120,451,178,633,358,297 595,79,203,762,856,988,556,562,791,528,635,678,865,205,449,870,823,341,260,817 407,24,904,411,818,365,859,654,491,817,297,86,674,218,360,840,620,54,806,708 466,210,258,641,199,766,76,256,651,267,824,343,940,405,198,701,431,259,205,536 561,164,326,563,765,897,177,805,207,571,425,572,349,734,907,233,255,310,54,88 934,866,361,699,709,861,140,680,217,699,172,647,572,923,56,319,164,475,136,255 689,587,52,885,751,517,624,915,790,347,172,366,162,941,893,916,358,419,421,226 562,516,58,626,940,802,840,212,473,230,887,875,180,893,332,942,274,896,718,170 863,557,196,692,263,53,145,340,211,61,117,816,417,108,171,111,683,312,559,75 250,808,732,474,174,261,312,587,349,167,573,934,790,334,819,643,784,212,564,500 480,103,319,230,477,428,119,563,896,421,568,712,923,519,737,672,882,398,496,625 424,787,54,256,917,880,415,466,309,410,59,836,230,189,594,927,620,730,561,168 584,104,415,451,747,808,349,742,54,410,315,711,531,277,705,521,368,259,144,708 365,467,337,75,993,147,223,519,150,206,864,946,763,51,596,105,736,310,695,146 79,365,85,309,649,676,324,597,938,310,733,942,223,693,316,904,413,229,833,484 946,921,52,450,229,180,700,268,16,701,919,885,730,682,494,836,786,852,171,220 295,750,718,149,626,497,335,819,518,624,199,705,631,825,418,897,468,19,698,866 556,584,807,269,721,213,420,721,870,812,88,359,180,829,738,789,295,877,151,360 940,333,838,622,637,173,325,923,547,866,304,398,943,789,822,916,639,679,261,340 480,266,711,197,322,112,362,169,705,828,84,862,719,17,593,864,142,561,916,356 337,675,859,872,586,689,329,949,771,573,267,932,200,526,333,161,350,115,300,697 562,362,942,150,924,215,330,162,753,565,498,321,307,709,641,697,863,578,205,868 655,464,886,153,318,402,818,733,490,73,354,853,936,858,637,473,203,301,177,312 705,429,402,348,882,471,644,193,427,687,804,841,414,270,332,720,228,633,787,880 265,927,325,889,345,403,88,168,219,696,230,570,733,521,833,217,482,711,522,742 335,702,271,178,592,569,845,913,176,649,299,916,788,253,205,860,146,113,710,168 264,219,87,368,798,852,470,224,646,367,355,710,655,17,649,219,942,169,314,118 54,710,880,343,270,468,269,850,167,50,675,303,688,750,419,870,324,674,728,914 528,423,153,101,939,471,418,21,414,926,656,446,211,826,681,863,897,530,839,347 909,298,338,890,335,216,693,171,584,480,228,987,198,252,582,657,641,218,824,791 254,578,837,816,936,271,368,268,167,101,685,516,743,399,465,542,495,626,888,319 268,140,857,844,79,763,115,322,735,159,409,519,857,699,317,917,520,910,75,728 628,2,410,568,299,252,168,683,587,303,743,141,702,723,498,911,766,165,465,800 431,583,212,933,253,358,981,114,766,764,942,361,524,586,203,730,562,627,449,926 631,337,858,720,866,567,723,828,731,926,145,204,640,653,231,724,688,371,482,144 83,571,836,361,797,349,834,809,704,293,839,301,271,219,797,743,803,637,719,811 844,59,356,851,692,180,786,476,703,801,323,797,943,86,432,329,943,596,868,745 230,922,302,180,118,241,231,867,469,639,161,207,807,325,825,74,338,526,722,855 628,0,416,116,143,467,262,937,269,590,80,926,176,523,519,674,523,911,651,366 873,934,81,406,163,945,905,216,359,795,819,554,314,583,722,568,597,317,204,880 433,683,181,426,583,631,826,873,894,938,588,854,308,267,885,222,861,843,719,144 905,825,294,143,203,465,794,674,346,364,180,88,865,168,905,947,897,943,252,717 492,416,629,719,827,108,921,163,745,930,500,343,426,740,777,326,574,149,250,589 940,340,584,722,251,520,880,532,151,398,795,886,869,253,185,304,468,311,852,877 833,371,112,810,56,516,829,352,641,466,295,528,476,718,413,725,559,917,818,533 677,355,203,373,356,398,573,831,750,410,697,809,53,597,435,946,173,890,905,152 588,465,475,201,523,521,340,897,427,834,875,718,635,407,733,323,908,341,440,595 478,496,748,82,890,210,623,809,315,273,58,681,655,101,640,325,621,337,494,299 216,761,834,342,766,808,466,325,51,480,221,721,433,411,403,342,267,620,218,255 301,58,310,355,891,149,474,681,76,677,518,734,532,745,908,333,519,418,278,446 842,527,339,354,940,828,198,478,413,181,695,84,637,988,712,938,165,147,696,211 795,712,522,698,402,310,813,465,910,630,263,331,731,706,936,686,226,829,199,828 575,786,691,828,447,512,730,270,56,722,794,108,175,346,639,174,217,347,652,822 530,732,51,688,74,696,416,309,264,521,209,727,710,259,361,401,559,909,260,510 368,590,119,906,200,725,329,696,942,140,118,933,474,847,657,557,652,823,162,332 107,940,194,558,335,798,926,366,528,918,880,867,695,491,268,226,70,765,150,732 161,684,179,184,732,749,265,529,349,87,934,467,723,111,216,201,861,795,449,801 649,141,914,636,468,196,656,703,813,897,852,472,347,56,337,809,736,901,707,747 594,141,425,316,174,573,885,357,873,595,726,334,59,745,717,887,207,200,310,357 732,368,862,346,795,657,531,464,721,356,732,422,114,735,328,421,741,332,394,164 264,261,806,898,471,170,763,819,642,690,500,267,847,592,73,906,171,175,909,532 77,852,267,578,219,913,795,839,85,920,645,560,303,871,404,804,595,206,727,138 264,323,50,338,301,417,702,817,791,666,172,674,597,721,876,705,576,449,786,945 880,633,356,366,197,692,209,426,261,940,643,634,926,160,269,590,191,293,928,529 295,700,113,627,643,557,141,820,379,140,430,677,791,450,686,118,322,479,495,423 467,749,178,367,520,566,938,114,176,226,894,470,908,824,806,373,436,596,497,575 816,233,748,518,829,424,901,643,56,565,333,570,561,948,114,430,632,901,301,708 208,268,409,297,571,838,722,62,889,885,256,725,166,869,168,150,647,406,498,762 646,695,359,76,710,363,748,887,416,515,696,227,166,86,742,308,140,721,311,663 635,479,734,830,338,224,563,359,88,587,676,370,582,871,840,476,247,790,856,584 226,101,270,301,423,103,264,674,724,361,349,620,646,337,801,830,445,688,746,64 821,112,882,887,295,764,760,789,623,198,655,922,109,809,922,88,399,419,925,305 891,308,685,214,106,147,228,903,114,497,309,743,175,399,416,416,354,935,747,990 642,449,852,913,621,752,318,255,331,478,229,680,630,871,865,922,253,422,151,201 115,732,583,361,316,500,210,77,319,737,448,625,371,651,202,949,403,228,263,999 711,280,169,354,364,255,176,633,560,225,194,214,252,229,168,117,329,348,344,681 168,471,181,476,368,691,918,19,910,325,629,793,298,340,880,570,201,686,795,398 763,206,648,686,679,163,250,167,178,917,301,205,69,372,175,201,802,629,258,513 340,304,195,422,220,450,942,500,620,505,88,924,266,566,832,50,647,480,222,840 643,560,923,526,880,942,411,945,184,527,630,725,258,118,908,868,205,422,416,523 376,639,418,938,425,905,650,891,317,269,495,940,113,582,728,178,176,589,802,78 775,312,631,797,931,103,109,588,109,464,680,293,655,149,167,821,415,816,260,881 478,655,496,170,419,806,582,115,908,639,110,153,644,571,543,164,103,210,175,228 206,211,889,225,703,901,857,530,648,144,81,934,110,923,305,846,433,745,529,646 493,763,224,310,921,644,355,479,81,115,269,265,886,9,110,625,694,675,350,636 836,518,345,917,78,445,478,892,945,476,417,107,862,744,380,327,872,935,884,691 928,475,349,927,404,801,203,924,667,915,143,932,119,197,864,513,646,802,359,592 194,369,582,115,422,531,675,373,166,640,311,268,703,710,826,699,722,114,795,847 179,257,525,695,324,197,745,719,171,450,707,576,814,478,888,426,828,749,268,916 654,520,898,640,929,586,425,828,862,861,861,266,743,297,0,689,884,116,414,366 318,365,189,651,586,294,326,429,735,569,934,109,447,914,675,701,701,803,106,634 145,229,170,364,581,722,918,875,866,410,566,982,635,321,750,164,741,335,403,918 890,497,731,81,432,417,919,338,355,297,153,640,675,799,620,684,518,4,209,301 197,733,109,834,889,207,898,400,140,525,424,583,416,448,902,201,902,688,472,14 0,809,569,206,625,431,56,448,913,800,476,344,882,269,166,314,908,202,373,570 206,201,414,688,166,718,677,696,978,431,594,263,628,449,868,360,807,305,346,499 217,513,429,924,143,167,526,348,268,101,260,654,917,866,812,748,59,816,589,655 788,52,203,270,361,796,895,466,596,149,864,929,895,325,351,702,883,316,892,239 831,500,911,524,820,498,547,315,737,103,494,406,220,358,467,414,725,415,466,472 577,821,171,9,863,807,398,354,266,268,339,724,932,691,334,679,450,264,228,654 116,497,360,294,166,469,919,870,321,592,566,206,883,214,736,309,806,762,810,748 839,525,166,295,269,203,892,578,740,645,305,583,874,634,681,499,998,912,365,638 419,692,496,597,297,945,929,410,911,699,733,868,831,709,932,680,890,199,728,615 944,820,324,693,736,874,637,872,528,249,681,149,339,151,464,591,225,314,315,313 270,639,345,944,690,150,201,822,851,468,876,830,511,303,57,923,762,869,472,316 641,793,104,944,23,870,307,788,877,591,860,328,492,899,472,328,419,361,903,820 799,992,500,116,516,142,903,451,177,477,931,560,744,77,570,52,344,695,816,50 691,227,707,202,302,813,149,623,261,116,575,564,704,824,653,890,937,101,174,256 257,112,339,420,261,834,492,907,912,649,874,838,729,826,271,345,361,470,637,193 339,812,319,906,401,575,867,586,207,351,697,497,855,740,407,347,945,736,152,896 925,845,88,477,58,216,885,565,623,259,142,307,621,304,115,476,939,700,202,469 808,786,83,651,174,623,579,224,224,789,208,161,7,722,116,350,698,733,883,199 682,421,887,432,847,336,524,654,361,371,161,480,59,880,797,348,407,308,681,403 686,571,408,941,788,705,480,365,678,728,631,591,152,555,119,725,595,936,143,142 825,331,993,830,876,399,142,880,741,140,694,947,293,532,445,855,78,912,357,412 898,315,491,897,927,807,165,596,695,563,877,700,56,307,480,253,139,77,117,762 299,690,341,493,500,152,351,810,631,339,828,87,205,565,725,696,207,828,270,404 484,260,809,639,52,620,910,223,499,706,465,348,85,698,116,622,579,707,826,571 621,655,13,445,733,686,411,449,467,898,491,75,344,805,148,356,195,79,449,653 988,891,824,632,229,909,571,176,928,586,708,117,471,560,864,805,725,161,114,934 741,165,570,908,632,728,938,570,516,220,86,301,655,882,581,637,877,475,234,320 67,801,766,731,254,827,916,572,449,621,628,596,478,175,166,696,323,533,416,701 720,58,837,307,695,306,629,215,522,706,856,591,281,110,175,872,532,524,181,167 525,841,651,174,940,530,165,869,423,250,920,705,724,742,112,144,378,259,467,360 740,648,791,679,674,404,165,265,151,256,348,162,880,150,66,353,80,636,258,115 886,575,150,754,365,562,362,522,498,571,639,364,834,169,55,562,470,446,466,366 552,361,412,118,318,724,652,828,450,627,469,594,424,620,519,108,884,884,53,349 519,587,585,341,892,56,175,316,312,472,874,496,267,358,946,874,812,218,943,228 927,307,867,229,597,448,929,557,688,886,269,331,718,345,471,651,369,838,619,469 203,796,199,515,424,212,572,529,220,786,170,889,198,359,596,65,626,569,933,687 208,105,266,278,269,653,531,627,881,253,81,632,836,445,574,788,348,209,166,586 425,543,702,474,424,673,918,747,628,762,175,931,832,863,79,213,109,557,881,494 606,789,514,465,893,339,315,494,314,921,944,477,724,920,856,150,733,932,897,415 """.trimIndent() }
0
Kotlin
0
1
f5efe2f0b6b09b0e41045dc7fda3a7565cb21db3
24,844
advent-of-code
MIT License
leetcode2/src/leetcode/longest-increasing-subsequence.kt
hewking
68,515,222
false
null
package leetcode import kotlin.math.max /** * 300. 最长上升子序列 https://leetcode-cn.com/problems/longest-increasing-subsequence/ 给定一个无序的整数数组,找到其中最长上升子序列的长度。 示例: 输入: [10,9,2,5,3,7,101,18] 输出: 4 解释: 最长的上升子序列是 [2,3,7,101],它的长度是 4。 说明: 可能会有多种最长上升子序列的组合,你只需要输出对应的长度即可。 你算法的时间复杂度应该为 O(n2) 。 进阶: 你能将算法的时间复杂度降低到 O(n log n) 吗? 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/longest-increasing-subsequence 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 **/ object LongestIncreasingSubsequence { class Solution { /** * 思路: * 采用回溯法, 最大,则需要包括Max * 回溯法通用框架 * res = [] * backTrack(路径,选择集) { * if 终止条件 * res.add(path) * return * for 选择 in 选择集 { * 选择 * backTrack(路径,选择集) * 撤销选择 * } * } */ var max = 0 /** * 回溯方式得到的是最长字串,而不是最长子序列 */ fun lengthOfLISubstr(nums: IntArray): Int { backTrack(nums,0) return max } fun backTrack(nums: IntArray,index: Int) { if (index > nums.size) { return } for (i in index until nums.size) { val rangeNums = nums.copyOfRange(index,i + 1) if (!checkLIS(rangeNums)) { continue } max = max(max, rangeNums.size) backTrack(nums,i + 1) } } fun checkLIS(nums: IntArray) : Boolean { if (nums.size == 1) { return true } for (i in 1 until nums.size) { if (nums[i] < nums[i - 1]) { return false } } return true } /** * 思路: * https://leetcode-cn.com/problems/longest-increasing-subsequence/solution/dong-tai-gui-hua-she-ji-fang-fa-zhi-pai-you-xi-jia/ * 动态规划 * */ fun lengthOfLIS(nums: IntArray): Int { if (nums.size == 1) { return 1 } // dp[i] 为nums数组中到 nums[i] 为止的最长子序列 val dp = IntArray(nums.size) // dp 数组子序列,最短需要包含自身,所以长度至少1 dp.fill(1) for (i in 0 until nums.size) { for (j in 0 until i) { if (nums[i] > nums[j]) { dp[i] = Math.max(dp[i],dp[j] + 1) } } } // dp 数组中的最大值,为LIS return dp.reduce { acc, i -> Math.max(acc,i) } } } @JvmStatic fun main(args: Array<String>) { print(Solution().lengthOfLIS(intArrayOf(10,67,11,12,8))) } }
0
Kotlin
0
0
a00a7aeff74e6beb67483d9a8ece9c1deae0267d
3,334
leetcode
MIT License
src/Day03.kt
Cryosleeper
572,977,188
false
{"Kotlin": 43613}
fun main() { fun MutableList<Char>.overallValue() = sumOf { if (it in 'a'..'z') { it - 'a' + 1 } else { it - 'A' + 27 } } fun part1(input: List<String>): Int { val misplacedItems = mutableListOf<Char>() for (line in input) { val left = line.substring(0, line.length/2).toHashSet() val right = line.substring(line.length/2).toHashSet() for (c in right) { if (left.contains(c)) { misplacedItems.add(c) break } } } return misplacedItems.overallValue() } fun part2(input: List<String>): Int { val badges = mutableListOf<Char>() for (group in input.chunked(3)) { val first = group[0].toHashSet() val second = group[1].toHashSet() val third = group[2].toHashSet() for (item in third) { if (first.contains(item) && second.contains(item)) { badges.add(item) break } } } return badges.overallValue() } // test if implementation meets criteria from the description, like: 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
a638356cda864b9e1799d72fa07d3482a5f2128e
1,461
aoc-2022
Apache License 2.0
src/Day07.kt
bananer
434,885,332
false
{"Kotlin": 36979}
import kotlin.math.absoluteValue fun main() { fun part1(input: List<String>): Int { val numbers = input[0].split(",") .map { it.toInt() } .sorted() // median val target = numbers[numbers.size / 2] return numbers.sumOf { (it - target).absoluteValue } } fun part2(input: List<String>): Int { val numbers = input[0].split(",") .map { it.toInt() } val min = numbers.minOrNull()!! val max = numbers.maxOrNull()!! // actual crab movement cost fun gaussSum(n: Int) = (n * (n+1))/2 // brute force, still efficient enough... return (min..max).minOf { target -> numbers.sumOf { gaussSum((it - target).absoluteValue) } } } val testInput = readInput("Day07_test") val testOutput1 = part1(testInput) println("test output1: $testOutput1") check(testOutput1 == 37) val testOutput2 = part2(testInput) println("test output2: $testOutput2") check(testOutput2 == 168) val input = readInput("Day07") println("output part1: ${part1(input)}") println("output part2: ${part2(input)}") }
0
Kotlin
0
0
98f7d6b3dd9eefebef5fa3179ca331fef5ed975b
1,177
advent-of-code-2021
Apache License 2.0
src/cn/leetcode/codes/simple239/Simple239.kt
shishoufengwise1234
258,793,407
false
{"Java": 771296, "Kotlin": 68641}
package cn.leetcode.codes.simple239 import cn.leetcode.codes.out import java.util.* fun main() { val nums = intArrayOf(1, 3, -1, -3, 5, 3, 6, 7) out(maxSlidingWindow(nums, 3).contentToString()) } /* 239. 滑动窗口最大值 给你一个整数数组 nums,有一个大小为 k 的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口内的 k 个数字。滑动窗口每次只向右移动一位。 返回滑动窗口中的最大值。 示例 1: 输入:nums = [1,3,-1,-3,5,3,6,7], k = 3 输出:[3,3,5,5,6,7] 解释: 滑动窗口的位置 最大值 --------------- ----- [1 3 -1] -3 5 3 6 7 3 1 [3 -1 -3] 5 3 6 7 3 1 3 [-1 -3 5] 3 6 7 5 1 3 -1 [-3 5 3] 6 7 5 1 3 -1 -3 [5 3 6] 7 6 1 3 -1 -3 5 [3 6 7] 7 示例 2: 输入:nums = [1], k = 1 输出:[1] 示例 3: 输入:nums = [1,-1], k = 1 输出:[1,-1] 示例 4: 输入:nums = [9,11], k = 2 输出:[11] 示例 5: 输入:nums = [4,-2], k = 2 输出:[4] 提示: 1 <= nums.length <= 105 -104 <= nums[i] <= 104 1 <= k <= nums.length */ fun maxSlidingWindow(nums: IntArray, k: Int): IntArray { if (nums.size < 2) return nums val list = LinkedList<Int>() val ans = IntArray(nums.size - k + 1) nums.forEachIndexed { i, _ -> //保证从大到小排列 while (list.isNotEmpty() && nums[list.peekLast()] <= nums[i]) { list.pollLast() } //添加到队列尾部 list.addLast(i) if (list.peek() <= i - k) { list.poll() } if (i + 1 >= k) { ans[i + 1 - k] = nums[list.peek()] } } return ans }
0
Java
0
0
f917a262bcfae8cd973be83c427944deb5352575
1,766
LeetCodeSimple
Apache License 2.0
src/Day04.kt
wooodenleg
572,658,318
false
{"Kotlin": 30668}
fun String.parseAssignmentRanges() = split(",") .map { section -> val (startNumber, endNumber) = section.split("-") (startNumber.toInt()..endNumber.toInt()) }.let { (first, second) -> first to second } fun main() { fun part1(input: List<String>): Int { var count = 0 for (line in input) { val (first, second) = line.parseAssignmentRanges() if (first in second || second in first) count++ } return count } fun part2(input: List<String>): Int { var count = 0 for (line in input) { val (first, second) = line.parseAssignmentRanges() if ((first.toSet() intersect second.toSet()).isNotEmpty()) count++ } return count } val testInput = readInputLines("Day04_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInputLines("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
ff1f3198f42d1880e067e97f884c66c515c8eb87
984
advent-of-code-2022
Apache License 2.0
src/Day09.kt
illarionov
572,508,428
false
{"Kotlin": 108577}
import kotlin.math.abs private enum class Direction { LEFT, UP, RIGHT, DOWN, } private fun String.toDirection(): Direction = when (this) { "L" -> Direction.LEFT "R" -> Direction.RIGHT "U" -> Direction.UP "D" -> Direction.DOWN else -> error("Unknown direction $this") } private data class RopeMove( val direction: Direction, val steps: Int ) private data class Coordinates( var y: Int, var x: Int ) { fun moveTo(direction: Direction): Coordinates { return when (direction) { Direction.LEFT -> Coordinates(this.y, this.x - 1) Direction.UP -> Coordinates(this.y - 1, this.x) Direction.RIGHT -> Coordinates(this.y, this.x + 1) Direction.DOWN -> Coordinates(this.y + 1, this.x) } } fun isTouchingOrOverlapping(other: Coordinates): Boolean { return abs(this.x - other.x) <= 1 && abs(this.y - other.y) <= 1 } } private fun Coordinates.getNewTailPosition(oldTailPosition: Coordinates): Coordinates { if (this.isTouchingOrOverlapping(oldTailPosition)) { return oldTailPosition } val newY = when (this.y - oldTailPosition.y) { 0 -> 0 -1, -2, -> -1 1, 2 -> 1 else -> error("Unsupported head - tail combination") } val newX = when (this.x - oldTailPosition.x) { 0 -> 0 -1, -2, -> -1 1, 2 -> 1 else -> error("Unsupported head - tail combination") } return Coordinates( y = oldTailPosition.y + newY, x = oldTailPosition.x + newX, ) } fun main() { fun part1(input: List<RopeMove>): Int { var head = Coordinates(0, 0) var tail = head val field = mutableSetOf(head) input.forEach { move -> repeat(move.steps) { head = head.moveTo(move.direction) tail = head.getNewTailPosition(tail) field += tail } } return field.count() } fun part2(input: List<RopeMove>): Int { // rope[0] == Head val rope = MutableList(10) { Coordinates(0, 0) } val field = mutableSetOf(rope.last()) input.forEach { move -> repeat(move.steps) { rope[0] = rope[0].moveTo(move.direction) for (r in 1..9) { rope[r] = rope[r - 1].getNewTailPosition(rope[r]) } field += rope.last() } } return field.count() } val input = readInput("Day09").map(String::parseMove) val part1Result = part1(input) println(part1Result) check(part1Result == 5874) val part2Result = part2(input) println(part2Result) check(part2Result == 2467) } private const val FIELD_SIZE: Int = 1000 private fun Set<Coordinates>.printRope() { val field: List<MutableList<Char>> = List(FIELD_SIZE) { MutableList(FIELD_SIZE) { '.' } } this.forEachIndexed { index, coords -> field[coords.y][coords.x] = if (index == 0) 'H' else index.digitToChar() } field.forEach { l -> println(l.joinToString("")) } } private fun String.parseMove(): RopeMove { val (d, c) = this.split(" ") return RopeMove(d.toDirection(), c.toInt()) }
0
Kotlin
0
0
3c6bffd9ac60729f7e26c50f504fb4e08a395a97
3,270
aoc22-kotlin
Apache License 2.0
src/2021/Day21.kt
nagyjani
572,361,168
false
{"Kotlin": 369497}
import java.io.File import java.math.BigInteger import java.util.* import kotlin.Comparator fun main() { Day21().solve() } class Day21 { val input = """ Player 1 starting position: 4 Player 2 starting position: 8 """.trimIndent() val input2 = """ Player 1 starting position: 8 Player 2 starting position: 1 """.trimIndent() class Dice { var rolls = 0 var last = 100 fun roll(): Int { ++rolls last = last.addMod(1, 100) return last } fun roll(n: Int): Int { return (1..n).map{roll()}.sum() } } class DiracState(val pos1: Int, val score1: Int, val pos2: Int, val score2: Int, val next1: Boolean, val winScore: Int) { val player1won: Boolean get() = score1 >= winScore val player2won: Boolean get() = score2 >= winScore val ended: Boolean get() = player1won || player2won fun roll(n: Int): DiracState { val newPos1 = if (next1) pos1.addMod(n) else pos1 val newScore1 = if (next1) score1 + newPos1 else score1 val newPos2 = if (next1) pos2 else pos2.addMod(n) val newScore2 = if (next1) score2 else score2 + newPos2 val newNext1 = !next1 return DiracState(newPos1, newScore1, newPos2, newScore2, newNext1, winScore) } override fun hashCode(): Int { val m = listOf(31, 31, 11, 11, 2) return toIntList().zip(m).fold(0) {acc, it -> acc * it.second + it.first} } override operator fun equals(other: Any?): Boolean = (other is DiracState) && hashCode() == other.hashCode() fun toIntList(): List<Int> { return listOf(score1, score2, pos1, pos2, if (next1) 0 else 1) } override fun toString(): String { return "(" + hashCode() + ":" + toIntList().joinToString (",") + ")" } } fun solve() { val f = File("src/2021/inputs/day21.in") val s = Scanner(f) // val s = Scanner(input) s.useDelimiter("(\\s*Player . starting position: )|(\\s+)") val p1start = s.nextInt() val p2start = s.nextInt() var p1pos = p1start var p1score = 0 var p2pos = p2start var p2score = 0 var p1next = true val dice = Dice() while (p1score<1000 && p2score<1000) { if (p1next) { p1pos = p1pos.addMod(dice.roll(3)) p1score += p1pos } else { p2pos = p2pos.addMod(dice.roll(3)) p2score += p2pos } p1next = !p1next } val losingScore = if (p1score>p2score) p2score else p1score println("${losingScore * dice.rolls}") val startState1 = DiracState(p1start, 0, p2start, 0, true, 1000) var nextState1: DiracState = startState1 val dice1 = Dice() while (!nextState1.ended) { nextState1 = nextState1.roll(dice1.roll(3)) } val losingScore1 = if (nextState1.player1won) nextState1.score2 else nextState1.score1 println("${losingScore1 * dice1.rolls}") val diracStates = TreeMap<DiracState, BigInteger>(object: Comparator<DiracState> { override fun compare(p0: DiracState?, p1: DiracState?): Int { if (p0 == null && p1 == null) return 0 if (p0 == null) return 1 if (p1 == null) return -1 return p0.hashCode().compareTo(p1.hashCode()) } }) val startState = DiracState(p1start, 0, p2start, 0, true, 21) diracStates[startState] = BigInteger.ONE val diceMax = 3 var p1won = BigInteger.ZERO var p2won = BigInteger.ZERO val diracDice = (1..3).flatMap { it1 -> (1..3).flatMap { it2 -> (1..3).map { it3 -> it1 + it2 + it3 } } } .fold(mutableMapOf<Int, BigInteger>()){acc, it -> acc[it] = (acc[it]?:BigInteger.ZERO).plus(BigInteger.ONE); acc} var sumUniverses: BigInteger var nextState: DiracState? = startState while (nextState != null) { if (!nextState.ended) { diracDice.forEach { val rolledState = nextState!!.roll(it.key) if (diracStates.get(rolledState) == null) { diracStates.put(rolledState, BigInteger(diracStates.get(nextState)!!.toString()).times(it.value)) } else { diracStates.put( rolledState, diracStates.get(nextState)!!.times(it.value).plus(diracStates.get(rolledState)!!) ) } } } else { if (nextState.player1won) { p1won = p1won.plus(diracStates.get(nextState)!!) } else { p2won = p2won.plus(diracStates.get(nextState)!!) } } val lastState = nextState // diracStates.remove(nextState) nextState = diracStates.higherKey(nextState) // sumUniverses = diracStates.tailMap(nextState).values.fold(BigInteger.ZERO){acc, it -> acc.plus(it)} if (nextState != null && lastState.hashCode() > nextState.hashCode()) { println("${lastState.hashCode()} ${nextState.hashCode()}") } } println("$p1won $p2won") } } fun Int.addMod(n: Int, m: Int = 10): Int { val s = (this+n) % 10 return if (s == 0) {m} else s }
0
Kotlin
0
0
f0c61c787e4f0b83b69ed0cde3117aed3ae918a5
5,628
advent-of-code
Apache License 2.0
src/main/kotlin/com/tonnoz/adventofcode23/day5/Five.kt
tonnoz
725,970,505
false
{"Kotlin": 78395}
package com.tonnoz.adventofcode23.day5 import com.tonnoz.adventofcode23.utils.readInput import kotlin.system.measureTimeMillis object Five { @JvmStatic fun main(args: Array<String>) { val time = measureTimeMillis { val input = "input5.txt".readInput() val seeds = input[0].parseSeeds() // I like explicit names :) val seedToSoilMap = input.parseRanges("seed-to-soil map:", "") val soilToFertilizerMap = input.parseRanges("soil-to-fertilizer map:", "") val fertilizerToWaterMap = input.parseRanges("fertilizer-to-water map:", "") val waterToLightMap = input.parseRanges("water-to-light map:", "") val lightToTemperatureMap = input.parseRanges("light-to-temperature map:", "") val temperatureToHumidityMap = input.parseRanges("temperature-to-humidity map:", "") val humidityToLocationMap = input.parseRanges("humidity-to-location map:", "") seeds.asSequence() .map { checkSeedAgainstRanges(it, seedToSoilMap) } .map { checkSeedAgainstRanges(it, soilToFertilizerMap) } .map { checkSeedAgainstRanges(it, fertilizerToWaterMap) } .map { checkSeedAgainstRanges(it, waterToLightMap) } .map { checkSeedAgainstRanges(it, lightToTemperatureMap) } .map { checkSeedAgainstRanges(it, temperatureToHumidityMap) } .map { checkSeedAgainstRanges(it, humidityToLocationMap) } .min() .let { println("lowest location: $it") } } println("milliseconds elapsed: $time") } private data class Range(val sourceRange: LongRange, val destinationRange: LongRange) private fun String.parseSeeds() : List<Long> = "\\d+".toRegex().findAll(this).map { it.value.toLong() }.toList() private fun checkSeedAgainstRanges(seed: Long, ranges: List<Range>): Long { ranges.forEach { val maybeSeed = transform(seed, it) if(maybeSeed != null) return maybeSeed } return seed } private fun transform(seed: Long, range: Range): Long? = range .sourceRange .positionInTheRange(seed) ?.let { range.destinationRange.elementAt(it.toInt()) } private fun LongRange.positionInTheRange(number: Long): Long? = if (number in this) number - this.first else null private fun List<String>.parseRanges(startLine:String, endLine:String): List<Range> { val startI = this.indexOfFirst { it.startsWith(startLine) } + 1 val endI = this.subList(startI+1, this.size).indexOfFirst { it == endLine } + startI + 1 return this.subList(startI, endI).map { val (destination,source, rangeLength ) = it.split(" ", limit = 3) val sourceRange = source.toLong()..< source.toLong() + rangeLength.toLong() val destinationRange = destination.toLong()..< destination.toLong() + rangeLength.toLong() Range(sourceRange, destinationRange) } } }
0
Kotlin
0
0
d573dfd010e2ffefcdcecc07d94c8225ad3bb38f
2,814
adventofcode23
MIT License
src/day03/Day03.kt
palpfiction
572,688,778
false
{"Kotlin": 38770}
package day03 import readInput fun main() { val priorities = (('a'..'z') .mapIndexed { index, it -> it to index + 1 } + ('A'..'Z') .mapIndexed { index, it -> it to index + 27 }).toMap() fun part1(input: List<String>): Int = input .asSequence() .map { it.toList() } .map { it.chunked(it.size / 2) } .map { (compartment1, compartment2) -> compartment1.intersect(compartment2.toSet()) } .map { it.single() } .sumOf { priorities[it]!! } fun part2(input: List<String>): Int = input .chunked(3) .map { (x, y, z) -> x.toSet().intersect(y.toSet()).intersect(z.toSet()) } .map { it.single() } .sumOf { priorities[it]!! } val testInput = readInput("/day03/Day03_test") println(part1(testInput)) println(part2(testInput)) check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("/day03/Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
5b79ec5fa4116e496cd07f0c7cea7dabc8a371e7
1,105
advent-of-code
Apache License 2.0
src/main/kotlin/days/Day03.kt
Kebaan
573,069,009
false
null
package days import utils.Day fun main() { Day03.solve() } object Day03 : Day<Int>(2022, 3) { private fun Char.priority() = when (this) { in 'a'..'z' -> this - 'a' + 1 in 'A'..'Z' -> this - 'A' + 27 else -> error("invalid input") } override fun part1(input: List<String>): Int { return input.sumOf { rucksack -> val (firstCompartment, secondCompartment) = rucksack.chunked(rucksack.length / 2) { it.toSet() } val item = firstCompartment.intersect(secondCompartment).first() item.priority() } } override fun part2(input: List<String>): Int { return input.chunked(3) .sumOf { rucksacks -> val badge = rucksacks .fold(rucksacks.first().toSet()) { acc, rucksack -> acc.intersect(rucksack.toSet()) }.first() badge.priority() } } override fun doSolve() { part1(input).let { println(it) check(it == 7821) } part2(input).let { println(it) check(it == 2752) } } override val testInput = """ vJrwpWtwJgWrhcsFMMfFFhFp jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL PmmdzqPrVvPwwTWBwg wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn ttgJtRGJQctTZtZT CrZsJsPPZsGzwwsLwLmpwMDw""".trimIndent().lines() }
0
Kotlin
0
0
ef8bba36fedbcc93698f3335fbb5a69074b40da2
1,438
Advent-of-Code-2022
Apache License 2.0
src/Day04.kt
carloxavier
574,841,315
false
{"Kotlin": 14082}
fun main() { check(getContainedPairsCount("Day04_test", ::isPairFullyContained) == 2) check(getContainedPairsCount("Day04_test", ::isPairOverlapped) == 4) // Part1 println(getContainedPairsCount("Day04", ::isPairFullyContained)) // Part2 println(getContainedPairsCount("Day04", ::isPairOverlapped)) } private fun getContainedPairsCount(fileName: String, comparison: (Int, Int, Int, Int) -> Boolean) = readInput(fileName).filter { line -> val (x1, x2, y1, y2) = line.split(",", "-").map { it.toInt() } comparison(x1, x2, y1, y2) }.size private fun isPairFullyContained(x1: Int, x2:Int, y1: Int, y2: Int) = (x1 in y1..y2 && x2 in y1..y2) || (y1 in x1..x2 && y2 in x1..x2) private fun isPairOverlapped(x1: Int, x2:Int, y1: Int, y2: Int) = (x1 in y1..y2 || x2 in y1..y2) || (y1 in x1..x2 || y2 in x1..x2)
0
Kotlin
0
0
4e84433fe866ce1a8c073a7a1e352595f3ea8372
837
adventOfCode2022
Apache License 2.0
src/y2023/Day09.kt
gaetjen
572,857,330
false
{"Kotlin": 325874, "Mermaid": 571}
package y2023 import util.readInput import util.timingStatistics object Day09 { private fun parse(input: List<String>): List<List<Long>> { return input.map { line -> line.split(" ").map { it.toLong() } } } fun part1(input: List<String>): Long { val parsed = parse(input) return parsed.sumOf { extrapolated(it) } } fun gradient(lst: List<Long>): List<Long> { return lst.zipWithNext { a, b -> b - a } } private fun allGradients(lst: List<Long>): List<List<Long>> { return buildList { add(lst) while (!last().all { it == 0L }) { add(gradient(last())) } } } private fun extrapolated(lst: List<Long>): Long { return allGradients(lst).sumOf { it.last() } } fun part2(input: List<String>): Long { val parsed = parse(input) return parsed.sumOf { line -> allGradients(line).map { it.first() }.reduceRight { previous, acc -> previous - acc } } } } fun main() { val testInput = """ 0 3 6 9 12 15 1 3 6 10 15 21 10 13 16 21 30 45 """.trimIndent().split("\n") println("------Tests------") println(Day09.part1(testInput)) println(Day09.part2(testInput)) println("------Real------") val input = readInput(2023, 9) println("Part 1 result: ${Day09.part1(input)}") println("Part 2 result: ${Day09.part2(input)}") timingStatistics { Day09.part1(input) } timingStatistics { Day09.part2(input) } }
0
Kotlin
0
0
d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a
1,621
advent-of-code
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/TargetSum.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 /** * 494. Target Sum * @see <a href="https://leetcode.com/problems/target-sum/">Source</a> */ fun interface TargetSum { fun findTargetSumWays(nums: IntArray, target: Int): Int } /** * Approach 1: Brute Force * Time complexity: O(2^n) * Space complexity: O(n) */ class TargetSumBruteForce : TargetSum { private var count = 0 override fun findTargetSumWays(nums: IntArray, target: Int): Int { calculate(nums, 0, 0, target) return count } fun calculate(nums: IntArray, i: Int, sum: Int, target: Int) { if (i == nums.size) { if (sum == target) { count++ } } else { calculate(nums, i + 1, sum + nums[i], target) calculate(nums, i + 1, sum - nums[i], target) } } } /** * Approach 2: Recursion with Memoization * Time complexity: O(t⋅n) * Space complexity: O(t⋅n) */ class TargetSumMemoization : TargetSum { private var total = 0 override fun findTargetSumWays(nums: IntArray, target: Int): Int { total = nums.sum() val memo = Array(nums.size) { IntArray(2 * total + 1) { Int.MIN_VALUE } } return calculate(nums, 0, 0, target, memo) } fun calculate(nums: IntArray, i: Int, sum: Int, target: Int, memo: Array<IntArray>): Int { return if (i == nums.size) { if (sum == target) { 1 } else { 0 } } else { if (memo[i][sum + total] != Int.MIN_VALUE) { return memo[i][sum + total] } val add = calculate(nums, i + 1, sum + nums[i], target, memo) val subtract = calculate(nums, i + 1, sum - nums[i], target, memo) memo[i][sum + total] = add + subtract memo[i][sum + total] } } } /** * Approach 3: 2D Dynamic Programming * Time complexity: O(t⋅n) * Space complexity: O(t⋅n) */ class TwoDDynamicProgramming : TargetSum { override fun findTargetSumWays(nums: IntArray, target: Int): Int { val total: Int = nums.sum() val dp = Array(nums.size) { IntArray(2 * total + 1) } dp[0][nums[0] + total] = 1 dp[0][-nums[0] + total] += 1 for (i in 1 until nums.size) { for (sum in -total..total) { if (dp[i - 1][sum + total] > 0) { dp[i][sum + nums[i] + total] += dp[i - 1][sum + total] dp[i][sum - nums[i] + total] += dp[i - 1][sum + total] } } } return if (abs(target) > total) 0 else dp[nums.size - 1][target + total] } } /** * Approach 4: 1D Dynamic Programming * Time complexity: O(t⋅n) * Space complexity: O(t) */ class OneDDynamicProgramming : TargetSum { override fun findTargetSumWays(nums: IntArray, target: Int): Int { val total: Int = nums.sum() var dp = IntArray(2 * total + 1) dp[nums[0] + total] = 1 dp[-nums[0] + total] += 1 for (i in 1 until nums.size) { val next = IntArray(2 * total + 1) for (sum in -total..total) { if (dp[sum + total] > 0) { next[sum + nums[i] + total] += dp[sum + total] next[sum - nums[i] + total] += dp[sum + total] } } dp = next } return if (abs(target) > total) 0 else dp[target + total] } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
4,108
kotlab
Apache License 2.0
kotlin/1269-number-of-ways-to-stay-in-the-same-place-after-some-steps.kt
neetcode-gh
331,360,188
false
{"JavaScript": 473974, "Kotlin": 418778, "Java": 372274, "C++": 353616, "C": 254169, "Python": 207536, "C#": 188620, "Rust": 155910, "TypeScript": 144641, "Go": 131749, "Swift": 111061, "Ruby": 44099, "Scala": 26287, "Dart": 9750}
// Optimized DP solution Time O(minOf(steps, arrLen)^2, and space optimized down from O(minOf(steps, arrLen)^2) to O(minOf(steps, arrLen)) class Solution { fun numWays(steps: Int, _arrLen: Int): Int { val mod = 1_000_000_000 + 7 val arrLen = minOf(steps, _arrLen) var dp = IntArray (arrLen) dp[0] = 1 for (step in 1..steps) { val nextDp = IntArray (arrLen) for (i in 0 until arrLen) { nextDp[i] = dp[i] if (i > 0) nextDp[i] = (nextDp[i] + dp[i - 1]) % mod if (i < arrLen - 1) nextDp[i] = (nextDp[i] + dp[i + 1]) % mod } dp = nextDp } return dp[0] } } /* Recursion + memoization, Time O(minOf(steps, arrLen)^2 and space O(minOf(steps, arrLen)^2 * Here we use arrays for memoization, however, we set the 2D array's size to [steps + 1][steps + 1] because: * 1) we can never move more than "steps" amount to the right, and we have constraints 1 <= steps <= 500 and 1 <= arrLen <= 10^6, * so we can therefor make an optimization since we dont need all that extra space, and 2) it will not AC on Leetcode since they are looking for this optimisation. */ class Solution { fun numWays(steps: Int, arrLen: Int): Int { val mod = 1_000_000_000 + 7 val dp = Array (steps + 1) { IntArray (steps + 1) { -1 } } fun dfs(i: Int, left: Int): Int { if (i < 0 || i == arrLen) return 0 if (left == 0) { if (i == 0) return 1 else return 0 } if (dp[i][left] != -1) return dp[i][left] var res = 0 res = (res + dfs(i - 1, left - 1)) % mod res = (res + dfs(i + 1, left - 1)) % mod res = (res + dfs(i, left - 1)) % mod dp[i][left] = res return res } return dfs(0, steps) } }
337
JavaScript
2,004
4,367
0cf38f0d05cd76f9e96f08da22e063353af86224
1,973
leetcode
MIT License
src/main/kotlin/com/tonnoz/adventofcode23/day3/Three.kt
tonnoz
725,970,505
false
{"Kotlin": 78395}
package com.tonnoz.adventofcode23.day3 import com.tonnoz.adventofcode23.utils.readInput object Three { @JvmStatic fun main(args: Array<String>) { val input = "inputThree.txt".readInput() problemOne(input) problemTwo(input) } //****************************** PROBLEM ONE ******************************// private fun problemOne(input: List<String>) { var iLine = 0 val resultList = mutableListOf<Int>() while (iLine < input.size) { val line = input[iLine] var iChar = 0 while (iChar < line.length) { val aChar = line[iChar] if (!aChar.isDigit()) { iChar++ continue } if (isACandidate(input, iLine, iChar)) { val aNumber = line.getNextNumberAfterIndex(iChar) iChar += aNumber.length resultList.add(aNumber.toInt()) continue } iChar++ } iLine++ } println("the result of first problem is ${resultList.sum()}") // 530849 } private val symbols = hashSetOf('@','#', '$', '%', '&', '*', '+', '-', '=', '/') private fun Char.isASymbol(): Boolean = symbols.contains(this) private fun isACandidate(input: List<String>, iLine: Int, iChar: Int): Boolean { val aNumber = input[iLine].getNextNumberAfterIndex(iChar) return isNumberAdjacentHorizontal(aNumber, input[iLine], iChar) || isNumberAdjacentVerticalOrDiagonal(aNumber, input, iLine, iChar, input[iLine]) } private fun isNumberAdjacentVerticalOrDiagonal(aNumber: String, input: List<String>, iLine: Int, iChar: Int, line: String): Boolean { val skipTop = iLine == 0 val skipBottom = iLine == input.size - 1 var i = if (iChar > 0) iChar - 1 else iChar val to = if (iChar + aNumber.length <= line.length - 1) iChar + aNumber.length else iChar + aNumber.length - 1 // nb. there is always at least "aNumber.length" chars left in the line while (i <= to) { if (!skipTop && input[iLine - 1][i].isASymbol()) return true if (!skipBottom && input[iLine + 1][i].isASymbol()) return true i++ } return false } private fun isNumberAdjacentHorizontal(aNumber: String, line: String, iChar: Int): Boolean = (iChar - 1 >= 0 && line[iChar - 1].isASymbol()) || (iChar + aNumber.length < line.length && line[iChar + aNumber.length].isASymbol()) private fun String.getNextNumberAfterIndex(iChar: Int): String = this.substring(iChar).takeWhile { it.isDigit() } // ****************************** PROBLEM TWO ******************************// private fun problemTwo(input: List<String>) { input.flatMapIndexed { iLine, line -> line.mapIndexedNotNull { iChar, aChar -> if (aChar == '*') input.gearsProduct(iLine, iChar) else null } }.sum().let { println("the solution to problem two is: $it") } } // calculate gears product if both terms are present Or else return zero private fun List<String>.gearsProduct(iLine: Int, iChar: Int): Int = hashSetOf( getGearNumberLeft(iLine, iChar), getGearNumberRight(iLine, iChar), getGearNumberTopCenter(iLine, iChar), getGearNumberTopLeft(iLine, iChar), getGearNumberTopRight(iLine, iChar), getGearNumberBottomCenter(iLine, iChar), getGearNumberBottomLeft(iLine, iChar), getGearNumberBottomRight(iLine, iChar) ).let { it.remove(0) if (it.size != 2) return 0 return it.reduce { acc, curr -> acc * curr } } private fun List<String>.getGearNumberRight(iLine: Int, iChar: Int) = this[iLine].findNumber(iChar + 1).tryToIntOrZero() private fun List<String>.getGearNumberLeft(iLine: Int, iChar: Int) = this[iLine].findNumber(iChar - 1).tryToIntOrZero() private fun String.tryToIntOrZero(): Int = try { this.toInt() } catch (e: Exception) { 0 } private fun String.findNumber(iChar: Int): String { if (iChar !in this.indices || !this[iChar].isDigit()) return "" val startIndex = this.substring(0, iChar).indexOfLast { !it.isDigit() } + 1 val lastIndexOfADigit = this.substring(iChar).indexOfFirst { !it.isDigit() } val endIndex = if (lastIndexOfADigit == -1) this.length else this.substring(iChar).indexOfFirst { !it.isDigit() } + iChar return if (endIndex > -1) { this.substring(startIndex, endIndex) } else { this.substring(startIndex) } } private fun List<String>.getGearNumberTopCenter(iLine: Int, iChar: Int): Int = this.getNumber(iLine, iChar, -1, 0) private fun List<String>.getGearNumberTopLeft(iLine: Int, iChar: Int): Int = this.getNumber(iLine, iChar, -1, -1) private fun List<String>.getGearNumberTopRight(iLine: Int, iChar: Int): Int = this.getNumber(iLine, iChar, -1, 1) private fun List<String>.getGearNumberBottomCenter(iLine: Int, iChar: Int): Int = this.getNumber(iLine, iChar, +1, 0) private fun List<String>.getGearNumberBottomLeft(iLine: Int, iChar: Int): Int = this.getNumber(iLine, iChar, +1, -1) private fun List<String>.getGearNumberBottomRight(iLine: Int, iChar: Int): Int = this.getNumber(iLine, iChar, +1, 1) private fun List<String>.getNumber(iLine: Int, iChar: Int, lineIAddendum: Int, charIAddendum: Int): Int { if (iLine == 0) return 0 if (iLine == this.size - 1) return 0 if (!this[iLine + lineIAddendum][iChar + charIAddendum].isDigit()) return 0 return this[iLine + lineIAddendum].findNumber(iChar + charIAddendum).tryToIntOrZero() } }
0
Kotlin
0
0
d573dfd010e2ffefcdcecc07d94c8225ad3bb38f
5,401
adventofcode23
MIT License
src/Day04.kt
Kbzinho-66
572,299,619
false
{"Kotlin": 34500}
fun main() { infix fun IntRange.fullyOverlaps(other: IntRange): Boolean = first < other.first && last >= other.last infix fun IntRange.overlaps(other: IntRange): Boolean = first <= other.last && last >= other.first fun getSections(pair: String): Pair<IntRange, IntRange> { val (first, second) = pair.split(",").map { sections -> val (a, b) = sections.split("-") IntRange(a.toInt(), b.toInt()) } return Pair(first, second) } fun part1(input: List<String>): Int = input.map { pair -> getSections(pair) }.count { (elf1, elf2) -> ( elf1 fullyOverlaps elf2 || elf2 fullyOverlaps elf1 ) } fun part2(input: List<String>): Int = input.map { pair -> getSections(pair) }.count{ (elf1, elf2) -> elf1 overlaps elf2 } // Testar os casos básicos val testInput = readInput("../inputs/Day04_test") sanityCheck(part1(testInput), 2) sanityCheck(part2(testInput), 4) val input = readInput("../inputs/Day04") println("Parte 1 = ${part1(input)}") println("Parte 2 = ${part2(input)}") }
0
Kotlin
0
0
e7ce3ba9b56c44aa4404229b94a422fc62ca2a2b
1,188
advent_of_code_2022_kotlin
Apache License 2.0
src/main/kotlin/com/github/michaelbull/advent2023/day1/Day1.kt
michaelbull
726,012,340
false
{"Kotlin": 195941}
package com.github.michaelbull.advent2023.day1 import com.github.michaelbull.advent2023.Puzzle private val STRING_TO_DIGIT = mapOf( "one" to 1, "two" to 2, "three" to 3, "four" to 4, "five" to 5, "six" to 6, "seven" to 7, "eight" to 8, "nine" to 9, ) private val NUMERICAL_WORD = STRING_TO_DIGIT.keys private val NUMERICAL_DIGIT = STRING_TO_DIGIT.values.map(Int::toString) private val NUMERICAL_STRINGS = NUMERICAL_WORD + NUMERICAL_DIGIT private fun String.toNumericCalibrationValue(): Int { val firstDigit = requireNotNull(firstOrNull(Char::isDigit)?.digitToInt()) { "could not find first digit in $this" } val secondDigit = requireNotNull(lastOrNull(Char::isDigit)?.digitToInt()) { "could not find last digit in $this" } return "$firstDigit$secondDigit".toInt() } private fun String.toLinguisticCalibrationValue(): Int { val (_, firstString) = requireNotNull(findAnyOf(NUMERICAL_STRINGS)) { "could not find first digit in $this" } val (_, lastString) = requireNotNull(findLastAnyOf(NUMERICAL_STRINGS)) { "could not find last digit in $this" } val firstDigit = firstString.toIntOrDigit() val secondDigit = lastString.toIntOrDigit() return "$firstDigit$secondDigit".toInt() } private fun String.toIntOrDigit(): Int { return toIntOrNull() ?: STRING_TO_DIGIT[this] ?: error("$this is not a number") } object Day1 : Puzzle<Sequence<String>, Int>(day = 1) { override fun parse(lines: Sequence<String>): Sequence<String> { return lines } override fun solutions() = listOf( ::part1, ::part2, ) fun part1(input: Sequence<String>): Int { return input.sumOf(String::toNumericCalibrationValue) } fun part2(input: Sequence<String>): Int { return input.sumOf(String::toLinguisticCalibrationValue) } }
0
Kotlin
0
1
ea0b10a9c6528d82ddb481b9cf627841f44184dd
1,912
advent-2023
ISC License
src/Day04.kt
semanticer
577,822,514
false
{"Kotlin": 9812}
import java.lang.Character.isUpperCase fun main() { fun part1(input: List<String>): Int { return input.count { val (first, second) = it.toRanges() first.minus(second).isEmpty() || second.minus(first).isEmpty() } } fun part2(input: List<String>): Int { return input.count { val (first, second) = it.toRanges() first.intersect(second).isNotEmpty() } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInput("Day04") part1(input).println() part2(input).println() } private fun String.toRanges(): Pair<IntRange, IntRange> { fun String.toRange(): IntRange { val (from, to) = this.split("-") return from.toInt()..to.toInt() } val (first, second) = split(",") return first.toRange() to second.toRange() }
0
Kotlin
0
0
9013cb13f0489a5c77d4392f284191cceed75b92
994
Kotlin-Advent-of-Code-2022
Apache License 2.0
src/main/kotlin/year2022/Day04.kt
simpor
572,200,851
false
{"Kotlin": 80923}
import AoCUtils import AoCUtils.test fun main() { fun part1(input: String, debug: Boolean = false): Long { return input.lines().map { line -> line.split(",").map { val x = it.split("-") IntRange(x[0].toInt(), x[1].toInt()) } }.map { elves -> val e1 = elves[0] val e2 = elves[1] if (e2.contains(e1.first) && e2.contains(e1.last)) true else e1.contains(e2.first) && e1.contains(e2.last) }.count { it }.toLong() } fun part2(input: String, debug: Boolean = false): Long { return input.lines().map { line -> line.split(",").map { val x = it.split("-") IntRange(x[0].toInt(), x[1].toInt()) } }.map { elves -> val e1 = elves[0] val e2 = elves[1] e1.contains(e2.first) || e1.contains(e2.last) || e2.contains(e1.first) || e2.contains(e1.last) }.count { it }.toLong() } val testInput = "2-4,6-8\n" + "2-3,4-5\n" + "5-7,7-9\n" + "2-8,3-7\n" + "6-6,4-6\n" + "2-6,4-8" val input = AoCUtils.readText("year2022/day04.txt") part1(testInput, false) test Pair(2L, "test 1 part 1") part1(input, false) test Pair(490L, "part 1") part2(testInput, false) test Pair(4L, "test 2 part 2") part2(input) test Pair(921L, "part 2") }
0
Kotlin
0
0
631cbd22ca7bdfc8a5218c306402c19efd65330b
1,485
aoc-2022-kotlin
Apache License 2.0
archive/src/main/kotlin/com/grappenmaker/aoc/year19/Day14.kt
770grappenmaker
434,645,245
false
{"Kotlin": 409647, "Python": 647}
package com.grappenmaker.aoc.year19 import com.grappenmaker.aoc.PuzzleSet import kotlin.math.ceil fun PuzzleSet.day14() = puzzle(day = 14) { data class Ratio(val amount: Long, val of: String) data class Recipe(val inputs: List<Ratio>, val output: Ratio) operator fun Ratio.times(n: Long) = copy(amount = amount * n) operator fun Recipe.times(n: Long) = Recipe(inputs.map { it * n }, output * n) fun String.parseRatio(): Ratio { val (amount, of) = split(" ") return Ratio(amount.toLong(), of) } val recipes = inputLines.map { l -> val (inputsPart, outputPart) = l.split(" => ") Recipe(inputsPart.split(", ").map(String::parseRatio), outputPart.parseRatio()) } val byOutput = recipes.associateBy { it.output.of } fun recurse(need: Ratio, have: MutableMap<String, Long> = mutableMapOf()): Long { if (need.of == "ORE") return need.amount val alreadyHave = have.getOrPut(need.of) { 0L } val needAdditionally = need.amount - alreadyHave have[need.of] = maxOf(0, alreadyHave - need.amount) if (needAdditionally <= 0) return 0L val recipe = byOutput.getValue(need.of) val result = recipe * ceil(needAdditionally.toDouble() / recipe.output.amount).toLong() have[need.of] = have.getValue(need.of) + result.output.amount - needAdditionally return result.inputs.sumOf { recurse(it, have) } } partOne = recurse(Ratio(1, "FUEL")).s() fun bs(): Long { val target = 1000000000000 var min = 0L var max = 1L shl 43 while (min + 1 < max) { val pivot = (min + max) / 2 val found = recurse(Ratio(pivot, "FUEL")) val s = found - target when { s < 0L -> min = pivot s > 0L -> max = pivot else -> return pivot } } return min } partTwo = bs().s() }
0
Kotlin
0
7
92ef1b5ecc3cbe76d2ccd0303a73fddda82ba585
1,958
advent-of-code
The Unlicense
src/main/kotlin/aoc2023/Day05.kt
Ceridan
725,711,266
false
{"Kotlin": 110767, "Shell": 1955}
package aoc2023 typealias Transform = Map<Pair<String, String>, List<Day05.TransformEntry>> class Day05 { fun part1(input: String): Long { val almanac = parseAlmanac(input) var key = "seed" val items = almanac.seeds.toLongArray() while (key in almanac.keys) { val keyPair = key to almanac.keys[key]!! items@ for (i in items.indices) { val transforms = almanac.transforms.getOrDefault(keyPair, listOf()) for (transform in transforms) { if (transform.source.contains(items[i])) { items[i] = transform.destination.first + (items[i] - transform.source.first) continue@items } } } key = almanac.keys.getOrDefault(key, "") } return items.min() } fun part2(input: String): Long { val almanac = parseAlmanac(input) var key = "seed" var items = almanac.seeds.windowed(2, 2).map { LongRange(it[0], it[0] + it[1]) }.toSet() while (key in almanac.keys) { val keyPair = key to almanac.keys[key]!! val newItems = mutableSetOf<LongRange>() val queue = ArrayDeque(items) queue@ while (queue.isNotEmpty()) { val range = queue.removeFirst() val transforms = almanac.transforms.getOrDefault(keyPair, listOf()) for (transform in transforms) { val (left, intersection, right) = range.splitIntersect(transform.source) if (intersection != null) { val dest = LongRange( transform.destination.first + (intersection.first - transform.source.first), transform.destination.first + (intersection.last - transform.source.first) ) newItems.add(dest) if (left != null) queue.addFirst(left) if (right != null) queue.addFirst(right) continue@queue } } newItems.add(range) } items = newItems key = almanac.keys.getOrDefault(key, "") } return items.minOf { it.first } } private fun LongRange.splitIntersect(other: LongRange): Triple<LongRange?, LongRange?, LongRange?> { var left: LongRange? = null var intersect: LongRange? = null var right: LongRange? = null if (first < other.first) { left = LongRange(first, last.coerceAtMost(other.first - 1L)) } if (last > other.last) { right = LongRange(first.coerceAtLeast(other.last + 1L), last) } if ((other.first in first..last) || (first in other.first..other.last)) { intersect = LongRange(first.coerceAtLeast(other.first), last.coerceAtMost(other.last)) } return Triple(left, intersect, right) } private fun parseAlmanac(almanac: String): Almanac { val lines = almanac.split('\n') val seeds = lines.first().split(' ').drop(1).filter { it.isNotEmpty() }.map { it.toLong() } val titleRegex = "^([a-z]+)-to-([a-z]+) map:$".toRegex() val numsRegex = "^(\\d+) (\\d+) (\\d+)$".toRegex() val transforms = mutableMapOf<Pair<String, String>, MutableList<TransformEntry>>() var key: Pair<String, String>? = null for (line in lines.drop(2).filter { it.isNotEmpty() }) { val numsMatch = numsRegex.find(line) if (numsMatch != null) { val (dest, source, count) = numsMatch.destructured val entry = TransformEntry( source = LongRange(source.toLong(), source.toLong() + count.toLong() - 1L), destination = LongRange(dest.toLong(), dest.toLong() + count.toLong() - 1L), ) transforms[key]!!.add(entry) continue } val titleMatch = titleRegex.find(line) if (titleMatch != null) { val (source, dest) = titleMatch.destructured key = source to dest transforms[key] = mutableListOf() } } return Almanac(seeds, transforms, transforms.keys.associateBy({ it.first }, { it.second })) } data class Almanac(val seeds: List<Long>, val transforms: Transform, val keys: Map<String, String>) data class TransformEntry(val source: LongRange, val destination: LongRange) } fun main() { val day05 = Day05() val input = readInputAsString("day05.txt") println("05, part 1: ${day05.part1(input)}") println("05, part 2: ${day05.part2(input)}") }
0
Kotlin
0
0
18b97d650f4a90219bd6a81a8cf4d445d56ea9e8
4,825
advent-of-code-2023
MIT License
Problem Solving/Algorithms/Basic - Mini-Max Sum.kt
MechaArms
525,331,223
false
{"Kotlin": 30017}
/* Given five positive integers, find the minimum and maximum values that can be calculated by summing exactly four of the five integers. Then print the respective minimum and maximum values as a single line of two space-separated long integers. Example arr = [1,3,5,7,9] The minimum sum is 1+3+5+7=16 and the maximum sum is 3+5+7+9=24. The function prints 16 24 Function Description Complete the miniMaxSum function in the editor below. miniMaxSum has the following parameter(s): arr: an array of integers Print Print two space-separated integers on one line: the minimum sum and the maximum sum of 4 of 5 elements. Input Format A single line of five space-separated integers. Output Format Print two space-separated long integers denoting the respective minimum and maximum values that can be calculated by summing exactly four of the five integers. (The output can be greater than a 32 bit integer.) Sample Input 1 2 3 4 5 Sample Output 10 14 Explanation The numbers are 1, 2, 3, 4, and 5. Calculate the following sums using four of the five integers: Sum everything except 1, the sum is 2+3+4+5=14. Sum everything except 2, the sum is 1+3+4+5=13. Sum everything except 3, the sum is 1+2+4+5=12. Sum everything except 4, the sum is 1+2+3+5=11. Sum everything except 5, the sum is 1+2+3+4=10. Hints: Beware of integer overflow! Use 64-bit Integer. */ fun miniMaxSum(arr: Array<Int>): Unit { // Write your code here var ordered: List<Long> = arr.map { it.toLong() } var max = ordered.max()!! var min = ordered.min()!! print("${ordered.sum() - max} ${ordered.sum() - min }") } fun main(args: Array<String>) { val arr = readLine()!!.trimEnd().split(" ").map{ it.toInt() }.toTypedArray() miniMaxSum(arr) }
0
Kotlin
0
1
eda7f92fca21518f6ee57413138a0dadf023f596
1,760
My-HackerRank-Solutions
MIT License
src/Day05.kt
gylee2011
573,544,473
false
{"Kotlin": 9419}
import java.util.* /** 012345678901234567890 [D] [N] [C] [Z] [M] [P] 1 2 3 1 + 4 * (n - 1) 1: 1 2: 5 3: 9 */ fun Int.times(block: () -> Unit) { for (i in 0 until this) { block() } } fun main() { fun readStackLine(line: String, stacks: List<Stack<Char>>) { var stackIndex = 0 var position = 1 while (position < line.lastIndex && stackIndex < stacks.count()) { val ch = line[position] if (ch == ' ') { stackIndex++ position += 4 continue } stacks[stackIndex].add(0, ch) stackIndex++ position += 4 } } fun move(count: Int, from: Stack<Char>, to: Stack<Char>) { for (i in 0 until count) { val c = from.pop() to.push(c) } } fun move2(count: Int, from: Stack<Char>, to: Stack<Char>) { val stack = Stack<Char>() count.times { stack.push(from.pop()) } count.times { to.push(stack.pop()) } } fun part1(input: String): String { val (cratesString, stepsString) = input.split("\n\n") val crates = cratesString.split('\n') val stackCountLine = crates.last() val stackCount = stackCountLine.last().digitToInt() val stacks = (0 until stackCount).map { Stack<Char>() } crates.subList(0, crates.count() - 1) .forEach { line -> readStackLine(line, stacks) } val steps = stepsString.split('\n') steps.forEach { val words = it.split(' ') val count = words[1].toInt() val from = words[3].toInt() - 1 val to = words[5].toInt() - 1 move(count, stacks[from], stacks[to]) } return stacks.map { it.peek() } .joinToString("") } fun part2(input: String): String { val (cratesString, stepsString) = input.split("\n\n") val crates = cratesString.split('\n') val stackCountLine = crates.last() val stackCount = stackCountLine.last().digitToInt() val stacks = (0 until stackCount).map { Stack<Char>() } crates.subList(0, crates.count() - 1) .forEach { line -> readStackLine(line, stacks) } val steps = stepsString.split('\n') steps.forEach { val words = it.split(' ') val count = words[1].toInt() val from = words[3].toInt() - 1 val to = words[5].toInt() - 1 move2(count, stacks[from], stacks[to]) } return stacks.map { it.peek() } .joinToString("") } val testInput = readInputText("Day05_test") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = readInputText("Day05") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
339e0895fd2484b7f712b966a0dae8a4cfebc2fa
2,931
aoc2022-kotlin
Apache License 2.0
src/Day10.kt
zsmb13
572,719,881
false
{"Kotlin": 32865}
fun main() { fun getXValues(testInput: List<String>) = testInput .flatMap { line -> when (line) { "noop" -> listOf(0) else -> listOf(0, line.substring(5).toInt()) } }.runningFold(1) { x, op -> x + op } fun part1(testInput: List<String>): Int { val xValues = getXValues(testInput) val cyclesOfInterest = listOf(20, 60, 100, 140, 180, 220) return cyclesOfInterest.sumOf { index -> index * xValues[index - 1] } } fun part2(testInput: List<String>) { (1..240).zip(getXValues(testInput)) .forEach { (cycle, x) -> val sprite = x until (x + 3) val pos = cycle % 40 print(if (pos in sprite) '#' else '.') if (pos == 0) println() } } val testInput = readInput("Day10_test") check(part1(testInput) == 13140) part2(testInput) val input = readInput("Day10") println(part1(input)) part2(input) }
0
Kotlin
0
6
32f79b3998d4dfeb4d5ea59f1f7f40f7bf0c1f35
1,045
advent-of-code-2022
Apache License 2.0
src/Day03.kt
PascalHonegger
573,052,507
false
{"Kotlin": 66208}
fun main() { fun Char.priority() = if (isLowerCase()) 1 + (this - 'a') else 27 + (this - 'A') fun part1(input: List<String>): Int { return input.sumOf { rucksack -> val (firstCompartment, secondCompartment) = rucksack.chunked(rucksack.length / 2) val overlap = firstCompartment.toSet().intersect(secondCompartment.toSet()).single() overlap.priority() } } fun part2(input: List<String>): Int { return input.chunked(3).sumOf { group -> val badge = group.map { it.toHashSet() }.reduce { acc, it -> acc.apply { retainAll(it) } }.single() badge.priority() } } 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
2215ea22a87912012cf2b3e2da600a65b2ad55fc
874
advent-of-code-2022
Apache License 2.0
src/Day06.kt
peterfortuin
573,120,586
false
{"Kotlin": 22151}
fun main() { fun uniqueValuesFinder(input: String, length: Int): Int { var index = length input.toCharArray().toList().windowed(length).forEach { possibleStartOfPacketMarker -> val pSOPMList = possibleStartOfPacketMarker.toCharArray().toList() if (pSOPMList.distinct() == pSOPMList) { return index } index++ } return -1 } fun part1(input: String): Int { return uniqueValuesFinder(input, 4) } fun part2(input: String): Int { return uniqueValuesFinder(input, 14) } // test if implementation meets criteria from the description, like: check(part1("bvwbjplbgvbhsrlpgdmjqwftvncz") == 5) check(part1("nppdvjthqldpwncqszvftbrmjlhg") == 6) check(part1("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg") == 10) check(part1("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw") == 11) check(part2("mjqjpqmgbljsphdztnvjfqwrcgsmlb") == 19) check(part2("bvwbjplbgvbhsrlpgdmjqwftvncz") == 23) check(part2("nppdvjthqldpwncqszvftbrmjlhg") == 23) check(part2("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg") == 29) check(part2("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw") == 26) val input = readInput("Day06").first() println("Part 1 = ${part1(input)}") println("Part 2 = ${part2(input)}") }
0
Kotlin
0
0
c92a8260e0b124e4da55ac6622d4fe80138c5e64
1,315
advent-of-code-2022
Apache License 2.0
src/main/kotlin/Day12.kt
akowal
434,506,777
false
{"Kotlin": 30540}
fun main() { println(Day12.solvePart1()) println(Day12.solvePart2()) } object Day12 { private val connections = readInput("day12") .map { it.split('-') } .flatMap { (a, b) -> listOf(a to b, b to a) } .groupBy({ it.first }, { it.second }) fun solvePart1() = traverse("start", emptySet(), false) fun solvePart2() = traverse("start", emptySet(), true) private fun traverse( cave: String, path: Set<String>, allowSmallCaveReentrance: Boolean ): Int { val reenteredSmallCave = cave.all { it.isLowerCase() } && cave in path when { cave == "end" -> return 1 reenteredSmallCave && cave == "start" -> return 0 reenteredSmallCave && !allowSmallCaveReentrance -> return 0 } return connections[cave]!!.sumOf { traverse(it, path + cave, allowSmallCaveReentrance && !reenteredSmallCave) } } }
0
Kotlin
0
0
08d4a07db82d2b6bac90affb52c639d0857dacd7
950
advent-of-kode-2021
Creative Commons Zero v1.0 Universal
src/day06/solution.kt
bohdandan
729,357,703
false
{"Kotlin": 80367}
package day06 import println import readInput import kotlin.math.sqrt fun main() { class Race(val time: Long, val distance: Long) { fun getNumberOfWaysYouCanWin(): Long { // d = t*th - th^2 // th^2 - t*th + d = 0 // D= t^2 – 4d // x1 = t - sqrt(D) / 2 // x2 = t + sqrt(D) / 2 val discriminant = time * time - 4L * distance val min = (time - sqrt(discriminant.toDouble())) / 2 val max = (time + sqrt(discriminant.toDouble())) / 2 var result = (Math.ceil(max) - Math.floor(min) - 1).toLong() return result } } class GameEngine { var races: List<Race> = emptyList() constructor(input: List<String>, ignoreSpaces: Boolean = false) { var timeString = input[0] var distanceString = input[1] if (ignoreSpaces) { timeString = timeString.replace(" ", "") distanceString = distanceString.replace(" ", "") } val times = "\\d+".toRegex().findAll(timeString) .map { it.value.toLong() } .toList() val distances = "\\d+".toRegex().findAll(distanceString) .map { it.value.toLong() } .toList() for ((index, time) in times.withIndex()) { races += Race(time, distances[index]) } } fun getNumberOfWaysYouCanWin(): Long { return races.map { it.getNumberOfWaysYouCanWin() } .reduce { acc, element -> acc * element } } } val testGameEngine = GameEngine(readInput("day06/test1")) check(testGameEngine.getNumberOfWaysYouCanWin() == 288L) val gameEngine = GameEngine(readInput("day06/input")) gameEngine.getNumberOfWaysYouCanWin().println() val testGameEngine2 = GameEngine(readInput("day06/test1"), true) check(testGameEngine2.getNumberOfWaysYouCanWin() == 71503L) val gameEngine2 = GameEngine(readInput("day06/input"), true) gameEngine2.getNumberOfWaysYouCanWin().println() }
0
Kotlin
0
0
92735c19035b87af79aba57ce5fae5d96dde3788
2,119
advent-of-code-2023
Apache License 2.0
src/Day05.kt
valerakostin
574,165,845
false
{"Kotlin": 21086}
import java.util.* fun main() { data class Move(val count: Int, val from: Int, val to: Int) fun parseStacks(input: List<String>): List<Stack<String>> { val lastLine = input.last() val stackCount = (lastLine.length + 2) / 4 val stacks = mutableListOf<Stack<String>>() repeat(stackCount) { stacks.add(Stack()) } for (i in input.size - 2 downTo 0) { val line = input[i] + " " for (offset in 0..line.length - 4 step 4) { val v = line.substring(offset, offset + 4).trim() if (v.isNotBlank()) stacks[offset / 4].push(v.removeSurrounding("[", "]")) } } return stacks } fun parseInput(input: List<String>): Pair<List<Stack<String>>, List<Move>> { val stackLines = mutableListOf<String>() for (iIter in input.withIndex()) { if (iIter.value.trim().isBlank()) { val stacks = parseStacks(stackLines) val index = iIter.index + 1 val pattern = """move (\d+) from (\d+) to (\d+)""".toRegex() val moves = mutableListOf<Move>() for (idx in index until input.size) { val moveLine = input[idx] val match = pattern.find(moveLine) val (repeatCount, from, to) = match!!.destructured moves.add(Move( repeatCount.toInt(), from.toInt() - 1, to.toInt() - 1)) } return Pair(stacks, moves) } else { stackLines.add(iIter.value) } } return Pair(listOf(), listOf()) } fun processStack( stacks: List<Stack<String>>, moves: List<Move>, algorithm: (List<Stack<String>>, Move) -> Unit ): String { moves.forEach { algorithm.invoke(stacks, it) } return buildString { for (stack in stacks) { append(stack.peek()) } } } fun part1(input: List<String>): String { val pair = parseInput(input) return processStack( pair.first, pair.second) { s, move -> repeat(move.count) { s[move.to].push(s[move.from].pop()) } } } fun part2(input: List<String>): String { val pair = parseInput(input) return processStack( pair.first, pair.second) { stacks, move -> val tmp = mutableListOf<String>() repeat(move.count) { tmp.add(stacks[move.from].pop()) } repeat(move.count) { stacks[move.to].push(tmp.removeLast()) } } } val testInput = readInput("Day05_test") check(part1(testInput) == "CMZ") val input = readInput("Day05") println(part1(input)) check(part2(testInput) == "MCD") println(part2(input)) }
0
Kotlin
0
0
e5f13dae0d2fa1aef14dc71c7ba7c898c1d1a5d1
3,039
AdventOfCode-2022
Apache License 2.0
src/main/kotlin/at/mpichler/aoc/solutions/year2022/Day21.kt
mpichler94
656,873,940
false
{"Kotlin": 196457}
package at.mpichler.aoc.solutions.year2022 import at.mpichler.aoc.lib.Day import at.mpichler.aoc.lib.PartSolution open class Part21A : PartSolution() { lateinit var monkeys: Map<String, Monkey> override fun parseInput(text: String) { val monkeys = mutableListOf<Monkey>() val pattern = Regex("(.*?): (.*)") for (line in text.trim().split("\n")) { val result = pattern.find(line)!! val op = result.groupValues[2] val parts = op.split(" ") if (parts.size > 1) { monkeys.add(Monkey(result.groupValues[1], listOf(parts[0], parts[2]), parts[1])) } else { monkeys.add(Monkey(result.groupValues[1], listOf(), op)) } } this.monkeys = monkeys.associateBy { it.name } } override fun compute(): Long { return monkeys["root"]!!.getResult(monkeys) } override fun getExampleAnswer(): Int { return 152 } data class Monkey(val name: String, val inputs: List<String>, val operation: String) { fun getResult(monkeys: Map<String, Monkey>): Long { if (inputs.isEmpty()) { return operation.toLong() } val arg1 = monkeys[inputs[0]] val arg2 = monkeys[inputs[1]] return when (operation) { "+" -> arg1!!.getResult(monkeys) + arg2!!.getResult(monkeys) "-" -> arg1!!.getResult(monkeys) - arg2!!.getResult(monkeys) "*" -> arg1!!.getResult(monkeys) * arg2!!.getResult(monkeys) "/" -> arg1!!.getResult(monkeys) / arg2!!.getResult(monkeys) else -> error("Invalid operation") } } } } class Part21B : Part21A() { override fun compute(): Long { val todo = ArrayDeque<String>() todo.add("humn") val newMonkeys = monkeys.toMutableMap() while (todo.isNotEmpty()) { val name = todo.removeFirst() for (monkey in monkeys.values) { if (name in monkey.inputs) { val otherMonkey = if (name == monkey.inputs[0]) monkey.inputs[1] else monkey.inputs[0] if (monkey.name == "root") { newMonkeys[name] = Monkey(name, listOf(), monkeys[otherMonkey]!!.getResult(monkeys).toString()) continue } val parts = reorder(monkey, name).split(" ") val inputs = listOf(parts[0], parts[2]) newMonkeys[name] = Monkey(name, inputs, parts[1]) todo.addLast(monkey.name) } } } return newMonkeys["humn"]!!.getResult(newMonkeys) } private fun reorder(monkey:Monkey, target: String): String { val left = monkey.inputs[0] val right = monkey.inputs[1] val op = monkey.operation val other = if (target == left) right else left return when (op) { "+" -> "${monkey.name} - $other" "-" -> { if (target == left) { "${monkey.name} + $right" } else { "$left - ${monkey.name}" } } "*" -> "${monkey.name} / $other" "/" -> { if (target == left) { "${monkey.name} * $right" } else { "$left / ${monkey.name}" } } else -> error("Unsupported operation") } } override fun getExampleAnswer(): Int { return 301 } } fun main() { Day(2022, 21, Part21A(), Part21B()) }
0
Kotlin
0
0
69a0748ed640cf80301d8d93f25fb23cc367819c
3,719
advent-of-code-kotlin
MIT License
2022/src/main/kotlin/de/skyrising/aoc2022/day8/solution.kt
skyrising
317,830,992
false
{"Kotlin": 411565}
package de.skyrising.aoc2022.day8 import de.skyrising.aoc.* import java.util.* private fun parseInput(input: PuzzleInput): Array<IntArray> { val rows = mutableListOf<IntArray>() for (line in input.byteLines) { val row = IntArray(line.remaining()) for (i in 0 until line.remaining()) { row[i] = line[i] - '0'.code.toByte() } rows.add(row) } return rows.toTypedArray() } private fun viewingDistance(limit: Int, lookup: (k: Int) -> Int): Int { val self = lookup(limit) var highest = 0 var count = 0 for (k in limit - 1 downTo 0) { val other = lookup(k) ++count if (other >= self) return count highest = maxOf(highest, other) } return count } val test = TestInput(""" 30373 25512 65332 33549 35390 """) @PuzzleName("Treetop Tree House") fun PuzzleInput.part1(): Any { val rows = parseInput(this) val width = rows[0].size val height = rows.size val visible = BitSet(width * height) val down = 0 until height val right = 0 until width for (i in down) { var highest = -1 for (j in right) { if (rows[j][i] > highest) visible.set(j * height + i) highest = maxOf(rows[j][i], highest) } highest = -1 for (j in right.reversed()) { if (rows[j][i] > highest) visible.set(j * height + i) highest = maxOf(rows[j][i], highest) } } for (j in right) { var highest = -1 for (i in down) { if (rows[j][i] > highest) visible.set(j * height + i) highest = maxOf(rows[j][i], highest) } highest = -1 for (i in down.reversed()) { if (rows[j][i] > highest) visible.set(j * height + i) highest = maxOf(rows[j][i], highest) } } /*for (j in 0 until height) { for (i in 0 until width) { if (visible.get(j * width + i)) print(rows[j][i]) else print(' ') } println() }*/ return visible.cardinality() } fun PuzzleInput.part2(): Any { val rows = parseInput(this) val width = rows[0].size val height = rows.size var highscore = 0 for (j in 1 until height - 1) { for (i in 1 until width - 1) { val left = viewingDistance(i) { k -> rows[j][k]} val right = viewingDistance(width - i - 1) { k -> rows[j][width - k - 1]} val up = viewingDistance(j) { k -> rows[k][i]} val down = viewingDistance(height - j - 1) { k -> rows[height - k - 1][i]} val score = left * right * up * down highscore = maxOf(highscore, score) } } return highscore }
0
Kotlin
0
0
19599c1204f6994226d31bce27d8f01440322f39
2,735
aoc
MIT License
src/test/kotlin/ch/ranil/aoc/aoc2023/Day19.kt
stravag
572,872,641
false
{"Kotlin": 234222}
package ch.ranil.aoc.aoc2023 import ch.ranil.aoc.AbstractDay import org.junit.jupiter.api.Test import kotlin.math.max import kotlin.math.min import kotlin.test.assertEquals class Day19 : AbstractDay() { @Test fun part1Test() { assertEquals(19114, compute1(testInput)) } @Test fun part1Puzzle() { assertEquals(472630, compute1(puzzleInput)) } @Test fun part2Test() { assertEquals(167409079868000, compute2(testInput)) } @Test fun part2Tests() { Workflow.parse("qqz{s>2770:qs,m<1801:hdj,R}").possibleCombinations() """ px{a<2006:qkq,m>2090:A,rfg} pv{a>1716:R,A} lnx{m>1548:A,A} rfg{s<537:gd,x>2440:R,A} qs{s>3448:A,lnx} qkq{x<1416:A,crn} crn{x>2662:A,R} in{s<1351:px,qqz} qqz{s>2770:qs,m<1801:hdj,R} gd{a>3333:R,R} hdj{m>838:A,pv} """.trimIndent() .lines() .map { Workflow.parse(it) } .map { it.name to it.possibleCombinations() } .forEach { (name, comb) -> println("${name.name} = ${comb.first}, ${comb.second.map { "${it.key.name} = ${it.value}" }}") } } @Test fun part2Puzzle() { assertEquals(0, compute2(puzzleInput)) } private fun compute1(input: List<String>): Int { val (workflows, ratings) = input.parse() return ratings.filter { isAccepted(it, WorkflowName("in"), workflows) }.sumOf { it.x + it.m + it.a + it.s } } private fun isAccepted( rating: PartsRating, workflowName: WorkflowName, workflows: Map<WorkflowName, Workflow>, ): Boolean { val workflow = workflows.getValue(workflowName) return when (val nextWorkflow = workflow.process(rating)) { Accepted -> true Rejected -> false is WorkflowName -> isAccepted(rating, nextWorkflow, workflows) } } private fun compute2(input: List<String>): Long { val (workflows, _) = input.parse() return countPossibleCombinations(PartsRatingRanges(), WorkflowName("in"), workflows) } private fun countPossibleCombinations( knownCombinations: PartsRatingRanges, workflowName: WorkflowName, workflows: Map<WorkflowName, Workflow>, ): Long { val workflow = workflows.getValue(workflowName) val (combinationsForWorkflow, nextWorkflows) = workflow.possibleCombinations() TODO() } private fun List<String>.parse(): Pair<Map<WorkflowName, Workflow>, List<PartsRating>> { val workflows = this .takeWhile { it.isNotBlank() } .map { Workflow.parse(it) } .associateBy { it.name } val ratings = this.drop(workflows.size + 1) .map { ratingsString -> val (x, m, a, s) = Regex("[0-9]+").findAll(ratingsString).map { it.value }.toList() PartsRating( x = x.toInt(), m = m.toInt(), a = a.toInt(), s = s.toInt(), ) } return workflows to ratings } private data class Workflow( val name: WorkflowName, val statements: List<Statement>, ) { fun process(rating: PartsRating): WorkFlowResponse { for (statement in statements) { val workFlowResponse = statement.process(rating) if (workFlowResponse != null) return workFlowResponse } throw IllegalStateException("Workflow $this didn't yield response for $rating") } fun possibleCombinations(): Pair<PartsRatingRanges, Map<WorkflowName, PartsRatingRanges>> { return statements.windowed(size = 2, step = 1) { (ifStmt, elseStmt) -> var ranges = PartsRatingRanges() val nextWorkflowCombinations = mutableMapOf<WorkflowName, PartsRatingRanges>() if (ifStmt.response is Accepted) { ranges = ranges.intersect(ifStmt.rangeForTrue()) } if (ifStmt.response is WorkflowName) { nextWorkflowCombinations.compute(ifStmt.response as WorkflowName) { _, c -> (c ?: PartsRatingRanges()).intersect(ifStmt.rangeForTrue()) } } if (elseStmt.response is Accepted) { ranges = ranges.intersect(ifStmt.rangeForTrue()) } if (elseStmt.response is WorkflowName) { nextWorkflowCombinations.compute(elseStmt.response as WorkflowName) { _, c -> (c ?: PartsRatingRanges()).intersect(ifStmt.rangeForFalse()) } } ranges to nextWorkflowCombinations }.reduce { acc, map -> acc.second.putAll(map.second) (acc.first.intersect(map.first)) to acc.second } } companion object { fun parse(s: String): Workflow { val (_, name, operationsString) = Regex("([a-z]+)\\{(.*)}").find(s)?.groupValues.orEmpty() val operations = operationsString .split(",") .map { stmt -> if (stmt.contains(":")) { IfStatement.of(stmt) } else { ElseStatement.of(stmt) } } return Workflow( name = WorkflowName(name), statements = operations, ) } } } private sealed interface Statement { val response: WorkFlowResponse fun rangeForTrue(): PartsRatingRanges fun rangeForFalse(): PartsRatingRanges fun process(rating: PartsRating): WorkFlowResponse? } private data class IfStatement( private val r: String, private val comparator: String, private val number: Int, override val response: WorkFlowResponse, ) : Statement { override fun process(rating: PartsRating): WorkFlowResponse? { val value = rating.get(r) return when (comparator) { "<" -> if (value < number) response else null ">" -> if (value > number) response else null else -> throw IllegalArgumentException("unexpected comparator $comparator in $this") } } override fun rangeForTrue(): PartsRatingRanges { val range = when (comparator) { "<" -> 1..<number ">" -> number..4000 else -> throw IllegalArgumentException("unexpected comparator $comparator in $this") } return PartsRatingRanges.build(r, range) } override fun rangeForFalse(): PartsRatingRanges { val range = when (comparator) { ">" -> 1..number "<" -> number..4000 else -> throw IllegalArgumentException("unexpected comparator $comparator in $this") } return PartsRatingRanges.build(r, range) } companion object { fun of(s: String): IfStatement { val (_, r, comparator, number, workflowName) = Regex("([a-z]+)([<>])([0-9]+):([a-zA-Z]+)") .find(s)?.groupValues.orEmpty() return IfStatement(r, comparator, number.toInt(), WorkFlowResponse.of(workflowName)) } } } private data class ElseStatement( override val response: WorkFlowResponse, ) : Statement { override fun process(rating: PartsRating): WorkFlowResponse { return response } override fun rangeForTrue(): PartsRatingRanges = PartsRatingRanges.empty() override fun rangeForFalse(): PartsRatingRanges = PartsRatingRanges.empty() companion object { fun of(s: String): ElseStatement { return ElseStatement(WorkFlowResponse.of(s)) } } } private sealed interface WorkFlowResponse { companion object { fun of(s: String) = when (s) { "A" -> Accepted "R" -> Rejected else -> WorkflowName(s) } } } private data object Accepted : WorkFlowResponse private data object Rejected : WorkFlowResponse private data class WorkflowName(val name: String) : WorkFlowResponse private data class PartsRating( val x: Int, val m: Int, val a: Int, val s: Int, ) { fun get(i: String): Int { return when (i) { "x" -> x "m" -> m "a" -> a "s" -> s else -> throw IllegalArgumentException("unexpected ratings value: $i") } } } private data class PartsRatingRanges( val x: IntRange = 1..4000, val m: IntRange = 1..4000, val a: IntRange = 1..4000, val s: IntRange = 1..4000, ) { fun intersect(other: PartsRatingRanges): PartsRatingRanges { return PartsRatingRanges( x = IntRange(max(x.first, other.x.first), min(x.last, other.x.last)), m = IntRange(max(m.first, other.m.first), min(m.last, other.m.last)), a = IntRange(max(a.first, other.a.first), min(a.last, other.a.last)), s = IntRange(max(s.first, other.s.first), min(s.last, other.s.last)), ) } companion object { fun build(r: String, range: IntRange): PartsRatingRanges { return when (r) { "x" -> PartsRatingRanges(x = range) "m" -> PartsRatingRanges(m = range) "a" -> PartsRatingRanges(a = range) "s" -> PartsRatingRanges(s = range) else -> throw IllegalArgumentException("unexpected ratings value: $r") } } fun empty(): PartsRatingRanges { return PartsRatingRanges(IntRange.EMPTY, IntRange.EMPTY, IntRange.EMPTY, IntRange.EMPTY) } } } }
0
Kotlin
1
0
dbd25877071cbb015f8da161afb30cf1968249a8
10,431
aoc
Apache License 2.0
kotlin/src/main/kotlin/adventofcode/day10/Day10.kt
thelastnode
160,586,229
false
null
package adventofcode.day10 import java.io.File import java.util.* object Day10 { data class Vector(val x: Int, val y: Int) { operator fun plus(other: Vector): Vector = Vector(x + other.x, y + other.y) fun neighbors(): List<Vector> { val offsets = listOf( Vector( 0, -1), Vector( 0, 1), Vector(-1, 0), Vector( 1, 0) ) return offsets.map { this + it } } } data class Point(val position: Vector, val velocity: Vector) { fun tick(): Point = Point(position = position + velocity, velocity = velocity) } val LINE_REGEX = Regex("position=< ?([0-9\\-]+), ?([0-9\\-]+)> velocity=< ?([0-9\\-]+), ?([0-9\\-]+)>") fun parse(line: String): Point { val (_, posX, posY, velX, velY) = LINE_REGEX.find(line)!!.groupValues return Point( position = Vector(x = posX.toInt(), y = posY.toInt()), velocity = Vector(x = velX.toInt(), y = velY.toInt()) ) } fun printInstant(points: List<Point>): String { val positions = points.map { it.position }.toSet() val ys = positions.map { it.y } val xs = positions.map { it.x } val (xmin, xmax) = Pair(xs.min()!!, xs.max()!!) val (ymin, ymax) = Pair(ys.min()!!, ys.max()!!) return buildString { for (y in ymin..ymax) { for (x in xmin..xmax) { if (Vector(x, y) in positions) { append("#") } else { append(".") } } appendln() } } } fun tick(points: List<Point>): List<Point> = points.map { it.tick() } fun connectedComponents(points: List<Point>): Int { val positions = points.map { it.position }.toSet() val visited = mutableSetOf<Vector>() var components = 0 for (point in positions) { if (point in visited) { continue } components++ val queue: Queue<Vector> = LinkedList() queue.add(point) while (queue.isNotEmpty()) { val p = queue.poll() visited.add(p) for (neighbor in p.neighbors()) { if (neighbor !in visited && neighbor in positions) { queue.add(neighbor) } } } } return components } fun process(inputs: List<Point>) { val tries = 100_000 var points = inputs val pointsAtTime = mutableListOf<List<Point>>() (0 until tries).forEach { pointsAtTime.add(points) points = tick(points) } val counts = pointsAtTime.map { connectedComponents(it) } val minIndex = counts.withIndex().minBy { it.value }!!.index println("Min components: ${counts[minIndex]} @ $minIndex") println(printInstant(pointsAtTime[minIndex])) } } fun main(args: Array<String>) { val lines = File("./day10-input").readLines() val inputs = lines.map { Day10.parse(it) } Day10.process(inputs) }
0
Kotlin
0
0
8c9a3e5a9c8b9dd49eedf274075c28d1ebe9f6fa
3,285
adventofcode
MIT License
src/Day05.kt
WilsonSunBritten
572,338,927
false
{"Kotlin": 40606}
fun main() { fun part1(input: List<String>): String { val splitIndex = input.indexOf("") val rawGridDefinition = input.subList(0, splitIndex) val rawInstructions = input.subList(splitIndex + 1, input.size) val stacks = mutableMapOf<Int, MutableList<Char>>() println(rawGridDefinition) // ignore the column name definitions, infer by position rawGridDefinition.dropLast(1).forEach { line -> // println("line: $line") line.forEachIndexed { index, c -> // println("index: $index, c: $c") // correspoinding column by index if ((index - 1) % 4 == 0 && c != ' ') { stacks.compute(((index - 1) / 4) + 1) { key, currentList -> currentList?.apply { add(c) } ?: mutableListOf(c) } } } } println(stacks) val instructionRegex = "move (\\d+) from (\\d+) to (\\d+)".toRegex() val instructions = rawInstructions.map {instructionLine -> println(instructionLine) val matchGroups = instructionRegex.matchEntire(instructionLine)!!.groupValues.drop(1).map { it.toInt() } Instruction(matchGroups[0], matchGroups[1], matchGroups[2]) } instructions.forEach { instruction -> repeat(instruction.count) { val fromColumn = stacks[instruction.sourceColumn] println(fromColumn) val from = stacks[instruction.sourceColumn]!!.removeAt(0) println("from: $from") stacks.compute(instruction.destinationColumn) { key, value -> (value ?: mutableListOf()).let { mutableListOf(from).plus(it).toMutableList() } } } } println(stacks) return stacks.toList().sortedBy { it.first }.map { it.second.first() }.joinToString("") { it.toString() } } fun part2(input: List<String>): String { val splitIndex = input.indexOf("") val rawGridDefinition = input.subList(0, splitIndex) val rawInstructions = input.subList(splitIndex + 1, input.size) val stacks = mutableMapOf<Int, MutableList<Char>>() println(rawGridDefinition) // ignore the column name definitions, infer by position rawGridDefinition.dropLast(1).forEach { line -> // println("line: $line") line.forEachIndexed { index, c -> // println("index: $index, c: $c") // correspoinding column by index if ((index - 1) % 4 == 0 && c != ' ') { stacks.compute(((index - 1) / 4) + 1) { key, currentList -> currentList?.apply { add(c) } ?: mutableListOf(c) } } } } println(stacks) val instructionRegex = "move (\\d+) from (\\d+) to (\\d+)".toRegex() val instructions = rawInstructions.map {instructionLine -> println(instructionLine) val matchGroups = instructionRegex.matchEntire(instructionLine)!!.groupValues.drop(1).map { it.toInt() } Instruction(matchGroups[0], matchGroups[1], matchGroups[2]) } instructions.forEach { instruction -> val fromColumn = stacks[instruction.sourceColumn] val movingElements = (0 until instruction.count).map { stacks[instruction.sourceColumn]!!.removeAt(0) } stacks.compute(instruction.destinationColumn) { key, value -> (value ?: mutableListOf()).let { movingElements.plus(it).toMutableList() } } } println(stacks) return stacks.toList().sortedBy { it.first }.map { it.second.first() }.joinToString("") { it.toString() } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day05_test") val input = readInput("Day05") val p1TestResult = part1(testInput) println(p1TestResult) check(p1TestResult == "CMZ") println(part1(input)) println("Part 2") val p2TestResult = part2(testInput) println(p2TestResult) check(part2(testInput) == "MCD") println(part2(input)) } data class Grid(val stacks: Map<Int, MutableList<Char>>) data class Instruction(val count: Int, val sourceColumn: Int, val destinationColumn: Int)
0
Kotlin
0
0
363252ffd64c6dbdbef7fd847518b642ec47afb8
4,441
advent-of-code-2022-kotlin
Apache License 2.0
src/Day02.kt
Vlisie
572,110,977
false
{"Kotlin": 31465}
import java.io.File //rock a en x paper b en y scissor c en z fun main() { fun isElfWinner(opponent: String, elf: String): Boolean { return opponent == "A" && elf == "Y" || opponent == "B" && elf == "Z" || opponent == "C" && elf == "X" } fun isDraw(opponent: String, elf: String): Boolean { return opponent == "A" && elf == "X" || opponent == "B" && elf == "Y" || opponent == "C" && elf == "Z" } fun keuzeWaarde(elf: String): Int { return when (elf) { "X" -> 1 "Y" -> 2 "Z" -> 3 else -> 0 } } fun makeLose(opponent: String): String { return when (opponent) { "A" -> "Z" "B" -> "X" "C" -> "Y" else -> "" } } fun makeDraw(opponent: String): String { return when (opponent) { "A" -> "X" "B" -> "Y" "C" -> "Z" else -> "" } } fun makeWin(opponent: String): String { return when (opponent) { "A" -> "Y" "B" -> "Z" "C" -> "X" else -> "" } } fun choosePlay(opponent: String, winOrLoose: String): Int { return when (winOrLoose) { "X" -> keuzeWaarde(makeLose(opponent)) "Y" -> keuzeWaarde(makeDraw(opponent)) + 3 "Z" -> keuzeWaarde(makeWin(opponent)) + 6 else -> 0 } } fun part1(): Int = File("src", "input/input2.txt") .readText() .trimEnd() .split("\n".toRegex()) .map { it.split("\\s".toRegex()).toTypedArray() } .map { element -> if (isElfWinner(element[0], element[1])) { return@map 6 + keuzeWaarde(element[1]) } else if (isDraw(element[0], element[1])) { return@map 3 + keuzeWaarde(element[1]) } else { return@map 0 + keuzeWaarde(element[1]) } } .sum() fun part2(file: File): Int = file .readText() .trimEnd() .split("\n".toRegex()) .map { it.split("\\s".toRegex()).toTypedArray() } .map { element -> return@map choosePlay(element[0], element[1]) } .sum() // test if implementation meets criteria from the description, like: val testInput = File("src", "input/testInput.txt") check(part2(testInput) == 12) val input = File("src", "input/input2.txt") println(part2(input)) }
0
Kotlin
0
0
b5de21ed7ab063067703e4adebac9c98920dd51e
2,562
AoC2022
Apache License 2.0
src/solutions/week1/CombinationSum.kt
yashovardhan99
300,555,774
false
null
package solutions.week1 import kotlin.test.assertTrue class CombinationSum { private val sums = mutableListOf<List<Int>>() /** * A simple backtracking algorithm is used. If target == 0 -> we have the sum => add the current list to output * If target<0 => Backtrack * Else => Iterate through each element, add it to a list and recursively call backtrack(). */ fun combinationSum(candidates: IntArray, target: Int): List<List<Int>> { backtrack(candidates, target, 0, mutableListOf()) return sums } private fun backtrack(candidates: IntArray, target: Int, index: Int, used: List<Int>) { println("backtrack($target, $index, $used)") if (target < 0) return if (target == 0) { println("Adding $used") sums.add(used.toList()) return } val cur = used.toMutableList() for (i in index until candidates.size) { cur.add(candidates[i]) backtrack(candidates, target - candidates[i], i, cur) cur.removeAt(cur.lastIndex) } } } // Testing against examples // Example 1: // //Input: candidates = [2,3,6,7], target = 7 //Output: [[2,2,3],[7]] //Explanation: //2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times. //7 is a candidate, and 7 = 7. //These are the only two combinations. // //Example 2: // //Input: candidates = [2,3,5], target = 8 //Output: [[2,2,2,2],[2,3,3],[3,5]] // //Example 3: // //Input: candidates = [2], target = 1 //Output: [] // //Example 4: // //Input: candidates = [1], target = 1 //Output: [[1]] // //Example 5: // //Input: candidates = [1], target = 2 //Output: [[1,1]] fun main() { val example1 = CombinationSum().combinationSum(intArrayOf(2, 3, 6, 7), 7) val example2 = CombinationSum().combinationSum(intArrayOf(2, 3, 5), 8) val example3 = CombinationSum().combinationSum(intArrayOf(2), 1) val example4 = CombinationSum().combinationSum(intArrayOf(1), 1) val example5 = CombinationSum().combinationSum(intArrayOf(1), 2) println("Output 1: $example1") assertTrue { example1.size == 2 } assertTrue { example1.contains(listOf(2, 2, 3)) } assertTrue { example1.contains(listOf(7)) } println("Output 2: $example2") assertTrue { example2.size == 3 } assertTrue { example2.contains(listOf(2, 2, 2, 2)) } assertTrue { example2.contains(listOf(2, 3, 3)) } assertTrue { example2.contains(listOf(3, 5)) } println("Output 3: $example3") assertTrue { example3.isEmpty() } println("Output 4: $example4") assertTrue { example4.size == 1 } assertTrue { example4.contains(listOf(1)) } println("Output 5: $example5") assertTrue { example5.size == 1 } assertTrue { example5.contains(listOf(1, 1)) } }
0
Kotlin
1
0
b2324e23631f29b61cda3b315d4ce7557070f1e4
2,804
October-LeetCoding-Challenge
MIT License
kotlin/src/com/daily/algothrim/leetcode/medium/CombinationSum.kt
idisfkj
291,855,545
false
null
package com.daily.algothrim.leetcode.medium /** * 39. 组合总和 * * 给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。 * candidates 中的数字可以无限制重复被选取。 * * 说明: * * 所有数字(包括 target)都是正整数。 * 解集不能包含重复的组合。  */ class CombinationSum { companion object { @JvmStatic fun main(args: Array<String>) { CombinationSum().combinationSum(intArrayOf(2, 3, 6, 7), 7).forEach { it.forEach { item -> print(item) } println() } CombinationSum().combinationSum(intArrayOf(2, 3, 5), 8).forEach { it.forEach { item -> print(item) } println() } } } // 输入:candidates = [2,3,6,7], target = 7, // 所求解集为: // [ // [7], // [2,2,3] // ] fun combinationSum(candidates: IntArray, target: Int): List<List<Int>> { if (candidates.isEmpty()) return listOf() val result = arrayListOf<List<Int>>() backtracking(target, candidates, 0, arrayListOf(), result) return result } private fun backtracking( remind: Int, candidates: IntArray, index: Int, currentList: ArrayList<Int>, result: ArrayList<List<Int>> ) { if (remind == 0) { val subList = arrayListOf<Int>() subList.addAll(currentList) result.add(subList) return } if (remind < 0 || index >= candidates.size) return backtracking(remind, candidates, index + 1, currentList, result) currentList.add(candidates[index]) backtracking(remind - candidates[index], candidates, index, currentList, result) currentList.removeAt(currentList.size - 1) } }
0
Kotlin
9
59
9de2b21d3bcd41cd03f0f7dd19136db93824a0fa
2,018
daily_algorithm
Apache License 2.0
src/Day02.kt
tsschmidt
572,649,729
false
{"Kotlin": 24089}
const val ROCK = "A" const val PAPER = "B" const val SCISSORS = "C" const val LOSE = "X" const val DRAW = "Y" const val WIN = "Z" fun main() { fun outcome(a: String, b: String): Int { return when (a+b) { "AA", "BB", "CC" -> 3 "AB", "BC", "CA" -> 6 "AC", "BA", "CB" -> 0 else -> error("Check Inputs") } } fun points(a: String): Int { return when(a) { ROCK -> 1 PAPER -> 2 SCISSORS -> 3 else -> error("Check Inputs") } } fun round(a: String, b: String): Int { val b1 = when (b) { "X" -> ROCK "Y" -> PAPER "Z" -> SCISSORS else -> error("Check Inputs") } return outcome(a, b1) + points(b1) } fun round2(a: String, b: String): Int { val b1 = when(b) { LOSE -> when (a) { ROCK -> SCISSORS PAPER -> ROCK else -> PAPER } WIN -> when(a) { ROCK -> PAPER PAPER -> SCISSORS else -> ROCK } DRAW -> a else -> error("Check Inputs") } return outcome(a, b1) + points(b1) } fun part1(input: List<String>): Int { return input.sumOf { val (a, b) = it.split(" ") round(a, b) } } fun part2(input: List<String>): Int { return input.sumOf { val (a, b) = it.split(" ") round2(a, b) } } //val input = readInput("Day02_test") //check(part2(input) == 12) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
7bb637364667d075509c1759858a4611c6fbb0c2
1,754
aoc-2022
Apache License 2.0
src/main/kotlin/g2401_2500/s2463_minimum_total_distance_traveled/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2401_2500.s2463_minimum_total_distance_traveled // #Hard #Array #Dynamic_Programming #Sorting // #2023_07_05_Time_153_ms_(100.00%)_Space_37_MB_(100.00%) import java.util.Arrays class Solution { fun minimumTotalDistance(robot: List<Int>, f: Array<IntArray>): Long { // sort factories : // 1. move all factories with 0-capacity to the end // 2. sort everything else by x-position in asc order Arrays.sort(f) { a: IntArray, b: IntArray -> if (a[1] == 0) 1 else if (b[1] == 0) -1 else a[0] - b[0] } // Sort robots by x-position in asc order // As we don't know the implementation of the List that is passed, it is better to map it to // an array explicitly val r = IntArray(robot.size) var i = 0 for (x in robot) { r[i++] = x } r.sort() // An array to be used for tracking robots assigned to each factory val d = Array(f.size) { IntArray(2) } // For each robot starting from the rightmost find the most optimal destination factory // and add it's cost to the result. var res: Long = 0 i = r.size - 1 while (i >= 0) { res += pop(d, i, r, f) i-- } return res } private fun pop(d: Array<IntArray>, i: Int, r: IntArray, f: Array<IntArray>): Long { var cost = Long.MAX_VALUE // try assigning robot to each factory starting from the leftmost var j = 0 while (j < d.size) { // cost of adding robot to the current factory var t = Math.abs(r[i] - f[j][0]).toLong() var tj = j // if current factory is full calculate the cost of moving the rightmost robot in the // factory to the next one // and add the calculated cost to the current cost. // repeat the same action until we fit our robots to factories. while (tj < d.size && d[tj][1] == f[tj][1]) { // if we faced a factory with 0-capactity or the rightmost factory // it would mean we reached the end and cannot fit our robot to the current factory if (d[tj][1] == 0 || tj == d.size - 1) { t = Long.MAX_VALUE break } val l = d[tj][0] + d[tj][1] - 1 t += (Math.abs(f[tj + 1][0] - r[l]) - Math.abs(f[tj][0] - r[l])).toLong() ++tj } // if the cost for adding robot to the current factory is greater than the previous one // it means that the previous one was the most optimal if (t > cost) { break } cost = t j++ } // assign current robot to the previous factory and move any non-fit robots to the right d[j - 1][0] = i var tj = j - 1 while (d[tj][1] == f[tj][1]) { d[tj + 1][0] = d[tj][0] + d[tj][1] ++tj } d[tj][1]++ return cost } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
3,074
LeetCode-in-Kotlin
MIT License
jvm/src/main/kotlin/io/prfxn/aoc2021/day18.kt
prfxn
435,386,161
false
{"Kotlin": 72820, "Python": 362}
// Snailfish (https://adventofcode.com/2021/day/18) package io.prfxn.aoc2021 private object Day18 { interface SFNum { operator fun plus(other: SFNum): SFNum = SFNumPair(this, other) fun traverseInPostOrder(depth: Int = 0, parent: SFNumPair? = null): Sequence<Triple<SFNum, Int, SFNumPair?>> = if (this is SFNumPair) this.left.traverseInPostOrder(depth + 1, this) + this.right.traverseInPostOrder(depth + 1, this) + Triple(this, depth, parent) else sequenceOf(Triple(this, depth, parent)) fun explode(): Boolean { var lastRegular = SFNumRegular(0) var rightResidue = -1 for ((sfn, depth, parent) in traverseInPostOrder().toList()) { if (rightResidue != -1) if (sfn is SFNumRegular) { sfn.value += rightResidue return true } else continue if (depth > 4) continue if (sfn is SFNumRegular) lastRegular = sfn if (sfn is SFNumPair && depth == 4) { lastRegular.value += (sfn.left as SFNumRegular).value rightResidue = (sfn.right as SFNumRegular).value parent?.apply { SFNumRegular(0).let { if (left == sfn) left = it else right = it } } } } return false } fun split(): Boolean { traverseInPostOrder() .toList() .forEach { (sfn, _, parent) -> if (sfn is SFNumRegular && sfn.value >= 10) { parent?.apply { val l = SFNumRegular(sfn.value / 2) SFNumPair(l, SFNumRegular(sfn.value - l.value)).let { if (left == sfn) left = it else right = it } } return true } } return false } fun reduce() { while (true) { if (explode()) continue if (split()) continue break } } fun magnitude(): Int = when (this) { is SFNumRegular -> value is SFNumPair -> 3 * left.magnitude() + 2 * right.magnitude() else -> fail() } } data class SFNumRegular(var value: Int): SFNum { override fun toString() = value.toString() } data class SFNumPair(var left: SFNum, var right: SFNum): SFNum { override fun toString() = "[$left,$right]" } fun parseSFNum(s: String, start: Int, end: Int): SFNum = if (s[start] == '[') { // parse pair val mid = with ((start..end)) { var depth = 0 find { i -> when (s[i]) { ',' -> depth == 1 '[' -> { depth++; false } ']' -> { depth--; false} else -> false } }!! } SFNumPair( parseSFNum(s, start + 1, mid - 1), parseSFNum(s, mid + 1, end - 1) ) } else { // parse regular SFNumRegular((start..end).map(s::get).joinToString("").toInt()) } fun parseSFNum(s: String) = parseSFNum(s, 0, s.length - 1) } fun main() { val lines = textResourceReader("input/18.txt").readLines() var totalSfn: Day18.SFNum? = null lines.map(Day18::parseSFNum).forEach { sfn -> totalSfn = totalSfn?.let { (it + sfn).apply { reduce() } } ?: sfn.apply { reduce() } } println(totalSfn?.magnitude()) val maxSfnMagnitude = lines.permutations(2).map { val (a, b) = it.map(Day18::parseSFNum) (a + b).apply { reduce() }.magnitude() }.maxOf { it } println(maxSfnMagnitude) }
0
Kotlin
0
0
148938cab8656d3fbfdfe6c68256fa5ba3b47b90
4,236
aoc2021
MIT License
src/main/kotlin/day08.kt
tobiasae
434,034,540
false
{"Kotlin": 72901}
class Day08 : Solvable("08") { override fun solveA(input: List<String>): String { return input .map { it.split("|").last().trim().split(" ") } .map { it.filter { listOf(2, 3, 4, 7).contains(it.length) }.size } .sum() .toString() } override fun solveB(input: List<String>): String { val lines = input.map { it.split("|").map { it.trim().split(" ").map { it.toSet() } } } return lines .map { val (learning, display) = it val ones = learning.find { it.size == 2 } as Set val fours = learning.find { it.size == 4 } as Set display .map { when (it.size) { 2 -> 1 3 -> 7 4 -> 4 5 -> if (it.intersect(ones).size == 2) 3 else if (it.intersect(fours).size == 2) 2 else 5 6 -> if (it.intersect(ones).size == 1) 6 else if (it.intersect(fours).size == 3) 0 else 9 else -> 8 } } .joinToString(separator = "") .toInt() } .sum() .toString() } }
0
Kotlin
0
0
16233aa7c4820db072f35e7b08213d0bd3a5be69
1,650
AdventOfCode
Creative Commons Zero v1.0 Universal
src/main/kotlin/g0901_1000/s0943_find_the_shortest_superstring/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0901_1000.s0943_find_the_shortest_superstring // #Hard #Array #String #Dynamic_Programming #Bit_Manipulation #Bitmask // #2023_04_29_Time_1290_ms_(100.00%)_Space_309.3_MB_(100.00%) class Solution { fun shortestSuperstring(words: Array<String>): String? { val l = words.size var state = 0 for (i in 0 until l) { state = state or (1 shl i) } val map: MutableMap<String?, String?> = HashMap() return solveTPS(words, state, "", map, l) } private fun solveTPS( words: Array<String>, state: Int, startWord: String, map: MutableMap<String?, String?>, l: Int ): String? { val key = "$startWord|$state" if (state == 0) { return startWord } if (map[key] != null) { return map[key] } var minLenWord: String? = "" for (i in 0 until l) { if (state shr i and 1 == 1) { val takenState = state and (1 shl i).inv() val result = solveTPS(words, takenState, words[i], map, l) val tmp = mergeAndGet(startWord, result) if (minLenWord!!.isEmpty() || minLenWord.length > tmp.length) { minLenWord = tmp } } } map[key] = minLenWord return minLenWord } private fun mergeAndGet(word: String, result: String?): String { val l = word.length val t = result!!.length if (result.contains(word)) { return result } if (word.contains(result)) { return word } var found = l for (k in 0 until l) { var i = k var j = 0 while (i < l && j < t) { if (word[i] == result[j]) { i++ j++ } else break } if (i == l) { found = k break } } return word.substring(0, found) + result } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
2,085
LeetCode-in-Kotlin
MIT License
src/questions/NextGreaterElementII.kt
realpacific
234,499,820
false
null
package questions import _utils.UseCommentAsDocumentation import utils.shouldBe import java.util.* /** * Given a circular integer array nums (i.e., the next element of nums[nums.length - 1] is nums[0]), * return the next greater number for every element in nums. * The next greater number of a number x is the first greater number to its traversing-order next in the array, * which means you could search circularly to find its next greater number. If it doesn't exist, return -1 for this number. * * [Source](https://leetcode.com/problems/next-greater-element-ii/) */ @UseCommentAsDocumentation private fun nextGreaterElement(nums: IntArray): IntArray { val result = IntArray(nums.size) { -1 } val unknownIndices: LinkedList<Int> = LinkedList<Int>() // holds indices that didn't have NGN val lastElem = nums.last() // this can be used to find its NGN in forward iteration var isLastElementNGNFound = false for (i in 1..nums.lastIndex) { val current = nums[i] val prev = nums[i - 1] // Find the [lastElem]'s NGN while iterating forward (since array is circular) if (!isLastElementNGNFound && prev > lastElem) { // if not already found result[result.lastIndex] = prev isLastElementNGNFound = true } // Check for every unknown index's NGN when traversing forward till lastIndex val iterator = unknownIndices.iterator() while (iterator.hasNext()) { val next = iterator.next() if (nums[next] < current) { // NGN found result[next] = current iterator.remove() } } if (prev < current) { // Found NGN (next greater number) result[i - 1] = current } else { // If not found, store the index of -1 into [unknownIndices] unknownIndices.addLast(i - 1) // add it to [unknownIndices] } } // Since NGN was not found when traversing forward, now start from 0 to unknown index to find NGN // since the array is circular while (unknownIndices.size > 1 // since there can be only one value with NGN=-1 (the highest value) || (unknownIndices.isNotEmpty() && unknownIndices.distinct().size != 1) // what if there are multiple equal highest value ) { val unknownIndex = unknownIndices.removeLast() ?: break // get the index for (i in 0..unknownIndex) { // from 0 to the above index if (nums[i] > nums[unknownIndex]) { // try to find NGN result[unknownIndex] = nums[i] break } } } return result } fun main() { nextGreaterElement(nums = intArrayOf(1, 2, 3, 2, 1)) shouldBe intArrayOf(2, 3, -1, 3, 2) nextGreaterElement(nums = intArrayOf(5, 4, 3, 2, 1)) shouldBe intArrayOf(-1, 5, 5, 5, 5) nextGreaterElement( nums = intArrayOf(1, 8, -1, -100, -1, 222, 1111111, -111111) ) shouldBe intArrayOf(8, 222, 222, -1, 222, 1111111, -1, 1) nextGreaterElement(nums = intArrayOf(100, 1, 11, 1, 120, 111, 123, 1, -1, -100)) nextGreaterElement( nums = intArrayOf(1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 100) ) shouldBe intArrayOf(2, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, -1) nextGreaterElement(nums = intArrayOf(1, 5, 3, 6, 8)) shouldBe intArrayOf(5, 6, 6, 8, -1) nextGreaterElement(nums = intArrayOf(1, 2, 1)) shouldBe intArrayOf(2, -1, 2) nextGreaterElement(nums = intArrayOf(1, 2, 3, 4, 3)) shouldBe intArrayOf(2, 3, 4, -1, 4) }
4
Kotlin
5
93
22eef528ef1bea9b9831178b64ff2f5b1f61a51f
3,582
algorithms
MIT License
src/commonMain/kotlin/advent2020/day25/Day25Puzzle.kt
jakubgwozdz
312,526,719
false
null
package advent2020.day25 fun part1(input: String): String { val lines = input.trim().lines() val cardPK = lines[0].toLong() val doorPK = lines[1].toLong() val enc = calcEnc(cardPK, doorPK) return enc.toString() } fun calcEnc(cardPK: Long, doorPK: Long): Long { val m = 20201227L var acc = 1L var loopSize = 0L while (true) { loopSize++ acc = (acc * 7) % m if (acc == cardPK) return modPow(doorPK, loopSize, m) if (acc == doorPK) return modPow(cardPK, loopSize, m) } } // using property (A * B) % C = (A % C * B % C) % C fun modPow(base: Long, exp: Long, m: Long): Long = exp.toString(2).map { if (it == '1') 1 else 0 } .reversed() .fold(ModPowState(1L, base % m)) { acc, base2digit -> val (prev, pow2mod) = acc val next = if (base2digit == 1) prev * pow2mod % m else prev ModPowState(next, (pow2mod * pow2mod % m)) } .result data class ModPowState(val result: Long, var pow2mod: Long)
0
Kotlin
0
2
e233824109515fc4a667ad03e32de630d936838e
1,034
advent-of-code-2020
MIT License
src/main/kotlin/g0601_0700/s0675_cut_off_trees_for_golf_event/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0601_0700.s0675_cut_off_trees_for_golf_event // #Hard #Array #Breadth_First_Search #Matrix #Heap_Priority_Queue // #2023_02_15_Time_777_ms_(100.00%)_Space_43.4_MB_(100.00%) import java.util.LinkedList import java.util.Objects import java.util.PriorityQueue import java.util.Queue class Solution { private var r = 0 private var c = 0 fun cutOffTree(forest: List<List<Int>>): Int { val pq = PriorityQueue<Int>() for (integers in forest) { for (v in integers) { if (v > 1) { pq.add(v) } } } var steps = 0 while (pq.isNotEmpty()) { val count = minSteps(forest, pq.poll()) if (count == -1) { return -1 } steps += count } return steps } private fun minSteps(forest: List<List<Int>>, target: Int): Int { var steps = 0 val dirs = arrayOf(intArrayOf(0, 1), intArrayOf(0, -1), intArrayOf(1, 0), intArrayOf(-1, 0)) val visited = Array(forest.size) { BooleanArray( forest[0].size ) } val q: Queue<IntArray> = LinkedList() q.add(intArrayOf(r, c)) visited[r][c] = true while (q.isNotEmpty()) { val qSize = q.size for (i in 0 until qSize) { val curr = q.poll() if (forest[Objects.requireNonNull(curr)[0]][curr[1]] == target) { r = curr[0] c = curr[1] return steps } for (k in 0..3) { val dir = dirs[k] val nr = dir[0] + curr[0] val nc = dir[1] + curr[1] if (nr < 0 || nr == visited.size || nc < 0 || nc == visited[0].size || visited[nr][nc] || forest[nr][nc] == 0 ) { continue } q.add(intArrayOf(nr, nc)) visited[nr][nc] = true } } steps++ } return -1 } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
2,190
LeetCode-in-Kotlin
MIT License
src/Day04.kt
ShuffleZZZ
572,630,279
false
{"Kotlin": 29686}
private fun rangesPairList(input: List<String>) = input.map { "(\\d+)-(\\d+),(\\d+)-(\\d+)".toRegex().find(it)!!.destructured } .map { (l1, l2, r1, r2) -> (l1.toInt() to l2.toInt()) to (r1.toInt() to r2.toInt()) } fun main() { fun part1(input: List<String>) = rangesPairList(input).sumOf { (first, second) -> first.include(second).toInt() } fun part2(input: List<String>) = rangesPairList(input).sumOf { (first, second) -> first.intersect(second).toInt() } // test if implementation meets criteria from the description, like: 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
5a3cff1b7cfb1497a65bdfb41a2fe384ae4cf82e
745
advent-of-code-kotlin
Apache License 2.0
src/Day02.kt
mythicaleinhorn
572,689,424
false
{"Kotlin": 11494}
import GameObject.* enum class GameObject(val points: Int) { ROCK(1), PAPER(2), SCISSORS(3) } enum class Move(val gameObject: GameObject) { A(ROCK), X(ROCK), B(PAPER), Y(PAPER), C(SCISSORS), Z( SCISSORS ) } enum class Outcome(val points: Int) { LOSE(0), DRAW(3), WIN(6) } enum class Outcome2(val outcome: Outcome) { X(Outcome.LOSE), Y(Outcome.DRAW), Z(Outcome.WIN) } data class Round(val opponent: GameObject, val me: GameObject) data class Round2(val opponent: GameObject, val outcome: Outcome) fun main() { fun part1(input: List<String>): Int { val rounds = mutableListOf<Round>() for (round in input) { rounds.add( Round( Move.valueOf(round.substringBefore(" ")).gameObject, Move.valueOf(round.substringAfter(" ")).gameObject ) ) } var score = 0 for ((opponent, me) in rounds) { score += me.points score += when (me) { ROCK -> when (opponent) { PAPER -> Outcome.LOSE.points SCISSORS -> Outcome.WIN.points ROCK -> Outcome.DRAW.points } PAPER -> when (opponent) { ROCK -> Outcome.WIN.points SCISSORS -> Outcome.LOSE.points PAPER -> Outcome.DRAW.points } SCISSORS -> when (opponent) { ROCK -> Outcome.LOSE.points PAPER -> Outcome.WIN.points SCISSORS -> Outcome.DRAW.points } } } return score } fun part2(input: List<String>): Int { val rounds = mutableListOf<Round2>() for (round in input) { rounds.add( Round2( Move.valueOf(round.substringBefore(" ")).gameObject, Outcome2.valueOf(round.substringAfter(" ")).outcome ) ) } var score = 0 for ((opponent, outcome) in rounds) { score += outcome.points score += when (outcome) { Outcome.LOSE -> when (opponent) { ROCK -> SCISSORS.points PAPER -> ROCK.points SCISSORS -> PAPER.points } Outcome.DRAW -> opponent.points Outcome.WIN -> when (opponent) { ROCK -> PAPER.points PAPER -> SCISSORS.points SCISSORS -> ROCK.points } } } return score } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
959dc9f82c14f59d8e3f182043c59aa35e059381
2,965
advent-of-code-2022
Apache License 2.0
src/Day09.kt
TheGreatJakester
573,222,328
false
{"Kotlin": 47612}
package day09 import utils.string.asLines import utils.numbers.justOne import utils.readInputAsText import utils.runSolver import java.lang.IllegalArgumentException import kotlin.math.absoluteValue private typealias SolutionType = Int private const val defaultSolution = 0 private const val dayNumber: String = "09" private val testSolution1: SolutionType? = 88 private val testSolution2: SolutionType? = 36 private class Knot(var tail: Knot? = null) { var x: Int = 0 var y: Int = 0 val last: Knot get() = tail?.last ?: this val asPair get() = x to y fun moveUp() { y += 1 updateTail() } fun moveDown() { y -= 1 updateTail() } fun moveLeft() { x -= 1 updateTail() } fun moveRight() { x += 1 updateTail() } private fun updateTail() { val t = tail ?: return val xDelta = (x - t.x) val yDelta = (y - t.y) if (xDelta.absoluteValue < 2 && yDelta.absoluteValue < 2) { return } t.x += xDelta.justOne() t.y += yDelta.justOne() t.updateTail() } companion object { fun builtRopeOfLength(length: Int): Knot { if(length < 1) throw IllegalArgumentException("Length must be 1 or more") var curKnot: Knot = Knot() repeat(length - 1) { val nextKnot = Knot(curKnot) curKnot = nextKnot } return curKnot } } } private fun readMoves(input: String, head: Knot, afterMove: () -> Unit) { input.asLines().forEach { line -> val (move, count) = line.split(" ") repeat(count.toInt()) { when (move) { "U" -> head.moveUp() "D" -> head.moveDown() "L" -> head.moveLeft() "R" -> head.moveRight() else -> println("Unknown move $move") } afterMove() } } } private fun doPartWithLength(input: String, length: Int): Int{ val tailPositions = mutableSetOf<Pair<Int, Int>>() val rope = Knot.builtRopeOfLength(length) val tail = rope.last readMoves(input, rope) { tailPositions.add(tail.asPair) } return tailPositions.size } private fun part1(input: String): SolutionType = doPartWithLength(input, 2) private fun part2(input: String): SolutionType = doPartWithLength(input, 10) fun main() { runSolver("Test 1", readInputAsText("Day${dayNumber}_test"), testSolution1, ::part1) runSolver("Test 2", readInputAsText("Day${dayNumber}_test"), testSolution2, ::part2) runSolver("Part 1", readInputAsText("Day${dayNumber}"), null, ::part1) runSolver("Part 2", readInputAsText("Day${dayNumber}"), null, ::part2) }
0
Kotlin
0
0
c76c213006eb8dfb44b26822a44324b66600f933
2,803
2022-AOC-Kotlin
Apache License 2.0
src/main/kotlin/se/brainleech/adventofcode/aoc2020/Aoc2020Day04.kt
fwangel
435,571,075
false
{"Kotlin": 150622}
package se.brainleech.adventofcode.aoc2020 import se.brainleech.adventofcode.compute import se.brainleech.adventofcode.readText import se.brainleech.adventofcode.verify class Aoc2020Day04 { companion object { private const val LINE_FEED = "\n" private const val PAIR_SEPARATOR = " " private const val KEY_VALUE_SEPARATOR = ":" } enum class Field { BYR, IYR, EYR, HGT, HCL, ECL, PID, CID } enum class EyeColor { AMB, BLU, BRN, GRY, GRN, HZL, OTH; companion object { fun accepts(value: String): Boolean { return values().map { it.name }.contains(value) } } } data class Passport(private val data: Map<Field, String>) { private fun acceptedByHeight(height: String): Boolean { return when (height.takeLast(2)) { "cm" -> height.dropLast(2).toInt() in 150..193 "in" -> height.dropLast(2).toInt() in 59..76 else -> false } } fun acceptedByFieldKeys(): Boolean { // verify all fields are present, ignoring "Country ID" return data.filter { it.key != Field.CID }.size == Field.values().size - 1 } fun acceptedByFieldValues(): Boolean { // verify all fields, ignoring "Country ID" var accepted = true accepted = accepted && (data.getValue(Field.BYR).toInt() in 1920..2002) accepted = accepted && (data.getValue(Field.IYR).toInt() in 2010..2020) accepted = accepted && (data.getValue(Field.EYR).toInt() in 2020..2030) accepted = accepted && (acceptedByHeight(data.getValue(Field.HGT))) accepted = accepted && (data.getValue(Field.HCL).matches(Regex("#[a-f0-9]{6}"))) accepted = accepted && (EyeColor.accepts(data.getValue(Field.ECL).uppercase())) accepted = accepted && (data.getValue(Field.PID).matches(Regex("[0-9]{9}"))) return accepted } } private fun String.asPassport(): Passport { val data = mutableMapOf<Field, String>() this.replace(LINE_FEED, PAIR_SEPARATOR).split(PAIR_SEPARATOR).forEach { pair -> val (key, value) = pair.split(KEY_VALUE_SEPARATOR) data[Field.valueOf(key.uppercase())] = value } return Passport(data.toMap()) } fun part1(input: String): Long { return input .split("\n\n") .asSequence() .filter { it.isNotBlank() } .map { it.asPassport() } .filter { it.acceptedByFieldKeys() } .count() .toLong() } fun part2(input: String): Long { return input .split("\n\n") .asSequence() .filter { it.isNotBlank() } .map { it.asPassport() } .filter { it.acceptedByFieldKeys() } .filter { it.acceptedByFieldValues() } .count() .toLong() } } fun main() { val solver = Aoc2020Day04() val prefix = "aoc2020/aoc2020day04" val testData = readText("$prefix.test.txt") val realData = readText("$prefix.real.txt") verify(10L, solver.part1(testData)) compute({ solver.part1(realData) }, "$prefix.part1 = ") verify(6L, solver.part2(testData)) compute({ solver.part2(realData) }, "$prefix.part2 = ") }
0
Kotlin
0
0
0bba96129354c124aa15e9041f7b5ad68adc662b
3,512
adventofcode
MIT License
Day_03/Solution_Part2.kts
0800LTT
317,590,451
false
null
import java.io.File data class Grid(val width: Int, val height: Int, val cells: Array<Array<Boolean>>) { fun isTree(row: Int, column: Int) = cells[row][column] fun countTrees(verticalStep: Int, horizontalStep: Int) : Int { var currentRow = 0 var currentColumn = 0 var trees = 0 while (currentRow < height - 1) { currentRow += verticalStep currentColumn = (currentColumn + horizontalStep) % width // this ensures we wrap around if (isTree(currentRow, currentColumn)) { trees++ } } return trees } } fun File.toGridOrNull(): Grid? { val cells = readLines().map { line -> line.map { it == '#' }.toTypedArray() }.toTypedArray() if (cells.size > 0 && cells[0].size > 0) { val height = cells.size val width = cells[0].size return Grid(width, height, cells) } return null } fun main() { val grid = File("input.txt").toGridOrNull() if (grid != null) { val steps = listOf( Pair(1, 1), Pair(1, 3), Pair(1, 5), Pair(1, 7), Pair(2, 1), ) val treeCounts = steps.map { (verticalStep, horizontalStep) -> grid.countTrees(verticalStep, horizontalStep) } val totalTrees = treeCounts.map { it.toBigInteger() }.reduce() { acc, n -> acc * n} println(totalTrees) } } main()
0
Kotlin
0
0
191c8c307676fb0e7352f7a5444689fc79cc5b54
1,272
advent-of-code-2020
The Unlicense
kotlin/src/x2023/Day01.kt
freeformz
573,924,591
false
{"Kotlin": 43093, "Go": 7781}
package x2023 open class Day01AExample { open val inputLines: List<String> = read2023Input("day01a-example") open val expected = 142 open var answer: Int = 0 fun run() { println(this.javaClass.name) answer = inputLines.sumOf { line -> val digits = line.filter { c -> c.isDigit() } "${digits.first()}${digits.last()}".toInt() } println(answer) } fun check() { assert(answer == expected) println() } } class Day01A : Day01AExample() { override val inputLines: List<String> = read2023Input("day01a") override val expected = 54916 } data class MInt(val s: String, val v: Int) open class Day01BExample { open val inputLines: List<String> = read2023Input("day01b-example") open val expected = 281 open var answer: Int = 0 private val findValues = listOf( MInt("one", 1), MInt("two", 2), MInt("three", 3), MInt("four", 4), MInt("five", 5), MInt("six", 6), MInt("seven", 7), MInt("eight", 8), MInt("nine", 9), MInt("1", 1), MInt("2", 2), MInt("3", 3), MInt("4", 4), MInt("5", 5), MInt("6", 6), MInt("7", 7), MInt("8", 8), MInt("9", 9) ) fun run() { println(this.javaClass.name) answer = inputLines.sumOf { line -> val first = findValues.mapNotNull { when (val idx = line.indexOf(it.s)) { -1 -> null else -> Pair(idx, it) } }.minBy { it.first } val last = findValues.mapNotNull { when (val idx = line.lastIndexOf(it.s)) { -1 -> null else -> Pair(idx, it) } }.maxBy { it.first } "${first.second.v}${last.second.v}".toInt() } println(answer) } fun check() { assert(answer == expected) println() } } class Day01B : Day01BExample() { override val inputLines: List<String> = read2023Input("day01b") override val expected = 54728 } fun main() { val day1aExample = Day01AExample() day1aExample.run() day1aExample.check() val day1a = Day01A() day1a.run() day1a.check() val day1bExample = Day01BExample() day1bExample.run() day1bExample.check() val day1b = Day01B() day1b.run() day1b.check() }
0
Kotlin
0
0
5110fe86387d9323eeb40abd6798ae98e65ab240
2,514
adventOfCode
Apache License 2.0
src/test/kotlin/ch/ranil/aoc/aoc2023/Day04.kt
stravag
572,872,641
false
{"Kotlin": 234222}
package ch.ranil.aoc.aoc2023 import ch.ranil.aoc.AbstractDay import org.junit.jupiter.api.Test import kotlin.math.pow import kotlin.test.assertEquals class Day04 : AbstractDay() { @Test fun part1() { assertEquals(13, compute1(testInput)) assertEquals(26218, compute1(puzzleInput)) } @Test fun part2() { assertEquals(30, compute2(testInput)) assertEquals(9997537, compute2(puzzleInput)) } private fun compute1(input: List<String>): Int { return parseScratchCards(input).sumOf { it.points } } private fun compute2(input: List<String>): Int { val cards = parseScratchCards(input) val totalWonCardsCount = cards.sumOf { card: Card -> processCard(card, cards) } return cards.size + totalWonCardsCount } private fun processCard(card: Card, cards: List<Card>): Int { val cardsWon = cards .subList(card.num, card.num + card.matchingCount) val cardsWonOfCardsCount = cardsWon.sumOf { processCard(it, cards) } return cardsWon.size + cardsWonOfCardsCount } private fun parseScratchCards(input: List<String>) = input.map { line -> val (gamePart, numbersPart) = line.split(":") val (winningPart, availablePart) = numbersPart.split("|") Card( num = gamePart .split(" ") .filter { it.isNotBlank() }[1] .toInt(), winning = winningPart .split(" ") .filter { it.isNotBlank() } .map { it.toInt() } .toSet(), avail = availablePart .split(" ") .filter { it.isNotBlank() } .map { it.toInt() } .toSet(), ) } data class Card( val num: Int, val winning: Set<Int>, val avail: Set<Int>, ) { private val matchingNumbers = winning.filter { avail.contains(it) } val points: Int get() = if (matchingNumbers.isEmpty()) { 0 } else { 2.0.pow(matchingNumbers.size.toDouble() - 1).toInt() } val matchingCount: Int = matchingNumbers.size } }
0
Kotlin
1
0
dbd25877071cbb015f8da161afb30cf1968249a8
2,326
aoc
Apache License 2.0
src/Day16.kt
LauwiMeara
572,498,129
false
{"Kotlin": 109923}
const val startValve = "AA" const val startMinutesPart1 = 30 const val startMinutesPart2 = 26 data class ValveInfo (val flowRate: Int, val tunnelsTo: List<String>) data class ValvePath (val pressure: Int, val minutes: Int, val openedValves: List<String>, val path1: List<String>, val path2: List<String> = listOf("")) fun main() { fun getValves(input: List<List<String>>): Map<String, ValveInfo> { val valves = mutableMapOf<String, ValveInfo>() for (line in input) { val id = line[0] val flowRate = line[1].toInt() val tunnelsTo = mutableListOf<String>() for (i in 2 until line.size) { tunnelsTo.add(line[i]) } valves[id] = ValveInfo(flowRate, tunnelsTo) } return valves } fun getConnectedPaths(valves: Map<String, ValveInfo>, totalPath: ValvePath, individualPath: List<String>): MutableList<ValvePath> { val connectedPaths = mutableListOf<ValvePath>() val minutes = totalPath.minutes - 1 val currentValve = individualPath.last() if (valves[currentValve]!!.flowRate > 0 && !totalPath.openedValves.contains(currentValve)) { // If currentValve does release pressure and hasn't been opened yet, open it. connectedPaths.add( ValvePath( valves[currentValve]!!.flowRate * minutes, minutes, listOf(currentValve), individualPath + currentValve ) ) } val connectedValves = valves[currentValve]!!.tunnelsTo for (connectedValve in connectedValves) { // Travel to connectedValve without opening it. connectedPaths.add( ValvePath( 0, minutes, listOf(""), individualPath + connectedValve ) ) } return connectedPaths } fun getConnectedPathsPart1(valves: Map<String, ValveInfo>, path: ValvePath): List<ValvePath> { return getConnectedPaths(valves, path, path.path1) .map{ ValvePath( path.pressure + it.pressure, it.minutes, (path.openedValves + it.openedValves).filter{ valve -> valve.isNotEmpty()}, it.path1 ) } } fun getConnectedPathsPart2(valves: Map<String, ValveInfo>, path: ValvePath): List<ValvePath> { val connectedPaths = mutableListOf<ValvePath>() val connectedPaths1 = getConnectedPaths(valves, path, path.path1) val connectedPaths2 = getConnectedPaths(valves, path, path.path2) for (cp1 in connectedPaths1) { for (cp2 in connectedPaths2) { // If both paths open the same valve, continue. if (!cp1.openedValves.contains("") && cp1.openedValves == cp2.openedValves) continue // Else, combine both paths. connectedPaths.add( ValvePath( path.pressure + cp1.pressure + cp2.pressure, cp1.minutes, (path.openedValves + cp1.openedValves + cp2.openedValves).distinct().filter{it.isNotEmpty()}, cp1.path1, cp2.path1 ) ) } } return connectedPaths } fun part1(input: List<List<String>>): Int { val valves = getValves(input) var maxPressure = 0 var paths = mutableListOf(ValvePath(0, startMinutesPart1, listOf(""), listOf(startValve))) while (paths.isNotEmpty()) { // Greedy search. if (paths.size > 5000) { paths.sortByDescending{it.pressure} paths = paths.subList(0,500) } val path = paths.removeFirst() if (path.minutes <= 1) { // If there is 1 minute or less left, no extra pressure can be released. if (path.pressure > maxPressure) { maxPressure = path.pressure } } else { paths.addAll(getConnectedPathsPart1(valves, path)) } } return maxPressure } fun part2(input: List<List<String>>): Int { val valves = getValves(input) var maxPressure = 0 var paths = mutableListOf(ValvePath(0, startMinutesPart2, listOf(""), listOf(startValve), listOf(startValve))) while (paths.isNotEmpty()) { // Greedy search. if (paths.size > 10000) { paths.sortByDescending{it.pressure} paths = paths.subList(0,2000) } val path = paths.removeFirst() if (path.minutes <= 1) { // If there is 1 minute or less left, no extra pressure can be released. if (path.pressure > maxPressure) { maxPressure = path.pressure } } else { paths.addAll(getConnectedPathsPart2(valves, path)) } } return maxPressure } val input = readInputAsStrings("Day16") .map{line -> line.split( "Valve ", " has flow rate=", "; tunnels lead to valve ", "; tunnels lead to valves ", "; tunnel leads to valve ", "; tunnel leads to valves ", ", ") .filter{it.isNotEmpty()}} println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
34b4d4fa7e562551cb892c272fe7ad406a28fb69
5,663
AoC2022
Apache License 2.0
src/main/aoc2022/Day11.kt
Clausr
575,584,811
false
{"Kotlin": 65961}
package aoc2022 class Day11(input: List<String>) { private val monkeys = input.parseMonkeys() fun solvePart1(): Long { rounds(numRounds = 20) { it / 3 } return monkeys.business() } fun solvePart2(): Long { val testProduct = monkeys.map { it.test }.reduce(Long::times) rounds(numRounds = 10_000) { it % testProduct } return monkeys.business() } private fun List<Monkey>.business(): Long = sortedByDescending { it.interactions }.let { it[0].interactions * it[1].interactions } private fun rounds(numRounds: Int, changeToWorryLevel: (Long) -> Long) { repeat(numRounds) { monkeys.forEach { it.inspectItems(monkeys, changeToWorryLevel) } } } private fun List<String>.parseMonkeys(): List<Monkey> { return chunked(7).map { attribute -> val operationValue = attribute[2].substringAfterLast(" ") val operation: (Long) -> Long = when { operationValue == "old" -> ({ it * it }) '*' in attribute[2] -> ({ it * operationValue.toLong() }) else -> ({ it + operationValue.toLong() }) } Monkey( items = attribute[1].substringAfter(": ").split(", ").map { it.toLong() }.toMutableList(), test = attribute[3].substringAfterLast(" ").toLong(), operation = operation, testTrue = attribute[4].split(" ").last().toInt(), testFalse = attribute[5].split(" ").last().toInt() ) } } } data class Monkey( val items: MutableList<Long>, //Worry level val operation: (Long) -> Long, val test: Long, val testTrue: Int, val testFalse: Int ) { var interactions: Long = 0 fun inspectItems(monkeys: List<Monkey>, changeToWorryLevel: (Long) -> Long) { items.forEach { item -> val worry = changeToWorryLevel(operation(item)) val target = if (worry % test == 0L) testTrue else testFalse monkeys[target].items.add(worry) } interactions += items.size items.clear() } }
1
Kotlin
0
0
dd33c886c4a9b93a00b5724f7ce126901c5fb3ea
2,156
advent_of_code
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/KeysAndRooms.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import java.util.Stack /** * 841. Keys and Rooms * @see <a href="https://leetcode.com/problems/keys-and-rooms">Source</a> */ fun interface KeysAndRooms { fun canVisitAllRooms(rooms: List<List<Int>>): Boolean } class KeysAndRoomsStraightForward : KeysAndRooms { override fun canVisitAllRooms(rooms: List<List<Int>>): Boolean { val dfs: Stack<Int> = Stack<Int>().apply { add(0) } val seen: HashSet<Int> = HashSet<Int>().apply { add(0) } while (dfs.isNotEmpty()) { val i: Int = dfs.pop() for (j in rooms[i]) { if (!seen.contains(j)) { dfs.add(j) seen.add(j) if (rooms.size == seen.size) return true } } } return rooms.size == seen.size } } class KeysAndRoomsDFS : KeysAndRooms { override fun canVisitAllRooms(rooms: List<List<Int>>): Boolean { val visited = BooleanArray(rooms.size) dfs(0, rooms, visited) for (visit in visited) if (!visit) return false return true } private fun dfs(u: Int, rooms: List<List<Int>>, visited: BooleanArray) { visited[u] = true for (v in rooms[u]) if (!visited[v]) dfs(v, rooms, visited) } } class KeysAndRoomsRecursive : KeysAndRooms { override fun canVisitAllRooms(rooms: List<List<Int>>): Boolean { return helper(rooms, 0, HashSet()) } private fun helper(rooms: List<List<Int>>, key: Int, seen: MutableSet<Int>): Boolean { seen.add(key) val keys = rooms[key] for (k in keys) { if (!seen.contains(k)) helper(rooms, k, seen) } return seen.size == rooms.size } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,402
kotlab
Apache License 2.0
src/main/kotlin/kr/co/programmers/P150369.kt
antop-dev
229,558,170
false
{"Kotlin": 695315, "Java": 213000}
package kr.co.programmers import java.util.* // https://github.com/antop-dev/algorithm/issues/491 class P150369 { fun solution(cap: Int, n: Int, deliveries: IntArray, pickups: IntArray): Long { val d = Stack<Int>() val p = Stack<Int>() var move = 0L // 총 이동거리 for (i in 0 until n) { if (deliveries[i] > 0) d.push(i) if (pickups[i] > 0) p.push(i) } while (d.isNotEmpty() || p.isNotEmpty()) { // 배달과 수거중 가장 먼 위치 찾기 val i = maxOf(peek(d), peek(p)) // 왕복 거리 계산 move += (i + 1) * 2 // 배달과 수거 계산하기 calculate(d, deliveries, cap) calculate(p, pickups, cap) } return move } private fun calculate(stack: Stack<Int>, arr: IntArray, cap: Int) { var sum = 0 while (stack.isNotEmpty() && sum < cap) { val i = stack.pop() val v = arr[i] // 배달(수거)할 양이 최대치(cap)보다 클 경우 최대한 차에 실는다. // 수거해야할 양이 6이고 차에 여유공간이 3일경우 3이라도 실어서 간다. // 다음에 같은 위치에 와서 남은 3을 수거해간다. if (sum + v > cap) { arr[i] = sum + v - cap stack.push(i) } sum += v } } // 스택이 비어 있으면 -1 처리 private fun peek(stack: Stack<Int>) = if (stack.isNotEmpty()) stack.peek() else -1 }
1
Kotlin
0
0
9a3e762af93b078a2abd0d97543123a06e327164
1,593
algorithm
MIT License
src/main/kotlin/days/Day7.kt
hughjdavey
317,575,435
false
null
package days class Day7 : Day(7) { private val bags = Bag.createBags(inputList) private val bagColour = "shiny gold" // 289 override fun partOne(): Any { return bags.count { Bag.canContain(it, bagColour) } } // 30055 override fun partTwo(): Any { return Bag.mustContain(Bag.fromColour(bagColour)) } data class Bag(val colour: String, val children: List<String> = mutableListOf()) { companion object { private lateinit var bags: List<Bag> fun canContain(bag: Bag, colour: String): Boolean { return if (bag.children.isEmpty()) false else { bag.children.contains(colour) || fromColours(bag.children).any { canContain(it, colour) } } } fun mustContain(bag: Bag, count: Int = 0): Int { return if (bag.children.isEmpty()) count else { bag.children.count() + bag.children.map { mustContain(fromColour(it), count) }.sum() } } fun createBags(strings: List<String>): List<Bag> { bags = fromStrings(strings) return bags } fun fromColour(colour: String): Bag { return bags.find { b -> b.colour == colour }!! } private fun fromColours(colours: List<String>): List<Bag> { return bags.filter { colours.contains(it.colour) } } private fun fromStrings(strings: List<String>): List<Bag> { return strings.map { it.replace(Regex("bags?|[.]"), "").split("contain").map { it.trim() } } .fold(listOf()) { bags, str -> val (colour, children) = str[0] to str[1].split(" , ").mapNotNull { if (it == "no other") null else { val split = Regex("(\\d+)\\s(.*)").matchEntire(it)!!.groupValues.drop(1) split.last() to split.first().toInt() } }.map { (col, count) -> List(count) { col } }.flatten() bags.plus(Bag(colour, children)) } } } } }
0
Kotlin
0
1
63c677854083fcce2d7cb30ed012d6acf38f3169
2,202
aoc-2020
Creative Commons Zero v1.0 Universal
kotlin/src/com/s13g/aoc/aoc2020/Day12.kt
shaeberling
50,704,971
false
{"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245}
package com.s13g.aoc.aoc2020 import com.s13g.aoc.* /** * --- Day 12: Rain Risk --- * https://adventofcode.com/2020/day/12 */ class Day12 : Solver { private val dirVec = hashMapOf('N' to XY(0, 1), 'S' to XY(0, -1), 'W' to XY(-1, 0), 'E' to XY(1, 0)) private var dirs = listOf('N', 'E', 'S', 'W') override fun solve(lines: List<String>): Result { val input = lines.map { Pair(it[0], it.substring(1).toInt()) } return Result("${partA(input).manhattan()}", "${partB(input).manhattan()}") } private fun partA(input: List<Pair<Char, Int>>): XY { val pos = XY(0, 0) var facing = 'E' for (foo in input) { when (foo.first) { in dirVec -> for (n in 0 until foo.second) pos.addTo(dirVec[foo.first]!!) 'F' -> for (n in 0 until foo.second) pos.addTo(dirVec[facing]!!) 'L' -> facing = dirs[(dirs.indexOf(facing) - (foo.second / 90) + 360) % dirs.size] 'R' -> facing = dirs[(dirs.indexOf(facing) + (foo.second / 90)) % dirs.size] } } return pos } private fun partB(input: List<Pair<Char, Int>>): XY { val pos = XY(0, 0) var waypoint = XY(10, 1) for (foo in input) { when (foo.first) { in dirVec -> for (n in 0 until foo.second) waypoint.addTo(dirVec[foo.first]!!) 'F' -> for (n in 0 until foo.second) pos.addTo(waypoint) 'L' -> waypoint = waypoint.rotate90(foo.second / 90, true) 'R' -> waypoint = waypoint.rotate90(foo.second / 90, false) } } return pos } }
0
Kotlin
1
2
7e5806f288e87d26cd22eca44e5c695faf62a0d7
1,503
euler
Apache License 2.0
kotlin/SuffixArray.kt
indy256
1,493,359
false
{"Java": 545116, "C++": 266009, "Python": 59511, "Kotlin": 28391, "Rust": 4682, "CMake": 571}
fun suffixArray(S: CharSequence): IntArray { val n = S.length // Stable sort of characters. // Same characters are sorted by their position in descending order. // E.g. last character which represents suffix of length 1 should be ordered first among same characters. val sa = S.indices.reversed().sortedBy { S[it] }.toIntArray() val classes = S.chars().toArray() // sa[i] - suffix on i'th position after sorting by first len characters // classes[i] - equivalence class of the i'th suffix after sorting by first len characters var len = 1 while (len < n) { // Calculate classes for suffixes of length len * 2 val c = classes.copyOf() for (i in 0 until n) { // Condition sa[i - 1] + len < n emulates 0-symbol at the end of the string. // A separate class is created for each suffix followed by emulated 0-symbol. classes[sa[i]] = if (i > 0 && c[sa[i - 1]] == c[sa[i]] && sa[i - 1] + len < n && c[sa[i - 1] + len / 2] == c[sa[i] + len / 2]) classes[sa[i - 1]] else i } // Suffixes are already sorted by first len characters // Now sort suffixes by first len * 2 characters val cnt = IntArray(n) { it } val s = sa.copyOf() for (i in 0 until n) { // s[i] - order of suffixes sorted by first len characters // (s[i] - len) - order of suffixes sorted only by second len characters val s1 = s[i] - len // sort only suffixes of length > len, others are already sorted if (s1 >= 0) sa[cnt[classes[s1]]++] = s1 } len *= 2 } return sa } // Usage example fun main() { val s = "abcab" val sa = suffixArray(s) // print suffixes in lexicographic order // print suffixes in lexicographic order for (p in sa) println(s.substring(p)) }
97
Java
561
1,806
405552617ba1cd4a74010da38470d44f1c2e4ae3
1,957
codelibrary
The Unlicense
src/main/kotlin/com/hj/leetcode/kotlin/problem2131/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem2131 /** * LeetCode page: [2131. Longest Palindrome by Concatenating Two Letter Words](https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/); */ class Solution { /* Complexity: * Time O(N) and Space O(1) where N is the size of words. Space complexity is O(1) because there are * at most 26^2 different words; */ fun longestPalindrome(words: Array<String>): Int { val countPerWord = countEachWord(words) return findMaxLength(countPerWord) } private fun countEachWord(words: Array<String>): MutableMap<String, Int> { val counts = hashMapOf<String, Int>() for (word in words) { counts[word] = counts.getOrDefault(word, 0) + 1 } return counts } private fun findMaxLength(countPerWord: MutableMap<String, Int>): Int { var halfMaxLength = 0 var hasOddCountTwin = false val countsIterator = countPerWord.iterator() fun updateWhenWordIsTwin(count: Int) { if (count.isEven()) { halfMaxLength += count } else { halfMaxLength += count - 1 hasOddCountTwin = true } countsIterator.remove() } fun updateWhenWordIsNotTwin(word: String, count: Int) { val reversed = word.reversed() val countOfReversed = countPerWord[reversed] if (countOfReversed != null) { halfMaxLength += minOf(count, countOfReversed) * 2 } countsIterator.remove() } while (countsIterator.hasNext()) { val (word, count) = countsIterator.next() val isTwin = isTwin(word) if (isTwin) updateWhenWordIsTwin(count) else updateWhenWordIsNotTwin(word, count) } if (hasOddCountTwin) halfMaxLength += 1 return halfMaxLength * 2 } private fun Int.isEven() = this and 1 == 0 private fun isTwin(word: String) = word.length == 2 && word[0] == word[1] }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
2,082
hj-leetcode-kotlin
Apache License 2.0
src/Day02.kt
iartemiev
573,038,071
false
{"Kotlin": 21075}
import java.lang.IllegalArgumentException // Super verbose solution - wanted to play with enums with anonymous classes enum class PlayerMove(val move: RockPaperScissors) { X(RockPaperScissors.ROCK), Y(RockPaperScissors.PAPER), Z(RockPaperScissors.SCISSORS) } enum class OpponentMove(val move: RockPaperScissors) { A(RockPaperScissors.ROCK), B(RockPaperScissors.PAPER), C(RockPaperScissors.SCISSORS) } enum class RoundOutcome(val outcomePoints: Int) { X(0), Y(3), Z(6) } enum class RockPaperScissors(val movePoints: Int) { ROCK(1) { override fun play(playerMove: RockPaperScissors): Int = when (playerMove) { ROCK -> ROCK.movePoints + 3 PAPER -> PAPER.movePoints + 6 SCISSORS -> SCISSORS.movePoints + 0 else -> throw IllegalArgumentException("Invalid move: $playerMove") } override fun strategy(outcome: RoundOutcome): Int = when (outcome) { RoundOutcome.X -> outcome.outcomePoints + SCISSORS.movePoints RoundOutcome.Y -> outcome.outcomePoints + ROCK.movePoints RoundOutcome.Z -> outcome.outcomePoints + PAPER.movePoints else -> throw IllegalArgumentException("Invalid outcome: $outcome") } }, PAPER(2) { override fun play(playerMove: RockPaperScissors): Int = when (playerMove) { ROCK -> ROCK.movePoints + 0 PAPER -> PAPER.movePoints + 3 SCISSORS -> SCISSORS.movePoints + 6 else -> throw IllegalArgumentException("Invalid move: $playerMove") } override fun strategy(outcome: RoundOutcome): Int = when (outcome) { RoundOutcome.X -> outcome.outcomePoints + ROCK.movePoints RoundOutcome.Y -> outcome.outcomePoints + PAPER.movePoints RoundOutcome.Z -> outcome.outcomePoints + SCISSORS.movePoints else -> throw IllegalArgumentException("Invalid outcome: $outcome") } }, SCISSORS(3) { override fun play(playerMove: RockPaperScissors): Int = when (playerMove) { ROCK -> ROCK.movePoints + 6 PAPER -> PAPER.movePoints + 0 SCISSORS -> SCISSORS.movePoints + 3 else -> throw IllegalArgumentException("Invalid move: $playerMove") } override fun strategy(outcome: RoundOutcome): Int = when (outcome) { RoundOutcome.X -> outcome.outcomePoints + PAPER.movePoints RoundOutcome.Y -> outcome.outcomePoints + SCISSORS.movePoints RoundOutcome.Z -> outcome.outcomePoints + ROCK.movePoints else -> throw IllegalArgumentException("Invalid outcome: $outcome") } }; abstract fun play(playerMove: RockPaperScissors): Int abstract fun strategy(outcome: RoundOutcome): Int } fun round(opponent: String, player: String): Int { val opponentMove = OpponentMove.valueOf(opponent).move val playerMove = PlayerMove.valueOf(player).move return opponentMove.play(playerMove) } fun strategyRound(opponent: String, outcome: String): Int { val opponentMove = OpponentMove.valueOf(opponent).move val expectedOutcome = RoundOutcome.valueOf(outcome) return opponentMove.strategy(expectedOutcome) } fun main() { fun part1(input: List<String>): Int { return input.sumOf { val (opponent, player) = it.split(" ") round(opponent, player) } } fun part2(input: List<String>): Int { return input.sumOf { val (opponent, outcome) = it.split(" ") strategyRound(opponent, outcome) } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
8d2b7a974c2736903a9def65282be91fbb104ffd
3,587
advent-of-code
Apache License 2.0
src/day10/Day10.kt
blundell
572,916,256
false
{"Kotlin": 38491}
package day10 import readInput fun main() { data class Instruction(val op: String, val value: Int) { override fun toString(): String { return "$op $value" } } fun part1(input: List<String>): Int { val instructions = input.map { val op = it.substring(0..3) val value: Int if (it.contains(' ')) { value = it.substringAfter(' ').toInt() } else { value = 0 } Instruction(op, value) } val totalCycles = instructions.map { if (it.op == "addx") { 2 } else { // noop 1 } }.sum() var x = 1 var currentInstruction: Instruction? var instructionIndex = 0 var firstAdd = false var inspectionX = 0 val inspectionCycles = listOf(20, 60, 100, 140, 180, 220) for (cycle in 0 until totalCycles) { println("Cycle $cycle") currentInstruction = instructions[instructionIndex] println("Instr $currentInstruction X $x") if (inspectionCycles.contains(cycle)) { println("Sum ${(cycle * x)}") inspectionX += (cycle * x) if (cycle == 220) { // inspectionX -= 220 } println("InspectionX $inspectionX") } if (currentInstruction.op == "addx") { if (!firstAdd) { println("first add") firstAdd = true } else { println("second add") firstAdd = false x += currentInstruction.value instructionIndex += 1 } } else { // noop println("noop") firstAdd = false instructionIndex += 1 } println("--") } return inspectionX } fun part2(input: List<String>): Int { return input.size } // test if implementation meets criteria from the description, like: val testInput = readInput("day10/Day10_test") val testResult = part1(testInput) check(testResult == 13140) { "Expected 13140 got [$testResult]." } // val input = readInput("day10/Day10") // println(part1(input)) // println(part2(input)) }
0
Kotlin
0
0
f41982912e3eb10b270061db1f7fe3dcc1931902
2,441
kotlin-advent-of-code-2022
Apache License 2.0
src/Day02.kt
touchman
574,559,057
false
{"Kotlin": 16512}
import java.lang.Exception fun main() { val input = readInput("Day02") fun part1(input: List<String>) = input.map { it.split(" ") .let { parseItem(it[0]) to parseItem(it[1]) }.let { pair -> getResult(pair.second, pair.first) + pair.second.value } }.reduce { acc: Int, i: Int -> acc + i } fun part2(input: List<String>) = input.map { it.split(" ") .let { parseItem(it[0]) to getItemForAction(parseItem(it[0]), it[1]) }.let { pair -> getResult(pair.second, pair.first) + pair.second.value } }.reduce { acc: Int, i: Int -> acc + i } println(part1(input)) println(part2(input)) } enum class Item(val value: Int) { ROCK(1), PAPER(2), SCISSORS(3), } fun parseItem(item: String): Item = when (item) { in listOf("A", "X") -> Item.ROCK in listOf("B", "Y") -> Item.PAPER in listOf("C", "Z") -> Item.SCISSORS else -> throw Exception("Unknown items: $item") } fun getResult(item1: Item, item2: Item): Int = when { item1 == item2 -> 3 item1 == Item.ROCK && item2 == Item.PAPER-> 0 item1 == Item.ROCK && item2 == Item.SCISSORS-> 6 item1 == Item.PAPER && item2 == Item.SCISSORS-> 0 item1 == Item.PAPER && item2 == Item.ROCK-> 6 item1 == Item.SCISSORS && item2 == Item.ROCK-> 0 item1 == Item.SCISSORS && item2 == Item.PAPER-> 6 else -> throw Exception("Unknown items: $item1 and $item2") } fun getItemForAction(oppItem: Item, action: String) = when (action) { "X" -> { when (oppItem) { Item.ROCK -> Item.SCISSORS Item.PAPER -> Item.ROCK Item.SCISSORS -> Item.PAPER } } "Y" -> oppItem "Z" -> when (oppItem) { Item.ROCK -> Item.PAPER Item.PAPER -> Item.SCISSORS Item.SCISSORS -> Item.ROCK } else -> throw Exception("Unknown action: $action") }
0
Kotlin
0
0
4f7402063a4a7651884be77bb9e97828a31459a7
2,202
advent-of-code-2022
Apache License 2.0
src/main/kotlin/mytechtoday/aoc/year2022/Day3.kt
mytechtoday
572,836,399
false
{"Kotlin": 15268, "Java": 1717}
package mytechtoday.aoc.year2022 import mytechtoday.aoc.util.readInput fun main() { fun getPriority(charItem: Char): Int { if(charItem.toInt() in 97..122) { return charItem.toInt() - 96; } if(charItem.toInt() in 65..90) { return charItem.toInt() - 38; } return 0; } fun part2(input: List<String>): Int { var duplicateChar = mutableListOf<Char>() for (i in input.indices step 3) { var elfOne = input[i].toSet(); var elfTwo = input[i+1].toSet(); var elfThree = input[i+2].toSet(); val intersect = elfOne.intersect(elfTwo).intersect(elfThree) duplicateChar.add(intersect.elementAt(0)) } var prioritySum = 0; for(charItem in duplicateChar) { prioritySum += getPriority(charItem) } return prioritySum; } fun part1(input: List<String>): Int { var duplicateChar = mutableListOf<Char>() for(item in input) { var compartmentOne = item.substring(0, item.length / 2); var compartmentTwo = item.substring(item.length / 2); val itemSet: Set<Char> = compartmentOne.toSet() for (item in compartmentTwo){ if(itemSet.contains(item)){ duplicateChar.add(item) break } } } var prioritySum = 0; for(charItem in duplicateChar) { prioritySum += getPriority(charItem) } return prioritySum; } val input = readInput(2022,"day3") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
3f25cb010e6367af20acaa2906aff17a80f4e623
1,676
aoc2022
Apache License 2.0
kotlin/graphs/shortestpaths/DijkstraSlow.kt
polydisc
281,633,906
true
{"Java": 540473, "Kotlin": 515759, "C++": 265630, "CMake": 571}
package graphs.shortestpaths import java.util.stream.Stream // https://en.wikipedia.org/wiki/Dijkstra's_algorithm object DijkstraSlow { // calculate shortest paths in O(V^2) fun shortestPaths(graph: Array<List<Edge>>, s: Int, prio: IntArray, pred: IntArray) { val n = graph.size Arrays.fill(pred, -1) Arrays.fill(prio, Integer.MAX_VALUE) prio[s] = 0 val visited = BooleanArray(n) for (i in 0 until n) { var u = -1 for (j in 0 until n) { if (!visited[j] && (u == -1 || prio[u] > prio[j])) u = j } if (prio[u] == Integer.MAX_VALUE) break visited[u] = true for (e in graph[u]) { val v = e.t val nprio = prio[u] + e.cost if (prio[v] > nprio) { prio[v] = nprio pred[v] = u } } } } // Usage example fun main(args: Array<String?>?) { val cost = arrayOf(intArrayOf(0, 3, 2), intArrayOf(0, 0, -2), intArrayOf(0, 0, 0)) val n = cost.size val graph: Array<List<Edge>> = Stream.generate { ArrayList() }.limit(n).toArray { _Dummy_.__Array__() } for (i in 0 until n) { for (j in 0 until n) { if (cost[i][j] != 0) { graph[i].add(Edge(j, cost[i][j])) } } } val dist = IntArray(n) val pred = IntArray(n) shortestPaths(graph, 0, dist, pred) System.out.println(0 == dist[0]) System.out.println(3 == dist[1]) System.out.println(1 == dist[2]) System.out.println(-1 == pred[0]) System.out.println(0 == pred[1]) System.out.println(1 == pred[2]) } class Edge(var t: Int, var cost: Int) }
1
Java
0
0
4566f3145be72827d72cb93abca8bfd93f1c58df
1,844
codelibrary
The Unlicense
app/src/main/java/com/lukaslechner/coroutineusecasesonandroid/playground/challenges/SearchingChallenge.kt
ahuamana
627,986,788
false
null
package com.lukaslechner.coroutineusecasesonandroid.playground.challenges //find the longest substring that contains k unique characters //The input string str must have at least length 2. //The first character of str must be a digit between 1 and 6 (inclusive), representing the number of unique characters in the longest substring to be found. //The remaining characters of str must be printable ASCII characters (i.e., characters with ASCII codes between 32 and 126, inclusive). //The function should return the longest substring of str that contains exactly k unique characters, where k is the digit extracted from the first character of str. //If there are multiple longest substrings that satisfy the above condition, the function should return the first one. fun SearchingChallenge(str: String): String { //The input string str must have at least length 2. if(str.length < 2) return "not possible" //get the number of unique characters handle exception use elvis operator val k = str[0].toString().toIntOrNull() ?: return "not possible" if(k !in 1..6) return "not possible" //Remove the first character from the string val substring = str.substring(1) //get the longest substring that contains k unique characters val longestSubstring = getLongestSubstring(substring, k) return if(longestSubstring.isEmpty()) "not possible" else longestSubstring } fun getLongestSubstring(substring: String, k: Int): String { //get the list of all substrings val substrings = mutableListOf<String>() for (i in substring.indices) { for (j in i + 1..substring.length) { substrings.add(substring.substring(i, j)) } } //get the list of all substring that contains k unique characters val substringsWithKUniqueChars = mutableListOf<String>() substrings.forEach { if(it.toSet().size == k) substringsWithKUniqueChars.add(it) } //get the longest substring that contains k unique characters avoid use maxByOrNull var longestSubstring = "" substringsWithKUniqueChars.forEach { if(it.length > longestSubstring.length) longestSubstring = it } return longestSubstring } fun main() { println(SearchingChallenge("3aabacbebebe")) //cbebebe println(SearchingChallenge("2aabbcbbbadef")) //bbcbbb println(SearchingChallenge("2aabbacbaa")) //aabba }
0
Kotlin
0
0
931ce884b8c70355e38e007141aab58687ed1909
2,377
KotlinCorutinesExpert
Apache License 2.0
src/main/kotlin/com/rubengees/pathfinder/PathFinder.kt
rubengees
159,884,211
false
null
package com.rubengees.pathfinder import java.util.PriorityQueue /** * Entry point for path calculation. * The A* algorithm is used to find an optimal way between a [CoordinateType.START] coordinate and an * [CoordinateType.END] coordinate on the given input. * * @author <NAME> */ class PathFinder( private val parser: GraphParser = GraphParser(), private val outputMarker: OutputMarker = OutputMarker() ) { /** * Parses the [input], finds the shortest (lowest cost) path between [CoordinateType.START] and [CoordinateType.END] * and returns the marked version of the input. * If no path is found, an exception will be thrown. */ fun addPath(input: String): String { val graph = parser.parse(input) val path = findPath(graph) return outputMarker.mark(input, path) } private fun findPath(graph: Graph): List<Coordinate> { val queue = PriorityQueue<PrioritizedCoordinate>(compareBy { it.priority }).apply { offer(graph.start.prioritize(0f)) } val costMap = mutableMapOf<Coordinate, Float>() val pathMap = mutableMapOf<Coordinate, Coordinate>() while (queue.isNotEmpty()) { val (current) = queue.poll() if (current == graph.end) { return reconstructPath(pathMap, graph.start, graph.end) } graph.neighbours(current).forEach { next -> val newCost = (costMap[current] ?: 0f) + (current costTo next) if (costMap.contains(next).not() || newCost < costMap.getValue(next)) { costMap[next] = newCost queue += next.prioritize(newCost + (next costTo graph.end)) pathMap[next] = current } } } throw IllegalArgumentException("No path found!") } private fun reconstructPath( pathMap: Map<Coordinate, Coordinate>, start: Coordinate, end: Coordinate ): List<Coordinate> { val result = mutableListOf<Coordinate>() var current = end while (current != start) { result += current current = pathMap[current] ?: throw IllegalStateException("Could not reconstruct path: No previous corrdinate for $current") } return result.plus(start) } private data class PrioritizedCoordinate(val coordinate: Coordinate, val priority: Float) private fun Coordinate.prioritize(priority: Float) = PrioritizedCoordinate(this, priority) }
0
Kotlin
0
0
c8499cc51e08b8196738c0990a75f6be85f514be
2,571
advent-of-kotlin-2018-week-1
MIT License
src/Day20.kt
mjossdev
574,439,750
false
{"Kotlin": 81859}
fun main() { // used to allow finding the right instance of a number with instanceOf class IdentityLong(val value: Long) { override fun toString(): String = value.toString() } fun decrypt(numbers: List<IdentityLong>, times: Int): Long { val workingNumbers = numbers.toMutableList() repeat(times) { for (n in numbers) { val index = workingNumbers.indexOf(n) var newIndex = ((index + n.value) % workingNumbers.lastIndex).toInt() if (newIndex <= 0) { newIndex += workingNumbers.lastIndex } if (index == newIndex) continue workingNumbers.removeAt(index) workingNumbers.add(newIndex, n) } } val indexOf0 = workingNumbers.indexOfFirst { it.value == 0L} return listOf(1000, 2000, 3000).sumOf { workingNumbers[(indexOf0 + it) % numbers.size].value } } fun part2(input: List<String>): Long = decrypt(input.map { IdentityLong(it.toLong() * 811589153) }, 10) fun part1(input: List<String>): Long = decrypt(input.map { IdentityLong(it.toLong()) }, 1) // test if implementation meets criteria from the description, like: val testInput = readInput("Day20_test") check(part1(testInput) == 3L) check(part2(testInput) == 1623178306L) val input = readInput("Day20") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
afbcec6a05b8df34ebd8543ac04394baa10216f0
1,482
advent-of-code-22
Apache License 2.0
src/Day02.kt
dyomin-ea
572,996,238
false
{"Kotlin": 21309}
fun main() { /* * A X rock * B Y paper * C Z scissors * */ fun pointsOf(value: String): Int = when (value) { "A", "X" -> 1 "B", "Y" -> 2 "C", "Z" -> 3 else -> error("unknown value") } fun getScore(l: String, r: String): Int { return when (l to r) { "A" to "X", "B" to "Y", "C" to "Z" -> 3 "A" to "Y", "B" to "Z", "C" to "X" -> 6 "A" to "Z", "B" to "X", "C" to "Y" -> 0 else -> error("unknown value") } + pointsOf(r) } fun String.win(): String = when (this) { "A" -> "B" "B" -> "C" "C" -> "A" else -> error("unknown value") } fun String.loose(): String = when (this) { "A" -> "C" "B" -> "A" "C" -> "B" else -> error("unknown value") } fun getTrueScore(l: String, r: String): Int = when (r) { "X" -> 0 + pointsOf(l.loose()) "Y" -> 3 + pointsOf(l) "Z" -> 6 + pointsOf(l.win()) else -> error("unknown value") } fun part1(input: List<String>): Int = input.sumOf { getScore( it.substringBefore(" "), it.substringAfter(" ") ) } fun part2(input: List<String>): Int = input.sumOf { getTrueScore( it.substringBefore(" "), it.substringAfter(" ") ) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
8aaf3f063ce432207dee5f4ad4e597030cfded6d
1,879
advent-of-code-2022
Apache License 2.0