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/Day02.kt | rickbijkerk | 572,911,701 | false | {"Kotlin": 31571} | fun main() {
fun part1(input: List<String>): Int {
val draw = 3
val win = 6
val choiceValue = mapOf(
"A" to 1,
"B" to 2,
"C" to 3,
)
val result = input.map {
val opponentPlay = it.split(" ")[0]
val myChoice = it.split(" ")[1].let { char ->
when (char) {
"X" -> return@let "A"
"Y" -> return@let "B"
"Z" -> return@let "C"
else -> {
throw Exception()
}
}
}
if (opponentPlay == myChoice) {
draw + choiceValue[myChoice]!!
} else if (opponentPlay == "A" && myChoice == "B") {
win + choiceValue[myChoice]!!
} else if (opponentPlay == "B" && myChoice == "C") {
win + choiceValue[myChoice]!!
} else if (opponentPlay == "C" && myChoice == "A") {
win + choiceValue[myChoice]!!
} else {
choiceValue[myChoice]!!
}
}
return result.sum()
}
fun lose(opponentPlay: String): String {
return when (opponentPlay) {
"B" -> "A"
"C" -> "B"
"A" -> "C"
else -> throw Exception()
}
}
fun win(opponentPlay: String): String {
return when (opponentPlay) {
"A" -> "B"
"B" -> "C"
"C" -> "A"
else -> throw Exception()
}
}
fun part2(input: List<String>): Int {
val draw = 3
val win = 6
val choiceValue = mapOf(
"A" to 1,
"B" to 2,
"C" to 3,
)
val result = input.map {
val opponentPlay = it.split(" ")[0]
val outcome = it.split(" ")[1]
val myChoice = outcome.let { char ->
when (char) {
"X" -> return@let lose(opponentPlay)
"Y" -> return@let opponentPlay
"Z" -> return@let win(opponentPlay)
else -> throw Exception()
}
}
when (outcome) {
"Y" -> choiceValue[myChoice]!! + draw
"X" -> choiceValue[myChoice]!!
"Z" -> choiceValue[myChoice]!! + win
else -> throw Exception()
}
}
return result.sum()
}
val testInput = readInput("Day02_test")
// test part1
val resultPart1 = part1(testInput)
val expectedPart1 = 15 //Change me
println("Part1\nresult: $resultPart1")
println("expected:$expectedPart1 \n")
check(resultPart1 == expectedPart1)
//Check results part1
val input = readInput("Day02")
println("Part1 ${part1(input)}\n\n")
// test part2
val resultPart2 = part2(testInput)
val expectedPart2 = 12 //Change me
println("Part2\nresult: $resultPart2")
println("expected:$expectedPart2 \n")
check(resultPart2 == expectedPart2)
//Check results part2
println("Part2 ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 817a6348486c8865dbe2f1acf5e87e9403ef42fe | 3,176 | aoc-2022 | Apache License 2.0 |
src/solutionsForBookCrackingTheCodingInterview/stacksAndQueues/MinArrayStack.kt | mrkostua | 120,207,236 | false | null | package solutionsForBookCrackingTheCodingInterview.stacksAndQueues
/**
* @author <NAME>
* @created on 3/21/2018
* "Cracking the Coding Interview" task 3.1, 3.2
*/
/**
* Task 1 :
* Describe how you could use a single array to implement three stacks.
*/
/**
* Solution :
* Fixed-size stack
* If it is fixed-size stack, by creating array and dividing into 3 parts with first and last element(problem is that by deleting form one stack we will crash other stacks indexes)
* Other way (easier) store elements of stack on after next like s1,s2,s3 first element If it is deleted it is set as null and pointer (top) just point to a previous element.
*
* Dynamic stack (stack is growing as long as there is place in array)
* wrong answer -> array size can't be dynamically increased. Solution is to 3 stacks growing independently one of each others and some way to free up array memory after pop().
*
* Solution - is to use stack with StackNode as linkedLists so every element has reference to previous element which in return gives way to add elements of 3 stacks
* one after one and deleting them just by moving topPointer to previous element. One problem -> by deleting inner element of the array leaves free space( solution is to create additional array
* with free spaces indexes and after pushing use places from this array first or move whole array after popping which is bad because of additional time and resource complexity.
*
* if we need only 2 stacks easy choice is to set their top pointers to first and last element and push until p1.pointer == p2.pointer.
*
*
*/
/**
* Task 2 :
*
* How would you design a stack which, in addition to push and pop, also has a function
* min which returns the minimum element? Push, pop and min should all operate in
* O(1) time
*/
/**
* WRONG answer it is mor for finding last element not min.
* Stack need to be implemented over some data structure so in case of array(constant time of find element as first) in case of linkedList(head is top element
* only choice is to iterate through all elements until node.next = null)
*
*/
public class MinArrayStack(initialCapacity: Int = 0) : ArrayStack<Int>(initialCapacity) {
private val minElementStack = ArrayStack<Int>(initialCapacity)
override fun push(item: Int): Int {
if (peek() <= item) {
minElementStack.push(item)
}
return super.push(item)
}
override fun pop(): Int {
val topElement = super.pop()
if (topElement == getMin()) {
minElementStack.pop()
}
return topElement
}
public fun getMin(): Int {
if (minElementStack.isEmpty()) {
return Integer.MAX_VALUE
}
return minElementStack.peek()
}
}
fun main(args: Array<String>) {
}
| 0 | Kotlin | 0 | 0 | bfb7124e93e485bee5ee8c4b69bf9c0a0a532ecf | 2,829 | Cracking-the-Coding-Interview-solutions | MIT License |
kotlin/src/katas/kotlin/leetcode/course_schedule_2/CourseSchedule2.kt | dkandalov | 2,517,870 | false | {"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221} | package katas.kotlin.leetcode.course_schedule_2
import datsok.shouldEqual
import org.junit.Test
/**
* https://leetcode.com/problems/course-schedule-ii
*/
class CourseSchedule2Tests {
@Test fun `find the ordering of courses you should take to finish all courses`() {
findOrder(0, emptyArray()) shouldEqual emptyArray()
findOrder(1, emptyArray()) shouldEqual arrayOf(0)
findOrder(1, arrayOf(arrayOf(0, 0))) shouldEqual emptyArray()
findOrder(2, emptyArray()) shouldEqual arrayOf(1, 0)
findOrder(2, arrayOf(arrayOf(1, 0))) shouldEqual arrayOf(0, 1)
findOrder(2, arrayOf(arrayOf(0, 1))) shouldEqual arrayOf(1, 0)
findOrder(2, arrayOf(arrayOf(0, 1), arrayOf(1, 0))) shouldEqual emptyArray()
findOrder(3, arrayOf(arrayOf(0, 1), arrayOf(1, 2))) shouldEqual arrayOf(2, 1, 0)
findOrder(3, arrayOf(arrayOf(1, 0), arrayOf(2, 1))) shouldEqual arrayOf(0, 1, 2)
findOrder(3, arrayOf(arrayOf(0, 1), arrayOf(0, 2))) shouldEqual arrayOf(2, 1, 0)
findOrder(3, arrayOf(arrayOf(0, 1), arrayOf(1, 2), arrayOf(2, 0))) shouldEqual emptyArray()
findOrder(4, arrayOf(arrayOf(0, 1), arrayOf(0, 2))) shouldEqual arrayOf(3, 2, 1, 0)
}
}
private fun findOrder(numberOfCourses: Int, prerequisites: Array<Array<Int>>): Array<Int> {
val coursesWithoutDependencies = 0.until(numberOfCourses).toHashSet()
prerequisites.forEach { (_, dependantCourse) -> coursesWithoutDependencies -= dependantCourse }
// if (coursesWithoutDependencies.isEmpty()) return emptyArray()
val result = LinkedHashSet<Int>()
val graph = Graph(prerequisites)
coursesWithoutDependencies.forEach { course ->
graph.traverseDepthFirst(course, result)
}
return result.reversed().toTypedArray()
}
private class Graph(private val prerequisites: Array<Array<Int>>) {
fun traverseDepthFirst(node: Int, visited: MutableSet<Int>) {
visited.add(node)
neighboursOf(node).forEach {
if (!visited.contains(it)) traverseDepthFirst(it, visited)
}
}
private fun neighboursOf(node: Int): List<Int> {
return prerequisites.filter { it[0] == node }.map { it[1] }
}
} | 7 | Roff | 3 | 5 | 0f169804fae2984b1a78fc25da2d7157a8c7a7be | 2,198 | katas | The Unlicense |
src/Day16.kt | Kvest | 573,621,595 | false | {"Kotlin": 87988} | import java.util.*
import kotlin.math.max
fun main() {
val testInput = readInput("Day16_test")
check(part1(testInput) == 1651)
check(part2(testInput) == 1707)
val input = readInput("Day16")
println(part1(input))
println(part2(input))
}
private const val PART1_MINUTES = 30
private const val PART2_MINUTES = 26
private const val START_VALVE = "AA"
private fun part1(input: List<String>): Int {
val valves = input.parseInputAndOptimize()
val bitsMapper = valves.calcBitsMapper()
return solve(
minutesLeft = PART1_MINUTES,
name = START_VALVE,
openedBitmask = 0,
valves = valves,
bitsMapper = bitsMapper
)
}
private fun part2(input: List<String>): Int {
val valves = input.parseInputAndOptimize()
val bitsMapper = valves.calcBitsMapper()
val valvesToOpen = bitsMapper.keys.toList() - START_VALVE
val allBits = valvesToOpen.fold(0L) { acc, valve -> acc or bitsMapper.getValue(valve) }
val memo = mutableMapOf<Long, Int>()
//Brut-force all possible variants where some valves will be opened by me and the rest - by elephant
return valvesToOpen.allCombinations()
.map { valves ->
valves.fold(0L) { acc, valve -> acc or bitsMapper.getValue(valve) }
}
.maxOf { valveBits ->
val otherBits = allBits and valveBits.inv()
val first = memo.getOrPut(valveBits) {
solve(
minutesLeft = PART2_MINUTES,
name = START_VALVE,
openedBitmask = valveBits,
valves = valves,
bitsMapper = bitsMapper
)
}
val second = memo.getOrPut(otherBits) {
solve(
minutesLeft = PART2_MINUTES,
name = START_VALVE,
openedBitmask = otherBits,
valves = valves,
bitsMapper = bitsMapper
)
}
first + second
}
}
private fun solve(
minutesLeft: Int,
name: String,
openedBitmask: Long,
valves: Map<String, Valve>,
bitsMapper: Map<String, Long>,
memo: MutableMap<String, Int> = mutableMapOf()
): Int {
val key = "${minutesLeft}_${name}_$openedBitmask"
if (key in memo) {
return memo.getValue(key)
}
val valve = valves.getValue(name)
val resultInc = valve.rate * minutesLeft
var result = resultInc
valve.destinations.forEach { (nextName, timeToReachAndOpen) ->
val nextBit = bitsMapper.getValue(nextName)
if (minutesLeft > timeToReachAndOpen && (openedBitmask and nextBit) == 0L) {
result = max(
result,
resultInc + solve(
minutesLeft = minutesLeft - timeToReachAndOpen,
name = nextName,
openedBitmask = (openedBitmask or nextBit),
valves = valves,
bitsMapper = bitsMapper,
memo = memo
)
)
}
}
memo[key] = result
return result
}
private val ROW_FORMAT = Regex("Valve ([A-Z]+) has flow rate=(\\d+); tunnel[s]? lead[s]? to valve[s]? ([A-Z, ]+)")
private fun List<String>.parseInputAndOptimize(): Map<String, Valve> {
val rates = mutableMapOf<String, Int>()
val tunnelsFromValve = mutableMapOf<String, List<String>>()
this.forEach {
val match = ROW_FORMAT.find(it)
val (valve, rate, tunnels) = requireNotNull(match).destructured
rates[valve] = rate.toInt()
tunnelsFromValve[valve] = tunnels.split(", ")
}
// Consider only valves with rate > 0
// Don't forget to add START valve
return rates.filter { it.value > 0 || it.key == START_VALVE }
.mapValues { (name, rate) ->
Valve(
rate = rate,
destinations = buildTunnelsChains(name, tunnelsFromValve, rates)
)
}
}
private fun buildTunnelsChains(
start: String,
tunnels: Map<String, List<String>>,
rates: Map<String, Int>
): List<Destination> {
return buildList {
val queue = PriorityQueue<Pair<String, Int>> { a, b -> a.second - b.second }
queue.offer(start to 0)
val visited = mutableSetOf<String>()
while (queue.isNotEmpty()) {
val (name, time) = queue.poll()
if (name in visited) {
continue
}
visited.add(name)
if (rates.getValue(name) > 0 && name != start) {
add(Destination(name, time + 1)) //add 1 minute for opening
}
tunnels[name]?.forEach { next ->
queue.offer(next to time + 1)
}
}
}
}
private fun Map<String, Valve>.calcBitsMapper(): Map<String, Long> {
var i = 1L
return this.mapValues {
val res = i
i = i shl 1
res
}
}
private data class Valve(
val rate: Int,
val destinations: List<Destination>
)
private data class Destination(
val name: String,
val timeToReachAndOpen: Int
) | 0 | Kotlin | 0 | 0 | 6409e65c452edd9dd20145766d1e0ea6f07b569a | 5,177 | AOC2022 | Apache License 2.0 |
src/day7.kt | eldarbogdanov | 577,148,841 | false | {"Kotlin": 181188} | class Node(val name: String, val folders: MutableMap<String, Node>, val files: MutableMap<String, Long>);
val parents: MutableMap<Node, Node> = mutableMapOf<Node, Node>();
val folderSizes: MutableMap<Node, Long> = mutableMapOf();
fun sumFiles(cur: Node, limit: Long): Pair<Long, Long> {
var size: Long = cur.files.values.sum();
var ret: Long = 0;
for(subfolder in cur.folders.keys) {
val (folderSize, ans) = sumFiles(cur.folders[subfolder]!!, limit);
size += folderSize;
ret += ans;
}
folderSizes.put(cur, size);
if (size <= limit) ret += size;
return Pair(size, ret);
}
fun main() {
val input = ""
var root = Node("/", mutableMapOf<String, Node>(), mutableMapOf<String, Long>());
var currentNode: Node? = null;
for(s in input.split("\n")) {
//println(s + " " + currentNode?.name);
if (!s.startsWith("$")) {
if (s.startsWith("dir")) {
val subfolder = s.split(" ")[1];
val newNode = Node(subfolder, mutableMapOf(), mutableMapOf());
currentNode!!.folders.put(subfolder, newNode);
parents.put(newNode, currentNode);
} else {
val fileName = s.split(" ")[1];
val fileSize = Integer.parseInt(s.split(" ")[0]);
currentNode!!.files.put(fileName, fileSize.toLong());
}
} else
if (s == "$ cd /") currentNode = root; else
if (s == "$ cd ..") currentNode = parents[currentNode!!]; else
if (s.startsWith("$ cd")) {
//println(currentNode!!.folders);
currentNode = currentNode!!.folders[s.split(" ")[2]];
} else {
if (s != "$ ls") println("oops " + s);
}
}
println(sumFiles(root, 100000).second);
val totalSize = folderSizes[root]!!;
var ans: Long = 1000000000;
for(entry in folderSizes.entries.iterator()) {
val size = entry.value;
if (70000000 - totalSize + size >= 30000000 && size < ans) {
ans = size;
}
}
println(ans);
}
| 0 | Kotlin | 0 | 0 | bdac3ab6cea722465882a7ddede89e497ec0a80c | 2,089 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/Day7.kt | ivan-gusiev | 726,608,707 | false | {"Kotlin": 34715, "Python": 2022, "Makefile": 50} | import util.AocDay
import util.AocInput
import util.AocSequence
typealias Day7InputType = List<String>;
class Day7 : Runner {
val TEST_INPUT: String = """
32T3K 765
T55J5 684
KK677 28
KTJJT 220
QQQJA 483
""".trimIndent()
override fun run() {
val day = AocDay("2023".toInt(), "7".toInt())
val lines = AocInput.lines(day)
//val lines = TEST_INPUT.split("\n")
part1(lines)
part2(lines)
}
private fun part1(input: Day7InputType) {
val handsWithBids = input.map(HandWithBid::parse)
val sorted = handsWithBids.sortedBy { hwb -> hwb.hand }
// equal to sorted.indices but 1-indexed
val ranks = (1..sorted.size).toList()
println(ranks.zip(sorted).sumOf { (rank, hwb) -> rank * hwb.bid })
}
private fun part2(input: Day7InputType) {
val handsWithBids = input.map(HandWithBid::parse)
val sorted = handsWithBids.sortedWith(HandWithBidComparator())
// equal to sorted.indices but 1-indexed
val ranks = (1..sorted.size).toList()
sorted.zip(ranks).forEach { (hwb, rank) -> println("$hwb is ${hwb.hand.jokerType()} -> $rank") }
println(ranks.zip(sorted).sumOf { (rank, hwb) -> rank * hwb.bid })
}
data class Card private constructor(val value: Char) : Comparable<Card> {
companion object {
//const val VALUES = "23456789TJQKA" //<- uncomment for part 1
const val VALUES = "J23456789TQKA"
fun of(value: Char): Card {
if (VALUES.contains(value)) {
return Card(value)
} else {
throw IllegalArgumentException("Invalid card value: $value")
}
}
fun all(): List<Card> {
return VALUES.map(Card::of)
}
}
private fun index(): Int {
return VALUES.indexOf(value)
}
override fun compareTo(other: Card): Int {
return index().compareTo(other.index())
}
override fun toString(): String {
return value.toString()
}
}
enum class HandType {
HIGH_CARD,
PAIR,
TWO_PAIR,
THREE_OF_A_KIND,
FULL_HOUSE,
FOUR_OF_A_KIND,
FIVE_OF_A_KIND
}
data class Hand(val cards: List<Card>) : Comparable<Hand> {
companion object {
fun parse(input: String): Hand {
val cards = input.map(Card::of)
return Hand(cards)
}
}
fun type(): HandType {
val counts = AocSequence.spectrum(cards)
return when (counts.size) {
1 -> HandType.FIVE_OF_A_KIND
2 -> {
if (counts.values.contains(4)) {
HandType.FOUR_OF_A_KIND
} else {
HandType.FULL_HOUSE
}
}
3 -> {
if (counts.values.contains(3)) {
HandType.THREE_OF_A_KIND
} else {
HandType.TWO_PAIR
}
}
4 -> HandType.PAIR
5 -> HandType.HIGH_CARD
else -> throw IllegalStateException("Invalid hand: $this")
}
}
// calculates type, but now joker can be any card
// and we should take the best type
fun jokerType(): HandType {
val jokerIndices = cards.indices.filter { i -> cards[i] == Card.of('J') }
val selfString = this.toString()
Card.all()
.map { parse(selfString.replace("J", it.toString())) }
.maxBy { it.type() }
.let { best ->
return best.type()
}
}
override fun compareTo(other: Hand): Int {
val typeComparison = type().compareTo(other.type())
if (typeComparison != 0) {
return typeComparison
}
for (i in cards.indices) {
val comparison = cards[i].compareTo(other.cards[i])
if (comparison != 0) {
return comparison
}
}
return 0
}
override fun toString(): String {
return cards.joinToString("")
}
}
data class HandWithBid(val hand: Hand, val bid: Int) {
companion object {
fun parse(input: String): HandWithBid {
val parts = input.split(" ")
val hand = Hand.parse(parts[0])
val bid = parts[1].toInt()
return HandWithBid(hand, bid)
}
}
}
class HandWithBidComparator : Comparator<HandWithBid> {
override fun compare(a: HandWithBid, b: HandWithBid): Int {
val handA = a.hand
val handB = b.hand
val typeComparison = handA.jokerType().compareTo(handB.jokerType())
if (typeComparison != 0) {
return typeComparison
}
for (i in handA.cards.indices) {
val comparison = handA.cards[i].compareTo(handB.cards[i])
if (comparison != 0) {
return comparison
}
}
return 0
}
}
} | 0 | Kotlin | 0 | 0 | 5585816b435b42b4e7c77ce9c8cabc544b2ada18 | 5,459 | advent-of-code-2023 | MIT License |
src/Day03.kt | janbina | 157,854,025 | false | null | import kotlin.test.assertEquals
object Day03 {
private fun createArea(input: List<Claim>): Array<IntArray> {
val area = Array(1000) { IntArray(1000) { 0 } }
input.forEach {
for (i in it.left until it.left+it.width) {
for (j in it.top until it.top+it.height) {
area[i][j]++
}
}
}
return area
}
fun part1(input: List<Claim>): Int {
val area = createArea(input)
return area.fold(0) { acc, ints -> acc + ints.count { it > 1 } }
}
fun part2(input: List<Claim>): Int {
val area = createArea(input)
outer@ for (it in input) {
for (i in it.left until it.left + it.width) {
for (j in it.top until it.top + it.height) {
if (area[i][j] > 1) continue@outer
}
}
return it.id
}
return -1
}
}
data class Claim(
val id: Int,
val left: Int,
val top: Int,
val width: Int,
val height: Int
) {
companion object {
private val REGEX = Regex("\\d+")
fun fromString(s: String): Claim {
val (id, left, top, width, height) = REGEX.findAll(s).map { it.value.toInt() }.take(5).toList()
return Claim(id, left, top, width, height)
}
}
}
fun main(args: Array<String>) {
val input = getInput(3).readLines().map { Claim.fromString(it) }
assertEquals(111266, Day03.part1(input))
assertEquals(266, Day03.part2(input))
}
| 0 | Kotlin | 0 | 0 | 522d93baf9ff4191bc2fc416d95b06208be32325 | 1,555 | advent-of-code-2018 | MIT License |
src/nativeMain/kotlin/com.qiaoyuang.algorithm/round0/MergeSort.kt | qiaoyuang | 100,944,213 | false | {"Kotlin": 338134} | package com.qiaoyuang.algorithm.round0
import kotlin.math.*
/**
* 归并排序
*/
fun testMergeSort() {
val array1 = intArrayOf(5, 7, 2, 9, 3, 1, 4, 0, 8, 6)
array1.mergeSort1()
array1.forEach { print("$it ") }
println()
val array2 = intArrayOf(5, 7, 2, 9, 3, 1, 4, 0, 8, 6)
array2.mergeSort2()
array2.forEach { print("$it ") }
}
// 自顶向下的归并排序
fun IntArray.mergeSort1() {
val aux = IntArray(size)
mergeSort(aux, 0, size - 1)
}
private fun IntArray.mergeSort(aux: IntArray, lo: Int, hi: Int) {
if (hi <= lo) return
val mid = lo + ((hi - lo) shr 1)
mergeSort(aux, lo, mid)
mergeSort(aux, mid + 1, hi)
merge(aux, lo, mid, hi)
}
// 自底向上的归并排序
fun IntArray.mergeSort2() {
val aux = IntArray(size)
var sz = 1
while (sz < size) {
var lo = 0
while (lo < size - sz) {
merge(aux, lo, lo + sz - 1, min(lo + sz + sz - 1, size - 1))
lo += sz shl 1
}
sz = sz shl 1
}
}
fun IntArray.merge(aux: IntArray, lo: Int, mid: Int, hi: Int) {
var i = lo
var j = mid + 1
for (k in lo..hi)
aux[k] = this[k]
for (k in lo..hi)
when {
i > mid -> this[k] = aux[j++]
j > hi -> this[k] = aux[i++]
aux[j] < aux[i] -> this[k] = aux[j++]
else -> this[k] = aux[i++]
}
} | 0 | Kotlin | 3 | 6 | 66d94b4a8fa307020d515d4d5d54a77c0bab6c4f | 1,230 | Algorithm | Apache License 2.0 |
src/main/kotlin/org/flightofstairs/ctci/treesAndGraphs/NumberOfIslands.kt | FlightOfStairs | 509,587,102 | false | {"Kotlin": 38930} | package org.flightofstairs.ctci.treesAndGraphs
data class Position(val x: Int, val y: Int) {
// Supports diagonals
fun adjacentPositions() = (-1..1).flatMap { dx ->
(-1..1).map { dy ->
Position(x + dx, y + dy)
}
}.filter { it != this }
}
private fun positionExists(position: Position, matrix: List<List<Int>>) =
matrix.indices.contains(position.x) && matrix[position.x].indices.contains(position.y)
private fun positionsPrioritizingIslands(matrix: List<List<Int>>): Sequence<Position> = sequence {
val visited = mutableSetOf<Position>()
val deque = ArrayDeque<Position>()
val first = Position(0, 0)
deque.add(first)
visited.add(first)
while (!deque.isEmpty()) {
val current = deque.removeLast()
yield(current)
val subsequent = current.adjacentPositions()
.filter { positionExists(it, matrix) }
.filter { !visited.contains(it) }
for (position in subsequent) {
visited.add(position)
if (matrix[position] == 0) deque.addFirst(position) else deque.addLast(position)
}
}
}
fun numberOfIslands(matrix: List<List<Int>>): Int {
val initialIslandCount = matrix[0][0]
return initialIslandCount + positionsPrioritizingIslands(matrix)
.map { matrix[it] }
.windowed(2)
.count { it[0] != 1 && it[1] == 1 }
}
private operator fun List<List<Int>>.get(position: Position): Int {
check(positionExists(position, this))
return this[position.x][position.y]
}
| 0 | Kotlin | 0 | 0 | 5f4636ac342f0ee5e4f3517f7b5771e5aabe5992 | 1,551 | FlightOfStairs-ctci | MIT License |
src/Day12.kt | spaikmos | 573,196,976 | false | {"Kotlin": 83036} | import java.util.Deque
fun main() {
fun part1(input: List<String>): Int {
val yLen = input[0].length
val xLen = input.size
val visited = Array(xLen) { IntArray(yLen){0} }
val nodes = input.map{it.toCharArray()}
val end = nodes.find { it.contains('E') }
val endX = nodes.indexOf(end)
val endY = end!!.indexOf('E')
val start = nodes.find { it.contains('S') }
val startX = nodes.indexOf(start)
val startY = start!!.indexOf('S')
println("startX: $startX, startY: $startY")
println("xLen: $xLen, yLen: $yLen")
var numSteps = 0
var numNodes = 0
val q = ArrayDeque<Pair<Int, Int>>()
q.add(Pair(startX, startY))
nodes[startX][startY] = 'a'
visited[startX][startY] = 1
fun checkNode(x: Int, y: Int, nextVal: Char) {
if ((x >= 0) && (x < xLen) && (y >=0) && (y < yLen)) {
val nodeVal = nodes[x][y]
if (visited[x][y] == 0) {
if ((nextVal == 'z' && nodeVal == 'E') || (nodeVal <= nextVal)) {
q.addLast(Pair(x, y))
visited[x][y] = 1
}
}
}
}
while (q.size > 0) {
val numElem = q.size
repeat(numElem) {
var node = q.removeFirst()
val nextVal = nodes[node.first][node.second] + 1
if (nextVal == 'F') {
return numSteps
}
// Check if adjacent nodes can be added to queue
checkNode(node.first+1, node.second, nextVal)
checkNode(node.first-1, node.second, nextVal)
checkNode(node.first, node.second+1, nextVal)
checkNode(node.first, node.second-1, nextVal)
numNodes++
}
numSteps++
var numQ = q.size
println("step: $numSteps nodes: $numNodes qSize: $numQ")
}
return 0
}
fun part2(input: List<String>): Int {
val yLen = input[0].length
val xLen = input.size
val nodes = input.map{it.toCharArray()}
val start = nodes.find { it.contains('S') }
var startX = nodes.indexOf(start)
var startY = start!!.indexOf('S')
nodes[startX][startY] = 'a'
var minSteps = 1000
startX = 0
startY = 0
repeat (xLen) {
repeat (yLen) {
if (nodes[startX][startY] == 'a') {
val visited = Array(xLen) { IntArray(yLen){0} }
var numSteps = 0
var numNodes = 0
val q = ArrayDeque<Pair<Int, Int>>()
q.add(Pair(startX, startY))
visited[startX][startY] = 1
fun checkNode(x: Int, y: Int, nextVal: Char) {
if ((x >= 0) && (x < xLen) && (y >=0) && (y < yLen)) {
val nodeVal = nodes[x][y]
if (visited[x][y] == 0) {
if ((nextVal == 'z' && nodeVal == 'E') || (nodeVal <= nextVal)) {
q.addLast(Pair(x, y))
visited[x][y] = 1
}
}
}
}
//println("startX: $startX startY: $startY")
while (q.size > 0) {
var numElem = q.size
var exit = false
while ((numElem > 0) && (exit == false )) {
var node = q.removeFirst()
val nextVal = nodes[node.first][node.second] + 1
if (nextVal == 'F') {
if (numSteps < minSteps) {
minSteps = numSteps
println("minSteps: $minSteps")
}
//q.clear()
exit = true
} else {
// Check if adjacent nodes can be added to queue
checkNode(node.first + 1, node.second, nextVal)
checkNode(node.first - 1, node.second, nextVal)
checkNode(node.first, node.second + 1, nextVal)
checkNode(node.first, node.second - 1, nextVal)
numNodes++
}
numElem--
}
numSteps++
var numQ = q.size
//println("step: $numSteps nodes: $numNodes qSize: $numQ")
}
}
startY++
}
startY = 0
startX++
}
return minSteps
}
val input = readInput("../input/Day12")
println(part1(input)) // 481
println(part2(input)) // 480
} | 0 | Kotlin | 0 | 0 | 6fee01bbab667f004c86024164c2acbb11566460 | 5,189 | aoc-2022 | Apache License 2.0 |
src/Day07.kt | pavlo-dh | 572,882,309 | false | {"Kotlin": 39999} | fun main() {
class Directory(val name: String, val parent: Directory?) {
var size = 0
}
fun processFiles(currentCommandIndex: Int, input: List<String>, currentDirectory: Directory): Int {
val nextCommandIndex =
(currentCommandIndex + 1 until input.size).firstOrNull { index -> input[index].startsWith('$') }
?: input.size
for (i in currentCommandIndex + 1 until nextCommandIndex) {
val line = input[i]
if (!line.startsWith('d')) {
val fileSize = line.split(' ').first()
currentDirectory.size += fileSize.toInt()
}
}
return nextCommandIndex
}
fun part1(input: List<String>): Int {
var commandIndex = 1
var currentDirectory = Directory(name = "/", parent = null)
var sizeSum = 0
do {
val command = input[commandIndex]
when (command[2]) {
'c' -> {
currentDirectory = when (command[5]) {
'.' -> {
if (currentDirectory.size <= 100000) sizeSum += currentDirectory.size
currentDirectory.parent!!.also { parentDirectory ->
parentDirectory.size += currentDirectory.size
}
}
else -> Directory(name = command.substring(5), parent = currentDirectory)
}
commandIndex++
}
'l' -> {
commandIndex = processFiles(commandIndex, input, currentDirectory)
}
}
} while (commandIndex != input.size)
while (currentDirectory.name != "/") {
if (currentDirectory.size <= 100000) sizeSum += currentDirectory.size
currentDirectory = currentDirectory.parent!!.also { parentDirectory ->
parentDirectory.size += currentDirectory.size
}
}
return sizeSum
}
fun part2(input: List<String>): Int {
var commandIndex = 1
var currentDirectory = Directory(name = "/", parent = null)
val directories = mutableListOf(currentDirectory)
do {
val command = input[commandIndex]
when (command[2]) {
'c' -> {
currentDirectory = when (command[5]) {
'.' -> {
currentDirectory.parent!!.also { parentDirectory ->
parentDirectory.size += currentDirectory.size
}
}
else -> Directory(name = command.substring(5), parent = currentDirectory).also { directory ->
directories.add(directory)
}
}
commandIndex++
}
'l' -> {
commandIndex = processFiles(commandIndex, input, currentDirectory)
}
}
} while (commandIndex != input.size)
while (currentDirectory.name != "/") {
currentDirectory = currentDirectory.parent!!.also { parentDirectory ->
parentDirectory.size += currentDirectory.size
}
}
val spaceTotal = 70000000
val spaceNeeded = 30000000
val currentSize = directories.first().size
directories.sortBy { it.size }
return directories.first { directory -> spaceTotal - (currentSize - directory.size) >= spaceNeeded }.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day07_test")
check(part1(testInput) == 95437)
check(part2(testInput) == 24933642)
val input = readInput("Day07")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 2 | c10b0e1ce2c7c04fbb1ad34cbada104e3b99c992 | 3,943 | aoc-2022-in-kotlin | Apache License 2.0 |
src/main/kotlin/adventofcode/y2021/Day21.kt | Tasaio | 433,879,637 | false | {"Kotlin": 117806} | import adventofcode.BigIntegerMap
import adventofcode.RotatingNumber
import adventofcode.parseNumbersToIntList
import adventofcode.runDay
import java.math.BigInteger
fun main() {
val testInput = """
Player 1 starting position: 4
Player 2 starting position: 8
""".trimIndent()
runDay(
day = Day21::class,
testInput = testInput,
testAnswer1 = 739785,
testAnswer2 = "444356092776315".toBigInteger()
)
}
open class Day21(staticInput: String? = null) : Y2021Day(21, staticInput) {
private val input = fetchInput().map { it.parseNumbersToIntList()[1] }
override fun part1(): Number? {
var rolls = 0
var p1 = RotatingNumber(1, 10, input[0])
var p2 = RotatingNumber(1, 10, input[1])
var die = RotatingNumber(1, 100)
var score1 = BigInteger.ZERO
var score2 = BigInteger.ZERO
while (true) {
var roll = BigInteger.ZERO
for (i in 0 until 3) {
rolls++
roll += die.value
die = die.inc()
}
p1 = p1.plus(roll)
score1 += p1.value
if (score1 >= (1000).toBigInteger()) {
return rolls.toBigInteger() * score2
}
roll = BigInteger.ZERO
for (i in 0 until 3) {
rolls++
roll += die.value
die = die.inc()
}
p2 = p2.plus(roll)
score2 += p2.value
if (score2 >= (1000).toBigInteger()) {
return rolls.toBigInteger() * score1
}
}
}
data class Game(val p1Score: Int, val p2Score: Int, val p1Pos: RotatingNumber, val p2Pos: RotatingNumber) {
fun moveP1(steps: Int): Game {
val p1 = p1Pos + steps
val score = p1.value
return Game(p1Score + score.toInt(), p2Score, p1, p2Pos)
}
fun moveP2(steps: Int): Game {
val p2 = p2Pos + steps
val score = p2.value
return Game(p1Score, p2Score + score.toInt(), p1Pos, p2)
}
fun won(): Boolean {
return p1Score >= 21 || p2Score >= 21
}
}
override fun part2(): Number? {
var map = BigIntegerMap<Game>()
val rolls = arrayListOf<Int>()
for (i in 1..3) {
for (j in 1..3) {
for (k in 1..3) {
rolls.add(i + j + k)
}
}
}
var winP1 = BigInteger.ZERO
var winP2 = BigInteger.ZERO
map[Game(
0, 0,
RotatingNumber(1, 10, input[0]),
RotatingNumber(1, 10, input[1])
)] = BigInteger.ONE
var turnP1 = true
while (map.isNotEmpty()) {
val newMap = BigIntegerMap<Game>()
for (e in map.entries) {
for (r in rolls) {
val ng = if (turnP1) e.key.moveP1(r) else e.key.moveP2(r)
if (ng.won()) {
if (turnP1) {
winP1 += e.value
} else {
winP2 += e.value
}
} else {
newMap[ng] += e.value
}
}
}
map = newMap
turnP1 = !turnP1
}
return if (winP1 > winP2) winP1 else winP2
}
}
| 0 | Kotlin | 0 | 0 | cc72684e862a782fad78b8ef0d1929b21300ced8 | 3,476 | adventofcode2021 | The Unlicense |
generator/src/main/kotlin/com/kylemayes/generator/generate/support/Struct.kt | KyleMayes | 305,287,877 | false | {"Rust": 6654307, "Kotlin": 153555, "GLSL": 3759, "Python": 2709, "Shell": 1142, "Makefile": 800, "PowerShell": 721} | // SPDX-License-Identifier: Apache-2.0
package com.kylemayes.generator.generate.support
import com.kylemayes.generator.registry.Identifier
import com.kylemayes.generator.registry.PointerType
import com.kylemayes.generator.registry.Registry
import com.kylemayes.generator.registry.Structure
import com.kylemayes.generator.registry.Type
import com.kylemayes.generator.registry.getBaseIdentifier
import com.kylemayes.generator.registry.getElement
import com.kylemayes.generator.registry.getIdentifier
import com.kylemayes.generator.registry.isPointer
import kotlin.math.max
/** Gets the non-pointer dependencies of a Vulkan struct on other Vulkan structs. */
val getStructDependencies = thunk { struct: Structure ->
struct.members
.mapNotNull { m -> m.type.getBaseIdentifier() }
.filter { d -> structs.containsKey(d) }
.toSet()
}
private val getStructDerivesResults = HashMap<Identifier, Set<String>>()
/** Gets the Rust traits which can be derived for a Vulkan struct. */
fun Registry.getStructDerives(struct: Structure): Set<String> {
val memoized = getStructDerivesResults[struct.name]
if (memoized != null) {
return memoized
}
val floats = struct.members.any { m -> m.type.getBaseIdentifier()?.value == "float" }
val functions = struct.members.any { m -> functions.containsKey(m.type.getIdentifier()) }
val pointers = struct.members.any { m -> m.type.isPointer() }
val unions = struct.members.any { m -> unions.containsKey(m.type.getIdentifier()) }
// These traits will be "manually" implemented for structs they can't be
// derived for so we don't need to worry about whether the struct
// dependencies will derive them.
val required = HashSet<String>()
if (!functions) required.add("Debug")
if (!pointers) required.add("Default")
// These traits will not be "manually" implemented so they can only be
// applied to structs that meet the requirements and don't (transitively)
// contain other structs that do not meet the requirements.
val optional = HashSet<String>()
val partialEq = !functions && !unions
if (partialEq) optional.add("PartialEq")
if (partialEq && !floats) { optional.add("Eq"); optional.add("Hash") }
for (dependency in getStructDependencies(struct)) {
val derives = getStructDerives(structs[dependency] ?: error("Missing struct."))
optional.removeIf { !derives.contains(it) }
}
val result = required.union(optional)
getStructDerivesResults[struct.name] = result
return result
}
/** Gets the length of the longest array in a Vulkan struct. */
private fun Registry.getMaxArrayLength(struct: Structure) = struct.members
.mapNotNull { getMaxArrayLength(it.type) }
.maxOrNull()
/** Gets the length of the longest array in a Vulkan type. */
private fun Registry.getMaxArrayLength(type: Type): Long? {
val length = getLengthValue(type) ?: return null
val elementLength = type.getElement()?.let { getMaxArrayLength(it) } ?: 0
return max(length, elementLength)
}
/** Gets the Vulkan structs that can be used to extend other Vulkan structs. */
val getStructExtensions = thunk { ->
structs.values
.filter { it.structextends != null }
.flatMap { it.structextends!!.map { e -> e to it.name } }
.groupBy({ it.first }, { it.second })
}
private val getStructLifetimeResults = HashMap<Identifier, Boolean>()
/** Gets whether a Vulkan struct requires a lifetime for its builder. */
fun Registry.getStructLifetime(struct: Structure): Boolean {
val memoized = getStructLifetimeResults[struct.name]
if (memoized != null) {
return memoized
}
// Builder methods for pointer members will use references with lifetimes
// so any struct that contains a pointer will need a lifetime. An exception
// is made for the `next` member if there are no extending structs since
// the corresponding builder method will be omitted in this case.
val members = struct.members.any {
it.type is PointerType &&
(it.name.value != "next" || getStructExtensions()[struct.name]?.isNotEmpty() ?: false)
}
// Builder method for struct members will use
val dependencies = getStructDependencies(struct).any {
getStructLifetime(structs[it] ?: error("Missing struct."))
}
val result = members || dependencies
getStructLifetimeResults[struct.name] = result
return result
}
/** Gets the Vulkan structs that can be part of a pointer chain. */
val getChainStructs = thunk { ->
structs.filter {
val name = it.key.original
if (name == "VkBaseInStructure" || name == "VkBaseOutStructure") {
// These are helper structs used for iterating through pointer
// chains, not pointer chain structs themselves.
false
} else {
val type = it.value.members.getOrNull(0)?.name?.original == "sType"
val next = it.value.members.getOrNull(1)?.name?.original == "pNext"
type && next
}
}
}
| 12 | Rust | 29 | 216 | c120c156dc5a6ebcfd8870d8688001f4accfb373 | 5,065 | vulkanalia | Apache License 2.0 |
src/main/kotlin/week1/SupplyStacks.kt | waikontse | 572,850,856 | false | {"Kotlin": 63258} | package week1
import shared.Puzzle
class SupplyStacks : Puzzle(5) {
override fun solveFirstPart(): Any {
val sections = splitSections(puzzleInput)
val startStacks = sections[0].map { parseStack(it) }
.map { it.filter { pair -> pair.second != ' ' } }
.let { createStacks(it) }
sections[2].map { parseMove(it) }
.forEach { moveStacks(it[0], it[1], it[2], { chars -> chars.reversed() }, startStacks) }
return startStacks.filter { it.isNotEmpty() }
.map { it.last() }
.joinToString("")
}
override fun solveSecondPart(): Any {
val sections = splitSections(puzzleInput)
val startStacks = sections[0].map { parseStack(it) }
.map { it.filter { pair -> pair.second != ' ' } }
.let { createStacks(it) }
sections[2].map { parseMove(it) }
.forEach { moveStacks(it[0], it[1], it[2], { chars -> chars }, startStacks) }
return startStacks.filter { it.isNotEmpty() }
.map { it.last() }
.joinToString("")
}
private fun splitSections(puzzleInput: List<String>): List<List<String>> {
val indexSplit = puzzleInput.indexOfFirst { it.isBlank() }
return listOf(
puzzleInput.subList(0, indexSplit - 1),
puzzleInput.subList(indexSplit - 1, indexSplit),
puzzleInput.subList(indexSplit + 1, puzzleInput.size)
)
}
private fun parseStack(row: String): List<Pair<Int, Char>> {
return parseStackIndividual(emptyList(), row, 1)
}
private tailrec fun parseStackIndividual(
acc: List<Pair<Int, Char>>,
row: String,
currentPos: Int
): List<Pair<Int, Char>> {
if (row.isEmpty()) {
return acc
}
return parseStackIndividual(
acc + (currentPos to row[1]),
row.drop(4),
currentPos.inc()
)
}
private fun createStacks(stackLocations: List<List<Pair<Int, Char>>>): MutableList<MutableList<Char>> {
val stacks = MutableList(10) { mutableListOf<Char>() }
stackLocations
.map { it.forEach { locations -> stacks[locations.first].add(0, locations.second) } }
return stacks
}
private fun parseMove(move: String): List<Int> {
val (count, from, to) = """move (\d+) from (\d+) to (\d+)""".toRegex()
.matchEntire(move)
?.destructured
?: throw IllegalArgumentException("Illegal move: $move")
return listOf(count.toInt(), from.toInt(), to.toInt())
}
private fun moveStacks(
count: Int,
from: Int,
to: Int,
action: (f: List<Char>) -> List<Char>,
stacks: MutableList<MutableList<Char>>
) {
val newMovableStack = action(stacks[from].takeLast(count))
val newFromStack = stacks[from].dropLast(count).toMutableList()
stacks[from] = newFromStack
stacks[to].addAll(newMovableStack)
}
}
| 0 | Kotlin | 0 | 0 | 860792f79b59aedda19fb0360f9ce05a076b61fe | 3,031 | aoc-2022-in-kotllin | Creative Commons Zero v1.0 Universal |
src/Day04.kt | jmorozov | 573,077,620 | false | {"Kotlin": 31919} | fun main() {
val inputData = readInput("Day04")
part1(inputData)
part2(inputData)
}
private fun part1(inputData: List<String>) {
var oneRangeFullyContainTheOtherTimes = 0
for (line in inputData) {
val trimmedLine = line.trim()
val parts = trimmedLine.split(",")
val range1 = parts[0].toRange()
val range2 = parts[1].toRange()
if (range1.contains(range2) || range2.contains(range1)) {
oneRangeFullyContainTheOtherTimes++
}
}
println("One range fully contain the other: $oneRangeFullyContainTheOtherTimes")
}
fun String.toRange(): IntRange = this
.split("-")
.let { (a, b) -> a.toInt()..b.toInt() }
fun IntRange.contains(other: IntRange): Boolean = this.first <= other.first && this.last >= other.last
private fun part2(inputData: List<String>) {
var rangesOverlapInPairs = 0
for (line in inputData) {
val trimmedLine = line.trim()
val parts = trimmedLine.split(",")
val range1 = parts[0].toRange()
val range2 = parts[1].toRange()
if (range1.overlaps(range2)) {
rangesOverlapInPairs++
}
}
println("The ranges overlap in pairs: $rangesOverlapInPairs")
}
fun IntRange.overlaps(other: IntRange) =
this.first in other ||
this.last in other ||
other.first in this ||
other.last in this | 0 | Kotlin | 0 | 0 | 480a98838949dbc7b5b7e84acf24f30db644f7b7 | 1,403 | aoc-2022-in-kotlin | Apache License 2.0 |
src/year2021/10/Day10.kt | Vladuken | 573,128,337 | false | {"Kotlin": 327524, "Python": 16475} | package year2021.`10`
import readInput
val entryBrackets = setOf<Char>(
'{',
'[',
'(',
'<',
)
val closingBracket = setOf<Char>(
'}',
']',
')',
'>',
)
fun charToValue(bracket: Char): Int {
return when (bracket) {
')' -> 3
']' -> 57
'}' -> 1197
'>' -> 25137
else -> error("Illegal bracket: $bracket")
}
}
private sealed class LineAnswer {
data class Success(val line: String) : LineAnswer()
data class Incomplete(
val line: String,
val stack: ArrayDeque<Char>,
) : LineAnswer()
data class Corrupted(
val line: String,
val corruptedBy: Char,
) : LineAnswer()
}
private fun processLine(line: String): LineAnswer {
val stack = ArrayDeque<Char>()
line.forEach { currentBracket ->
if (currentBracket in entryBrackets) {
stack.add(currentBracket)
} else if (currentBracket in closingBracket) {
when (stack.lastOrNull()) {
'{' -> if (currentBracket == '}') {
stack.removeLast()
} else {
return LineAnswer.Corrupted(line, currentBracket)
}
'[' -> if (currentBracket == ']') {
stack.removeLast()
} else {
return LineAnswer.Corrupted(line, currentBracket)
}
'(' -> if (currentBracket == ')') {
stack.removeLast()
} else {
return LineAnswer.Corrupted(line, currentBracket)
}
'<' -> if (currentBracket == '>') {
stack.removeLast()
} else {
return LineAnswer.Corrupted(line, currentBracket)
}
else -> stack.add(currentBracket)
}
}
}
return if (stack.isEmpty()) {
LineAnswer.Success(line)
} else {
LineAnswer.Incomplete(line, ArrayDeque(stack))
}
}
fun createEndingLineForStack(stack: ArrayDeque<Char>): String {
var resString = ""
while (stack.isNotEmpty()) {
val last = stack.removeLast()
resString += when (last) {
'{' -> '}'
'[' -> ']'
'(' -> ')'
'<' -> '>'
else -> error("Illegal state: $last")
}
}
return resString
}
fun mapToValue2(char: Char): Int {
// ): 1 point.
// ]: 2 points.
//}: 3 points.
//>: 4 points.
return when (char) {
')' -> 1
']' -> 2
'}' -> 3
'>' -> 4
else -> error("Illegal bracket: $char")
}
}
fun calculateAnswerFromLine(line: String): Long {
var counter = 0L
line.forEach {
counter = counter * 5 + mapToValue2(it)
}
return counter
}
fun main() {
fun part1(input: List<String>): Int {
return input
.map { processLine(it) }
.filterIsInstance<LineAnswer.Corrupted>()
.sumOf { charToValue(it.corruptedBy) }
}
fun part2(input: List<String>): Long {
val result = input
.asSequence()
.map { processLine(it) }
.filterIsInstance<LineAnswer.Incomplete>()
.map { createEndingLineForStack(it.stack) }
.map { answerLine -> calculateAnswerFromLine(answerLine) }
.sorted()
.toList()
return result[(result.size / 2)]
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day10_test")
val part1Test = part1(testInput)
val part2Test = part2(testInput)
println(part1Test)
println(part2Test)
check(part1Test == 26397)
check(part2Test == 288957L)
val input = readInput("Day10")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 5 | c0f36ec0e2ce5d65c35d408dd50ba2ac96363772 | 3,864 | KotlinAdventOfCode | Apache License 2.0 |
src/main/kotlin/Day12.kt | lanrete | 244,431,253 | false | null | import mathUti.lcm
import kotlin.math.abs
enum class Axis {
X,
Y,
Z,
ALL
}
data class Moon(var x: Int, var y: Int, var z: Int) {
private var vx = 0
private var vy = 0
private var vz = 0
val potentialEnergy: Int
get() {
return abs(x) + abs(y) + abs(z)
}
val kineticEnergy: Int
get() {
return abs(vx) + abs(vy) + abs(vz)
}
override fun toString(): String {
return "($x, $y, $z) with velocity of ($vx, $vy, $vz)"
}
fun updateVelocity(another: Moon, axis: Axis) {
when (axis) {
Axis.X -> {
if (another.x > x) vx += 1
if (another.x < x) vx -= 1
}
Axis.Y -> {
if (another.y > y) vy += 1
if (another.y < y) vy -= 1
}
Axis.Z -> {
if (another.z > z) vz += 1
if (another.z < z) vz -= 1
}
Axis.ALL -> {
for (it in listOf(Axis.X, Axis.Y, Axis.Z)) updateVelocity(another, it)
}
}
}
fun updateLocation(axis: Axis) {
when (axis) {
Axis.X -> x += vx
Axis.Y -> y += vy
Axis.Z -> z += vz
Axis.ALL -> {
for (it in listOf(Axis.X, Axis.Y, Axis.Z)) updateLocation(it)
}
}
}
}
object Day12 : Solver() {
override val day: Int = 12
override val inputs: List<String> = getInput()
private fun resetMoons(): List<Moon> {
return inputs.map {
val x = it.split(",").first().split("=").last().toInt()
val y = it.split(",")[1].split("=").last().toInt()
val z = it.split("=").last().split(">").first().toInt()
Moon(x, y, z)
}
}
private var moons = resetMoons()
private fun iterate(axis: Axis) {
moons.forEach { base ->
moons
.filter { it != base }
.forEach { base.updateVelocity(it, axis) }
}
moons.forEach { it.updateLocation(axis) }
}
override fun question1(): String {
repeat(1000) { iterate(Axis.ALL) }
return moons.map { it.kineticEnergy * it.potentialEnergy }.reduce { a, b -> a + b }.toString()
}
private fun findLoop(axis: Axis): Int {
moons = resetMoons()
val initialStage = resetMoons()
var cnt = 0
do {
iterate(axis)
cnt += 1
} while (moons.zip(initialStage).any { it.first != it.second })
return cnt + 1
}
override fun question2(): String {
return listOf(Axis.X, Axis.Y, Axis.Z)
.map {
val cycle = findLoop(it)
println("$cycle steps needed on Axis $it")
cycle.toLong()
}
.reduce { acc, i -> lcm(acc, i) }
.toString()
}
}
fun main() {
Day12.solveFirst()
Day12.solveSecond()
} | 0 | Kotlin | 0 | 1 | 15125c807abe53230e8d0f0b2ca0e98ea72eb8fd | 2,993 | AoC2019-Kotlin | MIT License |
src/main/kotlin/mirecxp/aoc23/day07/Day07.kt | MirecXP | 726,044,224 | false | {"Kotlin": 42343} | package mirecxp.aoc23.day07
import mirecxp.aoc23.readInput
//https://adventofcode.com/2023/day/7
class Day07(private val inputPath: String) {
private var hands: List<Hand> = readInput(inputPath).map { line ->
with(line.split(" ")) {
Hand(get(0), get(1).toInt())
}
}
fun mapCard(card: Char, part2: Boolean): Char {
return when (card) {
'A' -> 'A'
'K' -> 'B'
'Q' -> 'C'
'J' -> if (part2) 'N' else 'D'
'T' -> 'E'
'9' -> 'F'
'8' -> 'G'
'7' -> 'H'
'6' -> 'I'
'5' -> 'J'
'4' -> 'K'
'3' -> 'L'
'2' -> 'M'
else -> {
println("IMPOSSIBLE!")
'X'
}
}
}
class Hand(val cards: String, val bid: Int) {
fun getRegularType(handCards: String): HandType {
val sorted: Map<Char, List<Char>> = handCards.toList().sorted().groupBy { it }
return when (sorted.size) {
1 -> HandType.FIVE
2 -> {
if (sorted.values.maxBy { it.size }.size == 4) {
HandType.FOUR
} else {
HandType.FULLHOUSE
}
}
3 -> {
when (sorted.values.maxBy { it.size }.size) {
3 -> HandType.THREE
2 -> HandType.TWOPAIR
else -> HandType.IMPOSSIBLE
}
}
4 -> HandType.ONEPAIR
5 -> HandType.HIGH
else -> {
println("IMPOSSIBLE!")
HandType.IMPOSSIBLE
}
}
}
fun getType(part2: Boolean): HandType {
if (!part2) {
return getRegularType(cards)
} else {
var regularHandType = getRegularType(cards)
if (cards.contains('J')) {
if (regularHandType == HandType.HIGH) return HandType.ONEPAIR
if (regularHandType == HandType.ONEPAIR) {
check(
cards.count { it == 'J' } in 1..2
)
return HandType.THREE
}
if (regularHandType == HandType.TWOPAIR) {
return if (cards.count { it == 'J' } == 1) {
HandType.FULLHOUSE
} else {
check(cards.count { it == 'J' } == 2)
HandType.FOUR
}
}
if (regularHandType == HandType.THREE) {
check(cards.count { it == 'J' } == 1 || cards.count { it == 'J' } == 3)
return HandType.FOUR
}
if (regularHandType == HandType.FULLHOUSE) {
check(cards.count { it == 'J' } in 2..3)
return HandType.FIVE
}
if (regularHandType == HandType.FOUR) {
return if (cards.count { it == 'J' } == 1) {
HandType.FIVE
} else {
check(cards.count { it == 'J' } == 4)
HandType.FIVE
}
}
if (regularHandType == HandType.FIVE) return HandType.FIVE
}
return regularHandType
}
}
}
enum class HandType(val rank: Int) {
FIVE(6),
FOUR(5),
FULLHOUSE(4),
THREE(3),
TWOPAIR(2),
ONEPAIR(1),
HIGH(0),
IMPOSSIBLE(-1)
}
fun solve(part2: Boolean): String {
println("Solving day 7 for ${hands.size} hands [$inputPath]")
val topRank = hands.size
val groups: Map<HandType, List<Hand>> = hands.sortedBy { it.getType(part2) }.groupBy { it.getType(part2) }
val handsSorted = mutableListOf<Hand>()
HandType.values().sortedByDescending { it.rank }.forEach { handType ->
groups[handType]?.sortedBy { h ->
h.cards.map { mapCard(it, part2) }.toString()
}?.let {
handsSorted.addAll(it)
}
}
var result = 0L
handsSorted.forEachIndexed { index, hand ->
val r = hand.bid * (topRank - index)
result += r
}
val solution = "$result"
println(solution)
return solution
}
}
fun main(args: Array<String>) {
val testProblem = Day07("test/day07t")
check(testProblem.solve(part2 = false) == "6440")
check(testProblem.solve(part2 = true) == "5905")
val problem = Day07("real/day07a")
problem.solve(part2 = false)
problem.solve(part2 = true)
}
| 0 | Kotlin | 0 | 0 | 6518fad9de6fb07f28375e46b50e971d99fce912 | 5,060 | AoC-2023 | MIT License |
src/Day01.kt | RobvanderMost-TomTom | 572,005,233 | false | {"Kotlin": 47682} | fun main() {
fun foodPerElf(input: List<String>): List<List<String>> {
val separators = input.withIndex().filter { it.value.isEmpty() }.map { it.index }
return (listOf(-1) + separators + listOf(input.size)).zipWithNext().map { input.subList(it.first + 1, it.second) }
}
fun part1(input: List<String>): Int {
val elves = foodPerElf(input)
return elves.maxOf { food ->
food.sumOf { it.toInt() }
}
}
fun part2(input: List<String>): Int {
return foodPerElf(input)
.map { it.sumOf { it.toInt() }}
.sorted()
.takeLast(3)
.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 5 | Kotlin | 0 | 0 | b7143bceddae5744d24590e2fe330f4e4ba6d81c | 903 | advent-of-code-2022 | Apache License 2.0 |
src/day04/Code.kt | ldickmanns | 572,675,185 | false | {"Kotlin": 48227} | package day04
import readInput
fun main() {
val input = readInput("day04/input")
// val input = readInput("day04/input_test")
println(part1(input))
println(part2(input))
}
typealias IntPair = Pair<Int, Int>
val IntPair.lowerBound: Int get() = first
val IntPair.upperBound: Int get() = second
infix fun IntPair.isIn(other: IntPair) = (lowerBound >= other.lowerBound) and (upperBound <= other.upperBound)
infix fun IntPair.overlaps(other: IntPair) =
((lowerBound <= other.upperBound) and (lowerBound >= other.lowerBound)) or
((upperBound >= other.lowerBound) and (upperBound <= other.upperBound))
fun part1(input: List<String>): Int = input.fold(0) { acc: Int, line: String ->
val (firstBounds, secondBounds) = getBounds(line)
if ((firstBounds isIn secondBounds) or (secondBounds isIn firstBounds)) acc + 1 else acc
}
fun getBounds(line: String): Pair<IntPair, IntPair> {
val firstRange = line.substringBefore(',')
val secondRange = line.substringAfter(',')
val firstBounds = extractBounds(firstRange)
val secondBounds = extractBounds(secondRange)
return Pair(firstBounds, secondBounds)
}
fun extractBounds(string: String): Pair<Int, Int> {
val firstNumber = string.substringBefore('-').toInt()
val secondNumber = string.substringAfter('-').toInt()
return Pair(firstNumber, secondNumber)
}
fun part2(input: List<String>): Int = input.fold(0) { acc: Int, line: String ->
val (firstBounds, secondBounds) = getBounds(line)
if ((firstBounds overlaps secondBounds) or (secondBounds overlaps firstBounds)) acc + 1 else acc
} | 0 | Kotlin | 0 | 0 | 2654ca36ee6e5442a4235868db8174a2b0ac2523 | 1,607 | aoc-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/g1101_1200/s1170_compare_strings_by_frequency_of_the_smallest_character/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g1101_1200.s1170_compare_strings_by_frequency_of_the_smallest_character
// #Medium #Array #String #Hash_Table #Sorting #Binary_Search
// #2023_05_25_Time_221_ms_(50.00%)_Space_44_MB_(50.00%)
class Solution {
fun numSmallerByFrequency(queries: Array<String>, words: Array<String>): IntArray {
val queriesMinFrequecies = IntArray(queries.size)
for (i in queries.indices) {
queriesMinFrequecies[i] = computeLowestFrequency(queries[i])
}
val wordsMinFrequecies = IntArray(words.size)
for (i in words.indices) {
wordsMinFrequecies[i] = computeLowestFrequency(words[i])
}
wordsMinFrequecies.sort()
val result = IntArray(queries.size)
for (i in result.indices) {
result[i] = search(wordsMinFrequecies, queriesMinFrequecies[i])
}
return result
}
private fun search(nums: IntArray, target: Int): Int {
var count = 0
for (i in nums.indices.reversed()) {
if (nums[i] > target) {
count++
} else {
break
}
}
return count
}
private fun computeLowestFrequency(string: String): Int {
val str = string.toCharArray()
str.sort()
val sortedString = String(str)
var frequency = 1
for (i in 1 until sortedString.length) {
if (sortedString[i] == sortedString[0]) {
frequency++
} else {
break
}
}
return frequency
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,578 | LeetCode-in-Kotlin | MIT License |
src/Day11.kt | zt64 | 572,594,597 | false | null | import java.math.BigInteger
private object Day11 : Day(11) {
private val monkeys = input.split("\n\n").map(String::lines).map {
val operationString = it[2].substringAfter("= ")
val (_, op, b) = operationString.split(" ")
Monkey(
startingItems = it[1].substringAfter("Starting items: ")
.split(", ")
.map(String::toBigInteger)
.map(::Item)
.toMutableList(),
operation = when (op) {
"+" -> { old -> old + (b.toBigIntegerOrNull() ?: old) }
"*" -> { old -> old * (b.toBigIntegerOrNull() ?: old) }
"-" -> { old -> old - (b.toBigIntegerOrNull() ?: old) }
else -> throw Exception("Unknown operation $op")
},
test = Monkey.Test(
divisibleBy = it[3].substringAfter("by ").toInt(),
ifTrue = it[4].substringAfter("monkey ").toInt(),
ifFalse = it[5].substringAfter("monkey ").toInt()
)
)
}
override fun part1(): BigInteger {
repeat(20) {
monkeys.forEach { monkey ->
val copy = monkey.startingItems.toList()
copy.forEach { item ->
item.worryLevel = monkey.operation(item.worryLevel)
monkey.inspections++
item.worryLevel = item.worryLevel / BigInteger.valueOf(3)
val passIndex = if (item.worryLevel % monkey.test.divisibleBy.toBigInteger() == BigInteger.ZERO) {
monkey.test.ifTrue
} else {
monkey.test.ifFalse
}
monkeys[passIndex].startingItems += item
monkey.startingItems.removeFirst()
}
}
}
val (monkey1, monkey2) = monkeys.sortedByDescending(Monkey::inspections).take(2)
return monkey1.inspections * monkey2.inspections
}
override fun part2(): BigInteger {
repeat(10000) {
if (it % 100 == 0) println("Round $it")
monkeys.forEach { monkey ->
val copy = monkey.startingItems.toList()
copy.forEach { item ->
item.worryLevel = monkey.operation(item.worryLevel)
monkey.inspections++
val passIndex = if (item.worryLevel % monkey.test.divisibleBy.toBigInteger() == BigInteger.ZERO) {
monkey.test.ifTrue
} else {
monkey.test.ifFalse
}
monkeys[passIndex].startingItems += item
monkey.startingItems.removeFirst()
}
}
}
val (monkey1, monkey2) = monkeys.sortedByDescending(Monkey::inspections).take(2)
return monkey1.inspections * monkey2.inspections
}
data class Monkey(
val startingItems: MutableList<Item>,
val operation: (old: BigInteger) -> BigInteger,
val test: Test,
var inspections: BigInteger = BigInteger.ZERO
) {
class Test(
val divisibleBy: Int,
val ifTrue: Int,
val ifFalse: Int
)
}
data class Item(var worryLevel: BigInteger)
}
private fun main() = Day11.main() | 0 | Kotlin | 0 | 0 | 4e4e7ed23d665b33eb10be59670b38d6a5af485d | 3,382 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/cz/tomasbublik/Day03.kt | tomasbublik | 572,856,220 | false | {"Kotlin": 21908} | package cz.tomasbublik
fun main() {
fun getSameChar(firstHalf: CharSequence, secondHalf: CharSequence): Char {
for (firstChar in firstHalf) {
for (secondChar in secondHalf) {
if (firstChar == secondChar) {
return firstChar
}
}
}
throw IllegalStateException("Every line must have same chars!")
}
fun getSameChar(first: CharSequence, second: CharSequence, third: CharSequence): Char {
for (firstChar in first) {
for (secondChar in second) {
if (firstChar == secondChar) {
for (thirdChar in third) {
if (thirdChar == firstChar) {
return firstChar
}
}
}
}
}
throw IllegalStateException("Every line must have same chars!")
}
fun getPriorityForLetter(letter: Char): Int {
var c = 'a'
for (prio1 in 1..26) {
if (letter == c) {
return prio1
}
++c
}
c = 'A'
for (prio2 in 27..52) {
if (letter == c) {
return prio2
}
++c
}
throw IllegalStateException("Every possible letter must have a priority!")
}
fun part1(input: List<String>): Int {
val sameLettersList = ArrayList<Char>()
for (line in input) {
val firstHalf = line.subSequence(0, line.length / 2)
val secondHalf = line.subSequence(line.length / 2, line.length)
sameLettersList.add(getSameChar(firstHalf, secondHalf))
// println("half 1: $firstHalf, half 2: $secondHalf")
}
return sameLettersList.sumOf { getPriorityForLetter(it) }
}
fun part2(input: List<String>): Int {
val sameLettersList = ArrayList<Char>()
var tempInput = input
for (group in 1..(input.size / 3)) {
val currentGroup = tempInput.take(3)
tempInput = tempInput.drop(3)
sameLettersList.add(getSameChar(currentGroup[0], currentGroup[1], currentGroup[2]))
// println(currentGroup)
}
return sameLettersList.sumOf { getPriorityForLetter(it) }
}
// test if implementation meets criteria from the description, like:
val testInput = readFileAsLinesUsingUseLines("src/main/resources/day_3_input_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readFileAsLinesUsingUseLines("src/main/resources/day_3_input")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 8c26a93e8f6f7ab0f260c75a287608dd7218d0f0 | 2,692 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/Day03.kt | wedrychowiczbarbara | 573,185,235 | false | null | fun main() {
fun countPriority(letter: Char): Int{
val v = letter.code
if (v in 65..90) {
return v - 38
}
if (v in 95..126) {
return v - 96
}
return 0
}
fun part1(input: List<String>): Int {
var suma=0
input.forEach{
val line = it.toCharArray()
val l1 = line.copyOfRange(0, line.size/2).asIterable()
val l2 = line.copyOfRange(line.size/2, line.size).asIterable()
val c = l1.intersect(l2.toSet())
suma+=(countPriority(c.first()))
}
return suma
}
fun part2(input: List<String>): Int {
var suma=0
val newInput = input.windowed(3, step = 3)
newInput.forEach{
val subset = it[0].toCharArray().asIterable().intersect(
it[1].toCharArray().asIterable().toSet()
)
val result = subset.intersect(
it[2].toCharArray().asIterable().toSet())
suma+=(countPriority(result.first()))
}
return suma
}
val input = readInput("input3")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 04abc035c51649dffe1dde8a115d98640552a99d | 1,183 | AOC_2022_Kotlin | Apache License 2.0 |
src/Day25.kt | spaikmos | 573,196,976 | false | {"Kotlin": 83036} | fun main() {
fun snafuToDecimal(snafu: String): Long {
var num = 0L
for (c in snafu) {
num *= 5
when (c) {
'2' -> num += 2
'1' -> num += 1
'0' -> num += 0
'-' -> num -= 1
'=' -> num -= 2
}
}
return num
}
fun decimalToSnafu(num: Long): String {
var snafu = ""
var total = 0L
var digit = 5L
// The max number that can be represented is 3 times the MSB - 1
while ((digit * 3L) < num) {
digit *= 5L
}
val snafuChars = "=-012"
while (digit != 0L) {
// Generate list of values for this digit
val values = arrayListOf(-2L, -1L, 0L, 1L, 2L).map{ it * digit }
// Calculate the values when this digit is added to the string
val diff = values.map{ it -> Math.abs(it + total - num) }
// Find the minimum difference from the desired number. This is the digit to use.
val minIdx = diff.indexOf(diff.min())
snafu += snafuChars[minIdx]
total += values[minIdx]
digit /= 5L
}
return snafu
}
fun part1(input: List<String>): String {
var total = 0L
for (i in input) {
val num = snafuToDecimal(i)
total += num
}
return decimalToSnafu(total)
}
val input = readInput("../input/Day25")
println(part1(input)) // 2=112--220-=-00=-=20
}
| 0 | Kotlin | 0 | 0 | 6fee01bbab667f004c86024164c2acbb11566460 | 1,549 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/problems/Day3.kt | PedroDiogo | 432,836,814 | false | {"Kotlin": 128203} | package problems
class Day3(override val input: String) : Problem {
override val number: Int = 3
private val inputList = input.lines()
.map { line -> line.toCharArray().map { c -> c.digitToInt() }.toList() }
override fun runPartOne(): String {
val gammaRate = mostCommonBitPerPosition(inputList)
.toInt(2)
val numberOfBits = inputList.first().size
val mask = 1.shl(numberOfBits) - 1
val epsilonRate = gammaRate.xor(mask)
return (gammaRate * epsilonRate).toString()
}
override fun runPartTwo(): String {
val mostCommonBitBitCriteria = { l: List<List<Int>>, idx: Int ->
mostCommonBitPerPosition(l)[idx].digitToInt()
}
val leastCommonBitBitCriteria = { l: List<List<Int>>, idx: Int ->
mostCommonBitBitCriteria(l, idx).xor(1)
}
val oxygenGeneratorRating = searchRating(inputList, mostCommonBitBitCriteria)
val co2ScrubberRating = searchRating(inputList, leastCommonBitBitCriteria)
return (oxygenGeneratorRating * co2ScrubberRating).toString()
}
private fun mostCommonBitPerPosition(list: List<List<Int>>): String {
val numberOfNumbers = list.size
return rotateRight90(list)
.map { row -> row.sum() }
.map { i ->
when {
2 * i >= numberOfNumbers -> 1
else -> 0
}
}
.joinToString(separator = "")
}
private fun rotateRight90(list: List<List<Int>>): List<List<Int>> {
val rows = list.size
val columns = list.first().size
val rotatedList = List(columns) { MutableList(rows) { 0 } }
for (m in 0 until rows) {
for (n in 0 until columns) {
rotatedList[n][m] = list[m][n]
}
}
return rotatedList
}
private fun searchRating(initial: List<List<Int>>, bitCriteria: (list: List<List<Int>>, index: Int) -> Int): Int {
var list = initial
var index = 0
while (list.size > 1) {
list = list.filter { number ->
number[index] == bitCriteria(list, index)
}
index++
}
return list.single().joinToString(separator = "").toInt(2)
}
} | 0 | Kotlin | 0 | 0 | 93363faee195d5ef90344a4fb74646d2d26176de | 2,318 | AdventOfCode2021 | MIT License |
src/main/kotlin/y2022/day14/Day14.kt | TimWestmark | 571,510,211 | false | {"Kotlin": 97942, "Shell": 1067} | package y2022.day14
import Coord
fun main() {
AoCGenerics.printAndMeasureResults(
part1 = { part1() },
part2 = { part2() }
)
}
enum class Element {
ROCK,
SAND,
AIR,
SAND_SOURCE
}
fun input(): Pair<MutableMap<Int, MutableMap<Int, Element>>, Int> {
val allPaths = AoCGenerics.getInputLines("/y2022/day14/input.txt").map { line ->
val lineCoords = line.split(" -> ")
val paths: MutableList<Pair<Coord, Coord>> = mutableListOf()
for (i in 0 until lineCoords.size - 1) {
paths.add(
Pair(
Coord(
x = lineCoords[i].split(",")[0].toInt(),
y = lineCoords[i].split(",")[1].toInt(),
),
Coord(
x = lineCoords[i + 1].split(",")[0].toInt(),
y = lineCoords[i + 1].split(",")[1].toInt()
)
)
)
}
paths.toList()
}.flatten()
val maxFall = allPaths.map { pair -> listOf(pair.first, pair.second) }.flatten().maxOfOrNull { it.y }!!
val map: MutableMap<Int, MutableMap<Int, Element>> = mutableMapOf()
// TODO: Adjust these values
for (x in 0 until 1000) {
map[x] = mutableMapOf()
for (y in 0 until maxFall + 2) {
map[x]!![y] = Element.AIR
}
}
map[500]!![0] = Element.SAND_SOURCE
allPaths.forEach { path ->
val start = path.first
val end = path.second
for (x in minOf(start.x, end.x) .. maxOf(start.x, end.x) ) {
for(y in minOf(start.y, end.y) .. maxOf(start.y, end.y)) {
map[x]!![y] = Element.ROCK
}
}
}
return Pair(map, maxFall+2)
}
fun part1(): Int {
val map = input().first
var fallingIntoTheAbyss = false
var sandCounter = 0
while (!fallingIntoTheAbyss) {
var newSand = Coord(500,0)
sandCounter++
while (true) {
when {
map[newSand.x]!![newSand.y+1] == null -> {
fallingIntoTheAbyss = true
break
} // Endless abyss of Sand piles
map[newSand.x]!![newSand.y+1] == Element.AIR -> {
newSand = newSand.copy(y = newSand.y + 1) // move down
continue
}
map[newSand.x-1]!![newSand.y+1] == Element.AIR -> {
newSand = newSand.copy(x = newSand.x-1 ,y = newSand.y + 1) // move down left
continue
}
map[newSand.x+1]!![newSand.y+1] == Element.AIR -> {
newSand = newSand.copy(x = newSand.x+1 ,y = newSand.y + 1) // move down right
continue
}
else -> {
map[newSand.x]!![newSand.y] = Element.SAND // Sand block has been placed
break
}
}
}
}
return sandCounter-1
}
fun part2(): Int {
val map = input().first
val maxY = input().second
for (x in 0 until 1000) {
map[x]!![maxY] = Element.ROCK
}
var fallingIntoTheAbyss = false
var sandCounter = 0
while (!fallingIntoTheAbyss) {
var newSand = Coord(500,0)
sandCounter++
while (true) {
when {
map[newSand.x]!![newSand.y+1] == null -> {
fallingIntoTheAbyss = true // Endless abyss of Sand piles
break
}
map[newSand.x]!![newSand.y+1] == Element.AIR -> {
newSand = newSand.copy(y = newSand.y + 1) // move down
continue
}
map[newSand.x-1]!![newSand.y+1] == Element.AIR -> {
newSand = newSand.copy(x = newSand.x-1 ,y = newSand.y + 1) // move down left
continue
}
map[newSand.x+1]!![newSand.y+1] == Element.AIR -> {
newSand = newSand.copy(x = newSand.x+1 ,y = newSand.y + 1) // move down right
continue
}
else -> {
map[newSand.x]!![newSand.y] = Element.SAND // Sand block has been placed
if (newSand.x == 500 && newSand.y == 0) fallingIntoTheAbyss = true
break
}
}
}
}
return sandCounter
}
| 0 | Kotlin | 0 | 0 | 23b3edf887e31bef5eed3f00c1826261b9a4bd30 | 4,506 | AdventOfCode | MIT License |
aoc21/day_16/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 Packet(val version: Int, val id: Int) {
var value: Long = 0
val innerPackets = mutableListOf<Packet>()
var len = 0
fun versionSum(): Int = version + innerPackets.map { it.versionSum() }.sum()
fun eval(): Long = when (id) {
0 -> innerPackets.map { it.eval() }.sum()
1 -> innerPackets.fold(1) { prod, p -> prod * p.eval() }
2 -> innerPackets.map { it.eval() }.minOrNull()!!
3 -> innerPackets.map { it.eval() }.maxOrNull()!!
4 -> value
5 -> if (innerPackets[0].eval() > innerPackets[1].eval()) 1 else 0
6 -> if (innerPackets[0].eval() < innerPackets[1].eval()) 1 else 0
7 -> if (innerPackets[0].eval() == innerPackets[1].eval()) 1 else 0
else -> 0
}
}
fun parse(str: String): Packet {
val version = str.substring(0, 3).toInt(radix = 2)
val id = str.substring(3, 6).toInt(radix = 2)
val packet = Packet(version, id)
var headerLen = 6
var contentLen = 0
if (id == 4) {
var value = 0.toLong()
for (byte in str.substring(6).chunked(5)) {
value = (value * 16) + byte.substring(1).toInt(radix = 2)
contentLen += 5
if (byte[0] == '0') break
}
packet.value = value
} else {
val cond: (Int, Int, Int) -> Boolean
if (str[6] == '0') {
cond = { _, read, bound -> read < bound }
headerLen += 16
} else {
cond = { i, _, bound -> i < bound }
headerLen += 12
}
val bound = str.substring(7, headerLen).toInt(radix = 2)
var i = 0
while (cond(i, contentLen, bound)) {
packet.innerPackets.add(parse(str.substring(headerLen + contentLen)))
contentLen += packet.innerPackets.last().len
i += 1
}
}
packet.len = headerLen + contentLen
return packet
}
fun String.toBin(): String = this.map {
Integer.toBinaryString(it.toString().toInt(radix = 16)).padStart(4, '0')
}.joinToString("")
fun main() {
val input = File("input").readText().trim().toBin()
val packet = parse(input)
println("First: ${packet.versionSum()}")
println("Second: ${packet.eval()}")
}
| 0 | Rust | 1 | 0 | f47ef85393d395710ce113708117fd33082bab30 | 2,240 | advent-of-code | MIT License |
src/org/aoc2021/Day19.kt | jsgroth | 439,763,933 | false | {"Kotlin": 86732} | package org.aoc2021
import java.nio.file.Files
import java.nio.file.Path
import kotlin.math.abs
typealias Vector = List<Int>
typealias Matrix = List<List<Int>>
private fun Vector.vectorAdd(vector: Vector): Vector {
return this.mapIndexed { i, value ->
value + vector[i]
}
}
private fun Vector.vectorSubtract(vector: Vector): Vector {
return this.mapIndexed { i, value ->
value - vector[i]
}
}
private fun Vector.matrixMultiply(matrix: Matrix): Vector {
return this.indices.map { i ->
matrix.indices.sumOf { j ->
this[j] * matrix[j][i]
}
}
}
private fun Matrix.multiply(matrix: Matrix): Matrix {
return this.map { vector -> vector.matrixMultiply(matrix) }
}
object Day19 {
data class ScannerLocation(val coordinates: Vector, val rotation: Matrix)
private val identityMatrix = listOf(
listOf(1, 0, 0),
listOf(0, 1, 0),
listOf(0, 0, 1),
)
private val xRotationMatrix = listOf(
listOf(1, 0, 0),
listOf(0, 0, -1),
listOf(0, 1, 0),
)
private val yRotationMatrix = listOf(
listOf(0, 0, -1),
listOf(0, 1, 0),
listOf(1, 0, 0),
)
private val zRotationMatrix = listOf(
listOf(0, 1, 0),
listOf(-1, 0, 0),
listOf(0, 0, 1),
)
private val all3DRotationMatrices = generateRotationMatrices()
private fun solve(lines: List<String>): Pair<Int, Int> {
val scanners = parseLines(lines)
val scannerLocations = findScanners(scanners)
val solution1 = countBeacons(scanners, scannerLocations)
val solution2 = scannerLocations.values.maxOf { a ->
scannerLocations.values.filter { it !== a }.maxOf { b ->
a.coordinates.vectorSubtract(b.coordinates).map(::abs).sum()
}
}
return solution1 to solution2
}
private fun parseLines(lines: List<String>): List<List<Vector>> {
if (lines.isEmpty()) {
return listOf()
}
val nextScanner = lines.drop(1)
.takeWhile(String::isNotBlank)
.map { line -> line.split(",").map(String::toInt) }
return listOf(nextScanner).plus(parseLines(lines.dropWhile(String::isNotBlank).drop(1)))
}
private fun findScanners(scanners: List<List<Vector>>): Map<Int, ScannerLocation> {
val scannerLocations = mutableMapOf(
0 to ScannerLocation(listOf(0, 0, 0), identityMatrix),
)
// Triple(rotation matrix, base beacon, other beacon distances)
val precomputedRotatedDistances = scanners.mapIndexed { i, beaconLocations ->
i to beaconLocations.flatMap { beaconLocation ->
all3DRotationMatrices.map { rotationMatrix ->
val rotatedBeaconLocation = beaconLocation.matrixMultiply(rotationMatrix)
val rotatedBeaconDistances = beaconLocations.filter { it !== beaconLocation }
.map { it.matrixMultiply(rotationMatrix).vectorSubtract(rotatedBeaconLocation) }
Triple(rotationMatrix, rotatedBeaconLocation, rotatedBeaconDistances.toSet())
}
}
}.toMap()
while (scannerLocations.size < scanners.size) {
val foundScannerIds = scanners.indices.filter { i -> scannerLocations.containsKey(i) }
foundScannerIds.forEach { foundScannerId ->
val foundScannerLocation = scannerLocations[foundScannerId]!!
val foundBeaconDistances = precomputedRotatedDistances[foundScannerId]!!
.filter { (rotationMatrix, _, _) -> rotationMatrix == foundScannerLocation.rotation }
val unknownScannerIds = scanners.indices.filter { i -> !scannerLocations.containsKey(i) }
unknownScannerIds.forEach { unknownScannerId ->
for (t in precomputedRotatedDistances[unknownScannerId]!!) {
val (rotationMatrix, rotatedBeaconLocation, rotatedBeaconDistances) = t
val matchingFoundDistances = foundBeaconDistances.find { (_, _, foundDistancesSet) ->
foundDistancesSet.intersect(rotatedBeaconDistances).size >= 11
}
if (matchingFoundDistances != null) {
val (_, foundBeaconLocation, _) = matchingFoundDistances
val scannerCoordinates = foundScannerLocation.coordinates
.vectorAdd(foundBeaconLocation)
.vectorSubtract(rotatedBeaconLocation)
scannerLocations[unknownScannerId] = ScannerLocation(scannerCoordinates, rotationMatrix)
break
}
}
}
}
}
return scannerLocations.toMap()
}
private fun countBeacons(scanners: List<List<Vector>>, scannerLocations: Map<Int, ScannerLocation>): Int {
val allBeaconLocations = mutableSetOf<Vector>()
scanners.forEachIndexed { i, beaconLocations ->
val scannerLocation = scannerLocations[i]!!
allBeaconLocations.addAll(beaconLocations.map { beaconLocation ->
beaconLocation.matrixMultiply(scannerLocation.rotation).vectorAdd(scannerLocation.coordinates)
})
}
return allBeaconLocations.size
}
private fun generateRotationMatrices(): List<Matrix> {
val result = mutableListOf<Matrix>()
var currentMatrix = identityMatrix
listOf(
zRotationMatrix to yRotationMatrix,
yRotationMatrix to xRotationMatrix,
xRotationMatrix to zRotationMatrix,
).forEach { (axis1Matrix, axis2Matrix) ->
currentMatrix = currentMatrix.multiply(axis2Matrix)
result.addAll(generateRotationMatricesForAxis(currentMatrix, axis1Matrix))
currentMatrix = currentMatrix.multiply(axis2Matrix).multiply(axis2Matrix)
result.addAll(generateRotationMatricesForAxis(currentMatrix, axis1Matrix))
}
return result.toList()
}
private fun generateRotationMatricesForAxis(matrix: Matrix, rotation: Matrix): List<Matrix> {
val result = mutableListOf<Matrix>()
var current = matrix
(1..4).forEach { _ ->
result.add(current)
current = current.multiply(rotation)
}
return result.toList()
}
@JvmStatic
fun main(args: Array<String>) {
val lines = Files.readAllLines(Path.of("input19.txt"), Charsets.UTF_8)
val (solution1, solution2) = solve(lines)
println(solution1)
println(solution2)
}
} | 0 | Kotlin | 0 | 0 | ba81fadf2a8106fae3e16ed825cc25bbb7a95409 | 6,791 | advent-of-code-2021 | The Unlicense |
src/main/kotlin/com/ginsberg/advent2021/Day24.kt | tginsberg | 432,766,033 | false | {"Kotlin": 92813} | /*
* Copyright (c) 2021 by <NAME>
*/
/**
* Advent of Code 2021, Day 24 - Arithmetic Logic Unit
* Problem Description: http://adventofcode.com/2021/day/24
* Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2021/day24/
*/
package com.ginsberg.advent2021
class Day24(input: List<String>) {
private val magicParameters: List<Parameters> = parseMagicParameters(input)
fun solvePart1(): Long = solve().second
fun solvePart2(): Long = solve().first
private fun solve(): Pair<Long, Long> {
var zValues = mutableMapOf(0L to (0L to 0L))
magicParameters.forEach { parameters ->
val zValuesThisRound = mutableMapOf<Long, Pair<Long, Long>>()
zValues.forEach { (z, minMax) ->
(1..9).forEach { digit ->
val newValueForZ = magicFunction(parameters, z, digit.toLong())
if (parameters.a == 1 || (parameters.a == 26 && newValueForZ < z)) {
zValuesThisRound[newValueForZ] =
minOf(zValuesThisRound[newValueForZ]?.first ?: Long.MAX_VALUE, minMax.first * 10 + digit) to
maxOf(zValuesThisRound[newValueForZ]?.second ?: Long.MIN_VALUE, minMax.second * 10 + digit)
}
}
}
zValues = zValuesThisRound
}
return zValues.getValue(0)
}
private fun magicFunction(parameters: Parameters, z: Long, w: Long): Long =
if (z % 26 + parameters.b != w) ((z / parameters.a) * 26) + w + parameters.c
else z / parameters.a
private class Parameters(val a: Int, val b: Int, val c: Int)
private fun parseMagicParameters(input: List<String>): List<Parameters> =
input.chunked(18).map {
Parameters(
it[4].substringAfterLast(" ").toInt(),
it[5].substringAfterLast(" ").toInt(),
it[15].substringAfterLast(" ").toInt()
)
}
}
| 0 | Kotlin | 2 | 34 | 8e57e75c4d64005c18ecab96cc54a3b397c89723 | 2,006 | advent-2021-kotlin | Apache License 2.0 |
src/Day12.kt | rosyish | 573,297,490 | false | {"Kotlin": 51693} | private data class Cell(val x: Int, val y: Int, val elevation: Char, val steps: Int)
fun main() {
fun elevation(input: Char): Char {
return when (input) {
'S' -> 'a'
'E' -> 'z'
else -> input
}
}
fun solve(input: List<String>, isStartingCell: (Char) -> Boolean) {
val queue = ArrayDeque<Cell>()
input.forEachIndexed { x, str ->
str.forEachIndexed { y, ch ->
if (isStartingCell(ch)) {
queue.add(Cell(x, y, elevation('a'), 0))
}
}
}
val visited: MutableSet<Pair<Int, Int>> = mutableSetOf()
val next = listOf(Pair(0, 1), Pair(1, 0), Pair(0, -1), Pair(-1, 0))
while (queue.isNotEmpty()) {
val current: Cell = queue.removeFirst()
if (Pair(current.x, current.y) in visited) continue
for ((dx, dy) in next) {
val (neighborX, neighborY) = Pair(current.x + dx, current.y + dy)
if (neighborX in input.indices && neighborY in input[0].indices) {
val neighborElevation = elevation(input[neighborX][neighborY])
if (neighborElevation - current.elevation <= 1) {
queue.add(Cell(neighborX, neighborY, neighborElevation, current.steps + 1))
}
}
}
visited.add(Pair(current.x, current.y))
if (input[current.x][current.y] == 'E') {
println(current.steps)
break
}
}
}
val input = readInput("Day12_input")
val isStartingCellPart1: (Char) -> Boolean = { ch -> ch == 'S' }
val isStartingCellPart2: (Char) -> Boolean = { ch -> ch == 'S' || ch == 'a' }
solve(input, isStartingCellPart1)
solve(input, isStartingCellPart2)
} | 0 | Kotlin | 0 | 2 | 43560f3e6a814bfd52ebadb939594290cd43549f | 1,868 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/leetcode/uber/StringCompressionII.kt | Magdi | 390,731,717 | false | null | package leetcode.uber
/**
* 1531. String Compression II
* https://leetcode.com/problems/string-compression-ii/
*/
typealias Length = Int
class StringCompressionII {
fun getLengthOfOptimalCompression(s: String, k: Int): Int {
if (s.isEmpty()) return 0
val compressions = mutableListOf<Compression>()
var cnt = 0
var cur = s[0]
s.forEachIndexed { index, c ->
if (c != cur) {
compressions.add(Compression(cur, cnt))
cur = c
cnt = 1
} else {
cnt++
}
if (index == s.lastIndex) {
compressions.add(Compression(cur, cnt))
}
}
return minLength(0, null, k, compressions, hashMapOf())
}
fun minLength(
ind: Int,
prev: Compression? = null,
rem: Int,
compressions: List<Compression>,
cache: HashMap<State, Length>
): Length {
if (ind > compressions.size || rem < 0) return 102
if (ind == compressions.size) return 0
val key = State(ind, prev, rem)
if (cache.contains(key)) {
return cache[key]!!
}
val cur = compressions[ind]
var min = 102
if (prev?.char != cur.char) {
for (r in 0..Math.min(rem, cur.cnt)) {
val nCnt = cur.cnt - r
val nPrev = if (nCnt == 0) prev else cur.copy(cnt = nCnt)
min = Math.min(min, length(nCnt) + minLength(ind + 1, nPrev, rem - r, compressions, cache))
}
} else {
val newCnt = prev.cnt + cur.cnt
min = minLength(
ind + 1,
cur.copy(cnt = newCnt),
rem,
compressions,
cache
) - length(prev.cnt) + length(newCnt)
}
cache[key] = min
return min
}
private fun length(nCnt: Int): Int {
return when (nCnt) {
0 -> 0
1 -> 1
else -> {
1 + nCnt.toString().length
}
}
}
data class Compression(val char: Char, val cnt: Int)
data class State(val ind: Int, val compression: Compression?, val rem: Int)
} | 0 | Kotlin | 0 | 0 | 63bc711dc8756735f210a71454144dd033e8927d | 2,260 | ProblemSolving | Apache License 2.0 |
src/Day06.kt | papichulo | 572,669,466 | false | {"Kotlin": 16864} | fun main() {
fun solve(input: String, distinct: Int): Int {
var result = distinct
input.windowed(distinct).forEach {
if (it.toCharArray().distinct().size == distinct) {
return result
}
result++
}
return result
}
fun part2(input: String): Int {
return solve(input, 14)
}
fun part1(input: String): Int {
return solve(input, 4)
}
// test if implementation meets criteria from the description, like:
//val testInput = readInput("Day06_test")
check(part1("mjqjpqmgbljsphdztnvjfqwrcgsmlb") == 7)
check(part1("bvwbjplbgvbhsrlpgdmjqwftvncz") == 5)
check(part1("nppdvjthqldpwncqszvftbrmjlhg") == 6)
check(part1("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg") == 10)
check(part1("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw") == 11)
check(part2("mjqjpqmgbljsphdztnvjfqwrcgsmlb") == 19)
check(part2("bvwbjplbgvbhsrlpgdmjqwftvncz") == 23)
check(part2("nppdvjthqldpwncqszvftbrmjlhg") == 23)
check(part2("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg") == 29)
check(part2("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw") == 26)
val input = readInput("Day06")
println(part1(input.first()))
println(part2(input.first()))
}
| 0 | Kotlin | 0 | 0 | e277ee5bca823ce3693e88df0700c021e9081948 | 1,249 | aoc-2022-in-kotlin | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/PerfectRectangle.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import java.util.PriorityQueue
import java.util.TreeSet
import kotlin.math.max
import kotlin.math.min
/**
* 391. Perfect Rectangle
* @see <a href="https://leetcode.com/problems/perfect-rectangle/">Source</a>
*/
fun interface PerfectRectangle {
fun isRectangleCover(rectangles: Array<IntArray>): Boolean
}
class PerfectRectangleSweepLine : PerfectRectangle {
override fun isRectangleCover(rectangles: Array<IntArray>): Boolean {
val pq: PriorityQueue<Event> = PriorityQueue<Event>()
// border of y-intervals
val border = intArrayOf(Int.MAX_VALUE, Int.MIN_VALUE)
if (rectangles.size == 1 && rectangles.first().isEmpty()) {
return false
}
for (rect in rectangles) {
val e1 = Event(rect[0], rect)
val e2 = Event(rect[2], rect)
pq.add(e1)
pq.add(e2)
if (rect[1] < border[0]) border[0] = rect[1]
if (rect[3] > border[1]) border[1] = rect[3]
}
val set = TreeSet(
Comparator<IntArray> { rect1, rect2 ->
// if two y-intervals intersects, return 0
if (rect1[3] <= rect2[1]) -1 else if (rect2[3] <= rect1[1]) 1 else 0
},
)
var yRange = 0
while (pq.isNotEmpty()) {
val time: Int = pq.peek().time
while (pq.isNotEmpty() && pq.peek().time == time) {
val (_, rect) = pq.poll()
if (time == rect[2]) {
set.remove(rect)
yRange -= rect[3] - rect[1]
} else {
if (!set.add(rect)) return false
yRange += rect[3] - rect[1]
}
}
// check intervals' range
if (pq.isNotEmpty() && yRange != border[1] - border[0]) {
return false
}
}
return rectangles.isNotEmpty()
}
data class Event(var time: Int, var rect: IntArray) : Comparable<Event> {
override operator fun compareTo(other: Event): Int {
return if (time != other.time) time - other.time else rect[0] - other.rect[0]
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Event
if (time != other.time) return false
if (!rect.contentEquals(other.rect)) return false
return true
}
override fun hashCode(): Int {
var result = time
result = HASH_CODE_VALUE * result + rect.contentHashCode()
return result
}
companion object {
private const val HASH_CODE_VALUE = 31
}
}
}
class PerfectRectangleEasy : PerfectRectangle {
override fun isRectangleCover(rectangles: Array<IntArray>): Boolean {
if (rectangles.isEmpty() || rectangles[0].isEmpty()) return false
var x1 = Int.MAX_VALUE
var x2 = Int.MIN_VALUE
var y1 = Int.MAX_VALUE
var y2 = Int.MIN_VALUE
val set = HashSet<String>()
var area = 0
for (rect in rectangles) {
x1 = min(rect[0], x1)
y1 = min(rect[1], y1)
x2 = max(rect[2], x2)
y2 = max(rect[3], y2)
area += (rect[2] - rect[0]) * (rect[3] - rect[1])
val s1 = rect[0].toString() + " " + rect[1]
val s2 = rect[0].toString() + " " + rect[3]
val s3 = rect[2].toString() + " " + rect[3]
val s4 = rect[2].toString() + " " + rect[1]
if (!set.add(s1)) set.remove(s1)
if (!set.add(s2)) set.remove(s2)
if (!set.add(s3)) set.remove(s3)
if (!set.add(s4)) set.remove(s4)
}
val x1y1 = !set.contains("$x1 $y1")
val x1y2 = !set.contains("$x1 $y2")
val x2y1 = !set.contains("$x2 $y1")
val x2y2 = !set.contains("$x2 $y2")
val condition1 = x1y1 || x1y2 || x2y1 || x2y2 || set.size != 4
return if (condition1) {
false
} else {
area == (x2 - x1) * (y2 - y1)
}
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 4,823 | kotlab | Apache License 2.0 |
src/Day08.kt | KarinaCher | 572,657,240 | false | {"Kotlin": 21749} | fun main() {
/*
A tree is visible if all of the other trees between it and an edge of the grid are shorter than it
*/
fun isVisibleTree(x: Int, y: Int, forest: List<String>): Boolean {
val line = forest.get(x).toCharArray().toMutableList()
val column = forest.map { it.get(y) }.toMutableList()
val treeHeight = line.get(y).digitToInt()
// remove tree from calculation
line.removeAt(y)
column.removeAt(x)
val fromTop = column.subList(0, x)
val fromBottom = column.subList(x, column.size)
val fromLeft = line.subList(0, y)
val fromRight = line.subList(y, line.size)
//println("Tree $x,$y height $treeHeight $fromTop,$fromBottom $fromLeft,$fromRight]")
val top = fromTop.stream().mapToInt { it.digitToInt() }.max()
if (!top.isPresent || top.asInt < treeHeight) {
return true
}
val bottom = fromBottom.stream().mapToInt { it.digitToInt() }.max()
if (!bottom.isPresent || bottom.asInt < treeHeight) {
return true
}
val left = fromLeft.stream().mapToInt { it.digitToInt() }.max()
if (!left.isPresent || left.asInt < treeHeight) {
return true
}
val right = fromRight.stream().mapToInt { it.digitToInt() }.max()
if (!right.isPresent || right.asInt < treeHeight) {
return true
}
return false
}
fun getVisibleTrees(input: List<String>): List<Pair<Int, Int>> {
var result = mutableListOf<Pair<Int, Int>>()
for (x in 0 until input.size) {
for (y in 0 until input.get(0).length) {
if (isVisibleTree(x, y, input)) {
result.add(x to y)
}
}
}
return result
}
fun getScenicScore(x: Int, y: Int, forest: List<String>): Int {
val line = forest.get(x).toCharArray().toMutableList()
val column = forest.map { it.get(y) }.toMutableList()
val treeHeight = line.get(y).digitToInt()
// remove tree from calculation
line.removeAt(y)
column.removeAt(x)
val fromTop = column.subList(0, x)
val fromBottom = column.subList(x, column.size)
val fromLeft = line.subList(0, y)
val fromRight = line.subList(y, line.size)
var topSize = 0
var bottomSize = 0
var leftSize = 0
var rightSize = 0
val top = fromTop.reversed().takeWhile {
topSize++
it.digitToInt() < treeHeight
}
val bottom = fromBottom.takeWhile {
bottomSize++
it.digitToInt() < treeHeight
}
val left = fromLeft.reversed().takeWhile {
leftSize++
it.digitToInt() < treeHeight
}
val right = fromRight.takeWhile {
rightSize++
it.digitToInt() < treeHeight
}
// println("Tree $x,$y height $treeHeight $top,$bottom $left,$right")
return topSize * bottomSize * leftSize * rightSize
}
fun part1(input: List<String>): Int {
return getVisibleTrees(input).size
}
fun part2(input: List<String>): Int {
var result = 0;
for (x in 0 until input.size) {
for (y in 0 until input.get(0).length) {
result = Math.max(result, getScenicScore(y, x, input))
}
}
return result
}
val testInput = readInput("Day08_test")
check(part1(testInput) == 21)
check(part2(testInput) == 8)
val input = readInput("Day08")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 17d5fc87e1bcb2a65764067610778141110284b6 | 3,657 | KotlinAdvent | Apache License 2.0 |
src/Day04.kt | wmichaelshirk | 573,031,182 | false | {"Kotlin": 19037} | import kotlin.math.max
fun main() {
fun inputToRangePairs (input: String): Pair<IntRange, IntRange> {
val pairList = input.split(",")
.map { p ->
p.split("-")
.map { p -> p.toInt() }
}
.map { p ->
p.first()..p.last()
}
return pairList.first() to pairList.last()
}
fun part1(input: List<String>): Int {
return input
.map { inputToRangePairs(it) }
.count { it.first.union(it.second).count() == max(it.first.count(), it.second.count()) }
}
fun part2(input: List<String>): Int {
return input.map { inputToRangePairs(it) }
.count {
it.first.intersect(it.second).isNotEmpty()
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 2 | b748c43e9af05b9afc902d0005d3ba219be7ade2 | 1,074 | 2022-Advent-of-Code | Apache License 2.0 |
src/main/kotlin/com/chriswk/aoc/advent2021/Day11.kt | chriswk | 317,863,220 | false | {"Kotlin": 481061} | package com.chriswk.aoc.advent2021
import com.chriswk.aoc.AdventDay
import com.chriswk.aoc.util.Pos
import com.chriswk.aoc.util.report
class Day11 : AdventDay(2021, 11) {
companion object {
@JvmStatic
fun main(args: Array<String>) {
val day = Day11()
report {
day.part1()
}
report {
day.part2()
}
}
}
fun parseInput(lines: List<String>): MutableMap<Pos, Int> {
return lines.flatMapIndexed { y, line ->
line.mapIndexed { x, level ->
Pos(x, y) to Character.getNumericValue(level)
}
}.toMap().toMutableMap()
}
fun step(grid: Grid): Sequence<Grid> {
return generateSequence(grid) { p ->
p.step()
}
}
fun allFlashingGeneration(grid: Grid): Int {
return step(grid).first { it.allFlashing }.generation
}
fun steps(grid: Grid, days: Int): Grid {
return step(grid).drop(days).first()
}
data class Grid(val octopi: MutableMap<Pos, Int>, val maxX: Int, val maxY: Int, val flashCount: Int = 0, val generation: Int = 0, val allFlashing: Boolean = false) {
val size = octopi.size
fun step(): Grid {
octopi.keys.forEach { k -> octopi[k] = octopi.getValue(k) + 1 }
flash(emptySet()) // flash excited octopi
val flashedThisGen = octopi.values.count { it > 9 }
octopi.entries.filter { it.value > 9 }.forEach { (k, _) ->
octopi[k] = 0
}
return copy(flashCount = flashCount + flashedThisGen, generation = generation + 1, allFlashing = flashedThisGen == size)
}
fun flash(visited: Set<Pos>): Set<Pos> {
val flashingOctopi = octopi.keys.filter { !visited.contains(it) && octopi.getValue(it) > 9 }
val flashedOctopi = flashingOctopi.flatMap { k -> k.neighbours().filter { it.isInGrid(maxX, maxY) } }
flashedOctopi.forEach {
octopi[it] = octopi.getValue(it) + 1
}
return if (flashingOctopi.isEmpty()) {
visited
} else {
flash(visited.union(flashingOctopi))
}
}
override fun toString(): String {
return (0.until(maxX)).joinToString("\n") { x ->
(0.until(maxY)).joinToString("") { y ->
"${octopi[Pos(x, y)]!!}"
}
}
}
}
fun part1(): Int {
val octopuses = parseInput(inputAsLines)
val grid = Grid(octopuses, inputAsLines.size, inputAsLines[0].length)
return steps(grid, 100).flashCount
}
fun part2(): Int {
val octopuses = parseInput(inputAsLines)
val grid = Grid(octopuses, inputAsLines.size, inputAsLines[0].length)
return allFlashingGeneration(grid)
}
}
| 116 | Kotlin | 0 | 0 | 69fa3dfed62d5cb7d961fe16924066cb7f9f5985 | 2,923 | adventofcode | MIT License |
year2023/src/main/kotlin/net/olegg/aoc/year2023/day15/Day15.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.year2023.day15
import net.olegg.aoc.someday.SomeDay
import net.olegg.aoc.utils.toPair
import net.olegg.aoc.year2023.DayOf2023
import net.olegg.aoc.year2023.day15.Day15.Step.Companion.toStep
/**
* See [Year 2023, Day 15](https://adventofcode.com/2023/day/15)
*/
object Day15 : DayOf2023(15) {
override fun first(): Any? {
return data.split(",").sumOf { step ->
step.hash()
}
}
override fun second(): Any? {
val steps = data.split(",").map { it.toStep() }
val boxes = List(256) { LinkedHashMap<String, Int>() }
steps.forEach { step ->
val index = step.label.hash()
when (step) {
is Step.Remove -> boxes[index].remove(step.label)
is Step.Add -> boxes[index][step.label] = step.value
}
}
return boxes.mapIndexed { box, lenses ->
(box + 1) * lenses.values.mapIndexed { index, value -> (index + 1) * value }.sum()
}.sum()
}
private fun String.hash() = fold(0) { acc, char -> (acc + char.code) * 17 % 256 }
sealed interface Step {
val label: String
data class Add(
override val label: String,
val value: Int,
) : Step
data class Remove(
override val label: String,
) : Step
companion object {
fun String.toStep() = when {
last() == '-' -> Remove(dropLast(1))
else -> split("=").toPair().let { Add(it.first, it.second.toInt()) }
}
}
}
}
fun main() = SomeDay.mainify(Day15)
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 1,467 | adventofcode | MIT License |
kotlin/src/main/kotlin/com/github/jntakpe/aoc2021/days/day25/Day25.kt | jntakpe | 433,584,164 | false | {"Kotlin": 64657, "Rust": 51491} | package com.github.jntakpe.aoc2021.days.day25
import com.github.jntakpe.aoc2021.shared.Day
import com.github.jntakpe.aoc2021.shared.readInputLines
object Day25 : Day {
override val input = parseInput()
override fun part1(): Number {
var steps = 0
var seafloor = input
while (true) {
steps++
seafloor.move(SeaCucumber.EAST).move(SeaCucumber.SOUTH).run { if (this == seafloor) return steps else seafloor = this }
}
}
override fun part2() = 0
private fun parseInput(): Seafloor {
return readInputLines(25)
.flatMapIndexed { y, line -> line.toCharArray().mapIndexed { x, c -> Position(x, y) to SeaCucumber.from(c) } }
.toMap()
.let { l -> Seafloor(l, l.keys.run { Position(count { it.y == 0 }, count { it.x == 0 }) }) }
}
data class Seafloor(val locations: Map<Position, SeaCucumber?>, private val dimensions: Position) {
fun move(cucumber: SeaCucumber) = copy(locations = buildMap {
putAll(locations)
(0 until dimensions.y).flatMap { y -> (0 until dimensions.x).map { x -> Position(x, y) } }
.filter { locations[it] == cucumber }
.forEach {
val next = it.next(cucumber)
if (locations[next] == null) {
put(it, null)
put(next, cucumber)
}
}
})
private fun Position.next(cucumber: SeaCucumber) = when (cucumber) {
SeaCucumber.EAST -> copy(x = (x + 1) % dimensions.x)
SeaCucumber.SOUTH -> copy(y = (y + 1) % dimensions.y)
}
}
data class Position(val x: Int, val y: Int)
enum class SeaCucumber {
EAST,
SOUTH;
companion object {
fun from(char: Char) = when (char) {
'>' -> EAST
'v' -> SOUTH
'.' -> null
else -> error("Illegal $char character")
}
}
}
}
| 0 | Kotlin | 1 | 5 | 230b957cd18e44719fd581c7e380b5bcd46ea615 | 2,056 | aoc2021 | MIT License |
src/main/kotlin/se/saidaspen/aoc/aoc2023/Day05.kt | saidaspen | 354,930,478 | false | {"Kotlin": 301372, "CSS": 530} | package se.saidaspen.aoc.aoc2023
import se.saidaspen.aoc.util.*
fun main() = Day05.run()
object Day05 : Day(2023, 5) {
private val maps = input.split("\n\n").drop(1)
.map { it.lines().drop(1)
.associate {
l -> longs(l).let { (dst, src, len) -> src..(src + len) to dst..(dst + len) }
}
}
override fun part1() = longs(input.lines()[0])
.map { it..it }
.flatMap {
seed -> maps.fold(listOf(seed)) { acc, map -> acc.flatMap { translateRange(map, it) } }
}.minOf { it.first }
override fun part2() = longs(input.lines()[0]).chunked(2)
.map { it[0]..it[0] + it[1] }
.flatMap {
seed -> maps.fold(listOf(seed)) { acc, map -> acc.flatMap { translateRange(map, it) } }
}.minOf { it.first }
private fun translateRange(map: Map<LongRange, LongRange>, input: LongRange): List<LongRange> {
val outputRanges = mutableListOf<LongRange>()
var unmappedRanges = mutableListOf(input)
for (srcRange in map.keys) {
val outsideRanges = mutableListOf<LongRange>()
for (toMapRange in unmappedRanges) {
outsideRanges.addAll(toMapRange.exceptRange(srcRange))
toMapRange.intersectRange(srcRange)?.let {
outputRanges.add(it.shift(map[srcRange]!!.first - srcRange.first))
}
}
unmappedRanges = outsideRanges
}
outputRanges.addAll(unmappedRanges)
return outputRanges
}
}
| 0 | Kotlin | 0 | 1 | be120257fbce5eda9b51d3d7b63b121824c6e877 | 1,557 | adventofkotlin | MIT License |
advent-of-code2016/src/main/kotlin/day20/Advent20.kt | REDNBLACK | 128,669,137 | false | null | package day20
import parseInput
import splitToLines
import java.util.stream.LongStream
/**
--- Day 20: Firewall Rules ---
You'd like to set up a small hidden computer here so you can use it to get back into the network later. However, the corporate firewall only allows communication with certain external IP addresses.
You've retrieved the list of blocked IPs from the firewall, but the list seems to be messy and poorly maintained, and it's not clear which IPs are allowed. Also, rather than being written in dot-decimal notation, they are written as plain 32-bit integers, which can have any value from 0 through 4294967295, inclusive.
For example, suppose only the values 0 through 9 were valid, and that you retrieved the following blacklist:
5-8
0-2
4-7
The blacklist specifies ranges of IPs (inclusive of both the start and end value) that are not allowed. Then, the only IPs that this firewall allows are 3 and 9, since those are the only numbers not in any range.
Given the list of blocked IPs you retrieved from the firewall (your puzzle input), what is the lowest-valued IP that is not blocked?
--- Part Two ---
How many IPs are allowed by the blacklist?
*/
fun main(args: Array<String>) {
val test = """5-8
|0-2
|4-7""".trimMargin()
val input = parseInput("day20-input.txt")
println(findLowestIP(test) == 3L)
println(countWhitelisted(test))
println(findLowestIP(input))
println(countWhitelisted(input))
}
fun findLowestIP(input: String): Long? {
val ranges = parseRanges(input)
return (0..4294967295).first { number -> ranges.none { range -> range.contains(number) } }
}
fun countWhitelisted(input: String): Long {
val ranges = parseRanges(input)
// For speedup
return LongStream.rangeClosed(0, 4294967295L)
.parallel()
.filter { number -> ranges.none { range -> range.contains(number) } }
.count()
}
private fun parseRanges(input: String) = input.splitToLines()
.map { it ->
val (min, max) = it.split("-")
min.toLong()..max.toLong()
}
| 0 | Kotlin | 0 | 0 | e282d1f0fd0b973e4b701c8c2af1dbf4f4a149c7 | 2,121 | courses | MIT License |
kotlin/src/main/kotlin/com/pbh/soft/day2/Day2Solver.kt | phansen314 | 579,463,173 | false | {"Kotlin": 105902} | package com.pbh.soft.day2
import cc.ekblad.konbini.*
import com.pbh.soft.common.Solver
import com.pbh.soft.common.parsing.ParsingUtils.onSuccess
import com.pbh.soft.common.parsing.ParsingUtils.parseLines
import com.pbh.soft.day2.Color.*
import com.pbh.soft.day2.Parsing.gameP
import mu.KLogging
import kotlin.math.max
object Day2Solver : Solver, KLogging() {
val bag = mkBag(12, 13, 14)
override fun solveP1(text: String): String =
gameP.parseLines(text).onSuccess { games ->
games.asSequence()
.filter { it.isPossible(bag) }
.map(Game::id)
.sum()
.toString()
}
override fun solveP2(text: String): String =
gameP.parseLines(text).onSuccess { games ->
games.asSequence()
.map { it.maxColors().power() }
.sum()
.toString()
}
private fun mkBag(r: Int, g: Int, b: Int): Bag = Bag(linkedMapOf(R to r, G to g, B to b))
private fun Grabs.isPossible(bag: Bag): Boolean = Color.entries.all { bag[it] >= this[it] }
private fun Game.isPossible(bag: Bag): Boolean = grabs.all { grab -> grab.isPossible(bag) }
private fun Game.maxColors(): ColorsMap {
val maxMap = Color.entries.associateWithTo(mutableMapOf()) { -1 }
for (grab in grabs) {
for (color in Color.entries) {
maxMap.merge(color, grab[color], ::max)
}
}
return ColorsMap(maxMap)
}
private fun ColorsMap.power(): Int = map.values.fold(1) { acc, cv -> acc * cv }
}
object Parsing {
val intP: Parser<Int> = integer.map(Long::toInt)
val colorP: Parser<Color> = oneOf(
string(R.text).map { R },
string(G.text).map { G },
string(B.text).map { B })
val colorAmountP: Parser<Pair<Color, Int>> = parser {
whitespace()
val amount = intP()
whitespace1()
val color = colorP()
color to amount
}
val grabsP: Parser<Grabs> = chain(colorAmountP, char(',')).map { Grabs(it.terms.toMap(LinkedHashMap())) }
val gameP: Parser<Game> = parser {
string("Game ");
val id = intP(); string(":")
val grabs = chain1(grabsP, cc.ekblad.konbini.char(';')).terms
Game(id, grabs)
}
}
enum class Color(val text: String) {
R("red"),
G("green"),
B("blue");
}
data class ColorsMap(val map: Map<Color, Int>) {
operator fun get(color: Color): Int = map[color] ?: 0
}
typealias Bag = ColorsMap
typealias Grabs = ColorsMap
data class Game(val id: Int, val grabs: List<Grabs>) | 0 | Kotlin | 0 | 0 | 7fcc18f453145d10aa2603c64ace18df25e0bb1a | 2,407 | advent-of-code | MIT License |
src/Day07.kt | an4 | 575,331,225 | false | {"Kotlin": 117105} | fun main() {
fun printTree(root: Node) {
val currNode = root.getName()
var children = ""
if (root.isFile() || root.getChildren().isEmpty()) {
return
}
for (child in root.getChildren()) {
children = children + ", " + child.value.getName()
printTree(child.value)
}
println("Node: $currNode")
println("Children: $children")
}
fun computeSize(root: Node): Int {
var size = 0
if (root.getSize() != -1) {
return root.getSize()
}
for (child in root.getChildren()) {
size += computeSize(child.value)
}
root.setSize(size)
return size
}
fun computeDirSum(root: Node): Int {
var sum = 0
if (!root.isFile() && root.getSize() < 100000) {
sum += root.getSize()
}
for (child in root.getChildren()) {
sum += computeDirSum(child.value)
}
return sum
}
fun findDirToDelete(root: Node, minSizeToDelete: Int, currentSizeToDelete: Int): Int {
var sizeToDelete = currentSizeToDelete
if (!root.isFile() && root.getSize() > minSizeToDelete && root.getSize() < currentSizeToDelete) {
sizeToDelete = root.getSize()
}
for (child in root.getChildren()) {
val childMinSize = findDirToDelete(child.value, minSizeToDelete, sizeToDelete)
if (childMinSize < sizeToDelete) {
sizeToDelete = childMinSize
}
}
return sizeToDelete
}
fun getTree(commands: List<String>) : Node {
val tree = Node("/", Node.Type.DIR, null)
var currentNode: Node = tree
for(command in commands) {
if (command.startsWith("$")) {
// System command
val parts = command.split(" ")
val action = parts[1]
if (action == "ls") {
// nothing to do
} else if (action == "cd") {
val destination = parts[2]
if (destination == "/") {
continue
} else if (destination == "..") {
currentNode = currentNode.getParent()!!
} else {
currentNode = currentNode.getDir(destination)
}
} else {
throw Exception("Unknown action")
}
} else {
// File or dir
if (command.startsWith("dir")) {
val parts = command.split(" ")
val name = parts[1]
val child = Node(name, Node.Type.DIR, currentNode)
currentNode.addChild(child)
} else {
val parts = command.split(" ")
val size = parts[0].toInt()
val name = parts[1]
val child = Node(name, Node.Type.FILE, currentNode)
child.setSize(size)
currentNode.addChild(child)
}
}
}
computeSize(tree)
return tree
}
fun part1(commands: List<String>): Int {
val tree = getTree(commands)
return computeDirSum(tree)
}
fun part2(commands: List<String>): Int {
val tree = getTree(commands)
val fileTotalSize = tree.getSize()
val totalSpace = 70000000
val freeSpace = totalSpace - fileTotalSize
val minSpaceToFree = 30000000 - freeSpace
return findDirToDelete(tree, minSpaceToFree, tree.getSize())
}
val rawInput = "\$ cd /,\$ ls,dir bcfwbq,14779 cmss,dir ctctt,101350 gpbswq.njr,270744 mglrchsr,260405 qtvftbl,dir rbsrpg,dir rzgnbgv,dir svsgnbs,dir wqctlzz,71582 wrqbm,\$ cd bcfwbq,\$ ls,dir bsbpc,dir gpbswq,172204 lpn.qjd,269121 lts.zjd,dir pfps,dir phvgmv,dir pjcrwh,dir pvf,dir rthpbmhr,dir sjnvdz,\$ cd bsbpc,\$ ls,191305 hlqptq.nrj,15627 lts.zjd,\$ cd ..,\$ cd gpbswq,\$ ls,dir ctctt,dir jcw,dir jnh,53143 lts.zjd,dir qrrjgdbd,dir tnsjg,\$ cd ctctt,\$ ls,dir hhmm,\$ cd hhmm,\$ ls,89761 brfjczv.lmr,226384 gwqfwwp.ctl,174778 pgsdmfj,\$ cd ..,\$ cd ..,\$ cd jcw,\$ ls,149585 gpbswq.lbv,\$ cd ..,\$ cd jnh,\$ ls,10840 ctctt,dir fzplg,dir jvpc,dir lpn,dir mcz,48063 nczc,8024 rthpbmhr.qwq,65222 vqgbgm,\$ cd fzplg,\$ ls,34828 lpn.vcl,dir svsgnbs,\$ cd svsgnbs,\$ ls,216427 bvtl,242012 gpbswq.qlg,dir gsmltmw,11388 lpn.trp,dir lrr,dir vwqlvj,\$ cd gsmltmw,\$ ls,66467 pldhhjch,\$ cd ..,\$ cd lrr,\$ ls,dir ctctt,dir lpn,16831 lts.zjd,dir svsgnbs,dir tdpmdfgd,177469 wct.njp,\$ cd ctctt,\$ ls,145394 phd.tvj,\$ cd ..,\$ cd lpn,\$ ls,dir svsgnbs,\$ cd svsgnbs,\$ ls,148504 ctctt.vjd,\$ cd ..,\$ cd ..,\$ cd svsgnbs,\$ ls,245750 ggbhsgz.snc,\$ cd ..,\$ cd tdpmdfgd,\$ ls,dir cghfclv,dir mcfzvlvw,dir mdgvcgbc,\$ cd cghfclv,\$ ls,49162 shwslwsf.lww,\$ cd ..,\$ cd mcfzvlvw,\$ ls,dir bsbswh,\$ cd bsbswh,\$ ls,dir hqsdsp,\$ cd hqsdsp,\$ ls,70065 pldhhjch,\$ cd ..,\$ cd ..,\$ cd ..,\$ cd mdgvcgbc,\$ ls,235514 dhfms.nwl,\$ cd ..,\$ cd ..,\$ cd ..,\$ cd vwqlvj,\$ ls,269473 jwv.dqh,90324 mglrchsr,194977 rwgsvszh.jbf,\$ cd ..,\$ cd ..,\$ cd ..,\$ cd jvpc,\$ ls,dir rdgqr,dir sspn,\$ cd rdgqr,\$ ls,dir qcjccsth,\$ cd qcjccsth,\$ ls,dir rqwvslc,\$ cd rqwvslc,\$ ls,275985 pgqph.lcn,\$ cd ..,\$ cd ..,\$ cd ..,\$ cd sspn,\$ ls,200316 gpbswq,162820 pldhhjch,\$ cd ..,\$ cd ..,\$ cd lpn,\$ ls,277995 hlqptq.nrj,\$ cd ..,\$ cd mcz,\$ ls,dir fjtj,157693 gqfgrfqw.wtc,dir jqbpcd,206235 lpn,54229 mglrchsr,238506 rthpbmhr,dir snr,dir ztlrtgjl,\$ cd fjtj,\$ ls,240610 fbwzn,207688 hlqptq.nrj,150032 lts.zjd,48060 mcrgn,265551 zqrnt.srf,\$ cd ..,\$ cd jqbpcd,\$ ls,256141 ctctt.nbp,dir gpbswq,78480 hmddcjdd.bmc,31403 lpn,120619 mvdfjzdr,dir nqgvl,\$ cd gpbswq,\$ ls,125791 ctctt,\$ cd ..,\$ cd nqgvl,\$ ls,174465 jrbfcvf.rqr,144210 lts.zjd,258976 rthpbmhr,\$ cd ..,\$ cd ..,\$ cd snr,\$ ls,185943 rthpbmhr.jhb,\$ cd ..,\$ cd ztlrtgjl,\$ ls,232309 ntlzfsz.vjd,254942 zhrds.nbp,\$ cd ..,\$ cd ..,\$ cd ..,\$ cd qrrjgdbd,\$ ls,dir gpbswq,\$ cd gpbswq,\$ ls,170768 rthpbmhr.qwf,\$ cd ..,\$ cd ..,\$ cd tnsjg,\$ ls,242206 bjmgvmp.hht,245356 frtdp,dir jrflhz,128115 lpn,120081 rfhs,dir sfplvt,dir tts,114165 zfl.ccr,\$ cd jrflhz,\$ ls,dir gpbswq,dir nnlzjwts,dir sctf,\$ cd gpbswq,\$ ls,121401 mglrchsr,\$ cd ..,\$ cd nnlzjwts,\$ ls,dir gljnss,165011 lts.zjd,69364 svsgnbs.bqm,\$ cd gljnss,\$ ls,181850 cfjbd.fmj,\$ cd ..,\$ cd ..,\$ cd sctf,\$ ls,109435 gqfgrfqw.wtc,146343 lpn.mbs,255948 svsgnbs.hbf,231472 vdrfwqwv.pzf,263352 zgzj,\$ cd ..,\$ cd ..,\$ cd sfplvt,\$ ls,51580 hlqptq.nrj,dir mldph,\$ cd mldph,\$ ls,163815 hsnw,\$ cd ..,\$ cd ..,\$ cd tts,\$ ls,dir ctctt,211239 rpm,dir rthpbmhr,dir wpnnrzb,\$ cd ctctt,\$ ls,dir ctctt,137333 hshpfwl,183146 srd,\$ cd ctctt,\$ ls,89470 hlqptq.nrj,\$ cd ..,\$ cd ..,\$ cd rthpbmhr,\$ ls,139569 fhjlbrmp.phd,223589 jvrs.bpj,198566 rthpbmhr.qdr,\$ cd ..,\$ cd wpnnrzb,\$ ls,dir ctctt,158058 fjtcc,dir jqqhgjv,dir qvbvvb,16429 wds.hpj,\$ cd ctctt,\$ ls,166551 gcjt.wld,233189 gpbswq.mls,193694 rthpbmhr.rvz,dir svsgnbs,\$ cd svsgnbs,\$ ls,248185 fpssfvd.zft,215781 rwtg.gch,\$ cd ..,\$ cd ..,\$ cd jqqhgjv,\$ ls,dir gpbswq,14842 lts.zjd,dir mqp,258342 pldhhjch,103492 sddj.sbq,248024 svsgnbs,\$ cd gpbswq,\$ ls,dir sqchbqc,176209 vdq.jbz,\$ cd sqchbqc,\$ ls,dir cphf,\$ cd cphf,\$ ls,253613 snzbgfs.rjf,\$ cd ..,\$ cd ..,\$ cd ..,\$ cd mqp,\$ ls,10090 mfw,\$ cd ..,\$ cd ..,\$ cd qvbvvb,\$ ls,dir mzw,dir svsgnbs,\$ cd mzw,\$ ls,98994 mmv.hcl,\$ cd ..,\$ cd svsgnbs,\$ ls,108748 lts.zjd,10351 mglrchsr,\$ cd ..,\$ cd ..,\$ cd ..,\$ cd ..,\$ cd ..,\$ cd ..,\$ cd pfps,\$ ls,dir cpp,110535 mglrchsr,120669 qvh.fbm,\$ cd cpp,\$ ls,dir htnmrjpq,\$ cd htnmrjpq,\$ ls,120225 bdjmsbg.wfz,\$ cd ..,\$ cd ..,\$ cd ..,\$ cd phvgmv,\$ ls,113550 pldhhjch,31171 zcfm,\$ cd ..,\$ cd pjcrwh,\$ ls,265625 snbjdmg.jtn,\$ cd ..,\$ cd pvf,\$ ls,91010 ctctt,dir hdz,dir qtwfpmvz,\$ cd hdz,\$ ls,103787 rlnrs,\$ cd ..,\$ cd qtwfpmvz,\$ ls,244905 lts.zjd,\$ cd ..,\$ cd ..,\$ cd rthpbmhr,\$ ls,dir phq,dir svsgnbs,dir wzwfz,dir zpwfj,\$ cd phq,\$ ls,91709 bzfnqh,dir ccwqrjn,dir gpbswq,dir svsgnbs,\$ cd ccwqrjn,\$ ls,8953 fffqzmqp,dir ftnb,dir svsgnbs,\$ cd ftnb,\$ ls,226615 rthpbmhr,\$ cd ..,\$ cd svsgnbs,\$ ls,dir bhnnm,dir tjrqtmd,\$ cd bhnnm,\$ ls,dir prfqw,\$ cd prfqw,\$ ls,dir hzsjlq,\$ cd hzsjlq,\$ ls,99285 cfpwbvp,\$ cd ..,\$ cd ..,\$ cd ..,\$ cd tjrqtmd,\$ ls,237461 cqr.wfj,149955 zchnb,\$ cd ..,\$ cd ..,\$ cd ..,\$ cd gpbswq,\$ ls,dir bqqtnfb,dir ctctt,261108 gpbswq,135193 hnrflng,264503 jrp.bls,224864 mghhgrj.tgp,dir pljbtbn,dir rthpbmhr,244222 svsgnbs.rzp,\$ cd bqqtnfb,\$ ls,dir jnzfr,\$ cd jnzfr,\$ ls,dir bdrqmr,168907 pldhhjch,\$ cd bdrqmr,\$ ls,151767 vfw.jjc,\$ cd ..,\$ cd ..,\$ cd ..,\$ cd ctctt,\$ ls,dir zdsshmr,\$ cd zdsshmr,\$ ls,77208 hlqptq.nrj,\$ cd ..,\$ cd ..,\$ cd pljbtbn,\$ ls,63719 hlqptq.nrj,103719 jjctg.dhw,547 tljz.wnv,\$ cd ..,\$ cd rthpbmhr,\$ ls,dir sjbfhcpc,\$ cd sjbfhcpc,\$ ls,184946 sgpgszw,\$ cd ..,\$ cd ..,\$ cd ..,\$ cd svsgnbs,\$ ls,dir ctctt,dir flzsvb,dir pbw,23408 qprlnvwv.jmz,dir wjhplc,\$ cd ctctt,\$ ls,11507 cnf,dir gpbswq,87778 rthpbmhr.wzv,dir slmbb,dir sqc,75556 wsbzwn.mpf,\$ cd gpbswq,\$ ls,173498 dsg,202811 msvs.szd,208419 pldhhjch,\$ cd ..,\$ cd slmbb,\$ ls,dir jcth,dir njldhbln,\$ cd jcth,\$ ls,6106 hlqptq.nrj,\$ cd ..,\$ cd njldhbln,\$ ls,241153 mvnvzqfc.rtn,\$ cd ..,\$ cd ..,\$ cd sqc,\$ ls,dir zhrc,\$ cd zhrc,\$ ls,dir qswqqzb,\$ cd qswqqzb,\$ ls,264937 btqmqn.hqv,\$ cd ..,\$ cd ..,\$ cd ..,\$ cd ..,\$ cd flzsvb,\$ ls,58735 hlqptq.nrj,\$ cd ..,\$ cd pbw,\$ ls,80787 bgfmdg,234807 gqfgrfqw.wtc,44816 pldhhjch,dir qjjpmq,dir rthpbmhr,153500 ssmdz,\$ cd qjjpmq,\$ ls,155209 ctghhsdh,182544 fprdp.ffs,\$ cd ..,\$ cd rthpbmhr,\$ ls,136673 lts.zjd,\$ cd ..,\$ cd ..,\$ cd wjhplc,\$ ls,246593 hhcgnfjb.nbl,29266 hlqptq.nrj,246096 lts.zjd,40242 rrfgvvhg,\$ cd ..,\$ cd ..,\$ cd ..,\$ cd svsgnbs,\$ ls,215743 fwm,236816 gqfgrfqw.wtc,235185 sjdlr.rzj,dir ztsgb,\$ cd ztsgb,\$ ls,265998 rthpbmhr.pdp,275979 zqfcprz.wtd,\$ cd ..,\$ cd ..,\$ cd wzwfz,\$ ls,dir bsqwtf,dir ctctt,dir lpng,dir svsgnbs,\$ cd bsqwtf,\$ ls,dir rhjb,dir sgzvb,\$ cd rhjb,\$ ls,166599 rthpbmhr.msg,\$ cd ..,\$ cd sgzvb,\$ ls,185594 zmnb.bcq,\$ cd ..,\$ cd ..,\$ cd ctctt,\$ ls,130367 svsgnbs,17459 tdsztr.fsn,242273 wfs,\$ cd ..,\$ cd lpng,\$ ls,145778 snmcwfg.hjz,\$ cd ..,\$ cd svsgnbs,\$ ls,dir ctctt,dir nqrlzg,dir qczmdfm,54814 wtmjh.jdv,\$ cd ctctt,\$ ls,244171 pldhhjch,\$ cd ..,\$ cd nqrlzg,\$ ls,dir qjhlj,\$ cd qjhlj,\$ ls,dir gncct,\$ cd gncct,\$ ls,141943 wsdgmdd.ctz,\$ cd ..,\$ cd ..,\$ cd ..,\$ cd qczmdfm,\$ ls,4482 lpn.fmp,\$ cd ..,\$ cd ..,\$ cd ..,\$ cd zpwfj,\$ ls,226995 lts.zjd,dir sflcgdm,\$ cd sflcgdm,\$ ls,199168 bjrjrrm.bfw,dir fpcq,24906 gdzfmhz.jhp,7267 hdpzvh.ngg,dir jjsgqb,137796 psws.hvp,\$ cd fpcq,\$ ls,195792 nghcc.wps,\$ cd ..,\$ cd jjsgqb,\$ ls,18774 ctctt,106399 jvbgfhs,208035 rthpbmhr,dir zptz,\$ cd zptz,\$ ls,278792 gqfgrfqw.wtc,\$ cd ..,\$ cd ..,\$ cd ..,\$ cd ..,\$ cd ..,\$ cd sjnvdz,\$ ls,dir fchgggp,dir gldg,40164 gnh.gmv,dir lpn,dir njtgjt,81415 qqfm.grb,dir vvcbjct,\$ cd fchgggp,\$ ls,dir fjcclj,dir lpn,145291 lts.zjd,7288 mglrchsr,dir pmhdzvfn,dir qtpdfwh,dir vjwtvb,\$ cd fjcclj,\$ ls,28333 gpbswq.vtg,258676 lts.zjd,\$ cd ..,\$ cd lpn,\$ ls,197797 pldhhjch,\$ cd ..,\$ cd pmhdzvfn,\$ ls,21538 gpbswq.pwq,5451 hqjg,dir llhp,220717 lzqmh.stl,123800 pldhhjch,dir pmv,dir rzs,dir tztv,160018 zfvgjtzr.qth,\$ cd llhp,\$ ls,dir lsft,dir pfjmphs,\$ cd lsft,\$ ls,78424 gpbswq.ddb,101497 gqfgrfqw.wtc,137686 hlqptq.nrj,122325 mglrchsr,\$ cd ..,\$ cd pfjmphs,\$ ls,185141 mbw.gnd,\$ cd ..,\$ cd ..,\$ cd pmv,\$ ls,139255 gqfgrfqw.wtc,272882 hlqptq.nrj,\$ cd ..,\$ cd rzs,\$ ls,dir gpbswq,89153 gpbswq.vcv,81882 gqfgrfqw.wtc,39252 hlqptq.nrj,dir tmcm,\$ cd gpbswq,\$ ls,205674 ctctt.gqd,\$ cd ..,\$ cd tmcm,\$ ls,156591 gmjvzj.wzl,199254 lts.zjd,dir vzhbsdd,dir zfs,\$ cd vzhbsdd,\$ ls,70059 gsgzqgn.fhf,43456 hrttvrqc,\$ cd ..,\$ cd zfs,\$ ls,223726 hlqptq.nrj,\$ cd ..,\$ cd ..,\$ cd ..,\$ cd tztv,\$ ls,200126 lpn.bns,dir wfjwmbj,\$ cd wfjwmbj,\$ ls,120344 gdqgml.gdn,\$ cd ..,\$ cd ..,\$ cd ..,\$ cd qtpdfwh,\$ ls,dir qszjt,\$ cd qszjt,\$ ls,7207 rthpbmhr.rpv,20452 ztdnfmgp.dsb,\$ cd ..,\$ cd ..,\$ cd vjwtvb,\$ ls,dir scswlmn,\$ cd scswlmn,\$ ls,207195 svsgnbs.jqq,\$ cd ..,\$ cd ..,\$ cd ..,\$ cd gldg,\$ ls,119560 ctctt.wbc,203041 gqfgrfqw.wtc,dir hrp,274270 lts.zjd,25081 mhsfdhjr.ndw,dir svsgnbs,\$ cd hrp,\$ ls,dir lpn,\$ cd lpn,\$ ls,dir gpbswq,dir wvrzhdb,\$ cd gpbswq,\$ ls,dir vtgc,\$ cd vtgc,\$ ls,231107 hlqptq.nrj,\$ cd ..,\$ cd ..,\$ cd wvrzhdb,\$ ls,83303 lts.zjd,\$ cd ..,\$ cd ..,\$ cd ..,\$ cd svsgnbs,\$ ls,dir fhfqlv,13446 frn.hzg,126475 wmjjjl.cjr,\$ cd fhfqlv,\$ ls,243574 hjn.jzb,\$ cd ..,\$ cd ..,\$ cd ..,\$ cd lpn,\$ ls,dir mqglznd,\$ cd mqglznd,\$ ls,dir gpbswq,177654 gpbswq.zhv,128217 gqfgrfqw.wtc,66750 hlqptq.nrj,136018 hvphz,dir pswvwtf,113363 rthpbmhr.gwz,dir twddrn,\$ cd gpbswq,\$ ls,244278 lts.zjd,dir pfrjwbvl,dir qlrfw,222491 rthpbmhr,\$ cd pfrjwbvl,\$ ls,46802 cfl.ljt,dir ctctt,dir dfqzmd,110525 gshdhsfm,dir jcbw,dir lpn,237385 pldhhjch,15812 prcwhhq.jjh,dir rthpbmhr,260693 zmgq,\$ cd ctctt,\$ ls,6529 hctcg.dpw,188655 lpn.qjf,202221 wjnb,\$ cd ..,\$ cd dfqzmd,\$ ls,197980 ctctt,\$ cd ..,\$ cd jcbw,\$ ls,1281 gpbswq,15778 jfgjlcd.mqh,38803 mdtcrb.dbj,dir qtjbpbs,\$ cd qtjbpbs,\$ ls,59348 mglrchsr,\$ cd ..,\$ cd ..,\$ cd lpn,\$ ls,dir ctctt,dir hsjjp,260465 mglrchsr,\$ cd ctctt,\$ ls,dir wvbrsb,\$ cd wvbrsb,\$ ls,135584 lts.zjd,\$ cd ..,\$ cd ..,\$ cd hsjjp,\$ ls,249448 ddfqnwgf,164051 dsnhsbp.wvv,dir fmzgm,dir gpbswq,113907 gqfgrfqw.wtc,\$ cd fmzgm,\$ ls,150025 ngnqjcj.tbf,\$ cd ..,\$ cd gpbswq,\$ ls,33139 dmgqhf.nzd,dir gpbswq,dir rwd,\$ cd gpbswq,\$ ls,148820 lnqqds.rpg,\$ cd ..,\$ cd rwd,\$ ls,133433 pldhhjch,\$ cd ..,\$ cd ..,\$ cd ..,\$ cd ..,\$ cd rthpbmhr,\$ ls,262342 fdnr.svq,dir nbpsdm,161791 pldhhjch,6835 qvclr,228110 whf,\$ cd nbpsdm,\$ ls,dir rthpbmhr,dir svsgnbs,\$ cd rthpbmhr,\$ ls,267109 chb,\$ cd ..,\$ cd svsgnbs,\$ ls,150446 rlv.vcc,\$ cd ..,\$ cd ..,\$ cd ..,\$ cd ..,\$ cd qlrfw,\$ ls,dir sgcpwst,\$ cd sgcpwst,\$ ls,dir fss,\$ cd fss,\$ ls,244165 gpbswq.qtz,\$ cd ..,\$ cd ..,\$ cd ..,\$ cd ..,\$ cd pswvwtf,\$ ls,162099 jhdrnv.zrd,54856 mglrchsr,dir psdz,169053 qhq,\$ cd psdz,\$ ls,dir lbcf,\$ cd lbcf,\$ ls,218770 ctctt.chv,95266 pldhhjch,\$ cd ..,\$ cd ..,\$ cd ..,\$ cd twddrn,\$ ls,120791 hlqptq.nrj,212213 vffj,\$ cd ..,\$ cd ..,\$ cd ..,\$ cd njtgjt,\$ ls,dir mzwdb,\$ cd mzwdb,\$ ls,108520 lts.zjd,\$ cd ..,\$ cd ..,\$ cd vvcbjct,\$ ls,155890 ctctt.fbw,\$ cd ..,\$ cd ..,\$ cd ..,\$ cd ctctt,\$ ls,5656 mpftwp.nds,8998 pldhhjch,185601 snrng.qsv,\$ cd ..,\$ cd rbsrpg,\$ ls,113129 cpwmjw.rbj,dir jdhmlzr,114254 sqj.fzp,120708 svsgnbs.hpn,\$ cd jdhmlzr,\$ ls,dir cdnmflmm,248055 hlqptq.nrj,247942 pldhhjch,dir qrwsnzdv,80053 svsgnbs,219309 zhqgvd.bhw,\$ cd cdnmflmm,\$ ls,83138 lpn.wtg,\$ cd ..,\$ cd qrwsnzdv,\$ ls,197145 zspfb.sbd,\$ cd ..,\$ cd ..,\$ cd ..,\$ cd rzgnbgv,\$ ls,208692 clz,dir tmcqcpfc,dir twlnjr,\$ cd tmcqcpfc,\$ ls,dir jtnf,\$ cd jtnf,\$ ls,242978 fhvtvdff.swr,21748 lwcplzmw,\$ cd ..,\$ cd ..,\$ cd twlnjr,\$ ls,dir ctctt,dir gpbswq,98435 rthpbmhr.pcr,dir snpm,dir svsgnbs,104969 zzd,\$ cd ctctt,\$ ls,200382 pqswsnhp,\$ cd ..,\$ cd gpbswq,\$ ls,90380 qqrfbwn,\$ cd ..,\$ cd snpm,\$ ls,57996 swfjlfh.qft,\$ cd ..,\$ cd svsgnbs,\$ ls,86028 clcfrnr.jwl,199666 ctctt.ftr,200949 ctctt.mrh,23594 dhlmbh.gjt,278047 mbchg,dir pgfhp,\$ cd pgfhp,\$ ls,21555 rlblnvsd,\$ cd ..,\$ cd ..,\$ cd ..,\$ cd ..,\$ cd svsgnbs,\$ ls,155183 jgjj.sgs,28150 pldhhjch,\$ cd ..,\$ cd wqctlzz,\$ ls,23662 mglrchsr,60923 pldhhjch"
val input = rawInput.split(",")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | df64adcc5d1ccab370acef01a7ed4d480ffbe2be | 15,812 | aoc22 | Apache License 2.0 |
src/main/kotlin/kt/kotlinalgs/app/searching/SortedMatrixSearch.ws.kts | sjaindl | 384,471,324 | false | null | package kt.kotlinalgs.app.searching
println("test")
val matrix = arrayOf(
intArrayOf(15, 20, 40, 85),
intArrayOf(20, 35, 80, 95),
intArrayOf(30, 55, 95, 105),
intArrayOf(40, 80, 100, 120)
)
Solution().sortedMatrixSearch(matrix, 30)
for (row in matrix.indices) {
for (col in matrix[0].indices) {
println("check row $row col $col")
println(Solution().sortedMatrixSearch(matrix, matrix[row][col]))
}
}
// O(log M + log N) runtime, at each step eliminating 2 or 3 of 4 quadrants!
class Solution {
fun sortedMatrixSearch(matrix: Array<IntArray>, searched: Int): Pair<Int, Int>? {
if (matrix.isEmpty()) return null
if (matrix[0].isEmpty()) return null
return sortedMatrixSearchRec(matrix, searched, 0, matrix.size - 1, 0, matrix[0].size - 1)
}
private fun sortedMatrixSearchRec(
matrix: Array<IntArray>,
searched: Int,
rowLow: Int,
rowHigh: Int,
colLow: Int,
colHigh: Int
): Pair<Int, Int>? {
if (rowHigh < rowLow || colHigh < colLow) return null
val rowCenter = rowLow + (rowHigh - rowLow) / 2
val colCenter = colLow + (colHigh - colLow) / 2
val centerValue = matrix[rowCenter][colCenter]
val rowLowerCenter = rowCenter + 1
val colLowerCenter = colCenter + 1
val lowerIsInBounds = isInBounds(matrix, rowLowerCenter, colLowerCenter)
if (centerValue == searched) {
return (rowCenter to colCenter)
} else if (lowerIsInBounds && matrix[rowLowerCenter][colLowerCenter] == searched) {
return (rowLowerCenter to colLowerCenter)
} else if (centerValue > searched) {
// search left
val result = sortedMatrixSearchRec(
matrix,
searched,
rowLow,
rowHigh,
colLow,
colCenter - 1
)
if (result != null) return result
// search on top of
return sortedMatrixSearchRec(
matrix,
searched,
rowLow,
rowCenter - 1,
colCenter,
colCenter
)
} else if (lowerIsInBounds && matrix[rowLowerCenter][colLowerCenter] < searched) {
// search right
val result = sortedMatrixSearchRec(
matrix,
searched,
rowLow,
rowHigh,
colLowerCenter + 1,
colHigh
)
if (result != null) return result
// search below
return sortedMatrixSearchRec(
matrix,
searched,
rowLowerCenter + 1,
rowHigh,
colLowerCenter,
colLowerCenter
)
} else {
// search bottom left and top right quadrant
// bottom left:
sortedMatrixSearchRec(
matrix,
searched,
rowCenter + 1,
rowHigh,
colLow,
colCenter
)?.let {
return it
}
// top right
return sortedMatrixSearchRec(
matrix,
searched,
rowLow,
rowCenter,
colCenter + 1,
colHigh
)
}
}
private fun isInBounds(matrix: Array<IntArray>, row: Int, col: Int): Boolean {
return row >= 0 && col >= 0 && row < matrix.size && col < matrix[0].size
}
}
| 0 | Java | 0 | 0 | e7ae2fcd1ce8dffabecfedb893cb04ccd9bf8ba0 | 3,655 | KotlinAlgs | MIT License |
src/day04/Day04.kt | andreas-eberle | 573,039,929 | false | {"Kotlin": 90908} | package day04
import readInput
const val day = "04"
fun main() {
fun calculatePart1Score(input: List<String>): Int {
return input.asSequence()
.map { row -> row.split(",", "-").map { num -> num.toInt() } }
.map { (it[0]..it[1]).toSet() to (it[2]..it[3]).toSet() }
.filter { it.first.containsAll(it.second) || it.second.containsAll(it.first) }
.count()
}
fun calculatePart2Score(input: List<String>): Int {
return input.asSequence()
.map { row -> row.split(",", "-").map { num -> num.toInt() } }
.map { (it[0]..it[1]).toSet() to (it[2]..it[3]).toSet() }
.filter { it.first.intersect(it.second).isNotEmpty() }
.count()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("/day$day/Day${day}_test")
val input = readInput("/day$day/Day${day}")
val part1TestPoints = calculatePart1Score(testInput)
val part1Points = calculatePart1Score(input)
println("Part1 test points: $part1TestPoints")
println("Part1 points: $part1Points")
check(part1TestPoints == 2)
val part2TestPoints = calculatePart2Score(testInput)
val part2Points = calculatePart2Score(input)
println("Part2 test points: $part2TestPoints")
println("Part2 points: $part2Points")
check(part2TestPoints == 4)
} | 0 | Kotlin | 0 | 0 | e42802d7721ad25d60c4f73d438b5b0d0176f120 | 1,401 | advent-of-code-22-kotlin | Apache License 2.0 |
src/main/kotlin/year2022/day-19.kt | ppichler94 | 653,105,004 | false | {"Kotlin": 182859} | package year2022
import lib.Traversal
import lib.TraversalDijkstra
import lib.aoc.Day
import lib.aoc.Part
import year2022.PartA19.Materials.Type.*
import kotlin.math.max
fun main() {
Day(19, 2022, PartA19(), PartB19()).run()
}
open class PartA19 : Part() {
protected data class Materials(val ore: Int = 0, val clay: Int = 0, val obsidian: Int = 0, val geode: Int = 0) {
operator fun plus(other: Materials) =
Materials(ore + other.ore, clay + other.clay, obsidian + other.obsidian, geode + other.geode)
operator fun minus(other: Materials) =
Materials(ore - other.ore, clay - other.clay, obsidian - other.obsidian, geode - other.geode)
operator fun times(other: Int) = Materials(ore * other, clay * other, obsidian * other, geode * other)
fun canAfford(costs: Materials): Boolean {
return ore >= costs.ore && clay >= costs.clay && geode >= costs.geode && obsidian >= costs.obsidian
}
operator fun get(type: Type) = when (type) {
ORE -> ore
CLAY -> clay
OBSIDIAN -> obsidian
GEODE -> geode
}
fun inc(type: Type) = when (type) {
ORE -> Materials(ore + 1, clay, obsidian, geode)
CLAY -> Materials(ore, clay + 1, obsidian, geode)
OBSIDIAN -> Materials(ore, clay, obsidian + 1, geode)
GEODE -> Materials(ore, clay, obsidian, geode + 1)
}
enum class Type(val id: Int) {
ORE(0), CLAY(1), OBSIDIAN(2), GEODE(3)
}
}
protected data class Blueprint(val id: Int, val costs: List<Materials>) {
data class State(val materials: Materials, val production: Materials)
private var minutes = 0
private lateinit var maxRobotsNeeded: Materials
fun simulate(minutes: Int): Int {
this.minutes = minutes
maxRobotsNeeded = costs.reduce { acc, c -> maxm(acc, c) }
val start = State(Materials(), Materials(1))
val traversal = TraversalDijkstra(::nextStates)
.startFrom(start)
for (state in traversal) {
if (traversal.depth == minutes - 1) {
val (materials, production) = state
return materials[GEODE] + production[GEODE]
}
}
error("should not be reached")
}
private fun maxm(a: Materials, b: Materials): Materials {
return Materials(max(a.ore, b.ore), max(a.clay, b.clay), max(a.obsidian, b.obsidian), max(a.geode, b.geode))
}
private fun nextStates(state: State, traversal: Traversal<State>) = sequence {
val (materials, production) = state
val minutesLeft = minutes - traversal.depth
if (minutesLeft == 1) {
return@sequence
}
val nextMaterials = materials + production
var robotsBought = 0
val blockedRobotsCosts = mutableListOf<Materials>()
for (robot in Materials.Type.entries) {
if (robot != GEODE && production[robot] >= maxRobotsNeeded[robot])
continue
if (!materials.canAfford(costs[robot.id])) {
blockedRobotsCosts.add(costs[robot.id])
continue
}
yield(
Pair(
State(nextMaterials - costs[robot.id], production.inc(robot)),
if (robot == GEODE) 0f else minutesLeft.toFloat()
)
)
robotsBought++
}
var waitingPossible = false
if (robotsBought > 0) {
blockedRobotsCosts.forEach { blockedCosts ->
val maxProduction = materials + production * (minutesLeft - 1)
if (maxProduction.canAfford(blockedCosts)) {
waitingPossible = true
return@forEach
}
}
if (!waitingPossible) {
return@sequence
}
}
yield(Pair(State(nextMaterials, production), minutesLeft.toFloat()))
}.asIterable()
companion object {
fun fromString(string: String): Blueprint {
val regex =
"""Blueprint (\d+):.*ore robot.*(\d+) ore\..*clay robot.*(\d+) ore\..*obsidian robot.*(\d+) ore and (\d+) clay\..*geode robot.*(\d+) ore and (\d+) obsidian""".toRegex()
val match = regex.find(string)!!
val id = match.groupValues[1].toInt()
val oreRobotOreCost = match.groupValues[2].toInt()
val clayRobotOreCost = match.groupValues[3].toInt()
val obsidianRobotOreCost = match.groupValues[4].toInt()
val obsidianRobotClayCost = match.groupValues[5].toInt()
val geodeRobotOreCost = match.groupValues[6].toInt()
val geodeRobotObsidianCost = match.groupValues[7].toInt()
val costs = listOf(
Materials(oreRobotOreCost),
Materials(clayRobotOreCost),
Materials(obsidianRobotOreCost, obsidianRobotClayCost),
Materials(geodeRobotOreCost, 0, geodeRobotObsidianCost),
)
return Blueprint(id, costs)
}
}
}
protected lateinit var blueprints: List<Blueprint>
override fun parse(text: String) {
blueprints = text.split("\n").map(Blueprint::fromString)
}
override fun compute(): String {
val minutesToSimulate = 24
val results = blueprints.map { it.simulate(minutesToSimulate) * it.id }
return results.sum().toString()
}
override val exampleAnswer: String
get() = "33"
override val customExampleData: String?
get() = """
Blueprint 1: Each ore robot costs 4 ore. Each clay robot costs 2 ore. Each obsidian robot costs 3 ore and 14 clay. Each geode robot costs 2 ore and 7 obsidian.
Blueprint 2: Each ore robot costs 2 ore. Each clay robot costs 3 ore. Each obsidian robot costs 3 ore and 8 clay. Each geode robot costs 3 ore and 12 obsidian.
""".trimIndent()
}
class PartB19 : PartA19() {
override fun compute(): String {
val minutesToSimulate = 32
val results = blueprints.take(3).map { it.simulate(minutesToSimulate) }
return results.reduce(Int::times).toString()
}
override val exampleAnswer: String
get() = "3472"
}
| 0 | Kotlin | 0 | 0 | 49dc6eb7aa2a68c45c716587427353567d7ea313 | 6,827 | Advent-Of-Code-Kotlin | MIT License |
src/main/kotlin/no/chriswk/aoc2019/Day14.kt | chriswk | 317,863,220 | false | {"Kotlin": 481061} | package com.chriswk.aoc.advent2019
import com.chriswk.aoc.AdventDay
import com.chriswk.aoc.util.dayInputAsLines
import com.chriswk.aoc.util.fileToLines
import com.chriswk.aoc.util.report
import kotlin.math.ceil
import kotlin.math.sign
class Day14(val cost : Map<String, Pair<Long, List<Pair<Long, String>>>> = parseInput(dayInputAsLines(2019, 14))) {
companion object {
@JvmStatic
fun main(args: Array<String>) {
val day14 = Day14()
report { day14.part1() }
report { day14.part2() }
}
fun parseInput(input: List<String>): Map<String, Pair<Long, List<Pair<Long, String>>>> {
return input.map { row ->
val split: List<String> = row.split(" => ")
val left: List<Pair<Long, String>> = split.first().split(",")
.map { it.trim() }
.map {
it.split(" ").let { r ->
Pair(r.first().toLong(), r.last())
}
}
val (amount, type) = split.last().split(" ")
type to Pair(amount.toLong(), left)
}.toMap()
}
}
fun part1() : Long {
return calculateCost()
}
fun part2(): Long {
val oneTrillion = 1_000_000_000_000L
return binarySearch(0L..oneTrillion) { oneTrillion.compareTo(calculateCost(amountDesired = it)) }
}
fun binarySearch(range: LongRange, fn: (Long) -> Int): Long {
var low = range.first
var high = range.last
while (low <= high) {
val mid = (low + high) / 2
when(fn(mid).sign) {
-1 -> high = mid -1
1 -> low = mid + 1
0 -> return mid
}
}
return low - 1
}
fun calculateCost(material: String = "FUEL", amountDesired: Long = 1L, inventory: MutableMap<String, Long> = mutableMapOf()): Long {
return if (material == "ORE") {
amountDesired
} else {
val quant = inventory.getOrDefault(material, 0)
val need = if (quant > 0) {
inventory[material] = (quant - amountDesired).coerceAtLeast(0)
amountDesired - quant
} else {
amountDesired
}
if (need > 0) {
val recipe = cost.getValue(material)
val iterations = ceil(need.toDouble() / recipe.first).toInt()
val produced = recipe.first * iterations
if (need < produced) {
inventory[material] = inventory.getOrDefault(material, 0) + produced - need
}
val mats = recipe.second.map { calculateCost(it.second, it.first * iterations, inventory) }
mats.sum()
} else {
0
}
}
}
} | 116 | Kotlin | 0 | 0 | 69fa3dfed62d5cb7d961fe16924066cb7f9f5985 | 2,912 | adventofcode2019 | MIT License |
src/main/kotlin/io/github/pshegger/aoc/y2020/Y2020D12.kt | PsHegger | 325,498,299 | false | null | package io.github.pshegger.aoc.y2020
import io.github.pshegger.aoc.common.BaseSolver
import io.github.pshegger.aoc.common.Coordinate
import kotlin.math.absoluteValue
class Y2020D12 : BaseSolver() {
override val year = 2020
override val day = 12
override fun part1(): Int =
parseInput().fold(Pair(Coordinate(0, 0), 90)) { acc, action ->
val (c, facing) = acc
when (action.name) {
ActionsName.North -> Pair(c.copy(y = c.y + action.value), facing)
ActionsName.South -> Pair(c.copy(y = c.y - action.value), facing)
ActionsName.East -> Pair(c.copy(x = c.x + action.value), facing)
ActionsName.West -> Pair(c.copy(x = c.x - action.value), facing)
ActionsName.Left -> Pair(c, (360 + facing - action.value) % 360)
ActionsName.Right -> Pair(c, (360 + facing + action.value) % 360)
ActionsName.Forward -> when (facing) {
0 -> Pair(c.copy(y = c.y + action.value), facing)
90 -> Pair(c.copy(x = c.x + action.value), facing)
180 -> Pair(c.copy(y = c.y - action.value), facing)
270 -> Pair(c.copy(x = c.x - action.value), facing)
else -> error("Unknown facing $facing")
}
}
}.let { (c, _) -> c.x.absoluteValue + c.y.absoluteValue }
override fun part2(): Int =
parseInput().fold(Pair(Coordinate(0, 0), Coordinate(10, 1))) { acc, action ->
val (ship, wp) = acc
when (action.name) {
ActionsName.North -> Pair(ship, wp.copy(y = wp.y + action.value))
ActionsName.South -> Pair(ship, wp.copy(y = wp.y - action.value))
ActionsName.East -> Pair(ship, wp.copy(x = wp.x + action.value))
ActionsName.West -> Pair(ship, wp.copy(x = wp.x - action.value))
ActionsName.Left -> Pair(
ship,
(0 until (action.value / 90)).fold(wp) { (wpX, wpY), _ -> Coordinate(-wpY, wpX) }
)
ActionsName.Right -> Pair(
ship,
(0 until (action.value / 90)).fold(wp) { (wpX, wpY), _ -> Coordinate(wpY, -wpX) }
)
ActionsName.Forward -> Pair(
Coordinate(
ship.x + wp.x * action.value,
ship.y + wp.y * action.value
),
wp
)
}
}.let { (ship, _) -> ship.x.absoluteValue + ship.y.absoluteValue }
private fun parseInput() = readInput {
readLines().map { Action.parseString(it) }
}
private data class Action(val name: ActionsName, val value: Int) {
companion object {
fun parseString(str: String) = Action(
ActionsName.values().first { it.value == str[0] },
str.drop(1).toInt()
)
}
}
private enum class ActionsName(val value: Char) {
North('N'),
South('S'),
East('E'),
West('W'),
Left('L'),
Right('R'),
Forward('F')
}
}
| 0 | Kotlin | 0 | 0 | 346a8994246775023686c10f3bde90642d681474 | 3,225 | advent-of-code | MIT License |
src/Day02.kt | LukasAnda | 572,878,230 | false | {"Kotlin": 3190} | fun main() {
val input = readInput("Day02_test")
// check(processRockPaperScissors(input) == 15)
println(processRockPaperScissors2(readInput("Day02")))
}
fun processRockPaperScissors(input: List<String>) = input.sumOf { processMatch(it) }
fun processRockPaperScissors2(input: List<String>) = input.sumOf { processMatch2(it) }
fun processMatch(match: String): Int {
val (opponentHand, myHand) = match.split(" ")
val matchScore = when(opponentHand) {
"A" -> when(myHand) {
"X" -> 3
"Y" -> 6
"Z" -> 0
else -> 0
}
"B" -> when(myHand) {
"X" -> 0
"Y" -> 3
"Z" -> 6
else -> 0
}
"C" -> when(myHand) {
"X" -> 6
"Y" -> 0
"Z" -> 3
else -> 0
}
else -> 0
}
return matchScore + scoreForHand(myHand)
}
fun scoreForHand(hand: String) = when (hand) {
"X" -> 1
"Y" -> 2
"Z" -> 3
else -> 0
}
fun processMatch2(match: String): Int {
val (opponentHand, targetState) = match.split(" ")
val handScore = when(opponentHand) {
"A" -> when(targetState) {
"X" -> 3
"Y" -> 1
"Z" -> 2
else -> 0
}
"B" -> when(targetState) {
"X" -> 1
"Y" -> 2
"Z" -> 3
else -> 0
}
"C" -> when(targetState) {
"X" -> 2
"Y" -> 3
"Z" -> 1
else -> 0
}
else -> 0
}
return handScore + scoreForTargetState(targetState)
}
fun scoreForTargetState(state: String) = when(state) {
"X" -> 0
"Y" -> 3
"Z" -> 6
else -> 0
} | 0 | Kotlin | 0 | 0 | 20ccddd7b0517cbaf7590364333201e33bd5c0d6 | 1,739 | AdventOfCode2022 | Apache License 2.0 |
src/Day23.kt | Allagash | 572,736,443 | false | {"Kotlin": 101198} | import java.io.File
// Advent of Code 2022, Day 23: Unstable Diffusion
class Day23(input: String) {
data class Pt(val x: Int, val y: Int) {
fun generateNeighbors() : List<Pt> =
listOf( Pt(x-1, y-1), Pt(x-1, y), Pt (x-1, y+1),
Pt(x, y-1),Pt(x, y+1),
Pt(x+1, y-1), Pt(x+1, y), Pt(x+1, y+1))
operator fun plus(other: Pt): Pt {
return Pt(x + other.x, y + other.y)
}
}
private var points: Set<Pt>
init {
points = input.split("\n").mapIndexed { row, s ->
s.foldIndexed(emptyList<Pt>()) { col, sum, c ->
val newList = if (c == '#') {
sum + listOf(Pt(row, col))
} else {
sum
}
newList
}
}.flatten().toSet()
}
enum class Dir(val testPts: List<Pt>, val movePt: Pt) {
NORTH( listOf( Pt(-1, -1), Pt(-1, 0), Pt(-1, 1)), Pt(-1, 0)),
SOUTH( listOf( Pt(1, -1), Pt(1, 0), Pt(1, 1)), Pt(1, 0)),
WEST( listOf( Pt(-1, -1), Pt(0, -1), Pt(1, -1)), Pt(0, -1)),
EAST( listOf( Pt(-1, 1), Pt(0, 1), Pt(1, 1)), Pt(0, 1)),
}
private fun Set<Pt>.print() {
for (r in minOf{it.x}..maxOf{it.x}) {
for (c in minOf{it.y}..maxOf{it.y}) {
print(if (Pt(r, c) in this) '#' else '.')
}
println()
}
}
fun part1(): Int {
val dirs = mutableListOf(Dir.NORTH, Dir.SOUTH, Dir.WEST, Dir.EAST)
repeat(10) {
// for each point, add new proposed point
val newPts = proposeMoves(dirs)
moveElves(newPts)
dirs.add(dirs.removeFirst())
}
val xLength = points.maxOf{it.x} - points.minOf{it.x} + 1
val yLength = points.maxOf{it.y} - points.minOf{it.y} + 1
return xLength * yLength - points.size
}
private fun proposeMoves(dirs: MutableList<Dir>): MutableMap<Pt, List<Pt>> {
val newPts = mutableMapOf<Pt, List<Pt>>()
points.forEach nextPt@{ p ->
if (p.generateNeighbors().none { it in points }) {
check(p !in newPts)
newPts[p] = listOf(p)
return@nextPt // no neighbors, don't move
}
dirs.forEach { d ->
if (d.testPts.none { (p + it) in points }) {
val movers = newPts.getOrElse(p + d.movePt) { emptyList() }
newPts[p + d.movePt] = movers + listOf(p)
return@nextPt
}
}
check(p !in newPts)
newPts[p] = listOf(p) // can't move, add original position
}
return newPts
}
fun part2(): Int {
val dirs = mutableListOf(Dir.NORTH, Dir.SOUTH, Dir.WEST, Dir.EAST)
var count = 0
do {
count++
val prevPts = points.toSet()
val newPts = proposeMoves(dirs)
moveElves(newPts)
dirs.add(dirs.removeFirst())
} while (points != prevPts)
return count
}
private fun moveElves(newPts: MutableMap<Pt, List<Pt>>) {
val newConfig = mutableSetOf<Pt>()
for ((pt, movers) in newPts) {
if (movers.size == 1) {
newConfig.add(pt) // new pos for 1 elf
} else {
newConfig.addAll(movers) // these elves can't move
}
}
check(newConfig.size == points.size) { "${newConfig.size}, old ${points.size}" }
points = newConfig
}
}
fun main() {
fun readInputAsOneLine(name: String) = File("src", "$name.txt").readText()
val testInput = readInputAsOneLine("Day23_test2")
check( Day23(testInput).part1() == 110)
check(Day23(testInput).part2() == 20)
val input = readInputAsOneLine("Day23")
println(Day23(input).part1())
println(Day23(input).part2())
} | 0 | Kotlin | 0 | 0 | 8d5fc0b93f6d600878ac0d47128140e70d7fc5d9 | 3,923 | AdventOfCode2022 | Apache License 2.0 |
src/main/kotlin/com/dmc/advent2022/Day05.kt | dorienmc | 576,916,728 | false | {"Kotlin": 86239} | // --- Day 5: Supply Stacks ---
package com.dmc.advent2022
class Day05 : Day<String> {
override val index = 5
var crates = Crates(mutableListOf())
fun setCrates(input: List<String>) {
crates = Crates(input.toMutableList())
}
private fun String.parseInstruction() : Instruction {
val (lsh, rhs) = this.split(" from ")
val (_,moveNum) = lsh.split(" ")
val (fromS, toS) = rhs.split(" to ")
return Instruction(moveNum.toInt(),fromS.toInt(),toS.toInt())
}
override fun part1(input: List<String>): String {
input
.filter{ it.isNotEmpty()}
.map{ it.parseInstruction() }
.forEach { (amount, source, target) ->
repeat(amount) {
crates.moveCrate(source, target)
}
}
return crates.getCratesOnTop()
}
override fun part2(input: List<String>): String {
input.filter{ it.isNotEmpty()}.map{ it.parseInstruction()}
.forEach { (amount, source, target) ->
crates.moveCrate(source, target, amount)
}
return crates.getCratesOnTop()
}
}
data class Instruction(val amount: Int, val source: Int, val target: Int)
class Crates(var crates: MutableList<String>) {
fun moveCrate(stackFrom: Int, stackTo: Int, n: Int = 1) {
val crate = popCrate(stackFrom, n)
addCrates(stackTo, crate)
}
private fun popCrate(stackId: Int, n: Int = 1): String {
val stack = crates[stackId - 1]
val crate = stack.substring(stack.length - n)
crates[stackId - 1] = stack.dropLast(n)
return crate
}
private fun addCrates(stackId: Int, crate: String) {
val stack = crates[stackId - 1]
crates[stackId - 1] = stack.plus(crate)
}
fun getCratesOnTop() : String {
return crates.mapNotNull { it.lastOrNull() }.joinToString("")
}
}
val exampleCrates = listOf("ZN","MCD","P")
val exerciseCrates = listOf("CZNBMWQV","HZRWCB","FQRJ","ZSWHFNMT","GFWLNQP","LPW","VBDRGCQJ","ZQNBW","HLFCGTJ")
/*
[V] [T] [J]
[Q] [M] [P] [Q] [J]
[W] [B] [N] [Q] [C] [T]
[M] [C] [F] [N] [G] [W] [G]
[B] [W] [J] [H] [L] [R] [B] [C]
[N] [R] [R] [W] [W] [W] [D] [N] [F]
[Z] [Z] [Q] [S] [F] [P] [B] [Q] [L]
[C] [H] [F] [Z] [G] [L] [V] [Z] [H]
1 2 3 4 5 6 7 8 9
*/
fun main() {
val day = Day05()
// test if implementation meets criteria from the description, like:
val testInput = readInput(day.index, true)
day.setCrates(exampleCrates)
check(day.part1(testInput) == "CMZ")
day.setCrates(exampleCrates)
check(day.part2(testInput) == "MCD")
val input = readInput(day.index)
day.setCrates(exerciseCrates)
day.part1(input).println()
day.setCrates(exerciseCrates)
day.part2(input).println()
}
| 0 | Kotlin | 0 | 0 | 207c47b47e743ec7849aea38ac6aab6c4a7d4e79 | 2,896 | aoc-2022-kotlin | Apache License 2.0 |
src/main/kotlin/ru/timakden/aoc/year2023/Day02.kt | timakden | 76,895,831 | false | {"Kotlin": 321649} | package ru.timakden.aoc.year2023
import arrow.core.fold
import ru.timakden.aoc.util.measure
import ru.timakden.aoc.util.readInput
/**
* [Day 2: Cube Conundrum](https://adventofcode.com/2023/day/2).
*/
object Day02 {
@JvmStatic
fun main(args: Array<String>) {
measure {
val input = readInput("year2023/Day02")
println("Part One: ${part1(input)}")
println("Part Two: ${part2(input)}")
}
}
fun part1(input: List<String>): Int {
val limits = mapOf("blue" to 14, "green" to 13, "red" to 12)
return input.filter { s ->
s.substringAfter(": ").split("; ").forEach { result ->
result.split(", ").forEach { cube ->
val color = cube.substringAfter(" ")
val count = cube.substringBefore(" ").toInt()
if (checkNotNull(limits[color]) < count) return@filter false
}
}
true
}.sumOf { it.substringAfter("Game ").substringBefore(":").toInt() }
}
fun part2(input: List<String>): Long {
return input.sumOf { s ->
val minimumRequiredCubes = mutableMapOf("blue" to 0, "green" to 0, "red" to 0)
s.substringAfter(": ").split("; ").forEach { result ->
result.split(", ").forEach { cube ->
val color = cube.substringAfter(" ")
val count = cube.substringBefore(" ").toInt()
if (checkNotNull(minimumRequiredCubes[color]) < count) minimumRequiredCubes[color] = count
}
}
minimumRequiredCubes.fold(1L) { acc, entry -> entry.value * acc }
}
}
}
| 0 | Kotlin | 0 | 3 | acc4dceb69350c04f6ae42fc50315745f728cce1 | 1,708 | advent-of-code | MIT License |
src/test/kotlin/Day02.kt | christof-vollrath | 317,635,262 | false | null | import io.kotest.core.datatest.forAll
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
/*
--- Day 2: Password Philosophy ---
See https://adventofcode.com/2020/day/2
*/
fun String.validatePasswordInput(): Boolean {
val (policy, password) = parsePolicyAndPassword(this)
val count = password.count { it == policy.c }
return count in (policy.atLeast .. policy.atMost)
}
fun String.validatePasswordInput2(): Boolean {
val (policy, password) = parsePolicyAndPassword(this)
val count = listOf(password[policy.pos1 - 1], password[policy.pos2 - 1]).count { it == policy.c }
return count == 1
}
fun parsePolicyAndPassword(input: String): Pair<PasswordPolicy, String> {
val regex = """(\d+)-(\d+) ([a-z]): ([a-z]*)""".toRegex()
val match = regex.find(input) ?: throw IllegalArgumentException("Can not parse input")
if (match.groupValues.size != 5) throw IllegalArgumentException("Not all elements parsed")
val values = match.groupValues
return Pair(PasswordPolicy(values[1].toInt(), values[2].toInt(), values[3].first()), values[4])
}
data class PasswordPolicy(val atLeast: Int, val atMost: Int, val c: Char) {
val pos1: Int // Aliases for part 2
get() = atLeast
val pos2: Int
get() = atMost
}
class Day02_ParseInput : FunSpec({
val policyAndPassword = parsePolicyAndPassword("1-3 a: abcde")
test("should be parsed correctly") {
policyAndPassword.second shouldBe "abcde"
policyAndPassword.first shouldBe PasswordPolicy(atLeast = 1, atMost = 3, c = 'a')
}
})
class Day02_CheckInput : FunSpec({
data class CountTestCase(val s: String, val c: Char, val expected: Int)
context("count chars") {
forAll(
CountTestCase("abcde", 'a', 1),
CountTestCase("cdefg", 'b', 0),
CountTestCase("ccccccccc", 'c', 9),
) { (s, c, expected) ->
s.count { it == c } shouldBe expected
}
}
data class ValidateTestCase(val s: String, val expected: Boolean)
context("validate passwords") {
forAll(
ValidateTestCase("1-3 a: abcde", true),
ValidateTestCase("1-3 b: cdefg", false),
ValidateTestCase("2-9 c: ccccccccc", true),
) { (s, expected) ->
s.validatePasswordInput() shouldBe expected
}
}
})
class Day02_Part1: FunSpec({
val inputStrings = readResource("day02Input.txt")!!.split("\n")
val count = inputStrings.count { it.validatePasswordInput() }
test("solution") {
count shouldBe 410
}
})
class Day02_CheckInput2 : FunSpec({
data class CountTestCase(val s: String, val expected: Int)
context("count chars") {
forAll(
CountTestCase("1-3 a: abcde", 1),
CountTestCase("1-3 b: cdefg", 0),
CountTestCase("2-9 c: ccccccccc", 2),
) { (s, expected) ->
val (policy, password) = parsePolicyAndPassword(s)
listOf(password[policy.pos1 - 1], password[policy.pos2 - 1]).count { it == policy.c } shouldBe expected
}
}
data class ValidateTestCase(val s: String, val expected: Boolean)
context("validate passwords") {
forAll(
ValidateTestCase("1-3 a: abcde", true),
ValidateTestCase("1-3 b: cdefg", false),
ValidateTestCase("2-9 c: ccccccccc", false),
) { (s, expected) ->
s.validatePasswordInput2() shouldBe expected
}
}
})
class Day02_Part2: FunSpec({
val inputStrings = readResource("day02Input.txt")!!.split("\n")
val count = inputStrings.count { it.validatePasswordInput2() }
test("solution") {
count shouldBe 694
}
})
| 1 | Kotlin | 0 | 0 | 8ad08350aa4bd1a29b7e18765fc7a2d6de8021e8 | 3,707 | advent_of_code_2020 | Apache License 2.0 |
src/Day07.kt | chasegn | 573,224,944 | false | {"Kotlin": 29978} |
/**
* Day 07 for Advent of Code 2022
* https://adventofcode.com/2022/day/7
*/
class Day07 : Day {
override val inputFileName: String = "Day07"
override val test1Expected: Int = 95437
override val test2Expected: Int = 24933642
/**
* Accepted solution: 1642503
*/
override fun part1(input: List<String>): Int {
val root = parseFSTree(input)
return getAllDirs(root)
.filter { it.size!! <= 100000 }
.fold(0) { acc, dir -> acc + dir.size!! }
}
/**
* Accepted solution:
*/
override fun part2(input: List<String>): Int {
val root = parseFSTree(input)
val allDirs = getAllDirs(root).sortedBy { it.size }
val deficit = 30000000 - (70000000 - root.size!!)
return allDirs.first { it.size!! >= deficit }.size!!
}
private fun parseFSTree(input: List<String>) : ElfDirectory {
val root = ElfDirectory("/", null)
var currentDir = root
input.forEach { line ->
val tokens = line.split(' ')
if (tokens[0].startsWith('d')) {
currentDir.contents.add(ElfDirectory(tokens[1], currentDir))
} else if (!tokens[0].startsWith('$')) {
currentDir.contents.add(ElfFile(line))
} else if (tokens[1] == "cd") {
currentDir = when (tokens[2]) {
"/" -> root
".." -> currentDir.parent!!
else -> currentDir.contents.filter{ it.name == tokens[2] }[0] as ElfDirectory
}
}
}
return root
}
private fun getAllDirs(node: ElfDirectory): List<ElfDirectory> {
val dirs = mutableListOf(node)
node.contents
.filterIsInstance<ElfDirectory>()
.forEach { dirs.addAll(getAllDirs(it)) }
return dirs
}
interface ElfData {
val name: String
}
data class ElfFile(override val name: String, val size: Int) : ElfData {
constructor(input: String) : this(input.split(' ')[1], input.split(' ')[0].toInt())
}
data class ElfDirectory(override val name: String, val parent: ElfDirectory?) : ElfData {
val contents = mutableListOf<ElfData>()
val size: Int? = null
get() = field ?: size()
private fun size(): Int {
var size = contents.filterIsInstance<ElfFile>()
.map { it.size }
.fold(0) { acc, s -> acc + s }
size = contents.filterIsInstance<ElfDirectory>()
.filter { it.contents.isNotEmpty() }
.map { it.size() }
.fold(size) { acc, s -> acc + s }
return size
}
}
} | 0 | Kotlin | 0 | 0 | 2b9a91f083a83aa474fad64f73758b363e8a7ad6 | 2,737 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/days/Day05.kt | TheMrMilchmann | 725,205,189 | false | {"Kotlin": 61669} | /*
* Copyright (c) 2023 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package days
import utils.readInput
fun main() {
val data = readInput()
val mappings = data.drop(2).joinToString(separator = "\n").split("\n\n").map { map ->
map.lines().drop(1).associate {
val (destinationStart, sourceStart, length) = it.split(' ').map(String::toLong)
sourceStart..<(sourceStart + length) to destinationStart..<(destinationStart + length)
}
}
fun part1(): Long {
val seeds = data.first().removePrefix("seeds: ").split(' ').map(String::toLong)
return seeds.minOf { seed ->
mappings.fold(seed) { acc, map ->
val (sourceRange, destRange) = map.entries.firstOrNull { acc in it.key } ?: return@fold acc
destRange.first + (acc - sourceRange.first)
}
}
}
fun part2(): Long {
val seedRanges = data.first().removePrefix("seeds: ").split(' ')
.asSequence()
.map(String::toLong)
.chunked(2)
.map { (a, b) -> a..<(a + b) }
return seedRanges.flatMap { seedRange ->
mappings.fold(listOf(seedRange)) { acc, map ->
buildList {
val sortedAcc = acc.sortedBy { it.first }
val sortedMap = map.entries.sortedBy { it.key.first }
var mapIndex = 0
for (i in sortedAcc.indices) {
var currentRange = sortedAcc[i]
while (mapIndex < sortedMap.size) {
val currentMapRange = sortedMap[mapIndex]
if (currentRange.last < currentMapRange.key.first) break
if (currentMapRange.key.last < currentRange.first) {
mapIndex++
continue
}
when {
currentRange.first < currentMapRange.key.first -> {
val splitRange = currentRange.first..<currentMapRange.key.first
add(splitRange)
currentRange = currentMapRange.key.first..currentRange.last
}
currentRange.last <= currentMapRange.key.last -> {
val offset = currentMapRange.value.first - currentMapRange.key.first
currentRange = (currentRange.first + offset)..(currentRange.last + offset)
break
}
currentRange.last > currentMapRange.key.last -> {
val splitRange = currentRange.first..currentMapRange.key.last
val offset = currentMapRange.value.first - currentMapRange.key.first
add((splitRange.first + offset)..(splitRange.last + offset))
currentRange = (currentRange.first + (currentMapRange.key.last - currentRange.first))..currentRange.last
mapIndex++
}
}
}
add(currentRange)
}
}
}
}.minOf(LongRange::first)
}
println("Part 1: ${part1()}")
println("Part 2: ${part2()}")
} | 0 | Kotlin | 0 | 1 | f94ff8a4c9fefb71e3ea183dbc3a1d41e6503152 | 4,627 | AdventOfCode2023 | MIT License |
src/day06/Day06.kt | dkoval | 572,138,985 | false | {"Kotlin": 86889} | package day06
import readInputAsString
private const val DAY_ID = "06"
fun main() {
fun solve(input: String, windowSize: Int): Int {
// sliding window [start : start + k - 1]
var start = 0
while (start + windowSize < input.length) {
// starting from `start` index, check next k characters
val seen = hashMapOf<Char, Int>()
for (i in start until start + windowSize) {
if (input[i] in seen) {
start = seen[input[i]]!! + 1
break
}
seen[input[i]] = i
}
// are checked k characters unique?
if (seen.size == windowSize) {
return start + windowSize
}
}
return -1
}
fun part1(input: String): Int = solve(input, 4)
fun part2(input: String): Int = solve(input, 14)
// test if implementation meets criteria from the description, like:
check(part1(readInputAsString("day${DAY_ID}/Day${DAY_ID}_test_part1_1")) == 7)
check(part1(readInputAsString("day${DAY_ID}/Day${DAY_ID}_test_part1_2")) == 5)
check(part1(readInputAsString("day${DAY_ID}/Day${DAY_ID}_test_part1_3")) == 6)
check(part1(readInputAsString("day${DAY_ID}/Day${DAY_ID}_test_part1_4")) == 10)
check(part1(readInputAsString("day${DAY_ID}/Day${DAY_ID}_test_part1_5")) == 11)
check(part2(readInputAsString("day${DAY_ID}/Day${DAY_ID}_test_part2_1")) == 19)
check(part2(readInputAsString("day${DAY_ID}/Day${DAY_ID}_test_part2_2")) == 23)
check(part2(readInputAsString("day${DAY_ID}/Day${DAY_ID}_test_part2_3")) == 23)
check(part2(readInputAsString("day${DAY_ID}/Day${DAY_ID}_test_part2_4")) == 29)
check(part2(readInputAsString("day${DAY_ID}/Day${DAY_ID}_test_part2_5")) == 26)
val input = readInputAsString("day${DAY_ID}/Day06")
println(part1(input)) // answer = 1766
println(part2(input)) // answer = 2383
}
| 0 | Kotlin | 1 | 0 | 791dd54a4e23f937d5fc16d46d85577d91b1507a | 1,962 | aoc-2022-in-kotlin | Apache License 2.0 |
src/Utils.kt | FuKe | 433,722,611 | false | {"Kotlin": 19825} | import models.BinaryNumber
import models.BingoPlate
import models.Bit
import java.io.File
/**
* Reads lines from the given input file.
*/
fun readInput(name: String) = File("src", name).readLines()
fun String.toBinaryNumber(): BinaryNumber {
val bits: List<Bit> = map {
Bit(it.toString().toInt())
}
return BinaryNumber(bits)
}
fun filterByMostSignificantBit(input: List<BinaryNumber>, filterAtPosition: Int): List<BinaryNumber> {
val mostSignificantBit: Bit = findMostSignificantBitAtPosition(input, filterAtPosition)
var filtered: List<BinaryNumber> = input.filterByBitAtPosition(mostSignificantBit, filterAtPosition)
if (filtered.size > 1) {
filtered = filterByMostSignificantBit(filtered, filterAtPosition + 1)
}
return filtered
}
fun filterByLeastSignificantBit(input: List<BinaryNumber>, filterAtPosition: Int): List<BinaryNumber> {
val leastSignificantBit: Bit = findLeastSignificantBitAtPosition(input, filterAtPosition)
var filtered: List<BinaryNumber> = input.filterByBitAtPosition(leastSignificantBit, filterAtPosition)
if (filtered.size > 1) {
filtered = filterByLeastSignificantBit(filtered, filterAtPosition + 1)
}
return filtered
}
fun findMostSignificantBitAtPosition(bits: List<BinaryNumber>, position: Int): Bit {
val bitsAtPosition: List<Bit> = bits.map {
it.bits[position]
}
val zeroCount = bitsAtPosition.count { it.value == 0 }
val oneCount = bitsAtPosition.count { it.value == 1 }
return if (zeroCount > oneCount) {
Bit(0)
} else {
Bit(1)
}
}
fun findLeastSignificantBitAtPosition(bits: List<BinaryNumber>, position: Int): Bit =
findMostSignificantBitAtPosition(bits, position).flip()
fun List<BinaryNumber>.filterByBitAtPosition(bit: Bit, position: Int): List<BinaryNumber> =
filter {
it.bits[position] == bit
}
fun parseBingoPlates(rawPuzzleInput: List<String>): List<BingoPlate> {
var convertedPlates: List<BingoPlate> = emptyList()
var plateRows: MutableList<List<Int>> = mutableListOf()
// First bingo plate starts at index 2
for (i in 2 until rawPuzzleInput.size) {
val line: String = rawPuzzleInput[i]
if (line.isBlank()) {
val plate = BingoPlate(plateRows)
convertedPlates = convertedPlates + plate
plateRows = mutableListOf()
} else {
val bingoRow: List<Int> = line
.split(" ")
.filter {
it.isNotBlank()
}
.map { it.toInt() }
plateRows += bingoRow
}
}
return convertedPlates
}
| 0 | Kotlin | 0 | 0 | 1cfe66aedd83ea7df8a2bc26c453df257f349b0e | 2,674 | advent-of-code-2021 | Apache License 2.0 |
src/Day04.kt | dmarcato | 576,511,169 | false | {"Kotlin": 36664} | fun main() {
fun String.toRange(): IntRange {
val (start, end) = split("-").map { it.toInt() }
return IntRange(start, end)
}
fun IntRange.contains(other: IntRange): Boolean {
return contains(other.first) && contains(other.last)
}
fun IntRange.overlap(other: IntRange): Boolean {
return contains(other.first) || contains(other.last)
}
fun part1(input: List<String>): Int {
return input.sumOf { row ->
val (first, second) = row.split(",").map { it.toRange() }
@Suppress("USELESS_CAST")
if (first.contains(second) || second.contains(first)) 1 else 0 as Int
}
}
fun part2(input: List<String>): Int {
return input.sumOf { row ->
val (first, second) = row.split(",").map { it.toRange() }
@Suppress("USELESS_CAST")
if (first.overlap(second) || second.overlap(first)) 1 else 0 as Int
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part1(testInput) == 2) { "part1 check failed" }
check(part2(testInput) == 4) { "part2 check failed" }
val input = readInput("Day04")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | 6abd8ca89a1acce49ecc0ca8a51acd3969979464 | 1,286 | aoc2022 | Apache License 2.0 |
src/main/kotlin/_2020/Day16.kt | thebrightspark | 227,161,060 | false | {"Kotlin": 548420} | package _2020
import aocRun
import splitToInts
private val RULE_REGEX = Regex("^([\\w\\s]+): (\\d+)-(\\d+) or (\\d+)-(\\d+)$")
fun main() {
aocRun(puzzleInput) { input ->
val parts = input.split("\n\n")
val rules = parseRules(parts[0])
val tickets = parseTickets(parts[2])
var invalidTotal = 0
tickets.forEach { ticket ->
ticket.forEach { num ->
if (!rules.any { rule -> rule.second.any { it.contains(num) } }) {
invalidTotal += num
}
}
}
return@aocRun invalidTotal
}
aocRun(testInput) { input ->
val parts = input.split("\n\n")
val rules = parseRules(parts[0])
val myTicket = parseMyTicket(parts[1])
val tickets = parseTickets(parts[2])
var invalidTotal = 0
val validatedTickets = tickets.filter { ticket ->
var valid = true
ticket.forEach { num ->
if (!rules.any { rule -> rule.second.any { it.contains(num) } }) {
valid = false
invalidTotal += num
}
}
return@filter valid
}
// TODO: Need to use a process of elimination to work out field mappings
val fieldSize = rules.size
val fieldMappings = mutableMapOf<String, Int>()
for (ticket in validatedTickets) {
println("\nTicket $ticket")
for ((i, num) in ticket.withIndex()) {
println("Num $i: $num")
if (!fieldMappings.containsValue(i)) {
val matchingRules = rules.filter { rule -> rule.second.any { it.contains(num) } }
println("Matching rules: ${matchingRules.size}")
if (matchingRules.size == 1) {
val matchingRule = matchingRules.single()
println("Match: $matchingRule")
fieldMappings[matchingRule.first] = i
}
}
}
if (fieldMappings.size == fieldSize)
break
}
return@aocRun fieldMappings
}
}
private fun parseRules(rules: String): List<Pair<String, Array<IntRange>>> = rules.split("\n").map {
RULE_REGEX.matchEntire(it)!!.run {
groupValues[1] to arrayOf(groupValues[2].toInt()..groupValues[3].toInt(), groupValues[4].toInt()..groupValues[5].toInt())
}
}
private fun parseMyTicket(ticket: String): List<Int> = ticket.split("\n")[1].splitToInts(",")
private fun parseTickets(tickets: String): List<List<Int>> =
tickets.split("\n").run { subList(1, size) }.map { it.splitToInts(",") }
private val testInput = """
class: 0-1 or 4-19
row: 0-5 or 8-19
seat: 0-13 or 16-19
your ticket:
11,12,13
nearby tickets:
3,9,18
15,1,5
5,14,9
""".trimIndent()
private val puzzleInput = """
departure location: 27-672 or 680-954
departure station: 25-430 or 439-966
departure platform: 31-293 or 299-953
departure track: 29-749 or 775-955
departure date: 43-93 or 107-953
departure time: 50-916 or 941-963
arrival location: 31-682 or 702-954
arrival station: 38-663 or 672-960
arrival platform: 31-629 or 635-969
arrival track: 42-365 or 371-967
class: 30-147 or 167-966
duration: 39-525 or 545-967
price: 30-803 or 822-950
route: 39-235 or 257-957
row: 33-206 or 231-971
seat: 29-784 or 798-951
train: 38-302 or 316-957
type: 50-635 or 642-966
wagon: 25-502 or 510-973
zone: 42-843 or 861-965
your ticket:
73,53,173,107,113,89,59,167,137,139,71,179,131,181,67,83,109,127,61,79
nearby tickets:
401,502,276,495,9,177,627,330,621,478,589,620,657,138,563,260,167,837,351,943
492,714,451,146,914,565,290,882,280,405,626,666,597,349,461,340,342,348,482,885
904,625,470,94,269,863,710,747,284,429,371,866,401,351,259,377,69,189,801,723
64,238,70,81,478,280,426,609,460,603,137,647,589,76,140,588,472,891,66,376
458,425,56,320,347,742,887,648,3,389,257,143,646,362,268,195,500,586,895,730
802,50,181,740,908,732,416,423,895,128,445,905,117,462,881,206,833,86,725,369
475,107,203,404,627,493,478,870,346,778,383,604,737,668,721,331,454,780,912,784
464,906,405,206,882,195,2,196,888,344,497,552,841,624,263,417,404,839,561,78
340,167,568,390,78,397,123,366,828,652,495,445,570,275,144,948,76,893,838,328
72,173,645,443,610,941,131,335,400,500,379,804,887,824,479,831,582,916,360,884
469,352,705,914,714,367,520,603,681,137,184,329,702,76,779,524,72,318,167,650
351,512,110,422,904,832,345,101,55,388,196,547,401,354,57,524,875,386,570,269
170,489,130,251,188,262,784,517,941,883,875,332,484,82,556,653,656,495,282,611
408,545,180,349,425,72,139,707,415,722,723,140,350,426,301,831,435,521,897,358
574,292,491,708,620,895,332,836,599,590,891,589,324,455,734,333,652,61,626,312
360,595,843,933,289,475,523,441,730,327,473,876,708,599,550,521,554,594,83,909
467,737,707,717,177,572,191,404,681,704,748,580,418,550,644,58,987,520,599,784
471,325,736,520,458,720,200,867,469,65,655,81,77,148,654,83,888,711,439,717
609,283,945,141,465,352,453,833,561,192,582,452,447,400,724,724,897,483,504,588
404,382,124,337,583,356,897,614,728,346,479,296,337,57,90,626,490,202,401,402
75,658,402,884,350,615,548,836,171,384,829,910,332,636,660,885,826,875,426,548
354,890,779,407,823,883,249,360,142,486,316,194,911,722,865,550,867,907,406,883
132,373,490,886,494,273,518,803,285,609,872,60,54,654,144,324,519,95,802,343
379,263,524,643,359,726,865,140,712,993,261,178,718,661,338,454,144,880,511,600
615,703,836,181,202,356,888,132,409,330,505,234,74,656,373,491,350,580,330,316
356,837,297,137,451,417,736,586,202,470,77,181,742,139,780,144,349,276,202,347
442,466,547,872,463,327,625,616,979,616,119,650,293,342,577,870,182,145,175,338
873,201,360,639,116,839,354,828,905,584,912,781,660,647,893,266,334,69,711,549
231,281,153,616,482,380,874,622,477,490,646,708,902,316,413,93,83,269,574,174
204,52,875,619,870,385,450,573,173,739,54,150,568,357,741,71,557,907,579,471
268,615,726,825,360,887,377,523,993,495,268,501,175,204,489,619,643,871,863,52
718,609,204,353,178,349,592,407,734,721,420,894,459,300,742,712,60,366,729,189
899,657,635,126,590,581,658,418,945,485,570,901,471,644,175,131,196,157,186,83
325,762,316,476,92,783,894,374,635,713,473,324,353,749,912,456,401,480,658,915
865,109,504,724,133,663,261,417,342,907,71,180,191,587,269,578,93,257,62,397
884,833,331,589,830,911,902,653,469,501,624,311,453,613,946,779,403,719,749,554
827,165,592,727,572,714,452,948,83,682,178,627,85,442,719,193,741,475,358,322
391,331,352,725,809,389,173,139,523,713,546,80,635,870,187,801,390,197,803,708
714,474,276,434,336,520,171,407,338,262,798,657,189,270,327,324,524,287,862,944
889,580,829,634,439,517,550,87,202,485,486,738,681,866,292,136,802,90,291,180
650,379,359,364,887,192,275,386,430,742,629,903,364,920,235,336,345,703,647,475
151,583,835,92,578,823,425,126,199,502,731,193,680,732,800,493,893,885,521,378
707,324,59,108,448,202,107,565,525,912,371,89,262,487,247,825,124,780,320,620
377,656,80,310,864,115,778,906,611,55,142,512,408,949,381,561,489,132,470,712
867,870,800,175,825,401,262,155,280,782,904,399,393,302,586,599,59,375,274,799
897,603,262,590,580,281,645,656,549,800,232,902,425,473,449,423,174,611,998,175
199,414,891,445,114,314,833,412,910,522,723,262,573,419,776,914,724,612,502,330
934,478,891,193,75,130,55,739,738,875,122,81,838,611,115,871,833,448,646,568
508,394,595,271,360,375,587,329,568,625,706,629,602,864,332,392,136,570,620,448
413,381,427,264,288,373,8,583,834,56,451,361,340,195,462,183,448,672,905,351
442,601,304,139,134,449,557,65,884,145,117,610,781,517,423,945,574,458,373,263
111,188,743,495,611,390,183,141,875,587,837,282,293,595,185,475,492,376,92,255
186,642,70,523,140,302,193,732,63,429,149,461,168,742,280,233,234,418,204,500
357,92,567,440,572,565,233,465,293,810,894,870,405,592,131,704,729,645,338,780
604,187,339,173,886,944,716,192,622,658,279,949,603,885,883,568,0,748,424,362
728,873,904,405,482,656,590,270,587,52,619,300,987,487,871,942,421,800,200,910
315,577,351,831,63,80,62,417,119,167,268,131,328,492,471,363,409,184,578,800
356,405,565,624,137,147,341,617,748,174,466,62,181,269,277,824,674,279,395,411
716,801,190,615,174,554,588,885,181,715,672,256,420,745,657,776,169,352,193,722
497,107,680,901,731,137,115,195,353,110,861,401,836,836,663,509,415,515,418,895
276,471,565,606,704,116,468,351,593,385,284,180,110,145,362,167,671,646,741,647
440,364,476,72,72,192,127,293,283,593,502,544,620,548,644,718,447,914,335,643
96,822,317,364,874,571,270,288,398,124,67,107,652,453,783,915,127,501,385,138
287,423,398,295,548,553,878,349,582,319,583,462,605,906,598,190,398,732,882,286
197,723,281,488,325,194,128,885,798,717,3,232,93,127,890,494,205,72,409,197
136,674,393,277,329,189,398,711,60,589,454,389,873,199,278,380,888,590,280,338
779,391,186,825,390,733,122,54,726,87,946,658,976,628,91,291,899,125,839,346
403,353,392,123,583,730,416,556,458,577,133,425,709,234,834,944,582,455,611,161
945,946,912,138,429,443,118,311,465,942,451,838,525,720,886,561,654,498,740,454
501,747,396,191,997,441,206,496,555,885,455,418,614,72,404,722,479,880,569,498
440,398,206,623,801,124,459,825,282,985,458,91,266,681,863,717,409,744,182,835
710,867,259,618,574,882,628,61,825,251,450,275,717,412,607,576,452,606,426,406
896,276,397,343,385,383,894,383,133,703,748,577,180,624,710,718,506,589,737,603
706,724,181,841,452,832,475,861,23,167,316,258,782,465,350,445,185,203,682,62
634,339,347,874,393,266,50,146,643,382,879,454,189,682,301,518,423,838,829,600
652,748,834,559,70,390,162,545,322,775,577,644,206,429,176,472,495,183,525,658
325,499,239,135,280,516,316,781,776,204,547,647,400,51,726,822,325,514,522,71
375,290,900,293,902,643,271,783,383,605,232,780,325,348,608,815,905,909,562,402
862,428,119,82,360,191,292,281,192,496,462,113,57,761,555,400,51,610,54,456
460,800,263,170,498,617,14,519,365,479,511,660,144,423,413,454,557,863,300,257
351,887,478,147,336,627,110,559,721,260,325,141,468,132,276,366,277,468,61,290
451,317,194,726,948,380,416,841,834,414,478,75,628,547,14,573,377,905,783,328
405,894,575,300,512,409,645,302,392,347,352,20,487,622,324,682,483,663,465,864
122,804,320,393,477,672,835,547,711,471,126,882,125,72,88,495,117,130,50,580
442,779,406,601,912,406,572,435,134,129,439,50,588,110,569,546,779,177,113,745
838,428,583,730,281,196,782,832,334,643,865,631,565,202,364,398,299,825,404,583
945,681,484,347,548,430,369,489,174,485,864,874,112,201,501,357,328,781,142,735
287,702,320,157,592,879,578,597,490,206,77,900,830,77,560,909,710,862,899,349
448,335,560,908,185,742,134,398,566,51,278,390,521,916,285,236,123,784,262,360
76,318,938,557,79,171,914,481,231,261,829,896,657,706,491,331,824,362,822,861
433,803,577,326,267,841,138,131,338,199,191,842,464,193,167,457,888,62,524,460
332,941,363,481,179,361,118,915,737,131,559,690,621,199,69,359,731,714,906,801
825,779,681,367,90,877,143,273,184,317,77,473,650,564,361,910,885,568,575,722
618,109,174,826,552,73,511,373,557,75,91,391,656,259,407,741,300,826,159,179
283,458,901,466,609,976,473,415,79,67,566,387,635,882,203,649,799,736,603,116
415,447,681,710,550,727,289,284,54,287,945,385,416,646,280,581,766,498,598,293
447,407,890,482,803,405,300,588,571,203,112,231,874,266,832,338,340,438,406,710
624,85,467,487,443,404,779,76,455,353,1,628,288,557,356,601,749,129,136,340
173,548,413,709,185,349,470,635,328,279,741,833,412,632,125,488,374,284,133,578
613,525,725,898,399,660,644,201,114,607,455,350,186,833,123,289,632,426,647,64
358,56,5,778,587,710,479,184,408,286,743,270,711,468,397,112,622,181,385,80
889,340,168,496,76,579,990,56,395,446,607,280,512,359,604,282,384,647,486,584
481,456,735,418,585,723,926,129,627,553,495,778,140,51,624,628,826,453,655,885
778,602,446,726,396,629,632,200,465,517,382,476,285,259,708,123,88,404,425,620
233,895,802,878,585,117,82,508,408,445,177,87,91,585,399,567,407,385,108,274
475,892,584,905,748,359,182,280,484,293,620,734,729,503,601,275,799,418,373,378
266,552,908,591,720,814,170,593,714,357,116,550,177,441,189,134,720,705,494,169
112,945,714,391,377,81,467,389,279,299,361,916,195,101,111,110,449,517,86,719
242,449,456,272,783,338,396,353,715,183,571,643,882,417,385,861,78,141,177,741
300,196,359,119,604,836,490,646,622,662,501,655,778,190,578,733,343,128,491,503
496,596,711,621,720,320,333,823,183,562,468,291,421,315,338,739,292,745,54,81
488,370,830,185,458,386,628,272,143,513,373,654,802,359,477,316,629,362,655,422
944,538,628,514,710,110,714,721,122,654,411,491,626,602,387,206,57,397,653,404
709,288,22,706,783,278,388,329,174,445,452,144,194,79,598,300,895,523,386,202
381,294,863,58,833,80,707,643,329,875,834,827,479,838,128,384,467,454,204,834
284,575,596,774,502,593,704,442,136,58,741,71,513,378,391,489,194,302,289,831
395,69,127,705,52,743,376,629,609,442,334,193,142,869,137,320,629,246,202,186
410,364,261,489,182,139,350,702,340,132,140,489,299,480,81,280,821,871,944,733
551,454,592,440,727,552,617,829,413,738,183,928,480,717,116,346,562,283,661,598
943,911,119,589,593,568,462,514,287,486,278,577,646,382,653,79,705,561,808,394
800,847,269,839,299,259,468,358,77,428,712,382,272,120,721,624,136,625,546,462
68,711,275,415,132,605,405,137,394,577,558,553,572,501,778,272,298,489,144,680
259,601,62,593,615,187,739,889,52,77,622,871,413,555,975,128,948,740,391,829
732,662,446,829,245,454,567,439,496,378,135,84,57,422,628,352,282,834,263,269
476,741,105,386,470,87,512,829,378,574,588,126,374,573,865,388,943,603,467,276
913,488,336,326,293,122,947,658,745,649,623,321,736,113,393,365,920,286,263,902
295,595,645,943,607,600,478,173,425,422,478,344,498,490,377,374,343,281,864,564
391,312,629,68,178,486,713,546,551,650,609,498,681,266,235,167,643,651,301,323
624,446,600,626,180,345,588,648,642,723,910,916,442,182,947,358,778,506,487,826
134,723,775,275,416,576,231,327,238,285,396,378,872,579,402,299,591,511,266,721
554,91,724,615,193,866,430,495,655,64,872,485,620,596,11,133,410,721,456,646
88,824,438,841,144,121,394,525,81,514,383,496,202,482,86,469,489,487,726,203
676,943,862,578,610,887,460,703,716,707,881,731,338,351,61,895,648,831,570,799
578,715,191,189,379,910,406,941,182,801,369,607,291,353,886,741,420,653,331,469
809,883,898,581,125,825,130,658,495,393,400,355,588,405,458,604,781,424,426,841
59,137,289,736,783,459,191,561,391,908,410,501,467,583,360,377,155,110,829,109
422,115,474,885,571,447,324,926,390,591,823,583,205,138,778,510,876,723,269,839
511,578,197,947,878,350,302,133,83,597,645,182,65,337,798,832,725,772,115,861
622,863,748,200,832,329,729,70,651,565,51,289,381,322,329,188,399,309,414,519
405,496,355,511,428,318,664,134,864,316,520,829,660,112,598,564,660,290,549,381
742,885,285,649,338,413,826,758,178,890,133,342,472,653,201,946,279,64,727,205
190,841,429,456,400,575,58,553,510,384,416,596,916,941,418,115,235,175,246,617
331,300,206,393,442,352,579,510,383,519,450,4,376,704,65,555,442,730,802,626
723,652,418,896,193,508,82,392,185,448,494,608,120,172,300,863,887,199,266,477
334,922,655,477,175,720,132,454,598,647,205,777,346,320,646,388,569,596,745,642
779,576,493,613,517,361,375,783,984,421,176,231,627,364,823,468,381,901,450,585
85,658,745,209,142,734,415,281,731,405,189,720,877,559,579,188,492,941,356,88
733,400,387,583,331,192,813,593,659,471,171,545,317,649,834,399,611,876,643,126
717,634,289,134,283,174,823,445,612,201,520,266,130,361,129,267,337,424,661,570
380,841,472,905,881,85,295,825,317,351,122,291,355,195,776,143,360,321,749,175
947,430,888,146,479,186,515,747,622,374,873,658,611,990,78,346,128,269,947,352
898,876,628,916,142,250,357,908,327,745,167,897,119,182,780,872,321,393,608,867
406,777,656,77,367,288,575,525,463,338,333,729,196,568,92,581,358,362,459,888
563,66,412,571,442,62,293,296,344,73,147,56,316,569,488,733,84,59,145,112
741,802,514,546,81,730,434,868,827,463,341,706,184,622,203,863,117,522,143,356
732,729,129,728,775,619,371,653,279,568,252,408,567,192,837,872,645,908,565,284
563,492,176,660,872,562,675,623,714,196,727,393,484,405,269,393,721,904,279,602
366,802,487,949,562,825,69,202,877,442,288,866,593,443,114,868,343,131,517,379
329,659,744,59,599,445,576,410,6,907,288,524,839,91,55,185,523,179,287,703
82,104,135,292,425,662,881,659,458,580,453,199,722,747,394,680,552,281,880,595
374,667,424,461,269,473,355,129,867,354,63,629,469,332,829,602,900,869,706,480
743,375,370,881,442,274,886,408,418,444,878,646,268,482,133,134,661,561,397,396
864,656,82,531,625,448,181,714,481,494,899,913,475,275,489,742,359,474,385,474
579,604,591,343,266,576,20,107,357,905,833,115,397,378,781,829,464,943,562,345
704,115,902,331,988,269,91,628,459,474,563,902,893,620,610,869,422,711,418,355
428,208,877,613,744,739,91,197,177,108,874,872,493,54,407,338,521,887,284,288
259,334,652,261,502,405,411,563,88,891,421,67,739,623,832,388,987,607,339,121
781,456,376,384,625,109,636,744,446,76,361,124,324,196,589,736,197,703,647,480
479,572,387,869,579,90,336,584,602,419,600,572,180,394,234,313,127,289,112,716
359,234,264,720,735,446,742,111,74,728,905,340,83,73,725,412,401,606,865,436
141,580,365,194,654,739,736,65,870,301,944,136,715,484,609,342,579,810,139,390
82,285,364,421,393,831,315,411,611,913,460,126,388,479,413,886,82,888,895,730
57,830,835,472,457,411,430,826,419,383,362,856,61,737,831,831,112,206,232,179
265,882,90,677,617,548,89,76,133,571,704,472,54,107,554,497,323,713,452,187
662,124,452,727,553,588,20,723,655,884,429,713,862,843,552,626,417,870,395,549
329,126,807,876,738,441,231,292,580,388,892,729,141,322,416,365,573,379,619,407
875,461,170,559,548,874,175,516,146,337,661,511,83,621,189,497,398,654,947,809
186,902,183,376,800,490,911,424,64,486,356,390,623,679,450,907,829,738,280,361
839,185,394,196,575,831,716,824,146,51,383,561,283,916,778,913,836,316,366,400
422,653,551,608,629,893,547,460,894,480,705,367,190,609,68,324,947,172,82,59
656,169,864,565,80,496,358,493,841,483,904,439,199,448,645,942,248,523,231,282
450,880,91,176,51,893,770,832,68,115,866,282,662,784,55,875,376,522,416,732
623,705,284,602,178,881,467,832,318,548,391,407,486,363,598,613,103,552,521,803
81,431,462,201,649,189,911,621,582,183,523,290,576,749,399,735,914,823,621,725
828,347,460,672,289,603,719,325,728,873,517,889,575,612,159,726,405,799,748,79
257,125,381,593,891,416,444,126,898,199,877,775,67,862,174,574,303,327,469,911
682,410,705,623,803,111,862,447,417,271,70,678,475,548,383,861,907,447,561,658
19,556,408,589,713,261,126,335,74,894,595,611,169,419,280,592,872,586,561,329
599,264,647,350,85,780,550,360,197,552,494,874,351,816,302,320,468,744,282,729
195,564,173,604,451,71,87,746,89,151,446,144,126,391,863,352,361,121,483,335
725,574,448,439,426,268,128,243,879,823,651,877,481,551,267,601,949,801,358,456
904,121,525,710,282,191,508,331,586,451,65,387,718,824,107,132,491,274,500,373
734,459,837,417,826,660,522,108,175,748,733,947,446,826,867,166,830,266,586,613
784,989,708,574,733,629,602,117,863,518,388,524,361,560,205,607,257,582,713,81
545,565,59,302,621,616,722,945,584,516,267,882,987,601,283,656,604,563,113,777
899,349,742,800,299,449,381,490,583,343,571,195,324,245,178,341,189,730,722,578
182,257,862,659,729,87,511,409,130,836,811,398,648,259,397,877,455,717,487,462
168,383,179,429,587,406,555,392,177,522,341,436,331,477,142,869,194,347,147,642
613,174,609,327,284,949,604,647,457,484,742,870,137,4,616,440,590,129,909,550
499,556,21,292,334,569,379,723,414,746,287,916,420,573,382,682,871,280,727,494
358,878,717,185,318,60,54,61,264,658,59,717,192,210,615,627,69,453,451,837
109,50,775,548,901,604,129,556,493,189,734,638,552,85,878,916,878,881,282,863
375,469,743,865,481,383,893,675,329,571,502,576,365,451,616,648,330,177,912,908
753,464,867,445,444,468,616,618,894,916,563,355,602,910,832,493,191,363,865,442
112,363,913,141,71,740,442,327,274,617,377,635,353,301,605,107,596,932,775,146
591,191,322,484,616,338,380,812,127,137,257,657,884,301,600,423,112,581,415,877
501,639,324,648,344,499,377,58,901,577,359,493,187,112,69,477,146,720,292,609
835,513,398,171,622,659,359,325,654,419,432,869,61,405,398,478,654,659,943,600
82,681,575,594,116,484,890,383,76,655,705,446,454,261,562,396,729,741,343,919
884,889,268,833,360,870,722,579,52,389,402,582,414,370,783,623,379,635,721,889
491,466,577,475,841,428,800,843,365,116,307,90,605,720,877,658,682,866,882,234
349,877,754,346,409,93,176,736,387,377,168,782,205,409,460,867,896,430,826,749
647,281,574,718,86,928,340,843,708,55,365,470,704,55,725,343,378,822,520,347
780,826,470,873,557,709,110,557,476,191,83,129,281,297,911,570,128,645,823,376
339,916,477,68,278,233,945,492,620,74,933,736,617,182,881,337,836,393,204,901
660,891,563,403,152,888,170,615,333,362,591,672,861,69,324,599,714,410,173,882
354,864,359,642,613,643,447,709,731,170,502,909,592,800,52,144,914,554,8,944
59,445,392,509,624,374,586,61,274,396,556,117,128,601,601,123,653,264,270,611
468,470,350,520,483,739,735,743,550,578,911,984,351,896,523,58,335,708,91,460
271,372,185,593,650,331,291,598,663,414,591,508,359,779,325,143,520,942,470,740
582,138,194,373,734,192,139,188,392,520,477,167,648,433,174,878,74,913,515,840
627,186,325,233,372,152,911,425,781,395,841,561,554,413,739,418,454,398,316,291
712,728,712,53,746,897,513,453,142,865,2,167,717,133,656,560,354,650,203,661
905,606,60,183,653,874,325,944,494,576,728,565,331,907,111,708,274,410,122,102
301,124,711,749,394,709,799,656,50,167,574,76,113,87,735,627,408,592,15,495
387,712,356,783,498,982,363,644,335,781,395,514,183,458,884,894,194,493,842,74
204,600,428,458,351,512,113,119,258,653,472,226,422,608,430,87,595,456,879,356
281,206,895,408,50,610,98,882,443,898,608,737,842,405,580,481,279,746,178,731
546,10,262,270,333,910,466,337,567,258,729,178,743,379,86,525,460,92,652,799
901,487,336,821,77,330,889,601,302,421,121,289,879,680,719,496,83,409,613,480
89,124,616,668,613,414,708,842,323,458,602,826,472,373,599,278,268,120,615,864
724,506,350,371,870,417,588,473,342,896,59,576,515,680,945,573,397,716,182,494
61,888,277,259,88,523,57,652,170,175,607,757,91,276,732,427,361,593,781,169
452,517,739,180,646,471,269,290,610,335,579,984,443,429,704,597,475,525,581,293
363,672,456,887,898,586,572,142,861,604,457,94,131,77,175,343,884,464,274,396
581,63,232,130,589,80,775,499,910,603,618,571,880,280,455,491,370,118,283,611
""".trimIndent()
| 0 | Kotlin | 0 | 0 | ac62ce8aeaed065f8fbd11e30368bfe5d31b7033 | 21,685 | AdventOfCode | Creative Commons Zero v1.0 Universal |
src/year2022/day14/Day14.kt | kingdongus | 573,014,376 | false | {"Kotlin": 100767} | package year2022.day14
import Point2D
import readInputFileByYearAndDay
import readTestFileByYearAndDay
import kotlin.math.max
import kotlin.math.min
class Cave(val dimension: Point2D) {
// we go cheap and model the field as characters, similar to the visualization on the page
private var fieldState: Array<CharArray> = arrayOf(CharArray(1) { '.' })
private var leftEdge = Int.MAX_VALUE
private var rightEdge = -1
private var bottomEdge = -1
init {
fieldState = Array(dimension.y) { CharArray(dimension.x) { '.' } }
}
fun addRocks(locations: List<Point2D>) {
// very brittle code, does no checks against the dimensions
locations.forEach { fieldState[it.y][it.x] = '#' }
rightEdge = max(rightEdge, locations.maxOf { it.x })
leftEdge = min(leftEdge, locations.minOf { it.y })
bottomEdge = max(bottomEdge, locations.maxOf { it.y })
}
private fun isOutOfBounds(position: Point2D) =
position.y < leftEdge || position.y > rightEdge || position.x > bottomEdge
// true if sand was placed, false if it fell into the void OR would block the spawn
fun addSand(): Boolean {
var position = spawnPoint
while (true) {
val next = nextPosition(position)
if (isOutOfBounds(next)) return false
if (spawnPoint == next) return false
if (position == next) {
fieldState[next.x][next.y] = 'o'
return true
}
position = next
}
}
private fun nextPosition(sand: Point2D): Point2D {
for (direction in directions) {
val newPosition = sand.moveBy(direction)
if (isOutOfBounds(newPosition)) return newPosition
if (fieldState[newPosition.x][newPosition.y] == '.') {
return newPosition
}
}
return sand
}
companion object {
val spawnPoint = Point2D(0, 500)
val directions = listOf(Point2D(1, 0), Point2D(1, -1), Point2D(1, 1))
}
}
fun main() {
fun parseRockLocations(input: List<String>): List<Point2D> {
val rockLocations = input.map { it.split(" -> ") }
.map {
it.map { numbers -> numbers.split(",") }
.map { number -> Point2D(number.first().toInt(), number.last().toInt()) }
}.flatMap { it.dropLast(1).zip(it.drop(1)) }
.flatMap { it.first..it.second }
.distinct()
return rockLocations
}
fun part1(input: List<String>): Int =
parseRockLocations(input).let {
val cave = Cave(dimension = Point2D(it.maxOf { it.x } + 1, it.maxOf { it.y } + 1))
cave.addRocks(it)
cave
}.let {
var maxSand = 0
while (it.addSand()) maxSand++
return maxSand
}
fun part2(input: List<String>): Int =
parseRockLocations(input).toMutableList()
.also {
val depthFromReadings = it.maxOf { it.y }
// we manually add another layer of rocks slightly lower than whatever the reading tells us
// when the description says "infinite in both directions", it really meant the range 0..9999
it.addAll((0 until 1000).map { Point2D(it, depthFromReadings + 2) })
}
.let {
val cave = Cave(dimension = Point2D(it.maxOf { it.x } + 1, it.maxOf { it.y } + 1))
cave.addRocks(it)
cave
}.let {
var maxSand = 0
while (it.addSand()) maxSand++
return maxSand + 1// +1 since the code will not allow us to block the sand spawn point
}
val testInput = readTestFileByYearAndDay(2022, 14)
check(part1(testInput) == 24)
check(part2(testInput) == 93)
val input = readInputFileByYearAndDay(2022, 14)
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | aa8da2591310beb4a0d2eef81ad2417ff0341384 | 3,988 | advent-of-code-kotlin | Apache License 2.0 |
src/com/mrxyx/algorithm/ArrayAlg.kt | Mrxyx | 366,778,189 | false | null | package com.mrxyx.algorithm
/**
* 数组
*/
class ArrayAlg {
/**
* 吃香蕉
* https://leetcode-cn.com/problems/koko-eating-bananas/
*/
fun minEatingSpeed(piles: IntArray, h: Int): Int {
val max = getMax(piles)
var left = 1
var right = max + 1
while (left < right) {
val mid = left + (right - left) / 2
//是否可以吃完
if (canFinish(piles, mid, h)) {
right = mid
} else {
left = mid + 1
}
}
return left
}
private fun canFinish(piles: IntArray, mid: Int, h: Int): Boolean {
var time = 0
for (i in piles) {
time += timeOf(i, mid)
}
return time <= h
}
private fun timeOf(i: Int, mid: Int): Int {
return i / mid + if (i % mid > 0) 1 else 0
}
private fun getMax(piles: IntArray): Int {
var max = 0
for (i in piles) {
max = i.coerceAtLeast(max)
}
return max
}
/**
* 在 D 天内送达包裹的能力
* https://leetcode-cn.com/problems/capacity-to-ship-packages-within-d-days/
*/
fun shipWithinDays(weights: IntArray, days: Int): Int {
//最小值
var left = getMax(weights)
//最大值
var right = getSum(weights) + 1
while (left < right) {
val mid = left + (right - left) / 2
//是否可以完成
if (canShipFinish(weights, mid, days)) {
right = mid
} else {
left = mid + 1
}
}
return left
}
private fun canShipFinish(weights: IntArray, mid: Int, days: Int): Boolean {
var i = 0
for (day in 0 until days) {
var maxCap = mid
while (weights[i].let { maxCap -= it; maxCap } >= 0) {
i++
if (i == weights.size) return true
}
}
return false
}
private fun getSum(weights: IntArray): Int {
var sum = 0
for (weight in weights) {
sum += weight
}
return sum
}
} | 0 | Kotlin | 0 | 0 | b81b357440e3458bd065017d17d6f69320b025bf | 2,182 | algorithm-test | The Unlicense |
src/main/kotlin/io/github/clechasseur/adventofcode2021/Day3.kt | clechasseur | 435,726,930 | false | {"Kotlin": 315943} | package io.github.clechasseur.adventofcode2021
import io.github.clechasseur.adventofcode2021.data.Day3Data
object Day3 {
private val data = Day3Data.data
fun part1(): Int {
val gamma = data.lines().first().indices.map { i ->
data.lines().map { it[i] }.groupBy { it }.mapValues { it.value.size }.toList().maxByOrNull { it.second }!!.first
}.joinToString("")
val epsilon = gamma.map { when (it) {
'0' -> '1'
'1' -> '0'
else -> error("Wrong binary digit: $it")
} }.joinToString("")
return gamma.toInt(radix = 2) * epsilon.toInt(radix = 2)
}
fun part2(): Int {
val oxygen = rating(data.lines(), 0, '1')
val co2 = rating(data.lines(), 0, '0')
return oxygen.toInt(radix = 2) * co2.toInt(radix = 2)
}
private fun rating(nums: List<String>, pos: Int, tiebreaker: Char): String = when (nums.size) {
1 -> nums.first()
else -> {
val digit = commonDigit(nums, pos, tiebreaker)
rating(nums.filter { it[pos] == digit }, pos + 1, tiebreaker)
}
}
private fun commonDigit(nums: List<String>, pos: Int, tiebreaker: Char): Char {
val counts = nums.map { it[pos] }.groupBy { it }.mapValues { it.value.size }.toList().sortedBy { it.second }
return when (counts[0].second) {
counts[1].second -> tiebreaker
else -> counts[tiebreaker.toString().toInt()].first
}
}
}
| 0 | Kotlin | 0 | 0 | 4b893c001efec7d11a326888a9a98ec03241d331 | 1,492 | adventofcode2021 | MIT License |
kotlin/1846-maximum-element-after-decreasing-and-rearranging.kt | neetcode-gh | 331,360,188 | false | {"JavaScript": 473974, "Kotlin": 418778, "Java": 372274, "C++": 353616, "C": 254169, "Python": 207536, "C#": 188620, "Rust": 155910, "TypeScript": 144641, "Go": 131749, "Swift": 111061, "Ruby": 44099, "Scala": 26287, "Dart": 9750} | // 1. O(nlogn) solution using sorting
class Solution {
fun maximumElementAfterDecrementingAndRearranging(arr: IntArray): Int {
arr.sort()
var prev = 0
for (n in arr) {
prev = minOf(prev + 1, n)
}
return prev
}
}
// 2. O(n) solution but at the cost of O(1) -> O(n) space
class Solution {
fun maximumElementAfterDecrementingAndRearranging(arr: IntArray): Int {
val n = arr.size
var count = IntArray (n + 1).apply {
for (num in arr)
this[minOf(n, num)]++
}
var last = 1
for (num in 1..n)
last = minOf(last + count[num], num)
return last
}
}
// 3. Same as solution 1, but using Kotlin's Aggregate operation fold()
class Solution {
fun maximumElementAfterDecrementingAndRearranging(arr: IntArray) = arr.sorted()
.fold(0) { acc, num -> minOf(acc + 1, num) }
}
// 4. Or alternativly, we could use a runningFold()
class Solution {
fun maximumElementAfterDecrementingAndRearranging(arr: IntArray) = arr.sorted()
.runningFold (0) { acc, num -> minOf(acc + 1, num) }
.last()
}
// 5. Same logic as first solution, but using a minHeap instead of sorting
class Solution {
fun maximumElementAfterDecrementingAndRearranging(arr: IntArray) = with (PriorityQueue<Int>()) {
addAll(arr.asSequence())
var last = 0
while (isNotEmpty()) {
if (poll() > last)
last++
}
last
}
}
| 337 | JavaScript | 2,004 | 4,367 | 0cf38f0d05cd76f9e96f08da22e063353af86224 | 1,526 | leetcode | MIT License |
y2022/src/main/kotlin/adventofcode/y2022/Day18.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2022
import adventofcode.io.AdventSolution
import adventofcode.util.vector.Vec3
object Day18 : AdventSolution(2022, 18, "Boiling Boulders") {
override fun solvePartOne(input: String): Int {
val lava = parse(input).toList()
val internalFaces = lava.flatMap { l -> directions.map(l::plus) }.count(lava::contains)
return (6 * lava.size) - internalFaces
}
override fun solvePartTwo(input: String): Int {
val lava = parse(input).toSet()
//bounding box
val xs = lava.minOf { it.x } - 1..lava.maxOf { it.x } + 1
val ys = lava.minOf { it.y } - 1..lava.maxOf { it.y } + 1
val zs = lava.minOf { it.z } - 1..lava.maxOf { it.z } + 1
//all reachable cubes
fun bfs(start: Vec3, reachableNeighbors: (Vec3) -> List<Vec3>): Set<Vec3> =
generateSequence(Pair(setOf(start), setOf(start))) { (frontier, visited) ->
val unexploredNeighbors = frontier.flatMap(reachableNeighbors).toSet() - visited
Pair(unexploredNeighbors, visited + unexploredNeighbors)
}
.takeWhile { (frontier, _) -> frontier.isNotEmpty() }
.last().second
//flood-fill the outside
val casing = bfs(Vec3.origin) { v ->
//reachable if in box but not in lava
directions.map(v::plus)
.filterNot(lava::contains)
.filter { it.x in xs && it.y in ys && it.z in zs }
}
//all faces that touch the casing are exposed
return lava.flatMap { l -> directions.map(l::plus) }.count(casing::contains)
}
private fun parse(input: String) =
input.lineSequence()
.map { it.split(',').map(String::toInt) }
.map { Vec3(it[0], it[1], it[2]) }
private val directions = listOf(
Vec3(-1, 0, 0),
Vec3(1, 0, 0),
Vec3(0, -1, 0),
Vec3(0, 1, 0),
Vec3(0, 0, -1),
Vec3(0, 0, 1)
)
} | 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 2,002 | advent-of-code | MIT License |
advent-of-code-2021/src/code/day6/Main.kt | Conor-Moran | 288,265,415 | false | {"Kotlin": 53347, "Java": 14161, "JavaScript": 10111, "Python": 6625, "HTML": 733} | package code.day6
import java.io.File
fun main() {
doIt("Day 6 Part 1: Test Input", "src/code/day6/test.input", part1);
doIt("Day 6 Part 1: Real Input", "src/code/day6/part1.input", part1);
doIt("Day 6 Part 2: Test Input", "src/code/day6/test.input", part2);
doIt("Day 6 Part 2: Real Input", "src/code/day6/part1.input", part2);
}
fun doIt(msg: String, input: String, calc: (nums: List<String>) -> Long) {
val lines = arrayListOf<String>()
File(input).forEachLine { lines.add(it) };
println(String.format("%s: Ans: %d", msg , calc(lines)));
}
val part1: (List<String>) -> Long = { lines ->
val numDays = 80;
val input = parse(lines)
val fishList = MutableList<Long>(9) {0};
for (i in 0 .. 8) {
fishList[i] = 0
}
input.nums.forEach() {
fishList[it] = fishList[it]!!.inc()
}
for (i in 0 until numDays) {
tick(fishList)
}
fishList.sum()
}
val part2: (List<String>) -> Long = { lines ->
val numDays = 256;
val input = parse(lines)
val fishList = MutableList<Long>(9) {0};
for (i in 0 .. 8) {
fishList[i] = 0
}
input.nums.forEach() {
fishList[it] = fishList[it]!!.inc()
}
for (i in 0 until numDays) {
tick(fishList)
}
fishList.sum()
}
val tick: (MutableList<Long>) -> Unit = { fish ->
val zeros = fish[0]!!
for (i in 0 until 8) {
fish[i] = fish[i+1]!!
}
fish[8] = zeros
fish[6] += zeros
}
val parse: (List<String>) -> Input = { lines ->
val nums = lines[0].split(",").map { Integer.parseInt(it) }
Input(nums)
}
class Input(val nums: List<Int>) {}
| 0 | Kotlin | 0 | 0 | ec8bcc6257a171afb2ff3a732704b3e7768483be | 1,651 | misc-dev | MIT License |
src/kotlin2022/Day09.kt | egnbjork | 571,981,366 | false | {"Kotlin": 18156} | package kotlin2022
import readInput
import kotlin.math.abs
fun main() {
val gameInput = readInput("Day09_test")
val parsedInput = parseSteps(gameInput)
println(parsedInput)
val rope = Rope()
parsedInput.forEach { move(rope, it) }
println(rope.positionVisited.size)
}
fun move(rope: Rope, direction: Pair<Char, Int>) {
when (direction.first) {
'R' -> rope.right(direction.second)
'U' -> rope.up(direction.second)
'L' -> rope.left(direction.second)
'D' -> rope.down(direction.second)
}
}
fun parseSteps(input: List<String>): List<Pair<Char, Int>> {
return input.map {
Pair(
it.split(" ")[0].toCharArray()[0],
it.split(" ")[1].toInt()
)
}
}
class Rope {
var head = Pair(0, 0)
var tail = MutableList(9) { 0 to 0 }
var positionVisited = mutableSetOf <Pair<Int, Int>>()
fun right(steps: Int) {
repeat(steps) {
head = head.copy(head.first, head.second + 1)
loopTail()
positionVisited.add(tail.last())
}
}
fun up(steps: Int) {
repeat(steps) {
head = head.copy(head.first + 1, head.second)
loopTail()
positionVisited.add(tail.last())
}
}
fun left(steps: Int) {
repeat(steps) {
head = head.copy(head.first, head.second - 1)
loopTail()
positionVisited.add(tail.last())
}
}
fun down(steps: Int) {
repeat(steps) {
head = head.copy(head.first - 1, head.second)
loopTail()
positionVisited.add(tail.last())
}
}
private fun loopTail() {
tail.forEachIndexed { i, v ->
if(i == 0) {
tail[0] = getTailPosition(head, tail[0])
} else {
tail[i] = getTailPosition(tail[i - 1], tail[i])
}
}
}
private fun getTailPosition(start: Pair<Int, Int>, end: Pair<Int, Int>): Pair<Int, Int> {
val xDistance = start.first - end.first
val yDistance = start.second - end.second
if (xDistance == 0 && abs(yDistance) == 2) {
return Pair(end.first, (end.second + yDistance / 2))
}
if (yDistance == 0 && abs(xDistance) == 2) {
return Pair(end.first + (xDistance / 2), end.second)
}
if (abs(xDistance) <= 1 && abs(yDistance) <= 1) {
return Pair(end.first, end.second)
}
return Pair(end.first + (xDistance / abs(xDistance)),
end.second + (yDistance / abs(yDistance)))
}
} | 0 | Kotlin | 0 | 0 | 1294afde171a64b1a2dfad2d30ff495d52f227f5 | 2,624 | advent-of-code-kotlin | Apache License 2.0 |
advent-of-code/src/main/kotlin/com/akikanellis/adventofcode/year2022/Day23.kt | akikanellis | 600,872,090 | false | {"Kotlin": 142932, "Just": 977} | package com.akikanellis.adventofcode.year2022
import com.akikanellis.adventofcode.year2022.utils.Point
import com.akikanellis.adventofcode.year2022.utils.circularListIterator
object Day23 {
fun numberOfEmptyGroundTiles(input: String): Int {
var grove = Grove.of(input)
val directions = Direction.orderedDirections.circularListIterator()
repeat(10) { grove = grove.moveElves(directions.next()) }
return grove.emptyGroundTiles()
}
fun roundWhereNoElfMoves(input: String): Int {
var grove = Grove.of(input)
val directions = Direction.orderedDirections.circularListIterator()
var round = 0
do {
round++
grove = grove.moveElves(directions.next())
} while (grove.numberOfElvesThatMoved != 0)
return round
}
private data class Grove(
val elves: List<Elf>,
val numberOfElvesThatMoved: Int = 0
) {
private val positionToElf = elves.associateBy { it.position }
private val minX = elves.minOf { it.x }
private val maxX = elves.maxOf { it.x }
private val minY = elves.minOf { it.y }
private val maxY = elves.maxOf { it.y }
fun hasElfInAny(positions: List<Point>) = positions.any { it in positionToElf }
fun emptyGroundTiles(): Int {
val totalNumberOfTiles = (maxX - minX + 1) * (maxY - minY + 1)
return totalNumberOfTiles - elves.size
}
fun moveElves(direction: Direction): Grove {
val elvesToProposedPositions = elves
.map { elf -> Pair(elf, elf.proposedPosition(direction, this)) }
val numberOfElvesThatMoved = elvesToProposedPositions
.count { (elf, proposedPosition) -> elf.position != proposedPosition }
val duplicatePositions = elvesToProposedPositions
.map { (_, proposedPosition) -> proposedPosition }
.groupingBy { proposedPosition -> proposedPosition }
.eachCount()
.filter { (_, numberOfDuplicates) -> numberOfDuplicates > 1 }
.keys
val (movingElves, stationaryElves) = elvesToProposedPositions
.partition { (_, proposedPosition) -> proposedPosition !in duplicatePositions }
val movedElves = movingElves.map { (_, proposedPosition) -> Elf(proposedPosition) }
val stationedElves = stationaryElves.map { (originalElf, _) -> originalElf }
return Grove(
elves = movedElves + stationedElves,
numberOfElvesThatMoved = numberOfElvesThatMoved
)
}
companion object {
fun of(representation: String) = representation
.lines()
.flatMapIndexed { y, row ->
row.mapIndexedNotNull { x, tileType ->
if (tileType == '#') {
Elf(Point(x, y))
} else {
null
}
}
}
.let { Grove(it) }
}
}
private data class Elf(val position: Point) {
val x = position.x
val y = position.y
fun proposedPosition(startingDirection: Direction, grove: Grove): Point {
if (!grove.hasElfInAny(Direction.allAdjacentPositions(position))) return position
val directions = startingDirection.directionsOrder
for (direction in directions) {
if (!grove.hasElfInAny(direction.adjacentPositions(position))) {
return direction.nextPosition(position)
}
}
return position
}
}
private enum class Direction {
N {
override val directionsOrder by lazy { listOf(N, S, W, E) }
override fun adjacentPositions(position: Point) = listOf(
position.minusY(),
position.minusY().plusX(),
position.minusY().minusX()
)
override fun nextPosition(position: Point) = position.minusY()
},
S {
override val directionsOrder by lazy { listOf(S, W, E, N) }
override fun adjacentPositions(position: Point) = listOf(
position.plusY(),
position.plusY().plusX(),
position.plusY().minusX()
)
override fun nextPosition(position: Point) = position.plusY()
},
W {
override val directionsOrder by lazy { listOf(W, E, N, S) }
override fun adjacentPositions(position: Point) = listOf(
position.minusX(),
position.minusY().minusX(),
position.plusY().minusX()
)
override fun nextPosition(position: Point) = position.minusX()
},
E {
override val directionsOrder by lazy { listOf(E, N, S, W) }
override fun adjacentPositions(position: Point) = listOf(
position.plusX(),
position.minusY().plusX(),
position.plusY().plusX()
)
override fun nextPosition(position: Point) = position.plusX()
};
abstract val directionsOrder: List<Direction>
abstract fun adjacentPositions(position: Point): List<Point>
abstract fun nextPosition(position: Point): Point
companion object {
val orderedDirections = N.directionsOrder
fun allAdjacentPositions(position: Point) = orderedDirections
.flatMap { it.adjacentPositions(position) }
.distinct()
}
}
}
| 8 | Kotlin | 0 | 0 | 036cbcb79d4dac96df2e478938de862a20549dce | 5,741 | advent-of-code | MIT License |
src/test/kotlin/days/y2022/Day09Test.kt | jewell-lgtm | 569,792,185 | false | {"Kotlin": 161272, "Jupyter Notebook": 103410, "TypeScript": 78635, "JavaScript": 123} | package days.y2022
import days.Day
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.core.Is.`is`
import org.junit.jupiter.api.Test
import kotlin.math.absoluteValue
class Day09 : Day(2022, 9) {
override fun partOne(input: String): Any {
val directions = parseInput(input)
val visited = mutableSetOf(Pair(0, 0))
var head = Pair(0, 0)
var tail = Pair(0, 0)
for (direction in directions) {
val (dx, dy) = direction.direction
var toTravel = direction.distance
while (toTravel > 0) {
head += Pair(dx, dy)
tail = tail.follow(head)
visited.add(tail)
toTravel--
}
}
return visited.size
}
override fun partTwo(input: String): Any {
val directions = parseInput(input)
val snake = MutableList(10) { Pair(0, 0) }
val visited = mutableSetOf(Pair(0, 0))
for (instruction in directions) {
repeat(instruction.distance) {
snake[0] += instruction.direction
// pretty sure most of the snake could stay still
for (segment in snake.indices.drop(1)) {
snake[segment] = snake[segment].follow(snake[segment - 1])
}
visited.add(snake.last())
}
}
return visited.size
}
private fun parseInput(input: String): List<Instruction> = input.lines().map { line -> Instruction.from(line) }
data class Instruction(val direction: Pair<Int, Int>, val distance: Int) {
companion object {
val directions = mapOf(
'U' to Pair(0, -1),
'D' to Pair(0, 1),
'L' to Pair(-1, 0),
'R' to Pair(1, 0),
)
fun from(line: String): Instruction {
val vec = directions[line[0]] ?: error("Invalid direction: ${line[0]}")
val distance = line.substring(2).toInt()
return Instruction(vec, distance)
}
}
}
private operator fun Pair<Int, Int>.plus(that: Pair<Int, Int>): Pair<Int, Int> =
Pair(this.first + that.first, this.second + that.second)
private val Pair<Int, Int>.allNeighborsAndMe: Set<Pair<Int, Int>>
get() = setOf(
Pair(first - 1, second - 1),
Pair(first, second - 1),
Pair(first + 1, second - 1),
Pair(first - 1, second),
Pair(first, second),
Pair(first + 1, second),
Pair(first - 1, second + 1),
Pair(first, second + 1),
Pair(first + 1, second + 1)
)
// pretty sure I could compute this rather than looping
fun Pair<Int, Int>.follow(that: Pair<Int, Int>): Pair<Int, Int> =
if (that.allNeighborsAndMe.contains(this)) this
else this.allNeighborsAndMe.minBy { it.distance(that) }
fun Pair<Int, Int>.distance(that: Pair<Int, Int>): Int =
(this.first - that.first).absoluteValue + (this.second - that.second).absoluteValue
}
class Day09Test {
@Test
fun testExampleOne() {
assertThat(
Day09().partOne(
"""
R 4
U 4
L 3
D 1
R 4
D 1
L 5
R 2
""".trimIndent()
), `is`(13)
)
}
@Test
fun testPartOne() {
assertThat(Day09().partOne(), `is`(6498))
}
@Test
fun testExampleTwo() {
assertThat(
Day09().partTwo(
"""
R 5
U 8
L 8
D 3
R 17
D 10
L 25
U 20
""".trimIndent()
), `is`(36)
)
}
@Test
fun testPartTwo() {
assertThat(Day09().partTwo(), `is`(2531))
}
}
| 0 | Kotlin | 0 | 0 | b274e43441b4ddb163c509ed14944902c2b011ab | 3,931 | AdventOfCode | Creative Commons Zero v1.0 Universal |
src/main/kotlin/year2022/day12/Problem.kt | Ddxcv98 | 573,823,241 | false | {"Kotlin": 154634} | package year2022.day12
import IProblem
class Problem : IProblem {
private lateinit var source: Node
private lateinit var dest: Node
private val matrix = javaClass
.getResource("/2022/12.txt")!!
.readText()
.lines()
.filter(String::isNotEmpty)
.mapIndexed { i, line ->
line
.mapIndexed { j, char ->
val c = when (char) {
'S' -> 'a'
'E' -> 'z'
else -> char
}
val node = Node(c, i, j)
if (char == 'S') {
source = node
} else if (char == 'E') {
dest = node
}
node
}
.toTypedArray()
}
.toTypedArray()
private fun adjOf(node: Node): Sequence<Node> {
val (_, i, j) = node.toTriple()
return sequence {
if (j != 0 && node.canComeFrom(matrix[i][j - 1])) yield(matrix[i][j - 1])
if (i != 0 && node.canComeFrom(matrix[i - 1][j])) yield(matrix[i - 1][j])
if (j != matrix[i].lastIndex && node.canComeFrom(matrix[i][j + 1])) yield(matrix[i][j + 1])
if (i != matrix.lastIndex && node.canComeFrom(matrix[i + 1][j])) yield(matrix[i + 1][j])
}
}
private fun bfs(predicate: (Node) -> Boolean): Int {
val dist = mutableMapOf(Pair(dest, 0))
val queue = ArrayDeque<Node>()
queue.add(dest)
while (queue.isNotEmpty()) {
val node = queue.removeFirst()
val d = dist[node]!! + 1
for (adj in adjOf(node)) {
if (!dist.containsKey(adj)) {
dist[adj] = d
if (predicate(adj)) {
return d
}
queue.addLast(adj)
}
}
}
return -1
}
override fun part1(): Int {
return bfs { it === source }
}
override fun part2(): Int {
return bfs { it.c == 'a' }
}
}
| 0 | Kotlin | 0 | 0 | 455bc8a69527c6c2f20362945b73bdee496ace41 | 2,167 | advent-of-code | The Unlicense |
src/main/kotlin/year_2022/Day02.kt | krllus | 572,617,904 | false | {"Kotlin": 97314} | package year_2022
import utils.readInput
fun main() {
fun part1(input: List<String>): Int {
var sum = 0
for (round in input) {
val plays = round.split(" ")
val one = plays[0]
val two = plays[1]
val rockPaperScissorPart1 = RockPaperScissor.fromPartOne(one)
val rockPaperScissorPart2 = RockPaperScissor.fromPartTwo(two)
val score = calculateScore(rockPaperScissorPart1, rockPaperScissorPart2)
sum += score
}
return sum
}
fun part2(input: List<String>): Int {
var sum = 0
for (round in input) {
val plays = round.split(" ")
val one = plays[0]
val two = plays[1]
val opponent = RockPaperScissor.fromPartOne(one)
val rockPaperScissorPart2 = compareResult(opponent, two)
val score = calculateScore(opponent, rockPaperScissorPart2)
sum += score
}
return sum
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
// rock - A
// paper - B
// scissor - C
// rock - x
// paper - y
// scisor - z
fun calculateScore(one: RockPaperScissor, two: RockPaperScissor): Int {
val choose = when (two) {
RockPaperScissor.ROCK -> 1
RockPaperScissor.PAPER -> 2
RockPaperScissor.SCISSOR -> 3
}
val result = compareInputs(one, two)
return choose + result
}
fun compareInputs(opponent : RockPaperScissor, mine : RockPaperScissor) : Int {
var matchResult = ""
// draw
if(opponent == mine)
matchResult = "draw"
// rock
if(opponent == RockPaperScissor.ROCK){
if(mine == RockPaperScissor.PAPER){
matchResult = "win"
}
if(mine == RockPaperScissor.SCISSOR){
matchResult = "lost"
}
}
// paper
if(opponent == RockPaperScissor.PAPER){
if(mine == RockPaperScissor.SCISSOR){
matchResult = "win"
}
if(mine == RockPaperScissor.ROCK){
matchResult = "lost"
}
}
// paper
if(opponent == RockPaperScissor.SCISSOR){
if(mine == RockPaperScissor.ROCK){
matchResult = "win"
}
if(mine == RockPaperScissor.PAPER){
matchResult = "lost"
}
}
return when (matchResult) {
"lost" -> 0
"draw" -> 3
"win" -> 6
else -> 0
}
}
fun compareResult(opponent : RockPaperScissor, input : String) : RockPaperScissor {
// lose - x
// draw - y
// win - z
val matchResult = when (input.lowercase()) {
"x" -> "lose"
"y" -> "draw"
"z" -> "win"
else -> error("check your input")
}
// draw
if(matchResult == "draw")
return opponent
// rock
if(opponent == RockPaperScissor.ROCK){
if(matchResult == "win"){
return RockPaperScissor.PAPER
}
if(matchResult == "lose"){
return RockPaperScissor.SCISSOR
}
}
// paper
if(opponent == RockPaperScissor.PAPER){
if(matchResult == "win"){
return RockPaperScissor.SCISSOR
}
if(matchResult == "lose"){
return RockPaperScissor.ROCK
}
}
// paper
if(opponent == RockPaperScissor.SCISSOR){
if(matchResult == "win"){
return RockPaperScissor.ROCK
}
if(matchResult == "lose"){
return RockPaperScissor.PAPER
}
}
error("check your input")
}
enum class RockPaperScissor {
ROCK,
PAPER,
SCISSOR;
companion object {
fun fromPartOne(input: String): RockPaperScissor {
return when (input.lowercase()) {
"a" -> ROCK
"b" -> PAPER
"c" -> SCISSOR
else -> error("cleck your input")
}
}
fun fromPartTwo(input: String): RockPaperScissor {
return when (input.lowercase()) {
"x" -> ROCK
"y" -> PAPER
"z" -> SCISSOR
else -> error("cleck your input")
}
}
}
}
| 0 | Kotlin | 0 | 0 | b5280f3592ba3a0fbe04da72d4b77fcc9754597e | 4,441 | advent-of-code | Apache License 2.0 |
src/main/kotlin/cc/stevenyin/leetcode/_0881_BoatsToSavePeople.kt | StevenYinKop | 269,945,740 | false | {"Kotlin": 107894, "Java": 9565} | package cc.stevenyin.leetcode
/**
* https://leetcode.com/problems/boats-to-save-people/
* You are given an array people where people[i] is the weight of the ith person, and an infinite number of boats where each boat can carry a maximum weight of limit. Each boat carries at most two people at the same time, provided the sum of the weight of those people is at most limit.
*
* Return the minimum number of boats to carry every given person.
*
*
*
* Example 1:
*
* Input: people = [1,2], limit = 3
* Output: 1
* Explanation: 1 boat (1, 2)
* Example 2:
*
* Input: people = [3,2,2,1], limit = 3
* Output: 3
* Explanation: 3 boats (1, 2), (2) and (3)
* Example 3:
*
* Input: people = [3,5,3,4], limit = 5
* Output: 4
* Explanation: 4 boats (3), (3), (4), (5)
*
*
* Constraints:
*
* 1 <= people.length <= 5 * 104
* 1 <= people[i] <= limit <= 3 * 104
*/
class _0881_BoatsToSavePeople {
fun numRescueBoats(people: IntArray, limit: Int): Int {
people.sort()
var right = people.size - 1
var left = 0
var boats = 0
while (left <= right) {
if (people[left] + people[right] <= limit) {
boats ++
left ++
right --
} else {
boats ++
right --
}
}
return boats
}
}
fun main() {
val solution = _0881_BoatsToSavePeople()
assert(solution.numRescueBoats(intArrayOf(1, 2), 3) == 1)
assert(solution.numRescueBoats(intArrayOf(3, 2, 2, 1), 3) == 3)
assert(solution.numRescueBoats(intArrayOf(3, 5, 3, 4), 5) == 4)
}
| 0 | Kotlin | 0 | 1 | 748812d291e5c2df64c8620c96189403b19e12dd | 1,618 | kotlin-demo-code | MIT License |
src/main/kotlin/aoc2023/day15/day15Solver.kt | Advent-of-Code-Netcompany-Unions | 726,531,711 | false | {"Kotlin": 94973} | package aoc2023.day15
import lib.*
suspend fun main() {
setupChallenge().solveChallenge()
}
fun setupChallenge(): Challenge<List<String>> {
return setup {
day(15)
year(2023)
//input("example.txt")
parser {
it.readText().trim().split(",")
}
partOne {
val verifications = it.map { it.calculateHASH() }
verifications.sum().toString()
}
partTwo {
val boxes = (0..255).associateWith { Box(listOf()) }
it.forEach { inst -> if (inst.contains("-")) boxes.remove(inst) else boxes.set(inst) }
val powers = boxes.entries.map { it.value.getFocusPower(it.key) }
powers.sum().toString()
}
}
}
fun String.calculateHASH(): Int {
return this.fold(0) { sum, c -> ((sum + c.code) * 17) % 256 }
}
data class Lens(val label: String, var strength: Int)
data class Box(var contents: List<Lens>)
fun Map<Int, Box>.remove(inst: String) {
val label = inst.dropLast(1)
val box = this[label.calculateHASH()]!!
val lens = box.contents.firstOrNull() { it.label == label }
if (lens != null) {
box.contents = box.contents.minus(lens)
}
}
fun Map<Int, Box>.set(inst: String) {
val instParts = inst.split("=")
val label = instParts.first()
val box = this[label.calculateHASH()]!!
if (box.contents.any { it.label == label }) {
val lens = box.contents.first { it.label == label }
lens.strength = instParts.last().toInt()
} else {
box.contents = box.contents.plus(Lens(label, instParts.last().toInt()))
}
}
fun Box.getFocusPower(boxnumber: Int): Long {
return contents.foldIndexed(0) { i, s, l ->
s + (boxnumber + 1) * (i + 1) * l.strength
}
} | 0 | Kotlin | 0 | 0 | a77584ee012d5b1b0d28501ae42d7b10d28bf070 | 1,792 | AoC-2023-DDJ | MIT License |
src/main/kotlin/cc/stevenyin/leetcode/_0003_LengthOfLongestSubstring.kt | StevenYinKop | 269,945,740 | false | {"Kotlin": 107894, "Java": 9565} | package cc.stevenyin.leetcode
/**
* https://leetcode.com/problems/longest-substring-without-repeating-characters/description/
* Given a string s, find the length of the longest substring without repeating characters.
*
*
* Example 1:
* Input: s = "abcabcbb"
* Output: 3
* Explanation: The answer is "abc", with the length of 3.
* Example 2:
*
* Input: s = "bbbbb"
* Output: 1
* Explanation: The answer is "b", with the length of 1.
* Example 3:
*
* Input: s = "pwwkew"
* Output: 3
* Explanation: The answer is "wke", with the length of 3.
* Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
*
*
* Constraints:
*
* 0 <= s.length <= 5 * 104
* s consists of English letters, digits, symbols and spaces.
* /
*
*/
class _0003_LengthOfLongestSubstring {
// fun lengthOfLongestSubstring(str: String): Int {
// val charSet = HashSet<String>()
// var left = 0
// var right = 0
// var max = 0
// while (right < str.length) {
// if (!charSet.contains(str[right].toString())) {
// charSet.add(str[right].toString())
// right ++
// } else {
// charSet.remove(str[left].toString())
// left ++
// }
// max = maxOf(max, right - left)
// }
// return max
// }
fun lengthOfLongestSubstring(str: String): Int {
val charCounts = IntArray(256)
var left = 0
var right = 0
var maxLen = 0
var curLen: Int
while (right < str.length) {
val rightChar = str[right]
charCounts[rightChar.toInt()]++
while (charCounts[rightChar.toInt()] > 1) {
val leftChar = str[left]
charCounts[leftChar.toInt()]--
left++
}
curLen = right - left + 1
maxLen = maxOf(maxLen, curLen)
right++
}
return maxLen
}
}
fun main() {
val solution = _0003_LengthOfLongestSubstring()
assert(solution.lengthOfLongestSubstring("abcabcbb") == 3)
assert(solution.lengthOfLongestSubstring("bbbbb") == 1)
assert(solution.lengthOfLongestSubstring("pwwkew") == 3)
assert(solution.lengthOfLongestSubstring("aab") == 2)
assert(solution.lengthOfLongestSubstring("aba") == 2)
}
| 0 | Kotlin | 0 | 1 | 748812d291e5c2df64c8620c96189403b19e12dd | 2,370 | kotlin-demo-code | MIT License |
src/Day01.kt | jaldhar | 573,188,501 | false | {"Kotlin": 14191} | fun main() {
// convert the entries in [input[ to integers, provide the total calories
// for each elf and return the top [upto] elves
fun countCalories(input: List<String>, upto: Int): Int {
val elves = mutableMapOf<Int, Int>()
var elf = 1
elves[elf] = 0
for (line in input) {
if (line.isEmpty()) {
elf++;
elves[elf] = 0
} else {
val calories = line.toInt()
elves[elf] = elves[elf]!!.plus(calories)
}
}
val top: List<Int> = elves
.keys
.sortedWith(compareByDescending { elves[it] })
.slice(0 .. upto - 1)
var result = 0
for (e in top) {
result += elves[e]!!
}
return result;
}
fun part1(input: List<String>): Int {
return countCalories(input, 1);
}
fun part2(input: List<String>): Int {
return countCalories(input, 3);
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | b193df75071022cfb5e7172cc044dd6cff0f6fdf | 1,256 | aoc2022-kotlin | Apache License 2.0 |
src/Day04.kt | D000L | 575,350,411 | false | {"Kotlin": 23716} | fun main() {
fun part1(input: List<String>): Int {
return input.map {
val (a, b, x, y) = it.split(",", "-").map { it.toInt() }
val ra = IntRange(a, b)
val rb = IntRange(x, y)
if (ra.all { it in rb } || rb.all { it in ra }) 1
else 0
}.sumOf { it }
}
fun part2(input: List<String>): Int {
return input.map {
val (a, b, x, y) = it.split(",", "-").map { it.toInt() }
val ra = IntRange(a, b)
val rb = IntRange(x, y)
if (ra.intersect(rb).isNotEmpty()) 1
else 0
}.sumOf { it }
}
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | b733a4f16ebc7b71af5b08b947ae46afb62df05e | 735 | adventOfCode | Apache License 2.0 |
src/Day06.kt | Misano9699 | 572,108,457 | false | null | fun main() {
fun isUnique(substring: String, markerLength: Int): Boolean {
val setOfStrings = mutableSetOf<Char>()
substring.forEach {
setOfStrings.add(it)
}
return setOfStrings.size == markerLength
}
fun process(input: List<String>, markerLength: Int): String {
val startIndex = markerLength - 1
// although the real input is just one line I want to test all the lines of the test input to be sure I have it right
return input.map { line ->
var i = startIndex
while (i < line.length && !isUnique(line.substring(i - startIndex, i + 1), markerLength)) i++
i + 1
}.toString()
}
fun part1(input: List<String>): String {
return process(input, 4)
}
fun part2(input: List<String>): String {
return process(input, 14)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day06_test")
val input = readInput("Day06")
check(part1(testInput).also { println("Answer test input part1: $it") } == "[7, 5, 6, 10, 11]")
println("Answer part1: " + part1(input))
check(part2(testInput).also { println("Answer test input part2: $it") } == "[19, 23, 23, 29, 26]")
println("Answer part2: " + part2(input))
}
| 0 | Kotlin | 0 | 0 | adb8c5e5098fde01a4438eb2a437840922fb8ae6 | 1,327 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/ConstrainedSubsequenceSum.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.Deque
import java.util.LinkedList
import kotlin.math.max
/**
* 1425. Constrained Subsequence Sum
* @see <a href="https://leetcode.com/problems/constrained-subsequence-sum/">Source</a>
*/
fun interface ConstrainedSubsequenceSum {
operator fun invoke(nums: IntArray, k: Int): Int
}
class ConstrainedSubsequenceSumDeque : ConstrainedSubsequenceSum {
override operator fun invoke(nums: IntArray, k: Int): Int {
var res = nums.firstOrNull() ?: Int.MIN_VALUE
val q: Deque<Int> = LinkedList()
for (i in nums.indices) {
nums[i] += if (q.isNotEmpty()) q.peek() else 0
res = res.coerceAtLeast(nums[i])
while (q.isNotEmpty() && nums[i] > q.peekLast()) q.pollLast()
if (nums[i] > 0) q.offer(nums[i])
if (i >= k && q.isNotEmpty() && q.peek() == nums[i - k]) q.poll()
}
return res
}
}
class ConstrainedSubsequenceSumDP : ConstrainedSubsequenceSum {
override operator fun invoke(nums: IntArray, k: Int): Int {
val n: Int = nums.size
val dp = IntArray(n)
var ans = Int.MIN_VALUE
for (i in 0 until n) {
var max = 0
for (j in max(i - k, 0) until i) {
max = max(max, dp[j])
}
dp[i] = nums[i] + max
ans = max(ans, dp[i])
}
return ans
}
}
class ConstrainedSubsequenceSumQueue : ConstrainedSubsequenceSum {
override operator fun invoke(nums: IntArray, k: Int): Int {
val n: Int = nums.size
val dp = IntArray(n)
val deque: Deque<Int> = LinkedList()
var ans = Int.MIN_VALUE
for (i in 0 until n) {
val max = max(0, if (deque.isEmpty()) 0 else dp[deque.peekFirst()])
dp[i] = nums[i] + max
ans = max(ans, dp[i])
while (deque.isNotEmpty() && dp[i] >= dp[deque.peekLast()]) {
deque.pollLast()
}
deque.addLast(i)
if (i - deque.peekFirst() + 1 > k) {
deque.removeFirst()
}
}
return ans
}
}
/**
* Solution 3: DP + Decreasing Monotonic Queue + Optimized Space
*/
class ConstrainedSubsequenceSumQueueOpt : ConstrainedSubsequenceSum {
override operator fun invoke(nums: IntArray, k: Int): Int {
val n: Int = nums.size
val deque: Deque<Int> = LinkedList()
var ans = Int.MIN_VALUE
for (i in 0 until n) {
val max: Int = max(0, if (deque.isEmpty()) 0 else nums[deque.peekFirst()])
nums[i] += max
ans = max(ans, nums[i])
while (deque.isNotEmpty() && nums[i] >= nums[deque.peekLast()]) {
deque.pollLast()
}
deque.addLast(i)
if (i - deque.peekFirst() + 1 > k) {
deque.removeFirst()
}
}
return ans
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 3,548 | kotlab | Apache License 2.0 |
2023/src/main/kotlin/com/github/akowal/aoc/Day02.kt | akowal | 573,170,341 | false | {"Kotlin": 36572} | package com.github.akowal.aoc
import java.io.File
class Day02(input: File) : Problem<Int> {
private val games = loadGames(input)
override fun solve1(): Int {
return games
.filter { game -> game.grabs.all { it.r <= 12 && it.g <= 13 && it.b <= 14 } }
.sumOf { it.n }
}
override fun solve2(): Int {
return games.sumOf { game ->
val minR = game.grabs.maxOf { it.r }
val minG = game.grabs.maxOf { it.g }
val minB = game.grabs.maxOf { it.b }
minR * minG * minB
}
}
private fun loadGames(f: File): List<Game> {
return f.readLines().mapIndexed { i, line ->
val grabs = line.substringAfter(':').split(';').map { it.asGrab() }
Game(i + 1, grabs)
}
}
private data class Game(
val n: Int,
val grabs: List<Grab>,
)
private data class Grab(
val r: Int,
val g: Int,
val b: Int,
)
private fun String.asGrab(): Grab {
var r = 0
var g = 0
var b = 0
split(',').forEach {
val (n, color) = it.trim().split(' ')
when (color) {
"red" -> r = n.toInt()
"green" -> g = n.toInt()
"blue" -> b = n.toInt()
else -> error("xoxoxo: $color")
}
}
return Grab(r, g, b)
}
}
fun main() {
Launcher("day02", ::Day02).run()
}
| 0 | Kotlin | 0 | 0 | 02e52625c1c8bd00f8251eb9427828fb5c439fb5 | 1,475 | advent-of-kode | Creative Commons Zero v1.0 Universal |
src/Day11.kt | dmarmelo | 573,485,455 | false | {"Kotlin": 28178} | private typealias Operation = (old: Long) -> Long
private data class MonkeyTest(
val value: Long,
val ifTrue: Int,
val ifFalse: Int
) {
operator fun invoke(value: Long) =
if (value % this.value == 0L) ifTrue else ifFalse
}
private data class Monkey(
val id: Int,
val items: List<Long>,
val operation: Operation,
val test: MonkeyTest
)
private fun createOperation(expression: String): Operation {
val (operand1, operator, operand2) = """new = (.+) (.+) (.+)""".toRegex().matchEntire(expression)!!.destructured
return when (operator) {
"+" -> { old -> (operand1.toLongOrNull() ?: old) + (operand2.toLongOrNull() ?: old) }
"-" -> { old -> (operand1.toLongOrNull() ?: old) - (operand2.toLongOrNull() ?: old) }
"*" -> { old -> (operand1.toLongOrNull() ?: old) * (operand2.toLongOrNull() ?: old) }
"/" -> { old -> (operand1.toLongOrNull() ?: old) / (operand2.toLongOrNull() ?: old) }
else -> error("Unknown operator $operator")
}
}
private fun List<String>.toMonkey(): Monkey {
val number = """Monkey (\d+):""".toRegex().matchEntire(this[0])!!.groupValues[1].toInt()
val items = this[1].trim().substringAfter("Starting items: ").split(", ").map { it.toLong() }
val operation = this[2].trim().substringAfter("Operation: ").let(::createOperation)
val test = this[3].trim().substringAfter("Test: divisible by ").toLong()
val ifTestTrue = this[4].trim().substringAfter("If true: throw to monkey ").toInt()
val ifTestFalse = this[5].trim().substringAfter("If false: throw to monkey ").toInt()
return Monkey(
number,
items,
operation,
MonkeyTest(test, ifTestTrue, ifTestFalse)
)
}
fun main() {
fun <R> List<String>.parts(delimiter: String = "", part: (List<String>) -> R): List<R> = buildList {
var current = mutableListOf<String>()
this@parts.forEach {
if (it == delimiter) {
add(part(current))
current = mutableListOf()
} else {
current += it
}
}
if (current.isNotEmpty()) {
add(part(current))
}
}
fun List<String>.parseInput() = parts { it.toMonkey() }
fun solve(input: List<Monkey>, rounds: Int, processWorry: (Long) -> Long): Long {
val monkeys = input.toMutableList()
val monkeyOperations = LongArray(input.size) { 0 }
repeat(rounds) {
repeat(monkeys.size) { monkeyNumber ->
val monkey = monkeys[monkeyNumber]
monkey.items.forEach { item ->
val newItem = processWorry(monkey.operation(item))
val throwToMonkey = monkey.test(newItem)
val catcherMonkey = monkeys[throwToMonkey]
monkeys[throwToMonkey] = catcherMonkey.copy(items = catcherMonkey.items + newItem)
monkeyOperations[monkey.id] = monkeyOperations[monkey.id] + 1
}
monkeys[monkey.id] = monkey.copy(items = emptyList())
}
}
return monkeyOperations.sortedDescending().take(2).product()
}
fun part1(input: List<Monkey>) = solve(input, 20) { it / 3 }
fun part2(input: List<Monkey>): Long {
val commonModulus = input.fold(1L) { acc, monkey -> acc * monkey.test.value }
return solve(input, 10_000) { it % commonModulus }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day11_test").parseInput()
check(part1(testInput) == 10_605L)
check(part2(testInput) == 2_713_310_158L)
val input = readInput("Day11").parseInput()
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 5d3cbd227f950693b813d2a5dc3220463ea9f0e4 | 3,766 | advent-of-code-2022 | Apache License 2.0 |
kotlin/src/2022/Day23_2022.kt | regob | 575,917,627 | false | {"Kotlin": 50757, "Python": 46520, "Shell": 430} | fun main() {
data class P(val x: Int, val y: Int)
val init = mutableSetOf<P>()
readInput(23).trim()
.lines().withIndex().forEach {
it.value.withIndex().forEach {itc ->
if (itc.value == '#') init.add(P(itc.index, it.index))
}
}
var e = init.toMutableSet()
val constraints = mutableListOf(
listOf(P(-1, -1), P(0, -1), P(1, -1)) to P(0, -1),
listOf(P(0, 1), P(-1, 1), P(1, 1)) to P(0, 1),
listOf(P(-1, 0), P(-1, -1), P(-1, 1)) to P(-1, 0),
listOf(P(1, 0), P(1, -1), P(1, 1)) to P(1, 0),
)
val neigh = listOf(P(-1, -1), P(0, -1), P(1, -1), P(-1, 0), P(1, 0), P(-1, 1), P(0, 1), P(1, 1))
fun stepConstraints() = constraints.add(constraints.removeFirst())
fun next(p: P): P {
if (neigh.all {P(p.x + it.x, p.y + it.y) !in e}) return p
val diff = constraints.firstOrNull {it.first.all {ap -> P(ap.x + p.x, ap.y + p.y) !in e}}?.second
if (diff != null) return P(p.x + diff.x, p.y + diff.y)
return p
}
fun simulate(n: Int, part2: Boolean): Int {
for (rep in 1..n) {
val d = mutableMapOf<P, MutableList<P>>()
for (p in e) {
d.getOrPut(next(p)) { mutableListOf() }.add(p)
}
val ne = mutableSetOf<P>()
var moved = false
for ((p, pts) in d.entries) {
if (pts.size == 1) {
ne.add(p)
if (p != pts.first()) moved = true
}
else for (pt in pts) ne.add(pt)
}
e = ne
stepConstraints()
if (part2 && !moved) return rep
}
return n
}
// part1
simulate(10, part2 = false)
val (xmin, xmax) = e.minOf {p -> p.x} to e.maxOf {p -> p.x}
val (ymin, ymax) = e.minOf {p -> p.y} to e.maxOf {p -> p.y}
println((xmax - xmin + 1) * (ymax - ymin + 1) - e.size)
// part2
e = init
while (constraints.first().second != P(0, -1)) stepConstraints()
println(simulate(Int.MAX_VALUE, part2 = true))
} | 0 | Kotlin | 0 | 0 | cf49abe24c1242e23e96719cc71ed471e77b3154 | 2,109 | adventofcode | Apache License 2.0 |
src/test/kotlin/nl/dirkgroot/adventofcode/year2022/Day20Test.kt | dirkgroot | 317,968,017 | false | {"Kotlin": 187862} | package nl.dirkgroot.adventofcode.year2022
import io.kotest.core.spec.style.StringSpec
import io.kotest.matchers.shouldBe
import nl.dirkgroot.adventofcode.util.input
import nl.dirkgroot.adventofcode.util.invokedWith
import kotlin.math.abs
private fun solution1(input: String) = parse(input, 1L).let { file ->
file.mix()
file.sum()
}
private fun solution2(input: String) = parse(input, 811589153L).let { file ->
repeat(10) { file.mix() }
file.sum()
}
private fun parse(input: String, key: Long) = Numbers(input.lineSequence().map { it.toLong() }, key)
private class Numbers(longs: Sequence<Long>, key: Long) {
private class Entry(val value: Long, var next: Entry? = null, var previous: Entry? = null) {
override fun toString() = "value: $value"
}
private val entries = longs.map { Entry(it * key) }.toList().also { list ->
list.forEachIndexed { index, entry ->
entry.previous = list[(index + list.size - 1) % list.size]
entry.next = list[(index + 1) % list.size]
}
}
fun sum(): Long {
val zeroElement = entries.first { it.value == 0L }
return generateSequence(zeroElement.next) { it.next }
.windowed(1000, 1000)
.map { it.last().value }
.take(3)
.sum()
}
fun mix() {
entries.forEach { entry ->
if (entry.value == 0L) return@forEach
if (entry.value % (entries.size - 1) == 0L) return@forEach
val after = if (entry.value > 0)
generateSequence(entry) { it.next }
.drop((entry.value % (entries.size - 1)).toInt())
.first()
else
generateSequence(entry.previous) { it.previous }
.drop(abs(entry.value % (entries.size - 1)).toInt())
.first()
val before = after.next!!
entry.previous?.next = entry.next
entry.next?.previous = entry.previous
after.next = entry
before.previous = entry
entry.next = before
entry.previous = after
}
}
}
//===============================================================================================\\
private const val YEAR = 2022
private const val DAY = 20
class Day20Test : StringSpec({
"example part 1" { ::solution1 invokedWith exampleInput shouldBe 3L }
"part 1 solution" { ::solution1 invokedWith input(YEAR, DAY) shouldBe 13289L }
"example part 2" { ::solution2 invokedWith exampleInput shouldBe 1623178306L }
"part 2 solution" { ::solution2 invokedWith input(YEAR, DAY) shouldBe 2865721299243L }
})
private val exampleInput =
"""
1
2
-3
3
-2
0
4
""".trimIndent()
| 1 | Kotlin | 1 | 1 | ffdffedc8659aa3deea3216d6a9a1fd4e02ec128 | 2,809 | adventofcode-kotlin | MIT License |
src/main/kotlin/Day10.kt | ueneid | 575,213,613 | false | null | class Day10(inputs: List<String>) {
private val commandSets = parse(inputs)
private fun parse(inputs: List<String>): List<CommandSet> {
return inputs.asSequence().map { line ->
line.split(" ").let {
CommandSet(Command.valueOf(it[0].uppercase()), it.getOrElse(1) { "0" }.toInt())
}
}.toList()
}
enum class Command() {
ADDX {
override fun getCycle() = 2
},
NOOP {
override fun getCycle() = 1
};
abstract fun getCycle(): Int
}
data class CommandSet(val command: Command, val value: Int = 0)
class CPU() {
private var register = 1
private var cycleCount = 0
fun execute(commandSets: List<CommandSet>, callbackPerCycle: (cycleCount: Int, register: Int) -> Unit) {
commandSets.forEach { commandSet ->
val (command, value) = commandSet
repeat(command.getCycle()) {
cycleCount++
callbackPerCycle(cycleCount, register)
}
register += value
}
}
}
fun solve1(): Int {
var sumSignalStrength = 0
CPU().execute(commandSets) { cycleCount: Int, register: Int ->
if ((cycleCount + 20) % 40 == 0) {
sumSignalStrength += cycleCount * register
}
}
return sumSignalStrength
}
fun solve2(): List<String> {
val output = MutableList<String>(6) { "" }
CPU().execute(commandSets) { cycleCount: Int, register: Int ->
val spriteIndex = (cycleCount - 1) % 40
output[(cycleCount - 1) / 40] += if (spriteIndex >= register - 1 && spriteIndex <= register + 1) {
"#"
} else {
"."
}
}
return output
}
}
fun main() {
val obj = Day10(Resource.resourceAsListOfString("day10/input.txt"))
println(obj.solve1())
println(obj.solve2().joinToString("\n"))
}
| 0 | Kotlin | 0 | 0 | 743c0a7adadf2d4cae13a0e873a7df16ddd1577c | 2,046 | adventcode2022 | MIT License |
src/test/kotlin/ch/ranil/aoc/aoc2022/Day02.kt | stravag | 572,872,641 | false | {"Kotlin": 234222} | package ch.ranil.aoc.aoc2022
import ch.ranil.aoc.aoc2022.Day02.Outcome.*
import ch.ranil.aoc.aoc2022.Day02.Shape.*
import ch.ranil.aoc.AbstractDay
import org.junit.jupiter.api.Test
import kotlin.test.assertEquals
object Day02 : AbstractDay() {
@Test
fun tests() {
assertEquals(15, compute1(testInput))
assertEquals(12586, compute1(puzzleInput))
assertEquals(12, compute2(testInput))
assertEquals(13193, compute2(puzzleInput))
}
private fun compute1(input: List<String>): Int {
return input
.map { it.parse() }
.sumOf { (a, b) -> b.score + play(a, b).score }
}
private fun compute2(input: List<String>): Int {
return input
.map { it.parse2() }
.sumOf { (a, o) -> determineAnswer(a, o).score + o.score }
}
private enum class Shape(val score: Int) {
ROCK(1),
PAPER(2),
SCISSOR(3);
companion object {
fun of(s: String): Shape {
return when (s) {
"A", "X" -> ROCK
"B", "Y" -> PAPER
"C", "Z" -> SCISSOR
else -> throw IllegalArgumentException(s)
}
}
}
}
private enum class Outcome(val score: Int) {
LOSE(0), DRAW(3), WIN(6);
companion object {
fun of(s: String): Outcome {
return when (s) {
"X" -> LOSE
"Y" -> DRAW
"Z" -> WIN
else -> throw IllegalArgumentException(s)
}
}
}
}
private fun String.parse(): Pair<Shape, Shape> {
val (a, b) = this.split(" ")
.map { Shape.of(it) }
return a to b
}
private fun String.parse2(): Pair<Shape, Outcome> {
val (shapeStr, outcomeStr) = this.split(" ")
return Shape.of(shapeStr) to Outcome.of(outcomeStr)
}
private fun play(a: Shape, b: Shape): Outcome {
return when {
(a == ROCK && b == SCISSOR) || (a == PAPER && b == ROCK) || (a == SCISSOR && b == PAPER) -> LOSE
a == b -> DRAW
else -> WIN
}
}
private fun determineAnswer(a: Shape, o: Outcome): Shape {
return when (o) {
DRAW -> a
LOSE -> when (a) {
ROCK -> SCISSOR
PAPER -> ROCK
SCISSOR -> PAPER
}
WIN -> when (a) {
ROCK -> PAPER
PAPER -> SCISSOR
SCISSOR -> ROCK
}
}
}
}
| 0 | Kotlin | 1 | 0 | dbd25877071cbb015f8da161afb30cf1968249a8 | 2,646 | aoc | Apache License 2.0 |
src/day03/Day03Answer1.kt | IThinkIGottaGo | 572,833,474 | false | {"Kotlin": 72162} | package day03
import readInput
/**
* Answers from [Advent of Code 2022 Day 3 | Kotlin](https://youtu.be/IPLfo4zXNjk)
*/
fun main() {
fun part1(input: List<String>): Int {
return input.map { rucksack ->
rucksack.substring(0 until rucksack.length / 2) to rucksack.substring(rucksack.length / 2)
}.flatMap { (first, second) ->
first.toSet() intersect second.toSet()
}.sumOf {
it.toScore()
}
}
fun part2(input: List<String>): Int {
return input.chunked(3)
.map { elfGroup ->
elfGroup.zipWithNext()
.map { (first, second) ->
first.toSet() intersect second.toSet()
}
}.flatMap { sharedItems ->
// index safe because we chunked by 3 and then did zipWithNext
sharedItems[0] intersect sharedItems[1]
}.sumOf {
it.toScore()
}
}
val testInput = readInput("day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("day03")
println(part1(input)) // 8123
println(part2(input)) // 2620
}
// In the test example, the priority of the item type that appears in both compartments
// of each rucksack is 16 (p), 38 (L), 42 (P), 22 (v), 20 (t), and 19 (s); the sum of these is 157.
private fun Char.toScore(): Int =
if (isUpperCase()) {
this - 'A' + 27
} else {
this - 'a' + 1
} | 0 | Kotlin | 0 | 0 | 967812138a7ee110a63e1950cae9a799166a6ba8 | 1,528 | advent-of-code-2022 | Apache License 2.0 |
src/main/java/com/barneyb/aoc/aoc2022/day13/DistressSignal.kt | barneyb | 553,291,150 | false | {"Kotlin": 184395, "Java": 104225, "HTML": 6307, "JavaScript": 5601, "Shell": 3219, "CSS": 1020} | package com.barneyb.aoc.aoc2022.day13
import com.barneyb.aoc.util.Solver
import com.barneyb.aoc.util.toSlice
import com.barneyb.util.Stack
fun main() {
Solver.benchmark(
::parse,
::partOne, // 4809
::decoderKey, // 22600
)
}
typealias Packet = List<*> // List<Int | Packet>
internal fun parse(input: String) =
input.toSlice()
.trim()
.split('\n')
.filter(CharSequence::isNotBlank)
.map(::parsePacket)
internal fun parsePacket(str: CharSequence): Packet {
val stack = Stack<MutableList<Any>>()
var n: Int? = null
for (c in str) {
when (c) {
'[' -> {
stack.push(mutableListOf())
}
']' -> {
val l = stack.pop()
if (n != null) {
l.add(n)
n = null
}
if (stack.isEmpty()) return l
else stack.peek().add(l)
}
',' -> {
if (n != null) {
stack.peek().add(n)
n = null
}
}
else -> {
if (n == null) n = 0
else n *= 10
n += c.digitToInt()
}
}
}
throw IllegalArgumentException("mismatched brackets?")
}
internal fun comparePackets(left: Packet, right: Packet): Int {
val lItr = left.iterator()
val rItr = right.iterator()
while (lItr.hasNext() && rItr.hasNext()) {
val l = lItr.next()
val r = rItr.next()
val c = if (l is Int) {
if (r is Packet) {
comparePackets(listOf(l), r)
} else { // must be Int
l - r as Int
}
} else if (l is Packet) {
if (r is Packet) {
comparePackets(l, r)
} else { // must be Int
comparePackets(l, listOf(r))
}
} else {
throw IllegalStateException("non-int, non-List found?")
}
if (c != 0) return c
}
return left.size - right.size
}
internal fun partOne(packets: List<Packet>) =
packets.asSequence()
.chunked(2)
.withIndex()
.filter { (_, ps) -> comparePackets(ps[0], ps[1]) <= 0 }
.map(IndexedValue<*>::index)
.map(Int::inc)
.sum()
internal fun decoderKey(packets: List<Packet>) =
ArrayList<Packet>(packets.size + 2).run {
val one = parsePacket("[[2]]")
val two = parsePacket("[[6]]")
addAll(packets)
add(one)
add(two)
sortWith(::comparePackets)
asSequence()
.withIndex()
.filter { (_, p) -> p === one || p === two }
.take(2)
.map(IndexedValue<*>::index)
.map(Int::inc)
.reduce(Int::times)
}
| 0 | Kotlin | 0 | 0 | 8b5956164ff0be79a27f68ef09a9e7171cc91995 | 2,883 | aoc-2022 | MIT License |
src/main/kotlin/days/Day21.kt | andilau | 429,557,457 | false | {"Kotlin": 103829} | package days
import days.Day21.Item.ItemType
import kotlin.math.max
@AdventOfCodePuzzle(
name = "RPG Simulator 20XX",
url = "https://adventofcode.com/2015/day/21",
date = Date(day = 21, year = 2015)
)
class Day21(val input: List<String>) : Puzzle {
private val items = parseItems()
private val boss = Boss.from(input)
override fun partOne(): Int = items
.equipPlayer()
.filter { it isWinner boss.copy() }
.minOf { it.cost() }
override fun partTwo(): Int = items
.equipPlayer()
.filter { it isLooser boss.copy() }
.maxOf { it.cost() }
private fun Collection<Item>.equipPlayer() = sequence {
for (weapon in filter { it.type == ItemType.WEAPON })
for (armor in filter { it.type == ItemType.ARMOR } + null)
with(filter { it.type == ItemType.RING } + null) {
for (ring1 in this.withIndex())
for (ring2 in this.drop(ring1.index + 1))
yield(Player(100, weapon, armor, ring1.value, ring2))
}
}
fun testCollection(): Int = items.equipPlayer().count()
sealed interface Playable {
var health: Int
val attack: Int
val defense: Int
infix fun attacks(other: Playable): Boolean {
other.health -= max(attack - other.defense, 1)
return other.health <= 0
}
}
data class Boss(override var health: Int, override val attack: Int, override val defense: Int) : Playable {
companion object {
fun from(lines: List<String>) = lines
.map { it.replace(Regex("""[^\d]+"""), "") }
.map(String::toInt)
.let { Boss(it[0], it[1], it[2]) }
}
}
data class Player(
override var health: Int, val weapon: Item, val armor: Item?, val ring1: Item?, val ring2: Item?
) : Playable {
private val items = arrayOf(weapon, armor, ring1, ring2)
override val attack by lazy { items.filterNotNull().sumOf { it.damage } }
override val defense by lazy { items.filterNotNull().sumOf { it.armor } }
fun cost() = items.filterNotNull().sumOf { it.cost }
infix fun isWinner(other: Boss): Boolean {
while (true) {
if (this.attacks(other)) return true
if (other.attacks(this)) return false
}
}
infix fun isLooser(boss: Boss) = !isWinner(boss)
}
data class Item(val type: ItemType, val name: String, val cost: Int, val damage: Int, val armor: Int) {
companion object {
private val REGEX = Regex("""(\w+|\w+ \+\d]?) +(\d+) +(\d+) +(\d+)""")
fun from(line: String, type: ItemType) =
REGEX.matchEntire(line)?.destructured?.let { (name, cost, damage, armor) ->
Item(type, name, cost.toInt(), damage.toInt(), armor.toInt())
}
}
enum class ItemType { WEAPON, ARMOR, RING }
}
private fun parseItems(): List<Item> {
var type: ItemType = ItemType.WEAPON
return """
Weapons: Cost Damage Armor
Dagger 8 4 0
Shortsword 10 5 0
Warhammer 25 6 0
Longsword 40 7 0
Greataxe 74 8 0
Armor: Cost Damage Armor
Leather 13 0 1
Chainmail 31 0 2
Splintmail 53 0 3
Bandedmail 75 0 4
Platemail 102 0 5
Rings: Cost Damage Armor
Damage +1 25 1 0
Damage +2 50 2 0
Damage +3 100 3 0
Defense +1 20 0 1
Defense +2 40 0 2
Defense +3 80 0 3
"""
.trimIndent().lines()
.filter { it.isNotEmpty() }
.mapNotNull { line ->
if (line.any { it == ':' }) {
val section = line.substringBefore(':')
type = when (section) {
"Weapons" -> ItemType.WEAPON
"Armor" -> ItemType.ARMOR
"Rings" -> ItemType.RING
else -> error("Unknown section: $section")
}
null
}
else Item.from(line, type)
}
}
} | 0 | Kotlin | 0 | 0 | 55932fb63d6a13a1aa8c8df127593d38b760a34c | 4,593 | advent-of-code-2015 | Creative Commons Zero v1.0 Universal |
src/Day01.kt | paulgrugnale | 573,105,050 | false | {"Kotlin": 6378} | fun main() {
fun part1(input: List<String>): Int {
var answer = 0
var runningTotal = 0
input.forEach {
if (it.isNotEmpty()) {
runningTotal += it.toInt()
} else {
answer = answer.coerceAtLeast(runningTotal)
runningTotal = 0
}
}
return answer
}
fun part2(input: List<String>): Int {
val delimiters = input.mapIndexedNotNull {
index, s -> index.takeIf { s.isEmpty() }
}
val groups = delimiters.mapIndexed {
index, d -> input.subList(if (index == 0) 0 else delimiters[index-1] +1, d)
}
return groups.map {
it.fold(0) { sum, str -> sum + str.toInt() }
}.sortedDescending().take(3).sum()
}
// test if implementation meets criteria from the description, like:
// val testInput = readInput("Day01_test")
// check(part1(testInput) == 1)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | e62edc817a8b75e401d6c8a0a66243d009c31fbd | 1,060 | advent2022 | Apache License 2.0 |
src/Day09.kt | GreyWolf2020 | 573,580,087 | false | {"Kotlin": 32400} | import java.lang.Math.abs
fun main() {
fun part1(headKnotMotionsData: List<String>): Int {
val tail = Knot("tail")
val head = Knot("head")
tail `join to follow` head
headKnotMotionsData
.map { it.split(" ") }
.forEach {
val direction = it.first()
val magnitude = it.last().toInt()
head
.appendMove(direction, magnitude)
head.execute()
}
tail `unjoin so as not to follow` head
return tail
.positions
.distinct()
.also {
it.map(::println)
}
.size
}
fun part2(headKnotMotionsData: List<String>): Int {
val head = Knot("head")
val tailOne = Knot("tailOne")
val tailTwo = Knot("tailTwo")
val tailThree = Knot("tailThree")
val tailFour = Knot("tailFour")
val tailFive = Knot("tailFive")
val tailSix = Knot("tailSix")
val tailSeven = Knot("tailSeven")
val tailEight = Knot("tailEight")
val tailNine = Knot("tailNine")
tailOne `join to follow` head
tailTwo `join to follow` tailOne
tailThree `join to follow` tailTwo
tailFour `join to follow` tailThree
tailFive `join to follow` tailFour
tailSix `join to follow` tailFive
tailSeven `join to follow` tailSix
tailEight `join to follow` tailSeven
tailNine `join to follow` tailEight
headKnotMotionsData
.map { it.split(" ") }
.forEach {
val direction = it.first()
val magnitude = it.last().toInt()
head
.appendMove(direction, magnitude)
}
head.execute()
tailOne `unjoin so as not to follow` head
tailTwo `unjoin so as not to follow` tailOne
tailThree `unjoin so as not to follow` tailTwo
tailFour `unjoin so as not to follow` tailThree
tailFive `unjoin so as not to follow` tailFour
tailSix `unjoin so as not to follow` tailFive
tailSeven `unjoin so as not to follow` tailSix
tailEight `unjoin so as not to follow` tailSeven
tailNine `unjoin so as not to follow` tailEight
return tailNine
.positions
.distinct()
.also {
it.map(::println)
}
.size
}
// test if implementation meets criteria from the description, like:
/* val testInput = readInput("Day09_test")
check(part1(testInput) == 13)
// testInputTwo is the larger example on the AOC website day 09 challenge of 2022
val testInputTwo = readInput("Day09_test_two")
check(part2(testInputTwo) == 36)
check(part2(testInput) == 1)
val input = readInput("Day09")
println(part1(input))
println(part2(input))*/
}
typealias Command = () -> Unit
data class Position(val x: Int, val y: Int)
class Knot(
val name: String,
var _xPosition: Int = 0,
var _yPosition: Int = 0
) {
private val orders = mutableListOf<Command>()
private val _positions = mutableListOf<Position>()
val positions
get() = _positions.toList()
val followers: HashMap<String, Knot> = HashMap()
val moveGenerator = fun(
knot: Knot,
direction: String,
qnty: Int
): Command {
return fun() {
when (direction) {
"R" -> repeat(qnty) { knot.toRight() }
"L" -> repeat(qnty) { knot.toLeft() }
"U" -> repeat(qnty) { knot.toUp() }
"D" -> repeat(qnty) { knot.toDown() }
else -> {}
}
}
}
init {
appendOrigin()
}
fun xPosition(xPosition: Int) { _xPosition = xPosition }
fun yPosition(yPosition: Int) { _yPosition = yPosition }
fun appendMove(direction: String, qnty: Int) = apply {
orders.add(moveGenerator(this, direction, qnty))
}
fun appendOrigin() {
_positions.add(Position(0, 0))
}
private fun toLeft() {
_xPosition--
moved()
}
private fun toRight() {
_xPosition++
moved()
}
private fun toDown() {
_yPosition--
moved()
}
private fun toUp() {
_yPosition++
moved()
}
fun moved() {
_positions.add(Position(_xPosition, _yPosition))
for ((_, follower) in followers) {
follower.follow(this)
}
}
fun execute() {
while (!orders.isEmpty()) {
val order = orders.removeAt(0)
order.invoke()
println("$name x -> $_xPosition y -> $_yPosition")
}
}
fun follow(leader: Knot) {
val deltaX = abs(leader._xPosition - this._xPosition)
val deltaY = abs(leader._yPosition - this._yPosition)
val xDirection = if (leader._xPosition - _xPosition > 0) "R" else "L"
val yDirection = if (leader._yPosition - _yPosition > 0) "U" else "D"
when {
deltaX > 1 && deltaY > 0 || deltaY > 1 && deltaX > 0 -> {
moveDiagonally(xDirection, yDirection)
moved()
}
deltaX > 1 -> appendMove(xDirection, deltaX - 1).execute()
deltaY > 1 -> appendMove(yDirection, deltaY - 1).execute()
}
}
fun moveDiagonally(xDirection: String, yDirection: String) {
when {
xDirection == "L" -> _xPosition--
xDirection == "R" -> _xPosition++
}
when {
yDirection == "U" -> _yPosition++
yDirection == "D" -> _yPosition--
}
/*
appendMove(xDirection, 1)
.appendMove(yDirection, 1)
.execute()*/
}
}
infix fun Knot.`join to follow`(head: Knot) {
head.followers.put(this.name, this)
println("${head.name} has a new follower $name")
}
infix fun Knot.`unjoin so as not to follow`(head: Knot) {
head.followers.remove(name)
println("${head.name} has been unfollowed by $name")
}
| 0 | Kotlin | 0 | 0 | 498da8861d88f588bfef0831c26c458467564c59 | 6,132 | aoc-2022-in-kotlin | Apache License 2.0 |
2020/src/main/kotlin/org/suggs/adventofcode/Day07HandyHaversacks.kt | suggitpe | 321,028,552 | false | {"Kotlin": 156836} | package org.suggs.adventofcode
class Day07HandyHaversacks {
companion object {
data class BagRule(val parent: String, val number: Int, val child: String)
fun buildRulesFromRulesSet(rules: List<String>): List<BagRule> {
fun createRuleFrom(parent: String, number: Int, contains: String): BagRule {
return BagRule(parent, number, contains)
}
fun cleanBagRules(rules: List<String>): List<String> {
return rules.filterNot { it.contains("no other bags") }.map { it.replace("""bags|bag|\.""".toRegex(), "") }
}
return cleanBagRules(rules).map { bagRule ->
val (left, right) = bagRule.split(" contain ")
right.split(", ").map { bags ->
val (num, bag) = bags.split(" ", limit = 2)
createRuleFrom(left.trim(), num.toInt(), bag.trim())
}
}.flatten()
}
fun calculateDiscreteParentBagsFrom(rules: List<String>, bagName: String): Int {
fun buildMapOfRulesKeyedByChild(rules: List<String>) = buildRulesFromRulesSet(rules).groupBy { it.child }
fun calculateDiscreteParentBagsFrom(rulesMap: Map<String, List<BagRule>>, bagName: String, acc: List<String>): List<String> {
return if (!rulesMap.containsKey(bagName))
acc
else
rulesMap.getValue(bagName).map {
calculateDiscreteParentBagsFrom(rulesMap, it.parent, acc + it.parent)
}.flatten()
}
return calculateDiscreteParentBagsFrom(buildMapOfRulesKeyedByChild(rules), bagName, listOf()).toSet().size
}
fun calculateTheTotalContainedBagsFrom(rules: List<String>, bagName: String): Int {
fun buildMapOfRulesKeyedByParent(rules: List<String>) = buildRulesFromRulesSet(rules).groupBy { it.parent }
fun calculateTheTotalContainedBagsFrom(rulesMap: Map<String, List<BagRule>>, bagName: String, number: Int): Int {
return if (!rulesMap.containsKey(bagName)) {
number
} else
number + rulesMap.getValue(bagName).map {
calculateTheTotalContainedBagsFrom(rulesMap, it.child, it.number) * number
}.sum()
}
// the -1 at the end is to remove itself from the count
return calculateTheTotalContainedBagsFrom(buildMapOfRulesKeyedByParent(rules), bagName, 1) - 1
}
}
}
| 0 | Kotlin | 0 | 0 | 9485010cc0ca6e9dff447006d3414cf1709e279e | 2,593 | advent-of-code | Apache License 2.0 |
codeforces/vk2022/qual/d1.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package codeforces.vk2022.qual
const val VALUES = "6789TJQKA"
const val SUITS = "CDSH"
val INIT = VALUES.indexOf('9')
fun main() {
val totalCards = VALUES.length * SUITS.length
val allCardsList = (0 until totalCards).toList()
val aliceList = readStrings().map { parseCard(it) }
val bobList = allCardsList - aliceList.toSet()
val moveBit = 1L shl totalCards
val allMask = moveBit - 1
val aliceMask = aliceList.sumOf { 1L shl it }
val bobMask = bobList.sumOf { 1L shl it }
val memo = mutableMapOf<Long, Boolean>()
val initial = allMask
fun solve(position: Long): Boolean = memo.getOrPut(position) {
val move = (position shr totalCards) > 0
val otherMove = if (move) 0 else moveBit
val present = position and allMask
val me = present and (if (move) bobMask else aliceMask)
var canMove = false
for (suit in SUITS.indices) {
for (dir in -1..1 step 2) {
var canPlayValue = INIT
while (true) {
val isPresent = present.hasBit (suit * VALUES.length + canPlayValue)
if (isPresent) break
canPlayValue += dir
if (canPlayValue == VALUES.length) canPlayValue = -1
if (canPlayValue == -1) break
}
if (canPlayValue == -1) continue
if (canPlayValue == INIT && dir < 0) continue
val canPlay = suit * VALUES.length + canPlayValue
val canPlayBit = 1L shl canPlay
if ((me and canPlayBit) == 0L) continue
if (me == canPlayBit) return@getOrPut move
canMove = true
if (solve(otherMove or present xor canPlayBit) == move) return@getOrPut move
}
}
if (!canMove) solve(otherMove or present) else !move
}
println(if (solve(initial)) "Bob" else "Alice")
}
fun parseCard(card: String) = SUITS.indexOf(card[1]) * VALUES.length + VALUES.indexOf(card[0])
private fun Long.bit(index: Int) = shr(index) and 1
private fun Long.hasBit(index: Int) = bit(index) != 0L
private fun readStrings() = readln().split(" ")
| 0 | Java | 1 | 9 | 30953122834fcaee817fe21fb108a374946f8c7c | 1,886 | competitions | The Unlicense |
solutions/aockt/y2021/Y2021D21.kt | Jadarma | 624,153,848 | false | {"Kotlin": 435090} | package aockt.y2021
import io.github.jadarma.aockt.core.Solution
object Y2021D21 : Solution {
/**
* Simulates a practice round of the Dirac Dice game with a 100-sided deterministic die and a winning score of 1000.
* @return The number of times the dice was rolled, and the scores of each player.
*/
private fun playPracticeRound(
playerOneStartSquare: Int = 0,
playerTwoStartSquare: Int = 0,
): Triple<Int, Int, Int> {
require(playerOneStartSquare in 1..10) { "Invalid starting position for player 1." }
require(playerOneStartSquare in 1..10) { "Invalid starting position for player 2." }
val position = mutableListOf(playerOneStartSquare - 1, playerTwoStartSquare - 1)
val score = mutableListOf(0, 0)
var player = 0
var rolls = 0
fun nextRoll() = rolls++ % 100 + 1
fun gameWon() = score.any { it >= 1000 }
fun play(player: Int) {
val increment = List(3) { nextRoll() }.sum()
val current = position[player]
position[player] = (current + increment) % 10
score[player] += position[player] + 1
}
while (!gameWon()) {
play(player)
player = (player + 1) % 2
}
return Triple(rolls, score[0], score[1])
}
/**
* Simulates all the parallel universes with a three sided quantum die and returns the win rate of the players.
* @return In how many universes each player won.
*/
private fun playQuantumRound(
playerOneStartSquare: Int = 0,
playerTwoStartSquare: Int = 0,
): Pair<Long, Long> {
require(playerOneStartSquare in 1..10) { "Invalid starting position for player 1." }
require(playerOneStartSquare in 1..10) { "Invalid starting position for player 2." }
val possibleRolls = with(listOf(1, 2, 3)) { flatMap { a -> flatMap { b -> map { c -> listOf(a, b, c) } } } }
.groupingBy { it.sum() }
.eachCount()
.mapValues { it.value.toLong() }
fun play(position: List<Int>, score: List<Int>, player: Int): Pair<Long, Long> =
possibleRolls.map { (roll, count) ->
val nextPosition = position.toMutableList().apply { set(player, (position[player] + roll) % 10) }
val nextScore = score.toMutableList().apply { set(player, (score[player] + nextPosition[player] + 1)) }
when (nextScore.indexOfFirst { it >= 21 }) {
0 -> count to 0L
1 -> 0L to count
else -> play(nextPosition, nextScore, (player + 1) % 2).run { first * count to second * count }
}
}.reduce { acc, wins -> acc.first + wins.first to acc.second + wins.second }
return play(
position = listOf(playerOneStartSquare - 1, playerTwoStartSquare - 1),
score = listOf(0, 0),
player = 0,
)
}
/** Parse the [input] and return the starting positions of player one and two respectively. */
private fun parseInput(input: String): Pair<Int, Int> = runCatching {
val (line1, line2) = input.lines()
val lineRegex = Regex("""^Player (\d+) starting position: (\d+)$""")
val (p1, pos1) = lineRegex.matchEntire(line1)!!.destructured
val (p2, pos2) = lineRegex.matchEntire(line2)!!.destructured
require(p1 == "1" && p2 == "2")
pos1.toInt() to pos2.toInt()
}.getOrElse { throw IllegalArgumentException("Invalid input.", it) }
override fun partOne(input: String): Int {
val (p1, p2) = parseInput(input)
val (rolls, scoreP1, scoreP2) = playPracticeRound(p1, p2)
return rolls * minOf(scoreP1, scoreP2)
}
override fun partTwo(input: String): Long {
val (p1, p2) = parseInput(input)
val (universesWhereP1Won, universesWhereP2Won) = playQuantumRound(p1, p2)
return maxOf(universesWhereP1Won, universesWhereP2Won)
}
}
| 0 | Kotlin | 0 | 3 | 19773317d665dcb29c84e44fa1b35a6f6122a5fa | 4,009 | advent-of-code-kotlin-solutions | The Unlicense |
src/Day04.kt | zhtk | 579,137,192 | false | {"Kotlin": 9893} | data class Assignment(val start: Int, val end: Int)
fun main() {
val input = readInput("Day04").map {
it.split(',').map {
val range = it.split('-').map { it.toInt() }
Assignment(range[0], range[1])
}
}
input.count { assignmentsContained(it[0], it[1]) }.println()
input.count { isOverlap(it[0], it[1]) }.println()
}
fun assignmentIncludedIn(assignment: Assignment, includedIn: Assignment): Boolean =
includedIn.start <= assignment.start && assignment.end <= includedIn.end
fun assignmentsContained(assignment1: Assignment, assignment2: Assignment): Boolean =
assignmentIncludedIn(assignment1, assignment2) ||
assignmentIncludedIn(assignment2, assignment1)
fun isOverlap(assignment1: Assignment, assignment2: Assignment): Boolean =
assignment1.start <= assignment2.start && assignment2.start <= assignment1.end ||
assignment1.start <= assignment2.end && assignment2.end <= assignment1.end ||
assignmentsContained(assignment1, assignment2)
| 0 | Kotlin | 0 | 0 | bb498e93f9c1dd2cdd5699faa2736c2b359cc9f1 | 1,045 | aoc2022 | Apache License 2.0 |
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[395]至少有 K 个重复字符的最长子串.kt | maoqitian | 175,940,000 | false | {"Kotlin": 354268, "Java": 297740, "C++": 634} | //给你一个字符串 s 和一个整数 k ,请你找出 s 中的最长子串, 要求该子串中的每一字符出现次数都不少于 k 。返回这一子串的长度。
//
//
//
// 示例 1:
//
//
//输入:s = "aaabb", k = 3
//输出:3
//解释:最长子串为 "aaa" ,其中 'a' 重复了 3 次。
//
//
// 示例 2:
//
//
//输入:s = "ababbc", k = 2
//输出:5
//解释:最长子串为 "ababb" ,其中 'a' 重复了 2 次, 'b' 重复了 3 次。
//
//
//
// 提示:
//
//
// 1 <= s.length <= 104
// s 仅由小写英文字母组成
// 1 <= k <= 105
//
// Related Topics 递归 分治算法 Sliding Window
// 👍 380 👎 0
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
fun longestSubstring(s: String, k: Int): Int {
val len: Int = s.length
var ans = 0
if (len < k) return 0
val cnt = IntArray(26)
for (i in 0 until len) {
cnt[s[i] - 'a']++
}
for (i in 0..25) {
if (cnt[i] in 1 until k) {
for (t in s.split((i + 97).toChar())) {
ans = Math.max(ans, longestSubstring(t!!, k))
}
return ans
}
}
return len
}
}
//leetcode submit region end(Prohibit modification and deletion)
| 0 | Kotlin | 0 | 1 | 8a85996352a88bb9a8a6a2712dce3eac2e1c3463 | 1,348 | MyLeetCode | Apache License 2.0 |
src/Day22.kt | abeltay | 572,984,420 | false | {"Kotlin": 91982, "Shell": 191} | fun main() {
val right = 0
val down = 1
val left = 2
val up = 3
fun parseDirections(input: String): MutableList<String> {
val output = mutableListOf<String>()
var buffer = ""
for (it in input) {
if (it.isDigit()) {
buffer += it
} else {
output.add(buffer)
buffer = ""
output.add(it.toString())
}
}
return output
}
data class Facing(
val x: Int,
val y: Int,
val direction: Int
)
fun moveStraight(map: List<List<Char>>, facing: Facing, steps: Int): Facing {
if (steps == 0) {
return facing
}
var x = facing.x
var y = facing.y
when (facing.direction) {
right -> {
x++
if (x >= map[y].size || map[y][x] == ' ') {
x = map[y].indexOfFirst { it != ' ' }
}
}
left -> {
x--
if (x < 0 || map[y][x] == ' ') {
x = map[y].indexOfLast { it != ' ' }
}
}
down -> {
y++
if (y >= map.size || map[y].size <= x || map[y][x] == ' ') {
for (col in map.indices) {
if (map[col].size > x && map[col][x] != ' ') {
y = col
break
}
}
}
}
else -> {
y--
if (y < 0 || map[y].size <= x || map[y][x] == ' ') {
for (col in map.indices.reversed()) {
if (map[col].size > x && map[col][x] != ' ') {
y = col
break
}
}
}
}
}
if (map[y][x] == '#') {
return facing
}
val newFacing = Facing(x = x, y = y, direction = facing.direction)
return moveStraight(map, newFacing, steps - 1)
}
fun solve(map: List<List<Char>>, directions: MutableList<String>, facing: Facing): Facing {
if (directions.isEmpty()) {
return facing
}
val direction = directions.removeFirst()
val steps = direction.toIntOrNull()
if (steps != null) {
val newFacing = moveStraight(map, facing, steps)
return solve(map, directions, newFacing)
} else {
var newDirection: Int
if (direction == "L") {
newDirection = facing.direction - 1
if (newDirection < 0) newDirection += 4
} else {
newDirection = (facing.direction + 1) % 4
}
return solve(
map, directions, Facing(
x = facing.x,
y = facing.y,
direction = newDirection
)
)
}
}
fun part1(input: List<String>): Int {
val part2 = input.indexOf("")
val map = input.slice(0 until part2).map { it.toCharArray().toList() }
val facing = solve(map, parseDirections(input.last()), Facing(x = map[0].indexOf('.'), y = 0, direction = 0))
return (1000 * (facing.y + 1)) + (4 * (facing.x + 1)) + facing.direction
}
fun part2(input: List<String>): Int {
val part2 = input.indexOf("")
val map = input.slice(0 until part2).map { it.toCharArray().toList() }
val facing = solve(map, parseDirections(input.last()), Facing(x = map[0].indexOf('.'), y = 0, direction = 0))
return (1000 * (facing.y + 1)) + (4 * (facing.x + 1)) + facing.direction
}
val testInput = readInput("Day22_test")
check(part1(testInput) == 6032)
// check(part2(testInput) == 5031)
val input = readInput("Day22")
println(part1(input))
// println(part2(input))
}
| 0 | Kotlin | 0 | 0 | a51bda36eaef85a8faa305a0441efaa745f6f399 | 4,036 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/dev/bogwalk/batch0/Problem6.kt | bog-walk | 381,459,475 | false | null | package dev.bogwalk.batch0
import dev.bogwalk.util.maths.gaussSum
/**
* Problem 6: Sum Square Difference
*
* https://projecteuler.net/problem=6
*
* Goal: Find the absolute difference between the sum of the squares & the square of the sum
* of the first N natural numbers.
*
* Constraints: 1 <= N <= 1e4
*
* e.g.: N = 3 -> {1,2,3}
* sum of squares = {1,4,9} = 14
* square of sum = 6^2 = 36
* diff = |14 - 36| = 22
*/
class SumSquareDifference {
/**
* SPEED (WORST) 7.55ms for N = 1e4
*/
fun sumSquareDiffBruteOG(n: Int): Long {
val range = 1L..n
val sumOfRange = range.sum()
val sumOfSquares = range.sumOf { it * it }
return sumOfRange * sumOfRange - sumOfSquares
}
/**
* SPEED (BETTER) 5.15ms for N = 1e4
*/
fun sumSquareDiffBrute(n: Int): Long {
val range = 2L..n
val (sumOfRange, sumOfSquares) = range.fold(1L to 1L) { acc, num ->
acc.first + num to acc.second + num * num
}
return sumOfRange * sumOfRange - sumOfSquares
}
/**
* The sum of the 1st [n] natural numbers (triangular numbers) is found using the gauss
* summation method.
*
* The sum of the sequence's squares is based on the assumption that:
*
* f(n) = an^3 + bn^2 + cn + d, with f(0) = 0, f(1) = 1, f(2) = 5, f(3) = 14
*
* The formula (square pyramidal numbers) can then be solved as:
*
* f(n) = (2n^3 + 3n^2 + n)/6
*
* f(n) = (n(2n + 1)(n + 1))/6
*
* SPEED (BEST) 2.9e+04ns for N = 1e4
*/
fun sumSquareDiff(n: Int): Long {
val sumOfRange = n.gaussSum()
val sumOfSquares: Double = n / 6.0 * (2 * n + 1) * (n + 1)
return sumOfRange * sumOfRange - sumOfSquares.toLong()
}
} | 0 | Kotlin | 0 | 0 | 62b33367e3d1e15f7ea872d151c3512f8c606ce7 | 1,820 | project-euler-kotlin | MIT License |
src/day03/Day03.kt | spyroid | 433,555,350 | false | null | package day03
import kotlinx.coroutines.async
import kotlinx.coroutines.runBlocking
import readInput
enum class Type(val order: Int) {
OXY(1), CO2(-1)
}
fun main() = runBlocking {
fun part1(seq: List<String>): Int {
val counts = IntArray(seq.first().length) {
idx -> if (seq.sumOf { (if (it[idx].digitToInt() == 0) -1L else 1L) } > 0) 1 else 0
}
val gamma = counts.fold(0) { acc, el -> (acc shl 1) + el }
val epsilon = counts.fold(0) { acc, el -> (acc shl 1) + el xor 1 }
return gamma * epsilon
}
suspend fun part2(seq: List<String>): Int {
fun findMeasure(seq: List<String>, type: Type, idx: Int = 0): Int {
val group = seq.groupBy { it[idx].digitToInt() }
.entries
.sortedWith(compareBy({ it.value.size * -type.order }, { it.key * -type.order }))
.first().value
if (group.size == 1) return group.first().toInt(2)
return findMeasure(group, type, idx + 1)
}
val oxy = async { findMeasure(seq, Type.OXY) }
val co2 = async { findMeasure(seq, Type.CO2) }
return oxy.await() * co2.await()
}
val testSeq = readInput("day03/test")
val inputSeq = readInput("day03/input")
val res1 = part1(testSeq)
check(res1 == 198) { "Expected 198 but got $res1" }
println("Part1: ${part1(inputSeq)}")
val res2 = part2(testSeq)
check(res2 == 230) { "Expected 900 but got $res2" }
println("Part2: ${part2(inputSeq)}")
}
| 0 | Kotlin | 0 | 0 | 939c77c47e6337138a277b5e6e883a7a3a92f5c7 | 1,542 | Advent-of-Code-2021 | Apache License 2.0 |
src/Day03.kt | gojoel | 573,543,233 | false | {"Kotlin": 28426} | fun main() {
val input = readInput("03")
// val input = readInput("03_test")
val types = ('a'..'z').toMutableList()
types.addAll(('A'..'Z'))
fun getPriority(char: Char?) : Int {
return char?.let {
types.indexOf(it) + 1 // offset index from 0
} ?: run {
0
}
}
fun getCommonType(list: List<List<String>>) : Char? {
val rs1 = list[0]
val rucksacks = list.subList(1, list.size)
for (item in rs1) {
var contains = true
for (rucksack in rucksacks) {
if (!rucksack.contains(item)) {
contains = false
break
}
}
if (contains) {
return item.single()
}
}
return null
}
fun part1(input: List<String>) : Int {
return input.sumOf { line ->
val items = line.split("")
.filter { it.isNotBlank() }
val c = getCommonType(listOf(items.take(items.size / 2), items.takeLast(items.size / 2)))
getPriority(c)
}
}
fun part2(input: List<String>) : Int {
var fromIndex = 0
var toIndex = 3
var sum = 0
while (toIndex <= input.size) {
val subList = input.subList(fromIndex, toIndex)
val rucksacks = subList.map { line ->
line.split("")
.filter { it.isNotBlank() }
}.toList()
val c = getCommonType(rucksacks)
sum += getPriority(c)
if (toIndex == input.size) {
break
}
fromIndex = toIndex
toIndex += if (toIndex + 3 <= input.size) {
3
} else {
input.size - toIndex
}
}
return sum
}
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 0690030de456dad6dcfdcd9d6d2bd9300cc23d4a | 1,935 | aoc-kotlin-22 | Apache License 2.0 |
src/Day06.kt | stcastle | 573,145,217 | false | {"Kotlin": 24899} | import java.util.*
class SizedQueue<T>(val maxSize: Int) : LinkedList<T>() {
override fun add(element: T): Boolean {
if (super.size >= maxSize) {
super.remove()
}
return super.add(element)
}
}
fun <T> SizedQueue<T>.allDifferent(): Boolean {
// For this use case, return false if size is not max.
if (this.size < this.maxSize) {
return false
}
val uniqueElements: MutableSet<T> = mutableSetOf()
for (i in 0 until this.size) {
uniqueElements.add(this.elementAt(i))
}
return this.size == uniqueElements.size
}
fun solve(input: List<String>, maxSize: Int): Int {
val line = input.single()
val queue = SizedQueue<Char>(maxSize)
line.forEachIndexed { index, c ->
queue.add(c)
if (queue.allDifferent()) {
return index + 1
}
}
throw Exception("didn't find 4 all different.")
}
fun main() {
fun part1(input: List<String>) = solve(input, maxSize = 4)
fun part2(input: List<String>) = solve(input, maxSize = 14)
val day = "06"
val testInput = readInput("Day${day}_test")
println("Part 1 test = ${part1(testInput)}")
val input = readInput("Day${day}")
println("part1 = ${part1(input)}")
println("Part 2 test = ${part2(testInput)}")
println("part2 = ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 746809a72ea9262c6347f7bc8942924f179438d5 | 1,256 | aoc2022 | Apache License 2.0 |
src/Day04.kt | tsdenouden | 572,703,357 | false | {"Kotlin": 8295} | fun main() {
fun List<Int>.swap(index1: Int, index2: Int): MutableList<Int> {
val copy = this.toMutableList()
val tmp = copy[index1]
copy[index1] = copy[index2]
copy[index2] = tmp
return copy
}
fun part1(input: List<String>): Int {
var contains = 0
input.forEach { line ->
val num = line
.trim()
.split(',', '-')
.map { it.toInt() }
val acdb = num
.swap(1,2)
.swap(2,3)
val cabd = num
.swap(0,2)
.swap(1,2)
if (num.sorted() == acdb || num.sorted() == cabd) contains++
}
return contains
}
fun part2(input: List<String>): Int {
var overlaps = 0
input.forEach { line ->
val num = line
.trim()
.split(',', '-')
.map { it.toInt() }
if (kotlin.math.min(num[3], num[1]) - kotlin.math.max(num[0], num[2]) >= 0) overlaps++
}
return overlaps
}
// 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 | 68982ebffc116f3b49a622d81e725c8ad2356fed | 1,375 | aoc-2022-kotlin | Apache License 2.0 |
src/main/java/com/barneyb/aoc/aoc2020/day01/ReportRepair.kt | barneyb | 553,291,150 | false | {"Kotlin": 184395, "Java": 104225, "HTML": 6307, "JavaScript": 5601, "Shell": 3219, "CSS": 1020} | package com.barneyb.aoc.aoc2020.day01
import com.barneyb.aoc.util.Solver
import com.barneyb.aoc.util.toLong
fun main() {
Solver.benchmark(
::parse,
::productOfTwo,
::productOfThree,
)
}
internal fun parse(input: String) =
input.trim()
.lines()
.map(CharSequence::toLong)
.sorted()
internal fun productOfTwo(sortedExpenses: List<Long>) =
complement(sortedExpenses, 2020).let { n ->
n!! * (2020 - n)
}
private fun complement(sortedExpenses: List<Long>, sum: Long) =
sortedExpenses.find { n ->
n < sum && sortedExpenses.binarySearch(sum - n) > 0
}
internal fun productOfThree(sortedExpenses: List<Long>) =
sortedExpenses.firstNotNullOfOrNull { a ->
complement(sortedExpenses, 2020 - a)?.let { b ->
Pair(a, b)
}
}.let { pair ->
pair!!.first * pair.second * (2020 - pair.first - pair.second)
}
| 0 | Kotlin | 0 | 0 | 8b5956164ff0be79a27f68ef09a9e7171cc91995 | 935 | aoc-2022 | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.