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
advent-of-code-2023/src/main/kotlin/eu/janvdb/aoc2023/day06/day06.kt
janvdbergh
318,992,922
false
{"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335}
package eu.janvdb.aoc2023.day06 import eu.janvdb.aocutil.kotlin.readLines //const val FILENAME = "input06-test.txt" const val FILENAME = "input06.txt" fun main() { val lines = readLines(2023, FILENAME) part1(lines) part2(lines) } private fun part1(lines: List<String>) { val times = lines[0].split(":")[1].trim().split(Regex(" +")).map { it.toInt() } val distances = lines[1].split(":")[1].trim().split(Regex(" +")).map { it.toLong() } val puzzles = times.zip(distances).map { (time, distance) -> Puzzle(time, distance) } val totalWinningStarts = puzzles.map { it.numberOfWinningStarts() }.fold(1L) { acc, x -> acc * x } println(totalWinningStarts) } private fun part2(lines: List<String>) { val time = lines[0].split(":")[1].replace(Regex(" "), "").toInt() val distance = lines[1].split(":")[1].replace(Regex(" "), "").toLong() val puzzle = Puzzle(time, distance) println(puzzle.numberOfWinningStarts()) } data class Puzzle(val time: Int, val winningDistance: Long) { fun numberOfWinningStarts(): Int { return (0..time).count { isWinningStart(it) } } private fun isWinningStart(startTime: Int): Boolean { val distance = 1L * (time - startTime) * startTime return distance > winningDistance } }
0
Java
0
0
78ce266dbc41d1821342edca484768167f261752
1,227
advent-of-code
Apache License 2.0
aoc-2021/src/commonMain/kotlin/fr/outadoc/aoc/twentytwentyone/Day14.kt
outadoc
317,517,472
false
{"Kotlin": 183714}
package fr.outadoc.aoc.twentytwentyone import fr.outadoc.aoc.scaffold.Day import fr.outadoc.aoc.scaffold.readDayInput class Day14 : Day<Long> { private val input = readDayInput() .split("\n\n") .map { block -> block.lines() } private val template = input.first().first().toList() private val rules = input.last() .associate { rule -> val (from, to) = rule.split(" -> ") from.toList() to to.first() } private data class State( val pairFrequencies: Map<List<Char>, Long>, val charFrequencies: Map<Char, Long> ) private val initialState = State( pairFrequencies = template.windowed(size = 2).frequencyMap(), charFrequencies = template.frequencyMap() ) private fun State.reduce(): State { val pairFrequenciesNext = pairFrequencies.toMutableMap() val charFrequenciesNext = charFrequencies.toMutableMap() pairFrequencies .filterValues { count -> count > 0 } .forEach { (pair, count) -> val (left, right) = pair rules[pair]?.let { replacement -> with(pairFrequenciesNext) { set(pair, getValue(pair) - count) set(listOf(left, replacement), getOrElse(listOf(left, replacement)) { 0L } + count) set(listOf(replacement, right), getOrElse(listOf(replacement, right)) { 0L } + count) } with(charFrequenciesNext) { set(replacement, getOrElse(replacement) { 0L } + count) } } } return copy( pairFrequencies = pairFrequenciesNext.filterValues { count -> count > 0 }, charFrequencies = charFrequenciesNext ) } private fun <T> List<T>.frequencyMap(): Map<T, Long> = groupingBy { it } .eachCount() .map { (window, count) -> window to count.toLong() } .toMap() private fun <T> Map<T, Long>.minMaxDifference(): Long = maxOf { (_, count) -> count } - minOf { (_, count) -> count } override fun step1() = (0 until 10) .fold(initialState) { acc, _ -> acc.reduce() } .charFrequencies .minMaxDifference() override fun step2() = (0 until 40) .fold(initialState) { acc, _ -> acc.reduce() } .charFrequencies .minMaxDifference() override val expectedStep1 = 2010L override val expectedStep2 = 2437698971143L }
0
Kotlin
0
0
54410a19b36056a976d48dc3392a4f099def5544
2,568
adventofcode
Apache License 2.0
src/Day08.kt
TheGreatJakester
573,222,328
false
{"Kotlin": 47612}
import utils.string.asLines import utils.readInputAsText import utils.runSolver private val dayNumber: String = "08" private val testSolution1 = 21 private val testSolution2 = null private typealias Grid = List<List<Int>> private typealias MutableGrid = MutableList<MutableList<Int>> fun Grid.print() { forEach { println(it) } println() } fun buildMutableGrid(size: Int): MutableGrid { val grid = mutableListOf<MutableList<Int>>() repeat(size) { val nextLine = mutableListOf<Int>() repeat(size) { nextLine.add(0) } grid.add(nextLine) } return grid } fun translateGrid(grid: Grid): MutableGrid { val gridSize = grid.size val newGrid = buildMutableGrid(gridSize) for (i in 0 until gridSize) { for (k in 0 until gridSize) { newGrid[i][gridSize - (k + 1)] = grid[k][i] } } return newGrid } private fun scoreRight(grid: Grid, x: Int, y: Int): Int { val heightOfTreeHouse = grid[y][x] val row = grid[y].subList(x + 1, grid.size) row.forEachIndexed { index, it -> if(it >= heightOfTreeHouse){ return index + 1 } } return row.size.coerceAtLeast(1) } private fun rotate(x: Int, y: Int, size: Int): Pair<Int, Int> = size - (y + 1) to x private fun rotate(pair: Pair<Int, Int>, size: Int): Pair<Int, Int> = rotate(pair.first, pair.second, size) private fun part1(input: String): Int { var grid = input.asLines().map { it.toList().map { it.code - 48 } } var scoreGrid = buildMutableGrid(grid.size) repeat(4) { grid.forEachIndexed { line, list -> var tallest = -1 list.forEachIndexed { tree, height -> if (height > tallest) { scoreGrid[line][tree] = 1 tallest = height } } } grid = translateGrid(grid) scoreGrid = translateGrid(scoreGrid) } return scoreGrid.sumOf { it.sum() } } private fun part2(input: String): Int { val grid1 = input.asLines().map { it.toList().map { it.code - 48 } } val gridSize = grid1.size val grid2 = translateGrid(grid1) val grid3 = translateGrid(grid2) val grid4 = translateGrid(grid3) grid1.print() val scoreGrid = buildMutableGrid(gridSize) for (y in 0 until gridSize) { for (x in 0 until gridSize) { val right = scoreRight(grid1, x, y) val (x2, y2) = rotate(x, y, gridSize) val up = scoreRight(grid2, x2, y2) val (x3,y3) = rotate(x2,y2, gridSize) val left = scoreRight(grid3, x3, y3) val (x4,y4) = rotate(x3,y3, gridSize) val down = scoreRight(grid4, x4, y4) val total = right * up * left * down scoreGrid[y][x] = total } } scoreGrid.print() return scoreGrid.maxOf { it.max() } } 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
3,282
2022-AOC-Kotlin
Apache License 2.0
src/day12/Day12.kt
maxmil
578,287,889
false
{"Kotlin": 32792}
package day12 import println import readInput fun List<String>.parse() = flatMap { line -> line.split("-").let { listOf(Pair(it[0], it[1]), Pair(it[1], it[0])) } } .groupBy { it.first } .mapValues { entry -> entry.value.map { it.second }.toSet() } fun countPaths(input: List<String>, allowOneCaveTwice:Boolean = false): Int { val cave = input.parse() val complete = mutableListOf<List<String>>() val incomplete = cave["start"]!!.map { listOf("start", it) }.toMutableList() while (incomplete.isNotEmpty()) { val path = incomplete.removeLast() val next = cave[path.last()]?.filter { path.canMoveToCave(it, allowOneCaveTwice) } ?: emptyList() next.forEach { room -> val newPath = path.toMutableList().apply { add(room) } if (room == "end") complete.add(newPath) else incomplete.add(newPath) } } return complete.size } fun List<String>.canMoveToCave(dest: String, allowOneCaveTwice: Boolean = false) = dest != "start" && (dest == "end" || dest == dest.uppercase() || !contains(dest) || (allowOneCaveTwice && filter { it.lowercase() == it }.groupBy { it }.maxOf { it.value.size} == 1)) fun part1(input: List<String>) = countPaths(input) fun part2(input: List<String>) = countPaths(input, true) fun main() { val testInput = readInput("day12/input_test") check(part1(testInput) == 226) check(part2(testInput) == 3509) val input = readInput("day12/input") part1(input).println() part2(input).println() }
0
Kotlin
0
0
246353788b1259ba11321d2b8079c044af2e211a
1,545
advent-of-code-2021
Apache License 2.0
kotlin/src/main/kotlin/year2021/Day04.kt
adrisalas
725,641,735
false
{"Kotlin": 130217, "Python": 1548}
package year2021 private class Box(val number: Int) { var checked = false private set fun check() { this.checked = true } } private class Board(val rows: List<List<Box>>) { fun checkNumber(number: Int) { rows.forEach { row -> row.forEach { box -> if (box.number == number) { box.check() } } } } fun checkWin(): Boolean { var won = false rows.forEach { row -> if (row.all { it.checked }) won = true } if (!won) { for (i in rows.indices) { var column = true for (row in rows) { column = column && row[i].checked } won = column if (won) { break } } } return won } } private fun part1(input: List<String>): Int { val numbers = readNumbers(input) val boards: List<Board> = readBoards(input) for (number in numbers) { boards.forEach { it.checkNumber(number) } val board = boards.firstOrNull { it.checkWin() } if (board != null) { return sumUnmarkedNumbers(board) * number } } throw RuntimeException("No board won") } fun readNumbers(input: List<String>): List<Int> { return input[0] .split(",") .map { Integer.valueOf(it) } } private fun readBoards(input: List<String>): List<Board> { val boards: MutableList<Board> = ArrayList() var boardBuffer: MutableList<MutableList<Box>> = ArrayList() for (i in 2 until input.size) { if (input[i].isNotEmpty()) { val line: MutableList<Box> = ArrayList() input[i].split(" ") .filter { it != "" } .forEach { line.add(Box(Integer.valueOf(it))) } boardBuffer.add(line) } else { boards.add(Board(boardBuffer)) boardBuffer = ArrayList() } } if (boardBuffer.isNotEmpty()) { boards.add(Board(boardBuffer)) } return boards } private fun sumUnmarkedNumbers(board: Board): Int { return board.rows.fold(0) { boardAcc, row -> boardAcc + row.fold(0) { rowAcc, box -> if (!box.checked) (rowAcc + box.number) else rowAcc } } } private fun part2(input: List<String>): Int { val numbers = readNumbers(input) var boards: List<Board> = readBoards(input) var lastBoardToWinScore: Int? = null var lastNumberToWin: Int? = null for (number in numbers) { boards.forEach { it.checkNumber(number) } val board = boards.firstOrNull { it.checkWin() } if (board != null) { lastBoardToWinScore = sumUnmarkedNumbers(board) lastNumberToWin = number } boards = boards.filter { !it.checkWin() } } if (lastBoardToWinScore == null || lastNumberToWin == null) { throw RuntimeException("No board won") } return lastBoardToWinScore * lastNumberToWin } fun main() { // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_test") check(part1(testInput) == 4512) val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
2
6733e3a270781ad0d0c383f7996be9f027c56c0e
3,358
advent-of-code
MIT License
src/Day07.kt
mikemac42
573,071,179
false
{"Kotlin": 45264}
import java.io.File fun main() { val testInput = """${'$'} cd / ${'$'} ls dir a 14848514 b.txt 8504156 c.dat dir d ${'$'} cd a ${'$'} ls dir e 29116 f 2557 g 62596 h.lst ${'$'} cd e ${'$'} ls 584 i ${'$'} cd .. ${'$'} cd .. ${'$'} cd d ${'$'} ls 4060174 j 8033020 d.log 5626152 d.ext 7214296 k""" val testInput2 = """${'$'} cd / ${'$'} ls dir a dir b ${'$'} cd a ${'$'} ls 1 some.txt ${'$'} cd .. ${'$'} cd b ${'$'} ls dir a ${'$'} cd a ${'$'} ls 1 other.txt""" val realInput = File("src/Day07.txt").readText() val part1TestOutput = sumDirectorySizes(testInput) println("Part 1 Test Output: $part1TestOutput") check(part1TestOutput == 95437L) val part1Test2Output = sumDirectorySizes(testInput2) println("Part 1 Test2 Output: $part1Test2Output") check(part1Test2Output == 5L) val part1RealOutput = sumDirectorySizes(realInput) println("Part 1 Real Output: $part1RealOutput") val part2TestOutput = smallestDirToDelete(testInput) println("Part 2 Test Output: $part2TestOutput") check(part2TestOutput == 24933642L) println("Part 2 Real Output: ${smallestDirToDelete(realInput)}") } data class Dir( val name: String, val path: String, var parentDir: Dir?, val childDirs: MutableList<Dir>, val fileSizes: MutableList<Long> ) { fun size(): Long = fileSizes.sum() + childDirs.sumOf { it.size() } } /** * Find all of the directories with a total size of at most 100000. * What is the sum of the total sizes of those directories? * This process can count files more than once! */ fun sumDirectorySizes(input: String): Long = buildDirPathToSizeMap(input).values.filter { it <= 100_000L }.sum() fun smallestDirToDelete(input: String): Long { val dirPathToSizeMap = buildDirPathToSizeMap(input) val freeSpace = 70_000_000L - dirPathToSizeMap["/"]!! val minSpaceToDelete = 30_000_000L - freeSpace return dirPathToSizeMap.values.sorted().first { it >= minSpaceToDelete } } fun buildDirPathToSizeMap(input: String): Map<String, Long> { val lines = input.lines().filterNot { it.startsWith("$ ls") } val rootDir = Dir("/", "/", null, mutableListOf(), mutableListOf()) val dirPathMap = mutableMapOf(rootDir.path to rootDir) var currentDir = rootDir lines.forEach { line -> if (line == "$ cd /") { currentDir = rootDir } else if (line == "$ cd ..") { currentDir = currentDir.parentDir!! } else if (line.startsWith("$ cd ")) { currentDir = currentDir.childDirs.find { it.name == line.substring(5) }!! } else if (line.startsWith("dir ")) { val name = line.substring(4) val newDir = Dir(name, "${currentDir.path}$name/", parentDir = currentDir, mutableListOf(), mutableListOf()) dirPathMap[newDir.path] = newDir currentDir.childDirs.add(newDir) } else { currentDir.fileSizes.add(line.split(' ').first().toLong()) } } return dirPathMap.entries.associate { (path, dir) -> path to dir.size() } }
0
Kotlin
1
0
909b245e4a0a440e1e45b4ecdc719c15f77719ab
2,922
advent-of-code-2022
Apache License 2.0
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2023/2023-01.kt
ferinagy
432,170,488
false
{"Kotlin": 787586}
package com.github.ferinagy.adventOfCode.aoc2023 import com.github.ferinagy.adventOfCode.println import com.github.ferinagy.adventOfCode.readInputLines fun main() { val input = readInputLines(2023, "01-input") val test1 = readInputLines(2023, "01-test1") val test2 = readInputLines(2023, "01-test2") println("Part1:") part1(test1).println() part1(input).println() println() println("Part2:") part2(test2).println() part2(input).println() } private fun part1(input: List<String>) = input.sumOf { line -> val d1 = line.first { it.isDigit() } val d2 = line.last { it.isDigit() } "$d1$d2".toInt() } private fun part2(input: List<String>): Int { val regex = (names + digits).joinToString(separator = "|").toRegex() return input.sumOf { line -> val result = regex.findAllOverlapping(line) val d1 = result.first() val d2 = result.last() "${d1.toChar()}${d2.toChar()}".toInt() } } private fun String.toChar(): Char { if (length == 1) return first() return (names.indexOf(this) + 1).digitToChar() } private fun Regex.findAllOverlapping(text: String): List<String> = buildList { var index = 0 while (index < text.length) { val result = find(text, startIndex = index) ?: break this += result.value index = result.range.first + 1 } } private val names = listOf("one", "two", "three", "four", "five", "six", "seven", "eight", "nine") private val digits = listOf("1", "2", "3", "4", "5", "6", "7", "8", "9")
0
Kotlin
0
1
f4890c25841c78784b308db0c814d88cf2de384b
1,544
advent-of-code
MIT License
src/main/kotlin/aoc23/Day02.kt
tahlers
725,424,936
false
{"Kotlin": 65626}
package aoc23 import kotlin.math.max object Day02 { data class Drawing(val redCubes: Int = 0, val greenCubes: Int = 0, val blueCubes: Int = 0) data class Game(val id: Int, val drawings: List<Drawing>) private val redRegEx = """(\d+) red""".toRegex() private val greenRegEx = """(\d+) green""".toRegex() private val blueRegEx = """(\d+) blue""".toRegex() fun sumOfPossibleGameIds(input: String, allowedRed: Int = 12, allowedGreen: Int = 13, allowedBlue: Int = 14): Int { val games = parseInput(input) val filtered = games.filterValues { isGamePossible(it, allowedRed, allowedGreen, allowedBlue) } return filtered.keys.sum() } fun sumOfPowerOfMinimalGames(input: String): Int { val games = parseInput(input) val minimals = games.map { minimalDrawingForGame(it.value) } return minimals.sumOf { it.redCubes * it.greenCubes * it.blueCubes } } private fun minimalDrawingForGame(game: Game): Drawing = game.drawings.fold(Drawing()) { acc, nextDrawing -> Drawing( max(acc.redCubes, nextDrawing.redCubes), max(acc.greenCubes, nextDrawing.greenCubes), max(acc.blueCubes, nextDrawing.blueCubes), ) } private fun isGamePossible(game: Game, allowedRed: Int, allowedGreen: Int, allowedBlue: Int) = game.drawings.all { isDrawingPossible(it, allowedRed, allowedGreen, allowedBlue) } private fun isDrawingPossible(drawing: Drawing, allowedRed: Int, allowedGreen: Int, allowedBlue: Int): Boolean = drawing.redCubes <= allowedRed && drawing.greenCubes <= allowedGreen && drawing.blueCubes <= allowedBlue private fun parseInput(input: String): Map<Int, Game> { val lines = input.trim().lines() val gameList = lines.map { line -> val id = line.substringBefore(':').substringAfter(' ').toInt() val parts = line.substringAfter(':').split("; ") val drawings = parts.map { part -> val red = redRegEx.find(part)?.groupValues?.get(1)?.toInt() ?: 0 val green = greenRegEx.find(part)?.groupValues?.get(1)?.toInt() ?: 0 val blue = blueRegEx.find(part)?.groupValues?.get(1)?.toInt() ?: 0 Drawing(red, green, blue) } Game(id, drawings) } return gameList.associateBy { it.id } } }
0
Kotlin
0
0
0cd9676a7d1fec01858ede1ab0adf254d17380b0
2,442
advent-of-code-23
Apache License 2.0
src/main/kotlin/days/Day2.kt
nicopico-dev
726,255,944
false
{"Kotlin": 37616}
package days import kotlin.math.max class Day2( inputFileNameOverride: String? = null, ) : Day(2, inputFileNameOverride) { override fun partOne(): Any { val hypothesis = Hypothesis( red = 12, green = 13, blue = 14, ) return inputList .map { parseInput(it) } .filter { hypothesis isPossibleWith it } .sumOf { it.id } } override fun partTwo(): Any { return inputList .map { parseInput(it) } .map { it.getMinimumHypothesis() } .sumOf { it.power } } companion object { private val gameRegex = Regex("Game (\\d+):") private val cubeRegex = Regex("(\\d+) (red|green|blue)") fun parseInput(input: String): Game { val gameId = gameRegex.find(input)!!.groupValues[1] val takes = input.substringAfter(":") .split(";") .map { take -> cubeRegex .findAll(take) .associate { val color = Color.parse((it.groupValues[2])) val count = (it.groupValues[1]).toInt() color to count } } return Game( id = gameId.toInt(), takes = takes ) } } data class Game( val id: Int, val takes: List<Map<Color, Int>> ) { fun getMinimumHypothesis(): Hypothesis { return takes.fold(Hypothesis()) { acc, take -> Hypothesis( red = max(acc.red, take.getOrDefault(Color.Red, 0)), green = max(acc.green, take.getOrDefault(Color.Green, 0)), blue = max(acc.blue, take.getOrDefault(Color.Blue, 0)), ) } } } data class Hypothesis( val red: Int = 0, val green: Int = 0, val blue: Int = 0, ) { val power = red * green * blue infix fun isPossibleWith(game: Game): Boolean { return game.takes.all { take -> (take[Color.Red] ?: 0) <= red && (take[Color.Green] ?: 0) <= green && (take[Color.Blue] ?: 0) <= blue } } } enum class Color { Red, Green, Blue; companion object { fun parse(value: String): Color { return when (value) { "red" -> Red "green" -> Green "blue" -> Blue else -> throw IllegalArgumentException("Unknown color $value") } } } } }
0
Kotlin
0
0
1a13c8bd3b837c1ce5b13f90f326f0277249d23e
2,803
aoc-2023
Creative Commons Zero v1.0 Universal
Round 1A - B. Ratatouille/src/app.kt
amirkhanyana
110,548,909
false
{"Kotlin": 20514}
import java.util.* fun main(args: Array<String>) { val input = Scanner(System.`in`) val T = input.nextInt() var Ti = 1 while (Ti <= T) { val N = input.nextInt() val P = input.nextInt() val recipe = IntArray(N, { input.nextInt() }) val packages = Array(N, { IntArray(P, { input.nextInt() }) }) val ingredientToPackageSizeIntersections = Array(N, { mutableListOf<MutableSet<IntRange>>() }) for (ingredientId in 0 until N) { for (packageId in 0 until P) { var start = Math.ceil(packages[ingredientId][packageId] / 1.1 / recipe[ingredientId]).toInt() val end = (packages[ingredientId][packageId] / 0.9 / recipe[ingredientId]).toInt() if (end > 0 && start <= end) { start = if (start > 0) start else start + 1 ingredientToPackageSizeIntersections[ingredientId].add(mutableSetOf(IntRange(start, end))) } } } var minPackageSizes = ingredientToPackageSizeIntersections[0].size for (i in 1 until ingredientToPackageSizeIntersections.size) { var usedPackages = 0 for (packageSizeIntersectionSet in ingredientToPackageSizeIntersections[i].toList()) { val packageSizeRange = packageSizeIntersectionSet.first() packageSizeIntersectionSet.clear() for (prevPackageSizeIntersectionsSet in ingredientToPackageSizeIntersections[i - 1]) { for (prevPackageSizes in prevPackageSizeIntersectionsSet) { val intersection = intersectRanges(packageSizeRange, prevPackageSizes) if (!intersection.isEmpty()) { addAndOptimizeSet(packageSizeIntersectionSet, intersection) } } } if (packageSizeIntersectionSet.isNotEmpty()) ++usedPackages } minPackageSizes = minOf(minPackageSizes, usedPackages) } println("Case #$Ti: $minPackageSizes") ++Ti } } fun addAndOptimizeSet(optimizedSet: MutableSet<IntRange>, rangeToAdd: IntRange) { var newRangeStart = rangeToAdd.start var newRangeEnd = rangeToAdd.endInclusive for (intRange in optimizedSet.toSet()) { val intersection = intRange.intersect(rangeToAdd) if (!intersection.isEmpty()) { optimizedSet.remove(intRange) newRangeStart = minOf(intRange.start, newRangeStart) newRangeEnd = maxOf(intRange.endInclusive, newRangeEnd) } } optimizedSet.add(IntRange(newRangeStart, newRangeEnd)) } fun intersectRanges(range1: IntRange, range2: IntRange): IntRange { if (range1.start <= range2.endInclusive || range2.start <= range1.endInclusive) { return IntRange(maxOf(range1.start, range2.start), minOf(range1.endInclusive, range2.endInclusive)) } else { return IntRange.EMPTY } }
0
Kotlin
0
0
25a8e6dbd5843e9d4a054d316acc9d726995fffe
3,015
Google-Code-Jam-2017-Problem-Kotlin-Solutions
The Unlicense
src/Day02.kt
ChrisCrisis
575,611,028
false
{"Kotlin": 31591}
import java.lang.IllegalStateException fun main() { fun part1(input: List<String>): Int { return input.map { it.split(" ") }.map { (opo, pl) -> val opponentChoice = Choice.fromOpponent(opo) GameMove( opponentChoice, Choice.fromPlayer(pl), ) }.sumOf { it.calcPlayerScore() } } fun part2(input: List<String>): Int { return input.map { it.split(" ") }.map { (opo, pl) -> val opponentChoice = Choice.fromOpponent(opo) GameMove( opponentChoice, Choice.fromCondition(opponentChoice,pl), ) }.sumOf { it.calcPlayerScore() } } val testInput = readInput("Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("Day02") println(part1(input)) println(part2(input)) } data class GameMove( val opponentChoice: Choice, val playerChoice: Choice, ){ fun calcPlayerScore(): Int { val result = when { opponentChoice == playerChoice -> 3 (opponentChoice == Choice.ROCK && playerChoice == Choice.PAPER) || (opponentChoice == Choice.PAPER && playerChoice == Choice.SCISSOR) || (opponentChoice == Choice.SCISSOR && playerChoice == Choice.ROCK) -> 6 (opponentChoice == Choice.SCISSOR && playerChoice == Choice.PAPER) || (opponentChoice == Choice.ROCK && playerChoice == Choice.SCISSOR) || (opponentChoice == Choice.PAPER && playerChoice == Choice.ROCK) -> 0 else -> throw IllegalStateException() } return playerChoice.expectedPoints + result } } enum class Choice( val expectedPoints: Int ){ ROCK(1), PAPER(2), SCISSOR(3); companion object{ fun fromCondition(opponentChoice: Choice, choice: String) = when(choice){ "X" -> opponentChoice.getChoiceLoss() "Y" -> opponentChoice "Z" -> opponentChoice.getChoiceWin() else -> throw IllegalArgumentException() } fun fromPlayer(choice: String) = when(choice){ "X" -> ROCK "Y" -> PAPER "Z" -> SCISSOR else -> throw IllegalArgumentException() } fun fromOpponent(choice: String) = when(choice){ "A" -> ROCK "B" -> PAPER "C" -> SCISSOR else -> throw IllegalArgumentException() } } } fun Choice.getChoiceWin() = when(this){ Choice.ROCK -> Choice.PAPER Choice.PAPER -> Choice.SCISSOR Choice.SCISSOR -> Choice.ROCK } fun Choice.getChoiceLoss() = when(this){ Choice.ROCK -> Choice.SCISSOR Choice.PAPER -> Choice.ROCK Choice.SCISSOR -> Choice.PAPER }
1
Kotlin
0
0
732b29551d987f246e12b0fa7b26692666bf0e24
2,903
aoc2022-kotlin
Apache License 2.0
src/main/kotlin/com/adrielm/aoc2020/solutions/day03/Day03.kt
Adriel-M
318,860,784
false
null
package com.adrielm.aoc2020.solutions.day03 import com.adrielm.aoc2020.common.Solution import org.koin.dsl.module class Day03 : Solution<List<String>, Long>(3) { private val mapping = mapOf( '.' to Tile.OPEN, '#' to Tile.TREE ) override fun solveProblem1(input: List<String>): Long { return countTrees(input, 3, 1) } override fun solveProblem2(input: List<String>): Long { val movements = listOf( Pair(1, 1), Pair(3, 1), Pair(5, 1), Pair(7, 1), Pair(1, 2) ) return movements.asSequence() .map { countTrees(input, it.first, it.second) } .reduce { acc, i -> acc * i } } private fun countTrees(input: List<String>, xMovement: Int, yMovement: Int): Long { var answer = 0L traverse(input, xMovement, yMovement) { currentTile -> if (mapping[currentTile] == Tile.TREE) { answer++ } } return answer } private fun traverse(input: List<String>, xMovement: Int, yMovement: Int, runnable: (Char) -> Unit) { val inputWidth = input.first().length var currentY = 0 var currentX = 0 while (currentY < input.size) { runnable(input[currentY][currentX]) currentY += yMovement currentX = (currentX + xMovement) % inputWidth } } companion object { val module = module { single { Day03() } } } } private enum class Tile { TREE, OPEN }
0
Kotlin
0
0
8984378d0297f7bc75c5e41a80424d091ac08ad0
1,584
advent-of-code-2020
MIT License
aoc-2015/src/main/kotlin/aoc/AocDay24.kt
triathematician
576,590,518
false
{"Kotlin": 615974}
package aoc class AocDay24: AocDay(24) { companion object { @JvmStatic fun main(args: Array<String>) { AocDay24().run() } } override val testinput = """ 1 2 3 4 5 7 8 9 10 11 """.trimIndent().lines() fun List<String>.parse() = map { it.toInt() } override fun calc1(input: List<String>): Long { return 0 val pkgs = input.parse().toSet() val target = pkgs.sum() / 3 val combos = pkgs.subsetsSummingTo(target) val combosBySize = combos.groupBy { it.size } combosBySize.entries.sortedBy { it.key }.forEach { (count, combos) -> print("Combos of size $count: ${combos.size}") val valid = combos.filter { (pkgs - it.toSet()).dividesIntoGroups(target, 2) } println(", valid: ${valid.size}") if (valid.isNotEmpty()) return valid.minOf { it.fold(1L) { acc, i -> acc * i } } } return -1 } override fun calc2(input: List<String>): Long { val pkgs = input.parse().toSet() val target = pkgs.sum() / 4 val combos = pkgs.subsetsSummingTo(target, maxSize = 7) val combosBySize = combos.groupBy { it.size } combosBySize.entries.sortedBy { it.key }.forEach { (count, combos) -> print("Combos of size $count: ${combos.size}") val valid = combos.filter { (pkgs - it.toSet()).dividesIntoGroups(target, 3) } println(", valid: ${valid.size}") if (valid.isNotEmpty()) return valid.minOf { it.fold(1L) { acc, i -> acc * i } } } return -1 } fun Set<Int>.dividesIntoGroups(target: Int, groups: Int): Boolean { if (groups == 1) return sum() == target else if (groups == 2) return subsetsSummingTo(target).isNotEmpty() else { val s2 = subsetsSummingTo(target) return s2.any { (this - it.toSet()).dividesIntoGroups(target, 2) } } } fun Collection<Int>.subsetsSummingTo(target: Int, maxSize: Int? = null): List<List<Int>> { if (isEmpty()) return listOf() val first = first() val withFirst = when { first < target -> drop(1).subsetsSummingTo(target - first, maxSize?.let { it - 1}).map { it + first } first == target -> listOf(listOf(first)) else -> listOf() } return withFirst + drop(1).subsetsSummingTo(target, maxSize) } }
0
Kotlin
0
0
7b1b1542c4bdcd4329289c06763ce50db7a75a2d
2,544
advent-of-code
Apache License 2.0
advent-of-code-2023/src/main/kotlin/eu/janvdb/aoc2023/day13/day13.kt
janvdbergh
318,992,922
false
{"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335}
package eu.janvdb.aoc2023.day13 import eu.janvdb.aocutil.kotlin.readGroupedLines import kotlin.math.min //const val FILENAME = "input13-test.txt" const val FILENAME = "input13.txt" fun main() { val matrices = readGroupedLines(2023, FILENAME).map { Matrix.parse(it) } val sums1 = matrices.map { it.part1() } println(sums1.sum()) val sums2 = matrices.map { it.part2() } println(sums2.sum()) } data class Matrix(val height: Int, val width: Int, val cells: List<Boolean>) { fun part1(): Int { return findMirrors().sum() } fun part2(): Int { return findMirrorsWhenSmudged().sum() } fun findMirrorsWhenSmudged(): List<Int> { fun replaceCell(index: Int): Matrix { val newCells = cells.toMutableList() newCells[index] = !cells[index] return Matrix(height, width, newCells) } val baseLine = findMirrors().toSet() return cells.indices.asSequence() .map { index -> replaceCell(index) } .map { it.findMirrors().minus(baseLine) } .filter { it.size == 1 } .first() } private fun findMirrors(): List<Int> = findMirrorRows().map { it * 100 } + findMirrorColumns() private fun findMirrorRows(): List<Int> { return (1..<height).filter { isMirroredAtRow(it) } } private fun findMirrorColumns(): List<Int> { return (1..<width).filter { isMirroredAtColumn(it) } } private fun isMirroredAtRow(row: Int): Boolean { val rowsAbove = row val rowsBelow = height - row for (y in 0..<min(rowsAbove, rowsBelow)) { for (x in 1..width) { if (getCell(x, row - y) != getCell(x, row + y + 1)) return false } } return true } private fun isMirroredAtColumn(column: Int): Boolean { val columnsLeft = column val columnsRight = width - column for (x in 0..<min(columnsLeft, columnsRight)) { for (y in 1..height) { if (getCell(column - x, y) != getCell(column + x + 1, y)) return false } } return true } private fun getCell(x: Int, y: Int): Boolean { // we work one-based return cells[(y - 1) * width + x - 1] } companion object { fun parse(input: List<String>): Matrix { val height = input.size val width = input[0].length val cells = input.flatMap { it.map { it == '#' } } return Matrix(height, width, cells) } } }
0
Java
0
0
78ce266dbc41d1821342edca484768167f261752
2,215
advent-of-code
Apache License 2.0
src/day03/Day03.kt
lpleo
572,702,403
false
{"Kotlin": 30960}
package day03 import readInput fun main() { fun part1(input: List<String>): Int { return input .map { rucksack -> arrayOf(rucksack.substring(0, rucksack.length / 2), rucksack.substring((rucksack.length / 2), rucksack.length)) } .map { compartments -> compartments[0].toCharArray().first { character -> compartments[1].toCharArray().contains(character) } } .sumOf { identifier -> if (identifier.isUpperCase()) identifier.code - 'A'.code + 27 else identifier.code - 'a'.code + 1 } } fun part2(input: List<String>): Int { return input .chunked(3) .map { rucksacks -> rucksacks[0].toCharArray().first { charachter -> rucksacks[1].toCharArray().firstOrNull { innerCharacter -> rucksacks[2].toCharArray().contains(charachter) && innerCharacter == charachter } != null } }.sumOf { identifier -> if (identifier.isUpperCase()) identifier.code - 'A'.code + 27 else identifier.code - 'a'.code + 1 } } val testInput = readInput("files/Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("files/Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
115aba36c004bf1a759b695445451d8569178269
1,434
advent-of-code-2022
Apache License 2.0
src/year2022/day05/Day05.kt
lukaslebo
573,423,392
false
{"Kotlin": 222221}
package year2022.day05 import check import readInput import java.util.* fun main() { // test if implementation meets criteria from the description, like: val testInput = readInput("2022", "Day05_test") check(part1(testInput), "CMZ") check(part2(testInput), "MCD") val input = readInput("2022", "Day05") println(part1(input)) println(part2(input)) } private fun part1(input: List<String>): String { val (stacksById, instructions) = parseStacksByIdAndInstructions(input) return executeInstructions( stacksById = stacksById, instructions = instructions ).joinTopElementsToString() } private fun part2(input: List<String>): String { val (stacksById, instructions) = parseStacksByIdAndInstructions(input) return executeInstructions( stacksById = stacksById, instructions = instructions, useCrateMover9001 = true, ).joinTopElementsToString() } private val instructionPattern = "move (?<amount>\\d+) from (?<from>\\d+) to (?<to>\\d+)".toRegex() private data class Instruction( val amount: Int, val from: Int, val to: Int, ) private fun parseStacksByIdAndInstructions(input: List<String>): Pair<Map<Int, Stack<Char>>, List<Instruction>> { val separator = input.indexOfFirst { it.isEmpty() } val stacksById = parseStacksById(input.subList(0, separator)) val instructions = parseInstructions(input.subList(separator + 1, input.size)) return Pair(stacksById, instructions) } private fun parseStacksById(input: List<String>): Map<Int, Stack<Char>> { val reversed = input.reversed() val stackIds = reversed.first().trim().split(" ").map { it.toInt() } val stacksById = stackIds.associateWithTo(LinkedHashMap(stackIds.size)) { Stack<Char>() } for (line in reversed.subList(1, reversed.size)) { for (i in stackIds.indices) { val charIndex = 1 + i * 4 if (line.lastIndex < charIndex) break val stackId = stackIds[i] val stack = stacksById[stackId]!! val char = line[charIndex] if (char != ' ') stack += char } } return stacksById } private fun parseInstructions(input: List<String>): List<Instruction> { return input.map { line -> val groups = instructionPattern.find(line)!!.groups val amount = groups["amount"]!!.value.toInt() val from = groups["from"]!!.value.toInt() val to = groups["to"]!!.value.toInt() Instruction( amount = amount, from = from, to = to, ) } } private fun executeInstructions( stacksById: Map<Int, Stack<Char>>, instructions: List<Instruction>, useCrateMover9001: Boolean = false, ): Map<Int, Stack<Char>> { for (instruction in instructions) { val from = stacksById[instruction.from]!! val to = stacksById[instruction.to]!! if (useCrateMover9001) { val temp = Stack<Char>() repeat(instruction.amount) { temp += from.pop() } repeat(instruction.amount) { to += temp.pop() } } else { repeat(instruction.amount) { to += from.pop() } } } return stacksById } private fun Map<Int, Stack<Char>>.joinTopElementsToString() = values.map { it.peek() }.joinToString("")
0
Kotlin
0
1
f3cc3e935bfb49b6e121713dd558e11824b9465b
3,315
AdventOfCode
Apache License 2.0
solutions/round1/B/subtransmutation/src/main/kotlin/subtransmutation/SubtransmutationSolution.kt
Lysoun
351,224,145
false
null
import java.lang.Integer.max data class ProblemInput(val metalTypesNumber: Int, val spells: List<Int>, val unitsRequired: List<Int>) fun main(args: Array<String>) { val casesNumber = readLine()!!.toInt() for (i in 1..casesNumber) { val line1 = readLine()!!.split(" ").map { it.toInt() } val line2 = readLine()!!.split(" ").map { it.toInt() } println( "Case #$i: ${ findSmallestMetalToProduceAllRequiredUnits( ProblemInput( line1[0], line1.subList(1, 3), line2 ) ) }" ) } } fun applySpells(spells: List<Int>, metal: Int): List<Int> = spells.map { metal - it }.filter { it >= 0 } fun applySpells(spells:List<Int>, metalUnits: MutableList<Int>, unitsRequired: List<Int>): MutableList<Int> { var found = false var biggestMetalToTransmutate = metalUnits.size - 1 while(biggestMetalToTransmutate >= 0 && ! found) { if(metalUnits[biggestMetalToTransmutate] > 0 && (biggestMetalToTransmutate >= unitsRequired.size || metalUnits[biggestMetalToTransmutate] > unitsRequired[biggestMetalToTransmutate])) { found = true } else { --biggestMetalToTransmutate } } if (biggestMetalToTransmutate < 0) { return metalUnits } applySpells(spells, biggestMetalToTransmutate).forEach { ++metalUnits[it] } --metalUnits[biggestMetalToTransmutate] return metalUnits } const val IMPOSSIBLE = "IMPOSSIBLE" fun findSmallestMetalToProduceAllRequiredUnits(problemInput: ProblemInput): String { if(problemInput.spells.all { it % 2 == 0 } && problemInput.unitsRequired.filterIndexed {index: Int, i: Int -> index % 2 == 1 && i > 0 }.isNotEmpty()) { return IMPOSSIBLE } var i = 0 var found = false while(!found) { var lastMetalUnits: List<Int> = listOf() var metalUnits = MutableList(max(problemInput.metalTypesNumber, i + 1)) { if(it == i) { 1 } else { 0 } } while(lastMetalUnits != metalUnits && !found) { if (metalUnits .filterIndexed {index: Int, i: Int -> index < problemInput.metalTypesNumber && i < problemInput.unitsRequired[index] } .isEmpty()) { found = true } if(!found) { lastMetalUnits = metalUnits.toList() metalUnits = applySpells(problemInput.spells, metalUnits, problemInput.unitsRequired) } } if(!found) { ++i } } return (i + 1).toString() }
0
Kotlin
0
0
98d39fcab3c8898bfdc2c6875006edcf759feddd
2,803
google-code-jam-2021
MIT License
2022/src/main/kotlin/day19.kt
madisp
434,510,913
false
{"Kotlin": 388138}
import Day19.Resource.geode import Day19.Resource.ore import utils.Component4 import utils.Parser import utils.Solution import utils.Vec4i import utils.cut import utils.mapItems fun main() { Day19.run() } object Day19 : Solution<List<Day19.Blueprint>>() { override val name = "day19" override val parser = Parser.lines.mapItems { line -> val robots = line.cut(":").second.split(".").map { it.trim() }.filter { it.isNotBlank() } val bpmap = robots.associate { costLine -> val type = Resource.valueOf(costLine.removePrefix("Each").trim().split(" ", limit = 2).first()) val costs = costLine.split("costs", limit = 2).last().trim().split("and").map { it.trim() } type to costs.map { val (cost, resname) = it.split(" ", limit = 2) Resource.valueOf(resname).v * cost.toInt() }.reduce { a, b -> a + b } } Blueprint(bpmap) } enum class Resource(val c: Component4, val v: Vec4i) { ore(Component4.X, Vec4i(1, 0, 0, 0)), clay(Component4.Y, Vec4i(0, 1, 0, 0)), obsidian(Component4.Z, Vec4i(0, 0, 1, 0)), geode(Component4.W, Vec4i(0, 0, 0, 1)), } data class Blueprint(val costs: Map<Resource, Vec4i>) { fun computeMaxRobots() = Vec4i( costs.values.maxOf { it.x }, costs.values.maxOf { it.y }, costs.values.maxOf { it.z }, Integer.MAX_VALUE, // produce as many geode bots as possible ) } class Context( val bp: Blueprint, val cache: MutableMap<State, Int>, val maxRobots: Vec4i, val maxTime: Int, val maxGeodeBotsAt: IntArray, ) data class State(val timePassed: Int, val robots: Vec4i, val resources: Vec4i) { companion object { val INITIAL = State( timePassed = 0, robots = ore.v, // 1 ore only resources = Vec4i(0, 0, 0, 0), // all zero ) } } private fun step(blueprint: Blueprint, state: State, buildRobot: Resource? = null): State { return state.copy( timePassed = state.timePassed + 1, robots = if (buildRobot == null) state.robots else state.robots + buildRobot.v, resources = (if (buildRobot == null) state.resources else state.resources - blueprint.costs[buildRobot]!!) + state.robots ) } private val Vec4i.isPositive: Boolean get() = x >= 0 && y >= 0 && z >= 0 && w >= 0 private fun bestGeodes(ctx: Context, state: State): Int { val cached = ctx.cache[state] if (cached != null) { return cached } if (state.timePassed == ctx.maxTime) { return state.resources[geode.c] } val maxGBots = ctx.maxGeodeBotsAt[state.timePassed] if (state.robots.w < maxGBots - 1) { return 0 // not worth exploring as we are so much behind } else if (state.robots.w > maxGBots) { ctx.maxGeodeBotsAt[state.timePassed] = state.robots.w } // choose which robot to build val opts = Resource.values().reversed().filter { (state.resources - ctx.bp.costs[it]!!).isPositive && state.robots[it.c] < ctx.maxRobots[it.c] } + null // if you can build a geode bot, greedily build it? val geodes = if (opts.first() == geode) { bestGeodes(ctx, step(ctx.bp, state, geode)) } else { opts.maxOf { bestGeodes(ctx, step(ctx.bp, state, it)) } } ctx.cache[state] = geodes return geodes } override fun part1(input: List<Blueprint>): Int { return input.mapIndexed { idx, bp -> idx to bp }.parallelStream().map { (idx, bp) -> val ctx = Context(bp, HashMap(), bp.computeMaxRobots(), 24, IntArray(24) { 0 }) (idx + 1) * bestGeodes(ctx, State.INITIAL) }.reduce { a, b -> a + b }.get() } override fun part2(input: List<Blueprint>): Int { return input.take(3).parallelStream().map { bp -> val ctx = Context(bp, HashMap(), bp.computeMaxRobots(), 32, IntArray(32) { 0 }) bestGeodes(ctx, State.INITIAL) }.reduce { a, b -> a * b }.get() } }
0
Kotlin
0
1
3f106415eeded3abd0fb60bed64fb77b4ab87d76
3,898
aoc_kotlin
MIT License
src/commonMain/kotlin/com/jwoolston/cluster/RankOrderCluster.kt
jwoolston
288,544,510
false
null
package com.jwoolston.cluster import kotlin.math.min fun <V : Number> clusterOrderedList(cluster: Cluster<V>, clusters: List<Cluster<V>>): List<Cluster<V>> { return clusters.sortedBy { cluster.distance(it) } } /** * Calculates the asymmetric rank order distance between two clusters as described in Equation 1 */ fun <V : Number> asymmetricRankOrderDistance( cluster_j: Cluster<V>, order_i: List<Cluster<V>>, order_j: List<Cluster<V>> ): Int { val stopIndex = order_i.indexOf(cluster_j) var accumulator = 0 for (i in 0 until stopIndex) { // We can safely skip stop index because it should always be index 0 of orderB val index = order_j.indexOf(order_i[i]) accumulator += index } return accumulator } /** * Calculates the asymmetric rank order distance between two clusters as described in Equation 1 */ fun <V : Number> clusterRankOrderDistance( cluster_i: Cluster<V>, cluster_j: Cluster<V>, order_i: List<Cluster<V>>, order_j: List<Cluster<V>> ): Double { // Find the asymmetric rank order distance between cluster a and b val asym_ij = asymmetricRankOrderDistance(cluster_j, order_i, order_j) val asym_ji = asymmetricRankOrderDistance(cluster_i, order_j, order_i) val min_cluster_order = min(order_i.indexOf(cluster_j), order_j.indexOf(cluster_i)) return (asym_ij + asym_ji).toDouble() / min_cluster_order } /** * Calculates the inverse of the average distance of nodes in two clusters to their top K neighbors from the full * dataset as described in Equation 5. * * The inverse is returned to save one double precision floating point division by the consumer. */ fun <V : Number> kNeighborAverage(cluster_i: Cluster<V>, cluster_j: Cluster<V>, globalNodes: Set<Node<V>>, k: Int): Double { // The set of nodes present in either or both clusters val nodes = cluster_i.elements.union(cluster_j.elements) // Find the average distance between the K nearest nodes by finding all the distances, sorting the distances // then summing the K nearest distances as described in equation 5. val denom = nodes.fold(0.0, { acc, node -> val sorted = globalNodes.map { node.distance(it) }.sorted() val sum = sorted.subList(1, min(globalNodes.size, k)).sum() acc + (sum / k) }) return ((cluster_i.elements.size + cluster_j.elements.size) / denom) } fun <V> transitiveMerge(sets: Set<Set<V>>): Set<Set<V>> { val copy = sets.toMutableList() val size = sets.size val consolidated = BooleanArray(size) // all false by default var i = 0 while (i < size - 1) { if (!consolidated[i]) { while (true) { var intersects = 0 for (j in (i + 1) until size) { if (consolidated[j]) continue if (copy[i].intersect(copy[j]).isNotEmpty()) { copy[i] = copy[i].union(copy[j]) consolidated[j] = true intersects++ } } if (intersects == 0) break } } i++ } return (0 until size).filter { !consolidated[it] }.map { copy[it].toSet() }.toSet() } class RankOrderCluster<T : Number>(private val threshold: Double, private val topNeighborCount: Int) { private val nodes: MutableSet<Node<T>> = mutableSetOf() fun addNode(node: Node<T>): List<Cluster<T>> { nodes.add(node) return update() } fun addNodes(nodes: Collection<Node<T>>): List<Cluster<T>> { this.nodes.addAll(nodes) return update() } private fun update(): List<Cluster<T>> { // Create clusters for each node var clusters = nodes.map { Cluster(listOf(it)) } var iterate = true while (iterate) { // Compute the order lists for each cluster val orderLists = mutableMapOf<Cluster<T>, List<Cluster<T>>>() for (cluster in clusters) { orderLists[cluster] = clusterOrderedList(cluster, clusters) } val mergeCandidates = mutableSetOf<Set<Node<T>>>() // For each pair of clusters for (cluster_i in clusters) { for (cluster_j in clusters) { if (cluster_i == cluster_j) continue val rodCluster = clusterRankOrderDistance(cluster_i, cluster_j, orderLists[cluster_i]!!, orderLists[cluster_j]!!) val kNeighborAvg = kNeighborAverage(cluster_i, cluster_j, nodes, topNeighborCount) val lndCluster = kNeighborAvg * cluster_i.distance(cluster_j) if (rodCluster < threshold && lndCluster < 1.0) { mergeCandidates.add(mutableSetOf(*cluster_i.elements.toTypedArray(), *cluster_j.elements.toTypedArray())) } else { mergeCandidates.add(mutableSetOf(*cluster_i.elements.toTypedArray())) mergeCandidates.add(mutableSetOf(*cluster_j.elements.toTypedArray())) } } } val merged = transitiveMerge(mergeCandidates) if (mergeCandidates.size == merged.size) { // No merge happened, this is fully clustered iterate = false } // Update the cluster list and possibly iterate clusters = merged.map { Cluster(it) } } return clusters } }
0
Kotlin
0
0
837da7f2add2c7fb29da1d93029ab4279eacb2e5
5,542
RankOrderCluster
Apache License 2.0
src/Day25.kt
MartinsCode
572,817,581
false
{"Kotlin": 77324}
import kotlin.math.pow fun digitValue(sign: Char): Long { return when (sign) { '0' -> 0L '1' -> 1L '2' -> 2L '-' -> -1L '=' -> -2L else -> 0L } } fun desnafuify(snafu: String): Long { val snafuDigits = snafu.toCharArray() var value = 0L for (i in 0..snafuDigits.lastIndex) { value += (digitValue(snafuDigits[i]) * 5.0.pow(snafuDigits.lastIndex - i)).toLong() } return value } fun snafu(digit: Long): String = when (digit) { 2L -> "2" 1L -> "1" 0L -> "0" -1L -> "-" -2L -> "=" else -> "..." } fun snafuify(decimal: Long): String { var value = decimal // list of the digits. First entry is lowest(!) value, so it's written backwards val snafuRepresentation = mutableListOf<Long>() while (value > 0L) { snafuRepresentation.lastIndex var remainder = value % 5 remainder = when (remainder) { 4L -> { value += 1 -1 } 3L -> { value += 2 -2 } else -> remainder } snafuRepresentation.add(remainder) value /= 5 } println(snafuRepresentation) return snafuRepresentation.map{ snafu(it) }.reversed().joinToString("") } fun main() { fun part1(input: List<String>): String { var sum = 0L input.forEach { sum += desnafuify(it) } return snafuify(sum) } fun part2(input: List<String>): Int { return input.size } // test if implementation meets criteria from the description, like: val testInput = readInput("Day25-TestInput") println(part1(testInput)) check(part1(testInput) == "2=-1=0") // check(part2(testInput) == 0) val input = readInput("Day25-Input") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
1aedb69d80ae13553b913635fbf1df49c5ad58bd
1,900
AoC-2022-12-01
Apache License 2.0
src/commonMain/kotlin/ai/hypergraph/kaliningraph/types/Types.kt
breandan
245,074,037
false
{"Kotlin": 1482924, "Haskell": 744, "OCaml": 200}
package ai.hypergraph.kaliningraph.types /** Corecursive Fibonacci sequence of [Nat]s **/ tailrec fun <T> Nat<T>.fibonacci( n: T, seed: V2<T> = nil cc one, fib: (V2<T>) -> V2<T> = { (a, b) -> b cc a + b }, i: T = nil, ): T = if (i == n) fib(seed).first else fibonacci(n = n, seed = fib(seed), i = i.next()) /** Returns [n]! **/ fun <T> Nat<T>.factorial(n: T): T = prod(seq(to = n.next())) /** Returns a sequence of [Nat]s starting from [from] until [to] **/ tailrec fun <T> Nat<T>.seq( from: T = one, to: T, acc: Set<T> = emptySet() ): Set<T> = if (from == to) acc else seq(from.next(), to, acc + from) /** Returns true iff [t] is prime **/ fun <T> Nat<T>.isPrime(t: T, kps: Set<T> = emptySet()): Boolean = // Take Cartesian product, filter distinct pairs due to commutativity (if (kps.isNotEmpty()) kps * kps else seq(to = t) * seq(to = t)) .distinctBy { (l, r) -> setOf(l, r) } .all { (i, j) -> if (i == one || j == one) true else i * j != t } /** Returns [total] prime [Nat]s **/ tailrec fun <T> Nat<T>.primes( total: T, // total number of primes i: T = nil, // counter c: T = one.next(), // prime candidate kps: Set<T> = emptySet() // known primes ): Set<T> = when { i == total -> kps isPrime(c) -> primes(total, i.next(), c.next(), kps + c) else -> primes(total, i, c.next(), kps) } /** Returns the sum of two [Nat]s **/ tailrec fun <T> Nat<T>.plus(l: T, r: T, acc: T = l, i: T = nil): T = if (i == r) acc else plus(l, r, acc.next(), i.next()) /** Returns the product of two [Nat]s **/ tailrec fun <T> Nat<T>.times(l: T, r: T, acc: T = nil, i: T = nil): T = if (i == r) acc else times(l, r, acc + l, i.next()) tailrec fun <T> Nat<T>.pow(base: T, exp: T, acc: T = one, i: T = one): T = if (i == exp) acc else pow(base, exp, acc * base, i.next()) fun <T> Nat<T>.sum(list: Iterable<T>): T = list.reduce { acc, t -> acc + t } fun <T> Nat<T>.prod(list: Iterable<T>): T = list.reduce { acc, t -> (acc * t) } interface Nat<T> { val nil: T val one: T get() = nil.next() fun T.next(): T // TODO: implement pred, minus? // https://en.wikipedia.org/wiki/Church_encoding#Derivation_of_predecessor_function operator fun T.plus(t: T) = plus(this, t) operator fun T.times(t: T) = times(this, t) infix fun T.pow(t: T) = pow(this, t) class of<T>(override val nil: T, val vnext: T.() -> T): Nat<T> { override fun T.next(): T = vnext() } } interface Group<T>: Nat<T> { override fun T.next(): T = this + one override fun T.plus(t: T): T class of<T>( override val nil: T, override val one: T, val plus: T.(T, T) -> T ): Group<T> { override fun T.plus(t: T) = plus(this, t) } } interface Ring<T>: Group<T> { override fun T.plus(t: T): T override fun T.times(t: T): T open class of<T>( override val nil: T, override val one: T = nil, val plus: T.(T, T) -> T, val times: T.(T, T) -> T ): Ring<T> { override fun T.plus(t: T) = plus(this, t) override fun T.times(t: T) = times(this, t) } } @Suppress("NO_TAIL_CALLS_FOUND") /** Returns the result of subtracting two [Field]s **/ tailrec fun <T> Field<T>.minus(l: T, r: T, acc: T = nil, i: T = nil): T = TODO() @Suppress("NO_TAIL_CALLS_FOUND") /** Returns the result of dividing of two [Field]s **/ tailrec fun <T> Field<T>.div(l: T, r: T, acc: T = l, i: T = nil): T = TODO() interface Field<T>: Ring<T> { operator fun T.minus(t: T): T = minus(this, t) operator fun T.div(t: T): T = div(this, t) class of<T>( override val nil: T, override val one: T, val plus: T.(T, T) -> T, val times: T.(T, T) -> T, val minus: T.(T, T) -> T, val div: T.(T, T) -> T ): Field<T> { override fun T.plus(t: T) = plus(this, t) override fun T.times(t: T) = times(this, t) override fun T.minus(t: T) = minus(this, t) override fun T.div(t: T) = div(this, t) } } interface Vector<T> { val ts: List<T> fun vmap(map: (T) -> T) = of(ts.map { map(it) }) fun zip(other: Vector<T>, merge: (T, T) -> T) = of(ts.zip(other.ts).map { (a, b) -> merge(a, b) }) class of<T>(override val ts: List<T>): Vector<T> { constructor(vararg ts: T): this(ts.toList()) override fun toString() = ts.joinToString(",", "${ts::class.simpleName}[", "]") } } interface VectorField<T, F: Field<T>> { val f: F operator fun Vector<T>.plus(vec: Vector<T>): Vector<T> = zip(vec) { a, b -> with(f) { a + b } } infix fun T.dot(p: Vector<T>): Vector<T> = p.vmap { f.times(it, this) } class of<T, F: Field<T>>(override val f: F): VectorField<T, F> } // TODO: Clifford algebra? // http://www.math.ucsd.edu/~alina/oldcourses/2012/104b/zi.pdf data class GaussInt(val a: Int, val b: Int) { operator fun plus(o: GaussInt): GaussInt = GaussInt(a + o.a, b + o.b) operator fun times(o: GaussInt): GaussInt = GaussInt(a * o.a - b * o.b, a * o.b + b * o.a) } class Rational { constructor(i: Int, j: Int = 1) { if (j == 0) throw ArithmeticException("Denominator must not be zero!") canonicalRatio = reduce(i, j) a = canonicalRatio.first b = canonicalRatio.second } private val canonicalRatio: V2<Int> /** * TODO: Use [Nat] instead? */ val a: Int val b: Int operator fun times(r: Rational) = Rational(a * r.a, b * r.b) operator fun plus(r: Rational) = Rational(a * r.b + r.a * b, b * r.b) operator fun minus(r: Rational) = Rational(a * r.b - r.a * b, b * r.b) operator fun div(r: Rational) = Rational(a * r.b, b * r.a) override fun toString() = "$a/$b" override fun equals(other: Any?) = (other as? Rational).let { a == it!!.a && b == it.b } override fun hashCode() = toString().hashCode() companion object { val ZERO = Rational(0, 1) val ONE = Rational(1, 1) fun reduce(a: Int, b: Int) = a / a.gcd(b) cc b / a.gcd(b) // https://github.com/binkley/kotlin-rational/blob/61be6f7df2d579ad83c6810a5f9426a4478b99a2/src/main/kotlin/hm/binkley/math/math-functions.kt#L93 private tailrec fun Int.gcd(that: Int): Int = when { this == that -> this this in 0..1 || that in 0..1 -> 1 this > that -> (this - that).gcd(that) else -> gcd(that - this) } } }
0
Kotlin
8
100
c755dc4858ed2c202c71e12b083ab0518d113714
6,161
galoisenne
Apache License 2.0
src/Day09.kt
Akhunzaada
573,119,655
false
{"Kotlin": 23755}
import java.lang.Exception import kotlin.math.abs data class Point(var x: Int, var y: Int) { infix fun moveTo(delta: Point) { x += delta.x y += delta.y } infix fun follow(point: Point) { if (abs(x-point.x) > 1 || abs(y-point.y) > 1) { x += if (x < point.x) +1 else if (x > point.x) -1 else 0 y += if (y < point.y) +1 else if (y > point.y) -1 else 0 } } } fun main() { fun String.direction(): Pair<Point, Int> { val (direction, steps) = split(' ') val delta = when (direction) { "L" -> Point(-1, 0) "U" -> Point(0, -1) "R" -> Point(1, 0) "D" -> Point(0, 1) else -> throw Exception("Invalid Direction!") } return Pair(delta, steps.toInt()) } fun List<String>.directions(move: (delta: Point) -> Unit) { forEach { it.direction().let { (delta, steps) -> repeat(steps) { move(delta) } } } } fun positionsVisitedByTail(input: List<String>, ropeKnots: Int): Int { val visited = mutableSetOf<Point>() val knots = MutableList(ropeKnots) { Point(0, 0) } input.directions { knots.first() moveTo it knots.windowed(2) { it.component2() follow it.component1() } visited.add(knots.last().copy()) } return visited.count() } fun part1(input: List<String>) = positionsVisitedByTail(input, 2) fun part2(input: List<String>) = positionsVisitedByTail(input, 10) // test if implementation meets criteria from the description, like: val testInput = readInput("Day09_test") check(part1(testInput) == 13) check(part2(testInput) == 1) val testInput2 = readInput("Day09_test2") check(part2(testInput2) == 36) val input = readInput("Day09") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
b2754454080989d9579ab39782fd1d18552394f0
1,995
advent-of-code-2022
Apache License 2.0
src/Day02.kt
peterfortuin
573,120,586
false
{"Kotlin": 22151}
fun main() { fun part1(input: List<String>): Int { return input.map { rps -> when (rps) { "A X" -> 3 + 1// Rock rock "A Y" -> 6 + 2// Rock paper "A Z" -> 0 + 3// Rock scissors "B X" -> 0 + 1// Paper rock "B Y" -> 3 + 2// Paper paper "B Z" -> 6 + 3// Paper scissors "C X" -> 6 + 1// Scissors rock "C Y" -> 0 + 2// Scissors paper "C Z" -> 3 + 3// Scissors scissors else -> 0 } }.sum() } fun part2(input: List<String>): Int { return input.map { rps -> when (rps) { "A X" -> 0 + 3// Rock lose scissors "A Y" -> 3 + 1// Rock draw rock "A Z" -> 6 + 2// Rock win paper "B X" -> 0 + 1// Paper lose rock "B Y" -> 3 + 2// Paper draw paper "B Z" -> 6 + 3// Paper win scissors "C X" -> 0 + 2// Scissors lose paper "C Y" -> 3 + 3// Scissors draw scissors "C Z" -> 6 + 1// Scissors win rock else -> 0 } }.sum() } // 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("Part 1 = ${part1(input)}") println("Part 2 = ${part2(input)}") }
0
Kotlin
0
0
c92a8260e0b124e4da55ac6622d4fe80138c5e64
1,526
advent-of-code-2022
Apache License 2.0
src/main/kotlin/be/tabs_spaces/advent2021/days/Day15.kt
janvryck
433,393,768
false
{"Kotlin": 58803}
package be.tabs_spaces.advent2021.days import java.util.* class Day15 : Day(15) { override fun partOne() = Cave(inputList).lowestRiskPath(Point(0, 0)) override fun partTwo() = Cave(inputList, expand = true).lowestRiskPath(Point(0, 0)) class Cave(rawInput: List<String>, expand: Boolean = false) { private val riskLevelsByPoint = rawInput.indices .flatMap { y -> rawInput[y].indices.map { x -> Point(x, y) } } .associateWith { point -> rawInput[point.y][point.x].digitToInt() } .let { if (expand) it.expand() else it } private val xMax by lazy { riskLevelsByPoint.keys.maxOf { it.x } } private val yMax by lazy { riskLevelsByPoint.keys.maxOf { it.y } } fun lowestRiskPath(origin: Point): Int { val accumulatedRisk = mutableMapOf<Point, Int>() val visited = mutableSetOf(origin) val visiting = PriorityQueue<Point> { left, right -> (accumulatedRisk[left] ?: Int.MAX_VALUE).compareTo(accumulatedRisk[right] ?: Int.MAX_VALUE) } visiting.add(origin) while (visiting.isNotEmpty()) { visiting.poll() .also { visited.add(it) } .let { risksForNeighboursOf(it, accumulatedRisk[it] ?: 0) } .filterNot { (neighbour, _) -> visited.contains(neighbour) } .filter { (neighbour, risk) -> risk < (accumulatedRisk[neighbour] ?: Int.MAX_VALUE) } .forEach { (neighbour, risk) -> accumulatedRisk[neighbour] = risk visiting.add(neighbour) } } return accumulatedRisk[Point(xMax, yMax)]!! } private fun risksForNeighboursOf(point: Point, cost: Int) = point.neighbours(xMax, yMax) .map { current -> current to cost + riskLevelsByPoint[current]!! } private fun Map<Point, Int>.expand(): Map<Point, Int> { val xMax = keys.maxOf { it.x } val yMax = keys.maxOf { it.y } return (0 until 5).flatMap { offsetX -> (0 until 5).flatMap { offsetY -> entries.map { val (x, y) = it.key val offsetRisk = offsetX + offsetY + it.value val newRisk = if (offsetRisk > 9) offsetRisk - 9 else offsetRisk Point(x = x + offsetX * (xMax + 1), y = y + offsetY * (yMax + 1)) to newRisk } } }.toMap() } } data class Point(val x: Int, val y: Int) { fun neighbours(xMax: Int, yMax: Int) = listOf(x - 1, x + 1).filter { it in 0..xMax }.map { Point(it, y) } + listOf(y - 1, y + 1).filter { it in 0..yMax }.map { Point(x, it) } } }
0
Kotlin
0
0
f6c8dc0cf28abfa7f610ffb69ffe837ba14bafa9
2,829
advent-2021
Creative Commons Zero v1.0 Universal
src/Utils.kt
drademacher
725,945,859
false
{"Kotlin": 76037}
import kotlin.io.path.Path import kotlin.io.path.readLines import kotlin.io.path.readText import kotlin.math.abs import kotlin.math.sqrt fun readLines( year: String, day: String, ) = Path("src/year$year/resources/$day.txt").readLines() fun readFile( year: String, day: String, ) = Path("src/year$year/resources/$day.txt").readText() fun getPrimeTester(n: Int): (Int) -> Boolean { val sieve = BooleanArray(n / 3 + 1) { it != 0 } fun inWheel(k: Int) = k % 6 == 1 || k % 6 == 5 fun toWheel(k: Int) = k / 3 (1..sqrt(n.toDouble()).toInt() step 2) .filter { inWheel(it) && sieve[toWheel(it)] } .forEach { i -> (i * i..n step i).filter { inWheel(it) }.forEach { j -> sieve[toWheel(j)] = false } } return { it -> it == 2 || it == 3 || (it in 1..n && inWheel(it) && sieve[toWheel(it)]) } } fun getPrimesBelow(n: Int): List<Int> { val primeTester = getPrimeTester(n) return (1..n).filter(primeTester) } fun powerOfTwo(n: Int) = 1 shl n fun nthRightBinaryDigitIsOne( x: Int, n: Int, ) = x and (1 shl n) != 0 data class Point(val x: Int, val y: Int) { fun add(other: Point): Point = Point(this.x + other.x, this.y + other.y) fun manhattenDistance(other: Point) = abs(x - other.x) + abs(y - other.y) } enum class Direction { NORTH, EAST, SOUTH, WEST, ; fun toPoint() = when (this) { NORTH -> Point(0, -1) EAST -> Point(1, 0) SOUTH -> Point(0, 1) WEST -> Point(-1, 0) } }
0
Kotlin
0
0
4c4cbf677d97cfe96264b922af6ae332b9044ba8
1,535
advent_of_code
MIT License
src/Day04/Day04.kt
ctlevi
578,257,705
false
{"Kotlin": 10889}
fun main() { fun parseElfPair(row: String): Pair<Set<Int>, Set<Int>> { val (first, second) = row.split(',') val (firstOne, firstTwo) = first.split('-') val firstElfRange = (firstOne.toInt()..firstTwo.toInt()).toSet() val (secondOne, secondTwo) = second.split('-') val secondElfRange = (secondOne.toInt()..secondTwo.toInt()).toSet() return Pair(firstElfRange, secondElfRange) } fun part1(input: List<String>): Int { var count = 0 for (row in input) { val (firstElfRange, secondElfRange) = parseElfPair(row) val intersectionSize = firstElfRange.intersect(secondElfRange).size if (intersectionSize == firstElfRange.size || intersectionSize == secondElfRange.size) { count += 1 } } return count } fun part2(input: List<String>): Int { var count = 0 for (row in input) { val (firstElfRange, secondElfRange) = parseElfPair(row) val intersectionSize = firstElfRange.intersect(secondElfRange).size if (intersectionSize > 0) { count += 1 } } return count } val testInput = readInput("Day04/test") val testResult = part1(testInput) "Test Result: ${testResult}".println() val input = readInput("Day04/input") "Part 1 Result: ${part1(input)}".println() "Part 2 Result: ${part2(input)}".println() }
0
Kotlin
0
0
0fad8816e22ec0df9b2928983713cd5c1ac2d813
1,480
advent_of_code_2022
Apache License 2.0
src/y2015/Day07.kt
gaetjen
572,857,330
false
{"Kotlin": 325874, "Mermaid": 571}
package y2015 import util.readInput data class Signal( val instruction: String, var result: UShort? = null ) { fun update(result: UShort): UShort { this.result = result return result } } fun lShift(x: UShort, y: Int) : UShort { return x.rotateLeft(y) and (UShort.Companion.MAX_VALUE - ones(y)).toUShort() } fun rShift(x: UShort, y: Int): UShort { return x.rotateRight(y) and ones((16 - y)) } fun ones(x: Int): UShort { var result = 2 repeat(x - 1) { result *= 2 } return (result - 1).toUShort() } object Day07 { private fun parse(input: List<String>): Map<String, Signal> { return input.map { it.split(" -> ") }.associate { it.last() to Signal(it.first()) } } fun part1(input: List<String>): UShort { val signals = parse(input) signals.forEach { println("${it.key}: ${evaluate(signals, it.key)}") } return evaluate(signals, signals.keys.minOf { it }) } private fun evaluate(signals: Map<String, Signal>, id: String): UShort { if (id == "1") { return 1.toUShort() } if (signals[id] == null) { println("no thing: $id") } val signal = signals[id]!! if (signal.result != null) { return signal.result!! } val instructions = signal.instruction.split(' ') if (instructions.size == 1) { return signal.update(instructions.first().toUShort()) } if (instructions.size == 2) { return signal.update(evaluate(signals, instructions.last()).inv()) } return when (instructions[1]) { "LSHIFT" -> signal.update(lShift( evaluate(signals, instructions.first()), instructions.last().toInt() )) "RSHIFT" -> signal.update(rShift( evaluate(signals, instructions.first()), instructions.last().toInt() )) "OR" -> signal.update(evaluate(signals, instructions.first()) or evaluate(signals, instructions.last())) else -> signal.update(evaluate(signals, instructions.first()) and evaluate(signals, instructions.last())) } } fun part2(input: List<String>): UShort { val signals = parse(input) signals["b"]!!.result = 46065.toUShort() return evaluate(signals, signals.keys.minOf { it }) } } fun main() { val testInput = """ 543 -> a 53 -> b 123 -> x 456 -> y x AND y -> d x OR y -> e x LSHIFT 2 -> f y RSHIFT 2 -> g NOT x -> h NOT y -> i """.trimIndent().split("\n") println("------Tests------") println(Day07.part1(testInput)) println(Day07.part2(testInput)) println("------Real------") val input = readInput("resources/2015/day07") println(Day07.part1(input)) println(Day07.part2(input)) }
0
Kotlin
0
0
d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a
3,007
advent-of-code
Apache License 2.0
2022/src/test/kotlin/Day13.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.min private data class Packet(val integer: Int?, val packets: List<Packet>?) : Comparable<Packet> { constructor() : this (null, null) constructor(integer: Int) : this (integer, null) constructor(packets: List<Packet>) : this (null, packets) companion object { fun parse(packet: String): Packet { if (packet.isEmpty()) return Packet() if (packet == "[]") return Packet(listOf(Packet())) packet.toIntOrNull()?.let { return Packet(it) } return generateSequence(1) { start -> if (start >= packet.length) null else { val part = packet.drop(start) val length = if (packet[start] == '[') part.indexOfClosingBracket() else part.indexOfOrNull(',') ?: part.length.dec() start + length + 1 } } .toList() .zipWithNext() .map { (start, end) -> packet.drop(start).take(end - start - 1) } .map { token -> parse(token) } .let { Packet(it) } } fun wrap(integer: Int) = Packet(listOf(Packet(integer))) } override operator fun compareTo(other: Packet): Int { if (isValue() && other.isContainer()) return wrap(integer!!).compareTo(other) if (isContainer() && other.isValue()) return this.compareTo(wrap(other.integer!!)) if (isValue() && other.isValue()) return integer!!.compareTo(other.integer!!) if (!isEmpty() && other.isEmpty()) return 1 if (isEmpty() && !other.isEmpty()) return -1 if (isContainer() && other.isContainer()) { (0 until min(packets!!.size, other.packets!!.size)).forEach { if (other.packets[it] < packets[it]) return 1 if (packets[it] < other.packets[it]) return -1 } if (packets.size != other.packets.size) return packets.size.compareTo(other.packets.size) } return 0 } private fun isEmpty() = integer == null && packets == null private fun isContainer() = integer == null && packets != null private fun isValue() = integer != null && packets == null } class Day13 : StringSpec({ "puzzle part 01" { val indicesSum = getPuzzleInput("day13-input.txt", "$eol$eol") .map { pair -> pair.split(eol).let { Packet.parse(it.first()) to Packet.parse(it.last()) } } .toList().withIndex() .map { if (it.value.first < it.value.second) it.index + 1 else 0 } indicesSum.sum() shouldBe 5623 } "puzzle part 02" { val packet1 = Packet.parse("[[2]]") val packet2 = Packet.parse("[[6]]") val sortedPackets = getPuzzleInput("day13-input.txt") .mapNotNull { if (it.isNotBlank()) Packet.parse(it) else null } .plus(listOf(packet1, packet2)) .toList() .sorted().withIndex() val key1 = sortedPackets.single { it.value == packet1 }.index + 1 val key2 = sortedPackets.single { it.value == packet2 }.index + 1 key1 * key2 shouldBe 20570 } })
0
Kotlin
1
2
8bc5e92ce961440e011688319e07ca9a4a86d9c9
3,360
adventofcode
MIT License
src/main/kotlin/be/swsb/aoc2021/day4/Day4.kt
Sch3lp
433,542,959
false
{"Kotlin": 90751}
package be.swsb.aoc2021.day4 import java.util.* object Day4 { fun solve1(input: List<String>): Int { return solve(input).first().let { (board, winningNumber) -> board.findUnmarked().sum() * winningNumber } } fun solve2(input: List<String>): Int { return solve(input).last().let { (board, number) -> board.findUnmarked().sum() * number } } private fun solve(input: List<String>): List<Pair<BingoBoard, Int>> { val randomlyDrawnNumbers: List<Int> = input[0].split(",").map { it.toInt() } val bingoBoards: List<BingoBoard> = input.drop(2) .filterNot { it.isBlank() } .windowed(5, 5) .map { parseToBingoBoard(it) } val winningBoards = mutableMapOf<UUID, Pair<BingoBoard, Int>>() randomlyDrawnNumbers.forEach { number -> bingoBoards.map { bingoBoard -> if (bingoBoard.findAndMark(number)) { winningBoards.putIfAbsent(bingoBoard.id, bingoBoard to number) } } } return winningBoards.values.toList() } } fun parseToBingoBoard(input: List<String>): BingoBoard { return BingoBoard(rows = input.map { rowLine -> Row(*rowLine.split(" ").filter { it.isNotEmpty() }.map { it.toInt() }.toIntArray()) }) } data class BingoBoard(val id: UUID = UUID.randomUUID(), val rows: Rows) { val columns: Columns get() = (1..rows[0].size).map { value -> Column(rows.map { it[value - 1] }) } private var frozen: Boolean = false fun findAndMark(number: Int): Boolean = whenNotFrozen(true) { find(number)?.mark() return@whenNotFrozen checkBingo().also { freezeBoardWhenBingo(it) } } fun find(number: Int): MarkableNumber? = rows.find(number) fun findUnmarked(): List<Int> = rows.getUnmarked() private fun checkBingo(): Boolean = rows.any(Row::hasBingo) || columns.any(Column::hasBingo) private fun freezeBoardWhenBingo(bingo: Boolean) { this.frozen = bingo } private fun <T> whenNotFrozen(frozenDefault: T, block: () -> T): T { return if (!frozen) { block() } else { frozenDefault } } } private fun Rows.find(numberToFind: Int): MarkableNumber? { forEach { val attempt = it.find { markableNumber -> markableNumber.number == numberToFind } if (attempt != null) return attempt } return null } private fun Rows.getUnmarked(): List<Int> = flatMap { row -> row.getUnmarked() } data class Row(private val numbers: List<MarkableNumber>) : List<MarkableNumber> by numbers { constructor(vararg values: Int) : this(values.asList().map { MarkableNumber(it) }) fun hasBingo() = numbers.all { it.marked } fun getUnmarked(): List<Int> { return numbers.filter { it.unmarked }.map { it.number } } } data class Column(private val numbers: List<MarkableNumber>) : List<MarkableNumber> by numbers { constructor(vararg values: Int) : this(values.asList().map { MarkableNumber(it) }) fun hasBingo() = numbers.all { it.marked } } typealias Rows = List<Row> typealias Columns = List<Column> data class MarkableNumber(val number: Int, var marked: Boolean = false) { val unmarked: Boolean get() = !marked fun mark() { marked = true } }
0
Kotlin
0
0
7662b3861ca53214e3e3a77c1af7b7c049f81f44
3,372
Advent-of-Code-2021
MIT License
src/main/kotlin/com/github/michaelbull/advent2023/day19/System.kt
michaelbull
726,012,340
false
{"Kotlin": 195941}
package com.github.michaelbull.advent2023.day19 fun Sequence<String>.toSystem(): System { var readingWorkflows = true val workflows = mutableListOf<Workflow>() val parts = mutableListOf<Part>() for (line in this) { if (line.isEmpty()) { readingWorkflows = false } else if (readingWorkflows) { workflows += line.toWorkflow() } else { parts += line.toPart() } } return System( workflows = workflows.toList(), parts = parts.toList(), ) } data class System( val workflows: List<Workflow>, val parts: List<Part>, ) { private val initial = workflowByName("in") fun acceptedRatingTotal(): Long { return parts.apply(initial).entries.sumOf { (part, instruction) -> if (instruction == Accept) { part.totalRating } else { 0 } }.toLong() } fun distinctRatingCombinationCount(range: IntRange): Long { val ranges = mapOf( ExtremelyCoolLooking to range, Musical to range, Aerodynamic to range, Shiny to range, ) return distinctRatingCombinationCount(initial.rules, ranges) } private fun List<Part>.apply(workflow: Workflow): Map<Part, Instruction> { return associateWith { it.apply(workflow) } } private tailrec fun Part.apply(workflow: Workflow): Instruction { val rule = workflow.rules.first(::satisfies) return when (val instruction = rule.instruction) { is Accept -> instruction is Reject -> instruction is Send -> apply(workflowByName(instruction.workflow)) } } private fun workflowByName(name: String): Workflow { return workflows.first { it.name == name } } private fun distinctRatingCombinationCount(rules: List<Rule>, ranges: Map<Category, IntRange>): Long { return when (val rule = rules.first()) { is Always -> { distinctRatingCombinationCount(rule.instruction, ranges) } is If -> { val (category, operator, operand, instruction) = rule val range = ranges.getValue(category) val firstTrue = when (operator) { MoreThan -> maxOf(range.first, operand + 1) LessThan -> range.first } val lastTrue = when (operator) { MoreThan -> range.last LessThan -> minOf(range.last, operand - 1) } val firstFalse = when (operator) { MoreThan -> range.first LessThan -> maxOf(range.first, operand) } val lastFalse = when (operator) { MoreThan -> minOf(range.last, operand) LessThan -> range.last } var count = 0L val trueRange = firstTrue..lastTrue if (!trueRange.isEmpty()) { count += distinctRatingCombinationCount(instruction, ranges + Pair(category, trueRange)) } val falseRange = firstFalse..lastFalse if (!falseRange.isEmpty()) { count += distinctRatingCombinationCount(rules.drop(1), ranges + Pair(category, falseRange)) } count } } } private fun distinctRatingCombinationCount(instruction: Instruction, ranges: Map<Category, IntRange>): Long { return when (instruction) { Accept -> ranges.values.map { range -> range.count().toLong() }.reduce(Long::times) Reject -> 0 is Send -> { val workflow = workflowByName(instruction.workflow) distinctRatingCombinationCount(workflow.rules, ranges) } } } } private infix fun Part.satisfies(rule: Rule): Boolean { return when (rule) { is Always -> true is If -> { val rating = ratingIn(rule.category) when (rule.operator) { MoreThan -> rating > rule.operand LessThan -> rating < rule.operand } } } }
0
Kotlin
0
1
ea0b10a9c6528d82ddb481b9cf627841f44184dd
4,324
advent-2023
ISC License
src/main/kotlin/g0401_0500/s0480_sliding_window_median/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0401_0500.s0480_sliding_window_median // #Hard #Array #Hash_Table #Heap_Priority_Queue #Sliding_Window // #2023_01_01_Time_409_ms_(100.00%)_Space_44.6_MB_(81.48%) import java.util.TreeSet class Solution { fun medianSlidingWindow(nums: IntArray, k: Int): DoubleArray { require(k >= 1) { "Input is invalid" } val len = nums.size val result = DoubleArray(len - k + 1) if (k == 1) { for (i in 0 until len) { result[i] = nums[i].toDouble() } return result } val comparator = Comparator { a: Int?, b: Int? -> if (nums[a!!] != nums[b!!] ) Integer.compare(nums[a], nums[b]) else Integer.compare(a, b) } val smallNums = TreeSet(comparator.reversed()) val largeNums = TreeSet(comparator) for (i in 0 until len) { if (i >= k) { removeElement(smallNums, largeNums, i - k) } addElement(smallNums, largeNums, i) if (i >= k - 1) { result[i - (k - 1)] = getMedian(smallNums, largeNums, nums) } } return result } private fun addElement(smallNums: TreeSet<Int?>, largeNums: TreeSet<Int?>, idx: Int) { smallNums.add(idx) largeNums.add(smallNums.pollFirst()!!) if (smallNums.size < largeNums.size) { smallNums.add(largeNums.pollFirst()) } } private fun removeElement(smallNums: TreeSet<Int?>, largeNums: TreeSet<Int?>, idx: Int) { if (largeNums.contains(idx)) { largeNums.remove(idx) if (smallNums.size == largeNums.size + 2) { largeNums.add(smallNums.pollFirst()!!) } } else { smallNums.remove(idx) if (smallNums.size < largeNums.size) { smallNums.add(largeNums.pollFirst()) } } } private fun getMedian(smallNums: TreeSet<Int?>, largeNums: TreeSet<Int?>, nums: IntArray): Double { return if (smallNums.size == largeNums.size) { (nums[smallNums.first()!!].toDouble() + nums[largeNums.first()!!]) / 2 } else nums[smallNums.first()!!].toDouble() } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
2,239
LeetCode-in-Kotlin
MIT License
2022/src/main/kotlin/day9_imp.kt
madisp
434,510,913
false
{"Kotlin": 388138}
import utils.Parser import utils.Solution import utils.Vec2i import utils.badInput import utils.cut import kotlin.math.sign fun main() { Day9Imp.run() } enum class Direction(val delta: Vec2i) { UP(Vec2i(0, 1)), RIGHT(Vec2i(1, 0)), DOWN(Vec2i(0, -1)), LEFT(Vec2i(-1, 0)) } object Day9Imp : Solution<List<Direction>>() { override val name = "day9" override val parser = Parser.lines.map { lines -> lines.flatMap { line -> val (dir, count) = line.cut(" ", { when (it) { "R" -> Direction.RIGHT "D" -> Direction.DOWN "U" -> Direction.UP "L" -> Direction.LEFT else -> badInput() } }, { it.toInt() }) (0 until count).map { dir } } } private fun rubberBand(tail: Vec2i, head: Vec2i): Vec2i { if (tail in head.grow()) { // tail doesn't move return Vec2i(0, 0) } return Vec2i((head.x - tail.x).sign, (head.y - tail.y).sign) } override fun part1(input: List<Direction>): Int { return solve(input, 2) } override fun part2(input: List<Direction>): Int { return solve(input, 10) } private fun solve(input: List<Direction>, knotCount: Int): Int { val tailPositions = mutableSetOf<Vec2i>() val knots = MutableList(knotCount) { Vec2i(0, 0) } tailPositions.add(knots.last()) for (move in input) { knots[0] = knots[0] + move.delta for (i in 1 until knots.size) { knots[i] = knots[i] + rubberBand(knots[i], knots[i - 1]) } tailPositions.add(knots.last()) } return tailPositions.size } }
0
Kotlin
0
1
3f106415eeded3abd0fb60bed64fb77b4ab87d76
1,588
aoc_kotlin
MIT License
leetcode/src/sort/Q169.kt
zhangweizhe
387,808,774
false
null
package sort fun main() { // 169. 多数元素 // https://leetcode-cn.com/problems/majority-element/ println(majorityElement2(intArrayOf(2,2,1,1,1,2,2))) } /** * 排序法,排序后的数组,nums[n/2] 一定是众数 * 时间复杂度由排序算法决定 */ fun majorityElement1(nums: IntArray): Int { // 使用快速排序 quickSort(nums, 0, nums.size - 1) return nums[nums.size/2] } /** * 快速排序 */ private fun quickSort(nums: IntArray, start: Int, end: Int) { if (start >= end) { return } // 分区 val pivot = nums[end] var i = start for (j in start until end) { if (nums[j] < pivot) { val tmp = nums[j] nums[j] = nums[i] nums[i] = tmp i++ } } nums[end] = nums[i] nums[i] = pivot // 分区完成,继续对左右分区执行快排 quickSort(nums, start, i - 1) quickSort(nums, i + 1, end) } /** * 投票法 */ fun majorityElement2(nums: IntArray): Int { var result = 0 // 遍历数组,sum 为 0 时,把遍历到的元素 i 赋给 result;sum 不为 0 时,如果 i == result,则 sum++,否则 sum-- // 遍历完成后,result 即是众数(关键条件:众数出现次数大于 n/2) var sum = 0 for (i in nums) { if (sum == 0) { result = i } if (result == i) { sum++ }else { sum-- } } return result }
0
Kotlin
0
0
1d213b6162dd8b065d6ca06ac961c7873c65bcdc
1,494
kotlin-study
MIT License
kotlin/src/Day03.kt
ekureina
433,709,362
false
{"Kotlin": 65477, "C": 12591, "Rust": 7560, "Makefile": 386}
import java.lang.Long.parseLong data class BitCount(var ones: Long, var zeros: Long) fun main() { fun part1(input: List<String>): Long { val initialCounts = input.first().map { bit -> if (bit == '0') { BitCount(0L, 1L) } else { BitCount(1L, 0L) } } val (gamma, epsilon) = input.drop(0).fold(initialCounts) { bitCounts, bitString -> bitCounts.zip(bitString.toList()).map { (count, bit) -> if (bit == '0') { BitCount(count.ones, count.zeros + 1) } else { BitCount(count.ones + 1, count.zeros) } } }.fold(0L to 0L) { (gamma, epsilon), count -> if (count.ones > count.zeros) { ((gamma shl 1) + 1) to (epsilon shl 1) } else { (gamma shl 1) to ((epsilon shl 1) + 1) } } return gamma * epsilon } fun part2(input: List<String>): Long { val oxygen = input[0].indices.fold(input) { filteredInput, index -> if (filteredInput.size == 1) { return@fold filteredInput } val frequency = filteredInput.fold(BitCount(0L, 0L)) { bitCount, bitString -> if (bitString[index] == '1') { BitCount(bitCount.ones + 1, bitCount.zeros) } else { BitCount(bitCount.ones, bitCount.zeros + 1) } } filteredInput.filter { bitNum -> parseLong(bitNum, 2) if (frequency.ones >= frequency.zeros) { bitNum[index] == '1' } else { bitNum[index] == '0' } } }.first() val co2 = input[0].indices.fold(input) { filteredInput, index -> if (filteredInput.size == 1) { return@fold filteredInput } val frequency = filteredInput.fold(BitCount(0L, 0L)) { bitCount, bitString -> if (bitString[index] == '1') { BitCount(bitCount.ones + 1, bitCount.zeros) } else { BitCount(bitCount.ones, bitCount.zeros + 1) } } filteredInput.filter { bitNum -> parseLong(bitNum, 2) if (frequency.ones >= frequency.zeros) { bitNum[index] == '0' } else { bitNum[index] == '1' } } }.first() return parseLong(oxygen, 2) * parseLong(co2, 2) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") check(part1(testInput) == 198L) check(part2(testInput) == 230L) val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
391d0017ba9c2494092d27d22d5fd9f73d0c8ded
2,967
aoc-2021
MIT License
src/day4/day4.kt
mrm1st3r
573,163,888
false
{"Kotlin": 12713}
package day4 import Puzzle fun findSubRange(ranges: Pair<IntRange, IntRange>): Boolean { val left = ranges.first val right = ranges.second return (left.first >= right.first && left.last <= right.last) || (left.first <= right.first && left.last >= right.last) } fun convertToIntRanges(s: String): Pair<IntRange, IntRange> { val split = s.split(",") check(split.size == 2) return Pair(toIntRange(split[0]), toIntRange(split[1])) } fun toIntRange(s: String): IntRange { val split = s.split("-") check(split.size == 2) return IntRange(split[0].toInt(), split[1].toInt()) } fun findOverlap(pair: Pair<IntRange, IntRange>): Boolean { val left = pair.first val right = pair.second return (left.first <= right.first && left.last >= right.first) || (right.first <= left.first && right.last >= left.first) } fun part1(input: List<String>): Int { return input .map(::convertToIntRanges) .filter(::findSubRange) .size } fun part2(input: List<String>): Int { return input .map(::convertToIntRanges) .filter(::findOverlap) .size } fun main() { Puzzle( "day4", ::part1, 2, ::part2, 4 ).test() }
0
Kotlin
0
0
d8eb5bb8a4ba4223331766530099cc35f6b34e5a
1,266
advent-of-code-22
Apache License 2.0
src/Day02.kt
ajesh-n
573,125,760
false
{"Kotlin": 8882}
fun main() { val strategyShapeMap = mapOf( "A" to Shape.Rock, "X" to Shape.Rock, "B" to Shape.Paper, "Y" to Shape.Paper, "C" to Shape.Scissors, "Z" to Shape.Scissors, ) val strategyResultMap = mapOf( "X" to Result.LOSE, "Y" to Result.DRAW, "Z" to Result.WIN ) fun part1(input: List<String>): Int { return input.map { val round = it.split(" ") val opponent = strategyShapeMap[round[0]]!! val me = strategyShapeMap[round[1]]!! return@map me.score + me.result(opponent).score }.sum() } fun part2(input: List<String>): Int { return input.map { val round = it.split(" ") val opponent = strategyShapeMap[round[0]]!! val result = strategyResultMap[round[1]]!! return@map opponent.me(result).score + result.score }.sum() } val testInput = readInput("Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("Day02") println(part1(input)) println(part2(input)) } sealed class Shape(val score: Int) { abstract fun result(opponent: Shape): Result abstract fun me(result: Result): Shape object Rock : Shape(score = 1) { override fun result(opponent: Shape): Result { return when (opponent) { is Paper -> Result.LOSE is Scissors -> Result.WIN is Rock -> Result.DRAW } } override fun me(result: Result): Shape { return when (result) { Result.WIN -> Paper Result.LOSE -> Scissors Result.DRAW -> Rock } } } object Paper : Shape(score = 2) { override fun result(opponent: Shape): Result { return when (opponent) { is Paper -> Result.DRAW is Scissors -> Result.LOSE is Rock -> Result.WIN } } override fun me(result: Result): Shape { return when (result) { Result.WIN -> Scissors Result.LOSE -> Rock Result.DRAW -> Paper } } } object Scissors : Shape(score = 3) { override fun result(opponent: Shape): Result { return when (opponent) { is Paper -> Result.WIN is Scissors -> Result.DRAW is Rock -> Result.LOSE } } override fun me(result: Result): Shape { return when (result) { Result.WIN -> Rock Result.LOSE -> Paper Result.DRAW -> Scissors } } } } enum class Result(val score: Int) { WIN(6), LOSE(0), DRAW(3) }
0
Kotlin
0
0
2545773d7118da20abbc4243c4ccbf9330c4a187
2,875
kotlin-aoc-2022
Apache License 2.0
src/main/kotlin/Map.kt
alebedev
573,733,821
false
{"Kotlin": 82424}
import kotlin.math.abs fun main() = AocMap.solve() private object AocMap { fun solve() { val (board, moves) = readInput() println("$moves") // board.print() // val pos = applyMoves(board, moves) println("Board size ${board.cells.size}x${board.cells.first().size}") println("Cube size ${board.cubeSize()}") // Hardcoded for input shape val cubeRegions = listOf( Pair(0, 1), Pair(0, 2), Pair(1, 1), Pair(2, 0), Pair(2, 1), Pair(3, 0) ) // println("After moves: $pos ${getScore(pos)}") } private fun applyMoves(board: Board, moves: List<Move>): State { var state = board.findInitialState() println("Initial state: $state") for (move in moves) { state = board.applyMove(state, move) println("$move $state") } return state } private fun getScore(state: State): Int { return (state.y + 1) * 1000 + (state.x + 1) * 4 + when (state.facing) { Facing.Right -> 0 Facing.Down -> 1 Facing.Left -> 2 Facing.Up -> 3 } } fun readInput(): Pair<Board, List<Move>> { val rows = mutableListOf<List<Cell>>() var inMapSection = true var maxWidth = 0 for (line in generateSequence(::readLine)) { if (inMapSection) { if (line == "") { inMapSection = false continue } val cells = line.toCharArray().map { when (it) { ' ' -> Cell.None '.' -> Cell.Empty '#' -> Cell.Wall else -> throw Error("Unexpected char") } }.toMutableList() maxWidth = maxOf(maxWidth, cells.size) if (cells.size < maxWidth) { cells.addAll((1..maxWidth - cells.size).map { Cell.None }) } rows.add(cells) } else { val moves = "(\\d+)(L|R|$)".toRegex().findAll(line).map { match -> var rotateRight = 0 if (match.groupValues[2] == "L") { rotateRight = -1 } else if (match.groupValues[2] == "R") { rotateRight = 1 } Move(match.groupValues[1].toInt(10), rotateRight) }.toList() return Pair(Board(rows), moves) } } val moves = listOf<Move>() return Pair(Board(rows), moves) } enum class Facing { Right, Down, Left, Up; fun rotate(rotateRight: Int): Facing { var i = this.ordinal + rotateRight if (i == -1) { i = Facing.values().size - 1 } else if (i >= Facing.values().size) { i = 0 } return Facing.values()[i] } } data class Move(val len: Int, val rotateRight: Int) data class Board(val cells: List<List<Cell>>) { fun cubeSize(): Int { return cells.first().count { it != Cell.None } / 2 } fun findInitialState(): State { return State(cells.first().indexOfFirst { it == Cell.Empty }, 0, Facing.Right) } fun applyMove(state: State, move: Move): State { var x = state.x var y = state.y when (state.facing) { Facing.Right -> x = moveX(state, move.len) Facing.Down -> y = moveY(state, move.len) Facing.Left -> x = moveX(state, -move.len) Facing.Up -> y = moveY(state, -move.len) } val facing = state.facing.rotate(move.rotateRight) return State(x, y, facing) } private fun moveX(state: State, dx: Int): Int { val range = 1..abs(dx) val step = dx / abs(dx) var x = state.x for (i in range) { var nextX = x + step if (nextX == cells.first().size) { nextX = 0 } else if (nextX < 0) { nextX = cells.first().size - 1 } while (cells[state.y][nextX] == Cell.None) { nextX += step if (nextX == cells.first().size) { nextX = 0 } else if (nextX < 0) { nextX = cells.first().size - 1 } } if (cells[state.y][nextX] == Cell.Wall) { return x } else { x = nextX } } return x } private fun moveY(state: State, dy: Int): Int { val range = 1..abs(dy) val step = dy / abs(dy) var y = state.y for (i in range) { var next = y + step if (next == cells.size) { next = 0 } else if (next < 0) { next = cells.size - 1 } while (cells[next][state.x] == Cell.None) { next += step if (next == cells.size) { next = 0 } else if (next < 0) { next = cells.size - 1 } } if (cells[next][state.x] == Cell.Wall) { return y } else { y = next } } return y } fun print() { for (row in cells) { println(row.map { when (it) { Cell.None -> ' ' Cell.Empty -> '.' Cell.Wall -> '#' } }.joinToString("")) } } } enum class Cell { None, Empty, Wall } data class State(val x: Int, val y: Int, val facing: Facing) }
0
Kotlin
0
0
d6ba46bc414c6a55a1093f46a6f97510df399cd1
6,284
aoc2022
MIT License
app/src/main/kotlin/advent/of/code/twentytwenty/Day1.kt
obarcelonap
320,300,753
false
null
package advent.of.code.twentytwenty fun main(args: Array<String>) { val result = 2020 val numbers: List<Int> = getResourceAsLines("/day1-input") .map { it.trim().toIntOrNull() } .toList() .filterNotNull() val pairs = pairsAdding(result, numbers) println("Part 1: found ${pairs.size} pairs.") pairs.map { " ${it.first} + ${it.second} = $result => ${it.first} * ${it.second} = ${it.first * it.second}" } .forEach { println(it) } val triplets = tripletsAdding(result, numbers) println("Part 2: found ${triplets.size} triplets.") triplets.map { " ${it.first} + ${it.second} + ${it.third} = $result => ${it.first} * ${it.second} * ${it.third} = ${it.first * it.second * it.third}" } .forEach { println(it) } } fun pairsAdding(result: Int, numbers: List<Int>): List<Pair<Int, Int>> { if (numbers.size < 2) { return emptyList() } fun pairsAdding(number: Int, candidates: List<Int>): List<Pair<Int, Int>> { if (candidates.isEmpty()) { return emptyList() } val matches = candidates.filter { it + number == result } if (matches.isEmpty()) { return pairsAdding(candidates.first(), candidates.tail()) } val pairs = matches.map { Pair(number, it) } val newCandidates = candidates.filter { !matches.contains(it) } if (newCandidates.isEmpty()) { return pairs } return pairs + pairsAdding(newCandidates.first(), newCandidates) } return pairsAdding(numbers.first(), numbers.tail()) } fun tripletsAdding(result: Int, numbers: List<Int>): List<Triple<Int, Int,Int>> { if (numbers.size < 3) { return emptyList() } fun tripletsAdding(number: Int, candidates: List<Int>): List<Triple<Int, Int,Int>> { if (candidates.size < 2) { return emptyList() } val reminder = result - number val pairs = pairsAdding(reminder, candidates) if (pairs.isEmpty()) { return tripletsAdding(candidates.first(), candidates.tail()) } val triplets = pairs.map { Triple(number, it.first, it.second) } return triplets + tripletsAdding(candidates.first(), candidates.tail()) } return tripletsAdding(numbers.first(), numbers.tail()) }
0
Kotlin
0
0
a721c8f26738fe31190911d96896f781afb795e1
2,352
advent-of-code-2020
MIT License
src/day03/Day03.kt
sophiepoole
573,708,897
false
null
package day03 import readInput val priority: Map<Char, Int> = (('a'..'z' zip 1..26) + ('A'..'Z' zip 27..52)).toMap() fun main() { fun checkRucksack(rucksack: String): Int { val items = rucksack.toList() val n = items.size // get the size of the list val compartment1 = items.subList(0, (n + 1) / 2) val compartment2 = items.subList((n + 1) / 2, n) val first = compartment1.intersect(compartment2).first() return priority[first] ?: 0 } fun part1(input: List<String>): Int { return input.sumOf { checkRucksack(it) } } fun findBadges(rucksacks: List<List<Char>>): Int { val badge = rucksacks[0].intersect(rucksacks[1]).intersect(rucksacks[2]).first() return priority[badge] ?: 0 } fun part2(input: List<String>): Int { return input .map{ it.toList()} .chunked(3) .sumOf { findBadges(it) } } val testInput = readInput("day03/input_test") println("----------Test----------") println("Part 1: ${part1(testInput)}") println("Part 2: ${part2(testInput)}") val input = readInput("day03/input") println("----------Input----------") println("Part 1: ${part1(input)}") println("Part 2: ${part2(input)}") }
0
Kotlin
0
0
00ad7d82cfcac2cb8a902b310f01a6eedba985eb
1,291
advent-of-code-2022
Apache License 2.0
aoc-2015/src/main/kotlin/aoc/AocDay9.kt
triathematician
576,590,518
false
{"Kotlin": 615974}
package aoc import aoc.util.chunk class AocDay9: AocDay(9) { companion object { @JvmStatic fun main(args: Array<String>) { AocDay9().run() } } override val testinput = """ London to Dublin = 464 London to Belfast = 518 Dublin to Belfast = 141 """.trimIndent().lines() fun List<String>.parse() = map { Triple(it.chunk(0), it.chunk(2), it.chunk(4).toInt()) } override fun calc1(input: List<String>): Int { val parse = input.parse() val cities = parse.flatMap { setOf(it.first, it.second) }.toSet() val paths = cities.associateWith { c -> (parse.filter { it.first == c }.map { it.second to it.third } + parse.filter { it.second == c }.map { it.first to it.third }).toMap() } return cities.minOf { shortestPathThroughRemainder(it, paths, setOf(it)) } } private fun shortestPathThroughRemainder(start: String, paths: Map<String, Map<String, Int>>, visited: Set<String>): Int { if (visited.size == paths.size) return 0 return paths.keys.filter { it !in visited }.minOf { paths[start]!![it]!! + shortestPathThroughRemainder(it, paths, visited + it) } } override fun calc2(input: List<String>): Int { val parse = input.parse() val cities = parse.flatMap { setOf(it.first, it.second) }.toSet() val paths = cities.associateWith { c -> (parse.filter { it.first == c }.map { it.second to it.third } + parse.filter { it.second == c }.map { it.first to it.third }).toMap() } return cities.maxOf { longestPathThroughRemainder(it, paths, setOf(it)) } } private fun longestPathThroughRemainder(start: String, paths: Map<String, Map<String, Int>>, visited: Set<String>): Int { if (visited.size == paths.size) return 0 return paths.keys.filter { it !in visited }.maxOf { paths[start]!![it]!! + longestPathThroughRemainder(it, paths, visited + it) } } }
0
Kotlin
0
0
7b1b1542c4bdcd4329289c06763ce50db7a75a2d
2,098
advent-of-code
Apache License 2.0
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2021/2021-23.kt
ferinagy
432,170,488
false
{"Kotlin": 787586}
package com.github.ferinagy.adventOfCode.aoc2021 import com.github.ferinagy.adventOfCode.println import com.github.ferinagy.adventOfCode.readInputLines import com.github.ferinagy.adventOfCode.searchGraph fun main() { val input = readInputLines(2021, "23-input") val test1 = readInputLines(2021, "23-test1") println("Part1:") part1(test1).println() part1(input).println() println() println("Part2:") part2(test1).println() part2(input).println() } private fun part1(input: List<String>): Int { val initial = Burrow.parse(input) return sort(initial) } private fun part2(input: List<String>): Int { val initial = Burrow.parse(input) val toAdd = listOf("DD", "CB", "BA", "AC") val newRooms = initial.rooms.mapIndexed { i, room -> room[0] + toAdd[i] + room[1] } val new = initial.copy(rooms = newRooms) return sort(new) } private fun sort(initial: Burrow): Int = searchGraph( start = initial, isDone = { it.isOrganized() }, nextSteps = { it.possibleMoves().toSet() } ) private data class Burrow(val hallway: String, val rooms: List<String>) { companion object { fun parse(input: List<String>): Burrow { return input.let { lines -> val rooms = roomPositions.map { "${lines[2][it+1]}${lines[3][it+1]}" } Burrow(hallway = lines[1].substring(1..11), rooms = rooms) } } } } private val roomPositions = listOf(2, 4, 6, 8) private val energyCosts = listOf(1, 10, 100, 1000) private fun Burrow.isOrganized(): Boolean { return rooms.withIndex().all { (index, room) -> room.all { it == 'A' + index } } } private fun Burrow.possibleMoves(): List<Pair<Burrow, Int>> = buildList { val inHallway = hallway.mapIndexedNotNull { index, c -> if (c != '.') c to index else null } inHallway.forEach { (type, index) -> val roomIndex = type - 'A' val range = range(index, roomPositions[roomIndex]) val placeInRoom = rooms[roomIndex].freeRoomIndex(type) val isFree = hallway.substring(range).withIndex().all { it.value == '.' || it.index == index - range.first } if (isFree && placeInRoom != -1) { val steps = (range.last - range.first) + (placeInRoom + 1) val newHallway = hallway.replaceAt('.', index) val newRooms = rooms.mapIndexed { i, r -> if (i != roomIndex) r else r.replaceAt(type, placeInRoom) } this += Burrow(newHallway, newRooms) to steps * energyCosts[type - 'A'] } } rooms.forEachIndexed { roomIndex, room -> val positionInRoom = room.firstOccupiedIndex() if (positionInRoom == -1) return@forEachIndexed val type = room[positionInRoom] if (room.substring(positionInRoom).all { it == 'A' + roomIndex }) return@forEachIndexed val roomPosition = roomPositions[roomIndex] val left = hallway.substring(0, roomPosition).indexOfLast { it != '.' } val right = hallway.substring(roomPosition + 1) .indexOfFirst { it != '.' } .let { if (it == -1) hallway.length else it + roomPosition + 1 } for (i in left + 1 until roomPosition) { if (i in roomPositions) continue val steps = roomPosition - i + positionInRoom + 1 val newHallway = hallway.replaceAt(type, i) val newRooms = rooms.mapIndexed { ir, r -> if (ir != roomIndex) r else r.replaceAt('.', positionInRoom) } this += Burrow(newHallway, newRooms) to steps * energyCosts[type - 'A'] } for (i in roomPosition + 1 until right) { if (i in roomPositions) continue val steps = i - roomPosition + positionInRoom + 1 val newHallway = hallway.replaceAt(type, i) val newRooms = rooms.mapIndexed { ir, r -> if (ir != roomIndex) r else r.replaceAt('.', positionInRoom) } this += Burrow(newHallway, newRooms) to steps * energyCosts[type - 'A'] } } } private fun String.freeRoomIndex(type: Char): Int { var candidate = lastIndex while (0 <= candidate && this[candidate] == type) { candidate-- } if (candidate != -1 && this[candidate] != '.') return -1 return candidate } private fun String.firstOccupiedIndex() = indexOfFirst { it != '.' } private fun String.replaceAt(type: Char, index: Int): String { return substring(0, index) + type + substring(index + 1) } private fun range(a: Int, b: Int): IntRange = if (a <= b) a .. b else b .. a
0
Kotlin
0
1
f4890c25841c78784b308db0c814d88cf2de384b
4,559
advent-of-code
MIT License
src/main/kotlin/days/Day12.kt
jgrgt
575,475,683
false
{"Kotlin": 94368}
package days import util.MutableMatrix import util.Point class Day12 : Day(12) { override fun partOne(): Any { val heights = MutableMatrix.fromSingleDigits(inputList) { c -> c } val shortestPath = heights.map { _ -> heights.height() * heights.width() } val game = Day12Game(heights, shortestPath) game.run() return game.shortestPath() } override fun partTwo(): Any { val heights = MutableMatrix.fromSingleDigits(inputList) { c -> c } val oldStart = heights.find('S') heights.set(oldStart, 'a') val allLowest = heights.findAll('a') val lengths = allLowest.map { newStart -> heights.set(newStart, 'S') val shortestPath = heights.map { _ -> heights.height() * heights.width() } val game = Day12Game(heights, shortestPath) game.run() // clean up heights.set(newStart, 'a') game.shortestPath() } return lengths.min() } } class Day12Game(val heights: MutableMatrix<Char>, val shortestPath: MutableMatrix<Int>) { val start = 'S' val end = 'E' val heighest = 'z' val lowest = 'a' fun propagate(start: Point): List<Point> { val here = heights.get(start) val currentPathLength = shortestPath.get(start) val moves = start.cross() if (here == end) { // we reached the destination return emptyList() } val nextHeight = nextHeight(here) val nextPathLength = currentPathLength + 1 val validMoves = moves.filter { move -> var h = heights.getOrDefault(move) if (h == end) { h = heighest // E == z } h != null && h <= nextHeight } return validMoves.mapNotNull { move -> val currentBestPathLengthForMove = shortestPath.get(move) if (nextPathLength < currentBestPathLengthForMove) { shortestPath.set(move, nextPathLength) move } else { null } } // Go deeper // return validMoves } fun run() { val start = heights.find(start) shortestPath.set(start, 0) run(start) } fun run(start: Point) { val candidates = mutableListOf(start) val safety = heights.width() * heights.height() var i = 0 while (candidates.isNotEmpty() && i < safety) { i++ val newCandidates = candidates.flatMap { candidate -> propagate(candidate) } candidates.clear() candidates.addAll(newCandidates.toSet()) } } private fun nextHeight(here: Char): Char { if (here == start) { return lowest + 1 } else if (here == heighest) { // this will break for 'E' :( return heighest } return here + 1 } fun shortestPath(): Int { val endPoint = heights.find(end) return shortestPath.get(endPoint) } }
0
Kotlin
0
0
5174262b5a9fc0ee4c1da9f8fca6fb86860188f4
3,152
aoc2022
Creative Commons Zero v1.0 Universal
src/day12/Day12.kt
kerchen
573,125,453
false
{"Kotlin": 137233}
package day12 import readInput class Node(val id: Int) { var shortestPath = mutableListOf<Node>() var distanceToSource = Integer.MAX_VALUE; var adjacentNodes = mutableMapOf<Node, Int>() } fun getLowestDistanceNode(unsettledNodes: Set<Node>): Node { var lowestDistanceNode = unsettledNodes.first() var lowestDistance = lowestDistanceNode.distanceToSource for (node in unsettledNodes) { if (node.distanceToSource < lowestDistance) { lowestDistance = node.distanceToSource lowestDistanceNode = node } } return lowestDistanceNode } fun calculateMinimumDistance(evaluationNode: Node, weight: Int, sourceNode: Node) { if (sourceNode.distanceToSource + weight < evaluationNode.distanceToSource) { evaluationNode.distanceToSource = sourceNode.distanceToSource + weight var shortestPath = mutableListOf<Node>() shortestPath.addAll(sourceNode.shortestPath) shortestPath.add(sourceNode) evaluationNode.shortestPath = shortestPath } } class Graph(heights: Day12.HeightMap) { var nodes = HashSet<Node>() var nodeMap = mutableMapOf<Int, Node>() fun generateID(x: Int, y: Int): Int = x + y * 256 init { fun setAdjacent(x: Int, y: Int, nodeMap: Map<Int, Node>, node: Node, height: Int) { val adjacentHeight = heights.rows[y][x] var adjacentNode = nodeMap[generateID(x, y)] if (adjacentHeight <= height + 1) { adjacentNode?.let { node.adjacentNodes[adjacentNode] = 1 } } if (height <= adjacentHeight + 1) { adjacentNode?.let { adjacentNode.adjacentNodes[node] = 1 } } } for (x in IntRange(0, heights.columnCount-1)) { for (y in IntRange(0, heights.rowCount-1)) { val id = generateID(x, y) val node = Node(id) nodes.add(node) nodeMap[id] = node val cellHeight = heights.rows[y][x] if (x > 0 ) { setAdjacent(x-1, y, nodeMap, node, cellHeight) } if (y > 0 ) { setAdjacent(x, y-1, nodeMap, node, cellHeight) } } } } fun findShortestPath(startPosition: Day12.Position, endPosition: Day12.Position): Int { var startNode = nodeMap[generateID(startPosition.x, startPosition.y)] var endNode = nodeMap[generateID(endPosition.x, endPosition.y)] if (startNode == null || endNode == null) { return Integer.MAX_VALUE } startNode.distanceToSource = 0 var settledNodes = HashSet<Node>() var unsettledNodes = HashSet<Node>() unsettledNodes.add(startNode) while (unsettledNodes.isNotEmpty()) { var currentNode = getLowestDistanceNode(unsettledNodes) unsettledNodes.remove(currentNode) for (adjacencyPair in currentNode.adjacentNodes) { var adjacentNode = adjacencyPair.key val edgeWeight = adjacencyPair.value if (adjacentNode !in settledNodes) { calculateMinimumDistance(adjacentNode, edgeWeight, currentNode) unsettledNodes.add(adjacentNode) } } settledNodes.add(currentNode) if (currentNode == endNode) { return currentNode.distanceToSource } } return Integer.MAX_VALUE } } class Day12 { data class Position(var x: Int, var y: Int) class HeightMap(input: List<String>) { var rows = mutableListOf<List<Int>>() var rowCount = 0 var columnCount = 0 var startingPosition = Position(0, 0) var goalPosition = Position(0, 0) init { for (row in input) { if ("S" in row) { val index = row.indexOf('S') startingPosition.x = index startingPosition.y = rows.size } if ("E" in row) { val index = row.indexOf('E') goalPosition.x = index goalPosition.y = rows.size } rows.add(row.map { when (it) { 'S' -> 0 'E' -> 25 else -> it.code - 'a'.code } } ) } rowCount = rows.size columnCount = rows[0].size } } } fun main() { fun part1(input: List<String>): Int { var heightMap = Day12.HeightMap(input) println("Starting pos: ${heightMap.startingPosition}") println("Goal pos: ${heightMap.goalPosition}") var graph = Graph(heightMap) val distance = graph.findShortestPath(heightMap.startingPosition, heightMap.goalPosition) println(distance) return distance } fun part2(input: List<String>): Int { var heightMap = Day12.HeightMap(input) var bestDistance = Integer.MAX_VALUE for (x in IntRange(0, heightMap.columnCount-1)) { for (y in IntRange(0, heightMap.rowCount-1)) { if (heightMap.rows[y][x] == 0) { var graph = Graph(heightMap) val distance = graph.findShortestPath(Day12.Position(x, y), heightMap.goalPosition) if (distance < bestDistance) { bestDistance = distance } } } } println(bestDistance) return bestDistance } val testInput = readInput("Day12_test") check(part1(testInput) == 31) check(part2(testInput) == 29) val input = readInput("Day12") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
dc15640ff29ec5f9dceb4046adaf860af892c1a9
6,003
AdventOfCode2022
Apache License 2.0
src/day07/Day07.kt
gillyobeast
574,413,213
false
{"Kotlin": 27372}
package day07 import utils.appliedTo import utils.readInput /// strategy: // add `/` to tree // dirname = "/" // split input by lines starting $ // for each of those: // if `cd ..`, set dirname to 'parent' // if `cd dirname` set `currentDir` to `dirname` // if `ls`, iterate over remaining lines: // if starts with `\d+`, add child with that size and name that follows // else if starts with `dir dirname`, add child with name `dirname` // then traverse the tree, grabbing all `dir`s with size < limit and adding to list: // list.sumOf { it.size } private val whitespace = "\\s".toRegex() private val newline = "\\n".toRegex() private fun buildFs(input: List<String>): FsObject { val tree: FsObject = Directory("/") var currentDirectory: FsObject = tree input.joinToString("\n") .split("\\\$".toRegex()) // .also(::println) .drop(2) // as we're already in root .forEach { it -> val lines = it.split(newline) val argLine = lines.first() val args = argLine.split(whitespace) if (args[1] == "cd") { val dirname = args[2] currentDirectory = if (dirname == "..") { currentDirectory.parent!! } else { currentDirectory.getOrAddDir(dirname) } } else { // ls lines.drop(1) // ignore the ls .filter(String::isNotBlank).forEach { val response = it.split(whitespace) if (response[0] == "dir") { currentDirectory.addChild(Directory(response[1])) } else { // file val child = File(response[1], response[0].toInt()) currentDirectory.addChild(child) } } } } return tree } fun part1(input: List<String>): Int { return buildFs(input) .directoriesInRange(1..100_000) .sumOf { it.size } } // need directory x s.t. x.size is minimised and // tree.size - x.size < 70_000_000 - 30_000_000 = 40_000_000 fun part2(input: List<String>): Int { val fileSystem = buildFs(input) println(fileSystem.toString()) return fileSystem .allDirectories() .filter { fileSystem.size - it.size < 40_000_000 } .minOf { it.size } } fun main() { // test if implementation meets criteria from the description, like: val testInput = readInput("input_test") val input = readInput("input") // part 1 ::part1.appliedTo(testInput, returns = 95437) val part1 = part1(input) println("Part 1: $part1") check(part1 != 2127288) { "Shouldn't be 2127288!" } // part 2 ::part2.appliedTo(testInput, returns = 24933642) val part2 = part2(input) println("Part 2: $part2") check(part2 != 14694309) { "Shouldn't be 14694309!" } } class File(name: String) : FsObject(name) { constructor(name: String, size: Int) : this(name) { this.size = size } override fun type(): String = "file" } class Directory(name: String) : FsObject(name) { override fun type(): String = "dir" } sealed class FsObject(private val name: String) { var parent: FsObject? = null val children: MutableList<FsObject> = mutableListOf() var size: Int = 0 get() { return if (this is File) field else getChildFiles().sumOf { it.size } } fun addChild(child: FsObject): FsObject { children.add(child) child.parent = this return child } private fun getChildFiles(): List<File> { if (this is File) return listOf(this) val (files, dirs) = children.partition { it is File } val children = mutableListOf<File>() children.addAll(files.map { it as File }) children.addAll(dirs.flatMap { it.getChildFiles() }) return children.toList() } private fun depth(): Int { var parent = this.parent var depth = 0 while (parent != null) { depth++ parent = parent.parent } return depth } override fun toString(): String { var name = "\t".repeat(depth()) + (if (this is File) "-" else "\\") + " " + name + " (size = " + size + ", " + type() + ")" if (children.isNotEmpty()) { name += children.joinToString("") { "\n$it" } } return name } abstract fun type(): String fun getOrAddDir(name: String): FsObject { return children.find { it.name == name } ?: addChild(Directory(name)) } fun directoriesInRange(intRange: IntRange): List<FsObject> { return allDirectories().filter { it.size in intRange } } fun allDirectories(): List<FsObject> { if (this is File) return emptyList() val directories = mutableListOf(this) directories.addAll(children .filterIsInstance<Directory>() .flatMap { it.allDirectories() }) return directories } }
0
Kotlin
0
0
8cdbb20c1a544039b0e91101ec3ebd529c2b9062
5,265
aoc-2022-kotlin
Apache License 2.0
src/Day03.kt
derkalaender
433,927,806
false
{"Kotlin": 4155}
fun main() { fun List<String>.charsForColumn(n: Int) = groupingBy { it[n] }.eachCount() fun String.invertBinaryString() = map { if (it == '0') '1' else '0' }.joinToString("") fun part1(input: List<String>): Int { val charFreqPerColumn = input[0].indices.map { input.charsForColumn(it) } val gamma = charFreqPerColumn.joinToString("") { freqs -> freqs.maxByOrNull { it.value }?.key?.toString() ?: error("Could not find max!") } val epsilon = gamma.invertBinaryString() return gamma.toInt(2) * epsilon.toInt(2) } fun part2(input: List<String>): Int { fun List<String>.filterColumnsForChar(charByFreq: (zeros: Int, ones: Int) -> Char): String { var current = this for (column in input[0].indices) { val charFreqPerColumn = current.charsForColumn(column) val zeros = charFreqPerColumn['0'] ?: 0 val ones = charFreqPerColumn['1'] ?: 1 current = current.filter { it[column] == charByFreq(zeros, ones) } if (current.size == 1) break } return current.single() } val oxygen = input.filterColumnsForChar { zeros, ones -> if (zeros > ones) '0' else '1' } val co2 = input.filterColumnsForChar { zeros, ones -> if (zeros > ones) '1' else '0' } return oxygen.toInt(2) * co2.toInt(2) } readInput("Day03").let { println("Answer 1: ${part1(it)}") println("Answer 2: ${part2(it)}") } }
0
Kotlin
0
0
bf258ea0cf7cada31288a91d2204d5c7b3492433
1,580
aoc2021
The Unlicense
21.kt
pin2t
725,922,444
false
{"Kotlin": 48856, "Go": 48364, "Shell": 54}
import kotlin.math.pow fun main() { val up = Pair(0, -1); val right = Pair(1, 0); val down = Pair(0, 1); val left = Pair(-1, 0) val rocks = HashSet<Pair<Int, Int>>() var rows = 0 fun reachable(from: Pair<Int, Int>, steps: Int): Int { var reach = HashSet<Pair<Int, Int>>() reach.add(from) for (i in 1..steps) { val next = HashSet<Pair<Int, Int>>() fun move(p: Pair<Int, Int>, dir: Pair<Int, Int>) { if (!rocks.contains(Pair(p.first + dir.first, p.second + dir.second))) { next.add(Pair(p.first + dir.first, p.second + dir.second)) } } for (p in reach) { move(p, up); move(p, right); move(p, down); move(p, left) } reach = next } return reach.count { it.first >= 0 && it.second >= 0 && it.first < rows && it.second < rows } } var start = Pair(0, 0) while (true) { val l = readlnOrNull() ?: break l.forEachIndexed { col, ch -> when (ch) { 'S' -> start = Pair(col, rows); '#' -> rocks.add(Pair(col, rows)) } } rows++ } var grids: Long = 26501365.toLong() / rows - 1 var oddGrids: Long = (grids / 2 * 2 + 1).toDouble().pow(2).toLong() var evenGrids: Long = ((grids + 1) / 2 * 2).toDouble().pow(2).toLong() var res2: Long = oddGrids * reachable(start, rows * 2 + 1) + evenGrids * reachable(start, rows * 2) + reachable(Pair(start.first, rows - 1), rows - 1) + reachable(Pair(0, start.second), rows - 1) + reachable(Pair(start.first, 0), rows - 1) + reachable(Pair(rows - 1, start.second), rows - 1) + ((grids + 1) * (reachable(Pair(0, rows - 1), rows / 2 - 1) + reachable(Pair(rows - 1, rows - 1), rows / 2 - 1) + reachable(Pair(0, 0), rows / 2 - 1) + reachable(Pair(rows - 1, 0), rows / 2 - 1))) + (grids * (reachable(Pair(0, rows - 1), rows * 3 / 2 - 1) + reachable(Pair(rows - 1, rows - 1), rows * 3 / 2 - 1) + reachable(Pair(0, 0), rows * 3 / 2 - 1) + reachable(Pair(rows - 1, 0), rows * 3 / 2 - 1))) println(listOf(reachable(start, 64), res2)) }
0
Kotlin
1
0
7575ab03cdadcd581acabd0b603a6f999119bbb6
2,303
aoc2023
MIT License
leetcode2/src/leetcode/top-k-frequent-elements.kt
hewking
68,515,222
false
null
package leetcode import java.util.* /** * 347. 前 K 个高频元素 * https://leetcode-cn.com/problems/top-k-frequent-elements/ * @program: leetcode * @description: ${description} * @author: hewking * @create: 2019-10-21 11:32 * 给定一个非空的整数数组,返回其中出现频率前 k 高的元素。 示例 1: 输入: nums = [1,1,1,2,2,3], k = 2 输出: [1,2] 示例 2: 输入: nums = [1], k = 1 输出: [1] 说明: 你可以假设给定的 k 总是合理的,且 1 ≤ k ≤ 数组中不相同的元素的个数。 你的算法的时间复杂度必须优于 O(n log n) , n 是数组的大小。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/top-k-frequent-elements 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 **/ object TopKFrequentElements { class Solution { /** * 思路: key-value 形式保存某数的集合 * 比如1 出现3次,那么 {"1":3} 然后在获取第k个 * 暴力法: * */ fun topKFrequent(nums: IntArray, k: Int): List<Int> { val map = mutableMapOf<Int,Int>() nums.forEach { val value = map[it] if (value == null) { map[it] = 1 } else { map[it] = value + 1 } } val frequentsList = map.entries.sortedByDescending { it.value } val list = mutableListOf<Int>() for (i in 0 until k) { list.add(frequentsList[i].key) } return list } } } fun main(args: Array<String>) { TopKFrequentElements.Solution().topKFrequent(intArrayOf(3,0,1,0),1) }
0
Kotlin
0
0
a00a7aeff74e6beb67483d9a8ece9c1deae0267d
1,807
leetcode
MIT License
src/aoc2022/day18/aoC18.kt
Saxintosh
576,065,000
false
{"Kotlin": 30013}
package aoc2022.day18 import readLines private val incList = listOf( P3(-1, 0, 0), P3(1, 0, 0), P3(0, -1, 0), P3(0, 1, 0), P3(0, 0, -1), P3(0, 0, 1), ) private data class P3(val x: Int, val y: Int, val z: Int) { fun getAdj(): List<P3> = incList.map { P3(x + it.x, y + it.y, z + it.z) } fun faces() = listOf( Face(this, 'X'), Face(P3(x - 1, y, z), 'X'), Face(this, 'Y'), Face(P3(x, y - 1, z), 'Y'), Face(this, 'Z'), Face(P3(x, y, z - 1), 'Z'), ) } private data class Face(val p: P3, val f: Char) private class Bubble(p: P3? = null) { val s = mutableSetOf<P3>() init { if (p != null) s.add(p) } fun add(p: P3) = s.add(p) operator fun contains(p: P3) = p in s fun addAll(b: Bubble) = s.addAll(b.s) } private class SetOfBubble { val ss = mutableSetOf<Bubble>() fun put(p: P3, pp: List<P3>) { val sets = ss.filter { b -> pp.any { it in b } } when (sets.size) { 0 -> ss.add(Bubble(p)) 1 -> sets.first().add(p) else -> { // join ss.removeAll(sets.toSet()) val newSet = Bubble() sets.forEach { newSet.addAll(it) } newSet.add(p) ss.add(newSet) } } } fun processAir(pList: List<P3>) { val minX = pList.minBy { it.x }.x - 1 val minY = pList.minBy { it.y }.y - 1 val minZ = pList.minBy { it.z }.z - 1 val maxX = pList.maxBy { it.x }.x + 1 val maxY = pList.maxBy { it.y }.y + 1 val maxZ = pList.maxBy { it.z }.z + 1 val rx = minX..maxX val ry = minY..maxY val rz = minZ..maxZ for (x in rx) for (y in ry) for (z in rz) { val p = P3(x, y, z) val pp = p.getAdj() .filter { it !in pList && it.x in rx && it.y in ry && it.z in rz } if (p !in pList) put(p, pp) } // remove open air ss.removeIf { P3(minX, minY, minZ) in it } } } private fun parse(list: List<String>) = list .map { it.split(",") } .map { P3(it[0].toInt(), it[1].toInt(), it[2].toInt()) } private fun getAllFaces(pList: List<P3>): MutableSet<Face> { val faces = mutableSetOf<Face>() pList.forEach { p -> p.faces().forEach { face -> if (face in faces) faces.remove(face) else faces.add(face) } } return faces } fun main() { fun part1(lines: List<String>): Int { val pList = parse(lines) val faces = getAllFaces(pList) return faces.size } fun part2(lines: List<String>): Int { val pList = parse(lines) val faces = getAllFaces(pList) val airs = SetOfBubble() airs.processAir(pList) airs.ss.flatMap { it.s.toList() }.forEach { p -> p.faces().forEach { face -> faces.remove(face) } } return faces.size } readLines(64, 58, ::part1, ::part2) }
0
Kotlin
0
0
877d58367018372502f03dcc97a26a6f831fc8d8
2,600
aoc2022
Apache License 2.0
2015/Day02/src/main/kotlin/Main.kt
mcrispim
658,165,735
false
null
import java.io.File fun main() { fun surface(l: Int, w: Int, h: Int) = 2 * l * w + 2 * w * h + 2 * h * l fun extraPaper(l: Int, w: Int, h: Int): Int { val (dim1, dim2) = listOf(l, w, h).sorted().take(2) return dim1 * dim2 } fun ribbon(l: Int, w: Int, h: Int): Int { val (dim1, dim2) = listOf(l, w, h).sorted().take(2) return 2 * dim1 + 2 * dim2 } fun bow(l: Int, w: Int, h: Int) = l * w * h fun part1(input: List<String>): Int { var paper = 0 for (box in input) { val (l, w, h) = box.split("x").map { it.toInt() } paper += surface(l, w, h) + extraPaper(l, w, h) } return paper } fun part2(input: List<String>): Int { var totalRibbon = 0 for (box in input) { val (l, w, h) = box.split("x").map { it.toInt() } totalRibbon += ribbon(l, w, h) + bow(l, w, h) } return totalRibbon } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") check(part1(testInput) == 101) check(part2(testInput) == 48) val input = readInput("Day02_data") println(part1(input)) println(part2(input)) } /** * Reads lines from the given input txt file. */ fun readInput(name: String) = File("src", "$name.txt") .readLines()
0
Kotlin
0
0
2f4be35e78a8a56fd1e078858f4965886dfcd7fd
1,380
AdventOfCode
MIT License
src/Day09.kt
haraldsperre
572,671,018
false
{"Kotlin": 17302}
import kotlin.math.abs import kotlin.math.sign fun main() { fun moveHead(position: Pair<Int, Int>, direction: Char): Pair<Int, Int> = when (direction) { 'U' -> position.copy(first = position.first + 1) 'D' -> position.copy(first = position.first - 1) 'L' -> position.copy(second = position.second - 1) 'R' -> position.copy(second = position.second + 1) else -> throw IllegalArgumentException("Invalid direction: $direction") } fun moveTail(head: Pair<Int, Int>, tail: Pair<Int, Int>): Pair<Int, Int> { val horizontalDistance = head.second - tail.second val verticalDistance = head.first - tail.first return if (abs(horizontalDistance) <= 1 && abs(verticalDistance) <= 1) { tail } else { tail.copy( first = tail.first + verticalDistance.sign, second = tail.second + horizontalDistance.sign ) } } fun getVisitedByTail( headMovements: List<String>, ropeLength: Int ): MutableSet<Pair<Int, Int>> { val visited = mutableSetOf<Pair<Int, Int>>() val knots = MutableList(ropeLength) { 0 to 0 } headMovements.forEach { line -> val (direction, steps) = line.split(" ") repeat(steps.toInt()) { knots[0] = moveHead(knots[0], direction[0]) for (knotIndex in knots.indices.drop(1)) { knots[knotIndex] = moveTail(knots[knotIndex - 1], knots[knotIndex]) } visited += knots.last() } } return visited } fun part1(input: List<String>): Int { return getVisitedByTail(input, 2).size } fun part2(input: List<String>): Int { return getVisitedByTail(input, 10).size } // test if implementation meets criteria from the description, like: val testInput = readInput("Day09_test") check(part1(testInput) == 13) check(part2(testInput) == 1) val input = readInput("Day09") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
c4224fd73a52a2c9b218556c169c129cf21ea415
2,109
advent-of-code-2022
Apache License 2.0
src/year2021/15/Day15.kt
Vladuken
573,128,337
false
{"Kotlin": 327524, "Python": 16475}
package year2021.`15` import readInput import java.util.* private data class Point( val x: Int, val y: Int, ) private typealias PointsToValues = Map<Point, Int> private typealias MutablePointsToValues = MutableMap<Point, Int> private fun infinitePaths(initialPoint: Point, initialValues: PointsToValues): PointsToValues { return initialValues.mapValues { if (it.key == initialPoint) { 0 } else { Int.MAX_VALUE } } } private fun Point.neighbours(): Set<Point> { return setOf( Point(x = x, y = y + 1), Point(x = x, y = y - 1), Point(x = x + 1, y = y), Point(x = x - 1, y = y), ) } private fun multiplyWithRulesBy25(initialPoints: PointsToValues, width: Int): PointsToValues { val newPoints: MutablePointsToValues = mutableMapOf() initialPoints.keys.forEach { repeat(5) { i -> repeat(5) { j -> val sumIndex = i + j val newX = width * i + it.x val newY = width * j + it.y val res = (initialPoints.getValue(it) + sumIndex) val newRes = if (res > 9) { res - 9 } else { res } newPoints[Point(newX, newY)] = newRes } } } return newPoints } fun main() { fun parse(input: List<String>): PointsToValues { val mutableMap = mutableMapOf<Point, Int>() input.forEachIndexed { y, line -> line.forEachIndexed { x, number -> mutableMap[Point(x, y)] = number.digitToInt() } } return mutableMap } fun deikstra(initialPoint: Point, weights: PointsToValues): PointsToValues { val currentMutableValuesHolder = infinitePaths(initialPoint, weights).toMutableMap() val priorityQueue = PriorityQueue(compareBy<Point> { currentMutableValuesHolder[it] }) val visitedPoints = mutableSetOf<Point>() priorityQueue.add(initialPoint) while (priorityQueue.isNotEmpty()) { val currentElement = priorityQueue.poll() currentElement.neighbours() .filter { it in currentMutableValuesHolder.keys } .filter { it !in visitedPoints } .forEach { nextPoint -> val distanceToNextPoint = currentMutableValuesHolder.getValue(nextPoint) val distanceToCurrentPoint = currentMutableValuesHolder.getValue(currentElement) val weightOfNextPoint = weights.getValue(nextPoint) if (distanceToNextPoint > distanceToCurrentPoint + weightOfNextPoint) { currentMutableValuesHolder[nextPoint] = distanceToCurrentPoint + weightOfNextPoint priorityQueue.add(nextPoint) } } visitedPoints.add(currentElement) } return currentMutableValuesHolder } fun part1(input: List<String>): Int { val parsedValues = parse(input) val result = deikstra(Point(0, 0), parsedValues) val maxPoint = parsedValues.keys.maxBy { it.x + it.y } return result.getValue(maxPoint) } fun part2(input: List<String>): Int { val parsedValues = parse(input) val newRes = multiplyWithRulesBy25(parsedValues, parsedValues.keys.maxOf { it.x }.inc()) val result = deikstra(Point(0, 0), newRes) val maxPoint = newRes.keys.maxBy { it.x + it.y } return result.getValue(maxPoint) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day15_test") val part1Test = part1(testInput) val part2Test = part2(testInput) println(part1Test) check(part1Test == 40) println(part2Test) check(part2Test == 315) val input = readInput("Day15") println(part1(input)) println(part2(input)) }
0
Kotlin
0
5
c0f36ec0e2ce5d65c35d408dd50ba2ac96363772
4,018
KotlinAdventOfCode
Apache License 2.0
src/Day04.kt
brunojensen
572,665,994
false
{"Kotlin": 13161}
private fun String.toRange(): Pair<IntRange, IntRange> { val splitted = this.split(",") return splitted[0].substringBefore("-").toInt()..splitted[0].substringAfter("-").toInt() to splitted[1].substringBefore("-").toInt()..splitted[1].substringAfter("-").toInt() } private infix fun IntRange.fullyContains(other: IntRange): Boolean { val intersection = (this intersect other) return intersection.size == this.count() || intersection.size == other.count() } private infix fun IntRange.overlaps(other: IntRange): Boolean { return (this intersect other).isNotEmpty() } fun main() { fun part1(input: List<String>): Int { return input.count { val (first, last) = it.toRange() first fullyContains last } } fun part2(input: List<String>): Int { return input.count { val (first, last) = it.toRange() first overlaps last } } // 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
2707e76f5abd96c9d59c782e7122427fc6fdaad1
1,143
advent-of-code-kotlin-1
Apache License 2.0
app/src/y2021/day10/Day10SyntaxScoring.kt
henningBunk
432,858,990
false
{"Kotlin": 124495}
package y2021.day10 import common.Answers import common.AocSolution import common.annotations.AoCPuzzle fun main(args: Array<String>) { Day10SyntaxScoring().solveThem() } @AoCPuzzle(2021, 10) class Day10SyntaxScoring : AocSolution { override val answers = Answers(samplePart1 = 26397, samplePart2 = 288957, part1 = 392367, part2 = 2192104158) override fun solvePart1(input: List<String>): Any = input .mapNotNull { it.getFirstIllegalCharacter() } .sumOf { it.points } override fun solvePart2(input: List<String>): Any = input .filter { it.getFirstIllegalCharacter() == null } .map { it.getPointsForClosingString() } .sorted() .let { scores -> scores[scores.size / 2] } } fun String.getFirstIllegalCharacter(): Chunk? { val stack: MutableList<Chunk> = mutableListOf() this.forEach { val chunk = it.getChunk() when { it.isOpening() -> stack.add(chunk) else -> { if (stack.last().isCorrectClosing(chunk)) { stack.removeLast() } else { return chunk } } } } return null } fun String.getPointsForClosingString(): Long { val stack: MutableList<Chunk> = mutableListOf() this.forEach { val chunk = it.getChunk() when { it.isOpening() -> stack.add(chunk) else -> { if (stack.last().isCorrectClosing(chunk)) { stack.removeLast() } } } } return stack .reversed() .fold(0L) { acc, next -> acc * 5 + next.missingPoints } } enum class Chunk( val opening: Char, val closing: Char, val points: Int, val missingPoints: Int, ) { ROUND('(', ')', points = 3, missingPoints = 1), SQUARE('[', ']', points = 57, missingPoints = 2), CURLY('{', '}', points = 1197, missingPoints = 3), POINTY('<', '>', points = 25137, missingPoints = 4); fun isCorrectClosing(chunk: Chunk): Boolean = this == chunk } fun Char.getChunk(): Chunk = when (this) { Chunk.CURLY.opening, Chunk.CURLY.closing -> Chunk.CURLY Chunk.POINTY.opening, Chunk.POINTY.closing -> Chunk.POINTY Chunk.SQUARE.opening, Chunk.SQUARE.closing -> Chunk.SQUARE Chunk.ROUND.opening, Chunk.ROUND.closing -> Chunk.ROUND else -> error("OH NOOOOOO") } fun Char.isOpening(): Boolean = when (this) { Chunk.CURLY.opening, Chunk.POINTY.opening, Chunk.SQUARE.opening, Chunk.ROUND.opening -> true else -> false }
0
Kotlin
0
0
94235f97c436f434561a09272642911c5588560d
2,612
advent-of-code-2021
Apache License 2.0
src/main/day11/Day11.kt
rolf-rosenbaum
543,501,223
false
{"Kotlin": 17211}
package day11 import kotlin.math.min const val serial = 5177 const val gridSize = 300 val gridMap = (1..gridSize).flatMap { y -> (1..gridSize).map { x -> Point(x, y).let { it to it.power() } } }.associate { it.first to it.second } fun part1(): Point { return gridMap.maxByOrNull { (point, _) -> regionPower(point, 3).first }?.key ?: error("No max found") } fun part2(): String { var maxX = 0 var maxY = 0 var maxSize = 3 var maxSum = 0 for (x in 0..gridSize) { for (y in 0..gridSize) { var sum = 0 for (s in 1 until gridSize - maxOf(x, y)) { sum += (0 until s).sumOf { dx -> gridMap[Point(x + dx, y + s - 1)]!! } sum += (0 until s - 1).sumOf { dy -> gridMap[Point(x + s - 1, y + dy)]!! } if (sum > maxSum) { maxSum = sum maxX = x + 1 maxY = y + 1 maxSize = s } } } } val answer2 = "$maxX,$maxY,$maxSize" return answer2 } private fun regionPower(point: Point, size: Int) = (point.x until min(point.x + size, gridSize)).asSequence().flatMap { x -> (point.y until min(point.y + size, gridSize)).map { y -> if (x <= gridSize && y <= gridSize) gridMap[Point(x, y)]!! else 0 } }.sum() to size fun main() { println(part1()) println(part2()) } data class Point(val x: Int, val y: Int) { fun power(): Int = (((y * (x + 10) + serial) * (x + 10)) / 100) % 10 }
0
Kotlin
0
0
dfd7c57afa91dac42362683291c20e0c2784e38e
1,620
aoc-2018
Apache License 2.0
kotlin/src/main/kotlin/com/pbh/soft/day3/Day3Solver.kt
phansen314
579,463,173
false
{"Kotlin": 105902}
package com.pbh.soft.day3 import cc.ekblad.konbini.* import com.pbh.soft.common.Solver import com.pbh.soft.common.grid.Col import com.pbh.soft.common.grid.HasColumn import com.pbh.soft.common.grid.Loc import com.pbh.soft.common.grid.Row import com.pbh.soft.common.parsing.ParsingUtils.onSuccess import com.pbh.soft.common.parsing.ParsingUtils.parseSparseGrid import com.pbh.soft.common.parsing.ParsingUtils.withPos import com.pbh.soft.day3.Parsing.lineP import com.pbh.soft.day3.Parsing.numberRegex import com.pbh.soft.day3.Parsing.symbolRegex import mu.KLogging object Day3Solver : Solver, KLogging() { override fun solveP1(text: String): String { return lineP.parseSparseGrid(text).onSuccess { grid -> val symbols = grid.findAll { it.parsed.matches(symbolRegex) } val rowXintervals = grid.findAllByRow { it.parsed.matches(numberRegex) }.associate { (row, colXcells) -> row to Intervals().apply { colXcells.forEach { (_, cell) -> this[Interval(cell.column, cell.column + cell.parsed.length - 1, row)] = cell.parsed.toInt() } } } symbols.asSequence() .flatMap { (loc, _) -> adjacentNumbers(loc, rowXintervals) } .sum() .toString() } } override fun solveP2(text: String): String { return lineP.parseSparseGrid(text).onSuccess { grid -> val symbols = grid.findAll { it.parsed == "*" } val rowXintervals = grid.findAllByRow { it.parsed.matches(numberRegex) }.associate { (row, colXcells) -> row to Intervals().apply { colXcells.forEach { (_, cell) -> this[Interval(cell.column, cell.column + cell.parsed.length - 1, row)] = cell.parsed.toInt() } } } symbols.asSequence() .map { (loc, _) -> adjacentNumbers(loc, rowXintervals) } .filter { it.size == 2 } .map { (a, b) -> a * b} .sum() .toString() } } private fun adjacentNumbers(loc: Loc, rowXintervals: Map<Row, Intervals>): List<Int> { return loc.neighbors() .map { (r, c) -> rowXintervals[r]?.let { it[c] } } .filterNotNull() .distinctBy { it.first } .map { it.second } .toList() } } object Parsing { val numberRegex = Regex("[0-9]+") val symbolRegex = Regex("[^.\\d]") val cellP = oneOf(regex(numberRegex).withPos(), regex(symbolRegex).withPos()).map { (i, s) -> Cell(i, s) } val blankP = many(char('.')) val lineP = many(bracket(blankP, blankP, cellP)) } data class Cell(override val column: Col, val parsed: String) : HasColumn data class Interval(val start: Int, val endInclusive: Int, val row: Int) : Comparable<Interval> { constructor(start: Int, row: Int) : this(start, start, row) override fun compareTo(other: Interval): Int = if (other.endInclusive < start) -1 else if (endInclusive < other.start) 1 else 0 } class Intervals { private val intervalTree = sortedMapOf<Interval, Pair<Interval, Int>>() operator fun set(interval: Interval, value: Int) { intervalTree[interval] = interval to value } operator fun get(interval: Interval): Pair<Interval, Int>? = intervalTree[interval] operator fun get(column: Int): Pair<Interval, Int>? = intervalTree[Interval(column, column)] operator fun contains(column: Int): Boolean = intervalTree.containsKey(Interval(column, column)) }
0
Kotlin
0
0
7fcc18f453145d10aa2603c64ace18df25e0bb1a
3,318
advent-of-code
MIT License
src/main/kotlin/day17.kt
gautemo
725,273,259
false
{"Kotlin": 79259}
import shared.* /* I'ts slow, but it both A and B completes in 30 minutes */ fun main() { val input = Input.day(17) println(day17A(input)) println(day17B(input)) } fun day17A(input: Input): Int { val map = XYMap(input) { it.digitToInt() } return aStarIsh(map) } fun day17B(input: Input): Int { val map = XYMap(input) { it.digitToInt() } return aStarIsh(map, ultra = true) } private fun aStarIsh(map: XYMap<Int>, ultra: Boolean = false): Int { fun Mover.heuristic() = ((map.width - at.x) + (map.height - at.y)) * 10 val start = Mover(Point(0, 0), Right, 0) val openSet = mutableSetOf(start) val cameFrom = mutableMapOf<Mover, Mover>() val gScore = mutableMapOf(start to 0) val fScore = mutableMapOf(start to start.heuristic()) fun reconstructPath(end: Mover): Int { var totalPath = 0 var current = end while (cameFrom.contains(current)) { totalPath += map[current.at] current = cameFrom[current]!! } return totalPath } var best = Int.MAX_VALUE while (openSet.isNotEmpty()) { val current = openSet.minBy { it.heuristic() }.also { openSet.remove(it) } if(current.at == Point(map.width - 1, map.height - 1) && (!ultra || current.steps!! >= 4)) { best = minOf(best, reconstructPath(current)) } else { current.nextOptions(ultra).filter { map.getOrNull(it.at) != null }.forEach { neighbor -> val tentativeGScore = gScore[current]!! + map[neighbor.at] if(tentativeGScore < (gScore[neighbor] ?: Int.MAX_VALUE) && tentativeGScore < best) { cameFrom[neighbor] = current gScore[neighbor] = tentativeGScore fScore[neighbor] = tentativeGScore + neighbor.heuristic() openSet.add(neighbor) } } } } return best } private fun Mover.nextOptions(ultra: Boolean): List<Mover> { return when(dir) { Up -> listOf( left().apply { steps = 1 }, up(), right().apply { steps = 1 }, ) Right -> listOf( up().apply { steps = 1 }, right(), down().apply { steps = 1 }, ) Down -> listOf( right().apply { steps = 1 }, down(), left().apply { steps = 1 }, ) Left -> listOf( down().apply { steps = 1 }, left(), up().apply { steps = 1 }, ) }.filter { if(!ultra) { it.steps!! <= 3 } else if(steps!! < 4){ it.dir == dir } else { it.steps!! <= 10 } } }
0
Kotlin
0
0
6862b6d7429b09f2a1d29aaf3c0cd544b779ed25
2,743
AdventOfCode2023
MIT License
src/Day05.kt
Excape
572,551,865
false
{"Kotlin": 36421}
data class Instruction(val amount: Int, val source: Int, val dest: Int) class CrateMover(private val stacks: List<ArrayDeque<String>>) { fun moveSingleStacks(instruction: Instruction) { val source = stacks[instruction.source] val dest = stacks[instruction.dest] repeat(instruction.amount) { dest.addFirst(source.removeFirst()) } } fun moveMultipleStacks(instruction: Instruction) { val source = stacks[instruction.source] val dest = stacks[instruction.dest] val crates = (1..instruction.amount).fold(listOf<String>()) { crates, _ -> crates + source.removeFirst() } dest.addAll(0, crates) } fun getTopOfStacks(): String { return stacks.joinToString("") { it.first() } } } fun main() { fun parseDrawing(input: List<String>): List<ArrayDeque<String>> { val drawingLines = input.takeWhile { it[1] != '1' } return drawingLines.fold(mutableListOf()) { stacks, line -> line.chunked(4).forEachIndexed { i, elem -> if (stacks.size < i + 1) { stacks.add(ArrayDeque()) } val match = Regex("""\[(\w)\]""").find(elem) if (match != null) { val crate = match.groupValues[1] stacks[i].addLast(crate) } } return@fold stacks } } fun parseInstructions(input: List<String>): List<Instruction> { return input .filter { it.startsWith("move") } .map { line -> val match = Regex("""move (\d+) from (\d+) to (\d+)""").find(line) val (amount, source, dest) = match?.destructured ?: throw IllegalStateException("Invalid input") Instruction(amount.toInt(), source.toInt() - 1, dest.toInt() - 1) } } fun part1(input: List<String>): String { val drawing = parseDrawing(input) val instructions = parseInstructions(input) val crateMover = CrateMover(drawing) instructions.forEach { crateMover.moveSingleStacks(it) } return crateMover.getTopOfStacks() } fun part2(input: List<String>): String { val drawing = parseDrawing(input) val instructions = parseInstructions(input) val crateMover = CrateMover(drawing) instructions.forEach { crateMover.moveMultipleStacks(it) } return crateMover.getTopOfStacks() } val testInput = readInput("Day05_test") part1(testInput) check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = readInput("Day05") println("part 1: ${part1(input)}") println("part 2: ${part2(input)}") }
0
Kotlin
0
0
a9d7fa1e463306ad9ea211f9c037c6637c168e2f
2,774
advent-of-code-2022
Apache License 2.0
codeforces/codeton6/f.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package codeforces.codeton6 val toBaseArray = LongArray(Long.SIZE_BITS) private fun solve(): Long { val (n, k) = readLongs() val threshold = (n + 1) / k fun timesK(m: Long) = if (m <= threshold) m * k else n + 1 fun toBase(m: Long): Int { var i = 0 var mm = m do { toBaseArray[i++] = mm % k mm /= k } while (mm > 0) return i } val nLength = toBase(n) fun lex(m: Long): Long { val mLength = toBase(m) var res = mLength.toLong() var prefix = 0L var ten = 1L for (i in 0 until nLength) { prefix = timesK(prefix) + toBaseArray.getOrElse(mLength - 1 - i) { 0 } res += prefix - ten ten *= k } return res } var ans = 0L var ten = 1L repeat(nLength) { val searchHigh = timesK(ten) val high = (ten - 1..searchHigh).binarySearch { lex(it) > it } val low = (ten - 1..high).binarySearch { lex(it) >= it } ans += high - low ten = searchHigh } return ans } fun main() = repeat(readInt()) { println(solve()) } private fun LongRange.binarySearch(predicate: (Long) -> Boolean): Long { var (low, high) = this.first to this.last // must be false ... must be true while (low + 1 < high) (low + (high - low) / 2).also { if (predicate(it)) high = it else low = it } return high // first true } private fun readInt() = readln().toInt() private fun readStrings() = readln().split(" ") private fun readLongs() = readStrings().map { it.toLong() }
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
1,395
competitions
The Unlicense
src/Day04.kt
dmstocking
575,012,721
false
{"Kotlin": 40350}
fun main() { fun part1(input: List<String>): Int { return input .filter { line -> val (first, second) = line.split(",") .map { val (a, b) = it.split("-").map(String::toInt) a..b } first in second || second in first } .size } fun part2(input: List<String>): Int { return input .filter { line -> val (first, second) = line.split(",") .map { val (a, b) = it.split("-").map(String::toInt) a..b } first.overlaps(second) || second.overlaps(first) } .size } // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_test") check(part1(testInput) == 2) val input = readInput("Day04") println(part1(input)) println(part2(input)) } operator fun IntRange.contains(other: IntRange): Boolean { return other.first in this && other.last in this } fun IntRange.overlaps(other: IntRange): Boolean { return other.first in this || other.last in this }
0
Kotlin
0
0
e49d9247340037e4e70f55b0c201b3a39edd0a0f
1,258
advent-of-code-kotlin-2022
Apache License 2.0
app/src/main/kotlin/day03/Day03.kt
tobiasbexelius
437,250,135
false
{"Kotlin": 33606}
package day03 import common.InputRepo import common.readSessionCookie import common.solve fun main(args: Array<String>) { val day = 3 val input = InputRepo(args.readSessionCookie()).get(day = day) solve(day, input, ::solveDay03Part1, ::solveDay03Part2) } fun solveDay03Part1(input: List<String>): Int { val wordSize = input.first().length return input.asSequence() .fold(IntArray(wordSize) { 0 }) { acc, s -> s.forEachIndexed { index, c -> if (c == '1') { acc[index]++ } } acc } .let { bitCount -> val gamma = bitCount .map { if (it >= input.size / 2) 1 else 0 } .joinToString(separator = "") .let { Integer.parseInt(it, 2) } val ypsilon = bitCount .map { if (it >= input.size / 2) 0 else 1 } .joinToString(separator = "") .let { Integer.parseInt(it, 2) } gamma * ypsilon } } fun solveDay03Part2(input: List<String>): Int { val wordSize = input.first().length var ogrItems = input var csrItems = input.toList() repeat(wordSize) { index -> ogrItems = ogrItems.partition { it[index] == '0' } .let { if (it.first.size > it.second.size) it.first else it.second } csrItems = csrItems.partition { it[index] == '0' } .let { if ( it.second.isEmpty() || (it.first.size <= it.second.size && it.first.isNotEmpty()) ) it.first else it.second } } val ogr = ogrItems.single().let { Integer.parseInt(it, 2) } val csr = csrItems.single().let { Integer.parseInt(it, 2) } return ogr * csr }
0
Kotlin
0
0
3f9783e78e7507eeddde869cf24d34ec6e7e3078
1,806
advent-of-code-21
Apache License 2.0
src/main/kotlin/net/voldrich/aoc2021/Day14.kt
MavoCz
434,703,997
false
{"Kotlin": 119158}
package net.voldrich.aoc2021 import net.voldrich.BaseDay import net.voldrich.minMax // https://adventofcode.com/2021/day/14 fun main() { Day14().run() } class Day14 : BaseDay() { override fun task1() : Long { val polymer = Polymer() for (i in (1 .. 10)) polymer.multiply() val (min, max) = polymer.getCharCount().values.minMax { it } return max - min } override fun task2() : Long { val polymer = Polymer() for (i in (1 .. 40)) polymer.multiply() val (min, max) = polymer.getCharCount().values.minMax { it } return max - min } inner class Polymer { private val seed = input.lines()[0] private val polymerCounts = HashMap<String, Long>() private val pairInsertions = HashMap<String, Pair<String, String>>() init { for (i in (1 until seed.length)) { addPolymerCount(seed.substring(i-1, i+1), 1) } val regex = Regex("([A-Z]+) -> ([A-Z])") for ( i in 2 until input.lines().size) { val matches = regex.find(input.lines()[i])!! val key = matches.groups[1]!!.value val middle = matches.groups[2]!!.value pairInsertions[key] = Pair(key.substring(0, 1) + middle, middle + key.substring(1, 2)) } } private fun addPolymerCount(polymer: String, count: Long) { polymerCounts.compute(polymer) { _, value -> (value ?: 0L) + count } } fun multiply() { // get list of changes in the polymer counts // we can not apply them directly to the same map as that would impact the analysis of current loop val changes = pairInsertions.flatMap { (polymer, pair) -> if (polymerCounts.containsKey(polymer)) { val count = polymerCounts[polymer]!! listOf(Pair(pair.first, count), Pair(pair.second, count), Pair(polymer, -count)) } else { listOf() } } changes.forEach { (polymer, count) -> addPolymerCount(polymer, count) } } fun getCharCount() : Map<Char, Long> { val countMap = HashMap<Char, Long>() polymerCounts.entries.forEach { (key, value) -> key.toCharArray().forEach { char -> countMap.compute(char) { _, charValue -> (charValue ?: 0L) + value } } } // Each character is represented twice in neighbour elements countMap.forEach {(key, value) -> countMap[key] = value / 2 } // add the edge characters as they are not duplicated countMap[seed.first()] = countMap[seed.first()]!! + 1 countMap[seed.last()] = countMap[seed.last()]!! + 1 return countMap } } }
0
Kotlin
0
0
0cedad1d393d9040c4cc9b50b120647884ea99d9
2,949
advent-of-code
Apache License 2.0
src/Day16.kt
frozbiz
573,457,870
false
{"Kotlin": 124645}
fun <E> Collection<E>.choose(n: Int): List<List<E>> { if (n == 0) return emptyList() if (n == 1) return this.map { listOf(it) } val remaining = ArrayDeque(this) val output = mutableListOf<List<E>>() while (remaining.isNotEmpty()) { val item = remaining.removeFirst() for (list in remaining.choose(n-1)) { output.add((listOf(item) + list)) } } return output } class TunnelGraph { val graph = mutableMapOf<String, Pair<Int, Set<String>>>() fun load(input: List<String>) { val valve_regex = "Valve (\\w+) has flow rate=(-?\\d+)".toRegex() for (line in input) { val (valveString, tunnelString) = line.split(';') val match = valve_regex.find(valveString) ?: throw IllegalArgumentException() val valve = match.groupValues[1] val flow = match.groupValues[2].toInt() val tunnelStringParts = tunnelString.trim().split(',') val tunnels = tunnelStringParts.map { it.substringAfterLast(' ') } graph[valve] = flow to tunnels.toSet() // println("valve=$valve, flow=$flow, tunnels=$tunnels") } } val shortestPaths = mutableMapOf<String, MutableMap<String, List<String>>>() fun buildPaths() { var paths = graph.map { Triple(it.key, it.key, listOf<String>()) } while (paths.isNotEmpty()) { val newPaths = mutableListOf<Triple<String, String, List<String>>>() for ((node, start, path) in paths) { if (node !in shortestPaths) { shortestPaths[node] = mutableMapOf() } shortestPaths[start]!![node] = path for (branch in graph[node]!!.second) { if (shortestPaths[start]?.containsKey(branch) != true) { val newPath = path + listOf(branch) newPaths.add(Triple(branch, start, newPath)) } } } paths = newPaths } } class Route ( val node: String, val value: Int, val visitedNodes: Set<String>, val time: Int, ) { operator fun component1() = node operator fun component2() = value operator fun component3() = visitedNodes operator fun component4() = time } fun naiveTraversal(timeLimit: Int): Int { val nodesOfInterest = graph.filterValues { it.first > 0 }.keys val routes = ArrayDeque(listOf(Route("AA", 0, setOf<String>(), 0))) var bestValue = 0 buildPaths() while (routes.isNotEmpty()) { val (start, value, visitedNodes, time) = routes.removeFirst() bestValue = maxOf(bestValue, value) for (node in (nodesOfInterest - visitedNodes)) { val cost = shortestPaths[start]?.get(node)?.size ?: throw IllegalStateException() val totalTime = time + cost + 1 // one to turn on the valve if (totalTime < timeLimit) { val remainingTime = timeLimit - totalTime routes.add(Route(node, value + (nodeValue(node) * remainingTime), visitedNodes + node, totalTime)) } } } return bestValue } class Agent ( val node: String, val time: Int ) { override fun toString(): String { return "Agent($node, $time)" } override fun hashCode(): Int { return node.hashCode() + time } override fun equals(other: Any?): Boolean { return (super.equals(other) || ((other is Agent) && (other.node == node) && (other.time == time)) ) } } class MultiRoute ( val value: Int, val visitedNodes: Set<String>, val remainingNodes: Set<String>, val agents: Collection<Agent> ) { // val value get() = agents.sumOf { it.value } val time get() = agents.minOf { it.time } operator fun component1() = value operator fun component2() = visitedNodes operator fun component3() = time operator fun component4() = remainingNodes operator fun component5() = agents } private fun agents(agentList: Collection<Agent>, availableNodes: Set<String>, time: Int, timeLimit: Int): Set<Set<Pair<Agent, Int>>> { val inactiveAgents = agentList.filter { it.time > time }.toSet() val activeAgents = agentList.toSet() - inactiveAgents val inactiveAgentSet = inactiveAgents.map { it to 0 }.toSet() val agentSets = mutableSetOf<Set<Pair<Agent, Int>>>() for (agentSet in agentRecursion(activeAgents, availableNodes, timeLimit)) { agentSets.add(agentSet + inactiveAgentSet) } return agentSets } fun agentRecursion(agents: Set<Agent>, availableNodes: Set<String>, timeLimit: Int): Set<Set<Pair<Agent, Int>>> { if (availableNodes.isEmpty() || agents.isEmpty()) return setOf(emptySet()) val agentSets = mutableSetOf<Set<Pair<Agent, Int>>>() for (node in availableNodes) { for (agent in agents) { val cost = distance(agent.node, node) + 1 val totaltime = agent.time + cost if (totaltime >= timeLimit) continue val remainingTime = timeLimit - totaltime val newAgent = Agent(node, totaltime) to remainingTime * nodeValue(node) for (agentSet in agentRecursion(agents-agent, availableNodes - node, timeLimit)) { agentSets.add(agentSet + newAgent) } } } if (agentSets.isEmpty()) agentSets.add(emptySet()) return agentSets } fun distance(from: String, to: String): Int { return shortestPaths[from]?.get(to)?.size ?: throw IllegalArgumentException() } private fun nodeValue(node:String):Int { return graph[node]!!.first } fun naiveMultiAgentRecursiveTraversalStep(routes: List<MultiRoute>, timeLimit: Int): Int { var bestValue = 0 for (route in routes) { val (value, visitedNodes, time, availableNodes, agentList) = route val newRoutes = agents(agentList, availableNodes, time, timeLimit).mapNotNull { agentSet -> if (agentSet.isEmpty()) return@mapNotNull null val newVisitedNodes = visitedNodes + agentSet.map { it.first.node } val addedValue = agentSet.sumOf { it.second } MultiRoute(value + addedValue, newVisitedNodes, availableNodes - newVisitedNodes, agentSet.map { it.first }) } bestValue = maxOf(bestValue, naiveMultiAgentRecursiveTraversalStep(newRoutes, timeLimit), value) } return bestValue } fun naiveMultiAgentRecursiveTraversal(timeLimit: Int, numAgents: Int): Int { buildPaths() val nodesOfInterest = graph.mapNotNull { (key, value) -> when { value.first == 0 -> null distance("AA", key) >= (timeLimit-1) -> { println("Node[$key]=$value excluded for distance: ${distance("AA", key)}") null } else -> key } }.toSet() val startingOptions = nodesOfInterest.choose(numAgents) val routes = startingOptions.map { nodes -> val agents = nodes.map { val cost = distance("AA", it) + 1 Agent(it, cost) to nodeValue(it) * (timeLimit - cost) } val value = agents.sumOf { it.second } val visitedNodes = nodes.toSet() MultiRoute(value, visitedNodes, nodesOfInterest - visitedNodes, agents.map { it.first }) } return naiveMultiAgentRecursiveTraversalStep(routes, timeLimit) } fun naiveMultiAgentTraversal(timeLimit: Int, numAgents: Int): Int { buildPaths() val nodesOfInterest = graph.mapNotNull { (key, value) -> when { value.first == 0 -> null distance("AA", key) >= (timeLimit-1) -> { println("Node[$key]=$value excluded for distance: ${distance("AA", key)}") null } else -> key } }.toSet() val startingOptions = nodesOfInterest.choose(numAgents) val routes = ArrayDeque(startingOptions.map { nodes -> val agents = nodes.map { val cost = distance("AA", it) + 1 Agent(it, cost) to nodeValue(it) * (timeLimit - cost) } val value = agents.sumOf { it.second } val visitedNodes = nodes.toSet() MultiRoute(value, visitedNodes, nodesOfInterest - visitedNodes, agents.map { it.first }) }) var bestValue = 0 while (routes.isNotEmpty()) { val (value, visitedNodes, time, availableNodes, agentList) = routes.removeFirst() bestValue = maxOf(bestValue, value) val newRoutes = agents(agentList, availableNodes, time, timeLimit).mapNotNull { agentSet -> if (agentSet.isEmpty()) return@mapNotNull null val newVisitedNodes = visitedNodes + agentSet.map { it.first.node } val addedValue = agentSet.sumOf { it.second } MultiRoute(value + addedValue, newVisitedNodes, availableNodes - newVisitedNodes, agentSet.map { it.first }) } routes.addAll(newRoutes) } return bestValue } } fun main() { fun part1(input: List<String>): Int { val graph = TunnelGraph() graph.load(input) graph.buildPaths() // println(graph.shortestPaths) return graph.naiveTraversal(30) } fun part2(input: List<String>): Int { val graph = TunnelGraph() graph.load(input) return graph.naiveMultiAgentRecursiveTraversal(26, 2) } // test if implementation meets criteria from the description, like: val testInput = listOf( "Valve AA has flow rate=0; tunnels lead to valves DD, II, BB\n", "Valve BB has flow rate=13; tunnels lead to valves CC, AA\n", "Valve CC has flow rate=2; tunnels lead to valves DD, BB\n", "Valve DD has flow rate=20; tunnels lead to valves CC, AA, EE\n", "Valve EE has flow rate=3; tunnels lead to valves FF, DD\n", "Valve FF has flow rate=0; tunnels lead to valves EE, GG\n", "Valve GG has flow rate=0; tunnels lead to valves FF, HH\n", "Valve HH has flow rate=22; tunnel leads to valve GG\n", "Valve II has flow rate=0; tunnels lead to valves AA, JJ\n", "Valve JJ has flow rate=21; tunnel leads to valve II\n", ) check(part1(testInput) == 1651) println(part2(testInput)) val input = readInput("day16") // println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
4feef3fa7cd5f3cea1957bed1d1ab5d1eb2bc388
11,096
2022-aoc-kotlin
Apache License 2.0
src/main/kotlin/aoc2021/day4/Bingo.kt
arnab
75,525,311
false
null
package aoc2021.day4 object Bingo { data class Slot(val num: Int, val marked: Boolean = false) data class Board( val id: Int, val slots: List<List<Slot>> ) { companion object { fun from(id: Int, data: String): Board { val numbers = data.split("\n").map { row -> row.trim().split("\\s+".toRegex()).map { Slot(it.toInt()) } } return Board(id, numbers) } } fun mark(step: Int): Board { val markedSlots = slots.map { slotRow -> slotRow.map { slot -> val shouldMark = slot.marked || slot.num == step Slot(slot.num, shouldMark) } } return Board(id, markedSlots) } fun isWinner(): Boolean { val anyRowFullyMarked = slots.any { slotRow -> slotRow.all { it.marked } } if (anyRowFullyMarked) return true val columnIndexes = IntRange(0, slots.first().size - 1) val anyColumnFullyMarked = columnIndexes.any { columnIndex -> val column = slots.map { it[columnIndex] } column.all { it.marked } } return anyColumnFullyMarked } } data class Game( val steps: List<Int>, val boards: List<Board> ) { fun solvePart1(): Int { var nextStepBoards = boards steps.forEach { step -> nextStepBoards = play(step, nextStepBoards) val winner = findWinner(nextStepBoards) if (winner != null) { return calculateAnswer(winner, step) } } throw RuntimeException("Woah! No winner!") } private fun play(step: Int, boards: List<Board>) = boards.map { it.mark(step) } private fun findWinner(boards: List<Board>) = boards.find { it.isWinner() } private fun calculateAnswer(board: Board, step: Int): Int { val sumOfAllUnmarked = board.slots.flatten().filter { !it.marked }.sumOf { it.num } return sumOfAllUnmarked * step } fun solvePart2(): Int { var nextStepBoards = boards val remainingSteps = steps.dropWhile { step -> nextStepBoards = play(step, nextStepBoards).filterNot { it.isWinner() } nextStepBoards.size != 1 } var lastBoard = nextStepBoards.first() remainingSteps.forEach { step -> lastBoard = play(step, listOf(lastBoard)).first() if (lastBoard.isWinner()) { return calculateAnswer(lastBoard, step) } } throw RuntimeException("Woah! No winner!") } } fun parse(data: String): Game { val steps = data.split("\n").first().split(",").map { it.toInt() } val allBoards = data.split("\n").drop(2).joinToString("\n") val boards = allBoards.split("\n\n").mapIndexed() { i, boardData -> Board.from(i+1, boardData) } return Game(steps, boards) } }
0
Kotlin
0
0
1d9f6bc569f361e37ccb461bd564efa3e1fccdbd
3,180
adventofcode
MIT License
src/Day10.kt
fasfsfgs
573,562,215
false
{"Kotlin": 52546}
fun main() { fun part1(input: List<String>): Int { val registerValues = input.toRegisterValues() return listOf(20, 60, 100, 140, 180, 220) .sumOf { registerValues.signalStrength(it) } } fun part2(input: List<String>) { input.toRegisterValues() .chunked(40) .map { crtLine -> crtLine.mapIndexed { clock, register -> val sprite = (register - 1..register + 1) if (clock in sprite) "#" else "." } } .map { it.joinToString("") } .forEach { println(it) } } val testInput00 = readInput("Day10_test00") // println(testInput00.toRegisterValues()) val testInput = readInput("Day10_test") check(part1(testInput) == 13_140) part2(testInput) val input = readInput("Day10") println(part1(input)) part2(input) } fun List<String>.toRegisterValues(): List<Int> { var registerValue = 1 val computedValues = flatMap { val splitInstruction = it.split(" ") if (splitInstruction[0] == "noop") { listOf(registerValue) } else { val initialRegisterValue = registerValue.toInt() registerValue += splitInstruction[1].toInt() listOf(initialRegisterValue, registerValue) } } var mutComputedValues = computedValues.toMutableList() mutComputedValues.add(0, 1) return mutComputedValues } fun List<Int>.signalStrength(i: Int): Int = i * this[i - 1]
0
Kotlin
0
0
17cfd7ff4c1c48295021213e5a53cf09607b7144
1,545
advent-of-code-2022
Apache License 2.0
src/main/java/Exercise16-part2.kt
cortinico
317,667,457
false
null
fun main() { val input = object {}.javaClass.getResource("input-16.txt").readText().split("\n\n") val ranges = input[0] .split("\n") .associateBy( { it.substring(0, it.indexOf(":")) }, { it.substring(it.indexOf(":") + 1).replace(" or", "").trim().split(" ").map { range -> range.split("-").let { it[0].toInt()..it[1].toInt() } } }) val myTicket = input[1].split("\n")[1].split(",").map(String::toLong) val validTickets = input[2].split("\n").drop(1).map { it.split(",").map(String::toInt) }.filter { it.all { value -> ranges.any { entry -> entry.value.any { range -> value in range } } } } val possibleRules = (myTicket.indices) .map { index -> ranges .values .mapIndexed { rangeIndex, ranges -> rangeIndex to ranges } .filter { (_, ranges) -> validTickets.all { ticket -> ranges.any { range -> ticket[index] in range } } } .map { (rangeIndex, _) -> rangeIndex } .toMutableList() } .toMutableList() val ordering = IntArray(possibleRules.size) while (possibleRules.any { it.isNotEmpty() }) { val indexToRemove = possibleRules.indexOfFirst { it.size == 1 } val valueToRemove = possibleRules[indexToRemove][0] possibleRules[indexToRemove].clear() ordering[indexToRemove] = valueToRemove possibleRules.onEach { it.remove(valueToRemove) } } ranges .entries .asSequence() .filter { it.key.startsWith("departure") } .mapIndexed { index, entry -> index to entry.key } .map { (index, _) -> myTicket[ordering.indexOf(index)] } .fold(1L) { acc, next -> acc * next } .also(::println) }
1
Kotlin
0
4
a0d980a6253ec210433e2688cfc6df35104aa9df
2,065
adventofcode-2020
MIT License
src/Day02.kt
BrianEstrada
572,700,177
false
{"Kotlin": 22757}
fun main() { // Test Case val testInput = readInput("Day02_test") val part1TestResult = Day02.part1(testInput) println(part1TestResult) check(part1TestResult == 15) val part2TestResult = Day02.part2(testInput) println(part2TestResult) check(part2TestResult == 12) // Actual Case val input = readInput("Day02") println("Part 1: " + Day02.part1(input)) println("Part 2: " + Day02.part2(input)) } private object Day02 { fun part1(input: List<String>): Int { return input.sumOf { line -> val (firstMove, secondMove) = line.split(" ") val shape1 = Shape.fromString(firstMove) val shape2 = Shape.fromString(secondMove) val result = fight(shape1, shape2) result.points + shape2.points } } fun part2(input: List<String>): Int { return input.sumOf { line -> val (firstMove, secondMove) = line.split(" ") val expectedResult = Result.fromString(secondMove) val shape2 = riggedFight( shape1 = Shape.fromString(firstMove), expectedResult = expectedResult ) shape2.points + expectedResult.points } } private fun fight(shape1: Shape, shape2: Shape): Result { return when { shape1 == shape2 -> { Result.Tie } shape1.losesAgainst() == shape2 -> { Result.Win } else -> { Result.Loss } } } private fun riggedFight(shape1: Shape, expectedResult: Result): Shape { return when (expectedResult) { Result.Win -> shape1.losesAgainst() Result.Tie -> shape1 Result.Loss -> shape1.winsAgainst() } } enum class Shape( val stringValues: Array<String>, val points: Int ) { Rock( stringValues = arrayOf("A", "X"), points = 1 ), Paper( stringValues = arrayOf("B", "Y"), points = 2 ), Scissor( stringValues = arrayOf("C", "Z"), points = 3 ); companion object { fun fromString(value: String): Shape { return values().first { shape -> shape.stringValues.contains(value) } } } fun losesAgainst(): Shape { return when (this) { Rock -> Paper Paper -> Scissor Scissor -> Rock } } fun winsAgainst(): Shape { return when (this) { Rock -> Scissor Paper -> Rock Scissor -> Paper } } } enum class Result( val value: String, val points: Int ) { Win("Z", 6), Tie("Y", 3), Loss("X", 0); companion object { fun fromString(value: String): Result { return values().first { shape -> shape.value == value } } } } }
1
Kotlin
0
1
032a4693aff514c9b30e979e63560dc48917411d
3,190
aoc-kotlin-2022
Apache License 2.0
src/main/kotlin/io/github/clechasseur/adventofcode2021/Day9.kt
clechasseur
435,726,930
false
{"Kotlin": 315943}
package io.github.clechasseur.adventofcode2021 import io.github.clechasseur.adventofcode2021.data.Day9Data import io.github.clechasseur.adventofcode2021.dij.Dijkstra import io.github.clechasseur.adventofcode2021.dij.Graph import io.github.clechasseur.adventofcode2021.util.Direction import io.github.clechasseur.adventofcode2021.util.Pt object Day9 { private val data = Day9Data.data private val heightmap = data.lines().map { line -> line.toList().map { it.toString().toInt() } } fun part1(): Int = lowpoints().sumOf { it.second + 1 } fun part2(): Int = lowpoints().map { (lowpoint, _) -> Dijkstra.build(PointsGraph(), lowpoint).dist.filterValues { it != Long.MAX_VALUE }.size }.sortedDescending().take(3).fold(1) { acc, i -> acc * i } private fun lowpoints(): List<Pair<Pt, Int>> { val points = mutableListOf<Pair<Pt, Int>>() for (y in heightmap.indices) { for (x in heightmap[y].indices) { if (Direction.displacements.mapNotNull { adjacent(Pt(x, y), it) }.all { it > heightmap[y][x] }) { points.add(Pt(x, y) to heightmap[y][x]) } } } return points } private fun adjacent(pt: Pt, move: Pt): Int? { val target = pt + move if (target.y in heightmap.indices && target.x in heightmap[target.y].indices) { return heightmap[target.y][target.x] } return null } private class PointsGraph : Graph<Pt> { override fun allPassable(): List<Pt> = heightmap.indices.flatMap { y -> heightmap[y].indices.map { x -> Pt(x, y) } }.filter { heightmap[it.y][it.x] != 9 } override fun neighbours(node: Pt): List<Pt> { val value = heightmap[node.y][node.x] val higher = mutableListOf<Pt>() Direction.displacements.forEach { move -> val nextValue = adjacent(node, move) if (nextValue != null && nextValue > value) { higher.add(node + move) } } return higher.filter { heightmap[it.y][it.x] != 9 } } override fun dist(a: Pt, b: Pt): Long = 1L } }
0
Kotlin
0
0
4b893c001efec7d11a326888a9a98ec03241d331
2,216
adventofcode2021
MIT License
src/main/kotlin/day12/Solution.kt
TestaDiRapa
573,066,811
false
{"Kotlin": 50405}
package day12 import java.io.File fun Char.distance(other: Char) = if (this == 'E') other - 'z' else if (this == 'S') other - 'a' else if (other == 'E') 'z' - this else if (other == 'S') 'a' - this else other - this data class DijkstraParams( val dist: MutableMap<Pair<Int, Int>, Distance> = mutableMapOf(), val prev: MutableMap<Pair<Int, Int>, Pair<Int, Int>?> = mutableMapOf(), val queue: MutableList<Pair<Int, Int>> = mutableListOf() ) data class Distance( val distance: Int = Int.MAX_VALUE ) { operator fun plus(cost: Int): Distance = if(distance == Int.MAX_VALUE) throw Exception("Cannot sum to infinity") else Distance(distance + cost) fun isLess(other: Distance) = distance < other.distance } data class Node( val height: Char, val links: Map<Pair<Int, Int>, Int> ) { fun distance(node: Node) = height.distance(node.height) } data class Graph( val nodes: Map<Pair<Int, Int>, Node> = emptyMap(), val start: Pair<Int, Int> = Pair(0, 0), val end: Pair<Int, Int> = Pair(0, 0) ) { fun addNode(x: Int, y: Int, value: Char, vararg links: Triple<Int, Int, Char>?): Graph { val newNode = Node( when (value) { 'S' -> 'a' 'E' -> 'z' else -> value}, links .filterNotNull() .fold(emptyMap()) { acc, it -> acc + (Pair(it.first, it.second) to 1)} ) return when(value) { 'S' -> this.copy(nodes = nodes + (Pair(x,y) to newNode), start = Pair(x, y)) 'E' -> this.copy(nodes = nodes + (Pair(x,y) to newNode), end = Pair(x, y)) else -> this.copy(nodes = nodes + (Pair(x,y) to newNode)) } } private tailrec fun stepsToStart(end: Pair<Int, Int>, nodes: Map<Pair<Int, Int>, Pair<Int, Int>?>, acc: Int = 0): Int = if(nodes[end] != null) stepsToStart(nodes[end]!!, nodes, acc+1) else acc fun findShortestPathWithDijkstra(): Int { val params = DijkstraParams() nodes.keys.onEach { params.dist[it] = Distance(if (it == start) 0 else Int.MAX_VALUE) params.prev[it] = null params.queue.add(it) } while(params.queue.contains(end)) { val minVertex = params.dist.filter { params.queue.contains(it.key) }.minBy { it.value.distance }.key nodes[minVertex]!!.links.filter { nodes[minVertex]!!.distance(nodes[it.key]!!) <= 1 }.entries.onEach { if (params.queue.contains(it.key)) { val newDist = params.dist[minVertex]!! + it.value if (newDist.isLess(params.dist[it.key]!!)) { params.dist[it.key] = newDist params.prev[it.key] = minVertex } } } params.queue.remove(minVertex) } return stepsToStart(end, params.prev) } fun findShortestPathWithBFS(): Int { val queue = mutableListOf(Pair(end,0)) val explored = mutableSetOf(end) var current = queue.first() while(queue.isNotEmpty() && nodes[queue.first().first]!!.height != 'a') { current = queue.first() val validLinks = nodes[current.first]!!.links.keys .filter { !explored.contains(it) && nodes[it]!!.distance(nodes[current.first]!!) <= 1 } queue.addAll(validLinks.map { Pair(it, current.second+1) }) explored.addAll(validLinks) queue.removeAt(0) } return current.second } } fun parseInputFile() = File("src/main/kotlin/day12/input.txt") .readLines() .fold(emptyList<List<Char>>()) { acc, it -> acc + listOf(it.toCharArray().toList()) } fun getGraph() = parseInputFile() .let { rows -> (rows.indices).fold(Graph()) { acc, r -> (rows[r].indices).fold(acc) { graph, c -> graph.addNode( r, c, rows[r][c], if (r == 0) null else Triple(r-1, c, rows[r-1][c]), if (c == 0) null else Triple(r, c-1, rows[r][c-1]), if (r == rows.size-1) null else Triple(r+1, c, rows[r+1][c]), if (c == rows[r].size-1) null else Triple(r, c+1, rows[r][c+1]) ) } } } fun main() { println("The shortest path is made up of ${getGraph().findShortestPathWithDijkstra()} steps") println("The shortest hiking path is made up of ${getGraph().findShortestPathWithBFS()} steps") }
0
Kotlin
0
0
b5b7ebff71cf55fcc26192628738862b6918c879
4,614
advent-of-code-2022
MIT License
src/main/kotlin/day07/cards.kt
cdome
726,684,118
false
{"Kotlin": 17211}
package day07 import java.io.File fun main() { val file = File("src/main/resources/day07-cards").readLines() file .map { line -> val (cards, bid) = line.split(" ") Hand(cards.trim(), bid.trim().toInt()) } .sorted() .mapIndexed { order, hand -> (order + 1) * hand.bid } .sum() .let { println("Total: $it") } file .map { line -> val (cards, bid) = line.split(" ") HandWithJokers(cards.trim(), bid.trim().toInt()) } .sorted() .mapIndexed { order, hand -> (order + 1) * hand.bid } .sum() .let { println("Total with Js: $it") } } data class Hand(val cards: String, val bid: Int) : Comparable<Hand> { private val suits = mutableMapOf<Char, Int>() init { cards.forEach { suits[it] = suits.getOrDefault(it, 0) + 1 } } private fun handValue() = when { suits.values.contains(5) -> 10 suits.values.contains(4) -> 9 suits.values.contains(3) && suits.values.contains(2) -> 8 suits.values.contains(3) -> 7 suits.values.filter { it == 2 }.size == 2 -> 6 suits.values.contains(2) -> 5 else -> 0 } private fun suitValue(suit: Char) = when (suit) { 'A' -> 14 'K' -> 13 'Q' -> 12 'J' -> 11 'T' -> 10 else -> suit.digitToInt() } override fun compareTo(other: Hand) = when { this.handValue() < other.handValue() -> -1 this.handValue() > other.handValue() -> 1 else -> { cards.indices.first { index -> cards[index] != other.cards[index] }.let { suitValue(cards[it]).compareTo(suitValue(other.cards[it])) } } } } data class HandWithJokers(val cards: String, val bid: Int) : Comparable<HandWithJokers> { val suits = mutableMapOf<Char, Int>() init { cards.forEach { suits[it] = suits.getOrDefault(it, 0) + 1 } if (suits.contains('J') && !suits.values.contains(5)) { val noJokes = suits.filterKeys { it != 'J' } val bestCard = noJokes .filter { it.value == noJokes.maxOf { it.value } } .maxBy { suitValue(it.key) }.key suits[bestCard] = suits[bestCard]!! + suits['J']!! suits.remove('J') } } private fun handValue() = when { suits.values.contains(5) -> 10 suits.values.contains(4) -> 9 suits.values.contains(3) && suits.values.contains(2) -> 8 suits.values.contains(3) -> 7 suits.values.filter { it == 2 }.size == 2 -> 6 suits.values.contains(2) -> 5 else -> 0 } private fun suitValue(suit: Char) = when (suit) { 'A' -> 14 'K' -> 13 'Q' -> 12 'J' -> 1 'T' -> 10 else -> suit.digitToInt() } override fun compareTo(other: HandWithJokers) = when { this.handValue() < other.handValue() -> -1 this.handValue() > other.handValue() -> 1 else -> { cards.indices.first { index -> cards[index] != other.cards[index] }.let { suitValue(cards[it]).compareTo(suitValue(other.cards[it])) } } } }
0
Kotlin
0
0
459a6541af5839ce4437dba20019b7d75b626ecd
3,260
aoc23
The Unlicense
cz.wrent.advent/Day15.kt
Wrent
572,992,605
false
{"Kotlin": 206165}
package cz.wrent.advent import kotlin.math.abs import kotlin.math.max import kotlin.math.min fun main() { println(partOne(test, 10)) val result = partOne(input, 2000000) println("15a: $result") println(partTwo(test, 20)) println("15b: ${partTwo(input, 4000000)}") } private fun partOne(input: String, row: Int): Int { val map = input.parse() val sensors = map.flatMap { r -> r.value.filter { it.value > 0 }.map { (it.key to r.key) to it.value } } val beacons = map.flatMap { r -> r.value.filter { it.value == BEACON }.map { it.key to r.key } }.toSet() val set = mutableSetOf<Pair<Int, Int>>() sensors.forEach { (coord, dist) -> set.addAll(getCleared(coord, dist, row)) } set.removeAll(beacons) return set.size } private fun partTwo(input: String, limit: Int): Long { val map = input.parse() val sensors = map.flatMap { r -> r.value.filter { it.value > 0 }.map { (it.key to r.key) to it.value } } for (i in 0..limit) { val notCleared = sensors.map { (coord, dist) -> getCleared(coord, dist, i, limit) }.getNotCleared() if (notCleared != null) { return notCleared.toLong() * 4000000 + i.toLong() } } return -1 } private fun getCleared(coord: Pair<Int, Int>, dist: Int, row: Int): Set<Pair<Int, Int>> { val distToRow = abs(coord.second - row) val remainingDist = dist - distToRow return (coord.first - remainingDist..coord.first + remainingDist).map { it to row }.toSet() } private fun getCleared(coord: Pair<Int, Int>, dist: Int, row: Int, limit: Int): IntRange { val distToRow = abs(coord.second - row) val remainingDist = dist - distToRow if (remainingDist < 0) { return IntRange.EMPTY } return (max(0, coord.first - remainingDist)..min(coord.first + remainingDist, limit)) } private fun List<IntRange>.getNotCleared(): Int? { val sorted = this.sortedBy { it.start } var current = sorted.first() sorted.drop(1).forEach { if (!current.contains(it.start)) { return it.start - 1 } if (it.endInclusive > current.endInclusive) { current = current.start .. it.endInclusive } } return null } //private fun getNotCleared(coord: Pair<Int, Int>, dist: Int, row: Int, max: Int): List<IntRange> { // val distToRow = abs(coord.second - row) // val remainingDist = dist - distToRow // return listOf(0 until coord.first - remainingDist, coord.first + remainingDist until max) // todo ta nula tam asi hapruje //} //private fun Map<Int, Map<Int, Int>>.fill(): Map<Int, Map<Int, Int>> { // val clear = mutableMapOf<Int, MutableMap<Int, Int>>() // this.forEach { (y, row) -> // row.forEach { (x, value) -> // if (value > 0) { // addAllClears(x to y, value, clear) // } // } // } // this.forEach { (y, row) -> // row.forEach { (x, value) -> // clear.computeIfAbsent(y) { mutableMapOf() }[x] = value // } // } // return clear //} // //private fun addAllClears(from: Pair<Int, Int>, value: Int, to: MutableMap<Int, MutableMap<Int, Int>>) { // val remaining: Deque<Pair<Pair<Int, Int>, Int>> = LinkedList(listOf(from to 0)) // while (remaining.isNotEmpty()) { // val curr = remaining.pop() // val coord = curr.first // val next = curr.second // if (next <= value) { // to.computeIfAbsent(coord.second) { mutableMapOf() }[coord.first] = CLEAR // curr.first.toNeighbours().map { it to next + 1 } // .forEach { // remaining.push(it) // } // } // } //} private fun String.parse(): Map<Int, Map<Int, Int>> { val map = mutableMapOf<Int, MutableMap<Int, Int>>() val regex = Regex("Sensor at x=(-?\\d+), y=(-?\\d+): closest beacon is at x=(-?\\d+), y=(-?\\d+)") this.split("\n") .map { regex.matchEntire(it) } .filterNotNull() .map { it.groupValues } .forEach { val beacon = it.get(3).toInt() to it.get(4).toInt() val sensor = it.get(1).toInt() to it.get(2).toInt() map.computeIfAbsent(sensor.second) { mutableMapOf() }[sensor.first] = dist(sensor, beacon) map.computeIfAbsent(beacon.second) { mutableMapOf() }[beacon.first] = BEACON } return map } private fun dist(a: Pair<Int, Int>, b: Pair<Int, Int>): Int { return abs(a.first - b.first) + abs(a.second - b.second) } private const val BEACON = -1 private const val CLEAR = 0 private const val test = """Sensor at x=2, y=18: closest beacon is at x=-2, y=15 Sensor at x=9, y=16: closest beacon is at x=10, y=16 Sensor at x=13, y=2: closest beacon is at x=15, y=3 Sensor at x=12, y=14: closest beacon is at x=10, y=16 Sensor at x=10, y=20: closest beacon is at x=10, y=16 Sensor at x=14, y=17: closest beacon is at x=10, y=16 Sensor at x=8, y=7: closest beacon is at x=2, y=10 Sensor at x=2, y=0: closest beacon is at x=2, y=10 Sensor at x=0, y=11: closest beacon is at x=2, y=10 Sensor at x=20, y=14: closest beacon is at x=25, y=17 Sensor at x=17, y=20: closest beacon is at x=21, y=22 Sensor at x=16, y=7: closest beacon is at x=15, y=3 Sensor at x=14, y=3: closest beacon is at x=15, y=3 Sensor at x=20, y=1: closest beacon is at x=15, y=3""" private const val input = """Sensor at x=3844106, y=3888618: closest beacon is at x=3225436, y=4052707 Sensor at x=1380352, y=1857923: closest beacon is at x=10411, y=2000000 Sensor at x=272, y=1998931: closest beacon is at x=10411, y=2000000 Sensor at x=2119959, y=184595: closest beacon is at x=2039500, y=-250317 Sensor at x=1675775, y=2817868: closest beacon is at x=2307516, y=3313037 Sensor at x=2628344, y=2174105: closest beacon is at x=3166783, y=2549046 Sensor at x=2919046, y=3736158: closest beacon is at x=3145593, y=4120490 Sensor at x=16, y=2009884: closest beacon is at x=10411, y=2000000 Sensor at x=2504789, y=3988246: closest beacon is at x=3145593, y=4120490 Sensor at x=2861842, y=2428768: closest beacon is at x=3166783, y=2549046 Sensor at x=3361207, y=130612: closest beacon is at x=2039500, y=-250317 Sensor at x=831856, y=591484: closest beacon is at x=-175938, y=1260620 Sensor at x=3125600, y=1745424: closest beacon is at x=3166783, y=2549046 Sensor at x=21581, y=3243480: closest beacon is at x=10411, y=2000000 Sensor at x=2757890, y=3187285: closest beacon is at x=2307516, y=3313037 Sensor at x=3849488, y=2414083: closest beacon is at x=3166783, y=2549046 Sensor at x=3862221, y=757146: closest beacon is at x=4552923, y=1057347 Sensor at x=3558604, y=2961030: closest beacon is at x=3166783, y=2549046 Sensor at x=3995832, y=1706663: closest beacon is at x=4552923, y=1057347 Sensor at x=1082213, y=3708082: closest beacon is at x=2307516, y=3313037 Sensor at x=135817, y=1427041: closest beacon is at x=-175938, y=1260620 Sensor at x=2467372, y=697908: closest beacon is at x=2039500, y=-250317 Sensor at x=3448383, y=3674287: closest beacon is at x=3225436, y=4052707"""
0
Kotlin
0
0
8230fce9a907343f11a2c042ebe0bf204775be3f
6,617
advent-of-code-2022
MIT License
src/main/kotlin/day11/Code.kt
fcolasuonno
317,324,330
false
null
package day11 import isDebug import java.io.File import kotlin.system.measureTimeMillis 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, size) = parse(input) System.err.println(measureTimeMillis { part1(parsed) }) System.err.println(measureTimeMillis { part2(parsed, size) }) } fun parse(input: List<String>) = input.flatMapIndexed { j, line -> line.mapIndexedNotNull { i, c -> (i to j).takeIf { c != '.' }?.to(c == '#') } }.toMap() to maxOf(input.first().count(), input.count()) fun part1(input: Map<Pair<Int, Int>, Boolean>) { val neighboursMap = input.mapValues { (k, _) -> k.neighbours.filter { it in input } } val res = generateSequence(input) { seats -> seats.mapValues { (k, occupied) -> val neighboursCount = neighboursMap.getValue(k).count { seats.getOrDefault(it, false) } when { !occupied && neighboursCount == 0 -> true occupied && neighboursCount >= 4 -> false else -> occupied } } }.zipWithNext().first { (first, second) -> first == second }.second.values.count { it } println("Part 1 = $res") } fun part2(input: Map<Pair<Int, Int>, Boolean>, size: Int) { val neighboursMap = input.mapValues { (k, _) -> (1..size).asSequence().run { listOfNotNull( map { (k.first - it) to k.second }.firstOrNull { it in input }, map { (k.first - it) to (k.second - it) }.firstOrNull { it in input }, map { (k.first - it) to (k.second + it) }.firstOrNull { it in input }, map { (k.first + it) to k.second }.firstOrNull { it in input }, map { (k.first + it) to (k.second - it) }.firstOrNull { it in input }, map { (k.first + it) to (k.second + it) }.firstOrNull { it in input }, map { (k.first) to (k.second - it) }.firstOrNull { it in input }, map { (k.first) to (k.second + it) }.firstOrNull { it in input }) } } val res = generateSequence(input) { seats -> seats.mapValues { (k, occupied) -> val neighboursCount = neighboursMap.getValue(k).count { seats.getOrDefault(it, false) } when { !occupied && neighboursCount == 0 -> true occupied && neighboursCount >= 5 -> false else -> occupied } } }.zipWithNext().first { (first, second) -> first == second }.second.values.count { it } println("Part 2 = $res") } val Pair<Int, Int>.neighbours: List<Pair<Int, Int>> get() = listOf((first - 1) to (second - 1), (first) to (second - 1), (first + 1) to (second - 1), (first - 1) to second, (first + 1) to second, (first - 1) to (second + 1), (first) to (second + 1), (first + 1) to (second + 1))
0
Kotlin
0
0
e7408e9d513315ea3b48dbcd31209d3dc068462d
3,125
AOC2020
MIT License
src/Day19.kt
thpz2210
575,577,457
false
{"Kotlin": 50995}
private class Solution19(input: List<String>) { val blueprints = input.map { Blueprint.of(it) } fun part1() = blueprints.sumOf { nextMinute(24, State.getInitialState(), it) * it.id } fun part2() = blueprints.take(3).map { nextMinute(32, State.getInitialState(), it) }.reduce(Int::times) fun nextMinute(minute: Int, stateList: Set<State>, blueprint: Blueprint): Int { if (minute == 0) return stateList.maxOf { it.geodes } val states = stateList.flatMap { resources -> val newStates = mutableSetOf(resources) val geodesRobot = buildGeodeRobot(resources, blueprint) if (geodesRobot != null) { newStates.clear() newStates.add(geodesRobot) } else { val obsidianRobot = buildObsidianRobot(resources, blueprint) if (obsidianRobot != null) newStates.add(obsidianRobot) val clayRobot = buildClayRobot(resources, blueprint) if (clayRobot != null) newStates.add(clayRobot) val oreRobot = buildOreRobot(resources, blueprint) if (oreRobot != null) newStates.add(oreRobot) } newStates.forEach { it.ore += resources.oreRobots it.clay += resources.clayRobots it.obsidian += resources.obsidianRobots it.geodes += resources.geodesRobots } newStates }.toSet() val maxGeodeRobots = states.maxOf { it.geodesRobots } return if (maxGeodeRobots > 0) nextMinute(minute - 1, states.filter { it.geodesRobots >= maxGeodeRobots - 1 }.toSet(), blueprint) else nextMinute(minute - 1, states, blueprint) } fun buildOreRobot(state: State, blueprint: Blueprint): State? { if (state.ore < blueprint.oreForOre) return null return state.copy( ore = state.ore - blueprint.oreForOre, oreRobots = state.oreRobots + 1 ) } fun buildClayRobot(state: State, blueprint: Blueprint): State? { if (state.ore < blueprint.oreForClay) return null return state.copy( ore = state.ore - blueprint.oreForClay, clayRobots = state.clayRobots + 1 ) } fun buildObsidianRobot(state: State, blueprint: Blueprint): State? { if (state.ore < blueprint.oreForObsidian || state.clay < blueprint.clayForObsidian) return null return state.copy( ore = state.ore - blueprint.oreForObsidian, clay = state.clay - blueprint.clayForObsidian, obsidianRobots = state.obsidianRobots + 1 ) } fun buildGeodeRobot(state: State, blueprint: Blueprint): State? { if (state.ore < blueprint.oreForGeode || state.obsidian < blueprint.obsidianForGeode) return null return state.copy( ore = state.ore - blueprint.oreForGeode, obsidian = state.obsidian - blueprint.obsidianForGeode, geodesRobots = state.geodesRobots + 1 ) } data class Blueprint( val id: Int, val oreForOre: Int, val oreForClay: Int, val oreForObsidian: Int, val clayForObsidian: Int, val oreForGeode: Int, val obsidianForGeode: Int ) { companion object { fun of(line: String): Blueprint { val split = line.split(" ", ":") return Blueprint( split[1].toInt(), split[7].toInt(), split[13].toInt(), split[19].toInt(), split[22].toInt(), split[28].toInt(), split[31].toInt() ) } } } data class State( var ore: Int = 0, var clay: Int = 0, var obsidian: Int = 0, var geodes: Int = 0, val oreRobots: Int = 0, val clayRobots: Int = 0, val obsidianRobots: Int = 0, val geodesRobots: Int = 0 ) { companion object { fun getInitialState() = setOf(State(oreRobots = 1)) } } } fun main() { val testSolution = Solution19(readInput("Day19_test")) check(testSolution.part1() == 33) println("a") check(testSolution.part2() == 3472) println("a") val solution = Solution19(readInput("Day19")) println(solution.part1()) println(solution.part2()) }
0
Kotlin
0
0
69ed62889ed90692de2f40b42634b74245398633
4,480
aoc-2022
Apache License 2.0
src/Day09.kt
rifkinni
573,123,064
false
{"Kotlin": 33155, "Shell": 125}
import kotlin.math.abs data class Coordinate9(var x: Int, var y: Int) { private fun isTouching(other: Coordinate9): Boolean { if (abs(this.x - other.x) <= 1 && abs(this.y - other.y) <= 1) { return true } return false } fun follow(lead: Coordinate9) { if (isTouching(lead)) { return } val deltaX = lead.x - this.x val deltaY = lead.y - this.y if (abs(deltaX) == 2) { this.x += (deltaX/abs(deltaX)) if (abs(deltaY) >= 1) { //diagonal this.y += (deltaY/abs(deltaY)) } } else if (abs(deltaY) == 2) { this.y += (deltaY/abs(deltaY)) if (abs(deltaX) >= 1) { //diagonal this.x += (deltaX/abs(deltaX)) } } } } class Rope(size: Int) { private val head = Coordinate9(0, 0) private val knots: List<Coordinate9> val tail: Coordinate9 init { knots = (0 until size - 1).map { Coordinate9(0, 0) } tail = knots.last() } fun parseInstructions(input: List<String>): Int { val tails: MutableSet<Coordinate9> = mutableSetOf(tail.copy()) for (line in input) { val (symbol, stepString ) = line.split(" ") val direction = Direction.fromChar(symbol[0]) val steps = Integer.parseInt(stepString) for (i in 0 until steps) { move(direction) tails.add(tail.copy()) } } return tails.size } private fun move(direction: Direction) { direction.move(head) knots[0].follow(head) for (i in 0 until knots.size - 1) { knots[i + 1].follow(knots[i]) } } } enum class Direction(val symbol: Char) { UP('U'), DOWN('D'), LEFT('L'), RIGHT('R'); fun move(coordinate: Coordinate9) { when(this) { UP -> coordinate.y ++ DOWN -> coordinate.y -- LEFT -> coordinate.x -- RIGHT -> coordinate.x ++ } } companion object { fun fromChar(char: Char): Direction { return values().first { it.symbol == char } } } } fun main() { fun part1(input: List<String>): Int { return Rope(2).parseInstructions(input) } fun part2(input: List<String>): Int { return Rope(10).parseInstructions(input) } // test if implementation meets criteria from the description, like: val testCases = listOf( TestCase(0, 13, 1), TestCase(1, 88, 36) ) val testInputs = readChunk("Day09_test") .split("\n\n") .map { it.split("\n").filter { it.isNotBlank() } } for (case in testCases) { check(part1(testInputs[case.index]) == case.part1) check(part2(testInputs[case.index]) == case.part2) } val input = readInput("Day09") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
c2f8ca8447c9663c0ce3efbec8e57070d90a8996
2,961
2022-advent
Apache License 2.0
src/main/kotlin/com/colinodell/advent2023/Day12.kt
colinodell
726,073,391
false
{"Kotlin": 114923}
package com.colinodell.advent2023 class Day12(input: List<String>) { private val records = input.map { Record( conditions = it.split(" ").first(), expected = it.split(" ").last().split(",").map { it.toInt() } ) } private data class Record(val conditions: String, val expected: List<Int>) { fun unfold(x: Int) = Record( conditions = (1..x).joinToString("?") { conditions }, expected = (1..x).flatMap { expected } ) } private val cache = mutableMapOf<Triple<String, List<Int>, Int>, Long>() private fun calculateSolutions(conditions: String, expected: List<Int>, damagedEarlierInGroup: Int = 0): Long { val cacheKey = Triple(conditions, expected, damagedEarlierInGroup) if (cache.containsKey(cacheKey)) return cache[cacheKey]!! if (conditions.isEmpty()) { // We've reached the end - did everything match up? return if (expected.isEmpty() && damagedEarlierInGroup == 0) 1 else 0 } var result = 0L val next = if (conditions[0] == '?') listOf('.', '#') else listOf(conditions[0]) for (c in next) { result += when { c == '#' -> calculateSolutions(conditions.drop(1), expected, damagedEarlierInGroup + 1) damagedEarlierInGroup == 0 -> calculateSolutions(conditions.drop(1), expected) expected.isNotEmpty() && expected[0] == damagedEarlierInGroup -> calculateSolutions(conditions.drop(1), expected.drop(1)) else -> 0L } } cache[cacheKey] = result return result } private fun sumOfSolutions(folds: Int = 1) = records.map { it.unfold(folds) }.sumOf { calculateSolutions(it.conditions + '.', it.expected) } fun solvePart1() = sumOfSolutions() fun solvePart2() = sumOfSolutions(folds = 5) }
0
Kotlin
0
0
97e36330a24b30ef750b16f3887d30c92f3a0e83
1,962
advent-2023
MIT License
src/Day09.kt
arnoutvw
572,860,930
false
{"Kotlin": 33036}
import java.util.LinkedList import kotlin.math.abs fun main() { data class Point(var x: Int, var y: Int) fun isTouching(head: Point, tail: Point) :Boolean { if (abs(head.x - tail.x) <= 1 && abs(head.y - tail.y) <= 1) { return true } return false } fun part1(input: List<String>): Int { val visited = LinkedHashSet<Point>() val head = Point(0,0) val tail = Point(0,0) visited.add(Point(tail.x, tail.y)) input.forEach { val split = it.split(" ") for(i in 0 until split.get(1).toInt()) { when(split[0]) { "U" -> { head.x++ if(!isTouching(head, tail)) { tail.x = head.x - 1 tail.y = head.y visited.add(Point(tail.x, tail.y)) } } "D" -> { head.x-- if(!isTouching(head, tail)) { tail.x = head.x + 1 tail.y = head.y visited.add(Point(tail.x, tail.y)) } } "L" -> { head.y-- if(!isTouching(head, tail)) { tail.y = head.y + 1 tail.x = head.x visited.add(Point(tail.x, tail.y)) } } "R" -> { head.y++ if(!isTouching(head, tail)) { tail.y = head.y - 1 tail.x = head.x visited.add(Point(tail.x, tail.y)) } } } } } return visited.count() } operator fun Point.plus(o: Point) = Point(this.x + o.x, this.y + o.y) fun part2(input: List<String>): Int { val visited = LinkedHashSet<Point>() val rope = MutableList(10) { Point(0, 0) } visited.add(Point(0, 0)) val lookup = mapOf("D" to Point(0, 1), "U" to Point(0, -1), "L" to Point(-1, 0), "R" to Point(1, 0)) input.forEach { val split = it.split(" ") for (j in 1..split[1].toInt()) { rope[0] = rope[0] + lookup[split[0]]!! for (i in 0..rope.size-2) { val dx = rope[i].x - rope[i+1].x val dy = rope[i].y - rope[i+1].y if (abs(dx) >= 2 || abs(dy) >= 2) { rope[i+1] = rope[i+1] + Point(dx.coerceIn(-1..1), dy.coerceIn(-1..1)) } else { break } } visited.add(rope.last()) } } return visited.count() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day09_test") println("Test") val part1 = part1(testInput) println(part1) val part2 = part2(testInput) println(part2) check(part1 == 13) check(part2 == 1) println("Waarde") val input = readInput("Day09") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
0cee3a9249fcfbe358bffdf86756bf9b5c16bfe4
3,416
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/dec21/Main.kt
dladukedev
318,188,745
false
null
package dec21 data class Recipe( val ingredients: List<String>, val allergens: List<Allergen> ) enum class Allergen { DAIRY, FISH, SOY, NUTS, SESAME, PEANUTS, WHEAT, EGGS } fun parseInput(input: String): List<Recipe> { return input.lines() .map { val (ingredientsPart, allergensPart) = it.split(" (contains ") val ingredients = ingredientsPart.split(" ") val allergens = allergensPart.dropLast(1) .split(", ") .map { allergen -> when(allergen) { "dairy" -> Allergen.DAIRY "soy" -> Allergen.SOY "fish" -> Allergen.FISH "nuts" -> Allergen.NUTS "sesame" -> Allergen.SESAME "peanuts" -> Allergen.PEANUTS "wheat" -> Allergen.WHEAT "eggs" -> Allergen.EGGS else -> throw Exception("Unknown Allergen $allergen") } } Recipe(ingredients, allergens) } } fun findFoodWithAllergenCandidates(allergen: Allergen, recipes: List<Recipe>): List<String> { val recipesWithIngredient = recipes.filter { it.allergens.contains(allergen) } return recipesWithIngredient.first().ingredients.filter { ingredient -> recipesWithIngredient.all { it.ingredients.contains(ingredient) } } } tailrec fun reduceCandidates(candidates: List<Pair<Allergen, List<String>>>): List<Pair<Allergen, String>> { if(candidates.all { it.second.count() == 1 }) { return candidates.map { it.first to it.second.single() } } val haveOne = candidates.filter { it.second.count() == 1 } val updatedCandidates = candidates.map { candidate -> candidate.first to candidate.second.filter { potentialMatch -> haveOne.all { candidate.first == it.first || !it.second.contains(potentialMatch) } } } return reduceCandidates(updatedCandidates) } fun findFoodAllergenPairs(recipes: List<Recipe>): List<Pair<Allergen, String>> { val dairyCandidates = findFoodWithAllergenCandidates(Allergen.DAIRY, recipes) val fishCandidates = findFoodWithAllergenCandidates(Allergen.FISH, recipes) val soyCandidates = findFoodWithAllergenCandidates(Allergen.SOY, recipes) val nutsCandidates = findFoodWithAllergenCandidates(Allergen.NUTS, recipes) val sesameCandidates = findFoodWithAllergenCandidates(Allergen.SESAME, recipes) val peanutsCandidates = findFoodWithAllergenCandidates(Allergen.PEANUTS, recipes) val wheatCandidates = findFoodWithAllergenCandidates(Allergen.WHEAT, recipes) val eggsCandidates = findFoodWithAllergenCandidates(Allergen.EGGS, recipes) return reduceCandidates(listOf( Allergen.DAIRY to dairyCandidates, Allergen.EGGS to eggsCandidates, Allergen.FISH to fishCandidates, Allergen.NUTS to nutsCandidates, Allergen.PEANUTS to peanutsCandidates, Allergen.SESAME to sesameCandidates, Allergen.SOY to soyCandidates, Allergen.WHEAT to wheatCandidates )) } fun main() { val recipes = parseInput(input) val allergens = findFoodAllergenPairs(recipes).map { it.second } val result = recipes.flatMap { it.ingredients }.filter { !allergens.contains(it) }.count() println("------------ PART 1 ------------") println("result: $result") println("------------ PART 2 ------------") println("result: " + allergens.joinToString(",")) }
0
Kotlin
0
0
d4591312ddd1586dec6acecd285ac311db176f45
3,664
advent-of-code-2020
MIT License
src/Day03.kt
freszu
573,122,040
false
{"Kotlin": 32507}
fun main() { fun priorityForChar(duplicate: Char) = when { duplicate in 'a'..'z' -> duplicate.code - 'a'.code + 1 duplicate in 'A'..'Z' -> duplicate.code - 'A'.code + 27 else -> throw IllegalArgumentException("Invalid character") } fun part1(input: List<String>) = input.map { rucksack -> rucksack.chunked(rucksack.length / 2) } .map { (firstCompartment, secondCompartment) -> firstCompartment.toSet().intersect(secondCompartment.toSet()) } .map { duplicates -> duplicates.map(::priorityForChar) } .sumOf(List<Int>::sum) fun part2(input: List<String>) = input.map(String::toSet) .chunked(3) .map { elfGroup -> elfGroup.reduce { acc, chars -> acc.intersect(chars) } } .map { duplicates -> duplicates.map(::priorityForChar) } .sumOf(List<Int>::sum) // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") val dayInput = readInput("Day03") part1(testInput) check(part1(testInput) == 157) println(part1(dayInput)) check(part2(testInput) == 70) println(part2(dayInput)) }
0
Kotlin
0
0
2f50262ce2dc5024c6da5e470c0214c584992ddb
1,192
aoc2022
Apache License 2.0
src/main/kotlin/com/hj/leetcode/kotlin/problem2492/Solution2.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem2492 /** * LeetCode page: [2492. Minimum Score of a Path Between Two Cities](https://leetcode.com/problems/minimum-score-of-a-path-between-two-cities/); */ class Solution2 { /* Complexity: * Time O(n+E) and Space O(n) where E is the size of roads; */ fun minScore(n: Int, roads: Array<IntArray>): Int { val cityUnionFind = buildUnionFindOfCity(n, roads) check(cityUnionFind.inSameUnion(1, n)) return minDistanceAmongReachableRoads(1, roads, cityUnionFind) } private fun buildUnionFindOfCity(maxLabel: Int, roads: Array<IntArray>): UnionFind { val unionFind = UnionFind(maxLabel + 1) for ((u, v, _) in roads) { unionFind.union(u, v) } return unionFind } private class UnionFind(size: Int) { private val parent = IntArray(size) { it } private val rank = IntArray(size) fun union(u: Int, v: Int) { val uParent = find(u) val vParent = find(v) if (uParent == vParent) return val uRank = rank[uParent] val vRank = rank[vParent] when { uRank > vRank -> parent[vParent] = uParent uRank < vRank -> parent[uParent] = vParent else -> { parent[vParent] = uParent rank[uParent]++ } } } private fun find(city: Int): Int { return if (city == parent[city]) city else find(parent[city]) } fun inSameUnion(u: Int, v: Int): Boolean = find(u) == find(v) } private fun minDistanceAmongReachableRoads( origin: Int, roads: Array<IntArray>, cityUnionFind: UnionFind ): Int { var minDistance = Int.MAX_VALUE for ((u, _, distance) in roads) { if (cityUnionFind.inSameUnion(u, origin) && distance < minDistance) { minDistance = distance } } return minDistance } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
2,055
hj-leetcode-kotlin
Apache License 2.0
src/main/kotlin/Day24.kt
Avataw
572,709,044
false
{"Kotlin": 99761}
package aoc import aoc.Direction.* fun solve24A(input: List<String>): Int { val village = input.toVillage() val start = village.start return village.findShortestPathToEnd(Mover(start, 0)).moves } fun solve24B(input: List<String>): Int { val village = input.toVillage() val start = village.start val shortestFirstTrip = village.findShortestPathToEnd(Mover(start, 0)) val shortestSecondTrip = village.findShortestPathToStart(shortestFirstTrip) return village.findShortestPathToEnd(shortestSecondTrip).moves } data class Village(val spots: Set<Spot>) { val start = spots.minBy { it.pos.y }.pos private val end = spots.maxBy { it.pos.y }.pos private val top = start.y + 1 private val bot = end.y - 1 private val left = spots.minOf { it.pos.x } private val right = spots.maxOf { it.pos.x } fun findShortestPathToEnd(mover: Mover) = findShortestPath(mover, end) fun findShortestPathToStart(mover: Mover) = findShortestPath(mover, start) private fun findShortestPath(mover: Mover, target: Pos): Mover { var rounds = 0 var movers = mutableListOf(mover) while (true) { movers = movers.toSet().toMutableList() if (movers.any { it.pos == target }) return movers.first { it.pos == target } spots.forEach { spot -> spot.move(spots, top, bot, left, right) } movers.removeAll { !it.active } val newMovers = movers.flatMap { it.move(spots) } movers.addAll(newMovers) spots.forEach { spot -> spot.setBlizzards() } rounds++ } } } data class Mover(var pos: Pos, var moves: Int, var active: Boolean = true) { private fun getAvailableMoves() = listOf(pos.up(), pos.right(), pos.down(), pos.left()) fun move(spots: Set<Spot>): List<Mover> { val availableMoves = getAvailableMoves() val adjacentSpots = spots.filter { availableMoves.contains(it.pos) }.filter { it.nextBlizzards.isEmpty() } val newMovers = adjacentSpots.map { Mover(it.pos, moves + 1) } val currentSpot = spots.find { it.pos == pos && it.nextBlizzards.isNotEmpty() } if (currentSpot != null) active = false else moves++ return newMovers } } data class Spot(val pos: Pos, var blizzards: MutableList<Blizzard>, var nextBlizzards: MutableList<Blizzard>) { fun move(spots: Set<Spot>, top: Int, bot: Int, left: Int, right: Int) { val toRemove = mutableListOf<Blizzard>() blizzards.forEach { val nextPosition = when (it.dir) { RIGHT -> pos.right() DOWN -> pos.down() LEFT -> pos.left() UP -> pos.up() } val nextSpot = spots.find { spot -> spot.pos == nextPosition } if (nextSpot != null) nextSpot.nextBlizzards.add(it) else { val wrappedPosition = when (it.dir) { RIGHT -> pos.copy(x = left) DOWN -> pos.copy(y = top) LEFT -> pos.copy(x = right) UP -> pos.copy(y = bot) } val wrappedSpot = spots .find { spot -> spot.pos == wrappedPosition } ?: throw Exception("Spot not found") wrappedSpot.nextBlizzards.add(it) } toRemove.add(it) } toRemove.forEach { blizzards.remove(it) } } fun setBlizzards() { blizzards.addAll(nextBlizzards) nextBlizzards.clear() } } fun List<String>.toVillage(): Village { val spots = mutableSetOf<Spot>() this.forEachIndexed { y, s -> s.forEachIndexed { x, c -> val pos = Pos(x, y) when (c) { '.' -> spots.add(Spot(pos, mutableListOf(), mutableListOf())) '>' -> spots.add(Spot(pos, mutableListOf(Blizzard(RIGHT)), mutableListOf())) '<' -> spots.add(Spot(pos, mutableListOf(Blizzard(LEFT)), mutableListOf())) 'v' -> spots.add(Spot(pos, mutableListOf(Blizzard(DOWN)), mutableListOf())) '^' -> spots.add(Spot(pos, mutableListOf(Blizzard(UP)), mutableListOf())) } } } return Village(spots) } data class Blizzard(val dir: Direction)
0
Kotlin
2
0
769c4bf06ee5b9ad3220e92067d617f07519d2b7
4,313
advent-of-code-2022
Apache License 2.0
src/main/kotlin/days/Day19.kt
butnotstupid
571,247,661
false
{"Kotlin": 90768}
package days class Day19 : Day(19) { override fun partOne(): Any { val timeLeft = 24 val blueprints = parseInput() return blueprints.sumOf { blueprint -> blueprint.id * maxGeodes(blueprint, State.start(timeLeft)) } } override fun partTwo(): Any { val timeLeft = 32 val blueprints = parseInput().take(3) return blueprints.map { blueprint -> maxGeodes(blueprint, State.start(timeLeft)).toLong() }.reduce(Long::times) } private fun maxGeodes(blueprint: Blueprint, startState: State): Int { val finStates = mutableListOf<State>() val visited = Array(2) { mutableSetOf<State>() } var q = ArrayDeque<State>().apply { add(startState).also { visited[0].add(startState) } } var curTimeLeft = startState.timeLeft while (q.isNotEmpty()) { q = cutQueue(curTimeLeft, q) val state = q.removeFirst() if (state.timeLeft == 0) finStates.add(state) else with(state) { if (timeLeft < curTimeLeft) { visited[0] = visited[1] visited[1].clear() curTimeLeft = timeLeft } val produced = Resource(state.oreRobots, state.clayRobots, state.obsRobots) listOfNotNull( state, if (state.resource isEnoughFor blueprint.oreCost) state.copy( resource = state.resource - blueprint.oreCost, oreRobots = state.oreRobots + 1 ) else null, if (state.resource isEnoughFor blueprint.clayCost) state.copy( resource = state.resource - blueprint.clayCost, clayRobots = state.clayRobots + 1 ) else null, if (state.resource isEnoughFor blueprint.obsCost) state.copy( resource = state.resource - blueprint.obsCost, obsRobots = state.obsRobots + 1 ) else null, if (state.resource isEnoughFor blueprint.geoCost) state.copy( resource = state.resource - blueprint.geoCost, geoRobots = state.geoRobots.plus(state.timeLeft - 1) ) else null ).map { it.copy(resource = it.resource + produced, timeLeft = it.timeLeft - 1) }.forEach { if (it !in visited[1]) { visited[1].add(it) q.add(it) } } } } return finStates.maxOf { it.geodes } } private fun cutQueue(time: Int, q: ArrayDeque<State>, cap: Int = 1_000_000, takeTop: Double = 0.9): ArrayDeque<State> { val k = 0.25 * (time / 10 + 1) return if (q.size > cap) ArrayDeque(q.sortedByDescending { it.geodes * 70 + it.resource.obs * 4 + it.resource.ore }.take((cap * takeTop * k).toInt())) else q } private fun parseInput(): List<Blueprint> { return inputList.map { ("Blueprint (\\d*): " + "Each ore robot costs (\\d*) ore. " + "Each clay robot costs (\\d*) ore. " + "Each obsidian robot costs (\\d*) ore and (\\d*) clay. " + "Each geode robot costs (\\d*) ore and (\\d*) obsidian.") .toRegex().find(it)?.destructured ?.let { (id, oreCostOre, clayCostOre, obsidianCostOre, obsidianCostClay, geodeCostOre, geodeCostObsidian) -> Blueprint( id.toInt(), Resource(oreCostOre.toInt(), 0, 0), Resource(clayCostOre.toInt(), 0, 0), Resource(obsidianCostOre.toInt(), obsidianCostClay.toInt(), 0), Resource(geodeCostOre.toInt(), 0, geodeCostObsidian.toInt()), ) } ?: error("Failed to parse input string $it") } } data class Blueprint( val id: Int, val oreCost: Resource, val clayCost: Resource, val obsCost: Resource, val geoCost: Resource, ) data class State( val resource: Resource, val oreRobots: Int, val clayRobots: Int, val obsRobots: Int, val geoRobots: List<Int>, // timeLeft at geode robots creation val timeLeft: Int ) { val geodes = geoRobots.sum() companion object { fun start(timeLeft: Int) = State(Resource(0, 0, 0), 1, 0, 0, emptyList(), timeLeft) } } data class Resource( val ore: Int, val clay: Int, val obs: Int, ) { infix fun isEnoughFor(cost: Resource): Boolean { return (ore >= cost.ore && clay >= cost.clay && obs >= cost.obs) } operator fun minus(another: Resource): Resource { assert(ore - another.ore >= 0) { "Resource should be all positive, ore=${ore - another.ore}" } assert(clay - another.clay >= 0) { "Resource should be all positive, clay=${clay - another.clay}" } assert(obs - another.obs >= 0) { "Resource should be all positive, obs=${obs - another.obs}" } return Resource(ore - another.ore, clay - another.clay, obs - another.obs) } operator fun plus(another: Resource): Resource { return Resource(ore + another.ore, clay + another.clay, obs + another.obs) } } }
0
Kotlin
0
0
4760289e11d322b341141c1cde34cfbc7d0ed59b
5,689
aoc-2022
Creative Commons Zero v1.0 Universal
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2022/2022-24.kt
ferinagy
432,170,488
false
{"Kotlin": 787586}
package com.github.ferinagy.adventOfCode.aoc2022 import com.github.ferinagy.adventOfCode.Coord2D import com.github.ferinagy.adventOfCode.lcm import com.github.ferinagy.adventOfCode.println import com.github.ferinagy.adventOfCode.readInputLines import com.github.ferinagy.adventOfCode.searchGraph import com.github.ferinagy.adventOfCode.singleStep fun main() { val input = readInputLines(2022, "24-input") val testInput1 = readInputLines(2022, "24-test1") println("Part1:") part1(testInput1).println() part1(input).println() println() println("Part2:") part2(testInput1).println() part2(input).println() } private fun part1(input: List<String>): Int { val bb = BlizzardBasin(input) return bb.search(bb.entry, bb.exit, 0) } private fun part2(input: List<String>): Int { val bb = BlizzardBasin(input) val t1 = bb.search(bb.entry, bb.exit, 0) val t2 = bb.search(bb.exit, bb.entry, t1) val t3 = bb.search(bb.entry, bb.exit, t1 + t2) return t1 + t2 + t3 } private class BlizzardBasin(lines: List<String>) { private data class Blizzard(val position: Coord2D, val direction: Coord2D) val height = lines.size val width = lines.first().length val entry = Coord2D(lines.first().indexOf('.'), 0) val exit = Coord2D(lines.last().indexOf('.'), lines.lastIndex) private val blizzards = buildList { for (x in 0 until width) { for (y in 0 until height) { when (lines[y][x]) { '>' -> this += Blizzard(Coord2D(x, y), Coord2D(1, 0)) '<' -> this += Blizzard(Coord2D(x, y), Coord2D(-1, 0)) '^' -> this += Blizzard(Coord2D(x, y), Coord2D(0, -1)) 'v' -> this += Blizzard(Coord2D(x, y), Coord2D(0, 1)) } } } } private val loop = lcm((width - 2), (height - 2)) private val precomputed = (0 until loop).map { time -> blizzards.map { it.positionAt(time) }.toSet() } fun search(start: Coord2D, goal: Coord2D, startTime: Int): Int { return searchGraph( start = start to startTime, isDone = { (position, _) -> position == goal }, nextSteps = { state -> val (position, time) = state val all = position.adjacent(false) + position val possible = all.filter { candidate -> candidate.x in 1 .. width - 2 && (candidate.y in 1 .. height - 2 || candidate == entry || candidate == exit) && candidate !in precomputed[(time + 1) % loop] } possible.map { it to time + 1 }.toSet().singleStep() }, ) } private fun Blizzard.positionAt(time: Int): Coord2D { val c = position + (direction * time) return Coord2D(x = ((c.x - 1).mod(width - 2)) + 1, y = ((c.y - 1).mod(height - 2)) + 1) } }
0
Kotlin
0
1
f4890c25841c78784b308db0c814d88cf2de384b
2,961
advent-of-code
MIT License
kotlin/0135-candy.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}
// O(n) linear sweep solution class Solution { fun candy(ratings: IntArray): Int { val n = ratings.size val candies = IntArray (n) { 1 } for (i in 1 until n) { if (ratings[i] > ratings[i - 1]) candies[i] = candies[i - 1] + 1 } for (i in n - 2 downTo 0){ if (ratings[i] > ratings[i + 1]) candies[i] = max(candies[i], candies[i + 1] + 1) } return candies.sum() ?: n } //graph dfs solution class Solution { fun candy(ratings: IntArray): Int { val n = ratings.size val outdegree = IntArray (n) for (i in 0 until n) { if (i > 0 && ratings[i] > ratings[i - 1]) outdegree[i]++ if (i + 1 < n && ratings[i] > ratings[i + 1]) outdegree[i]++ } val q = LinkedList<Int>() for ((index, degree) in outdegree.withIndex()) { if (degree == 0) q.addLast(index) } val candies = IntArray (n) while (q.isNotEmpty()) { val i = q.removeFirst() var candy = 1 if (i > 0 && ratings[i] > ratings[i - 1]) candy = maxOf(candy, candies[i - 1] + 1) if (i < n - 1 && ratings[i] > ratings[i + 1]) candy = maxOf(candy, candies[i + 1] + 1) candies[i] = candy if (i > 0 && ratings[i] < ratings[i - 1]) { outdegree[i - 1]-- if (outdegree[i - 1] == 0) q.addLast(i - 1) } if (i < n - 1 && ratings[i] < ratings[i + 1]) { outdegree[i + 1]-- if (outdegree[i + 1] == 0) q.addLast(i + 1) } } return candies.sum()!! } }
337
JavaScript
2,004
4,367
0cf38f0d05cd76f9e96f08da22e063353af86224
1,828
leetcode
MIT License
src/questions/UniquePaths.kt
realpacific
234,499,820
false
null
package questions import _utils.UseCommentAsDocumentation import utils.shouldBe import java.math.BigInteger import java.util.* /** * A robot is located in the top-left corner of a `m x n` grid (marked 'Start' in the diagram below). * The robot can only move either down or right at any point in time. * The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). * * <img src="https://assets.leetcode.com/uploads/2018/10/22/robot_maze.png" height="150" width="350"/> * * How many possible unique paths are there? * * [Source](https://leetcode.com/problems/unique-paths/) */ @UseCommentAsDocumentation // Naive approach (times out for larger value) private class UniquePathsNaive { // this times out for large value private enum class Dir { R, D } private var answer = 0 fun uniquePaths(m: Int, n: Int): Int { if (m == 1 && n == 1) return 1 traverse(Dir.R, 0, 0, m - 1, n - 1) // go right traverse(Dir.D, 0, 0, m - 1, n - 1) // go down return answer } private fun traverse(direction: Dir, posX: Int, posY: Int, rowMaxIndex: Int, colMaxIndex: Int) { if (posX > colMaxIndex || posY > rowMaxIndex) { return } if (direction == Dir.R) { val newPositionX = posX + 1 if (newPositionX > colMaxIndex) { return } if (newPositionX == colMaxIndex && posY == rowMaxIndex) { answer++ } else { traverse(Dir.R, newPositionX, posY, rowMaxIndex, colMaxIndex) traverse(Dir.D, newPositionX, posY, rowMaxIndex, colMaxIndex) } } else { val newPositionY = posY + 1 if (newPositionY > rowMaxIndex) { return } if (posX == colMaxIndex && newPositionY == rowMaxIndex) { answer++ } else { traverse(Dir.R, posX, newPositionY, rowMaxIndex, colMaxIndex) traverse(Dir.D, posX, newPositionY, rowMaxIndex, colMaxIndex) } } } } // https://leetcode.com/problems/unique-paths/discuss/254228/Python-3-solutions:-Bottom-up-DP-Math-Picture-Explained-Clean-and-Concise // Approach III: Maintain array of arrays private class UniquePathsArraysOfArray { fun uniquePaths(m: Int, n: Int): Int { val dp = Array<Array<Int>>(m) { Array<Int>(n) { 0 } } for (row in 0..dp.lastIndex) { for (col in 0..dp[0].lastIndex) { if (row == 0 && col == 0) { dp[row][col] = 1 // only one way to get to (0,0) is moving left } else if (row == 0) { dp[row][col] = dp[row][col - 1] // only way to get to first row is move up } else if (col == 0) { dp[row][col] = dp[row - 1][col] // only way to get to left col is move left } else { dp[row][col] = dp[row - 1][col] + dp[row][col - 1] // two ways } } } return dp[m - 1][n - 1] } } // another way // Approach II: Use Combination (Yes, from high school maths) private class UniquePathsUsingCombination { fun uniquePaths(m: Int, n: Int): Int { // there are (m-1)+(n-1) moves to get to the destination // Among (m+n-2) moves, you can have max of (m-1) downs and max of (n-1) rights // how do you combine these Ds and Rs to get to the destination? // C(n, r) = n!/(n-r)!/r! // C(m+n-2, m-1) = (m+n-2)!/(n-1)!/(m-1)! // GOTCHA: 50! can't fit in Long so use BigInteger :O val _factCache = TreeMap<Int, BigInteger?>() val min = minOf(m - 1, n - 1) val max = maxOf(m - 1, n - 1) val denominator = factorial(min, _factCache) * factorial(max, _factCache) val numerator = factorial(m + n - 2, _factCache) return (numerator / denominator).toInt() } /** * Efficient if [m] sent to it is in sorted as it starts from already calculated lesser value * if it exists */ private fun factorial(m: Int, factCache: TreeMap<Int, BigInteger?>): BigInteger { if (factCache.containsKey(m)) return factCache[m]!! // add it to TreeMap i.e. key-sorted map factCache[m] = null // then find the lower key whose factorial has already been calculated val startFrom = factCache.lowerKey(m) ?: 1 // else start from 1 var ans: BigInteger = factCache[startFrom] ?: BigInteger.ONE // fact(1)=1 for (i in startFrom + 1..m) { ans = ans.multiply(i.toBigInteger()) } factCache[m] = ans return ans } } fun main() { UniquePathsNaive().uniquePaths(m = 3, n = 2) shouldBe UniquePathsUsingCombination().uniquePaths(m = 3, n = 2) shouldBe UniquePathsArraysOfArray().uniquePaths(m = 3, n = 2) shouldBe 3 UniquePathsNaive().uniquePaths(m = 7, n = 3) shouldBe UniquePathsUsingCombination().uniquePaths(m = 7, n = 3) shouldBe UniquePathsArraysOfArray().uniquePaths(m = 7, n = 3) shouldBe 28 UniquePathsNaive().uniquePaths(m = 3, n = 3) shouldBe UniquePathsUsingCombination().uniquePaths(m = 3, n = 3) shouldBe UniquePathsArraysOfArray().uniquePaths(m = 3, n = 3) shouldBe 6 UniquePathsArraysOfArray().uniquePaths(m = 51, n = 9) shouldBe UniquePathsUsingCombination().uniquePaths(m = 51, n = 9) // UniquePathsNaive().uniquePaths(m = 51, n = 9) // Leetcode times out for this }
4
Kotlin
5
93
22eef528ef1bea9b9831178b64ff2f5b1f61a51f
5,627
algorithms
MIT License
src/aoc2023/Day13.kt
anitakar
576,901,981
false
{"Kotlin": 124382}
package aoc2023 import readInput import kotlin.math.min fun main() { fun check(terrain: List<String>, split: Int): Boolean { for (i in 1..min(split, terrain.size - split - 2)) { val before = terrain[split - i] val after = terrain[split + 1 + i] if (after != before) return false } return true } fun findHorizontalLine(terrain: List<String>): Int { for (i in 0 until terrain.size - 1) { if (terrain[i] == terrain[i + 1] && check(terrain, i)) return i } return -1 } fun revert(terrain: List<String>): List<String> { val result = mutableListOf<String>() for (i in terrain[0].indices) { result.add("") } for (i in terrain.indices) { for (j in terrain[0].indices) { result[j] = result[j] + terrain[i][j] } } return result } fun summary(terrain: List<String>): Int { val horizontalIndex = findHorizontalLine(terrain) if (horizontalIndex >= 0) { return 100 * (horizontalIndex + 1) } val verticalIndex = findHorizontalLine(revert(terrain)) if (verticalIndex >= 0) { return verticalIndex + 1 } return 0 } fun summaryWithSmudge(terrain: List<String>): Int { var returnWithSmudge = false val summaryWithoutSmudge = summary(terrain) val mapping = mapOf('.' to '#', '#' to '.') for (i in terrain.indices) { for (j in terrain[0].indices) { val withSmudge = mutableListOf<String>() withSmudge.addAll(terrain) withSmudge[i] = terrain[i].substring(0, j) + mapping[terrain[i][j]] + terrain[i].substring(j + 1) val summaryWithSmudge = summary(withSmudge) if (summaryWithSmudge > 0) { if (summaryWithSmudge != summaryWithoutSmudge) return summaryWithSmudge else returnWithSmudge = true } } } return if (returnWithSmudge) summaryWithoutSmudge else 0 } fun part1(lines: List<String>): Int { var sum = 0 var startIndex = 0 var endIndex: Int while (startIndex < lines.size) { endIndex = lines.subList(startIndex, lines.size).indexOfFirst { it.trim().isEmpty() } if (endIndex == -1) endIndex = lines.size - startIndex val terrain = lines.subList(startIndex, startIndex + endIndex) sum += summary(terrain) startIndex += (endIndex + 1) } return sum } fun part2(lines: List<String>): Int { var sum = 0 var startIndex = 0 var endIndex: Int while (startIndex < lines.size) { endIndex = lines.subList(startIndex, lines.size).indexOfFirst { it.trim().isEmpty() } if (endIndex == -1) endIndex = lines.size - startIndex val terrain = lines.subList(startIndex, startIndex + endIndex) sum += summaryWithSmudge(terrain) startIndex += (endIndex + 1) } return sum } println(part1(readInput("aoc2023/Day13_test"))) println(part1(readInput("aoc2023/Day13"))) println(part2(readInput("aoc2023/Day13_test"))) println(part2(readInput("aoc2023/Day13"))) }
0
Kotlin
0
1
50998a75d9582d4f5a77b829a9e5d4b88f4f2fcf
3,392
advent-of-code-kotlin
Apache License 2.0
src/main/kotlin/days/Day11.kt
andilau
726,429,411
false
{"Kotlin": 37060}
package days @AdventOfCodePuzzle( name = "Cosmic Expansion", url = "https://adventofcode.com/2023/day/11", date = Date(day = 11, year = 2023) ) class Day11(input: List<String>) : Puzzle { private val galaxies = input.extractOnly('#').toList() override fun partOne(): Int { return galaxies .expandBy() .uniquePairs() .sumOf { pair -> pair.first.distance(pair.second) } } override fun partTwo(): Long = galaxies .expandBy(1000_000) .uniquePairs() .sumOf { pair -> pair.first.distance(pair.second).toLong() } fun sumOfTheShortestPathsBetweenAllGalaxiesExpanded(times: Int): Long = galaxies .expandBy(times) .uniquePairs() .sumOf { pair -> pair.first.distance(pair.second).toLong() } } private fun List<Point>.expandBy(factor: Int = 2): List<Point> { val emptyCols = (0..maxOf { it.x }) - map { it.x }.toSet() val emptyRows = (0..maxOf { it.y }) - map { it.y }.toSet() val xFactors = (0..maxOf { it.x }).map { col -> emptyCols.count { it < col } } val yFactors = (0..maxOf { it.y }).map { row -> emptyRows.count { it < row } } return map { (x, y) -> Point(x + xFactors[x] * (factor - 1), y + yFactors[y] * (factor - 1)) } }
3
Kotlin
0
0
9a1f13a9815ab42d7fd1d9e6048085038d26da90
1,294
advent-of-code-2023
Creative Commons Zero v1.0 Universal
aoc-2020/src/commonMain/kotlin/fr/outadoc/aoc/twentytwenty/Day16.kt
outadoc
317,517,472
false
{"Kotlin": 183714}
package fr.outadoc.aoc.twentytwenty import fr.outadoc.aoc.scaffold.Day import fr.outadoc.aoc.scaffold.readDayInput class Day16 : Day<Long> { companion object { private val ruleRegex = Regex("^([a-z ]+): ([0-9]+)-([0-9]+) or ([0-9]+)-([0-9]+)$") } private data class Rule(val fieldName: String, val validRanges: List<LongRange>) private fun Rule.isValueValid(value: Long): Boolean { return validRanges.any { range -> range.contains(value) } } private val sections: List<String> = readDayInput().split("\n\n") private val rules: List<Rule> = sections[0] .lines() .map { rule -> val groups = ruleRegex.find(rule)!!.groupValues Rule( fieldName = groups[1], validRanges = listOf( groups[2].toLong()..groups[3].toLong(), groups[4].toLong()..groups[5].toLong() ) ) } private fun String.parseTicketValues(): List<Long> = split(',').map { it.toLong() } private val myTicket: List<Long> = sections[1] .lines() .drop(1) .map { ticket -> ticket.parseTicketValues() } .first() private val nearbyTickets: List<List<Long>> = sections[2] .lines() .drop(1) .map { ticket -> ticket.parseTicketValues() } private fun mapFieldIndexesToRules(rules: List<Rule>, tickets: List<List<Long>>): Map<Int, Rule> { val fieldIndices = rules.indices // Map each index to the list of rules that could fit it val validRulesForIndices = fieldIndices.map { index -> val rulesForIndex = rules.filter { rule -> tickets.all { ticketValues -> rule.isValueValid(ticketValues[index]) } } index to rulesForIndex } // Sort the list by the number of rules that matches each index. // Helpfully, there's always n+1 valid rule for each new element, // so we can just check which element didn't exist yet in the accumulator. return validRulesForIndices .sortedBy { (_, rules) -> rules.size } .fold(emptyMap()) { acc: Map<Int, Rule>, (index: Int, possibleRules: List<Rule>) -> acc + (index to possibleRules.first { rule -> rule !in acc.values }) } } private data class Field(val name: String, val value: Long) private data class Ticket(val fields: List<Field>) private fun List<Long>.parseTicket(): Ticket { val validTickets: List<List<Long>> = nearbyTickets.filter { ticket -> ticket.all { value -> rules.any { rule -> rule.isValueValid(value) } } }.plusElement(this) val validRuleIndexes = mapFieldIndexesToRules(rules, validTickets) val myTicketRules: List<Pair<Rule, Long>> = this.mapIndexed { index, value -> validRuleIndexes.getValue(index) to value } return Ticket( fields = myTicketRules.map { (rule, value) -> Field(name = rule.fieldName, value = value) } ) } override fun step1(): Long { return nearbyTickets.flatMap { ticket -> ticket.filterNot { value -> // Filter out all valid values rules.any { rule -> rule.isValueValid(value) } } }.sum() } override fun step2(): Long { return myTicket.parseTicket() .fields .filter { field -> field.name.startsWith("departure") } .fold(1) { acc, field -> acc * field.value } } override val expectedStep1: Long = 20231 override val expectedStep2: Long = 1940065747861 }
0
Kotlin
0
0
54410a19b36056a976d48dc3392a4f099def5544
3,918
adventofcode
Apache License 2.0
src/Lesson3TimeComplexity/TapeEquilibrium.kt
slobodanantonijevic
557,942,075
false
{"Kotlin": 50634}
/** * 100/100 * @param A * @return */ fun solution(A: IntArray): Int { var left = 0 var right = A.sum() var min = 0 for (i in 1 until A.size) { left += A[i - 1] right -= A[i - 1] val diff: Int = Math.abs(left - right) min = getMin(i, diff, min) } return min } private fun getMin(i: Int, diff: Int, min: Int): Int { return if (i == 1 || diff < min) { diff } else min } /** * A non-empty array A consisting of N integers is given. Array A represents numbers on a tape. * * Any integer P, such that 0 < P < N, splits this tape into two non-empty parts: A[0], A[1], ..., A[P − 1] and A[P], A[P + 1], ..., A[N − 1]. * * The difference between the two parts is the value of: |(A[0] + A[1] + ... + A[P − 1]) − (A[P] + A[P + 1] + ... + A[N − 1])| * * In other words, it is the absolute difference between the sum of the first part and the sum of the second part. * * For example, consider array A such that: * * A[0] = 3 * A[1] = 1 * A[2] = 2 * A[3] = 4 * A[4] = 3 * We can split this tape in four places: * * P = 1, difference = |3 − 10| = 7 * P = 2, difference = |4 − 9| = 5 * P = 3, difference = |6 − 7| = 1 * P = 4, difference = |10 − 3| = 7 * Write a function: * * class Solution { public int solution(int[] A); } * * that, given a non-empty array A of N integers, returns the minimal difference that can be achieved. * * For example, given: * * A[0] = 3 * A[1] = 1 * A[2] = 2 * A[3] = 4 * A[4] = 3 * the function should return 1, as explained above. * * Write an efficient algorithm for the following assumptions: * * N is an integer within the range [2..100,000]; * each element of array A is an integer within the range [−1,000..1,000]. */
0
Kotlin
0
0
155cf983b1f06550e99c8e13c5e6015a7e7ffb0f
1,798
Codility-Kotlin
Apache License 2.0
src/days/Day02/Day02.kt
SimaoMata
573,172,347
false
{"Kotlin": 3659}
package days.Day02 import readInput //Part1 //A - Rock - X : 1 Point //B - Paper - Y : 2 Points //C - Scissors - Z : 3 Points //W = 6 //D = 3 //L = 0 //Part2 //W = 6 Z //D = 3 Y //L = 0 X fun main() { // test if implementation meets criteria from the description, like: val inputPart1 = readInput("Day02") println(part1(inputPart1)) val inputPart2 = readInput("Day02") println(part2(inputPart2)) } fun part1(input: String): Int { return getTotalScore(input) } private fun getTotalScore(rounds: String): Int { return rounds .split("\n") .sumOf { val signs = it.split(" ") getResult(signs[0], signs[1]) + getSignValue(signs[1]) } } private fun getResult(opponentSign: String, yourSign: String): Int { return when (opponentSign) { "A" -> when (yourSign) { "X" -> 3 "Y" -> 6 else -> 0 } "B" -> when (yourSign) { "X" -> 0 "Y" -> 3 else -> 6 } "C" -> when (yourSign) { "X" -> 6 "Y" -> 0 else -> 3 } else -> 0 } } private fun getSignValue(sign: String): Int { return when (sign) { "X" -> 1 "Y" -> 2 "Z" -> 3 else -> 0 } } fun part2(input: String): Int { return getTotalScorePart2(input) } private fun getTotalScorePart2(rounds: String): Int { return rounds .split("\n") .sumOf { val values = it.split(" ") getResultPart2(values[0], values[1]) } } private fun getResultPart2(opponentSign: String, condition: String): Int { return when (opponentSign) { "A" -> when (condition) { "X" -> 3 "Y" -> 4 else -> 8 } "B" -> when (condition) { "X" -> 1 "Y" -> 5 else -> 9 } "C" -> when (condition) { "X" -> 2 "Y" -> 6 else -> 7 } else -> 0 } }
0
Kotlin
0
0
bc3ba76e725b02c893aacc033c99169d7a022614
2,066
advent-of-code-2022
Apache License 2.0
src/main/kotlin/de/mbdevelopment/adventofcode/year2021/solvers/day9/Day9Puzzle2.kt
Any1s
433,954,562
false
{"Kotlin": 96683}
package de.mbdevelopment.adventofcode.year2021.solvers.day9 import de.mbdevelopment.adventofcode.year2021.solvers.PuzzleSolver class Day9Puzzle2 : PuzzleSolver { override fun solve(inputLines: Sequence<String>) = sizeSumOfThreeLargestBasins(inputLines).toString() private fun sizeSumOfThreeLargestBasins(rawHeightMap: Sequence<String>): Int { val heightMap = rawHeightMap .filter { it.isNotBlank() } .map { line -> line.map { it.digitToInt() } } .toList() val lowPointStarts = (heightMap.first().indices).map { x -> (heightMap.indices).map { y -> val adjacentHeights = listOfNotNull( heightMap[y].getOrNull(x - 1), // value to the left heightMap[y].getOrNull(x + 1), // value to the right heightMap.getOrNull(y - 1)?.get(x), // value above heightMap.getOrNull(y + 1)?.get(x), // value below ) val currentHeight = heightMap[y][x] if (adjacentHeights.all { currentHeight < it }) Point(x, y) else null } }.flatMap { it.filterNotNull() } .toMutableSet() val basinSizes = mutableListOf<Int>() while (lowPointStarts.isNotEmpty()) { val basin = scoutBasin(heightMap, lowPointStarts.first()) basinSizes += basin.size lowPointStarts -= lowPointStarts.filter { it in basin }.toSet() // Probably faster than '-= basin' } return basinSizes.sorted().takeLast(3).reduce(Int::times) } private fun scoutBasin( heightMap: List<List<Int>>, currentPoint: Point, knownBasinPart: MutableSet<Point> = mutableSetOf(), border: MutableSet<Point> = mutableSetOf() ): Set<Point> { return if (heightMap[currentPoint.y][currentPoint.x] == 9) { // Basin border reached border += currentPoint emptySet() } else { knownBasinPart += currentPoint val left = currentPoint.copy(x = currentPoint.x - 1) val right = currentPoint.copy(x = currentPoint.x + 1) val above = currentPoint.copy(y = currentPoint.y + 1) val below = currentPoint.copy(y = currentPoint.y - 1) sequenceOf(left, right, above, below) .filter { it.x >= 0 && it.x < heightMap.first().size && it.y >= 0 && it.y < heightMap.size } .filter { it !in border } .filter { it !in knownBasinPart } .map { scoutBasin(heightMap, it, knownBasinPart, border) } .fold(emptySet(), Set<Point>::union) .plus(currentPoint) } } data class Point(val x: Int, val y: Int) }
0
Kotlin
0
0
21d3a0e69d39a643ca1fe22771099144e580f30e
2,806
AdventOfCode2021
Apache License 2.0
kotlin/problems/src/solution/SimulatedProgram.kt
lunabox
86,097,633
false
{"Kotlin": 146671, "Python": 38767, "JavaScript": 19188, "Java": 13966}
package solution import data.structure.Employee import java.util.* import kotlin.collections.HashMap import kotlin.collections.HashSet import kotlin.math.abs import kotlin.math.max import kotlin.math.min class SimulatedProgram { /** * https://leetcode-cn.com/problems/robot-return-to-origin/ */ fun judgeCircle(moves: String): Boolean { var x = 0 var y = 0 moves.forEach { when (it) { 'R' -> x++ 'L' -> x-- 'D' -> y-- 'U' -> y++ } } return x == 0 && y == 0 } fun coinChange(coins: IntArray, amount: Int): Int { // 缓存钱数对应的最小硬币数 val coinsMin = IntArray(amount + 1) { 0 } for (i in 1..amount) { var minCount = Int.MAX_VALUE coins.filter { it <= i }.forEach { val curUsed = coinsMin[i - it] + 1 if (coinsMin[i - it] >= 0 && curUsed < minCount) { minCount = curUsed } } coinsMin[i] = if (minCount != Int.MAX_VALUE) { minCount } else { -1 } } return coinsMin[amount] } /** * https://leetcode-cn.com/problems/minimum-index-sum-of-two-lists/ */ fun findRestaurant(list1: Array<String>, list2: Array<String>): Array<String> { var minStep = Int.MAX_VALUE val hash = HashMap<String, Int>(list1.size) val result = HashMap<String, Int>() list1.forEachIndexed { index, s -> hash[s] = index } list2.forEachIndexed { index, s -> if (s in hash) { if (index + hash[s]!! < minStep) { minStep = index + hash[s]!! } result[s] = hash[s]!! + index } } return result.filter { it.value == minStep }.keys.toTypedArray() } /** * https://leetcode-cn.com/problems/binary-search/ */ fun search(nums: IntArray, target: Int): Int { var left = 0 var right = nums.lastIndex while (left <= right) { val middle = (left + right) / 2 when { target < nums[middle] -> right = middle - 1 target > nums[middle] -> left = middle + 1 else -> return middle } } return -1 } /** * https://leetcode-cn.com/problems/rectangle-overlap/ */ fun isRectangleOverlap(rec1: IntArray, rec2: IntArray): Boolean { val w1 = (rec1[2] - rec1[0]).toLong() val h1 = (rec1[3] - rec1[1]).toLong() val xm1 = (rec1[2] + rec1[0]).toLong() val ym1 = (rec1[3] + rec1[1]).toLong() val w2 = (rec2[2] - rec2[0]).toLong() val h2 = (rec2[3] - rec2[1]).toLong() val xm2 = (rec2[2] + rec2[0]).toLong() val ym2 = (rec2[3] + rec2[1]).toLong() return (abs(xm1 - xm2) < (w1 + w2)) && (abs(ym1 - ym2) < (h1 + h2)) } /** * https://leetcode-cn.com/problems/rectangle-area/ * 在二维平面上计算出两个由直线构成的矩形重叠后形成的总面积。 */ fun computeArea(A: Int, B: Int, C: Int, D: Int, E: Int, F: Int, G: Int, H: Int): Int { val lx = max(A, E).toLong() val ly = max(B, F).toLong() val rx = min(C, G).toLong() val ry = min(D, H).toLong() val area1 = (C - A).toLong() * (D - B) val area2 = (G - E).toLong() * (H - F) // 未相交 if (E > C || F > D || G < A || H < B) { return (area1 + area2).toInt() } return (area1 + area2 - (rx - lx) * (ry - ly)).toInt() } /** * https://leetcode-cn.com/problems/available-captures-for-rook/ * 车的可用捕获量 */ fun numRookCaptures(board: Array<CharArray>): Int { var rx = 0 var ry = 0 var result = 0 board.forEachIndexed { indexArray, chars -> chars.forEachIndexed { indexChar, c -> if (c == 'R') { rx = indexChar ry = indexArray } } } right@ for (i in rx + 1 until board.size) { when (board[ry][i]) { 'p' -> { result++ break@right } '.' -> continue@right 'B', 'b', 'P' -> break@right } } left@ for (i in rx - 1 downTo 0) { when (board[ry][i]) { 'p' -> { result++ break@left } '.' -> continue@left 'B', 'b', 'P' -> break@left } } up@ for (j in ry - 1 downTo 0) { when (board[j][rx]) { 'p' -> { result++ break@up } '.' -> continue@up 'B', 'b', 'P' -> break@up } } down@ for (j in ry + 1 until board.size) { when (board[j][rx]) { 'p' -> { result++ break@down } '.' -> continue@down 'B', 'b', 'P' -> break@down } } return result } /** * https://leetcode-cn.com/problems/unique-morse-code-words/ */ fun uniqueMorseRepresentations(words: Array<String>): Int { val morse = arrayOf( ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.." ) val set = HashSet<String>() words.forEach words@{ word -> val code = StringBuffer() word.forEach { code.append(morse[it - 'a']) } set.add(code.toString()) } return set.size } /** * https://leetcode-cn.com/problems/subdomain-visit-count/ */ fun subdomainVisits(cpdomains: Array<String>): List<String> { val countMap = HashMap<String, Int>() cpdomains.forEach { val countName = it.split(" ") if (countName.size >= 2) { val count = countName[0].toInt() val domain = countName[1] countMap[domain] = countMap[domain]?.plus(count) ?: count var index = -1 while (true) { index = domain.indexOf(".", index + 1) if (index == -1) { break } val newDomain = domain.slice(IntRange(index + 1, domain.lastIndex)) countMap[newDomain] = countMap[newDomain]?.plus(count) ?: count } } } val result = mutableListOf<String>() countMap.keys.forEach { result.add("${countMap[it]} $it") } return result } /** * https://leetcode-cn.com/problems/count-number-of-teams/ */ fun numTeams(rating: IntArray): Int { var sum = 0 for (i in 1 until rating.lastIndex) { var minLeftSum = 0 var maxLeftSum = 0 for (j in 0 until i) { if (rating[j] > rating[i]) { maxLeftSum++ } else if (rating[j] < rating[i]) { minLeftSum++ } } var minRightSum = 0 var maxRightSum = 0 for (j in i + 1 until rating.size) { if (rating[j] > rating[i]) { maxRightSum++ } else if (rating[j] < rating[i]) { minRightSum++ } } sum += (minLeftSum * maxRightSum) + (maxLeftSum * minRightSum) } return sum } /** * https://leetcode-cn.com/problems/number-of-days-between-two-dates/ */ fun daysBetweenDates(date1: String, date2: String): Int { val parserDate: (Int, Int, Int) -> Int = { year, month, day -> val monthDays = intArrayOf(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31) var days = 0 for (i in 1 until month) { days += monthDays[i - 1] } if ((year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) && month > 2) { days++ } days += day days += 365 * (year - 1970) + (year - 1) / 4 - (year - 1) / 100 + (year - 1) / 400 days } val days1 = parserDate(date1.take(4).toInt(), date1.slice(IntRange(5, 6)).toInt(), date1.takeLast(2).toInt()) val days2 = parserDate(date2.take(4).toInt(), date2.slice(IntRange(5, 6)).toInt(), date2.takeLast(2).toInt()) return abs(days2 - days1) } /** * https://leetcode-cn.com/problems/container-with-most-water/ */ fun maxArea(height: IntArray): Int { var area = 0 for (i in 0 until height.lastIndex) { for (j in i + 1 until height.size) { val s = (j - i) * min(height[j], height[i]) area = max(area, s) } } return area } /** * https://leetcode-cn.com/contest/weekly-contest-125/problems/find-the-town-judge/ */ fun findJudge(N: Int, trust: Array<IntArray>): Int { val vote = IntArray(N) { 0 } trust.forEach { if (it.size >= 2) { vote[it[0] - 1]-- vote[it[1] - 1]++ } } val index = vote.indexOfFirst { it == N - 1 } return if (index >= 0) index + 1 else -1 } /** * https://leetcode-cn.com/contest/weekly-contest-135/problems/valid-boomerang/ */ fun isBoomerang(points: Array<IntArray>): Boolean { if (points[0][1] == points[1][1] && points[0][0] == points[1][0] || points[1][1] == points[2][1] && points[1][0] == points[2][0] || points[0][1] == points[2][1] && points[0][0] == points[2][0] ) { return false } // x相同 if (points[0][0] == points[1][0]) { return points[0][0] != points[2][0] } // y相同 if (points[0][1] == points[1][1]) { return points[0][1] != points[2][1] } return (points[2][1] - points[0][1]) * (points[1][0] - points[0][0]) != (points[2][0] - points[0][0]) * (points[1][1] - points[0][1]) } /** * https://leetcode-cn.com/problems/surface-area-of-3d-shapes/ */ fun surfaceArea(grid: Array<IntArray>): Int { var ans = 0 grid.forEachIndexed { i, ints -> ints.forEachIndexed { j, n -> if (n > 0) { ans += 4 * n + 2 if (j > 0) { ans -= min(ints[j - 1], n) * 2 } if (i > 0) { ans -= min(grid[i - 1][j], n) * 2 } } } } return ans } /** * */ fun minCount(coins: IntArray): Int { var sum = 0 coins.forEach { sum += (it + 1) / 2 } return sum } private var wayCount = 0 /** * */ fun numWays(n: Int, relation: Array<IntArray>, k: Int): Int { wayDfs(n, k, 0, 0, relation) return wayCount } private fun wayDfs(n: Int, k: Int, level: Int, pos: Int, relation: Array<IntArray>) { if (level == k) { // k轮 if (pos == n - 1) { wayCount++ } return } relation.forEach { if (it[0] == pos) { wayDfs(n, k, level + 1, it[1], relation) } } } /** * */ fun getTriggerTime(increase: Array<IntArray>, requirements: Array<IntArray>): IntArray { val m = IntArray(3) { 0 } val ans = IntArray(requirements.size) { -1 } val rSort = Array(requirements.size) { IntArray(4) } var startIndex = 0 requirements.forEachIndexed { index, ints -> rSort[index][0] = ints[0] rSort[index][1] = ints[1] rSort[index][2] = ints[2] rSort[index][3] = index if (ints[0] == 0 && ints[1] == 0 && ints[2] == 0) { ans[index] = 0 } } increase.forEachIndexed { index, it -> m[0] += it[0] m[1] += it[1] m[2] += it[2] val start = startIndex for (i in start until rSort.size) { if (ans[rSort[i][3]] == -1 && rSort[i][0] <= m[0] && rSort[i][1] <= m[1] && rSort[i][2] <= m[2]) { ans[rSort[i][3]] = index + 1 val temp = rSort[i] rSort[i] = rSort[startIndex] rSort[startIndex] = temp startIndex++ } } } return ans } /** * https://leetcode-cn.com/contest/weekly-contest-185/problems/display-table-of-food-orders-in-a-restaurant/ */ fun displayTable(orders: List<List<String>>): List<List<String>> { val ans = mutableListOf<List<String>>() val foods = HashSet<String>() val orderMap = HashMap<Int, MutableMap<String, Int>>() orders.forEach { order -> val foodName = order[2] foods.add(foodName) val id = order[1].toInt() if (id in orderMap) { val map = orderMap[id]!! map[foodName] = map[foodName]?.plus(1) ?: 1 } else { orderMap[id] = mutableMapOf(Pair(foodName, 1)) } } val title = mutableListOf("Table") foods.sorted().forEach { title.add(it) } ans.add(title) orderMap.keys.sorted().forEach { key -> val map = orderMap[key]!! val line = mutableListOf(key.toString()) for (i in 1 until title.size) { line.add(map[title[i]]?.toString() ?: "0") } ans.add(line) } return ans } /** * https://leetcode-cn.com/contest/weekly-contest-185/problems/minimum-number-of-frogs-croaking/ */ fun minNumberOfFrogs(croakOfFrogs: String): Int { val frogs = mutableListOf<Int>() val croak = charArrayOf('c', 'r', 'o', 'a', 'k') croakOfFrogs.forEach { val index = croak.indexOf(it) frogs.forEachIndexed { i, item -> if (item + 1 == index) { frogs[i]++ if (index == croak.lastIndex) { frogs[i] = -1 } return@forEach } } if (index != 0) { return -1 } frogs.add(0) } if (frogs.count { it == -1 } != frogs.size) { return -1 } return frogs.size } /** * https://leetcode-cn.com/problems/employee-importance/ */ fun getImportance(employees: List<Employee?>, id: Int): Int { val ids = HashMap<Int, Employee>() employees.forEach { if (it != null) { ids[it.id] = it } } var ans = 0 val target = mutableListOf<Int>() target.add(id) while (target.isNotEmpty()) { val p = ids[target.first()] if (p != null) { ans += p.importance target.addAll(p.subordinates) target.removeAt(0) } } return ans } /** * https://leetcode-cn.com/problems/gray-code/ */ fun grayCode(n: Int): List<Int> { val ans = mutableListOf<Int>() ans.add(0) repeat(n) { val size = ans.size for (i in size - 1 downTo 0) { val code = (1).shl(it).or(ans[i]) ans.add(code) } } return ans } fun largestPerimeter(A: IntArray): Int { A.sort() for (i in A.lastIndex downTo 2) { if (A[i - 1] + A[i - 2] > A[i]) { return A[i - 1] + A[i - 2] + A[i] } } return 0 } /** * https://leetcode-cn.com/problems/number-of-lines-to-write-string/ */ fun numberOfLines(widths: IntArray, S: String): IntArray { var line = 1 var width = 0 S.forEach { val charWidth = widths[it - 'a'] if (charWidth + width <= 100) { width += charWidth } else { width = charWidth line++ } } return intArrayOf(line, width) } /** * https://leetcode-cn.com/problems/how-many-numbers-are-smaller-than-the-current-number/ */ fun smallerNumbersThanCurrent(nums: IntArray): IntArray { val count = Array(101) { 0 } val ans = IntArray(nums.size) nums.forEach { count[it]++ } var temp = 0 count.forEachIndexed { index, i -> if (index > 0) { val small = temp + count[index - 1] temp = i count[index] = small } else { temp = count[0] count[0] = 0 } } nums.forEachIndexed { index, i -> ans[index] = count[i] } return ans } /** * https://leetcode-cn.com/problems/maximize-distance-to-closest-person/ */ fun maxDistToClosest(seats: IntArray): Int { val left = IntArray(seats.size) { seats.size } val right = IntArray(seats.size) { seats.size } for (i in seats.indices) { if (seats[i] == 1) { left[i] = 0 } else if (i > 0) { left[i] = left[i - 1] + 1 } } for (i in seats.lastIndex downTo 0) { if (seats[i] == 1) { right[i] = 0 } else if (i < seats.lastIndex) { right[i] = right[i + 1] + 1 } } var ans = 0 seats.forEachIndexed { index, i -> if (i == 0) { ans = max(ans, min(left[index], right[index])) } } return ans } /** * https://leetcode-cn.com/problems/backspace-string-compare/ */ fun backspaceCompare(S: String, T: String): Boolean { val s = Stack<Char>() val t = Stack<Char>() val action: (String, Stack<Char>) -> Unit = { c, stack -> c.forEach { if (it == '#') { if (stack.isNotEmpty()) { stack.pop() } } else { stack.push(it) } } } action(S, s) action(T, t) if (s.size != t.size) { return false } for (i in s.indices) { if (s.pop() != t.pop()) { return false } } return true } /** * https://leetcode-cn.com/problems/diagonal-traverse-ii/ */ fun findDiagonalOrder(nums: List<List<Int>>): IntArray { val ans = mutableListOf<Int>() val queue = LinkedList<IntArray>() val addQueue: (LinkedList<IntArray>, Int, Int, List<MutableList<Int>>) -> Unit = { q, i, j, n -> if (i < nums.size && j < nums[i].size && nums[i][j] >= 0) { val num = n[i][j] n[i][j] = -num q.add(intArrayOf(i, j, num)) } } addQueue(queue, 0, 0, nums as List<MutableList<Int>>) while (queue.isNotEmpty()) { val item = queue.pop() ans.add(item[2]) addQueue(queue, item[0] + 1, item[1], nums) addQueue(queue, item[0], item[1] + 1, nums) } return ans.toIntArray() } /** * https://leetcode-cn.com/problems/jewels-and-stones/ */ fun numJewelsInStones(J: String, S: String): Int { val flag = IntArray(52) { 0 } var ans = 0 J.forEach { if (it.isLowerCase()) { flag[it - 'a']++ } else if (it.isUpperCase()) { flag[it - 'A' + 26]++ } } S.forEach { if (it.isLowerCase()) { ans += if (flag[it - 'a'] > 0) 1 else 0 } else if (it.isUpperCase()) { ans += if (flag[it - 'A' + 26] > 0) 1 else 0 } } return ans } }
0
Kotlin
0
0
cbb2e3ad8f2d05d7cc54a865265561a0e391a9b9
21,253
leetcode
Apache License 2.0
src/Day04.kt
cisimon7
573,872,773
false
{"Kotlin": 41406}
fun main() { fun part1(pairs: List<Pair<IntRange, IntRange>>): Int { return pairs.count { (section1, section2) -> val inter = section1 intersect section2 inter.containsAll(section1.toSet()) || inter.containsAll(section2.toSet()) } } fun part2(pairs: List<Pair<IntRange, IntRange>>): Int { return pairs.count { (section1, section2) -> (section1 intersect section2).isNotEmpty() } } fun parse(stringList: List<String>): List<Pair<IntRange, IntRange>> { return stringList.map { pair -> pair.split(",") .map { section -> section.split("-") } .map { section -> section[0].toInt()..section[1].toInt() } }.map { pair -> Pair(pair[0], pair[1]) } } val testInput = readInput("Day04_test") check(part1(parse(testInput)) == 2) check(part2(parse(testInput)) == 4) val input = readInput("Day04_input") println(part1(parse(input))) println(part2(parse(input))) }
0
Kotlin
0
0
29f9cb46955c0f371908996cc729742dc0387017
1,029
aoc-2022
Apache License 2.0
src/main/kotlin/d5/D5_2.kt
MTender
734,007,442
false
{"Kotlin": 108628}
package d5 import input.Input fun findRangeDestination(sourceRange: Pair<Long, Long>, mappings: List<Mapping>): List<Pair<Long, Long>> { val sourceStart = sourceRange.first val sourceLength = sourceRange.second val mappedRanges = mutableListOf<Pair<Long, Long>>() val destinations = mutableListOf<Pair<Long, Long>>() for (mapping in mappings) { val offset = mapping.dest - mapping.source if (mapping.source <= sourceStart && sourceStart < mapping.source + mapping.length) { val destStart = sourceStart + offset val destLength = if (sourceStart + sourceLength < mapping.source + mapping.length) sourceLength else mapping.source + mapping.length - sourceStart mappedRanges.add(Pair(sourceStart, destLength)) destinations.add(Pair(destStart, destLength)) } else if (sourceStart < mapping.source && mapping.source < sourceStart + sourceLength) { val destStart = mapping.source + offset val destLength = if (sourceStart + sourceLength < mapping.source + mapping.length) sourceStart + sourceLength - mapping.source else mapping.length mappedRanges.add(Pair(mapping.source, destLength)) destinations.add(Pair(destStart, destLength)) } } destinations.addAll(getComplementRanges(sourceRange, mappedRanges)) return destinations } fun getComplementRanges(parentRange: Pair<Long, Long>, ranges: List<Pair<Long, Long>>): List<Pair<Long, Long>> { var start = parentRange.first val end = parentRange.first + parentRange.second - 1 val sortedRanges = ranges.sortedBy { it.first } val complementRanges = mutableListOf<Pair<Long, Long>>() for (range in sortedRanges) { if (start < range.first) complementRanges.add(Pair(start, range.first - start)) start = range.first + range.second } if (start < end) complementRanges.add(Pair(start, end - start + 1)) return complementRanges } fun main() { val lines = Input.read("input.txt") val seeds = parseSeeds(lines[0]) val mappingLists = getMappingLists(lines) var ranges = mutableListOf<Pair<Long, Long>>() for (i in seeds.indices step 2) { ranges.add(Pair(seeds[i], seeds[i + 1])) } for (mappings in mappingLists) { val newRanges = mutableListOf<Pair<Long, Long>>() for (range in ranges) { newRanges.addAll(findRangeDestination(range, mappings)) } ranges = newRanges } val locations = ranges.map { it.first } println(locations.min()) }
0
Kotlin
0
0
a6eec4168b4a98b73d4496c9d610854a0165dbeb
2,663
aoc2023-kotlin
MIT License
Array/austenYang/Leetcode/JavaKotlin/src/algorithms4/chapter_2/Sort/sort.kt
JessonYue
268,215,243
false
null
package algorithms4.chapter_2.Sort fun selectSort(array: IntArray) { for (i in array.indices) { var minIndex = i for (j in i until array.size) { if (array[minIndex] > array[j]) { minIndex = j } } swap(array, i, minIndex) } } /** * 1. 将第一待排序序列第一个元素看做一个有序序列,把第二个元素到最后一个元素当成是未排序序列。 * 2. 从头到尾依次扫描未排序序列,将扫描到的每个元素插入有序序列的适当位置。 */ fun insertSort(array: IntArray) { for (i in 1 until array.size) { var j = i while (j > 0 && array[j] < array[j - 1]) { val temp = array[j - 1] array[j - 1] = array[j] array[j] = temp j-- } } } fun mergeSort(array: IntArray) { mergeSortInner(array, 0, array.size - 1) } private fun mergeSortInner(array: IntArray, lo: Int, hi: Int) { if (lo >= hi) return val mid = lo + (hi - lo) / 2 mergeSortInner(array, lo, mid) mergeSortInner(array, mid + 1, hi) merge(array, lo, mid, hi) } private fun merge(array: IntArray, lo: Int, mid: Int, hi: Int) { var i = lo var j = mid + 1 val temp = array.copyOf() for (k in lo..hi) { when { i > mid -> array[k] = temp[j++] j > hi -> array[k] = temp[i++] temp[i] < temp[j] -> array[k] = temp[i++] else -> array[k] = temp[j++] } } } fun quickSort(intArray: IntArray) { quickSortInner(intArray, 0, intArray.size - 1) } private fun quickSortInner(intArray: IntArray, lo: Int, hi: Int) { if (lo >= hi) return val j = partition(intArray, lo, hi) quickSortInner(intArray, lo, j - 1) quickSortInner(intArray, j + 1, hi) } private fun partition(intArray: IntArray, lo: Int, hi: Int): Int { var i = lo var j = hi + 1 val v = intArray[lo] while (true) { while (intArray[++i] < v) if (i == hi) break while (intArray[--j] > v) if (j == lo) break if (i >= j) break swap(intArray, i, j) } swap(intArray, lo, j) return j } private fun swap(intArray: IntArray, i: Int, j: Int) { val temp = intArray[i] intArray[i] = intArray[j] intArray[j] = temp } fun main() { val arrays = intArrayOf(1, 3, 2, 1) insertSort(arrays) mergeSort(arrays) quickSort(arrays) selectSort(arrays) arrays.forEach(::println) }
0
C
19
39
3c22a4fcdfe8b47f9f64b939c8b27742c4e30b79
2,494
LeetCodeLearning
MIT License
src/Day02.kt
Qdelix
574,590,362
false
null
fun main() { fun part1(input: List<String>): Int { var score = 0 input.forEach { line -> val lineWithoutWhiteSpaces = line.filter { !it.isWhitespace() } val opponent = lineWithoutWhiteSpaces[0].toString() val you = lineWithoutWhiteSpaces[1].toString() val opponentMove = Thing.getThing(opponent) val yourMove = Thing.getThing(you) score += Thing.getRoundResultScore(opponentMove, yourMove) score += yourMove.points } return score } fun part2(input: List<String>): Int { var score = 0 input.forEach { line -> val lineWithoutWhiteSpaces = line.filter { !it.isWhitespace() } val opponent = lineWithoutWhiteSpaces[0].toString() val endingResult = lineWithoutWhiteSpaces[1].toString() val opponentMove = Thing.getThing(opponent) val yourMove = Thing.getThingInCaseOfEndingResult(opponentMove, endingResult) score += Thing.getRoundResultScore(opponentMove, yourMove) score += yourMove.points } return score } val input = readInput("Day02") println(part1(input)) println(part2(input)) } enum class Thing(val points: Int) { SCISSORS(3), ROCK(1), PAPER(2); companion object { fun getThing(letter: String): Thing { return when (letter) { "A", "X" -> ROCK "B", "Y" -> PAPER "C", "Z" -> SCISSORS else -> SCISSORS } } fun getThingInCaseOfEndingResult(opponentThing: Thing, endingResult: String): Thing { return when { endingResult == "Y" -> opponentThing opponentThing == ROCK && endingResult == "X" -> SCISSORS opponentThing == ROCK && endingResult == "Z" -> PAPER opponentThing == PAPER && endingResult == "X" -> ROCK opponentThing == PAPER && endingResult == "Z" -> SCISSORS opponentThing == SCISSORS && endingResult == "X" -> PAPER opponentThing == SCISSORS && endingResult == "Z" -> ROCK else -> SCISSORS } } fun getRoundResultScore(opponentMove: Thing, yourMove: Thing): Int { val lose = (opponentMove == ROCK && yourMove == SCISSORS) || (opponentMove == SCISSORS && yourMove == PAPER) || (opponentMove == PAPER && yourMove == ROCK) val draw = opponentMove == yourMove val win = (opponentMove == SCISSORS && yourMove == ROCK) || (opponentMove == PAPER && yourMove == SCISSORS) || (opponentMove == ROCK && yourMove == PAPER) return when { draw -> 3 lose -> 0 win -> 6 else -> 0 } } } }
0
Kotlin
0
0
8e5c599d5071d9363c8f33b800b008875eb0b5f5
2,960
aoc22
Apache License 2.0
src/main/kotlin/wtf/log/xmas2021/day/day14/Day14.kt
damianw
434,043,459
false
{"Kotlin": 62890}
package wtf.log.xmas2021.day.day14 import com.google.common.collect.HashMultiset import wtf.log.xmas2021.Day import java.io.BufferedReader object Day14 : Day<Input, Int, Long> { override fun parseInput(reader: BufferedReader): Input { val template = reader.readLine() require(reader.readLine().isEmpty()) val rules = reader .lineSequence() .map { line -> val split = line.split(" -> ") require(split.size == 2) val first = split.first() require(first.length == 2) val second = split.last().single() Rule( pattern = first[0] to first[1], insertedChar = second, ) } .toList() return Input(template, rules) } override fun part1(input: Input): Int { var polymer = input.template val rules = input.ruleMap repeat(10) { val windows = polymer.windowed(2) polymer = windows .mapIndexed { index, window -> check(window.length == 2) val pair = window[0] to window[1] val replacement = rules[pair]?.replacement ?: window if (index == windows.lastIndex) replacement else replacement.dropLast(1) } .joinToString("") } val chars = HashMultiset.create(polymer.asIterable()) val mostCommonChar = checkNotNull(chars.elementSet().maxByOrNull(chars::count)) val leastCommonChar = checkNotNull(chars.elementSet().minByOrNull(chars::count)) return chars.count(mostCommonChar) - chars.count(leastCommonChar) } override fun part2(input: Input): Long { val rules = input.ruleMap val startingPatterns = input.template.windowed(2).map { window -> check(window.length == 2) window[0] to window[1] } val patterns = mutableMapOf<Pair<Char, Char>, Long>() for (pattern in startingPatterns) { patterns.merge(pattern, 1, Long::plus) } val newPatterns = mutableMapOf<Pair<Char, Char>, Long>() repeat(40) { for ((pattern, count) in patterns.entries) { val rule = rules[pattern] if (rule == null) { newPatterns.merge(pattern, count, Long::plus) } else { for (replacement in rule.replacementPatterns) { newPatterns.merge(replacement, count, Long::plus) } } } patterns.clear() patterns.putAll(newPatterns) newPatterns.clear() } val chars = mutableMapOf<Char, Long>() for ((pattern, count) in patterns) { chars.merge(pattern.first, count, Long::plus) chars.merge(pattern.second, count, Long::plus) } // Every character is counted twice, except for the starting and ending characters. Add one // for each of those so that all entries are exactly doubled. chars[input.template.first()] = chars.getValue(input.template.first()) + 1 chars[input.template.last()] = chars.getValue(input.template.last()) + 1 val mostCommonCount = chars.entries.maxOf { it.value } val leastCommonCount = chars.entries.minOf { it.value } val difference = mostCommonCount - leastCommonCount return difference / 2L } } data class Rule( val pattern: Pair<Char, Char>, val insertedChar: Char, ) { val replacement: String = "${pattern.first}$insertedChar${pattern.second}" val replacementPatterns: List<Pair<Char, Char>> = listOf( pattern.first to insertedChar, insertedChar to pattern.second, ) } data class Input( val template: String, val ruleList: List<Rule>, ) { val ruleMap: Map<Pair<Char, Char>, Rule> = ruleList.associateBy { it.pattern } }
0
Kotlin
0
0
1c4c12546ea3de0e7298c2771dc93e578f11a9c6
4,042
AdventOfKotlin2021
BSD Source Code Attribution
src/main/kotlin/Day4.kt
Ostkontentitan
434,500,914
false
{"Kotlin": 73563}
import java.lang.IllegalStateException fun puzzleDayFourPartOne() { val inputs = readInput(4).filter { it.isNotEmpty() } val drawnNumbers = inputs[0].split(",") val boards: List<BingoBoard> = constructBoards(inputs) var finished = false drawnNumbers.forEach { number -> if (finished) { return@forEach } boards.forEach { it.checkNumber(number) } val completedBoard = boards.firstOrNull { it.isCompleted() } if (completedBoard != null) { val uncheckedValues = completedBoard.rows.flatMap { row -> row.filter { !it.checked }.map { it.value.toInt() } } val finalResults = uncheckedValues.sum() * number.toInt() println("First winning bingo board score: $finalResults") finished = true return } } } fun puzzleDayFourPartTwo() { val inputs = readInput(4).filter { it.isNotEmpty() } val drawnNumbers = inputs[0].split(",") var boards: List<BingoBoard> = constructBoards(inputs) var lastWinningNumber = -1 var lastWinningBoard: BingoBoard? = null drawnNumbers.forEach { number -> boards.forEach { it.checkNumber(number) } val (completedBoards, notCompletedBoards) = boards.partition { it.isCompleted() } boards = notCompletedBoards if (completedBoards.isNotEmpty()) { lastWinningNumber = number.toInt() lastWinningBoard = completedBoards.last() } } val uncheckedValues = lastWinningBoard!!.rows.flatMap { row -> row.filter { !it.checked }.map { it.value.toInt() } } val finalResults = uncheckedValues.sum() * lastWinningNumber println("Last winning bingo board score: $finalResults") } fun constructBoards(inputs: List<String>): List<BingoBoard> { val boardsInputs = inputs.subList(1, inputs.lastIndex + 1) return boardsInputs.windowed(5, 5).map { rawRows -> val rows = rawRows.map { rowValue -> rowValue.trim().replace(" ", " ").split(" ").map { if (it.isNotEmpty()) Entry(it) else throw IllegalStateException("Malformed input for row value in row.: $rowValue") } } val columns = rows.indices.map { index -> rows.map { it[index] } } BingoBoard(rows, columns) } } private fun BingoBoard.checkNumber(number: String) { rows.forEach { row -> row.forEach { if (it.value == number) { it.check() } } } } private fun BingoBoard.isCompleted(): Boolean { val completedRow = rows.firstOrNull { it.isComplete() } val completedColumn = columns.firstOrNull { it.isComplete() } return completedRow != null || completedColumn != null } private fun List<Entry>.isComplete() = all { it.checked } data class BingoBoard(val rows: List<Row>, val columns: List<Column>) typealias Row = List<Entry> typealias Column = List<Entry> data class Entry(val value: String) { var checked: Boolean = false private set fun check() { checked = true } }
0
Kotlin
0
0
e0e5022238747e4b934cac0f6235b92831ca8ac7
3,114
advent-of-kotlin-2021
Apache License 2.0
src/Day04.kt
phamobic
572,925,492
false
{"Kotlin": 12697}
private const val RANGES_DELIMITER = "," private const val START_END_DELIMITER = "-" private fun getParsedRanges(rangesText: String): List<IntRange> = rangesText.split(RANGES_DELIMITER) .map { it.split(START_END_DELIMITER) } .map { it.first().toInt()..it.last().toInt() } private fun IntRange.contains(range: IntRange): Boolean = contains(range.first) && contains(range.last) private fun IntRange.overlapWith(range: IntRange): Boolean = contains(range.first) || contains(range.last) || range.contains(first) || range.contains(last) fun main() { fun part1(input: List<String>): Int { var count = 0 input.forEach { line -> val ranges = getParsedRanges(line) val firstRange = ranges.first() val secondRange = ranges.last() if (firstRange.contains(secondRange) || secondRange.contains(firstRange)) { count++ } } return count } fun part2(input: List<String>): Int { var count = 0 input.forEach { line -> val ranges = getParsedRanges(line) val firstRange = ranges.first() val secondRange = ranges.last() if (firstRange.overlapWith(secondRange)) { count++ } } return count } val testInput = readInput("Day04_test") check(part1(testInput) == 2) check(part2(testInput) == 4) }
1
Kotlin
0
0
34b2603470c8325d7cdf80cd5182378a4e822616
1,455
aoc-2022
Apache License 2.0
src/leetcode_problems/hard/MedianOfTwoSortedArrays.kt
MhmoudAlim
451,633,139
false
{"Kotlin": 31257, "Java": 586}
package leetcode_problems.hard /* https://leetcode.com/problems/median-of-two-sorted-arrays/ */ fun findMedianSortedArrays(nums1: IntArray, nums2: IntArray): Double { val maxNumSize = 1000 ; val maxAllNumsSize = 2000 // Lengths of two arrays val m = nums1.size val n = nums2.size val allNums = nums1.plus(nums2).sorted() // eliminate constraints if (m > maxNumSize) throw IllegalArgumentException("nums1 can't be larger than $maxNumSize") if (n > maxNumSize) throw IllegalArgumentException("nums2 can't be larger than $maxNumSize") if (allNums.size > maxAllNumsSize) throw IllegalArgumentException("nums1 + nums2 can't be larger than $maxAllNumsSize together") if (allNums.size == 1) return allNums[0].toDouble() // Check if num1 is smaller than num2 // If not, then we will swap num1 with num2 if (nums1.size > nums2.size) { return findMedianSortedArrays(nums2, nums1) } // Pointers for binary search var start = 0 var end = m // Binary search starts from here while (start <= end) { // Partitions of both the array val partitionNums1 = (start + end) / 2 val partitionNums2 = (m + n + 1) / 2 - partitionNums1 // Edge cases // If there are no elements left on the left side after partition val maxLeftNums1 = if (partitionNums1 == 0) Int.MIN_VALUE else nums1[partitionNums1 - 1] // If there are no elements left on the right side after partition val minRightNums1 = if (partitionNums1 == m) Int.MAX_VALUE else nums1[partitionNums1] // Similarly for nums2 val maxLeftNums2 = if (partitionNums2 == 0) Int.MIN_VALUE else nums2[partitionNums2 - 1] val minRightNums2 = if (partitionNums2 == n) Int.MAX_VALUE else nums2[partitionNums2] // Check if we have found the match if (maxLeftNums1 <= minRightNums2 && maxLeftNums2 <= minRightNums1) { // Check if the combined array is of even/odd length return if ((m + n) % 2 == 0) { (maxLeftNums1.coerceAtLeast(maxLeftNums2) + minRightNums1.coerceAtMost(minRightNums2)) / 2.0 } else { maxLeftNums1.coerceAtLeast(maxLeftNums2).toDouble() } } else if (maxLeftNums1 > minRightNums2) { end = partitionNums1 - 1 } else { start = partitionNums1 + 1 } } throw IllegalArgumentException() } fun main(){ val nums2 = arrayListOf<Int>() (1..1000).forEach { nums2.add(it) } val ans = findMedianSortedArrays(intArrayOf() , intArrayOf(1,2,3,4,5)) println(ans) }
0
Kotlin
0
0
31f0b84ebb6e3947e971285c8c641173c2a60b68
2,646
Coding-challanges
MIT License
src/Day05.kt
VadimB95
574,449,732
false
{"Kotlin": 19743}
import java.util.* fun main() { // test if implementation meets criteria from the description, like: val testInput = readInput("Day05_test") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = readInput("Day05") println(part1(input)) println(part2(input)) } private fun part1(input: List<String>): String { val stacksNumberLineIndex = input.indexOfFirst { it.startsWith(" 1") } val startStack = parseStartStack(input, stacksNumberLineIndex) val moves = parseMoves(stacksNumberLineIndex, input) moves.forEach { move -> repeat(move.count) { startStack[move.to - 1].push(startStack[move.from - 1].pop()) } } val answer = startStack.joinToString(separator = "") { it.peek().toString() } return answer } private fun part2(input: List<String>): String { val stacksNumberLineIndex = input.indexOfFirst { it.startsWith(" 1") } val startStack = parseStartStack(input, stacksNumberLineIndex) val moves = parseMoves(stacksNumberLineIndex, input) moves.forEach { move -> val cratesToMove = startStack[move.from - 1].subList(0, move.count) startStack[move.to - 1].addAll(0, cratesToMove) cratesToMove.clear() } val answer = startStack.joinToString(separator = "") { it.peek().toString() } return answer } private fun parseStartStack(input: List<String>, stacksNumberLineIndex: Int): List<LinkedList<Char>> { val startStack = mutableListOf<LinkedList<Char>>() input[stacksNumberLineIndex].forEachIndexed { index, c -> if (c.isDigit()) { val stack = LinkedList<Char>() for (i in stacksNumberLineIndex - 1 downTo 0) { val crateMark = input[i][index] if (crateMark.isLetter()) { stack.addFirst(crateMark) } } startStack.add(stack) } } return startStack } private fun parseMoves( stacksNumberLineIndex: Int, input: List<String>, ): List<Move> { val moves = mutableListOf<Move>() for (i in stacksNumberLineIndex + 2..input.lastIndex) { val inputSplit = input[i].split("move ", " from ", " to ").filter { it.isNotEmpty() }.map(String::toInt) moves.add(Move(inputSplit[0], inputSplit[1], inputSplit[2])) } return moves } private data class Move( val count: Int, val from: Int, val to: Int )
0
Kotlin
0
0
3634d1d95acd62b8688b20a74d0b19d516336629
2,440
aoc-2022
Apache License 2.0
src/main/kotlin/Day11.kt
uipko
572,710,263
false
{"Kotlin": 25828}
data class Monkey(val items: MutableList<Long> = mutableListOf(), var operator: String, var first: String, var second: String, var test: Long, var t: Int, var f: Int, var inspected: Long = 0L) fun main() { val monkeys = monkeyBusiness("Day11.txt", 20, 3) println("Total monkey business part 1: ${totalMonkeyBusiness(monkeys)}") val monkeys2 = monkeyBusiness("Day11.txt", 10_000, 1L) println("Total monkey business part 2: ${totalMonkeyBusiness(monkeys2)}") } fun totalMonkeyBusiness(monkeys: List<Monkey>): Long { return monkeys.sortedBy { it.inspected }.takeLast(2).fold(1L) { acc, elem -> acc * elem.inspected } } fun monkeyBusiness(fileName: String, rounds: Int, divider: Long): List<Monkey> { val monkeys = readFile(fileName).split("\n\n").map() { text -> val lines = text.lines() val items = lines[1].split("items: ").last().split(", ").map { it.toLong() }.toMutableList() val (first, operator, second) = lines[2].split(" ").takeLast(3) val test = lines[3].split(" ").last().toLong() val t = lines[4].split(" ").last().toInt() val f = lines[5].split(" ").last().toInt() Monkey(items, operator, first, second, test, t, f) } val superModulo = monkeys.fold(1L) { acc, elem -> acc * elem.test} //rounds (1..rounds).forEach() { _ -> monkeys.forEach { monkey -> monkey.items.forEach { item -> monkey.inspected++ var worries = when (monkey.operator) { "*" -> when (monkey.second) { "old" -> item * item else -> item * monkey.second.toLong() } else -> when (monkey.second) { "old" -> item + item else -> item + monkey.second.toLong() } } worries /= divider worries %= superModulo val newMonkey = if (worries.mod(monkey.test) == 0L) monkey.t else monkey.f monkeys[newMonkey].items.add(worries) } monkey.items.clear() } } return monkeys }
0
Kotlin
0
0
b2604043f387914b7f043e43dbcde574b7173462
2,253
aoc2022
Apache License 2.0