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/year2022/10/Day10.kt
Vladuken
573,128,337
false
{"Kotlin": 327524, "Python": 16475}
package year2022.`10` import readInput sealed class Command { object NOP : Command() data class Addx(val amount: Int) : Command() companion object { fun from(string: String): Command { val items = string.split(" ") return when (items[0]) { "addx" -> Addx(items[1].toInt()) "noop" -> NOP else -> error("!!") } } } } fun main() { fun cacheSignalIfConditionMet( currentCycle: Int, currentSignal: Int, results: MutableList<Int>, ) { if (currentCycle == 20 || ((currentCycle - 20) % 40 == 0)) { results.add(currentSignal * currentCycle) } } fun drawPixel( currentCycle: Int, currentSignal: Int, stringRes: StringBuilder ) { val width = 40 val pixelToDraw = ((currentCycle - 1) % width) val spriteRange = (pixelToDraw - 1..pixelToDraw + 1) val symbol = if (currentSignal in spriteRange) { "%" } else { "." } stringRes.append(symbol) if (pixelToDraw + 1 == width) { stringRes.appendLine() } } fun iterateOver( commands: List<Command>, doEachCycle: (cycle: Int, signal: Int) -> Unit ) { var currentCycle = 1 var currentSignal = 1 val iterator = commands.iterator() while (iterator.hasNext()) { when (val command = iterator.next()) { is Command.Addx -> { repeat(2) { doEachCycle(currentCycle, currentSignal) if (it == 1) currentSignal += command.amount currentCycle++ } } Command.NOP -> { doEachCycle(currentCycle, currentSignal) currentCycle++ } } } } fun part1(input: List<String>): Int { val commands = input.map { Command.from(it) } val results = mutableListOf<Int>() iterateOver(commands) { currentCycle, currentValue -> cacheSignalIfConditionMet(currentCycle, currentValue, results) } return results.sum() } fun part2(input: List<String>): String { val commands = input.map { Command.from(it) } val stringRes = StringBuilder() iterateOver(commands) { currentCycle, currentValue -> drawPixel(currentCycle, currentValue, stringRes) } return stringRes.toString() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day10_test") val part1Test = part1(testInput) println(part1Test) check(part1Test == 13140) val input = readInput("Day10") println(part1(input)) println(part2(input)) }
0
Kotlin
0
5
c0f36ec0e2ce5d65c35d408dd50ba2ac96363772
2,920
KotlinAdventOfCode
Apache License 2.0
src/main/java/com/booknara/problem/union/GraphValidTreeKt.kt
booknara
226,968,158
false
{"Java": 1128390, "Kotlin": 177761}
package com.booknara.problem.union /** * 261. Graph Valid Tree (Medium) * https://leetcode.com/problems/graph-valid-tree/ */ class GraphValidTreeKt { // T:O(n), S:O(n) fun validTree(n: Int, edges: Array<IntArray>): Boolean { var edge = n - 1 val root = IntArray(n) {i -> i} val rank = IntArray(n) { 1 } for (i in edges.indices) { val root1 = find(root, edges[i][0]) val root2 = find(root, edges[i][1]) if (root1 == root2) { return false } // union if (rank[root1] < rank[root2]) { root[root1] = root2 } else if (rank[root1] < rank[root2]) { root[root2] = root1 } else { root[root2] = root1 rank[root1]++ } edge-- } return edge == 0 } // T:O(a, a means Inverse Ackermann function. In practice constant) fun find(root: IntArray, index: Int): Int { if (index == root[index]) { return index } root[index] = find(root, root[index]) return root[index] } }
0
Java
1
1
04dcf500ee9789cf10c488a25647f25359b37a53
1,018
playground
MIT License
LeetCode/0448. Find All Numbers Disappeared in an Array/Solution.kt
InnoFang
86,413,001
false
{"C++": 501928, "Kotlin": 291271, "Python": 280936, "Java": 78746, "Go": 43858, "JavaScript": 27490, "Rust": 6410}
class Solution { fun findDisappearedNumbers(nums: IntArray): List<Int> { var i = 0 while (i < nums.size) { if (nums[i] != nums[nums[i] - 1]) { swap(nums, i, nums[i] - 1) --i } i++ } return (1..nums.size).filter { nums[it - 1] != it }.toList() } private fun swap(nums: IntArray, x: Int, y: Int) { nums[x] += nums[y] nums[y] = nums[x] - nums[y] nums[x] -= nums[y] } } class Solution2 { fun findDisappearedNumbers(nums: IntArray): List<Int> { nums.indices.forEach { i -> nums[(nums[i] - 1) % nums.size] += nums.size } return (1..nums.size).filter { nums[it-1] <= nums.size }.toList() } } fun main(args: Array<String>) { Solution2().findDisappearedNumbers(intArrayOf(4, 3, 2, 7, 8, 2, 3, 1)).forEach(::println) } // https://www.cnblogs.com/grandyang/p/6222149.html
0
C++
8
20
2419a7d720bea1fd6ff3b75c38342a0ace18b205
953
algo-set
Apache License 2.0
src/main/kotlin/com/hj/leetcode/kotlin/problem953/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem953 /** * LeetCode page: [953. Verifying an Alien Dictionary](https://leetcode.com/problems/verifying-an-alien-dictionary/); */ class Solution { /* Complexity: * Time O(M) and Space O(1) where M is the flat length of words; */ fun isAlienSorted(words: Array<String>, order: String): Boolean { val comparator = getComparatorFollowAlienOrder(order) for (index in 1 until words.size) { val currWord = words[index] val prevWord = words[index - 1] val isOutOfOrder = comparator.compare(currWord, prevWord) < 0 if (isOutOfOrder) return false } return true } private fun getComparatorFollowAlienOrder(order: String): Comparator<String> { val intFormOrder = buildIntFormOrder(order) return Comparator { o1, o2 -> val shorterLength = minOf(o1.length, o2.length) for (index in 0 until shorterLength) { val order1 = intFormOrder[o1[index] - 'a'] val order2 = intFormOrder[o2[index] - 'a'] if (order1 != order2) return@Comparator order1.compareTo(order2) } o1.length.compareTo(o2.length) } } private fun buildIntFormOrder(order: String): IntArray { val intFormOrder = IntArray(26) for ((index, char) in order.withIndex()) { intFormOrder[char - 'a'] = index } return intFormOrder } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
1,495
hj-leetcode-kotlin
Apache License 2.0
codeforces/round633/b.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package codeforces.round633 fun main() { val n = readInt() val nei = List(n) { mutableListOf<Int>() } repeat(n - 1) { val (u, v) = readInts().map { it - 1 } nei[u].add(v); nei[v].add(u) } val mark = BooleanArray(n) val dist = IntArray(n) fun dfs(v: Int) { mark[v] = true for (u in nei[v]) if (!mark[u]) { dist[u] = dist[v] + 1 dfs(u) } } dfs(0) val leaves = nei.indices.filter { nei[it].size == 1 } val differentParities = leaves.map { dist[it] % 2 }.toSet().size val ansMin = if (differentParities == 1) 1 else 3 val ansMax = n - 1 - nei.indices.sumBy { v -> val neiLeaves = nei[v].count { nei[it].size == 1 } maxOf(neiLeaves - 1, 0) } println("$ansMin $ansMax") } private fun readLn() = readLine()!! private fun readInt() = readLn().toInt() private fun readStrings() = readLn().split(" ") private fun readInts() = readStrings().map { it.toInt() }
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
886
competitions
The Unlicense
2015/src/main/kotlin/day23.kt
madisp
434,510,913
false
{"Kotlin": 388138}
import utils.Parser import utils.Solution import utils.cut import utils.mapItems import kotlin.reflect.KMutableProperty1 fun main() { Day23.run() } object Day23 : Solution<List<Day23.Insn>>() { override val name = "day23" override val parser = Parser.lines.mapItems { Insn.parse(it) } enum class Opcode { hlf, tpl, inc, jmp, jie, jio } enum class Register(val reg: KMutableProperty1<State, Int>) { a(State::a), b(State::b) } data class State( var pc: Int = 0, var a: Int = 0, var b: Int = 0, ) sealed interface Insn { data class Hlf(val r: Register): Insn data class Tpl(val r: Register): Insn data class Inc(val r: Register): Insn data class Jmp(val off: Int): Insn data class Jie(val r: Register, val off: Int): Insn data class Jio(val r: Register, val off: Int): Insn companion object { fun parse(line: String): Insn { val (op, rest) = line.cut(" ") val opcode = Opcode.valueOf(op) return when (opcode) { Opcode.hlf -> Hlf(Register.valueOf(rest)) Opcode.tpl -> Tpl(Register.valueOf(rest)) Opcode.inc -> Inc(Register.valueOf(rest)) Opcode.jmp -> Jmp(rest.toInt()) Opcode.jie -> { val (reg, off) = rest.cut(", ") Jie(Register.valueOf(reg), off.toInt()) } Opcode.jio -> { val (reg, off) = rest.cut(", ") Jio(Register.valueOf(reg), off.toInt()) } } } } } private fun run(state: State) { while (state.pc in input.indices) { val insn = input[state.pc] when (insn) { is Insn.Hlf -> { insn.r.reg.set(state, insn.r.reg.get(state) ushr 1) } is Insn.Tpl -> { insn.r.reg.set(state, insn.r.reg.get(state) * 3) } is Insn.Inc -> { insn.r.reg.set(state, insn.r.reg.get(state) + 1) } is Insn.Jmp -> { state.pc += insn.off continue } is Insn.Jie -> { if (insn.r.reg.get(state) % 2 == 0) { state.pc += insn.off continue } } is Insn.Jio -> { if (insn.r.reg.get(state) == 1) { state.pc += insn.off continue } } } state.pc++ } } override fun part1(): Int { val state = State() run(state) return state.b } override fun part2(): Int { val state = State(a = 1) run(state) return state.b } }
0
Kotlin
0
1
3f106415eeded3abd0fb60bed64fb77b4ab87d76
2,531
aoc_kotlin
MIT License
src/main/kotlin/fr/pturpin/coursera/divconquer/QuickSort.kt
TurpIF
159,055,822
false
null
package fr.pturpin.coursera.divconquer import java.util.* class QuickSort(private val elements: IntArray) { private val random = Random(42) fun sortInPlace(): IntArray { sortInPlace(0, elements.size) return elements } private fun sortInPlace(from: Int, untilExcluded: Int) { if (from == untilExcluded) { return } val pivotIndex = getPivotIndex(from, untilExcluded) val partition = partitionAround(elements[pivotIndex], from, untilExcluded) sortInPlace(partition.lowerFrom, partition.lowerUntil) sortInPlace(partition.higherFrom, partition.higherUntil) } private fun partitionAround(pivotValue: Int, from: Int, untilExcluded: Int): Partition { var lowerUntil = from var higherFrom = untilExcluded var i = from while(i < higherFrom) { val currentValue = elements[i] if (currentValue < pivotValue) { swap(lowerUntil, i) lowerUntil++ } else if (currentValue > pivotValue) { higherFrom-- swap(higherFrom, i) i-- } i++ } elements.fill(pivotValue, lowerUntil, higherFrom - 1) return Partition(from, lowerUntil, higherFrom, untilExcluded) } private fun swap(i: Int, j: Int) { val tmp = elements[i] elements[i] = elements[j] elements[j] = tmp } private fun getPivotIndex(from: Int, untilExcluded: Int): Int { return random.nextInt(untilExcluded - from) + from } private data class Partition(val lowerFrom: Int, val lowerUntil: Int, val higherFrom: Int, val higherUntil: Int) { init { assert(lowerFrom <= lowerUntil) assert(lowerUntil < higherFrom) assert(higherFrom <= higherUntil) } } } fun main(args: Array<String>) { readLine()!! val elements = readLine()!!.split(" ").map { it.toInt() }.toIntArray() val quickSort = QuickSort(elements) val sorted = quickSort.sortInPlace() print(sorted.joinToString(" ")) }
0
Kotlin
0
0
86860f8214f9d4ced7e052e008b91a5232830ea0
2,149
coursera-algo-toolbox
MIT License
src/Day05.kt
BrianEstrada
572,700,177
false
{"Kotlin": 22757}
fun main() { // Test Case val testInput = readInput("Day05_test") val part1TestResult = Day05.part1(testInput) println(part1TestResult) check(part1TestResult == "CMZ") val part2TestResult = Day05.part2(testInput) println(part2TestResult) check(part2TestResult == "MCD") // Actual Case val input = readInput("Day05") println("Part 1: " + Day05.part1(input)) println("Part 2: " + Day05.part2(input)) } private object Day05 { fun part1(lines: List<String>): String { val (stackMap, moveMap) = lines.splitLines() for (move in moveMap) { for (i in 0 until move.times) { val fromIndex = move.from - 1 val toIndex = move.to - 1 val indexOfFrom = stackMap[fromIndex].indexOfFirst { it.isNotEmpty() } val indexOfTo = stackMap[toIndex].indexOfLast { it.isEmpty() } val moveLetter = stackMap[fromIndex][indexOfFrom] stackMap[fromIndex][indexOfFrom] = "" if (indexOfTo == -1) { stackMap[toIndex].add(0, moveLetter) } else { stackMap[toIndex][indexOfTo] = moveLetter } } } return stackMap.joinToString("") { column -> column.first { letter -> letter.isNotEmpty() } } } fun part2(lines: List<String>): String { val (stackMap, moveMap) = lines.splitLines() stackMap.printMap() for (move in moveMap) { val fromIndex = move.from - 1 val toIndex = move.to - 1 val newList = stackMap[fromIndex].take(move.times) stackMap[fromIndex] = stackMap[fromIndex].subList(move.times, stackMap[fromIndex].size) stackMap[toIndex].addAll(0, newList) stackMap.printMap() } return stackMap.joinToString("") { column -> column.first { letter -> letter.isNotEmpty() } } } private fun List<List<String>>.printMap() { println() for (i in 0 until this.maxOf { it.size }) { for (j in 0 until this.size) { val value: String? = getOrNull(j)?.getOrNull(i) if (value.isNullOrBlank()) { print(" ") } else { print("$value ") } } println() } println() } private fun List<String>.splitLines(): Pair<MutableList<MutableList<String>>, List<Move>> { val stackMap = mutableListOf<String>() val moveMap = mutableListOf<String>() var ended = false for (line in this) { if (line.isBlank()) { ended = true continue } if (!ended) { stackMap.add(line) } else { moveMap.add(line) } } val columnMap = mutableListOf<MutableList<String>>() stackMap.forEach { stack -> stack.chunked(4).forEachIndexed { boxIndex, box -> val column = columnMap.getOrNull(boxIndex) if (column == null) columnMap.add(mutableListOf()) val letter = box.replace("[", "") .replace("]", "") .trim() if (letter.isNotEmpty()) { columnMap[boxIndex].add(letter) } } } return columnMap to Move.parse(moveMap) } data class Move( val times: Int, val from: Int, val to: Int, ) { companion object { fun parse(move: IntArray): Move { return Move( move[0], move[1], move[2], ) } fun parse(moves: List<String>): List<Move> { return moves.map { move -> Move.parse( move = move.split(" ") .mapNotNull { it.toIntOrNull() } .toIntArray() ) } } } } }
1
Kotlin
0
1
032a4693aff514c9b30e979e63560dc48917411d
4,331
aoc-kotlin-2022
Apache License 2.0
src/main/kotlin/exercises/mergetwosortedlists/MergeTwoSortedLists.kt
amykv
538,632,477
false
{"Kotlin": 169929}
package exercises.mergetwosortedlists /*You are given the heads of two sorted linked lists list1 and list2. Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list. Example 1: Input: list1 = [1,2,4], list2 = [1,3,4] Output: [1,1,2,3,4,4] Example 2: Input: list1 = [], list2 = [] Output: [] Example 3: Input: list1 = [], list2 = [0] Output: [0]*/ fun main() { // Test case 1: Input: 1->2->4, 1->3->4; Output: 1->1->2->3->4->4 val l1 = ListNode(1).apply { next = ListNode(2).apply { next = ListNode(4) } } val l2 = ListNode(1).apply { next = ListNode(3).apply { next = ListNode(4) } } // Merge the two lists and print the result val mergedList = mergeTwoLists(l1, l2) var current = mergedList while (current != null) { print("${current.value} ") current = current.next } // Output: 1 1 2 3 4 4 } /** * Example: * var li = ListNode(5) * var v = li.`val` * Definition for singly-linked list. * class ListNode(var `val`: Int) { * var next: ListNode? = null * } */ fun mergeTwoLists(l1: ListNode?, l2: ListNode?): ListNode? { // Create a dummy node as the head of the merged list val dummy = ListNode(0) var tail = dummy // Traverse the two input lists and add the smaller node to the merged list var p1 = l1 var p2 = l2 while (p1 != null && p2 != null) { if (p1.value < p2.value) { tail.next = p1 p1 = p1.next } else { tail.next = p2 p2 = p2.next } tail = tail.next!! } // Add the remaining nodes to the merged list if (p1 != null) { tail.next = p1 } else if (p2 != null) { tail.next = p2 } // Return the head of the merged list (excluding the dummy node) return dummy.next } class ListNode(var value: Int) { var next: ListNode? = null } /*The ListNode class is a simple class to represent a node in a linked list. Each node contains an integer value and a reference to the next node. The mergeTwoLists function takes two linked lists (l1 and l2) as input and returns a merged linked list. It first creates a dummy node to hold the result, and initializes a current pointer to it. The function then iterates through both input lists as long as both lists are not empty. It compares the values of the heads of the two lists, and appends the smaller one to the result list. It then moves the current pointer to the next node in the result list. After the while loop, the function checks if there are any remaining nodes in either input list, and appends them to the result list. Finally, the function returns the merged list (skipping the dummy head). The main function creates two sorted linked lists (list1 and list2), merges them using the mergeTwoLists function, and prints the values of the merged list. The time complexity of this program is O(n), where n is the total number of nodes in the input lists. The space complexity is O(1), as we only use a constant amount of extra space to hold the dummy node and the current pointer.*/
0
Kotlin
0
2
93365cddc95a2f5c8f2c136e5c18b438b38d915f
3,240
dsa-kotlin
MIT License
src/day22/Day22.kt
kerchen
573,125,453
false
{"Kotlin": 137233}
package day22 import readInput import java.util.regex.Pattern enum class Facing(val weight: Int) { EAST(0) { override fun delta(): Point = Point(1, 0) override fun left(): Facing = NORTH override fun right(): Facing = SOUTH }, SOUTH(1) { override fun delta(): Point = Point(0, 1) override fun left(): Facing = EAST override fun right(): Facing = WEST }, WEST(2) { override fun left(): Facing = SOUTH override fun right(): Facing = NORTH override fun delta(): Point = Point(-1, 0) }, NORTH(3) { override fun delta(): Point = Point(0, -1) override fun left(): Facing = WEST override fun right(): Facing = EAST }; abstract fun delta(): Point abstract fun left(): Facing abstract fun right(): Facing } data class Point(val column: Int, val row: Int) class Cell(val passable: Boolean, val wallTravelDistances: IntArray) { } class Board(input: List<String>) { lateinit var startingPoint: Point val cells = mutableMapOf<Point, Cell>() val validColumnsForRow = mutableMapOf<Int, Pair<Int, Int>>() val validRowsForColumn = mutableMapOf<Int, Pair<Int, Int>>() var maxRow: Int var maxColumn: Int init { var row = 0 var foundStart = false maxRow = 0 maxColumn = 0 for (line in input) { var index = 0 var firstColumn = 0 var column: Int if (line.trim().isEmpty()) break row += 1 maxRow = maxRow.coerceAtLeast(row) while (true) { val match = line.findAnyOf(listOf(".", "#"), index, true) if (match == null) break column = match.first + 1 if (firstColumn == 0) { firstColumn = column validColumnsForRow[row] = Pair(column, 0) } else { validColumnsForRow[row] = Pair(firstColumn, column) } maxColumn = maxColumn.coerceAtLeast(column) index = column if (match.second == ".") { if (!foundStart) { foundStart = true startingPoint = Point(column, row) } cells[Point(column, row)] = Cell(true, IntArray(4)) } else { cells[Point(column, row)] = Cell(false, IntArray(0)) } } } for (column in IntRange(1, maxColumn)) { var firstRow = 0 for (row in IntRange(1, maxRow)) { if (cells.containsKey(Point(column, row))) { if (firstRow == 0) { firstRow = row validRowsForColumn[column] = Pair(firstRow, 0) } else { validRowsForColumn[column] = Pair(firstRow, row) } } } } fun distanceToWall(startingPoint: Point, delta: Point): Int { var distance = 0 var testPoint = step(startingPoint, delta) while (testPoint != startingPoint) { if (cells.containsKey(testPoint)) { if (cells[testPoint]!!.passable) { distance += 1 } else break } testPoint = step(testPoint, delta) } return if (testPoint != startingPoint) distance else Int.MAX_VALUE } // Compute distances to walls for (cell in cells) { if (cell.value.passable) { for (d in Facing.values()) { cell.value.wallTravelDistances[d.ordinal] = distanceToWall(cell.key, d.delta()) } } } } fun step(point: Point, delta: Point, steps: Int = 1): Point { var row = point.row var column = point.column // Assume no diagonal movement. I may regret this assumption in part 2. check(delta.row == 0 || delta.column == 0) for (i in IntRange(1, steps)) { row += delta.row column += delta.column if (delta.row < 0 && row < validRowsForColumn[column]!!.first) row = validRowsForColumn[column]!!.second if (delta.row > 0 && row > validRowsForColumn[column]!!.second) row = validRowsForColumn[column]!!.first if (delta.column < 0 && column < validColumnsForRow[row]!!.first) column = validColumnsForRow[row]!!.second if (delta.column > 0 && column > validColumnsForRow[row]!!.second) column = validColumnsForRow[row]!!.first } return Point(column, row) } fun move(startingLocation: Point, facing: Facing, steps: Int): Point { if (cells.containsKey(startingLocation)) { if (cells[startingLocation]!!.passable) { val stepCount = steps.coerceAtMost(cells[startingLocation]!!.wallTravelDistances[facing.ordinal]) return step(startingLocation, facing.delta(), stepCount) } } return startingLocation } } class Pawn(var location: Point) { var facing = Facing.EAST } fun main() { fun part1(input: List<String>): Long { val board = Board(input) val directions = input.lastOrNull() { it.contains(Regex("[0-9]+")) } var index = 0 val pattern = Pattern.compile( """([0-9]+)([RL]?)""") val pawn = Pawn(board.startingPoint) println("Board size is ${board.maxColumn} x ${board.maxRow}") println("Directions: $directions") while (true) { val matcher = pattern.matcher(directions!!.substring(index)) if (matcher.find()) { val steps = matcher.group(1).toInt() println("Move $steps ${pawn.facing}") pawn.location = board.move(pawn.location, pawn.facing, steps) println("After steps: ${pawn.location.column} ${pawn.location.row} ${pawn.facing}") if (matcher.group(2).length > 0) { val newFacing = when (matcher.group(2)[0]) { 'R' -> pawn.facing.right() 'L' -> pawn.facing.left() else -> throw Exception("Unexpected direction") } pawn.facing = newFacing } index += matcher.group(0).length } else { break } } println("Final pawn position & facing: ${pawn.location.row} ${pawn.location.column} ${pawn.facing.ordinal}") return (1000 * pawn.location.row + 4 * pawn.location.column + pawn.facing.ordinal).toLong() } fun part2(input: List<String>): Long { return 0 } val testInput = readInput("Day22_test") check(part1(testInput) == 6032.toLong()) check(part2(testInput) == 0.toLong()) val input = readInput("Day22") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
dc15640ff29ec5f9dceb4046adaf860af892c1a9
7,165
AdventOfCode2022
Apache License 2.0
src/main/kotlin/pj/saari/map/Graph.kt
piizei
202,340,455
false
null
package pj.saari.map import pj.saari.Island import pj.saari.Tile import pj.saari.TileCoord import pj.saari.TileType fun createMatrix(tiles: List<Tile>): Array<IntArray> { fun getDimensions(tiles: List<Tile>): List<Int> { var x = 0 var y = 0 tiles.forEach { if (it.x > x) x = it.x if (it.y > y) y = it.y } return listOf(x, y) } val (x, y) = getDimensions(tiles) val array = Array(size = y) { IntArray(x) } tiles.forEach { if (it.type == TileType.land) { array[it.y - 1][it.x - 1] = 1 } else { array[it.y - 1][it.x - 1] = 0 } } return array } fun matrixAsString(matrix: Array<IntArray>): String { var rendered = "" matrix.forEach { x -> x.forEach { y -> rendered += y } rendered += '\n' } return rendered } fun dfsMatrixForIslands(matrix: Array<IntArray>): List<Island> { val offsets = intArrayOf(-1, 0, +1) fun neighborExists(matrix: Array<IntArray>, i: Int, j: Int): Boolean { if ((i >= 0) && (i < matrix.size) && (j >= 0) && (j < matrix[0].size)) { return matrix[i][j] == 1 } return false } fun dfs(matrix: Array<IntArray>, i: Int, j: Int, visited: Array<IntArray>, count: Int) { if (visited[i][j] > 0) return visited[i][j] = count var xOffset: Int var yOffset: Int for (xi in offsets.indices) { xOffset = offsets[xi] for (yi in offsets.indices) { yOffset = offsets[yi] if (xOffset == 0 && yOffset == 0) continue if (neighborExists(matrix, i + xOffset, j + yOffset)) { dfs(matrix, i + xOffset, j + yOffset, visited, count) } } } } fun clusters(matrix: Array<IntArray>): Array<IntArray> { val visited = Array(size = matrix.size) { IntArray(matrix[0].size) } var count = 0 for (i in matrix.indices) for (j in matrix[0].indices) { if ((matrix[i][j] == 1) && (visited[i][j] == 0)) { count += 1 dfs(matrix, i, j, visited, count) } } return visited } fun islandsFromClusters(matrix: Array<IntArray>): List<Island> { val islandMap = mutableMapOf<Int, Island>() for (i in matrix.indices) for (j in matrix[0].indices) { if (matrix[i][j] > 0){ val id = matrix[i][j] val tile = TileCoord(j + 1, i + 1) if (! islandMap.containsKey(id)) { islandMap[id] = Island(id).apply { tiles.add(tile) } } else { islandMap[id]?.tiles?.add(tile) } } } return islandMap.values.toList() } return islandsFromClusters(clusters(matrix)) }
0
Kotlin
0
0
befda8a460d27fe9d39bb7e7e5286e136bcf3c40
2,933
saari
MIT License
aoc-2021/src/main/kotlin/nerok/aoc/aoc2021/day02/Day02.kt
nerok
572,862,875
false
{"Kotlin": 113337}
package nerok.aoc.aoc2021.day02 import nerok.aoc.utils.Input import kotlin.time.DurationUnit import kotlin.time.measureTime fun main() { fun part1(input: List<String>): Long { var depth = 0 var horizontal = 0 input.forEach { val (command, value) = it.split(" ") when (command) { "forward" -> horizontal = horizontal.plus(value.toInt()) "down" -> depth = depth.plus(value.toInt()) "up" -> depth = depth.minus(value.toInt()) } } println("Horizontal: $horizontal") println("Depth: $depth") println("Score: ${depth*horizontal}") return (depth*horizontal).toLong() } fun part2(input: List<String>): Long { var depth = 0 var horizontal = 0 var aim = 0 input.forEach { val (command, value) = it.split(" ") when (command) { "forward" -> { horizontal = horizontal.plus(value.toInt()) depth = depth.plus(aim.times(value.toInt())) } "down" -> aim = aim.plus(value.toInt()) "up" -> aim = aim.minus(value.toInt()) } } println("Horizontal: $horizontal") println("Depth: $depth") println("Score: ${depth*horizontal}") return (depth*horizontal).toLong() } // test if implementation meets criteria from the description, like: val testInput = Input.readInput("Day02_test") check(part1(testInput) == 150L) check(part2(testInput) == 900L) val input = Input.readInput("Day02") println(measureTime { println(part1(input)) }.toString(DurationUnit.SECONDS, 3)) println(measureTime { println(part2(input)) }.toString(DurationUnit.SECONDS, 3)) }
0
Kotlin
0
0
7553c28ac9053a70706c6af98b954fbdda6fb5d2
1,829
AOC
Apache License 2.0
day14/src/main/kotlin/com/lillicoder/adventofcode2023/day14/Day14.kt
lillicoder
731,776,788
false
{"Kotlin": 98872}
package com.lillicoder.adventofcode2023.day14 import com.lillicoder.adventofcode2023.grids.Direction import com.lillicoder.adventofcode2023.grids.Grid import com.lillicoder.adventofcode2023.grids.GridParser import com.lillicoder.adventofcode2023.grids.Node fun main() { val day14 = Day14() val grid = GridParser().parseFile("input.txt").first() println("The total load for a single tilt to the north is ${day14.part1(grid)}.") println("The total load for a 1000000000 cycles is ${day14.part2(grid)}.") } class Day14 { fun part1(grid: Grid<String>) = load(grid, 1, mutableListOf(Direction.UP)) fun part2(grid: Grid<String>) = load(grid) /** * Finds the load for the given [Grid]. * @param grid Grid to evaluate. * @return Load. */ private fun load( grid: Grid<String>, cycles: Int = 1000000000, order: List<Direction> = mutableListOf( Direction.UP, Direction.LEFT, Direction.DOWN, Direction.RIGHT, ), ): Long { val cache = mutableMapOf<String, Int>() val tilter = Tilter() val calculator = LoadCalculator() var tilted = grid repeat(cycles) { cycle -> val key = tilted.toString() if (key in cache) { val distance = cycle - cache[key]!! val remaining = (cycles - cycle) % distance repeat(remaining) { tilted = tilter.tiltSequence(tilted, order) } return calculator.load(tilted) } cache[key] = cycle tilted = tilter.tiltSequence(tilted, order) } return calculator.load(tilted) } } class LoadCalculator { /** * Calculates the load for the given [Grid]. * @param grid Grid to evaluate. * @return Load. */ fun load(grid: Grid<String>): Long { var load = 0L grid.forEachRowIndexed { index, row -> val spheres = row.count { it.value == "O" } load += spheres * (grid.height - index) } return load } } class Tilter { /** * Tilts the given [Grid] with the given sequence of [Direction]. * @param grid Grid to tilt. * @param directions Directions to tilt. * @return Tilted grid. */ fun tiltSequence( grid: Grid<String>, directions: List<Direction>, ): Grid<String> { var tilted = grid directions.forEach { tilted = tilt(tilted, it) } return tilted } /** * Tilts the given [Grid] in the given [Direction]. * @param grid Grid to tilt. * @param direction Direction to tilt. * @return Tilted grid.. */ private fun tilt( grid: Grid<String>, direction: Direction, ): Grid<String> { return when (direction) { Direction.RIGHT, Direction.LEFT -> tiltRows(grid, direction) Direction.UP, Direction.DOWN -> tiltColumns(grid, direction) } } /** * Tilts the given [Grid]'s columns in the given [Direction]. * @param grid Grid to tilt. * @param direction Direction to tilt. * @return Tilted grid. */ private fun tiltColumns( grid: Grid<String>, direction: Direction, ): Grid<String> { val tilted = mutableListOf<String>() grid.forEachColumn { column -> // Split column by cubes val raw = column.joinToString("") { it.value }.split("#") val processed = mutableListOf<String>() raw.forEach { chunk -> // Sort this chunk to roll the spheres val sorted = chunk.split("").filter { it.isNotEmpty() }.sortedWith( Comparator { node, other -> if (node == other) return@Comparator 0 return@Comparator when (node) { "O" -> if (direction == Direction.UP) -1 else 1 "." -> if (direction == Direction.UP) 1 else -1 else -> 0 } }, ) // Save the chunk processed.add(sorted.joinToString("")) } // Column fully processed, reconstitute the cubes tilted.add(processed.joinToString(separator = "#")) } // Columns repopulated, convert to grid val rows = MutableList<MutableList<Node<String>>>(tilted.size) { mutableListOf() } tilted.forEachIndexed { x, column -> column.split("").filter { it.isNotEmpty() }.forEachIndexed { y, value -> rows[y].add(Node(x.toLong(), y.toLong(), value)) } } return Grid(rows) } /** * Tilts the given [Grid]'s rows in the given [Direction]. * @param grid Grid to tilt. * @param direction Direction to tilt. * @return Tilted grid. */ private fun tiltRows( grid: Grid<String>, direction: Direction, ): Grid<String> { val tilted = mutableListOf<String>() grid.forEachRow { row -> // Split row by cubes val raw = row.joinToString("") { it.value }.split("#") val processed = mutableListOf<String>() raw.forEach { chunk -> // Sort this chunk to roll the spheres val sorted = chunk.split("").filter { it.isNotEmpty() }.sortedWith( Comparator { node, other -> if (node == other) return@Comparator 0 return@Comparator when (node) { "O" -> if (direction == Direction.LEFT) -1 else 1 "." -> if (direction == Direction.LEFT) 1 else -1 else -> 0 } }, ) // Save the chunk processed.add(sorted.joinToString("")) } // Column fully processed, reconstitute the cubes tilted.add(processed.joinToString(separator = "#")) } // Rows repopulated, convert to grid val rows = MutableList<MutableList<Node<String>>>(tilted.size) { mutableListOf() } tilted.forEachIndexed { y, row -> row.split("").filter { it.isNotEmpty() }.forEachIndexed { x, value -> rows[y].add(Node(x.toLong(), y.toLong(), value)) } } return Grid(rows) } }
0
Kotlin
0
0
390f804a3da7e9d2e5747ef29299a6ad42c8d877
6,770
advent-of-code-2023
Apache License 2.0
year2021/day02/part2/src/main/kotlin/com/curtislb/adventofcode/year2021/day02/part2/Year2021Day02Part2.kt
curtislb
226,797,689
false
{"Kotlin": 2146738}
/* --- Part Two --- Based on your calculations, the planned course doesn't seem to make any sense. You find the submarine manual and discover that the process is actually slightly more complicated. In addition to horizontal position and depth, you'll also need to track a third value, aim, which also starts at 0. The commands also mean something entirely different than you first thought: - `down X` increases your aim by X units. - `up X` decreases your aim by X units. - `forward X` does two things: - It increases your horizontal position by X units. - It increases your depth by your aim multiplied by X. Again note that since you're on a submarine, down and up do the opposite of what you might expect: "down" means aiming in the positive direction. Now, the above example does something different: - `forward 5` adds 5 to your horizontal position, a total of 5. Because your aim is 0, your depth does not change. - `down 5` adds 5 to your aim, resulting in a value of 5. - `forward 8` adds 8 to your horizontal position, a total of 13. Because your aim is 5, your depth increases by 8*5=40. - `up 3` decreases your aim by 3, resulting in a value of 2. `down 8` adds 8 to your aim, resulting in a value of 10. - `forward 2` adds 2 to your horizontal position, a total of 15. Because your aim is 10, your depth increases by 2*10=20 to a total of 60. After following these new instructions, you would have a horizontal position of 15 and a depth of 60. (Multiplying these produces 900.) Using this new interpretation of the commands, calculate the horizontal position and depth you would have after following the planned course. What do you get if you multiply your final horizontal position by your final depth? */ package com.curtislb.adventofcode.year2021.day02.part2 import com.curtislb.adventofcode.year2021.day02.submarine.AimingSubmarine import java.nio.file.Path import java.nio.file.Paths /** * Returns the solution to the puzzle for 2021, day 2, part 2. * * @param inputPath The path to the input file for this puzzle. * @param initialPosition The horizontal position of the submarine before running any commands. * @param initialDepth The depth of the submarine before running any commands. */ fun solve( inputPath: Path = Paths.get("..", "input", "input.txt"), initialPosition: Int = 0, initialDepth: Int = 0 ): Int { val submarine = AimingSubmarine(initialPosition, initialDepth) inputPath.toFile().forEachLine { submarine.runCommand(it) } return submarine.horizontalPosition * submarine.depth } fun main() { println(solve()) }
0
Kotlin
1
1
6b64c9eb181fab97bc518ac78e14cd586d64499e
2,667
AdventOfCode
MIT License
src/Day02.kt
ditn
572,953,437
false
{"Kotlin": 5079}
import java.lang.IllegalArgumentException fun main() { fun part1(input: List<String>): Int = input .toRounds() .sumOf { round -> val outcomeComponent = round.toOutcome().score val handComponent = round.second.score outcomeComponent + handComponent } fun part2(input: List<String>): Int = input .toScenarios() .sumOf { scenario -> val outcomeComponent = scenario.second.score val handComponent = scenario.toHand().score outcomeComponent + handComponent } val testInput = readInput("Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("Day02") println(part1(input)) println(part2(input)) } private typealias Opponent = Hand private typealias Yours = Hand private typealias Round = Pair<Opponent, Yours> private typealias Scenario = Pair<Opponent, Outcome> private fun List<String>.toRounds(): List<Round> = map { it.first().toHand() to it.last().toHand() } private fun List<String>.toScenarios(): List<Scenario> = map { it.first().toHand() to it.last().toOutcome() } private fun Char.toHand(): Hand = when (this) { 'X', 'A' -> Hand.Rock 'Y', 'B' -> Hand.Paper 'Z', 'C' -> Hand.Scissors else -> throw IllegalArgumentException("Invalid hand with value $this") } private fun Char.toOutcome(): Outcome = when (this) { 'X' -> Outcome.Loss 'Y' -> Outcome.Draw 'Z' -> Outcome.Win else -> throw IllegalArgumentException("Invalid outcome with value $this") } private fun Scenario.toHand(): Yours = when (first) { Hand.Paper -> when (second) { Outcome.Draw -> Hand.Paper Outcome.Loss -> Hand.Rock Outcome.Win -> Hand.Scissors } Hand.Rock -> when (second) { Outcome.Draw -> Hand.Rock Outcome.Loss -> Hand.Scissors Outcome.Win -> Hand.Paper } Hand.Scissors -> when (second) { Outcome.Draw -> Hand.Scissors Outcome.Loss -> Hand.Paper Outcome.Win -> Hand.Rock } } private fun Round.toOutcome(): Outcome = when (first) { Hand.Paper -> when (second) { Hand.Paper -> Outcome.Draw Hand.Rock -> Outcome.Loss Hand.Scissors -> Outcome.Win } Hand.Rock -> when (second) { Hand.Paper -> Outcome.Win Hand.Rock -> Outcome.Draw Hand.Scissors -> Outcome.Loss } Hand.Scissors -> when (second) { Hand.Paper -> Outcome.Loss Hand.Rock -> Outcome.Win Hand.Scissors -> Outcome.Draw } } enum class Hand(val score: Int) { Rock(1), Paper(2), Scissors(3), } enum class Outcome(val score: Int) { Loss(0), Draw(3), Win(6), }
0
Kotlin
0
0
4c9a286a911cd79d433075cda5ed01249ecb5994
2,753
aoc2022
Apache License 2.0
src/pl/shockah/aoc/y2015/Day21.kt
Shockah
159,919,224
false
null
package pl.shockah.aoc.y2015 import pl.shockah.aoc.AdventTask import kotlin.math.max class Day21: AdventTask<Day21.Stats, Int, Int>(2015, 21) { private val playerHealth = 100 data class Stats( val health: Int, val damage: Int, val armor: Int ) { constructor( health: Int, equipment: Set<Item> ): this(health, equipment.sumOf { it.damage }, equipment.sumOf { it.armor }) } private class Character( val stats: Stats ) { var health: Int = stats.health fun attack(character: Character): Boolean { val actualDamage = max(stats.damage - character.stats.armor, 1) character.health -= actualDamage return character.health <= 0 } } enum class ItemType( val equipLimit: IntRange ) { Weapon(1..1), Armor(0..1), Ring(0..2) } data class Item( val type: ItemType, val name: String, val cost: Int, val damage: Int = 0, val armor: Int = 0 ) { override fun toString(): String { return "${type.name}: $name" } } private data class Result( val playerHealth: Int, val enemyHealth: Int, val turns: Int ) { override fun toString(): String { return if (playerHealth <= 0) "Died after $turns turns. Health left: $enemyHealth" else "Victorious after $turns turns. Health left: $playerHealth" } } private val shop = setOf( Item(ItemType.Weapon, "Dagger", 8, damage = 4), Item(ItemType.Weapon, "Shortsword", 10, damage = 5), Item(ItemType.Weapon, "Warhammer", 25, damage = 6), Item(ItemType.Weapon, "Longsword", 40, damage = 7), Item(ItemType.Weapon, "Greataxe", 74, damage = 8), Item(ItemType.Armor, "Leather", 13, armor = 1), Item(ItemType.Armor, "Chainmail", 31, armor = 2), Item(ItemType.Armor, "Splintmail", 53, armor = 3), Item(ItemType.Armor, "Bandedmail", 75, armor = 4), Item(ItemType.Armor, "Platemail", 102, armor = 5), Item(ItemType.Ring, "Damage +1", 25, damage = 1), Item(ItemType.Ring, "Damage +2", 50, damage = 2), Item(ItemType.Ring, "Damage +3", 100, damage = 3), Item(ItemType.Ring, "Defense +1", 20, armor = 1), Item(ItemType.Ring, "Defense +2", 40, armor = 2), Item(ItemType.Ring, "Defense +3", 80, armor = 3) ) override fun parseInput(rawInput: String): Stats { val lines = rawInput.lines() return Stats( lines[0].split(" ").last().toInt(), lines[1].split(" ").last().toInt(), lines[2].split(" ").last().toInt() ) } private fun simulate(stats1: Stats, stats2: Stats): Result { val character1 = Character(stats1) val character2 = Character(stats2) var turns = 0 while (true) { turns++ if (character1.attack(character2)) break turns++ if (character2.attack(character1)) break } return Result(character1.health, character2.health, turns) } private fun generateEquipmentSets(): Set<Set<Item>> { val typeSets = ItemType.values().map { generateEquipmentTypeSets(it) }.map { it.toList() } val variations = typeSets.map { it.size }.reduce { acc, it -> acc * it } return (0 until variations).map { i -> var index = i val fullSet = mutableSetOf<Item>() for (typeSet in typeSets) { fullSet += typeSet[index % typeSet.size] index /= typeSet.size } return@map fullSet }.toSet() } private fun generateEquipmentTypeSets(type: ItemType): Set<Set<Item>> { return type.equipLimit.flatMap { generateEquipmentTypeSets(shop.filter { it.type == type }.toSet(), it) }.toSet() } private fun generateEquipmentTypeSets(options: Set<Item>, count: Int, existing: Set<Item> = emptySet()): Set<Set<Item>> { return when (count) { 0 -> setOf(existing) 1 -> options.map { existing + it }.toSet() else -> options.flatMap { generateEquipmentTypeSets(options - it, count - 1, existing + it) }.toSet() } } private enum class ExpectedResult { CheapWin, ExpensiveLoss } private fun task(enemyStats: Stats, expectedResult: ExpectedResult): Int { var sets = generateEquipmentSets().toList() sets = when (expectedResult) { ExpectedResult.CheapWin -> sets.sortedBy { it.sumOf { it.cost } } ExpectedResult.ExpensiveLoss -> sets.sortedByDescending { it.sumOf { it.cost } } } for (set in sets) { println("${set.joinToString()} (cost: ${set.sumOf { it.cost }}, damage: ${set.sumOf { it.damage }}, armor: ${set.sumOf { it.armor }})") val playerStats = Stats(playerHealth, set) val result = simulate(playerStats, enemyStats) println("\t$result") when (expectedResult) { ExpectedResult.CheapWin -> { if (result.playerHealth > 0) return set.sumOf { it.cost } } ExpectedResult.ExpensiveLoss -> { if (result.enemyHealth > 0) return set.sumOf { it.cost } } } } throw IllegalStateException() } override fun part1(input: Stats): Int { return task(input, ExpectedResult.CheapWin) } override fun part2(input: Stats): Int { return task(input, ExpectedResult.ExpensiveLoss) } }
0
Kotlin
0
0
9abb1e3db1cad329cfe1e3d6deae2d6b7456c785
4,856
Advent-of-Code
Apache License 2.0
src/Day02.kt
DevHexs
573,262,501
false
{"Kotlin": 11452}
fun main(){ fun part1(): Int { var pointsPlayer1 = 0 var pointsPlayer2 = 0 // A | X = Rock, B | Y = Paper, C | Z = Scissors val pointSelection = mapOf( "A" to 1, "B" to 2, "C" to 3, "X" to 1, "Y" to 2, "Z" to 3) val pointResult = mapOf("lost" to 0, "draw" to 3, "win" to 6) fun resultPoints(result1: String, selection1: String, result2: String, selection2: String){ pointsPlayer1 += pointResult[result1]!! + pointSelection[selection1]!! pointsPlayer2 += pointResult[result2]!! + pointSelection[selection2]!! } fun draw(selection: String){ pointsPlayer1 += pointResult["draw"]!! + pointSelection[selection]!! pointsPlayer2 += pointResult["draw"]!! + pointSelection[selection]!! } val input = readInput("Day02") for(i in input){ when(i.split(" ")){ listOf("A","X") -> draw("A") listOf("A","Y") -> resultPoints("lost", "A","win","Y") listOf("A","Z") -> resultPoints("win","A", "lost", "Z") listOf("B","X") -> resultPoints("win","B", "lost","X") listOf("B","Y") -> draw("B") listOf("B","Z") -> resultPoints("lost", "B" ,"win","Z") listOf("C","X") -> resultPoints("lost","C","win","X") listOf("C","Y") -> resultPoints("win","C","lost","Y") listOf("C","Z") -> draw("C") else -> continue } } return if (pointsPlayer1 > pointsPlayer2) pointsPlayer1 else pointsPlayer2 } fun part2(): Int { var pointsPlayer1 = 0 var pointsPlayer2 = 0 // A | X = Rock, B | Y = Paper, C | Z = Scissors val pointSelection = mapOf( "A" to 1, "B" to 2, "C" to 3) val pointResult = mapOf("lost" to 0, "draw" to 3, "win" to 6) fun resultPoints(result1: String, selection1: String, result2: String, selection2: String){ pointsPlayer1 += pointResult[result1]!! + pointSelection[selection1]!! pointsPlayer2 += pointResult[result2]!! + pointSelection[selection2]!! } fun draw(selection: String){ pointsPlayer1 += pointResult["draw"]!! + pointSelection[selection]!! pointsPlayer2 += pointResult["draw"]!! + pointSelection[selection]!! } val input = readInput("Day02") for(i in input){ when(i.split(" ")){ listOf("A","X") -> resultPoints("lost","C","win","A") listOf("A","Y") -> draw("A") listOf("A","Z") -> resultPoints("win","B", "lost", "A") listOf("B","X") -> resultPoints("lost","A", "win","B") listOf("B","Y") -> draw("B") listOf("B","Z") -> resultPoints("win", "C" ,"lost","B") listOf("C","X") -> resultPoints("lost","B","win","C") listOf("C","Y") -> draw("C") listOf("C","Z") -> resultPoints("win","A","lost","C") else -> continue } } return if (pointsPlayer1 > pointsPlayer2) pointsPlayer1 else pointsPlayer2 } println(part1()) println(part2()) }
0
Kotlin
0
0
df0ff2ed7c1ebde9327cd1a102499ac5467b73be
3,354
AdventOfCode-2022-Kotlin
Apache License 2.0
src/main/kotlin/days/Geometry.kt
andilau
726,429,411
false
{"Kotlin": 37060}
package days import kotlin.math.absoluteValue import kotlin.math.sign data class Point(val x: Int, val y: Int) { val north: Point get() = this.copy(y = y - 1) val northwest: Point get() = this + Point(-1, -1) val northeast: Point get() = this + Point(1, -1) val south: Point get() = this + Point(0, 1) val southwest: Point get() = this + Point(-1, 1) val southeast: Point get() = this + Point(1, 1) val west: Point get() = this + Point(-1, 0) val east: Point get() = this + Point(1, 0) fun neighboursAndSelf(): Set<Point> = setOf( copy(x = x + 1), copy(y = y + 1), copy(x = x - 1), copy(y = y - 1), copy(), ) fun neighbours() = setOf( copy(x = x + 1), copy(y = y + 1), copy(x = x - 1), copy(y = y - 1), ) fun neighboursAll() = setOf( copy(x = x + 1), copy(x = x - 1), copy(x = x + 1, y = y - 1), copy(x = x + 1, y = y + 1), copy(y = y + 1), copy(y = y - 1), copy(x = x - 1, y = y - 1), copy(x = x - 1, y = y + 1), ) fun lineto(to: Point): Sequence<Point> { val dx = (to.x - x).sign val dy = (to.y - y).sign return generateSequence(this) { if (it == to) null else it + Point(dx, dy) } } operator fun plus(other: Point) = Point(x + other.x, y + other.y) operator fun minus(other: Point) = Point(x - other.x, y - other.y) operator fun times(value: Int) = Point(x * value, y * value) fun distance(other: Point): Int { return (other.x - x).absoluteValue + (other.y - y).absoluteValue } override fun toString(): String { return "P($x,$y)" } companion object { val WEST = Point(-1, 0) val EAST = Point(1, 0) val NORTH = Point(0, -1) val SOUTH = Point(0, 1) fun from(line: String) = line .split(",") .map(String::toInt) .let { (x, y) -> Point(x, y) } } } operator fun Int.times(vector: Point) = vector.times(this) fun List<String>.extractOnly(char: Char): Set<Point> { return this.flatMapIndexed() { y, row -> row.mapIndexedNotNull { x, c -> if (c == char) Point(x, y) else null } } .toSet() } fun Iterable<Point>.draw() { (minOf { it.y }..maxOf { it.y }).forEach { y -> (minOf { it.x }..maxOf { it.x }).map { x -> if (Point(x, y) in this) '#' else '.' }.joinToString("") .also { println(it) } } } fun <T> Map<Point, T>.mapAsString(default: T, mapping: (T) -> Char) = buildString { val map = this@mapAsString val yRange = keys.minOf(Point::y)..keys.maxOf(Point::y) val xRange = (keys.minOf(Point::x)..keys.maxOf(Point::x)) for (y in yRange) { val line = xRange .map { x -> map.getOrDefault(Point(x, y), default) } .map { mapping(it) } .joinToString("") appendLine(line) } }
3
Kotlin
0
0
9a1f13a9815ab42d7fd1d9e6048085038d26da90
3,026
advent-of-code-2023
Creative Commons Zero v1.0 Universal
src/main/kotlin/Puzzle17.kt
namyxc
317,466,668
false
null
object Puzzle17 { @JvmStatic fun main(args: Array<String>) { val input = Puzzle17::class.java.getResource("puzzle17.txt").readText() val calculatedActiveCountIn3D = calculateActiveCountIn3D(input) println(calculatedActiveCountIn3D) val calculatedActiveCountIn4D = calculateActiveCountIn4D(input) println(calculatedActiveCountIn4D) } fun calculateActiveCountIn3D(input: String): Int { var state = State3D(input) for (i in 1..6){ state = state.getNextState() } return state.countActiveCells() } fun calculateActiveCountIn4D(input: String): Int { var state = State4D(input) for (i in 1..6){ state = state.getNextState() } return state.countActiveCells() } class State3D{ private val grid: List<List<CharArray>> constructor(input: String){ val initialState = input.split("\n").map { line -> line.toCharArray() } grid = listOf(initialState) } constructor(grid: List<List<CharArray>>){ this.grid = grid } private fun zDimension() = grid.size private fun yDimension() = grid.first().size private fun xDimension() = grid.first().first().size private fun getGridAt(z: Int, y: Int, x: Int): Char{ return if (z in 0 until zDimension() && y in 0 until yDimension() && x in 0 until xDimension()){ grid[z][y][x] }else '.' } fun getNextState(): State3D { val nextState = mutableListOf<List<CharArray>>() val nextXDimension = xDimension() + 2 val nextYDimension = yDimension() + 2 val nextZDimension = zDimension() + 2 for (z in 0 until nextZDimension) { val rows = mutableListOf<CharArray>() for (y in 0 until nextYDimension) { val row = CharArray(nextXDimension) for (x in 0 until nextXDimension) { val currentStateZ = z - 1 val currentStateY = y - 1 val currentStateX = x - 1 val activeNeighbourCount = activeNeighbourCount(currentStateZ, currentStateY, currentStateX) row[x] = if (getGridAt(currentStateZ, currentStateY, currentStateX) == '#') { if (activeNeighbourCount == 2 || activeNeighbourCount == 3) '#' else '.' } else if (activeNeighbourCount == 3) '#' else '.' } rows.add(row) } nextState.add(rows) } return State3D(nextState) } private fun activeNeighbourCount(z: Int, y: Int, x: Int): Int { var count = 0 for (i in -1..1) for (j in -1..1) for (k in -1..1){ if ( (i != 0 || j != 0 || k != 0) && getGridAt(z+k, y+j, x+i) == '#' ){ count++ } } return count } fun countActiveCells(): Int { return grid.sumOf { z -> z.sumOf { y -> y.count { x -> x == '#' } }} } } class State4D{ private val grid: List<List<List<CharArray>>> constructor(input: String){ val initialState = input.split("\n").map { line -> line.toCharArray() } grid = listOf(listOf(initialState)) } constructor(grid: List<List<List<CharArray>>>){ this.grid = grid } private fun wDimension() = grid.size private fun zDimension() = grid.first().size private fun yDimension() = grid.first().first().size private fun xDimension() = grid.first().first().first().size private fun getGridAt(w: Int, z: Int, y: Int, x: Int): Char{ return if ( w in 0 until wDimension() && z in 0 until zDimension() && y in 0 until yDimension() && x in 0 until xDimension()){ grid[w][z][y][x] }else '.' } fun getNextState(): State4D { val nextState = mutableListOf<List<List<CharArray>>>() val nextXDimension = xDimension() + 2 val nextYDimension = yDimension() + 2 val nextZDimension = zDimension() + 2 val nextWDimension = wDimension() + 2 for (w in 0 until nextWDimension) { val layers = mutableListOf<List<CharArray>>() for (z in 0 until nextZDimension) { val rows = mutableListOf<CharArray>() for (y in 0 until nextYDimension) { val row = CharArray(nextXDimension) for (x in 0 until nextXDimension) { val currentStateW = w - 1 val currentStateZ = z - 1 val currentStateY = y - 1 val currentStateX = x - 1 val activeNeighbourCount = activeNeighbourCount(currentStateW, currentStateZ, currentStateY, currentStateX) row[x] = if (getGridAt(currentStateW, currentStateZ, currentStateY, currentStateX) == '#') { if (activeNeighbourCount == 2 || activeNeighbourCount == 3) '#' else '.' } else if (activeNeighbourCount == 3) '#' else '.' } rows.add(row) } layers.add(rows) } nextState.add(layers) } return State4D(nextState) } private fun activeNeighbourCount(w: Int, z: Int, y: Int, x: Int): Int { var count = 0 for (i in -1..1) for (j in -1..1) for (k in -1..1) for (l in -1..1){ if ( (i != 0 || j != 0 || k != 0 || l != 0) && getGridAt(w+l,z+k, y+j, x+i) == '#' ){ count++ } } return count } fun countActiveCells(): Int { return grid.sumOf { w -> w.sumOf { z -> z.sumOf { y -> y.count { x -> x == '#' } }}} } } }
0
Kotlin
0
0
60fa6991ac204de6a756456406e1f87c3784f0af
6,867
adventOfCode2020
MIT License
src/main/kotlin/dev/siller/aoc2022/Day04.kt
chearius
575,352,798
false
{"Kotlin": 41999}
package dev.siller.aoc2022 private val example = """ 2-4,6-8 2-3,4-5 5-7,7-9 2-8,3-7 6-6,4-6 2-6,4-8 """.trimIndent() private fun part1(input: List<String>): Int = getRanges(input) .count { (r1, r2) -> r1.first <= r2.first && r1.last >= r2.last || r2.first <= r1.first && r2.last >= r1.last } private fun part2(input: List<String>): Int = getRanges(input) .count { (r1, r2) -> r1.first <= r2.first && r1.last >= r2.first || r2.first <= r1.first && r2.last >= r1.first } private fun getRanges(input: List<String>) = input .map { l -> val (s1, s2) = l.split(",", limit = 2) val r1 = s1.substringBefore("-").toInt()..s1.substringAfter("-").toInt() val r2 = s2.substringBefore("-").toInt()..s2.substringAfter("-").toInt() r1 to r2 } fun aocDay04() = aocTaskWithExample( day = 4, part1 = ::part1, part2 = ::part2, exampleInput = example, expectedOutputPart1 = 2, expectedOutputPart2 = 4 ) fun main() { aocDay04() }
0
Kotlin
0
0
e070c0254a658e36566cc9389831b60d9e811cc5
1,040
advent-of-code-2022
MIT License
src/Day06.kt
AndreiShilov
572,661,317
false
{"Kotlin": 25181}
import java.io.File import java.util.Stack fun main() { fun solve(input: String, msgSize: Int): Int { var marker = 0 val windowed = input.toCharArray().toList().asSequence().windowed(msgSize) for (window in windowed) { marker++ if (window.toSet().size == msgSize) break } return marker + msgSize - 1 } fun part1(input: String): Int { return solve(input, 4) } fun part2(input: String): Int { return solve(input, 14) } // test if implementation meets criteria from the description, like: check(part1(readInput("Day06_test")[1]) == 5) check(part1(readInput("Day06_test")[2]) == 6) check(part1(readInput("Day06_test")[3]) == 10) check(part1(readInput("Day06_test")[4]) == 11) check(part2(readInput("Day06_test")[0]) == 19) check(part2(readInput("Day06_test")[1]) == 23) check(part2(readInput("Day06_test")[2]) == 23) check(part2(readInput("Day06_test")[3]) == 29) check(part2(readInput("Day06_test")[4]) == 26) // check(part2(name = "Day05_test") == "MCD") val input = readInput("Day06") println(part1(input[0])) println(part2(input[0])) }
0
Kotlin
0
0
852b38ab236ddf0b40a531f7e0cdb402450ffb9a
1,202
aoc-2022
Apache License 2.0
src/Day02.kt
petoS6
573,018,212
false
{"Kotlin": 14258}
fun main() { fun part1(input: List<String>): Int { return input.sumOf { it.split(" ").let { Game(it[0], it[1]) }.score1 } } fun part2(input: List<String>): Int { return input.sumOf { it.split(" ").let { Game(it[0], it[1]) }.score2 } } val testInput = readInput("Day02.txt") println(part1(testInput)) println(part2(testInput)) } private data class Game( val other : String, val yours : String ) { val score1 = when { other == "A" && yours == "X" -> 4 // Rock Draw other == "A" && yours == "Y" -> 8 // Rock Win other == "A" && yours == "Z" -> 3 // Rock Lose other == "B" && yours == "X" -> 1 // Paper Lose other == "B" && yours == "Y" -> 5 // Paper Draw other == "B" && yours == "Z" -> 9 // Paper Win other == "C" && yours == "X" -> 7 // Scissors Win other == "C" && yours == "Y" -> 2 // Scissors Lose other == "C" && yours == "Z" -> 6 // Scissors Draw else -> throw IllegalStateException("Unsupported choose $other and $yours") } val score2 = when { other == "A" && yours == "X" -> 3 // Lose other == "A" && yours == "Y" -> 4 // Draw other == "A" && yours == "Z" -> 8 // Win other == "B" && yours == "X" -> 1 // Lose other == "B" && yours == "Y" -> 5 // Draw other == "B" && yours == "Z" -> 9 // Win other == "C" && yours == "X" -> 2 // Lose other == "C" && yours == "Y" -> 6 // Draw other == "C" && yours == "Z" -> 7 // Win else -> throw IllegalStateException("Unsupported choose $other and $yours") } }
0
Kotlin
0
0
40bd094155e664a89892400aaf8ba8505fdd1986
1,521
kotlin-aoc-2022
Apache License 2.0
src/main/kotlin/advent/of/code/day12/Solution.kt
brunorene
160,263,437
false
null
package advent.of.code.day12 import java.io.File // STILL WRONG :( data class PlantsInPots(val data: MutableSet<Long> = mutableSetOf()) { companion object { fun build(init: String): PlantsInPots { val instance = PlantsInPots() init.forEachIndexed { index, c -> instance[index.toLong()] = c } return instance } } fun copy() = PlantsInPots(data.toMutableSet()) operator fun get(index: Long) = if (data.contains(index)) '#' else '.' operator fun set(index: Long, c: Char) = if (c == '#') data.add(index) else data.remove(index) fun sumPlantIndexes() = data.sum() fun plantCount() = data.size fun min() = data.min() ?: 0 fun max() = data.max() ?: 0 fun slice(middle: Long, borderSize: Long) = ((middle - borderSize)..(middle + borderSize)).map { get(it) }.joinToString("") override fun toString() = (-10..max()).joinToString("") { idx -> if (idx == 0L) get(idx).toString() .replace('#', 'X') .replace('.', 'o') else get(idx).toString() } } const val initState = "#...##.#...#..#.#####.##.#..###.#.#.###....#...#...####.#....##..##..#..#..#..#.#..##.####.#.#.###" val rules = File("day12.txt").readLines().drop(2) .map { it.substring((0..4)) to it[9] } fun calculate(lasIteration: Int): Long { val generation = PlantsInPots.build(initState) // println(info(0, generation)) for (g in (1..lasIteration)) { val before = generation.copy() ((before.min() - 5)..(before.max() + 5)) .map { pos -> val pattern = before.slice(pos, 2) val rule = rules.firstOrNull { pattern == it.first } generation[pos] = rule?.second ?: '.' } // println(info(g, generation)) } return generation.sumPlantIndexes() } fun part1() = calculate(20) fun part2(): Long { val res200 = calculate(200) val res300 = calculate(300) // val res400 = calculate(400) val diff = res300 - res200 // println("${res400 - res300} ${res300 - res200}") return (50_000_000_000 - 200) / 100 * diff + res200 } fun info(g: Int, gen: PlantsInPots) = g.toString().padStart(4, '0') + " - $gen" + " - ${gen.sumPlantIndexes()}" + " - ${gen.plantCount()}" + " - ${gen.min()}" + " - ${gen.max()}"
0
Kotlin
0
0
0cb6814b91038a1ab99c276a33bf248157a88939
2,434
advent_of_code_2018
The Unlicense
kotlin/graphs/flows/MaxFlowDinic.kt
polydisc
281,633,906
true
{"Java": 540473, "Kotlin": 515759, "C++": 265630, "CMake": 571}
package graphs.flows import java.util.stream.Stream // https://en.wikipedia.org/wiki/Dinic%27s_algorithm in O(V^2 * E) class MaxFlowDinic(nodes: Int) { var graph: Array<List<Edge>> var dist: IntArray inner class Edge(var t: Int, var rev: Int, var cap: Int) { var f = 0 } fun addBidiEdge(s: Int, t: Int, cap: Int) { graph[s].add(Edge(t, graph[t].size(), cap)) graph[t].add(Edge(s, graph[s].size() - 1, 0)) } fun dinicBfs(src: Int, dest: Int): Boolean { Arrays.fill(dist, -1) dist[src] = 0 val q = IntArray(graph.size) var sizeQ = 0 q[sizeQ++] = src for (i in 0 until sizeQ) { val u = q[i] for (e in graph[u]) { if (dist[e.t] < 0 && e.f < e.cap) { dist[e.t] = dist[u] + 1 q[sizeQ++] = e.t } } } return dist[dest] >= 0 } fun dinicDfs(ptr: IntArray, dest: Int, u: Int, f: Int): Int { if (u == dest) return f while (ptr[u] < graph[u].size()) { val e = graph[u][ptr[u]] if (dist[e.t] == dist[u] + 1 && e.f < e.cap) { val df = dinicDfs(ptr, dest, e.t, Math.min(f, e.cap - e.f)) if (df > 0) { e.f += df graph[e.t][e.rev].f -= df return df } } ++ptr[u] } return 0 } fun maxFlow(src: Int, dest: Int): Int { var flow = 0 while (dinicBfs(src, dest)) { val ptr = IntArray(graph.size) var df: Int while (dinicDfs(ptr, dest, src, Integer.MAX_VALUE).also { df = it } != 0) { flow += df } } return flow } // invoke after maxFlow() fun minCut(): BooleanArray { val cut = BooleanArray(graph.size) for (i in cut.indices) cut[i] = dist[i] != -1 return cut } fun clearFlow() { for (edges in graph) for (edge in edges) edge.f = 0 } companion object { // Usage example fun main(args: Array<String?>?) { val flow = MaxFlowDinic(3) flow.addBidiEdge(0, 1, 3) flow.addBidiEdge(0, 2, 2) flow.addBidiEdge(1, 2, 2) System.out.println(4 == flow.maxFlow(0, 2)) } } init { graph = Stream.generate { ArrayList() }.limit(nodes).toArray { _Dummy_.__Array__() } dist = IntArray(nodes) } }
1
Java
0
0
4566f3145be72827d72cb93abca8bfd93f1c58df
2,558
codelibrary
The Unlicense
solutions/src/SmallestStringFromLeaf.kt
JustAnotherSoftwareDeveloper
139,743,481
false
{"Kotlin": 305071, "Java": 14982}
import kotlin.math.min //https://leetcode.com/problems/smallest-string-starting-from-leaf/ /** * Example: * var ti = TreeNode(5) * var v = ti.`val` * Definition for a binary tree node. * class TreeNode(var `val`: Int) { * var left: TreeNode? = null * var right: TreeNode? = null * } */ class SmallestStringFromLeaf { companion object { val charMap: MutableMap<Int,Char> = mutableMapOf(); } fun smallestFromLeaf(root: TreeNode?): String { "abcdefghijklmnopqrstuvwxyz".forEachIndexed { index, c -> charMap[index] = c } return traverse(root, "") } private fun traverse(t: TreeNode?, currString: String) : String { if (t == null ) { return "" } val newString = charMap[t.`val`]!!.toString() + currString return if (t.left == null && t.right == null) { newString } else if (t.left == null && t.right != null) { traverse(t.right,newString) } else if (t.right == null && t.left != null) { traverse(t.left,newString) } else { val left = traverse(t.left,newString) val right = traverse(t.right, newString) if (left > right) {right} else {left} } } class TreeNode(var `val`: Int?) { var left: TreeNode? = null var right: TreeNode? = null } }
0
Kotlin
0
0
fa4a9089be4af420a4ad51938a276657b2e4301f
1,399
leetcode-solutions
MIT License
src/Day10.kt
JohannesPtaszyk
573,129,811
false
{"Kotlin": 20483}
fun main() { fun getCycles(input: List<String>) = input.flatMap { val instruction = it.split(" ") if (instruction.first() == "noop") { listOf(null) } else { listOf(null, instruction[1].toInt()) } } fun part1(input: List<String>): Int { var x = 1 var result = 0 val measuredCycles = IntProgression.fromClosedRange(20,220,40) getCycles(input).forEachIndexed { index, instruction -> val cycleNo = index + 1 if(measuredCycles.contains(cycleNo)){ val signalStrength = x * cycleNo result += signalStrength } if(instruction != null) { x += instruction } } return result } fun part2(input: List<String>): String { var x = 1 var result = "" getCycles(input).chunked(40).forEach { it.forEachIndexed { index, instruction -> result += if(index in x-1..x+1) "#" else "." if(result.replace(System.lineSeparator(), "").length % 40 == 0) { result+=System.lineSeparator() } if(instruction != null) { x += instruction } } } return result } val testInput = readInput("Day10_test") val input = readInput("Day10") val testResultPart1 = part1(testInput) println("Part1 test: $testResultPart1") check(testResultPart1 == 13140) println("Part 1: ${part1(input)}") val testResultPart2 = part2(testInput) println("Part2 test: ${System.lineSeparator()}$testResultPart2") println("Part 2: ${System.lineSeparator()}${part2(input)}") }
0
Kotlin
0
1
6f6209cacaf93230bfb55df5d91cf92305e8cd26
1,770
advent-of-code-2022
Apache License 2.0
src/Day20.kt
greg-burgoon
573,074,283
false
{"Kotlin": 120556}
fun main() { data class Node(val value: Long, var visited: Boolean, var leftNode: Node? = null, var rightNode: Node? = null) { fun printLeft(): String { var trackNode = leftNode var s = this.value.toString() + ", " while (trackNode != this) { s = s + trackNode?.value!! + ", " trackNode = trackNode?.leftNode!! } return s } fun printRight(): String { var trackNode = rightNode var s = this.value.toString() + ", " while (trackNode != this) { s = s + trackNode?.value!! + ", " trackNode = trackNode?.rightNode!! } return s } } fun getMixedList(originalList: List<Node>, rotations: Int): Node { var startNode = originalList.first() var zeroNode = Node(0, false) var doubleLinkedCircularList = originalList.reduce { acc, node -> acc.rightNode = node node.leftNode = acc node } startNode.leftNode = doubleLinkedCircularList doubleLinkedCircularList.rightNode = startNode repeat(rotations) { for (currentNode in originalList) { var numberOfMoves = currentNode?.value!! % (originalList.size - 1) if (currentNode.value == 0L) { zeroNode = currentNode continue } currentNode.leftNode?.rightNode = currentNode.rightNode currentNode.rightNode?.leftNode = currentNode.leftNode var newPosition = currentNode!! for (i in 0..Math.abs(numberOfMoves) - 1) { if (numberOfMoves < 0) { newPosition = newPosition.leftNode!! } else if (numberOfMoves > 0) { newPosition = newPosition.rightNode!! } } if (numberOfMoves < 0) { newPosition.leftNode?.rightNode = currentNode currentNode.leftNode = newPosition.leftNode newPosition.leftNode = currentNode currentNode.rightNode = newPosition } else if (numberOfMoves > 0) { newPosition.rightNode?.leftNode = currentNode currentNode.rightNode = newPosition.rightNode newPosition.rightNode = currentNode currentNode.leftNode = newPosition } } } return zeroNode } fun part1(input: String): Long { var originalList = input.split("\n").map { Node(it.toLong(), false) } var zeroNode = getMixedList(originalList, 1) var sum = 0L var trackNode = zeroNode repeat(1000){ trackNode = trackNode.rightNode!! } sum += trackNode.value trackNode = zeroNode repeat(2000){ trackNode = trackNode.rightNode!! } sum += trackNode.value trackNode = zeroNode repeat(3000){ trackNode = trackNode.rightNode!! } sum += trackNode.value return sum } fun part2(input: String): Long { var inputLists = input.split("\n") var originalList = inputLists.map { Node((it.toLong()*811589153), false) } var zeroNode = getMixedList(originalList, 10) var sum = 0L var trackNode = zeroNode repeat(1000){ trackNode = trackNode.rightNode!! } sum += trackNode.value trackNode = zeroNode repeat(2000){ trackNode = trackNode.rightNode!! } sum += trackNode.value trackNode = zeroNode repeat(3000){ trackNode = trackNode.rightNode!! } sum += trackNode.value return sum } // test if implementation meets criteria from the description, like: val testInput = readInput("Day20_test") val output = part1(testInput) check(output== 3L) val input = readInput("Day20") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
74f10b93d3bad72fa0fc276b503bfa9f01ac0e35
4,228
aoc-kotlin
Apache License 2.0
src/Day02.kt
casslabath
573,177,204
false
{"Kotlin": 27085}
fun main() { /** * Rock = A or X 1pt * Paper = B or Y 2pt * Scissors = C or Z 3pt * * AX beats CZ * BY beats AX * CZ beats BY */ val leftResults = listOf("A","B","C") val rightResults = listOf("X","Y","Z") fun calculateWinningPoints(leftIndex: Int, rightIndex: Int): Int { if(rightIndex == (leftIndex + 1) % 3) { return 6 } else if (rightIndex == leftIndex) { return 3 } return 0 } fun expectedMoveIndex(opponentIndex: Int, gameResultIndex: Int): Int { if(gameResultIndex == 0) { var index = opponentIndex - 1 if (index < 0) { index = 2 } return index } else if(gameResultIndex == 1) { return opponentIndex } else { return (opponentIndex + 1) % 3 } } fun part1(input: List<String>): Int { var total = 0 input.map { val results = it.split(" ") val opponentIndex = leftResults.indexOf(results[0]) val yourIndex = rightResults.indexOf(results[1]) total += yourIndex + 1 + calculateWinningPoints(opponentIndex, yourIndex) } return total } /** * Rock = A 1pt * Paper = B 2pt * Scissors = C 3pt * * X Lose 0pt * Y Draw 3pt * Z Win 6pt */ fun part2(input: List<String>): Int { var total = 0 input.map { val results = it.split(" ") val opponentIndex = leftResults.indexOf(results[0]) val gameResultIndex = rightResults.indexOf(results[1]) total += gameResultIndex * 3 + expectedMoveIndex(opponentIndex, gameResultIndex) + 1 } return total } val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
5f7305e45f41a6893b6e12c8d92db7607723425e
1,935
KotlinAdvent2022
Apache License 2.0
src/main/kotlin/io/queue/FindNearestZero.kt
jffiorillo
138,075,067
false
{"Kotlin": 434399, "Java": 14529, "Shell": 465}
package io.queue import java.util.* //https://leetcode.com/explore/learn/card/queue-stack/239/conclusion/1388/ class FindNearestZero { private val defaultValue = Int.MAX_VALUE fun execute(input: Array<IntArray>): Array<IntArray> = Array(input.size) { IntArray(input[0].size) }.apply { for (row in this) Arrays.fill(row, defaultValue) input.mapIndexed { x, row -> row.mapIndexed { y, element -> when { element == 0 -> this[x][y] = 0 this[x][y] == defaultValue -> { var stack = listOf(CoordinatesLinkedList(Coordinates(x, y))) var steps = 0 var found = false while (!found) { stack = stack.flatMap { current -> when { input[current.coordinates.i][current.coordinates.j] == 0 -> { this[x][y] = steps found = true updateParent(this, current) emptyList() } else -> current.coordinates.generateChild(input.size, input[0].size).map { CoordinatesLinkedList(it, current) } } } steps++ } } } } } } private fun updateParent(output: Array<IntArray>, coordinatesLinkedList: CoordinatesLinkedList) = generateSequence(coordinatesLinkedList to 0) { seed -> seed.first.father?.let { it to (seed.second + 1) } } .map { (coordinates, value) -> if (output[coordinates.coordinates.i][coordinates.coordinates.j] == defaultValue) output[coordinates.coordinates.i][coordinates.coordinates.j] = value } data class CoordinatesLinkedList(val coordinates: Coordinates, val father: CoordinatesLinkedList? = null) } fun main() { val findNearestZero = FindNearestZero() listOf( arrayOf( intArrayOf(0, 0, 0), intArrayOf(0, 1, 0), intArrayOf(0, 0, 0) ) to arrayOf( intArrayOf(0, 0, 0), intArrayOf(0, 1, 0), intArrayOf(0, 0, 0)), arrayOf( intArrayOf(0, 0, 0), intArrayOf(0, 1, 0), intArrayOf(1, 1, 1) ) to arrayOf( intArrayOf(0, 0, 0), intArrayOf(0, 1, 0), intArrayOf(1, 2, 1) ), arrayOf( intArrayOf(0, 1, 0, 1, 1), intArrayOf(1, 1, 0, 0, 1), intArrayOf(0, 0, 0, 1, 0), intArrayOf(1, 0, 1, 1, 1), intArrayOf(1, 0, 0, 0, 1) ) to arrayOf( intArrayOf(0, 1, 0, 1, 2), intArrayOf(1, 1, 0, 0, 1), intArrayOf(0, 0, 0, 1, 0), intArrayOf(1, 0, 1, 1, 1), intArrayOf(1, 0, 0, 0, 1) ) ).mapIndexed { index, (input, output) -> val execute = findNearestZero.execute(input) val isValid = execute.indices.fold(true) { iAcc, i -> iAcc && execute.first().indices.fold(true) { jAcc, j -> jAcc && execute[i][j] == output[i][j] } } println("$index is ${if (isValid) "valid" else "invalid"}") } }
0
Kotlin
0
0
f093c2c19cd76c85fab87605ae4a3ea157325d43
3,129
coding
MIT License
archive/src/main/kotlin/com/grappenmaker/aoc/year19/Day20.kt
770grappenmaker
434,645,245
false
{"Kotlin": 409647, "Python": 647}
package com.grappenmaker.aoc.year19 import com.grappenmaker.aoc.* import com.grappenmaker.aoc.Direction.* fun PuzzleSet.day20() = puzzle(day = 20) { val grid = inputLines.asCharGrid() val valid = grid.findPointsValued('.').toSet() data class Portal(val name: String, val at: Point) val portals = with(grid) { valid.mapNotNull { p -> listOf( p + LEFT + LEFT to p + LEFT, p + DOWN to p + DOWN + DOWN, p + UP + UP to p + UP, p + RIGHT to p + RIGHT + RIGHT ).singleOrNull { (a, b) -> a in grid && b in grid && this[a] in 'A'..'Z' && this[b] in 'A'..'Z' } ?.let { (a, b) -> Portal(this[a].toString() + this[b].toString(), p) } } } val byName = portals.groupBy { it.name } val links = buildMap { byName.forEach { (_, v) -> if (v.size == 2) { val (a, b) = v put(a.at, b.at) put(b.at, a.at) } } } val start = byName.getValue("AA").single().at val end = byName.getValue("ZZ").single().at val insideX = valid.minX() + 1..<valid.maxX() val insideY = valid.minY() + 1..<valid.maxY() data class State(val at: Point, val layer: Int = 0) fun solve(partTwo: Boolean) = bfsDistance( initial = State(start), isEnd = { it.at == end && it.layer == 0 }, neighbors = { (at, layer) -> at.adjacentSidesInf().filter { it in valid }.map { State(it, layer) } + listOfNotNull(links[at]).map { p -> val newLayer = when { !partTwo -> 0 at.x in insideX && at.y in insideY -> layer + 1 else -> layer - 1 } State(p, newLayer) }.filterNot { it.layer < 0 } } ).dist.s() partOne = solve(false) partTwo = solve(true) }
0
Kotlin
0
7
92ef1b5ecc3cbe76d2ccd0303a73fddda82ba585
1,932
advent-of-code
The Unlicense
2021/src/main/kotlin/com/trikzon/aoc2021/Day7.kt
Trikzon
317,622,840
false
{"Kotlin": 43720, "Rust": 21648, "C#": 12576, "C++": 4114, "CMake": 397}
package com.trikzon.aoc2021 import kotlin.math.absoluteValue fun main() { val input = getInputStringFromFile("/day7.txt") benchmark(Part.One, ::day7Part1, input, 328262, 5000) benchmark(Part.Two, ::day7Part2, input, 90040997, 500) } fun day7Part1(input: String): Int { val horizPositions = input.split(',').map { str -> str.toInt() } var smallestFuelAmount = Int.MAX_VALUE for (i in 0..horizPositions.maxOf { num -> num }) { var fuelAmount = 0 for (horizPos in horizPositions) { fuelAmount += (horizPos - i).absoluteValue } if (smallestFuelAmount > fuelAmount) smallestFuelAmount = fuelAmount } return smallestFuelAmount } fun day7Part2(input: String): Int { val horizPositions = input.split(',').map { str -> str.toInt() } var smallestFuelAmount = Int.MAX_VALUE for (i in 0..horizPositions.maxOf { num -> num }) { var fuelAmount = 0 for (horizPos in horizPositions) { (0..(horizPos - i).absoluteValue).forEach { num -> fuelAmount += num} } if (smallestFuelAmount > fuelAmount) smallestFuelAmount = fuelAmount } return smallestFuelAmount }
0
Kotlin
1
0
d4dea9f0c1b56dc698b716bb03fc2ad62619ca08
1,184
advent-of-code
MIT License
src/Day14.kt
Aldas25
572,846,570
false
{"Kotlin": 106964}
fun main() { fun dropSand(grid: Array<Array<Boolean>>): Pair<Int, Int> { var x = 500 var y = 0 while (true) { if (y >= 1000-1) break if (!grid[x][y+1]) y++ else if (!grid[x-1][y+1]) { x-- y++ } else if (!grid[x+1][y+1]) { x++ y++ } else break } return Pair(x, y) } fun printGrid(grid: Array<Array<Boolean>>) { println("grid:") for (y in 0..11) { for (x in 490..505) { if (grid[x][y]) print('#') else print('.') } println() } println("-----") } fun part1(grid: Array<Array<Boolean>>): Int { var ans = 0 // printGrid(grid) while (true) { val sandPos = dropSand(grid) if (sandPos.second >= 1000-1) break ans++ grid[sandPos.first][sandPos.second] = true if (sandPos.first == 500 && sandPos.second == 0) break // printGrid(grid) } return ans } fun prepareGridPart2(grid: Array<Array<Boolean>>) { var maxY = 0 for (y in grid.indices) { for (x in grid[0].indices) { if (grid[x][y]) maxY = maxOf(maxY, y) } } maxY += 2 for (x in grid[0].indices) grid[x][maxY] = true } fun part2(grid: Array<Array<Boolean>>): Int { prepareGridPart2(grid) return part1(grid) } fun markPath(grid: Array<Array<Boolean>>, fromX: Int, fromY: Int, toX: Int, toY: Int) { val dx = if (fromX == toX) 0 else if (fromX > toX) -1 else 1 val dy = if (fromY == toY) 0 else if (fromY > toY) -1 else 1 var i = fromX var j = fromY while (i != toX || j != toY) { grid[i][j] = true i += dx j += dy } grid[i][j] = true } fun constructGrid(input: List<String>): Array<Array<Boolean>> { val grid = Array(1000) { Array(1000) {false} } for (path in input) { val steps = path.split(" -> ") for (i in steps.indices) { if (i == 0) continue val from = steps[i-1].split(",") val to = steps[i].split(",") val fromX = from[0].toInt() val fromY = from[1].toInt() val toX = to[0].toInt() val toY = to[1].toInt() markPath(grid, fromX, fromY, toX, toY) } } return grid } val filename = // "inputs/day14_sample" "inputs/day14" val input = readInput(filename) val grid1 = constructGrid(input) val grid2 = constructGrid(input) println("Part 1: ${part1(grid1)}") println("Part 2: ${part2(grid2)}") }
0
Kotlin
0
0
80785e323369b204c1057f49f5162b8017adb55a
3,040
Advent-of-Code-2022
Apache License 2.0
src/main/kotlin/io/array/KthLargestElementInArray.kt
jffiorillo
138,075,067
false
{"Kotlin": 434399, "Java": 14529, "Shell": 465}
package io.array import io.utils.runTests // https://leetcode.com/problems/kth-largest-element-in-an-array/ class KthLargestElementInArray { // https://leetcode.com/problems/kth-largest-element-in-an-array/discuss/60312/AC-Clean-QuickSelect-Java-solution-avg.-O(n)-time fun execute(input: IntArray, kth: Int, low: Int = 0, high: Int = input.lastIndex): Int { var pivot = low // use quick sort's idea // put nums that are <= pivot to the left // put nums that are > pivot to the right for (index in low until high) { if (input[index] <= input[high]) { input.swap(pivot++, index) } } input.swap(pivot, high) // count the nums that are > pivot from high val count = high - pivot + 1 return when { // pivot is the one! count == kth -> input[pivot] // pivot is too small, so it must be on the right count > kth -> execute(input, kth, pivot + 1, high) // pivot is too big, so it must be on the left else -> execute(input, kth - count, low, pivot - 1) } } } private fun IntArray.swap(pivot: Int, j: Int) { this[pivot].let { this[pivot] = this[j] this[j] = it } } fun main() { runTests(listOf( // Triple(intArrayOf(1), 1, 1), Triple(intArrayOf(3, 2, 1, 5, 6, 4), 2, 5) )) { (input, kth, value) -> value to KthLargestElementInArray().execute(input, kth) } }
0
Kotlin
0
0
f093c2c19cd76c85fab87605ae4a3ea157325d43
1,431
coding
MIT License
src/main/kotlin/y2022/day10/Day10.kt
TimWestmark
571,510,211
false
{"Kotlin": 97942, "Shell": 1067}
package y2022.day10 import kotlin.math.abs fun main() { AoCGenerics.printAndMeasureResults( part1 = { part1() }, part2 = { part2() } ) } fun input(): List<String> { return AoCGenerics.getInputLines("/y2022/day10/input.txt") } fun getCycleValues(commands: List<String>): Map<Int, Int> { var x = 1 val commandIterator = commands.iterator() var needsToWait = false var command = "" val valueByCycle: MutableMap<Int, Int> = mutableMapOf() for (cycle in 1..240) { valueByCycle[cycle] = x if (!needsToWait) { if (!commandIterator.hasNext()) { break } command = commandIterator.next() when (command) { "noop" -> { needsToWait = false continue } else -> { needsToWait = true continue } } } x += command.split(" ")[1].toInt() needsToWait = false } return valueByCycle } fun part1(): Int { val cycleValues = getCycleValues(input()) val interestingCylcles = listOf(20,60,100,140,180,220) return interestingCylcles.sumOf { cycle -> cycle * cycleValues[cycle]!! } } fun part2(): Int { val cyclesValues = getCycleValues(input()) for (row in 0 until 6) { for (charPosition in 1..40) { val cycleNumber = row * 40 + charPosition val x = cyclesValues[cycleNumber]!! val spritePosition = x + 1 when { abs(charPosition - spritePosition) <= 1 -> print("#") else -> print(" ") // we use spaces instead of dots to prevent cluttering of the output with dots } // just for better visualization of the result letters if (charPosition % 5 == 0) { print(" ") } } println() } return 0 // Actual result in the console output (ZKGRKGRK) }
0
Kotlin
0
0
23b3edf887e31bef5eed3f00c1826261b9a4bd30
2,063
AdventOfCode
MIT License
src/main/kotlin/days/Day8.kt
andilau
544,512,578
false
{"Kotlin": 29165}
package days import java.lang.IllegalArgumentException @AdventOfCodePuzzle( name = "Two-Factor Authentication", url = "https://adventofcode.com/2016/day/8", date = Date(day = 8, year = 2016) ) class Day8(private val input: List<String>) : Puzzle { override fun partOne(): Int = with(Display(50, 6)) { input.map { line -> Instruction.from(line) } .forEach { when (it) { is Instruction.RectInstruction -> rect(it.x, it.y) is Instruction.ColumnInstruction -> rotateColumn(it.x, it.amount) is Instruction.RowInstruction -> rotateRow(it.y, it.amount) } } lit() } override fun partTwo() = "CFLELOYFCS" class Display(private val xSize: Int, private val ySize: Int) { private val display: Array<BooleanArray> = Array(ySize) { BooleanArray(xSize) } fun rect(x: Int, y: Int) { (0..<x).forEach { column -> (0..<y).forEach { row -> display[row][column] = true } } } fun show() { (0..<ySize).forEach { row -> display[row].joinToString("") { lit -> if (lit) "#" else "." }.also { println(it) } } println() } fun rotateColumn(x: Int, amount: Int) { (0..<ySize).map { y -> display[y][x] } .forEachIndexed { y, lit -> display[(y + amount) % ySize][x] = lit } } fun rotateRow(y: Int, amount: Int) { display[y].toList() .forEachIndexed { x, lit -> display[y][(x + amount) % xSize] = lit } } fun lit() = display.sumOf { row -> row.count { it } } } sealed class Instruction { data class RectInstruction(val x: Int, val y: Int) : Instruction() data class ColumnInstruction(val x: Int, val amount: Int) : Instruction() data class RowInstruction(val y: Int, val amount: Int) : Instruction() companion object { private val patternRect = Regex("""rect (\d+)x(\d+)""") private val patternColumn = Regex("""rotate column x=(\d+) by (\d+)""") private val patternRow = Regex("""rotate row y=(\d+) by (\d+)""") fun from(line: String): Instruction { patternRect.find(line)?.groupValues?.drop(1)?.let { RectInstruction(it[0].toInt(), it[1].toInt()) }?.run { return this } patternColumn.find(line)?.groupValues?.drop(1)?.let { ColumnInstruction(it[0].toInt(), it[1].toInt()) }?.run { return this } patternRow.find(line)?.groupValues?.drop(1)?.let { RowInstruction(it[0].toInt(), it[1].toInt()) }?.run { return this } throw IllegalArgumentException("Valid instruction not found: $line") } } } }
3
Kotlin
0
0
b2a836bd3f1c5eaec32b89a6ab5fcccc91b665dc
2,947
advent-of-code-2016
Creative Commons Zero v1.0 Universal
src/main/kotlin/com/ginsberg/advent2020/Day13.kt
tginsberg
315,060,137
false
null
/* * Copyright (c) 2020 by <NAME> */ /** * Advent of Code 2020, Day 13 - Shuttle Search * Problem Description: http://adventofcode.com/2020/day/13 * Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2020/day13/ */ package com.ginsberg.advent2020 class Day13(input: List<String>) { private val startTime: Int = input.first().toInt() private val busses: List<Int> = input .last() .split(",") .mapNotNull { s -> if (s == "x") null else s.toInt() } private val indexedBusses: List<IndexedBus> = input .last() .split(",") .mapIndexedNotNull { index, s -> if (s == "x") null else IndexedBus(index, s.toLong()) } fun solvePart1(): Int = generateSequence(startTime) { it + 1 } .mapNotNull { time -> busses .firstOrNull { bus -> time % bus == 0 } ?.let { bus -> Pair(time, bus) } } .first() .run { (first - startTime) * second } fun solvePart2(): Long { var stepSize = indexedBusses.first().bus var time = 0L indexedBusses.drop(1).forEach { (offset, bus) -> while ((time + offset) % bus != 0L) { time += stepSize } stepSize *= bus // New Ratio! } return time } data class IndexedBus(val index: Int, val bus: Long) }
0
Kotlin
2
38
75766e961f3c18c5e392b4c32bc9a935c3e6862b
1,425
advent-2020-kotlin
Apache License 2.0
src/main/java/com/ncorti/aoc2021/Exercise17.kt
cortinico
433,486,684
false
{"Kotlin": 36975}
package com.ncorti.aoc2021 import kotlin.math.abs import kotlin.math.max object Exercise17 { private fun getInput() = getInputAsTest("17") { removePrefix("target area: x=").split(", y=").flatMap { it.split("..").map(String::toInt) } } private val steps = listOf(0 to 1, 1 to 1, 1 to 0) private fun simulate(startx: Int, starty: Int, area: List<Int>): Pair<Boolean, Int> { var vx = startx var vy = starty var x = 0 var y = 0 var maxy = Int.MIN_VALUE while (true) { x += vx y += vy vy-- vx += when { vx > 0 -> -1 vx < 0 -> 1 else -> 0 } maxy = max(maxy, y) if (x in area[0]..area[1] && y in area[2]..area[3]) { return true to maxy } else if (y < area[2]) { return false to Int.MIN_VALUE } } } private fun discoverLandingPoints( input: List<Int>, seen: MutableSet<Pair<Int, Int>> = mutableSetOf() ): Pair<Int, Int> { val queue = mutableListOf(0 to 0) var maxy = Int.MIN_VALUE var foundFirstHit = false var count = 0 while (queue.isNotEmpty()) { val (x, y) = queue.removeFirst().apply { seen.add(this) } val (hit, height) = simulate(x, y, input) if (hit) { count++ maxy = max(maxy, height) foundFirstHit = true for (k in 0..abs(input[0] - input[1])) { for (l in 0..abs(input[0] - input[1])) { (x + k to y + l).apply { queue.addIfNotSeen(this, seen) } } } } if (!foundFirstHit) { steps.forEach { (incx, incy) -> (x + incx to y + incy).apply { queue.addIfNotSeen(this, seen) } } } } return maxy to count } private fun MutableList<Pair<Int, Int>>.addIfNotSeen( pair: Pair<Int, Int>, seen: MutableSet<Pair<Int, Int>> ) { if (pair !in this && pair !in seen) { this.add(pair) } } fun part1() = discoverLandingPoints(getInput()).first fun part2(): Int { val input = getInput() val seen = mutableSetOf<Pair<Int, Int>>() var count = 0 for (i in 0..input[1]) { for (j in 0 downTo input[2]) { simulate(i, j, input).let { (hit, _) -> if (hit) { count++ seen.add(i to j) } } } } return count + discoverLandingPoints(input, seen).second } } fun main() { println(Exercise17.part1()) println(Exercise17.part2()) }
0
Kotlin
0
4
af3df72d31b74857201c85f923a96f563c450996
2,972
adventofcode-2021
MIT License
src/Day10.kt
calindumitru
574,154,951
false
{"Kotlin": 20625}
import java.util.* fun main() { val part1 = Implementation("Find the signal strength during the 20th, 60th, 100th, 140th, 180th, and 220th cycles. What is the sum of these six signal strengths?", 13140) { lines -> val instructions = mapInstructions(lines) val process = Process(instructions) process.processInstructions() return@Implementation process.getSnapshotsSum() } val part2 = Implementation("Render the image given by your program. What eight capital letters appear on your CRT?", "NO ANSWER") { lines -> val instructions = mapInstructions(lines) val process = Process(instructions) process.processMonitor() process.draw() return@Implementation "NO ANSWER" } OhHappyDay(10, part1, part2).checkResults() } data class Process(val instructions: List<Op>) { var x = 1 val snapshots = mutableListOf<Pair<Int,Int>>() val monitor = mutableListOf<CharArray>() private fun newLine() = "........................................".toCharArray() fun processInstructions() { val q = LinkedList(instructions) for (i in 1 .. 220) { if (i == 20 || (i+20) % 40 == 0) { snapshots.add (i to x) } val instruction = q.first() instruction.entropy() if (instruction.cycle == 0) { x = instruction.apply(x) q.removeFirst() } } } fun processMonitor() { val q = LinkedList(instructions) var currentLine = newLine() for (i in 0 until 240) { val pixelPosition = i % 40 if (pixelPosition == 0) { currentLine = newLine() monitor.add(currentLine) } val instruction = q.first() instruction.entropy() if (pixelPosition in (x-1)..(x+1)) { currentLine[pixelPosition] = '#' } if (instruction.cycle == 0) { x = instruction.apply(x) q.removeFirst() } } } fun draw() { monitor.forEach{ println(String(it)) } } fun getSnapshotsSum(): Int { //println(snapshots) return snapshots.sumOf { it.first * it.second } } } fun mapInstructions(lines: List<String>): List<Op> { return lines.map { when { it == "noop" -> Op(Operation.NOOP, 0) it.startsWith("addx") -> Op(Operation.ADD, it.substringAfter(" ").toInt(), 2) else -> throw IllegalArgumentException() } } } data class Op(val op: Operation, val value : Int = 0, var cycle: Int = 1) { fun entropy() { cycle-- } fun apply(x: Int): Int { return when(op) { Operation.NOOP -> x Operation.ADD -> x + value } } } enum class Operation { ADD, NOOP }
0
Kotlin
0
0
d3cd7ff5badd1dca2fe4db293da33856832e7e83
2,964
advent-of-code-2022
Apache License 2.0
kotlin/src/katas/kotlin/skiena/graphs/Graph.kt
dkandalov
2,517,870
false
{"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221}
package katas.kotlin.skiena.graphs import katas.kotlin.skiena.graphs.UnweightedGraphs.meshGraph import katas.kotlin.skiena.graphs.UnweightedGraphs.diamondGraph import nonstdlib.join import datsok.shouldEqual import org.junit.Test data class Edge<T>(val from: T, val to: T, val weight: Int? = null) { override fun toString(): String { val weightString = if (weight != null) "/$weight" else "" return "$from-$to$weightString" } companion object { fun <T> read(token: String, parse: (String) -> T): Edge<T>? { val split = token.split('-', '/') val weight = if (split.size == 3) split[2].toInt() else null val to = if (split.size >= 2) parse(split[1]) else return null val from = parse(split[0]) return Edge(from, to, weight) } } } data class Graph<T>(val edgesByVertex: MutableMap<T, LinkedHashSet<Edge<T>>> = HashMap()) { val vertices: Set<T> get() = edgesByVertex.keys val edges: List<Edge<T>> get() = edgesByVertex.values.flatten() fun addEdge(fromVertex: T, toVertex: T): Graph<T> = addEdge(Edge(fromVertex, toVertex)) fun addEdge(edge: Edge<T>): Graph<T> { edgesByVertex.getOrPut(edge.from, { LinkedHashSet() }).add(edge) edgesByVertex.getOrPut(edge.to, { LinkedHashSet() }).add(Edge(edge.to, edge.from, edge.weight)) return this } fun addVertex(vertex: T) { edgesByVertex.getOrPut(vertex, { LinkedHashSet() }) } override fun toString(): String { val processedFrom = HashSet<T>() val processedTo = HashSet<T>() return edgesByVertex.entries.flatMap { (vertex, edges) -> if (edges.isEmpty()) listOf("$vertex") else edges.filterNot { (from, to) -> processedFrom.contains(to) && processedTo.contains(from) } .map { edge -> processedFrom.add(edge.from) processedTo.add(edge.to) edge.toString() } }.join(",") } companion object { fun read(s: String): Graph<String> = read(s) { it } fun readInts(s: String): Graph<Int> = read(s) { it.toInt() } fun <T> read(s: String, parse: (String) -> T): Graph<T> { val graph = Graph<T>() s.split(",").forEach { token -> val edge = Edge.read(token, parse) if (edge != null) graph.addEdge(edge) else graph.addVertex(parse(token)) } return graph } } } class GraphTest { @Test fun `create undirected graph from string`() { Graph.readInts("1-2").toString() shouldEqual "1-2" Graph.readInts("2-1").toString() shouldEqual "1-2" Graph.readInts("1-2,2-3").toString() shouldEqual "1-2,2-3" Graph.readInts("1-2,3").toString() shouldEqual "1-2,3" diamondGraph.toString() shouldEqual "1-2,1-4,2-3,3-4" meshGraph.toString() shouldEqual "1-2,1-3,1-4,2-3,2-4,3-4" } @Test fun `create undirected weighted graph from string`() { Graph.readInts("1-2/10").toString() shouldEqual "1-2/10" Graph.readInts("2-1/10").toString() shouldEqual "1-2/10" Graph.readInts("1-2/10,2-3/20").toString() shouldEqual "1-2/10,2-3/20" Graph.readInts("1-2/10,3").toString() shouldEqual "1-2/10,3" } } object UnweightedGraphs { // 1 -- 2 -- 3 val linearGraph = Graph.readInts("1-2,2-3") // 1 -- 2 3 -- 4 val disconnectedGraph = Graph.readInts("1-2,3-4") // 3 // / \ // 2 4 // \ / // 1 val diamondGraph = Graph.readInts("1-2,1-4,2-3,3-4") // 3 // /|\ // 2-+-4 // \|/ // 1 val meshGraph = Graph.readInts("1-2,1-3,1-4,2-3,2-4,3-4") } object WeightedGraphs { // 1 -- 2 -- 3 val linearGraph = Graph.readInts("1-2/10,2-3/20") // 2 -- 3 // \ / // 1 val triangleGraph = Graph.readInts("1-2/20,1-3/20,2-3/10") // 3 // / \ // 2 4 // \ / // 1 val diamondGraph = Graph.readInts("1-2/10,1-4/20,2-3/30,3-4/40") // From Skiena Figure 6.3 val exampleGraph = Graph.read("A-B/5,A-C/7,A-D/12,B-C/9,C-D/4,B-E/7,C-E/4,C-F/3,E-F/2,E-G/5,F-G/2") }
7
Roff
3
5
0f169804fae2984b1a78fc25da2d7157a8c7a7be
4,241
katas
The Unlicense
src/main/kotlin/days/Day3Solution.kt
yigitozgumus
434,108,608
false
{"Kotlin": 17835}
package days import BaseSolution import java.io.File import kotlin.math.ceil const val zeroCode = '0'.code class Day3Solution(inputList: List<String>) : BaseSolution(inputList) { val formattedInput by lazy { inputList.map { it.toCharArray().map { it.code - zeroCode } } } private fun List<Boolean>.mapToRate(): Int = Integer.parseInt( this.map { it.compareTo(false) }.joinToString(""), 2 ) private fun List<Int>.mapToRating(): Int = Integer.parseInt( this.joinToString(""), 2 ) override fun part1() { val totalCount = defineCounter() formattedInput.forEach { it.forEachIndexed { index, i -> totalCount[index] += i } } val gammaRate = totalCount.map { it >= inputList.size / 2 }.mapToRate() val epsilonRate = totalCount.map { it < inputList.size / 2 }.mapToRate() println(gammaRate * epsilonRate) } override fun part2() { var oxygenRatingList = formattedInput var co2RatingList = formattedInput var index = 0 while (oxygenRatingList.size > 1) { val totalCount = oxygenRatingList.map { it[index] }.sum() val converted = (totalCount >= ceil(oxygenRatingList.size.toDouble().div(2))).toInt() oxygenRatingList = oxygenRatingList.filter { bitList -> bitList[index] == converted } index = index.inc() } index = 0 while (co2RatingList.size > 1) { val totalCount = co2RatingList.map { it[index] }.sum() val converted = (totalCount >= ceil(co2RatingList.size.toDouble().div(2))).toInt() co2RatingList = co2RatingList.filter { bitList -> bitList[index] != converted } index = index.inc() } println(oxygenRatingList.first().mapToRating() * co2RatingList.first().mapToRating()) } fun defineCounter() = MutableList(inputList.first().length) { 0 } }
0
Kotlin
0
0
c0f6fc83fd4dac8f24dbd0d581563daf88fe166a
1,916
AdventOfCode2021
MIT License
src/questions/MinLengthAfterDeletingSimilarEnds.kt
realpacific
234,499,820
false
null
package questions import _utils.UseCommentAsDocumentation import utils.shouldBe /** * Given a string s consisting only of characters 'a', 'b', and 'c'. * You are asked to apply the following algorithm on the string any number of times: * * * Pick a non-empty prefix from the string s where all the characters in the prefix are equal. * * Pick a non-empty suffix from the string s where all the characters in this suffix are equal. * * The prefix and the suffix should not intersect at any index. * * The characters from the prefix and suffix must be the same. * * Delete both the prefix and the suffix. * Return the minimum length of s after performing the above operation any number of times (possibly zero times). * [Source](https://leetcode.com/problems/min-length-after-deleting-similar-ends-kt/) */ @UseCommentAsDocumentation private fun minimumLength(s: String): Int { if (s.length <= 1) return 1 var frontPointer = 0 var endPointer = s.lastIndex val totalLength = s.length if (s[frontPointer] != s[endPointer]) return totalLength var result = totalLength while (frontPointer < endPointer) { val frontChar = s[frontPointer] val endChar = s[endPointer] var nextFrontIndex = frontPointer + 1 var nextEndIndex = endPointer - 1 var countsOfCharRemovedFromFront = 0 var countsOfCharRemovedFromBack = 0 if (frontChar == endChar) { // prefix and suffix can be removed // delete prefix and suffix at current index countsOfCharRemovedFromFront++ countsOfCharRemovedFromBack++ // eg: 'bcb' the [nextEndIndex] and [nextFrontIndex] is same so this is the final answer if (nextFrontIndex == nextEndIndex) { result -= (countsOfCharRemovedFromFront + countsOfCharRemovedFromBack) return result } // remove all prefix that matches [frontChar] while (nextFrontIndex < endPointer && frontChar == s[nextFrontIndex]) { nextFrontIndex++ countsOfCharRemovedFromFront++ // count how many prefixes have been removed } // remove all suffix that matches [endChar] while (nextEndIndex > nextFrontIndex && endChar == s[nextEndIndex]) { nextEndIndex-- countsOfCharRemovedFromBack++ // count how many suffixes have been removed } if (nextFrontIndex == nextEndIndex) { return result } else { result -= (countsOfCharRemovedFromFront + countsOfCharRemovedFromBack) } frontPointer = nextFrontIndex endPointer = nextEndIndex } else { // nothing can be further removed break } } return result } fun main() { minimumLength("bbbbbbbbbbbbbbbbbbbbbbbbbbbabbbbbbbbbbbbbbbccbcbcbccbbabbb") shouldBe 1 // - Take prefix = "aa" and suffix = "a" and remove them, s = "bccabb". // - Take prefix = "b" and suffix = "bb" and remove them, s = "cca". minimumLength("aabccabba") shouldBe 3 minimumLength("cabaabac") shouldBe 0 minimumLength("ca") shouldBe 2 }
4
Kotlin
5
93
22eef528ef1bea9b9831178b64ff2f5b1f61a51f
3,230
algorithms
MIT License
src/Day01.kt
MwBoesgaard
572,857,083
false
{"Kotlin": 40623}
fun main() { fun part1(input: List<String>): Int { var totalKcal = 0 var highestKcal = 0 for (kcal in input) { if (kcal == "") { if (totalKcal > highestKcal) { highestKcal = totalKcal } totalKcal = 0 } else { val intKcal = kcal.toInt() totalKcal += intKcal } } return highestKcal } fun part2(inputString: String): Int { return inputString .split(Regex("\\r?\\n\\r?\\n")) .map { it .split(Regex("\\r?\\n")) .sumOf { kcal -> kcal.toInt() } } .sortedDescending() .take(3) .sum() } printSolutionFromInputLines("Day01", ::part1) printSolutionFromInputRaw("Day01", ::part2) }
0
Kotlin
0
0
3bfa51af6e5e2095600bdea74b4b7eba68dc5f83
910
advent_of_code_2022
Apache License 2.0
src/main/kotlin/aoc2022/Day14.kt
lukellmann
574,273,843
false
{"Kotlin": 175166}
package aoc2022 import AoCDay // https://adventofcode.com/2022/day/14 object Day14 : AoCDay<Int>( title = "Regolith Reservoir", part1ExampleAnswer = 24, part1Answer = 817, part2ExampleAnswer = 93, part2Answer = 23416, ) { private data class Point(val x: Int, val y: Int) private val SAND_SOURCE = Point(x = 500, y = 0) private fun parseRockPaths(input: String) = input .lineSequence() .map { rockPath -> rockPath.split(" -> ").map { point -> val (x, y) = point.split(',', limit = 2) Point(x.toInt(), y.toInt()) } } private fun MutableSet<Point>.fillWithRocks(rockPaths: Sequence<List<Point>>) { for (rockPath in rockPaths) { for ((from, to) in rockPath.zipWithNext()) { val xs = if (from.x < to.x) from.x..to.x else to.x..from.x val ys = if (from.y < to.y) from.y..to.y else to.y..from.y for (x in xs) { for (y in ys) { add(Point(x, y)) } } } } } override fun part1(input: String): Int { val points = HashSet<Point>() points.fillWithRocks(parseRockPaths(input)) val rockCount = points.size val yLowestRock = points.maxOf { it.y } var sandUnit = SAND_SOURCE while (sandUnit.y < yLowestRock) { // once sandUnit.y == yLowestRock it will fall forever val x = sandUnit.x val yDown = sandUnit.y + 1 var p: Point sandUnit = when { Point(x, yDown).also { p = it } !in points -> p Point(x - 1, yDown).also { p = it } !in points -> p Point(x + 1, yDown).also { p = it } !in points -> p else -> { points += sandUnit // sand unit comes to rest SAND_SOURCE // create next sand unit } } } return points.size - rockCount } override fun part2(input: String): Int { val points = HashSet<Point>() points.fillWithRocks(parseRockPaths(input)) val rockCount = points.size val yFloor = points.maxOf { it.y } + 2 var sandUnit = SAND_SOURCE while (true) { val x = sandUnit.x val yDown = sandUnit.y + 1 var p: Point sandUnit = when { yDown == yFloor -> { points += sandUnit // sand unit comes to rest on the floor SAND_SOURCE // create next sand unit } Point(x, yDown).also { p = it } !in points -> p Point(x - 1, yDown).also { p = it } !in points -> p Point(x + 1, yDown).also { p = it } !in points -> p else -> { points += sandUnit // sand unit comes to rest if (sandUnit == SAND_SOURCE) break // source is blocked SAND_SOURCE // create next sand unit } } } return points.size - rockCount } }
0
Kotlin
0
1
344c3d97896575393022c17e216afe86685a9344
3,167
advent-of-code-kotlin
MIT License
y2016/src/main/kotlin/adventofcode/y2016/Day04.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2016 import adventofcode.io.AdventSolution object Day04 : AdventSolution(2016, 4, "Security Through Obscurity") { override fun solvePartOne(input: String) = parseRooms(input) .sumOf { it.id } .toString() override fun solvePartTwo(input: String) = parseRooms(input) .map { it.decrypt() to it.id } .first { "north" in it.first } .second .toString() private fun parseRooms(input: String): Sequence<Room> { return input.lineSequence() .map { Room( name = it.substringBeforeLast("-"), id = it.substringAfterLast("-").substringBefore("[").toInt(), checksum = it.substringAfterLast("[").dropLast(1) ) } .filter { it.isValid() } } data class Room(val name: String, val id: Int, val checksum: String) { fun isValid(): Boolean = name.groupingBy { it } .eachCount() .toSortedMap() .asSequence() .sortedByDescending { it.value } .map { it.key } .filterNot { it == '-' } .take(5) .joinToString("") == checksum fun decrypt(): String = name.map { when (it) { '-' -> '-' in 'a'..'z' -> ((((it - 'a') + id) % 26) + 'a'.code).toChar() else -> '?' } } .joinToString("") } }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
1,600
advent-of-code
MIT License
src/main/kotlin/tr/emreone/adventofcode/days/Day05.kt
EmRe-One
726,902,443
false
{"Kotlin": 95869, "Python": 18319}
package tr.emreone.adventofcode.days import tr.emreone.kotlin_utils.Logger.logger import tr.emreone.kotlin_utils.automation.Day class Day05 : Day(5, 2023, "If You Give A Seed A Fertilizer") { class Process { private var steps = arrayOf("seed", "soil", "fertilizer", "water", "light", "temperature", "humidity", "location") private var currentStepNumber = 0 val currentStep: String get() = this.steps[this.currentStepNumber] fun next(): String? { if (this.currentStepNumber == this.steps.size - 1) { return null } return this.steps[this.currentStepNumber + 1] } fun stepForward() { if (this.next() != null) { this.currentStepNumber++ } } } class Mapping(val srcStart: Long, private val destStart: Long, private val length: Long) { private val offset: Long = this.destStart - this.srcStart fun inRange(x: Long): Boolean { return x in this.srcStart until (this.srcStart + length) } fun mapNumber(x: Long): Long { if (this.inRange(x)) return x + this.offset; return x } } override fun part1(): Long { val blocks = inputAsString.split("(\r?\n){2}".toRegex()) val seeds = blocks[0].split(":")[1].trim().split("\\s".toRegex()).map { it.toLong() } val maps = blocks.drop(1).associate { m -> val lines = m.split("(\r?\n){1}".toRegex()) val title = lines[0].split("\\s".toRegex())[0] val list = lines.drop(1) .map { val (dest, src, length) = it.split("\\s".toRegex()) Mapping(src.toLong(), dest.toLong(), length.toLong()) } .sortedBy { it.srcStart } title to list } return seeds .minOf { seed -> val process = Process() var currentNumber = seed logger.debug { "Seed: $currentNumber " } do { val title = "${process.currentStep}-to-${process.next()}" logger.debug { "-> " + process.next() + ": " } currentNumber = maps[title] ?.firstOrNull() { it.inRange(currentNumber) } ?.mapNumber(currentNumber) ?: currentNumber logger.debug { "$currentNumber " } process.stepForward() } while (process.next() != null) println() currentNumber } } override fun part2(): Long { val blocks = inputAsString.split("(\r?\n){2}".toRegex()) val seedRanges = blocks[0] .split(":")[1] .trim() .split("\\s".toRegex()) .map { it.toLong() } .windowed(2, 2) val maps = blocks.drop(1).associate { m -> val lines = m.split("(\r?\n){1}".toRegex()) val title = lines[0].split("\\s".toRegex())[0] val list = lines.drop(1) .map { val (dest, src, length) = it.split("\\s".toRegex()) Mapping(src.toLong(), dest.toLong(), length.toLong()) } .sortedBy { it.srcStart } title to list } var min = Long.MAX_VALUE seedRanges.forEach { for (seed in it[0] until it[0] + it[1]) { val process = Process() var currentNumber = seed do { val title = "${process.currentStep}-to-${process.next()}" currentNumber = maps[title] ?.firstOrNull() { it.inRange(currentNumber) } ?.mapNumber(currentNumber) ?: currentNumber process.stepForward() } while (process.next() != null) min = minOf(min, currentNumber) } } return min } }
0
Kotlin
0
0
c75d17635baffea50b6401dc653cc24f5c594a2b
4,342
advent-of-code-2023
Apache License 2.0
src/day-4.kt
drademacher
160,820,401
false
null
import java.io.File import java.time.LocalDateTime fun main(args: Array<String>) { println("part 1: " + partOne()) println("part 2: " + partTwo()) } private fun partOne(): Int { val rawFile = File("res/day-4.txt").readText() val datetimeAndActions = rawFile .split("\n") .filter { it != "" } .sorted() .map(::parseLine) val guardsSleepingTimes = hashMapOf<Int, IntArray>() var currentGuard = -1 var fallAsleepTime = LocalDateTime.MIN for ((dateTime, action) in datetimeAndActions) { if (action[0] == 'G') { currentGuard = action.filter { it.isDigit() }.toInt() fallAsleepTime = dateTime } if (action == "falls asleep") { fallAsleepTime = dateTime } else { val sleepingMinutes = guardsSleepingTimes.getOrDefault(currentGuard, IntArray(60)) (fallAsleepTime.minute until dateTime.minute).forEach { sleepingMinutes[it] += 1 } guardsSleepingTimes[currentGuard] = sleepingMinutes } } val sleepyGuard = guardsSleepingTimes.maxBy { it.value.sum() }!! val guardsMinuteWithMostSleep = sleepyGuard.value.withIndex().maxBy { it.value }!!.index return sleepyGuard.key * guardsMinuteWithMostSleep } private fun partTwo(): Int { val rawFile = File("res/day-4.txt").readText() val datetimeAndActions = rawFile .split("\n") .filter { it != "" } .sorted() .map(::parseLine) val guardsSleepingTimes = hashMapOf<Int, IntArray>() var currentGuard = -1 var fallAsleepTime = LocalDateTime.MIN for ((dateTime, action) in datetimeAndActions) { if (action[0] == 'G') { currentGuard = action.filter { it.isDigit() }.toInt() fallAsleepTime = dateTime } if (action == "falls asleep") { fallAsleepTime = dateTime } else { val sleepingMinutes = guardsSleepingTimes.getOrDefault(currentGuard, IntArray(60)) (fallAsleepTime.minute until dateTime.minute).forEach { sleepingMinutes[it] += 1 } guardsSleepingTimes[currentGuard] = sleepingMinutes } } val guardWithMostConsistentSleep = guardsSleepingTimes.maxBy { it.value.max()!! }!! val mostSleeptMinute = guardWithMostConsistentSleep.value.withIndex().maxBy { it.value }!!.index return guardWithMostConsistentSleep.key * mostSleeptMinute } private fun parseLine(line: String): Pair<LocalDateTime, String> { val splitLine = line.drop(1).split("]") val datetime = parseDateTime(splitLine) return Pair(datetime, splitLine[1].drop(1)) } private fun parseDateTime(splitLine: List<String>): LocalDateTime { val datetimeString = splitLine[0] .replace(Regex("[^0-9]"), " ") .split(" ") .map { it.toInt() } val datetime = LocalDateTime.of(datetimeString[0], datetimeString[1], datetimeString[2], datetimeString[3], datetimeString[4]) return datetime!! }
0
Kotlin
0
0
a7f04450406a08a5d9320271148e0ae226f34ac3
3,041
advent-of-code-2018
MIT License
src/Day03.kt
kerchen
573,125,453
false
{"Kotlin": 137233}
import java.lang.Exception fun main() { fun findCommonItem(sack: String): Char { val midPoint = sack.length/2 for (itemIndex in IntRange(0, midPoint-1)) { var item = sack[itemIndex] if (item in sack.slice(IntRange(midPoint, sack.length - 1))) { return item } } throw Exception("No common item found") } fun findCommonItem(sack1: String, sack2: String, sack3: String): Char { for (item in sack1) { if (item in sack2 && item in sack3) return item } throw Exception("No common item found") } fun getItemPriority(item: Char): Int { if (item in 'a'..'z') return item - 'a' + 1 return item - 'A' + 27 } fun part1(input: List<String>): Int { var total = 0 for (sack in input) { val commonItem = findCommonItem(sack) val priority = getItemPriority(commonItem) total += priority } return total } fun part2(input: List<String>): Int { var total = 0 var it = input.iterator() while (it.hasNext()) { val sack1 = it.next() val sack2 = it.next() val sack3 = it.next() val commonItem = findCommonItem(sack1, sack2, sack3) total += getItemPriority(commonItem) } return total } 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
dc15640ff29ec5f9dceb4046adaf860af892c1a9
1,645
AdventOfCode2022
Apache License 2.0
src/main/kotlin/org/hydev/lcci/lcci_03.kt
VergeDX
334,298,924
false
null
import java.util.* import kotlin.collections.ArrayList // https://leetcode-cn.com/problems/three-in-one-lcci/ class TripleInOne(val stackSize: Int) { val stackOne = Stack<Int>() val stackTwo = Stack<Int>() val stackThree = Stack<Int>() private fun whichStack(stackNum: Int): Stack<Int> { return when (stackNum) { 0 -> stackOne 1 -> stackTwo 2 -> stackThree else -> throw AssertionError() } } private fun Stack<Int>.canPush(): Boolean { if (this.size == this@TripleInOne.stackSize) return false return true } fun push(stackNum: Int, value: Int) { val stack = whichStack(stackNum) if (stack.canPush()) stack.push(value) } fun pop(stackNum: Int): Int { val stack = whichStack(stackNum) return stack.runCatching { pop() }.getOrDefault(-1) } fun peek(stackNum: Int): Int { val stack = whichStack(stackNum) return stack.runCatching { peek() }.getOrDefault(-1) } fun isEmpty(stackNum: Int): Boolean { return whichStack(stackNum).isEmpty() } } // https://leetcode-cn.com/problems/min-stack-lcci/ class MinStack() { val stack = Stack<Int>() fun push(x: Int) { stack.push(x) } fun pop() { stack.pop() } fun top(): Int { return stack.peek() } fun getMin(): Int { return Collections.min(stack) } } // https://leetcode-cn.com/problems/stack-of-plates-lcci/ class StackOfPlates(val cap: Int) { val stackList = ArrayList<Stack<Int>>() fun push(`val`: Int) { if (cap == 0) return // cap != 0 here. if (stackList.isEmpty() || stackList.last().size == cap) stackList += Stack<Int>().apply { push(`val`) } else stackList.last().push(`val`) } fun pop(): Int { // last() will raise exception if list empty. if (stackList.isEmpty()) return -1 // Last stack size == 1, pop & remove it. if (stackList.last().size == 1) { val lastStack = stackList.last() val result = lastStack.pop() stackList.remove(lastStack) return result } // stackList.last() exists, and it size != 1. return stackList.last().pop() } fun popAt(index: Int): Int { // index is legal. if (stackList.size > index) { val stack = stackList[index] val result = stack.pop() if (stack.isEmpty()) stackList.remove(stack) return result } return -1 } } // https://leetcode-cn.com/problems/implement-queue-using-stacks-lcci/ class MyQueue() { val queue = ArrayList<Int>() fun push(x: Int) { queue += x } fun pop(): Int { return queue.removeAt(0) } fun peek(): Int { return queue[0] } fun empty(): Boolean { return queue.isEmpty() } } // https://leetcode-cn.com/problems/sort-of-stacks-lcci/ class SortedStack() { val innerStack = Stack<Int>() fun push(`val`: Int) { innerStack.push(`val`) // Only push can mess up the order of stack. innerStack.sortByDescending { it } } fun pop() { // Ignore EmptyStackException. innerStack.runCatching { pop() } } fun peek(): Int { return innerStack.runCatching { peek() } // Return -1 if stack empty. .getOrDefault(-1) } fun isEmpty(): Boolean { return innerStack.isEmpty() } } // https://leetcode-cn.com/problems/animal-shelter-lcci/ class AnimalShelf() { // 0 -> Cat, 1 -> Dog. val innerCatList = LinkedList<IntArray>() val innerDogList = LinkedList<IntArray>() val nope = intArrayOf(-1, -1) fun enqueue(animal: IntArray) { when (animal[1]) { 0 -> innerCatList.add(animal) 1 -> innerDogList.add(animal) } } fun dequeueAny(): IntArray { val sumList = innerCatList + innerDogList val result = sumList.sortedBy { it[0] }.elementAtOrElse(0) { nope } innerDogList.runCatching { remove(result) } innerCatList.runCatching { remove(result) } return result } fun dequeueDog(): IntArray { val result = innerDogList.sortedBy { it[0] }.elementAtOrElse(0) { nope } innerDogList.runCatching { remove(result) } return result } fun dequeueCat(): IntArray { val result = innerCatList.sortedBy { it[0] }.elementAtOrElse(0) { nope } innerCatList.runCatching { remove(result) } return result } } fun main() { val tio = TripleInOne(1) tio.apply { push(0, 1) push(0, 2) pop(0) pop(0) pop(0) isEmpty(0) } // Stack<Int>().last() }
0
Kotlin
0
0
9a26ac2e24b0a0bdf4ec5c491523fe9721c6c406
4,863
LeetCode_Practice
MIT License
src/Day02.kt
ChristianNavolskyi
573,154,881
false
{"Kotlin": 29804}
import kotlin.time.ExperimentalTime import kotlin.time.measureTime @ExperimentalTime fun main() { val pointMap: Map<String, Int> = mapOf( Pair("A X", 4), Pair("A Y", 8), Pair("A Z", 3), Pair("B X", 1), Pair("B Y", 5), Pair("B Z", 9), Pair("C X", 7), Pair("C Y", 2), Pair("C Z", 6), ) val strategyMap: Map<String, Int> = mapOf( Pair("A X", 3), Pair("A Y", 4), Pair("A Z", 8), Pair("B X", 1), Pair("B Y", 5), Pair("B Z", 9), Pair("C X", 2), Pair("C Y", 6), Pair("C Z", 7), ) fun part1(input: List<String>): Int = input.mapNotNull { pointMap[it] }.sum() fun part2(input: List<String>): Int = input.mapNotNull { strategyMap[it] }.sum() // test if implementation meets criteria from the description, like: val testInput = readLines("Day02_test") check(part1(testInput) == 15) val input = readLines("Day02") println(part1(input)) println(part2(input)) val times = 1 val firstTime = measureTime { repeat(times) { part1(input) } }.div(times) val secondTime = measureTime { repeat(times) { part2(input) } }.div(times) println("Times") println("First part took: $firstTime") println("Second part took: $secondTime") }
0
Kotlin
0
0
222e25771039bdc5b447bf90583214bf26ced417
1,333
advent-of-code-2022
Apache License 2.0
src/Day14.kt
ambrosil
572,667,754
false
{"Kotlin": 70967}
import Type.* enum class Type { NONE, SAND, WALL } fun main() { fun parse(input: List<String>): MutableMap<Point, Type> { val terrain = mutableMapOf<Point, Type>() val walls = input.map { it.split(" -> ") .map { it.split(",") } .map { (x, y) -> Point(x.toInt(), y.toInt()) } } walls.forEach { wall -> wall.reduce { p1, p2 -> val xRange = if (p1.x > p2.x) { p2.x..p1.x } else { p1.x..p2.x } val yRange = if (p1.y > p2.y) { p2.y..p1.y } else { p1.y..p2.y } for (x in xRange) { terrain[Point(x, p1.y)] = WALL } for (y in yRange) { terrain[Point(p1.x, y)] = WALL } p2 } } return terrain } fun findMaxY(terrain: MutableMap<Point, Type>): Int { return terrain.keys.maxOf { it.y } } fun addSand(terrain: MutableMap<Point, Type>): Boolean { val maxY = findMaxY(terrain) val sandPoint = Point(500, 0) while (true) { sandPoint += Point(0, 1) if (sandPoint.y > maxY) { return false } val type = terrain[sandPoint] ?: NONE when (type) { NONE -> continue SAND, WALL -> { val leftType = terrain[sandPoint + Point(-1, 0)] ?: NONE when (leftType) { NONE -> sandPoint += Point(-1, 0) WALL, SAND -> { val rightType = terrain[sandPoint + Point(+1, 0)] ?: NONE if (rightType == NONE) { sandPoint += Point(+1, 0) } else { terrain[sandPoint + Point(0, -1)] = SAND return true } } } } } } } fun addSand2(terrain: MutableMap<Point, Type>, maxY: Int): Boolean { val sandPoint = Point(500, 0) while (true) { sandPoint += Point(0, 1) if (sandPoint.y >= maxY+2) { terrain[sandPoint + Point(0, -1)] = SAND return true } val type = terrain[sandPoint] ?: NONE when (type) { NONE -> continue SAND, WALL -> { val leftType = terrain[sandPoint + Point(-1, 0)] ?: NONE when (leftType) { NONE -> sandPoint += Point(-1, 0) WALL, SAND -> { val rightType = terrain[sandPoint + Point(+1, 0)] ?: NONE if (rightType == NONE) { sandPoint += Point(+1, 0) } else { val restPoint = sandPoint + Point(0, -1) terrain[restPoint] = SAND if (restPoint.x == 500 && restPoint.y == 0) { return false } return true } } } } } } } fun part1(input: List<String>): Int { val terrain = parse(input) var counter = 0 while (addSand(terrain)) { counter++ } return counter } fun part2(input: List<String>): Int { val terrain = parse(input) val maxY = findMaxY(terrain) var counter = 0 while (addSand2(terrain, maxY)) { counter++ } return counter+1 } val input = readInput("inputs/Day14") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
ebaacfc65877bb5387ba6b43e748898c15b1b80a
4,130
aoc-2022
Apache License 2.0
src/Day03.kt
leeturner
572,659,397
false
{"Kotlin": 13839}
fun priority(c: Char) = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".indexOf(c) + 1 fun main() { fun part1(rucksacks: List<String>) = rucksacks .map { it.chunked(it.length / 2) } .map { it[0].toSet() intersect it[1].toSet() } .sumOf { priority(it.first()) } fun part2(rucksacks: List<String>) = rucksacks .chunked(3) .map { it[0].toSet() intersect it[1].toSet() intersect it[2].toSet() } .sumOf { priority(it.first()) } // 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
8da94b6a0de98c984b2302b2565e696257fbb464
771
advent-of-code-2022
Apache License 2.0
src/Day16.kt
max-zhilin
573,066,300
false
{"Kotlin": 114003}
import java.util.* val solutions = mutableMapOf<Int, Int>() data class Link(val valve: Valve, val dist: Int) data class Valve(val name: String, val rate: Int, var opened: Boolean = false, var lastRateA: Int = -1, var lastRateB: Int = -1) { lateinit var names: List<String> val links: MutableList<Link> = mutableListOf() var lastVisitedRate: Int = -1 companion object { fun parse(s: String): Valve { val scanner = Scanner(s) scanner.useDelimiter(", |[,; ]") //scanner.useDelimiter(":") val name = scanner.skip("Valve ").next() val rate = scanner.skip(" has flow rate=").nextInt() scanner.skip("; tunnels? leads? to valves?") val names = mutableListOf<String>() while (scanner.hasNext()) { names.add(scanner.next()) } val valve = Valve(name, rate) valve.names = names return valve } } } fun MutableList<Valve>.fillList() { forEach { v -> v.names.forEach { name -> v.links.add(Link(find { it.name == name }!!, 1)) } } } fun MutableList<Valve>.optimize() { do { val v = find { it.rate == 0 && it.name != "AA" } ?: return val leads = filter { it.links.map { it.valve }.contains(v) } leads.forEach { lead -> val link = lead.links.first { it.valve == v } lead.links.remove(link) val listCopy = v.links.filter { it.valve != lead }.toMutableList() for ((i, e) in listCopy.withIndex()) listCopy[i] = Link(e.valve, e.dist + link.dist) lead.links.addAll(listCopy) } remove(v) } while (true) } fun Valve.maxPressure(valves: MutableList<Valve>, time: Int, releasedRate: Int): Int { val additionalPressure: Int // time is out if (time <= 0) return 0 // last...Rate - prevent cycling if (releasedRate == lastVisitedRate) return 0 // println("$name $time $releasedRate") var foundSubPressure = 0 if (!opened) { val lastClosedRate = lastVisitedRate lastVisitedRate = releasedRate links.forEach { link -> foundSubPressure = maxOf(foundSubPressure, link.valve.maxPressure(valves, time - link.dist, releasedRate)) } lastVisitedRate = lastClosedRate if (name == "AA") return foundSubPressure opened = true additionalPressure = rate * (time - 1) // println("open") // no more nodes -> time * pressure if (valves.all { it.opened || it.name == "AA" }) { opened = false return additionalPressure } val lastOpenedRate = lastVisitedRate lastVisitedRate = releasedRate links.forEach { link -> foundSubPressure = maxOf(foundSubPressure, additionalPressure + link.valve.maxPressure(valves, time - 1 - link.dist, releasedRate + rate)) } lastVisitedRate = lastOpenedRate opened = false } else /* opened */ { val lastOpenedRate = lastVisitedRate lastVisitedRate = releasedRate links.forEach { link -> foundSubPressure = maxOf(foundSubPressure, link.valve.maxPressure(valves, time - link.dist, releasedRate)) } lastVisitedRate = lastOpenedRate } return foundSubPressure } fun MutableList<Valve>.maxPressure(linkA: Link, linkB: Link, time: Int, releasedRateA: Int, releasedRateB: Int, depth: Int, result: Int): Int { val a = linkA.valve // target valve val b = linkB.valve val spentTime = minOf(linkA.dist, linkB.dist) // time to target (1+) val timeLeft = time - spentTime val waitA = linkA.dist - spentTime // 0+ val waitB = linkB.dist - spentTime // println(" ".repeat(counter) + "${a.name} ${b.name} time $timeLeft rate $releasedRate ${this.filter { it.opened }.joinToString { it.name }}") // time is out if (timeLeft < 2) return 0 // it takes min 2 to open and release if (timeLeft < 14) { // if (solutions[result] == null) solutions[result] = 1 // else solutions[result] = solutions[result]!! + 1 if (result < 2000) return 0 } // last...Rate - prevent cycling // if (a.lastRateA == releasedRateA || b.lastRateB == releasedRateB) { // // TODO: remove //// println(" ".repeat(counter) + "ret lastRate ${if (a.lastRateA == releasedRate) "a" else ""} ${if (b.lastRateB == releasedRate) "b" else ""}") // return 0 // } var foundSubPressure = 0 val tempRateA = a.lastRateA val tempRateB = b.lastRateB if (waitA == 0) a.lastRateA = releasedRateA if (waitB == 0) b.lastRateB = releasedRateB if (waitA > 0) { if (!b.opened && b.name != "AA") { // closed & !AA so we open val openedPressure = b.rate * (timeLeft - 1) if (all { it.opened || it.name == "AA" || it == b }) { a.lastRateA = tempRateA b.lastRateB = tempRateB return openedPressure } b.opened = true b.lastRateB = releasedRateB + b.rate for (linkB in b.links) foundSubPressure = maxOf(foundSubPressure, openedPressure + maxPressure(Link(a, waitA - 1), linkB, timeLeft - 1, releasedRateA, releasedRateB + b.rate, depth + 1, openedPressure + result)) b.opened = false b.lastRateB = releasedRateB } val links = b.links.filter { it.valve.lastRateB < releasedRateB } if (links.isEmpty() && b.opened) foundSubPressure = maxOf(foundSubPressure, maxPressure(Link(a, waitA), Link(b, 1000), timeLeft, releasedRateA, releasedRateB, depth + 1, result)) else for (linkB in links) foundSubPressure = maxOf(foundSubPressure, maxPressure(Link(a, waitA), linkB, timeLeft, releasedRateA, releasedRateB, depth + 1, result)) } else if (waitB > 0) { if (!a.opened && a.name != "AA") { // closed && !AA so we open val openedPressure = a.rate * (timeLeft - 1) if (all { it.opened || it.name == "AA" || it == a }) { a.lastRateA = tempRateA b.lastRateB = tempRateB return openedPressure } a.opened = true a.lastRateA = releasedRateA + a.rate for (linkA in a.links) foundSubPressure = maxOf(foundSubPressure, openedPressure + maxPressure(linkA, Link(b, waitB - 1), timeLeft - 1, releasedRateA + a.rate, releasedRateB, depth + 1, openedPressure + result)) a.opened = false a.lastRateA = releasedRateA } val links = a.links.filter { it.valve.lastRateA < releasedRateA } if (links.isEmpty() && a.opened) foundSubPressure = maxOf(foundSubPressure, maxPressure(Link(a, 1000), Link(b, waitB), timeLeft, releasedRateA, releasedRateB, depth + 1, result)) else for (linkA in links) foundSubPressure = maxOf(foundSubPressure, maxPressure(linkA, Link(b, waitB), timeLeft, releasedRateA, releasedRateB, depth + 1, result)) } else // waitA & waitB = 0 if (a == b) { if (!a.opened && a.name != "AA") { // val openedPressure = a.rate * (timeLeft - 1) if (all { it.opened || it.name == "AA" || it == a }) { a.lastRateA = tempRateA b.lastRateB = tempRateB return openedPressure } a.opened = true // a open, b pass a.lastRateA = releasedRateA + a.rate val links = b.links.filter { it.valve.lastRateB < releasedRateB } if (links.isEmpty()) foundSubPressure = maxOf(foundSubPressure, openedPressure + maxPressure(Link(a, 0), Link(b, 1000), timeLeft - 1, releasedRateA + a.rate, releasedRateB, depth + 1, openedPressure + result)) else for (linkB in links) foundSubPressure = maxOf(foundSubPressure, openedPressure + maxPressure(Link(a, 0), Link(linkB.valve, linkB.dist - 1), timeLeft - 1, releasedRateA + a.rate, releasedRateB, depth + 1, openedPressure + result)) a.opened = false a.lastRateA = releasedRateA } // both pass thru val linksA = a.links.filter { it.valve.lastRateA < releasedRateA } val linksB = b.links.filter { it.valve.lastRateB < releasedRateB } if (linksA.isEmpty()) if (linksB.isEmpty()) // return 0 else for (linkB in linksB) foundSubPressure = maxOf(foundSubPressure, maxPressure(Link(a, 1000), linkB, timeLeft, releasedRateA, releasedRateB, depth + 1, result)) else for (linkA in linksA) if (linksB.isEmpty()) foundSubPressure = maxOf(foundSubPressure, maxPressure(linkA, Link(b, 1000), timeLeft, releasedRateA, releasedRateB, depth + 1, result)) else for (linkB in linksB) foundSubPressure = maxOf(foundSubPressure, maxPressure(linkA, linkB, timeLeft, releasedRateA, releasedRateB, depth + 1, result)) } else { // a <> b if (!a.opened && a.name != "AA") { val openedPressureA = a.rate * (timeLeft - 1) if (all { it.opened || it.name == "AA" || it == a }) { a.lastRateA = tempRateA b.lastRateB = tempRateB return openedPressureA } a.opened = true a.lastRateA = releasedRateA + a.rate if (!b.opened && b.name != "AA") { val openedPressureB = b.rate * (timeLeft - 1) if (all { it.opened || it.name == "AA" || it == b }) { a.opened = false a.lastRateA = tempRateA b.lastRateB = tempRateB return openedPressureA + openedPressureB } b.opened = true b.lastRateB = releasedRateB + b.rate foundSubPressure = maxOf(foundSubPressure, openedPressureA + openedPressureB + maxPressure(Link(a, 0), Link(b, 0), timeLeft - 1, releasedRateA + a.rate, releasedRateB + b.rate, depth + 1, openedPressureA + openedPressureB + result)) b.opened = false b.lastRateB = releasedRateB } val links = b.links.filter { it.valve.lastRateB < releasedRateB } if (links.isEmpty()) foundSubPressure = maxOf(foundSubPressure, openedPressureA + maxPressure(Link(a, 0), Link(b, 1000), timeLeft - 1, releasedRateA + a.rate, releasedRateB, depth + 1, openedPressureA + result)) else for (linkB in links) foundSubPressure = maxOf(foundSubPressure, openedPressureA + maxPressure(Link(a, 0), Link(linkB.valve, linkB.dist - 1), timeLeft - 1, releasedRateA + a.rate, releasedRateB, depth + 1, openedPressureA + result)) a.opened = false a.lastRateA = releasedRateA } val linksA = a.links.filter { it.valve.lastRateA < releasedRateA } val linksB = b.links.filter { it.valve.lastRateB < releasedRateB } if (linksA.isEmpty()) if (linksB.isEmpty()) // return 0 else for (link in linksB) foundSubPressure = maxOf(foundSubPressure, maxPressure(Link(a, 1000), link, timeLeft, releasedRateA, releasedRateB, depth + 1, result)) else for (linkA in linksA) if (linksB.isEmpty()) foundSubPressure = maxOf(foundSubPressure, maxPressure(linkA, Link(b, 1000), timeLeft, releasedRateA, releasedRateB, depth + 1, result)) else for (linkB in linksB) foundSubPressure = maxOf(foundSubPressure, maxPressure(linkA, linkB, timeLeft, releasedRateA, releasedRateB, depth + 1, result)) } a.lastRateA = tempRateA b.lastRateB = tempRateB // b.lastRateA = tempRateB return foundSubPressure } fun main() { fun part1(input: List<String>, time: Int): Int { val valves = mutableListOf<Valve>() input.forEach { line -> valves.add(Valve.parse(line)) } val rootValve = valves.first {it.name == "AA" } valves.fillList() valves.optimize() return rootValve.maxPressure(valves, time, 0) } fun part2(input: List<String>, time: Int): Int { val valves = mutableListOf<Valve>() input.forEach { line -> valves.add(Valve.parse(line)) } valves.fillList() valves.optimize() val rootNode = Link(valves.first {it.name == "AA" }, 0) return valves.maxPressure(rootNode, rootNode, time - 0, 0, 0, 0, 0) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day16_test") // val testInput = readInput("Day16_test2") // val testInput = readInput("Day16_test3") // println(part1(testInput)) // check(part1(testInput, 30) == 1651) // println(part2(testInput, 26)) // check(part2(testInput, 26) == 1707) //1652 val input = readInput("Day16") // println(part1(input, 30)) println(part2(input, 26)) // 2772 // println(solutions.map { (key, value) -> Pair(key, value) }.sortedBy { it.first }.joinToString("\n")) }
0
Kotlin
0
0
d9dd7a33b404dc0d43576dfddbc9d066036f7326
14,175
AoC-2022
Apache License 2.0
src/intervals/Interval.kt
hopshackle
225,904,074
false
null
package intervals import java.lang.AssertionError import kotlin.random.Random import kotlin.reflect.KFunction interface Interval { fun sampleFrom(): Number fun sampleFrom(rnd: Random): Number fun sampleGrid(n: Int): List<Number> } fun interval(from: Number, to: Number): Interval { return when (from) { is Int -> IntegerInterval(from, to.toInt()) is Double -> DoubleInterval(from, to.toDouble()) else -> throw AssertionError("Type not yet supported for Interval: " + from::class) } } fun interval(singleValue: Number): Interval { return when (singleValue) { is Int -> IntegerInterval(singleValue) is Double -> DoubleInterval(singleValue) else -> throw AssertionError("Type not yet supported for Interval: " + singleValue::class) } } fun intervalList(stringRepresentation: String): List<Interval> { // format is one of: // a // [a, b] // a : b // a : [b, c] // [a, b] : c // [a, b] : [c, d] return stringRepresentation.split(":").map { s: String -> interval(s) } } fun interval(stringRepresentation: String): Interval { // format is one of: // a // [a, b] // [a, b], [c, d] ... val funToApply: (String) -> Number = when { stringRepresentation.contains("true") || stringRepresentation.contains("false") -> { s -> if (s == "true") 1 else 0 } stringRepresentation.contains(".") -> { s -> s.toDouble() } else -> String::toInt } fun convertToInterval(stringRep: List<String>): Interval { return when (stringRep.size) { 1 -> interval(funToApply(stringRep[0].trim())) 2 -> interval(funToApply(stringRep[0].trim()), funToApply(stringRep[1].trim())) else -> { val splitByBrackets = stringRepresentation.filterNot(Character::isWhitespace) .replace("],", "]") .split("]") .map { it.filterNot { c -> c in "[]" } } .filterNot { it == "," } CompositeInterval(splitByBrackets.filter(String::isNotEmpty).map { val intervalE = it.split(",") convertToInterval(intervalE) }) } } } val intervalEnds = stringRepresentation.filterNot { c -> c in "[]" }.split(",") return convertToInterval(intervalEnds) } private val rnd = Random(System.currentTimeMillis()) data class IntegerInterval(val startPoint: Int, val endPoint: Int) : Interval { constructor(singlePoint: Int) : this(singlePoint, singlePoint) override fun sampleFrom(rnd: Random): Int = rnd.nextInt(startPoint, endPoint + 1) override fun sampleFrom(): Int = sampleFrom(rnd) override fun sampleGrid(n: Int): List<Int> { if ((endPoint + 1 - startPoint) % n != 0) throw AssertionError(String.format("Number in grid (%d) must be factor of total length (%d)", n, endPoint + 1 - startPoint)) val stepAmount = (endPoint + 1 - startPoint) / n return (0 until n).map { startPoint + it * stepAmount }.toList() } } data class DoubleInterval(val startPoint: Double, val endPoint: Double) : Interval { constructor(singlePoint: Double) : this(singlePoint, singlePoint + 1e-6) override fun sampleFrom(rnd: Random): Double = rnd.nextDouble(startPoint, endPoint) override fun sampleFrom(): Double = sampleFrom(rnd) override fun sampleGrid(n: Int): List<Double> { val stepAmount = (endPoint - startPoint) / (n - 1) return (0 until n).map { startPoint + it * stepAmount }.toList() } } data class CompositeInterval(val components: List<Interval>) : Interval { override fun sampleFrom(rnd: Random): Double { val componentToUse = rnd.nextInt(components.size) return components[componentToUse].sampleFrom(rnd).toDouble() } override fun sampleFrom(): Double = sampleFrom(rnd) override fun sampleGrid(n: Int): List<Number> { TODO("Not yet implemented") } }
0
Kotlin
0
0
e5992d6b535b3f4a6552bf6f2351865a33d56248
4,037
SmarterSims
MIT License
src/Day01.kt
matusekma
572,617,724
false
{"Kotlin": 119912, "JavaScript": 2024}
class Day01 { fun part1MostCalories(input: List<String>): Int { var max = 0 var current = 0 for (calorie in input) { if (calorie == "") { if (current > max) { max = current } current = 0 } else { current += calorie.toInt() } } return max } fun part2Top3MostCalories(input: List<String>): Int { val maxes = IntArray(3) var current = 0 for (calorie in input) { if (calorie == "") { if (current > maxes[2]) { maxes[0] = maxes[1] maxes[1] = maxes[2] maxes[2] = current } else if (current > maxes[1]) { maxes[0] = maxes[1] maxes[1] = current } else if (current > maxes[0]) { maxes[0] = current } current = 0 } else { current += calorie.toInt() } } return maxes.sum() } } fun main() { val day01 = Day01() val input = readInput("input01_1") println(day01.part1MostCalories(input)) println(day01.part2Top3MostCalories(input)) }
0
Kotlin
0
0
744392a4d262112fe2d7819ffb6d5bde70b6d16a
1,307
advent-of-code
Apache License 2.0
src/day03/Day03.kt
pnavais
727,416,570
false
{"Kotlin": 17859}
package day03 import readInput class EngineSchematic { val rows: MutableList<List<Char>> = mutableListOf() } private fun readMatrix(input: List<String>) : EngineSchematic { val engineSchematic = EngineSchematic() input.forEach { s -> engineSchematic.rows.add(s.toList()) } return engineSchematic } private fun hasElementNearby(engineSchematic: EngineSchematic, i: Int, j: Int, checker: (row: Int, col: Int) -> Boolean): Boolean { var hasSymbol = false for (row in i-1..i+1) { for (col in j-1..j+1) { if (row in 0 until engineSchematic.rows.size && col in 0 until engineSchematic.rows[row].size) { hasSymbol = hasSymbol || checker(row, col) } } } return hasSymbol } private fun hasSymbolNearby(engineSchematic: EngineSchematic, i: Int, j: Int): Boolean { return hasElementNearby(engineSchematic, i, j) { r, c -> !engineSchematic.rows[r][c].isDigit() && engineSchematic.rows[r][c] != '.' } } private fun hasGearNearby(engineSchematic: EngineSchematic, i: Int, j: Int): Pair<Boolean, String> { var gearPos = "" return hasElementNearby(engineSchematic, i, j) { r, c -> if (engineSchematic.rows[r][c] == '*') { gearPos = "${r}_${c}" }; engineSchematic.rows[r][c] == '*' } to gearPos } private fun saveGear( gearMap: MutableMap<String, MutableList<Long>>, gearPos: String, currentNumber: String ) { if (!gearMap.containsKey(gearPos)) { gearMap[gearPos] = mutableListOf() } gearMap[gearPos]!!.add(currentNumber.toLong()) } fun part1(input: List<String>): Long { val engineSchematic = readMatrix(input) var total = 0L for (i in 0 until engineSchematic.rows.size) { var currentNumber = "" var isValid = false for (j in 0 until engineSchematic.rows[i].size) { if (engineSchematic.rows[i][j].isDigit()) { currentNumber += engineSchematic.rows[i][j] // Check symbol presence in all directions isValid = isValid || hasSymbolNearby(engineSchematic, i, j) } else { if (currentNumber.isNotBlank() && isValid) { total += currentNumber.toLong() } currentNumber = "" isValid = false } if (j == engineSchematic.rows[i].size-1 && currentNumber.isNotBlank() && isValid) { total += currentNumber.toLong() } } } return total } fun part2(input: List<String>): Long { val gearMap = linkedMapOf<String, MutableList<Long>>() val engineSchematic = readMatrix(input) for (i in 0 until engineSchematic.rows.size) { var currentNumber = "" var isValid = false var gearPos = "" for (j in 0 until engineSchematic.rows[i].size) { if (engineSchematic.rows[i][j].isDigit()) { currentNumber += engineSchematic.rows[i][j] // Check symbol presence in all directions val (hasGear, gearPosAux) = hasGearNearby(engineSchematic, i, j) isValid = isValid || hasGear if (hasGear) { gearPos = gearPosAux } } else { if (currentNumber.isNotBlank() && isValid) { saveGear(gearMap, gearPos, currentNumber) } currentNumber = "" isValid = false } if (j == engineSchematic.rows[i].size-1 && currentNumber.isNotBlank() && isValid) { saveGear(gearMap, gearPos, currentNumber) } } } return gearMap.filterValues { v -> v.size == 2 }.map { (_,v) -> v.reduce { a, b -> a * b } }.sum() } fun main() { val testInput = readInput("input/day03") println(part1(testInput)) println(part2(testInput)) }
0
Kotlin
0
0
f5b1f7ac50d5c0c896d00af83e94a423e984a6b1
3,931
advent-of-code-2k3
Apache License 2.0
src/main/kotlin/com/github/shmvanhouten/adventofcode/day13/Maze.kt
SHMvanHouten
109,886,692
false
{"Kotlin": 616528}
package com.github.shmvanhouten.adventofcode.day13 import com.github.shmvanhouten.adventofcode.day13.MazeComponent.* import com.github.shmvanhouten.adventofcode.day22gridcomputing.Coordinate class Maze(val height: Int = 50, val width: Int = 50) { private var mazeGrid: Map<Int, Map<Int, MazeComponent>> = initializeMap() private fun initializeMap(): Map<Int, Map<Int, MazeComponent>> { val row = 0.until(width).associateBy({ it }, { CORRIDOR }) return 0.until(height).associateBy({it}, {row}) } fun buildWall(x: Int, y: Int) { if(mazeGrid.containsKey(y)) { val row = mazeGrid.getValue(y) if (row.containsKey(x)){ val newRow = row.minus(x).plus(x to WALL) mazeGrid = mazeGrid.minus(y).plus(y to newRow) }else { println("x: $x not found") } } else { println("y: $y not found") } } fun getComponent(x: Int, y: Int): MazeComponent { if(mazeGrid.containsKey(y)){ val row = mazeGrid.getValue(y) if (row.containsKey(x)){ return row.getValue(x) } } return WALL } fun getComponent(coordinate: Coordinate): MazeComponent { if(mazeGrid.containsKey(coordinate.y)){ val row = mazeGrid.getValue(coordinate.y) if (row.containsKey(coordinate.x)){ return row.getValue(coordinate.x) } } return WALL } fun getAdjacentCorridors(originCoordinate: Coordinate): List<Coordinate> { val x = originCoordinate.x val y = originCoordinate.y val possibleAdjacent = listOf( Coordinate(x - 1, y), Coordinate(x + 1, y), Coordinate(x, y - 1), Coordinate(x, y + 1)) return possibleAdjacent .filter { this.getComponent(it) == CORRIDOR } } } fun buildMazeFromMazeRepresentation(mazeRepresentation: List<String>): Maze { val maze = Maze(mazeRepresentation.size, mazeRepresentation[0].length) mazeRepresentation.forEachIndexed { y, row -> row.forEachIndexed{ x, char -> if (char == '#') maze.buildWall(x,y)} } return maze } enum class MazeComponent { WALL, CORRIDOR }
0
Kotlin
0
0
a8abc74816edf7cd63aae81cb856feb776452786
2,316
adventOfCode2016
MIT License
src/Day09.kt
felldo
572,233,925
false
{"Kotlin": 76496}
fun main() { data class Position(var x: Int, var y: Int) fun moveHead(head: Position, direction: String) { when (direction) { "U" -> head.y++ "D" -> head.y-- "L" -> head.x-- "R" -> head.x++ } } fun moveKnot(head: Position, tail: Position): Boolean { if (tail.y < head.y - 1) { when { tail.x < head.x - 1 -> tail.x++ tail.x > head.x + 1 -> tail.x-- else -> tail.x = head.x } tail.y = head.y - 1 return true } if (tail.y > head.y + 1) { when { tail.x < head.x - 1 -> tail.x++ tail.x > head.x + 1 -> tail.x-- else -> tail.x = head.x } tail.y = head.y + 1 return true } if (tail.x > head.x + 1) { tail.x = head.x + 1 when { tail.y < head.y - 1 -> tail.y++ tail.y > head.y + 1 -> tail.y-- else -> tail.y = head.y } return true } if (tail.x < head.x - 1) { tail.x = head.x - 1 when { tail.y < head.y - 1 -> tail.y++ tail.y > head.y + 1 -> tail.y-- else -> tail.y = head.y } return true } return false } fun part1(input: List<String>): Int { val headPosition = Position(0, 0) val tailPosition = Position(0, 0) val positions = mutableSetOf<Position>() for (line in input) { val inputs = line.split(" ") val direction = inputs[0] val distance = inputs[1].toInt() for (i in 0 until distance) { moveHead(headPosition, direction) moveKnot(headPosition, tailPosition) positions.add(Position(tailPosition.x, tailPosition.y)) } } return positions.size } fun part2(input: List<String>): Int { val knots = Array(10) { Position(0, 0) } val positions = mutableSetOf<Position>() for (line in input) { val inputs = line.split(" ") val direction = inputs[0] val distance = inputs[1].toInt() for (i in 0 until distance) { moveHead(knots[0], direction) for (k in 0 until knots.size - 1) { val moved = moveKnot(knots[k], knots[k + 1]) if (!moved) break } positions.add(Position(knots.last().x, knots.last().y)) } } return positions.size } val input = readInput("Day09") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
0ef7ac4f160f484106b19632cd87ee7594cf3d38
2,856
advent-of-code-kotlin-2022
Apache License 2.0
src/Day10.kt
MartinsCode
572,817,581
false
{"Kotlin": 77324}
class Machine { private var cycle = 0 private var strength = 1 var addedSignal = 0 var display = mutableListOf("........................................", "........................................", "........................................", "........................................", "........................................", "........................................") private var coords = Pair(0, 0) // Coords of Ray private fun calculateCoords() { val y = (cycle - 1) / 40 val x = ((cycle - 1) % 40) coords = Pair(x, y) } private fun spriteIsVisible(): Boolean { return (coords.first >= strength - 1 && coords.first <= strength + 1) } private fun addCycle() { cycle++ if (cycle in arrayOf(20, 60, 100, 140, 180, 220)) { addedSignal += strength * cycle } calculateCoords() if (spriteIsVisible()) { val lineArray = display[coords.second].toCharArray() lineArray[coords.first] = '#' display[coords.second] = String(lineArray) } } fun parse (line: String) { when (line) { "noop" -> addCycle() else -> { // addx addCycle() addCycle() strength += line.split(" ")[1].toInt() } } } } fun main() { fun part1(input: List<String>): Int { val machine = Machine() input.forEach { machine.parse(it) } return machine.addedSignal } fun part2(input: List<String>): MutableList<String> { val machine = Machine() input.forEach { machine.parse(it) } // println(machine.display.joinToString("\n")) return machine.display } // test if implementation meets criteria from the description, like: val testInput = readInput("Day10-TestInput") println(part1(testInput)) check(part1(testInput) == 13140) check(part2(testInput) == mutableListOf("##..##..##..##..##..##..##..##..##..##..", "###...###...###...###...###...###...###.", "####....####....####....####....####....", "#####.....#####.....#####.....#####.....", "######......######......######......####", "#######.......#######.......#######.....")) val input = readInput("Day10-Input") println(part1(input)) println(part2(input).joinToString("\n")) }
0
Kotlin
0
0
1aedb69d80ae13553b913635fbf1df49c5ad58bd
2,524
AoC-2022-12-01
Apache License 2.0
src/main/kotlin/year2023/Day08.kt
forketyfork
572,832,465
false
{"Kotlin": 142196}
package year2023 import utils.lcm class Day08 { fun part1(input: String) = solve(input, { it == "AAA" }, { it == "ZZZ" }) fun part2(input: String) = solve(input, { it.endsWith('A') }, { it.endsWith('Z') }) data class Node(val left: String, val right: String, val terminal: Boolean) fun solve(input: String, isSource: (String) -> Boolean, isDestination: (String) -> Boolean): Long { val lines = input.lines() val path = lines.first() val nodes = lines.drop(2).associate { line -> val (name, left, right) = line.split(*" =,()".toCharArray()).filter(String::isNotBlank) name to Node(left, right, isDestination(name)) } return nodes.filter { isSource(it.key) }.map { node -> (1..Long.MAX_VALUE).fold(node.value) { node, iteration -> path.fold(node) { node, dir -> nodes[(if (dir == 'L') node.left else node.right)]!! } .apply { if (terminal) { return@map iteration } } } 0 }.reduce(Long::lcm) * path.length } }
0
Kotlin
0
0
5c5e6304b1758e04a119716b8de50a7525668112
1,173
aoc-2022
Apache License 2.0
src/Day01.kt
brunojensen
572,665,994
false
{"Kotlin": 13161}
import java.util.PriorityQueue import kotlin.math.max private fun PriorityQueue<Int>.offerAndPollIfMaxSize(input: Int, maxSizw: Int) { this.offer(input) if (this.size > maxSizw) { this.poll() } } fun main() { fun part1(input: List<String>): Int { var sum = 0 var max = 0 for (i in input) { if (i.isBlank()) { sum = 0 continue } sum += i.toInt() max = max(sum, max) } return max } fun part2(input: List<String>): Int { val queue: PriorityQueue<Int> = PriorityQueue() var sum = 0 for (i in input) { if (i.isBlank()) { queue.offerAndPollIfMaxSize(sum, 3) sum = 0 continue } sum += i.toInt() } queue.offerAndPollIfMaxSize(sum, 3) return queue.sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01.test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
2707e76f5abd96c9d59c782e7122427fc6fdaad1
1,063
advent-of-code-kotlin-1
Apache License 2.0
src/main/kotlin/g1701_1800/s1782_count_pairs_of_nodes/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1701_1800.s1782_count_pairs_of_nodes // #Hard #Binary_Search #Two_Pointers #Graph // #2023_06_18_Time_1441_ms_(100.00%)_Space_116_MB_(100.00%) class Solution { fun countPairs(n: Int, edges: Array<IntArray>, queries: IntArray): IntArray { val edgeCount: MutableMap<Int, Int> = HashMap() val degree = IntArray(n) for (e in edges) { val u = e[0] - 1 val v = e[1] - 1 degree[u]++ degree[v]++ val eId = Math.min(u, v) * n + Math.max(u, v) edgeCount[eId] = edgeCount.getOrDefault(eId, 0) + 1 } val degreeCount: MutableMap<Int, Int> = HashMap() var maxDegree = 0 for (d in degree) { degreeCount[d] = degreeCount.getOrDefault(d, 0) + 1 maxDegree = Math.max(maxDegree, d) } val count = IntArray(2 * maxDegree + 1) for (d1 in degreeCount.entries) { for (d2 in degreeCount.entries) { count[d1.key + d2.key] += if (d1 === d2) d1.value * (d1.value - 1) else d1.value * d2.value } } for (i in count.indices) { count[i] /= 2 } for ((key, value) in edgeCount) { val u = key / n val v = key % n count[degree[u] + degree[v]]-- count[degree[u] + degree[v] - value]++ } for (i in count.size - 2 downTo 0) { count[i] += count[i + 1] } val res = IntArray(queries.size) for (q in queries.indices) { res[q] = if (queries[q] + 1 >= count.size) 0 else count[queries[q] + 1] } return res } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,672
LeetCode-in-Kotlin
MIT License
src/main/kotlin/com/colinodell/advent2021/Day22.kt
colinodell
433,864,377
true
{"Kotlin": 111114}
package com.colinodell.advent2021 class Day22(input: List<String>) { private val initializationProcedureRegion = Cuboid(Vector3(-50, -50, -50), Vector3(50, 50, 50)) private val procedure = parseInput(input) private val initializationProcedure = procedure.mapKeys { it.key.intersect(initializationProcedureRegion) }.filter { it.key.isValid() } fun solvePart1() = initializeAndCountLitCuboids(initializationProcedure) fun solvePart2() = initializeAndCountLitCuboids(procedure) private fun initializeAndCountLitCuboids(instructions: Map<Cuboid, Boolean>): Long { val initialized = mutableListOf<Pair<Cuboid, Boolean>>() instructions.forEach { (cuboid, isOn) -> // Invert any cuboids intersecting with this one initialized .map { it.first.intersect(cuboid) to !it.second } .filter { it.first.isValid() } .run { initialized.addAll(this) } // Add this cuboid, but only if it's on if (isOn) { initialized.add(cuboid to true) } } // Calculate the number of lit points return initialized.sumOf { (cuboid, isOn) -> cuboid.getVolume() * (if (isOn) 1 else -1) } } private fun parseInput(input: List<String>): Map<Cuboid, Boolean> { val map = mutableMapOf<Cuboid, Boolean>() // Parse each input line with regex input.map { "(on|off) x=(-?\\d+)..(-?\\d+),y=(-?\\d+)..(-?\\d+),z=(-?\\d+)..(-?\\d+)".toRegex().find(it)?.let { val (action, x1, x2, y1, y2, z1, z2) = it.destructured map[Cuboid(Vector3(x1.toInt(), y1.toInt(), z1.toInt()), Vector3(x2.toInt(), y2.toInt(), z2.toInt()))] = action == "on" } } return map } }
0
Kotlin
0
1
a1e04207c53adfcc194c85894765195bf147be7a
1,808
advent-2021
Apache License 2.0
archive/src/main/kotlin/com/grappenmaker/aoc/year21/Day23.kt
770grappenmaker
434,645,245
false
{"Kotlin": 409647, "Python": 647}
package com.grappenmaker.aoc.year21 import com.grappenmaker.aoc.* import com.grappenmaker.aoc.Direction.* import java.util.* fun PuzzleSet.day23() = puzzle(day = 23) { fun List<String>.parse() = map { it.padEnd(inputLines.first().length, ' ') }.asCharGrid() fun solve(grid: Grid<Char>): String { fun Point.bucket() = if (x in 3..9 && y >= 2) (x - 3) / 2 else null data class Amphipod( val position: Point, val type: Int, val cost: Int = 10.pow(type), ) fun Amphipod.atBucket(bucket: Int) = position.bucket() == bucket // First time ever overwriting equals and hashcode in kotlin data class State( val pods: Set<Amphipod>, val lastCost: Int = 0, val lastMoved: Amphipod = pods.first(), val done: Set<Int> = emptySet() ) { override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as State if (pods != other.pods) return false return lastMoved == other.lastMoved } override fun hashCode(): Int { var result = pods.hashCode() result = 31 * result + lastMoved.hashCode() return result } } val initial = grid.findPoints { it in 'A'..'D' }.map { Amphipod(it, grid[it] - 'A') } val needsInBucket = initial.count { it.type == 0 } fun adaptedDijkstra(): DijkstraPath<State> = with(grid) { val start = State(initial.toSet()) val seen = hashSetOf(start) val queue = PriorityQueue(compareBy<Pair<State, Int>> { (_, c) -> c }) .also { it.add(start to 0) } queue.drain { (state, currentCost) -> if (state.done.size == 4) return DijkstraPath( end = state, path = emptyList(), cost = currentCost ) fun findAtBucket(bucket: Int) = state.pods.find { it.atBucket(bucket) } fun findAllAtBucket(bucket: Int) = state.pods.filter { it.atBucket(bucket) } fun Point.valid() = grid[this] != '#' && state.pods.none { it.position == this } fun Point.poss() = adjacentSides().filter { it.valid() } state.pods.flatMap { moving -> val bucket = moving.position.bucket() if (bucket in state.done) return@flatMap emptyList() val update = { new: Point, steps: Int -> val updated = moving.copy(position = new) State( pods = state.pods - moving + updated, lastCost = moving.cost * steps, lastMoved = updated, done = state.done, ) } val otherPod = findAtBucket(moving.type) val approves = otherPod == null || otherPod.type == moving.type val pathToEnd = bfsDistance( initial = moving.position, isEnd = { it.bucket() == moving.type }, neighbors = { if (approves) it.poss() else emptyList() } ) val originalEnd = pathToEnd.original.end val pathEnd = originalEnd?.let { var curr = it while (curr.valid()) curr += DOWN curr - DOWN } when { pathEnd != null && pathToEnd.dist != 0 -> listOf( update(pathEnd, pathToEnd.dist + (pathEnd manhattanDistanceTo originalEnd)).let { val thereBefore = findAllAtBucket(moving.type).size if (thereBefore == needsInBucket - 1) it.copy(done = it.done + moving.type) else it } ) bucket != null && grid.column(moving.position.x) .none { it.y < moving.position.y && state.pods.any { p -> p.position == it } } -> { var curr = moving.position while (grid[curr] != '#') curr += UP val endedAt = curr - UP listOf(LEFT, RIGHT) .map { endedAt + it } .filter { it.valid() } .map { update(it, curr manhattanDistanceTo moving.position) } } moving == state.lastMoved -> { listOf(LEFT, RIGHT).mapNotNull { d -> val nextIntended = moving.position + d if (!nextIntended.valid()) return@mapNotNull null nextIntended .let { if ((it + DOWN).bucket() != null) it + d else it } .takeIf { it.valid() } }.map { update(it, moving.position manhattanDistanceTo it) } } else -> emptyList() } }.forEach { if (seen.add(it)) queue.offer(it to currentCost + it.lastCost) } } error("Should never happen") } return adaptedDijkstra().cost.s() } partOne = solve(inputLines.parse()) val transformed = inputLines.toMutableList() transformed.addAll(3, """ | #D#C#B#A# | #D#B#A#C# """.trimMargin().lines()) partTwo = solve(transformed.parse()) }
0
Kotlin
0
7
92ef1b5ecc3cbe76d2ccd0303a73fddda82ba585
5,925
advent-of-code
The Unlicense
src/main/kotlin/se/saidaspen/aoc/aoc2016/Day21.kt
saidaspen
354,930,478
false
{"Kotlin": 301372, "CSS": 530}
package se.saidaspen.aoc.aoc2016 import se.saidaspen.aoc.util.Day import se.saidaspen.aoc.util.e import se.saidaspen.aoc.util.ints import se.saidaspen.aoc.util.permutations import java.lang.RuntimeException import kotlin.math.absoluteValue fun main() = Day21.run() object Day21 : Day(2016, 21) { override fun part1(): Any { val operations = input.lines().map { toOperation(it) }.toList() return scramble(operations, "abcdefgh") } private fun scramble(operations: List<(String) -> String>, s: String): Any { var str = s for (op in operations) { str = op.invoke(str) } return str } private fun toOperation(it: String): (String) -> String { if (it.startsWith("swap position")) { return { s -> val (f, t) = ints(it) val n = s.e().toMutableList() val tmp = n[f] n[f] = n[t] n[t] = tmp n.joinToString("") } } else if (it.startsWith("swap letter")) { return { s -> val f = it.split(" ")[2] val t = it.split(" ")[5] var tmp = s.replace(f, "*") tmp = tmp.replace(t, f) tmp = tmp.replace("*", t) tmp } } else if (it.startsWith("rotate based")) { return { s -> val letter = it.split(" ")[6] val index = s.indexOf(letter) rotate(s, 1+ index + (if (index >= 4) +1 else 0)) } } else if (it.startsWith("rotate")) { return { s -> val steps = it.split(" ")[2].toInt() val dir = it.split(" ")[1] rotate(s, if (dir == "right") steps else steps * -1) } } else if (it.startsWith("move")) { return { s -> val (f, t) = ints(it) val n = s.e().toMutableList() val elem = n.removeAt(f) n.add(t, elem) n.joinToString("") } } else if (it.startsWith("reverse")) { return { s -> val (f, t) = ints(it) s.substring(0, f) + s.substring(f, t + 1 ).reversed() + if(t+1 < s.length) s.substring(t+1) else "" } } else { throw RuntimeException("Unsupported operation") } } fun rotate(s: String, i: Int): String { val steps = i % s.length return if (steps > 0) { s.substring(s.length - steps) + s.substring(0, s.length - steps) } else { s.substring(steps.absoluteValue) + s.substring(0, steps.absoluteValue) } } override fun part2(): Any { val operations = input.lines().map { toOperation(it) }.toList() val possibles = permutations("abcdefgh".e(), "abcdefgh".length) return possibles.first { scramble(operations, it.joinToString("")) == "fbgdceah" }.joinToString("") } }
0
Kotlin
0
1
be120257fbce5eda9b51d3d7b63b121824c6e877
3,021
adventofkotlin
MIT License
src/Day06.kt
cornz
572,867,092
false
{"Kotlin": 35639}
fun main() { fun getSequence(input: String, lengthOfMarker: Int): String { // mjqjpqmgbljsphdztnvjfqwrcgsmlb val arr = input.toCharArray().map { c -> c.code } val windows = arr.windowed(size = lengthOfMarker, step = 1) for (window in windows) { if (window.size == window.toSet().size) { return window.map { code -> code.toChar() }.joinToString("") } } return "" } fun findEndIndex(input: String, testinput: String): Int { val start = input.indexOf(testinput) return start + testinput.length } fun part1(input: List<String>): Int { val inp = input[0] val target = getSequence(inp, 4) return findEndIndex(inp, target) } fun part2(input: List<String>): Int { val inp = input[0] val target = getSequence(inp, 14) return findEndIndex(inp, target) } // test if implementation meets criteria from the description, like: val testInput = readInput("input/Day06_test") check(part1(testInput) == 7) check(part2(testInput) == 19) val input = readInput("input/Day06") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
2800416ddccabc45ba8940fbff998ec777168551
1,221
aoc2022
Apache License 2.0
kotlin/src/katas/kotlin/leetcode/swype_lock/SwypeLock.kt
dkandalov
2,517,870
false
{"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221}
package katas.kotlin.leetcode.swype_lock import datsok.* import org.junit.* import kotlin.math.* /** * By <NAME>. */ class SwypeLock { @Test fun `some examples`() { // 1 2 3 // 4 5 6 // 7 8 9 validate(emptyList()) shouldEqual false validate((1..10).toList()) shouldEqual false validate(listOf(1, 1)) shouldEqual false validate(listOf(0)) shouldEqual false validate(listOf(10)) shouldEqual false check(digit = 1, validMoves = listOf(2, 4, 5), invalidMoves = listOf(1, 3, 6, 7, 8, 9)) check(digit = 2, validMoves = listOf(1, 3, 4, 5, 6), invalidMoves = listOf(2, 7, 8, 9)) check(digit = 3, validMoves = listOf(2, 5, 6), invalidMoves = listOf(1, 3, 4, 7, 8, 9)) check(digit = 4, validMoves = listOf(1, 2, 5, 8, 7), invalidMoves = listOf(3, 4, 6, 9)) check(digit = 5, validMoves = listOf(1, 2, 3, 4, 6, 7, 8, 9), invalidMoves = listOf(5)) check(digit = 6, validMoves = listOf(2, 3, 5, 8, 9), invalidMoves = listOf(1, 4, 6, 7)) check(digit = 7, validMoves = listOf(4, 5, 8), invalidMoves = listOf(1, 2, 3, 6, 7, 9)) check(digit = 8, validMoves = listOf(4, 5, 6, 7, 9), invalidMoves = listOf(1, 2, 3, 8)) check(digit = 9, validMoves = listOf(5, 6, 8), invalidMoves = listOf(1, 2, 3, 4, 7, 9)) validate(listOf(1, 2, 3)) shouldEqual true validate(listOf(3, 2, 1)) shouldEqual true validate(listOf(1, 2, 3, 4)) shouldEqual false validate(listOf(4, 3, 2, 1)) shouldEqual false } private fun check(digit: Int, validMoves: List<Int>, invalidMoves: List<Int>) { validMoves.forEach { validate(listOf(digit, it)) shouldEqual true validate(listOf(it, digit)) shouldEqual true } invalidMoves.forEach { validate(listOf(digit, it)) shouldEqual false validate(listOf(it, digit)) shouldEqual false } } } private fun validate(swypeLock: List<Int>): Boolean { return swypeLock.size in 1..9 && swypeLock.size == swypeLock.toSet().size && swypeLock.all { it in 1..9 } && swypeLock.windowed(size = 2).all { (digit1, digit2) -> areNeighbours(digit1, digit2) } } private fun areNeighbours(digit1: Int, digit2: Int): Boolean { val absDiff = (digit1 - digit2).absoluteValue val isHorizontal = absDiff == 1 && digit1.row == digit2.row val isVertical = absDiff == 3 val isDiagonal = (absDiff == 2 || absDiff == 4) && (digit1.row - digit2.row).absoluteValue == 1 return isHorizontal || isVertical || isDiagonal } private val Int.row: Int get() = (this - 1) / 3
7
Roff
3
5
0f169804fae2984b1a78fc25da2d7157a8c7a7be
2,658
katas
The Unlicense
src/main/kotlin/day24/part2/Part2.kt
bagguley
329,976,670
false
null
package day24.part2 import day24.data import day24.testData var x: Int = 0 var y: Int = 0 var hexMap = mutableMapOf<String, String>() var nextMap = mutableMapOf<String, String>() fun main() { load(data) } fun load(input: List<String>) { for (line in input) { x = 0 y = 0 val t = Regex("(ne|e|se|sw|w|nw)").findAll(line).toList().map{it.value} for (x in t) { when (x) { "ne" -> northEast() "e" -> east() "se" -> southEast() "sw" -> southWest() "w" -> west() "nw" -> northWest() } } val h = hexMap.getOrPut("$x,$y"){"w"} when (h) { "w" -> hexMap.put("$x,$y", "b") "b" -> hexMap.put("$x,$y", "w") } } val r = hexMap.values.count { it == "b" } println(r) // Part 1 answer for (i in 1..100) { nextMap = hexMap.toMutableMap() val keys = hexMap.keys for (k in keys) { val v = hexMap[k]!! val x = k.split(",")[0].toInt() val y = k.split(",")[1].toInt() mutate(v, x, y) } val allEdges = allEdges() for (e in allEdges) { val x = e.split(",")[0].toInt() val y = e.split(",")[1].toInt() mutate("w", x, y) } hexMap = nextMap } val r2 = hexMap.values.count { it == "b" } println(r2) // Part 2 answer } fun mutate(v: String, x: Int, y: Int) { val c = countBlackNeighbours(x, y) when (v) { "b" -> { if (c == 0 || c > 2) { nextMap["$x,$y"] = "w" } } "w" -> { if (c == 2) { nextMap["$x,$y"] = "b" } } } } fun countBlackNeighbours(x: Int, y: Int): Int { var count = 0 if (isBlack(x+1, y-1)) count++ if (isBlack(x+2, y)) count++ if (isBlack(x+1, y+1)) count++ if (isBlack(x-1, y+1)) count++ if (isBlack(x-2, y)) count++ if (isBlack(x-1, y-1)) count++ return count } fun allEdges(): Set<String> { val result = mutableSetOf<String>() for (k in hexMap.keys) { val x = k.split(",")[0].toInt() val y = k.split(",")[1].toInt() if (!containsKey(x+1, y-1)) result.add("${x+1},${y-1}") if (!containsKey(x+2, y)) result.add("${x+2},$y") if (!containsKey(x+1, y+1)) result.add("${x+1},${y+1}") if (!containsKey(x-1, y+1)) result.add("${x-1},${y+1}") if (!containsKey(x-2, y)) result.add("${x-2},$y") if (!containsKey(x-1, y-1)) result.add("${x-1},${y-1}") } return result } fun isBlack(x: Int, y: Int) = hexMap.getOrElse("$x,$y"){"w"} == "b" fun containsKey(x: Int, y: Int) = hexMap.containsKey("$x,$y") fun northEast() { x += 1 y -= 1 } fun east() { x += 2 } fun southEast() { x += 1 y += 1 } fun southWest() { x -= 1 y += 1 } fun west() { x -= 2 } fun northWest() { x -= 1 y -= 1 }
0
Kotlin
0
0
6afa1b890924e9459f37c604b4b67a8f2e95c6f2
3,046
adventofcode2020
MIT License
src/main/kotlin/com/chriswk/aoc/advent2018/Day11.kt
chriswk
317,863,220
false
{"Kotlin": 481061}
package com.chriswk.aoc.advent2018 object Day11 { fun part1(squareSize: Int, gridSerial: Int): Cell { return (1..squareSize - 3).flatMap { y -> (1..squareSize - 3).map { x -> val cell = Cell(x, y) Pair(cell, squarePower(cell, gridSerial, 3)) } }.maxByOrNull { it.second }!!.first } fun part2(squareSize: Int, gridSerial: Int): Pair<Cell, Int> { val cells = (1..squareSize).flatMap { y -> (1..squareSize).map { x -> Cell(y, x) } } val powers = (1..300).map { square -> val max = cells.asSequence().filter { it.y + square < 300 && it.x + square < 300 }.map { it to squarePower(it, gridSerial, square) }.maxByOrNull { it.second }!! square to max } val x = powers.maxByOrNull { it.second.second }!! return x.second.first to x.first } private fun squarePower(topLeft: Cell, gridSerial: Int, squareSize: Int): Int { return (topLeft.y until topLeft.y + squareSize).flatMap { y -> (topLeft.x until topLeft.x + squareSize).map { x -> powerLevel(Cell(x, y), gridSerial) } }.sum() } fun powerLevel(cell: Cell, gridSerial: Int): Int { val rackIdPwr = (cell.initialPowerLevel + gridSerial) * cell.rackId return hundreds(rackIdPwr) - 5 } private fun hundreds(power: Int): Int { return (power % 1000) / 100 } }
116
Kotlin
0
0
69fa3dfed62d5cb7d961fe16924066cb7f9f5985
1,535
adventofcode
MIT License
src/main/kotlin/problems/Day16.kt
PedroDiogo
432,836,814
false
{"Kotlin": 128203}
package problems class Day16(override val input: String) : Problem { override val number: Int = 16 private val packets = BITS.fromString(input).packets override fun runPartOne(): String { return packets .first() .packetVersion() .toString() } override fun runPartTwo(): String { return packets .first() .packetValue() .toString() } class BITS(val packets: List<Packet>) { companion object { fun fromString(str: String): BITS { val packets = mutableListOf<Packet>() val binary = str.convertToBinary() var start = 0 while (!binary.substring(start).isPadding()) { val (packet, read) = createPacket(binary.substring(start)) packets.add(packet) start += read } return BITS(packets) } private fun String.convertToBinary(): String { return this .toCharArray() .joinToString(separator = "") { it.digitToInt(16).toString(2).padStart(4, '0') } } private fun String.isPadding(): Boolean { return this.matches("""0*""".toRegex()) } private fun createPacket(str: String): Pair<Packet, Int> { val typeId = str.substring(3, 6).toInt(2) return when (typeId) { 4 -> LiteralValue.fromString(str) else -> Operator.fromString(str) } } } interface Packet { val version: Int val typeId: Int fun packetVersion(): Int fun packetValue(): Long } data class Operator(override val version: Int, override val typeId: Int, val packets: List<Packet>) : Packet { companion object { fun fromString(str: String): Pair<Operator, Int> { val version = str.substring(0, 3).toInt(2) val typeId = str.substring(3, 6).toInt(2) val lengthTypeId = str.substring(6, 7) val (packets, read) = when (lengthTypeId) { "0" -> createPacketsTotalLength(str.substring(7)) else -> createPacketsNumberOfPackets(str.substring(7)) } return Pair(Operator(version, typeId, packets), 7 + read) } private fun createPacketsNumberOfPackets(str: String): Pair<List<Packet>, Int> { val numberOfPackets = str.substring(0, 11).toInt(2) val packets = mutableListOf<Packet>() var read = 11 for (packetNo in 0 until numberOfPackets) { val (newPacket, packetRead) = BITS.createPacket(str.substring(read)) packets.add(newPacket) read += packetRead } return Pair(packets, read) } private fun createPacketsTotalLength(str: String): Pair<List<Packet>, Int> { val totalLength = str.substring(0, 15).toInt(2) val packets = mutableListOf<Packet>() var read = 15 while (read - 15 < totalLength) { val (newPacket, packetRead) = BITS.createPacket(str.substring(read)) packets.add(newPacket) read += packetRead } return Pair(packets, read) } } override fun packetVersion(): Int { return this.version + this.packets.sumOf { it.packetVersion() } } override fun packetValue(): Long { val packetValues = packets.map { packet -> packet.packetValue() } return when (typeId) { 0 -> packetValues.sumOf { it } 1 -> packetValues.fold(1) { mul, value -> mul * value } 2 -> packetValues.minOf { it } 3 -> packetValues.maxOf { it } 5 -> when (packetValues[0] > packetValues[1]) { true -> 1; else -> 0 } 6 -> when (packetValues[0] < packetValues[1]) { true -> 1; else -> 0 } 7 -> when (packetValues[0] == packetValues[1]) { true -> 1; else -> 0 } else -> 0L } } } data class LiteralValue(override val version: Int, val value: Long) : Packet { override val typeId: Int = 4 override fun packetVersion(): Int { return version } override fun packetValue(): Long { return value } companion object { fun fromString(str: String): Pair<LiteralValue, Int> { val version = str.substring(0, 3).toInt(2) var read = 6 var lastGroup = false val valueStrBuilder = StringBuilder() while (!lastGroup) { lastGroup = str.substring(read, read + 1) == "0" valueStrBuilder.append(str.substring(read + 1, read + 5).toInt(2).toString(16)) read += 5 } val value = valueStrBuilder.toString().toLong(16) return Pair(LiteralValue(version, value), read) } } } } }
0
Kotlin
0
0
93363faee195d5ef90344a4fb74646d2d26176de
5,872
AdventOfCode2021
MIT License
2017-kotlin/src/main/kotlin/com/morninghacks/aoc2017/Day02.kt
whaley
116,508,747
false
null
package com.morninghacks.aoc2017 import kotlin.math.abs /* Part One: The spreadsheet consists of rows of apparently-random numbers. To make sure the recovery process is on the right track, they need you to calculate the spreadsheet's checksum. For each row, determine the difference between the largest value and the smallest value; the checksum is the sum of all of these differences. For example, given the following spreadsheet: 5 1 9 5 7 5 3 2 4 6 8 The first row's largest and smallest values are 9 and 1, and their difference is 8. The second row's largest and smallest values are 7 and 3, and their difference is 4. The third row's difference is 6. In this example, the spreadsheet's checksum would be 8 + 4 + 6 = 18. ======================================================================================================================== Part Two: It sounds like the goal is to find the only two numbers in each row where one evenly divides the other - that is, where the result of the division operation is a whole number. They would like you to find those numbers on each line, divide them, and add up each line's result. For example, given the following spreadsheet: 5 9 2 8 9 4 7 3 3 8 6 5 In the first row, the only two numbers that evenly divide are 8 and 2; the result of this division is 4. In the second row, the two numbers are 9 and 3; the result is 3. In the third row, the result is 2. In this example, the sum of the results would be 4 + 3 + 2 = 9. */ fun checksum(spreadsheet: String, lineSummer: (List<Int>) -> Int = ::minAndMax): Int { val lines = spreadsheet.split("\n") val rows: List<List<Int>> = lines.map { line -> line.split(Regex("""\s""")).map { num -> Integer.valueOf(num) } } return rows.fold(0, { sum: Int, list -> sum + lineSummer(list)}) } fun minAndMax(list: List<Int>): Int { return abs((list.max() ?: 0) - (list.min() ?: 0)) } fun evenlyDivides(list: List<Int>): Int { val pair : Pair<Int,Int>? = allPairs(list).find { it -> it.first % it.second == 0 || it.second % it.first == 0 } return when { pair == null -> 0 pair.first > pair.second -> pair.first / pair.second else -> pair.second / pair.first } } fun <T> allPairs(list: List<T>): List<Pair<T, T>> { val pairs = arrayListOf<Pair<T, T>>() for ((index, left) in list.withIndex()) { if (index != list.size - 1) { list.subList(index + 1, list.size).mapTo(pairs) { left to it } } } return pairs } fun main(args: Array<String>) { val input = """5806 6444 1281 38 267 1835 223 4912 5995 230 4395 2986 6048 4719 216 1201 74 127 226 84 174 280 94 159 198 305 124 106 205 99 177 294 1332 52 54 655 56 170 843 707 1273 1163 89 23 43 1300 1383 1229 5653 236 1944 3807 5356 246 222 1999 4872 206 5265 5397 5220 5538 286 917 3512 3132 2826 3664 2814 549 3408 3384 142 120 160 114 1395 2074 1816 2357 100 2000 112 103 2122 113 92 522 1650 929 1281 2286 2259 1068 1089 651 646 490 297 60 424 234 48 491 245 523 229 189 174 627 441 598 2321 555 2413 2378 157 27 194 2512 117 140 2287 277 2635 1374 1496 1698 101 1177 104 89 542 2033 1724 1197 474 1041 1803 770 87 1869 1183 553 1393 92 105 1395 1000 85 391 1360 1529 1367 1063 688 642 102 999 638 4627 223 188 5529 2406 4980 2384 2024 4610 279 249 2331 4660 4350 3264 242 769 779 502 75 1105 53 55 931 1056 1195 65 292 1234 1164 678 1032 2554 75 4406 484 2285 226 5666 245 4972 3739 5185 1543 230 236 3621 5387 826 4028 4274 163 5303 4610 145 5779 157 4994 5053 186 5060 3082 2186 4882 588 345 67 286 743 54 802 776 29 44 107 63 303 372 41 810 128 2088 3422 111 3312 740 3024 1946 920 131 112 477 3386 2392 1108 2741""" println(checksum(input, ::minAndMax)) println(checksum(input, ::evenlyDivides)) }
0
Kotlin
0
0
16ce3c9d6310b5faec06ff580bccabc7270c53a8
3,788
advent-of-code
MIT License
src/Day05.kt
buongarzoni
572,991,996
false
{"Kotlin": 26251}
fun solveDay05() { val input = readInput("Day05") println(makeHardcodedMap()) solvePart1(input) solvePart2(input) } private fun solvePart1(input: List<String>) { val hardcodedMap = makeHardcodedMap() input.map { line -> val strings = line.split(" ") val quantity = strings[1].toInt() val from = strings[3].toInt() val target = strings[5].toInt() repeat(quantity) { hardcodedMap[target]!!.add(hardcodedMap[from]!!.removeLast()) } } println("Part 1") println(hardcodedMap) } private fun solvePart2(input: List<String>) { val hardcodedMap = makeHardcodedMap() input.map { line -> val strings = line.split(" ") val quantity = strings[1].toInt() val from = strings[3].toInt() val target = strings[5].toInt() val removedItems: ArrayDeque<String> = ArrayDeque() repeat(quantity) { removedItems.add(hardcodedMap[from]!!.removeLast()) } repeat(quantity) { hardcodedMap[target]!!.add(removedItems.removeLast()) } } println("Part 2") println(hardcodedMap) } private fun makeHardcodedMap(): Map<Int, ArrayDeque<String>> { val first: ArrayDeque<String> = ArrayDeque() first.fillWith("WMLF") val second: ArrayDeque<String> = ArrayDeque() second.fillWith("BZVMF") val third: ArrayDeque<String> = ArrayDeque() third.fillWith("HVRSLQ") val fourth: ArrayDeque<String> = ArrayDeque() fourth.fillWith("FSVQPMTJ") val five: ArrayDeque<String> = ArrayDeque() five.fillWith("LSW") val six: ArrayDeque<String> = ArrayDeque() six.fillWith("FVPMRJW") val seven: ArrayDeque<String> = ArrayDeque() seven.fillWith("JQCPNRF") val eight: ArrayDeque<String> = ArrayDeque() eight.fillWith("VHPSZWRB") val nine: ArrayDeque<String> = ArrayDeque() nine.fillWith("BMJCGHZW") return mapOf( 1 to first, 2 to second, 3 to third, 4 to fourth, 5 to five, 6 to six, 7 to seven, 8 to eight, 9 to nine, ) } private fun ArrayDeque<String>.fillWith(string: String) { for (char in string) { this.add(char.toString()) } }
0
Kotlin
0
0
96aadef37d79bcd9880dbc540e36984fb0f83ce0
2,268
AoC-2022
Apache License 2.0
Lab 1/lab1_3/src/main/kotlin/part1/main.kt
katlaang
461,564,362
false
null
fun main(args: Array<String>) { println("Hello World...!") val num = 256656 val a:IntArray = intArrayOf(1,3,5,8,6,4,9)//1+9+81+25 println(firstDigit(num)) println(lastDigit(num)) println(SumOfOddsinArray(a)) println(weightOnPlanentsFunction(180.00, "Mars")) } fun firstDigit(n: Int): Int { var n = n while (n >= 10) n /= 10 return n } fun lastDigit(n: Int): Int { return n % 10 } fun SumOfOddsinArray(a: IntArray): Int { var oddSum = 0 val length=a.size var i= 0 while (i < length) { if (a[i] % 2 != 0) { oddSum += a[i]*a[i] } i++ } return oddSum } fun weightOnPlanentsFunction(input: Double, planet: String): Double { var gravity: Double? = 0.0 gravity = when (planet) { "Venus" -> 0.78 "Mars" -> 0.39 "Jupiter" -> 2.65 "Saturn" -> 1.17 "Uranus" -> 1.05 "Neptune" -> 1.23 else -> { return 0.0} } return input * gravity } fun dollarsToChange
0
Kotlin
0
0
8efb8e9f4170189656d47dc5ffeedb1cd59eb30e
1,034
Mobile_Device_Programing
MIT License
lib/src/main/kotlin/de/linkel/aoc/utils/graph/Graph.kt
norganos
726,350,504
false
{"Kotlin": 162220}
package de.linkel.aoc.utils.graph data class Node<K>( val id: K, val edges: Map<K, Int> ) class Graph<K>( val nodes: Set<Node<K>> ) { private val network = nodes.associateBy { it.id } fun dijkstra(start: K, isDest: (id: K) -> Boolean): List<K>? { val max = this.network.size + 1 val weightMap = network.mapValues { e -> DijkstraNode(e.key, if (e.key == start) 0 else max, null) }.toMutableMap() val points = weightMap.keys.toMutableSet() var dest: DijkstraNode<K>? = null while (points.isNotEmpty()) { val point = points.minBy { weightMap[it]!!.distance } val pointWeightData = weightMap[point]!! points.remove(point) network[point]!!.edges .filter { it.key in points } .forEach { weightMap[it.key] = weightMap[it.key]!!.copy(distance = pointWeightData.distance + it.value, before = point) } if (isDest(point)) { dest = pointWeightData break } } return if (dest != null) { var prev: DijkstraNode<K>? = dest val result = mutableListOf<K>() while (prev != null) { result.add(0, prev.id) prev = prev.before?.let { weightMap[it] } } result.toList() } else { null } } fun dfs(start: K, isDest: (id: K) -> Boolean): List<K>? { return dfsStep(start, isDest, emptyList()) } private fun dfsStep(pos: K, isDest: (id: K) -> Boolean, path: List<K>): List<K>? { return if (isDest(pos)) path else network[pos]!!.edges.entries .sortedBy { it.value } .filter { it.key !in path } .firstNotNullOfOrNull { dfsStep(it.key, isDest, path + listOf(it.key)) } } fun bfs(start: K, isDest: (id: K) -> Boolean): List<K>? { if (isDest(start)) { return listOf(start) } return bfsStep(start, isDest, emptyList()) } private fun bfsStep(pos: K, isDest: (id: K) -> Boolean, path: List<K>): List<K>? { return network[pos]!!.edges.entries .sortedBy { it.value } .filter { it.key !in path } .let { possibleNext -> possibleNext .firstNotNullOfOrNull { if (isDest(it.key)) path + listOf(it.key) else null } ?: possibleNext .firstNotNullOfOrNull { bfsStep(it.key, isDest, path + listOf(it.key)) } } } fun subGraphs(): Iterable<Graph<K>> { val results = mutableListOf<Set<Node<K>>>() val all = network.keys.toMutableSet() while (all.isNotEmpty()) { val first = all.first() val current = mutableSetOf<K>() val queue = mutableListOf(first) while (queue.isNotEmpty()) { val node = queue.removeAt(0) current.add(node) queue.addAll( network[node]!!.edges.keys .filter { it !in current } ) } results.add(current.map { network[it]!! }.toSet()) all.removeAll(current) } return results .map { Graph(it) } } data class DijkstraNode<K>( val id: K, val distance: Int, val before: K? ) } class GraphBuilder<K> { private val nodes = mutableMapOf<K, Map<K, Int>>() fun node(id: K): GraphBuilder<K> { nodes[id] = nodes[id] ?: emptyMap() return this } fun edge(from: K, to: K, weight: Int = 1, bidirectional: Boolean = false): GraphBuilder<K> { nodes[from] = (nodes[from] ?: emptyMap()) + mapOf(to to weight) if (bidirectional) { nodes[to] = (nodes[to] ?: emptyMap()) + mapOf(from to weight) } else { nodes[to] = (nodes[to] ?: emptyMap()) } return this } fun build(): Graph<K> { return Graph( nodes.entries .map { Node(it.key, it.value)} .toSet() ) } }
0
Kotlin
0
0
3a1ea4b967d2d0774944c2ed4d96111259c26d01
4,304
aoc-utils
Apache License 2.0
src/main/kotlin/adventofcode2022/solution/day_4.kt
dangerground
579,293,233
false
{"Kotlin": 51472}
package adventofcode2022.solution import adventofcode2022.util.readDay private const val DAY_NUM = 4 fun main() { Day4(DAY_NUM.toString()).solve() } class Day4(private val num: String) { private val inputText = readDay(num) fun solve() { println("Day $num Solution") println("* Part 1: ${solution1()}") println("* Part 2: ${solution2()}") } fun solution1(): Long { return inputText.lines().map { it.split(",").let { it[0].toIntRange() to it[1].toIntRange() } } .count { it.first.contains(it.second) || it.second.contains(it.first) } .toLong() } private fun String.toIntRange() = this.split("-") .let { IntRange(it[0].toInt(), it[1].toInt()) } private fun IntRange.contains(range: IntRange) = this.contains(range.first) && this.contains(range.last) private fun IntRange.overlaps(range: IntRange) = this.contains(range.first) || this.contains(range.last) fun solution2(): Long { return inputText.lines().map { it.split(",").let { it[0].toIntRange() to it[1].toIntRange() } } .count { it.first.overlaps(it.second) || it.second.overlaps(it.first) } .toLong() } }
0
Kotlin
0
0
f1094ba3ead165adaadce6cffd5f3e78d6505724
1,324
adventofcode-2022
MIT License
2023/src/main/kotlin/Day01.kt
dlew
498,498,097
false
{"Kotlin": 331659, "TypeScript": 60083, "JavaScript": 262}
object Day01 { private val NUMBER_REGEX = Regex("\\d") private val NUMBER_AND_TEXT_REGEX = Regex("(?=(one|two|three|four|five|six|seven|eight|nine|\\d))") fun part1(input: String): Int { return input.splitNewlines() .map { line -> NUMBER_REGEX.findAll(line).map { it.value.toInt() } } .sumCalibrationValues() } fun part2(input: String): Int { return input.splitNewlines() .map { line -> NUMBER_AND_TEXT_REGEX.findAll(line).map { when (val value = it.groups[1]!!.value) { "one" -> 1 "two" -> 2 "three" -> 3 "four" -> 4 "five" -> 5 "six" -> 6 "seven" -> 7 "eight" -> 8 "nine" -> 9 else -> value.toInt() } } } .sumCalibrationValues() } private fun List<Sequence<Int>>.sumCalibrationValues() = this.sumOf { it.first() * 10 + it.last() } }
0
Kotlin
0
0
6972f6e3addae03ec1090b64fa1dcecac3bc275c
947
advent-of-code
MIT License
src/Day03.kt
JonahBreslow
578,314,149
false
{"Kotlin": 6978}
import java.io.File val Char.priority: Int get(): Int { return when (this){ in 'a'..'z' -> this -'a' + 1 in 'A'..'Z' -> this - 'A' + 27 else -> error("Check your input! $this") } } fun main () { fun parseInput(input: String): ArrayList<Pair<String, String>> { val data = File(input).readLines() var parsed: ArrayList<Pair<String, String>> = arrayListOf() for (pack in data){ val size = pack.length / 2 val compartments = pack.chunked(size) val pair = Pair(compartments[0], compartments[1]) parsed.add(pair) } return parsed } fun part1(input: String): Int { val knapsacks = parseInput(input) var res: Int = 0 for (pack in knapsacks){ var f = pack.first.toSet() var b = pack.second.toSet() var item = (f intersect b).first() res += item.priority } return res } fun part2(input: String) : Int { val knapsacks = parseInput(input) var res: Int = 0 var allItems: MutableList<Set<Char>> = mutableListOf() var iter = 0 for (pack in knapsacks){ var bagContents = (pack.first.toSet() union pack.second.toSet()) allItems += bagContents if (iter % 3 == 2){ val common = (allItems[0] intersect allItems[1] intersect allItems[2]).first() res += common.priority allItems = mutableListOf() } ++iter } return res } val testInput: String = "data/day3_test.txt" check(part1(testInput) == 157) check(part2(testInput) == 70) val input: String = "data/day3.txt" println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
c307ff29616f613473768168cc831a7a3fa346c2
1,884
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/aoc2020/HandheldHalting.kt
komu
113,825,414
false
{"Kotlin": 395919}
package komu.adventofcode.aoc2020 import komu.adventofcode.utils.nonEmptyLines fun handheldHalting1(input: String): Int { val vm = VM(Instruction.parseProgram(input)) vm.run() return vm.accumulator } fun handheldHalting2(input: String): Int { for (instructions in Instruction.parseProgram(input).modified()) { val vm = VM(instructions) if (vm.run()) return vm.accumulator } error("no result") } private fun List<Instruction>.modified(): Sequence<List<Instruction>> = sequence { for ((i, instruction) in withIndex()) { val swapped = swap(instruction) ?: continue yield(subList(0, i) + swapped + subList(i + 1, size)) } } private fun swap(instruction: Instruction): Instruction? = when (instruction) { is Instruction.Nop -> Instruction.Jmp(instruction.value) is Instruction.Jmp -> Instruction.Nop(instruction.value) is Instruction.Acc -> null } private class VM(private val instructions: List<Instruction>) { var accumulator = 0 private var pc = 0 private val seen = Array(instructions.size) { false } fun run(): Boolean { while (pc < instructions.size) { if (seen[pc]) return false seen[pc] = true when (val instruction = instructions[pc]) { is Instruction.Acc -> { accumulator += instruction.value pc += 1 } is Instruction.Nop -> pc += 1 is Instruction.Jmp -> pc += instruction.value } } return true } } private sealed class Instruction { class Nop(val value: Int) : Instruction() class Acc(val value: Int) : Instruction() class Jmp(val value: Int) : Instruction() companion object { private val regex = Regex("""(\w+) ([-+]\d+)""") fun parseProgram(program: String): List<Instruction> = program.nonEmptyLines().map { parse(it) } private fun parse(line: String): Instruction { val (_, op, arg) = regex.matchEntire(line)?.groupValues ?: error("invalid line '$line'") val value = arg.toInt() return when (op) { "nop" -> Nop(value) "acc" -> Acc(value) "jmp" -> Jmp(value) else -> error("invalid instruction '$op'") } } } }
0
Kotlin
0
0
8e135f80d65d15dbbee5d2749cccbe098a1bc5d8
2,451
advent-of-code
MIT License
src/day2/Day02.kt
Johnett
572,834,907
false
{"Kotlin": 9781}
package day2 import readInput fun main() { fun part1(input: List<String>): Int { var total = 0 input.forEach { round -> val opponentChoice = round.first() val yourChoice = round.last() total += when (yourChoice) { 'X' -> when (opponentChoice) { 'A' -> 3 'B' -> 0 else -> 6 }.plus(1) 'Y' -> when (opponentChoice) { 'A' -> 6 'B' -> 3 else -> 0 }.plus(2) else -> when (opponentChoice) { 'A' -> 0 'B' -> 6 else -> 3 }.plus(3) } } return total } fun part2(input: List<String>): Int { var total = 0 input.forEach { round -> val opponentChoice = round.first() val yourChoice = round.last() total += when (yourChoice) { 'X' -> when (opponentChoice) { 'A' -> 3 'B' -> 1 else -> 2 }.plus(0) 'Y' -> when (opponentChoice) { 'A' -> 1 'B' -> 2 else -> 3 }.plus(3) else -> when (opponentChoice) { 'A' -> 2 'B' -> 3 else -> 1 }.plus(6) } } return total } // test if implementation meets criteria from the description, like: val testInput = readInput("day2/Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("day2/Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
c8b0ac2184bdad65db7d2f185806b9bb2071f159
1,863
AOC-2022-in-Kotlin
Apache License 2.0
kotlin/aoc2018/src/main/kotlin/Day02.kt
aochsner
160,386,044
false
null
class Day02 { fun solvePart1(rawValues : List<String>): Int { val (twos, threes) = rawValues.fold(Pair(0,0)) { sum, element -> val counts = element.asSequence().groupingBy { it }.eachCount() Pair(sum.first + if (counts.values.contains(2)) 1 else 0, sum.second + if(counts.values.contains(3)) 1 else 0) } return twos * threes } fun solvePart2(rawValues : List<String>): String { return rawValues.mapIndexed { i, outer -> rawValues.drop(i).mapNotNull { val diffIndexes = diffIndexes(outer, it) if (diffIndexes.first == 1) { outer.removeRange(diffIndexes.second, diffIndexes.second+1) } else null } } .flatten() .first() } fun diffIndexes(a: String, b: String): Pair<Int, Int> { var index = 0 val diff = a.mapIndexed { i, char -> if (char != b[i]) { index = i 1 } else 0 }.sum() return Pair(diff, index) } }
0
Kotlin
0
1
7c42ec9c20147c4be056d03e5a1492c137e63615
1,106
adventofcode2018
MIT License
codeforces/polynomial2022/e_slow.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package codeforces.polynomial2022 fun main() { val (n, d) = readInts() val nei = List(n) { mutableListOf<Int>() } repeat(n - 1) { val (u, v) = readInts().map { it - 1 } nei[u].add(v) nei[v].add(u) } val arrays = List(2) { readInts().drop(1).map { it - 1 } } val needed = List(2) { BooleanArray(n).also { it[0] = true } } for (t in 0..1) { for (x in arrays[t]) needed[t][x] = true val stack = IntArray(n) var stackSize = 0 fun dfs(v: Int, p: Int) { stack[stackSize++] = v if (needed[t][v] && stackSize > d) { needed[t xor 1][stack[stackSize - 1 - d]] = true } for (u in nei[v]) if (u != p) { dfs(u, v) } stackSize-- } dfs(0, -1) } var ans = 0 for (t in 0..1) { var travel = 0 fun dfs(v: Int, p: Int): Boolean { var result = needed[t][v] for (u in nei[v]) if (u != p) { if (dfs(u, v)) result = true } if (result) travel++ return result } dfs(0, -1) ans += (travel - 1) * 2 } println(ans) } private fun readStrings() = readln().split(" ") private fun readInts() = readStrings().map { it.toInt() }
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
1,081
competitions
The Unlicense
app/src/main/kotlin/ai/flowstorm/core/dialogue/BasicExtensions.kt
flowstorm
327,536,541
false
null
package ai.flowstorm.core.dialogue import ai.flowstorm.core.language.English import kotlin.math.absoluteValue enum class Article { None, Indefinite, Definite } fun BasicDialogue.article(subj: String, article: Article = Article.Indefinite) = when (language) { "en" -> when (article) { Article.Indefinite -> (if (subj.startsWithVowel()) "an " else "a ") + subj Article.Definite -> "the $subj" else -> subj } else -> subj } fun BasicDialogue.definiteArticle(subj: String) = article(subj, Article.Definite) fun BasicDialogue.empty(subj: String) = when (language) { "en" -> "zero" "de" -> "kein" //TODO male vs. female else -> unsupportedLanguage() } + " $subj" fun BasicDialogue.lemma(word: String) = word fun BasicDialogue.plural(input: String, count: Int = 2) = if (input.isBlank()) { input } else with (if (input.indexOf('+') > 0) input else "$input+") { split(" ").joinToString(" ") { val word = if (it[it.length - 1] == '+' || it[it.length - 1] == '?') it.substring(0, it.length - 1) else it if (count < 1 && it.endsWith('?')) { "" } else if (count.absoluteValue != 1 && it.endsWith('+')) { when (language) { "en" -> English.irregularPlurals.getOrElse(word) { when { word.endsWith("y") && !word.endsWith(listOf("ay", "ey", "iy", "oy", "uy", "yy")) -> word.substring(0, word.length - 1) + "ies" word.endsWith(listOf("s", "sh", "ch", "x", "z", "o")) -> word + "es" else -> word + "s" } } else -> unsupportedLanguage() } } else { word } } } fun BasicDialogue.plural(data: Collection<String>, count: Int = 2) = data.map { plural(it, count) }
1
Kotlin
5
9
53dae04fa113963d632ea4d44e184885271b0322
2,307
core
Apache License 2.0
src/main/kotlin/org/sjoblomj/adventofcode/day4/Day4.kt
sjoblomj
225,241,573
false
null
package org.sjoblomj.adventofcode.day4 import kotlin.streams.toList private const val START = 245182 private const val STOP = 790572 fun day4(): Pair<Int, Int> { val numberOfPasswordsFulfillingFirstCriteria = countPasswordsFulfillingFirstCriteria(START, STOP) val numberOfPasswordsFulfillingSecondCriteria = countPasswordsFulfillingSecondCriteria(START, STOP) println("Number of passwords fulfilling first criteria $numberOfPasswordsFulfillingFirstCriteria") println("Number of passwords fulfilling second criteria $numberOfPasswordsFulfillingSecondCriteria") return numberOfPasswordsFulfillingFirstCriteria to numberOfPasswordsFulfillingSecondCriteria } internal fun countPasswordsFulfillingFirstCriteria(start: Int, stop: Int): Int { return (start .. stop) .filter { digitsAreIncreasingOrEquals(it) } .filter { hasAdjacentEqualDigits(it) } .count() } internal fun countPasswordsFulfillingSecondCriteria(start: Int, stop: Int): Int { return (start .. stop) .filter { digitsAreIncreasingOrEquals(it) } .filter { hasAdjacentEqualDigitsNotPartOfLargerGroup(it) } .count() } internal fun digitsAreIncreasingOrEquals(digits: Int): Boolean { val chars = intToCharList(digits) return (0 until chars.size - 1).none { chars[it] > chars[it + 1] } } internal fun hasAdjacentEqualDigits(digits: Int): Boolean { val chars = intToCharList(digits) return (0 until chars.size - 1).any { chars[it] == chars[it + 1] } } internal fun hasAdjacentEqualDigitsNotPartOfLargerGroup(digits: Int): Boolean { val chars = intToCharList(digits) return (0 until chars.size - 1).any { chars[it] == chars[it + 1] && chars.filter { char -> char == chars[it] }.count() == 2 } } private fun intToCharList(digits: Int) = digits.toString().chars().toList()
0
Kotlin
0
0
f8d03f7ef831bc7e26041bfe7b1feaaadcb40e68
1,758
adventofcode2019
MIT License
14/src/main/kotlin/Reindeers.kt
kopernic-pl
109,750,709
false
null
import com.google.common.io.Resources const val TIMER_INPUT = 2503 @Suppress("UnstableApiUsage") fun main() { val reindeers = Resources.getResource("input.txt") .readText().lineSequence() .map { ReindeerReader.read(it) } val winningReindeerBySpeed = reindeers .map { (name, r) -> name to r.getPosition(TIMER_INPUT) } .sortedByDescending { (_, distance) -> distance } .first() println("Winner by speed: $winningReindeerBySpeed") val leadershipResult = ReindeerLeadershipRaceSimulator(TIMER_INPUT).calculateLeadershipRace(reindeers) val winnerByLeadership = leadershipResult.toList().maxByOrNull { (_, result) -> result } println("Winner by leadership: $winnerByLeadership") } class ReindeerLeadershipRaceSimulator(private val raceTime: Int) { fun calculateLeadershipRace(reindeers: Sequence<Pair<String, Reindeer>>): Map<String, Int> { return (1..raceTime).asSequence() .fold(reindeers.toMap().keys.map { name -> name to 0 }.toMap()) { result, second -> val reindeerResults = reindeers.map { (name, r) -> name to r.getPosition(second) } val maxDistance = reindeerResults.sortedByDescending { (_, distance) -> distance } .first().second val leaders = reindeerResults .filter { (_, distance) -> distance == maxDistance } .map { (name, _) -> name } result.mapValues { (name, score) -> when { leaders.contains(name) -> score + 1 else -> score } } } } } object ReindeerReader { fun read(description: String): Pair<String, Reindeer> { description.split(" ").let { return it[nameIdx] to Reindeer(it[speedIdx].toInt(), it[flyTime].toInt(), it[restTime].toInt()) } } private const val nameIdx = 0 private const val speedIdx = 3 private const val flyTime = 6 private const val restTime = 13 } class Reindeer(private val speed: Int, private val speedTime: Int, private val sleep: Int) { val cycleTime: Int get() = speedTime + sleep internal fun getPositionInLastCycle(timeInLastCycle: Int): Int { return when (timeInLastCycle) { in 0..speedTime -> speed * timeInLastCycle in speedTime + 1..cycleTime -> getPositionInLastCycle(speedTime) else -> throw IllegalArgumentException() } } internal fun fullCycles(time: Int): Int = time / cycleTime internal fun reminderTime(time: Int): Int = time % cycleTime fun getPosition(time: Int): Int { return fullCycles(time) * speed * speedTime + getPositionInLastCycle(reminderTime(time)) } }
0
Kotlin
0
0
06367f7e16c0db340c7bda8bc2ff991756e80e5b
2,815
aoc-2015-kotlin
The Unlicense
src/main/kotlin/dev/shtanko/algorithms/leetcode/ValidPartition.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 /** * 2369. Check if There is a Valid Partition For The Array * @see <a href="https://leetcode.com/problems/check-if-there-is-a-valid-partition-for-the-array/">Source</a> */ fun interface ValidPartition { operator fun invoke(nums: IntArray): Boolean } /** * Approach 1: Top-Down Dynamic Programming */ class ValidPartitionTopDown : ValidPartition { // Memoization map to store the results of subproblems private val memo: MutableMap<Int, Boolean> = HashMap() // Overriding the invoke operator to implement the top-down approach override operator fun invoke(nums: IntArray): Boolean { val n = nums.size // Base case: An empty array is considered a valid partition memo[-1] = true return prefixIsValid(nums, n - 1) } // Determine if the prefix array nums[0 ~ i] has a valid partition private fun prefixIsValid(nums: IntArray, i: Int): Boolean { // Check if the result for the current index is already memoized if (memo.containsKey(i)) { return memo[i]!! } var ans = false // Check the three possibilities for a valid partition if (i > 0 && nums[i] == nums[i - 1]) { // Case 1: Two consecutive equal elements ans = ans or prefixIsValid(nums, i - 2) } if (i > 1 && nums[i] == nums[i - 1] && nums[i - 1] == nums[i - 2]) { // Case 2: Three consecutive equal elements ans = ans or prefixIsValid(nums, i - 3) } if (i > 1 && nums[i] == nums[i - 1] + 1 && nums[i - 1] == nums[i - 2] + 1) { // Case 3: Three consecutive elements in increasing order ans = ans or prefixIsValid(nums, i - 3) } // Memoize the result to avoid redundant computations memo[i] = ans return ans } } /** * Approach 2: Bottom-Up Dynamic Programming */ class ValidPartitionBottomUp : ValidPartition { override operator fun invoke(nums: IntArray): Boolean { val n: Int = nums.size val dp = BooleanArray(n + 1) dp[0] = true // Determine if the prefix array nums[0 ~ i] has a valid partition for (i in 0 until n) { val dpIndex = i + 1 // Check 3 possibilities if (i > 0 && nums[i] == nums[i - 1]) { dp[dpIndex] = dp[dpIndex] or dp[dpIndex - 2] } if (i > 1 && nums[i] == nums[i - 1] && nums[i] == nums[i - 2]) { dp[dpIndex] = dp[dpIndex] or dp[dpIndex - 3] } if (i > 1 && nums[i] == nums[i - 1] + 1 && nums[i] == nums[i - 2] + 2) { dp[dpIndex] = dp[dpIndex] or dp[dpIndex - 3] } } return dp[n] } } /** * Approach 3: Space Optimized Bottom-Up Dynamic Programming */ class ValidPartitionBottomUpSpaceOpt : ValidPartition { override operator fun invoke(nums: IntArray): Boolean { val n: Int = nums.size val dp = BooleanArray(3) dp[0] = true // Determine if prefix array nums[0 ~ i] has a valid partition for (i in 0 until n) { val dpIndex = i + 1 var ans = false // Check 3 possibilities if (i > 0 && nums[i] == nums[i - 1]) { ans = ans or dp[(dpIndex - 2) % 3] } if (i > 1 && nums[i] == nums[i - 1] && nums[i] == nums[i - 2]) { ans = ans or dp[(dpIndex - 3) % 3] } if (i > 1 && nums[i] == nums[i - 1] + 1 && nums[i] == nums[i - 2] + 2) { ans = ans or dp[(dpIndex - 3) % 3] } dp[dpIndex % 3] = ans } return dp[n % 3] } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
4,344
kotlab
Apache License 2.0
Kotlin for Java Developers. Week 5/Games/Task/src/board/BoardImpl.kt
obarcelonap
374,972,699
false
null
package board fun createSquareBoard(width: Int): SquareBoard = CellSquareBoard(width) fun <T> createGameBoard(width: Int): GameBoard<T> = CellGameBoard(createSquareBoard(width)) class CellSquareBoard(override val width: Int) : SquareBoard { private val cells = generateSequence(1) { it + 1 } .take(width) .map { i -> generateSequence(1) { it + 1 } .take(width) .map { j -> Cell(i, j) } .toList() } .toList() override fun getCellOrNull(i: Int, j: Int): Cell? = cells.getOrNull(i - 1)?.getOrNull(j - 1) override fun getCell(i: Int, j: Int): Cell = cells[i - 1][j - 1] override fun getAllCells(): Collection<Cell> = cells.flatten() override fun getRow(i: Int, jRange: IntProgression): List<Cell> = cells[i - 1] .filter { it.j in jRange } .sortedWith(jRange.comparator { it.j }) override fun getColumn(iRange: IntProgression, j: Int): List<Cell> = cells .flatMap { it.filter { cell -> cell.i in iRange && cell.j == j } } .sortedWith(iRange.comparator { it.i }) override fun Cell.getNeighbour(direction: Direction): Cell? { val neighbour = when (direction) { Direction.UP -> copy(i = i - 1) Direction.DOWN -> copy(i = i + 1) Direction.RIGHT -> copy(j = j + 1) Direction.LEFT -> copy(j = j - 1) } return getCellOrNull(neighbour.i, neighbour.j) } private fun <T> IntProgression.comparator(selector: (T) -> Comparable<*>?): Comparator<T> = if (step < 0) compareByDescending(selector) else compareBy(selector) } class CellGameBoard<T>(private val squareBoard: SquareBoard) : GameBoard<T>, SquareBoard by squareBoard { private val cellValues: MutableMap<Cell, T?> = squareBoard.getAllCells() .associateWith { null } .toMutableMap() override fun get(cell: Cell): T? = cellValues[cell] override fun set(cell: Cell, value: T?) { cellValues[cell] = value } override fun filter(predicate: (T?) -> Boolean) = cellValues.filterValues(predicate).keys override fun find(predicate: (T?) -> Boolean) = filter(predicate).firstOrNull() override fun any(predicate: (T?) -> Boolean) = cellValues.values.any(predicate) override fun all(predicate: (T?) -> Boolean) = cellValues.values.all(predicate) }
0
Kotlin
0
0
d79103eeebcb4f1a7b345d29c0883b1eebe1d241
2,457
coursera-kotlin-for-java-developers
MIT License
Word_Ladder_II.kt
xiekch
166,329,519
false
{"C++": 165148, "Java": 103273, "Kotlin": 97031, "Go": 40017, "Python": 22302, "TypeScript": 17514, "Swift": 6748, "Rust": 6579, "JavaScript": 4244, "Makefile": 349}
import java.util.* import kotlin.collections.ArrayList import kotlin.collections.HashMap class Solution { fun findLadders( beginWord: String, endWord: String, wordList: List<String> ): List<List<String>> { val res = ArrayList<List<String>>() val levelMap = HashMap<String, Int>() val allComboDict = HashMap<String, MutableList<String>>() val parents = HashMap<String, MutableList<String>>() val wordLen = beginWord.length if (!wordList.contains(endWord)) return res for (word in wordList) { levelMap[word] = 0 parents[word] = mutableListOf() for (i in 0 until wordLen) { val newWord = word.substring(0, i) + '*' + word.substring(i + 1, wordLen) val transformations = allComboDict.getOrDefault(newWord, ArrayList()) transformations.add(word) allComboDict[newWord] = transformations } } parents[beginWord] = mutableListOf() levelMap[beginWord] = 1 val qu = LinkedList<String>() qu.add(beginWord) while (!qu.isEmpty()) { val word = qu.remove() for (i in 0 until wordLen) { val newWord = word.substring(0, i) + '*' + word.substring(i + 1, wordLen) for (adjacentWord in allComboDict.getOrDefault(newWord, ArrayList())) { if (levelMap[adjacentWord] == 0 || (levelMap[word]?.plus(1) ?: 0 <= levelMap[adjacentWord]!! && !parents[adjacentWord]!!.contains(word)) ) { levelMap[adjacentWord] = (levelMap[word] ?: 0) + 1 // println("$word - $newWord - $adjacentWord") parents[adjacentWord]?.add(word) if (adjacentWord == endWord) { continue } qu.add(adjacentWord) } } } } if (parents[endWord].isNullOrEmpty()) return res // println(parents) backtrack(endWord, parents, mutableListOf(endWord), res) return res } private fun backtrack( word: String, parents: HashMap<String, MutableList<String>>, path: MutableList<String>, res: ArrayList<List<String>> ) { if (parents[word]!!.isEmpty()) { res.add(path.toList()) return } for (i in parents[word] ?: mutableListOf()) { path.add(0, i) backtrack(i, parents, path, res) path.removeAt(0) } } } fun main() { class TestCase(val beginWord: String, val endWord: String, val wordList: List<String>) val solution = Solution() val testCases = arrayOf( TestCase("hit", "cog", listOf("hot", "dot", "dog", "lot", "log", "cog")), TestCase("hit", "log", listOf("hot", "dot", "dog", "lot", "log", "cog")), TestCase("hot", "dog", listOf("hot", "dog")), TestCase("hit", "cog", listOf("hot", "dot", "dog", "lot", "log")), TestCase("red", "tax", listOf("ted", "tex", "red", "tax", "tad", "den", "rex", "pee")) ) for (testCase in testCases) { println( solution.findLadders(testCase.beginWord, testCase.endWord, testCase.wordList) .joinToString("\n") ) println() } }
0
C++
0
0
eb5b6814e8ba0847f0b36aec9ab63bcf1bbbc134
3,481
leetcode
MIT License
src/Day06.kt
hoppjan
573,053,610
false
{"Kotlin": 9256}
fun main() { val testLines = readInput("Day06_test") val testResult1 = part1(testLines) println("test part 1: $testResult1") check(testResult1 == 7) val testResult2 = part2(testLines) println("test part 2: $testResult2") check(testResult2 == 19) val lines = readInput("Day06") println("part 1: ${part1(lines)}") println("part 2: ${part2(lines)}") } private fun part1(input: List<String>) = input.first().let { stream -> for (i in stream.indices.drop(3)) { if ("${stream[i]}${stream[i + 1] }${stream[i + 2]}${stream[i + 3]}".hasNoRepeats()) return@let i + 4 } return 0 } private fun part2(input: List<String>) = input.first().let { stream -> for (i in stream.indices) { if (stream.substring(i, i + 14).hasNoRepeats()) return@let i + 14 } return 0 } private fun String.hasNoRepeats(): Boolean { for (i in indices) if (substring((i + 1)..lastIndex).contains(this[i])) return false return true }
0
Kotlin
0
0
f83564f50ced1658b811139498d7d64ae8a44f7e
1,032
advent-of-code-2022
Apache License 2.0
src/main/kotlin/se/saidaspen/aoc/aoc2016/Day10.kt
saidaspen
354,930,478
false
{"Kotlin": 301372, "CSS": 530}
package se.saidaspen.aoc.aoc2016 import se.saidaspen.aoc.util.* import java.lang.StringBuilder fun main() = Day10.run() object Day10 : Day(2016, 10) { data class Bot(val nr: Int, var low: Bot?, var high: Bot?) { val chips: MutableList<Int> = mutableListOf() fun receive(value: Int) { chips.add(value) } } override fun part1(): Any { val bots = mutableMapOf<Int, Bot>() val outputs = mutableMapOf<Int, Bot>() input.lines() .flatMap { l -> """bot (\d+)""".toRegex().findAll(l) .map { it.groupValues[1] } .distinct() .map { it.toInt() } } .distinct() .map { Bot(it, null, null) } .forEach { bots[it.nr] = it } input.lines().flatMap { l -> """output (\d+)""".toRegex().findAll(l).map { it.groupValues[1] }.distinct().map { it.toInt() } }.distinct().map { Bot(it, null, null) }.forEach { outputs[it.nr] = it } input.lines().filter { !it.contains("goes to") }.forEach { val bot = ints(it)[0] val lowType = it.split(" ")[5] val lowTarget = ints(it)[1] val lowReceiver = if (lowType == "bot") bots[lowTarget] else outputs[lowTarget]!! val highType = it.split(" ")[10] val highTarget = ints(it)[2] val highReceiver = if (highType == "bot") bots[highTarget] else outputs[highTarget]!! bots[bot]!!.low = lowReceiver bots[bot]!!.high = highReceiver } input.lines().filter { it.contains("goes to") }.forEach { val value = ints(it)[0] val bot = ints(it)[1] bots[bot]!!.receive(value) } while(bots.values.any { it.chips.size == 2 }) { val giver = bots.values.first{ it.chips.size == 2} val lowVal = giver.chips.minOrNull()!! val highVal = giver.chips.maxOrNull()!! if (lowVal == 17 && highVal == 61) { return giver.nr } giver.low!!.receive(lowVal) giver.high!!.receive(highVal) giver.chips.clear() } return "" } override fun part2(): Any { val bots = mutableMapOf<Int, Bot>() val outputs = mutableMapOf<Int, Bot>() input.lines().flatMap { l -> """bot (\d+)""".toRegex().findAll(l).map { it.groupValues[1] }.distinct().map { it.toInt() } }.distinct().map { Bot(it, null, null) }.forEach { bots[it.nr] = it } input.lines().flatMap { l -> """output (\d+)""".toRegex().findAll(l).map { it.groupValues[1] }.distinct().map { it.toInt() } }.distinct().map { Bot(it, null, null) }.forEach { outputs[it.nr] = it } input.lines().filter { !it.contains("goes to") }.forEach { val bot = ints(it)[0] val lowType = it.split(" ")[5] val lowTarget = ints(it)[1] val lowReceiver = if (lowType == "bot") bots[lowTarget] else outputs[lowTarget]!! val highType = it.split(" ")[10] val highTarget = ints(it)[2] val highReceiver = if (highType == "bot") bots[highTarget] else outputs[highTarget]!! bots[bot]!!.low = lowReceiver bots[bot]!!.high = highReceiver } input.lines().filter { it.contains("goes to") }.forEach { val value = ints(it)[0] val bot = ints(it)[1] bots[bot]!!.receive(value) } while(bots.values.any { it.chips.size == 2 }) { val giver = bots.values.first{ it.chips.size == 2} val lowVal = giver.chips.minOrNull()!! val highVal = giver.chips.maxOrNull()!! giver.low!!.receive(lowVal) giver.high!!.receive(highVal) giver.chips.clear() } return outputs[0]!!.chips[0] * outputs[1]!!.chips[0] * outputs[2]!!.chips[0] } }
0
Kotlin
0
1
be120257fbce5eda9b51d3d7b63b121824c6e877
4,038
adventofkotlin
MIT License
src/Day06/Day06.kt
suttonle24
573,260,518
false
{"Kotlin": 26321}
package Day06 import readInput fun main() { fun getFirstPacketMarker(input: CharArray): Int { for ((i, char) in input.withIndex()) { if (i > 3) { if (input[i] != input[i-1] && // i input[i] != input[i-2] && // i input[i] != input[i-3] && // i input[i-1] != input[i] && // i-1 input[i-1] != input[i-2] && // i-1 input[i-1] != input[i-3] && // i-1 input[i-2] != input[i] && // i-2 input[i-2] != input[i-1] && // i-2 input[i-2] != input[i-3] && // i-2 input[i-3] != input[i] && // i-3 input[i-3] != input[i-1] && // i-3 input[i-3] != input[i-2]) { // i-3 return i+1; } } } return 0; } fun hasDuplicates(list: List<Char>): Boolean { return list.size != list.distinct().count(); } fun msgDetector(input: CharArray, lookback: Int): Int { var charIndex = 0; for ((i, char) in input.withIndex()) { if (i > lookback) { val checkSet = input.slice(IntRange(i - lookback + 1, i)); if(!hasDuplicates(checkSet)) { charIndex = i; break; } } } return if(charIndex != 0) { charIndex + 1; } else { charIndex; } } fun part1(input: List<String>): Int { val firstPacketMarker: Int = getFirstPacketMarker(input.get(0).toCharArray()); println(firstPacketMarker); return input.size } fun part2(input: List<String>): Int { val firstMsgMarker = msgDetector(input.get(0).toCharArray(), 14); println(firstMsgMarker); return input.size } val input = readInput("Day06/Day06input") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
039903c7019413d13368a224fd402625023d6f54
2,037
AoC-2022-Kotlin
Apache License 2.0
main/src/main/kotlin/siliconsloth/miniruler/planner/Planner.kt
SiliconSloth
229,996,790
false
null
package siliconsloth.miniruler.planner import siliconsloth.miniruler.* /** * Simple action planner that uses a backtracking breadth-first search to find the shortest action sequence * from arbitrary states to a fixed goal. * * @param goal the goal state * @param actions all actions that can be taken by the agent */ class Planner(val goal: State, val actions: List<Action>) { // cost is length of path from current state to goal via this action. data class ActionProposal(val action: Action?, val cost: Int, val resourceTargets: List<ResourceTarget>, val source: State?) // cost is length of shortest path to goal from this state. data class StateAndCost(val state: State, val cost: Int) val chosenActions = mutableMapOf(goal to ActionProposal(null, 0, listOf(), goal)) // Used as a FIFO queue so that the lowest-cost states are always visited next. val frontier = mutableListOf(StateAndCost(goal, 0)) val finalized = mutableSetOf<State>() // Returns null if already at goal or the goal is unreachable from given state. fun chooseAction(state: State): ActionProposal = chosenActions.filter { it.key.supersetOf(state) && it.key in finalized }.values.minBy { it.cost } ?: searchTo(state) // Continue the breadth-first search until (a superset of) the given state is visited. // Returns the chosen action for that state, or a null action if the search terminates without reaching the state. private fun searchTo(target: State): ActionProposal { var result: ActionProposal? = null var step = 0 while (result == null && frontier.any()) { val current = frontier.minBy { it.cost }!! finalized.add(current.state) if (current.state.supersetOf(target)) { result = chosenActions[current.state] break } frontier.remove(current) if (step % 1000 == 0) { println(current.cost) } step++ // Try unapplying every action to see if it ends up in a valid, novel state. // If the resulting state is a subset of an already visited state, we can discard this action edge; // in a BFS if a superstate has already been visited then a shorter (or equal) path has already been found. actions.forEach { act -> val before = act.unapply(current.state) if (before.isValid() && !finalized.any { it.supersetOf(before) }) { val actCost = current.cost + act.cost(before, current.state) val cheapest = chosenActions.filter { it.key.supersetOf(before) }.values.map { it.cost }.min() if (cheapest?.let { it > actCost } != false) { chosenActions[before] = ActionProposal(act, actCost, act.resourceTarget(before, current.state), current.state) frontier.add(StateAndCost(before, actCost)) } } } } return result ?: ActionProposal(null, -1, listOf(), null) } fun printPlan(start: State) { var current: State? = start while (current != null && !goal.supersetOf(current)) { val prop = chosenActions.filter { it.key.supersetOf(current!!) && it.key in finalized }.values .minBy { it.cost } ?: searchTo(current) println(prop.action) current = prop.source } } }
0
Kotlin
0
0
2c30a2a9d92385f2015b63f1fadb683e3edcddfc
3,545
MiniRuler
MIT License
src/day-9/part-2/solution-day-9-part-2.kts
d3ns0n
572,960,768
false
{"Kotlin": 31665}
import java.io.File import kotlin.math.abs class Coordinate(val x: Int = 0, val y: Int = 0) { fun moveRight() = Coordinate(x + 1, y) fun moveLeft() = Coordinate(x - 1, y) fun moveUp() = Coordinate(x, y + 1) fun moveDown() = Coordinate(x, y - 1) fun isTouching(other: Coordinate) = abs(x - other.x) <= 1 && abs(y - other.y) <= 1 override fun equals(other: Any?): Boolean { return other is Coordinate && x == other.x && y == other.y } override fun hashCode(): Int { var result = x result = 31 * result + y return result } } var knotLog: Array<MutableList<Coordinate>> = Array(10) { mutableListOf(Coordinate()) } fun moveHead(direction: String, distance: Int) { for (i in 1..distance) { when (direction) { "R" -> knotLog[0].add(knotLog[0].last().moveRight()) "L" -> knotLog[0].add(knotLog[0].last().moveLeft()) "U" -> knotLog[0].add(knotLog[0].last().moveUp()) "D" -> knotLog[0].add(knotLog[0].last().moveDown()) } moveKnotsIfNecessary() } } fun moveKnotsIfNecessary() { for (i in 1..9) { val knot = knotLog[i].last() val previousKnot = knotLog[i - 1].last() if (!knot.isTouching(previousKnot)) { var tempKnot = knot if (previousKnot.x != knot.x) { tempKnot = if (previousKnot.x - knot.x > 0) tempKnot.moveRight() else tempKnot.moveLeft() } if (previousKnot.y != knot.y) { tempKnot = if (previousKnot.y - knot.y > 0) tempKnot.moveUp() else tempKnot.moveDown() } knotLog[i].add(tempKnot) } else { knotLog[i].add(knot) } } } fun process(line: String) { val (direction, distance) = line.split(" ", limit = 2) moveHead(direction, distance.toInt()) } File("../input.txt").readLines() .forEach { process(it) } val tailLogDistinctSize = knotLog[9].distinct().size println(tailLogDistinctSize) assert(tailLogDistinctSize == 2541)
0
Kotlin
0
0
8e8851403a44af233d00a53b03cf45c72f252045
2,095
advent-of-code-22
MIT License
src/medium/_8StringToInteger.kt
ilinqh
390,190,883
false
{"Kotlin": 382147, "Java": 32712}
package medium class _8StringToInteger { class Solution { fun myAtoi(str: String): Int { val automaton = Automaton() for (item in str) { automaton[item] } return (automaton.sign * automaton.ans).toInt() } class Automaton { var sign = 1 var ans = 0L private var state = "start" private val map = object : HashMap<String, Array<String>>() { init { put("start", arrayOf("start", "sign", "in_number", "end")) put("sign", arrayOf("end", "end", "in_number", "end")) put("in_number", arrayOf("end", "end", "in_number", "end")) put("end", arrayOf("end", "end", "end", "end")) } } operator fun get(c: Char) { state = map[state]!![getCol(c)] if (state == "sign") { sign = if (c == '+') { 1 } else { -1 } } else if (state == "in_number") { ans = ans * 10 + c.code.toLong() - '0'.code.toLong() ans = if (sign == 1) { Math.min(ans, Int.MAX_VALUE.toLong()) } else { Math.min(ans, -Int.MIN_VALUE.toLong()) } } } private fun getCol(c: Char): Int { if (c == ' ') { return 0 } else if (c == '+' || c == '-') { return 1 } else if (Character.isDigit(c)) { return 2 } return 3 } } } // Best 状态机思想 class BestSolution { fun myAtoi(str: String): Int { val automaton = Automaton() val length = str.length for (i in 0 until length) { automaton[str[i]] } return (automaton.sign * automaton.ans).toInt() } } class Automaton { var sign = 1 var ans: Long = 0 private var state = "start" private val table = object : HashMap<String, Array<String>>() { init { put("start", arrayOf("start", "signed", "in_number", "end")) put("signed", arrayOf("end", "end", "in_number", "end")) put("in_number", arrayOf("end", "end", "in_number", "end")) put("end", arrayOf("end", "end", "end", "end")) } } operator fun get(c: Char) { state = table[state]!![getCol(c)] if ("in_number" == state) { ans = ans * 10 + c.code.toLong() - '0'.code.toLong() ans = if (sign == 1) Math.min(ans, Int.MAX_VALUE.toLong()) else Math.min(ans, -Int.MIN_VALUE.toLong()) } else if ("signed" == state) { sign = if (c == '+') 1 else -1 } } private fun getCol(c: Char): Int { if (c == ' ') { return 0 } if (c == '+' || c == '-') { return 1 } return if (Character.isDigit(c)) { 2 } else 3 } } }
0
Kotlin
0
0
8d2060888123915d2ef2ade293e5b12c66fb3a3f
3,397
AlgorithmsProject
Apache License 2.0
baparker/08/main.kt
VisionistInc
433,099,870
false
{"Kotlin": 91599, "Go": 87605, "Ruby": 65600, "Python": 21104}
import java.io.File fun brokenTrash1() { var counter = 0 File("input.txt").forEachLine { it.split(" | ")[1] .split(" ") .forEach({ when (it.length) { 2, 3, 4, 7 -> counter++ } }) } println(counter) } fun brokenTrash2() { var counter = 0 File("input.txt").forEachLine { var codeList: MutableList<List<Char>> = MutableList(10) { listOf() } val input = it.split(" | ") val patterns = input[0].split(" ") val fives: MutableList<String> = mutableListOf() val sixes: MutableList<String> = mutableListOf() // Set the freebies and sort the lengths of 5 and 6 patterns.forEach({ when (it.length) { 2 -> codeList.set(1, it.toCharArray().sorted()) 3 -> codeList.set(7, it.toCharArray().sorted()) 4 -> codeList.set(4, it.toCharArray().sorted()) 5 -> fives.add(it) 6 -> sixes.add(it) 7 -> codeList.set(8, it.toCharArray().sorted()) } }) // Figure out the codes of length 6 sixes.forEach({ sixCode -> val sixCodeAsCharList = sixCode.toCharArray().sorted() if (codeList.get(4).intersect(sixCodeAsCharList).size == codeList.get(4).size) { codeList.set(9, sixCodeAsCharList) } else if (codeList.get(7).intersect(sixCodeAsCharList).size == codeList.get(7).size) { codeList.set(0, sixCodeAsCharList) } else { codeList.set(6, sixCodeAsCharList) } }) // Figure out the codes of length 5 fives.forEach({ fiveCode -> val fiveCodeAsCharList = fiveCode.toCharArray().sorted() if (codeList.get(7).intersect(fiveCodeAsCharList).size == codeList.get(7).size) { codeList.set(3, fiveCodeAsCharList) } else if (codeList.get(6).intersect(fiveCodeAsCharList).size == fiveCodeAsCharList.size ) { codeList.set(5, fiveCodeAsCharList) } else { codeList.set(2, fiveCodeAsCharList) } }) val codeListAsStrings = codeList.map({ code -> code.joinToString(separator = "") }) var outputString = "" input[1].split(" ") .forEach({ output -> outputString += codeListAsStrings.indexOf( output.toCharArray().sorted().joinToString(separator = "") ) }) counter += outputString.toInt() } println(counter) } fun main() { brokenTrash1() brokenTrash2() }
0
Kotlin
4
1
e22a1d45c38417868f05e0501bacd1cad717a016
2,805
advent-of-code-2021
MIT License
src/main/kotlin/g1001_1100/s1044_longest_duplicate_substring/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1001_1100.s1044_longest_duplicate_substring // #Hard #String #Binary_Search #Sliding_Window #Hash_Function #Rolling_Hash #Suffix_Array // #2023_05_27_Time_592_ms_(100.00%)_Space_106.4_MB_(100.00%) class Solution { private lateinit var hsh: LongArray private lateinit var pw: LongArray private val cnt: Array<MutableList<Int>?> = arrayOfNulls(26) fun longestDupSubstring(s: String): String { val n = s.length val base = 131 for (i in 0..25) { cnt[i] = ArrayList() } hsh = LongArray(n + 1) pw = LongArray(n + 1) pw[0] = 1 for (j in 1..n) { hsh[j] = (hsh[j - 1] * base + s[j - 1].code.toLong()) % MOD pw[j] = pw[j - 1] * base % MOD cnt[s[j - 1].code - 'a'.code]!!.add(j - 1) } var ans = "" for (i in 0..25) { if (cnt[i]!!.isEmpty()) { continue } val idx: MutableList<Int>? = cnt[i] var set: MutableSet<Long?> var lo = 1 var hi = n - idx!![0] while (lo <= hi) { val len = (lo + hi) / 2 set = HashSet() var found = false for (nxt in idx) { if (nxt + len <= n) { val substrHash = getSubstrHash(nxt, nxt + len) if (set.contains(substrHash)) { found = true if (len + 1 > ans.length) { ans = s.substring(nxt, nxt + len) } break } set.add(substrHash) } } if (found) { lo = len + 1 } else { hi = len - 1 } } } return ans } private fun getSubstrHash(l: Int, r: Int): Long { return (hsh[r] - hsh[l] * pw[r - l] % MOD + MOD) % MOD } companion object { private const val MOD = 1e9.toInt() + 7 } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
2,160
LeetCode-in-Kotlin
MIT License
project-euler/kotlin/src/test/kotlin/dev/mikeburgess/euler/problems/Problems00x.kt
mddburgess
469,258,868
false
{"Kotlin": 47737}
package dev.mikeburgess.euler.problems import dev.mikeburgess.euler.extensions.* import dev.mikeburgess.euler.math.lcm import dev.mikeburgess.euler.sequences.fibonacciSequence import dev.mikeburgess.euler.sequences.primeSequence import org.assertj.core.api.Assertions.assertThat import kotlin.test.Test class Problems00x { /** * Problem 1 * * If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 * and 9. The sum of these multiples is 23. * * Find the sum of all the multiples of 3 or 5 below 1000. */ @Test fun `Problem 1`() { val result = (1 until 1000L) .filter { it % 3 == 0L || it % 5 == 0L } .sum() assertThat(result).isEqualTo(233168L) } /** * Problem 2 * * Each new term in the Fibonacci sequence is generated by adding the previous two terms. By * starting with 1 and 2, the first 10 terms will be: * * 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... * * By considering the terms in the Fibonacci sequence whose values do not exceed four million, * find the sum of the even-valued terms. */ @Test fun `Problem 2`() { val result = fibonacciSequence() .takeWhile { it < 4_000_000 } .filter { it.isEven() } .sum() assertThat(result).isEqualTo(4613732L) } /** * Problem 3 * * The prime factors of 13195 are 5, 7, 13 and 29. * * What is the largest prime factor of the number 600851475143? */ @Test fun `Problem 3`() { var number = 600_851_475_143 var factor = 2L while (factor < number) { when { number % factor == 0L -> number /= factor else -> factor++ } } assertThat(factor).isEqualTo(6857L) } /** * Problem 4 * * A palindromic number reads the same both ways. The largest palindrome made from the product * of two 2-digit numbers is 9009 = 91 × 99. * * Find the largest palindrome made from the product of two 3-digit numbers. */ @Test fun `Problem 4`() { val result = (100..999L) .associateWith { it..999L } .flatMap { entry -> entry.value.map { entry.key * it } } .filter { it.isPalindrome() } .maxOf { it } assertThat(result).isEqualTo(906609L) } /** * Problem 5 * * 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without * any remainder. * * What is the smallest positive number that is evenly divisible by all of the numbers from * 1 to 20? */ @Test fun `Problem 5`() { val result = (1..20L) .reduce { x, y -> lcm(x, y) } assertThat(result).isEqualTo(232792560L) } /** * Problem 6 * * The sum of the squares of the first ten natural numbers is, * * 1^2 + 2^2 + ... + 10^2 = 385 * * The square of the sum of the first ten natural numbers is, * * (1 + 2 + ... + 10)^2 = 552 = 3025 * * Hence the difference between the sum of the squares of the first ten natural numbers and the * square of the sum is 3025 − 385 = 2640. * * Find the difference between the sum of the squares of the first one hundred natural numbers * and the square of the sum. */ @Test fun `Problem 6`() { val sumOfSquares = (1..100L).sumOf { it.squared() } val squareOfSums = (1..100L).sum().squared() val result = squareOfSums - sumOfSquares assertThat(result).isEqualTo(25164150L) } /** * Problem 7 * * By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime * is 13. * * What is the 10,001st prime number? */ @Test fun `Problem 7`() { val result = primeSequence() .take(10001) .last() assertThat(result).isEqualTo(104743L) } /** * Problem 8 * * The four adjacent digits in the 1000-digit number that have the greatest product are * 9 × 9 × 8 × 9 = 5832. * * Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. * What is the value of this product? */ @Test fun `Problem 8`() { val number = "73167176531330624919225119674426574742355349194934" + "96983520312774506326239578318016984801869478851843" + "85861560789112949495459501737958331952853208805511" + "12540698747158523863050715693290963295227443043557" + "66896648950445244523161731856403098711121722383113" + "62229893423380308135336276614282806444486645238749" + "30358907296290491560440772390713810515859307960866" + "70172427121883998797908792274921901699720888093776" + "65727333001053367881220235421809751254540594752243" + "52584907711670556013604839586446706324415722155397" + "53697817977846174064955149290862569321978468622482" + "83972241375657056057490261407972968652414535100474" + "82166370484403199890008895243450658541227588666881" + "16427171479924442928230863465674813919123162824586" + "17866458359124566529476545682848912883142607690042" + "24219022671055626321111109370544217506941658960408" + "07198403850962455444362981230987879927244284909188" + "84580156166097919133875499200524063689912560717606" + "05886116467109405077541002256983155200055935729725" + "71636269561882670428252483600823257530420752963450" val result = (13..number.length) .map { number.subSequence(it - 13, it) } .maxOf { it.chars() .mapToLong { c -> c - '0'.code.toLong() } .reduce(1) { x, y -> x * y } } assertThat(result).isEqualTo(23514624000L) } /** * Problem 9 * * A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, * * a^2 + b^2 = c^2 * * For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. * * There exists exactly one Pythagorean triplet for which a + b + c = 1000. * Find the product abc. */ @Test fun `Problem 9`() { val result = (1..332L) .flatMap { a -> LongRange(a + 1, (1000 - a) / 2).map { b -> a to b to 1000 - a - b } } .first { it.isPythagorean() } .product() assertThat(result).isEqualTo(31875000L) } }
0
Kotlin
0
0
9ad8f26583b204e875b07782c8d09d9d8b404b00
6,811
code-kata
MIT License
src/main/kotlin/2021/Day6.kt
mstar95
317,305,289
false
null
package `2021` import days.Day class Day6 : Day(6) { override fun partOne(): Any { val input = inputString.split(",").map { it.toInt() } val grouped = input.groupBy { it }.mapValues { it.value.size.toLong() } var fishes = Fishes(grouped.toMutableMap(), mutableMapOf()) repeat(256) { fishes = runFast(fishes, it) // println("After $it $fishes") } //372300 return fishes.size() } override fun partTwo(): Any { val input = inputString.split(",").map { it.toInt() } val grouped = input.groupBy { it }.mapValues { it.value.size.toLong() } var fishes = Fishes(grouped.toMutableMap(), mutableMapOf()) repeat(256) { fishes = runFast(fishes, it) // println("After $it $fishes") } //372300 return fishes.size() } fun run(fishes: List<Int>): List<Int> { var kids = 0 val newFishes = fishes.map { if (it == 0) { kids++ 6 } else it - 1 } return newFishes + (0 until kids).map { 8 }.toList() } fun runFast(fishes: Fishes, day: Int): Fishes { val dayOfWeek = day % 7 fishes.children[dayOfWeek]?.let { fishes.children.remove(day, dayOfWeek) val parents = fishes.parents[(dayOfWeek + 2) % 7] ?: 0 fishes.parents[(dayOfWeek + 2) % 7] = parents + it } fishes.getNewChildren(day)?.let { fishes.addChildren(day, it) } return fishes } data class Fishes(val parents: MutableMap<Int, Long>, val children: MutableMap<Int, Long>) { fun addChildren(day: Int, number: Long) { val count = children.getOrDefault(day, 0) children.put(day % 7, count + number) } fun getNewChildren(day: Int): Long? = parents.get(day % 7) fun size() = parents.map { it.value }.sum() + children.map { it.value }.sum() } }
0
Kotlin
0
0
ca0bdd7f3c5aba282a7aa55a4f6cc76078253c81
2,008
aoc-2020
Creative Commons Zero v1.0 Universal
games-dsl/common/src/main/kotlin/net/zomis/games/components/grids/GridTransformations.kt
Zomis
125,767,793
false
{"Kotlin": 1346310, "Vue": 212095, "JavaScript": 43020, "CSS": 4513, "HTML": 1459, "Shell": 801, "Dockerfile": 348}
package net.zomis.games.components.grids import net.zomis.Best data class Position(val x: Int, val y: Int, val sizeX: Int, val sizeY: Int) { fun next(): Position? { if (x == sizeX - 1) { return if (y == sizeY - 1) null else Position(0, y + 1, sizeX, sizeY) } return Position(this.x + 1, this.y, this.sizeX, this.sizeY) } internal fun rotate(): Position = Position(this.sizeY - 1 - this.y, this.x, this.sizeY, this.sizeX) internal fun flipX(): Position = Position(this.sizeX - 1 - this.x, this.y, this.sizeX, this.sizeY) internal fun flipY(): Position = Position(this.x, this.sizeY - 1 - this.y, this.sizeX, this.sizeY) fun transform(transformation: Transformation): Position = transformation.transform(this) } enum class TransformationType(val transforming: (Position) -> Position, val reverse: (Position) -> Position) { FLIP_X(Position::flipX, Position::flipX), FLIP_Y(Position::flipY, Position::flipY), ROTATE(Position::rotate, { start -> start.rotate().rotate().rotate() }), ; } enum class Transformation(private val transformations: List<TransformationType>) { // FLIP_XY with matrix (0, 1) (1, 0) is possible by using FLIP_X / FLIP_Y with rotation. NO_CHANGE(listOf()), FLIP_X(listOf(TransformationType.FLIP_X)), FLIP_Y(listOf(TransformationType.FLIP_Y)), ROTATE_90_CLOCKWISE(listOf(TransformationType.ROTATE)), ROTATE_180(listOf(TransformationType.ROTATE, TransformationType.ROTATE)), ROTATE_90_ANTI_CLOCKWISE(listOf(TransformationType.ROTATE, TransformationType.ROTATE, TransformationType.ROTATE)), ROTATE_90_FLIP_X(listOf(TransformationType.ROTATE, TransformationType.FLIP_X)), ROTATE_90_FLIP_Y(listOf(TransformationType.ROTATE, TransformationType.FLIP_Y)), ; fun transform(position: Position): Position { return transformations.fold(position) { pos, trans -> trans.transforming(pos) } } fun reverseTransform(position: Position): Position { return transformations.reversed().fold(position) { pos, trans -> trans.reverse(pos) } } private val referencePoints = arrayOf( Position(3, 2, 5, 5), Position(4, 0, 5, 5) ) fun apply(transformation: Transformation): Transformation { val simplestTransformation = Transformation.values().filter { result -> referencePoints.all {p -> transformation.transform(this.transform(p)) == result.transform(p) } } return simplestTransformation.single() } } private fun <T> Grid<T>.originalPossibleTransformations(): MutableSet<Transformation> { val possibleTransformations = Transformation.values().toMutableSet() if (sizeX != sizeY) { // Rotating 90 or 270 degrees only works if both width or height is the same possibleTransformations.remove(Transformation.ROTATE_90_CLOCKWISE) possibleTransformations.remove(Transformation.ROTATE_90_ANTI_CLOCKWISE) } return possibleTransformations } fun <T> Grid<T>.standardizedTransformation(valueFunction: (T) -> Int): Transformation { // keep a Set<Transformation>, start with all of them // loop through Transformations and find ones with the extremes // the goal is that of all the possible transformations, the result should be the one with the lowest/highest value // start in the possible fields for the target map upper-left corner // then continue, line by line, beginning with increasing X and then increase Y val possibleTransformations = originalPossibleTransformations() var position: Position? = Position(0, 0, sizeX, sizeY) while (possibleTransformations.size > 1 && position != null) { val best = Best<Transformation> { transformation -> val originalPos = transformation.reverseTransform(position!!) val originalT = get(originalPos.x, originalPos.y) valueFunction(originalT).toDouble() } possibleTransformations.forEach { best.next(it) } possibleTransformations.retainAll(best.getBest()) position = position.next() } val transformation = possibleTransformations.first() // map can be symmetric so don't use .single return transformation } fun <T> Grid<T>.symmetryTransformations(equalsFunction: (T, T) -> Boolean): Set<Transformation> { val possibleTransformations = originalPossibleTransformations() return possibleTransformations.filter { transformation -> positions().all { pos -> val other = transformation.transform(pos) equalsFunction(get(pos.x, pos.y), get(other.x, other.y)) } }.toSet() } fun <T> Grid<T>.transformed(transformation: Transformation): Grid<T> { return GridImpl(sizeX, sizeY) { x, y -> val pos = Position(x, y, sizeX, sizeY) val oldPos = transformation.reverseTransform(pos) get(oldPos.x, oldPos.y) } } fun <T> Grid<T>.transform(transformation: Transformation) { val rotated = transformed(transformation) (0 until sizeY).forEach {y -> (0 until sizeX).forEach {x -> set(x, y, rotated.get(x, y)) } } } fun <T> Grid<T>.positions(): Sequence<Position> { return (0 until sizeY).asSequence().flatMap { y -> (0 until sizeX).asSequence().map { x -> Position(x, y, sizeX, sizeY) } } } fun <T> Grid<T>.standardize(valueFunction: (T) -> Int) { this.transform(this.standardizedTransformation(valueFunction)) }
89
Kotlin
5
17
dd9f0e6c87f6e1b59b31c1bc609323dbca7b5df0
5,525
Games
MIT License
kotlin/src/katas/kotlin/leetcode/optimal_utilisation/OptimalUtilisation.kt
dkandalov
2,517,870
false
{"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221}
package katas.kotlin.leetcode.optimal_utilisation import datsok.shouldEqual import org.junit.Test class OptimalUtilisationTests { @Test fun examples() { findOptimalPairs( a = listOf(Item(1, 2), Item(2, 4), Item(3, 6)), b = listOf(Item(1, 2)), target = 7 ) shouldEqual listOf(Pair(2, 1)) findOptimalPairs( a = listOf(Item(1, 3), Item(2, 5), Item(3, 7), Item(4, 1)), b = listOf(Item(1, 2), Item(2, 3), Item(3, 4), Item(4, 5)), target = 10 ) shouldEqual listOf(Pair(2, 4), Pair(3, 2)) } } private fun findOptimalPairs(a: List<Item>, b: List<Item>, target: Int): List<Pair<Int, Int>> { val sortedB = b.sortedBy { it.value } var max = Int.MIN_VALUE val maxIds = ArrayList<Pair<Int, Int>>() a.forEach { item1 -> val targetB = Item(-1, target - item1.value) val i = sortedB.binarySearch(targetB, Comparator { o1: Item, o2: Item -> o1.value.compareTo(o2.value) }) val item2 = if (i >= 0) { sortedB[i] } else { val j = -i - 2 if (j < 0) null else sortedB[j] } if (item2 != null) { val sum = item1.value + item2.value if (sum <= target) { if (sum > max) { max = sum maxIds.clear() } if (sum >= max) { maxIds.add(Pair(item1.id, item2.id)) } } } } return maxIds } private data class Item(val id: Int, val value: Int)
7
Roff
3
5
0f169804fae2984b1a78fc25da2d7157a8c7a7be
1,610
katas
The Unlicense
src/Day09.kt
i-tatsenko
575,595,840
false
{"Kotlin": 90644}
import kotlin.math.abs data class Point(val x: Int, val y: Int) { fun move(direction: String): Point { return when (direction) { "R", ">" -> Point(x, y + 1) "L", "<" -> Point(x, y - 1) "U", "^" -> Point(x + 1, y) else -> Point(x - 1, y) } } fun distance(other: Point): Int = abs(x - other.x) + y - other.y fun inBounds(maxValidX: Int, maxValidY: Int): Boolean = x > -1 && x <= maxValidX && y > -1 && y <= maxValidY // fun keepUp(to: Point): Point { // if (abs(x - to.x) < 2 && abs(y - to.y) < 2) { // return this // } // val newX = if (abs(x - to.x) > 1) if (x < to.x) x + 1 else x - 1 else x // val newY = if (abs(y - to.y) > 1) if (y < to.y) y + 1 else y - 1 else y // return Point(newX, newY) // } fun keepUp(to: Point): Point { val xDiff = x - to.x val yDiff = y - to.y if (abs(xDiff) < 2 && abs(yDiff) < 2) { return this } if (abs(xDiff) == 2 && abs(yDiff) == 2) { val newX = if (to.x > x) x + 1 else x - 1 val newY = if (to.y > y) y + 1 else y - 1 return Point(newX, newY) } if (x == to.x || abs(yDiff) > abs(xDiff)) { return Point(to.x, if (y < to.y) to.y - 1 else to.y + 1) } return Point(if (x < to.x) to.x - 1 else to.x + 1, to.y) } operator fun plus(other: Point): Point = Point(x + other.x, y + other.y) } val MutableList<Point>.tail: Point get() = this.last() var MutableList<Point>.head: Point get() = this.first() set(p) { this[0] = p } fun MutableList<Point>.head() = this.first() fun main() { fun part1(input: List<String>, knotsCount: Int, boardRows: Int = 5, bordColumns: Int = 6, doPrintBoard: Boolean = false): Int { val tailVisited = mutableSetOf<Point>() val rope = mutableListOf<Point>() for (index in 1..knotsCount) { rope.add(Point(0, 0)) } tailVisited.add(rope.tail) val printBoard = { for (x in boardRows - 1 downTo 0) { println() for (y in 0 until bordColumns) { val point = Point(x, y) val indexOf = rope.indexOf(point) if (rope.head() == point) { print('H') } else if(indexOf != -1) { print(indexOf) } else if (rope.tail == point) { print('T') } else if (tailVisited.contains(point)) { print('#') } else { print(".") } } } println() println() } input.forEach { val split = it.split(" ") val direction = split[0] val distance = split[1].toInt() for (move in 1..distance) { rope.head = rope.head.move(direction) for (knot in 1 until knotsCount) { rope[knot] = rope[knot].keepUp(rope[knot - 1]) } tailVisited.add(rope.tail) if (doPrintBoard) printBoard() } } return tailVisited.size } fun part2(input: List<String>): Int { return part1(input, 10, 21, 26, true) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day09_test") val testInput21 = readInput("Day09_test_2") check(part1(testInput, 2) == 13) // check(part2(testInput2) == 9) check(part2(testInput21) == 36) val input = readInput("Day09") println(part1(input, 2)) check(part1(input, 2) == 6190) println(part2(input)) }
0
Kotlin
0
0
0a9b360a5fb8052565728e03a665656d1e68c687
3,867
advent-of-code-2022
Apache License 2.0
kt/factor.main.kts
dfings
31,622,045
false
{"Go": 12328, "Kotlin": 12241, "Clojure": 11585, "Python": 9457, "Haskell": 8314, "Dart": 5990, "Rust": 5389, "TypeScript": 4158, "Elixir": 3093, "F#": 2745, "C++": 1608}
fun primeFactors(value: Long): Sequence<Long> { fun recur(n: Long, i: Long): Sequence<Long> = when { n == 1L -> sequenceOf<Long>() n % i == 0L -> sequence { yield(i); yieldAll(recur(n / i, i)) } else -> recur(n, i + 1) } return recur(value, 2) } fun factors(value: Long): Sequence<Long> { fun recur(n: Long, i: Long): Sequence<Long> = when { n < i * i -> sequenceOf<Long>() n == i * i -> sequenceOf(i) n % i == 0L -> sequence { yield(i); yield(n/i); yieldAll(recur(n, i + 1)) } else -> recur(n, i + 1) } return recur(value, 2) }
0
Go
0
0
f66389dcd8ff4e4d64fbd245cfdaebac7b9bd4ef
570
project-euler
The Unlicense