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/day25/Day25.kt
andreas-eberle
573,039,929
false
{"Kotlin": 90908}
package day25 import readInput import kotlin.math.pow import kotlin.math.roundToLong const val day = "25" fun Int.pow(p: Int): Long = this.toDouble().pow(p.toDouble()).roundToLong() fun String.snafuToLong(): Long { return reversed() .mapIndexed { index, c -> val digit = when (c) { '=' -> -2 '-' -> -1 else -> c.digitToInt() } digit * 5.pow(index) }.sum() } fun Long.toSnafu(): String { var value = this return buildString { while (value > 0) { val remainder = (value % 5).toInt() when (remainder) { 3 -> append('=') 4 -> append('-') else -> append(remainder) } value = value / 5 + if (remainder >= 3) 1 else 0 } }.reversed() } fun main() { fun calculatePart1Score(input: List<String>): String { val numbers = input.map { it.snafuToLong() } val snafuNumbers = numbers.map { it.toSnafu() } return numbers.sum().toSnafu() } fun calculatePart2Score(input: List<String>): Int { return 0 } // 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) println("Part1 test points: $part1TestPoints") check(part1TestPoints == "2=-1=0") val part1points = calculatePart1Score(input) println("Part1 points: $part1points") val part2TestPoints = calculatePart2Score(testInput) println("Part2 test points: $part2TestPoints") check(part2TestPoints == 1707) val part2points = calculatePart2Score(input) println("Part2 points: $part2points") }
0
Kotlin
0
0
e42802d7721ad25d60c4f73d438b5b0d0176f120
1,834
advent-of-code-22-kotlin
Apache License 2.0
src/day02/Day02.kt
TheJosean
573,113,380
false
{"Kotlin": 20611}
package day02 import readInput fun main() { fun calculateScore(round: Pair<Int, Int>) = when { round.second - 1 == round.first || round.second + 1 < round.first -> round.second + 6 + 1 round.first == round.second -> round.second + 3 + 1 else -> round.second + 1 } fun part1(input: List<String>) = input.map { val split = it.split(" ") Pair( when (split[0]) {"A" -> 0; "B" -> 1; else -> 2}, when (split[1]) {"X" -> 0; "Y" -> 1; else -> 2} ) }.sumOf { calculateScore(it) } fun part2(input: List<String>) = input.map { val split = it.split(" ") val first = when (split[0]) {"A" -> 0; "B" -> 1; else -> 2} val second = when (split[1]) {"X" -> (first + 2) % 3; "Z" -> (first + 1) % 3; else -> first} Pair(first, second) }.sumOf { calculateScore(it) } // test if implementation meets criteria from the description, like: val testInput = readInput("/day02/Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("/day02/Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
798d5e9b1ce446ba3bac86f70b7888335e1a242b
1,193
advent-of-code
Apache License 2.0
src/Day05.kt
jwklomp
572,195,432
false
{"Kotlin": 65103}
import java.util.Stack typealias CargoStack = List<Stack<String>> fun main() { fun elementsToStack(elements: List<String>): Stack<String> { val stack = Stack<String>() stack.addAll(elements) return stack } fun makeElements(initialStackList: List<String>): MutableList<MutableList<String>> { //val indexPositions = listOf(1, 5, 9) val indexPositions = listOf(1, 5, 9, 13, 17, 21, 25, 29, 33) val reversed = initialStackList.reversed() val stackElements = indexPositions .map { i: Int -> reversed.map { line: String -> if (line.length >= i) line.substring(i, i + 1) else null } .filterNot { it.isNullOrBlank() } } return stackElements as MutableList<MutableList<String>> } fun makeInitialStacks(initialStackList: List<String>): CargoStack { val stackElements = makeElements(initialStackList) return stackElements.map { elementsToStack(it)} } fun modifyStacks(stacks: CargoStack, move: List<String>) { val amount = move[1].toInt() val fromIndex = move[3].toInt() - 1 val toIndex = move[5].toInt() - 1 repeat(amount) { val element = stacks[fromIndex].pop(); stacks[toIndex].push(element) } } fun modifyLists(lists: MutableList<MutableList<String>>, move: List<String>) { val amount = move[1].toInt() val fromIndex = move[3].toInt() - 1 val toIndex = move[5].toInt() - 1 val elementsToMove = lists[fromIndex].takeLast(amount) lists[toIndex].addAll(elementsToMove) val old = lists[fromIndex].dropLast(amount) lists[fromIndex] = old.toMutableList() } fun part1(stacksInput: List<String>, movesInput: List<String>): String { val stacks = makeInitialStacks(stacksInput) val moves = movesInput.map { it.split(" ") } moves.forEach { modifyStacks(stacks, it) } val answer = stacks.map { it.peek() } return answer.joinToString(separator = "") } fun part2(stacksInput: List<String>, movesInput: List<String>): String { val cargoLists = makeElements(stacksInput) val moves = movesInput.map { it.split(" ") } moves.forEach { modifyLists(cargoLists, it) } val answer = cargoLists.map { it.last()} return answer.joinToString(separator = "") } val testStacks = readInput("Day05_test_stacks") val testMoves = readInput("Day05_test_moves") //println(part1(testStacks, testMoves)) //println(part2(testStacks, testMoves)) val stacks = readInput("Day05_stacks") val moves = readInput("Day05_moves") //println(part1(stacks, moves)) println(part2(stacks, moves)) }
0
Kotlin
0
0
1b1121cfc57bbb73ac84a2f58927ab59bf158888
2,778
aoc-2022-in-kotlin
Apache License 2.0
src/Day07.kt
ranveeraggarwal
573,754,764
false
{"Kotlin": 12574}
import kotlin.math.min enum class FileType { FILE, DIRECTORY } class TreeNode { private val fileType: FileType private var size: Long = 0 private val children: HashMap<String, TreeNode> = HashMap() private var parent: TreeNode? = null private var isDirty = false constructor(size: Long) { this.fileType = FileType.FILE this.size = size } constructor() { this.fileType = FileType.DIRECTORY } fun addChild(name: String, child: TreeNode) { children[name] = child child.parent = this isDirty = true } fun getSize(): Long { if ((fileType == FileType.DIRECTORY) and isDirty) { size = children.values.fold(0) { sum, child -> sum + child.getSize() } isDirty = false } return size } fun getParent(): TreeNode? { return parent } fun getChild(name: String): TreeNode? { return children[name] } // Part 1 fun sumOfSmallDirectories(): Long { if (fileType == FileType.FILE) return 0L return (if (size > 100000) 0L else size) + children.values.fold(0L) { sum, child -> sum + child.sumOfSmallDirectories() } } // Part 2 fun findSmallDirectorySizeToDelete(deletionNeeded: Long): Long { if (fileType == FileType.FILE) return Long.MAX_VALUE return min( children.values.minOf { it.findSmallDirectorySizeToDelete(deletionNeeded) }, returnLargeIfOverLimit(deletionNeeded, getSize()) ) } } fun returnLargeIfOverLimit(deletionNeeded: Long, currSize: Long): Long { return if (currSize > deletionNeeded) currSize else Long.MAX_VALUE } fun buildDirectory(input: List<String>): TreeNode { val root = TreeNode() var cursor = root input.forEach { line -> run { val command = line.split(' ') if (command[0] == "$") { if (command[1] == "cd") { cursor = if (command[2] == "..") cursor.getParent()!! else cursor.getChild(command[2])!! } } else { if (command[0] == "dir") { cursor.addChild(command[1], TreeNode()) } else { cursor.addChild(command[1], TreeNode(command[0].toLong())) } } } } return root } fun main() { fun part1(input: List<String>): Long { val root = buildDirectory(input.drop(1)) root.getSize() return root.sumOfSmallDirectories() } fun part2(input: List<String>): Long { val root = buildDirectory(input.drop(1)) return root.findSmallDirectorySizeToDelete(30000000 - (70000000 - root.getSize())) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day07_test") println(part1(testInput)) println(part2(testInput)) val input = readInput("Day07") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
c8df23daf979404f3891cdc44f7899725b041863
3,019
advent-of-code-2022-kotlin
Apache License 2.0
src/Day03.kt
colund
573,040,201
false
{"Kotlin": 10244}
fun main() { val testInput = readInput("Day03") val day3Part1 = day3Part1(testInput) println("Day3 part 1: $day3Part1") val day3Part2 = day3Part2(testInput) println("Day3 part 2: $day3Part2") } private fun day3Part1( testInput: List<String> ): Int { val priorities = priorityChars() return testInput .asSequence() .map { line -> line.chunked(line.length / 2) } .mapNotNull { val first = it[0] val second = it[1] first.find { char -> second.contains(char) } }.sumOf { priorities.indexOf(it) + 1 } } private fun day3Part2(testInput: List<String>): Int { val priorities = priorityChars() return testInput .asSequence() .chunked(3) .mapNotNull { threeLines: List<String> -> threeLines[0].find { threeLines[1].contains(it) && threeLines[2].contains(it) } }.sumOf { priorities.indexOf(it) + 1 } } private fun priorityChars(): List<Char> { val priorities = mutableListOf<Char>() priorities.addAll(charRange('a', 'z')) priorities.addAll(charRange('A', 'Z')) return priorities } private fun charRange(firstChar: Char, lastChar: Char): MutableList<Char> { val chars = mutableListOf<Char>() var char = firstChar while (char <= lastChar) { chars.add(char) char++ } return chars }
0
Kotlin
0
0
49dcd2fccad0e54ee7b1a9cb99df2acdec146759
1,404
aoc-kotlin-2022
Apache License 2.0
src/Day13.kt
frungl
573,598,286
false
{"Kotlin": 86423}
class Block : Comparable<Block> { private var value: Int? = null private val inside = mutableListOf<Block>() private fun isLast() = value != null fun set(x: Int) { value = x } fun add(x: Block) { inside.add(x) } override fun compareTo(other: Block): Int { if (isLast() && other.isLast()) { return value!!.compareTo(other.value!!) } if (!isLast() && !other.isLast()) { inside.indices.forEach { if (other.inside.size == it) { return 1 } val res = inside[it].compareTo(other.inside[it]) if (res != 0) return res } if (other.inside.size > inside.size) { return -1 } } else if (isLast()) { val tmp = Block() tmp.add(this) return tmp.compareTo(other) } else { val tmp = Block() tmp.add(other) return this.compareTo(tmp) } return 0 } override fun toString(): String { if (value != null) { return value.toString() } return inside.joinToString(prefix = "[", postfix = "]", separator = ", ") } } fun parse(str: String): Block { val here = Block() if(str.startsWith('[')) { val tmp = str.substring(1, str.length - 1) var cnt = 0 var spos = 0 for (i in tmp.indices) { cnt += when { tmp[i] == '[' -> 1 tmp[i] == ']' -> -1 else -> 0 } if (cnt == 0 && (i + 1 == tmp.length || tmp[i + 1] == ',')) { here.add(parse(tmp.substring(spos, i+1))) spos = i + 2 } } } else { if (str.isNotEmpty()) here.set(str.toInt()) else here.set(-1000) } return here } fun main() { fun part1(input: List<String>): Int { var ind = 0 return input.chunked(3).sumOf { arr -> ind++ val s = arr[0] val t = arr[1] when { parse(s) < parse(t) -> ind else -> 0 } } } fun part2(input: List<String>): Int { val f = parse("[[2]]") val s = parse("[[6]]") val tmp = ((input + "[[2]]") + "[[6]]") .filter { it.isNotEmpty() } .map { parse(it) } .sorted() return (tmp.binarySearch(f) + 1) * (tmp.binarySearch(s) + 1) } val testInput = readInput("Day13_test") check(part1(testInput) == 13) check(part2(testInput) == 140) val input = readInput("Day13") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d4cecfd5ee13de95f143407735e00c02baac7d5c
2,801
aoc2022
Apache License 2.0
src/Day13.kt
amelentev
573,120,350
false
{"Kotlin": 87839}
fun main() { fun solve(map: List<CharArray>): MutableList<Int> { val n = map.size val res = mutableListOf<Int>() for (i in 0 until n-1) { val ok = (0 .. i).all { i1 -> val i2 = i + 1 + (i-i1) i2 !in map.indices || map[i1].contentEquals(map[i2]) } if (ok) res.add(i+1) } return res } fun transpose(map: List<CharArray>): List<CharArray> { return map[0].indices.map { j -> map.indices.joinToString("") { map[it][j].toString() }.toCharArray() } } fun solve1(map: List<CharArray>): List<Int> { val rows = solve(map) val cols = solve(transpose(map)) return cols + rows.map { it*100 } } fun solve2(map: List<CharArray>): Int { val r1 = solve1(map).toSet() for (i in map.indices) { for (j in map[i].indices) { val old = map[i][j] map[i][j] = when (old) { '.' -> '#' '#' -> '.' else -> error(old) } val r2 = solve1(map).toSet() - r1 if (r2.isNotEmpty()) { return r2.sum() } map[i][j] = old } } error("solve2") } val input = readInput("Day13") val curmap = mutableListOf<CharArray>() var res1 = 0 var res2 = 0 for (i in input.indices) { if (input[i].isEmpty()) { res1 += solve1(curmap).sum() res2 += solve2(curmap) curmap.clear() } else { curmap.add(input[i].toCharArray()) } } res1 += solve1(curmap).sum() res2 += solve2(curmap) println(res1) println(res2) }
0
Kotlin
0
0
a137d895472379f0f8cdea136f62c106e28747d5
1,802
advent-of-code-kotlin
Apache License 2.0
src/main/kotlin/cloud/dqn/leetcode/TrappingRainWater2Kt.kt
aviuswen
112,305,062
false
null
package cloud.dqn.leetcode import java.util.Comparator import java.util.PriorityQueue /** * https://leetcode.com/problems/trapping-rain-water-ii/description/ Given an m x n matrix of positive integers representing the height of each unit cell in a 2D elevation map, compute the volume of water it is able to trap after raining. Note: Both m and n are less than 110. The height of each unit cell is greater than 0 and is less than 20,000. Example: Given the following 3x6 height map: [ [1,4,3,1,3,2], [3,2,1,3,2,4], [2,3,3,2,3,1] ] Return 4. */ class TrappingRainWater2Kt { /** Algo0: 0. create visited array 1. Create priority queue 2. Add all boarder cells to priority queue and mark as visited 3. while priority queue is not empty { 4. val cell = poll() 5. cell.forEach NorthSouthEastWest { 6. if (inside of heightMap && not visited) { 7. mark as visited 8. res += max(0, cell.height - it.height) 9. enqueue(new cell(it.row, it.col, max(it.height, cell.height))) } } } Why each step 0. Gather water only once 1. Accumulate water by account for the lowest point 2. Border cells cannot contain any water and are already visited 3-5. Grab the lowest point and visit the neighbor cells 7-8. Only count the water once and accumlate the water between the neighbor cell and origin cell 9. Add cell to queue in order to visit its neighbors */ class Solution { companion object { private val directions = arrayOf( Pair(-1, 0), Pair(0, 1), Pair(1, 0), Pair(0, -1) ) } data class Cell ( val row: Int, val col: Int, val height: Int = 0 ) private fun max(x: Int, y: Int): Int = if (x > y) x else y private fun min(x: Int, y: Int): Int = if (x > y) y else x private fun inRange(x: Int, y: Int, arr: Array<IntArray>): Boolean { return x >= 0 && y >= 0 && x < arr.size && y < arr[x].size } fun trapRainWater(heightMap: Array<IntArray>): Int { if (heightMap.size <= 2 || heightMap[0].size <= 2) { return 0 } val visited = Array( heightMap.size, { BooleanArray(heightMap[0].size) } ) // val queue = PriorityQueue<Cell>(Comparator<Cell> { o1, o2 -> // o1.height - o2.height // }) val queue = PriorityQueue<Cell>(1, Comparator<Cell> { (_, _, h0), (_, _, h1) -> h0 - h1 }) // add all borders val m = heightMap.size val n = heightMap[0].size var i = 0 while (i < n) { visited[0][i] = true visited[m - 1][i] = true queue.add(Cell(0, i, heightMap[0][i])) queue.add(Cell(m - 1, i, heightMap[m - 1][i])) i++ } i = 0 while (i < m) { visited[i][0] = true visited[i][n - 1] = true queue.add(Cell(i, 0, heightMap[i][0])) queue.add(Cell(i, n - 1, heightMap[i][n - 1])) i++ } var res = 0 var row: Int var col: Int while (queue.isNotEmpty()) { val cell = queue.poll() directions.forEach { (rowAdd, colAdd) -> row = cell.row + rowAdd col = cell.col + colAdd if (inRange(row, col, heightMap) && !visited[row][col]) { visited[row][col] = true res += max(0, cell.height - heightMap[row][col]) queue.offer(Cell(row, col, max(cell.height, heightMap[row][col]))) } } } return res } } }
0
Kotlin
0
0
23458b98104fa5d32efe811c3d2d4c1578b67f4b
4,307
cloud-dqn-leetcode
No Limit Public License
advent-of-code-2022/src/Day01.kt
osipxd
572,825,805
false
{"Kotlin": 141640, "Shell": 4083, "Scala": 693}
fun main() { fun readInput(name: String) = readText(name).splitToSequence("\n\n") .map { it.lineSequence().map(String::toInt) } // Time - O(N), Space - O(1) // where N is number of Elves fun part1(elves: Sequence<Sequence<Int>>): Int = elves.maxOf { it.sum() } // Time - O(N*log(N)), Space - O(N) fun part2Simple(elves: Sequence<Sequence<Int>>): Int { return elves.map { it.sum() } .sortedDescending() .take(3) .sum() } // Time - O(N), Space - O(1) fun part2Fast(elves: Sequence<Sequence<Int>>): Int { val topThree = arrayOf(0, 0, 0) for (elf in elves) { val sum = elf.sum() when { sum > topThree[0] -> { topThree[2] = topThree[1] topThree[1] = topThree[0] topThree[0] = sum } sum > topThree[1] -> { topThree[2] = topThree[1] topThree[1] = sum } sum > topThree[2] -> { topThree[2] = sum } } } return topThree.sum() } val testInput = readInput("Day01_test") check(part1(testInput) == 24000) val input = readInput("Day01") println(part1(input)) println(part2Simple(input)) println(part2Fast(input)) }
0
Kotlin
0
5
6a67946122abb759fddf33dae408db662213a072
1,412
advent-of-code
Apache License 2.0
aoc-2023/src/main/kotlin/aoc/aoc12a.kts
triathematician
576,590,518
false
{"Kotlin": 615974}
import aoc.AocParser.Companion.parselines import aoc.* import aoc.util.getDayInput val testInput = """ ???.### 1,1,3 .??..??...?##. 1,1,3 ?#?#?#?#?#?#?#? 1,3,1,6 ????.#...#... 4,1,1 ????.######..#####. 1,6,5 ?###???????? 3,2,1 """.parselines class Springs(_line: String, val nums: List<Int>) { val max = nums.maxOrNull()!! val line = "." + _line .replace("?" + "#".repeat(max), "." + "#".repeat(max)) .replace("#".repeat(max) + "?", "#".repeat(max) + ".") .replace("[.]+".toRegex(), ".") fun arrangements() = arrangements(line, nums) } fun arrangements(str: String, nums: List<Int>): Long { if ('?' !in str) { val match = str.split("\\.+".toRegex()).map { it.length }.filter { it > 0 } == nums return if (match) 1 else 0 } val option1 = str.replaceFirst('?', '#') val option2 = str.replaceFirst('?', '.') return arrangements(option1, nums) + arrangements(option2, nums) } fun String.parse() = Springs(chunk(0), chunk(1).split(",").map { it.toInt() }) // part 1 fun List<String>.part1(): Long = sumOf { print(".") it.parse().arrangements() }.also { println() } // part 2 fun List<String>.part2(): Long = 0L // calculate answers val day = 12 val input = getDayInput(day, 2023) val testResult = testInput.part1().also { it.print } val answer1 = input.part1().also { it.print } val testResult2 = testInput.part2().also { it.print } val answer2 = input.part2().also { it.print } // print results AocRunner(day, test = { "$testResult, $testResult2" }, part1 = { answer1 }, part2 = { answer2 } ).run()
0
Kotlin
0
0
7b1b1542c4bdcd4329289c06763ce50db7a75a2d
1,600
advent-of-code
Apache License 2.0
aoc2023/day7.kt
davidfpc
726,214,677
false
{"Kotlin": 127212}
package aoc2023 import utils.InputRetrieval fun main() { Day7.execute() } private object Day7 { fun execute() { val input = readInput() println("Part 1: ${part1(input)}") println("Part 2: ${part2(input)}") } private fun part1(input: List<Hand>): Long = input .sortedWith(HandComparator(CARD_STRENGTH) { it.handType }) .mapIndexed { i, hand -> hand.bid * (i + 1L) } .sum() private fun part2(input: List<Hand>): Long = input .sortedWith(HandComparator(CARD_STRENGTH_PART_2) { it.jokerHandType }) .mapIndexed { i, hand -> hand.bid * (i + 1L) } .sum() private fun readInput(): List<Hand> = InputRetrieval.getFile(2023, 7) .readLines() .map { val (cards, bid) = it.split(' ') Hand(cards, bid.toInt()) } private enum class HandType { FIVE_OF_A_KIND, FOUR_OF_A_KIND, FULL_HOUSE, THREE_OF_A_KIND, TWO_PAIR, ONE_PAIR, HIGH_CARD } private val CARD_STRENGTH = listOf('A', 'K', 'Q', 'J', 'T', '9', '8', '7', '6', '5', '4', '3', '2') private val CARD_STRENGTH_PART_2 = listOf('A', 'K', 'Q', 'T', '9', '8', '7', '6', '5', '4', '3', '2', 'J') private class HandComparator(val cardStrength: List<Char>, val handTypeMapper: (Hand) -> HandType) : Comparator<Hand> { override fun compare(a: Hand, b: Hand): Int { val handTypeOfA = handTypeMapper.invoke(a) val handTypeOfB = handTypeMapper.invoke(b) return if (handTypeOfA == handTypeOfB) { // They have the same type, fallback to check the bigger label of the first different card val (aCard, bCard) = a.cards.zip(b.cards).first { it.first != it.second } if (cardStrength.indexOf(aCard) > cardStrength.indexOf(bCard)) { -1 } else { 1 } } else { handTypeOfB.ordinal - handTypeOfA.ordinal } } } private data class Hand(val cards: String, val bid: Int, val handType: HandType = calculateHandType(cards), val jokerHandType: HandType = calculateHandTypeWithJoker(cards)) { companion object { fun calculateHandType(cards: String): HandType { val tmp = cards.groupBy { it } return when (tmp.size) { 1 -> HandType.FIVE_OF_A_KIND 2 -> when (tmp.map { it.value.size }.max()) { 4 -> HandType.FOUR_OF_A_KIND else -> HandType.FULL_HOUSE } 3 -> when (tmp.map { it.value.size }.max()) { 3 -> HandType.THREE_OF_A_KIND else -> HandType.TWO_PAIR } 4 -> HandType.ONE_PAIR else -> HandType.HIGH_CARD } } fun calculateHandTypeWithJoker(cards: String): HandType { return if (!cards.contains('J')) { calculateHandType(cards) } else { val numberOfJokers = cards.count { it == 'J' } val tmp = cards.filter { it != 'J' }.groupBy { it } return when (tmp.size) { 0, 1 -> HandType.FIVE_OF_A_KIND 2 -> when (tmp.map { it.value.size }.max() + numberOfJokers) { 4 -> HandType.FOUR_OF_A_KIND else -> HandType.FULL_HOUSE } 3 -> when (tmp.map { it.value.size }.max() + numberOfJokers) { 3 -> HandType.THREE_OF_A_KIND else -> HandType.TWO_PAIR } else -> HandType.ONE_PAIR } } } } } }
0
Kotlin
0
0
8dacf809ab3f6d06ed73117fde96c81b6d81464b
3,927
Advent-Of-Code
MIT License
src/Day07.kt
MisterTeatime
560,956,854
false
{"Kotlin": 37980}
fun main() { val totalSpace = 70_000_000 val updateSpace = 30_000_000 fun part1(input: List<String>): Int { val nodes = mutableSetOf<TreeNode>() val root = TreeNode("/") var currentNode = root nodes.add(root) //Verzeichnisbaum erstellen input.drop(2).map { it.split(" ") } .forEach {item -> when { item[0].matches("""\d+""".toRegex()) -> currentNode.addChild(item[1], item[0].toInt()) item[0] == "dir" -> nodes.add(currentNode.addChild(item[1])) item[0] == "$" && item[1] == "cd" -> currentNode = when (item[2]) { ".." -> currentNode.parent!! else -> currentNode.getContent(item[2]) } } } //Ergebnis suchen return nodes.map { it.getSize() }.filter { it <= 100_000 }.sum() } fun part2(input: List<String>): Int { val nodes = mutableSetOf<TreeNode>() val root = TreeNode("/") var currentNode = root nodes.add(root) //Verzeichnisbaum erstellen input.drop(2).map { it.split(" ") } .forEach {item -> when { item[0].matches("""\d+""".toRegex()) -> currentNode.addChild(item[1], item[0].toInt()) item[0] == "dir" -> nodes.add(currentNode.addChild(item[1])) item[0] == "$" && item[1] == "cd" -> currentNode = when (item[2]) { ".." -> currentNode.parent!! else -> currentNode.getContent(item[2]) } } } //Ergebnis suchen val spaceToFreeUp = updateSpace - (totalSpace - root.getSize()) if (spaceToFreeUp <= 0) return 0 return nodes .map { it.getSize() } .filter { it >= spaceToFreeUp } .minOf { it } } // 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)) } data class TreeNode(val name: String, val content: MutableList<TreeNode> = mutableListOf()) { private var size: Int = 0 var parent: TreeNode? = null constructor(name: String, size: Int, content: MutableList<TreeNode> = mutableListOf()) : this(name, content) { this.size = size } fun getSize(): Int = when { content.isEmpty() -> size else -> content.sumOf { it.getSize() } } private fun addChild(item: TreeNode) { content.add(item) item.parent = this } fun addChild(name: String, size: Int) = addChild(TreeNode(name, size)) fun addChild(name: String): TreeNode { val item = TreeNode(name) addChild(item) return item } fun getContent(name: String) = this.content.first { it.name == name } }
0
Kotlin
0
0
8ba0c36992921e1623d9b2ed3585c8eb8d88718e
3,071
AoC2022
Apache License 2.0
src/main/kotlin/day7/Day7.kt
Arch-vile
317,641,541
false
null
package day7 import readFile data class Row(val color: String, val capacity: List<Pair<String, Int>>) data class Capacity(val bag: Bag, val amount: Int) data class Bag(val color: String, var capacity: MutableList<Capacity>) { fun getContainedBagCount(): Int { return capacity .map { it.amount + it.amount * it.bag.getContainedBagCount() } .sum() } } fun main(args: Array<String>) { val rows = readFile("./src/main/resources/day7Input.txt") .map { parse(it) } val bags = rows.map { Bag(it.color, mutableListOf()) } rows .forEachIndexed { index, row -> // Warning: Here we trust that the bags are in the same order as the rows in input val bag = bags[index] val bagsCapacity = row.capacity .map { Capacity( bags.find { bag -> bag.color == it.first }!!, it.second) } bag.capacity = bagsCapacity.toMutableList() } // # Part 1 println( bags .map { it.toString() } .filter { it.contains("shiny gold") } .count() - 1 ) // # Part 2 val ourBag = bags.find { it.color == "shiny gold" }!! println(ourBag.getContainedBagCount()) } fun parse(input: String): Row { var regexpForBag = """([^ ]* [^ ]*) bags contain""".toRegex() var regexpForContents = """(\d+) ([^ ]* [^ ]*)""".toRegex() var color = regexpForBag.find(input)?.groupValues!![1] var contents = regexpForContents.findAll(input).toList().flatMap { it.groupValues } .drop(1) .windowed(2, 3) .map { Pair(it[1], it[0].toInt()) } return Row(color, contents) }
0
Kotlin
0
0
12070ef9156b25f725820fc327c2e768af1167c0
1,604
adventOfCode2020
Apache License 2.0
src/Day12.kt
joy32812
573,132,774
false
{"Kotlin": 62766}
import java.util.LinkedList fun main() { fun toKey(x: Int, y: Int) = x * 10000 + y fun toCord(key: Int) = key / 10000 to key % 10000 fun shortestPath(grid: Array<CharArray>, edgeMap: Map<Int, MutableSet<Int>>, sx: Int, sy: Int, tx: Int, ty: Int): Int { val m = grid.size val n = grid[0].size val ans = Array(m) { Array(n) { Int.MAX_VALUE } } ans[sx][sy] = 0 val sKey = toKey(sx, sy) val Q = LinkedList<Int>() val inQ = mutableSetOf<Int>() Q += sKey inQ += sKey while (Q.isNotEmpty()) { val top = Q.poll() inQ.remove(top) val (ax, ay) = toCord(top) val edges = edgeMap[top] ?: emptySet() for (b in edges) { val (bx, by) = toCord(b) if (ans[bx][by] > ans[ax][ay] + 1) { ans[bx][by] = ans[ax][ay] + 1 if (b !in inQ) { inQ += b Q += b } } } } return ans[tx][ty] } fun getSourceAndDest(grid: Array<CharArray>): List<Int> { var (sx, sy, tx, ty) = listOf(0, 0, 0, 0) for (i in grid.indices) { for (j in grid[0].indices) { if (grid[i][j] == 'S') { grid[i][j] = 'a' sx = i sy = j } if (grid[i][j] == 'E') { grid[i][j] = 'z' tx = i ty = j } } } return listOf(sx, sy, tx, ty) } fun getEdgeMap(grid: Array<CharArray>): Map<Int, MutableSet<Int>> { val dx = listOf(0, 0, 1, -1) val dy = listOf(1, -1, 0, 0) val edgeMap = mutableMapOf<Int, MutableSet<Int>>() for (i in grid.indices) { for (j in grid[0].indices) { for (k in dx.indices) { val zx = i + dx[k] val zy = j + dy[k] if (zx !in grid.indices || zy !in grid[0].indices) continue if (grid[zx][zy] - grid[i][j] > 1) continue val aKey = toKey(i, j) val bKey = toKey(zx, zy) edgeMap.getOrPut(aKey) { mutableSetOf() } += bKey } } } return edgeMap } fun part1(input: List<String>): Int { val grid = input.map { it.toCharArray() }.toTypedArray() val (sx, sy, tx, ty) = getSourceAndDest(grid) val edgeMap = getEdgeMap(grid) return shortestPath(grid, edgeMap, sx, sy, tx, ty) } fun part2(input: List<String>): Int { val grid = input.map { it.toCharArray() }.toTypedArray() val (_, _, tx, ty) = getSourceAndDest(grid) val edgeMap = getEdgeMap(grid) var ans = Int.MAX_VALUE for (i in grid.indices) { for (j in grid[0].indices) { if (grid[i][j] == 'a') { ans = minOf(ans, shortestPath(grid, edgeMap, i, j, tx, ty)) } } } return ans } println(part1(readInput("data/Day12_test"))) println(part1(readInput("data/Day12"))) println(part2(readInput("data/Day12_test"))) println(part2(readInput("data/Day12"))) }
0
Kotlin
0
0
5e87958ebb415083801b4d03ceb6465f7ae56002
2,888
aoc-2022-in-kotlin
Apache License 2.0
src/Day07.kt
GreyWolf2020
573,580,087
false
{"Kotlin": 32400}
const val TOTALDISKSPACE = 70000000 const val NEEDEDUNUSEDSPACE = 30000000 fun main() { fun part1(input: String): Int = FileSystem().run { parseInstructions(input) getListOfDirNSizes() .map { it.second } .filter { it < 100000 } .sum() } fun part2(input: String): Pair<String, Int> = FileSystem().run { parseInstructions(input) val listOfDirNSizes = getListOfDirNSizes() val totalUsedSize = getListOfDirNSizes().maxOf { it.second } val totalUnUsedSpace = TOTALDISKSPACE - totalUsedSize listOfDirNSizes .filter { dirNSize -> val (_, size) = dirNSize size >= NEEDEDUNUSEDSPACE - totalUnUsedSpace } .minBy { it.second } } // test if implementation meets criteria from the description, like: // table test of part1 // val testInput = readInputAsString("Day07_test") // check(part1(testInput) == 95437) // check(part2(testInput) == Pair("d", 24933642)) // // val input = readInputAsString("Day07") // println(part1(input)) // println(part2(input)) } sealed class FileType (val name: String, val parent: FileType.Dir?) { class Dir(name: String, parent: FileType.Dir?, val children: HashMap<String, FileType> = hashMapOf()) : FileType(name, parent) { override fun getTheSize(): Int = children .map { it.value } .fold(0) { sizes, children -> sizes + children.getTheSize() } } class MyFile(name: String, parent: FileType.Dir, val size: Int) : FileType(name, parent) { override fun getTheSize(): Int = size } abstract fun getTheSize(): Int } fun FileType.Dir.getDirNSize(list: MutableList<Pair<String, Int>>) { children.map { it.value } .forEach { if (it is FileType.Dir) it.getDirNSize(list) } val size = getTheSize() list.add( Pair(name, size) ) } class FileSystem { private val rootDir = FileType.Dir("/", null) private var current = rootDir fun changeDirectory(param: String) { current = when(param) { ".." -> current.parent ?: rootDir "/" -> rootDir else -> current .children .getOrElse(param){ val newChild = FileType.Dir(param, current) current.children.put(param, newChild) newChild } as FileType.Dir } } fun listing(files: List<String>) { files .map { it.split(" ") } .fold(current) { cur, file -> when { file.first() == "dir" -> cur.children.put(file.last(), FileType.Dir(file.last(), cur)) else -> cur.children.put(file.last(), FileType.MyFile(file.last(), cur, file.first().toInt())) } cur } } fun parseInstructions(instructions: String) { instructions .split("$") .map { it.trim() } .forEach { val commandNParamsData = it .lines() val command = commandNParamsData .first() .split(" ") when (command.first()) { "cd" -> changeDirectory(command.last()) "ls" -> listing(commandNParamsData .drop(1) // remove any string that follows the command ls, which is blank in this case ) else -> {} } } } fun getListOfDirNSizes(): MutableList<Pair<String, Int>> = mutableListOf<Pair<String, Int>>().apply { rootDir.getDirNSize(this) } }
0
Kotlin
0
0
498da8861d88f588bfef0831c26c458467564c59
3,909
aoc-2022-in-kotlin
Apache License 2.0
src/Day04.kt
handrodev
577,884,162
false
{"Kotlin": 7670}
fun main() { fun part1(input: List<String>): Int { var overlapping = 0 for (line in input) { // Get sections covered by each elf val (elf1, elf2) = line.split(",") // Get first and last section covered by each elf val (x1, x2) = elf1.split("-").map { s -> s.toInt() } val (y1, y2) = elf2.split("-").map { s -> s.toInt() } // Check if one of the sections is fully contained by the other if ((y1 >= x1 && y2 <= x2) || (x1 >= y1 && x2 <= y2)) overlapping++ } return overlapping } fun part2(input: List<String>): Int { var overlapping = 0 for (line in input) { // Get sections covered by each elf val (elf1, elf2) = line.split(",") // Get first and last section covered by each elf val (x1, x2) = elf1.split("-").map { s -> s.toInt() } val (y1, y2) = elf2.split("-").map { s -> s.toInt() } // Check if sections overlap at any point if (x1 <= y2 && y1 <= x2) overlapping++ } return overlapping } // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInput("Day04") part1(input).println() part2(input).println() }
0
Kotlin
0
0
d95aeb85b4baf46821981bb0ebbcdf959c506b44
1,464
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/se/brainleech/adventofcode/aoc2022/Aoc2022Day05.kt
fwangel
435,571,075
false
{"Kotlin": 150622}
package se.brainleech.adventofcode.aoc2022 import se.brainleech.adventofcode.aoc2022.Aoc2022Day05.CraneModel.CRATE_MOVER_9000 import se.brainleech.adventofcode.aoc2022.Aoc2022Day05.CraneModel.CRATE_MOVER_9001 import se.brainleech.adventofcode.compute import se.brainleech.adventofcode.readLines import se.brainleech.adventofcode.verify class Aoc2022Day05 { enum class CraneModel { CRATE_MOVER_9000, CRATE_MOVER_9001 } data class Action(val quantity: Int, val from: Int, val to: Int) { fun applyOn(stacks: MutableMap<Int, String>, craneModel: CraneModel): MutableMap<Int, String> { val steps = if (craneModel == CRATE_MOVER_9001) 1 else quantity val perStep = if (craneModel == CRATE_MOVER_9001) quantity else 1 for (step in 1..steps) { stacks[to] = stacks[from]!!.take(perStep) + stacks[to] stacks[from] = stacks[from]!!.drop(perStep) } return stacks } } private fun String.asRowOfCrates() : MutableMap<Int, String> { val crates = mutableMapOf<Int, String>() this .trimEnd().plus(" ") .replace("] ", ",") .replace("[", "") .replace(" ", ",") // mind the gap :) .trimEnd(',') .split(",") .forEachIndexed { index, crate -> if (crate.isNotBlank()) crates[index + 1] = crate } return crates } private fun String.asAction() : Action { val operands = this.replace(Regex("(move |from |to )"), "") val (quantity, from, to) = operands.split(" ").map { it.toInt() } return Action(quantity, from, to) } private fun List<String>.toStacks(): MutableMap<Int, String> { return this .filter { it.contains("[") } .flatMap { it.asRowOfCrates().asSequence() } .groupBy({ it.key }, { it.value }) .mapValues { it.value.joinToString("") } .toSortedMap() .toMutableMap() } private fun List<String>.toRules(): List<Action> { return this .filter { it.contains("move") } .map { it.asAction() } } private fun process(input: List<String>, craneModel: CraneModel): String { val stacks = input.toStacks() input.toRules().forEach { it.applyOn(stacks, craneModel) } return stacks.values .map { it.first() } .joinToString("") } fun part1(input: List<String>) : String { return process(input, CRATE_MOVER_9000) } fun part2(input: List<String>) : String { return process(input, CRATE_MOVER_9001) } } fun main() { val solver = Aoc2022Day05() val prefix = "aoc2022/aoc2022day05" val testData = readLines("$prefix.test.txt") val realData = readLines("$prefix.real.txt") verify("CMZ", solver.part1(testData)) compute({ solver.part1(realData) }, "$prefix.part1 = ") verify("MCD", solver.part2(testData)) compute({ solver.part2(realData) }, "$prefix.part2 = ") }
0
Kotlin
0
0
0bba96129354c124aa15e9041f7b5ad68adc662b
3,053
adventofcode
MIT License
src/Day04.kt
sk0g
572,854,602
false
{"Kotlin": 7597}
fun sectionsOverlapCompletely(s: String): Boolean { val (assignment1, assignment2) = s.split(",") val bounds1 = assignment1.toBounds() val bounds2 = assignment2.toBounds() var overlaps = bounds1.first <= bounds2.first && bounds1.second >= bounds2.second overlaps = overlaps || bounds2.first <= bounds1.first && bounds2.second >= bounds1.second return overlaps } fun sectionsOverlapPartially(s: String): Boolean { val (bounds1, bounds2) = s .split(",") .map { it.toBounds() } return bounds1.first <= bounds2.second && bounds1.second >= bounds2.first } fun String.toBounds(): Pair<Int, Int> { val bounds = this .split("-") .map { it.toInt() } return bounds[0] to bounds[1] } fun main() { fun part1Assertions() { assert(!sectionsOverlapCompletely("2-4,6-8")) assert(!sectionsOverlapCompletely("2-3,4-5")) assert(!sectionsOverlapCompletely("5-7,7-9")) assert(sectionsOverlapCompletely("2-8,3-7")) assert(sectionsOverlapCompletely("6-6,4-6")) assert(!sectionsOverlapCompletely("2-6,4-8")) } fun part2Assertions() { assert(!sectionsOverlapPartially("2-4,6-8")) assert(!sectionsOverlapPartially("2-3,4-5")) assert(sectionsOverlapPartially("5-7,7-9")) assert(sectionsOverlapPartially("2-8,3-7")) assert(sectionsOverlapPartially("6-6,4-6")) assert(sectionsOverlapPartially("2-6,4-8")) } part1Assertions() part2Assertions() val input = readInput("Day04") val part1Answer = input.count { sectionsOverlapCompletely(it) } println("Part 1: $part1Answer") val part2Answer = input.count { sectionsOverlapPartially(it) } println("Part 2: $part2Answer") }
0
Kotlin
0
0
cd7e0da85f71d40bc7e3761f16ecfdce8164dae6
1,759
advent-of-code-22
Apache License 2.0
src/Day11.kt
StephenVinouze
572,377,941
false
{"Kotlin": 55719}
import java.lang.IllegalArgumentException import kotlin.math.floor data class Monkey( val id: Int, val items: MutableList<Long>, val operation: (Long) -> Long, val throwToMonkey: (Long) -> Unit, val divider: Int, ) fun main() { fun List<String>.toMonkeys(): List<Monkey> { val monkeys = mutableListOf<Monkey>() this .filter { it.isNotBlank() } .chunked(6) .forEach { line -> monkeys.add( Monkey( id = line[0].drop("Monkey ".length) .first() .digitToInt(), items = line[1] .drop(" Starting items: ".length) .filterNot { it.isWhitespace() } .split(",") .map { it.toLong() } .toMutableList(), operation = { worryLevel -> val (operatorStr, valueStr) = line[2] .drop(" Operation: new = old ".length) .split(" ") val value = when (valueStr) { "old" -> worryLevel else -> valueStr.toLong() } when (operatorStr) { "+" -> worryLevel + value "*" -> worryLevel * value "-" -> worryLevel - value "/" -> worryLevel / value else -> throw IllegalArgumentException("Unknown operator : $operatorStr") } }, throwToMonkey = { worryLevel -> val divider = line[3] .drop(" Test: divisible by ".length) .toInt() val monkeyIdIfTrue = line[4] .drop(" If true: throw to monkey ".length) .toInt() val monkeyIdIfFalse = line[5] .drop(" If false: throw to monkey ".length) .toInt() val monkeyId = if (worryLevel % divider == 0L) monkeyIdIfTrue else monkeyIdIfFalse monkeys.first { it.id == monkeyId }.items.add(worryLevel) }, divider = line[3] .drop(" Test: divisible by ".length) .toInt(), ) ) } return monkeys } fun compute(monkeys: List<Monkey>, rounds: Int, keepWorryLevelManageable: (Long) -> Long): Long { val inspectedItemsPerMonkey = MutableList(monkeys.size) { 0 } repeat(rounds) { monkeys.forEach { monkey -> monkey.items.forEach { inspectedItem -> val worryLevel = keepWorryLevelManageable(monkey.operation(inspectedItem)) monkey.throwToMonkey(worryLevel) } inspectedItemsPerMonkey[monkey.id] = inspectedItemsPerMonkey[monkey.id] + monkey.items.size monkey.items.clear() } } return inspectedItemsPerMonkey .sortedDescending() .take(2) .fold(1) { acc, i -> acc * i } } fun part1(input: List<String>): Long { val monkeys = input.toMonkeys() return compute(monkeys, 20) { worryLevel -> floor((worryLevel / 3.0)).toLong() } } fun part2(input: List<String>): Long { val monkeys = input.toMonkeys() val lcm = monkeys.fold(1) { acc, monkey -> acc * monkey.divider } return compute(monkeys, 10000) { worryLevel -> worryLevel % lcm } } check(part1(readInput("Day11_test")) == 10605L) check(part2(readInput("Day11_test")) == 2713310158L) val input = readInput("Day11") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
11b9c8816ded366aed1a5282a0eb30af20fff0c5
4,276
AdventOfCode2022
Apache License 2.0
src/main/kotlin/executeTermCmds.kt
sam-hoodie
534,831,633
false
{"Kotlin": 43732}
import java.time.Duration import java.time.LocalDateTime fun interpretTermCmds(command: String, data: List<Person>) { val commandParameters = command.split('.') if (commandParameters[3] == "pop") { if (commandParameters[4] == "state") { println(getMostPopularState(data)) return } if (commandParameters[4] == "party") { val result = getMostPopularParty(data) println(" The most popular party is ${result.partyName}" + " with ${result.appearances} appearances") return } } else if (commandParameters[3] == "most_terms") { val result = getMostTerms(data) println(" The most terms served by a person is ${result.terms} by ${result.person}") return } else if (commandParameters[3] == "longest_time") { val result = getMostDaysServed(data) println("The longest time served by a person is ${result.time} by ${result.person}") return } printAutocorrect(command) } data class LongestTime(val person: String, val time: Int) fun getMostDaysServed(data: List<Person>): LongestTime { var mostDaysServed = 0 var personWithMost = "" for (element in data) { val daysServed = getTotalDays(element.terms) if (daysServed > mostDaysServed) { mostDaysServed = daysServed personWithMost = data[0].name.first + " " + data[0].name.last } } return LongestTime(personWithMost, mostDaysServed) } fun getTotalDays(terms: List<Term>): Int { var result = 0 for (i in terms.indices) { result += getDaysBetween(terms[i].start, terms[i].end) } return result } data class TermsInfo(val person: String, val terms: Int) fun getMostTerms(data: List<Person>): TermsInfo { var mostTerms = data[0].terms.size var personWithMost = data[0].name.first + " " + data[0].name.last for (i in 1 until data.size) { if (data[i].terms.size > mostTerms) { mostTerms = data[i].terms.size personWithMost = data[i].name.first + " " + data[i].name.last } } return TermsInfo(personWithMost, mostTerms) } data class PartyInfo(val partyName: String, val appearances: Int) fun getMostPopularParty(data: List<Person>): PartyInfo { val uniqueParties = getAllParties(data).toSet().toList() val parties = getAllParties(data) var mostPopularParty = "" var amountOfMostPopParty = 0 for (i in uniqueParties.indices) { val predicate: (String) -> Boolean = { it == parties[i] } val stateAppearances = parties.count(predicate) if (stateAppearances > amountOfMostPopParty) { amountOfMostPopParty = stateAppearances mostPopularParty = parties[i] } } return PartyInfo(partyName = mostPopularParty, appearances = amountOfMostPopParty) } fun getAllParties(data: List<Person>): List<String> { val result = arrayListOf<String>() for (element in data) { val terms = element.terms for (element2 in terms) { if (element2.party != null) { result.add(element2.party) } } } return result } fun getDaysBetween(date1: String, date2: String): Int { val firstDate = LocalDateTime.parse(date1 + "T20:00:00.0000") val secondDate = LocalDateTime.parse(date2 + "T20:00:00.0000") return Duration.between(firstDate, secondDate).toDays().toInt() } data class PopState(val state: String, val amount: Int) fun getMostPopularState(data: List<Person>): PopState { val allStates = getAllStates(data) val uniqueStates = allStates.toSet().toList() var mostPopularState = "" var amountOfMostPopState = 0 for (i in uniqueStates.indices) { val predicate: (String) -> Boolean = { it == allStates[i] } val stateAppearances = allStates.count(predicate) if (stateAppearances > amountOfMostPopState) { amountOfMostPopState = stateAppearances mostPopularState = uniqueStates[i] } } return PopState(convertStateNames(mostPopularState), amountOfMostPopState) } fun getAllStates(data: List<Person>): List<String> { val result = arrayListOf<String>() for (element in data) { val terms = element.terms for (element2 in terms) { result.add(element2.state) } } return result } fun convertStateNames(state: String): String { val states = HashMap<String, String>() states.put("AL", "Alabama") states.put("AK", "Alaska") states.put("AB", "Alberta") states.put("AZ", "Arizona") states.put("AR", "Arkansas") states.put("BC", "British Columbia") states.put("CA", "California") states.put("CO", "Colorado") states.put("CT", "Connecticut") states.put("DE", "Delaware") states.put("DC", "District Of Columbia") states.put("FL", "Florida") states.put("GA", "Georgia") states.put("GU", "Guam") states.put("HI", "Hawaii") states.put("ID", "Idaho") states.put("IL", "Illinois") states.put("IN", "Indiana") states.put("IA", "Iowa") states.put("KS", "Kansas") states.put("KY", "Kentucky") states.put("LA", "Louisiana") states.put("ME", "Maine") states.put("MB", "Manitoba") states.put("MD", "Maryland") states.put("MA", "Massachusetts") states.put("MI", "Michigan") states.put("MN", "Minnesota") states.put("MS", "Mississippi") states.put("MO", "Missouri") states.put("MT", "Montana") states.put("NE", "Nebraska") states.put("NV", "Nevada") states.put("NB", "New Brunswick") states.put("NH", "New Hampshire") states.put("NJ", "New Jersey") states.put("NM", "New Mexico") states.put("NY", "New York") states.put("NF", "Newfoundland") states.put("NC", "North Carolina") states.put("ND", "North Dakota") states.put("NT", "Northwest Territories") states.put("NS", "Nova Scotia") states.put("NU", "Nunavut") states.put("OH", "Ohio") states.put("OK", "Oklahoma") states.put("ON", "Ontario") states.put("OR", "Oregon") states.put("PA", "Pennsylvania") states.put("PE", "Prince Edward Island") states.put("PR", "Puerto Rico") states.put("QC", "Quebec") states.put("RI", "Rhode Island") states.put("SK", "Saskatchewan") states.put("SC", "South Carolina") states.put("SD", "South Dakota") states.put("TN", "Tennessee") states.put("TX", "Texas") states.put("UT", "Utah") states.put("VT", "Vermont") states.put("VI", "Virgin Islands") states.put("VA", "Virginia") states.put("WA", "Washington") states.put("WV", "West Virginia") states.put("WI", "Wisconsin") states.put("WY", "Wyoming") states.put("YT", "Yukon Territory") states.put("Yukon Territory", "YT") return states[state].toString() }
0
Kotlin
0
0
9efea9f9eec55c1e61ac1cb11d3e3460f825994b
6,871
congress-challenge
Apache License 2.0
src/Day04.kt
Svikleren
572,637,234
false
{"Kotlin": 11180}
fun main() { fun isPairContains(pairToContain: List<String>, pairToCheckInto: List<String>): Boolean { val firstPairStart = pairToContain[0].toInt() val firstPairEnd = pairToContain[1].toInt() val secondPairStart = pairToCheckInto[0].toInt() val secondPairEnd = pairToCheckInto[1].toInt() return (firstPairStart <= secondPairStart && firstPairEnd >= secondPairEnd) } fun isPairOverlaps(pairToContain: List<String>, pairToCheckInto: List<String>): Boolean { val firstPairStart = pairToContain[0].toInt() val firstPairEnd = pairToContain[1].toInt() val secondPairStart = pairToCheckInto[0].toInt() val secondPairEnd = pairToCheckInto[1].toInt() return Math.max(firstPairEnd, secondPairEnd) - Math.min( firstPairStart, secondPairStart ) <= (firstPairEnd - firstPairStart) + (secondPairEnd - secondPairStart) } fun checkIfContains(pair1: String, pair2: String): Boolean { val firstList = pair1.split("-") val secondList = pair2.split("-") return isPairContains(firstList, secondList) || isPairContains(secondList, firstList) } fun checkIfOverlaps(pair1: String, pair2: String): Boolean { val firstList = pair1.split("-") val secondList = pair2.split("-") return isPairOverlaps(firstList, secondList) } fun part1(input: List<String>): Int { return input .map { twoPairs -> twoPairs.split(",") } .map { (pair1, pair2) -> checkIfContains(pair1, pair2) } .count { pairResult -> pairResult } } fun part2(input: List<String>): Int { return input .map { twoPairs -> twoPairs.split(",") } .map { (pair1, pair2) -> checkIfOverlaps(pair1, pair2) } .count { pairResult -> pairResult } } val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
e63be3f83b96a73543bf9bc00c22dc71b6aa0f57
1,964
advent-of-code-2022
Apache License 2.0
src/main/kotlin/biz/koziolek/adventofcode/year2022/day10/day10.kt
pkoziol
434,913,366
false
{"Kotlin": 715025, "Shell": 1892}
package biz.koziolek.adventofcode.year2022.day10 import biz.koziolek.adventofcode.findInput fun main() { val inputFile = findInput(object {}) val commands = parseCPUCommands(inputFile.bufferedReader().lineSequence()).toList() val cpu = CPU(cycle = 1, registers = Registers(x = 1)) val cpuStates = runProgram(cpu, commands.asSequence()) println("Sum of signal strength during the 20th, 60th, 100th, 140th, 180th, and 220th cycles: ${sumSignalStrengths(cpuStates, cycles = listOf(20, 60, 100, 140, 180, 220))}") val crt = CRT(width = 40, height = 6, contents = "") val lastCRT = syncCRTWithCPU(crt, cpu, commands.asSequence()) println("CRT:\n${lastCRT.render()}") } data class CPU( val cycle: Int = 1, val registers: Registers = Registers(), ) { val signalStrength: Int = cycle * registers.x } data class Registers( val x: Int = 1, ) sealed interface Command { val cycles: Int fun execute(registers: Registers): Registers } object Noop : Command { override val cycles = 1 override fun execute(registers: Registers) = registers } data class AddX(val value: Int) : Command { override val cycles = 2 override fun execute(registers: Registers) = registers.copy(x = registers.x + value) } data class CRT( val width: Int, val height: Int, val contents: String, ) { fun addPixel(isLit: Boolean): CRT = copy(contents = contents + if (isLit) '#' else '.') fun render() = contents.chunked(width).joinToString("\n") } fun parseCPUCommands(lines: Sequence<String>): Sequence<Command> = lines.map { line -> val parts = line.split(' ') when (parts[0]) { "noop" -> Noop "addx" -> AddX(parts[1].toInt()) else -> throw IllegalArgumentException("Unknown command: '${parts[0]}'") } } fun runProgram(cpu: CPU, commands: Sequence<Command>): Sequence<CPU> = sequence { var currentCPU = cpu for (command in commands) { repeat(command.cycles) { yield(currentCPU) currentCPU = currentCPU.copy( cycle = currentCPU.cycle + 1, ) } currentCPU = currentCPU.copy( registers = command.execute(currentCPU.registers), ) } yield(currentCPU) } fun sumSignalStrengths(cpuStates: Sequence<CPU>, cycles: Collection<Int>): Int = cpuStates .filter { cycles.contains(it.cycle) } .sumOf { it.signalStrength } fun syncCRTWithCPU(crt: CRT, cpu: CPU, commands: Sequence<Command>): CRT = runProgram(cpu, commands) .take(crt.width * crt.height) .fold(crt, ::updateCRT) fun updateCRT(crt: CRT, cpu: CPU, spriteLength: Int = 3): CRT { val spritePosition = cpu.registers.x val spriteRange = (spritePosition - spriteLength/2)..(spritePosition + spriteLength/2) val drawnPixelPosition = crt.contents.length % crt.width val isLit = drawnPixelPosition in spriteRange return crt.addPixel(isLit) }
0
Kotlin
0
0
1b1c6971bf45b89fd76bbcc503444d0d86617e95
3,072
advent-of-code
MIT License
src/Day08.kt
haitekki
572,959,197
false
{"Kotlin": 24688}
fun main() { fun part1(input: String): Int { val grid = input.lines() val seeableTrees = mutableSetOf<String>() for (i in grid.indices) { for (j in grid[i].indices) { if (i <= 0 || i == grid.lastIndex || j <= 0 || j == grid[i].lastIndex) { seeableTrees.add("${i}-${j}") } else { val currentTreeHeight = grid[i][j].digitToInt() val currentRow = grid[i].map { it.digitToInt() } val currentColumn = grid.map { it[j].digitToInt() } if (currentRow.subList(0,j).maxOrNull()!! < currentTreeHeight || currentRow.subList(j+1,currentRow.size).maxOrNull()!! < currentTreeHeight || currentColumn.subList(0,i).maxOrNull()!! < currentTreeHeight || currentColumn.subList(i+1,currentColumn.size).maxOrNull()!! < currentTreeHeight) { seeableTrees.add("${i}-${j}") } } } } return seeableTrees.size } fun part2(input:String): Int { val grid = input.lines() var max = 0 for (i in 1..grid.size-2) { for (j in 1..grid[i].length-2) { val currentTreeHeight = grid[i][j].digitToInt() val currentRow = grid[i].map { it.digitToInt() } val currentColumn = grid.map { it[j].digitToInt() } val values = listOf(currentRow.subList(0,j).reversed(), currentRow.subList(j+1,currentRow.size), currentColumn.subList(0,i).reversed(), currentColumn.subList(i+1,currentColumn.size) ).map { var k = 0 while (k < it.size) { if (it[k] >= currentTreeHeight) { break } k++ } if (k == it.size) it.size else k+1 } val scenicValue = values[0]*values[1]*values[2]*values[3] if (scenicValue > max) { max = scenicValue } } } return max } val testInput = """ 30373 25512 65332 33549 35390 """.trimIndent() println(part1(testInput)) println(part2(testInput)) val input = readInput("Day08") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
b7262133f9115f6456aa77d9c0a1e9d6c891ea0f
2,775
aoc2022
Apache License 2.0
2021/src/main/kotlin/Day19.kt
eduellery
433,983,584
false
{"Kotlin": 97092}
import kotlin.math.abs class Day19(input: String) { private val scanners = input.split("""--- scanner \d+ ---""".toRegex()).filterNot { it.isEmpty() }.map { s -> Scanner(s.trim().lines().map { it.split(",") }.map { (x, y, z) -> Point3D(x.toInt(), y.toInt(), z.toInt()) } .toSet()) } fun solve1() = assembleMap().beacons.size fun solve2() = assembleMap().scannersPositions.let { positions -> positions.flatMapIndexed { index, first -> positions.drop(index + 1).map { second -> first to second } } .maxOf { (first, second) -> first distanceTo second } } private fun assembleMap(): AssembledMap { val foundBeacons = scanners.first().beacons.toMutableSet() val foundScannersPositions = mutableSetOf(Point3D(0, 0, 0)) val remaining = ArrayDeque<Scanner>().apply { addAll(scanners.drop(1)) } while (remaining.isNotEmpty()) { val candidate = remaining.removeFirst() when (val transformedCandidate = Scanner(foundBeacons).getTransformedIfOverlap(candidate)) { null -> remaining.add(candidate) else -> { foundBeacons.addAll(transformedCandidate.beacons) foundScannersPositions.add(transformedCandidate.position) } } } return AssembledMap(foundBeacons, foundScannersPositions) } private data class Scanner(val beacons: Set<Point3D>) { fun allRotations() = beacons.map { it.allRotations() }.transpose().map { Scanner(it) } fun getTransformedIfOverlap(otherScanner: Scanner): TransformedScanner? { return otherScanner.allRotations().firstNotNullOfOrNull { otherReoriented -> beacons.firstNotNullOfOrNull { first -> otherReoriented.beacons.firstNotNullOfOrNull { second -> val otherPosition = first - second val otherTransformed = otherReoriented.beacons.map { otherPosition + it }.toSet() when ((otherTransformed intersect beacons).size >= 12) { true -> TransformedScanner(otherTransformed, otherPosition) false -> null } } } } } private fun List<Set<Point3D>>.transpose(): List<Set<Point3D>> { return when (all { it.isNotEmpty() }) { true -> listOf(map { it.first() }.toSet()) + map { it.drop(1).toSet() }.transpose() false -> emptyList() } } } private data class TransformedScanner(val beacons: Set<Point3D>, val position: Point3D) private data class AssembledMap(val beacons: Set<Point3D>, val scannersPositions: Set<Point3D>) private data class Point3D(val x: Int, val y: Int, val z: Int) { operator fun plus(other: Point3D) = Point3D(x + other.x, y + other.y, z + other.z) operator fun minus(other: Point3D) = Point3D(x - other.x, y - other.y, z - other.z) infix fun distanceTo(other: Point3D) = abs(x - other.x) + abs(y - other.y) + abs(z - other.z) fun allRotations(): Set<Point3D> { return setOf( Point3D(x, y, z), Point3D(x, -z, y), Point3D(x, -y, -z), Point3D(x, z, -y), Point3D(-x, -y, z), Point3D(-x, -z, -y), Point3D(-x, y, -z), Point3D(-x, z, y), Point3D(-z, x, -y), Point3D(y, x, -z), Point3D(z, x, y), Point3D(-y, x, z), Point3D(z, -x, -y), Point3D(y, -x, z), Point3D(-z, -x, y), Point3D(-y, -x, -z), Point3D(-y, -z, x), Point3D(z, -y, x), Point3D(y, z, x), Point3D(-z, y, x), Point3D(z, y, -x), Point3D(-y, z, -x), Point3D(-z, -y, -x), Point3D(y, -z, -x) ) } } }
0
Kotlin
0
1
3e279dd04bbcaa9fd4b3c226d39700ef70b031fc
4,140
adventofcode-2021-2025
MIT License
dcp_kotlin/src/main/kotlin/dcp/day250/bf.kt
sraaphorst
182,330,159
false
{"C++": 577416, "Kotlin": 231559, "Python": 132573, "Scala": 50468, "Java": 34742, "CMake": 2332, "C": 315}
package dcp.day250 import java.util.LinkedList interface Circular<T> : Iterable<T> { fun state(): T fun inc() fun isZero(): Boolean // `true` in exactly one state fun hasNext(): Boolean // `false` if the next state `isZero()` override fun iterator() : Iterator<T> { return object : Iterator<T> { var started = false override fun next(): T { if(started) { inc() } else { started = true } return state() } override fun hasNext() = this@Circular.hasNext() } } } class Ring(val size: Int) : Circular<Int> { private var state = 0 override fun state() = state override fun inc() {state = (1 + state) % size} override fun isZero() = (state == 0) override fun hasNext() = (state != size - 1) init { assert(size > 0) } } abstract class CircularList<E, H: Circular<E>>(val size: Int) : Circular<List<E>> { protected abstract val state: List<H> // state.size == size override fun inc() { state.forEach { it.inc() if(! it.isZero()) return } } override fun isZero() = state.all {it.isZero()} override fun hasNext() = state.any {it.hasNext()} } abstract class IntCombinations(size: Int) : CircularList<Int, Ring>(size) class BinaryBits(N: Int) : IntCombinations(N) { override val state = Array(N, {Ring(2)}).toList() override fun state() = state.map {it.state()}.reversed() } class Permutations(N: Int) : IntCombinations(N) { override val state = mutableListOf<Ring>() init { for(i in N downTo 1) { state += Ring(i) } } override fun state(): List<Int> { val items = (0..size - 1).toCollection(LinkedList()) return state.map {ring -> items.removeAt(ring.state())} } } fun <T> `⊃`(set1: Set<T>, set2: Set<T>): Set<T> = set1.intersect(set2) fun bruteForceCryptopuzzle(word1: String, word2: String, wordSum: String): Map<Char, Int>? { val chars = (word1 + word2 + wordSum).toCharArray().distinct() for (configuration in Permutations(10)) { val map = chars.zip(configuration).toMap() val n1 = word1.fold(word1){acc, char -> acc.replace(char.toString(), map[char].toString())}.toInt() val n2 = word2.fold(word2){acc, char -> acc.replace(char.toString(), map[char].toString())}.toInt() val nSum = wordSum.fold(wordSum){acc, char -> acc.replace(char.toString(), map[char].toString())}.toInt() if (n1 + n2 == nSum) return map } return null } fun main() { println(bruteForceCryptopuzzle("SEND", "MORE", "MONEY")) }
0
C++
1
0
5981e97106376186241f0fad81ee0e3a9b0270b5
2,753
daily-coding-problem
MIT License
src/main/kotlin/com/github/dangerground/aoc2020/Day19.kt
dangerground
317,439,198
false
null
package com.github.dangerground.aoc2020 import com.github.dangerground.aoc2020.util.DayInput import com.github.dangerground.aoc2020.util.World import kotlin.math.max fun main() { val process = Day19(DayInput.batchesOfStringList(19)) println("result part 1: ${process.part1()}") println("result part 2: ${process.part2()}") } class Day19(val input: List<List<String>>) { val rules = input[0].map { rule -> val tmp = rule.split(":"); return@map tmp[0].toInt() to tmp[1] }.toMap().toMutableMap() val messages = input[1] fun expandRules(rule: Int): String { var content = rules[rule]!! val regex = "(\\d+) \\| \\1 \\b$rule\\b".toRegex() if (content.contains(regex)) { val result = regex.matchEntire(content)!!.groupValues content = "( ${result[1]} )+" println("::$content") } val regex2 = "(\\d+) (\\d+) \\| \\1 \\b$rule\\b \\2".toRegex() if (rule == 11 && content.contains(regex2)) { val result = regex2.matchEntire(content)!!.groupValues content = "( ${result[1]} ${result[2]} | ${result[1]} ${result[1]} ${result[2]} ${result[2]} | ${result[1]} ${result[1]} ${result[1]} ${result[2]} ${result[2]} ${result[2]} | ${result[1]} ${result[1]} ${result[1]} ${result[1]} ${result[2]} ${result[2]} ${result[2]} ${result[2]} | ${result[1]} ${result[1]} ${result[1]} ${result[1]} ${result[1]} ${result[2]} ${result[2]} ${result[2]} ${result[2]} ${result[2]} )" println("::$content") } val numbers = content.replace("| ", "") .split(" ") .sortedByDescending { it.length } .filter { it.matches("\\d+".toRegex()) } .map { it.toInt() } numbers.forEach { val expandRules = expandRules(it) content = content.replace("$it", if(expandRules.contains('|')) "($expandRules)" else expandRules) } return content } fun part1(): Int { val rule = cleanup(expandRules(0)).toRegex() println(rule) return messages.map { rule.matches(it) }.count { it } } private fun cleanup(rule: String): String { return rule.replace("\"","").replace(" ", "") } fun part2(): Int { rules[8] = "42 | 42 8" rules[11] = "42 31 | 42 11 31" val rule = cleanup(expandRules(0)).toRegex() println(rule) return messages.map { rule.matches(it) }.count { it } } }
0
Kotlin
0
0
c3667a2a8126d903d09176848b0e1d511d90fa79
2,502
adventofcode-2020
MIT License
src/Day15.kt
fedochet
573,033,793
false
{"Kotlin": 77129}
import kotlin.math.abs fun main() { data class Pos(val x: Int, val y: Int) fun distance(from: Pos, to: Pos): Int = abs(from.x - to.x) + abs(from.y - to.y) fun parsePos(posStr: String): Pos { val (x, y) = posStr.split(", ", limit = 2) return Pos( x.removePrefix("x=").toInt(), y.removePrefix("y=").toInt() ) } fun parsePositions(input: List<String>) = input.map { val (posStr, beaconStr) = it.split(": ", limit = 2) val pos = parsePos(posStr.removePrefix("Sensor at ")) val beacon = parsePos(beaconStr.removePrefix("closest beacon is at ")) pos to beacon } fun part1(input: List<String>, y: Int): Int { val dots = parsePositions(input) val xStart = dots.minOf { (dot, beacon) -> dot.x - distance(dot, beacon) - 1 } val xEnd = dots.maxOf { (dot, beacon) -> dot.x + distance(dot, beacon) + 1 } var count = 0 for (x in xStart..xEnd) { val currentPos = Pos(x, y) if (dots.any { (dot, beacon) -> currentPos == dot || currentPos == beacon }) { continue } for ((dot, beacon) in dots) { if (dot != beacon && distance(dot, currentPos) <= distance(dot, beacon)) { count++ break } } } return count } fun notInRadius(dotAndBeacon: Pair<Pos, Pos>, possibleDot: Pos): Boolean { val (dot, beacon) = dotAndBeacon return distance(dot, possibleDot) > distance(dot, beacon) } fun walkAround(pos: Pos, radius: Int): Sequence<Pos> = sequence { var xAdd = radius var yAdd = 0 while (yAdd < radius) { xAdd-- yAdd++ yield(Pos(pos.x + xAdd, pos.y + yAdd)) } while (xAdd > -radius) { xAdd-- yAdd-- yield(Pos(pos.x + xAdd, pos.y + yAdd)) } while (yAdd > -radius) { xAdd++ yAdd-- yield(Pos(pos.x + xAdd, pos.y + yAdd)) } while (xAdd < radius) { xAdd++ yAdd++ yield(Pos(pos.x + xAdd, pos.y + yAdd)) } } fun positionFrequency(possibleDot: Pos): Long = possibleDot.x.toLong() * 4_000_000L + possibleDot.y.toLong() fun part2(input: List<String>, x: Int, y: Int): Long { val dots = parsePositions(input) fun inArea(pos: Pos): Boolean = pos.x in 0..x && pos.y in 0..y val targetPoint = dots.asSequence() .flatMap { (dot, beacon) -> walkAround(dot, distance(dot, beacon) + 1) } .filter { inArea(it) } .first { candidate -> dots.all { pair -> notInRadius(pair, candidate) } } return positionFrequency(targetPoint) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day15_test") check(part1(testInput, y = 10) == 26) check(part2(testInput, x = 20, y = 20) == 56000011L) val input = readInput("Day15") println(part1(input, y = 2_000_000)) println(part2(input, x = 4_000_000, y = 4_000_000)) } // 4436198 // 4535198
0
Kotlin
0
1
975362ac7b1f1522818fc87cf2505aedc087738d
3,267
aoc2022
Apache License 2.0
src/Day05.kt
rickbijkerk
572,911,701
false
{"Kotlin": 31571}
fun main() { fun test_startContainers(): Map<Int, ArrayDeque<String>> = mapOf( 1 to ArrayDeque(listOf("z", "n")), 2 to ArrayDeque(listOf("m", "c", "d")), 3 to ArrayDeque(listOf("p")) ) fun startContainers() = mapOf( 1 to ArrayDeque(listOf("b", "w", "n")), 2 to ArrayDeque(listOf("l", "z", "s", "p", "t", "d", "m", "b")), 3 to ArrayDeque(listOf("q", "h", "z", "w", "r")), 4 to ArrayDeque(listOf("w", "d", "v", "j", "z", "r")), 5 to ArrayDeque(listOf("s", "h", "m", "b")), 6 to ArrayDeque(listOf("l", "g", "n", "j", "h", "v", "p", "b")), 7 to ArrayDeque(listOf("j", "q", "z", "f", "h", "d", "l", "s")), 8 to ArrayDeque(listOf("w", "s", "f", "j", "g", "q", "b")), 9 to ArrayDeque(listOf("z", "w", "m", "s", "c", "d", "j")) ) fun part1(input: List<String>, containerRows: Map<Int, ArrayDeque<String>>): String { input.forEach { line -> val moves = line.substringAfter("move ").substringBefore(" from").toInt() val from = line.substringAfter("from ").substringBefore(" to").toInt() val to = line.substringAfter("to ").toInt() repeat(moves) { val removedContainer = containerRows[from]!!.removeLast() containerRows[to]!!.addLast(removedContainer) } } return containerRows.values.joinToString(separator = "") { it.last().toUpperCase() } } fun part2(input: List<String>, containerRows: Map<Int, ArrayDeque<String>>): String { input.forEach { line -> val moves = line.substringAfter("move ").substringBefore(" from").toInt() val from = line.substringAfter("from ").substringBefore(" to").toInt() val to = line.substringAfter("to ").toInt() val result = (1..moves).map { containerRows[from]!!.removeLast() }.toList().reversed() result.map { removedContainer -> containerRows[to]!!.addLast(removedContainer) } } return containerRows.values.joinToString(separator = "") { it.last().toUpperCase() } } val testInput = readInput("day05_test") // TEST PART 1 val resultPart1 = part1(testInput, test_startContainers()) val expectedPart1 = "CMZ" //TODO Change me println("testresult:$resultPart1 expected:$expectedPart1 \n") check(resultPart1 == expectedPart1) //Check results part1 val input = readInput("day05") println("ANSWER 1: ${part1(input, startContainers())}\n\n") // TEST PART 2 val resultPart2 = part2(testInput, test_startContainers()) val expectedPart2 = "MCD" //TODO Change me println("testresult:$resultPart2 expected:$expectedPart2 \n") check(resultPart2 == expectedPart2) //Check results part2 println("ANSWER 2: ${part2(input, startContainers())}") }
0
Kotlin
0
0
817a6348486c8865dbe2f1acf5e87e9403ef42fe
2,862
aoc-2022
Apache License 2.0
src/Day13.kt
sbaumeister
572,855,566
false
{"Kotlin": 38905}
import kotlinx.serialization.json.* fun listsInRightOrder(leftList: JsonArray, rightList: JsonArray): Boolean? { var i = 0 while (true) { if (leftList.getOrNull(i) == null && rightList.getOrNull(i) == null) { return null } if (leftList.getOrNull(i) == null && rightList.getOrNull(i) != null) { return true } if (leftList.getOrNull(i) != null && rightList.getOrNull(i) == null) { return false } if (leftList[i] is JsonPrimitive && rightList[i] is JsonPrimitive) { if (leftList[i].jsonPrimitive.int < rightList[i].jsonPrimitive.int) { return true } if (leftList[i].jsonPrimitive.int > rightList[i].jsonPrimitive.int) { return false } } if (leftList[i] is JsonArray && rightList[i] is JsonArray) { listsInRightOrder(leftList[i].jsonArray, rightList[i].jsonArray)?.let { return it } } if (leftList[i] is JsonPrimitive && rightList[i] is JsonArray) { listsInRightOrder(buildJsonArray { add(leftList[i]) }, rightList[i].jsonArray)?.let { return it } } if (leftList[i] is JsonArray && rightList[i] is JsonPrimitive) { listsInRightOrder(leftList[i].jsonArray, buildJsonArray { add(rightList[i]) })?.let { return it } } i++ } } fun main() { fun part1(input: List<String>): Int { val indicesInRightOrder = mutableSetOf<Int>() input.filter { it.isNotEmpty() }.chunked(2).forEachIndexed { i, (left, right) -> val leftList = Json.parseToJsonElement(left).jsonArray val rightList = Json.parseToJsonElement(right).jsonArray listsInRightOrder(leftList, rightList)?.let { if (it) indicesInRightOrder.add(i + 1) } } return indicesInRightOrder.sum() } fun part2(input: List<String>): Int { val packets = input.filter { it.isNotEmpty() }.map { Json.parseToJsonElement(it).jsonArray } val divider1 = buildJsonArray { addJsonArray { add(2) } } val divider2 = buildJsonArray { addJsonArray { add(6) } } val sortedPackets = packets.plusElement(divider1).plusElement(divider2).sortedWith { left, right -> when (listsInRightOrder(left, right)) { null -> 0 true -> -1 else -> 1 } } return (sortedPackets.indexOfFirst { it == divider1 } + 1) * (sortedPackets.indexOfFirst { it == divider2 } + 1) } val testInput = readInput("Day13_test") check(part1(testInput) == 13) check(part2(testInput) == 140) val input = readInput("Day13") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
e3afbe3f4c2dc9ece1da7cf176ae0f8dce872a84
2,765
advent-of-code-2022
Apache License 2.0
day03/src/main/kotlin/Main.kt
rstockbridge
159,586,951
false
null
import java.io.File fun main() { val claims = parseInput(readInputFile()) println("Part I: the solution is ${solvePartI(claims)}.") println("Part II: the solution is ${solvePartII(claims)}.") } fun readInputFile(): List<String> { return File(ClassLoader.getSystemResource("input.txt").file).readLines() } fun parseInput(input: List<String>): List<Claim> { val regex = "#(\\d+) @ (\\d+),(\\d+): (\\d+)x(\\d+)".toRegex() return input .map { line -> val (id, dim1, dim2, dim3, dim4) = regex.matchEntire(line)!!.destructured Claim(id.toInt(), dim1.toInt(), dim2.toInt(), dim3.toInt(), dim4.toInt()) } } fun solvePartI(claims: List<Claim>): Int { return calculateCoordinateClaimCount(claims) .filter { coordinateClaimCount -> coordinateClaimCount.value >= 2 } .size } fun solvePartII(claims: List<Claim>): Int { val claimCount = calculateCoordinateClaimCount(claims) // only one claim will satisfy the criterion return claims .first { claim -> claim.coordinates.sumBy { coordinate -> claimCount[coordinate]!! } == claim.coordinates.size } .id } fun calculateCoordinateClaimCount(claims: List<Claim>): Map<Coordinate, Int> { return claims .flatMap { claim -> claim.coordinates } .groupingBy { it } .eachCount() } data class Claim(val id: Int, val numberOfInchesFromLeftEdge: Int, val numberOfInchesFromTopEdge: Int, var width: Int, var height: Int) { val coordinates: MutableSet<Coordinate> = mutableSetOf() init { for (i in numberOfInchesFromLeftEdge until numberOfInchesFromLeftEdge + width) { for (j in numberOfInchesFromTopEdge until numberOfInchesFromTopEdge + height) { coordinates.add(Coordinate(i, j)) } } } } data class Coordinate(val inchesFromLeftEdge: Int, val inchesFromTopEdge: Int)
0
Kotlin
0
0
c404f1c47c9dee266b2330ecae98471e19056549
2,011
AdventOfCode2018
MIT License
src/main/kotlin/me/grison/aoc/y2022/Day11.kt
agrison
315,292,447
false
{"Kotlin": 267552}
package me.grison.aoc.y2022 import me.grison.aoc.* import java.math.BigInteger.ONE class Monkey( var id: Int, var items: MutableList<Long>, var operation: (Long) -> Long, var divisible: Long, var destinations: Pair<Int, Int> ) class Day11 : Day(11, 2022) { override fun title() = "Monkey in the Middle" override fun partOne() = solve(20, parseMonkeys()) { level -> level / 3L } override fun partTwo() = parseMonkeys().let { monkeys -> val lcm = lcm(monkeys) solve(10_000, monkeys) { level -> level % lcm } } private fun parseMonkeys(): List<Monkey> { val monkeys = mutableListOf<Monkey>() inputGroups.forEach { monkey -> val (id, items, operation, divisible, ok, nok) = monkey.lines() val after = operation.after(": ").words() val (op, operand) = p(after[3], after[4]) monkeys.add( Monkey( id.firstInt(), items.allLongs().toMutableList(), { i -> when (operand.isDigits()) { false -> if (op == "+") i + i else i * i true -> if (op == "+") i + operand.toLong() else i * operand.toLong() } }, divisible.allLongs().first(), p(ok.firstInt(), nok.firstInt()) ) ) } return monkeys } private fun lcm(monkeys: List<Monkey>) = monkeys.map { it.divisible.toBigInteger() }.fold(ONE) { acc, i -> (acc * i) / acc.gcd(i) }.toLong() private fun solve(rounds: Int, monkeys: List<Monkey>, newLevel: (Long) -> Long): Long { val monkeyBusiness = mutableList(monkeys.size, 0L) repeat(rounds) { monkeys.forEach { monkey -> monkey.items.forEach { item -> monkeyBusiness[monkey.id] += 1L val level = newLevel(monkey.operation(item)) val destination = if (level % monkey.divisible == 0L) monkey.destinations.first else monkey.destinations.second monkeys[destination].items.add(level) } monkey.items.clear() } } return monkeyBusiness.sorted().takeLast(2).product() } }
0
Kotlin
3
18
ea6899817458f7ee76d4ba24d36d33f8b58ce9e8
2,414
advent-of-code
Creative Commons Zero v1.0 Universal
src/Day02.kt
makohn
571,699,522
false
{"Kotlin": 35992}
import java.lang.IllegalArgumentException fun main() { fun toScore(c: Char) = when(c) { 'X', 'A' -> 1 'Y', 'B' -> 2 'Z', 'C' -> 3 else -> throw IllegalArgumentException() } fun calcScore(o: Char, m: Char): Int { val sm = toScore(m) val so = toScore(o) when (m) { 'X' -> when (o) { 'A' -> return sm + 3 'B' -> return sm 'C' -> return sm + 6 } 'Y' -> when (o) { 'A' -> return sm + 6 'B' -> return sm + 3 'C' -> return sm } 'Z' -> when (o) { 'A' -> return sm 'B' -> return sm + 6 'C' -> return sm + 3 } } return -1 } fun calcScore2(o: Char, m: Char): Int { when (m) { 'X' -> when (o) { 'A' -> return toScore('Z') 'B' -> return toScore('X') 'C' -> return toScore('Y') } 'Y' -> when (o) { 'A' -> return toScore('X') + 3 'B' -> return toScore('Y') + 3 'C' -> return toScore('Z') + 3 } 'Z' -> when (o) { 'A' -> return toScore('Y') + 6 'B' -> return toScore('Z') + 6 'C' -> return toScore('X') + 6 } } return -1 } fun part1(input: List<String>) = input .map { it.split(" ") }.sumOf { calcScore(it.first()[0], it.last()[0]) } fun part2(input: List<String>) = input .map { it.split(" ") }.sumOf { calcScore2(it.first()[0], it.last()[0]) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
2734d9ea429b0099b32c8a4ce3343599b522b321
2,012
aoc-2022
Apache License 2.0
aoc-2023/src/main/kotlin/aoc/aoc3.kts
triathematician
576,590,518
false
{"Kotlin": 615974}
import aoc.AocParser.Companion.parselines import aoc.* import aoc.util.* val testInput = """ 467..114.. ...*...... ..35..633. ......#... 617*...... .....+.58. ..592..... ......755. ...$.*.... .664.598.. """.parselines fun CharGrid.symbols() = findCoords2 { it != '.' && !it.isDigit() } fun CharGrid.numLocs() = indices.flatMap { y -> val search = "[0-9]+".toRegex() search.findAll(this[y]).map { it.value.toInt() to Coord(it.range.first, y) } } // part 1 fun List<String>.part1(): Int { val nums = numLocs() val symbolLocs = symbols().flatMap { it.value } return nums.filter { (1..it.first.toString().length).any { i -> val testLoc = it.second.plus(i - 1, 0) symbolLocs.any { it.adjacentTo(testLoc, diagonal = true) } } }.sumOf { it.first } } // part 2 fun List<String>.part2(): Int { val nums = numLocs() val symbols = symbols()['*']!! return symbols.sumOf { loc -> val numsAdj = nums.filter { (1..it.first.toString().length).any { i -> val testLoc = it.second.plus(i - 1, 0) testLoc.adjacentTo(loc, diagonal = true) } }.map { it.first } if (numsAdj.size == 2) numsAdj[0] * numsAdj[1] else 0 } } // calculate answers val day = 3 val input = getDayInput(day, 2023) val testResult = testInput.part1() val testResult2 = testInput.part2() val answer1 = input.part1().also { it.print } val answer2 = input.part2().also { it.print } // print results AocRunner(day, test = { "$testResult, $testResult2" }, part1 = { answer1 }, part2 = { answer2 } ).run()
0
Kotlin
0
0
7b1b1542c4bdcd4329289c06763ce50db7a75a2d
1,676
advent-of-code
Apache License 2.0
src/main/kotlin/day12/Day12.kt
qnox
575,581,183
false
{"Kotlin": 66677}
package day12 import readInput import java.util.LinkedList fun main() { data class Location(val x: Int, val y: Int) fun findEnd(input: List<String>): Location { for (x in input.indices) { for (y in input[x].indices) { if (input[x][y] == 'E') { return Location(x, y) } } } error("No start found") } fun height(c: Char): Int { return when (c) { 'S' -> 0 'E' -> 'z' - 'a' else -> c - 'a' } } fun solve(input: List<String>, ends: Set<Char>): Int { val q = LinkedList<Location>() q.add(findEnd(input)) var steps = 0 val directions = listOf( 1 to 0, 0 to 1, -1 to 0, 0 to -1 ) val visited = mutableSetOf<Location>() while (q.isNotEmpty()) { var rest = q.size while (rest > 0) { val l = q.removeFirst() if (input[l.x][l.y] in ends) { return steps } directions.forEach { (dx, dy) -> val nx = l.x + dx val ny = l.y + dy if (nx in input.indices && ny in input[nx].indices && height(input[l.x][l.y]) - height(input[nx][ny]) < 2 && visited.add(Location(nx, ny)) ) { q.addLast(Location(nx, ny)) } } rest -= 1 } steps += 1 } error("No solution") } fun part1(input: List<String>): Int { return solve(input, setOf('S')) } fun part2(input: List<String>): Int { return solve(input, setOf('a', 'S')) } val testInput = readInput("day12", "test") val input = readInput("day12", "input") check(part1(testInput) == 31) println(part1(input)) check(part2(testInput) == 29) println(part2(input)) }
0
Kotlin
0
0
727ca335d32000c3de2b750d23248a1364ba03e4
2,099
aoc2022
Apache License 2.0
src/main/kotlin/day7/Day7.kt
mortenberg80
574,042,993
false
{"Kotlin": 50107}
package day7 import day6.Day6 class Day7(input: List<String>) { val commands = parseCommands(listOf(), input) private val pathMap = buildMap() private fun parseCommands(initial: List<Command>, input: List<String>): List<Command> { if (input.isEmpty()) return initial val line = input.first().split(" ") val commandInput = line[1] val tail = input.drop(1) if (commandInput == "cd") return parseCommands(initial + Command.Cd(line[2]), tail) if (commandInput == "ls") { val results = tail.takeWhile { !it.startsWith("$") } return parseCommands(initial + Command.Ls(results), tail.drop(results.size)) } println("Should not reach this..?") return initial } private fun buildMap(): Map<String, Pair<Int, List<String>>> { val resultMap = mutableMapOf<String, Pair<Int, List<String>>>() var currentDir: List<String> = listOf() commands.forEach { when (it) { is Command.Cd -> { currentDir = when (it.path) { "/" -> { listOf() } ".." -> { currentDir.dropLast(1) } else -> { currentDir.plus(it.path) } } } is Command.Ls -> { val currnetPath = computePath(currentDir) val dirs = it.result.filter { c -> c.startsWith("dir") }.map { c -> c.split(" ")[1] }.map { path -> computePath(currentDir + path) } val size = it.result.filter { c -> !c.startsWith("dir") }.map { c -> c.split(" ")[0].toInt() }.sum() resultMap[currnetPath] = Pair(size, dirs) } } } return resultMap } private fun computePath(currentDir: List<String>): String { if (currentDir.isEmpty()) return "/" return "/" + currentDir.joinToString("/") } fun part1(): Int { val scoreMap = scoreMap() return scoreMap.filter { it.second < 100000 }.sumOf { it.second } } private fun scoreMap(): List<Pair<String, Int>> { return pathMap.keys.map { it to computeScore(it) } } fun part2(): Int { val totalSpace = 70000000 val neededSpace = 30000000 val usedSpace = computeScore("/") val availableSpace = totalSpace - usedSpace val toBeDeleted = neededSpace - availableSpace //println("UsedSpace = $usedSpace, toBeDeleted=$toBeDeleted") return scoreMap().map { it.second }.filter { it > toBeDeleted }.minBy { it } } private fun computeScore(path: String): Int { val pathScore = pathMap[path]!! val dirScore = pathScore.first val subdirScore = pathScore.second.sumOf { computeScore(it) } return dirScore.plus(subdirScore) } } sealed class Command { data class Cd(val path: String): Command() data class Ls(val result: List<String>): Command() } fun main() { val testInput = Day6::class.java.getResourceAsStream("/day7_test.txt").bufferedReader().readLines() val input = Day6::class.java.getResourceAsStream("/day7_input.txt").bufferedReader().readLines() val day7Test = Day7(testInput) // println(day7Test.commands) // println(day7Test.buildMap()) println("Part 1 test answer: ${day7Test.part1()}") println("Part 2 test answer: ${day7Test.part2()}") val day7Input = Day7(input) // println(day7Input.commands) // println(day7Input.buildMap()) println("Part 1 answer: ${day7Input.part1()}") println("Part 2 answer: ${day7Input.part2()}") }
0
Kotlin
0
0
b21978e145dae120621e54403b14b81663f93cd8
3,905
adventofcode2022
Apache License 2.0
src/Day05.kt
Soykaa
576,055,206
false
{"Kotlin": 14045}
private fun parseStacks(processedInput: MutableList<List<String>>): List<MutableList<Char>> { val stacksNumber = processedInput.last().last().last().code val stacks: List<MutableList<Char>> = List(stacksNumber) { mutableListOf() } processedInput.forEach { line -> line.forEachIndexed { i, chunk -> run { if (chunk[1].isUpperCase()) stacks[i].add(chunk[1]) } } } return stacks.map { it.reversed().toMutableList() } } private fun transformInput(input: List<String>): Pair<MutableList<List<String>>, MutableList<String>> { val stacksLines = arrayListOf<List<String>>() val cmds = arrayListOf<String>() var counter = 0 for (i in input.indices) { if (input[i].isEmpty()) { counter = i break } stacksLines.add(input[i].chunked(4)) } for (i in counter until input.size) { if (input[i].isNotEmpty()) cmds.add(input[i]) } // println(cmds.size) return Pair(stacksLines, cmds) } private fun getTopElements(parsedStacks: List<List<Char>>): String = parsedStacks.map { it.lastOrNull() ?: "" }.joinToString("") private fun processCommands(input: List<String>, move: (List<MutableList<Char>>, Int, Int, Int) -> Unit): String { val (stacks, cmds) = transformInput(input) val parsedStacks = parseStacks(stacks) cmds.map { cmd -> cmd.split(" ").filter { it.toIntOrNull() != null } } .forEach { move(parsedStacks, it[0].toInt(), it[1].toInt() - 1, it[2].toInt() - 1) } return getTopElements(parsedStacks) } private fun move1(stacks: List<MutableList<Char>>, amount: Int, from: Int, to: Int) = repeat(amount) { stacks[to].add(stacks[from].removeLast()) } private fun move2(stacks: List<MutableList<Char>>, amount: Int, from: Int, to: Int) { stacks[to].addAll(stacks[from].takeLast(amount)) repeat(amount) { stacks[from].removeLast() } } fun main() { fun part1(input: List<String>): String = processCommands(input, ::move1) fun part2(input: List<String>): String = processCommands(input, ::move2) val input = readInput("Day05") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
1e30571c475da4db99e5643933c5341aa6c72c59
2,235
advent-of-kotlin-2022
Apache License 2.0
src/Day12.kt
Kietyo
573,293,671
false
{"Kotlin": 147083}
fun main() { val fn = fun Grid<Char>.(point: MutableIntPoint): List<MutableIntPoint> { val currChar = get(point) val nextChar = when (currChar) { 'S' -> 'a' 'z' -> 'E' else -> currChar + 1 } val nextRange = when (currChar) { 'S' -> 'a'..'a' 'z' -> 'a'..'z' else -> 'a'..(currChar + 1) } val possibleStates = listOf( point.copy2(first = point.first + 1), point.copy2(first = point.first - 1), point.copy2(second = point.second + 1), point.copy2(second = point.second - 1), ) return possibleStates.filter { getOrDefault(it) { '?' }.run { (this == currChar) || this == nextChar || (this in nextRange) } } } fun part1(input: List<String>): Unit { val grid = Grid(input.map { it.toCharArray().toTypedArray() }) println(grid.data.joinToString("\n")) val startPoint: MutableIntPoint = grid.find('S') val endPoint: MutableIntPoint = grid.find('E') val result = grid.bfs(startPoint, fn) grid.forEach { x, y, value, gotNextRow -> if (gotNextRow) { println() print("${y.toString().padStart(3, '0')}: ") } if (value == 'l') { if (result.pointToMinDist.containsKey(x toip y)) { print('X') } else { print('O') } } else { print('O') } } println() println("startPoint: $startPoint, endPoint: $endPoint") println(result.pointToMinDist[endPoint]) } fun part2(input: List<String>): Unit { val grid = Grid(input.map { it.toCharArray().toTypedArray() }) println(grid.data.joinToString("\n")) val startPoint: MutableIntPoint = grid.find('S') val endPoint: MutableIntPoint = grid.find('E') val aPoints = mutableListOf<MutableIntPoint>() grid.forEach { x, y, value, gotNextRow -> if (value == 'a') aPoints.add(x toip y) } val dists = aPoints.map { val result = grid.bfs(it, fn) result.pointToMinDist[endPoint] }.filterNotNull().sorted() println(dists) } val dayString = "day12" // test if implementation meets criteria from the description, like: val testInput = readInput("${dayString}_test") // part1(testInput) // part2(testInput) val input = readInput("${dayString}_input") // part1(input) part2(input) }
0
Kotlin
0
0
dd5deef8fa48011aeb3834efec9a0a1826328f2e
2,702
advent-of-code-2022-kietyo
Apache License 2.0
src/day01/Day01.kt
mahan-ym
572,901,965
false
{"Kotlin": 4240}
package day01 import readInput fun main() { fun getEachElfWithMostCal(input: List<String>): ArrayList<Int> { var recordIndex = 0 val summedCals = arrayListOf<Int>() input.forEachIndexed { index ,record -> if (record == "") { summedCals.add(input.subList(recordIndex,index).sumOf { it.toInt() }) recordIndex = index + 1 } } if (recordIndex == input.size - 1 || recordIndex < input.size - 1) summedCals.add(input.subList(recordIndex,input.size).sumOf { it.toInt() }) return summedCals } fun getElfWithMostCal(input: List<String>): Pair<Int,Int> { val summedCals = getEachElfWithMostCal(input) return summedCals.indexOf(summedCals.max()) + 1 to summedCals.max() } fun getTopThreeElvesWithMostCalSum(input: List<String>): Int { val summedCals = getEachElfWithMostCal(input) summedCals.sortDescending() return summedCals[0] + summedCals[1] + summedCals[2] } val testInput = readInput("Day01_test") check(getElfWithMostCal(testInput).first == 4) check(getTopThreeElvesWithMostCalSum(testInput) == 45000) val input = readInput("day01") val elfWithMostCal = getElfWithMostCal(input) println("${elfWithMostCal.first} with ${elfWithMostCal.second} calories ") val topThreeElvesWithMostCal = getTopThreeElvesWithMostCalSum(input) println(topThreeElvesWithMostCal) }
0
Kotlin
0
0
d09acc419480bcc025d482afae9da9438b87e4eb
1,475
AOC-kotlin-2022
Apache License 2.0
src/main/kotlin/aoc22/Day12.kt
tom-power
573,330,992
false
{"Kotlin": 254717, "Shell": 1026}
package aoc22 import aoc22.Day12Domain.HeightMap import aoc22.Day12Parser.toHeightMap import aoc22.Day12Solution.part1Day12 import aoc22.Day12Solution.part2Day12 import common.Monitoring import common.Space2D.Point import common.Space2D.Parser.toPointToChars import common.Year22 import common.graph.Dijkstra import common.graph.Edge import common.graph.Node object Day12 : Year22 { fun List<String>.part1(): Int = part1Day12() fun List<String>.part2(): Int = part2Day12() } object Day12Solution { fun List<String>.part1Day12(): Int = toHeightMap().run { shortestPath( begin = startPoint, isDestination = { it == endPoint }, canMove = { from, to -> to - from <= 1 } ) } fun List<String>.part2Day12(): Int = toHeightMap().run { shortestPath( begin = endPoint, isDestination = { elevations[it] == 0 }, canMove = { from, to -> from - to <= 1 } ) } } object Day12Domain { data class PointNode( override val value: Point ) : Node<Point> class HeightMap( val elevations: Map<Point, Int>, val startPoint: Point, val endPoint: Point, val monitor: Monitoring.PointMonitor? = null, ) { lateinit var begin: Point lateinit var isDestination: (Point) -> Boolean lateinit var canMove: (Int, Int) -> Boolean fun shortestPath( begin: Point, isDestination: (Point) -> Boolean, canMove: (Int, Int) -> Boolean ): Int { this.begin = begin this.isDestination = isDestination this.canMove = canMove return PointDijkstra() .run { shortestPath().also { monitor?.invoke(shortestPaths.last().first.map { it.value }.toSet()) } } } inner class PointDijkstra : Dijkstra<Point, PointNode>(monitoring = monitor != null) { override val start: () -> PointNode = { PointNode(value = begin) } override val isEnd: (PointNode) -> Boolean = { isDestination(it.value) } override fun next(node: PointNode): List<Edge<Point, PointNode>> = node.value.adjacent() .filter { it in elevations } .filter { canMove(elevations.getValue(node.value), elevations.getValue(it)) } .map { Edge(PointNode(it), 1) } } } } object Day12Parser { private fun Char.toCode(): Int = when (this) { 'S' -> 0 'E' -> 25 else -> this.code - 'a'.code } fun List<String>.toHeightMap(monitor: Monitoring.PointMonitor? = null): HeightMap = toPointToChars().toMap().let { p -> HeightMap( elevations = p.mapValues { it.value.toCode() }, startPoint = p.filterValues { it == 'S' }.keys.first(), endPoint = p.filterValues { it == 'E' }.keys.first(), monitor = monitor ) } }
0
Kotlin
0
0
baccc7ff572540fc7d5551eaa59d6a1466a08f56
3,099
aoc
Apache License 2.0
src/main/kotlin/dev/paulshields/aoc/Day4.kt
Pkshields
433,609,825
false
{"Kotlin": 133840}
/** * Day 4: Giant Squid */ package dev.paulshields.aoc import dev.paulshields.aoc.common.readFileAsString fun main() { println(" ** Day 4: Giant Squid ** \n") val splitFile = readFileAsString("/Day4BingoBoards.txt") .trim() .split("\n\n") val drawnNumbers = splitFile[0] .split(",") .mapNotNull { it.toIntOrNull() } val boards = splitFile .drop(1) .map { BingoBoard(it) } drawnNumbers.first { drawnNumber -> boards.forEach { it.markNumber(drawnNumber) } boards.any { it.bingo() } } val bingoBoardScore = boards.first { it.bingo() }.calculateBoardScore() println("The score of the first board that called bingo is $bingoBoardScore") val lastWinningBoard = splitFile .drop(1) .map { RiggedBingoBoard(it) } .onEach { it.checkAllDrawnNumbers(drawnNumbers) } .maxByOrNull { it.indexWhenBingo } println("The score of the board that would win last is ${lastWinningBoard?.calculateBoardScore()}") } open class BingoBoard(rawBoard: String) { private var board = rawBoard .split("\n") .map { it.trim() .replace(" ", " ") .split(" ") .associate { Pair(it.toInt(), false) } } private var lastCalledNumber = -1 fun markNumber(number: Int) { lastCalledNumber = number board = board.map { it.mapValues { it.key == number || it.value } } } fun bingo(): Boolean { val rowCheck = board.any { it.all { it.value } } val columnCheck = board .flatMap { it.values.mapIndexed { index, item -> Pair(index, item) } } .groupBy(keySelector = { it.first }, valueTransform = { it.second }) .any { it.value.all { it } } return rowCheck || columnCheck } fun calculateBoardScore() = board.flatMap { it.filter { !it.value }.keys }.sum() * lastCalledNumber } class RiggedBingoBoard(rawBoard: String) : BingoBoard(rawBoard) { var indexWhenBingo = -1 private set fun checkAllDrawnNumbers(drawnNumbers: List<Int>) { indexWhenBingo = 0 do { markNumber(drawnNumbers[indexWhenBingo]) } while (!bingo() && drawnNumbers.size > ++indexWhenBingo) } }
0
Kotlin
0
0
e3533f62e164ad72ec18248487fe9e44ab3cbfc2
2,308
AdventOfCode2021
MIT License
src/AoC10.kt
Pi143
317,631,443
false
null
import java.io.File fun main() { println("Starting Day 10 A Test 1") calculateDay10PartA("Input/2020_Day10_A_Test1") println("Starting Day 10 A Real") calculateDay10PartA("Input/2020_Day10_A") println("Starting Day 10 B Test 1") calculateDay10PartB("Input/2020_Day10_A_Test1") println("Starting Day 10 B Real") calculateDay10PartB("Input/2020_Day10_A") } fun calculateDay10PartA(file: String): Int { val Day10Data = readDay10Data(file) val deviceJolt = Day10Data.max()!! + 3 val chargingJolt = 0 val sortedJolts = (Day10Data + chargingJolt + deviceJolt).sorted() val jumpMap = mutableMapOf(1 to 0, 2 to 0, 3 to 0) for (i in 1 until sortedJolts.size) { val jumpSize = sortedJolts[i] - sortedJolts[i - 1] jumpMap[jumpSize] = jumpMap[jumpSize]!! + 1 } println(jumpMap) println(jumpMap[1]!! * jumpMap[3]!!) return jumpMap[1]!! * jumpMap[3]!! } fun calculateDay10PartB(file: String): Long { val Day10Data = readDay10Data(file) val deviceJolt = Day10Data.max()!! + 3 val chargingJolt = 0 val sortedJolts = (Day10Data + chargingJolt + deviceJolt).sorted() var amountValidConfigs:Long = 1 val jumpSizeLists = mutableListOf<List<Int>>() var currentJumpSizeList = mutableListOf<Int>() for (i in 1 until sortedJolts.size) { when (val jumpSize = sortedJolts[i] - sortedJolts[i - 1]) { 1, 2 -> currentJumpSizeList.add(jumpSize) 3 -> { if (currentJumpSizeList.isNotEmpty()) { jumpSizeLists.add(currentJumpSizeList) } currentJumpSizeList = mutableListOf() } else -> throw Exception("Jumpsize to high") } } for (currentList in jumpSizeLists) { //split in groups var amountValidSublists = 0 val possibleSublists = createSublists(currentList) for (possibleSublistCombination in possibleSublists) { var isValid = true for (partOfSublist in possibleSublistCombination) { if (partOfSublist.sum() > 3) { isValid = false } } if (isValid) { amountValidSublists++ } } amountValidConfigs *= amountValidSublists } println("$amountValidConfigs are valid") return amountValidConfigs } fun createSublists(currentList: List<Int>): List<List<List<Int>>> { when (currentList.size) { 0 -> throw Exception("List is Empty") 1 -> return listOf(listOf(currentList)) 2 -> return listOf(listOf(currentList), listOf(listOf(currentList[0]), listOf(currentList[1]))) 3 -> return listOf( listOf(currentList), listOf(listOf(currentList[0]), listOf(currentList[1]), listOf(currentList[2])), listOf(listOf(currentList[0], currentList[1]), listOf(currentList[2])), listOf(listOf(currentList[0]), listOf(currentList[1], currentList[2])) ) else -> { var newSublistList: MutableList<List<List<Int>>> = mutableListOf() val sublist1 = createSublists(currentList.subList(1, currentList.size)) for (listConfig in sublist1) { newSublistList.add((listConfig + listOf(listOf(currentList[0])))) } val sublist2 = createSublists(currentList.subList(2, currentList.size)) for (listConfig in sublist2) { newSublistList.add((listConfig + listOf(listOf(currentList[0], currentList[1])))) } val sublist3 = createSublists(currentList.subList(3, currentList.size)) for (listConfig in sublist3) { newSublistList.add((listConfig + listOf(listOf(currentList[0], currentList[1], currentList[2])))) } return newSublistList } } } fun readDay10Data(input: String): MutableList<Int> { val joltList: MutableList<Int> = ArrayList() File(localdir + input).forEachLine { joltList.add(it.toInt()) } return joltList }
0
Kotlin
0
1
fa21b7f0bd284319e60f964a48a60e1611ccd2c3
4,111
AdventOfCode2020
MIT License
src/day05/Day05.kt
zypus
573,178,215
false
{"Kotlin": 33417, "Shell": 3190}
package day05 import AoCTask import java.util.Stack // https://adventofcode.com/2022/day/5 data class Instruction(val from: Int, val to: Int, val count: Int) { companion object { fun fromString(string: String): Instruction { val split = string.split(" ") return Instruction( from = split[3].toInt() - 1, to = split[5].toInt() - 1, count = split[1].toInt(), ) } } } private fun extractInstructions(input: List<String>): List<Instruction> { val instructions = input .dropWhile { it != "" } .drop(1) return instructions.map { Instruction.fromString(it) } } private fun extractStacks(input: List<String>): List<Stack<Char>> { val crateStacks = input.takeWhile { it != "" } val stackIds = crateStacks.last().trim().split("\\s+".toRegex()).map { it.toInt() } val stacks = stackIds.map { Stack<Char>() } crateStacks.reversed().drop(1).forEach { stackLevel -> stackLevel.windowed(3, step = 4) .map { it.firstOrNull { c -> c in 'A'..'Z' } } .forEachIndexed { index, crate -> if (crate != null) { stacks[index].push(crate) } } } return stacks } fun stackToString(stack: Stack<Char>): String { return stack.joinToString("] [", prefix = "[", postfix = "]") } private fun printStacks(stacks: List<Stack<Char>>) { stacks.forEachIndexed { index, stack -> println("$index ${stackToString(stack)}") } } private fun getStringFromTopCrates(stacks: List<Stack<Char>>) = stacks.joinToString(separator = "") { it.peek().toString() } fun part1(input: List<String>): String { val stacks = extractStacks(input) val instructions = extractInstructions(input) instructions.forEach { instruction -> val (from, to, count) = instruction repeat(count) { stacks[to].push(stacks[from].pop()) } } val result = getStringFromTopCrates(stacks) return result } fun part2(input: List<String>): String { val stacks = extractStacks(input) val instructions = extractInstructions(input) instructions.forEach { instruction -> val (from, to, count) = instruction (1..count) .map { stacks[from].pop() }.reversed() .forEach { crate -> stacks[to].push(crate) } } val result = getStringFromTopCrates(stacks) return result } fun main() = AoCTask("day05").run { // test if implementation meets criteria from the description, like: check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
f37ed8e9ff028e736e4c205aef5ddace4dc73bfc
2,831
aoc-2022
Apache License 2.0
src/Day12.kt
karloti
573,006,513
false
{"Kotlin": 25606}
import java.util.ArrayDeque val valueByChar: Map<Char, Int> = "SabcdefghijklmnopqrstuvwxyzE".withIndex().associate { (k, v) -> v to k } val directions = listOf(-1 to 0, 1 to 0, 0 to -1, 0 to +1) data class Point(val h: Int, val v: Int, val c: Char, var d: Int? = null) fun List<String>.toPoints(): List<List<Point>> = mapIndexed { v, s -> s.mapIndexed { h, c -> Point(h, v, c) } } fun Point.adjPoints(points: List<List<Point>>, compare: (Int, Int) -> Boolean): List<Point> = directions .mapNotNull { (v1, h1) -> points.getOrNull(v + v1)?.getOrNull(h + h1) } .filter { compare(valueByChar[c]!!, valueByChar[it.c]!!) } fun List<String>.solution(startChar: Char, endChar: Char, compare: (Int, Int) -> Boolean): Int? { val points: List<List<Point>> = toPoints() val startPoint: Point = points.flatten().first { it.c == startChar } val queue = ArrayDeque<Point>().apply { add(startPoint.apply { d = 0 }) } while (queue.isNotEmpty()) queue.removeFirst().apply { if (c == endChar) return d adjPoints(points, compare).filter { it.d == null }.forEach { it.d = d!! + 1; queue.addLast(it) } } return null } fun main() { readInput("Day12").solution('S', 'E') { i1, i2 -> i2 in 0..i1 + 1 }.let(::println) readInput("Day12").solution('E', 'a') { i1, i2 -> i1 in 0..i2 + 1 }.let(::println) }
0
Kotlin
1
2
39ac1df5542d9cb07a2f2d3448066e6e8896fdc1
1,338
advent-of-code-2022-kotlin
Apache License 2.0
src/Day02.kt
markhor1999
574,354,173
false
{"Kotlin": 4937}
fun main() { fun Pair<String, String>.getRoundScore(): Int { return when { //Rock & Rock -> Draw first == "A" && second == "X" -> 1 + 3 //Rock & Paper -> Win first == "A" && second == "Y" -> 2 + 6 //Rock & Scissors -> Loss first == "A" && second == "Z" -> 3 + 0 //Paper & Rock -> Loss first == "B" && second == "X" -> 1 + 0 //Paper & Paper -> Draw first == "B" && second == "Y" -> 2 + 3 //Paper & Scissors -> Win first == "B" && second == "Z" -> 3 + 6 //Scissors & Rock -> Win first == "C" && second == "X" -> 1 + 6 //Scissors & Paper -> Loss first == "C" && second == "Y" -> 2 + 0 //Scissors & Scissors -> Draw first == "C" && second == "Z" -> 3 + 3 else -> 0 } } fun Pair<String, String>.getNewMove(): Pair<String, String> { return when (second) { "X" -> { first to when (first) { "A" -> "Z" "B" -> "X" else -> "Y" } } "Y" -> first to when (first) { "A" -> "X" "B" -> "Y" else -> "Z" } "Z" -> first to when (first) { "A" -> "Y" "B" -> "Z" else -> "X" } else -> this } } fun List<String>.getInputInPairs(): List<Pair<String, String>> = map { round -> val roundValues = round.split(" ") roundValues.first() to roundValues.last() } fun part1(input: List<String>): Int { val data = input.getInputInPairs() return data.sumOf { it.getRoundScore() } } fun part2(input: List<String>): Int { val data = input.getInputInPairs() return data.sumOf { it.getNewMove().getRoundScore() } } val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
800f218ff12908ebd885c3f475793c6be2d7fd7d
2,110
kotlin-advent-of-code-2022
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/MinimumEffortPath.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import java.util.PriorityQueue import kotlin.math.abs /** * 1631. Path With Minimum Effort * @see <a href="https://leetcode.com/problems/path-with-minimum-effort">Source</a> */ fun interface MinimumEffortPath { operator fun invoke(heights: Array<IntArray>): Int } /** * Solution 1: Dijikstra */ class MinimumEffortPathDijikstra : MinimumEffortPath { private val dir = intArrayOf(0, 1, 0, -1, 0) override fun invoke(heights: Array<IntArray>): Int { val m = heights.size val n = heights[0].size val dist = Array(m) { IntArray(n) { Int.MAX_VALUE } } val minHeap = PriorityQueue(compareBy<IntArray> { it[0] }) minHeap.offer(intArrayOf(0, 0, 0)) // distance, row, col dist[0][0] = 0 while (minHeap.isNotEmpty()) { val top = minHeap.poll() val d = top[0] val r = top[1] val c = top[2] if (d > dist[r][c]) continue // this is an outdated version -> skip it if (r == m - 1 && c == n - 1) return d // Reach to bottom right for (i in 0 until 4) { val nr = r + dir[i] val nc = c + dir[i + 1] if (nr in 0 until m && nc >= 0 && nc < n) { val newDist = maxOf(d, abs(heights[nr][nc] - heights[r][c])) if (dist[nr][nc] > newDist) { dist[nr][nc] = newDist minHeap.offer(intArrayOf(dist[nr][nc], nr, nc)) } } } } return 0 // Unreachable code, Kotlin does not require an explicit return here. } } /** * Solution 2: Binary Search + DFS */ class MinimumEffortPathDFS : MinimumEffortPath { private val dir = intArrayOf(0, 1, 0, -1, 0) companion object { private const val UPPER_BOUND = 1000000 } override fun invoke(heights: Array<IntArray>): Int { val m = heights.size val n = heights[0].size fun dfs(r: Int, c: Int, visited: Array<BooleanArray>, threshold: Int): Boolean { if (r == m - 1 && c == n - 1) return true // Reach destination visited[r][c] = true for (i in 0 until 4) { val nr = r + dir[i] val nc = c + dir[i + 1] if (nr < 0 || nr == m || nc < 0 || nc == n || visited[nr][nc]) continue if (abs(heights[nr][nc] - heights[r][c]) <= threshold && dfs(nr, nc, visited, threshold)) { return true } } return false } fun canReachDestination(threshold: Int): Boolean { val visited = Array(m) { BooleanArray(n) } return dfs(0, 0, visited, threshold) } var left = 0 var ans = 0 var right = UPPER_BOUND // Set an upper bound while (left <= right) { val mid = left + (right - left) / 2 if (canReachDestination(mid)) { right = mid - 1 // Try to find a better result on the left side ans = mid } else { left = mid + 1 } } return ans } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,833
kotlab
Apache License 2.0
src/Day07.kt
ThijsBoehme
572,628,902
false
{"Kotlin": 16547}
/* Followed along with the Kotlin by JetBrains livestream, with some personal adjustments */ fun main() { lateinit var sizes: MutableList<Int> data class Tree(val name: String, var parent: Tree? = null) { var size: Int = 0 val children: MutableList<Tree> = mutableListOf() } fun recursiveSizeOfDirectory(directory: Tree): Int { val size = directory.size + directory.children.sumOf { recursiveSizeOfDirectory(it) } sizes.add(size) return size } fun parseToTree(input: List<String>): Tree { val parsedInput = input.map { it.replace("$ ", "") } .filter { it != "ls" } val root = Tree("/") var currentDirectory = root parsedInput.forEach { line -> val (command, argument) = line.split(" ") when (command) { "cd" -> currentDirectory = when (argument) { "/" -> root ".." -> currentDirectory.parent!! else -> currentDirectory.children.first { it.name == argument } } "dir" -> currentDirectory.children.add(Tree(argument, currentDirectory)) else -> currentDirectory.size += command.toInt() } } return root } fun part1(input: List<String>): Int { val root = parseToTree(input) sizes = mutableListOf() recursiveSizeOfDirectory(root) return sizes.filter { it <= 100_000 }.sum() } fun part2(input: List<String>): Int { val root = parseToTree(input) sizes = mutableListOf() recursiveSizeOfDirectory(root) return sizes.filter { it >= 30_000_000 - (70_000_000 - sizes.max()) }.min() } // 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
0
707e96ec77972145fd050f5c6de352cb92c55937
2,036
Advent-of-Code-2022
Apache License 2.0
src/Day10.kt
sebokopter
570,715,585
false
{"Kotlin": 38263}
fun main() { fun callStack(inputs: List<String>): List<Pair<String, Int>> = inputs.map { input -> val line = input.split(" ") line[0] to line.getOrElse(1) { "0" }.toInt() } fun execute(callStack: List<Pair<String, Int>>): List<Pair<Int, Int>> = callStack.fold(mutableListOf(1 to 1)) { history, current -> val (cmd, arg) = current val (cycle, register) = history.last() val currentExecution = mutableListOf(cycle + 1 to register) if (cmd == "addx") currentExecution.add(cycle + 2 to register + arg) history + currentExecution } fun part1(input: List<String>): Int { //cycle to register val callStack = callStack(input) val executionHistory = execute(callStack) return executionHistory.sumOf { (cycle, register) -> if (cycle < 20) return@sumOf 0 if ((cycle - 20) % 40 != 0) return@sumOf 0 cycle * register } } fun part2(input: List<String>): String { val callStack = callStack(input) val executionHistory = execute(callStack) val crt = MutableList<String>(240) { "." } executionHistory.forEach { (cycle, register) -> println("cycle: $cycle, register: $register") val currentCrtIndex = cycle - 1 if (currentCrtIndex % 40 in register - 1..register + 1) { crt[currentCrtIndex] = "#" } } return crt.chunked(40) { it.joinToString("") }.joinToString("\n") } val testInput2 = readInput("Day10_test2") val testInput1 = readInput("Day10_test1") val testInput = readInput("Day10_test") println("part1(testInput): " + part1(testInput)) println("part2(testInput): ") println(part2(testInput)) check(part1(testInput) == 13140) // check(part2(testInput) == 24000) val input = readInput("Day10") println("part1(input): " + part1(input)) println("part2(input): ") println(part2(input)) }
0
Kotlin
0
0
bb2b689f48063d7a1b6892fc1807587f7050b9db
2,031
advent-of-code-2022
Apache License 2.0
advent-of-code-2022/src/Day14.kt
osipxd
572,825,805
false
{"Kotlin": 141640, "Shell": 4083, "Scala": 693}
fun main() { val testInput = readInput("Day14_test") val input = readInput("Day14") "Part 1" { part1(testInput) shouldBe 24 answer(part1(input)) } "Part 2" { part2(testInput) shouldBe 93 answer(part2(input)) } } private fun part1(input: List<List<List<Int>>>) = simulateSandFalling(input, hasFloor = false) private fun part2(input: List<List<List<Int>>>) = simulateSandFalling(input, hasFloor = true) private const val AIR = '.' private const val ROCK = '#' private const val SAND = 'o' private const val SAND_SOURCE_COL = 500 private const val WIDTH = SAND_SOURCE_COL * 2 private const val HEIGHT = WIDTH / 2 private fun simulateSandFalling(structures: List<List<List<Int>>>, hasFloor: Boolean): Int { val cave = Array(HEIGHT) { Array(WIDTH) { AIR } } // Add rock structures from the input to the cave var lastRow = 0 for (structure in structures) { structure // Remember last row, it will be helpful later .onEach { lastRow = maxOf(lastRow, it.row) } .windowed(2) { (from, to) -> // Either row, or column will be equal, so we just draw a line, not a square for (row in (from.row..to.row).fixOrder()) { for (col in (from.col..to.col).fixOrder()) { cave[row][col] = ROCK } } } } // Add floor if we need it if (hasFloor) { lastRow += 2 for (col in 0 until WIDTH) cave[lastRow][col] = ROCK } // Here we will count how many sand blocks have fallen already var sandBlocks = 0 // Simulate sand falling block-by-block var row = 0 var col = SAND_SOURCE_COL while (row < lastRow && cave[row][col] == AIR) { when { cave[row + 1][col] == AIR -> row++ // Move down cave[row + 1][col - 1] == AIR -> { row++; col-- } // Move down-left cave[row + 1][col + 1] == AIR -> { row++; col++ } // Move down-right // It is impossible to move down, so just place sand block here and stop falling else -> { sandBlocks++ cave[row][col] = SAND // Reset row and column to spawn next sand block row = 0 col = SAND_SOURCE_COL } } } return sandBlocks } /** Returns [this] range in right order. */ private fun IntRange.fixOrder() = if (start > endInclusive) endInclusive..start else this // "498,4 -> 498,6 -> 496,6" => [[498, 4], [498, 6], [496, 6]] private fun readInput(name: String) = readLines(name).map { line -> line.split(" -> ").map { it.splitInts(",") } } // Extensions to hide 0 and 1 indices from code private val List<Int>.col: Int get() = get(0) private val List<Int>.row: Int get() = get(1)
0
Kotlin
0
5
6a67946122abb759fddf33dae408db662213a072
2,882
advent-of-code
Apache License 2.0
src/Day12.kt
PascalHonegger
573,052,507
false
{"Kotlin": 66208}
fun main() { class Node(val character: Char, val index: Int, val neighbors: MutableList<Node> = mutableListOf()) { val height = when (character) { 'S' -> 'a' - 'a' 'E' -> 'z' - 'a' else -> character - 'a' } override fun toString() = "[$index]: $character" } fun findShortestPath(input: List<String>, isStart: (c: Char) -> Boolean): Int? { lateinit var end: Node val distanceFromStart = mutableListOf<Int>() val nodes = mutableListOf<Node>() for (row in input) { for (cell in row) { val node = Node(character = cell, index = nodes.size) nodes += node val isEnd = cell == 'E' distanceFromStart += if (isStart(cell)) 0 else Int.MAX_VALUE if (isEnd) { end = node } } } val numRows = input.size val rowLength = input.first().length nodes.forEachIndexed { index, node -> fun addAsNeighborIfReachable(neighbor: Node?) { neighbor?.let { if ((it.height - 1) <= node.height) { node.neighbors += it } } } val row = index / rowLength val col = index % rowLength if (col != 0) addAsNeighborIfReachable(nodes[index - 1]) if (col != rowLength - 1) addAsNeighborIfReachable(nodes[index + 1]) if (row != 0) addAsNeighborIfReachable(nodes[index - rowLength]) if (row != numRows - 1) addAsNeighborIfReachable(nodes[index + rowLength]) } val workingSet = nodes.toMutableList() while (workingSet.isNotEmpty()) { val min = workingSet.minBy { distanceFromStart[it.index] } workingSet.remove(min) val newDistance = distanceFromStart[min.index] + 1 if (newDistance < 0) { // No path to node found, early exit return null } for (neighbor in min.neighbors) { if (distanceFromStart[neighbor.index] > newDistance) { distanceFromStart[neighbor.index] = newDistance if (neighbor == end) { return newDistance } } } } return null } fun part1(input: List<String>): Int { return findShortestPath(input) { it == 'S' } ?: error("No path found") } fun part2(input: List<String>): Int { return findShortestPath(input) { it == 'S' || it == 'a' } ?: error("No path found") } val testInput = readInput("Day12_test") check(part1(testInput) == 31) check(part2(testInput) == 29) val input = readInput("Day12") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
2215ea22a87912012cf2b3e2da600a65b2ad55fc
2,920
advent-of-code-2022
Apache License 2.0
src/main/kotlin/Packets.kt
alebedev
573,733,821
false
{"Kotlin": 82424}
fun main() = Packets.solve() private object Packets { fun solve() { val input = readInput().toMutableList() val dividers = setOf( Lst(listOf(Lst(listOf(Num(2))))), Lst(listOf(Lst(listOf(Num(6))))) ) input.addAll(dividers) val sorted = input.sorted() println("Problem 2: ${(sorted.indexOf(dividers.first()) + 1) * (sorted.indexOf(dividers.last()) + 1)}") } private fun readInput(): List<Item> { val items = mutableListOf<Item>() generateSequence(::readLine).forEach { when { !it.isEmpty() -> { items.add(parseItem(it)) } } } return items } private fun parseItem(line: String): Item { fun extractNums(string: String): List<Num> = string.split(",").map { it.toIntOrNull(10) }.filterNotNull().map { Num(it) } fun parseLst(): Lst { val values = mutableListOf<MutableList<Item>>() val indices = mutableListOf<Int>() var lastGroupClose = 0 for (i in line.indices) { when (line[i]) { '[' -> { if (!indices.isEmpty()) { val substr = line.substring((indices.last() + 1) until i) values.last().addAll(extractNums(substr)) } indices.add(i) values.add(mutableListOf()) } ']' -> { val from = indices.removeLast() val items = values.removeLast() // Non-empty list val substr = line.substring( (maxOf(from, lastGroupClose) + 1) until i ) items.addAll(extractNums(substr)) lastGroupClose = i if (values.isEmpty()) { // println("Parsed $items") return Lst(items) } else { values.last().add(Lst(items)) } } else -> continue } } throw Error("Did not terminate properly") } return when (line.first()) { '[' -> parseLst() else -> Num(line.toInt(10)) } } private sealed interface Item : Comparable<Item> private data class Num(val value: Int) : Item { override fun compareTo(other: Item): Int { return when (other) { is Num -> value.compareTo(other.value) is Lst -> Lst(listOf(this)).compareTo(other) } } } private data class Lst(val value: List<Item>) : Item { override fun compareTo(other: Item): Int { return when (other) { is Num -> compareTo(Lst(listOf(other))) is Lst -> { for (i in value.indices) { if (i >= other.value.size) { return 1 } val cmp = value[i].compareTo(other.value[i]) if (cmp != 0) { return cmp } } return value.size.compareTo(other.value.size) } } } } }
0
Kotlin
0
0
d6ba46bc414c6a55a1093f46a6f97510df399cd1
3,569
aoc2022
MIT License
src/questions/InsertInterval.kt
realpacific
234,499,820
false
null
package questions import _utils.UseCommentAsDocumentation import utils.assertIterableSame import java.util.* /** * You are given an array of non-overlapping intervals `intervals` where `intervals[i] = [starti, endi]` * represent the start and the end of the ith interval and intervals is sorted in ascending order by `starti`. * You are also given an interval `newInterval = [start, end]` that represents the start and end of another interval. * * Insert `newInterval` into `intervals` such that `intervals` is still sorted in ascending order by `starti` and * `intervals` still does not have any overlapping intervals (merge overlapping intervals if necessary). * Return `intervals` after the insertion. * * [Source](https://leetcode.com/problems/insert-interval/) */ @UseCommentAsDocumentation private fun insert(intervals: Array<IntArray>, newInterval: IntArray): Array<IntArray> { if (intervals.isEmpty()) { return arrayOf(newInterval) } fun hasOverlap(current: IntArray, intervalInHand: IntArray): Boolean { val range1 = current.first()..current.last() val range2 = intervalInHand.first()..intervalInHand.last() return intervalInHand[0] in range1 || intervalInHand[1] in range1 || current[0] in range2 || current[1] in range2 } fun isSelfInBetweenPrevAndCurrent(prev: IntArray, current: IntArray, self: IntArray): Boolean { return self.first() > prev.last() && self.last() < current.first() } fun isLessThanFirst(): Boolean { return newInterval.last() < intervals.first().last() } fun isHigherThanLast(): Boolean { return newInterval.first() > intervals.last().last() } fun merge(vararg _intervals: IntArray): IntArray { return intArrayOf(_intervals.map { it[0] }.minOrNull()!!, _intervals.map { it[1] }.maxOrNull()!!) } val result = arrayListOf<IntArray>() fun getLatestAddedElem(): IntArray { return result.last() } // check if whether [newInterval] should be inserted before [intervals] i.e. no overlaps with the first if (isLessThanFirst() && !hasOverlap(intervals.first(), newInterval)) { result.add(newInterval) result.addAll(intervals) return result.toTypedArray() } // check if whether [newInterval] should be inserted after [intervals] i.e. no overlaps with the last if (isHigherThanLast() && !hasOverlap(intervals.last(), newInterval)) { result.addAll(intervals) result.add(newInterval) return result.toTypedArray() } // add first interval immediately // the latest value of [result] is what we will be merging with [newInterval] result.add(intervals.first()) // loop till the size not the index as it might be required to merge [newIntervals] with the last element for (i in 1..intervals.size) { // [newInterval] has overlap with [result]'s latest so merge them and replace if (hasOverlap(getLatestAddedElem(), newInterval)) { val latestAddedInterval = result.removeAt(result.lastIndex) // remove result.add(merge(latestAddedInterval, newInterval)) // merge and add } // now do same for the [current] val current = intervals.getOrNull(i) if (current != null) { // since we are looping till size if (hasOverlap(current, getLatestAddedElem())) { // [current] overlaps with the [result] so merge them val latestAddedInterval = result.removeAt(result.lastIndex) result.add(merge(latestAddedInterval, current)) } else { // [current] doesn't require merging so, it should be added to [result] // However, it is possible that the [newInterval] lies in between [current] & [result] WITHOUT overlaps // // In this case, the [newInterval] is added as it is to the final [result] and then [current] is added if (isSelfInBetweenPrevAndCurrent(prev = getLatestAddedElem(), current = current, self = newInterval)) { result.add(newInterval) } result.add(current) } } } return result.toTypedArray() } fun main() { assertIterableSame( actual = insert( intervals = arrayOf(intArrayOf(3, 5), intArrayOf(12, 15)), newInterval = intArrayOf(6, 6) ).toList(), expected = arrayOf(intArrayOf(3, 5), intArrayOf(6, 6), intArrayOf(12, 15)).toList() ) assertIterableSame( actual = insert( intervals = arrayOf(intArrayOf(1, 2)), newInterval = intArrayOf(2, 7) ).toList(), expected = arrayOf(intArrayOf(1, 7)).toList() ) assertIterableSame( actual = insert( intervals = arrayOf(intArrayOf(1, 5)), newInterval = intArrayOf(1, 7) ).toList(), expected = arrayOf(intArrayOf(1, 7)).toList() ) assertIterableSame( actual = insert( intervals = arrayOf(intArrayOf(1, 5)), newInterval = intArrayOf(2, 7) ).toList(), expected = arrayOf(intArrayOf(1, 7)).toList() ) assertIterableSame( actual = insert( intervals = arrayOf(intArrayOf(1, 3), intArrayOf(6, 9)), newInterval = intArrayOf(2, 5) ).toList(), expected = arrayOf(intArrayOf(1, 5), intArrayOf(6, 9)).toList() ) assertIterableSame( actual = insert( intervals = arrayOf( intArrayOf(1, 2), intArrayOf(3, 5), intArrayOf(6, 7), intArrayOf(8, 10), intArrayOf(12, 16) ), newInterval = intArrayOf(4, 8) ).toList(), expected = arrayOf(intArrayOf(1, 2), intArrayOf(3, 10), intArrayOf(12, 16)).toList() ) assertIterableSame( actual = insert( intervals = arrayOf(intArrayOf(3, 5)), newInterval = intArrayOf(1, 2) ).toList(), expected = arrayOf(intArrayOf(1, 2), intArrayOf(3, 5)).toList() ) assertIterableSame( actual = insert( intervals = arrayOf(intArrayOf(3, 5)), newInterval = intArrayOf(3, 5) ).toList(), expected = arrayOf(intArrayOf(3, 5)).toList() ) assertIterableSame( actual = insert( intervals = arrayOf(intArrayOf(1, 5)), newInterval = intArrayOf(2, 3) ).toList(), expected = arrayOf(intArrayOf(1, 5)).toList() ) assertIterableSame( actual = insert( intervals = arrayOf(intArrayOf(1, 5)), newInterval = intArrayOf(6, 8) ).toList(), expected = arrayOf(intArrayOf(1, 5), intArrayOf(6, 8)).toList() ) }
4
Kotlin
5
93
22eef528ef1bea9b9831178b64ff2f5b1f61a51f
6,866
algorithms
MIT License
src/Day04.kt
EnyediPeti
573,882,116
false
{"Kotlin": 8717}
fun main() { fun part1(input: List<String>): Int { return input.sumOf { pairString -> val assignment = getAssignments(pairString) val first = assignment[0] val second = assignment[1] val firstRange = getRange(first) val secondRange = getRange(second) if (firstRange.contains(secondRange.first) && firstRange.contains(secondRange.last) || secondRange.contains(firstRange.first) && secondRange.contains(firstRange.last) ) { 1 as Int } else 0 as Int } } fun part2(input: List<String>): Int { return input.sumOf { pairString -> val assignment = getAssignments(pairString) val first = assignment[0] val second = assignment[1] val firstRange = getRange(first) val secondRange = getRange(second) if (firstRange.contains(secondRange.first) || firstRange.contains(secondRange.last) || secondRange.contains(firstRange.first) || secondRange.contains(firstRange.last) ) { 1 as Int } else 0 as Int } } // 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)) } fun getAssignments(pairString: String): List<String> { return pairString.split(',') } fun getRange(rangeString: String): IntRange { val start = rangeString.takeWhile { it != '-' } val end = rangeString.takeLastWhile { it != '-' } return start.toInt()..end.toInt() }
0
Kotlin
0
0
845ef2275540a6454a97a9e4c71f239a5f2dc295
1,756
AOC2022
Apache License 2.0
src/main/kotlin/aoc23/Day14.kt
tahlers
725,424,936
false
{"Kotlin": 65626}
package aoc23 import io.vavr.collection.LinkedHashMap import kotlin.math.min object Day14 { data class Pos(val x: Int, val y: Int) data class MirrorMap(val maxX: Int, val maxY: Int, val rocks: Set<Pos>, val cubes: Set<Pos>) { fun turn(): MirrorMap { val turnedRocks = rocks.map { Pos(it.y, maxX + 1 - it.x) } val turnedCubes = cubes.map { Pos(it.y, maxX + 1 - it.x) } return MirrorMap(maxY, maxX, turnedRocks.toSet(), turnedCubes.toSet()) } fun load(): Int = rocks.sumOf { it.y } } fun calculateRockWeight(input: String): Int { val mirrorMap = parseMap(input) val tilted = tiltNorth(mirrorMap) return tilted.load() } fun calculateRockWeightCycles(input: String, cycles: Int): Int { val mirrorMap = parseMap(input) val target = runCycles(0, mirrorMap, LinkedHashMap.empty(), cycles) val load = target.rocks.map { it.y } return load.sum() } private tailrec fun runCycles( currentCount: Int, mirrorMap: MirrorMap, visited: LinkedHashMap<MirrorMap, Int> = LinkedHashMap.empty(), targetCount: Int ): MirrorMap { if (currentCount == targetCount) return mirrorMap val newCount = currentCount + 1 val newMirrorMap = doCycle(mirrorMap) val foundOption = visited.get(newMirrorMap) if (foundOption.isEmpty) { return runCycles(newCount, newMirrorMap, visited.put(newMirrorMap, newCount), targetCount) } else { val cycleStart = foundOption.get() println("cycle detected from $cycleStart to $newCount") val offset = (targetCount - newCount) % (newCount - cycleStart) val final = visited.toSet().first { it._2 == cycleStart + offset }._1 return final } } private fun doCycle(mirrorMap: MirrorMap): MirrorMap { val north = tiltNorth(mirrorMap).turn()//.also { printMap(it.turn().turn().turn(), "after north") } val west = tiltNorth(north).turn()//.also { printMap(it.turn().turn(), "after west") } val south = tiltNorth(west).turn()//.also { printMap(it.turn(), "after south") } val east = tiltNorth(south).turn()//.also { printMap(it, "after east") } return east } private fun tiltNorth(mirrorMap: MirrorMap): MirrorMap { val newRockPos = mirrorMap.rocks.map { targetPos(it, mirrorMap) } return MirrorMap(mirrorMap.maxX, mirrorMap.maxY, newRockPos.toSet(), mirrorMap.cubes)//.also { printMap(it) } } private fun targetPos(rockPos: Pos, mirrorMap: MirrorMap): Pos { val cubeBoundary = mirrorMap.cubes .filter { it.x == rockPos.x && it.y > rockPos.y } .minOfOrNull { it.y - 1 } ?: (mirrorMap.maxY) val boundary = min(mirrorMap.maxY, cubeBoundary) val otherRocks = mirrorMap.rocks.count { it.x == rockPos.x && it.y > rockPos.y && it.y <= boundary } return Pos(rockPos.x, boundary - otherRocks) } private fun parseMap(input: String): MirrorMap { val lines = input.trim().lines().reversed() val maxY = lines.size val maxX = lines.first().length val positions = lines.flatMapIndexed { y, line -> line.mapIndexedNotNull { x, c -> if (c in "O#") { c to Pos(x + 1, y + 1) } else null } } val (rocks, cubes) = positions.partition { it.first == 'O' } return MirrorMap(maxX, maxY, rocks.map { it.second }.toSet(), cubes.map { it.second }.toSet()) } private fun printMap(mirrorMap: MirrorMap, label: String = "") { if (label.isNotBlank()) println("$label:") (mirrorMap.maxY downTo 1).forEach { y -> (1..mirrorMap.maxX).forEach { x -> val pos = Pos(x, y) when (pos) { in mirrorMap.rocks -> { print('O') } in mirrorMap.cubes -> { print('#') } else -> { print('.') } } } print("\n") } println("\n") } }
0
Kotlin
0
0
0cd9676a7d1fec01858ede1ab0adf254d17380b0
4,293
advent-of-code-23
Apache License 2.0
src/Day23.kt
Fedannie
572,872,414
false
{"Kotlin": 64631}
enum class Direction(val xRange: IntRange, val yRange: IntRange) { N(-1 .. -1, -1 .. 1), S(1 .. 1, -1 .. 1), W(-1 .. 1, -1 .. -1), E(-1 .. 1, 1 .. 1); fun next(coordinate: Coordinate): Coordinate { return when (this) { N -> Coordinate(coordinate.x - 1, coordinate.y) S -> Coordinate(coordinate.x + 1, coordinate.y) W -> Coordinate(coordinate.x, coordinate.y - 1) E -> Coordinate(coordinate.x, coordinate.y + 1) } } } class Elf(var coordinate: Coordinate) { companion object { val directions = Direction.values() } var i = 0 override fun hashCode(): Int { return coordinate.hashCode() } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as Elf if (coordinate != other.coordinate) return false return true } } fun main() { fun parseInput(input: List<String>): HashSet<Elf> { val emptyCoordinate = Coordinate(-1, -1) return input .flatMapIndexed { i, s -> s.toList().mapIndexed { j, c -> if (c == '#') Coordinate(i, j) else emptyCoordinate } } .filter { it != emptyCoordinate } .map { Elf(it) } .toHashSet() } fun countNeighbours(cur: Elf, elves: HashSet<Elf>, direction: Direction? = null): Int { var result = 0 for (dx in direction?.xRange ?: -1 .. 1) { for (dy in direction?.yRange ?: -1 .. 1) { if (dx == 0 && dy == 0) continue if (elves.count { it.coordinate == Coordinate(cur.coordinate.x + dx, cur.coordinate.y + dy)} > 0) result += 1 } } return result } fun proposal(cur: Elf, elves: HashSet<Elf>): Coordinate? { for (i in 0 .. 4) { val direction = Elf.directions[(cur.i + i + 3) % 4] if (countNeighbours(cur, elves, direction) == 0) return direction.next(cur.coordinate) } return null } fun setNewCoordinate(cur: Elf, mapping: List<Pair<Elf, Coordinate>>): Boolean { val elfProposal = mapping.find { it.first == cur } ?: return false if (mapping.count { it.second == elfProposal.second } > 1) return false cur.coordinate = elfProposal.second return true } fun step(previous: HashSet<Elf>): Boolean { val proposals = previous .map { it.i = (it.i + 1) % 4 it to countNeighbours(it, previous) } .filter { it.second > 0 } .map { it.first to proposal(it.first, previous) } .filter { it.second != null } as List<Pair<Elf, Coordinate>> return previous.map { oldElf -> setNewCoordinate(oldElf, proposals) }.any { it } } fun countEmptyTiles(elves: HashSet<Elf>): Int { val coordinates = elves.map { it.coordinate } return (coordinates.maxOf { it.x } - coordinates.minOf { it.x } + 1) * (coordinates.maxOf { it.y } - coordinates.minOf { it.y } + 1) - coordinates.size } fun print(elves: HashSet<Elf>) { val coordinates = elves.map { it.coordinate } for (x in coordinates.minOf { it.x } .. coordinates.maxOf { it.x }) { for (y in coordinates.minOf { it.y } .. coordinates.maxOf { it.y }) { if (coordinates.contains(Coordinate(x, y))) print('#') else print('.') } println() } println() } fun part1(input: List<String>): Int { val positions = parseInput(input) repeat(10) { step(positions) } return countEmptyTiles(positions) } fun part2(input: List<String>): Int { val positions = parseInput(input) var rounds = 1 while (step(positions)) rounds++ return rounds } val testInput = readInputLines("Day23_test") check(part1(testInput) == 110) check(part2(testInput) == 20) val input = readInputLines(23) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
1d5ac01d3d2f4be58c3d199bf15b1637fd6bcd6f
3,750
Advent-of-Code-2022-in-Kotlin
Apache License 2.0
src/main/kotlin/days/aoc2023/Day7.kt
bjdupuis
435,570,912
false
{"Kotlin": 537037}
package days.aoc2023 import days.Day class Day7 : Day(2023, 7) { override fun partOne(): Any { return calculatePartOne(inputList) } override fun partTwo(): Any { return calculatePartTwo(inputList) } fun calculatePartOne(input: List<String>): Int { val hands = input.map { it.split(" ") }.map { Hand(it[0], it[1].toInt())} val sortedHands = hands.sorted() return sortedHands.mapIndexed { index, hand -> (hands.size - index) * hand.bid }.sum() } internal class Hand(private val orderedCards: String, val bid: Int): Comparable<Hand> { private val conversions = mapOf( 'A' to 'A', 'K' to 'B', 'Q' to 'C', 'J' to 'D', 'T' to 'E', '9' to 'F', '8' to 'G', '7' to 'H', '6' to 'I', '5' to 'J', '4' to 'K', '3' to 'L', '2' to 'M', '1' to 'N' ) private val converted = orderedCards.map { conversions[it] ?: throw IllegalStateException() }.joinToString("") private val grouped = orderedCards.groupingBy { it }.eachCount().toList().sortedBy { (_, value) -> value }.reversed() private val rank = if (grouped.size == 1) { 1 } else if (grouped.size == 2) { if (grouped.first().second == 4) { 2 } else { 3 } } else if (grouped.size == 3) { if (grouped.first().second == 3) { 4 } else { 5 } } else if (grouped.size == 4) { 6 } else { 7 } override fun compareTo(other: Hand): Int { return if (rank == other.rank) { converted.compareTo(other.converted) } else { rank.compareTo(other.rank) } } } fun calculatePartTwo(input: List<String>): Int { val hands = input.map { it.split(" ") }.map { HandWithJokers(it[0], it[1].toInt())} val sortedHands = hands.sorted() return sortedHands.mapIndexed { index, hand -> (hands.size - index) * hand.bid }.sum() } internal class HandWithJokers(private val orderedCards: String, val bid: Int): Comparable<HandWithJokers> { private val conversions = mapOf( 'A' to 'A', 'K' to 'B', 'Q' to 'C', 'T' to 'E', '9' to 'F', '8' to 'G', '7' to 'H', '6' to 'I', '5' to 'J', '4' to 'K', '3' to 'L', '2' to 'M', '1' to 'N', 'J' to 'O' ) private val converted = orderedCards.map { conversions[it] ?: throw IllegalStateException() }.joinToString("") private val originalGrouped = orderedCards.groupingBy { it }.eachCount().toList().sortedBy { (_, value) -> value }.reversed() private val grouped = if (originalGrouped.size > 1 && originalGrouped.any { it.first == 'J' }) { val jokerCount = originalGrouped.first { it.first == 'J' }.second val topCard = originalGrouped.first { it.first != 'J' } listOf(Pair(topCard.first, topCard.second + jokerCount)) + originalGrouped.filter { it.first != 'J' }.filter { it.first != topCard.first } } else { originalGrouped } private val rank = if (grouped.size == 1) { 1 } else if (grouped.size == 2) { if (grouped.first().second == 4) { 2 } else { 3 } } else if (grouped.size == 3) { if (grouped.first().second == 3) { 4 } else { 5 } } else if (grouped.size == 4) { 6 } else { 7 } override fun compareTo(other: HandWithJokers): Int { return if (rank == other.rank) { converted.compareTo(other.converted) } else { rank.compareTo(other.rank) } } } }
0
Kotlin
0
1
c692fb71811055c79d53f9b510fe58a6153a1397
4,186
Advent-Of-Code
Creative Commons Zero v1.0 Universal
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2023/2023-08.kt
ferinagy
432,170,488
false
{"Kotlin": 787586}
package com.github.ferinagy.adventOfCode.aoc2023 import com.github.ferinagy.adventOfCode.lcm import com.github.ferinagy.adventOfCode.println import com.github.ferinagy.adventOfCode.readInputLines fun main() { val input = readInputLines(2023, "08-input") val test1 = readInputLines(2023, "08-test1") val test2 = readInputLines(2023, "08-test2") val test3 = readInputLines(2023, "08-test3") println("Part1:") part1(test1).println() part1(test2).println() part1(input).println() println() println("Part2:") part2(test3).println() part2(input).println() } private fun part1(input: List<String>): Int { val instructions = input.first() val map = input.drop(2).associate { val (from, left, right) = regex.matchEntire(it)!!.destructured from to (left to right) } return followMap( start = "AAA", instructions = instructions, map = map, endCondition = { _, current -> current == "ZZZ" } ).first } private fun part2(input: List<String>): Long { val instructions = input.first() val map = input.drop(2).associate { val (from, left, right) = regex.matchEntire(it)!!.destructured from to (left to right) } val start = map.keys.filter { it.endsWith('A') } val ends = start.map { val result = followMap( start = it, instructions = instructions, map = map, endCondition = { _, current -> current.endsWith('Z') } ) val endToEnd = followMap( start = result.second, instructions = instructions, map = map, endCondition = { steps, current -> steps != 0 && current.endsWith('Z') }, startIndex = result.first % instructions.length ) require(endToEnd.second == result.second && endToEnd.first == result.first) result.first } return ends.map { it.toLong() }.reduce { acc, i -> lcm(acc, i) } } private fun followMap( start: String, instructions: String, map: Map<String, Pair<String, String>>, endCondition: (Int, String) -> Boolean, startIndex: Int = 0 ): Pair<Int, String> { var index = startIndex var result = 0 var current = start while (!endCondition(result, current)) { current = if (instructions[index] == 'L') { map[current]!!.first } else { map[current]!!.second } index = (index + 1) % instructions.length result++ } return result to current } private val regex = """(...) = \((...), (...)\)""".toRegex()
0
Kotlin
0
1
f4890c25841c78784b308db0c814d88cf2de384b
2,628
advent-of-code
MIT License
src/Day01.kt
lsimeonov
572,929,910
false
{"Kotlin": 66434}
class Calorie(val calorie: Int) { } class Dwarf { private var calories: MutableList<Calorie> = mutableListOf() fun addCalorie(calorie: Calorie) { calories.add(calorie) } fun totalCalories(): Int { return calories.sumOf { it.calorie } } } fun main() { fun prepareDwarfs(input: List<String>): List<Dwarf> { val dwarfs = mutableListOf<Dwarf>() var dwarf = Dwarf() input.iterator().forEach { if (it.equals("")) { dwarfs.add(dwarf) dwarf = Dwarf() } else { dwarf.addCalorie(Calorie(it.toInt())) } } dwarfs.sortWith<Dwarf>(object : Comparator<Dwarf> { override fun compare(d0: Dwarf, di: Dwarf): Int { val c0 = d0.totalCalories() val c1 = di.totalCalories() if (c0 > c1) { return -1 } if (c0 == c1) { return 0 } return 1 } }) return dwarfs } fun part1(input: List<String>): Int { val dwarfs = prepareDwarfs(input) return dwarfs.first().totalCalories() } fun part2(input: List<String>): Int { val dwarfs = prepareDwarfs(input) return dwarfs.subList(0, 3).sumOf { dwarf -> dwarf.totalCalories() } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 3000) check(part2(testInput) == 3900) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
9d41342f355b8ed05c56c3d7faf20f54adaa92f1
1,688
advent-of-code-2022
Apache License 2.0
src/nativeMain/kotlin/com.qiaoyuang.algorithm/round1/Questions51.kt
qiaoyuang
100,944,213
false
{"Kotlin": 338134}
package com.qiaoyuang.algorithm.round1 import kotlin.math.min fun test51() { printlnResult(intArrayOf(7, 5, 6, 4)) printlnResult(intArrayOf(7, 5, 6, 4, 1)) printlnResult(intArrayOf(0, 7, 5, 6, 4, 1)) printlnResult(intArrayOf(1)) } /** * Questions 51: Find the count of reverse-order-pair in an IntArray */ private fun IntArray.getCountOfReverseOrderPair1(): Int { if (isEmpty()) return 0 val aux = IntArray(size) var sz = 1 var count = 0 while (sz < size) { var start = 0 while (start < size - sz) { count += merge(aux, start, start + sz - 1, min(start + sz + sz -1, size - 1)) start += sz * 2 } sz *= 2 } return count } private fun IntArray.getCountOfReverseOrderPair2(): Int { val aux = IntArray(size) return mergeSort(aux, 0, lastIndex) } private fun IntArray.mergeSort(aux: IntArray, start: Int, end: Int): Int { if (start == end) return 0 val mid = start + (end - start) / 2 return mergeSort(aux, start, mid) + mergeSort(aux, mid + 1, end) + merge(aux, start, mid, end) } private fun IntArray.merge(aux: IntArray, start: Int, mid: Int, end: Int): Int { for (k in start..end) aux[k] = this[k] var count = 0 var i = mid var j = end for (k in end downTo start) { when { i < start -> this[k] = aux[j--] j < mid + 1 -> this[k] = aux[i--] aux[i] > aux[j] -> { this[k] = aux[i--] count += j - mid } else -> this[k] = aux[j--] } } return count } private fun printlnResult(array: IntArray) { val list = array.toList() val arrayCopy = IntArray(array.size) { array[it] } println("There are: (${array.getCountOfReverseOrderPair1()}, ${arrayCopy.getCountOfReverseOrderPair2()}) reverse-order-pair in array $list") }
0
Kotlin
3
6
66d94b4a8fa307020d515d4d5d54a77c0bab6c4f
1,893
Algorithm
Apache License 2.0
src/main/kotlin/day15.kt
gautemo
572,204,209
false
{"Kotlin": 78294}
import shared.Point import shared.getText import kotlin.math.abs fun main() { val input = getText("day15.txt") println(day15A(input, 2000000)) println(day15B(input, 4000000)) } fun day15A(input: String, rowToCheck: Int): Int { val pairs = input.lines().map { positions(it) } val mostLeft = pairs.minOf { minOf(it.first.x, it.second.x) - manhattanDist(it.first, it.second) } val mostRight = pairs.maxOf { maxOf(it.first.x, it.second.x) + manhattanDist(it.first, it.second) } return (mostLeft .. mostRight).count { x -> val toCheck = Point(x, rowToCheck) pairs.none { it.first == toCheck || it.second == toCheck } && pairs.any { toCheck.isCoveredBy(it) } } } fun day15B(input: String, max: Int): Long { val pairs = input.lines().map { positions(it) } for(y in 0 .. max) { var x = 0 xLoop@while(x <= max) { val toCheck = Point(x, y) for(p in pairs){ if(toCheck.isCoveredBy(p)){ x = (p.first.x + manhattanDist(p.first, p.second) + 1) - abs(toCheck.y - p.first.y) continue@xLoop } } return x * 4000000L + y } } return -1 } private fun positions(input: String): Pair<Point, Point> { val (sensorInput, beaconInput) = input.split(":") return position(sensorInput) to position(beaconInput) } private fun position(input: String): Point { val x = Regex("""(?<=x=)-?\d+""").find(input)!!.value.toInt() val y = Regex("""(?<=y=)-?\d+""").find(input)!!.value.toInt() return Point(x,y) } private fun manhattanDist(a: Point, b: Point) = abs(a.x-b.x) + abs(a.y-b.y) private fun Point.isCoveredBy(pair: Pair<Point, Point>) = manhattanDist(pair.first, this) <= manhattanDist(pair.first, pair.second)
0
Kotlin
0
0
bce9feec3923a1bac1843a6e34598c7b81679726
1,814
AdventOfCode2022
MIT License
math/MaxPointsOnALine/kotlin/Solution.kt
YaroslavHavrylovych
78,222,218
false
{"Java": 284373, "Kotlin": 35978, "Shell": 2994}
import kotlin.math.sign /** * Given n points on a 2D plane, find the maximum number of points that * lie on the same straight line. * <br> * https://leetcode.com/problems/max-points-on-a-line/ */ class Solution { fun maxPoints(points: Array<IntArray>): Int { if (points.size < 2) return points.size var max = 2 for (i in 0 until points.size - max) { val lines = HashMap<String, Int>() var same = 1 //k = (y2 - y1) / (x2 - x1) - this we can save as the fraction var nextPointMax = 0 for (j in i + 1 until points.size) { var pts:Int if (points[i][0] == points[j][0] && points[i][1] == points[j][1]) { same += 1 continue } else if (points[i][0] == points[j][0]) { pts = lines.inc("inf") } else if (points[i][1] == points[j][1]) { pts = lines.inc("0") } else { val dx = points[i][0] - points[j][0] // dx != 0 (checked before) val dy = points[i][1] - points[j][1] // dy != 0 (checked before) val d = gcd(dx, dy) val sign = if (dx.sign + dy.sign == 0) "-" else "" pts = lines.inc("$sign${kotlin.math.abs(dx / d)}${kotlin.math.abs(dy / d)}") } nextPointMax = kotlin.math.max(nextPointMax, pts) } nextPointMax += same max = kotlin.math.max(nextPointMax, max) } return max } private fun gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b) private fun MutableMap<String, Int>.inc(k: String): Int = this.let { m -> m[k] = getOrDefault(k, 0) + 1 m[k]!! } } fun main() { println("Max Point in a line: test is not implemented") }
0
Java
0
2
cb8e6f7e30563e7ced7c3a253cb8e8bbe2bf19dd
1,927
codility
MIT License
src/Day04.kt
seana-zr
725,858,211
false
{"Kotlin": 28265}
import java.util.LinkedList import java.util.regex.Pattern import kotlin.math.max import kotlin.math.min import kotlin.math.pow fun main() { data class Card( val id: Int, val winning: Set<Int>, val hand: Set<Int> ) fun parseCard(card: String): Card { val combos = card .dropWhile { it != ':' } .drop(2) .trim() .split("|") .map { s -> s .trim() .split(regex = Pattern.compile("\\s+")) .map { it.toInt() } .toSet() } assert(combos.size == 2) return Card(-1, combos.first(), combos.last()) } fun part1(input: List<String>): Int { var result = 0 for (card in input) { val (_, winning, hand) = parseCard(card) result += 2.0.pow(winning.intersect(hand).size-1).toInt() } return result } fun part2(input: List<String>): Int { var result = 0 val cardMenu = input.mapIndexed { index, s -> parseCard(s).copy(id = index) } val queue = LinkedList(cardMenu) while (queue.isNotEmpty()) { result++ val card = queue.pop() val (id, winning, hand) = card val numCopies = winning.intersect(hand).size print("${card.id} won $numCopies | \t") val range = (id + 1..min(input.size - 1 , id + numCopies)) print("adding $range \t") range.forEach { i -> queue.offer(cardMenu[i]) } println() } println("RESULT: $result") return result } // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_test") check(part2(testInput) == 30) val input = readInput("Day04") // part1(input).println() part2(input).println() }
0
Kotlin
0
0
da17a5de6e782e06accd3a3cbeeeeb4f1844e427
1,963
advent-of-code-kotlin-template
Apache License 2.0
src/main/kotlin/com/sk/set2/212. Word Search II.kt
sandeep549
262,513,267
false
{"Kotlin": 530613}
package com.sk.set2 class Solution212 { fun findWords(board: Array<CharArray>, words: Array<String>): List<String> { val res = mutableListOf<String>() outerLoop@ for (word in words) { for (r in board.indices) { for (c in board[0].indices) { val seen = Array(board.size) { BooleanArray(board[0].size) { false } } if (find(word, 0, r, c, board, seen)) { res.add(word) continue@outerLoop } } } } return res } private fun find( word: String, i: Int, r: Int, c: Int, board: Array<CharArray>, seen: Array<BooleanArray> ): Boolean { if (i == word.length) return true if (r < 0 || r >= board.size || c < 0 || c >= board[0].size) return false if (seen[r][c]) return false if (board[r][c] == word[i]) { // matched this character seen[r][c] = true if (find(word, i + 1, r - 1, c, board, seen) || find(word, i + 1, r + 1, c, board, seen) || find(word, i + 1, r, c - 1, board, seen) || find(word, i + 1, r, c + 1, board, seen) ) return true seen[r][c] = false return false } else { return false } } } class Solution212_2 { fun findWords(board: Array<CharArray>, words: Array<String>): List<String> { val trie = buildTrie(words) val res = HashSet<String>() for (i in board.indices) { for (j in board[0].indices) { dfs(board, trie, res, i, j) } } return ArrayList(res) } private fun dfs(board: Array<CharArray>, node: Trie, res: HashSet<String>, i: Int, j: Int) { var node = node if (i < 0 || i >= board.size || j < 0 || j >= board[0].size || board[i][j] == '#' || node.next[board[i][j] - 'a'] == null) { return } if (node.next[board[i][j] - 'a']!!.word != null) { res.add(node.next[board[i][j].code - 'a'.code]!!.word!!) } // Go to next char node = node.next[board[i][j].code - 'a'.code]!! val c = board[i][j] board[i][j] = '#' dfs(board, node, res, i - 1, j) dfs(board, node, res, i + 1, j) dfs(board, node, res, i, j - 1) dfs(board, node, res, i, j + 1) board[i][j] = c } private fun buildTrie(words: Array<String>): Trie { val root = Trie() for (w in words) { var p = root for (c in w.toCharArray()) { if (p.next[c.code - 'a'.code] == null) { p.next[c.code - 'a'.code] = Trie() } p = p.next[c.code - 'a'.code]!! // will point to curr char } p.word = w } return root } private class Trie { var next = arrayOfNulls<Trie>(26) var word: String? = null } }
1
Kotlin
0
0
cf357cdaaab2609de64a0e8ee9d9b5168c69ac12
3,062
leetcode-kotlin
Apache License 2.0
src/main/kotlin/days/day12/Day12.kt
Stenz123
725,707,248
false
{"Kotlin": 123279, "Shell": 862}
package days.day12 import days.Day class Day12 : Day() { override fun partOne(): Any { val springs: MutableList<Pair<List<Char>, List<Int>>> = mutableListOf() val rawInput = readInput() rawInput.forEach { val input = it.split(" ") val spring = input[0].toCharArray().toList() val output = input[1].split(",").map { it.toInt() } springs.add(Pair(spring, output)) } var result = 0 for (spring in springs) { val combinations = allCombinations(spring.first.count { it == '?' }) for (combination in combinations) { //replace ? with combination var counter = -1 val newSpring = spring.first.mapIndexed { index, c -> if (c == '?') { counter++ combination[counter] } else { c } }.joinToString("") //check if newSpring is valid var valid = true val split = newSpring.split(".").filter { it.isNotEmpty() } if (split.size == spring.second.size) { for (i in spring.second.indices) { if (spring.second[i] != split[i].length) { valid = false break } } } else { valid = false } if (valid) { result++ } } } return result } override fun partTwo(): Any { val springs: MutableList<Pair<List<Char>, List<Int>>> = mutableListOf() val rawInput = readInput() rawInput.forEach { val input = it.split(" ") val spring = "${input[0]}?${input[0]}?${input[0]}?${input[0]}?${input[0]}" //val spring = input[0] val output = input[1].split(",").map { it.toInt() } springs.add( Pair( spring.toCharArray().toList(), output + output + output + output + output //output ) ) } var result = 0L for (spring in springs) { val res = makeGroup(spring.first.joinToString (""), spring.second) println(res) result += res } return result } private val cache = hashMapOf<Pair<String, List<Int>>, Long>() private fun makeGroup(springs: String, values: List<Int>): Long { if (values.isEmpty()) return if (springs.contains('#')) 0 else 1 if (springs.isEmpty()) return 0 return cache.getOrPut(springs to values) { var result = 0L if (springs[0] == '.' || springs[0] == '?') { result += makeGroup(springs.drop(1), values) } if (springs[0] in "#?" && values[0] <= springs.length){ if ("." !in springs.take(values[0])) { if (values.first() == springs.length || springs[values[0]] != '#'){ result += makeGroup(springs.drop(values[0] + 1), values.drop(1)) } } } result } } fun allCombinations(length: Int): List<List<Char>> { val values = listOf('.', '#') // Base case: If the length is 0, return a list containing an empty list if (length == 0) { return listOf(emptyList()) } // Recursive case: Generate combinations for the previous length val prevCombinations = allCombinations(length - 1) // Build new combinations by appending each value to the existing combinations return values.flatMap { value -> prevCombinations.map { combination -> listOf(value) + combination } } } }
0
Kotlin
1
0
3de47ec31c5241947d38400d0a4d40c681c197be
4,009
advent-of-code_2023
The Unlicense
advent2022/src/main/kotlin/year2022/Day11.kt
bulldog98
572,838,866
false
{"Kotlin": 132847}
package year2022 import AdventDay import lcm class Day11 : AdventDay(2022, 11) { data class Monkey( val monkeyNumber: Int, val items: List<Int>, val operation: (Long) -> Long, val throwToMonkey: (Int) -> Int ) private fun List<String>.parseSingleMonkey(): Monkey { val monkeyNumber = first().split(" ")[1].split(":")[0].toInt() val items = get(1).split(" Starting items: ")[1].split(", ").map { it.toInt() } val (op, commands) = get(2).split(" Operation: ")[1] .split(" = ") .let { (_, b) -> val op: (Long, Long) -> Long = if (b.contains('*')) Long::times else Long::plus op to b.split(" * ", " + ") } fun operation(old: Long): Long { val first = when { commands.first() == "old" -> old else -> commands.first().toLong() } val second = when { commands[1] == "old" -> old else -> commands[1].toLong() } return op(first, second) } val testLine = get(3).split(" Test: divisible by ")[1].toInt() val trueLine = get(4).split(" If true: throw to monkey ")[1].toInt() val falseLine = get(5).split(" If false: throw to monkey ")[1].toInt() fun throwTo(value: Int) = if (value % testLine == 0) { trueLine } else falseLine return Monkey( monkeyNumber, items, operation = ::operation, ::throwTo ) } private fun Array<Monkey>.simulateFor( rounds: Int, adjustExpectation: (Long) -> Int ): IntArray { val monkeyInspects = IntArray(size) { 0 } for(round in 0 until rounds) { for (i in indices) { val monkey = get(i) monkey.items.forEachIndexed { _, oldValue -> monkeyInspects[i] = monkeyInspects[i] + 1 val newValue = adjustExpectation(monkey.operation(oldValue.toLong())) val newMonkey = monkey.throwToMonkey(newValue) set(newMonkey, get(newMonkey).copy(items = get(newMonkey).items + newValue)) } set(i, get(i).copy(items = listOf())) } } return monkeyInspects } override fun part1(input: List<String>): Int { val monkeys = input.joinToString("\n") .split("\n\n") .map { it.split("\n").parseSingleMonkey() } .toTypedArray() val monkeyInspects = monkeys.simulateFor(20) { i -> (i / 3).toInt() } val order = monkeyInspects.sortedByDescending { it } return order[0] * order[1] } override fun part2(input: List<String>): Long { val monkeys = input.joinToString("\n") .split("\n\n") .map { it.split("\n").parseSingleMonkey() } .toTypedArray() val divisors = input .filter { it.contains(" Test: divisible by ") } .map { it.split(" Test: divisible by ")[1].toLong() } val lcm = lcm(divisors) val monkeyInspects = monkeys.simulateFor(10_000) { i -> (i % lcm).toInt() } val order = monkeyInspects.sortedByDescending { it } return order[0].toLong() * order[1] } } fun main() = Day11().run()
0
Kotlin
0
0
02ce17f15aa78e953a480f1de7aa4821b55b8977
3,440
advent-of-code
Apache License 2.0
src/Day18.kt
flex3r
572,653,526
false
{"Kotlin": 63192}
suspend fun main() { val testInput = readInput("Day18_test") check(part1(testInput) == 64) check(part2(testInput) == 58) val input = readInput("Day18") measureAndPrintResult { part1(input) } measureAndPrintResult { part2(input) } } private fun part1(input: List<String>): Int { val points = input.map(Point3::fromString) return points.sumOf { point -> 6 - point.neighbors.count { it in points } } } private fun part2(input: List<String>): Int { val points = input.map(Point3::fromString) val ranges = listOf( points.openRangeOf { it.x }, points.openRangeOf { it.y }, points.openRangeOf { it.z } ) val start = Point3(ranges[0].first, ranges[1].first, ranges[2].first) var sides = 0 bfs(start) { point -> point.neighbors .onEach { if (it in points) sides++ } .filter { it !in points && it in ranges } }.toList() return sides } private inline fun List<Point3>.openRangeOf(selector: (Point3) -> Int): IntRange { return minOf(selector) - 1..maxOf(selector) + 1 } private operator fun List<IntRange>.contains(point: Point3) = let { (xRange, yRange, zRange) -> point.x in xRange && point.y in yRange && point.z in zRange } private data class Point3(val x: Int, val y: Int, val z: Int) { val neighbors get() = setOf( copy(x = x - 1), copy(x = x + 1), copy(y = y - 1), copy(y = y + 1), copy(z = z - 1), copy(z = z + 1) ) companion object { fun fromString(input: String) = input.split(",").let { (x, y, z) -> Point3(x.toInt(), y.toInt(), z.toInt()) } } }
0
Kotlin
0
0
8604ce3c0c3b56e2e49df641d5bf1e498f445ff9
1,723
aoc-22
Apache License 2.0
src/day_12/kotlin/Day12.kt
Nxllpointer
573,051,992
false
{"Kotlin": 41751}
// AOC Day 12 operator fun Array<IntArray>.get(position: Vector2D) = this[position.y][position.x] operator fun Array<IntArray>.set(position: Vector2D, value: Int) = this[position.y].set(position.x, value) val Array<IntArray>.verticalSize get() = this.size val Array<IntArray>.horizontalSize get() = this.first().size fun generateDistanceMap(heightMap: Array<IntArray>, startPosition: Vector2D): Array<IntArray> { val distanceMap = Array(heightMap.size) { IntArray(heightMap.first().size) { -1 } } fun Vector2D.getAdjacentUnsetPositions(): Set<Vector2D> = listOf(Vector2D(x, y + 1), Vector2D(x + 1, y), Vector2D(x, y - 1), Vector2D(x - 1, y)) .filter { val isInMap = it.x in 0 until heightMap.horizontalSize && it.y in 0 until heightMap.verticalSize val isUnset by lazy { distanceMap[it] == -1 } // ----- Lazy to avoid index out of bounds val isElevationChangeAllowed by lazy { heightMap[it] >= heightMap[this] - 1 } // ------- isInMap && isUnset && isElevationChangeAllowed }.toSet() distanceMap[startPosition] = 0 var adjacentPositions = startPosition.getAdjacentUnsetPositions() var adjacentDistance = 1 while (adjacentPositions.isNotEmpty()) { adjacentPositions = adjacentPositions.flatMap { adjacentPosition -> distanceMap[adjacentPosition] = adjacentDistance adjacentPosition.getAdjacentUnsetPositions() }.toSet() adjacentDistance++ } return distanceMap } fun part1and2(heightMap: Array<IntArray>, startPosition: Vector2D, destinationPosition: Vector2D) { val distanceMap = generateDistanceMap(heightMap, destinationPosition) val lowestPositionsSteps = mutableListOf<Int>() for (rowIndex in 0 until heightMap.verticalSize) { for (colnumIndex in 0 until heightMap.horizontalSize) { val position = Vector2D(colnumIndex, rowIndex) val height = heightMap[position] val distance = distanceMap[position] if (height == 0 && distance > 0) { lowestPositionsSteps += distance } } } val destinationStepsStartPosition = distanceMap[startPosition] val destinationStepsNearestLowestPosition = lowestPositionsSteps.min() println("Part 1: You need to walk $destinationStepsStartPosition from the start position to reach the destination") println("Part 2: You need to walk $destinationStepsNearestLowestPosition from the nearest lowest position to reach the destination") } fun Char.letterToHeight() = "abcdefghijklmnopqrstuvwxyz".indexOf(this) fun main() { val (heightMap, startPosition, destinationPosition) = getAOCInput { rawInput -> lateinit var startPosition: Vector2D lateinit var destinationPosition: Vector2D val heightMap = rawInput.trim().lines().mapIndexed { rowIndex, row -> row.mapIndexed { colnumIndex, letter -> when (letter) { 'S' -> { startPosition = Vector2D(colnumIndex, rowIndex) 'a' } 'E' -> { destinationPosition = Vector2D(colnumIndex, rowIndex) 'z' } else -> letter }.letterToHeight() }.toIntArray() }.toTypedArray() Triple(heightMap, startPosition, destinationPosition) } part1and2(heightMap, startPosition, destinationPosition) }
0
Kotlin
0
0
b6d7ef06de41ad01a8d64ef19ca7ca2610754151
3,569
AdventOfCode2022
MIT License
src/main/kotlin/com/sk/set1/149. Max Points on a Line.kt
sandeep549
262,513,267
false
{"Kotlin": 530613}
package com.sk.set1 class Solution149 { // ??? fun maxPoints(points: Array<IntArray>): Int { fun slope(a: IntArray, b: IntArray): Double { return (b[1].toDouble() - a[1]) / (b[0] - a[0]) } val map = HashMap<Double, MutableSet<Pair<Int, Int>>>() for (i in points.indices) { for (j in i + 1 until points.size) { val s = slope(points[i], points[j]) val set = map.getOrDefault(s, mutableSetOf()) set.add(Pair(points[i][0], points[i][1])) set.add(Pair(points[j][0], points[j][1])) map[s] = set } } return if (map.values.isNotEmpty()) map.values.maxOf { it.size } else 0 } /** * Solution taken from here https://leetcode.com/problems/max-points-on-a-line/solutions/47113/a-java-solution-with-notes * Algorithm: * Consider every point and all other points to the right of it. * Find slope(i.e. dy/dx, where dy=y2-y1 and dx=x2-x1) of these 2 points. * Store slope count in map. As starting point is same for all slopes, there can not be parallel line having same slope. * Keep track of max slope count. * Return max. * * Why +1: We are never adding starting point to count, so add it last to simplify the calculation. * Why GCD: Slope 10/6 is equal to 5/3, read this topic to get this https://en.wikipedia.org/wiki/Irreducible_fraction * */ fun maxPoints2(points: Array<IntArray>): Int { if (points.size <= 2) return points.size val map = HashMap<String, Int>() var max = 0 for (i in points.indices) { map.clear() for (j in i + 1 until points.size) { var x = points[j][0] - points[i][0] var y = points[j][1] - points[i][1] val gcd = generateGCD(x, y) if (gcd != 0) { x /= gcd y /= gcd } val key = "$y/$x" map[key] = map.getOrDefault(key, 0) + 1 max = maxOf(max, map[key]!!) } } return max + 1 } private fun generateGCD(a: Int, b: Int): Int { return if (b == 0) a else generateGCD(b, a % b) } // why this is faster than maxPoints2 ??? fun maxPoints3(points: Array<IntArray>): Int { var maxCount = 1 for (i in 0 until points.size) { for (j in i + 1 until points.size) { var count = 2 for (k in j + 1 until points.size) { if (points[k].isColliniar(points[i], points[j])) { count++ } } if (maxCount < count) { maxCount = count } } } return maxCount } // https://byjus.com/maths/collinearity-of-three-points/ private fun IntArray.isColliniar(x: IntArray, y: IntArray): Boolean { val x1 = x[0] val y1 = x[1] val x2 = y[0] val y2 = y[1] val x3 = this[0] val y3 = this[1] return y3 * (x2 - x1) - x3 * (y2 - y1) == y1 * (x2 - x1) - (y2 - y1) * x1 } }
1
Kotlin
0
0
cf357cdaaab2609de64a0e8ee9d9b5168c69ac12
3,264
leetcode-kotlin
Apache License 2.0
src/main/kotlin/year2023/day-04.kt
ppichler94
653,105,004
false
{"Kotlin": 182859}
package year2023 import lib.aoc.Day import lib.aoc.Part import lib.memoize import lib.splitLines import kotlin.math.pow fun main() { Day(4, 2023, PartA4(), PartB4()).run() } open class PartA4 : Part() { protected data class Card(val id: Int, val winningNumbers: List<Int>, val yourNumbers: List<Int>) { val points: Int get() = yourNumbers.count { it in winningNumbers } companion object { fun ofLine(line: String): Card { val (cardText, numbers) = line.split(":") val id = """\d+""".toRegex().find(cardText)!!.value.toInt() val (winningText, yourText) = numbers.split(" | ") val winningNumbers = """\d+""".toRegex().findAll(winningText).map { it.value.toInt() }.toList() val yourNumbers = """\d+""".toRegex().findAll(yourText).map { it.value.toInt() }.toList() return Card(id, winningNumbers, yourNumbers) } } } protected lateinit var cards: List<Card> override fun parse(text: String) { cards = text.splitLines().map(Card::ofLine) } override fun compute(): String { return cards .map { it.points } .filter { it > 0 } .map { it - 1 } .sumOf { 2.0.pow(it.toDouble()).toInt() } .toString() } override val exampleAnswer: String get() = "13" } class PartB4 : PartA4() { private val pointsFn = ::points.memoize() override fun compute(): String { val cardMap = cards.indices .associate { index -> index + 1 to cards .drop(index + 1) .take(cards[index].points) .map { it.id } } return cards.indices .sumOf { pointsFn(cardMap, it + 1) } .toString() } private fun points(cardMap: Map<Int, List<Int>>, cardId: Int): Int { if (cardMap[cardId] == null || cardMap[cardId]?.isEmpty() == true) { return 1 } return cardMap[cardId]!!.sumOf { pointsFn(cardMap, it) } + 1 } override val exampleAnswer: String get() = "30" }
0
Kotlin
0
0
49dc6eb7aa2a68c45c716587427353567d7ea313
2,275
Advent-Of-Code-Kotlin
MIT License
src/Day14.kt
mjossdev
574,439,750
false
{"Kotlin": 81859}
private enum class Unit { ROCK, SAND } fun main() { data class Coordinate(val x: Int, val y: Int) { override fun toString() = "$x,$y" } operator fun Coordinate.rangeTo(other: Coordinate) = when { this == other -> sequenceOf(this) x == other.x -> (if (y < other.y) y..other.y else y downTo other.y).asSequence().map { copy(y = it) } y == other.y -> (if (x < other.x) x..other.x else x downTo other.x).asSequence().map { copy(x = it) } else -> throw IllegalArgumentException() } fun String.toCoordinate() = split(',').let { (x, y) -> Coordinate(x.toInt(), y.toInt()) } fun readCoordinates(input: List<String>): Set<Coordinate> = input.flatMap { line -> line.split(" -> ") .zipWithNext() .flatMap { (s, e) -> s.toCoordinate()..e.toCoordinate() } }.toSet() fun part1(input: List<String>): Int { val cave = readCoordinates(input).associateWith { Unit.ROCK }.toMutableMap() val sandSpawn = Coordinate(500, 0) val lowestY = cave.keys.maxOf { it.y } var spawnedSand = 0 while (true) { var current = sandSpawn while (current.y < lowestY) { var next = current.copy(y = current.y + 1) if (cave[next] != null) { next = next.copy(x = current.x - 1) if (cave[next] != null) { next = next.copy(x = current.x + 1) if (cave[next] != null) { break } } } current = next } if (current.y >= lowestY) { return spawnedSand } cave[current] = Unit.SAND ++spawnedSand } } fun part2(input: List<String>): Int { val cave = readCoordinates(input).associateWith { Unit.ROCK }.toMutableMap() val lowestY = cave.keys.maxOf { it.y } + 2 fun isBlocked(coordinate: Coordinate) = coordinate.y >= lowestY || cave[coordinate] != null val sandSpawn = Coordinate(500, 0) var spawnedSand = 0 while (cave[sandSpawn] == null) { var current = sandSpawn while (current.y < lowestY) { var next = current.copy(y = current.y + 1) if (isBlocked(next)) { next = next.copy(x = current.x - 1) if (isBlocked(next)) { next = next.copy(x = current.x + 1) if (isBlocked(next)) { break } } } current = next } cave[current] = Unit.SAND ++spawnedSand } return spawnedSand } // test if implementation meets criteria from the description, like: val testInput = readInput("Day14_test") check(part1(testInput) == 24) check(part2(testInput) == 93) val input = readInput("Day14") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
afbcec6a05b8df34ebd8543ac04394baa10216f0
3,140
advent-of-code-22
Apache License 2.0
2015/kotlin/src/main/kotlin/nl/sanderp/aoc/common/Collections.kt
sanderploegsma
224,286,922
false
{"C#": 233770, "Kotlin": 126791, "F#": 110333, "Go": 70654, "Python": 64250, "Scala": 11381, "Swift": 5153, "Elixir": 2770, "Jinja": 1263, "Ruby": 1171}
package nl.sanderp.aoc.common import java.util.* /** * Generates all permutations of a list. * @see <a href="https://rosettacode.org/wiki/Permutations#Kotlin">Source on RosettaCode</a> */ fun <T> List<T>.permutations(): List<List<T>> { if (this.size == 1) return listOf(this) val perms = mutableListOf<List<T>>() val toInsert = this[0] for (perm in this.drop(1).permutations()) { for (i in 0..perm.size) { val newPerm = perm.toMutableList() newPerm.add(i, toInsert) perms.add(newPerm) } } return perms } /** * Generates all combinations of a list of size m. * @see <a href="https://rosettacode.org/wiki/Combinations#Kotlin">Source on RosettaCode</a> */ inline fun <reified T> List<T>.combinations(m: Int): Sequence<List<T>> { val items = this return sequence { val result = MutableList(m) { items[0] } val stack = LinkedList<Int>() stack.push(0) while (stack.isNotEmpty()) { var resIndex = stack.size - 1 var arrIndex = stack.pop() while (arrIndex < size) { result[resIndex++] = items[arrIndex++] stack.push(arrIndex) if (resIndex == m) { yield(result.toList()) break } } } } } fun <T, U> allPairs(first: Iterable<T>, second: Iterable<U>) = sequence { for (a in first) { for (b in second) { yield(Pair(a, b)) } } } fun <T, U, V> allTriples(first: Iterable<T>, second: Iterable<U>, third: Iterable<V>) = sequence { for (a in first) { for (b in second) { for (c in third) { yield(Triple(a, b, c)) } } } } fun <T> Iterable<T>.allPairs() = allPairs(this, this) fun <T> Iterable<T>.allTriples() = allTriples(this, this, this) fun <T> MutableMap<T, Int>.increaseBy(key: T, value: Int) = merge(key, value) { a, b -> a + b } fun <T> MutableMap<T, Long>.increaseBy(key: T, value: Long) = merge(key, value) { a, b -> a + b } /** * Given a list of lists (ie a matrix), transpose it */ fun <T> List<List<T>>.transpose(): List<List<T>> { return (this[0].indices).map { i -> (this.indices).map { j -> this[j][i] } } } /** * Given an array of arrays (ie a matrix), transpose it */ inline fun <reified T> Array<Array<T>>.transpose(): Array<Array<T>> { return Array(this[0].size) { i -> Array(this.size) { j -> this[j][i] } } }
0
C#
0
6
8e96dff21c23f08dcf665c68e9f3e60db821c1e5
2,522
advent-of-code
MIT License
src/leetcodeProblem/leetcode/editor/en/SearchInRotatedSortedArray.kt
faniabdullah
382,893,751
false
null
//There is an integer array nums sorted in ascending order (with distinct //values). // // Prior to being passed to your function, nums is possibly rotated at an //unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k] //, nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For //example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0 //,1,2]. // // Given the array nums after the possible rotation and an integer target, //return the index of target if it is in nums, or -1 if it is not in nums. // // You must write an algorithm with O(log n) runtime complexity. // // // Example 1: // Input: nums = [4,5,6,7,0,1,2], target = 0 //Output: 4 // Example 2: // Input: nums = [4,5,6,7,0,1,2], target = 3 //Output: -1 // Example 3: // Input: nums = [1], target = 0 //Output: -1 // // // Constraints: // // // 1 <= nums.length <= 5000 // -10⁴ <= nums[i] <= 10⁴ // All values of nums are unique. // nums is an ascending array that is possibly rotated. // -10⁴ <= target <= 10⁴ // // Related Topics Array Binary Search 👍 10540 👎 772 package leetcodeProblem.leetcode.editor.en class SearchInRotatedSortedArray { fun solution() { } //below code will be used for submission to leetcode (using plugin of course) //leetcode submit region begin(Prohibit modification and deletion) class Solution { fun search(nums: IntArray, target: Int): Int { var l = 0 var r = nums.size - 1 // t =4 while (l <= r) { val m = l + (r - l) / 2 // if (nums[m] == target) { return m } if (nums[l] <= nums[m]) { if (target > nums[m] || target < nums[l]) l = m + 1 else r = m - 1 } else { if (target < nums[m] || target > nums[r]) r = m - 1 else l = m + 1 } } return -1 } } //leetcode submit region end(Prohibit modification and deletion) } fun main() { SearchInRotatedSortedArray.Solution().search(intArrayOf(4,5,6,7,0,1,2) , 4) }
0
Kotlin
0
6
ecf14fe132824e944818fda1123f1c7796c30532
2,202
dsa-kotlin
MIT License
jk/src/main/kotlin/leetcode/Solution_LeetCode_912_21_Merge_Sort_Related.kt
lchang199x
431,924,215
false
{"Kotlin": 86230, "Java": 23581}
package leetcode import common.ListNode import common.buildLinkedList import common.printPretty class Solution_LeetCode_912_21_Merge_Sort_Related { /** * 归并排序 * [](https://leetcode-cn.com/problems/sort-an-array/) */ fun mergeSort(nums: IntArray): IntArray { // 归并排序需要一个临时数组保存左右两子数组合并后的结果,这个合并后的结果最终会拷贝回原数组对应位置,达到原地排序的效果 val temp = IntArray(nums.size) mergeSort(nums, temp, 0, nums.size - 1) return nums } private fun mergeSort(nums: IntArray, temp: IntArray, l: Int, r: Int) { if (l < r) { val mid = (l + r) shr 1 mergeSort(nums, temp, l, mid) mergeSort(nums, temp, mid + 1, r) var i = l var j = mid + 1 var idx = 0 while (i <= mid && j <= r) { temp[idx++] = if (nums[i] < nums[j]) nums[i++] else nums[j++] } while (i <= mid) { temp[idx++] = nums[i++] } while (j <= r) { temp[idx++] = nums[j++] } for (k in l..r) { nums[k] = temp[k - l] } } } /** * 链表排序: 归并排序思想 * [](https://leetcode-cn.com/problems/7WHec2/) */ fun sortList(head: ListNode?): ListNode? { if (head?.next == null) return head var head1 = head var head2 = split(head) head1 = sortList(head1) head2 = sortList(head2) return merge(head1, head2) } private fun split(head: ListNode): ListNode? { var slow = head var fast: ListNode? = head.next while (fast?.next != null) { slow = slow.next!! fast = fast.next!!.next } val result = slow.next slow.next = null // 使原链表在此节点断开 return result } private fun merge(head1: ListNode?, head2: ListNode?): ListNode { val result = ListNode(-1) // 哑节点,归并排序所需临时链表的头 var l1 = head1 var l2 = head2 var cur = result while (l1 != null && l2 != null) { if (l1.`val` < l2.`val`) { cur.next = l1 l1 = l1.next } else { cur.next = l2 l2 = l2.next } cur = cur.next!! } cur.next = l1 ?: l2 return result.next!! } /** * 合并有序链表 * [](https://leetcode-cn.com/problems/merge-two-sorted-lists/) */ fun mergeTwoLists(l1: ListNode?, l2: ListNode?): ListNode? { if (l1 == null) return l2 if (l2 == null) return l1 // 这两步处理基本是定式 val result = ListNode(-1) // 1 var temp = result // 2 // kotlin中这两句是必须的,因为函数形参默认是final的 // java中如果没有明确要求不要改变原链表,可以直接用l1, l2进行迭代 // 但其实原链表怎么都会改变,因为除了头节点,后面的next指针指向全变了 var head1 = l1 var head2 = l2 while (head1 != null && head2 != null) { if (head1.`val` < head2.`val`) { // head1重新赋值,不会影响已经设置到temp.next中的值 // head1对所引用的对象执行操作会影响,如head1.data = -1 temp.next = head1 // 3 head1 = head1.next // 4 } else { temp.next = head2 head2 = head2.next } temp = temp.next!! } // 数组这里要while循环,链表只用if接上,后面的自动接上了 if (head1 != null) temp.next = head1 if (head2 != null) temp.next = head2 return result.next } /** * 合并有序链表: 递归解法 * [](https://leetcode-cn.com/problems/merge-two-sorted-lists/) * * 注意这里不用给l1和l2新建可变引用,也不用哑节点 */ fun mergeTwoListsRecursive(l1: ListNode?, l2: ListNode?): ListNode? { return if (l1 == null) { l2 } else if (l2 == null) { l1 } else if (l1.`val` > l2.`val`) { l2.next = mergeTwoListsRecursive(l1, l2.next) l2 } else { l1.next = mergeTwoListsRecursive(l1.next, l2) l1 } } } fun main() { println( Solution_LeetCode_912_21_Merge_Sort_Related() .mergeSort(intArrayOf(1, 5, 3, 2, 4)) .contentToString() ) println( Solution_LeetCode_912_21_Merge_Sort_Related() .mergeSort(intArrayOf(1, 1, 5, 3, 3, 3, 2, 5, 4)) .contentToString() ) Solution_LeetCode_912_21_Merge_Sort_Related() .mergeTwoLists( buildLinkedList(intArrayOf(1, 7, 10)), buildLinkedList(intArrayOf(2, 5, 8)) ).printPretty() }
0
Kotlin
0
0
52a008325dd54fed75679f3e43921fcaffd2fa31
5,095
Codelabs
Apache License 2.0
src/Day19.kt
mathijs81
572,837,783
false
{"Kotlin": 167658, "Python": 725, "Shell": 57}
import kotlin.math.max import kotlin.math.min private const val EXPECTED_1 = 19114 private const val EXPECTED_2 = 167409079868000L typealias XmasRange = List<Pair<Int, Int>> private class Day19(isTest: Boolean) : Solver(isTest) { val desc: String val parts: String val indexStr = "xmas" init { readAsString().split("\n\n").let { (desc, parts) -> this.desc = desc this.parts = parts } } val rules = desc.split("\n").map { val (name, rest) = it.split("{") val orders = rest.removeSuffix("}").split(",") name to orders }.toMap() fun part1(): Any { fun List<Int>.match(s: String): Boolean { val instr = s.split(":")[0] val comp = instr.substring(2).toInt() val value = get(indexStr.indexOf(instr[0])) when (instr[1]) { '>' -> return value > comp '<' -> return value < comp else -> error("instr " + s) } } return parts.split("\n").sumOf { part -> val res = part.splitInts() var ruleName = "in" w@ while (ruleName != "A" && ruleName != "R") { val orders = rules[ruleName]!! for (i in 0..<orders.size - 1) { if (res.match(orders[i])) { ruleName = orders[i].substringAfter(":") continue@w } } ruleName = orders.last() } if (ruleName == "A") res.sum() else 0 } } fun part2(): Any { fun XmasRange.count(): Long { var ans = 1L for (p in this) { ans *= if (p.second < p.first) 0 else (p.second - p.first) } return ans } fun XmasRange.empty(): Boolean = count() == 0L fun XmasRange.match(s: String): Pair<XmasRange, XmasRange> { val instr = s.split(":")[0] val comp = instr.substring(2).toInt() val ind = indexStr.indexOf(instr[0]) val value = get(ind) when (instr[1]) { '>' -> { return toMutableList().apply { set(ind, max(value.first, comp + 1) to value.second) } to toMutableList().apply { set(ind, value.first to min(comp + 1, value.second)) } } '<' -> { return toMutableList().apply { set(ind, value.first to min(value.second, comp)) } to toMutableList().apply { set(ind, max(comp, value.first) to value.second) } } else -> error("instr " + s) } } var rangeSum = 0L fun process(range: List<Pair<Int, Int>>, ruleName: String) { if (range.empty() || ruleName == "R") { return } if (ruleName == "A") { rangeSum += range.count() return } val orders = rules[ruleName]!! var rangeLeft = range for (i in 0 ..< orders.size - 1) { val (match, noMatch) = rangeLeft.match(orders[i]) if (!match.empty()) { process(match, orders[i].substringAfter(":")) } rangeLeft = noMatch } process(rangeLeft,orders.last()) } process(listOf(1 to 4001, 1 to 4001, 1 to 4001, 1 to 4001), "in") return rangeSum } } fun main() { val testInstance = Day19(true) val instance = Day19(false) testInstance.part1().let { check(it == EXPECTED_1) { "part1: $it != $EXPECTED_1" } } println("part1 ANSWER: ${instance.part1()}") testInstance.part2().let { check(it == EXPECTED_2) { "part2: $it != $EXPECTED_2" } println("part2 ANSWER: ${instance.part2()}") } }
0
Kotlin
0
2
92f2e803b83c3d9303d853b6c68291ac1568a2ba
4,114
advent-of-code-2022
Apache License 2.0
src/main/kotlin/io/dp/PowerSetsII.kt
jffiorillo
138,075,067
false
{"Kotlin": 434399, "Java": 14529, "Shell": 465}
package io.dp import io.utils.runTests import java.util.* // https://leetcode.com/problems/subsets-ii/ class PowerSetsII { fun execute(input: IntArray, size: Int = 0): List<List<Int>> = when (size) { !in input.indices -> listOf(listOf()) else -> { execute(input, size + 1).let { previousSubsets -> previousSubsets + previousSubsets.map { it + input[size] } + listOf(listOf(input[size])) }.distinctBy { it.sorted() }.also { item -> item.sortedBy { it.size } } } } fun countSubsets(nums: IntArray, k: Int): Int { Arrays.sort(nums) var count = 0 var lo = 0 var hi = nums.size - 1 while (lo <= hi) { if (nums[lo] + nums[hi] > k) { hi-- } else { count += 1 shl (hi - lo) lo++ } } return count } } fun main() { runTests(listOf( intArrayOf(1, 2, 2) to listOf(emptyList(), listOf(2), listOf(1), listOf(1, 2, 2), listOf(2, 2), listOf(1, 2), emptyList()), intArrayOf(4, 4, 4, 1, 4) to listOf(emptyList(), listOf(1), listOf(1, 4), listOf(1, 4, 4), listOf(1, 4, 4, 4), listOf(1, 4, 4, 4, 4), listOf(4), listOf(4, 4), listOf(4, 4, 4), listOf(4, 4, 4, 4)) ),evaluation = {value, output -> value.map { it.toSet() }.toSet() == output.map { it.toSet() }.toSet() }) { (input, value) -> value to PowerSetsII().execute(input) } }
0
Kotlin
0
0
f093c2c19cd76c85fab87605ae4a3ea157325d43
1,382
coding
MIT License
advent-of-code-2022/src/Day07.kt
osipxd
572,825,805
false
{"Kotlin": 141640, "Shell": 4083, "Scala": 693}
fun main() { val testInput = readLines("Day07_test") val input = readLines("Day07") "Part 1" { part1(testInput) shouldBe 95437 measureAnswer { part1(input) } } "Part 2" { part2(testInput) shouldBe 24933642 measureAnswer { part2(input) } } } private fun part1(input: List<String>): Int { val dirs = inflateDirs(input).values return dirs.asSequence() .filter { it.size <= 100_000 } .sumOf { it.size } } private fun part2(input: List<String>): Int { val dirs = inflateDirs(input) val totalSpace = 70_000_000 val freeSpace = totalSpace - dirs.getValue("/").size val neededSpace = 30_000_000 - freeSpace var minimalToDelete = totalSpace for (dir in dirs.values) { if (dir.size in (neededSpace + 1) until minimalToDelete) minimalToDelete = dir.size } return minimalToDelete } private fun inflateDirs(input: List<String>): Map<String, Dir> { val rootDir = Dir("/") val dirs = mutableMapOf("/" to rootDir) val stack = ArrayDeque<Dir>() fun addDir(path: String) { dirs[path] = Dir(path) } fun goBack() { val currentDir = stack.removeFirst() if (stack.isNotEmpty()) stack.first().size += currentDir.size } for (line in input) { val parts = line.split(" ") val cwd = stack.firstOrNull()?.path.orEmpty() when (parts[0]) { "$" -> when (parts[1]) { "cd" -> when (parts[2]) { ".." -> goBack() "/" -> stack.addFirst(rootDir) else -> stack.addFirst(dirs.getValue("$cwd/${parts[2]}")) } } "dir" -> addDir("$cwd/${parts[1]}") else -> stack.first().size += parts[0].toInt() } } while (stack.isNotEmpty()) { goBack() } return dirs } private class Dir(val path: String, var size: Int = 0)
0
Kotlin
0
5
6a67946122abb759fddf33dae408db662213a072
1,956
advent-of-code
Apache License 2.0
day12/kotlin/corneil/src/main/kotlin/solution.kt
timgrossmann
224,991,491
true
{"HTML": 2739009, "Python": 169603, "Java": 157274, "Jupyter Notebook": 116902, "TypeScript": 113866, "Kotlin": 89503, "Groovy": 73664, "Dart": 47763, "C++": 43677, "CSS": 34994, "Ruby": 27091, "Haskell": 26727, "Scala": 11409, "Dockerfile": 10370, "JavaScript": 6496, "PHP": 4152, "Go": 2838, "Shell": 2493, "Rust": 2082, "Clojure": 567, "Tcl": 46}
package com.github.corneil.aoc2019.day12 import java.math.BigInteger import java.util.* import kotlin.math.abs typealias Axis = IntArray fun Axis.energy(): Int = this.sumBy { abs(it) } fun Axis.copy() = this.toList().toIntArray() class Moon( val id: Int, val pos: Axis, val vel: Axis ) { init { require(pos.size == 3) require(vel.size == 3) } fun applyGravity(moons: List<Moon>) { for (i in 0..2) { vel[i] += moons.count { pos[i] < it.pos[i] } - moons.count { pos[i] > it.pos[i] } } } fun move() { for (i in 0..2) { pos[i] += vel[i] } } fun totalEnergy(): Int = pos.energy() * vel.energy() fun copy() = Moon(id, pos.copy(), vel.copy()) fun snapShot(index: Int) = Pair(pos[index], vel[index]) override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as Moon if (!pos.contentEquals(other.pos)) return false if (!vel.contentEquals(other.vel)) return false return true } override fun hashCode(): Int { var result = pos.contentHashCode() result = 31 * result + vel.contentHashCode() return result } } typealias SnapShot = List<Pair<Int, Int>> class Orbits(val moons: List<Moon>) { fun advanceOrbit() { moons.forEach { moon -> moon.applyGravity(moons) } moons.forEach { moon -> moon.move() } } fun totalEnergy() = moons.sumBy { it.totalEnergy() } fun sameAs(original: Orbits): Boolean { return moons.filterIndexed { index, moon -> val orig = original.moons[index] moon == orig }.count() == moons.size } fun copy() = Orbits(moons.map { it.copy() }) fun snapShot(index: Int): SnapShot { return moons.map { it.snapShot(index) } } fun makeSnapShot(): Map<Int, SnapShot> = (0..2).map { it to snapShot(it) }.toMap() } fun readBlock(line: String): Map<String, String> { val tokens = StringTokenizer(line, "=,<>", true).toList().map { it as String } var name = "" var value = "" val result = mutableMapOf<String, String>() for (i in 0 until tokens.size) { val token = tokens[i] when (token) { "=" -> { name = tokens[i - 1].trim() require(name.length > 0) { "Expected name to be not empty" } value = tokens[i + 1].trim() require(value.length > 0) { "Expected value for $name to be not empty" } } ">", "," -> result.put(name, value) else -> Unit } } return result } fun readOrbits(lines: List<String>): Orbits { return Orbits(lines.map { line -> readBlock(line).map { it.key to it.value.toInt() }.toMap() }.map { arrayOf(it["x"]!!, it["y"]!!, it["z"]!!).toIntArray() }.mapIndexed { i, pos -> Moon(i, pos, arrayOf(0, 0, 0).toIntArray()) }) } fun mapAxis(input: Map<String, String>): Axis { return input.map { it.key to it.value.toInt() }.toMap().let { arrayOf(it["x"]!!, it["y"]!!, it["z"]!!).toIntArray() } } fun readPosition(line: String): Pair<Axis, Axis> { val position = mapAxis(readBlock(line.substringAfter("pos=").substringBefore(", vel="))) val velocity = mapAxis(readBlock(line.substringAfter("vel="))) return Pair(position, velocity) } // Find how often each axis cycles by comparing to a snapshot of the start. fun findCycles(orbits: Orbits): List<Long> { val snap = orbits.makeSnapShot().toMutableMap() val cycle = mutableListOf<Long>() var counter = 0L do { orbits.advanceOrbit() counter++ for (x in 0..2) { if (snap.containsKey(x) && snap[x] == orbits.snapShot(x)) { println("Cycle[$x]=$counter") cycle.add(counter) snap.remove(x) } } } while (snap.isNotEmpty()) return cycle } fun lowestCommonMultiplier(v1: BigInteger, v2: BigInteger): BigInteger { return (v1 * v2).abs() / v1.gcd(v2) } // This will work for any number of values fun lowestCommonMultiplier(list: List<BigInteger>): BigInteger { return if (list.size == 2) { lowestCommonMultiplier(list[0], list[1]) } else { val lcds = mutableListOf<BigInteger>() for (i in 0 until list.size - 1) { lcds.add(lowestCommonMultiplier(list[i], list[i + 1])) } lowestCommonMultiplier(lcds) } } fun main() { val input = """ <x=14, y=2, z=8> <x=7, y=4, z=10> <x=1, y=17, z=16> <x=-4, y=-1, z=1> """.trimIndent() val orbits = readOrbits(input.split('\n')) val original = orbits.copy() repeat(1000) { orbits.advanceOrbit() } val totalEnergy = orbits.totalEnergy() println("Total Energy=$totalEnergy") // Ensure still valid after refactoring require(totalEnergy == 9139) val totalOrbits = lowestCommonMultiplier(findCycles(original).map { it.toBigInteger() }) println("Total = $totalOrbits") // Ensure still valid after refactoring require(totalOrbits == BigInteger("420788524631496")) }
0
HTML
0
1
bb19fda33ac6e91a27dfaea27f9c77c7f1745b9b
5,328
aoc-2019
MIT License
src/Day05.kt
Kbzinho-66
572,299,619
false
{"Kotlin": 34500}
private fun String.getValues() = this .split(" ") .filter { parts -> parts.all { it.isDigit() } } .map { it.toInt() } private fun Array<ArrayDeque<Char>>.move(from: Int, to: Int) { this[to].add(this[from].removeLastOrNull() ?: ' ') } private fun Array<ArrayDeque<Char>>.move(n: Int, from: Int, to: Int) { this[from].takeLast(n).forEach { this[to].add(it) }.also { repeat (n) { this[from].removeLast() } } } private data class StacksState( val stacks: Array<ArrayDeque<Char>>, val moves: List<String> ) private fun parseInput(input: List<String>): StacksState { val stacks = initializeStacks(input.takeWhile { it.isNotEmpty() }) val moves = input.filter { it.startsWith("move") } return StacksState(stacks, moves) } private fun initializeStacks(input: List<String>): Array<ArrayDeque<Char>> { val brackets = Regex("[\\[\\]]") val numberOfStacks = input.last().takeLast(4).trim().toInt() val stacks = Array<ArrayDeque<Char>>(numberOfStacks) { ArrayDeque() } input.dropLast(1).reversed().map { row -> val crates = row.chunked(4).map { rawCrate -> val crate = rawCrate.trim().replace(brackets, "") if (crate.isNotEmpty()) crate[0] else ' ' } crates.forEachIndexed { s, crate -> if (crate != ' ') { stacks[s].add(crate) } } } return stacks } fun main() { fun part1(input: StacksState): String { val stacks = input.stacks for (move in input.moves) { val (n, from, to) = move.getValues() repeat (n) { stacks.move(from - 1, to - 1) } } return stacks.fold(""){ top, crate -> top + crate.last() } } fun part2(input: StacksState): String { val stacks = input.stacks for (move in input.moves) { val (n, from, to) = move.getValues() stacks.move(n, from - 1, to - 1) } return stacks.fold(""){ top, crate -> top + crate.last() } } // Testar os casos básicos val testInput = readInput("../inputs/Day05_test") sanityCheck(part1(parseInput(testInput)), "CMZ") sanityCheck(part2(parseInput(testInput)), "MCD") val input = readInput("../inputs/Day05") // Como as funções são impuras, precisa criar um "StacksState" para cada uma delas println("Parte 1 = ${part1(parseInput(input))}") println("Parte 2 = ${part2(parseInput(input))}") }
0
Kotlin
0
0
e7ce3ba9b56c44aa4404229b94a422fc62ca2a2b
2,537
advent_of_code_2022_kotlin
Apache License 2.0
src/main/kotlin/advent2019/day10/day10.kt
davidpricedev
225,621,794
false
null
package advent2019.day10 import kotlin.math.PI import kotlin.math.atan2 import kotlin.math.pow import kotlin.math.sqrt /** * Part1 Notes: * 1st translate dots and hashes into a list of asteroids w/ coordinates * 2nd for each asteroid calculate how many asteroids it can "see" * - this means finding ray collisions or being able to answer is point x on the line between A -> B? * - alternatively, if we calculate the angle in radians or degrees at which the other asteroids are located * we could simplify that to just picking one when the angles for more than one asteroid are equivalent * this appears to be atan2(dy,dx) to calculate the angle in radians * Part2 Notes: * Angles matter here, so we might need to flip things around or figure out what our native zero angle is and adjust for it * instead of doing a distinct + count to get the number, we can simply add them to a list and sort by distance * Then we can merge the x,y,angle,list-depth into an object and sort by "$listDepth_$radian" and pick the 200th element */ fun main() { // part1 println(pickBestAsteroid(inputToAsteroids(getPart1Input()))) // part2 println(find200th(inputToAsteroids(getPart1Input()))) } sealed class MaybeRoid { data class Asteroid(val x: Int, val y: Int) : MaybeRoid() { fun toSingleNumber() = x * 100 + y } object EmptySpace : MaybeRoid() } fun inputToAsteroids(input: List<String>) = input.mapIndexed { y, line -> line.mapIndexed { x, char -> if (char == '#') MaybeRoid.Asteroid(x, y) else MaybeRoid.EmptySpace } }.flatten().filter { it != MaybeRoid.EmptySpace } fun pickBestAsteroid(asteroids: List<MaybeRoid>) = asteroids.map { Pair(it, calculateVisible(it, asteroids)) }.maxBy { it.second } fun calculateVisible(center: MaybeRoid, others: List<MaybeRoid>) = calculateAngles(center, others).filter { it != -99.9 }.distinct().count() fun calculateAngles(center: MaybeRoid, others: List<MaybeRoid>) = when (center) { MaybeRoid.EmptySpace -> listOf(-99.9) is MaybeRoid.Asteroid -> others.map { other -> when (other) { MaybeRoid.EmptySpace -> -99.9 center -> -99.9 is MaybeRoid.Asteroid -> calculateAngle(center, other) } } } /** * Rotates angle coordinates by 90degrees anti-clockwise (so "up" is zero angle) * and shifts the range from (-PI,PI) to (0,2PI) */ fun rotateAnti90(angle: Double) = (angle + (2.5 * PI)) % (2 * PI) fun calculateAngle(a: MaybeRoid.Asteroid, b: MaybeRoid.Asteroid) = atan2(b.y - a.y.toDouble(), b.x - a.x.toDouble()) fun distance(a: MaybeRoid.Asteroid, b: MaybeRoid.Asteroid) = sqrt((a.x - b.x).toDouble().pow(2.0) + (a.y - b.y).toDouble().pow(2.0)) data class SurveyData( val x: Int, val y: Int, val angle: Double, val distance: Double = -1.0, val ordinalDistance: Int = -1 ) { companion object { fun bogusValue() = SurveyData(-1, -1, -99.9) } } fun calculateAngleData(center: MaybeRoid, others: List<MaybeRoid>) = when (center) { MaybeRoid.EmptySpace -> listOf(SurveyData.bogusValue()) is MaybeRoid.Asteroid -> others.map { other -> when (other) { MaybeRoid.EmptySpace -> SurveyData.bogusValue() center -> SurveyData.bogusValue() is MaybeRoid.Asteroid -> SurveyData(other.x, other.y, angle = rotateAnti90(calculateAngle(center, other)), distance = distance(center, other)) } } } fun find200th(asteroids: List<MaybeRoid>): SurveyData { val center = pickBestAsteroid(asteroids)?.first ?: asteroids.first() val surveyData = calculateAngleData(center, asteroids).filterNot { it == SurveyData.bogusValue()} // turn distance and radians into ordinal distance for each angle val ordinaledData = surveyData.groupBy { it.angle }.map { angleInfo -> angleInfo.value .sortedBy { it.distance } .mapIndexed { i, x -> x.copy(ordinalDistance = i) } }.flatten() val finalData = ordinaledData.sortedWith(compareBy({it.ordinalDistance}, {it.angle})) return finalData[199] } fun getPart1Input() = """ ##.###.#.......#.#....#....#..........#. ....#..#..#.....#.##.............#...... ...#.#..###..#..#.....#........#......#. #......#.....#.##.#.##.##...#...#......# .............#....#.....#.#......#.#.... ..##.....#..#..#.#.#....##.......#.....# .#........#...#...#.#.....#.....#.#..#.# ...#...........#....#..#.#..#...##.#.#.. #.##.#.#...#..#...........#..........#.. ........#.#..#..##.#.##......##......... ................#.##.#....##.......#.... #............#.........###...#...#.....# #....#..#....##.#....#...#.....#......#. .........#...#.#....#.#.....#...#...#... .............###.....#.#...##........... ...#...#.......#....#.#...#....#...#.... .....#..#...#.#.........##....#...#..... ....##.........#......#...#...#....#..#. #...#..#..#.#...##.#..#.............#.## .....#...##..#....#.#.##..##.....#....#. ..#....#..#........#.#.......#.##..###.. ...#....#..#.#.#........##..#..#..##.... .......#.##.....#.#.....#...#........... ........#.......#.#...........#..###..## ...#.....#..#.#.......##.###.###...#.... ...............#..#....#.#....#....#.#.. #......#...#.....#.#........##.##.#..... ###.......#............#....#..#.#...... ..###.#.#....##..#.......#.............# ##.#.#...#.#..........##.#..#...##...... ..#......#..........#.#..#....##........ ......##.##.#....#....#..........#...#.. #.#..#..#.#...........#..#.......#..#.#. #.....#.#.........#............#.#..##.# .....##....#.##....#.....#..##....#..#.. .#.......#......#.......#....#....#..#.. ...#........#.#.##..#.#..#..#........#.. #........#.#......#..###....##..#......# ...#....#...#.....#.....#.##.#..#...#... #.#.....##....#...........#.....#...#... """.trimIndent().trim().split("\n")
0
Kotlin
0
0
2283647e5b4ed15ced27dcf2a5cf552c7bd49ae9
6,423
adventOfCode2019
Apache License 2.0
src/Day02.kt
freszu
573,122,040
false
{"Kotlin": 32507}
private enum class Move { ROCK, PAPER, SCISSORS; fun score(against: Move) = when { this == against -> 3 this.losingAgainst() == against -> 0 this.winsAgainst() == against -> 6 else -> throw IllegalStateException("Invalid move combination: $this vs $against") } fun losingAgainst() = Move.values()[(this.ordinal + 1) % Move.values().size] fun winsAgainst() = Move.values()[(this.ordinal + 2) % Move.values().size] fun scoreForMove() = this.ordinal + 1 companion object { fun fromChar(char: Char) = when (char) { 'A', 'X' -> ROCK 'B', 'Y' -> PAPER 'C', 'Z' -> SCISSORS else -> throw IllegalArgumentException("Invalid move") } fun fromElfCode(opponentMove: Move, expectedResult: Char) = when (expectedResult) { 'X' -> opponentMove.winsAgainst() 'Y' -> opponentMove 'Z' -> opponentMove.losingAgainst() else -> throw IllegalArgumentException("Invalid result") } } } fun main() { fun part1(input: List<String>) = input.map { val opponentMove = Move.fromChar(it[0]) val myMove = Move.fromChar(it[2]) myMove.scoreForMove() + myMove.score(against = opponentMove) }.sum() fun part2(input: List<String>) = input.map { val opponentMove = Move.fromChar(it[0]) val myMove = Move.fromElfCode(opponentMove, it[2]) myMove.scoreForMove() + myMove.score(against = opponentMove) }.sum() // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") val dayInput = readInput("Day02") check(part1(testInput) == 15) println(part1(dayInput)) check(part2(testInput) == 12) println(part2(dayInput)) }
0
Kotlin
0
0
2f50262ce2dc5024c6da5e470c0214c584992ddb
1,814
aoc2022
Apache License 2.0
src/main/kotlin/Day02.kt
Mariyo
728,179,583
false
{"Kotlin": 10845}
class Day02(private val bag: Bag) { fun puzzle1IsPossible(game: Game): Boolean { return bag.hasEnoughColoredCubes(game) } fun puzzle1SumAllPossibleGameIds(games: List<Game>): Int { return games.filter { game -> bag.hasEnoughColoredCubes(game) }.sumOf { game -> game.id } } fun loadGameFromInput(input: String): Game { val gameSegments = input.split(":") if (gameSegments.size != 2) throw RuntimeException("Invalid Game input") val cubeSets = mutableListOf<CubeSet>() val redRegex = Regex("(\\d+)\\s+red") val greenRegex = Regex("(\\d+)\\s+green") val blueRegex = Regex("(\\d+)\\s+blue") gameSegments[1].split(";").forEach { cubeSegment -> val redCount = redRegex.find(cubeSegment)?.groups?.get(1)?.value?.toInt() ?: 0 val greenCount = greenRegex.find(cubeSegment)?.groups?.get(1)?.value?.toInt() ?: 0 val blueCount = blueRegex.find(cubeSegment)?.groups?.get(1)?.value?.toInt() ?: 0 cubeSets.add( CubeSet(redCount, greenCount, blueCount) ) } return Game( gameSegments[0].replace("Game ", "").toInt(), cubeSets ) } fun puzzle1SumAllPossibleGameIdsFromFile(fileName: String): Int { return readInput(fileName) .map { input -> Day02(bag).loadGameFromInput(input) } .filter { game -> bag.hasEnoughColoredCubes(game) } .sumOf { game -> game.id } } } data class Game(val id: Int, val cubeSets: List<CubeSet>) data class CubeSet(val redCount: Int, val greenCount: Int, val blueCount: Int) class Bag(private val redTotal: Int, private val greenTotal: Int, private val blueTotal: Int) { fun hasEnoughColoredCubes(game: Game): Boolean { game.cubeSets.forEach { cubeSet -> when { cubeSet.redCount > redTotal -> return false cubeSet.greenCount > greenTotal -> return false cubeSet.blueCount > blueTotal -> return false } } return true } }
0
Kotlin
0
0
da779852b808848a26145a81cbf4330f6af03d84
2,237
advent-of-code-kotlin-2023
Apache License 2.0
src/Day03.kt
MSchu160475
573,330,549
false
{"Kotlin": 5456}
fun main() { fun part1(input: List<String>): Int { //ASCII A-Z 65-90 -38 //ASCII a-z 97-122 -96 return input.sumOf { val firstHalf = it.substring(0, (it.length / 2)).toCharArray() val secondHalf = it.substring(it.length / 2).toSet() firstHalf.intersect(secondHalf).map { it -> if (it.code in 65..90) it.code - 38 else it.code - 96 } .first() } } fun part2(input: List<String>): Int { //ASCII A-Z 65-90 -38 //ASCII a-z 97-122 -96 return input.chunked(3).map { it[0].toCharArray().intersect(it[1].toCharArray().intersect(it[2].toSet())) .map { it -> if (it.code in 65..90) it.code - 38 else it.code - 96 } .first() }.sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
c6f9a0892a28f0f03b95768b6611e520c85db75c
1,084
advent-of-code-2022-kotlin
Apache License 2.0
src/main/kotlin/day03/solution.kt
bukajsytlos
433,979,778
false
{"Kotlin": 63913}
package day03 import java.io.File fun main() { val lines = File("src/main/kotlin/day03/input.txt").readLines() val binaryCodeCounts = IntArray(12) { 0 } val reportDatBitsHistogram = lines .map { it.toCharArray() } .fold(binaryCodeCounts) { counter, reportLine -> for (i in counter.indices) { counter[i] += reportLine[i].digitToInt() } counter } val gammaRate = reportDatBitsHistogram .map { if (it > lines.size / 2) 0 else 1 } .joinToString(separator = "") .toCharArray() .binaryToDecimal() val epsilonRate = reportDatBitsHistogram .map { if (it > lines.size / 2) 1 else 0 } .joinToString(separator = "") .toCharArray() .binaryToDecimal() println(gammaRate) //1519 println(epsilonRate) //2576 println(gammaRate * epsilonRate) //Part 2 val diagnosticReportLines = lines .map { it.toCharArray() } val oxygenGeneratorRating = filterOxygenGeneratorRating(diagnosticReportLines, 0)[0].binaryToDecimal() println(oxygenGeneratorRating) //3597 val co2ScrubberRating = filterCO2ScrubberRating(diagnosticReportLines, 0)[0].binaryToDecimal() println(co2ScrubberRating) //1389 println(oxygenGeneratorRating * co2ScrubberRating) } fun filterOxygenGeneratorRating(reportData: List<CharArray>, reportIndex: Int): List<CharArray> = filterDiagnosticReport( reportData, reportIndex ) { filterSize, significantBit, reportSize -> (filterSize + if (reportSize % 2 == 0 && significantBit != null && significantBit == 1) 1 else 0) > reportSize / 2 } fun filterCO2ScrubberRating(reportData: List<CharArray>, reportIndex: Int): List<CharArray> = filterDiagnosticReport( reportData, reportIndex ) { filterSize, significantBit, reportSize -> (filterSize - if (reportSize % 2 == 0 && significantBit != null && significantBit == 0) 1 else 0) < (reportSize + 1) / 2 } fun filterDiagnosticReport( reportData: List<CharArray>, reportIndex: Int, evaluationPredicate: (Int, Int?, Int) -> Boolean ): List<CharArray> { if (reportIndex == reportData[0].size || reportData.size == 1) { return reportData } val filteredReportData = reportData .partition { it[reportIndex] == '1' } .toList() .first { evaluationPredicate( it.size, if (it.isNotEmpty()) it[0][reportIndex].digitToInt() else null, reportData.size ) } return filterDiagnosticReport(filteredReportData, reportIndex + 1, evaluationPredicate) } fun CharArray.binaryToDecimal(): Int { var value = 0 for (char in this) { value = value shl 1 value += char - '0' } return value }
0
Kotlin
0
0
f47d092399c3e395381406b7a0048c0795d332b9
2,832
aoc-2021
MIT License
2019/03 - Crossed Wires/kotlin/src/app.kt
Adriel-M
225,250,242
false
null
import java.io.File import kotlin.math.absoluteValue enum class Direction(val dx: Int, val dy: Int) { UP(0, -1), DOWN(0, 1), LEFT(-1, 0), RIGHT(1, 0) } data class Move(val direction: Direction, val magnitude: Int) fun extractMovesFromString(moveString: String): List<Move> { return moveString.split(",").map { val direction = when (it[0]) { 'U' -> Direction.UP 'D' -> Direction.DOWN 'L' -> Direction.LEFT 'R' -> Direction.RIGHT else -> Direction.UP } val magnitude = it.substring(1).toInt() Move(direction, magnitude) } } fun getWireMoves(path: String): Pair<List<Move>, List<Move>> { val lines = File(path).readLines() return Pair( extractMovesFromString(lines[0]), extractMovesFromString(lines[1]) ) } fun getCoordinatesFromMoves(moves: List<Move>): Set<Pair<Int, Int>> { val coordinates: MutableSet<Pair<Int, Int>> = mutableSetOf() var currX = 0 var currY = 0 for (move in moves) { for (x in 0 until move.magnitude) { currX += move.direction.dx currY += move.direction.dy coordinates.add(Pair(currX, currY)) } } return coordinates.toSet() } fun getDistancesFromMoves(moves: List<Move>): Map<Pair<Int, Int>, Int> { val distances: MutableMap<Pair<Int, Int>, Int> = mutableMapOf() var currX = 0 var currY = 0 var currDistance = 0 for (move in moves) { for (x in 0 until move.magnitude) { currX += move.direction.dx currY += move.direction.dy currDistance += 1 val key = Pair(currX, currY) if (!distances.containsKey(key)) { distances[key] = currDistance } } } return distances.toMap() } fun getManhattanDistance(x: Int, y: Int): Int { return x.absoluteValue + y.absoluteValue } fun part1(moves1: List<Move>, moves2: List<Move>): Int { val coords1 = getCoordinatesFromMoves(moves1) val coords2 = getCoordinatesFromMoves(moves2) var closestIntersection = Int.MAX_VALUE for ((x, y) in coords1 intersect coords2) { val manhattanDistance = getManhattanDistance(x, y) if (manhattanDistance < closestIntersection) { closestIntersection = manhattanDistance } } return closestIntersection } fun part2(moves1: List<Move>, moves2: List<Move>): Int { val coords1 = getCoordinatesFromMoves(moves1) val coords2 = getCoordinatesFromMoves(moves2) val distances1 = getDistancesFromMoves(moves1) val distances2 = getDistancesFromMoves(moves2) var closestDistance = Int.MAX_VALUE for ((x, y) in coords1 intersect coords2) { val key = Pair(x, y) val d1 = distances1[key] val d2 = distances2[key] if (d1 == null || d2 == null) { continue } val totalDistance = d1 + d2 if (totalDistance < closestDistance) { closestDistance = totalDistance } } return closestDistance } fun main() { val (moves1, moves2) = getWireMoves("../input") println("===== Part 1 =====") println(part1(moves1, moves2)) println("===== Part 2 =====") println(part2(moves1, moves2)) }
0
Kotlin
0
0
ceb1f27013835f13d99dd44b1cd8d073eade8d67
3,300
advent-of-code
MIT License
src/day02/day03.kt
zoricbruno
573,440,038
false
{"Kotlin": 13739}
package day02 import readInput fun getSignPoints(sign: Char): Int { val points = hashMapOf<Char, Int>('A' to 1, 'B' to 2, 'C' to 3) return points[sign]!! } fun mapToOutcome(sign: Char): Char { val mapping = hashMapOf<Char, Char>('X' to 'A', 'Y' to 'B', 'Z' to 'C') return mapping[sign]!! } fun mapToAdapt(sign: Char, elf: Char): Char { val wins = hashMapOf<Char, Char>('A' to 'C', 'B' to 'A', 'C' to 'B') val loss = hashMapOf<Char, Char>('A' to 'B', 'B' to 'C', 'C' to 'A') when (sign) { 'Y' -> return elf 'X' -> return wins[elf]!! 'Z' -> return loss[elf]!! } throw IllegalArgumentException() } fun getUserOutcomePoints(user: Char, elf: Char): Int { val wins = hashMapOf<Char, Char>('A' to 'C', 'B' to 'A', 'C' to 'B') if (elf == user) return 3 if (wins[user] == elf) return 6 return 0 } fun part1(input: List<String>): Int { var total = 0; for (line in input) { val elf: Char = line.first() val user: Char = mapToOutcome(line.last()) total += getUserOutcomePoints(user, elf) + getSignPoints(user) } return total } fun part2(input: List<String>): Int { var total = 0; for (line in input) { val elf: Char = line.first() val user: Char = mapToAdapt(line.last(), elf) total += getUserOutcomePoints(user, elf) + getSignPoints(user) } return total } fun main() { val day = "Day02" val test = "${day}_test" val testInput = readInput(day, test) val input = readInput(day, day) val testFirst = part1(testInput) println(testFirst) check(testFirst == 15) println(part1(input)) val testSecond = part2(testInput) println(testSecond) check(testSecond == 12) println(part2(input)) }
0
Kotlin
0
0
16afa06aff0b6e988cbea8081885236e4b7e0555
1,786
kotlin_aoc_2022
Apache License 2.0
advent/src/test/kotlin/org/elwaxoro/advent/y2020/Dec16.kt
elwaxoro
328,044,882
false
{"Kotlin": 376774}
package org.elwaxoro.advent.y2020 import org.elwaxoro.advent.PuzzleDayTester class Dec16 : PuzzleDayTester(16, 2020) { override fun part1(): Any = parse().let { shebang -> shebang.rules.map { it.range }.flatten().toSet().let { validNums -> shebang.otherTickets.map { it.numbers.filterNot { validNums.contains(it) } }.flatten().sum() } } private data class Shebang(val rules: List<Rule>, val yourTicket: Ticket, val otherTickets: List<Ticket>) private data class Rule(val name: String, val range: Set<Long>) { companion object { fun parseRule(input: String): Rule { val splitA = input.split(": ") val name = splitA[0] val ranges = splitA[1].split(" or ") val range1 = ranges[0].split("-").map { it.toLong() }.toRangeList() val range2 = ranges[1].split("-").map { it.toLong() }.toRangeList() return Rule(name, range1.plus(range2).toSet()) } fun List<Long>.toRangeList() = (first()..last()).toList() } fun contains(input: Long): Boolean = range.contains(input) } private data class Ticket(val idx: Int, val numbers: List<Long>) { companion object { fun parseTicket(idx: Int, input: String): Ticket = Ticket(idx, input.split(",").map { it.toLong() }) } } private fun parse() = load(delimiter = "\n\n").let { sections -> Shebang( rules = sections[0].split("\n").map { Rule.parseRule(it) }, yourTicket = Ticket.parseTicket(-1, sections[1].split("\n")[1]), otherTickets = sections[2].split("\n").mapIndexedNotNull { idx, str -> if (idx == 0) { null } else { Ticket.parseTicket(idx, str) } } ) } /** * STOP READING HERE NO SERIOUSLY JUST TURN BACK NOWWWWWW */ override fun part2(): Any { val shebang = parse() val masterValidSet: Set<Long> = shebang.rules.map { it.range }.flatten().toSet() // get rid of all the crap tickets from puzzle 1 val validTickets: List<Ticket> = shebang.otherTickets.filter { it.numbers.all { masterValidSet.contains(it) } }.plus(shebang.yourTicket) // map ticket number index to a list of all valid choices for that index val sectionIdxToChoiceMap: Map<Int, List<String>> = validTickets.map { ticket -> ticket.numbers.mapIndexed { idx, num -> idx to shebang.rules.filter { rule -> rule.contains(num) }.map { it.name } } }.flatten().groupBy({ it.first }, { it.second }) .map { // map ticket number index to all lists of valid choices for that index // reduce the list of lists to a single list of common choices it.key to it.value.reduce { acc, list -> acc.intersect(list).toList() } }.toMap() // holy fuck how many different ways can I map this shit val sectionAssignments: MutableMap<String, Int> = shebang.rules.map { it.name to -1 }.toMap(mutableMapOf()) // oh look, a while loop. super original. while (sectionAssignments.any { it.value < 0 }) { sectionIdxToChoiceMap.forEach { sectionChoices -> // just gonna bang thru these things over and over till everything just has one valid match. SUPER EFFICIENT sectionChoices.value.filter { sectionAssignments[it] == -1 }.takeIf { it.size == 1 }?.let { sectionAssignments[it.single()] = sectionChoices.key } } } // OK NOW LOOK HERE YOU LITTLE SHIT YOU CANT JUST KEEP MAPPING SHIT TO OTHER RANDOM SHIT return sectionAssignments.map { assignment -> assignment.key to shebang.yourTicket.numbers[assignment.value] } .filter { it.first.contains("departure") } .fold(1L) { acc, op -> acc * op.second } } }
0
Kotlin
4
0
1718f2d675f637b97c54631cb869165167bc713c
4,074
advent-of-code
MIT License
src/Day05.kt
pavlo-dh
572,882,309
false
{"Kotlin": 39999}
fun main() { fun String.getCrate(stackIndex: Int): Char? { val crateIndex = 4 * stackIndex + 1 if (crateIndex > this.length) return null val crate = this[crateIndex] return if (crate.isWhitespace()) null else crate } fun createStacks(input: List<String>, inputDelimiterIndex: Int): List<ArrayDeque<Char>> { val stacks = input[inputDelimiterIndex - 1].split(" ").map { ArrayDeque<Char>() } for (i in inputDelimiterIndex - 2 downTo 0) { for (j in stacks.indices) { input[i].getCrate(j)?.let { crate -> stacks[j].addLast(crate) } } } return stacks } fun part1(input: List<String>): String { val inputDelimiterIndex = input.indexOfFirst(String::isEmpty) val stacks = createStacks(input, inputDelimiterIndex) for (i in inputDelimiterIndex + 1 until input.size) { val (_, amountString, _, fromString, _, toString) = input[i].split(' ') repeat(amountString.toInt()) { stacks[toString.toInt() - 1].addLast(stacks[fromString.toInt() - 1].removeLast()) } } return stacks.map { it.last() }.joinToString(separator = "") } fun part2(input: List<String>): String { val inputDelimiterIndex = input.indexOfFirst(String::isEmpty) val stacks = createStacks(input, inputDelimiterIndex) for (i in inputDelimiterIndex + 1 until input.size) { val (_, amountString, _, fromString, _, toString) = input[i].split(' ') val movedCrated = ArrayDeque<Char>() repeat(amountString.toInt()) { movedCrated.addFirst(stacks[fromString.toInt() - 1].removeLast()) } stacks[toString.toInt() - 1].addAll(movedCrated) } return stacks.map { it.last() }.joinToString(separator = "") } // test if implementation meets criteria from the description, like: val testInput = readInput("Day05_test") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = readInput("Day05") println(part1(input)) println(part2(input)) } private operator fun <E> List<E>.component6(): E = this[5]
0
Kotlin
0
2
c10b0e1ce2c7c04fbb1ad34cbada104e3b99c992
2,234
aoc-2022-in-kotlin
Apache License 2.0
src/Day05.kt
jfiorato
573,233,200
false
null
import java.util.* fun main() { fun part1(input: List<String>): String { val stacks: MutableMap<Int, Stack<String>> = mutableMapOf() for (line in input) { if (line.take(4) == "move") { val moveRegex = """move (\d*) from (\d*) to (\d*)""".toRegex() val moveMatchResult = moveRegex.find(line)!! repeat(moveMatchResult.groupValues[1].toInt()) { val popped = stacks[moveMatchResult.groupValues[2].toInt()]?.pop() stacks[moveMatchResult.groupValues[3].toInt()]?.push(popped) } } else { val stackRegex = """\[[A-Z]]""".toRegex() val stackMatchResults = stackRegex.findAll(line) stackMatchResults.forEach { val stack = it.range.first/4 if (stacks[stack+1] == null) stacks[stack+1] = Stack<String>() stacks[stack+1]?.insertElementAt(it.value[1].toString(), 0) } } } return stacks.toSortedMap().values.joinToString(separator = "") { it.last() } } fun part2(input: List<String>): String { val stacks: MutableMap<Int, Stack<String>> = mutableMapOf() for (line in input) { if (line.take(4) == "move") { val moveRegex = """move (\d*) from (\d*) to (\d*)""".toRegex() val moveMatchResult = moveRegex.find(line)!! val popped: Stack<String> = Stack<String>() repeat(moveMatchResult.groupValues[1].toInt()) { popped.push(stacks[moveMatchResult.groupValues[2].toInt()]?.pop()!!) } while (popped.isNotEmpty()) { stacks[moveMatchResult.groupValues[3].toInt()]?.push(popped.pop()) } } else { val stackRegex = """\[[A-Z]]""".toRegex() val stackMatchResults = stackRegex.findAll(line) stackMatchResults.forEach { val stack = it.range.first/4 if (stacks[stack+1] == null) stacks[stack+1] = Stack<String>() stacks[stack+1]?.insertElementAt(it.value[1].toString(), 0) } } } return stacks.toSortedMap().values.joinToString(separator = "") { it.last() } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day05_test") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = readInput("Day05") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
4455a5e9c15cd067d2661438c680b3d7b5879a56
2,668
kotlin-aoc-2022
Apache License 2.0
src/main/kotlin/aoc2021/Day11.kt
davidsheldon
565,946,579
false
{"Kotlin": 161960}
package aoc2021 import utils.InputUtils typealias Int2d = Array<IntArray> fun Int2d.copy() = map { it.clone() }.toTypedArray() fun Int2d.countZeros() = sumOf { it.count { i -> i == 0 } } fun Int2d.allZeros() = all { it.all { it == 0 } } class Cave(val energy: Int2d) { fun step(): Cave { val copy = energy.map { it.map { o -> o + 1 }.toIntArray() }.toTypedArray() do { var flashes = 0 for (y in copy.indices) { for (x in copy[y].indices) { if (copy[y][x] > 9) { flashes++ copy[y][x] = 0 flash(x, y, copy) } } } } while (flashes > 0) return Cave(copy) } private fun flash(x: Int, y: Int, copy: Array<IntArray>) { for (dX in -1..1) { for (dY in -1..1) { val nY = y + dY val nX = x + dX if (nY in copy.indices && nX in copy[nY].indices && copy[nY][nX] != 0 ) { copy[nY][nX]++ } } } } } fun List<String>.toCave() = Cave( Array(size) { i -> get(i).let { row -> IntArray(row.length) { row[it].digitToInt() } } }) fun main() { val testInput = """5483143223 2745854711 5264556173 6141336146 6357385478 4167524645 2176841721 6882881134 4846848554 5283751526""".split("\n") fun part1(input: List<String>): Int { val cave = input.toCave() return (1..100).runningFold(cave) { acc, _ -> acc.step()}.sumOf { it.energy.countZeros() } } fun part2(input: List<String>): Int { return generateSequence(input.toCave(), Cave::step) .withIndex() .first { (_, cave) -> cave.energy.allZeros() } .index } // test if implementation meets criteria from the description, like: val testValue = part1(testInput) println(testValue) check(testValue == 1656) val puzzleInput = InputUtils.downloadAndGetLines(2021, 11) val input = puzzleInput.toList() println(part1(input)) println("=== Part 2 ===") println(part2(testInput)) println(part2(input)) }
0
Kotlin
0
0
5abc9e479bed21ae58c093c8efbe4d343eee7714
2,304
aoc-2022-kotlin
Apache License 2.0
src/main/kotlin/solutions/Day13DistressSignal.kt
aormsby
571,002,889
false
{"Kotlin": 80084}
package solutions import utils.Input import utils.Solution import java.util.* // run only this day fun main() { Day13DistressSignal() } class Day13DistressSignal : Solution() { private val ten = ':' init { begin("Day 13 - Distress Signal") // remove blank lines, replace 10s with colon -> next highest ASCII code after 9 val input = Input.parseLines(filename = "/d13_packets.txt") .mapNotNull { if (it.isBlank()) null else it.replace("10", ten.toString()) } // chunking and pairing for part 1 only val pairs = input.chunked(2) .map { Pair(it.first(), it.last()) } val sol1 = getCorrectlyOrderedPairs(pairs) output("Sum of Correctly Ordered Pair Indices", sol1) val sol2 = findDecoderKey(input) output("Decoder Key", sol2) } // check each packet pair and aggregate the indices of correctly ordered pairs private fun getCorrectlyOrderedPairs( packets: List<Pair<String, String>> ): Int = packets.foldIndexed(initial = 0) { i, acc, p -> acc + checkPackets(p, i + 1) // +1 since lists start at 0 } // create stacks of strings (reversed for popping) and make comparisons private fun checkPackets(packet: Pair<String, String>, index: Int): Int { val left = Stack<Char>().apply { addAll(packet.first.map { it }.reversed()) } val right = Stack<Char>().apply { addAll(packet.second.map { it }.reversed()) } while (left.isNotEmpty() && right.isNotEmpty()) { val lChar = left.pop() val rChar = right.pop() when { // don't care if same, next lChar == rChar -> continue // when only one side is a comma, // push the other side's current char to its stack to replay, // move to next lChar == ',' -> { right.push(rChar) continue } rChar == ',' -> { left.push(lChar) continue } // when only one side is a digit (or :) compared to a list, // push this side's current char to its stack and an end bracket to simulate list, // move to next // (this treats the current char as an open bracket) (lChar.isDigit() || lChar == ten) && rChar == '[' -> { left.addAll(listOf(']', lChar)) continue } (rChar.isDigit() || rChar == ten) && lChar == '[' -> { right.addAll(listOf(']', rChar)) continue } // direct comparisons... // if left list ends first, break and return current index // else right list is short, return 0 (not current index) lChar == ']' -> break rChar == ']' -> return 0 // if left greater, return 0 (not current index), // else break and return current index lChar > rChar -> return 0 lChar < rChar -> break } } return index } // add the new packets, sort, find, multiply private fun findDecoderKey(input: List<String>): Int { val two = "[[2]]" val six = "[[6]]" return with( (input + listOf(two, six)) .sortedWith(PacketSorter()) ) { (indexOf(two) + 1) * (indexOf(six) + 1) } } // quick sorter using packet checker from part 1! private inner class PacketSorter : Comparator<String> { override fun compare(s1: String, s2: String): Int = if (checkPackets(Pair(s1, s2), 1) == 1) -1 else 1 } }
0
Kotlin
0
0
1bef4812a65396c5768f12c442d73160c9cfa189
3,949
advent-of-code-2022
MIT License
lib/src/main/kotlin/com/bloidonia/advent/day16/Day16.kt
timyates
433,372,884
false
{"Kotlin": 48604, "Groovy": 33934}
package com.bloidonia.advent.day16 import com.bloidonia.advent.readText sealed class Packet(val version: Int, val type: Int) { abstract fun versionSum(): Long abstract fun run(): Long } class Literal(version: Int, type: Int, private val value: Long) : Packet(version, type) { override fun versionSum() = version.toLong() override fun run() = value } class Operator(version: Int, type: Int, private val contents: List<Packet>) : Packet(version, type) { override fun versionSum() = version + contents.sumOf { it.versionSum() } override fun run(): Long = when (type) { 0 -> contents.fold(0) { acc, p -> acc + p.run() } 1 -> contents.fold(1) { acc, p -> acc * p.run() } 2 -> contents.minOf { it.run() } 3 -> contents.maxOf { it.run() } 5 -> if (contents[0].run() > contents[1].run()) 1 else 0 6 -> if (contents[0].run() < contents[1].run()) 1 else 0 else -> if (contents[0].run() == contents[1].run()) 1 else 0 } } fun Char.toBin(): String = Character.digit(this, 16).toString(2).padStart(4, '0') fun String.toBin() = this.flatMap { it.toBin().toCharArray().toList() } fun String.parse(): Packet = ArrayDeque(this.toBin()).let { deque -> fun parsePacket(): Packet { val takeBits = { n: Int -> (0 until n).map { deque.removeFirst() }.joinToString("") } val version = takeBits(3).toInt(2) val type = takeBits(3).toInt(2) if (type == 4) { // it's a literal val sb = StringBuilder() do { val chunk = takeBits(5).apply { sb.append(this.substring(1)) } } while (chunk[0] == '1') return Literal(version, type, sb.toString().toLong(2)) } else { // it's an operator val opType = takeBits(1).toInt(2) val packets = mutableListOf<Packet>() if (opType == 0) { // length type operator var dataLength = takeBits(15).toInt(2) while (dataLength > 0) { val original = deque.size val p = parsePacket() packets.add(p) dataLength -= (original - deque.size) } } else { // num packets type operator var packetCount = takeBits(11).toLong(2) while (packetCount > 0) { val p = parsePacket() packetCount-- packets.add(p) } } return Operator(version, type, packets) } } parsePacket() } fun main() { println(readText("/day16input.txt").parse().versionSum()) println(readText("/day16input.txt").parse().run()) }
0
Kotlin
0
1
9714e5b2c6a57db1b06e5ee6526eb30d587b94b4
2,806
advent-of-kotlin-2021
MIT License
src/Day08.kt
Kietyo
573,293,671
false
{"Kotlin": 147083}
import kotlin.math.max fun main() { fun part1(input: List<String>): Unit { val height = input.size val width = input.first().length val grid = input.map { it.map { it.digitToInt() } } var numVisible = 0 for (h in 0 until height) { for (w in 0 until width) { val curr = grid[h][w] if (w == 0) { numVisible++ } else if (h == 0) { numVisible++ } else if (w == width - 1) { numVisible++ } else if (h == height - 1) { numVisible++ } else { val columnValues = grid.map { it[w] } val leftVisible = grid[h].take(w).all { it < curr } val rightVisible = grid[h].drop(w + 1).all { it < curr } val topVisible = columnValues.take(h).all { it < curr } val bottomVisible = columnValues.drop(h + 1).all { it < curr } if (leftVisible || rightVisible || topVisible || bottomVisible) { numVisible++ } } } } println(numVisible) } fun part2(input: List<String>): Unit { fun <T> List<T>.indexOfLastSequential(predicate: (T) -> Boolean): Int { val iterator = this.listIterator() while (iterator.hasNext()) { if (!predicate(iterator.next())) { return iterator.previousIndex() } } return size - 1 } val height = input.size val width = input.first().length var highestScenicScore = 0 val grid = input.map { it.map { it.digitToInt() } } println(grid) for (h in 0 until height) { for (w in 0 until width) { val curr = grid[h][w] val columnValues = grid.map { it[w] } val leftIndex = grid[h].take(w).reversed().indexOfLastSequential { it < curr } val rightIndex = grid[h].drop(w + 1).indexOfLastSequential { it < curr } val topIndex = columnValues.take(h).reversed().indexOfLastSequential { it < curr } val bottomIndex = columnValues.drop(h + 1).indexOfLastSequential { it < curr } val indexes = listOf(leftIndex, rightIndex, topIndex, bottomIndex) val scenicScore = indexes.map { it + 1 }.reduce { acc, i -> acc * i } highestScenicScore = max(scenicScore, highestScenicScore) } } println(highestScenicScore) } val dayString = "day8" // test if implementation meets criteria from the description, like: val testInput = readInput("${dayString}_test") // part1(testInput) part2(testInput) val input = readInput("${dayString}_input") // part1(input) part2(input) }
0
Kotlin
0
0
dd5deef8fa48011aeb3834efec9a0a1826328f2e
3,197
advent-of-code-2022-kietyo
Apache License 2.0
src/main/kotlin/Day09.kt
N-Silbernagel
573,145,327
false
{"Kotlin": 118156}
import kotlin.math.abs import kotlin.math.sign fun main() { val input = readFileAsList("Day09") println(Day09.part1(input)) println(Day09.part2(input)) } object Day09 { fun part1(input: List<String>): Int { return solve(input, 2) } fun part2(input: List<String>): Int { return solve(input, 10) } private fun solve(input: List<String>, numberOfKnots: Int): Int { val directions = mapOf( "R" to Vector(1, 0), "U" to Vector(0, 1), "L" to Vector(-1, 0), "D" to Vector(0, -1), ) val visited = HashSet<Vector>() val knots = MutableList(numberOfKnots) { Vector(0, 0) } visited.add(Vector(0, 0)) for (instruction in input) { if (instruction.isBlank()) { continue } val splitInstruction = instruction.split(" ") val direction = splitInstruction[0] val distance = splitInstruction[1].toInt() val directionVector = directions[direction] ?: continue repeat(distance) { knots[0] += directionVector val headAndTailPairs = knots.indices.windowed(2) for ((headIndex, tailIndex) in headAndTailPairs) { if (!(knots[tailIndex] touches knots[headIndex])) { knots[tailIndex] = knots[tailIndex] moveBy knots[headIndex] } } visited.add(knots.last()) } } return visited.size } data class Vector(var x: Int, var y: Int) { infix fun touches(other: Vector): Boolean { return abs(this.x - other.x) < 2 && abs(this.y - other.y) < 2 } operator fun plus(other: Vector): Vector { return Vector(x + other.x, y + other.y) } infix fun moveBy(other: Vector): Vector { return this + Vector((other.x - x).sign, (other.y - y).sign) } } }
0
Kotlin
0
0
b0d61ba950a4278a69ac1751d33bdc1263233d81
2,024
advent-of-code-2022
Apache License 2.0
src/day05/day05.kt
mahmoud-abdallah863
572,935,594
false
{"Kotlin": 16377}
package day05 import assertEquals import readInput import readTestInput data class Instruction( val moveCount: Int, val fromStackIndex: Int, val toStackIndex: Int ) fun main() { fun readStacks(input: List<String>): MutableList<MutableList<String>> { val output = mutableListOf<MutableList<String>>() var filteredLines = input.map { line -> line .toList() .chunked(4) .map { it.joinToString(separator = "").trim() } } var indexOfNumbersLine = 0 filteredLines.forEachIndexed { index, strings -> if (strings.isNotEmpty() && strings.first().toIntOrNull() != null) { indexOfNumbersLine = index return@forEachIndexed } } filteredLines = filteredLines.subList(0, indexOfNumbersLine) filteredLines.forEach {line -> line.forEachIndexed { index, crate -> if (crate.isEmpty()) return@forEachIndexed if (output.size <= index+1) { repeat(index+1 - output.size) { output.add(mutableListOf()) } } output[index].add(crate) } } return output } fun readInstructions(input: List<String>): List<Instruction> { val output = mutableListOf<Instruction>() val emptyLineIndex = input.indexOfFirst { it.trim().isEmpty() } for (lineIndex in (emptyLineIndex+1 until input.size)) { val a = input[lineIndex].split(" ").filterIndexed{index, _ -> index%2==1} val newInstruction = Instruction( moveCount = a[0].toInt(), fromStackIndex = a[1].toInt()-1, toStackIndex = a[2].toInt()-1, ) output.add(newInstruction) } return output } fun part1(input: List<String>): String { val stacks = readStacks(input) val instructions = readInstructions(input) instructions.forEach { instruction -> repeat(instruction.moveCount){ val element = stacks[instruction.fromStackIndex].removeFirst() stacks[instruction.toStackIndex].add(0, element) } } return stacks.joinToString(separator = "") { it.first().filter { c -> c.isLetter() } } } fun part2(input: List<String>): String { val stacks = readStacks(input) val instructions = readInstructions(input) instructions.forEach { instruction -> repeat(instruction.moveCount){ index -> val element = stacks[instruction.fromStackIndex].removeFirst() stacks[instruction.toStackIndex].add(index, element) } } return stacks.joinToString(separator = "") { it.first().filter { c -> c.isLetter() } } } // test if implementation meets criteria from the description, like: val testInput = readTestInput() assertEquals(part1(testInput), "CMZ") assertEquals(part2(testInput), "MCD") val input = readInput() println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
f6d1a1583267e9813e2846f0ab826a60d2d1b1c9
3,136
advent-of-code-2022
Apache License 2.0
src/main/kotlin/Day08.kt
robfletcher
724,814,488
false
{"Kotlin": 18682}
import kotlin.math.max import kotlin.math.min class Day08 : Puzzle { override fun test() { val input1 = """ RL AAA = (BBB, CCC) BBB = (DDD, EEE) CCC = (ZZZ, GGG) DDD = (DDD, DDD) EEE = (EEE, EEE) GGG = (GGG, GGG) ZZZ = (ZZZ, ZZZ)""".trimIndent() assert(part1(input1.lineSequence()) == 2) val input2 = """ LR 11A = (11B, XXX) 11B = (XXX, 11Z) 11Z = (11B, XXX) 22A = (22B, XXX) 22B = (22C, 22C) 22C = (22Z, 22Z) 22Z = (22B, 22B) XXX = (XXX, XXX)""".trimIndent() assert(part2(input2.lineSequence()) == 6L) } override fun part1(input: Sequence<String>): Int { val (instructions, terrain) = parseInput(input) return pathLength(instructions, terrain, "AAA") { it == "ZZZ" } } override fun part2(input: Sequence<String>): Long { val (instructions, terrain) = parseInput(input) return terrain.keys .filter { it.endsWith('A') } .map { start -> pathLength(instructions, terrain, start) { pos -> pos.endsWith('Z') } } .map(Int::toLong) .reduce(::lcm) } private fun pathLength(instructions: Iterator<Char>, terrain: Map<String, Either>, start: String, done: (String) -> Boolean): Int { var pos = start var steps = 0 while (!done(pos)) { when (instructions.next()) { 'L' -> pos = terrain.getValue(pos).l 'R' -> pos = terrain.getValue(pos).r } steps++ } return steps } private fun parseInput(input: Sequence<String>): Pair<Iterator<Char>, Map<String, Either>> { val iterator = input.iterator() val instructions = iterator.next().asSequence().repeatForever().iterator() val terrain = iterator.asSequence().filterNot(String::isBlank).associate { line -> checkNotNull(Regex("""(\w+) = \((\w+), (\w+)\)""").matchEntire(line)).groupValues.let { (_, key, l, r) -> key to Either(l, r) } } return instructions to terrain } // stolen from https://www.baeldung.com/java-least-common-multiple fun lcm(a: Long, b: Long): Long { if (a == 0L || b == 0L) { return 0 } val high = max(a, b) val low = min(a, b) var lcm = high while (lcm % low != 0L) { lcm += high } return lcm } data class Either(val l: String, val r: String) fun <T> Sequence<T>.repeatForever() = generateSequence(this) { it }.flatten() }
0
Kotlin
0
0
cf10b596c00322ea004712e34e6a0793ba1029ed
2,435
aoc2023
The Unlicense
src/aoc2018/kot/Day11.kt
Tandrial
47,354,790
false
null
package aoc2018.kot object Day11 { data class Result(val x: Int = 0, val y: Int = 0, val power: Int = Int.MIN_VALUE, val size: Int = 0) { override fun toString() = "$x,$y,$size" } fun partOne(gId: Int) = solve(3, calcSumGrid(gId, 300)).toString().dropLast(2) fun partTwo(gId: Int): String { val grid = calcSumGrid(gId, 300) return (1..300).map { solve(it, grid) }.maxBy { it.power }!!.toString() } private fun calcSumGrid(gId: Int, maxSize: Int): Array<IntArray> { val grid = Array(maxSize + 1) { IntArray(maxSize + 1) } for (x in (1 until grid.size)) { for (y in (1 until grid[0].size)) { grid[x][y] = getPower(x, y, gId) + grid[x - 1][y] + grid[x][y - 1] - grid[x - 1][y - 1] } } return grid } private fun getPower(x: Int, y: Int, gId: Int) = (((((x + 10) * y) + gId) * (x + 10)) / 100) % 10 - 5 private fun solve(size: Int, grid: Array<IntArray>): Result { var max = Result() for (x in (1..300 - size)) { for (y in (1..300 - size)) { val power = grid[x][y] + grid[x + size][y + size] - grid[x + size][y] - grid[x][y + size] if (power > max.power) { max = Result(x + 1, y + 1, power, size) } } } return max } } fun main(args: Array<String>) { val gId = 1308 println("Part One = ${Day11.partOne(gId)}") println("Part Two = ${Day11.partTwo(gId)}") }
0
Kotlin
1
1
9294b2cbbb13944d586449f6a20d49f03391991e
1,393
Advent_of_Code
MIT License
src/Day13.kt
meierjan
572,860,548
false
{"Kotlin": 20066}
import kotlinx.serialization.* import kotlinx.serialization.json.* import kotlinx.serialization.json.JsonArray import kotlinx.serialization.json.JsonElement import kotlinx.serialization.json.JsonPrimitive sealed class NestedIntList { data class List( val list: kotlin.collections.List<NestedIntList> ) : NestedIntList() data class Int( val int: kotlin.Int ) : NestedIntList() } fun NestedIntList.Int.wrap(): NestedIntList.List = NestedIntList.List(listOf(this)) fun List<String>.toNestedIntList(): List<Pair<NestedIntList.List, NestedIntList.List>> { return this.chunked(3).map { val first = Json.decodeFromString<JsonArray>(it[0]).toNestedIntList() as NestedIntList.List val second = Json.decodeFromString<JsonArray>(it[1]).toNestedIntList() as NestedIntList.List Pair(first, second) } } fun compare(left: NestedIntList, right: NestedIntList): Int = if (left is NestedIntList.Int && right is NestedIntList.Int) { left.int.compareTo(right.int) } else if (left is NestedIntList.List && right is NestedIntList.List) { left.list.zip(right.list).map { (left, right) -> compare(left, right) }.find { it != 0 } ?: left.list.size.compareTo(right.list.size) } else if (left is NestedIntList.Int && right is NestedIntList.List) { compare(left.wrap(), right) } else if (left is NestedIntList.List && right is NestedIntList.Int) { compare(left, right.wrap()) } else { throw IllegalArgumentException(); } fun JsonElement.toNestedIntList(): NestedIntList = when (this) { is JsonArray -> NestedIntList.List(this.map { it.toNestedIntList() }) is JsonPrimitive -> NestedIntList.Int(this.toString().toInt()) else -> throw IllegalArgumentException("not supported type") } fun day13_part1(input: List<String>): Int = input.toNestedIntList() .map { (left, right) -> compare(left, right) } .mapIndexed { index, isRightOrder -> Pair(index, isRightOrder) } .filter { it.second != 1} .sumOf { it.first + 1 } fun day13_part2(input: List<String>): Int { val divider = listOf("[[2]]\n","[[6]]\n","").toNestedIntList().first() val orderedList = input.toNestedIntList() .plus(divider) .flatMap { listOf(it.first, it.second) } .sortedWith {a,b -> compare(a,b) } return orderedList.indexOf(divider.first).inc() * orderedList.indexOf(divider.second).inc() } fun main() { val testInput = readInput("Day13_1_test") val realInput = readInput("Day13_1") println(day13_part1(testInput)) println(day13_part1(realInput)) println(day13_part2(testInput)) println(day13_part2(realInput)) }
0
Kotlin
0
0
a7e52209da6427bce8770cc7f458e8ee9548cc14
2,743
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/day4/Day4.kt
Arch-vile
317,641,541
false
null
package day4 import day4.FieldType.byr import day4.FieldType.cid import day4.FieldType.ecl import day4.FieldType.eyr import day4.FieldType.hcl import day4.FieldType.hgtCm import day4.FieldType.hgtIn import day4.FieldType.iyr import day4.FieldType.pid import java.io.File enum class FieldType { byr, iyr, eyr, hgtCm, hgtIn, hcl, ecl, pid, cid, } var matchers = mapOf( byr to """.*(byr):(\d{4}) """.toRegex(), iyr to """.*(iyr):(\d{4}) """.toRegex(), eyr to """.*(eyr):(\d{4}) """.toRegex(), hgtCm to """.*(hgt):(\d*)cm """.toRegex(), hgtIn to """.*(hgt):(\d*)in """.toRegex(), hcl to """.*(hcl):(#[a-f0-9]{6}) """.toRegex(), ecl to """.*(ecl):(amb|blu|brn|gry|grn|hzl|oth) """.toRegex(), pid to """.*(pid):(\d{9}) """.toRegex(), cid to """.*(cid):([^ ]*) """.toRegex()) fun findValue(type: FieldType, input: String) = matchers[type]?.find(input)?.groupValues?.get(2) fun isValid(passport: String): Boolean { val validFields = matchers .map { Pair(it.key, findValue(it.key, passport)) } .mapNotNull { if (isValid(it.first, it.second)) it.first else null } val hasRequired = validFields.containsAll( listOf(byr, iyr, eyr, hcl, ecl, pid) ) val hasHgt = validFields.contains(hgtIn) || validFields.contains(hgtCm) return hasRequired && hasHgt } fun isValid(type: FieldType, value: String?): Boolean { if (value == null) return false return when (type) { byr -> value.toInt() in 1920..2002 iyr -> value.toInt() in 2010..2020 eyr -> value.toInt() in 2020..2030 hgtCm -> value.toInt() in 150..193 hgtIn -> value.toInt() in 59..76 hcl,ecl,pid,cid -> true } } fun main(args: Array<String>) { println(File("./src/main/resources/day4Input.txt") .readText() .split("\n\n") .map { it.split("\n").joinToString("") { line -> line.plus(" ") } } .map { isValid(it) } .filter { it } .count()) }
0
Kotlin
0
0
12070ef9156b25f725820fc327c2e768af1167c0
2,264
adventOfCode2020
Apache License 2.0
src/day05/Day05.kt
TheRishka
573,352,778
false
{"Kotlin": 29720}
package day05 import readInput import java.util.Stack import kotlin.math.max import kotlin.math.min fun main() { val startStacksField = mutableMapOf( 1 to Stack<Char>().apply { addAll(listOf('D', 'H', 'R', 'Z', 'S', 'P', 'W', 'Q').reversed()) }, 2 to Stack<Char>().apply { addAll(listOf('F', 'H', 'Q', 'W', 'R', 'B', 'V').reversed()) }, 3 to Stack<Char>().apply { addAll(listOf('H', 'S', 'V', 'C').reversed()) }, 4 to Stack<Char>().apply { addAll(listOf('G', 'F', 'H').reversed()) }, 5 to Stack<Char>().apply { addAll(listOf('Z', 'B', 'J', 'G', 'P').reversed()) }, 6 to Stack<Char>().apply { addAll(listOf('L', 'F', 'W', 'H', 'J', 'T', 'Q').reversed()) }, 7 to Stack<Char>().apply { addAll(listOf('N', 'J', 'V', 'L', 'D', 'W', 'T', 'Z').reversed()) }, 8 to Stack<Char>().apply { addAll(listOf('F', 'H', 'G', 'J', 'C', 'Z', 'T', 'D').reversed()) }, 9 to Stack<Char>().apply { addAll(listOf('H', 'B', 'M', 'V', 'P', 'W').reversed()) }, ) fun part1(startField: Map<Int, Stack<Char>>, operations: List<Operation>): String { val operationField = startField.toMutableMap() operations.forEach { operation -> for (actionCount in 1..operation.amount) { val char = operationField[operation.from]!!.pop() operationField[operation.to]!!.push(char) } } var endString = "" operationField.forEach { endString += it.value.peek() } return endString } fun part2(startField: Map<Int, Stack<Char>>, operations: List<Operation>): String { val operationField = startField.toMutableMap() operations.forEach { operation -> val pickedItems = mutableListOf<Char>() for (actionCount in 1..operation.amount) { val char = operationField[operation.from]!!.pop() pickedItems.add(char) } operationField[operation.to]!!.addAll(pickedItems.reversed()) } var endString = "" operationField.forEach { endString += it.value.peek() } return endString } val input = readInput("day05/Day05") val commands = input.drop(10) // move 2 from 2 to 1 val operations = commands.map { comms -> val digits = comms.split(" ").filter { !(it.contains("move") || it.contains("from") || it.contains("to")) }.map { it.toInt() } Operation( amount = digits[0], from = digits[1], to = digits[2] ) } // println(part1(startStacksField.toMap(), operations)) println(part2(startStacksField.toMap(), operations)) } data class Operation( val amount: Int, val from: Int, val to: Int )
0
Kotlin
0
1
54c6abe68c4867207b37e9798e1fdcf264e38658
3,012
AOC2022-Kotlin
Apache License 2.0
src/day07/Day07.kt
armanaaquib
572,849,507
false
{"Kotlin": 34114}
package day07 import readInputAsText data class File(val name: String, val size: Int) data class Directory( val name: String, val files: MutableList<File> = mutableListOf(), val directories: MutableList<Directory> = mutableListOf(), val parent: Directory? ) fun main() { fun parseFiles(list: List<String>): MutableList<File> { val files = mutableListOf<File>() list.forEach { val (c, name) = it.split(" ") if (c != "dir") { files.add(File(name, c.toInt())) } } return files } fun parseDirectories(list: List<String>, parent: Directory): MutableList<Directory> { val directories = mutableListOf<Directory>() list.forEach { val (c, name) = it.split(" ") if (c == "dir") { directories.add(Directory(name, parent = parent)) } } return directories } fun parseFileSystem(commands: List<List<String>>): Directory { val root = Directory("/", parent = null) var pwd = root for (command in commands) { when(command[0].subSequence(0, 2)) { "cd" -> { val path = command[0].removePrefix("cd ") pwd = if (path == "..") { pwd.parent ?: error("Invalid move.") } else { pwd.directories.find { it.name == path } ?: error("Directory not found.") } } "ls" -> { pwd.directories += parseDirectories(command.drop(1), pwd) pwd.files += parseFiles(command.drop(1)) } } } return root } fun parseInput(input: String): Directory { val commands = input.split("$ ").drop(2).map { it.trim().lines() } return parseFileSystem(commands) } fun calculateSizes(directory: Directory, sizes: MutableMap<String, Long>): Long { var size = 0L for (file in directory.files) { size += file.size } for (dir in directory.directories) { size += calculateSizes(dir, sizes) } // sizes[directory.name] = (sizes[directory.name] ?: 0) + size sizes[directory.name] = size return size } fun part1(input: String): Long { val directory = parseInput(input) val sizes = mutableMapOf<String, Long>() calculateSizes(directory, sizes) println(sizes) return sizes.values.filter { it <= 100_000 }.sum() } // // fun part2(input: List<String>): Int { // val data = parseInput(input) // // // return 2 // } // test if implementation meets criteria from the description, like: check(part1(readInputAsText("Day07_test")) == 95437L) println(part1(readInputAsText("Day07"))) // check(part2(readInput("Day02_test")) == 12) // println(part2(readInput("Day02"))) }
0
Kotlin
0
0
47c41ceddacb17e28bdbb9449bfde5881fa851b7
3,015
aoc-2022
Apache License 2.0
2023/7/solve-2.kts
gugod
48,180,404
false
{"Raku": 170466, "Perl": 121272, "Kotlin": 58674, "Rust": 3189, "C": 2934, "Zig": 850, "Clojure": 734, "Janet": 703, "Go": 595}
import java.io.File import kotlin.math.pow enum class HandType(val strongness: Int) { FiveOfAKind(7), FourOfAKind(6), FullHouse(5), ThreeOfAKind(4), TwoPair(3), OnePair(2), HighCard(1); companion object { fun fromFreq (freq: Map<Char,Int>): HandType = when(freq.keys.count()) { 1 -> FiveOfAKind 2 -> when(freq.values.max()) { 4 -> FourOfAKind else -> FullHouse } 3 -> when(freq.values.max()) { 3 -> ThreeOfAKind else -> TwoPair } 4 -> OnePair else -> HighCard } fun fromString(hand: String) : HandType { val freq = hand.fold(hashMapOf<Char,Int>()) { f,c -> f.apply { set(c, f.getOrDefault(c,0)+1) } } if (! freq.containsKey('J') || freq.keys.count() == 1) { return fromFreq(freq) } return freq.keys.minus('J').map { card -> fromFreq( freq.minus('J').plus(mapOf(card to (freq.getValue(card) + freq.getValue('J')))) ) }.maxBy { it.strongness } } } } fun cardRank(c: Char) = "J23456789TQKA".indexOf(c) fun handToNum(hand: String) = HandType.fromString(hand).strongness * 13.0.pow(5) + hand.mapIndexed { i,c -> cardRank(c) * (13.0.pow(4-i)) }.sum() File(args.getOrNull(0) ?: "input") .readLines() .map { it.split(" ") } .sortedBy { handToNum(it[0]) } .mapIndexed { i,xs -> xs[1].toInt() * (i + 1) } .sum() .run { println(this) }
0
Raku
1
5
ca0555efc60176938a857990b4d95a298e32f48a
1,688
advent-of-code
Creative Commons Zero v1.0 Universal