path stringlengths 5 169 | owner stringlengths 2 34 | repo_id int64 1.49M 755M | is_fork bool 2
classes | languages_distribution stringlengths 16 1.68k ⌀ | content stringlengths 446 72k | issues float64 0 1.84k | main_language stringclasses 37
values | forks int64 0 5.77k | stars int64 0 46.8k | commit_sha stringlengths 40 40 | size int64 446 72.6k | name stringlengths 2 64 | license stringclasses 15
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/Day09.kt | mpythonite | 572,671,910 | false | {"Kotlin": 29542} | import kotlin.math.abs
fun main() {
data class Point(var x: Int = 0, var y: Int = 0)
fun part1(input: List<String>): Int {
var head = Point()
var tail = Point()
var trail = HashSet<Point>()
var visited = 0
input.forEach {
val split = it.split(' ')
val dir = split[0]
val vel = split[1].toInt()
for (i in 1..vel) {
when (dir) {
"R" -> head.x++
"L" -> head.x--
"U" -> head.y++
"D" -> head.y--
}
if (tail.x == head.x) {
if (tail.y + 1 < head.y) tail.y++
if (tail.y - 1 > head.y) tail.y--
}
else if (tail.y == head.y) {
if (tail.x +1 < head.x) tail.x++
if (tail.x -1 > head.x) tail.x--
}
else {
if (abs(tail.x - head.x) + abs(tail.y - head.y) > 2) {
if (tail.x < head.x) tail.x++
else if (tail.x > head.x) tail.x--
if (tail.y < head.y) tail.y++
else if (tail.y > head.y) tail.y--
}
}
if(!trail.contains(tail)) {
visited++
trail.add(tail.copy())
}
}
}
return visited
}
fun part2(input: List<String>): Int {
val rope = List(10) { Point() }
var trail = HashSet<Point>()
var visited = 0
input.forEach {
val split = it.split(' ')
val dir = split[0]
val vel = split[1].toInt()
val head = rope[0]
for (i in 1..vel) {
when (dir) {
"R" -> head.x++
"L" -> head.x--
"U" -> head.y++
"D" -> head.y--
}
for (j in 1 until rope.size) {
if (rope[j].x == rope[j-1].x) {
if (rope[j].y + 1 < rope[j-1].y) rope[j].y++
if (rope[j].y - 1 > rope[j-1].y) rope[j].y--
} else if (rope[j].y == rope[j-1].y) {
if (rope[j].x + 1 < rope[j-1].x) rope[j].x++
if (rope[j].x - 1 > rope[j-1].x) rope[j].x--
} else {
if (abs(rope[j].x - rope[j-1].x) + abs(rope[j].y - rope[j-1].y) > 2) {
if (rope[j].x < rope[j-1].x) rope[j].x++
else if (rope[j].x > rope[j-1].x) rope[j].x--
if (rope[j].y < rope[j-1].y) rope[j].y++
else if (rope[j].y > rope[j-1].y) rope[j].y--
}
}
}
if(!trail.contains(rope[9])) {
visited++
trail.add(rope[9].copy())
}
}
}
return visited
}
// 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 | cac94823f41f3db4b71deb1413239f6c8878c6e4 | 3,491 | advent-of-code-2022 | Apache License 2.0 |
2023/src/main/kotlin/de/skyrising/aoc2023/day22/solution.kt | skyrising | 317,830,992 | false | {"Kotlin": 411565} | package de.skyrising.aoc2023.day22
import de.skyrising.aoc.*
val test = TestInput("""
1,0,1~1,2,1
0,0,2~2,0,2
0,2,3~2,2,3
0,0,4~0,2,4
2,0,5~2,2,5
0,1,6~2,1,6
1,1,8~1,1,9
""")
private fun parse(input: PuzzleInput) = input.lines.map {
val (x1,y1,z1, x2, y2, z2) = it.ints()
Cube(listOf(Vec3i(x1, y1, z1), Vec3i(x2, y2, z2)).boundingBox())
}
private fun letFall(cubes: List<Cube>, shortCircuit: Boolean = false): Pair<List<Cube>, Int> {
val newCubes = ArrayList<Cube>(cubes.size)
var count = 0
var maxZ = 0
for (oldCube in cubes.sortedBy { it.z }) {
val cube = oldCube.copy()
cube.z = minOf(maxZ + 1, cube.z)
while (cube.z > 1) {
cube.z--
if (newCubes.any { it.maxZ >= cube.z && it.maxX >= cube.x && it.x <= cube.maxX && it.intersects(cube)} ) {
cube.z++
break
}
}
if (cube.z < oldCube.z) {
count++
if (shortCircuit) return newCubes to count
}
newCubes.add(cube)
maxZ = maxOf(cube.maxZ, maxZ)
}
return newCubes to count
}
@PuzzleName("Sand Slabs")
fun PuzzleInput.part1(): Any {
val (cubes, _) = letFall(parse(this))
return cubes.count {
letFall(cubes - it, shortCircuit = true).second == 0
}
}
fun PuzzleInput.part2(): Any {
val (cubes, _) = letFall(parse(this))
return cubes.sumOf {
letFall(cubes - it).second
}
} | 0 | Kotlin | 0 | 0 | 19599c1204f6994226d31bce27d8f01440322f39 | 1,474 | aoc | MIT License |
src/main/kotlin/io/github/mikaojk/day3/part1/day3Part1.kt | MikAoJk | 573,000,620 | false | {"Kotlin": 15562} | package io.github.mikaojk.day3.part1
import io.github.mikaojk.common.getFileAsString
import java.util.Locale
fun day3Part1(): Int {
val rucksacksItems = getFileAsString("src/main/resources/day3/rucksacksItems.txt")
val rucksacks = rucksacksItems.split("\\n".toRegex()).map {
Rucksack(
firstCompartment = Items(items = it.slice(0 until (it.length / 2))),
secoundCompartment = Items(items = it.slice((it.length / 2) until (it.length)))
)
}
val sameItems = rucksacks.map { rucksack ->
findSameItem(rucksack.firstCompartment, rucksack.secoundCompartment)
}
val sumForEachRucksack = sameItems.flatMap { charList ->
charList.map { char ->
findPriorityValueForItem(char)
}
}
return sumForEachRucksack.sum()
}
fun findPriorityValueForItem(item: Char): Int {
return if (item.isUpperCase()) {
PriorityUpperCase.values().find { it.name == item.toString() }!!.value
} else {
(PriorityUpperCase.values().find { it.name == (item.uppercase(Locale.getDefault())) }!!.value) - 26
}
}
fun findSameItem(items1: Items, items2: Items): List<Char> {
val items1CharArray = items1.items.toCharArray()
val distinctSameItem = items1CharArray.filter { item -> items2.items.contains(item) }.toSet().toList();
return distinctSameItem
}
enum class PriorityUpperCase(val value: Int) {
A(27),
B(28),
C(29),
D(30),
E(31),
F(32),
G(33),
H(34),
I(35),
J(36),
K(37),
L(38),
M(39),
N(40),
O(41),
P(42),
Q(43),
R(44),
S(45),
T(46),
U(47),
V(48),
W(49),
X(50),
Y(51),
Z(52)
}
data class Rucksack(
val firstCompartment: Items,
val secoundCompartment: Items
)
data class Items(
val items: String
) | 0 | Kotlin | 0 | 0 | eaa90abc6f64fd42291ab42a03478a3758568ecf | 1,833 | aoc2022 | MIT License |
src/Day04.kt | mpythonite | 572,671,910 | false | {"Kotlin": 29542} | import java.awt.PageAttributes.PrintQualityType
fun main() {
fun part1(input: List<String>): Int {
var redundancies = 0
input.forEach{
val splits = it.split(',')
val first = splits.first().split('-')
val second = splits.last().split('-')
val low1 = first.first().toInt()
val high1 = first.last().toInt()
val low2 = second.first().toInt()
val high2 = second.last().toInt()
if (low1 <= low2 && high1 >= high2) redundancies++
else if (low2 <= low1 && high2 >= high1) redundancies++
}
return redundancies
}
fun part2(input: List<String>): Int {
var overlaps = 0
input.forEach{
val splits = it.split(',')
val first = splits.first().split('-')
val second = splits.last().split('-')
val low1 = first.first().toInt()
val high1 = first.last().toInt()
val low2 = second.first().toInt()
val high2 = second.last().toInt()
if (low1 in low2..high2) overlaps++
else if (low2 in low1..high1) overlaps++
}
return overlaps
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
println(part2(testInput))
check(part2(testInput) == 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | cac94823f41f3db4b71deb1413239f6c8878c6e4 | 1,512 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/astminer/featureextraction/TreeFeature.kt | JetBrains-Research | 161,813,380 | false | {"Kotlin": 339696, "ANTLR": 110038, "C++": 25952, "Java": 22416, "Python": 14294, "JavaScript": 7698, "PHP": 3778, "Dockerfile": 1431, "Shell": 988} | package astminer.featureextraction
import astminer.common.model.Node
/**
* Interface that describes tree feature.
* @param T tree feature's type
*/
interface TreeFeature<out T> {
/**
* Computes this feature for given tree.
* @param tree tree for which this feature is computed
* @return computed feature
*/
fun compute(tree: Node): T
}
/**
* Tree feature for computing depth of a given tree.
*/
object Depth : TreeFeature<Int> {
override fun compute(tree: Node): Int {
val max = tree.children.map { compute(it) }.maxOrNull() ?: 0
return max + 1
}
}
/**
* Tree feature for computing branching factor of a given tree.
*/
object BranchingFactor : TreeFeature<Double> {
override fun compute(tree: Node): Double {
if (tree.isLeaf()) {
return 0.0
}
val isLeafByNodes = tree.preOrder().groupBy { it.isLeaf() }
val leavesNumber = isLeafByNodes[true]?.size ?: 0
val branchingNodesNumber = isLeafByNodes[false]?.size ?: 0
val edgesNumber = (branchingNodesNumber + leavesNumber - 1).toDouble()
return edgesNumber / branchingNodesNumber
}
}
/**
* Tree feature for computing the number of nodes in a given tree.
*/
object NumberOfNodes : TreeFeature<Int> {
override fun compute(tree: Node): Int = tree.children.sumOf { compute(it) } + 1
}
/**
* Tree feature for computing list of all node tokens from a given tree.
*/
object Tokens : TreeFeature<List<String>> {
override fun compute(tree: Node): List<String> = findTokens(tree, ArrayList())
private fun findTokens(node: Node, tokensList: MutableList<String>): List<String> {
node.children.forEach { findTokens(it, tokensList) }
tokensList.add(node.token.final())
return tokensList
}
}
/**
* Tree feature for computing list of all node types from a given tree.
*/
object NodeTypes : TreeFeature<List<String>> {
override fun compute(tree: Node): List<String> = findNodeTypes(tree, ArrayList())
private fun findNodeTypes(node: Node, nodeTypesList: MutableList<String>): List<String> {
node.children.forEach { findNodeTypes(it, nodeTypesList) }
nodeTypesList.add(node.typeLabel)
return nodeTypesList
}
}
/**
* Tree feature for computing list of all compressible path lengths in a given tree.
* A path is called compressible if it consists of consistent nodes that have only one child.
*/
object CompressiblePathLengths : TreeFeature<List<Int>> {
override fun compute(tree: Node): List<Int> {
val pathLengths = ArrayList<Int>()
tree.preOrder().filter { it.isStartingNode() }.forEach { pathLengths.add(findPathLengthFromStartingNode(it)) }
return pathLengths
}
private fun Node.isStartingNode(): Boolean = this.hasOneChild() && !(this.parent?.hasOneChild() ?: false)
private fun Node.hasOneChild(): Boolean = children.size == 1
private fun findPathLengthFromStartingNode(node: Node): Int {
var length = 1
var next = node.children.first()
while (next.hasOneChild()) {
length++
next = next.children.first()
}
return length
}
}
| 11 | Kotlin | 79 | 269 | 8e7872fa78983b3b9b4ff4b9f70d24cc4dfed280 | 3,203 | astminer | MIT License |
src/year2022/day09/Day09.kt | lukaslebo | 573,423,392 | false | {"Kotlin": 222221} | package year2022.day09
import check
import readInput
import kotlin.math.abs
fun main() {
// test if implementation meets criteria from the description, like:
val testInputA = readInput("2022", "Day09_test_a")
val testInputB = readInput("2022", "Day09_test_b")
check(part1(testInputA), 13)
check(part2(testInputA), 1)
check(part1(testInputB), 88)
check(part2(testInputB), 36)
val input = readInput("2022", "Day09")
println(part1(input))
println(part2(input))
}
private fun part1(input: List<String>) = findTailPathUniquePositionCount(input, 2)
private fun part2(input: List<String>) = findTailPathUniquePositionCount(input, 10)
private fun findTailPathUniquePositionCount(input: List<String>, size: Int): Int {
val snake = List(size) { Knot() }
val tailPath = mutableSetOf<Knot>()
for (line in input) {
val (dir, amount) = line.split(' ')
repeat(amount.toInt()) {
snake.first().move(dir)
snake.windowed(2) { pair ->
val (h, t) = pair
t.follow(h)
}
tailPath += snake.last().copy()
}
}
return tailPath.size
}
private data class Knot(private var x: Int = 0, private var y: Int = 0) {
fun move(dir: String) {
when (dir) {
"R" -> x++
"L" -> x--
"U" -> y++
"D" -> y--
}
}
fun follow(other: Knot) {
val dx = other.x - x
val dy = other.y - y
if (abs(dx) <= 1 && abs(dy) <= 1) return
if (dx == 0 || dy == 0) {
when {
dx > 1 -> x++
dx < -1 -> x--
dy > 1 -> y++
dy < -1 -> y--
}
} else {
if (dx > 0) x++ else x--
if (dy > 0) y++ else y--
}
}
} | 0 | Kotlin | 0 | 1 | f3cc3e935bfb49b6e121713dd558e11824b9465b | 1,848 | AdventOfCode | Apache License 2.0 |
src/week3/TopKFrequent.kt | anesabml | 268,056,512 | false | null | package week3
import java.util.*
import kotlin.system.measureNanoTime
class TopKFrequent {
fun topKFrequent(nums: IntArray, k: Int): IntArray {
if (k == nums.size) return nums
val map = hashMapOf<Int, Int>()
nums.forEach { n ->
map[n] = map.getOrDefault(n, 0) + 1
}
return map.toList().sortedByDescending { (_, value) -> value }.toMap().keys.toList().subList(0, k).toIntArray()
}
/** PriorityQueue - maxHeap
* Time complexity: O(n log k)
* Space complexity: O(n + k)*/
fun topKFrequent2(nums: IntArray, k: Int): IntArray {
if (k == nums.size) return nums
val map = hashMapOf<Int, Int>()
nums.forEach { n ->
map[n] = map.getOrDefault(n, 0) + 1
}
val priorityQueue = PriorityQueue<Int>(compareByDescending { map[it] })
map.forEach {
priorityQueue.add(it.key)
}
val output = IntArray(k)
for (i in 0 until k) {
output[i] = priorityQueue.poll()
}
return output
}
/** Bucket sort
* Time complexity: O(n)
* Space complexity: O(n)
*/
fun topKFrequent3(nums: IntArray, k: Int): IntArray {
if (k == nums.size) return nums
val map = hashMapOf<Int, Int>()
nums.forEach { n ->
map[n] = map.getOrDefault(n, 0) + 1
}
val buckets = Array<MutableList<Int>>(nums.size + 1) { mutableListOf() }
map.forEach { (key, value) ->
buckets[value].add(key)
}
val output = mutableListOf<Int>()
var i = buckets.size - 1
var j = k
while (i > 0 && j > 0) {
if (buckets[i].isNotEmpty()) {
output.addAll(buckets[i])
j -= buckets[i].size
}
i--
}
return output.toIntArray()
}
}
fun main() {
val nums = intArrayOf(1, 1, 1, 2, 2, 3)
val k = 2
val topKFrequent = TopKFrequent()
val firstSolutionTime = measureNanoTime { println(topKFrequent.topKFrequent(nums, k).contentToString()) }
val secondSolutionTime = measureNanoTime { println(topKFrequent.topKFrequent2(nums, k).contentToString()) }
val thirdSolutionTime = measureNanoTime { println(topKFrequent.topKFrequent3(nums, k).contentToString()) }
println("First Solution execution time: $firstSolutionTime")
println("Second Solution execution time: $secondSolutionTime")
println("Third Solution execution time: $thirdSolutionTime")
} | 0 | Kotlin | 0 | 1 | a7734672f5fcbdb3321e2993e64227fb49ec73e8 | 2,529 | leetCode | Apache License 2.0 |
src/year2015/day19/Day19.kt | lukaslebo | 573,423,392 | false | {"Kotlin": 222221} | package year2015.day19
import readInput
fun main() {
val input = readInput("2015", "Day19")
println(part1(input))
println(part2(input))
}
private fun part1(input: List<String>): Int {
val replacements = input.dropLast(2).map { it.split(" => ") }.map { it[0] to it[1] }
val molecule = input.last()
val transformations = hashSetOf<String>()
for ((replace, with) in replacements) {
var index = 0
do {
val replaceAt = molecule.indexOf(replace, index)
if (replaceAt != -1) {
transformations += molecule.replaceAt(replaceAt, replace, with)
}
index = replaceAt + 1
} while (index > 0)
}
return transformations.size
}
private fun part2(input: List<String>): Int {
val replacements = input.dropLast(2)
.map { it.split(" => ") }
.map { it[0] to it[1] }
.sortedByDescending { it.second.length }
val medicine = input.last()
val queue = ArrayDeque<Pair<String, Int>>()
queue += medicine to 0
while (queue.isNotEmpty()) {
val (molecule, steps) = queue.removeFirst()
for ((with, replace) in replacements) {
val nextMolecule = molecule.replaceFirst(replace, with)
if (nextMolecule == "e") return steps + 1
if (nextMolecule != molecule) {
queue += nextMolecule to steps + 1
break
}
}
}
error("Medicine can't be obtained with alchemy")
}
private fun String.replaceAt(index: Int, replace: String, with: String) = substring(0, index) +
with + substring(index + replace.length) | 0 | Kotlin | 0 | 1 | f3cc3e935bfb49b6e121713dd558e11824b9465b | 1,650 | AdventOfCode | Apache License 2.0 |
src/main/kotlin/org/motivesearch/csma/MotiveGenerator.kt | JonasKellerer | 754,498,515 | false | {"Kotlin": 10127, "Python": 6871} | package org.motivesearch.csma
data class MotiveUnit(val name: String)
data class MotivePosition(val position: Int, val length: Int)
data class Motive(val positions: List<MotivePosition>, val frequency: Int, val sequence: List<MotiveUnit>) {
companion object {
fun fromPositions(positions: List<MotivePosition>, sequence: List<MotiveUnit>) =
Motive(positions, positions.size, sequence)
}
}
class MotiveGenerator {
fun generateMotives(
sequence: List<MotiveUnit>,
minFrequency: Int,
maxGap: Int,
minLength: Int,
maxLength: Int
): List<Motive> {
val basicMotives = getBasicMotives(sequence, minFrequency)
var motivesOfIteration = basicMotives
var motivesOfAllIterations = emptyList<Motive>()
while (motivesOfIteration.isNotEmpty()) {
motivesOfIteration =
motiveOfIteration(motivesOfIteration, basicMotives, minFrequency, maxLength, maxGap)
motivesOfAllIterations = motivesOfAllIterations + motivesOfIteration.filter { it.sequence.size >= minLength}
}
return motivesOfAllIterations
}
private fun motiveOfIteration(
motivesOfLastIteration: List<Motive>,
baseMotives: List<Motive>,
minFrequency: Int,
maxLength: Int,
maxGap: Int
): List<Motive> {
val motivesOfNextIteration = motivesOfLastIteration.map { motiveOfIteration ->
val frequentPosition = getFrequentPosition(motiveOfIteration, minFrequency)
val candidateExtensions = generateCandidateExtension(baseMotives, frequentPosition)
candidateExtensions.map { candidateExtension ->
mergeMotives(motiveOfIteration, candidateExtension, maxGap, maxLength)
}
}.flatten()
return filterMotives(motivesOfNextIteration, minFrequency, maxLength)
}
fun getBasicMotives(sequence: List<MotiveUnit>, minFrequency: Int): List<Motive> {
val basicMotiveUnits = sequence.toSet()
val basicMotives =
basicMotiveUnits.map { it to Motive(emptyList(), 0, listOf(it)) }
.toMap().toMutableMap()
sequence.forEachIndexed { index, motiveUnit ->
val motive = basicMotives[motiveUnit]!!
val newPositions = motive.positions.toMutableList()
newPositions.add(MotivePosition(index, 1))
basicMotives[motiveUnit] = motive.copy(positions = newPositions, frequency = motive.frequency + 1)
}
val basicMotivesAboveMinFrequency = basicMotives.filter { it.value.frequency >= minFrequency }
return basicMotivesAboveMinFrequency.values.toList()
}
fun getMotiveUnits(sequence: String): List<MotiveUnit> {
val uniqueValues = sequence.split(",")
return uniqueValues.map { MotiveUnit(it) }
}
fun getFrequentPosition(motive: Motive, minFrequency: Int): Int {
if (motive.frequency < minFrequency) throw IllegalArgumentException("Motiv frequency is less than minFrequency")
val position = motive.positions[minFrequency - 1]
return position.position + position.length
}
fun generateCandidateExtension(baseMotives: List<Motive>, frequentPosition: Int): List<Motive> {
return baseMotives.filter { baseMotive ->
baseMotive.positions.any { position -> position.position >= frequentPosition - 1 }
}
}
fun mergeMotives(motive: Motive, candidateExtension: Motive, maxGap: Int, maxLength: Int): Motive {
val newSequence = motive.sequence + candidateExtension.sequence
val newPositions = motive.positions.map { position ->
val nextCandidatePosition = candidateExtension.positions.filter { candidatePosition ->
val notToLargeGap = candidatePosition.position - (position.position + position.length) <= maxGap
val afterPosition = candidatePosition.position >= (position.position + position.length)
val notToLong = candidatePosition.position + candidatePosition.length - position.position <= maxLength
notToLargeGap && afterPosition && notToLong
}.firstOrNull()
if (nextCandidatePosition != null) {
MotivePosition(position.position, position.length + nextCandidatePosition.length)
} else {
null
}
}.filterNotNull()
return motive.copy(positions = newPositions, frequency = newPositions.size, sequence = newSequence)
}
private fun filterMotives(motives: List<Motive>, minFrequency: Int, maxLength: Int): List<Motive> {
return motives.filter { it.frequency >= minFrequency && it.sequence.size <= maxLength }
}
} | 0 | Kotlin | 0 | 0 | 7d57ab65c379beab24d81a82dad7ee215afb5567 | 4,763 | motivsearch | MIT License |
day18/src/main/kotlin/Day18.kt | bzabor | 160,240,195 | false | null | class Day18(private val input: List<String>) {
val gridDim = 50
var grid = Array(gridDim) { Array(gridDim) { Cell() } }
var minutes = 0
fun init() {
for (row in input.indices) {
for (col in input[row].indices) {
val c = input[row][col]
grid[row][col] = Cell(row, col, cellTypeForChar(c))
}
}
}
fun part1(): Int {
init()
printGrid(grid)
do {
minutes++
grid = getNextGrid()
printGrid(grid)
} while (minutes < 10000)
val trees = grid.flatMap { it.filter { it.cellType == CellType.TREES} }.count()
val lumberyards = grid.flatMap { it.filter { it.cellType == CellType.LUMBERYARD} }.count()
return trees * lumberyards
}
fun part2(): Int {
return 0
}
private fun getNextGrid(): Array<Array<Cell>> {
val nextGrid = Array(gridDim) { Array(gridDim) { Cell() } }
for (row in grid.indices) {
for (col in grid[row].indices) {
nextGrid[row][col] = nextCell(grid[row][col])
}
}
return nextGrid
}
// An open acre will become filled with trees if three or more adjacent acres contained trees. Otherwise, nothing happens.
// An acre filled with trees will become a lumberyard if three or more adjacent acres were lumberyards. Otherwise, nothing happens.
// An acre containing a lumberyard will remain a lumberyard if it was adjacent to at least one other lumberyard and at least one acre containing trees. Otherwise, it becomes open.
private fun nextCell(cell: Cell): Cell {
val neighbors = neighborCells(cell)
val nextCell = when {
cell.cellType == CellType.OPEN -> if (neighbors.count { it.cellType == CellType.TREES } >= 3) Cell(cell.row, cell.col, CellType.TREES) else cell
cell.cellType == CellType.TREES -> if (neighbors.count { it.cellType == CellType.LUMBERYARD } >= 3) Cell(cell.row, cell.col, CellType.LUMBERYARD) else cell
cell.cellType == CellType.LUMBERYARD -> if (neighbors.count { it.cellType == CellType.LUMBERYARD } >= 1 && neighbors.count { it.cellType == CellType.TREES } >= 1) cell else Cell(cell.row, cell.col, CellType.OPEN)
else -> throw IllegalArgumentException("Unknown cellType for cell: $cell")
}
return nextCell
}
private fun neighborCells(cell: Cell): List<Cell> {
return grid.flatMap { it.filter { it.row in cell.row-1..cell.row+1 && it.col in cell.col-1..cell.col+1 }. filterNot { it.row == cell.row && it.col == cell.col} }
}
private fun cellTypeForChar(c: Char): CellType {
return when (c) {
'.' -> CellType.OPEN
'|' -> CellType.TREES
'#' -> CellType.LUMBERYARD
else -> CellType.OPEN
}
}
private fun printGrid(aGrid: Array<Array<Cell>>) {
// println("")
// println("-".repeat(50))
// for (row in aGrid) {
// for (col in row) {
// print("${col.cellType.symbol} ")
// }
// println("")
// }
// if (minutes % 100 == 0) {
print("Minutes: $minutes ----- ")
val trees = grid.flatMap { it.filter { it.cellType == CellType.TREES} }.count()
val lumberyards = grid.flatMap { it.filter { it.cellType == CellType.LUMBERYARD} }.count()
println("trees: $trees lumberyards: $lumberyards value: ${trees * lumberyards}")
// }
// println("-".repeat(50))
// println("")
// println("")
}
}
enum class CellType(val symbol: Char) {
OPEN('.'),
LUMBERYARD('#'),
TREES('|')
}
data class Cell(
var row: Int = 0,
var col: Int = 0,
var cellType: CellType = CellType.OPEN
) {
override fun toString() = "$row:$col"
}
| 0 | Kotlin | 0 | 0 | 14382957d43a250886e264a01dd199c5b3e60edb | 3,954 | AdventOfCode2018 | Apache License 2.0 |
src/year2023/Day14.kt | drademacher | 725,945,859 | false | {"Kotlin": 76037} | package year2023
import Direction
import MutableGrid
import readLines
fun main() {
val input = parseInput(readLines("2023", "day14"))
val testInput = parseInput(readLines("2023", "day14_test"))
val testResultPart1 = part1(testInput.simpleCopy())
check(testResultPart1 == 136) { "Incorrect result for part 1: $testResultPart1" }
println("Part 1:" + part1(input))
val testResultPart2 = part2(testInput.simpleCopy())
check(testResultPart2 == 64) { "Incorrect result for part 2: $testResultPart2" }
println("Part 2:" + part2(input))
}
private fun parseInput(input: List<String>): MutableGrid<Char> {
return MutableGrid(input.map { it.toCharArray().toMutableList() }.toMutableList())
}
private fun part1(grid: MutableGrid<Char>): Int {
grid.tilt(Direction.NORTH)
return grid.calculateTotalLoad()
}
private fun part2(grid: MutableGrid<Char>): Int {
val totalCycles = 1_000_000_000
val gridStateCache = mutableMapOf<String, Int>()
for (cycle in (0..<totalCycles)) {
val stateInPreviousCycleReached = gridStateCache[grid.toCacheableString()]
if (stateInPreviousCycleReached != null) {
val cycleLength = cycle - stateInPreviousCycleReached
val remainingCycles = (totalCycles - stateInPreviousCycleReached) % cycleLength
repeat(remainingCycles) {
grid.executeTiltCycle()
}
return grid.calculateTotalLoad()
} else {
gridStateCache[grid.toCacheableString()] = cycle
}
grid.executeTiltCycle()
}
return -1
}
private fun MutableGrid<Char>.executeTiltCycle() {
tilt(Direction.NORTH)
tilt(Direction.WEST)
tilt(Direction.SOUTH)
tilt(Direction.EAST)
}
private fun MutableGrid<Char>.calculateTotalLoad(): Int {
return data
.withIndex()
.sumOf { (rowIndex, row) -> row.count { it == 'O' } * (rows - rowIndex) }
}
private fun MutableGrid<Char>.tilt(direction: Direction) {
when (direction) {
Direction.NORTH -> {
for (x in data[0].indices) {
var obstacle = -1
for (y in (0..<rows)) {
if (data[y][x] == '#') {
obstacle = y
} else if (data[y][x] == 'O') {
obstacle++
data[y][x] = '.'
data[obstacle][x] = 'O'
}
}
}
}
Direction.EAST -> {
for (y in (0..<rows)) {
var obstacle = cols
for (x in (0..<cols).reversed()) {
if (data[y][x] == '#') {
obstacle = x
} else if (data[y][x] == 'O') {
obstacle--
data[y][x] = '.'
data[y][obstacle] = 'O'
}
}
}
}
Direction.SOUTH -> {
for (x in (0..<cols)) {
var obstacle = rows
for (y in (0..<rows).reversed()) {
if (data[y][x] == '#') {
obstacle = y
} else if (data[y][x] == 'O') {
obstacle--
data[y][x] = '.'
data[obstacle][x] = 'O'
}
}
}
}
Direction.WEST -> {
for (y in (0..<rows)) {
var obstacle = -1
for (x in (0..<cols)) {
if (data[y][x] == '#') {
obstacle = x
} else if (data[y][x] == 'O') {
obstacle++
data[y][x] = '.'
data[y][obstacle] = 'O'
}
}
}
}
}
}
| 0 | Kotlin | 0 | 0 | 4c4cbf677d97cfe96264b922af6ae332b9044ba8 | 3,906 | advent_of_code | MIT License |
src/Day05.kt | jamOne- | 573,851,509 | false | {"Kotlin": 20355} | import java.util.ArrayDeque
data class Day5Command(val count: Int, val from: Int, val to: Int)
data class Day5Data(val stacks: List<ArrayDeque<Char>>, val commands: List<Day5Command>)
val COMMAND_REGEX = """^move (\d+) from (\d+) to (\d+)$""".toRegex()
fun main() {
fun part1(input: List<String>): String {
val (stacks, commands) = parseInput(input)
for (command in commands) {
val (count, from, to) = command
for (i in 1..count) {
val el = stacks[from - 1].pop()
stacks[to - 1].push(el)
}
}
return stacks.map { stack -> stack.peek() }.joinToString("")
}
fun part2(input: List<String>): String {
val (stacks, commands) = parseInput(input)
for (command in commands) {
val (count, from, to) = command
val tempStack = ArrayDeque<Char>()
for (i in 1..count) {
tempStack.push(stacks[from - 1].pop())
}
for (i in 1..count) {
stacks[to - 1].push(tempStack.pop())
}
}
return stacks.map { stack -> stack.peek() }.joinToString("")
}
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
fun parseInput(input: List<String>): Day5Data {
val numberOfStacks = (input[0].length + 1) / 4;
val stacks = List(numberOfStacks) { ArrayDeque<Char>() };
var lineIndex = 0
while (input[lineIndex][1] != '1') {
for (i in 0 until numberOfStacks) {
if (input[lineIndex][1 + i*4] != ' ') {
stacks[i].addLast(input[lineIndex][1 + i*4])
}
}
lineIndex += 1
}
lineIndex += 2
val commands = mutableListOf<Day5Command>()
while (lineIndex < input.size) {
val match = COMMAND_REGEX.matchEntire(input[lineIndex])!!
val (count, from, to) = match.destructured
commands.add(Day5Command(count.toInt(), from.toInt(), to.toInt()))
lineIndex += 1
}
return Day5Data(stacks, commands)
} | 0 | Kotlin | 0 | 0 | 77795045bc8e800190f00cd2051fe93eebad2aec | 2,196 | adventofcode2022 | Apache License 2.0 |
codeforces/round621/e.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package codeforces.round621
const val M = 1_000_000_007
fun main() {
val (n, m) = readInts()
val a = readInts().map { it - 1 }
val indices = List(n) { mutableListOf<Int>() }
for (x in a.indices) { indices[a[x]].add(x) }
val eaters = List(n) { mutableSetOf<Int>() }
repeat(m) {
val (id, hunger) = readInts().map { it - 1 }
eaters[id].add(hunger)
}
val eatable = List(2) { BooleanArray(n) { false } }
val count = List(2) { IntArray(n) { 0 } }
for (id in eaters.indices) {
for (hunger in eaters[id]) {
if (hunger < indices[id].size) {
eatable[0][indices[id][hunger]] = true
eatable[1][indices[id][indices[id].size - 1 - hunger]] = true
count[1][id]++
}
}
}
var max = 0
var waysMax = 1
for (v in count[1].filter { it > 0 }) {
max++
waysMax = ((waysMax.toLong() * v) % M).toInt()
}
for (x in a.indices) {
if (eatable[1][x]) count[1][a[x]]--
if (eatable[0][x]) count[0][a[x]]++ else continue
var cur = 0
var ways = 1
for (id in a.indices) {
val left = count[0][id]
val right = count[1][id]
val (two, one) = if (id == a[x]) {
(if (left - 1 < right) right - 1 else right) to 1
} else {
left * right - minOf(left, right) to left + right
}
val mul = if (two > 0) { cur += 2; two } else if (one > 0) { cur++; one } else continue
ways = ((ways.toLong() * mul) % M).toInt()
}
if (cur > max) {
max = cur; waysMax = ways
} else if (cur == max) {
waysMax = (waysMax + ways) % M
}
}
println("$max $waysMax")
}
private fun readLn() = readLine()!!
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| 0 | Java | 1 | 9 | 30953122834fcaee817fe21fb108a374946f8c7c | 1,640 | competitions | The Unlicense |
yandex/y2020/qual/e.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package yandex.y2020.qual
import kotlin.random.Random
fun main() {
readLn()
var treap: PersistentTreap? = null
var ans = 0.toBigInteger()
val a = readInts()
println(a.mapIndexed { index, x ->
ans += (PersistentTreap.split(treap, (x + 1L) * a.size)[1]?.sum ?: 0).toBigInteger()
treap = PersistentTreap.add(treap, x.toLong() * a.size + index, x)
ans
}.joinToString(" "))
}
internal class PersistentTreap private constructor(val key: Long, val value: Int, val h: Int, val left: PersistentTreap?, val right: PersistentTreap?) {
val sum: Long
constructor(key: Long, value: Int, left: PersistentTreap?, right: PersistentTreap?) : this(key, value, r.nextInt(), left, right)
companion object {
var r = Random(566)
fun split(treap: PersistentTreap?, keySplit: Long): Array<PersistentTreap?> {
if (treap == null) return arrayOfNulls(2)
val split: Array<PersistentTreap?>
if (treap.key < keySplit) {
split = split(treap.right, keySplit)
split[0] = PersistentTreap(treap.key, treap.value, treap.h, treap.left, split[0])
} else {
split = split(treap.left, keySplit)
split[1] = PersistentTreap(treap.key, treap.value, treap.h, split[1], treap.right)
}
return split
}
fun merge(left: PersistentTreap?, right: PersistentTreap?): PersistentTreap? {
if (left == null) return right
if (right == null) return left
return if (left.h > right.h) {
PersistentTreap(left.key, left.value, left.h, left.left, merge(left.right, right))
} else PersistentTreap(right.key, right.value, right.h, merge(left, right.left), right.right)
}
fun add(treap: PersistentTreap?, key: Long, value: Int): PersistentTreap? {
val split = split(treap, key)
return merge(split[0], merge(PersistentTreap(key, value, null, null), split[1]))
}
}
init {
// calcMeta
var sum = 0L
if (left != null) {
sum = left.sum
}
sum += value
if (right != null) {
sum += right.sum
}
this.sum = sum
}
}
private fun readLn() = readLine()!!
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| 0 | Java | 1 | 9 | 30953122834fcaee817fe21fb108a374946f8c7c | 2,097 | competitions | The Unlicense |
src/Day10.kt | nordberg | 573,769,081 | false | {"Kotlin": 47470} | fun main() {
fun addInterestingSignals(cycleCount: Int, signalStrength: Int): Int {
return when (cycleCount) {
20, 60, 100, 140, 180, 220 -> signalStrength * cycleCount
else -> 0
}
}
fun part1(input: List<String>): Int {
var signalStrength = 1
var cycleCount = 0
var interestingSignal = 0
input.forEach { line ->
if (line == "noop") {
cycleCount += 1
interestingSignal += addInterestingSignals(cycleCount, signalStrength)
} else {
val (_, addVal) = line.split(" ")
cycleCount += 1
interestingSignal += addInterestingSignals(cycleCount, signalStrength)
cycleCount += 1
interestingSignal += addInterestingSignals(cycleCount, signalStrength)
signalStrength += addVal.toInt()
}
}
return interestingSignal
}
fun part2(input: List<String>): String {
var signalStrength = 1
val spriteLocations = mutableListOf(listOf(0, 1, 2))
var cycleCount = 0
var interestingSignal = 0
input.forEach { line ->
if (line == "noop") {
cycleCount += 1
spriteLocations.add(listOf(signalStrength - 1, signalStrength, signalStrength + 1))
interestingSignal += addInterestingSignals(cycleCount, signalStrength)
} else {
val (_, addVal) = line.split(" ")
cycleCount += 1
spriteLocations.add(listOf(signalStrength - 1, signalStrength, signalStrength + 1))
interestingSignal += addInterestingSignals(cycleCount, signalStrength)
cycleCount += 1
interestingSignal += addInterestingSignals(cycleCount, signalStrength)
signalStrength += addVal.toInt()
spriteLocations.add(listOf(signalStrength - 1, signalStrength, signalStrength + 1))
}
}
val sb = StringBuilder(40*6)
(1..(40*6)).forEach { atCycle ->
if (spriteLocations[atCycle].contains(atCycle % 40)) {
sb.append('#')
} else {
sb.append('.')
}
if (atCycle % 40 == 0) {
sb.appendLine()
}
}
return sb.toString()
}
// test if implementation meets criteria from the description, like:
//val testInput = readInput("Day10_test")
//check(part1(testInput) == 13140)
val input = readInput("Day10")
//println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 3de1e2b0d54dcf34a35279ba47d848319e99ab6b | 2,664 | aoc-2022 | Apache License 2.0 |
src/medium/_15ThreeSum.kt | ilinqh | 390,190,883 | false | {"Kotlin": 382147, "Java": 32712} | package medium
import java.util.*
class _15ThreeSum {
/**
* 直接三重循环的话,会超时
* 优化-> 先对数组进行排序,然后结合双指针减少遍历次数
*/
class Solution {
fun threeSum(nums: IntArray): List<List<Int>> {
if (nums.size < 3) {
return emptyList()
}
Arrays.sort(nums)
var secondPointIndex: Int
var thirdPointIndex: Int
val result = ArrayList<ArrayList<Int>>()
for (x in nums.indices) {
if (x > 0 && nums[x] == nums[x - 1]) {
continue
}
secondPointIndex = x + 1
thirdPointIndex = nums.size - 1
if (secondPointIndex >= thirdPointIndex) {
break
}
while (secondPointIndex < thirdPointIndex && nums[secondPointIndex] + nums[thirdPointIndex] + nums[x] < 0) {
secondPointIndex++
}
for (y in secondPointIndex until nums.size) {
if ((y - secondPointIndex) > 0 && nums[y] == nums[y - 1]) {
continue
}
while (thirdPointIndex > y && nums[thirdPointIndex] + nums[y] > -nums[x]) {
thirdPointIndex--
}
if (thirdPointIndex != y && nums[thirdPointIndex] + nums[y] + nums[x] == 0) {
result.add(arrayListOf(nums[x], nums[y], nums[thirdPointIndex]))
}
}
}
return result
}
}
class BestSolution {
fun threeSum(nums: IntArray): List<List<Int>> {
val n = nums.size
Arrays.sort(nums)
val ans: MutableList<List<Int>> = ArrayList()
// 枚举 a
for (first in 0 until n) {
// 需要和上一次枚举的数不相同
if (first > 0 && nums[first] == nums[first - 1]) {
continue
}
// c 对应的指针初始指向数组的最右端
var third = n - 1
val target = -nums[first]
// 枚举 b
for (second in first + 1 until n) {
// 需要和上一次枚举的数不相同
if (second > first + 1 && nums[second] == nums[second - 1]) {
continue
}
// 需要保证 b 的指针在 c 的指针的左侧
while (second < third && nums[second] + nums[third] > target) {
--third
}
// 如果指针重合,随着 b 后续的增加
// 就不会有满足 a+b+c=0 并且 b<c 的 c 了,可以退出循环
if (second == third) {
break
}
if (nums[second] + nums[third] == target) {
val list: MutableList<Int> = ArrayList()
list.add(nums[first])
list.add(nums[second])
list.add(nums[third])
ans.add(list)
}
}
}
return ans
}
}
} | 0 | Kotlin | 0 | 0 | 8d2060888123915d2ef2ade293e5b12c66fb3a3f | 3,397 | AlgorithmsProject | Apache License 2.0 |
project-euler/kotlin/src/test/kotlin/dev/mikeburgess/euler/problems/Problems02x.kt | mddburgess | 469,258,868 | false | {"Kotlin": 47737} | package dev.mikeburgess.euler.problems
import dev.mikeburgess.euler.extensions.*
import dev.mikeburgess.euler.math.factorial
import dev.mikeburgess.euler.getResourceAsLines
import org.assertj.core.api.Assertions.assertThat
import java.math.BigInteger
import kotlin.test.Test
class Problems02x {
/**
* Problem 20
*
* n! means n × (n − 1) × ... × 3 × 2 × 1
*
* For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800,
* and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
*
* Find the sum of the digits in the number 100!
*/
@Test
fun `Problem 20`() {
val result = factorial(100).sumDigits().toLong()
assertThat(result).isEqualTo(648L)
}
/**
* Problem 21
*
* Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide
* evenly into n).
*
* If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and each of a and b
* are called amicable numbers.
*
* For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110;
* therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220.
*
* Evaluate the sum of all the amicable numbers under 10000.
*/
@Test
fun `Problem 21`() {
val sums = (1..9999).associateWith { it.properDivisors.sum() }
val result = sums.filter { (a, b) -> a != b }
.mapValues { (_, b) -> sums[b] }
.filter { (a, b) -> a == b }
.keys.sum().toLong()
assertThat(result).isEqualTo(31626L)
}
/**
* Problem 22
*
* Using a text file containing over five-thousand first names, begin by sorting it into
* alphabetical order. Then working out the alphabetical value for each name, multiply this
* value by its alphabetical position in the list to obtain a name score.
*
* For example, when the list is sorted into alphabetical order, COLIN, which is worth
* 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of
* 938 × 53 = 49714.
*
* What is the total of all the name scores in the file?
*/
@Test
fun `Problem 22`() {
val result = getResourceAsLines("Problem022.txt")
.sorted()
.mapIndexed { index, name -> (index + 1L) * name.wordScore }
.sum()
assertThat(result).isEqualTo(871198282L)
}
/**
* Problem 23
*
* A perfect number is a number for which the sum of its proper divisors is exactly equal to the
* number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28,
* which means that 28 is a perfect number.
*
* A number n is called deficient if the sum of its proper divisors is less than n and it is
* called abundant if this sum exceeds n.
*
* As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can
* be written as the sum of two abundant numbers is 24. By mathematical analysis, it can be
* shown that all integers greater than 28123 can be written as the sum of two abundant numbers.
* However, this upper limit cannot be reduced any further by analysis even though it is known
* that the greatest number that cannot be expressed as the sum of two abundant numbers is less
* than this limit.
*
* Find the sum of all the positive integers which cannot be written as the sum of two abundant
* numbers.
*/
@Test
fun `Problem 23`() {
val numbers = (0..28122).map { it.isAbundant() }
fun Int.isSumOfTwoAbundant(): Boolean {
for (i in 1..this / 2) {
if (numbers[i] && numbers[this - i]) {
return true
}
}
return false
}
val result = (1..28123)
.filterNot { it.isSumOfTwoAbundant() }
.sumOf { it.toLong() }
assertThat(result).isEqualTo(4179871L)
}
/**
* Problem 24
*
* A permutation is an ordered arrangement of objects. For example, 3124 is one possible
* permutation of the digits 1, 2, 3 and 4. If all of the permutations are listed numerically
* or alphabetically, we call it lexicographic order. The lexicographic permutations of 0, 1
* and 2 are:
*
* 012 021 102 120 201 210
*
* What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8
* and 9?
*/
@Test
fun `Problem 24`() {
val digits = (0..9).toMutableList()
var index = 999_999
var value = 0L
while (digits.size > 1) {
val temp = factorial(digits.size - 1L).toInt()
val i = index / temp
index -= (i * temp)
value = value * 10 + digits.removeAt(i)
}
val result = value * 10 + digits[0]
assertThat(result).isEqualTo(2783915460L)
}
/**
* Problem 25
*
* The Fibonacci sequence is defined by the recurrence relation:
*
* F(n) = F(n - 1) + F(n - 2), where F(1) = 1 and F(2) = 1.
*
* Hence the first 12 terms will be:
*
* 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144
*
* The 12th term, F(12), is the first term to contain three digits.
*
* What is the index of the first term in the Fibonacci sequence to contain 1000 digits?
*/
@Test
fun `Problem 25`() {
var index = 2L
var fibonacci = BigInteger.valueOf(1) to BigInteger.valueOf(1)
while (fibonacci.second < BigInteger.TEN.pow(999)) {
fibonacci = fibonacci.second to fibonacci.first + fibonacci.second
index++
}
val result = index
assertThat(result).isEqualTo(4782L)
}
/**
* Problem 26
*
* A unit fraction contains 1 in the numerator. The decimal representation of the unit fractions
* with denominators 2 to 10 are given:
*
* - 1/2 = 0.5
* - 1/3 = 0.(3)
* - 1/4 = 0.25
* - 1/5 = 0.2
* - 1/6 = 0.1(6)
* - 1/7 = 0.(142857)
* - 1/8 = 0.125
* - 1/9 = 0.(1)
* - 1/10 = 0.1
*
* Where 0.1(6) means 0.166666..., and has a 1-digit recurring cycle. It can be seen that 1/7
* has a 6-digit recurring cycle.
*
* Find the value of d < 1000 for which 1/d contains the longest recurring cycle in its decimal
* fraction part.
*/
@Test
fun `Problem 26`() {
val result = (1 until 1000L)
.maxByOrNull { it.reciprocalCycleLength() }!!
assertThat(result).isEqualTo(983L)
}
}
| 0 | Kotlin | 0 | 0 | 9ad8f26583b204e875b07782c8d09d9d8b404b00 | 6,773 | code-kata | MIT License |
src/main/kotlin/com/hjk/advent22/Day10.kt | h-j-k | 572,485,447 | false | {"Kotlin": 26661, "Racket": 3822} | package com.hjk.advent22
import kotlin.math.abs
object Day10 {
fun part1(input: List<String>): Int =
process(input).filter { (_, cycle) -> cycle in setOf(20, 60, 100, 140, 180, 220) }
.sumOf { (x, cycle) -> x * cycle }
fun part2(input: List<String>): List<String> = process(input).chunked(40).map { chunk ->
chunk.fold("") { acc, (x, cycle) -> "$acc${if (abs(x - ((cycle - 1) % 40)) <= 1) "#" else " "}" }
}.toList()
private fun process(input: List<String>): Sequence<Cycle> =
input.asSequence().runningFold(listOf(Cycle(x = 1, cycle = 1))) { acc, line ->
val (x, cycle) = acc.last()
listOfNotNull(
Cycle(x = x, cycle = cycle + 1),
line.split(" ").takeIf { it.size == 2 }
?.let { (_, delta) -> Cycle(x = x + delta.toInt(), cycle = cycle + 2) }
)
}.flatten()
private data class Cycle(val x: Int, val cycle: Int)
}
| 0 | Kotlin | 0 | 0 | 20d94964181b15faf56ff743b8646d02142c9961 | 971 | advent22 | Apache License 2.0 |
utility/src/main/kotlin/aoc2015/utility/Lists.kt | sihamark | 581,653,112 | false | {"Kotlin": 263428, "Shell": 467, "Batchfile": 383} | package aoc2015.utility
/**
* finds all permutations of the receiver list.
* Each permutation has the same length of the receiver list.
*
* For example, when applying this function in the list (1, 2, 3) = (1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)
*/
fun <T> List<T>.allPermutations(): List<List<T>> {
val solutions = mutableListOf<List<T>>()
fun iteratePermutations(already: List<T>, leftElements: List<T>) {
if (leftElements.isEmpty()) {
solutions.add(already)
return
}
for (left in leftElements) {
iteratePermutations(
already.toMutableList().apply { add(left) },
leftElements.toMutableList().apply { remove(left) }
)
}
}
iteratePermutations(listOf(), this)
return solutions
}
/**
* finds all variants of the receiver list.
*
* For example, when applying this function in the list (1, 2, 3) = (), (1), (1, 2), (1, 2, 3), (1, 3), (1, 3, 2), (2), (2, 1), (2, 1, 3), (2, 3), (2, 3, 1), (3), (3, 1), (3, 1, 2), (3, 2), (3, 2, 1)
*/
fun <T> List<T>.allVariants(onSolution: (List<T>) -> Unit) {
fun iterateVariants(already: List<T>, leftElements: List<T>) {
onSolution(already)
for (left in leftElements) {
iterateVariants(
already.toMutableList().apply { add(left) },
leftElements.toMutableList().apply { remove(left) }
)
}
}
iterateVariants(listOf(), this)
}
/**
* finds all variants of the receiver list.
*
* For example, when applying this function in the list (1, 2, 3) = (), (1), (1, 2), (1, 2, 3), (1, 3), (1, 3, 2), (2), (2, 1), (2, 1, 3), (2, 3), (2, 3, 1), (3), (3, 1), (3, 1, 2), (3, 2), (3, 2, 1)
*/
fun <T> List<T>.allVariants(): List<List<T>> {
val solutions = mutableListOf<List<T>>()
allVariants { solutions.add(it) }
return solutions
}
| 0 | Kotlin | 0 | 0 | 6d10f4a52b8c7757c40af38d7d814509cf0b9bbb | 1,946 | aoc2015 | Apache License 2.0 |
src/day01/Day01.kt | Klaus-Anderson | 572,740,347 | false | {"Kotlin": 13405} | package day01
import readInput
fun main() {
fun getTotalCaloriesList(input: List<String>): MutableList<Int> {
val totalCalorieList = mutableListOf<Int>()
val listDelimiter = ""
val breakLines = input.mapIndexedNotNull{ index, elem -> index.takeIf{ elem == listDelimiter } }
breakLines.forEachIndexed { index, breakLineInt ->
val startingIndex = if(index == 0){
0
} else {
breakLines[index-1]
}
val elfCalorieList = input.subList(startingIndex,breakLineInt).filterNot {
it == ""
}
totalCalorieList.add(elfCalorieList.sumOf {
it.toInt()
})
}
return totalCalorieList
}
fun part1(input: List<String>): Int {
return getTotalCaloriesList(input).max()
}
fun part2(input: List<String>): Int {
val totalCaloriesList = getTotalCaloriesList(input)
val topThreeTotalList = mutableListOf<Int>()
repeat(3) {
topThreeTotalList.add(totalCaloriesList.max())
totalCaloriesList.remove(totalCaloriesList.max())
}
return topThreeTotalList.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("day01", "Day01_test")
check(part1(testInput) == 24000)
val input = readInput("day01", "Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | faddc2738011782841ec20475171909e9d4cee84 | 1,486 | harry-advent-of-code-kotlin-template | Apache License 2.0 |
src/main/kotlin/solutions/day14/Day14.kt | Dr-Horv | 112,381,975 | false | null |
package solutions.day14
import solutions.Solver
import utils.Coordinate
import utils.Direction
import utils.KnotHasher
import utils.step
fun Long.toBinaryString(): String {
val s = java.lang.Long.toBinaryString(this)
return if(s.length < 4) {
s.padStart(4, '0')
} else {
s
}
}
class Day14: Solver {
override fun solve(input: List<String>, partTwo: Boolean): String {
val key = input.first()
val map = mutableMapOf<Coordinate, Boolean>()
.withDefault { false }
for (row in 0 until 128) {
val hashKey = "$key-$row"
val hasher = KnotHasher(lengths = KnotHasher.lengthsFromString(hashKey))
for (round in 1..64) {
hasher.doRound()
}
val denseHash = hasher.calculateDenseHash()
var column = 0
for (hex in denseHash) {
val binaryString = hex.toString().toLong(16).toBinaryString()
for(c in binaryString) {
when(c) {
'1' -> {
map[Coordinate(column, row)] = true
}
}
column++
}
}
}
if(!partTwo) {
return map.values.size.toString()
}
val regions = mutableListOf<Set<Coordinate>>()
map.entries
.filter { it.value }
.forEach {
if(hasNoRegion(it.key, regions)) {
regions.add(traverseRegion(it.key, map))
}
}
return regions.size.toString()
}
private fun traverseRegion(key: Coordinate, map: Map<Coordinate, Boolean>, region:MutableSet<Coordinate> = mutableSetOf()): Set<Coordinate> {
val used = map.getValue(key);
if(used) {
region.add(key)
Direction.values()
.forEach {
val next = key.step(it)
if(!region.contains(next)) {
traverseRegion(next, map, region)
}
}
}
return region
}
private fun hasNoRegion(key: Coordinate, regions: MutableList<Set<Coordinate>>): Boolean {
return regions.none { it.contains(key) }
}
}
| 0 | Kotlin | 0 | 2 | 975695cc49f19a42c0407f41355abbfe0cb3cc59 | 2,386 | Advent-of-Code-2017 | MIT License |
kotlin/src/com/s13g/aoc/aoc2022/Day14.kt | shaeberling | 50,704,971 | false | {"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245} | package com.s13g.aoc.aoc2022
import com.s13g.aoc.Result
import com.s13g.aoc.Solver
import com.s13g.aoc.XY
import com.s13g.aoc.resultFrom
import kotlin.math.max
import kotlin.math.min
/**
* --- Day 14: Regolith Reservoir ---
* https://adventofcode.com/2022/day/14
*/
class Day14 : Solver {
override fun solve(lines: List<String>): Result {
val map = drawMap(lines.map { parseTrace(it) })
return resultFrom(
solvePart(map.toMutableMap(), false),
solvePart(map.toMutableMap(), true)
)
}
private fun drawMap(traces: List<List<XY>>): Map<XY, Int> {
val map = mutableMapOf<XY, Int>()
map[XY(500, 0)] = 2
for (trace in traces) {
var prev = trace.first()
trace.subList(1, trace.size).forEach {
for (y in min(prev.y, it.y)..max(prev.y, it.y)) {
for (x in min(prev.x, it.x)..max(prev.x, it.x)) {
map[XY(x, y)] = 1
}
}
prev = it
}
}
return map
}
private fun solvePart(map: MutableMap<XY, Int>, partB: Boolean): Int {
val minX = map.keys.minOf { it.x }
val maxX = map.keys.maxOf { it.x }
val minY = map.keys.minOf { it.y }
val maxY = map.keys.maxOf { it.y }
val floorY = maxY + 2
fun isFree(pos: XY): Boolean = (!partB || pos.y != floorY) && pos !in map
// Simulate sand falling
while (true) {
var falling = true
var newSand = XY(500, 0)
while (falling) {
falling = false
val nextDown = XY(newSand.x, newSand.y + 1)
if (isFree(nextDown)) {
newSand = nextDown
falling = true
} else {
// Left down
val leftDown = XY(newSand.x - 1, newSand.y + 1)
if (isFree(leftDown)) {
newSand = leftDown
falling = true
} else {
val rightDown = XY(newSand.x + 1, newSand.y + 1)
if (isFree(rightDown)) {
newSand = rightDown
falling = true
}
}
}
if (!partB && newSand.y >= maxY) {
printMap(map, minX, maxX, minY, maxY)
return map.values.count { it == 3 }
}
}
if (partB && newSand == XY(500, 0)) {
printMap(map, minX, maxX, minY, maxY)
return map.values.count { it == 3 } + 1
}
map[newSand] = 3
}
}
private fun printMap(
map: Map<XY, Int>,
minX: Int,
maxX: Int,
minY: Int,
maxY: Int
) {
for (y in minY..maxY) {
var line = ""
for (x in minX..maxX) {
line += if (map[XY(x, y)] == 1) "#"
else if (map[XY(x, y)] == 2) "+"
else if (map[XY(x, y)] == 3) "o"
else "."
}
println(line)
}
}
private fun parseTrace(line: String): List<XY> {
return line.split(" -> ").map { it.split(",") }
.map { XY(it[0].toInt(), it[1].toInt()) }
}
} | 0 | Kotlin | 1 | 2 | 7e5806f288e87d26cd22eca44e5c695faf62a0d7 | 2,865 | euler | Apache License 2.0 |
src/day2.kt | miiila | 725,271,087 | false | {"Kotlin": 77215} | import java.io.File
import kotlin.math.max
import kotlin.system.exitProcess
private const val DAY = 2
fun main() {
if (!File("./day${DAY}_input").exists()) {
downloadInput(DAY)
println("Input downloaded")
exitProcess(0)
}
val transformer = { x: String -> x }
val input = loadInput(DAY, false, transformer)
println(input)
val games = mutableListOf<GameRecord>()
for (line in input) {
line.split(":").let {
val gameId = it[0].split(" ").last().toInt()
val gameRecord = GameRecord(gameId)
it[1].split(";").let {
gameRecord.records = it.map {
val game = it.split(",").fold(Game()) { sum, el ->
el.split(" ").let {
when (it[2]) {
"green" -> sum.green = it[1].toInt()
"red" -> sum.red = it[1].toInt()
"blue" -> sum.blue = it[1].toInt()
}
sum
}
}
game
}
}
games.add(gameRecord)
}
}
solvePart1(games)
solvePart2(games)
}
data class GameRecord(val id: Int, var records: List<Game> = mutableListOf())
data class Game(var red: Int = 0, var green: Int = 0, var blue: Int = 0)
// Part 1
private fun solvePart1(games: List<GameRecord>) {
val limits = mapOf("red" to 12, "green" to 13, "blue" to 14)
val result = games.fold(0) { sum: Int, el: GameRecord ->
if (el.records.all { game -> game.blue <= limits["blue"]!! && (game.red <= limits["red"]!!) && game.green <= limits["green"]!! })
sum + el.id
else sum
}
println(result)
}
// Part 2
private fun solvePart2(games: List<GameRecord>) {
val result = games.map { el: GameRecord ->
val mins = el.records.fold(mutableListOf(0, 0, 0)) { agg, el ->
agg[0] = max(agg[0], el.red)
agg[1] = max(agg[1], el.blue)
agg[2] = max(agg[2], el.green)
agg
}
mins.reduce(Int::times)
}.sum()
print(result)
} | 0 | Kotlin | 0 | 1 | 1cd45c2ce0822e60982c2c71cb4d8c75e37364a1 | 2,218 | aoc2023 | MIT License |
src/Day14.kt | fmborghino | 573,233,162 | false | {"Kotlin": 60805} | fun main() {
fun log(message: Any?) {
println(message)
}
data class Vec2(val x: Int, val y: Int)
data class Node(val c: Char)
class Grid(val grid: MutableMap<Vec2, Node>, val hasFloor: Boolean,
val rangeX: Pair<Int, Int>, val rangeY: Pair<Int, Int>)
fun parse(input: List<String>, hasFloor: Boolean = false): Grid {
var rangeXmin = Int.MAX_VALUE
var rangeXmax = Int.MIN_VALUE
var rangeYmin = Int.MAX_VALUE
var rangeYmax = Int.MIN_VALUE
val grid = buildMap<Vec2, Node> {
input.forEachIndexed() { i, line ->
val xys = line.split(" -> ")
xys.windowed(2) { xyPair ->
val (leftX, leftY) = xyPair.first().split(",").map { it.toInt() }
val (rightX, rightY) = xyPair.last().split(",").map { it.toInt() }
when {
leftX == rightX -> { // x same, y moves
// make sure we go small to large
val min = minOf(leftY, rightY)
val max = maxOf(leftY, rightY)
for (y in min..max) { this[Vec2(leftX, y)] = Node('#') }
rangeYmin = minOf(rangeYmin, min)
rangeYmax = maxOf(rangeYmax, max)
}
leftY == rightY -> { // y same, x moves
val min = minOf(leftX, rightX)
val max = maxOf(leftX, rightX)
for (x in min..max) { this[Vec2(x, leftY)] = Node('#') }
rangeXmin = minOf(rangeXmin, min)
rangeXmax = maxOf(rangeXmax, max)
}
else -> error("unexpected diagonal at line $i: $xyPair")
}
}
}
if (hasFloor) {
rangeYmax += 2
val stretch = rangeYmax // not sure how much wider the floor needs to be but...
rangeXmin -= stretch
rangeXmax += stretch
for (x in (rangeXmin - stretch)..(rangeXmax + stretch)) {
this[Vec2(x, rangeYmax)] = Node('#')
}
}
}
return Grid(grid.toMutableMap(), hasFloor, Pair(rangeXmin, rangeXmax), Pair(rangeYmin, rangeYmax))
}
fun printGrid(grid: Grid) {
for (y in grid.rangeY.first - 3..grid.rangeY.second) { // y are the rows top to bottom
print("${"%2d".format(y) } ")
for(x in grid.rangeX.first..grid.rangeX.second) { // x are the columns left to right
val node = grid.grid.getOrDefault(Vec2(x, y), Node('.'))
print(node.c)
}
println()
}
}
fun dropSand(grid: Grid): Int {
fun g(x: Int, y: Int): Char = grid.grid.getOrDefault(Vec2(x, y), Node('.')).c
val startX = 500
val startY = 0
var grainCount = 0
var pouring = true
while (pouring) {
grainCount++
var x = startX
var y = startY
var falling = true
while (falling) {
when {
g(x, y + 1) == '.' -> y++ // below is free, drop 1
g(x - 1, y + 1) == '.' -> { x--; y++ } // else below left is free, drop 1 and left 1
g(x + 1, y + 1) == '.' -> { x++; y++ } // else below right is free, drop 1 and right 1
else -> { grid.grid[Vec2(x, y)] = Node('o'); falling = false } // grain came to rest
}
when (grid.hasFloor) {
// grain fell past bottom, we're done
false -> if (y > grid.rangeY.second) { falling = false; pouring = false }
true -> if (g(startX, startY) == 'o') { falling = false; pouring = false }
}
}
// log("grainCount $grainCount ${if (!pouring) " LAST GRAIN!" else ""}")
// printGrid(grid)
}
return if (grid.hasFloor) grainCount else grainCount - 1
}
fun part1(input: List<String>): Int {
val grid = parse(input)
// printGrid(grid)
val grains = dropSand(grid)
// printGrid(grid)
return grains
}
fun part2(input: List<String>): Int {
val grid = parse(input, hasFloor = true)
// printGrid(grid)
val grains = dropSand(grid)
// printGrid(grid)
return grains
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day14_test.txt")
check(part1(testInput) == 24)
check(part2(testInput) == 93)
val input = readInput("Day14.txt")
println(part1(input))
check(part1(input) == 592)
println(part2(input))
check(part2(input) == 30367)
}
| 0 | Kotlin | 0 | 0 | 893cab0651ca0bb3bc8108ec31974654600d2bf1 | 4,947 | aoc2022 | Apache License 2.0 |
src/main/kotlin/com/github/michaelbull/advent2023/day23/HikingTrailMap.kt | michaelbull | 726,012,340 | false | {"Kotlin": 195941} | package com.github.michaelbull.advent2023.day23
import com.github.michaelbull.advent2023.math.Vector2
import com.github.michaelbull.advent2023.math.Vector2.Companion.CARDINAL_DIRECTIONS
import com.github.michaelbull.advent2023.math.Vector2.Companion.EAST
import com.github.michaelbull.advent2023.math.Vector2.Companion.NORTH
import com.github.michaelbull.advent2023.math.Vector2.Companion.SOUTH
import com.github.michaelbull.advent2023.math.Vector2.Companion.WEST
import com.github.michaelbull.advent2023.math.Vector2CharMap
import com.github.michaelbull.advent2023.math.toVector2CharMap
fun Sequence<String>.toHikingTrailMap(): HikingTrailMap {
return HikingTrailMap(this.toVector2CharMap())
}
data class HikingTrailMap(
val trails: Vector2CharMap,
) {
private val start = Vector2(1, 0)
private val end = Vector2(trails.xRange.last - 1, trails.yRange.last)
private val junctionPositions = trails
.filter(::isJunction)
.map(Pair<Vector2, Char>::first)
fun longestHikeSteps(): Int {
return longestHikeSteps(
tile = start,
findPaths = ::slopedPaths,
)
}
fun levelledOutLongestHikeSteps(): Int {
return longestHikeSteps(
tile = start,
findPaths = levelledOutPaths(),
)
}
private fun longestHikeSteps(
tile: Vector2,
visited: MutableSet<Vector2> = mutableSetOf(),
cumulativeSteps: Int = 0,
findPaths: (Vector2) -> Iterable<Path>,
): Int {
return if (tile == end) {
cumulativeSteps
} else {
visited += tile
val paths = findPaths(tile)
val unvisitedPaths = paths.filter { it.tile !in visited }
val max = unvisitedPaths.maxOfOrNull { (destination, steps) ->
longestHikeSteps(destination, visited, cumulativeSteps + steps, findPaths)
}
visited -= tile
max ?: 0
}
}
private fun slopedPaths(position: Vector2): Iterable<Path> {
val trail = trails[position]
val delta = SLOPES_TO_DELTA[trail]
return if (delta == null) {
position.adjacentTiles().map { Path(it, 1) }
} else {
val downhill = position + delta
if (downhill in trails) {
listOf(Path(downhill, 1))
} else {
emptyList()
}
}
}
private fun levelledOutPaths(): (Vector2) -> Iterable<Path> {
val pathsByJunctionPosition = junctionPositions.associateWith {
mutableListOf<Path>()
}
for ((junctionPosition, junctionPaths) in pathsByJunctionPosition) {
val visited = mutableSetOf(junctionPosition)
var current = mutableSetOf(junctionPosition)
var steps = 1
while (current.isNotEmpty()) {
val next = mutableSetOf<Vector2>()
for (position in current) {
val adjacentTiles = position.adjacentTiles()
val unvisitedTiles = adjacentTiles.filter { it !in visited }
for (unvisitedTile in unvisitedTiles) {
if (unvisitedTile in pathsByJunctionPosition) {
junctionPaths += Path(unvisitedTile, steps)
} else {
visited += unvisitedTile
next += unvisitedTile
}
}
}
current = next
steps++
}
}
return pathsByJunctionPosition::getValue
}
private fun isJunction(pair: Pair<Vector2, Char>): Boolean {
val (position, tile) = pair
return when (position) {
start -> true
end -> true
else -> tile.isPath() && position.isJunction()
}
}
private fun Vector2.isJunction(): Boolean {
return adjacentTiles().size > 2
}
private fun Vector2.adjacentTiles(): List<Vector2> {
return CARDINAL_DIRECTIONS
.map(::plus)
.filter { it in trails && !trails[it].isForest() }
}
private fun Char.isPath(): Boolean {
return this == PATH
}
private fun Char.isForest(): Boolean {
return this == FOREST
}
private data class Path(
val tile: Vector2,
val steps: Int,
)
private companion object {
private const val PATH = '.'
private const val FOREST = '#'
private const val SLOPE_UP = '^'
private const val SLOPE_RIGHT = '>'
private const val SLOPE_DOWN = 'v'
private const val SLOPE_LEFT = '<'
private val SLOPES_TO_DELTA = mapOf(
SLOPE_UP to SOUTH,
SLOPE_RIGHT to EAST,
SLOPE_DOWN to NORTH,
SLOPE_LEFT to WEST,
)
}
}
| 0 | Kotlin | 0 | 1 | ea0b10a9c6528d82ddb481b9cf627841f44184dd | 4,931 | advent-2023 | ISC License |
src/Day09.kt | thomasreader | 573,047,664 | false | {"Kotlin": 59975} | import java.io.Reader
import kotlin.math.abs
data class RopeKnot(var x: Int, var y: Int)
data class IntPair(val x: Int, val y: Int)
infix fun Int.diff(other: Int) = abs((this) - (other))
fun RopeKnot.isAdjacentTo(other: RopeKnot): Boolean {
return (this.x diff other.x < 2 && this.y diff other.y < 2)
}
fun RopeKnot.toPair() = IntPair(this.x, this.y)
fun main() {
val testInput = """
R 4
U 4
L 3
D 1
R 4
D 1
L 5
R 2
""".trimIndent()
val testResult = partOne(testInput.reader())
println(testResult.size)
val input = file("Day09.txt")
println(partOne(input.bufferedReader()).size)
println(partTwo(input.bufferedReader()).size)
}
private fun partTwo(src: Reader): Set<IntPair> {
val rope = Array(10) { RopeKnot(0, 0) }
fun Array<RopeKnot>.head() = this[0]
fun Array<RopeKnot>.tail() = this[this.size - 1]
val tailVisited = mutableSetOf(rope.tail().toPair())
src.forEachLine { line ->
val (cmd, moves) = line.split(" ")
repeat(moves.toInt()) { iter ->
when (cmd) {
"R" -> rope.head().x++
"L" -> rope.head().x--
"U" -> rope.head().y--
"D" -> rope.head().y++
else -> TODO()
}
for (i in 1 until rope.size) {
val ahead = rope[i-1]
val knot = rope[i]
if (!knot.isAdjacentTo(ahead)) {
knot.x += ahead.x.compareTo(knot.x)
knot.y += ahead.y.compareTo(knot.y)
}
}
tailVisited += rope.tail().toPair()
}
}
return tailVisited
}
private fun partOne(src: Reader): Set<IntPair> {
val head = RopeKnot(0, 0)
val tail = RopeKnot(0, 0)
val tailVisited = mutableSetOf(tail.toPair())
src.forEachLine { line ->
val (cmd, moves) = line.split(" ")
repeat(moves.toInt()) { iter ->
when (cmd) {
"R" -> head.x++
"L" -> head.x--
"U" -> head.y--
"D" -> head.y++
else -> TODO()
}
if (!head.isAdjacentTo(tail)) {
tail.x += head.x.compareTo(tail.x)
tail.y += head.y.compareTo(tail.y)
}
tailVisited += tail.toPair()
}
}
return tailVisited
} | 0 | Kotlin | 0 | 0 | eff121af4aa65f33e05eb5e65c97d2ee464d18a6 | 2,430 | advent-of-code-2022-kotlin | Apache License 2.0 |
2022/src/main/kotlin/day1_fast.kt | madisp | 434,510,913 | false | {"Kotlin": 388138} | import utils.Parser
import utils.Solution
import utils.parseItems
fun main() {
Day1Fast.run()
}
object Day1All {
@JvmStatic fun main(args: Array<String>) {
mapOf("func" to Day1Func, "imp" to Day1Imp, "fast" to Day1Fast).forEach { (header, solution) ->
solution.run(
header = header,
printParseTime = false
)
}
}
}
object Day1Fast : Solution<List<IntArray>>() {
override val name = "day1"
override val parser = Parser.blocks.parseItems(Parser.intLines.map { it.toIntArray() })
override fun part1(input: List<IntArray>): Int {
var largestSum = Integer.MIN_VALUE
input.forEach { calories ->
val sum = calories.sum()
if (sum > largestSum) {
largestSum = sum
}
}
return largestSum
}
override fun part2(input: List<IntArray>): Int {
var smallest = 0
var r1 = 0
var r2 = 0
input.forEach { calories ->
val sum = calories.sum()
if (smallest < sum) {
smallest = sum
// rebalance smallest between r1 and r2
if (smallest > r1) {
smallest = r1
r1 = sum
}
if (smallest > r2) {
val r3 = r2
r2 = smallest
smallest = r3
}
}
}
return smallest + r1 + r2
}
}
| 0 | Kotlin | 0 | 1 | 3f106415eeded3abd0fb60bed64fb77b4ab87d76 | 1,282 | aoc_kotlin | MIT License |
solutions/aockt/y2021/Y2021D16.kt | Jadarma | 624,153,848 | false | {"Kotlin": 435090} | package aockt.y2021
import aockt.y2021.Y2021D16.BitsPacket.TypeID.*
import io.github.jadarma.aockt.core.Solution
object Y2021D16 : Solution {
/** A BITS packet type. */
private sealed interface BitsPacket {
/** The version of this packet. Seemingly unused, unless you find the manual. */
val version: Int
/** The type of this packet, describing its behaviour. */
val type: TypeID
/** Evaluate the expressing defined by this packet. */
fun evaluate(): Long
/** The possible types of [BitsPacket], defining their behaviour. */
enum class TypeID(val value: Int) {
Sum(0),
Product(1),
Minimum(2),
Maximum(3),
Literal(4),
GreaterThan(5),
LessThan(6),
EqualTo(7);
companion object {
fun fromValue(value: Int) = values().first { it.value == value }
}
}
/** A literal packet, holding a single [literal] value. */
data class Literal(override val version: Int, val literal: Long) : BitsPacket {
override val type = Literal
override fun evaluate() = literal
}
/** An operator packet, holding one or more [subPackets], which can be evaluated based on the [type]. */
data class Operator(
override val version: Int,
override val type: TypeID,
val subPackets: List<BitsPacket>,
) : BitsPacket {
init {
when (type) {
Literal -> require(false) { "An operator packet cannot be of a literal type." }
GreaterThan, LessThan, EqualTo -> require(subPackets.size == 2) { "Comparison operator should always have exactly two operands." }
else -> require(subPackets.isNotEmpty()) { "Operator missing operands." }
}
}
override fun evaluate(): Long = when (type) {
Sum -> subPackets.sumOf { it.evaluate() }
Product -> subPackets.fold(1L) { acc, packet -> acc * packet.evaluate() }
Minimum -> subPackets.minOf { it.evaluate() }
Maximum -> subPackets.maxOf { it.evaluate() }
GreaterThan -> if (subPackets.first().evaluate() > subPackets.last().evaluate()) 1 else 0
LessThan -> if (subPackets.first().evaluate() < subPackets.last().evaluate()) 1 else 0
EqualTo -> if (subPackets.first().evaluate() == subPackets.last().evaluate()) 1 else 0
Literal -> error("Cannot be a literal")
}
}
companion object {
fun parse(hexInput: String): BitsPacket {
val bitStream = hexInput
.asSequence()
.flatMap { it.digitToInt(16).toString(2).padStart(4, '0').asSequence() }
.map { it == '1' }
.iterator()
var bitsRead = 0
// Consumes the next bit and returns whether it is set.
fun readBoolean(): Boolean = bitStream.next().also { bitsRead++ }
// Consumes the next few [bits] and returns them as a binary string.
fun readString(bits: Int): String = buildString(bits) {
repeat(bits) { append(if (readBoolean()) '1' else '0') }
}
// Consumes the next few [bits] and returns their integer value.
fun readInt(bits: Int): Int = readString(bits).toInt(2)
// Consumes the next few bits in chunks of five, reading the value of a literal.
fun readLiteralValue(): Long = buildString(32) {
while (readBoolean()) append(readString(4))
append(readString(4))
}.toLong(2)
// Consumes the next few bits and attempts to parse an entire packet.
fun readPacket(): BitsPacket {
val version = readInt(3)
val type = TypeID.fromValue(readInt(3))
if (type == Literal) return Literal(version, readLiteralValue())
val subPackets = buildList {
if (readBoolean()) {
val numberOfSubPackets = readInt(11)
repeat(numberOfSubPackets) {
add(readPacket())
}
} else {
val subPacketsLength = readInt(15)
val stopReadingAt = bitsRead + subPacketsLength
while (bitsRead < stopReadingAt) add(readPacket())
}
}
return Operator(version, type, subPackets)
}
val packet = readPacket()
while (bitStream.hasNext()) require(!readBoolean()) { "Found set bit in end padding." }
return packet
}
}
}
override fun partOne(input: String) = BitsPacket.parse(input).run {
fun BitsPacket.versionSum(): Int = when (this) {
is BitsPacket.Literal -> version
is BitsPacket.Operator -> version + subPackets.sumOf { it.versionSum() }
}
versionSum()
}
override fun partTwo(input: String) = BitsPacket.parse(input).evaluate()
}
| 0 | Kotlin | 0 | 3 | 19773317d665dcb29c84e44fa1b35a6f6122a5fa | 5,459 | advent-of-code-kotlin-solutions | The Unlicense |
src/main/kotlin/5. Longest Palindromic Substring Manacher's algorithm.kts | ShreckYe | 206,086,675 | false | null | import kotlin.math.min
// Manacher's Algorithm
class Solution {
fun longestPalindrome(s: String): String {
val lastPosition = 2 * s.length
val numPositions = lastPosition + 1
val longestPalindromeLengthsCenteredAt = IntArray(numPositions)
var rightmostPalindromeCenter = 0
// Always even
var rightmostPalindromeRight = 0
var longestPalindromeCenter = 0
var longestPalindromeLength = 0
longestPalindromeLengthsCenteredAt[0] = 0
for (i in 1 until numPositions) {
val symmetricPalindromeLength =
longestPalindromeLengthsCenteredAt.getOrElse(rightmostPalindromeCenter * 2 - i) { 0 }
val lengthAtI: Int
if (i + symmetricPalindromeLength < rightmostPalindromeRight)
lengthAtI = symmetricPalindromeLength
else {
val minPossibleLength = rightmostPalindromeRight - i
lengthAtI = (minPossibleLength + 2..min(i, lastPosition - i) step 2).asSequence()
// (i * 2 - it) / 2 = i - it / 2 - 1
.takeWhile { s[(i - it) / 2] == s[(i + it) / 2 - 1] }.lastOrNull() ?: minPossibleLength
rightmostPalindromeCenter = i
rightmostPalindromeRight = i + lengthAtI
}
longestPalindromeLengthsCenteredAt[i] = lengthAtI
if (lengthAtI > longestPalindromeLength) {
longestPalindromeCenter = i
longestPalindromeLength = lengthAtI
}
}
return s.substring(
(longestPalindromeCenter - longestPalindromeLength) / 2,
(longestPalindromeCenter + longestPalindromeLength) / 2
)
}
} | 0 | Kotlin | 0 | 0 | 20e8b77049fde293b5b1b3576175eb5703c81ce2 | 1,743 | leetcode-solutions-kotlin | MIT License |
src/Day13.kt | rosyish | 573,297,490 | false | {"Kotlin": 51693} | private data class SpecialList(val children: ArrayDeque<Any>, val parent: SpecialList?) {
override fun toString(): String {
val s = StringBuilder("")
for (i in children.indices) {
val c = children[i]
if (c is Int) s.append(c)
if (c is SpecialList) s.append("[").append(c).append("]")
if (i < children.size - 1) {
s.append(", ")
}
}
return s.toString()
}
}
fun main() {
fun createSpecialList(str: String, current: SpecialList) {
if (str.isNullOrBlank()) return
if (str[0] == '[') {
var child = SpecialList(ArrayDeque(), current)
current.children.add(child)
createSpecialList(str.substring(1), child)
return
}
if (str[0] == ']') {
createSpecialList(str.substring(1), current.parent!!)
return
}
var nextPos = 1;
if (str[0].isDigit()) {
var value = str[0].digitToInt()
if (str.length > 1 && str[1].isDigit()) {
value = str.substring(0, 2).toInt()
nextPos = 2
}
current.children.add(value)
}
createSpecialList(str.substring(nextPos), current)
}
fun checkRightness(left: SpecialList, right: SpecialList, leftIndex: Int, rightIndex: Int): Int {
// println("checkRightness")
// println(left)
// println(right)
var l = left.children.getOrNull(leftIndex)
var r = right.children.getOrNull(rightIndex)
if (l == null && r == null) {
return 0
}
if (l == null) {
// both lists empty or left emptied first
return -1
}
if (r == null) {
// left non-empty but right became empty
return 1
}
if (l is Int && r is SpecialList) {
val temp = SpecialList(ArrayDeque(), null)
temp.children.add(l as Int)
l = temp
}
if (l is SpecialList && r is Int) {
val temp = SpecialList(ArrayDeque(), null)
temp.children.add(r as Int)
r = temp
}
if (l is SpecialList && r is SpecialList) {
var result = checkRightness(l as SpecialList, r as SpecialList, 0, 0)
if (result == 0) {
result = checkRightness(left, right, leftIndex + 1, rightIndex + 1)
}
return result
}
l as Int
r as Int
return when {
l < r -> -1
l > r -> 1
else -> {
checkRightness(left, right, leftIndex + 1, rightIndex + 1)
}
}
}
fun solvePart1(input: List<String>) {
val answer = input.chunked(3).mapIndexed { index, list ->
val left = SpecialList(ArrayDeque(), null)
val right = SpecialList(ArrayDeque(), null)
createSpecialList(list[0], left)
createSpecialList(list[1], right)
if (checkRightness(left, right, 0, 0) == -1) {
index + 1
} else {
0
}
}.sum()
println(answer)
}
fun solvePart2(input: List<String>) {
val input = input.toMutableList()
val comparator = { left: SpecialList, right: SpecialList -> checkRightness(left, right, 0, 0) }
input += "[[2]]"
input += "[[6]]"
val sortedInput = input
.filter { str -> !str.isNullOrBlank() }
.map { str ->
val value = SpecialList(ArrayDeque(), null)
createSpecialList(str, value)
value
}
.sortedWith(comparator)
var answer = 1
sortedInput.forEachIndexed { index, value ->
val str = value.toString().trim()
if (str == "[[2]]" || str == "[[6]]") {
answer *= (index + 1)
}
}
println(answer)
}
val input = readInput("Day13_input")
solvePart1(input)
solvePart2(input)
} | 0 | Kotlin | 0 | 2 | 43560f3e6a814bfd52ebadb939594290cd43549f | 4,123 | aoc-2022 | Apache License 2.0 |
solutions/aockt/y2016/Y2016D02.kt | Jadarma | 624,153,848 | false | {"Kotlin": 435090} | package aockt.y2016
import io.github.jadarma.aockt.core.Solution
object Y2016D02 : Solution {
/** Parses the input and returns the list of instructions for obtaining the bathroom passcode. */
private fun parseInput(input: String): List<List<Direction>> =
input.lines().map { line -> line.map { Direction.valueOf(it.toString()) } }
/** The directions and their effect on grid movement. */
private enum class Direction(val xOffset: Int, val yOffset: Int) {
U(-1, 0), D(1, 0), L(0, -1), R(0, 1)
}
/** Move one unit in the given [direction], but only if that point is one of the given [validPoints]. */
private fun Pair<Int, Int>.move(direction: Direction, validPoints: Set<Pair<Int, Int>>): Pair<Int, Int> {
val point = (first + direction.xOffset) to (second + direction.yOffset)
return point.takeIf { it in validPoints } ?: this
}
/**
* Finds the passcode for a given keypad by following instructions.
*
* @param instructions The list of instructions for each button press, split by lines.
* @param startFrom The keypad button to start from when reading the first set of instructions.
* @param keypad A map from a button's coordinates on the grid to the character it represents. Coordinates have the
* origin in the top right corner.
*/
private fun passcodeFor(
instructions: List<List<Direction>>,
startFrom: Pair<Int, Int>,
keypad: Map<Pair<Int, Int>, Char>,
): String {
require(startFrom in keypad.keys) { "Cannot start from this button because it's not on the keypad." }
return instructions
.runningFold(startFrom) { start, dirs -> dirs.fold(start) { pos, dir -> pos.move(dir, keypad.keys) } }
.drop(1)
.map(keypad::getValue)
.joinToString("")
}
override fun partOne(input: String) =
passcodeFor(
instructions = parseInput(input),
startFrom = 1 to 1,
keypad = mapOf(
0 to 0 to '1', 0 to 1 to '2', 0 to 2 to '3',
1 to 0 to '4', 1 to 1 to '5', 1 to 2 to '6',
2 to 0 to '7', 2 to 1 to '8', 2 to 2 to '9',
),
)
override fun partTwo(input: String): Any =
passcodeFor(
instructions = parseInput(input),
startFrom = 2 to 0,
keypad = mapOf(
0 to 2 to '1',
1 to 1 to '2', 1 to 2 to '3', 1 to 3 to '4',
2 to 0 to '5', 2 to 1 to '6', 2 to 2 to '7', 2 to 3 to '8', 2 to 4 to '9',
3 to 1 to 'A', 3 to 2 to 'B', 3 to 3 to 'C',
4 to 2 to 'D',
),
)
}
| 0 | Kotlin | 0 | 3 | 19773317d665dcb29c84e44fa1b35a6f6122a5fa | 2,712 | advent-of-code-kotlin-solutions | The Unlicense |
kotlin/src/main/kotlin/dev/mikeburgess/euler/problems/Problem026.kt | mddburgess | 261,028,925 | false | null | package dev.mikeburgess.euler.problems
/**
* Problem 26
*
* A unit fraction contains 1 in the numerator. The decimal representation of the unit fractions
* with denominators 2 to 10 are given:
*
* 1/2 = 0.5
* 1/3 = 0.(3)
* 1/4 = 0.25
* 1/5 = 0.2
* 1/6 = 0.1(6)
* 1/7 = 0.(142857)
* 1/8 = 0.125
* 1/9 = 0.(1)
* 1/10 = 0.1
*
* Where 0.1(6) means 0.166666..., and has a 1-digit recurring cycle. It can be seen that 1/7 has a
* 6-digit recurring cycle.
*
* Find the value of d < 1000 for which 1/d contains the longest recurring cycle in its decimal
* fraction part.
*/
class Problem026 : Problem {
private fun Long.reciprocalPeriod(): Long {
val remainders = mutableMapOf<Long, Long>()
var i = 1L
var position = 1L
do {
remainders[i] = position++
i = (i % this) * 10
} while (i != 0L && remainders[i] == null)
return when (i) {
0L -> 0L
else -> position - remainders[i]!!
}
}
override fun solve(): Long =
(1..999L).maxBy { it.reciprocalPeriod() }!!
}
| 0 | Kotlin | 0 | 0 | 86518be1ac8bde25afcaf82ba5984b81589b7bc9 | 1,106 | project-euler | MIT License |
codeforces/kotlinheroes1/f.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package codeforces.kotlinheroes1
fun main() {
val (n, m, canIncrease) = readInts()
val a = readInts().sorted()
val acc = mutableListOf(0L)
for (i in 0 until n) { acc.add(acc[i] + a[i]) }
var ans = a.fold(0L, Long::plus)
for (left in 0..n - m) {
var low = a[left]
var high = a[left + (m - 1) / 2] + 1
while (low + 1 < high) {
val mid = (low + high) / 2
val index = a.binarySearch(mid, left, m)
val increases = (index - left) * 1L * mid - (acc[index] - acc[left])
if (increases <= canIncrease) {
low = mid
} else {
high = mid
}
}
val index = a.binarySearch(low, left, m)
val ops = (index - left) * 1L * low - (acc[index] - acc[left]) +
(acc[left + m] - acc[index]) - (left + m - index) * 1L * low
ans = minOf(ans, ops)
}
println(ans)
}
private fun List<Int>.binarySearch(value: Int, from: Int, length: Int): Int {
val binarySearch = this.binarySearch(value, from, from + length)
return if (binarySearch >= 0) binarySearch else -1 - binarySearch
}
private fun readLn() = readLine()!!
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| 0 | Java | 1 | 9 | 30953122834fcaee817fe21fb108a374946f8c7c | 1,306 | competitions | The Unlicense |
src/main/kotlin/Day03.kt | JPQuirmbach | 572,636,904 | false | {"Kotlin": 11093} | fun main() {
fun priority(group: List<String>): Int {
val chars = group.flatMap { it.toSet() }
val sharedItem = chars.groupingBy { it }
.eachCount()
.maxBy { it.value }.key
return if (sharedItem.isLowerCase())
sharedItem - 'a' + 1
else
sharedItem - 'A' + 27
}
fun part1(input: String): Int {
return input.lines()
.map { it.chunked(it.length / 2) }
.sumOf { priority(it) }
}
fun part2(input: String): Int {
return input.lines()
.chunked(3)
.sumOf { priority(it) }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 829e11bd08ff7d613280108126fa6b0b61dcb819 | 913 | advent-of-code-Kotlin-2022 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/MinFallingPathSum.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import dev.shtanko.algorithms.MOD
import kotlin.math.min
/**
* 931. Minimum Falling Path Sum
* @see <a href="https://leetcode.com/problems/minimum-falling-path-sum">Source</a>
*/
fun interface MinFallingPathSum {
operator fun invoke(matrix: Array<IntArray>): Int
}
class MinFallingPathSumTopDown : MinFallingPathSum {
override operator fun invoke(matrix: Array<IntArray>): Int {
val (rowCount, colCount) = listOf(matrix.size, matrix[0].size)
fun calculatePathSum(row: Int, col: Int): Int {
if (col < 0 || col == colCount) {
return MOD
}
if (row == 0) {
return matrix[row][col]
}
val leftSum = calculatePathSum(row - 1, col - 1)
val straightSum = calculatePathSum(row - 1, col)
val rightSum = calculatePathSum(row - 1, col + 1)
return matrix[row][col] + listOf(leftSum, straightSum, rightSum).min()
}
var minPathSum = MOD
for (currentCol in 0 until colCount) {
minPathSum = min(minPathSum, calculatePathSum(rowCount - 1, currentCol))
}
return minPathSum
}
}
class MinFallingPathSumDPMemo : MinFallingPathSum {
override operator fun invoke(matrix: Array<IntArray>): Int {
val memo = mutableMapOf<String, Int>()
val (rowCount, colCount) = listOf(matrix.size, matrix[0].size)
fun calculatePathSum(row: Int, col: Int): Int {
if (col < 0 || col == colCount) {
return MOD
}
if (row == 0) {
return matrix[row][col]
}
val memoKey = "$row,$col"
if (!memo.contains(memoKey)) {
val leftSum = calculatePathSum(row - 1, col - 1)
val straightSum = calculatePathSum(row - 1, col)
val rightSum = calculatePathSum(row - 1, col + 1)
memo[memoKey] = matrix[row][col] + listOf(leftSum, straightSum, rightSum).min()
}
return memo[memoKey] ?: 0
}
var minPathSum = MOD
for (currentCol in 0 until colCount) {
minPathSum = min(minPathSum, calculatePathSum(rowCount - 1, currentCol))
}
return minPathSum
}
}
class MinFallingPathSumBottomUp : MinFallingPathSum {
override operator fun invoke(matrix: Array<IntArray>): Int {
val (rowCount, colCount) = matrix.size to matrix[0].size
for (currentRow in 1 until rowCount) {
updateMatrixRow(matrix, currentRow, colCount)
}
return matrix[rowCount - 1].min()
}
private fun updateMatrixRow(matrix: Array<IntArray>, row: Int, colCount: Int) {
for (currentCol in 0 until colCount) {
val leftValue = getMatrixValue(matrix, row - 1, currentCol - 1, colCount)
val straightValue = getMatrixValue(matrix, row - 1, currentCol, colCount)
val rightValue = getMatrixValue(matrix, row - 1, currentCol + 1, colCount)
matrix[row][currentCol] += listOf(leftValue, straightValue, rightValue).min()
}
}
private fun getMatrixValue(matrix: Array<IntArray>, row: Int, col: Int, colCount: Int): Int {
return if (col in 0 until colCount) matrix[row][col] else MOD
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 3,945 | kotlab | Apache License 2.0 |
src/Day04.kt | Soykaa | 576,055,206 | false | {"Kotlin": 14045} | // https://stackoverflow.com/questions/67712063/kotlin-split-string-into-range
private fun IntRange.isSubset(other: IntRange): Boolean = first in other && last in other
private fun IntRange.isOverlap(other: IntRange): Boolean = first in other || last in other
private fun getRanges(input: List<String>): List<List<IntRange>> = input.map { line ->
line.split(",")
.map {
it.split("-")
.let { (a, b) -> a.toInt()..b.toInt() }
}
}
fun main() {
fun part1(input: List<String>): Int = getRanges(input).count { (range1, range2) ->
range1.isSubset(range2) || range2.isSubset(range1)
}
fun part2(input: List<String>): Int = getRanges(input).count { (range1, range2) ->
range1.isOverlap(range2) || range2.isOverlap(range1)
}
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 1e30571c475da4db99e5643933c5341aa6c72c59 | 889 | advent-of-kotlin-2022 | Apache License 2.0 |
src/Day01.kt | ExpiredMinotaur | 572,572,449 | false | {"Kotlin": 11216} | fun main() {
fun part1(input: List<String>): Int {
val elves = input.chunkedByBlank() //separate elves
.map { cal -> cal.sumOf { it.toInt() } } //count calories
return elves.max() //return max amount of calories
}
fun part2(input: List<String>): Int {
return input.chunkedByBlank()//separate elves
.map { cal -> cal.sumOf { it.toInt() } } //count calories
.sortedDescending() //sort elves by calories
.take(3) //take top 3
.sum() //sum top 3
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
val input = readInput("Day01")
println("Part 1: " + part1(input))
println("Part 2: " + part2(input))
}
| 0 | Kotlin | 0 | 0 | 7ded818577737b0d6aa93cccf28f07bcf60a9e8f | 853 | AOC2022 | Apache License 2.0 |
src/main/kotlin/github/walkmansit/aoc2020/Day14.kt | walkmansit | 317,479,715 | false | null | package github.walkmansit.aoc2020
class Day14(val input: List<String>) : DayAoc<Long, Long> {
private class MaskMachine(val commands: Collection<String>) {
fun applyCommandsAndGetSum(): Long {
var zeroMask = Long.MAX_VALUE // for mult
var oneMask = Long.MIN_VALUE // for add
val dict: MutableMap<Int, Long> = mutableMapOf()
fun updateMasks(mask: String) {
zeroMask = 0L
oneMask = 0L
for (i in mask.indices) {
val idx = mask.length - i - 1
if (mask[idx] == '1') {
oneMask = oneMask or (1L shl i)
continue
}
if (mask[idx] == '0') {
zeroMask = zeroMask or (1L shl i)
}
}
zeroMask = (zeroMask.inv() shl 28) ushr 28
}
fun applyMemoryCommand(key: Int, value: Long) {
dict[key] = (value and zeroMask) or oneMask
}
for (command in commands) {
val parts = command.split(" = ")
if (parts[0] == "mask") {
updateMasks(parts[1])
} else {
applyMemoryCommand(
parts[0].subSequence(4, parts[0].length - 1).toString().toInt(),
parts[1].toLong()
)
}
}
return dict.values.sum()
}
fun applyCommandsWithMemory(): Long {
val dict: MutableMap<Long, Long> = mutableMapOf()
var mask = ""
var address = 0L
fun getAddresses(inp: List<Long>, currentIdx: Int): List<Long> {
if (currentIdx == 36)
return inp
val maskIdx = mask.length - currentIdx - 1
when (mask[maskIdx]) {
'0' -> {
val adrVal = address and (1L shl currentIdx)
if (adrVal != 0L)
return getAddresses(inp.map { x -> x or (1L shl currentIdx) }, currentIdx + 1)
return getAddresses(inp, currentIdx + 1)
}
'1' -> {
return getAddresses(inp.map { x -> x or (1L shl currentIdx) }, currentIdx + 1)
}
else -> { // X
return getAddresses(inp + inp.map { x -> x or (1L shl currentIdx) }, currentIdx + 1)
}
}
}
for (command in commands) {
val parts = command.split(" = ")
if (parts[0] == "mask") {
mask = parts[1]
} else {
address = parts[0].subSequence(4, parts[0].length - 1).toString().toLong()
val value = parts[1].toLong()
for (adr in getAddresses(mutableListOf(0L), 0))
dict[adr] = value
}
}
return dict.values.sum()
}
}
override fun getResultPartOne(): Long {
return MaskMachine(input).applyCommandsAndGetSum()
}
override fun getResultPartTwo(): Long {
return MaskMachine(input).applyCommandsWithMemory()
}
}
| 0 | Kotlin | 0 | 0 | 9c005ac4513119ebb6527c01b8f56ec8fd01c9ae | 3,412 | AdventOfCode2020 | MIT License |
src/main/aoc2022/Day11.kt | nibarius | 154,152,607 | false | {"Kotlin": 963896} | package aoc2022
class Day11(input: List<String>) {
data class Monkey(
val holding: MutableList<Long>,
val test: Int,
val ifTrue: Int,
val ifFalse: Int,
val op: (Long) -> Long
) {
var numInspections = 0L
fun inspectAndThrow(copingStrategy: (Long) -> Long): Pair<Long, Int> {
numInspections++
var toThrow = holding.removeAt(0)
toThrow = op(toThrow)
toThrow = copingStrategy(toThrow)
return toThrow to if (toThrow % test == 0L) ifTrue else ifFalse
}
}
private val monkeys = parseInput(input)
fun parseInput(input: List<String>): List<Monkey> {
return input.map { monkey ->
val lines = monkey.split("\n").drop(1)
val items = lines[0].substringAfter(": ").split(", ").map { it.toLong() }
val test = lines[2].substringAfterLast(" ").toInt()
val ifTrue = lines[3].substringAfterLast(" ").toInt()
val ifFalse = lines[4].substringAfterLast(" ").toInt()
val (operation, amount) = lines[1].substringAfter("new = old ").split(" ")
val op = when {
amount == "old" -> { a: Long -> a * a }
operation == "*" -> { a: Long -> a * amount.toLong() }
operation == "+" -> { a: Long -> a + amount.toLong() }
else -> error("Unknown operation: ${lines[1]}")
}
Monkey(items.toMutableList(), test, ifTrue, ifFalse, op)
}
}
private fun play(rounds: Int, copingStrategy: (Long) -> Long) {
repeat(rounds) {
monkeys.forEach { monkey ->
while (monkey.holding.isNotEmpty()) {
val (item, toMonkey) = monkey.inspectAndThrow(copingStrategy)
monkeys[toMonkey].holding.add(item)
}
}
}
}
private fun calculateMonkeyBusiness() = monkeys
.map { it.numInspections }
.sortedDescending()
.take(2)
.let { (a, b) -> a * b }
fun solvePart1(): Long {
play(20) { a -> a / 3 }
return calculateMonkeyBusiness()
}
fun solvePart2(): Long {
// The divisors used for the tests are all primes. Multiply them together to find the
// least common denominator shared between all the monkeys
val worryModulo = monkeys.map { it.test }.reduce(Int::times)
play(10000) { a -> a % worryModulo }
return calculateMonkeyBusiness()
}
} | 0 | Kotlin | 0 | 6 | f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22 | 2,540 | aoc | MIT License |
src/day10/Day10.kt | TheJosean | 573,113,380 | false | {"Kotlin": 20611} | package day10
import readInput
fun main() {
fun part1(input: List<String>): Int {
val cycles = listOf(20, 60, 100, 140, 180, 220)
var cycle = 0
var x = 1
return input.sumOf {
var result = 0
cycle++
when (it) {
"noop" -> {
if (cycles.contains(cycle)) result = x * cycle
}
else -> {
if (cycles.contains(cycle)) result = x * (cycle)
cycle++
if (cycles.contains(cycle)) result = x * (cycle)
x += it.split(' ').last().toInt()
}
}
result
}
}
fun part2(input: List<String>): String {
fun print(x: Int, cycle: Int, cycles: List<Int>): String {
var result = if (((x - 1)..(x + 1)).contains((cycle - 1) % 40)) "#" else "."
if (cycles.contains(cycle)) result += "\n"
return result
}
val cycles = listOf(40, 80, 120, 160, 200, 240)
var cycle = 0
var x = 1
return input.joinToString("") {
cycle++
when (it) {
"noop" -> {
print(x, cycle, cycles)
}
else -> {
val result = print(x, cycle++, cycles) + print(x, cycle, cycles)
x += it.split(' ').last().toInt()
result
}
}
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("/day10/Day10_test")
check(part1(testInput) == 13140)
check(part2(testInput) ==
"##..##..##..##..##..##..##..##..##..##..\n" +
"###...###...###...###...###...###...###.\n" +
"####....####....####....####....####....\n" +
"#####.....#####.....#####.....#####.....\n" +
"######......######......######......####\n" +
"#######.......#######.......#######.....\n" )
val input = readInput("/day10/Day10")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 798d5e9b1ce446ba3bac86f70b7888335e1a242b | 2,158 | advent-of-code | Apache License 2.0 |
kotlin/wordy/src/main/kotlin/Wordy.kt | fredyw | 523,079,058 | false | null | import kotlin.math.pow
object Wordy {
fun answer(input: String): Int {
val initial =
("What is (-?\\d+)" +
"(?: " +
"plus -?\\d+" +
"| minus -?\\d+" +
"| multiplied by -?\\d+" +
"| divided by -?\\d+" +
"| raised to the \\d+(?:st|nd|rd|th) power" +
")*\\?").toRegex().getNumber(input)
val opRegex =
("plus -?\\d+" +
"|minus -?\\d+" +
"|multiplied by -?\\d+" +
"|divided by -?\\d+" +
"|raised to the \\d+(?:st|nd|rd|th) power"
).toRegex()
return generateSequence(opRegex.find(input)) { opRegex.find(input, it.range.last + 1) }
.map { it.value }
.fold(initial) { acc, s -> evaluate(acc, s) }
}
private fun evaluate(num: Int, s: String): Int {
return when {
s.startsWith("plus") ->
num + "plus (-?\\d+)".toRegex().getNumber(s)
s.startsWith("minus") ->
num - "minus (-?\\d+)".toRegex().getNumber(s)
s.startsWith("multiplied by") ->
num * "multiplied by (-?\\d+)".toRegex().getNumber(s)
s.startsWith("divided by") ->
num / "divided by (-?\\d+)".toRegex().getNumber(s)
else ->
num.toDouble().pow(
"raised to the (\\d+)(?:st|nd|rd|th) power".toRegex()
.getNumber(s)
).toInt()
}
}
private fun Regex.getNumber(s: String): Int =
this.find(s)?.groupValues?.get(1)?.toInt() ?: throw Exception()
}
| 0 | Kotlin | 0 | 0 | 101a0c849678ebb7d2e15b896cfd9e5d82c56275 | 1,747 | exercism | MIT License |
src/twentytwentytwo/day2/Day02.kt | colinmarsch | 571,723,956 | false | {"Kotlin": 65403, "Python": 6148} | fun main() {
fun part1(input: List<String>): Int = input.sumOf { round ->
val choices = round.split(" ")
val them = choices[0]
val me = choices[1]
win(them, me) + extraScore(me)
}
fun part2(input: List<String>): Int = input.sumOf { round ->
val choices = round.split(" ")
val them = choices[0]
val result = choices[1]
val me = myChoice(them, result)
extraScore(me) + win(them, me)
}
val input = readInput("day2", "Day02_input")
println(part1(input))
println(part2(input))
}
private fun win(them: String, me: String): Int = when (them) {
"A" -> {
when (me) {
"X", "A" -> 3
"Y", "B" -> 6
"Z", "C" -> 0
else -> 0
}
}
"B" -> when (me) {
"X", "A" -> 0
"Y", "B" -> 3
"Z", "C" -> 6
else -> 0
}
"C" -> when (me) {
"X", "A" -> 6
"Y", "B" -> 0
"Z", "C" -> 3
else -> 0
}
else -> 0
}
private fun extraScore(me: String): Int = when (me) {
"X", "A" -> 1
"Y", "B" -> 2
"Z", "C" -> 3
else -> 0
}
private fun myChoice(them: String, result: String): String = when (them) {
"A" -> {
when (result) {
"X" -> "C"
"Y" -> "A"
"Z" -> "B"
else -> ""
}
}
"B" -> when (result) {
"X" -> "A"
"Y" -> "B"
"Z" -> "C"
else -> ""
}
"C" -> when (result) {
"X" -> "B"
"Y" -> "C"
"Z" -> "A"
else -> ""
}
else -> ""
}
| 0 | Kotlin | 0 | 0 | bcd7a08494e6db8140478b5f0a5f26ac1585ad76 | 1,612 | advent-of-code | Apache License 2.0 |
src/main/kotlin/day16/day16.kt | lavong | 317,978,236 | false | null | /*
--- Day 16: Ticket Translation ---
As you're walking to yet another connecting flight, you realize that one of the legs of your re-routed trip coming up is on a high-speed train. However, the train ticket you were given is in a language you don't understand. You should probably figure out what it says before you get to the train station after the next flight.
Unfortunately, you can't actually read the words on the ticket. You can, however, read the numbers, and so you figure out the fields these tickets must have and the valid ranges for values in those fields.
You collect the rules for ticket fields, the numbers on your ticket, and the numbers on other nearby tickets for the same train service (via the airport security cameras) together into a single document you can reference (your puzzle input).
The rules for ticket fields specify a list of fields that exist somewhere on the ticket and the valid ranges of values for each field. For example, a rule like class: 1-3 or 5-7 means that one of the fields in every ticket is named class and can be any value in the ranges 1-3 or 5-7 (inclusive, such that 3 and 5 are both valid in this field, but 4 is not).
Each ticket is represented by a single line of comma-separated values. The values are the numbers on the ticket in the order they appear; every ticket has the same format. For example, consider this ticket:
.--------------------------------------------------------.
| ????: 101 ?????: 102 ??????????: 103 ???: 104 |
| |
| ??: 301 ??: 302 ???????: 303 ??????? |
| ??: 401 ??: 402 ???? ????: 403 ????????? |
'--------------------------------------------------------'
Here, ? represents text in a language you don't understand. This ticket might be represented as 101,102,103,104,301,302,303,401,402,403; of course, the actual train tickets you're looking at are much more complicated. In any case, you've extracted just the numbers in such a way that the first number is always the same specific field, the second number is always a different specific field, and so on - you just don't know what each position actually means!
Start by determining which tickets are completely invalid; these are tickets that contain values which aren't valid for any field. Ignore your ticket for now.
For example, suppose you have the following notes:
class: 1-3 or 5-7
row: 6-11 or 33-44
seat: 13-40 or 45-50
your ticket:
7,1,14
nearby tickets:
7,3,47
40,4,50
55,2,20
38,6,12
It doesn't matter which position corresponds to which field; you can identify invalid nearby tickets by considering only whether tickets contain values that are not valid for any field. In this example, the values on the first nearby ticket are all valid for at least one field. This is not true of the other three nearby tickets: the values 4, 55, and 12 are are not valid for any field. Adding together all of the invalid values produces your ticket scanning error rate: 4 + 55 + 12 = 71.
Consider the validity of the nearby tickets you scanned. What is your ticket scanning error rate?
*/
package day16
fun main() {
val input = AdventOfCode.file("day16/input")
.lines().filterNot { it.isBlank() }
solvePartOne(input)
.also { println("solution part 1: $it") }
solvePartTwo(input)
.also { println("solution part 2: $it") }
}
data class Rule(val name: String, val valid: Set<Int>) {
companion object {
fun parse(input: String): Rule {
return with(input.split(":")) {
val name = first()
val valid = mutableSetOf<Int>()
last().split("or")
.map { it.trim().split("-") }
.onEach {
IntRange(it.first().toInt(), it.last().toInt()).forEach {
valid.add(it)
}
}
Rule(name, valid)
}
}
}
}
data class Ticket(val ids: List<Int>) {
companion object {
fun parse(input: String) = Ticket(input.split(",").map { it.toInt() })
}
}
data class Note(
val rules: List<Rule>,
val yourTicket: Ticket,
val nearbyTickets: List<Ticket>
) {
fun invalidTicketIds(): List<Int> {
val validIds = mutableSetOf<Int>()
.apply { rules.map { it.valid }.onEach { addAll(it) } }
val ids = mutableListOf<Int>()
.apply { nearbyTickets.map { it.ids }.onEach { addAll(it) } }
return ids.filterNot { it in validIds }
}
companion object {
fun parse(input: List<String>): Note {
val ytStart = input.indexOf("your ticket:")
val ntStart = input.indexOf("nearby tickets:")
val rules = input.subList(0, ytStart)
.map { Rule.parse(it) }
val yourTicket = input.subList(ytStart + 1, ntStart)
.map { Ticket.parse(it) }
.first()
val nearbyTickets = input.takeLast(input.size - ntStart - 1)
.map { Ticket.parse(it) }
return Note(rules, yourTicket, nearbyTickets)
}
}
}
fun solvePartOne(input: List<String>): Int {
return Note.parse(input)
.invalidTicketIds()
.sum()
}
fun solvePartTwo(input: List<String>): Any {
// TODO 🤷🏼 meh.
return """¯\_(ツ)_/¯"""
}
| 0 | Kotlin | 0 | 1 | a4ccec64a614d73edb4b9c4d4a72c55f04a4b77f | 5,419 | adventofcode-2020 | MIT License |
src/main/kotlin/com/chriswk/aoc/2020/Day1.kt | chriswk | 317,550,327 | false | null | package com.chriswk.aoc.`2020`
class Day1 {
companion object {
@JvmStatic
fun main(args: Array<String>): Unit {
val day = Day1()
val numbers = "day1.txt".fileToLines().map { it.toInt() }.sorted()
report {
day.part1(numbers)
}
report {
day.part2(numbers)
}
report {
day.part2ByCombinations(numbers)
}
}
}
fun findPair(goal: Int, options: Set<Int>): Pair<Int,Int>? {
return options.mapNotNull { a ->
if(options.contains(goal-a)) {
a to (goal-a)
} else {
null
}
}.firstOrNull()
}
fun findTriplet(goal: Int, options:Set<Int>): Triple<Int, Int, Int>? {
return options.asSequence().mapNotNull { a ->
val pair = findPair(goal - a, options-a)
if (pair != null) {
Triple(a, pair.first, pair.second)
} else {
null
}
}.firstOrNull()
}
fun findByCombinations(goal: Int, options: List<Int>): List<Int> {
return options.combinations(3).first { (a,b,c) -> a+b+c == goal }
}
fun part1(numbers: List<Int>): Int {
val (a,b) = findPair(2020, numbers.toSortedSet())!!
return a*b
}
fun part2(numbers: List<Int>): Int {
return findTriplet(2020, numbers.toSortedSet())?.let { (a,b,c) ->
a*b*c
} ?: 0
}
fun part2ByCombinations(numbers: List<Int>): Int {
val ans = findByCombinations(2020, numbers)
return ans.fold(1) { acc, e -> acc*e }
}
fun fmrPartOne(): Int = fmrFindTarget("day1.txt".fileToLines().map { it.toInt() }, 2020)!!
private fun fmrFindTarget(expences: List<Int>, target: Int): Int? {
return expences
.firstOrNull { expences.contains(target - it) }
?.let { (target - it) * it }
}
fun fmrPartTwo(): Int {
val expenses = "day1.txt".fileToLines().map { it.toInt() }
return expenses
.map { it to fmrFindTarget(expenses, 2020 - it) }
.first { it.second != null }
.let { it.first * it.second!! }
}
} | 0 | Kotlin | 0 | 0 | b2ec866e565bcba9ec0287a6d51297e91831a5b2 | 2,269 | aoc2020 | MIT License |
src/main/kotlin/com/chriswk/aoc/advent2020/Day7.kt | chriswk | 317,863,220 | false | {"Kotlin": 481061} | package com.chriswk.aoc.advent2020
import com.chriswk.aoc.AdventDay
import com.chriswk.aoc.util.report
import com.chriswk.aoc.util.toInt
import org.apache.logging.log4j.LogManager
class Day7: AdventDay(2020, 7) {
companion object {
@JvmStatic
fun main(args: Array<String>) {
val day = Day7()
report {
day.part1()
}
report {
day.part2()
}
}
val logger = LogManager.getLogger(Day7::class.java)
}
val childRegex = """(\d+) (\S* \S*)""".toRegex()
fun readRule(rule: String): List<Pair<ColoredBag, ColoredBag>> {
val content = rule.split(" ")
val parent = content.take(2).joinToString(" ")
val children = content.drop(4).joinToString(" ").split(",")
return children.mapNotNull {
val child = it.trim()
val match = childRegex.find(child)
if (match != null) {
(parent to 1) to (match.groups[2]!!.value to toInt(match.groups[1]))
} else {
null
}
}
}
fun toAscendantGraph(rules: List<Pair<ColoredBag, ColoredBag>>): Map<String, List<ColoredBag>> {
return rules.groupBy { it.second.first }.mapValues { it.value.map { it.first } }
}
fun toAdjacencyGraph(rules: List<Pair<ColoredBag, ColoredBag>>): Map<String, List<ColoredBag>> {
return rules.groupBy { it.first.first }.mapValues { it.value.map { it.second } }
}
fun parsePart1(input: List<String>): Map<String, List<ColoredBag>> {
return toAscendantGraph(input.flatMap { readRule(it) })
}
fun parsePart2(input: List<String>): Map<String, List<ColoredBag>> {
return toAdjacencyGraph(input.flatMap { readRule(it) })
}
fun findBagColors(graph: Map<String, List<String>>, visited: Set<String>, color: String): Set<String> {
val direct = graph[color]?.toSet() ?: emptySet()
val remainToVisit = direct - visited
return if (remainToVisit.isEmpty()) {
emptySet()
} else {
direct + remainToVisit.flatMap { findBagColors(graph, visited + color, it) }
}
}
fun findHowManyBags(graph: Map<String, List<ColoredBag>>, color: String): Int {
val children = graph[color] ?: emptyList()
return if (children.isNotEmpty()) {
1 + children.sumOf { it.second * findHowManyBags(graph, it.first) }
} else {
1
}
}
fun part1(): Int {
val graph = parsePart1(inputAsLines)
return findBagColors(graph.mapValues { it.value.map { it.first }}, emptySet(), "shiny gold").size
}
fun part2(): Int {
val graph = parsePart2(inputAsLines)
return findHowManyBags(graph, "shiny gold") - 1
}
}
typealias ColoredBag = Pair<String, Int>
typealias Graph = Map<String, Pair<String, Int>>
| 116 | Kotlin | 0 | 0 | 69fa3dfed62d5cb7d961fe16924066cb7f9f5985 | 2,915 | adventofcode | MIT License |
src/main/kotlin/org/sjoblomj/adventofcode/day11/Day11.kt | sjoblomj | 161,537,410 | false | null | package org.sjoblomj.adventofcode.day11
import org.sjoblomj.adventofcode.readFile
import kotlin.system.measureTimeMillis
private const val inputFile = "src/main/resources/inputs/day11.txt"
private const val defaultSquareSize = 3
private const val gridWidth = 300
private const val gridHeight = 300
private const val maxSquareSize = 300
inline fun <reified T> matrix2d(height: Int, width: Int, initialize: (Int, Int) -> T) =
Array(height) { x -> Array(width) { y -> initialize.invoke(x, y) } }
fun day11() {
println("== DAY 11 ==")
val timeTaken = measureTimeMillis { calculateAndPrintDay11() }
println("Finished Day 11 in $timeTaken ms\n")
}
private fun calculateAndPrintDay11() {
val gridSerialNumber = readFile(inputFile)[0].toInt()
val squareOfSize3 = getBestSquareOfSize3(gridSerialNumber)
val squareOfAnySize = getBestSquareOfAnySize(gridSerialNumber)
println("X,Y coordinate of the best square of size $defaultSquareSize is ${squareOfSize3.topLeftX},${squareOfSize3.topLeftY}")
println("X,Y,Size of the best square of any size is ${squareOfAnySize.topLeftX},${squareOfAnySize.topLeftY},${squareOfAnySize.squareSize}")
}
internal fun getBestSquareOfSize3(gridSerialNumber: Int) =
getBestSquare(gridSerialNumber, defaultSquareSize) { squareSize -> squareSize == defaultSquareSize }
internal fun getBestSquareOfAnySize(gridSerialNumber: Int): Square {
val squareSizeLimit = maxSquareSize
return getBestSquare(gridSerialNumber, squareSizeLimit) { true }
}
private fun getBestSquare(gridSerialNumber: Int, squareSizeLimit: Int, squareSizeIncluder: (Int) -> Boolean): Square {
val area = createArea(gridSerialNumber)
val powerLinesHori = matrix2d(gridHeight, gridWidth) { _, _ -> 0 }
val powerLinesVert = matrix2d(gridHeight, gridWidth) { _, _ -> 0 }
val grid = matrix2d(gridHeight, gridWidth) { _, _ -> 0 }
var bestSquare = Square(-1, -1, -1, Int.MIN_VALUE)
for (squareSize in 1..squareSizeLimit) {
for (x in 1 until gridWidth - squareSize) {
for (y in 1 until gridHeight - squareSize) {
val xsq = x - 1 + squareSize
val ysq = y - 1 + squareSize
powerLinesHori[x - 1][ysq] += area[xsq][ysq]
powerLinesVert[xsq][y - 1] += area[xsq][ysq]
val totalPower = grid[x - 1][y - 1] - area[xsq][ysq] +
powerLinesHori[x - 1][ysq] + powerLinesVert[xsq][y - 1]
grid[x - 1][y - 1] = totalPower
if (totalPower > bestSquare.totalPower && squareSizeIncluder.invoke(squareSize)) {
val square = Square(x + 1, y + 1, squareSize, totalPower)
bestSquare = square
}
}
}
}
return bestSquare
}
private fun createArea(gridSerialNumber: Int) =
matrix2d(gridHeight, gridWidth) { x, y -> FuelCell(x + 1, y + 1, gridSerialNumber).powerLevel }
internal class Square(val topLeftX: Int, val topLeftY: Int, val squareSize: Int, val totalPower: Int)
internal class FuelCell(x: Int, private val y: Int, private val gridSerialNumber: Int) {
private val rackId = x + 10
val powerLevel = calculatePowerLevel()
private fun calculatePowerLevel(): Int {
val res = (rackId * y + gridSerialNumber) * rackId
return ((res / 100) % 10) - 5
}
}
| 0 | Kotlin | 0 | 0 | 80db7e7029dace244a05f7e6327accb212d369cc | 3,195 | adventofcode2018 | MIT License |
src/main/kotlin/leetcode/kotlin/tree/270. Closest Binary Search Tree Value.kt | sandeep549 | 262,513,267 | false | {"Kotlin": 530613} | package leetcode.kotlin.tree
import java.util.*
import kotlin.math.abs
/**
* Traverse the tree in inorder, store result in array, then find closet value searching sorted array
*/
private fun closestValue(root: TreeNode?, target: Double): Int {
var list = mutableListOf<Int>()
fun dfs(root: TreeNode?) {
root?.let {
dfs(it.left)
list.add(it.`val`)
dfs(it.right)
}
}
dfs(root) // store in array
// find closest in sorted array
var diff = Double.MAX_VALUE
var ans = 0
list.forEach {
if (abs(it.toDouble() - target) < diff) {
diff = abs(it.toDouble() - target)
ans = it
}
}
return ans
}
/**
* Iterative; Traverse BST in inorder using iterative approach, keep track of min diff so far and element of it.
* Loop will terminate if we encountered just bigger element or tree is fully traversed.
* If we found just bigger element than target, that means we have calculated our closed element
* till now, break the loop.
*/
private fun closestValue2(root: TreeNode?, target: Double): Int {
var stack = ArrayDeque<TreeNode>()
var curr = root // to iterate
var diff = Double.MAX_VALUE // to track min diff
var ans = root?.`val` ?: 0 // to track element with min diff
stack.push(curr)
while (curr != null || !stack.isEmpty()) {
while (curr != null) {
stack.push(curr)
curr = curr.left
}
curr = stack.pop()
if (Math.abs(curr!!.`val` - target) < diff) {
ans = curr.`val`
diff = Math.abs(curr.`val` - target)
}
if (curr.`val` > target) break
curr = curr.right
}
return ans
}
/**
* Explanation for solution:
* To find closet value, we need max-lower-value and min-upper-value available in BST for the target.
* If we search BST for given target using binary search approach, at every node we cut down the input space
* by setting either a new lower/upper bound for target.
* If target is less than node, then we set new upper bound, otherwise new lower bound. This way we go till leaf
* node and both bound would have come max possible close to each other.
* As we are calculating closet every time, we will get closet of either of them at the end.
*/
private fun closestValue3(root: TreeNode?, target: Double): Int {
var root = root
var ret = root?.`val` ?: 0
while (root != null) {
if (Math.abs(target - root.`val`) < Math.abs(target - ret)) {
ret = root.`val`
}
root = if (root.`val` > target) root.left else root.right
}
return ret
}
| 1 | Kotlin | 0 | 0 | cf357cdaaab2609de64a0e8ee9d9b5168c69ac12 | 2,666 | leetcode-kotlin | Apache License 2.0 |
domain/src/main/java/com/example/domain/helper/RestaurantSortingHelper.kt | RomisaaAttiaa | 440,273,040 | false | {"Kotlin": 73572} | import com.example.domain.model.Restaurant
import com.example.domain.model.SortOptions
fun sortRestaurants(sortOptions: SortOptions, restaurants: List<Restaurant>): List<Restaurant> {
return sortBasedOnFavorite(
sortBasedOnOpeningStatus(
sortBasedOnSortingOptions(
sortOptions,
restaurants
)
)
)
}
fun sortBasedOnSortingOptions(
sortOptions: SortOptions,
restaurants: List<Restaurant>
): List<Restaurant> {
return when (sortOptions) {
SortOptions.BEST_MATCH, SortOptions.NEWEST, SortOptions.POPULARITY, SortOptions.RATING_AVERAGE -> sortRestaurantsByDescendingOrder(
restaurants,
sortOptions
)
SortOptions.DISTANCE, SortOptions.AVERAGE_PRODUCT_PRICE, SortOptions.DELIVERY_COSTS, SortOptions.MINIMUM_COST -> sortRestaurantsByAscendingOrder(
restaurants,
sortOptions
)
}
}
fun sortRestaurantsByAscendingOrder(
restaurants: List<Restaurant>,
sortOptions: SortOptions
) = restaurants.sortedBy {
val sortingValues = it.sortingValues
when (sortOptions) {
SortOptions.DISTANCE -> sortingValues.distance
SortOptions.AVERAGE_PRODUCT_PRICE -> sortingValues.averageProductPrice
SortOptions.DELIVERY_COSTS -> sortingValues.deliveryCosts
SortOptions.MINIMUM_COST -> sortingValues.minCost
else -> sortingValues.bestMatch
}
}
fun sortRestaurantsByDescendingOrder(
restaurants: List<Restaurant>,
sortOptions: SortOptions
) = restaurants.sortedByDescending {
val sortingValues = it.sortingValues
when (sortOptions) {
SortOptions.BEST_MATCH -> sortingValues.bestMatch
SortOptions.NEWEST -> sortingValues.newest
SortOptions.POPULARITY -> sortingValues.popularity
SortOptions.RATING_AVERAGE -> sortingValues.ratingAverage
else -> sortingValues.bestMatch
}
}
fun sortBasedOnOpeningStatus(
restaurants: List<Restaurant>
): List<Restaurant> {
return restaurants.filter {
it.status == Constants.OPEN_STATE
} + restaurants.filter {
it.status == Constants.ORDER_AHEAD_STATE
} + restaurants.filter {
it.status == Constants.CLOSED_STATE
}
}
fun sortBasedOnFavorite(
restaurants: List<Restaurant>
): List<Restaurant> {
return restaurants.sortedByDescending {
it.isFavorite
}
}
object Constants {
const val OPEN_STATE = "open"
const val ORDER_AHEAD_STATE = "order ahead"
const val CLOSED_STATE = "closed"
}
| 0 | Kotlin | 0 | 0 | d82d5cc6feafd1e832d959eee3d69b49d5bb3bc9 | 2,558 | RestaurantsSample | Apache License 2.0 |
src/Day10.kt | ambrosil | 572,667,754 | false | {"Kotlin": 70967} | fun main() {
data class Step(val cycle: Int, val sum: Int)
fun run(input: List<String>): MutableList<Step>{
var cycle = 1
var sum = 1
val steps = mutableListOf<Step>()
input.forEach {
when (it) {
"noop" -> steps.add(Step(cycle++, sum))
else -> {
val (_, amount) = it.split(" ")
steps += Step(cycle++, sum)
steps += Step(cycle++, sum)
sum += amount.toInt()
}
}
}
return steps
}
fun part1(input: List<String>): Int {
val cycles = List(6) { i -> 20 + i * 40 }
return run(input)
.filter { it.cycle in cycles }
.sumOf { it.cycle * it.sum }
}
fun part2(input: List<String>) {
run(input)
.map {
val sprite = it.sum - 1..it.sum + 1
if ((it.cycle - 1) % 40 in sprite) "🟨" else "⬛"
}
.chunked(40)
.forEach { println(it.joinToString("")) }
}
val input = readInput("inputs/Day10")
println(part1(input))
part2(input)
}
| 0 | Kotlin | 0 | 0 | ebaacfc65877bb5387ba6b43e748898c15b1b80a | 1,186 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/championofgoats/advent/2019/day10/day10.kt | ChampionOfGoats | 225,446,764 | false | null | package championofgoats.advent.twentynineteen.day10
import java.io.File
import kotlin.sequences.*
import championofgoats.advent.Problem
import championofgoats.advent.utils.Direction
import championofgoats.advent.utils.Point
import championofgoats.advent.utils.logging.Logger
object Day10 : Problem {
override fun solve(inputDir: String, outputDir: String, log: Logger) {
// Extract a list of all asteroid locations, then
val lines = File("$inputDir/day10.input").readText().lines()
/** Part 1 solution
* For each line s at y, and for each character c at x on that line, if c is # then store Point(x, y), else do nothing
* Map point p with the list of astroids (sans p) grouped by their direction from p
* Of those maps generated, take the largest
* Output is, ideally, Pair<Point, Map<Direction, List<Point>>>
*/
var candidates = lines.withIndex()
.flatMap {
(y, s) -> s.withIndex().mapNotNull {
(x, c) ->if (c == '#') Point(x, y) else null
}
}
val asteroid = candidates.map {
p -> candidates.filter {
q -> p != q
}
.groupBy {
k -> p.directionTo(k)
}
}
.sortedByDescending {
it.size
}
.first()
log.Solution("DAY10p1 ans = %d".format(asteroid.size))
/** part 2 solution
* Take the best map, A, and sort its keys by direction clockwise ascending
* Then, perform a round robin eliminaton:
* Reduce A down to a map M of iterators for each direction
* While M is not an empty map, take an iterator over M Ia.
* While Ia is not empty, take the next iterator Ib.
* If Ib is not empty, yield the next item, else remove it from Ia.
* The result is the sequence of asteroids in the order they would be destroyed by the laser.
*/
var destroyed = mutableListOf<Point>()
val iterA = asteroid.toSortedMap(Direction.comparator).values.map { it.iterator() }.toMutableList().iterator()
while (iterA.hasNext()) {
val iterB = iterA.next()
if (iterB.hasNext()) {
destroyed.add(iterB.next())
} else {
iterA.remove()
}
}
destroyed.get(199).apply {
log.Solution("DAY10p2 ans = %d".format(100 * x + y))
}
}
}
| 0 | Kotlin | 0 | 0 | 4f69de1579f40928c1278c3cea4e23e0c0e3b742 | 2,534 | advent-of-code | MIT License |
src/year2022/day09/Day09.kt | kingdongus | 573,014,376 | false | {"Kotlin": 100767} | package year2022.day09
import Point2D
import readInputFileByYearAndDay
import readTestFileByYearAndDay
fun main() {
infix fun Point2D.moveTowards(other: Point2D): Point2D {
if (this == other || this isAdjacentTo other) return this
// move by 1 in direction of dx and dy each
val newX = this.x + (if (other.x > this.x) 1 else if (other.x < this.x) -1 else 0)
val newY = this.y + (if (other.y > this.y) 1 else if (other.y < this.y) -1 else 0)
return Point2D(newX, newY)
}
fun calculateRopeMovements(headMovements: List<String>, ropeLength: Int = 2): MutableSet<Pair<Int, Int>> {
val rope = Array(ropeLength) { Point2D(0, 0) }
val track = mutableSetOf<Pair<Int, Int>>()
headMovements.map { it.split(" ") }
.map { it.first() to it.last().toInt() } // direction string and step count
.forEach {
val direction =
when (it.first) {
"U" -> Point2D(0, 1)
"D" -> Point2D(0, -1)
"L" -> Point2D(-1, 0)
"R" -> Point2D(1, 0)
else -> Point2D(0, 0)
}
repeat(it.second) {
rope[0] = rope[0].moveBy(direction)
rope.indices.drop(1).forEach { i ->
rope[i] = rope[i] moveTowards rope[i - 1]
}
track.add(rope.last().x to rope.last().y)
}
}
return track
}
fun part1(input: List<String>): Int = calculateRopeMovements(input).size
fun part2(input: List<String>): Int = calculateRopeMovements(input, ropeLength = 10).size
val testInput = readTestFileByYearAndDay(2022, 9)
check(part1(testInput) == 13)
check(part2(testInput) == 1)
val input = readInputFileByYearAndDay(2022, 9)
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | aa8da2591310beb4a0d2eef81ad2417ff0341384 | 1,974 | advent-of-code-kotlin | Apache License 2.0 |
src/main/kotlin/adventofcode2023/day13/day13.kt | dzkoirn | 725,682,258 | false | {"Kotlin": 133478} | package adventofcode2023.day13
import adventofcode2023.readInput
import java.lang.RuntimeException
import kotlin.math.min
import kotlin.time.measureTime
fun main() {
println("Day 13")
val input = readInput("day13")
val puzzle1Duration = measureTime {
println("Puzzle 1 ${puzzle1(input)}")
}
println("Puzzle 1 took $puzzle1Duration")
println("\n================================================================\n")
}
fun parseInput(input: List<String>): Collection<List<String>> {
return buildList {
var list = mutableListOf<String>()
input.forEach {
if (it.isEmpty()) {
add(list)
list = mutableListOf()
} else {
list.add(it)
}
}
add(list)
}
}
fun findReflection(input: List<String>): Int {
fun findIndex(input: List<String>): Int? {
val candidates = input.windowed(2).mapIndexedNotNull { index, (a, b) ->
println("findIndex: $index, $a, $b, ${a == b}")
if (a == b) {
if (index > 0) {
val range = min(index, (input.lastIndex - (index + 1)))
val isReflection = (0..range).all { i ->
println("all $range, $index, $i, ${input[index - i]}, ${input[index + 1 + i]}, ${input[index - i] == input[index + 1 + i]}")
input[index - i] == input[index + 1 + i]
}
println("isReflection = $isReflection, $index, $a, $b")
if (isReflection) {
return@mapIndexedNotNull index
}
} else {
return@mapIndexedNotNull index
}
}
null
}
return candidates.firstOrNull()
}
val row = findIndex(input)
return if (row != null) {
(row + 1) * 100
} else {
val column = findIndex(buildList {
input.first.indices.forEach { i ->
add(buildString {
input.forEach { l ->
try {
append(l[i])
} catch (ex: RuntimeException) {
println("$ex $l")
throw ex
}
}
})
}
})
if (column != null) {
column + 1
} else {
0
}
}
}
fun puzzle1(input: List<String>): Int = parseInput(input).sumOf { findReflection(it) } | 0 | Kotlin | 0 | 0 | 8f248fcdcd84176ab0875969822b3f2b02d8dea6 | 2,601 | adventofcode2023 | MIT License |
src/Day03.kt | ekgame | 573,100,811 | false | {"Kotlin": 20661} |
fun main() {
fun Char.priorityScore() = when (this) {
in 'a'..'z' -> this - 'a' + 1
in 'A'..'Z' -> this - 'A' + 27
else -> error("Invalid for priority")
}
fun part1(input: List<String>): Int = input
.map { it.chunked(it.length/2) }
.sumOf {
val set1 = it[0].toCharArray().toSet()
val set2 = it[1].toCharArray().toSet()
set1.intersect(set2).first().priorityScore()
}
fun part2(input: List<String>): Int = input
.chunked(3)
.sumOf {
val set1 = it[0].toCharArray().toSet()
val set2 = it[1].toCharArray().toSet()
val set3 = it[2].toCharArray().toSet()
set1.intersect(set2).intersect(set3).first().priorityScore()
}
val testInput = readInput("03.test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 2 | 0c2a68cedfa5a0579292248aba8c73ad779430cd | 984 | advent-of-code-2022 | Apache License 2.0 |
kotlin/main-native.kt | frol | 133,128,231 | false | null | import kotlin.io.*
import java.util.Random
val random = Random()
class Node(var x: Int)
{
var y = random.nextInt()
var left: Node? = null
var right: Node? = null
}
fun merge(lower: Node?, greater: Node?): Node?
{
if(lower == null)
return greater
if(greater == null)
return lower
if(lower.y < greater.y)
{
lower.right = merge(lower.right, greater)
return lower
}
else
{
greater.left = merge(lower, greater.left)
return greater
}
}
fun splitBinary(orig: Node?, value: Int): Pair<Node?, Node?>
{
if(orig == null)
return Pair(null, null)
if(orig.x < value)
{
val splitPair = splitBinary(orig.right, value)
orig.right = splitPair.first
return Pair(orig, splitPair.second)
}
else
{
val splitPair = splitBinary(orig.left, value)
orig.left = splitPair.second
return Pair(splitPair.first, orig)
}
}
fun merge(lower: Node?, equal: Node?, greater: Node?): Node?
{
return merge(merge(lower, equal), greater)
}
class SplitResult(val lower: Node?, var equal: Node?, var greater: Node?)
fun split(orig: Node?, value: Int): SplitResult
{
val (lower, equalGreater) = splitBinary(orig, value)
val (equal, greater) = splitBinary(equalGreater, value + 1)
return SplitResult(lower, equal, greater)
}
class Tree
{
public fun hasValue(x: Int): Boolean
{
val splited = split(mRoot, x)
val res = splited.equal != null
mRoot = merge(splited.lower, splited.equal, splited.greater)
return res
}
public fun insert(x: Int)
{
val splited = split(mRoot, x)
if(splited.equal == null)
splited.equal = Node(x)
mRoot = merge(splited.lower, splited.equal, splited.greater)
}
public fun erase(x: Int)
{
val splited = split(mRoot, x)
mRoot = merge(splited.lower, splited.greater)
}
private var mRoot: Node? = null
}
fun main(args: Array<String>)
{
val tree = Tree()
var cur = 5;
var res = 0
for(i in 1..1000000)
{
val a = i % 3
cur = (cur * 57 + 43) % 10007
when(a)
{
0 -> tree.insert(cur)
1 -> tree.erase(cur)
2 -> res += if(tree.hasValue(cur)) 1 else 0
}
}
println(res)
}
| 14 | C++ | 73 | 523 | baeadaac61807f0049ad35b9282b0c27eeb6d104 | 2,388 | completely-unscientific-benchmarks | Apache License 2.0 |
kotlin/combinatorics/CombinatorialEnumerations.kt | polydisc | 281,633,906 | true | {"Java": 540473, "Kotlin": 515759, "C++": 265630, "CMake": 571} | package combinatorics
import java.util.Arrays
object CombinatorialEnumerations {
fun main(args: Array<String?>?) {
val permutations = Permutations(3)
permutations.enumerate()
val combinations = Combinations(4, 3)
combinations.enumerate()
val arrangements = Arrangements(3, 2)
arrangements.enumerate()
val correctBracketSequences = CorrectBracketSequences(6)
correctBracketSequences.enumerate()
val partitions = Partitions(4)
partitions.enumerate()
}
// subclass and implement count() method
abstract class AbstractEnumeration protected constructor(// range of definition of sequence elements
protected val range: Int, // length of generated sequences
protected val length: Int
) {
// returns number of combinatorial sequences starting with prefix
// by contract only the last element of prefix can be invalid and in this case 0 must be returned
protected abstract fun count(prefix: IntArray?): Long
fun next(sequence: IntArray): IntArray {
return fromNumber(toNumber(sequence) + 1)
}
fun totalCount(): Long {
return count(IntArray(0))
}
fun toNumber(sequence: IntArray): Long {
var res: Long = 0
for (i in sequence.indices) {
val prefix: IntArray = Arrays.copyOf(sequence, i + 1)
prefix[i] = 0
while (prefix[i] < sequence[i]) {
res += count(prefix)
++prefix[i]
}
}
return res
}
fun fromNumber(number: Long): IntArray {
var number = number
val sequence = IntArray(length)
for (i in sequence.indices) {
val prefix: IntArray = Arrays.copyOf(sequence, i + 1)
prefix[i] = 0
while (prefix[i] < range) {
val cur = count(prefix)
if (number < cur) {
break
}
number -= cur
++prefix[i]
}
sequence[i] = prefix[i]
}
return sequence
}
fun enumerate() {
System.out.println(getClass().getName())
val total = totalCount()
for (i in 0 until total) {
val p = fromNumber(i)
System.out.println(i.toString() + " " + Arrays.toString(p))
val j = toNumber(p)
if (i != j) throw RuntimeException()
}
}
}
class Arrangements(n: Int, k: Int) : AbstractEnumeration(n, k) {
@Override
protected override fun count(prefix: IntArray): Long {
val size = prefix.size
// if the last element appears twice, then prefix is invalid and 0 must be returned
for (i in 0 until size - 1) if (prefix[size - 1] == prefix[i]) return 0
var res: Long = 1
for (i in 0 until length - size) res *= (range - size - i).toLong()
return res
}
}
class Permutations(n: Int) : Arrangements(n, n)
class Combinations(n: Int, k: Int) : AbstractEnumeration(n, k) {
val binomial: Array<LongArray>
@Override
protected override fun count(prefix: IntArray): Long {
val size = prefix.size
// if there is no combination with given prefix, 0 must be returned.
// by contract only the last element can make prefix invalid.
if (size >= 2 && prefix[size - 1] <= prefix[size - 2]) return 0
// prefix is valid. return the number of combinations starting with prefix
val last = if (size > 0) prefix[size - 1] else -1
return binomial[range - 1 - last][length - size]
}
init {
binomial = Array(n + 1) { LongArray(n + 1) }
// calculate binomial coefficients in advance
for (i in 0..n) for (j in 0..i) binomial[i][j] =
if (j == 0) 1 else binomial[i - 1][j - 1] + binomial[i - 1][j]
}
}
class CorrectBracketSequences(sequenceLength: Int) : AbstractEnumeration(2, sequenceLength) {
val d: Array<LongArray>
@Override
protected override fun count(prefix: IntArray): Long {
val size = prefix.size
var balance = 0
for (cur in prefix) // 0 designates '('
// 1 designates ')'
balance += if (cur == 0) 1 else -1
return if (balance < 0 || balance > length - size) 0 else d[length - size][balance]
}
// sequenceLength must be a multiple of 2
init {
d = Array(sequenceLength + 1) { LongArray(sequenceLength / 2 + 1) }
// d[i][j] - number of bracket sequences of length i with balance j
d[0][0] = 1
for (i in 1..sequenceLength) {
for (balance in 0..sequenceLength / 2) {
if (balance - 1 >= 0) d[i][balance] += d[i - 1][balance - 1]
if (balance + 1 <= sequenceLength / 2) d[i][balance] += d[i - 1][balance + 1]
}
}
}
}
class Partitions(value: Int) : AbstractEnumeration(value + 1, value) {
val pp: Array<LongArray>
@Override
protected override fun count(prefix: IntArray): Long {
val size = prefix.size
var sum = 0
for (e in prefix) sum += e
if (sum == range - 1) return 1
if (sum > range - 1 || size > 0 && prefix[size - 1] == 0 || size >= 2 && prefix[size - 1] > prefix[size - 2]) return 0
val last = if (size > 0) prefix[size - 1] else range - 1
return pp[range - 1 - sum][last]
}
init {
val p = Array(value + 1) { LongArray(value + 1) }
// p[i][j] - number of partitions of i with largest summand equal to j
p[0][0] = 1
for (i in 1..value) for (j in 1..i) p[i][j] = p[i - 1][j - 1] + p[i - j][j]
pp = Array(value + 1) { LongArray(value + 1) }
for (i in 1..value) for (j in 1..value) pp[i][j] = p[i][j] + pp[i][j - 1]
}
}
}
| 1 | Java | 0 | 0 | 4566f3145be72827d72cb93abca8bfd93f1c58df | 6,309 | codelibrary | The Unlicense |
src/main/kotlin/lib/matrix/MatrixHelpers.kt | ecxyzzy | 679,985,671 | false | null | package lib.matrix
fun isSymmetric(a: Matrix): Boolean {
return if (a.m != a.n) false else a == t(a)
}
fun isSkewSymmetric(a: Matrix): Boolean {
return if (a.m != a.n) false else a == -t(a)
}
fun t(a: Matrix): Matrix {
return Matrix(a.n, a.m, Array(a.n) { i -> Array(a.m) { j -> a[j + 1, i + 1] } })
}
fun tr(a: Matrix): Double {
if (a.m != a.n)
throw IllegalArgumentException("Cannot find trace of a non-square (${a.m} x ${a.n}) matrix")
return Array(a.m) { a[it + 1, it + 1] }.sum()
}
fun det(a: Matrix): Double {
if (a.m != a.n)
throw IllegalArgumentException(
"Cannot find determinant of a non-square (${a.m} x ${a.n}) matrix")
return when (a.m) {
1 -> a[1, 1]
2 -> (a[1, 1] * a[2, 2]) - (a[1, 2] * a[2, 1])
3 ->
(a[1, 1] * a[2, 2] * a[3, 3]) +
(a[1, 2] * a[2, 3] * a[3, 1]) +
(a[1, 3] * a[2, 1] * a[3, 2]) -
(a[1, 3] * a[2, 2] * a[3, 1]) -
(a[1, 2] * a[2, 1] * a[3, 3]) -
(a[1, 1] * a[2, 3] * a[3, 2])
else -> TODO("Cannot find determinant of a ${a.m} x ${a.n} matrix")
}
}
fun identityMatrix(n: Int): Matrix {
return Matrix(n, n, Array(n) { i -> Array(n) { j -> if (i == j) 1.0 else 0.0 } })
}
| 0 | Kotlin | 0 | 0 | 6b2d12797379b47e2a9b23ee234f5d00820398c3 | 1,230 | cs164-kt | MIT License |
src/main/kotlin/ca/kiaira/advent2023/day5/Day5.kt | kiairatech | 728,913,965 | false | {"Kotlin": 78110} | package ca.kiaira.advent2023.day5
import ca.kiaira.advent2023.Puzzle
/**
* Solves the Day 5 puzzle of Advent of Code.
*
* The puzzle involves processing a list of seed numbers through a series of mappings
* to transform each seed number and determine specific results based on these transformations.
*
* @constructor Creates an instance of Day5 puzzle solver which extends the Puzzle class.
*
* @author <NAME> <<EMAIL>>
* @since December 10th, 2023
*/
object Day5 : Puzzle<SeedMappingData>(5) {
/**
* Parses the input data for the puzzle.
*
* The input is expected to start with a line of seed numbers followed by several blocks
* of mapping data. Each block of mapping data consists of multiple lines that define
* a transformation mapping from a source range to a destination range.
*
* @param input A sequence of strings representing the lines of puzzle input.
* @return The parsed seed numbers and their corresponding mapping data as [SeedMappingData].
*/
override fun parse(input: Sequence<String>): SeedMappingData {
val lines = input.toList()
val seeds = lines.first().removePrefix("seeds: ").split(" ").map(String::toLong)
val mappings = lines.drop(2).joinToString("\n").split("\n\n").map { block ->
SeedMapping(block.split("\n").drop(1).map { line ->
line.split(" ").map(String::toLong).let { SeedMappingRange(it[0], it[1], it[2]) }
})
}
return SeedMappingData(seeds, mappings)
}
/**
* Solves Part 1 of the Day 5 puzzle.
*
* This method sequentially applies each mapping to the list of seed numbers
* and finds the minimum value among the final transformed seeds.
*
* @param input The parsed puzzle input data as [SeedMappingData].
* @return The smallest transformed seed number as a result of applying all mappings.
*/
override fun solvePart1(input: SeedMappingData): Any = input.mappings.fold(input.seeds) { acc, mapping ->
acc.map(mapping::mapSeed)
}.minOrNull() ?: -1L
/**
* Solves Part 2 of the Day 5 puzzle.
*
* This method involves more complex logic dealing with ranges of seed numbers. It reverses
* the order of the conversion maps and finds the first number that, after applying all
* reversed mappings, falls within any specified seed range.
*
* @param input The parsed puzzle input data as [SeedMappingData].
* @return The first number that meets the criteria defined for Part 2 of the puzzle.
*/
override fun solvePart2(input: SeedMappingData): Any {
val seedRanges = input.seeds.windowed(2, 2, false).map { it[0] until it[0] + it[1] }
val reversedMapping = input.mappings.asReversed().map(SeedMapping::reversed)
return generateSequence(0L) { it + 1 }.first { location ->
val finalSeed = reversedMapping.fold(location) { acc, map ->
map.mapSeed(acc)
}
seedRanges.any { finalSeed in it }
}
}
}
| 0 | Kotlin | 0 | 1 | 27ec8fe5ddef65934ae5577bbc86353d3a52bf89 | 2,859 | kAdvent-2023 | Apache License 2.0 |
2023/src/day07/Day07.kt | scrubskip | 160,313,272 | false | {"Kotlin": 198319, "Python": 114888, "Dart": 86314} | package day07
import java.io.File
fun main() {
val input = File("src/day07/day07.txt").readLines()
println(getWinnings(input, true))
}
fun getWinnings(input: List<String>, useJoker: Boolean = false): Int {
val handBids = input.map { handBid ->
val parts = handBid.split(" ")
Pair(Hand(parts[0], useJoker), parts[1].toInt())
}
return handBids.sortedBy { it.first }.mapIndexed { index, pair ->
(index + 1) * pair.second
}.sum()
}
enum class HandType {
HIGH_CARD,
ONE_PAIR,
TWO_PAIR,
THREE_OF_A_KIND,
FULL_HOUSE,
FOUR_OF_A_KIND,
FIVE_OF_A_KIND,
}
enum class CardValue(val stringValue: Char) {
JOKER('J'),
ONE('1'),
TWO('2'),
THREE('3'),
FOUR('4'),
FIVE('5'),
SIX('6'),
SEVEN('7'),
EIGHT('8'),
NINE('9'),
TEN('T'),
// JACK('J'),
QUEEN('Q'),
KING('K'),
ACE('A');
companion object {
fun getFromChar(char: Char): CardValue {
return CardValue.values().first { it.stringValue == char }
}
fun compareLists(thisList: List<CardValue>, otherList: List<CardValue>): Int {
if (thisList.size == otherList.size) {
// Loop through until item doesn't match
thisList.zip(otherList).forEach {
if (it.first != it.second) {
return it.first.compareTo(it.second)
}
}
return 0
} else {
throw IllegalArgumentException("Lists are not the same size")
}
}
}
}
class Hand(val input: String, val useJoker: Boolean = false) : Comparable<Hand> {
private val handCharMap: Map<Char, Int> = input.groupingBy { it }.eachCount()
val handType: HandType = getHandType(handCharMap)
private fun getHandType(inputCharMap: Map<Char, Int>): HandType {
var charMap = inputCharMap.toMutableMap()
var jokerCount: Int = 0
if (useJoker) {
// Adjust the charMap: remove the Js
jokerCount = charMap.getOrDefault('J', 0)
if (jokerCount == 5) {
// Special case: if we have all J, then this was five of a kind
return HandType.FIVE_OF_A_KIND
}
charMap.remove('J')
}
return if (charMap.values.any { it == 5 - jokerCount }) {
HandType.FIVE_OF_A_KIND
} else if (charMap.values.any { it == 4 - jokerCount }) {
HandType.FOUR_OF_A_KIND
} else if (charMap.values.any { it == 3 - jokerCount }) {
if (useJoker && jokerCount == 1) {
// If we got to here and the jokerCount is 1, then only is a full house IF it's two pair
if (charMap.values.filter { it == 2 }.size == 2) {
return HandType.FULL_HOUSE
} else {
return HandType.THREE_OF_A_KIND
}
} else {
if (charMap.values.any { it == 2 }) {
HandType.FULL_HOUSE
} else {
HandType.THREE_OF_A_KIND
}
}
} else if (charMap.values.filter { it == 2 }.size == 2) {
HandType.TWO_PAIR
} else if (charMap.values.filter { it == 2 }.size == 1) {
if (jokerCount >= 1) {
// If the jokerCount is even greater, would have fallen out earlier.
HandType.TWO_PAIR
} else {
HandType.ONE_PAIR
}
} else {
if (jokerCount >= 1) {
HandType.ONE_PAIR
} else {
HandType.HIGH_CARD
}
}
}
override fun compareTo(other: Hand): Int {
if (handType == other.handType) {
return CardValue.compareLists(input.map { CardValue.getFromChar(it) },
other.input.map { CardValue.getFromChar(it) })
} else {
return handType.compareTo(other.handType)
}
}
} | 0 | Kotlin | 0 | 0 | a5b7f69b43ad02b9356d19c15ce478866e6c38a1 | 4,054 | adventofcode | Apache License 2.0 |
src/nativeMain/kotlin/com.qiaoyuang.algorithm/round1/Questions34.kt | qiaoyuang | 100,944,213 | false | {"Kotlin": 338134} | package com.qiaoyuang.algorithm.round1
import com.qiaoyuang.algorithm.round0.BinaryTreeNode
import com.qiaoyuang.algorithm.round0.Stack
import com.qiaoyuang.algorithm.round0.toIntArray
fun test34() {
val (root, target) = testCase()
printlnResults(root, target)
printlnResults(root, 21)
printlnResults(root, 19)
}
/**
* Find all the paths that sum equals a number in a binary tree
*/
private infix fun BinaryTreeNode<Int>.findAllPathsInBinaryTree(target: Int): List<IntArray> = buildList {
findAllPathsInBinaryTree(target, 0, Stack(), this)
}
private fun BinaryTreeNode<Int>.findAllPathsInBinaryTree(target: Int, current: Int, stack: Stack<Int>, results: MutableList<IntArray>) {
stack.push(value)
val sum = value + current
when {
sum == target -> results.add(stack.toIntArray())
sum < target -> {
left?.findAllPathsInBinaryTree(target, sum, stack, results)
right?.findAllPathsInBinaryTree(target, sum, stack, results)
}
}
stack.pop()
}
private fun printlnResults(root: BinaryTreeNode<Int>, target: Int) {
println("The paths that sum equals $target are: ")
val results = root findAllPathsInBinaryTree target
if (results.isEmpty())
println("No path;")
else results.forEach {
println(it.toList())
}
}
private fun testCase(): Pair<BinaryTreeNode<Int>, Int> = BinaryTreeNode(10,
left = BinaryTreeNode(5,
left = BinaryTreeNode(4),
right = BinaryTreeNode(7)
),
right = BinaryTreeNode(12),
) to 22
| 0 | Kotlin | 3 | 6 | 66d94b4a8fa307020d515d4d5d54a77c0bab6c4f | 1,550 | Algorithm | Apache License 2.0 |
src/day7/d7_2.kt | svorcmar | 720,683,913 | false | {"Kotlin": 49110} | fun main() {
val input = ""
val byTarget = input.lines().map { parseConnection(it) }.associate { it.target to it }
// take the signal you got on wire a
val origA = eval("a", byTarget, mutableMapOf<String, UShort>())
// override wire b to that signal
val rewired = byTarget + ("b" to Connection(Gate.WIRE, origA.toString(), "", "b"))
// reset the other wires
println(eval("a", rewired, mutableMapOf<String, UShort>()))
}
enum class Gate { WIRE, NOT, AND, OR, LSHIFT, RSHIFT }
data class Connection(val gate: Gate, val leftOp: String, val rightOp: String, val target: String)
fun parseConnection(input: String): Connection {
val lr = input.split(" -> ")
val target = lr[1]
val l = lr[0].split(" ")
return when (l.size) {
1 -> Connection(Gate.WIRE, l[0], "", target)
2 -> Connection(Gate.NOT, l[1], "", target)
else -> Connection(Gate.valueOf(l[1]), l[0], l[2], target)
}
}
fun eval(wire: String, connections: Map<String, Connection>, cache: MutableMap<String, UShort>): UShort {
if (!cache.containsKey(wire))
cache[wire] = evalConnection(connections[wire]!!, connections, cache)
return cache[wire]!!
}
fun evalConnection(connection: Connection, connections: Map<String, Connection>, cache: MutableMap<String, UShort>): UShort {
return when(connection.gate) {
Gate.WIRE -> evalOperand(connection.leftOp, connections, cache)
Gate.NOT -> evalOperand(connection.leftOp, connections, cache).inv()
Gate.AND -> evalOperand(connection.leftOp, connections, cache) and evalOperand(connection.rightOp, connections, cache)
Gate.OR -> evalOperand(connection.leftOp, connections, cache) or evalOperand(connection.rightOp, connections, cache)
Gate.LSHIFT -> (evalOperand(connection.leftOp, connections, cache).toInt() shl evalOperand(connection.rightOp, connections, cache).toInt()).toUShort()
Gate.RSHIFT -> (evalOperand(connection.leftOp, connections, cache).toInt() shr evalOperand(connection.rightOp, connections, cache).toInt()).toUShort()
}
}
fun evalOperand(operand: String, connections: Map<String, Connection>, cache: MutableMap<String, UShort>): UShort {
if (operand.matches("[0-9]+".toRegex()))
return operand.toUShort()
return eval(operand, connections, cache)
}
| 0 | Kotlin | 0 | 0 | cb097b59295b2ec76cc0845ee6674f1683c3c91f | 2,263 | aoc2015 | MIT License |
2021/src/day16/Day16.kt | Bridouille | 433,940,923 | false | {"Kotlin": 171124, "Go": 37047} | package day16
import readInput
import java.lang.IllegalStateException
data class ParsingResult(val packet: Packet, val restOfString: String)
sealed class Packet {
data class LiteralValue(val v: Int, val number: Long) : Packet() {
override fun getVersionSum() = v
override fun getTotal() = number
}
data class Operator(val v: Int, val typeId: Int, val subPackets: List<Packet>) : Packet() {
override fun getVersionSum() = v + subPackets.map { it.getVersionSum() }.sum()
override fun getTotal() = when (typeId) {
0 -> subPackets.sumOf { it.getTotal() }
1 -> subPackets.fold(1L) { acc, p -> acc * p.getTotal() }
2 -> subPackets.minOfOrNull { it.getTotal() }!!
3 -> subPackets.maxOfOrNull { it.getTotal() }!!
5 -> if (subPackets[0].getTotal() > subPackets[1].getTotal()) 1L else 0L
6 -> if (subPackets[0].getTotal() < subPackets[1].getTotal()) 1L else 0L
7 -> if (subPackets[0].getTotal() == subPackets[1].getTotal()) 1L else 0L
else -> throw IllegalStateException("Unknown typeId($typeId)")
}
}
abstract fun getVersionSum() : Int
abstract fun getTotal() : Long
}
const val LITERAL_VALUE_ID = 4
fun String.hexToBinary(): String {
val sb = StringBuilder()
for (c in this) {
val digit = String.format("%4s", Integer.toBinaryString(c.digitToInt(16))).replace(" ", "0")
sb.append(digit)
}
return sb.toString()
}
fun parseLiteralValue(version: Int, binary: String) : ParsingResult {
val binaryNb = StringBuilder()
var lastIdx = 0
for (idx in binary.indices step 5) {
binaryNb.append(binary.drop(idx + 1).take(4))
if (binary[idx] != '1') {
lastIdx = idx
break
}
}
return ParsingResult(Packet.LiteralValue(version, binaryNb.toString().toLong(2)), binary.drop(lastIdx + 5))
}
fun parseOperatorPacket(version: Int, typeId: Int, binary: String) : ParsingResult {
val subPackets = mutableListOf<Packet>()
var rest = ""
when (binary.first()) {
'1' -> {
val numberOfSubPackets = binary.drop(1).take(11).toInt(2)
var result = parsePacket(binary.drop(1 + 11))
subPackets.add(result.packet)
for (i in 1 until numberOfSubPackets) {
result = parsePacket(result.restOfString)
subPackets.add(result.packet)
}
rest = result.restOfString
}
'0' -> {
val totalLength = binary.drop(1).take(15).toInt(2)
var result = parsePacket(binary.drop(1 + 15).take(totalLength))
subPackets.add(result.packet)
while (result.restOfString.isNotEmpty()) {
result = parsePacket(result.restOfString)
subPackets.add(result.packet)
}
rest = binary.drop(1 + 15 + totalLength)
}
}
return ParsingResult(Packet.Operator(version, typeId, subPackets), rest)
}
fun parsePacket(binary: String) : ParsingResult {
val version = binary.take(3)
val typeID = binary.drop(3).take(3)
return when (val typeIDInt = typeID.toInt(2)) {
LITERAL_VALUE_ID -> parseLiteralValue(version.toInt(2), binary.drop(6))
else -> parseOperatorPacket(version.toInt(2), typeIDInt, binary.drop(6))
}
}
fun part1(lines: List<String>): Int {
val binary = lines.first().hexToBinary()
println(binary)
return parsePacket(binary).packet.let {
it.also { println(it) }
}.getVersionSum()
}
fun part2(lines: List<String>) = parsePacket(lines.first().hexToBinary()).packet.getTotal()
fun main() {
val testInput = readInput("day16/test")
println("part1(testInput) => " + part1(testInput))
println("part2(testInput) => " + part2(testInput))
val input = readInput("day16/input")
println("part1(input) => " + part1(input))
println("part2(input) => " + part2(input))
}
| 0 | Kotlin | 0 | 2 | 8ccdcce24cecca6e1d90c500423607d411c9fee2 | 3,987 | advent-of-code | Apache License 2.0 |
src/main/kotlin/ru/timakden/aoc/year2015/Day18.kt | timakden | 76,895,831 | false | {"Kotlin": 321649} | package ru.timakden.aoc.year2015
import arrow.core.Either
import arrow.core.getOrElse
import ru.timakden.aoc.util.measure
import ru.timakden.aoc.util.readInput
/**
* [Day 18: Like a GIF For Your Yard](https://adventofcode.com/2015/day/18).
*/
object Day18 {
@JvmStatic
fun main(args: Array<String>) {
measure {
val input = readInput("year2015/Day18")
println("Part One: ${solve(input, 100)}")
println("Part Two: ${solve(input, 100, true)}")
}
}
fun solve(input: List<String>, numberOfSteps: Int, isPartTwo: Boolean = false): Int {
var matrix = input.map { it.toCharArray() }.toTypedArray()
repeat(numberOfSteps) { matrix = performStep(matrix, isPartTwo) }
return matrix.sumOf { it.count { ch -> ch == '#' } }
}
private fun performStep(matrix: Array<CharArray>, isPartTwo: Boolean): Array<CharArray> {
val size = matrix.size
val newMatrix = Array(size) { CharArray(size) }
matrix.forEachIndexed { i, chars ->
chars.forEachIndexed { j, c ->
val neighbours = mutableListOf<Char>()
for (k in (i - 1)..(i + 1)) {
for (l in (j - 1)..(j + 1)) {
if (k == i && l == j) continue // skip the current "cell"
neighbours += Either.catch { matrix[k][l] }.getOrElse { '.' }
}
}
val count = neighbours.count { it == '#' }
newMatrix[i][j] = when (c) {
'#' -> if (count in 2..3) '#' else '.'
else -> if (count == 3) '#' else '.'
}
if (isPartTwo && (i == 0 || i == matrix.lastIndex) && (j == 0 || j == chars.lastIndex))
newMatrix[i][j] = '#'
}
}
return newMatrix
}
}
| 0 | Kotlin | 0 | 3 | acc4dceb69350c04f6ae42fc50315745f728cce1 | 1,889 | advent-of-code | MIT License |
src/Day03.kt | Ramo-11 | 573,610,722 | false | {"Kotlin": 21264} | fun main() {
fun mainLogicPart1(first: String, second: String): Int {
val matchingLetters: MutableList<Char> = ArrayList()
for (letter in first) {
if (letter in second && letter !in matchingLetters) {
matchingLetters.add(letter)
if (letter.isUpperCase()) {
return letter.lowercaseChar().code - 70
}
return letter.code - 96
}
}
return 0
}
fun part1(input: List<String>): Int {
var middle = 0
var firstString = ""
var secondString = ""
var value = 0
for (i in input.indices) {
middle = input[i].length / 2
firstString = input[i].substring(0, middle)
secondString = input[i].substring(middle)
value += mainLogicPart1(firstString, secondString)
}
return value
}
fun mainLogicPart2(input: List<String>): Int {
for (letter in input[0]) {
if (letter in input[1] && letter in input[2]) {
if (letter.isUpperCase()) {
return letter.lowercaseChar().code - 70
}
return letter.code - 96
}
}
return 0
}
fun part2(input: List<String>): Int {
var value = 0
var allInput = ""
var chunkedList: List<List<String>>?
for (i in 0..input.size) {
if (i >= 3 && i % 3 == 0) {
allInput = allInput.dropLast(1)
chunkedList = allInput.split(" ").chunked(3)
value += mainLogicPart2(chunkedList[0])
allInput = ""
}
if (i == input.size) {
break
}
allInput += input[i]
allInput += " "
}
return value
}
val input = readInput("Day03")
val part1Answer = part1(input)
val part2Answer = part2(input)
println("Answer for part 1: $part1Answer")
println("Answer for part 2: $part2Answer")
}
| 0 | Kotlin | 0 | 0 | a122cca3423c9849ceea5a4b69b4d96fdeeadd01 | 2,071 | advent-of-code-kotlin | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/ShortestBridge.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import java.util.LinkedList
import java.util.Queue
/**
* 934. Shortest Bridge
* @see <a href="https://leetcode.com/problems/shortest-bridge/">Source</a>
*/
fun interface ShortestBridge {
operator fun invoke(grid: Array<IntArray>): Int
}
class ShortestBridgeDP : ShortestBridge {
override operator fun invoke(grid: Array<IntArray>): Int {
val queue: Queue<IntArray> = LinkedList()
var flag = false
for (i in grid.indices) {
for (j in grid[0].indices) {
if (grid[i][j] == 1) {
dfs(i, j, queue, grid)
flag = true
break
}
}
if (flag) break
}
return bfs(grid, queue)
}
private fun bfs(
grid: Array<IntArray>,
queue: Queue<IntArray>,
): Int {
var step = 0
val dirs = arrayOf(intArrayOf(-1, 0), intArrayOf(1, 0), intArrayOf(0, -1), intArrayOf(0, 1))
while (queue.isNotEmpty()) {
val size: Int = queue.size
for (i in 0 until size) {
val point: IntArray = queue.poll()
for (dir in dirs) {
val x = dir[0] + point[0]
val y = dir[1] + point[1]
if (x >= 0 && y >= 0 && x < grid.size && y < grid[0].size && grid[x][y] != -1) {
if (grid[x][y] == 1) return step
queue.offer(intArrayOf(x, y))
grid[x][y] = -1
}
}
}
step++
}
return -1
}
private fun dfs(x: Int, y: Int, queue: Queue<IntArray>, arr: Array<IntArray>) {
if (x < 0 || y < 0 || x == arr.size || y == arr[0].size || arr[x][y] != 1) {
return
}
queue.offer(intArrayOf(x, y))
arr[x][y] = -1
dfs(x + 1, y, queue, arr)
dfs(x - 1, y, queue, arr)
dfs(x, y + 1, queue, arr)
dfs(x, y - 1, queue, arr)
}
}
class ShortestBridgeDFS : ShortestBridge {
override operator fun invoke(grid: Array<IntArray>): Int {
return shortestBridge(grid)
}
private fun shortestBridge(grid: Array<IntArray>): Int {
val m = grid.size
val n = grid[0].size
val visited = Array(m) { BooleanArray(n) }
val dirs = arrayOf(intArrayOf(1, 0), intArrayOf(-1, 0), intArrayOf(0, 1), intArrayOf(0, -1))
val q: Queue<IntArray> = LinkedList()
var found = false
// 1. dfs to find an island, mark it in `visited`
for (i in 0 until m) {
if (found) {
break
}
for (j in 0 until n) {
if (grid[i][j] == 1) {
dfs(grid, visited, q, i, j, dirs)
found = true
break
}
}
}
// 2. bfs to expand this island
return bfs(grid, visited, q, n, m, dirs)
}
private fun bfs(
grid: Array<IntArray>,
visited: Array<BooleanArray>,
q: Queue<IntArray>,
n: Int,
m: Int,
dirs: Array<IntArray>,
): Int {
var step = 0
while (q.isNotEmpty()) {
var size = q.size
while (size-- > 0) {
val cur = q.poll()
for (dir in dirs) {
val i = cur[0] + dir[0]
val j = cur[1] + dir[1]
if (i >= 0 && j >= 0 && i < m && j < n && !visited[i][j]) {
if (grid[i][j] == 1) {
return step
}
q.offer(intArrayOf(i, j))
visited[i][j] = true
}
}
}
step++
}
return -1
}
private fun dfs(
grid: Array<IntArray>,
visited: Array<BooleanArray>,
q: Queue<IntArray>,
i: Int,
j: Int,
dirs: Array<IntArray>,
) {
val left = i < 0 || j < 0 || i >= grid.size || j >= grid[0].size
if (left || visited[i][j] || grid[i][j] == 0) {
return
}
visited[i][j] = true
q.offer(intArrayOf(i, j))
for (dir in dirs) {
dfs(grid, visited, q, i + dir[0], j + dir[1], dirs)
}
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 5,019 | kotlab | Apache License 2.0 |
src/Day03.kt | korsik | 573,366,257 | false | {"Kotlin": 5186} | import kotlin.properties.Delegates
fun main() {
fun part1(input: List<String>): Int {
fun Char.toScore(): Int {
return if(this.isLowerCase()) {
this.code - 'a'.code + 1
} else {
this.code - 'A'.code + 27
}
}
return input.sumOf {
val compartments = listOf(
it.substring(0, it.length / 2).toCharArray().sorted(),
it.substring(it.length / 2, it.length).toCharArray().sorted())
var repeated by Delegates.notNull<Char>()
for (i in 0 until compartments[0].size) {
if (compartments[1].contains(compartments[0][i])) {
repeated = compartments[0][i]
break
}
}
repeated.toScore()
}
}
fun part2(input: List<String>): Int {
fun Char.toScore(): Int {
return if(this.isLowerCase()) {
this.code - 'a'.code + 1
} else {
this.code - 'A'.code + 27
}
}
return input.chunked(3) {
it[0].toSet()
.intersect(it[1].toSet())
.intersect(it[2].toSet())
.first().toScore()
}.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_default")
println(part2(testInput))
// check(part1(testInput) == 1)
val input = readInput("Day03_test")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 1a576c51fc8233b1a2d64e44e9301c7f4f2b6b01 | 1,600 | aoc-2022-in-kotlin | Apache License 2.0 |
src/Day02.kt | Feketerig | 571,677,145 | false | {"Kotlin": 14818} | enum class Type(val score: Int){
ROCK(1), PAPER(2), SCISSORS(3)
}
fun main() {
fun fight(first: Type, second: Type): Int{
if (first == second){
return 3 + second.score
}
return when(second){
Type.ROCK -> {
if (first == Type.PAPER){
0 + second.score
}else{
6 + second.score
}
}
Type.PAPER -> {
if (first == Type.SCISSORS){
0 + second.score
}else{
6 + second.score
}
}
Type.SCISSORS -> {
if (first == Type.ROCK){
0 + second.score
}else{
6 + second.score
}
}
}
}
fun parseInput(input: List<String>): List<Pair<Type, Type>>{
return input.map { line ->
val first = when(line.first()){
'A' -> Type.ROCK
'B' -> Type.PAPER
'C' -> Type.SCISSORS
else -> Type.ROCK
}
val last = when(line.last()){
'X' -> Type.ROCK
'Y' -> Type.PAPER
'Z' -> Type.SCISSORS
else -> Type.ROCK
}
Pair(first, last)
}
}
fun part1(input: List<String>): Int {
val parsed = parseInput(input)
var sum = 0
parsed.forEach {
sum += fight(it.first, it.second)
}
return sum
}
fun part2(input: List<String>): Int {
val parsed = parseInput(input)
var sum = 0
parsed.forEach {
sum += when(it.second){
Type.ROCK -> {
when (it.first) {
Type.ROCK -> {
Type.SCISSORS.score
}
Type.PAPER -> {
Type.ROCK.score
}
Type.SCISSORS -> {
Type.PAPER.score
}
}
}
Type.PAPER -> {
3 + it.first.score
}
Type.SCISSORS -> {
when (it.first) {
Type.ROCK -> {
6 + Type.PAPER.score
}
Type.PAPER -> {
6 + Type.SCISSORS.score
}
Type.SCISSORS -> {
6 + Type.ROCK.score
}
}
}
}
}
return sum
}
val testInput = readInput("Day02_test_input")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02_input")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | c65e4022120610d930293788d9584d20b81bc4d7 | 3,027 | Advent-of-Code-2022 | Apache License 2.0 |
aoc16/day_07/main.kt | viktormalik | 436,281,279 | false | {"Rust": 227300, "Go": 86273, "OCaml": 82410, "Kotlin": 78968, "Makefile": 13967, "Roff": 9981, "Shell": 2796} | import java.io.File
data class IPv7(val supernet: List<String>, val hypernet: List<String>)
fun parse_ip(line: String): IPv7 {
val split = line.split("[\\[\\]]".toRegex())
return IPv7(
split.filterIndexed { i, _ -> (i % 2) == 0 },
split.filterIndexed { i, _ -> (i % 2) == 1 },
)
}
fun has_abba(s: String): Boolean {
return s
.indices
.any { i -> i >= 3 && s[i] == s[i - 3] && s[i - 1] == s[i - 2] && s[i] != s[i - 1] }
}
fun has_tls(ip: IPv7): Boolean =
ip.supernet.any { has_abba(it) } && ip.hypernet.none { has_abba(it) }
fun has_ssl(ip: IPv7): Boolean =
ip.supernet.any { seq ->
seq.withIndex().any { (i, c) ->
i > 0 && i < seq.length - 1 && seq[i - 1] == seq[i + 1] && c != seq[i - 1] &&
ip.hypernet.any { it.contains(charArrayOf(c, seq[i + 1], c).joinToString("")) }
}
}
fun main() {
val ips = File("input").readLines().map { parse_ip(it) }
val first = ips.filter { has_tls(it) }.count()
println("First: $first")
val second = ips.filter { has_ssl(it) }.count()
println("Second: $second")
}
| 0 | Rust | 1 | 0 | f47ef85393d395710ce113708117fd33082bab30 | 1,127 | advent-of-code | MIT License |
src/main/kotlin/com/github/h0tk3y/probabilistik/distribution/Multinomial.kt | h0tk3y | 124,875,312 | false | null | package com.github.h0tk3y.probabilistik.distribution
import com.github.h0tk3y.probabilistik.normalize
class Multinomial<T>(val probabilities: Map<T, Double>) : FiniteDistribution<T> {
init {
require(probabilities.isNotEmpty()) { "At least one value is required." }
require(probabilities.values.all { it >= 0.0 }) { "All probabilities should be non-negative." }
}
private val normalizedProbabilities = probabilities.normalize()
private val scores = probabilities.normalize().mapValues { Math.log(it.value) }
private val valuesList = probabilities.keys.toList()
private val accumulatedP = run {
var p = 0.0
normalizedProbabilities.values.map { p += it; p }
}
override fun takeSample(): T {
val d = random.nextDouble()
val index = accumulatedP.binarySearch(d)
.let { if (it > 0) it else -it - 1 }
.coerceAtMost(accumulatedP.lastIndex)
return valuesList[index]
}
constructor(keys: List<T>, probabilityFunction: (T) -> Double) :
this(keys.associate { it to probabilityFunction(it) }.normalize())
override fun logLikelihood(value: T): Double = scores[value] ?: 0.0
override val support: Iterable<T>
get() = normalizedProbabilities.keys
}
fun randomInteger(range: IntRange) =
Multinomial(range.associate { it to 1.0 / (range.endInclusive - range.start + 1) })
| 1 | Kotlin | 3 | 20 | d5abd5c58b223957afcc91e7c71093e966757643 | 1,411 | probabilistik | Apache License 2.0 |
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2023/2023-21.kt | ferinagy | 432,170,488 | false | {"Kotlin": 787586} | package com.github.ferinagy.adventOfCode.aoc2023
import com.github.ferinagy.adventOfCode.CharGrid
import com.github.ferinagy.adventOfCode.Coord2D
import com.github.ferinagy.adventOfCode.IntGrid
import com.github.ferinagy.adventOfCode.contains
import com.github.ferinagy.adventOfCode.println
import com.github.ferinagy.adventOfCode.readInputLines
import com.github.ferinagy.adventOfCode.set
import com.github.ferinagy.adventOfCode.toCharGrid
import java.util.LinkedList
fun main() {
val input = readInputLines(2023, "21-input")
val test1 = readInputLines(2023, "21-test1")
println("Part1:")
part1(test1, 6).println()
part1(input, 64).println()
println()
println("Part2:")
bruteForce(test1.toCharGrid(), 6).println()
bruteForce(test1.toCharGrid(), 10).println()
part2(input, 26501365).println()
}
private fun part1(input: List<String>, maxSteps: Int): Int {
val grid = input.toCharGrid()
val start = grid.yRange.map { y ->
val x = grid.xRange.singleOrNull { x -> grid[x, y] == 'S' }
x to y
}.single { it.first != null }.let { Coord2D(it.first!!, it.second) }
return createStepGrid(grid, start).count { it != -2 && it <= maxSteps && it % 2 == maxSteps % 2 }
}
private fun part2(input: List<String>, maxSteps: Int): Long {
val grid = input.toCharGrid()
val start = grid.yRange.map { y ->
val x = grid.xRange.singleOrNull { x -> grid[x, y] == 'S' }
x to y
}.single { it.first != null }.let { Coord2D(it.first!!, it.second) }
require(grid.width == grid.height) { "grid must be square" }
val radius = grid.width / 2
require(maxSteps % grid.width == radius) { "steps must end at edge" }
val stepGrid = createStepGrid(grid, start)
val even = stepGrid.count { 0 <= it && it % 2 == 0 }
val odd = stepGrid.count { 0 <= it && it % 2 == 1 }
val evenCorners = stepGrid.count { radius < it && it % 2 == 0 }
val oddCorners = stepGrid.count { radius < it && it % 2 == 1 }
val evenRoot = maxSteps.toLong() / grid.width
val oddRoot = evenRoot + 1
return (oddRoot * oddRoot) * odd - oddRoot * oddCorners + evenRoot * evenRoot * even + evenRoot * evenCorners
}
private fun createStepGrid(grid: CharGrid, start: Coord2D): IntGrid {
val stepGrid = IntGrid(grid.width, grid.height) { x, y -> -1 }
for (x in grid.xRange) {
for (y in grid.yRange) {
if (grid[x, y] == '#') stepGrid[x, y] = -2
}
}
val visited = mutableSetOf<Coord2D>()
val queue = LinkedList<Pair<Coord2D, Int>>()
queue += start to 0
while (queue.isNotEmpty()) {
val (pos, steps) = queue.removeFirst()
if (pos in visited) continue
visited += pos
if (pos !in grid) continue
stepGrid[pos] = steps
pos.adjacent(false).filter { (totalX, totalY) ->
val x = totalX.mod(grid.width)
val y = totalY.mod(grid.height)
grid[x, y] != '#'
}.forEach {
queue += it to steps + 1
}
}
return stepGrid
}
private fun bruteForce(grid: CharGrid, maxSteps: Int): Int {
val visited = mutableSetOf<Coord2D>()
val queue = LinkedList<Pair<Coord2D, Int>>()
val start = Coord2D(grid.width / 2, grid.height / 2)
queue += start to 0
var result = 0
while (queue.isNotEmpty()) {
val (pos, steps) = queue.removeFirst()
if (pos in visited) continue
visited += pos
if (maxSteps % 2 == steps % 2) result++
if (steps == maxSteps) continue
pos.adjacent(false).filter { (totalX, totalY) ->
val x = totalX.mod(grid.width)
val y = totalY.mod(grid.height)
grid[x, y] != '#'
}.forEach {
queue += it to steps + 1
}
}
return result
}
| 0 | Kotlin | 0 | 1 | f4890c25841c78784b308db0c814d88cf2de384b | 3,816 | advent-of-code | MIT License |
src/main/java/com/liueq/leetcode/easy/NextGreaterElementI.kt | liueq | 129,225,615 | false | {"Java": 240910, "Kotlin": 5671} | package com.liueq.leetcode.easy
import java.util.*
/**
* 问题描述:给定两个数组 nums1, nums2。其中 1 是 2的子集。求nums1 每一个element 在 nums2 中的位置,往后最大的数字。如果不存在,用 -1 代替。
* 比如: [4, 1, 2]
* [1, 3, 4, 2]
* =
* [-1, 3, -1] 因为 4 在 nums2 中往后只有一个 2,不比4大,所以不存在;1在 nums2 中,往后第一个比 1 大的是3,所以返回3。同理。
*
* 解:先求出 nums2 每一个 element 往后的第一个更大的值,保存在 map 中。遍历 nums1,从 map 取出即可,如果不存在,说明是 -1
*/
class NextGreaterElementI
fun main(args: Array<String>) {
nextGreaterElement(intArrayOf(4, 1, 2), intArrayOf(1, 3, 4, 2)).apply {
for (i in this) {
print("$i,")
}
println()
}
nextGreaterElement(intArrayOf(2, 4), intArrayOf(1, 2, 3, 4)).apply {
for (i in this) {
print("$i,")
}
println()
}
}
fun nextGreaterElement(nums1: IntArray, nums2: IntArray): IntArray {
var map = HashMap<Int, Int>()
for (i in 0.until(nums2.size)) {
var nextGreater = -1
for (j in (i + 1).until(nums2.size)) {
if (nums2[i] < nums2[j]) {
nextGreater = nums2[j]
map[nums2[i]] = nextGreater
break
}
}
}
nums1.mapIndexed { index, value ->
if (map[value] == null)
nums1[index] = -1
else
nums1[index] = map[value]!!
}
return nums1
} | 0 | Java | 0 | 0 | dda0178efe6899800b46b8b7527a8f59e429f5e1 | 1,599 | LeetCodePractice | Apache License 2.0 |
src/Day04.kt | KarinaCher | 572,657,240 | false | {"Kotlin": 21749} | fun main() {
fun part1(input: List<String>): Int {
var result = 0
input.forEach {
val elves = it.split(",")
val firstElves = elves[0].split("-")
val secondElves = elves[1].split("-")
val firstElvesSections = (firstElves[0].toInt()..firstElves[1].toInt()).toList()
val secondElvesSections = (secondElves[0].toInt()..secondElves[1].toInt()).toList()
if (firstElvesSections.containsAll(secondElvesSections)
|| secondElvesSections.containsAll(firstElvesSections)) {
result++
}
}
return result
}
fun part2(input: List<String>): Int {
var result = 0
input.forEach {
val elves = it.split(",")
val firstElves = elves[0].split("-")
val secondElves = elves[1].split("-")
val firstElvesSections = (firstElves[0].toInt()..firstElves[1].toInt()).toList()
val secondElvesSections = (secondElves[0].toInt()..secondElves[1].toInt()).toList()
if (firstElvesSections.intersect(secondElvesSections).isNotEmpty()) {
result++
}
}
return result
}
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 | 17d5fc87e1bcb2a65764067610778141110284b6 | 1,433 | KotlinAdvent | Apache License 2.0 |
src/Day02.kt | cnietoc | 572,880,374 | false | {"Kotlin": 15990} | fun main() {
fun part1(input: List<String>): Long {
var sumResult = 0L
input.forEach {
val (opponentShapeEncrypted, myShapeEncrypted) = it.split(" ")
val myShape = myShapeEncrypted.toMyShape()
val opponentShape = opponentShapeEncrypted.toOpponentShape()
sumResult += myShape.shapeValue() + myShape.playVs(opponentShape).resultValue()
}
return sumResult
}
fun part2(input: List<String>): Long {
var sumResult = 0L
input.forEach {
val (opponentShapeEncrypted, myExpectedResultEncrypted) = it.split(" ")
val myExpectedResult = myExpectedResultEncrypted.toResult()
val opponentShape = opponentShapeEncrypted.toOpponentShape()
val myShape = myExpectedResult.whatShapeShouldIPlayVs(opponentShape)
sumResult += myShape.shapeValue() + myShape.playVs(opponentShape).resultValue()
}
return sumResult
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 15L)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
enum class Shape {
ROCK {
override fun playVs(shape: Shape): Result {
return when (shape) {
ROCK -> Result.DRAW
PAPER -> Result.LOSE
SCISSORS -> Result.WIN
}
}
},
PAPER {
override fun playVs(shape: Shape): Result {
return when (shape) {
ROCK -> Result.WIN
PAPER -> Result.DRAW
SCISSORS -> Result.LOSE
}
}
},
SCISSORS {
override fun playVs(shape: Shape): Result {
return when (shape) {
ROCK -> Result.LOSE
PAPER -> Result.WIN
SCISSORS -> Result.DRAW
}
}
};
abstract fun playVs(shape: Shape): Result
enum class Result {
WIN, LOSE, DRAW
}
}
fun String.toOpponentShape(): Shape = when (this) {
"A" -> Shape.ROCK
"B" -> Shape.PAPER
"C" -> Shape.SCISSORS
else -> {
throw IllegalArgumentException("WTF is $this??")
}
}
fun String.toMyShape(): Shape = when (this) {
"X" -> Shape.ROCK
"Y" -> Shape.PAPER
"Z" -> Shape.SCISSORS
else -> {
throw IllegalArgumentException("WTF is $this??")
}
}
fun String.toResult(): Shape.Result = when (this) {
"X" -> Shape.Result.LOSE
"Y" -> Shape.Result.DRAW
"Z" -> Shape.Result.WIN
else -> {
throw IllegalArgumentException("WTF is $this??")
}
}
fun Shape.shapeValue() = when (this) {
Shape.ROCK -> 1L
Shape.PAPER -> 2L
Shape.SCISSORS -> 3L
}
fun Shape.Result.resultValue() = when (this) {
Shape.Result.WIN -> 6L
Shape.Result.LOSE -> 0L
Shape.Result.DRAW -> 3L
}
fun Shape.Result.whatShapeShouldIPlayVs(shape: Shape) = when (this) {
Shape.Result.WIN -> shape.loseVs()
Shape.Result.LOSE -> shape.winsVs()
Shape.Result.DRAW -> shape.drawVs()
}
private fun Shape.loseVs() = Shape.values().first { this.playVs(it) == Shape.Result.LOSE }
private fun Shape.winsVs() = Shape.values().first { this.playVs(it) == Shape.Result.WIN }
private fun Shape.drawVs() = Shape.values().first { this.playVs(it) == Shape.Result.DRAW }
| 0 | Kotlin | 0 | 0 | bbd8e81751b96b37d9fe48a54e5f4b3a0bab5da3 | 3,404 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/year2022/Day23.kt | simpor | 572,200,851 | false | {"Kotlin": 80923} | import AoCUtils
import AoCUtils.test
enum class MapType { SPACE, ELF }
fun main() {
data class MovementLogic(val moveDirection: Map2dDirection, val checks: List<Map2dDirection>) {
fun checkIfElf(map: Map2d<MapType>, elf: Point): Boolean {
val toCheck = map.around(elf, checks).values.any { it == MapType.ELF }
return toCheck
}
fun checkIfSpace(map: Map2d<MapType>, elf: Point): Boolean {
val toCheck = map.around(elf, checks).values.any { it == MapType.SPACE }
return toCheck
}
fun pointToMoveTo(point: Point) = when (moveDirection) {
Map2dDirection.N -> Point(point.x, point.y - 1)
Map2dDirection.NE -> Point(point.x + 1, point.y - 1)
Map2dDirection.E -> Point(point.x + 1, point.y)
Map2dDirection.SE -> Point(point.x + 1, point.y + 1)
Map2dDirection.S -> Point(point.x, point.y + 1)
Map2dDirection.SW -> Point(point.x - 1, point.y + 1)
Map2dDirection.W -> Point(point.x - 1, point.y)
Map2dDirection.NW -> Point(point.x - 1, point.y - 1)
Map2dDirection.CENTER -> point
}
}
fun part1(input: String, debug: Boolean = false): Long {
val map = parseMap(input) { c ->
when (c) {
'.' -> MapType.SPACE
'#' -> MapType.ELF
else -> throw Exception("Unknown Type")
}
}
val movementLogics = mutableListOf<MovementLogic>()
movementLogics.add(
MovementLogic(
Map2dDirection.N,
listOf(Map2dDirection.N, Map2dDirection.NE, Map2dDirection.NW)
)
)
movementLogics.add(
MovementLogic(
Map2dDirection.S,
listOf(Map2dDirection.S, Map2dDirection.SE, Map2dDirection.SW)
)
)
movementLogics.add(
MovementLogic(
Map2dDirection.W,
listOf(Map2dDirection.W, Map2dDirection.NW, Map2dDirection.SW)
)
)
movementLogics.add(
MovementLogic(
Map2dDirection.E,
listOf(Map2dDirection.E, Map2dDirection.NE, Map2dDirection.SE)
)
)
data class ElfToMove(val from: Point, val to: Point)
while (true) {
val elfes = map.filter { it.value == MapType.ELF }.map { it.key }
// val movements = elfes.filter { e -> movementLogic.checkIfSpace(map, e) }.map { ElfToMove(it, movementLogic.pointToMoveTo(it))}
val movementLogic = movementLogics.removeAt(0)
movementLogics.add(movementLogic)
}
return 0L
}
fun part2(input: String, debug: Boolean = false): Long {
return 0L
}
val testInput =
"....#..\n" +
"..###.#\n" +
"#...#.#\n" +
".#...##\n" +
"#.###..\n" +
"##.#.##\n" +
".#..#.."
val input = AoCUtils.readText("year2022/day23.txt")
part1(testInput, false) test Pair(24L, "test 1 part 1")
part1(input, false) test Pair(0L, "part 1")
part2(testInput, false) test Pair(0L, "test 2 part 2")
part2(input) test Pair(0L, "part 2")
}
| 0 | Kotlin | 0 | 0 | 631cbd22ca7bdfc8a5218c306402c19efd65330b | 3,323 | aoc-2022-kotlin | Apache License 2.0 |
src/main/kotlin/com/github/wtfjoke/day4/Day4Part1.kts | WtfJoke | 434,008,687 | false | {"Kotlin": 80582} | import java.nio.file.Paths
typealias BingoBoard = List<List<Int>>
val inputs = Paths.get("inputs.txt").toFile().useLines { it.toList() }
val drawnNumbers = inputs.first().split(',').map { it.toInt() }
val boards: Set<BingoBoard> = inputs
.asSequence()
.drop(1)
.filter { it.isNotEmpty() }
.chunked(5)
.map { parseBoard(it) }
.toSet()
fun parseBoard(boards: List<String>): BingoBoard = boards.map { row ->
row.split(' ')
.filter { it.isNotEmpty() }
.map { it.toInt() }
}
fun BingoBoard.isWinning(drawn: Collection<Int>): Boolean {
val rowMatch = this.any { row -> row.all { it in drawn } }
val columnMatch = (0..4).any { column -> this.all { row -> row[column] in drawn } }
return rowMatch || columnMatch
}
fun BingoBoard.sumUnmarked(drawn: Collection<Int>): Int {
return this.sumOf { row ->
row.filterNot { it in drawn }
.sum()
}
}
fun part1() {
val drawn = mutableListOf<Int>()
val score = drawnNumbers.firstNotNullOf { draw ->
drawn += draw
boards.firstOrNull { it.isWinning(drawn) }
?.let { winningBoard ->
winningBoard.sumUnmarked(drawn) * draw
}
}
println(score)
}
part1()
| 1 | Kotlin | 0 | 0 | 9185b9ddf3892be24838139fcfc849d3cb6e89b4 | 1,242 | adventofcode-21 | MIT License |
classroom/src/main/kotlin/com/radix2/algorithms/extras/Scribble.kt | rupeshsasne | 190,130,318 | false | {"Java": 66279, "Kotlin": 50290} | package com.radix2.algorithms.extras
import java.util.*
fun print(array: IntArray, lo: Int, hi: Int) {
if (lo == hi) {
println(array[lo])
} else {
println(array[lo])
print(array, lo + 1, hi)
}
}
fun map(array: IntArray, lo: Int, hi: Int, transform: (Int) -> Int) {
array[lo] = transform(lo)
if (lo < hi)
map(array, lo + 1, hi, transform)
}
fun fib(n: Int): Int {
return if (n < 2)
n
else
fib(n - 1) + fib(n - 2)
}
fun towerOfHanoi(num: Int, from: Char, to: Char, aux: Char) {
if (num == 1) {
println("$from -> $to")
} else {
towerOfHanoi(num - 1, from, aux, to)
println("$from -> $to")
towerOfHanoi(num - 1, aux, to, from)
}
}
fun isPallindrom(str: String, lo: Int, hi: Int): Boolean {
if (hi <= lo)
return str[lo] == str[hi]
return str[lo] == str[hi] && isPallindrom(str, lo + 1, hi - 1)
}
fun power(a: Int, b: Int): Int {
if (b == 1)
return a
return a * power(a, b - 1)
}
fun reversePrint(str: String) {
if (str.length == 1)
print(str)
else {
print("${str.last()}")
reversePrint(str.substring(0, str.lastIndex))
}
}
fun shiftBlankToRight(array: IntArray) {
val list = array.sortedWith(kotlin.Comparator { o1, o2 ->
when {
o1 == ' '.toInt() -> 1
o2 == ' '.toInt() -> -1
else -> 0
}
})
println(list.joinToString())
}
fun main(args: Array<String>) {
val array = intArrayOf('A'.toInt(), 'B'.toInt(), ' '.toInt(), 'C'.toInt(), ' '.toInt(), ' '.toInt(), 'D'.toInt())
shiftBlankToRight(array)
println()
}
| 0 | Java | 0 | 1 | 341634c0da22e578d36f6b5c5f87443ba6e6b7bc | 1,683 | coursera-algorithms-part1 | Apache License 2.0 |
src/main/kotlin/me/grison/aoc/y2021/Day23.kt | agrison | 315,292,447 | false | {"Kotlin": 267552} | package me.grison.aoc.y2021
import me.grison.aoc.*
import me.grison.aoc.y2021.Day23.Amphipod.*
import java.util.*
import kotlin.math.abs
class Day23 : Day(23, 2021) {
override fun title() = "Amphipod"
enum class Amphipod { A, B, C, D }
private val roomExits = listOf(2, 4, 6, 8)
override fun partOne() = organizeAmphipods(loadRooms(0), 2)
override fun partTwo() = organizeAmphipods(loadRooms(1), 4)
private fun loadRooms(problem: Int): Rooms {
return inputGroups[problem].lines()
.map { it.filter { it in 'A'..'D' }.stringList() }
.filter { it.isNotEmpty() }
.transpose()
.map { it.reversed() }
.map { it.map { Amphipod.valueOf(it).ordinal } }
}
private fun organizeAmphipods(rooms: List<List<Int>>, roomSize: Int): Int {
val queue = PriorityQueue<Situation>()
queue.add(Situation(roomSize, 0, rooms))
val visited = mutableSetOf<Pair<Rooms, Hallway>>()
while (queue.isNotEmpty()) {
val situation = queue.poll()
if (situation.isOrganized())
return situation.energy
if (situation.currentState() in visited)
continue
visited.add(situation.currentState())
// first move amphipods from rooms to hallway
for ((roomNumber, currentRoom) in situation.rooms.withIndex()) {
if (currentRoom.isNotEmpty() && !currentRoom.all { it == roomNumber }) {
val amphipod = currentRoom.last()
val left = (roomExits[roomNumber] downTo 0) - roomExits
val right = (roomExits[roomNumber]..10) - roomExits
for (direction in listOf(left, right)) {
for (position in direction) {
if (situation.hallwayIsOccupied(position)) break
val steps = roomSize - currentRoom.size + abs(roomExits[roomNumber] - position) + 1
Situation(roomSize,
situation.energy + steps * cost(amphipod),
situation.rooms.update(roomNumber, currentRoom.butLast()),
situation.hallway.update(position, amphipod)
).also { if (it.currentState() !in visited) queue.add(it) }
}
}
}
}
// then move amphipods back to room where possible
for ((index, amphipod) in situation.hallway.withIndex()) {
if (cannotEnterRoom(situation, index, amphipod))
continue
val steps = roomSize - situation.occupants(amphipod!!) + abs(roomExits[amphipod] - index)
Situation(roomSize,
situation.energy + steps * cost(amphipod),
situation.rooms.update(amphipod, situation.rooms[amphipod] + amphipod),
situation.hallway.update(index, null)
).also { if (it.currentState() !in visited) queue.add(it) }
}
}
return -1
}
private fun cannotEnterRoom(situation: Situation, index: Int, amphipod: Int?): Boolean {
return situation.hallwayIsFree(index) ||
index < roomExits[amphipod!!] && !situation.hallwayIsFree(index + 1, roomExits[amphipod]) ||
index > roomExits[amphipod] && !situation.hallwayIsFree(roomExits[amphipod] + 1, index) ||
situation.rooms[amphipod].any { it != amphipod }
}
private fun cost(amphipod: Int): Int {
return when (Amphipod.values()[amphipod]) {
A -> 1
B -> 10
C -> 100
D -> 1000
}
}
data class Situation(
val size: Int,
val energy: Int, val rooms: Rooms,
val hallway: Hallway = List(11) { null }
) : Comparable<Situation> {
override fun compareTo(other: Situation) = energy.compareTo(other.energy)
fun currentState() = p(rooms, hallway)
fun occupants(amphipod: Int) = rooms[amphipod].size
fun hallwayIsOccupied(i: Int) = hallway[i] != null
fun hallwayIsFree(i: Int) = hallway[i] == null
fun hallwayIsFree(from: Int, to: Int) = hallway.subList(from, to).all { it == null }
fun isOrganized(): Boolean {
return hallway.all { it == null } &&
rooms.all { it.size == size } &&
rooms.withIndex().all { it.value.isOrganized(it.index) }
}
}
}
private typealias Room = List<Int>
fun Room.isOrganized(roomNumber: Int) = isNotEmpty() && all { it == roomNumber }
private typealias Rooms = List<Room>
private typealias Hallway = List<Int?> | 0 | Kotlin | 3 | 18 | ea6899817458f7ee76d4ba24d36d33f8b58ce9e8 | 4,795 | advent-of-code | Creative Commons Zero v1.0 Universal |
src/main/kotlin/day5.kt | kevinrobayna | 436,414,545 | false | {"Ruby": 195446, "Kotlin": 42719, "Shell": 1288} | import java.util.stream.Collectors
import kotlin.math.roundToLong
data class BoardingPass(
val row: List<String>,
val seat: List<String>
) {
companion object {
const val LEFT = "L"
const val RIGHT = "R"
const val BACK = "B"
const val FRONT = "F"
}
}
fun day5ProblemReader(string: String): List<BoardingPass> {
return string.split("\n").stream().map { line ->
val row = mutableListOf<String>()
val seat = mutableListOf<String>()
line.split("").forEach {
if (it == BoardingPass.LEFT || it == BoardingPass.RIGHT) {
seat.add(it)
} else if (it == BoardingPass.BACK || it == BoardingPass.FRONT) {
row.add(it)
}
}
BoardingPass(row, seat)
}.collect(Collectors.toList())
}
// https://adventofcode.com/2020/day/5
class Day5(
private val boardingPasses: List<BoardingPass>,
) {
companion object {
const val ROW_RANGE: Long = 128
const val COLUMN_RANGE: Long = 8
}
private fun calculateIds(): List<Long> {
return boardingPasses
.stream()
.map { calculateSeatId(it) }
.sorted()
.collect(Collectors.toList())
}
fun getHighestSeatId(): Long {
return calculateIds()[boardingPasses.size - 1]
}
fun getMySeat(): Long {
val ids = calculateIds()
var index = ids.size - 1
while ((ids[index] - ids[index - 1]) == 1L) {
index -= 1
}
return ids[index] - 1
}
private fun calculateSeatId(boardingPass: BoardingPass): Long {
return (calculateRowNumber(boardingPass) * COLUMN_RANGE) + calculateColumnNumber(boardingPass)
}
private fun calculateRowNumber(boardingPass: BoardingPass): Long {
if (boardingPass.row.isEmpty()) {
return 1
}
return calculateNumber(boardingPass.row, ROW_RANGE, BoardingPass.BACK)
}
private fun calculateColumnNumber(boardingPass: BoardingPass): Long {
if (boardingPass.seat.isEmpty()) {
return 1
}
return calculateNumber(boardingPass.seat, COLUMN_RANGE, BoardingPass.RIGHT)
}
private fun calculateNumber(list: List<String>, endRange: Long, upHalfChar: String): Long {
var startPost: Long = 0
var endPosition: Long = endRange.minus(1)
for (character in list) {
if (endPosition - startPost == 1L) {
if (character == upHalfChar) {
return endPosition
}
return startPost
}
if (character == upHalfChar) {
startPost = (((endPosition - startPost) / 2.0) + startPost).roundToLong()
} else {
endPosition = ((endPosition - startPost) / 2) + startPost
}
}
return startPost
}
}
fun main() {
val problem = day5ProblemReader(Day4::class.java.getResource("day5.txt").readText())
println("solution = ${Day5(problem).getHighestSeatId()}")
println("solution = ${Day5(problem).getMySeat()}")
} | 0 | Kotlin | 0 | 0 | 9e48ecdebdb4c479ef00f0fd3b1a44a211fb6577 | 3,141 | adventofcode_2020 | MIT License |
src/Day04.kt | jvmusin | 572,685,421 | false | {"Kotlin": 86453} | fun main() {
fun String.toRange() = split("-").map { it.toInt() }.let { it[0]..it[1] }
fun part1(input: List<String>): Int {
var cnt = 0
for (s in input) {
val p = s.split(",")
val r1 = p[0].toRange().toList()
val r2 = p[1].toRange().toList()
if (r1.containsAll(r2) || r2.containsAll(r1)) cnt++
}
return cnt
}
fun part2(input: List<String>): Int {
var cnt = 0
for (s in input) {
val p = s.split(",")
val r1 = p[0].toRange().toList()
val r2 = p[1].toRange().toList()
if (r1.any { it in r2 } || r2.any { it in r1 }) cnt++
}
return cnt
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
println(part1(testInput))
println(part2(testInput))
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 1 | Kotlin | 0 | 0 | 4dd83724103617aa0e77eb145744bc3e8c988959 | 984 | advent-of-code-2022 | Apache License 2.0 |
2021/src/day23/Solution.kt | vadimsemenov | 437,677,116 | false | {"Kotlin": 56211, "Rust": 37295} | package day23
import java.nio.file.Files
import java.nio.file.Paths
import java.util.TreeSet
import kotlin.math.absoluteValue
import kotlin.system.measureTimeMillis
fun main() {
val amphipods = "ABCD"
val step = listOf(1, 10, 100, 1000)
val rooms = listOf(3, 5, 7, 9)
fun Input.isFinal(): Boolean {
for (i in this[0]) {
if (i != '.' && i != '#') return false
}
for (i in amphipods.indices) {
for (j in 1 until this.size) {
if (this[j][rooms[i]] != amphipods[i]) {
return false
}
}
}
return true
}
fun Input.swap(x1: Int, y1: Int, x2: Int, y2: Int): Input = map { it.toCharArray() }.run {
this[x1][y1] = this[x2][y2].also {
this[x2][y2] = this[x1][y1]
}
map { String(it) }
}
fun generateNextStates(list: List<String>) = buildList {
for (i in list[0].indices) {
if (list[0][i] !in amphipods) continue
val amphipod = list[0][i].code - 'A'.code // move from hallway to the final room.
val roomId = rooms[amphipod]
val target = list.indexOfLast { it[roomId] == '.' }
if (target == -1) continue
if (list.subList(0, target).any { it[roomId] != '.' }) continue
if (list.subList(target + 1, list.size).any { it[roomId] != amphipods[amphipod] }) continue
if (list[0].substring(minOf(i + 1, roomId), maxOf(roomId, i - 1)).any { it != '.' }) continue
val nextState = list.swap(0, i, target, roomId)
val distance = (i - roomId).absoluteValue + target
add(nextState to distance * step[amphipod])
}
for ((index, roomId) in rooms.withIndex()) {
if (list.all { it[roomId] == '.' || it[roomId] == amphipods[index] }) continue
for (i in 1 until list.size) {
if (list[i][roomId] == '.') continue
val amphipod = list[i][roomId].code - 'A'.code // move from starting room to the hallway.
for (range in listOf(roomId + 1 until list[0].length, roomId - 1 downTo 0)) {
for (j in range) {
if (list[0][j] != '.') break
if (j in rooms) continue
val nextState = list.swap(0, j, i, roomId)
val distance = (j - roomId).absoluteValue + i
add(nextState to distance * step[amphipod])
}
}
break
}
}
}
fun part1(input: Input): Int {
val stateIds = mutableMapOf<List<String>, Int>()
val states = mutableListOf<List<String>>()
val costs = mutableListOf<Int>()
val queue = TreeSet(Comparator.comparingInt<Int> { costs[it] }.thenComparingInt { it })
stateIds[input] = states.size
states.add(input)
costs.add(0)
queue.add(0)
while (queue.isNotEmpty()) {
val id = queue.pollFirst()!!
if (states[id].isFinal()) {
return costs[id]
}
for ((state, delta) in generateNextStates(states[id])) {
val newCost = costs[id] + delta
val stateId = stateIds.computeIfAbsent(state) { states.size }
if (stateId == states.size) {
states.add(state)
costs.add(newCost)
queue.add(stateId)
} else if (newCost < costs[stateId]) {
check(queue.remove(stateId))
costs[stateId] = newCost
queue.add(stateId)
}
}
}
error("Polundra!")
}
fun part2(input: Input): Int {
return part1(
buildList {
add(input[0])
add(input[1])
add(" #D#C#B#A#")
add(" #D#B#A#C#")
add(input[2])
}
)
}
check(part1(readInput("test-input.txt")) == 12521)
check(part2(readInput("test-input.txt")) == 44169)
val millis = measureTimeMillis {
println(part1(readInput("input.txt")))
println(part2(readInput("input.txt")))
}
System.err.println("Done in $millis ms")
}
private fun readInput(s: String): Input {
return Files.newBufferedReader(Paths.get("src/day23/$s")).readLines().subList(1, 4)
}
private typealias Input = List<String>
| 0 | Kotlin | 0 | 0 | 8f31d39d1a94c862f88278f22430e620b424bd68 | 3,937 | advent-of-code | Apache License 2.0 |
src/main/kotlin/com/hj/leetcode/kotlin/problem229/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem229
/**
* LeetCode page: [229. Majority Element II](https://leetcode.com/problems/majority-element-ii/);
*/
class Solution {
private val k = 3 // Divisor of size of nums describing the threshold to be considered as majority;
/* Complexity:
* Time O(N) and Space O(k) where N is the size of nums. For this problem k = 3 thus space complexity
* is actually O(1);
*/
fun majorityElement(nums: IntArray): List<Int> {
val candidates = findCandidatesForMajorityElements(nums)
return findMajorityElements(candidates, nums)
}
private fun findCandidatesForMajorityElements(nums: IntArray): List<Int> {
val countPerCandidates = hashMapOf<Int, Int>()
for (num in nums) {
countPerCandidates[num] = countPerCandidates.getOrDefault(num, 0) + 1
reduceCandidatesIfTotalReachesK(countPerCandidates)
}
return countPerCandidates.keys.toList()
}
private fun reduceCandidatesIfTotalReachesK(countPerCandidates: MutableMap<Int, Int>) {
if (countPerCandidates.size == k) {
val iterator = countPerCandidates.iterator()
while (iterator.hasNext()) {
val (candidate, count) = iterator.next()
val newCount = count - 1
if (newCount == 0) iterator.remove() else countPerCandidates[candidate] = newCount
}
}
}
private fun findMajorityElements(candidates: List<Int>, nums: IntArray): List<Int> {
val threshold = nums.size / k
return candidates.filter { candidate ->
val count = nums.count { num -> num == candidate }
count > threshold
}
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 1,733 | hj-leetcode-kotlin | Apache License 2.0 |
src/commonMain/kotlin/ai/hypergraph/kaliningraph/parsing/SeqValiant.kt | breandan | 245,074,037 | false | {"Kotlin": 1482924, "Haskell": 744, "OCaml": 200} | package ai.hypergraph.kaliningraph.parsing
import ai.hypergraph.kaliningraph.*
import ai.hypergraph.kaliningraph.repair.*
import ai.hypergraph.kaliningraph.sampling.*
import ai.hypergraph.kaliningraph.tensor.UTMatrix
import ai.hypergraph.kaliningraph.types.*
import com.ionspin.kotlin.bignum.integer.*
import kotlin.jvm.JvmName
import kotlin.math.*
import kotlin.random.Random
import kotlin.time.measureTimedValue
typealias PForest = Map<String, PTree> // ℙ₃
// Algebraic data type / polynomial functor for parse forests (ℙ₂)
class PTree(val root: String = ".ε", val branches: List<Π2A<PTree>> = listOf()) {
// val hash by lazy { root.hashCode() + if (branches.isEmpty()) 0 else branches.hashCode() }
// override fun hashCode(): Int = hash
val branchRatio: Pair<Double, Double> by lazy { if (branches.isEmpty()) 0.0 to 0.0 else
(branches.size.toDouble() + branches.sumOf { (l, r) -> l.branchRatio.first + r.branchRatio.first }) to
(1 + branches.sumOf { (l, r) -> l.branchRatio.second + r.branchRatio.second })
}
val allTerminals: Set<String> by lazy {
if (branches.isEmpty()) setOf(root)
else branches.map { (l, r) -> l.allTerminals + r.allTerminals }.flatten().toSet()
}
// Σ^n/|T(n)|, if < 1 then we know the grammar is surely ambiguous
val inverseDensity by lazy {
measureTimedValue { allTerminals.size.toBigInteger().pow(depth) / totalTrees }
.also { println("Solution density was: 1/${it.value} (${it.duration})") }.value
}
// TODO: Use weighted choice mechanism
val shuffledBranches by lazy { branches.shuffled().sortedBy { "ε" !in it.first.root + it.second.root } }
val totalTrees: BigInteger by lazy {
if (branches.isEmpty()) BigInteger.ONE
else branches.map { (l, r) -> l.totalTrees * r.totalTrees }
.reduce { acc, it -> acc + it }
}
// e.g., if we want to prioritize shorter strings we can sort by total epsilons
val numEpsilons: BigInteger by lazy {
if (branches.isEmpty()) if (root == "ε") BigInteger.ONE else BigInteger.ZERO
else branches.map { (l, r) -> l.totalTrees * r.totalTrees }.reduce { acc, it -> acc + it }
// else branches.maxOf { (l, r) -> l.numEpsilons + r.numEpsilons }
}
fun Π2A<PTree>.countEpsilons() = first.numEpsilons + second.numEpsilons
val epsSortedBranches by lazy { branches.sortedBy { -it.countEpsilons() } }
val depth: Int by lazy {
if (branches.isEmpty()) 0
else branches.maxOf { (l, r) -> maxOf(l.depth, r.depth) + 1 }
}
private val choice by lazy {
if (branches.isEmpty()) listOf(if ("ε" in root) "" else root)
else shuffledBranches.flatMap { (l, r) ->
(l.choose() * r.choose()).map { (a, b) ->
if (a.isEmpty()) b else if (b.isEmpty()) a else "$a $b"
}
}.distinct()
}
fun choose(): Sequence<String> = choice.asSequence()
// Average time: 436.96ms, total time 43696.959ms (testRandomCFG)
private fun decodeString(i: BigInteger): Pair<String, BigInteger> {
if (branches.isEmpty()) return (if ("ε" in root) "" else root) to i
val (quotient1, remainder) = i.divrem(branches.size.toBigInteger())
val (lb, rb) = shuffledBranches[remainder.intValue()]
val (l, quotient2) = lb.decodeString(quotient1)
val (r, quotient3) = rb.decodeString(quotient2)
val concat = (if(l.isEmpty()) r else if(r.isEmpty()) l else "$l $r")
return concat to quotient3
}
// Average time: 328.99ms, total time 32899.708ms (testRandomCFG)
private fun decodeStringFast(i: Long): Pair<String, Long> {
if (branches.isEmpty()) return (if ("ε" in root) "" else root) to i
val (quotient1, remainder) = i / branches.size.toLong() to (i % branches.size.toLong())
val (lb, rb) = shuffledBranches[remainder.toInt()]
val (l, quotient2) = lb.decodeStringFast(quotient1)
val (r, quotient3) = rb.decodeStringFast(quotient2)
val concat = (if(l.isEmpty()) r else if(r.isEmpty()) l else "$l $r")
return concat to quotient3
}
private fun decodeTree(i: BigInteger): Pair<Tree, BigInteger> {
if (branches.isEmpty()) return Tree(root) to i
val (quotient1, remainder) = i.divrem(branches.size.toBigInteger())
val (lb, rb) = shuffledBranches[remainder.toString().toInt()]
val (l, quotient2) = lb.decodeTree(quotient1)
val (r, quotient3) = rb.decodeTree(quotient2)
val isSingleton = l.children.isEmpty() && r.root == ".ε"
return (if (isSingleton) Tree(root, terminal = l.root)
else Tree(root, children = arrayOf(l, r))) to quotient3
}
fun sampleTreesWithoutReplacement(): Sequence<Tree> = sequence {
var i = BigInteger.ZERO
while (i < 3 * totalTrees) yield(decodeTree(i++).first)
}
fun sampleStrWithoutReplacement(stride: Int = 1, offset: Int = 0): Sequence<String> =
sequence {
var i = BigInteger.ZERO
while (i < 5 * totalTrees) yield(decodeString(i++ * stride + offset).first)
}
// Samples instantaneously from the parse forest, but may return duplicates
// and only returns a fraction of the number of distinct strings when compared
// to SWOR on medium-sized finite sets under the same wall-clock timeout. If
// the set is sufficiently large, distinctness will never be a problem.
fun sampleWithReplacement(): Sequence<String> = generateSequence { sample() }
fun sampleDiverseTrees(): Sequence<Tree> =
sampleTreesWithoutReplacement().distinctBy { it.structureEncode() }
fun sampleTree(): Tree =
if (branches.isEmpty()) Tree(root)
else shuffledBranches.random().let { (l, r) ->
val (a, b) = l.sampleTree() to r.sampleTree()
Tree(root, children = arrayOf(a, b))
}
fun sample(): String =
if (branches.isEmpty()) if ("ε" in root) "" else root
else branches.random().let { (l, r) ->
val (a, b) = l.sample() to r.sample()
if (a.isEmpty()) b else if (b.isEmpty()) a else "$a $b"
}
fun sampleWRGD(): Sequence<String> = generateSequence { sampleStrWithGeomDecay() }
// Prefers shorter strings, i.e., strings with more ε tokens
fun sampleStrWithGeomDecay(): String =
if (branches.isEmpty()) if (".ε" in root) "" else root
else {
// val p = 0.9 // Adjust this for different decay rates
// val rnd = Random.nextDouble()
// val index =(-(1.0 / ln(1 - p)) * ln(1 - rnd) * branches.size).toInt().coerceIn(branches.indices)
// println(index)
epsSortedBranches.sampleWithGeomDecay().let { (l, r) ->
val (a, b) = l.sampleStrWithGeomDecay() to r.sampleStrWithGeomDecay()
if (a.isEmpty()) b else if (b.isEmpty()) a else "$a $b"
}
}
// fun List<Π2A<PTree>>.sampleWithGeomDecay(): Π2A<PTree> {
// val p = 0.5 // Adjust this for different decay rates
// val rnd = Random.nextDouble()
// val index = -(1.0 / ln(1 - p)) * ln(1 - rnd)
// return epsSortedBranches[index.toInt().coerceAtMost(branches.size - 1)]
// }
}
fun CFG.startPTree(tokens: List<String>) = //measureTimedValue {
initPForestMat(tokens).seekFixpoint().diagonals.last()[0][START_SYMBOL]
//}.also { println("Took ${it.duration} to compute parse forest") }.value
// Instead of defining a special case, we instead represent the unit production
// as a left child whose sibling is empty like so: Left child to Right child
fun PSingleton(v: String): List<Π2A<PTree>> = listOf(PTree(v) to PTree())
fun CFG.initPForestMat(tokens: List<String>): UTMatrix<PForest> =
UTMatrix(
ts = tokens.map { token ->
(if (token != HOLE_MARKER) bimap[listOf(token)] else unitNonterminals)
.associateWith { nt ->
if (token != HOLE_MARKER) PSingleton(token)
else bimap.UNITS[nt]?.map { PSingleton(it) }?.flatten() ?: listOf()
}.map { (k, v) -> k to PTree(k, v) }.toMap()
}.toTypedArray(),
algebra = Ring.of(
nil = emptyMap(),
plus = { x, y -> merge(x, y) },
times = { x, y -> joinSeq(x, y) },
)
)
fun merge(X: PForest, Z: PForest): PForest =
X.toMutableMap().apply {
Z.forEach { (k, v) ->
if (k in this) this[k] = PTree(k, (this[k]!!.branches + v.branches))
else this[k] = v
}
}.toMap()
// Too slow:
// (X.keys + Z.keys).associateWith { k ->
//// PTree(k, ((X[k]?.branches ?: listOf()) + (Z[k]?.branches ?: listOf())).toSet().toList())
// PTree(k, (X[k]?.branches ?: listOf()) + (Z[k]?.branches ?: listOf()))
// }
//fun merge(X: PForest, Z: PForest): PForest =
// (X.keys + Z.keys).associateWith { k ->
// PTree(k, ((X[k]?.branches ?: listOf()) + (Z[k]?.branches ?: listOf()))
// .groupBy { it.first.root to it.second.root }.map { (k, v) ->
// PTree(k.first, v.map { it.first.branches }.flatten()) to PTree(k.second, v.map { it.second.branches }.flatten())
// }
// )
// }
// X ⊗ Z := { w | <x, z> ∈ X × Z, (w -> xz) ∈ P }
fun CFG.joinSeq(X: PForest, Z: PForest): PForest =
bimap.TRIPL.filter { (_, x, z) -> x in X && z in Z }
// .map { (w, x, z) -> PTree(w, listOf(X[x]!! to Z[z]!!)) }
.map { (w, x, z) -> Triple(w, X[x]!!, Z[z]!!) }.groupBy { it.first }
.map { (k, v) -> k to PTree(k, v.map { it.second to it.third }) }
.toMap()
// .groupingBy { it.first }.aggregate { _, acc: List<Π2A<PTree>>?, it, _->
// val pair = X[it.second]!! to Z[it.third]!!
// if (acc == null) listOf(pair) else acc + pair
// }.map { (k, v) -> k to PTree(k, v) }.toMap()
fun CFG.sliceSolve(size: Int): Sequence<String> = solveSeq(List(size) { "_" })
fun CFG.sliceSample(size: Int): Sequence<String> = sampleSeq(List(size) { "_" })
// Lazily computes all syntactically strings compatible with the given template
// Generally slow, but guaranteed to return all solutions
fun CFG.solveSeq(tokens: List<String>): Sequence<String> =
startPTree(tokens)?.choose()?.distinct() ?: sequenceOf()
// This should never return duplicates and is the second fastest.
// Eventually, this will become the default method for sampling.
fun CFG.enumSeq(tokens: List<String>): Sequence<String> =
startPTree(tokens)?.sampleStrWithoutReplacement() ?: sequenceOf()
fun CFG.enumSeqMinimal(
prompt: List<String>,
tokens: List<String>,
stoppingCriterion: () -> Boolean = { true }
): Sequence<String> =
startPTree(prompt)?.sampleStrWithoutReplacement()
?.takeWhile { stoppingCriterion() }
?.distinct()
?.flatMap { minimizeFix(tokens, it.tokenizeByWhitespace()) { this in language } }
?.distinct()
?: sequenceOf()
var maxTrees = 50_000
// This should never return duplicates and is the second fastest.
// Eventually, this will become the default method for sampling.
fun CFG.enumSeqSmart(tokens: List<String>): Sequence<String> =
startPTree(tokens)?.let { pt ->
if (BigInteger.ONE < pt.inverseDensity) {
if (pt.totalTrees < BigInteger(maxTrees)) {
println("Small number of parse trees (${pt.totalTrees}), sampling without replacement!")
pt.sampleStrWithoutReplacement()
}
else {
println("Large number of parse trees (${pt.totalTrees}), sampling with replacement!")
pt.sampleWithReplacement()
// pt.sampleDiverseTrees().map { it.contents(true) }
}
}
// This means the grammar is highly ambiguous and we would probably be
// better off sampling from the bottom-up, instead of from the top-down.
else {
println("Ambiguity exceeds total solutions, switching to bottom-up naïve search!")
tokens.solve(this)
}
} ?: sequenceOf()
// This is generally the fastest method, but may return duplicates
fun CFG.sampleSeq(tokens: List<String>): Sequence<String> =
startPTree(tokens)?.sampleWithReplacement() ?: sequenceOf()
fun CFG.enumTrees(tokens: List<String>): Sequence<Tree> =
startPTree(tokens)?.sampleTreesWithoutReplacement() ?: sequenceOf()
fun CFG.sampleSWOR(tokens: List<String>): Sequence<String> =
startPTree(tokens)?.sampleWRGD() ?: sequenceOf()
fun CFG.hammingBallRepair(tokens: List<String>): Sequence<String> =
tokens.indices.toSet().choose(5)
.map { tokens.substituteIndices(it) { it, i -> "_" } }
.flatMap { sampleSWOR(it).take(100) }
fun CFG.repairSeq(tokens: List<String>): Sequence<String> =
tokens.intersperse(2, "ε").let { prompt ->
hammingBallRepair(prompt).flatMap {
val result = it.tokenizeByWhitespace()
val edit = prompt.calcEdit(it.tokenizeByWhitespace())
Repair(prompt, edit, result, 0.0)
.minimalAdmissibleSubrepairs({ it.filter { it != "ε" } in language }, { edit.size.toDouble() })
}.distinct().map { it.resToStr().removeEpsilon() }.distinct()
}
fun CFG.fastRepairSeq(tokens: List<String>, spacing: Int = 2, holes: Int = 6): Sequence<String> =
tokens.intersperse(spacing, "ε").let { prompt ->
prompt.indices.toSet().choose(minOf(holes, prompt.size - 1))
.map { prompt.substituteIndices(it) { _, _ -> "_" } }
// ifEmpty {...} is a hack to ensure the sequence emits values at a steady frequency
.flatMap { sampleSWOR(it).take(100).ifEmpty { sequenceOf("ε") } }
.map { it.removeEpsilon() }
}.flatMap { if (it.isEmpty()) sequenceOf(it) else minimizeFix(tokens, it.tokenizeByWhitespace()) { this in language } }
fun CFG.barHillelRepair(tokens: List<String>): Sequence<String> =
generateSequence(1) { it + 1 }
.flatMap { radius ->
try { intersectLevFSA(makeLevFSA(tokens, radius)).ifEmpty { null } }
catch (e: Exception) { null }?.toPTree()?.sampleStrWithoutReplacement() ?: sequenceOf()
}
// Note the repairs are not distinct as we try to avoid long delays between
// repairs, so callees must remember to append .distinct() if they want this.
fun CFG.fasterRepairSeq(tokens: List<String>, spacing: Int = 2, holes: Int = 6): Sequence<String> {
var levenshteinBlanket = tokens
var blanketSeq = emptySequence<String>().iterator()
val uniformSeq = tokens.intersperse(spacing, "ε").let { prompt ->
prompt.indices.toSet().choose(minOf(holes, prompt.size - 1))
.map { prompt.substituteIndices(it) { _, _ -> "_" } }
// ifEmpty {...} is a hack to ensure the sequence emits values at a steady frequency
.flatMap { sampleSWOR(it).take(100).ifEmpty { sequenceOf("ε") } }
}.iterator()
val distinct1 = mutableSetOf<String>()
val distinct2 = mutableSetOf<String>()
return generateSequence {
if (blanketSeq.hasNext() && Random.nextBoolean()) blanketSeq.next()
else if (uniformSeq.hasNext()) uniformSeq.next()
else null
}.map { it.removeEpsilon() }.flatMap {
if (it.isEmpty() || !distinct1.add(it)) sequenceOf(it)
else minimizeFix(tokens, it.tokenizeByWhitespace()) { this in language }
.onEach { minfix ->
if (minfix !in distinct2) {
distinct2.add(minfix)
val newBlanket =
updateLevenshteinBlanket(levenshteinBlanket, minfix.tokenizeByWhitespace())
if (newBlanket != levenshteinBlanket && "_" in newBlanket) {
levenshteinBlanket = newBlanket
blanketSeq = enumSeqSmart(levenshteinBlanket).iterator()
println("Levenshtein blanket: ${levenshteinBlanket.joinToString(" ")}")
}
}
}
}
}
/**
* We define the Levenshtein blanket as the union of all hole locations that overlap a
* minimal admissible patch. Crucially, the patches must be minimal, see [minimizeFix].
*/
fun updateLevenshteinBlanket(oldBlanket: List<String>, newRepair: List<String>) =
levenshteinAlign(oldBlanket, newRepair).map { (old, new) ->
if (old == null || new == null || old != new) "_" else old
}
@JvmName("updateLevenshteinBlanketInt")
fun updateLevenshteinBlanket(oldBlanket: List<Int>, newRepair: List<Int>) =
levenshteinAlign(oldBlanket, newRepair).map { (old, new) ->
if (old == null || new == null || old != new) -1 else old
}
fun List<Int>.toStrLevBlanket(imap: (Int) -> String) = map { if (it == -1) "_" else imap(it) } | 0 | Kotlin | 8 | 100 | c755dc4858ed2c202c71e12b083ab0518d113714 | 15,764 | galoisenne | Apache License 2.0 |
src/Day16.kt | PascalHonegger | 573,052,507 | false | {"Kotlin": 66208} | import kotlin.math.max
fun main() {
val inputPattern = "Valve (.+) has flow rate=(\\d+); tunnels? leads? to valves? (.+)".toRegex()
data class Valve(val id: Long, val name: String, val flowRate: Int, val leadsTo: List<String>) {
override fun toString() = name
}
fun String.toValve(id: Long): Valve {
val (name, flowRate, leadsTo) = inputPattern.matchEntire(this)!!.destructured
return Valve(id, name, flowRate.toInt(), leadsTo.split(", "))
}
fun List<String>.toValves() = mapIndexed { index, row -> row.toValve(1L shl index) }.associateBy { it.name }
fun Set<Valve>.releasingPressure() = sumOf { it.flowRate }
fun part1(input: List<String>): Int {
val valves = input.toValves()
val cache = HashMap<Triple<Long, Int, Long>, Int>()
val openValves = mutableSetOf<Valve>()
fun Valve.countPotentialGain(releasedPressure: Int, remainingMinutes: Int): Int {
val newPressure = releasedPressure + openValves.releasingPressure()
if (remainingMinutes == 0) {
return newPressure
}
val cacheKey = Triple(id, remainingMinutes, openValves.fold(0L) { acc, v -> acc or v.id })
cache[cacheKey]?.let {
return releasedPressure + it
}
fun maxPotentialGain(timeSpent: Int) =
leadsTo.maxOf { valves.getValue(it).countPotentialGain(newPressure, remainingMinutes - timeSpent) }
return if (flowRate == 0 || this in openValves) {
maxPotentialGain(timeSpent = 1)
} else {
if (remainingMinutes == 1) {
// Cannot open and move at the same time, always open it
openValves.add(this)
val potentialWithThisOpen = newPressure + openValves.releasingPressure()
openValves.remove(this)
potentialWithThisOpen
} else {
val potentialWithThisClosed = maxPotentialGain(timeSpent = 1)
val releasedWhileOpening = openValves.releasingPressure()
openValves.add(this)
val potentialWithThisOpen = releasedWhileOpening + maxPotentialGain(timeSpent = 2)
openValves.remove(this)
max(potentialWithThisClosed, potentialWithThisOpen)
}
}.also { cache[cacheKey] = it - releasedPressure; }
}
return valves.getValue("AA").countPotentialGain(0, 30)
}
fun part2(input: List<String>): Int {
val valves = input.toValves()
val cache = HashMap<Triple<Long, Int, Long>, Int>()
fun List<String>.cartesianProduct(other: List<String>) = flatMap { thisIt ->
other.map { otherIt ->
valves.getValue(thisIt) to valves.getValue(otherIt)
}
}
val openValves = mutableSetOf<Valve>()
fun Pair<Valve, Valve>.countPotentialGain(releasedPressure: Int = 0, minute: Int = 1): Int {
val newPressure = releasedPressure + openValves.releasingPressure()
check(minute < 26)
val (human, elephant) = this
val cacheKey =
Triple(human.id or elephant.id, minute, openValves.fold(0L) { acc, v -> acc or v.id })
cache[cacheKey]?.let {
return releasedPressure + it
}
fun maxPotentialGainIfHumanMoves() = human.leadsTo.maxOf {
(valves.getValue(it) to elephant).countPotentialGain(
newPressure,
minute + 1
)
}
fun maxPotentialGainIfElephantMoves() = elephant.leadsTo.maxOf {
(human to valves.getValue(it)).countPotentialGain(
newPressure,
minute + 1
)
}
fun maxPotentialGainIfNeitherMoves() = countPotentialGain(newPressure, minute + 1)
fun maxPotentialGainIfBothMove() = (human.leadsTo.cartesianProduct(elephant.leadsTo)).maxOf {
it.countPotentialGain(
newPressure,
minute + 1
)
}
return if (minute == 25) {
// Cannot open and move at the same time, always open it
val humanAdded = openValves.add(human)
val elephantAdded = openValves.add(elephant)
val potentialWithBothOpen = newPressure + openValves.releasingPressure()
if (elephantAdded)
openValves.remove(elephant)
if (humanAdded)
openValves.remove(human)
potentialWithBothOpen
} else {
val humanCanOpen = human.flowRate != 0 && human !in openValves
val elephantCanOpen = elephant.flowRate != 0 && elephant !in openValves
val potentialWithNeitherOpening = maxPotentialGainIfBothMove()
when {
!humanCanOpen && !elephantCanOpen -> potentialWithNeitherOpening
!humanCanOpen && elephantCanOpen -> {
openValves.add(elephant)
val potentialWithElephantOpening = maxPotentialGainIfHumanMoves()
openValves.remove(elephant)
max(potentialWithNeitherOpening, potentialWithElephantOpening)
}
humanCanOpen && !elephantCanOpen -> {
openValves.add(human)
val potentialWithHumanOpening = maxPotentialGainIfElephantMoves()
openValves.remove(human)
max(potentialWithNeitherOpening, potentialWithHumanOpening)
}
else -> {
val potentialWithEitherOrBothOpening = if (human == elephant) {
// Human and Elephant are the same, just assume the human keeps opening
openValves.add(human)
val potentialWithHumanOpening = maxPotentialGainIfElephantMoves()
openValves.remove(human)
potentialWithHumanOpening
} else {
openValves.add(elephant)
val potentialWithElephantOpening = maxPotentialGainIfHumanMoves()
openValves.remove(elephant)
openValves.add(human)
val potentialWithHumanOpening = maxPotentialGainIfElephantMoves()
openValves.remove(human)
openValves.add(human)
openValves.add(elephant)
val potentialWithBothOpening = maxPotentialGainIfNeitherMoves()
openValves.remove(elephant)
openValves.remove(human)
val potentialWithEitherMoving = max(potentialWithHumanOpening, potentialWithElephantOpening)
max(potentialWithEitherMoving, potentialWithBothOpening)
}
max(potentialWithNeitherOpening, potentialWithEitherOrBothOpening)
}
}
}.also { cache[cacheKey] = it - releasedPressure }
}
return (valves.getValue("AA") to valves.getValue("AA")).countPotentialGain().also { println(it) }
}
val testInput = readInput("Day16_test")
check(part1(testInput) == 1651)
check(part2(testInput) == 1707)
val input = readInput("Day16")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 2215ea22a87912012cf2b3e2da600a65b2ad55fc | 7,829 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/com/ginsberg/advent2021/Day25.kt | tginsberg | 432,766,033 | false | {"Kotlin": 92813} | /*
* Copyright (c) 2021 by <NAME>
*/
/**
* Advent of Code 2021, Day 25 - Sea Cucumber
* Problem Description: http://adventofcode.com/2021/day/25
* Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2021/day25/
*/
package com.ginsberg.advent2021
class Day25(input: List<String>) {
private val initialState: Map<Point2d, Char> = parseInput(input)
private val gridMax: Point2d = Point2d(input.first().lastIndex, input.lastIndex)
fun solvePart1(): Int =
generateSequence(initialState) { it.next() }
.zipWithNext()
.indexOfFirst { it.first == it.second } + 1
private fun Map<Point2d, Char>.next(): Map<Point2d, Char> {
val nextMap = this.toMutableMap()
filterValues { it == '>' }
.keys
.map { it to it.east() }
.filter { it.second !in this }
.forEach { (prev, east) ->
nextMap.remove(prev)
nextMap[east] = '>'
}
nextMap.filterValues { it == 'v' }
.keys
.map { it to it.south() }
.filter { it.second !in nextMap }
.forEach { (prev, south) ->
nextMap.remove(prev)
nextMap[south] = 'v'
}
return nextMap
}
private fun Point2d.east(): Point2d =
if (x == gridMax.x) Point2d(0, y) else Point2d(x + 1, y)
private fun Point2d.south(): Point2d =
if (y == gridMax.y) Point2d(x, 0) else Point2d(x, y + 1)
private fun parseInput(input: List<String>): Map<Point2d, Char> =
buildMap {
input.forEachIndexed { y, row ->
row.forEachIndexed { x, c ->
if (c != '.') put(Point2d(x, y), c)
}
}
}
}
| 0 | Kotlin | 2 | 34 | 8e57e75c4d64005c18ecab96cc54a3b397c89723 | 1,798 | advent-2021-kotlin | Apache License 2.0 |
src/year2021/07/Day07.kt | Vladuken | 573,128,337 | false | {"Kotlin": 327524, "Python": 16475} | package year2021.`07`
import readInput
import kotlin.math.abs
fun main() {
fun calculateFullAmountOfFuelToPosition(
position: Int,
map: Map<Int, Int>,
modifier: (Int) -> Int
): Int {
return map.keys.sumOf {
modifier(abs(it - position)) * map[it]!!
}
}
fun solution(
input: List<String>,
modifier: (Int) -> Int
): Int {
val mappedResult = input.first()
.split(",")
.map { it.toInt() }
.groupBy { it }
.mapValues { it.value.count() }
return (mappedResult.keys.min()..mappedResult.keys.max())
.minOf { calculateFullAmountOfFuelToPosition(it, mappedResult, modifier) }
}
fun part1(input: List<String>): Int = solution(input) { n -> n }
fun part2(input: List<String>): Int = solution(input) { n -> n * (n + 1) / 2 }
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day07_test")
val part1Test = part1(testInput)
println(part1Test)
check(part1Test == 37)
val input = readInput("Day07")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 5 | c0f36ec0e2ce5d65c35d408dd50ba2ac96363772 | 1,190 | KotlinAdventOfCode | Apache License 2.0 |
src/net/sheltem/aoc/y2023/Day15.kt | jtheegarten | 572,901,679 | false | {"Kotlin": 178521} | package net.sheltem.aoc.y2023
suspend fun main() {
Day15().run()
}
class Day15 : Day<Long>(1320, 145) {
override suspend fun part1(input: List<String>): Long = input[0].split(",").sumOf { it.hash() }.toLong()
override suspend fun part2(input: List<String>): Long = part2(input[0])
}
private fun String.hash(): Int =
this.fold(0) { acc, char ->
(acc + char.code).times(17).mod(256)
}
private fun part2(input: String): Long {
val boxes = (0 until 256).associateWith { mutableListOf<Pair<String, Int>>() }
input.split(",").forEach { instruction ->
val label = if (instruction.contains("-")) instruction.dropLast(1) else instruction.takeWhile { it.isLetter() }
val labelHash = label.hash()
when {
instruction.contains("-") -> boxes[labelHash]!!.removeAll { it.first == label }
boxes[labelHash]!!.any { it.first == label } -> boxes[labelHash]!!.replaceAll { old -> if (old.first == label) label to instruction.takeLast(1).toInt() else old }
else -> boxes[labelHash]!!.add(label to instruction.takeLast(1).toInt())
}
}
boxes.entries.filter{ it.value.isNotEmpty() }.forEach { entry ->
println("${entry.key} => ${entry.value.foldIndexed(0) { lensIndex, innerAcc, lens ->
innerAcc + ((entry.key + 1) * (lensIndex + 1) * lens.second)
}} (${entry.value.joinToString(", ")})")
}
return boxes.entries.foldIndexed(0) { index, acc, box ->
acc + (index + 1) * box.value.foldIndexed(0) { lensIndex, innerAcc, lens ->
innerAcc + ((lensIndex + 1) * lens.second)
}
}
}
| 0 | Kotlin | 0 | 0 | ac280f156c284c23565fba5810483dd1cd8a931f | 1,639 | aoc | Apache License 2.0 |
src/main/kotlin/com/hj/leetcode/kotlin/problem31/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem31
/**
* LeetCode page: [31. Next Permutation](https://leetcode.com/problems/next-permutation/);
*/
class Solution {
/* Complexity:
* Time O(N) and Space O(1) where N is the size of nums;
*/
fun nextPermutation(nums: IntArray): Unit {
val leftIndex = findIndexOfFirstDecreaseFromEnd(nums)
val decreaseNotFound = leftIndex == -1
if (decreaseNotFound) {
nums.reverse(nums.indices)
return
}
val indexSwap = findIndexOfFirstHigherFromEnd(nums[leftIndex], nums, leftIndex + 1)
nums.swap(leftIndex, indexSwap)
nums.reverse(leftIndex + 1..nums.lastIndex)
}
private fun findIndexOfFirstDecreaseFromEnd(nums: IntArray): Int {
for (index in nums.lastIndex - 1 downTo 0) {
if (nums[index] < nums[index + 1]) {
return index
}
}
return -1
}
private fun IntArray.reverse(range: IntRange) {
var leftIndex = range.first
var rightIndex = range.last
while (leftIndex < rightIndex) {
swap(leftIndex, rightIndex)
leftIndex++
rightIndex--
}
}
private fun IntArray.swap(index: Int, withIndex: Int) {
this[index] = this[withIndex].also { this[withIndex] = this[index] }
}
private fun findIndexOfFirstHigherFromEnd(target: Int, sortedDescending: IntArray, downToIndex: Int): Int {
val higher = target + 1
var leftIndex = downToIndex
var rightIndex = sortedDescending.lastIndex
while (leftIndex <= rightIndex) {
val midIndex = (leftIndex + rightIndex) ushr 1
val mid = sortedDescending[midIndex]
if (mid >= higher) leftIndex = midIndex + 1 else rightIndex = midIndex - 1
}
val higherNotFound = sortedDescending[rightIndex] < higher
return if (higherNotFound) -1 else rightIndex
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 1,969 | hj-leetcode-kotlin | Apache License 2.0 |
src/main/kotlin/tr/emreone/adventofcode/days/Day2.kt | EmRe-One | 434,793,519 | false | {"Kotlin": 44202} | package tr.emreone.adventofcode.days
object Day2 {
fun part1(input: List<String>): Int {
val regex = """^(?<length>\d+)x(?<width>\d+)x(?<height>\d+)$""".toRegex()
return input.sumOf { line ->
val (l, w, h) = regex.find(line)?.destructured!!
val side1 = l.toInt() * w.toInt()
val side2 = w.toInt() * h.toInt()
val side3 = h.toInt() * l.toInt()
2 * side1 + 2 * side2 + 2 * side3 + minOf(side1, side2, side3)
}
}
fun part2(input: List<String>): Int {
val regex = """^(?<length>\d+)x(?<width>\d+)x(?<height>\d+)$""".toRegex()
return input.sumOf { line ->
val (l, w, h) = regex.find(line)?.destructured!!
val lengths = listOf(l.toInt(), w.toInt(), h.toInt()).sorted()
val wrapRibbon = 2 * lengths[0] + 2 * lengths[1]
val bowRibbon = lengths[0] * lengths[1] * lengths[2]
wrapRibbon + bowRibbon
}
}
}
| 0 | Kotlin | 0 | 0 | 57f6dea222f4f3e97b697b3b0c7af58f01fc4f53 | 987 | advent-of-code-2015 | Apache License 2.0 |
src/main/kotlin/Day2.kt | mikegehard | 114,013,792 | false | null | import kotlin.math.absoluteValue
data class Spreadsheet(private val rows: List<Row>) {
companion object {
fun from(s: String): Spreadsheet = Spreadsheet(
s.split("\n")
.filter { it.isNotBlank() }
.map { Row.from(it) }
)
}
fun checksum(rowCalculation: (Row) -> Int) = rows.map(rowCalculation).sum()
}
data class Row(val cells: List<Cell>) {
companion object {
fun from(s: String): Row = Row(
s.split(" ")
.map(Integer::parseInt)
.sorted()
.map { Cell(it) }
)
}
val difference: Int
get() = (cells.first().value - cells.last().value).absoluteValue
val division: Int
get() = permutations()
.first { (a, b) -> a.value.rem(b.value) == 0 }
.run { first.value / second.value }
}
data class Cell(val value: Int)
fun Row.permutations(): List<Pair<Cell, Cell>> = cells
.associate { key -> key to cells.filter { it != key } }
.map { (cell, others) -> others.map { Pair(cell, it) } }
.flatten()
| 0 | Kotlin | 0 | 1 | d58268847a7dba42d5e7a45b9eb59078711ca53d | 1,172 | AdventOfCode2017Kotlin | MIT License |
src/main/kotlin/com/lucaszeta/adventofcode2020/day09/day09.kt | LucasZeta | 317,600,635 | false | null | package com.lucaszeta.adventofcode2020.day09
import com.lucaszeta.adventofcode2020.ext.getResourceAsText
import java.lang.IllegalArgumentException
fun main() {
val input = getResourceAsText("/day09/xmas-number-series.txt")
.split("\n")
.filter { it.isNotEmpty() }
.map { it.toLong() }
val invalidNumber = findNumberNotSumOfPrevious(input, 25)
println("First number not result of sum of the previous ones: $invalidNumber")
val encryptionWeakness = calculateXmasEncryptionWeakness(
findNumbersThatSumToTarget(input, invalidNumber)
)
println("Encryption weakness: $encryptionWeakness")
}
fun findNumbersThatSumToTarget(numbers: List<Long>, targetNumber: Long): List<Long> {
for (i in 0 until numbers.size - 1) {
for (j in (i + 1) until numbers.size) {
val numbersInRange = numbers.slice(i..j)
if (numbersInRange.reduce(Long::plus) == targetNumber) {
return numbersInRange
}
}
}
throw IllegalArgumentException("No numbers in list sum to $targetNumber")
}
fun calculateXmasEncryptionWeakness(numberList: List<Long>) =
(numberList.minOrNull() ?: 0) +
(numberList.maxOrNull() ?: 0)
fun findNumberNotSumOfPrevious(numbers: List<Long>, preamble: Int): Long {
for (index in preamble until numbers.size) {
val previousNumbersGroup = numbers.slice((index - preamble) until index)
val currentNumber = numbers[index]
val isResultOfSumOfPrevious = previousNumbersGroup.any { previousNumber ->
previousNumbersGroup
.filter { it != previousNumber }
.contains(currentNumber - previousNumber)
}
if (!isResultOfSumOfPrevious) {
return currentNumber
}
}
throw IllegalArgumentException("All numbers are sum of the previous $preamble")
}
| 0 | Kotlin | 0 | 1 | 9c19513814da34e623f2bec63024af8324388025 | 1,891 | advent-of-code-2020 | MIT License |
day14/Part2.kt | anthaas | 317,622,929 | false | null | import java.io.File
fun main(args: Array<String>) {
val input = File("input.txt").bufferedReader().use { it.readText() }.split("\n")
val mem = mapOf<Long, Long>().toMutableMap()
var mask = ""
input.map {
when {
it.startsWith("mask") -> mask = it.split(" = ")[1]
it.startsWith("mem") -> it.split(" = ")
.let { (index, value) -> index.replace(Regex("""mem\[|\]"""), "").toInt() to value.toLong() }
.let { (index, value) -> getAllIndexesByMask(index, mask).map { mem.put(it, value) } }
else -> error("unknown op")
}
}
println(mem.values.sum())
}
fun getAllIndexesByMask(index: Int, mask: String): List<Long> {
val binaryString = Integer.toBinaryString(index)
val binaryIndex = "0".repeat(mask.length - binaryString.length) + binaryString
val masked = binaryIndex.zip(mask) { c, m ->
when (m) {
'0' -> c
else -> m
}
}.toCharArray()
return getAllCombinations(String(masked)).map { it.toLong(2) }
}
private fun getAllCombinations(entry: String): List<String> {
if ('X' !in entry) {
return listOf(entry)
}
return getAllCombinations(entry.replaceFirst('X', '0')) + getAllCombinations(entry.replaceFirst('X', '1'))
}
| 0 | Kotlin | 0 | 0 | aba452e0f6dd207e34d17b29e2c91ee21c1f3e41 | 1,300 | Advent-of-Code-2020 | MIT License |
src/Day12.kt | lassebe | 573,423,378 | false | {"Kotlin": 33148} | fun main() {
fun buildGraph(input: List<String>): Triple<MutableMap<Pair<Int, Int>, List<Pair<Int, Int>>>, MutableMap<Pair<Int, Int>, Int>, Pair<Pair<Int, Int>,Pair<Int,Int>>> {
val edges = mutableMapOf<Pair<Int, Int>, List<Pair<Int, Int>>>()
val cost = mutableMapOf<Pair<Int, Int>, Int>()
val chunked = input.map { it.chunked(1) }
var start = Pair(0, 0)
var end = Pair(0, 0)
chunked.mapIndexed { i, line ->
List(line.size) { j ->
val current = Pair(i, j)
if (line[j] == "S") {
start = current
cost[start] = 0
} else if (line[j] == "E") {
end = current
cost[current] = 25
} else {
cost[current] = (line[j].toCharArray().first()).code - 97
}
if (i > 0) {
edges[current] = edges.getOrDefault(current, emptyList()) + Pair(i - 1, j)
}
if (j > 0) {
edges[current] = edges.getOrDefault(current, emptyList()) + Pair(i, j - 1)
}
if (i != chunked.size - 1) {
edges[current] = edges.getOrDefault(current, emptyList()) + Pair(i + 1, j)
}
if (j != line.size - 1) {
edges[current] = edges.getOrDefault(current, emptyList()) + Pair(i, j + 1)
}
}
}
return Triple(edges, cost, Pair(start,end))
}
fun bfs(
start: Pair<Int, Int>,
end: Pair<Int, Int>,
edges: Map<Pair<Int, Int>, List<Pair<Int, Int>>>,
cost: Map<Pair<Int, Int>, Int>
): Int {
val parent = mutableMapOf<Pair<Int, Int>, Pair<Int, Int>>()
val visited = mutableSetOf<Pair<Int, Int>>()
val queue = mutableListOf<Pair<Int, Int>>()
queue.add(start)
while (queue.isNotEmpty()) {
val next = queue.removeFirst()
if (visited.contains(next))
continue
visited.add(next)
if (next == end) {
break
}
val actualNeighbours = edges.getOrDefault(next, emptyList()).filter {
cost[it]!! <= cost[next]!! + 1
}
if (actualNeighbours.isEmpty()) throw IllegalStateException("no neighbours!")
actualNeighbours.forEach {
if (!queue.contains(it)) {
if (parent[it] == null)
parent[it] = next
queue.add(it)
}
}
}
val path = mutableListOf(end)
while (path.last() != start) {
val parentNode = parent[path.last()]
path.add(parentNode!!)
}
return path.size - 1
}
fun bfsPredicate(
start: Pair<Int, Int>,
end: (Pair<Int, Int>) -> Boolean,
edges: Map<Pair<Int, Int>, List<Pair<Int, Int>>>,
cost: Map<Pair<Int, Int>, Int>
): Int {
val parent = mutableMapOf<Pair<Int, Int>, Pair<Int, Int>>()
val visited = mutableSetOf<Pair<Int, Int>>()
val queue = mutableListOf<Pair<Int, Int>>()
var endNode = Pair(-1, -1)
queue.add(start)
while (queue.isNotEmpty()) {
val next = queue.removeFirst()
if (visited.contains(next))
continue
visited.add(next)
if (end(next)) {
endNode = next
break
}
val possibleNeighbours = edges.getOrDefault(next, emptyList())
val actualNeighbours = possibleNeighbours.filter {
cost[next]!! - 1 <= cost[it]!! && it != start
}
if (actualNeighbours.isEmpty()) throw IllegalStateException("no neighbours!")
actualNeighbours.forEach {
if (!queue.contains(it)) {
if (parent[it] == null)
parent[it] = next
queue.add(it)
}
}
}
val path = mutableListOf(endNode)
while (path.last() != start) {
val parentNode = parent[path.last()]
path.add(parentNode!!)
}
return path.size - 1
}
fun part1(input: List<String>): Int {
val (edges, cost, startEnd) = buildGraph(input)
val (start,end) = startEnd
return bfs(start, end, edges, cost)
}
fun part2(input: List<String>): Int {
val (edges, cost, startEnd) = buildGraph(input)
val (_,end) = startEnd
return bfsPredicate(end, { node -> cost[node] == 0 }, edges, cost)
}
val testInput = readInput("Day12_test")
expect(31, part1(testInput))
val input = readInput("Day12")
println(part1(input))
expect(408, part1(input))
expect(
29,
part2(testInput)
)
expect(
399,
part2(input)
)
println(part2(input))
} | 0 | Kotlin | 0 | 0 | c3157c2d66a098598a6b19fd3a2b18a6bae95f0c | 5,048 | advent_of_code_2022 | Apache License 2.0 |
src/Day03.kt | bigtlb | 573,081,626 | false | {"Kotlin": 38940} | fun main() {
fun itemSum(items: Iterable<Char>): Int =
items.map { "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".indexOf(it) + 1 }.sum()
fun part1(input: List<String>): Int =
itemSum(input.map {
it.toCharArray(endIndex = it.length / 2).intersect(it.toCharArray(it.length / 2).toSet()).first()
})
fun part2(input: List<String>): Int =
itemSum(input.map { it.toSet() }.chunked(3).fold(listOf<Char>()) { acc, cur ->
acc.plus(cur.reduce { a, b ->
a.intersect(b)
}.first())
})
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
val part1 = part1(testInput)
check(part1 == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | d8f76d3c75a30ae00c563c997ed2fb54827ea94a | 886 | aoc-2022-demo | Apache License 2.0 |
src/day16/Solution.kt | chipnesh | 572,700,723 | false | {"Kotlin": 48016} | package day16
import readInput
fun main() {
fun part1(input: List<String>): Int {
return Valves
.parse(input)
.mostPressure()
}
fun part2(input: List<String>): Int {
return -1
}
val input = readInput("test")
//val input = readInput("prod")
println(part1(input))
println(part2(input))
}
data class Valves(
val defs: List<ValveDef>,
val byId: Map<String, ValveDef>
) {
val valves get() = defs.map { Valve.of(it, byId) }
fun mostPressure(): Int {
val start = valves.first()
val released = mutableSetOf<String>()
val current = start
val leads = ArrayDeque<ValveDef>()
return 0
}
companion object {
fun parse(input: List<String>): Valves {
val defs = input.map(ValveDef::parse)
val byId = defs.associateBy(ValveDef::id)
return Valves(defs, byId)
}
}
}
data class Valve(
val id: String,
val rate: Int,
val tunnelsTo: List<String>,
val byId: Map<String, ValveDef>
) {
//val leads get() = tunnelsTo.map {
// Valve(it)
//}
companion object {
fun of(def: ValveDef, byId: Map<String, ValveDef>): Valve {
return Valve(def.id, def.rate, def.leads, byId)
}
}
}
data class ValveDef(
val id: String,
val rate: Int,
val leads: List<String>
) {
companion object {
fun parse(input: String): ValveDef {
val nameString = input.substringAfter("Valve ")
val id = nameString.take(2)
val rateString = nameString.drop(2).substringAfter(" has flow rate=")
val rate = rateString.substringBefore(";")
val leads = rateString.substring(rateString.indexOf(";")).substringAfter(" tunnels lead to valves ").split(", ")
return ValveDef(id, rate.toInt(), leads)
}
}
} | 0 | Kotlin | 0 | 1 | 2d0482102ccc3f0d8ec8e191adffcfe7475874f5 | 1,909 | AoC-2022 | Apache License 2.0 |
2021/src/Day04.kt | Bajena | 433,856,664 | false | {"Kotlin": 65121, "Ruby": 14942, "Rust": 1698, "Makefile": 454} | // https://adventofcode.com/2021/day/4
fun main() {
class Table(size: Int, tableNumbers : Collection<Int>) {
val size = size
var won = false
val unselectedNumbers : MutableList<Int> = tableNumbers as MutableList<Int>
val numberToPosition = mutableMapOf<Int, Pair<Int, Int>>()
val selectedPositions = mutableListOf<Pair<Int, Int>>()
init {
unselectedNumbers.forEachIndexed { index, value ->
numberToPosition[value] = Pair(index / size, index % size)
}
}
fun selectNumber(number : Int) : Int {
val position = numberToPosition[number]
if (position != null) {
selectedPositions.add(position)
unselectedNumbers.remove(number)
val value = checkWinningValue(number, position)
if (value > -1) won = true
return value
}
return -1
}
fun checkWinningValue(lastSelectedNumber : Int, lastSelectedPosition : Pair<Int, Int>) : Int {
if (isColumnFull(lastSelectedPosition.second) || isRowFull(lastSelectedPosition.first)) {
return unselectedNumbers.sum() * lastSelectedNumber
}
return -1
}
fun isColumnFull(column : Int): Boolean {
for (i in 0 until size) {
if (selectedPositions.indexOf(Pair(i, column)) > -1) continue
return false
}
return true
}
fun isRowFull(row : Int): Boolean {
for (i in 0 until size) {
if (selectedPositions.indexOf(Pair(row, i)) > -1) continue
return false
}
return true
}
}
fun part1() {
var numbers : Array<Int> = arrayOf()
var tables = mutableListOf<Table>()
var currentTableNumbers = mutableListOf<Int>()
for (line in readInput("Day04")) {
if (numbers.isEmpty()) {
numbers = line.split(",").map { it.toInt() }.toTypedArray()
continue
}
if (line.isEmpty()) {
// First empty line after numbers
if (currentTableNumbers.isEmpty()) continue
tables.add(Table(5, currentTableNumbers))
currentTableNumbers = mutableListOf<Int>()
continue
}
currentTableNumbers.addAll(line.split(" ").filter { it != "" }.map { it.toInt() })
}
tables.add(Table(5, currentTableNumbers))
numbers.forEach { number ->
tables.forEach { table ->
val result = table.selectNumber(number)
if (result > -1) {
println(result)
return
}
}
}
}
fun part2() {
var numbers : Array<Int> = arrayOf()
var tables = mutableListOf<Table>()
var currentTableNumbers = mutableListOf<Int>()
for (line in readInput("Day04")) {
if (numbers.isEmpty()) {
numbers = line.split(",").map { it.toInt() }.toTypedArray()
continue
}
if (line.isEmpty()) {
// First empty line after numbers
if (currentTableNumbers.isEmpty()) continue
tables.add(Table(5, currentTableNumbers))
currentTableNumbers = mutableListOf<Int>()
continue
}
currentTableNumbers.addAll(line.split(" ").filter { it != "" }.map { it.toInt() })
}
tables.add(Table(5, currentTableNumbers))
var winningResult = -1
numbers.forEach { number ->
tables.filter { !it.won }.forEach { table ->
val result = table.selectNumber(number)
if (result > -1) {
winningResult = result
}
}
}
println(winningResult)
}
part1()
part2()
}
| 0 | Kotlin | 0 | 0 | a5ca56b7ac8d9d48f82dc079c8ea0cf06d17109a | 3,464 | advent-of-code | Apache License 2.0 |
src/main/kotlin/org/sj/aoc2022/day06/SignalScanner.kt | sadhasivam | 573,168,428 | false | {"Kotlin": 10910} | package org.sj.aoc2022.day06
import org.sj.aoc2022.util.readInput
fun String.hasUniqueChars(): Boolean = this.toCharArray().distinct().count() != length
fun scanSignal(input: String, marker: Int): Int {
var signal = ""
var count = 0
for (char in input.asSequence()) {
signal += char
count++
if (count > 3 && signal.length == marker && signal.hasUniqueChars()) {
signal = signal.drop(1)
}
if (signal.length == marker) {
return count
}
}
return -1
}
data class SignalIO(val marker: Int, val output: Int)
fun main() {
val basePath = "/org/sj/aoc2022/day06/"
var testSignalData = mapOf(
"mjqjpqmgbljsphdztnvjfqwrcgsmlb" to listOf(SignalIO(4, 7), SignalIO(14, 19)),
"bvwbjplbgvbhsrlpgdmjqwftvncz" to listOf(SignalIO(4, 5), SignalIO(14, 23)),
"nppdvjthqldpwncqszvftbrmjlhg" to listOf(SignalIO(4, 6), SignalIO(14, 23)),
"nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg" to listOf(SignalIO(4, 10), SignalIO(14, 29)),
"zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw" to listOf(SignalIO(4, 11), SignalIO(14, 26))
)
testSignalData.forEach { (signal, value) ->
for (sio in value) {
check(scanSignal(signal, sio.marker) == sio.output)
return@forEach
}
}
val signalData = readInput("${basePath}Day06")
for (signal in signalData) {
check(scanSignal(signal, 4) == 1542)
check(scanSignal(signal, 14) == 3153)
}
}
| 0 | Kotlin | 0 | 0 | 7a1ceaddbe7e72bad0e9dfce268387d333b62143 | 1,495 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/Day04.kt | hufman | 573,586,479 | false | {"Kotlin": 29792} | fun main() {
fun parseRange(input: String): IntRange {
val parts = input.split('-')
.mapNotNull { it.toIntOrNull() }
return IntRange(parts[0], parts[1])
}
fun parse(input: List<String>): List<Pair<IntRange, IntRange>> {
return input
.map { it.split(',') }
.filter { parts -> parts.size == 2}
.map { parts -> Pair(parseRange(parts[0]), parseRange(parts[1])) }
}
fun part1(input: List<String>): Int {
return parse(input).count { (left, right) ->
left.all { right.contains(it) } ||
right.all { left.contains(it) }
}
}
fun part2(input: List<String>): Int {
return parse(input).count { (left, right) ->
left.any { right.contains(it) } ||
right.any { left.contains(it) }
}
}
// 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 | 1bc08085295bdc410a4a1611ff486773fda7fcce | 970 | aoc2022-kt | Apache License 2.0 |
src/main/kotlin/com/txq/graph/graph.kt | flyingyizi | 124,735,014 | false | null | package com.txq.graph
data class Graph (val numVertices: Int, val isDirection:Boolean=true) {
val edage = AdjacencyMatrix(numVertices)
val vertex = arrayOfNulls<String>( numVertices)
val isTrav = arrayOfNulls<Boolean>( numVertices)
//https://www.programiz.com/dsa/graph-dfs
//Depth First Search
fun DFS(start: String) {
vertex.find { it==start }?.let { DFS(it) }
}
fun dfsR(start: Int) {
isTrav[start] = true
print(start.toString() + " ")
edage.adjMatrix[start].forEachIndexed { index, i ->
if ( edage.isEdge(start,index) ) {
isTrav[index]?.let { if (!it) dfsR(index) } ?: dfsR(index)
}
}
}
/*
* BFS pseudocode Breadth First Search
create a queue Q
mark v as visited and put v into Q
while Q is non-empty
remove the head u of Q
mark and enqueue all (unvisited) neighbours of u
*/
fun CreateByConsloe(){
var input :List<String>
do {
println("输入图中各顶点信息, 请输入${numVertices}个顶点,以空格分开:")
input= readLine()!!.split(' ')
if (input.size == numVertices) {
for ( i in 0 until numVertices) {
vertex[i] = input[i]
}
break
}
} while (true)
do {
println("输入构成各边的顶点与权值. start end weight :")
val input = readLine()!!.split(' ')
if(input.size!=3) break
var ii = -1
var jj=-1
for ( i in 0 until numVertices) {
if ( input[0] == vertex[i] ) ii=i
if ( input[1] == vertex[i] ) jj=i
}
if (ii==-1 || jj==-1 ) {
println("请输入正确的顶点 startV(${input[0]}), endV(${input[1]})不合法")
continue
}
edage.addEdge(ii,jj,input[2].toInt() )
if (!isDirection) edage.addEdge(jj,ii,input[2].toInt() )
} while (true)
}
fun cleanEdage() {
edage.clean()
}
override fun toString(): String {
val s = StringBuilder()
val title = StringBuilder()
vertex.forEach { title.append(it + " ") }
println(" ${title}")
for (i in 0 until numVertices) {
s.append( vertex[i] + ": ")
for (j in edage.adjMatrix[i]) {
s.append( j/*(if (j>0) j else 0)*/.toString() + " ")
}
s.append("\n")
}
return s.toString()
}
}
fun main(args: Array<String>) {
//val g = AdjacencyMatrix(4)
val g = Graph(4)
g.CreateByConsloe()
println(g.toString())
var input :List<String>
do {
println("DFS 路径查找,输入图中起始顶点:")
input= readLine()!!.split(' ')
g.DFS(input[0])
} while (true)
}
| 0 | Kotlin | 0 | 0 | f4ace2d018ae8a93becaee85b7db882098074b7a | 2,912 | helloworldprovider | Apache License 2.0 |
src/main/kotlin/io/github/pshegger/aoc/y2022/Y2022D2.kt | PsHegger | 325,498,299 | false | null | package io.github.pshegger.aoc.y2022
import io.github.pshegger.aoc.common.BaseSolver
class Y2022D2 : BaseSolver() {
override val year = 2022
override val day = 2
override fun part1(): Int {
fun EncryptedSymbol.decrypt() = when (this) {
EncryptedSymbol.X -> Symbol.Rock
EncryptedSymbol.Y -> Symbol.Paper
EncryptedSymbol.Z -> Symbol.Scissors
}
return parseInput().fold(0) { score, (enemy, me) ->
val decrypted = me.decrypt()
score + (resultTable[enemy]?.get(decrypted) ?: 0) + decrypted.pointValue
}
}
override fun part2(): Int {
fun EncryptedSymbol.decrypt(enemy: Symbol): Symbol = when (this) {
EncryptedSymbol.X -> resultTable[enemy]!!.entries.first { it.value == LOSE_SCORE }.key
EncryptedSymbol.Y -> resultTable[enemy]!!.entries.first { it.value == DRAW_SCORE }.key
EncryptedSymbol.Z -> resultTable[enemy]!!.entries.first { it.value == WIN_SCORE }.key
}
return parseInput().fold(0) { score, (enemy, me) ->
val decrypted = me.decrypt(enemy)
score + (resultTable[enemy]?.get(decrypted) ?: 0) + decrypted.pointValue
}
}
private fun parseInput() = readInput {
readLines()
.map { line ->
val (enemyChar, myChar) = line.split(' ', limit = 2)
val enemySymbol = when (enemyChar) {
"A" -> Symbol.Rock
"B" -> Symbol.Paper
"C" -> Symbol.Scissors
else -> throw IllegalArgumentException("Unknown symbol: $enemyChar")
}
val mySymbol = when (myChar) {
"X" -> EncryptedSymbol.X
"Y" -> EncryptedSymbol.Y
"Z" -> EncryptedSymbol.Z
else -> throw IllegalArgumentException("Unknown symbol: $enemyChar")
}
Pair(enemySymbol, mySymbol)
}
}
private enum class Symbol(val pointValue: Int) {
Rock(1), Paper(2), Scissors(3)
}
private enum class EncryptedSymbol {
X, Y, Z
}
companion object {
private const val LOSE_SCORE = 0
private const val DRAW_SCORE = 3
private const val WIN_SCORE = 6
private val resultTable = mapOf(
Symbol.Rock to mapOf(
Symbol.Rock to DRAW_SCORE,
Symbol.Paper to WIN_SCORE,
Symbol.Scissors to LOSE_SCORE,
),
Symbol.Paper to mapOf(
Symbol.Rock to LOSE_SCORE,
Symbol.Paper to DRAW_SCORE,
Symbol.Scissors to WIN_SCORE,
),
Symbol.Scissors to mapOf(
Symbol.Rock to WIN_SCORE,
Symbol.Paper to LOSE_SCORE,
Symbol.Scissors to DRAW_SCORE,
),
)
}
}
| 0 | Kotlin | 0 | 0 | 346a8994246775023686c10f3bde90642d681474 | 2,949 | advent-of-code | MIT License |
src/Day02.kt | RichardLiba | 572,867,612 | false | {"Kotlin": 16347} | fun main() {
val values = mapOf(
//rock
"A" to 1,
//paper
"B" to 2,
//scissors
"C" to 3,
//rock
"X" to 1,
//paper
"Y" to 2,
//scissors
"Z" to 3
)
fun evalWin(round: Pair<String, String>): Int {
return when (round.first) {
"A" -> when (round.second) {
"X" -> 3
"Y" -> 6
"Z" -> 0
else -> 0
}
"B" -> when (round.second) {
"X" -> 0
"Y" -> 3
"Z" -> 6
else -> 0
}
"C" -> when (round.second) {
"X" -> 6
"Y" -> 0
"Z" -> 3
else -> 0
}
else -> 0
}
}
//X- loose, Y-draw, Z-win
fun evalWin2(round: Pair<String, String>): Int {
return when (round.second) {
"X" -> when (round.first) {
"A" -> 3
"B" -> 1
"C" -> 2
else -> 0
} + 0
"Y" -> when (round.first) {
"A" -> 1
"B" -> 2
"C" -> 3
else -> 0
} + 3
"Z" -> when (round.first) {
"A" -> 2
"B" -> 3
"C" -> 1
else -> 0
} + 6
else -> 0
}
}
fun readRounds(input: List<String>): List<Pair<String, String>> {
return input.map { it.split(" ").let { it[0] to it[1] } }
}
fun countPoints(round: Pair<String, String>): Int {
return values[round.second]!! + evalWin(round)
}
fun countPart2(round: Pair<String, String>): Int {
return evalWin2(round)
}
fun part1(input: List<String>): Int {
return readRounds(input).sumOf { countPoints(it) }
}
fun part2(input: List<String>): Int {
return readRounds(input).sumOf { countPart2(it) }
}
val input = readInput("Day02")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 6a0b6b91b5fb25b8ae9309b8e819320ac70616ed | 2,143 | aoc-2022-in-kotlin | Apache License 2.0 |
src/main/kotlin/com/ginsberg/advent2019/Day18.kt | tginsberg | 222,116,116 | false | null | /*
* Copyright (c) 2019 by <NAME>
*/
/**
* Advent of Code 2019, Day 18 - Many-Worlds Interpretation
* Problem Description: http://adventofcode.com/2019/day/18
* Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2019/day18/
*/
package com.ginsberg.advent2019
import java.util.ArrayDeque
class Day18(input: List<String>) {
private val maze = Maze.from(input)
fun solve(): Int =
maze.minimumSteps()
class Maze(private val starts: Set<Point2D>, private val keys: Map<Point2D, Char>, private val doors: Map<Point2D, Char>, private val openSpaces: Set<Point2D>) {
private fun findReachableKeys(from: Point2D, haveKeys: Set<Char> = mutableSetOf()): Map<Char, Pair<Point2D, Int>> {
val queue = ArrayDeque<Point2D>().apply { add(from) }
val distance = mutableMapOf(from to 0)
val keyDistance = mutableMapOf<Char, Pair<Point2D, Int>>()
while (queue.isNotEmpty()) {
val next = queue.pop()
next.neighbors()
.filter { it in openSpaces }
.filterNot { it in distance }
.forEach { point ->
distance[point] = distance[next]!! + 1
val door = doors[point]
val key = keys[point]
if (door == null || door.toLowerCase() in haveKeys) {
if (key != null && key !in haveKeys) {
keyDistance[key] = Pair(point, distance[point]!!)
} else {
queue.add(point)
}
}
}
}
return keyDistance
}
private fun findReachableFromPoints(from: Set<Point2D>, haveKeys: Set<Char>): Map<Char, Triple<Point2D, Int, Point2D>> =
from.map { point ->
findReachableKeys(point, haveKeys).map { entry ->
entry.key to Triple(entry.value.first, entry.value.second, point)
}
}.flatten().toMap()
fun minimumSteps(from: Set<Point2D> = starts,
haveKeys: Set<Char> = mutableSetOf(),
seen: MutableMap<Pair<Set<Point2D>, Set<Char>>, Int> = mutableMapOf()): Int {
val state = Pair(from, haveKeys)
if (state in seen) return seen.getValue(state)
val answer = findReachableFromPoints(from, haveKeys).map { entry ->
val (at, dist, cause) = entry.value
dist + minimumSteps((from - cause) + at, haveKeys + entry.key, seen)
}.min() ?: 0
seen[state] = answer
return answer
}
companion object {
fun from(input: List<String>): Maze {
val starts = mutableSetOf<Point2D>()
val keys = mutableMapOf<Point2D, Char>()
val doors = mutableMapOf<Point2D, Char>()
val openSpaces = mutableSetOf<Point2D>()
input.forEachIndexed { y, row ->
row.forEachIndexed { x, c ->
val place = Point2D(x, y)
if (c == '@') starts += place
if (c != '#') openSpaces += place
if (c in ('a'..'z')) keys[place] = c
if (c in ('A'..'Z')) doors[place] = c
}
}
return Maze(starts, keys, doors, openSpaces)
}
}
}
} | 0 | Kotlin | 2 | 23 | a83e2ecdb6057af509d1704ebd9f86a8e4206a55 | 3,605 | advent-2019-kotlin | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.