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/y2021/Day08.kt | Yg0R2 | 433,731,745 | false | null | package y2021
private val SEGMENT_BITS = arrayOf("1110111", "0010010", "1011101", "1011011", "0111010", "1101011", "1101111", "1010010", "1111111", "1111011")
fun main() {
fun part1(input: List<String>): Int {
return input
.map { line -> line.split("|").map { it.trim() } }
.map { it[1] }
.flatMap { it.split(" ") }
.count {
when (it.length) {
2, 3, 4, 7 -> true
else -> false
}
}
}
fun part2(input: List<String>): Int {
return input
.map { it.split(" | ") }
.sumOf { (patterns, outputs) ->
val digitInputs = patterns
.split(" ")
.sortedBy { it.length }
val decodedSegments = decodeSegments(Array(7) { null }, digitInputs, 0)
outputs
.split(" ")
.map { it.decode(decodedSegments) }
.joinToString("")
.toInt()
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day08_test")
check(part1(testInput).also { println(it) } == 26)
check(part2(testInput).also { println(it) } == 61229)
val input = readInput("Day08")
println(part1(input))
println(part2(input))
}
private fun decodeSegments(decodedSegments: Array<Char?>, digitInputs: List<String>, digitLengthCounter: Int): Array<Char?> {
val reducedSegments = decodedSegments
.filterNotNull()
.map { it.toString() }
.fold(digitInputs[digitLengthCounter]) { acc: String, c: String ->
acc.replace(c, "")
}
return when(digitInputs[digitLengthCounter].length) {
2 -> { // 1
val copyOfDecodedSegments = decodedSegments.copyOf()
.also {
it[2] = reducedSegments[0]
it[5] = reducedSegments[1]
}
val resolved = decodeSegments(copyOfDecodedSegments, digitInputs, digitLengthCounter + 1)
if (resolved.filterNotNull().size == 7) {
resolved
}
else {
copyOfDecodedSegments
.also {
it[2] = reducedSegments[1]
it[5] = reducedSegments[0]
}
decodeSegments(copyOfDecodedSegments, digitInputs, digitLengthCounter + 1)
}
}
3 -> { // 7
val copyOfDecodedSegments = decodedSegments.copyOf()
.also {
it[0] = reducedSegments[0]
}
decodeSegments(copyOfDecodedSegments, digitInputs, digitLengthCounter + 1)
}
4 -> { // 4
val copyOfDecodedSegments = decodedSegments.copyOf()
.also {
it[1] = reducedSegments[0]
it[3] = reducedSegments[1]
}
val resolved = decodeSegments(copyOfDecodedSegments, digitInputs, digitLengthCounter + 1)
if (resolved.filterNotNull().size == 7) {
resolved
}
else {
copyOfDecodedSegments
.also {
it[1] = reducedSegments[1]
it[3] = reducedSegments[0]
}
decodeSegments(copyOfDecodedSegments, digitInputs, digitLengthCounter + 1)
}
}
7 -> { // 8
val copyOfDecodedSegments = decodedSegments.copyOf()
.also {
it[4] = reducedSegments[0]
it[6] = reducedSegments[1]
}
if (digitInputs.all { it.decode(copyOfDecodedSegments) != -1 }) {
copyOfDecodedSegments
}
else {
copyOfDecodedSegments
.also {
it[4] = reducedSegments[1]
it[6] = reducedSegments[0]
}
if (digitInputs.all { it.decode(copyOfDecodedSegments) != -1 }) {
copyOfDecodedSegments
}
else {
decodedSegments
}
}
}
else -> decodeSegments(decodedSegments, digitInputs, digitLengthCounter + 1)
}
}
private fun String.decode(decodedSegments: Array<Char?>): Int {
return decodedSegments
.fold("") { acc: String, c: Char? ->
if (c?.let { contains(it) } == true) {
acc + 1
}
else {
acc + 0
}
}
.let { SEGMENT_BITS.indexOf(it) }
}
| 0 | Kotlin | 0 | 0 | d88df7529665b65617334d84b87762bd3ead1323 | 4,800 | advent-of-code | Apache License 2.0 |
src/main/java/leetcode/a350_intersectTwoArrays/Solution.kt | Laomedeia | 122,696,571 | true | {"Java": 801075, "Kotlin": 38473, "JavaScript": 8268} | package leetcode.a350_intersectTwoArrays
import java.util.*
import kotlin.math.min
/**
* 给定两个数组,编写一个函数来计算它们的交集。
*
* 示例 1:
* 输入:nums1 = [1,2,2,1], nums2 = [2,2]
* 输出:[2,2]
*
* 示例 2:
* 输入:nums1 = [4,9,5], nums2 = [9,4,9,8,4]
* 输出:[4,9]
*
*
* 说明:
* 输出结果中每个元素出现的次数,应与元素在两个数组中出现次数的最小值一致。
* 我们可以不考虑输出结果的顺序。
* 进阶:
* 如果给定的数组已经排好序呢?你将如何优化你的算法?
* 如果 nums1 的大小比 nums2 小很多,哪种方法更优?
* 如果 nums2 的元素存储在磁盘上,磁盘内存是有限的,并且你不能一次加载所有的元素到内存中,你该怎么办?
*
* @author neptune
* @create 2020 07 13 10:39 下午
*/
class Solution {
fun intersect(nums1: IntArray, nums2: IntArray): IntArray {
// return nums2.intersect(nums1.asIterable()).toIntArray()
nums1.sort()
nums2.sort()
val length1 = nums1.size
val length2 = nums2.size
val intersection = IntArray(min(length1, length2))
var index1 = 0
var index2 = 0
var index = 0
while (index1 < length1 && index2 < length2) {
if (nums1[index1] < nums2[index2]) {
index1++
} else if (nums1[index1] > nums2[index2]) {
index2++
} else {
intersection[index] = nums1[index1]
index1++
index2++
index++
}
}
return Arrays.copyOfRange(intersection, 0, index)
}
}
fun main(args: Array<String>) {
val solution = Solution()
val nums1:IntArray = arrayOf(1,2,2,1).toIntArray()
val nums2:IntArray = arrayOf(2).toIntArray()
// val nums1:IntArray = arrayOf(1,2,2,1).toIntArray()
// val nums2:IntArray = arrayOf(2,2).toIntArray()
solution.intersect(nums1,nums2).iterator().forEach { el -> println(el) }
} | 0 | Java | 0 | 0 | 0dcd8438e0846493ced9c1294ce686bac34c8614 | 2,068 | Java8InAction | MIT License |
solutions/src/Day12.kt | khouari1 | 573,893,634 | false | {"Kotlin": 132605, "HTML": 175} | import java.util.*
fun main() {
fun part1(input: List<String>): Int {
val grid = parseGrid(input, destinationChar = 'E')
return search(
grid = grid,
destinationChar = 'E',
fromCharGetter = { char ->
if (char == 'S') {
'a'
} else {
char
}
},
toCharGetter = { char ->
if (char == 'E') {
'z'
} else {
char
}
},
isWithinDistance = { to, from -> to - from <= 1 }
)
}
fun part2(input: List<String>): Int {
val grid = parseGrid(input, destinationChar = 'S') { 'a' }
var start = Node(0, 0)
grid.forEachIndexed { rowIndex, row ->
row.forEachIndexed { colIndex, _ ->
val current = grid[rowIndex][colIndex]
if (current == 'E') {
start = Node(rowIndex, colIndex)
}
}
}
return search(
grid = grid,
start = start,
destinationChar = 'a',
fromCharGetter = { char ->
if (char == 'E') {
'z'
} else {
char
}
},
toCharGetter = { char ->
if (char == 'S') {
'a'
} else {
char
}
},
isWithinDistance = { to, from -> from - to <= 1 }
)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day12_test")
check(part1(testInput) == 31)
check(part2(testInput) == 29)
val input = readInput("Day12")
println(part1(input))
println(part2(input))
}
private fun search(
grid: List<List<Char>>,
start: Node = Node(0, 0),
destinationChar: Char,
fromCharGetter: (c: Char) -> Char,
toCharGetter: (c: Char) -> Char,
isWithinDistance: (to: Char, from: Char) -> Boolean,
): Int {
val height = grid.size - 1
val width = grid[0].size - 1
val visited = mutableSetOf<Node>()
val queue = LinkedList<Pair<Node, Int>>()
visited.add(start)
queue.add(start to 0)
var currentLeader = Int.MAX_VALUE
while (queue.isNotEmpty()) {
val (node, count) = queue.removeLast()
val (rowIndex, colIndex) = node
val currentNodeChar = grid[rowIndex][colIndex]
if (currentNodeChar == destinationChar) {
if (count < currentLeader) {
currentLeader = count
}
break
}
val neighbours = mutableListOf<Node>()
if (rowIndex > 0) {
neighbours.add(Node(rowIndex - 1, colIndex))
}
if (rowIndex < height) {
neighbours.add(Node(rowIndex + 1, colIndex))
}
if (colIndex > 0) {
neighbours.add(Node(rowIndex, colIndex - 1))
}
if (colIndex < width) {
neighbours.add(Node(rowIndex, colIndex + 1))
}
neighbours.forEach { neighbour ->
val (neighbourX, neighbourY) = neighbour
val neighbourChar = grid[neighbourX][neighbourY]
val from = fromCharGetter(currentNodeChar)
val to = toCharGetter(neighbourChar)
if (isWithinDistance(to, from) && !visited.contains(neighbour)) {
visited.add(neighbour)
queue.addFirst(neighbour to count + 1)
}
}
}
return currentLeader
}
private fun parseGrid(
input: List<String>,
destinationChar: Char,
destinationCharTransformer: (c: Char) -> Char = { it },
): List<List<Char>> {
return input.map {
it.split("")
.filterNot { it == "" }
.map {
val char = it.single()
if (char == destinationChar) {
destinationCharTransformer(char)
} else {
char
}
}
}
}
data class Node(
val rowIndex: Int,
val colIndex: Int,
)
| 0 | Kotlin | 0 | 1 | b00ece4a569561eb7c3ca55edee2496505c0e465 | 4,217 | advent-of-code-22 | Apache License 2.0 |
src/main/kotlin/com/chriswk/aoc/advent2018/Day4.kt | chriswk | 317,863,220 | false | {"Kotlin": 481061} | package com.chriswk.aoc.advent2018
import com.chriswk.aoc.util.dayInputAsLines
import com.chriswk.aoc.util.fileToLines
import com.chriswk.aoc.util.rangeTo
import com.chriswk.aoc.util.toLocalDateTime
import java.time.Duration
import java.time.LocalDateTime
object Day4 {
val lines = dayInputAsLines(2018, 4)
val guardPattern = """(\d+)""".toRegex()
val shifts = lines.asSequence().map { stringToLine(it) }
.sortedBy {
it.timestamp
}.fold(mutableListOf(GuardShift(-1))) { acc, line ->
when {
line.action.contains("falls asleep") -> acc[acc.lastIndex] = acc.last().copy(asleepFrom = line.timestamp)
line.action.contains("wakes up") -> {
acc[acc.lastIndex] = acc.last().copy(awakeAt = line.timestamp)
acc += GuardShift(guardId = acc.last().guardId)
}
else -> {
val id = guardPattern.find(line.action)!!.groupValues[0].toInt()
acc[acc.lastIndex] = GuardShift(id)
}
}
acc
}.filter {
it.asleepFrom != null && it.awakeAt != null
}.groupBy { it.guardId }
fun solution1(): Int {
val guardId = guardMostAsleep(shifts).maxByOrNull { it.value }!!.key
val minute = minuteMostAsleep(shifts[guardId]!!).maxByOrNull { it.value }!!.key
return guardId * minute
}
fun solution2(): Int {
val guardMinute = shifts.mapValues {
minuteMostAsleep(it.value).maxByOrNull { guard ->
guard.value
}!!
}.maxByOrNull {
it.value.value
}!!
return guardMinute.key * guardMinute.value.key
}
fun minuteMostAsleep(guardShifts: List<GuardShift>): Map<Int, Int> {
return guardShifts.flatMap { shift ->
(shift.asleepFrom!!..shift.awakeAt!!).map {
it.minute
}
}.groupBy { it }.mapValues { it.value.size }
}
fun guardMostAsleep(guardShifts: Map<Int, List<GuardShift>>): Map<Int, Long> {
return guardShifts.mapValues { (_, v) ->
v.fold(0L) { acc, shift ->
acc + Duration.between(shift.asleepFrom!!, shift.awakeAt!!).toMinutes()
}
}
}
fun stringToLine(line: String): Line {
val (date, action) = line.split("]")
return Line(date.substringAfter("[").toLocalDateTime(), action)
}
data class Line(val timestamp: LocalDateTime, val action: String)
data class GuardShift(val guardId: Int, val asleepFrom: LocalDateTime? = null, val awakeAt: LocalDateTime? = null)
} | 116 | Kotlin | 0 | 0 | 69fa3dfed62d5cb7d961fe16924066cb7f9f5985 | 2,743 | adventofcode | MIT License |
src/main/kotlin/days/Day15.kt | poqueque | 430,806,840 | false | {"Kotlin": 101024} | package days
import util.Coor
// Using Dijkstra's algorithm
// https://es.wikipedia.org/wiki/Algoritmo_de_Dijkstra
class Day15 : Day(15) {
val size = 100
override fun partOne(): Any {
val map = mutableMapOf<Coor, Int>()
val shortest = mutableMapOf<Coor, Int>()
val pending = mutableListOf<Coor>()
var i = 0
inputList.forEach {
for (x in it.indices) {
map[Coor(x, i)] = it[x].toString().toInt()
shortest[Coor(x, i)] = 10000000
pending.add(Coor(x,i))
}
i++
}
val start = Coor(0,0)
val end = Coor(size -1,size -1)
shortest[start] = 0
while (pending.size > 0){
val coor = pending[0]
if (map[Coor(coor.x+1,coor.y)] != null && shortest[Coor(coor.x,coor.y)]!! + map[Coor(coor.x+1,coor.y)]!! < shortest[Coor(coor.x+1,coor.y)]!!) {
shortest[Coor(coor.x+1,coor.y)] = shortest[Coor(coor.x,coor.y)]!! + map[Coor(coor.x+1,coor.y)]!!
}
if (map[Coor(coor.x,coor.y+1)] != null && shortest[Coor(coor.x,coor.y)]!! + map[Coor(coor.x,coor.y+1)]!! < shortest[Coor(coor.x,coor.y+1)]!!) {
shortest[Coor(coor.x, coor.y+1)] = shortest[Coor(coor.x,coor.y)]!! + map[Coor(coor.x,coor.y+1)]!!
}
pending.removeAt(0)
}
return shortest[end]!!
}
override fun partTwo(): Any {
val map = mutableMapOf<Coor, Int>()
val shortest = mutableMapOf<Coor, Int>()
val pending = mutableListOf<Coor>()
val calculated = mutableListOf<Coor>()
var i = 0
inputList.forEach {
for (x in it.indices) {
for (dx in 0 .. 4)
for (dy in 0..4) {
var sum = it[x].toString().toInt()+(dx+dy)
while (sum > 9)
sum -= 9
if (map[Coor(x+size*dx, i+size*dy)] != null)
println(Coor(x+size*dx, i+size*dy))
map[Coor(x+size*dx, i+size*dy)] = sum
shortest[Coor(x+size*dx, i+size*dy)] = 1000000000
pending.add(Coor(x+size*dx, i+size*dy))
}
}
i++
}
/* for (x in 0 until size*5) {
for (y in 0 until size * 5)
print(map[Coor(y,x)])
println()
}*/
val start = Coor(0,0)
val end = Coor(size*5-1,size*5-1)
shortest[start] = 0
pending.sortBy { c -> c.x + c.y }
calculated.add(start)
while (pending.size > 0){
val coor = calculated.minByOrNull { c -> shortest[c]!! } !!
if (pending.size % 1000 == 0) {
println("pending.size = ${pending.size}")
}
if (map[Coor(coor.x+1,coor.y)] != null && shortest[Coor(coor.x,coor.y)]!! + map[Coor(coor.x+1,coor.y)]!! < shortest[Coor(coor.x+1,coor.y)]!!) {
shortest[Coor(coor.x+1,coor.y)] = shortest[Coor(coor.x,coor.y)]!! + map[Coor(coor.x+1,coor.y)]!!
calculated.add(Coor(coor.x+1,coor.y))
}
if (map[Coor(coor.x,coor.y+1)] != null && shortest[Coor(coor.x,coor.y)]!! + map[Coor(coor.x,coor.y+1)]!! < shortest[Coor(coor.x,coor.y+1)]!!) {
shortest[Coor(coor.x, coor.y+1)] = shortest[Coor(coor.x,coor.y)]!! + map[Coor(coor.x,coor.y+1)]!!
calculated.add(Coor(coor.x, coor.y+1))
}
if (map[Coor(coor.x-1,coor.y)] != null && shortest[Coor(coor.x,coor.y)]!! + map[Coor(coor.x-1,coor.y)]!! < shortest[Coor(coor.x-1,coor.y)]!!) {
shortest[Coor(coor.x-1, coor.y)] = shortest[Coor(coor.x,coor.y)]!! + map[Coor(coor.x-1,coor.y)]!!
calculated.add(Coor(coor.x-1, coor.y))
}
if (map[Coor(coor.x,coor.y-1)] != null && shortest[Coor(coor.x,coor.y)]!! + map[Coor(coor.x,coor.y-1)]!! < shortest[Coor(coor.x,coor.y-1)]!!) {
shortest[Coor(coor.x, coor.y-1)] = shortest[Coor(coor.x,coor.y)]!! + map[Coor(coor.x,coor.y-1)]!!
calculated.add(Coor(coor.x, coor.y-1))
}
pending.remove(coor)
calculated.remove(coor)
}
return shortest[end]!!
}
}
| 0 | Kotlin | 0 | 0 | 4fa363be46ca5cfcfb271a37564af15233f2a141 | 4,350 | adventofcode2021 | MIT License |
src/com/weiliange/algorithm/AddTwoNumbers.kt | WeiLianYang | 467,326,442 | false | {"Kotlin": 3867} | package com.weiliange.algorithm
import kotlin.math.pow
/**
* @author : WilliamYang
* @date : 2022/3/8 11:36
* @description : <a href="https://leetcode-cn.com/problems/add-two-numbers">两数相加</a>
*
* 给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。
* 请你将两个数相加,并以相同形式返回一个表示和的链表。
* 你可以假设除了数字 0 之外,这两个数都不会以 0 开头。
*
* 示例 1:
* 输入:l1 = [2,4,3], l2 = [5,6,4]
* 输出:[7,0,8]
* 解释:342 + 465 = 807.
*
* 示例 2:
* 输入:l1 = [0], l2 = [0]
* 输出:[0]
*
* 示例 3:
* 输入:l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
* 输出:[8,9,9,9,0,0,0,1]
*
* 提示:
* 每个链表中的节点数在范围 [1, 100] 内
* 0 <= Node.val <= 9
* 题目数据保证列表表示的数字不含前导零
*
*/
data class ListNode(
var value: Int = 0,
var next: ListNode? = null
)
/**
* 第一种:没有考虑链表长度,存在溢出情况
* @param l1 链表1
* @param l2 链表2
*/
fun addTwoNumbers1(l1: ListNode?, l2: ListNode?): ListNode {
println(l1)
println(l2)
println("---------> start <---------")
val list1 = arrayListOf<Int>()
val list2 = arrayListOf<Int>()
flatNodeValue(l1, list1)
flatNodeValue(l2, list2)
println(list1)
println(list2)
val sum1 = sumNodeValue(list1)
val sum2 = sumNodeValue(list2)
val sum = sum1 + sum2
println("sum1: $sum1, sum2: $sum2, sum: $sum")
return numberToNode(sum)
}
/**
* 链表中的节点值展开为集合
* @param node 链表
* @param list 集合
*/
fun flatNodeValue(node: ListNode?, list: ArrayList<Int>): ArrayList<Int> {
if (node == null) {
return list
}
list.add(node.value)
return flatNodeValue(node.next, list)
}
/**
* 对链表中的数求和
* @param list
*/
fun sumNodeValue(list: ArrayList<Int>): Int {
var sum = 0
list.forEachIndexed { index, value ->
val r = 10f.pow(index.toFloat()) * value
sum += r.toInt()
}
return sum
}
/**
* 将数字转为链表
*/
fun numberToNode(number: Int): ListNode {
val source = number.toString().reversed()
println("source: $source")
var firstNode: ListNode? = null
var node: ListNode? = null
source.forEachIndexed { _, char ->
if (node == null) {
node = ListNode(char.digitToInt())
firstNode = node
} else {
val nextNode = ListNode(char.digitToInt())
node?.next = nextNode
node = nextNode
}
}
println(firstNode)
return firstNode!!
}
/**
* 第二种:解决第一种中的溢出情况,其实就是解决大数相加问题:
*
* 1. 将对应位的数字逆序相加,然后存到数组中
* 2. 检查数组中的各项如果 >=10,就将该项 /10=十位上的数,再累加到后一项。将该项对 %10=个位,重新赋值给当前项
* 3. 最后再逆序组装获得链表
*/
fun addTwoNumbers2(l1: ListNode?, l2: ListNode?): ListNode {
println(l1)
println(l2)
println("---------> start <---------")
val list1 = arrayListOf<Int>()
val list2 = arrayListOf<Int>()
flatNodeValue(l1, list1)
flatNodeValue(l2, list2)
println(list1)
println(list2)
return ListNode()
}
fun main() {
val node11 = ListNode(1)
val node12 = ListNode(2, node11)
val node13 = ListNode(3, node12)
// [2, 1] + [3, 2, 1] = [5, 3, 1]
// 12 + 123 = 135
// ListNode(value=5, next=ListNode(value=3, next=ListNode(value=1, next=null)))
addTwoNumbers1(node12, node13)
}
| 0 | Kotlin | 0 | 3 | 0b2defc34a14af396fe2d08fe3ef30b3f734f8a4 | 3,741 | AlgorithmAnalysis | Apache License 2.0 |
src/Day05.kt | realpacific | 573,561,400 | false | {"Kotlin": 59236} | import java.util.*
fun main() {
val commandRegex = Regex("move (\\d+) from (\\d+) to (\\d+)")
class CrateHolder {
private val stack = Stack<String>()
fun push(item: String) {
stack.push(item)
}
fun pop(): String {
return stack.pop()!!
}
fun peek(): String {
return stack.peek()
}
}
data class Command(val from: Int, val to: Int, val count: Int)
class SupplyStacks(count: Int) {
val crateHolders = Array(count) { CrateHolder() }
fun load(index: Int, crate: String) {
if (crate.isBlank()) return
crateHolders[index].push(crate)
}
fun process(command: Command) {
val fromCrate = crateHolders[command.from - 1]
val toCrate = crateHolders[command.to - 1]
repeat(command.count) {
val popped = fromCrate.pop()
toCrate.push(popped)
}
}
fun processV2(command: Command) {
val fromCrate = crateHolders[command.from - 1]
val toCrate = crateHolders[command.to - 1]
val collector = mutableListOf<String>()
repeat(command.count) {
collector.add(fromCrate.pop())
}
collector.reversed().forEach(toCrate::push)
}
}
fun parseCommands(line: String): Command {
val find = commandRegex.find(line)!!.groupValues
return Command(from = find[2].toInt(), to = find[3].toInt(), count = find[1].toInt())
}
fun findCrateRow(input: List<String>) = input.indexOfFirst { !it.trim().startsWith("[") }
fun extractCrateName(currentRow: String, column: Int): String {
return currentRow
.substring(column..column + 2) // 2 braces + 1 character
.replace("[", "")
.replace("]", "")
}
fun part1(input: List<String>): String {
val crateLineIndex = findCrateRow(input)
val crateNumbers = input[crateLineIndex].trim().split(" ").filter(String::isNotEmpty)
val stacks = SupplyStacks(crateNumbers.size)
for (row in (crateLineIndex - 1) downTo 0) {
val currentRow = input[row]
for (column in 0..currentRow.lastIndex step 4) {
val crateName = extractCrateName(currentRow, column)
stacks.load(column / 4, crateName)
}
}
for (i in crateLineIndex + 2..input.lastIndex) {
val cmd = parseCommands(input[i])
stacks.process(cmd)
}
return stacks.crateHolders.joinToString("") { it.peek() }
}
fun part2(input: List<String>): String {
val crateLineIndex = findCrateRow(input)
val crateNumbers = input[crateLineIndex].trim().split(" ").filter(String::isNotEmpty)
val stacks = SupplyStacks(crateNumbers.size)
for (row in (crateLineIndex - 1) downTo 0) {
for (column in 0..input[row].lastIndex step 4) {
val crateName = extractCrateName(input[row], column)
stacks.load(column / 4, crateName)
}
}
for (i in crateLineIndex + 2..input.lastIndex) {
val cmd = parseCommands(input[i])
stacks.processV2(cmd)
}
return stacks.crateHolders.joinToString("") { it.peek() }
}
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f365d78d381ac3d864cc402c6eb9c0017ce76b8d | 3,486 | advent-of-code-2022 | Apache License 2.0 |
src/Day07.kt | valerakostin | 574,165,845 | false | {"Kotlin": 21086} | import java.util.*
data class FileElement(val name: String, val length: Long)
data class Dir(
val name: String,
val parent: Dir? = null,
val children: MutableList<Dir> = mutableListOf(),
val files: MutableList<FileElement> = mutableListOf(),
var size: Long = 0
) {
override fun toString(): String {
return name
}
}
class FileSystem {
private var root: Dir? = null
private var currentDirectory: Dir? = null
var size: Long = 0
fun cd(value: String) {
currentDirectory = when (value) {
"/" -> {
if (root == null)
root = Dir("/", null, mutableListOf(), mutableListOf())
root
}
".." -> {
currentDirectory?.parent
}
else -> {
var newDir: Dir? = null
if (currentDirectory != null) {
for (d in currentDirectory?.children!!) {
if (d.name == value) {
newDir = d
break
}
}
}
newDir
}
}
}
fun addDirectory(dir: String) {
val d = Dir(dir, currentDirectory)
currentDirectory?.children?.add(d)
}
fun addFile(file: FileElement) {
currentDirectory?.files?.add(file)
var d = currentDirectory
while (d != null) {
d.size += file.length
d = d.parent
}
}
fun sizeAtMost(s: Long): Long {
val queue = LinkedList<Dir>()
var sum: Long = 0
if (root != null) {
queue.add(root!!)
while (!queue.isEmpty()) {
val head = queue.removeFirst()
if (head.size <= s)
sum += head.size
queue.addAll(head.children)
}
}
return sum
}
fun freeSpace(total: Long, required: Long): Long {
var candidate = total
if (root != null) {
val available = total - root?.size!!
val toFree = required - available
val queue = LinkedList<Dir>()
if (root != null) {
queue.add(root!!)
while (!queue.isEmpty()) {
val head = queue.removeFirst()
if (toFree < head.size)
candidate = candidate.coerceAtMost(head.size)
queue.addAll(head.children)
}
}
}
return candidate
}
}
fun main() {
fun fs(input: List<String>): FileSystem {
val fs = FileSystem()
for (line in input) {
if (line.startsWith("$")) {
if (line.startsWith("$ cd")) {
val dir = line.substringAfterLast(" ")
fs.cd(dir)
}
} else if (line.startsWith("dir")) {
val dir = line.substringAfterLast(" ")
fs.addDirectory(dir)
} else {
val (size, name) = line.split(" ")
fs.addFile(FileElement(name, size.toLong()))
}
}
return fs
}
fun part1(fs: FileSystem): Long {
return fs.sizeAtMost(100000L)
}
fun part2(fs: FileSystem): Long {
return fs.freeSpace(70000000L, 30000000L)
}
check(part1(fs(readInput("Day07_test"))) == 95437L)
println(part1(fs(readInput("Day07"))))
check(part2(fs(readInput("Day07_test"))) == 24933642L)
println(part2(fs(readInput("Day07"))))
}
| 0 | Kotlin | 0 | 0 | e5f13dae0d2fa1aef14dc71c7ba7c898c1d1a5d1 | 3,636 | AdventOfCode-2022 | Apache License 2.0 |
src/main/kotlin/divine/brothers/qual/Setup.kt | AarjavP | 450,892,849 | false | {"Kotlin": 28300} | package divine.brothers.qual
import com.google.common.collect.BiMap
import com.google.common.collect.HashBiMap
@JvmInline
value class Skill(val id: Int) {
override fun toString(): String = id.toString()
}
@JvmInline
value class ContributorId(val id: Int)
@JvmInline
value class ProjectId(val id: Int)
data class SkillLevel(
val skill: Skill,
var level: Int,
)
data class Contributor(
val id: ContributorId,
val name: String,
val skills: MutableList<SkillLevel>,
) {
operator fun get(skill: Skill): Int = skills.firstOrNull { it.skill == skill }?.level ?: 0
infix fun canFill(requirement: SkillLevel): Boolean = get(requirement.skill) >= requirement.level
infix fun learn(skill: Skill) {
val skillLevel = skills.firstOrNull { it.skill == skill } ?: SkillLevel(skill, 0).also { skills += it }
skillLevel.level++
}
}
data class Project(
val id: ProjectId,
val name: String,
val duration: Int,
val bestBefore: Int,
val score: Int,
val roles: List<SkillLevel>,
)
data class Input(
val contributors: List<Contributor>,
val projects: List<Project>,
//id to name
val skills: BiMap<Skill, String>,
)
fun parse(lines: Sequence<String>): Input {
val iter = lines.iterator()
val (numContributors, numProjects) = iter.next().split(" ").map { it.toInt() }
var skillCounter = 0
val skillAliases: BiMap<Skill, String> = HashBiMap.create()
val skillNameToId = skillAliases.inverse()
fun readSkills(count: Int): ArrayList<SkillLevel> {
val ret = ArrayList<SkillLevel>(count)
repeat(count) {
val skillHeader = iter.next()
val skillName = skillHeader.substringBefore(" ")
val skillLevel = skillHeader.substringAfter(" ").toInt()
val skill = skillNameToId.computeIfAbsent(skillName) { Skill(skillCounter++) }
ret += SkillLevel(skill, skillLevel)
}
return ret
}
val contributors = ArrayList<Contributor>(numContributors)
for (contributorId in 0 until numContributors) {
val contributorHeader = iter.next()
val contributorName = contributorHeader.substringBefore(" ")
val contributorSkillCount = contributorHeader.substringAfter(" ").toInt()
val skills = readSkills(contributorSkillCount)
contributors += Contributor(ContributorId(contributorId), contributorName, skills)
}
val projects = ArrayList<Project>(numProjects)
for (projectId in 0 until numProjects) {
val projectHeader = iter.next().split(" ")
val projectName = projectHeader[0]
val projectDuration = projectHeader[1].toInt()
val projectScore = projectHeader[2].toInt()
val projectBestBy = projectHeader[3].toInt()
val projectNumRoles = projectHeader[4].toInt()
val roles = readSkills(projectNumRoles)
projects += Project(
id = ProjectId(projectId),
name = projectName,
duration = projectDuration,
bestBefore = projectBestBy,
score = projectScore,
roles = roles
)
}
return Input(
contributors = contributors,
projects = projects,
skills = skillAliases,
)
}
| 0 | Kotlin | 0 | 0 | 3aaaefc04d55b1e286dde0895fa32f9c34f5c945 | 3,270 | google-hash-code-2022 | MIT License |
src/main/kotlin/jks/Day2.kt | jksolbakken | 572,966,811 | false | {"Kotlin": 6326} | package jks
import java.io.File
import java.lang.RuntimeException
import jks.Item.PAPER
import jks.Item.ROCK
import jks.Item.SCISSORS
import jks.Result.DRAW
import jks.Result.LOSER
import jks.Result.WINNER
fun main() {
val uri = object {}::class.java.getResource("/day2_input")?.toURI()
?: throw RuntimeException("oh noes!")
val lines = File(uri).readLines()
val sumPart1 = lines
.map { chars -> Round(toItem(chars[0]), toItem(chars[2])) }
.map { round -> Pair(round, result(round)) }
.sumOf { (round, result) -> round.myItem.points + result.points }
println("Part 1: $sumPart1")
val sumPart2 = lines
.map { chars -> Pair(toItem(chars[0]), toResult(chars[2])) }
.map { Pair(it, itemForDesiredResult(it.first, it.second)) }
.sumOf { (othersItemAndResult, myItem) -> myItem.points + othersItemAndResult.second.points }
println("Part 2: $sumPart2")
}
data class Round(val opponentsItem: Item, val myItem: Item)
enum class Item(val points: Int){
ROCK(1),
PAPER(2),
SCISSORS(3)
}
enum class Result(val points: Int) {
WINNER(6),
DRAW(3),
LOSER(0)
}
private fun result(round: Round): Result = when (round) {
Round(ROCK, ROCK) -> DRAW
Round(ROCK, PAPER) -> WINNER
Round(ROCK, SCISSORS) -> LOSER
Round(PAPER, ROCK) -> LOSER
Round(PAPER, PAPER) -> DRAW
Round(PAPER, SCISSORS) -> WINNER
Round(SCISSORS, ROCK) -> WINNER
Round(SCISSORS, PAPER) -> LOSER
Round(SCISSORS, SCISSORS) -> DRAW
else -> throw RuntimeException("$round is not valid")
}
private fun toItem(c: Char) = when (c) {
'A', 'X' -> ROCK
'B', 'Y' -> PAPER
'C', 'Z' -> SCISSORS
else -> throw RuntimeException("oh noes!")
}
private fun toResult(c: Char) = when (c) {
'X' -> LOSER
'Y' -> DRAW
'Z' -> WINNER
else -> throw RuntimeException("oh noes!")
}
private fun itemForDesiredResult(othersItem: Item, desiredResult: Result) = when {
desiredResult == DRAW -> othersItem
othersItem == ROCK && desiredResult == WINNER -> PAPER
othersItem == ROCK && desiredResult == LOSER -> SCISSORS
othersItem == PAPER && desiredResult == WINNER -> SCISSORS
othersItem == PAPER && desiredResult == LOSER -> ROCK
othersItem == SCISSORS && desiredResult == WINNER -> ROCK
othersItem == SCISSORS && desiredResult == LOSER -> PAPER
else -> throw RuntimeException("oh noes!")
}
| 0 | Kotlin | 0 | 0 | afc771f8a2843d92347929dab471aa491a40a675 | 2,423 | aoc2022 | MIT License |
kotlin/problems/src/solution/WeeklyContest.kt | lunabox | 86,097,633 | false | {"Kotlin": 146671, "Python": 38767, "JavaScript": 19188, "Java": 13966} | package solution
import java.util.*
import kotlin.Comparator
import kotlin.collections.HashMap
import kotlin.math.abs
import kotlin.math.max
class WeeklyContest {
/**
* https://leetcode-cn.com/contest/weekly-contest-187/problems/destination-city/
*/
fun destCity(paths: List<List<String>>): String {
val vote = HashMap<String, Int>()
paths.forEach {
vote[it[0]] = vote[it[0]]?.minus(1) ?: -1
vote[it[1]] = vote[it[1]]?.plus(1) ?: 1
}
for (key in vote.keys) {
if (vote[key] == 1) {
return key
}
}
return ""
}
/**
* https://leetcode-cn.com/contest/weekly-contest-187/problems/check-if-all-1s-are-at-least-length-k-places-away/
*/
fun kLengthApart(nums: IntArray, k: Int): Boolean {
val list = mutableListOf<Int>()
nums.forEachIndexed { index, i ->
if (i == 1) {
list.add(index)
}
}
for (i in 0 until list.size - 1) {
if (list[i + 1] - list[i] - 1 < k) {
return false
}
}
return true
}
/**
* https://leetcode-cn.com/contest/weekly-contest-188/problems/build-an-array-with-stack-operations/
*/
fun buildArray(target: IntArray, n: Int): List<String> {
val ans = mutableListOf<String>()
var index = 0
repeat(n) {
if (index == target.size) {
return@repeat
}
ans.add("Push")
if (target.indexOf(it + 1) == -1) {
ans.add("Pop")
} else {
index++
}
}
return ans
}
/**
* https://leetcode-cn.com/contest/weekly-contest-188/problems/count-triplets-that-can-form-two-arrays-of-equal-xor/
*/
fun countTriplets(arr: IntArray): Int {
val a = IntArray(arr.size)
var ans = 0
for (i in arr.indices) {
if (i == 0) {
a[i] = arr[0]
} else {
a[i] = a[i - 1].xor(arr[i])
}
}
for (i in 0 until arr.size - 1) {
for (k in i + 1 until arr.size) {
for (j in i + 1..k) {
val left = if (i == 0) {
a[j - 1]
} else {
a[j - 1].xor(a[i - 1])
}
val right = a[k].xor(a[j - 1])
if (left == right) {
ans++
}
}
}
}
return ans
}
/**
* https://leetcode-cn.com/contest/weekly-contest-190/problems/check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/
*/
fun isPrefixOfWord(sentence: String, searchWord: String): Int {
var firstIndex = -1
sentence.split(" ").forEachIndexed { index, s ->
if (s.startsWith(searchWord)) {
if (firstIndex >= 0) {
return firstIndex + 1
} else {
firstIndex = index
}
}
}
return if (firstIndex == -1) -1 else firstIndex + 1
}
/**
* https://leetcode-cn.com/contest/weekly-contest-190/problems/maximum-number-of-vowels-in-a-substring-of-given-length/
*/
fun maxVowels(s: String, k: Int): Int {
val vowels = "aeiou"
var maxCount = 0
repeat(k) {
if (s[it] in vowels) {
maxCount++
}
}
var currentCount = maxCount
for (i in 1..s.length - k) {
if (s[i - 1] in vowels) {
currentCount--
}
if (s[i + k - 1] in vowels) {
currentCount++
}
maxCount = max(currentCount, maxCount)
}
return maxCount
}
/**
* https://leetcode-cn.com/contest/weekly-contest-191/problems/maximum-product-of-two-elements-in-an-array/
*/
fun maxProduct(nums: IntArray): Int {
var ans = -1
for (i in nums.indices) {
for (j in i + 1 until nums.size) {
ans = max(ans, (nums[i] - 1) * (nums[j] - 1))
}
}
return ans
}
/**
* https://leetcode-cn.com/contest/weekly-contest-191/problems/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/
*/
fun maxArea(h: Int, w: Int, horizontalCuts: IntArray, verticalCuts: IntArray): Int {
horizontalCuts.sort()
var maxH = horizontalCuts.first()
for (i in 1 until horizontalCuts.size) {
maxH = max(maxH, horizontalCuts[i] - horizontalCuts[i - 1])
}
maxH = max(maxH, h - horizontalCuts.last())
verticalCuts.sort()
var maxV = verticalCuts.first()
for (i in 1 until verticalCuts.size) {
maxV = max(maxV, verticalCuts[i] - verticalCuts[i - 1])
}
maxV = max(maxV, w - verticalCuts.last())
return ((maxH.toLong() * maxV.toLong()) % 1000000007L).toInt()
}
/**
* https://leetcode-cn.com/contest/weekly-contest-192/problems/shuffle-the-array/
*/
fun shuffle(nums: IntArray, n: Int): IntArray {
val ans = IntArray(nums.size)
var index = 0
repeat(n) {
ans[index++] = nums[it]
ans[index++] = nums[it + n]
}
return ans
}
/**
* https://leetcode-cn.com/contest/weekly-contest-192/problems/the-k-strongest-values-in-an-array/
*/
fun getStrongest(arr: IntArray, k: Int): IntArray {
arr.sort()
val m = arr[(arr.size - 1) / 2]
return arr.sortedWith(Comparator { o1, o2 ->
val s1 = abs(o1 - m)
val s2 = abs(o2 - m)
if (s1 == s2) {
return@Comparator if (o1 > o2) {
-1
} else {
1
}
} else {
return@Comparator if (s1 > s2) {
-1
} else {
1
}
}
}).subList(0, k).toIntArray()
}
/**
*
*/
fun canMakeArithmeticProgression(arr: IntArray): Boolean {
arr.sort()
val step = arr[1] - arr[0]
for (i in 1 until arr.size) {
if (arr[i] - arr[i - 1] != step) {
return false
}
}
return true
}
/**
* https://leetcode-cn.com/contest/weekly-contest-196/problems/last-moment-before-all-ants-fall-out-of-a-plank/
*/
fun getLastMoment(n: Int, left: IntArray, right: IntArray): Int {
var t = 0
val leftAnt = left.toMutableList()
val rightAnt = right.toMutableList()
while (leftAnt.isNotEmpty() || rightAnt.isNotEmpty()) {
t++
var removeIndex = -1
leftAnt.forEachIndexed { index, i ->
if (i == 0) {
removeIndex = index
} else {
leftAnt[index] = i - 1
}
}
if (removeIndex >= 0) {
leftAnt.removeAt(removeIndex)
}
removeIndex = -1
rightAnt.forEachIndexed { index, i ->
if (i == n) {
removeIndex = index
} else {
rightAnt[index] = i + 1
}
}
if (removeIndex >= 0) {
rightAnt.removeAt(removeIndex)
}
}
return t - 1
}
/**
* https://leetcode-cn.com/contest/weekly-contest-196/problems/count-submatrices-with-all-ones/
*/
fun numSubmat(mat: Array<IntArray>): Int {
val n = Array(mat.size + 1) { IntArray(mat[0].size + 1) { 0 } }
//预处理
for (i in 1 until mat.size) {
for (j in 1 until mat.size) {
if (mat[i][j] == 1) {
n[i][j] = n[i - 1][j] + 1
} else {
n[i][j] = 0
}
}
}
var ans = 0
var cnt = 0
val stack = IntArray(100000) { 0 }
var top = 0
for (i in 1..mat.size) {
cnt = 0
top = 0
for (j in 1..mat[0].size) {
cnt += n[i][j]
while (top != 0 && n[i][j] <= n[i][stack[top]]) {
cnt -= (stack[top] - stack[top - 1]) * (n[i][stack[top]] - n[i][j])
//(栈顶元素) - (第二大的元素) = 距离
//(栈顶元素) - (当前元素) = 差值
// 距离 × 差值 = 不作贡献的个数
top--
}
ans += cnt
stack[++top] = j
}
}
return ans
}
/**
* https://leetcode-cn.com/contest/weekly-contest-197/problems/number-of-good-pairs/
*/
fun numIdenticalPairs(nums: IntArray): Int {
var ans = 0
for (i in nums.indices) {
for (j in i + 1 until nums.size) {
if (nums[i] == nums[j]) {
ans++
}
}
}
return ans
}
/**
* https://leetcode-cn.com/contest/weekly-contest-197/problems/number-of-substrings-with-only-1s/
*/
fun numSub(s: String): Int {
var ans = 0L
s.split("0").filter { it.isNotEmpty() }.forEach {
for (i in 1..it.length) {
ans += (it.length - i + 1)
}
}
return (ans % 1000000007).toInt()
}
private var probabilityAns = 0.0
/**
*
*/
fun maxProbability(n: Int, edges: Array<IntArray>, succProb: DoubleArray, start: Int, end: Int): Double {
val matrix = Array(n) {
DoubleArray(it + 1) { 0.0 }
}
edges.forEachIndexed { index, ints ->
if (ints[0] > ints[1]) {
matrix[ints[0]][ints[1]] = succProb[index]
} else {
matrix[ints[1]][ints[0]] = succProb[index]
}
}
probabilityDfs(matrix, start, end, 1.0)
return probabilityAns
}
private fun probabilityDfs(matrix: Array<DoubleArray>, start: Int, end: Int, maxPath: Double) {
if (start == end) {
probabilityAns = max(probabilityAns, maxPath)
return
}
for (i in matrix.indices) {
if (i > start && matrix[i][start] > 0) {
probabilityDfs(matrix, i, end, matrix[i][start] * maxPath)
} else if (i < start && matrix[start][i] > 0) {
probabilityDfs(matrix, i, end, matrix[start][i] * maxPath)
}
}
}
fun numWaterBottles(numBottles: Int, numExchange: Int): Int {
var ans = numBottles
var empty = numBottles
while (empty / numExchange >= 1) {
ans += empty / numExchange
empty = empty / numExchange + empty % numExchange
}
return ans
}
fun countSubTrees(n: Int, edges: Array<IntArray>, labels: String): IntArray {
val ans = IntArray(n) { 0 }
val reach = BooleanArray(edges.size) { false }
val edgesMap = HashMap<Int, MutableList<Int>>()
edges.forEach {
val list0 = edgesMap.getOrDefault(it[0], mutableListOf())
val list1 = edgesMap.getOrDefault(it[1], mutableListOf())
list0.add(it[1])
list1.add(it[0])
edgesMap[it[0]] = list0
edgesMap[it[1]] = list1
}
countSubTreesDfs(0, edgesMap, labels, ans, reach)
return ans
}
private fun countSubTreesDfs(
currentPoint: Int,
edges: Map<Int, List<Int>>,
labels: String,
ans: IntArray,
reach: BooleanArray
): IntArray {
val counts = IntArray(26)
reach[currentPoint] = true
counts[labels[currentPoint] - 'a']++
edges[currentPoint]?.forEach {
if (!reach[it]) {
val r = countSubTreesDfs(it, edges, labels, ans, reach)
r.forEachIndexed { index, i ->
counts[index] += i
}
}
}
ans[currentPoint] = counts[labels[currentPoint] - 'a']
return counts
}
/**
* https://leetcode-cn.com/contest/weekly-contest-199/problems/shuffle-string/
*/
fun restoreString(s: String, indices: IntArray): String {
val ans = CharArray(s.length)
indices.forEachIndexed { index, i ->
ans[i] = s[index]
}
return String(ans)
}
/**
*
*/
fun minFlips(target: String): Int {
var ans = 0
var flag = 0
target.map { it - '0' }.forEach {
if (it != flag) {
ans++
flag = (flag + 1) % 2
}
}
return ans
}
fun countGoodTriplets(arr: IntArray, a: Int, b: Int, c: Int): Int {
var ans = 0
for (i in arr.indices) {
for (j in i + 1 until arr.size) {
for (k in j + 1 until arr.size) {
if (abs(arr[i] - arr[j]) <= a &&
abs(arr[j] - arr[k]) <= b &&
abs(arr[i] - arr[k]) <= c
) {
ans++
}
}
}
}
return ans
}
fun getWinner(arr: IntArray, k: Int): Int {
if (k > arr.size) {
return arr.max()!!
}
var maxIndex = 0
var count = 0
var index = 0
while (count < k) {
if (maxIndex != index) {
if (arr[maxIndex] > arr[index]) {
count++
} else {
count = 1
maxIndex = index
}
}
index++
if (index == arr.size) {
index = 0
}
}
return arr[maxIndex]
}
fun findKthPositive(arr: IntArray, k: Int): Int {
val flag = IntArray(3000) { 0 }
arr.forEach {
flag[it - 1] = 1
}
var count = 0
flag.forEachIndexed { index, i ->
if (i == 0) {
count++
}
if (count == k) {
return index + 1
}
}
return 1
}
fun canConvertString(s: String, t: String, k: Int): Boolean {
if (s.length != t.length) {
return false
}
val dis = IntArray(s.length) { 0 }
t.forEachIndexed { index, c ->
dis[index] = c - s[index]
}
val flag = BooleanArray(k + 1) { false }
dis.forEach { i ->
if (i == 0) {
return@forEach
}
var n = i
if (n > k) {
return false
}
while (n < 0 || flag[n]) {
n += 26
if (n > k) {
return false
}
}
if (n > k) {
return false
}
flag[n] = true
}
return true
// dis.forEachIndexed { index, i ->
// var n = i
// while (n < 0) {
// n += 26
// }
// dis[index] = n
// }
// dis.sort()
// dis.forEachIndexed { index, i ->
// if (i > k) {
// return false
// }
// var n = i
// var has = false
// do {
// for (j in 0 until index) {
// if (dis[j] == n) {
// n += 26
// has = true
// break
// }
// }
// } while (has)
// dis[index] = n
// }
// return true
}
fun minInsertions(s: String): Int {
var left = 0
var right = 0
var index = 0
val q = Stack<Char>()
while (index < s.length) {
if (s[index] == '(') {
q.push(s[index])
} else if (s[index] == ')') {
if (index + 1 < s.length) {
if (q.isNotEmpty()) {
q.pop()
} else {
left++
}
if (s[index + 1] == ')') {
index++
} else {
right++
}
} else if (q.isNotEmpty()) {
q.pop()
right++
} else {
right++
left++
}
}
index++
}
return left + right + q.size * 2
}
fun makeGood(s: String): String {
val buffer = mutableListOf<Char>()
s.forEach { buffer.add(it) }
var done: Boolean
do {
done = true
for (i in 0 until buffer.size - 1) {
if ((buffer[i].toLowerCase() == buffer[i + 1].toLowerCase()) &&
((buffer[i].isLowerCase() && buffer[i + 1].isUpperCase()) ||
(buffer[i + 1].isLowerCase() && buffer[i].isUpperCase()))
) {
buffer.removeAt(i)
buffer.removeAt(i)
done = false
break
}
}
} while (!done)
val ans = StringBuffer()
buffer.forEach { ans.append(it) }
return ans.toString()
}
fun findKthBit(n: Int, k: Int): Char {
val ans = StringBuffer()
ans.append('0')
repeat(n - 1) {
val currentLength = ans.length
ans.append('1')
for (i in currentLength - 1 downTo 0) {
ans.append(if (ans[i] == '0') '1' else '0')
}
}
return ans[k - 1]
}
/**
*
*/
fun maxNonOverlapping(nums: IntArray, target: Int): Int {
val map = HashMap<Int, Int>()
map[0] = 1
var ans = 0
var curSum = 0
nums.forEach { i ->
curSum += i
ans += map.getOrDefault(curSum - target, 0)
map[curSum] = map.getOrDefault(curSum, 0) + 1
}
return ans
}
fun threeConsecutiveOdds(arr: IntArray): Boolean {
for (i in 0..arr.size - 3) {
if (arr[i] % 2 == 1 && arr[i + 1] % 2 == 1 && arr[i + 2] % 2 == 1) {
return true
}
}
return false
}
fun minOperations(n: Int): Int {
var ans = 0
repeat(n / 2) {
ans += n - 2 * it - 1
}
return ans
}
fun thousandSeparator(n: Int): String {
val ans = StringBuffer()
val m = n.toString()
var count = 0
for (i in m.length - 1 downTo 0) {
if (count == 3) {
ans.append(".")
count = 0
}
ans.append(m[i])
count++
}
return ans.reverse().toString()
}
fun containsPattern(arr: IntArray, m: Int, k: Int): Boolean {
repeat(m) { start ->
var current = ""
var count = 0
for (i in start until arr.size - m + 1 step m) {
val key = StringBuffer()
arr.slice(IntRange(i, i + m - 1)).forEach { key.append(it) }
if (key.toString() != current) {
current = key.toString()
count = 1
} else {
count++
}
if (count >= k) {
return true
}
}
}
return false
}
fun getMaxLen(nums: IntArray): Int {
var maxLength = 0
var currentLength = 0
var positive = true
nums.forEach { i ->
if (i == 0) {
currentLength = 0
// positive = true
} else if (i > 0) {
currentLength++
// if (!positive) {
// currentLength = 1
// }
} else {
if (positive) {
positive = false
} else {
currentLength += 2
positive = true
}
}
maxLength = max(maxLength, currentLength)
}
return maxLength
}
/**
* https://leetcode-cn.com/contest/weekly-contest-205/problems/replace-all-s-to-avoid-consecutive-repeating-characters/
*/
fun modifyString(s: String): String {
val chars = s.toCharArray()
val flag = BooleanArray(26)
chars.forEachIndexed { index, c ->
flag.fill(false)
if (c == '?') {
if (index > 0 && chars[index - 1] != '?') {
flag[chars[index - 1] - 'a'] = true
}
if (index < chars.size - 1 && chars[index + 1] != '?') {
flag[chars[index + 1] - 'a'] = true
}
flag.forEachIndexed flag@{ i, b ->
if (!b) {
chars[index] = 'a' + i
return@flag
}
}
}
}
return String(chars)
}
fun specialArray(nums: IntArray): Int {
nums.sort()
for (i in 1..nums.size) {
val s = nums.count { it >= i }
if (s == i) {
return s
}
}
return -1
}
fun slowestKey(releaseTimes: IntArray, keysPressed: String): Char {
var ansChar = keysPressed[0]
var ansTime = releaseTimes[0]
for (i in 1 until releaseTimes.size) {
val time = releaseTimes[i] - releaseTimes[i - 1]
if (time > ansTime || (time == ansTime && keysPressed[i] > ansChar)) {
ansChar = keysPressed[i]
ansTime = time
}
}
return ansChar
}
} | 0 | Kotlin | 0 | 0 | cbb2e3ad8f2d05d7cc54a865265561a0e391a9b9 | 22,281 | leetcode | Apache License 2.0 |
src/main/kotlin/g2101_2200/s2101_detonate_the_maximum_bombs/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g2101_2200.s2101_detonate_the_maximum_bombs
// #Medium #Array #Math #Depth_First_Search #Breadth_First_Search #Graph #Geometry
// #2023_06_25_Time_262_ms_(98.96%)_Space_40.7_MB_(78.76%)
class Solution {
fun maximumDetonation(bombs: Array<IntArray>): Int {
val n = bombs.size
val graph: Array<MutableList<Int>?> = arrayOfNulls(n)
for (i in 0 until n) {
graph[i] = ArrayList()
}
for (i in 0 until n) {
for (j in i + 1 until n) {
val dx = bombs[i][0] - bombs[j][0].toDouble()
val dy = bombs[i][1] - bombs[j][1].toDouble()
val r1 = bombs[i][2].toDouble()
val r2 = bombs[j][2].toDouble()
val dist = dx * dx + dy * dy
if (dist <= r1 * r1) {
graph[i]?.add(j)
}
if (dist <= r2 * r2) {
graph[j]?.add(i)
}
}
}
val visited = BooleanArray(n)
var ans = 0
for (i in 0 until n) {
ans = Math.max(ans, dfs(graph, i, visited))
if (ans == n) {
return ans
}
visited.fill(false)
}
return ans
}
private fun dfs(graph: Array<MutableList<Int>?>, i: Int, visited: BooleanArray): Int {
var cc = 0
if (visited[i]) {
return 0
}
visited[i] = true
for (neigh in graph[i]!!) {
cc += dfs(graph, neigh, visited)
}
return cc + 1
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,578 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/days/Day9.kt | andilau | 433,504,283 | false | {"Kotlin": 137815} | package days
typealias Basin = MutableList<List<IntRange>>
typealias Basins = Set<Basin>
@AdventOfCodePuzzle(
name = "<NAME>",
url = "https://adventofcode.com/2021/day/9",
date = Date(day = 9, year = 2021)
)
class Day9(private val seafloor: List<String>) : Puzzle {
override fun partOne() =
seafloor.flatMapIndexed { y, line ->
line.mapIndexedNotNull { x, spot ->
if (seafloor.getNeighbours(x, y).all { it > spot }) Pair(x, y) else null
}
}.sumOf { seafloor.levelAt(it) }
override fun partTwo() =
seafloor.indices.asSequence().map { y -> ranges(y) }
.fold(emptySet(), buildBasins())
.map { it.size() }
.sortedDescending()
.take(3)
.reduce { a, b -> a * b }
private fun Basin.size() =
sumOf { ranges -> ranges.sumOf { range -> range.last - range.first + 1 } }
private fun ranges(y: Int): List<IntRange> {
val line = seafloor[y]
val nineAt = line.mapIndexedNotNull { index, c -> if (c == '9') index else null }
val limits = buildList {
add(-1)
addAll(nineAt)
add(line.lastIndex + 1)
}
return limits
.zipWithNext()
.mapNotNull { (start, end) -> if (end - start > 1) start + 1 until end else null }
}
private fun buildBasins() = { basins: Basins, lineRanges: List<IntRange> ->
val newBasins = mutableSetOf<Basin>()
val rangesToAdd = lineRanges.toMutableSet()
for (basin in basins) {
if (basin.last().isEmpty()) {
newBasins.add(basin)
}
else {
val add = basin.inRangeOf(lineRanges)
basin.add(add)
newBasins.add(basin)
rangesToAdd.removeAll(add)
}
}
val basinsToMerge: List<MutableList<List<IntRange>>>? = basins
.filter { it.last().isNotEmpty() }
.groupBy { it.last() }
.filterValues { it.size >= 2 }
.values
.firstOrNull()
if (basinsToMerge != null && basinsToMerge.isNotEmpty()) {
val basinMerged = basinsToMerge
.map { it.reversed() }
.flatMap { it.withIndex() }
.groupBy { it.index }
.mapValues { it.value.flatMap { it.value }.distinct() }
.values
.reversed()
.toMutableList()
newBasins.removeAll(basinsToMerge)
newBasins.add(basinMerged)
}
for (addRange in rangesToAdd) {
val newBasin = mutableListOf(listOf(addRange))
newBasins.add(newBasin)
}
newBasins
}
private fun Basin.inRangeOf(ranges: List<IntRange>): List<IntRange> =
ranges.filter { range ->
last().any { basinRange ->
range.any { it in basinRange }
}
}
private fun List<String>.getNeighbours(x: Int, y: Int) =
setOfNotNull(
this.getOrNull(y - 1)?.getOrNull(x),
this.getOrNull(y)?.getOrNull(x - 1),
this.getOrNull(y)?.getOrNull(x + 1),
this.getOrNull(y + 1)?.getOrNull(x)
)
private fun List<String>.levelAt(at: Pair<Int, Int>) =
get(at.second)[at.first].toString().toInt() + 1
} | 0 | Kotlin | 0 | 0 | b3f06a73e7d9d207ee3051879b83e92b049a0304 | 3,411 | advent-of-code-2021 | Creative Commons Zero v1.0 Universal |
src/aoc2022/Day04.kt | NoMoor | 571,730,615 | false | {"Kotlin": 101800} | package aoc2022
import utils.*
internal class Day04(lines: List<String>) {
init { lines.forEach { println(it) } }
private val lines = lines
.map {
val (a, b, c, d) = it.split('-', ',').map { it.toInt() }
(a .. b) to (c .. d)
}
fun IntRange.contains(b: IntRange): Boolean {
return this.first <= b.first && b.last <= this.last
}
fun IntRange.overlaps(b: IntRange): Boolean {
return this.contains(b.first) || this.contains(b.last) || b.contains(this.first)
}
fun part1(): Int {
return lines.count {
if (it.first.contains(it.second)) {
println("${it.first} contains ${it.second}")
return@count true
}
if (it.second.contains(it.first)) {
println("${it.second} contains ${it.first}")
return@count true
}
return@count false
}
}
fun part2(): Int {
return lines.count {
return@count it.first.overlaps(it.second)
}
}
companion object {
fun runDay() {
val day = "04".toInt()
val todayTest = Day04(readInput(day, 2022, true))
execute(todayTest::part1, "Day[Test] $day: pt 1", 2)
val today = Day04(readInput(day, 2022))
execute(today::part1, "Day $day: pt 1", 599)
execute(todayTest::part2, "Day[Test] $day: pt 2", 4)
execute(today::part2, "Day $day: pt 2", 928)
}
}
}
fun main() {
Day04.runDay()
}
| 0 | Kotlin | 1 | 2 | d561db73c98d2d82e7e4bc6ef35b599f98b3e333 | 1,389 | aoc2022 | Apache License 2.0 |
advent-of-code2015/src/main/kotlin/day10/Advent10.kt | REDNBLACK | 128,669,137 | false | null | package day10
/**
--- Day 10: Elves Look, Elves Say ---
Today, the Elves are playing a game called look-and-say. They take turns making sequences by reading aloud the previous sequence and using that reading as the next sequence. For example, 211 is read as "one two, two ones", which becomes 1221 (1 2, 2 1s).
Look-and-say sequences are generated iteratively, using the previous value as input for the next step. For each step, take the previous value, and replace each run of digits (like 111) with the number of digits (3) followed by the digit itself (1).
For example:
1 becomes 11 (1 copy of digit 1).
11 becomes 21 (2 copies of digit 1).
21 becomes 1211 (one 2 followed by one 1).
1211 becomes 111221 (one 1, one 2, and two 1s).
111221 becomes 312211 (three 1s, two 2s, and one 1).
Starting with the digits in your puzzle input, apply this process 40 times. What is the length of the result?
--- Part Two ---
Neat, right? You might also enjoy hearing John Conway talking about this sequence (that's Conway of Conway's Game of Life fame).
Now, starting again with the digits in your puzzle input, apply this process 50 times. What is the length of the new result?
*/
fun main(args: Array<String>) {
println("1".transform() == "11")
println("11".transform() == "21")
println("21".transform() == "1211")
println("1211".transform() == "111221")
println("111221".transform() == "312211")
val input = "1113222113"
println(input.transform(40).length)
println(input.transform(50).length)
}
fun String.transform(times: Int = 1) = (1..times).fold(this, { str, _i -> str.transform() })
private fun String.transform(): String {
val result = StringBuilder()
var index = 0
while (index < length) {
var count = 1
val current = this[index]
while (index + 1 < length && this[index + 1] == current) {
++index
++count
}
result.append(count)
result.append(current)
index++
}
return result.toString()
}
| 0 | Kotlin | 0 | 0 | e282d1f0fd0b973e4b701c8c2af1dbf4f4a149c7 | 2,039 | courses | MIT License |
src/main/kotlin/com/hj/leetcode/kotlin/problem72/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem72
/**
* LeetCode page: [72. Edit Distance](https://leetcode.com/problems/edit-distance/);
*/
class Solution {
/* Complexity:
* Time O(MN) and Space O(MN) where M and N are the length of word1 and word2;
*/
fun minDistance(word1: String, word2: String): Int {
// holder[i][j] = minDistance(word1[i:], word2[j:])
val holder = createSubResultHolder(word1, word2)
return holder.let {
setBaseCases(it, word1, word2)
propagateRelation(it, word1, word2)
solveOriginalProblem(it)
}
}
private fun createSubResultHolder(word1: String, word2: String): Array<IntArray> {
return Array(word1.length + 1) { IntArray(word2.length + 1) }
}
private fun setBaseCases(subResultHolder: Array<IntArray>, word1: String, word2: String) {
val len1 = word1.length
val len2 = word2.length
for (i in 0..len1) {
subResultHolder[i][len2] = len1 - i
}
for (j in 0..len2) {
subResultHolder[len1][j] = len2 - j
}
}
private fun propagateRelation(subResultHolder: Array<IntArray>, word1: String, word2: String) {
for (i in word1.length - 1 downTo 0) {
for (j in word2.length - 1 downTo 0) {
solveAndStoreSubResult(subResultHolder, i, j, word1, word2)
}
}
}
private fun solveAndStoreSubResult(
subResultHolder: Array<IntArray>,
i: Int,
j: Int,
word1: String,
word2: String
) {
val subResult = if (word1[i] == word2[j]) {
subResultHolder[i + 1][j + 1]
} else {
1 + minOf(
subResultHolder[i][j + 1], // apply insertion
subResultHolder[i + 1][j], // apply deletion
subResultHolder[i + 1][j + 1] // apply replacement
)
}
subResultHolder[i][j] = subResult
}
private fun solveOriginalProblem(subResultHolder: Array<IntArray>): Int {
return subResultHolder[0][0]
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 2,107 | hj-leetcode-kotlin | Apache License 2.0 |
src/main/kotlin/aoc2019/SlamShuffle.kt | komu | 113,825,414 | false | {"Kotlin": 395919} | package komu.adventofcode.aoc2019
import komu.adventofcode.utils.multiplicativeInverse
import komu.adventofcode.utils.nonEmptyLines
fun slamShuffle(input: String): Long {
val shuffle = Shuffle.parse(input.nonEmptyLines(), size = 10007)
return shuffle(2019)
}
fun slamShuffle2(input: String): Long {
val one = Shuffle.parse(input.nonEmptyLines(), size = 119_315_717_514_047)
val thousand = 1000 * one
val million = 1000 * thousand
val billion = 1000 * million
val trillion = 1000 * billion
val repeated = (101 * trillion) + (741 * billion) + (582 * million) + (76 * thousand) + (661 * one)
val shuffle = repeated.inverse()
return shuffle(2020)
}
private class Shuffle(
private val multiplier: ModularNatural,
private val offset: ModularNatural
) {
constructor(size: Long, multiplier: Long, offset: Long) : this(
multiplier = ModularNatural(multiplier, size),
offset = ModularNatural(offset, size)
)
operator fun invoke(index: Long) =
(multiplier * index + offset).toLong()
operator fun plus(b: Shuffle) =
Shuffle(multiplier = multiplier * b.multiplier, offset = b.multiplier * offset + b.offset)
fun inverse() =
Shuffle(multiplier = multiplier.multiplicativeInverse, offset = multiplier.multiplicativeInverse * offset.additiveInverse)
companion object {
fun deal(size: Long) = Shuffle(size, multiplier = size - 1, offset = size - 1)
fun cut(size: Long, count: Long) = Shuffle(size, multiplier = 1, offset = (size - count) % size)
fun deal(size: Long, increment: Long) = Shuffle(size, multiplier = increment, offset = 0)
fun parse(input: List<String>, size: Long) =
input.map { parse(it, size) }.reduce { a, b -> a + b }
fun parse(input: String, size: Long): Shuffle = when {
input == "deal into new stack" -> deal(size)
input.startsWith("cut ") -> cut(size, input.drop(4).toLong())
input.startsWith("deal with increment ") -> deal(size, input.drop(20).toLong())
else -> error("invalid input '$input'")
}
}
}
private operator fun Int.times(shuffle: Shuffle): Shuffle {
require(this > 0)
var result = shuffle
repeat(this - 1) {
result += shuffle
}
return result
}
private class ModularNatural(private val value: Long, val modulo: Long) {
init {
require(value in 0 until modulo)
}
fun toLong() = value
operator fun plus(rhs: ModularNatural) = ModularNatural((value + rhs.value) % modulo, modulo)
operator fun plus(rhs: Long) = plus(ModularNatural(rhs, modulo))
operator fun minus(rhs: ModularNatural) = ModularNatural((value - rhs.value + modulo) % modulo, modulo)
operator fun times(rhs: ModularNatural) = times(rhs.value)
operator fun times(rhs: Long) = ModularNatural((value.toBigInteger() * rhs.toBigInteger() % modulo.toBigInteger()).toLong(), modulo)
val additiveInverse: ModularNatural
get() = ModularNatural((-value + modulo) % modulo, modulo)
val multiplicativeInverse: ModularNatural
get() = ModularNatural(multiplicativeInverse(value, modulo), modulo)
}
| 0 | Kotlin | 0 | 0 | 8e135f80d65d15dbbee5d2749cccbe098a1bc5d8 | 3,197 | advent-of-code | MIT License |
src/day09/Day09.kt | ivanovmeya | 573,150,306 | false | {"Kotlin": 43768} | package day09
import readInput
import kotlin.math.abs
import kotlin.math.sign
enum class Direction {
LEFT,
UP,
RIGHT,
DOWN;
companion object {
fun from(letter: Char) = when (letter) {
'L' -> LEFT
'U' -> UP
'R' -> RIGHT
'D' -> DOWN
else -> throw IllegalArgumentException("Wow wow wow, unknown move $letter")
}
}
}
fun main() {
data class Move(val direction: Direction, val steps: Int)
data class Point(val i: Int, val j: Int) {
override fun toString(): String {
return "$i,$j"
}
}
fun List<String>.parseMoves(): List<Move> {
return this.map {
val (directionRow, stepsRow) = it.split(' ')
Move(
direction = Direction.from(directionRow.first()),
steps = stepsRow.toInt()
)
}
}
fun processMoveStep(initial: Point, move: Move): Point {
return when (move.direction) {
Direction.LEFT -> initial.copy(j = initial.j - 1)
Direction.UP -> initial.copy(i = initial.i + 1)
Direction.RIGHT -> initial.copy(j = initial.j + 1)
Direction.DOWN -> initial.copy(i = initial.i - 1)
}
}
fun Point.atSamePosition(other: Point) = this.i == other.i && this.j == other.j
fun Point.isTouching(other: Point) = !this.atSamePosition(other) &&
abs(other.i - this.i) <= 1 && abs(other.j - this.j) <= 1
fun adjustTailPosition(tail: Point, head: Point): Point {
return when {
tail.atSamePosition(head) || tail.isTouching(head) -> tail.copy()
else -> Point(
i = tail.i + (head.i - tail.i).sign,
j = tail.j + (head.j - tail.j).sign
)
}
}
fun moveKnots(knotsSnake: MutableList<Point>) {
for (i in 0..knotsSnake.size - 2) {
knotsSnake[i + 1] = adjustTailPosition(knotsSnake[i + 1], knotsSnake[i])
}
}
@Suppress("KotlinConstantConditions")
fun tailVisitedCount(input: List<String>, numberOfKnots: Int): Int {
val moves = input.parseMoves()
val isVisited = hashMapOf<String, Boolean>()
val knotsSnake = Array(numberOfKnots) { Point(0, 0) }.toMutableList()
isVisited[knotsSnake[numberOfKnots - 1].toString()] = true
moves.forEach { move ->
repeat(move.steps) {
knotsSnake[0] = processMoveStep(knotsSnake[0], move)
moveKnots(knotsSnake)
isVisited[knotsSnake[numberOfKnots - 1].toString()] = true
}
}
return isVisited.size
}
fun part1(input: List<String>): Int {
return tailVisitedCount(input, 2)
}
fun part2(input: List<String>): Int {
return tailVisitedCount(input, 10)
}
val testInput = readInput("day09/input_test")
val test1Result = part1(testInput)
val test2Result = part2(testInput)
val testInputLarge = readInput("day09/input_test_large")
val test2LargeResult = part2(testInputLarge)
println(test1Result)
println(test2Result)
println(test2LargeResult)
check(test1Result == 13)
check(test2Result == 1)
check(test2LargeResult == 36)
val input = readInput("day09/input")
val part1 = part1(input)
val part2 = part2(input)
check(part1 == 6037)
check(part2 == 2485)
println(part1)
println(part2)
} | 0 | Kotlin | 0 | 0 | 7530367fb453f012249f1dc37869f950bda018e0 | 3,474 | advent-of-code-2022 | Apache License 2.0 |
src/Day03.kt | acunap | 573,116,784 | false | {"Kotlin": 23918} | import kotlin.time.ExperimentalTime
import kotlin.time.measureTime
@OptIn(ExperimentalTime::class)
fun main() {
fun Char.itemCodeToPoints(): Int = if (isLowerCase()) code - 96 else code - 38
fun String.mapCharsToIndexes(): MutableMap<Char, MutableList<Int>> {
val charsToIndexes = mutableMapOf<Char, MutableList<Int>>()
this.forEachIndexed { index, char ->
if (charsToIndexes.containsKey(char)) {
charsToIndexes[char]?.add(index)
} else {
charsToIndexes[char] = mutableListOf(index)
}
}
return charsToIndexes
}
fun part1(input: List<String>): Int = input.sumOf { row ->
val rucksackChangeIndex = row.count() / 2
row.mapCharsToIndexes().filter { char ->
char.value.any { index -> index < rucksackChangeIndex } && char.value.any { index -> index >= rucksackChangeIndex }
}.map { char -> char.key.itemCodeToPoints() }.sum()
}
fun part2(input: List<String>): Int =input
.chunked(3)
.map { group -> group.map { it.toSet() } }
.sumOf { group ->
group.first().filter { char ->
val result = group.all {
it.contains(char)
}
result
}.sumOf { it.itemCodeToPoints() }
}
val time = measureTime {
val input = readLines("Day03")
println(part1(input))
println(part2(input))
}
println("Real data time $time.")
val timeTest = measureTime {
val testInput = readLines("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
}
println("Test data time $timeTest.")
}
| 0 | Kotlin | 0 | 0 | f06f9b409885dd0df78f16dcc1e9a3e90151abe1 | 1,731 | advent-of-code-2022 | Apache License 2.0 |
src/aoc2018/kot/Day16.kt | Tandrial | 47,354,790 | false | null | package aoc2018.kot
import getNumbers
import java.io.File
object Day16 {
fun partOne(input: List<String>) = input.chunked(4).takeWhile { it[0] != it[1] }.count { (before, op, after) ->
check(before.getNumbers(), op.getNumbers(), after.getNumbers()).size >= 3
}
fun partTwo(input: List<String>): Int {
val calibration = input.chunked(4).takeWhile { it[0] != it[1] }
val matchings = calibration.map { (before, op, after) ->
val ops = op.getNumbers()
val possible = check(before.getNumbers(), ops, after.getNumbers()).toMutableSet()
Pair(ops.first(), possible)
}.toMap()
while (matchings.any { it.value.size > 1 }) {
matchings.filter { it.value.size == 1 }.forEach { id, set ->
matchings.forEach { id2, set2 -> if (id != id2) set2.removeAll(set) }
}
}
val program = input.drop(4 * calibration.size + 2).map {
val (opCode, in1, in2, out1) = it.getNumbers()
"${matchings[opCode]!!.first()} $in1 $in2 $out1"
}
return program.fold(listOf(0, 0, 0, 0)) { regs, instruction -> apply(regs, instruction) }[0]
}
private fun check(before: List<Int>, line: List<Int>, after: List<Int>): List<String> {
val (_, in1, in2, out1) = line
return listOf("addr", "addi", "mulr", "muli", "banr", "bani", "borr", "bori", "setr", "seti", "gtir", "gtri", "gtrr", "eqir", "eqri", "eqrr")
.filter { apply(before, "$it $in1 $in2 $out1") == after }
}
private fun apply(oldRegs: List<Int>, line: String): List<Int> {
val (in1, in2, out1) = line.split(" ").drop(1).map { it.toInt() }
val regs = oldRegs.toMutableList()
when (line.split(" ")[0]) {
"addr" -> regs[out1] = regs[in1] + regs[in2]
"addi" -> regs[out1] = regs[in1] + in2
"mulr" -> regs[out1] = regs[in1] * regs[in2]
"muli" -> regs[out1] = regs[in1] * in2
"banr" -> regs[out1] = regs[in1] and regs[in2]
"bani" -> regs[out1] = regs[in1] and in2
"borr" -> regs[out1] = regs[in1] or regs[in2]
"bori" -> regs[out1] = regs[in1] or in2
"setr" -> regs[out1] = regs[in1]
"seti" -> regs[out1] = in1
"gtir" -> regs[out1] = if (in1 > regs[in2]) 1 else 0
"gtri" -> regs[out1] = if (regs[in1] > in2) 1 else 0
"gtrr" -> regs[out1] = if (regs[in1] > regs[in2]) 1 else 0
"eqir" -> regs[out1] = if (in1 == regs[in2]) 1 else 0
"eqri" -> regs[out1] = if (regs[in1] == in2) 1 else 0
"eqrr" -> regs[out1] = if (regs[in1] == regs[in2]) 1 else 0
}
return regs
}
}
fun main(args: Array<String>) {
val input = File("./input/2018/Day16_input.txt").readLines()
println("Part One = ${Day16.partOne(input)}")
println("Part Two = ${Day16.partTwo(input)}")
}
| 0 | Kotlin | 1 | 1 | 9294b2cbbb13944d586449f6a20d49f03391991e | 2,711 | Advent_of_Code | MIT License |
src/day14/Code.kt | fcolasuonno | 162,470,286 | false | null | package day14
import java.io.File
import java.lang.Integer.min
fun main(args: Array<String>) {
val name = if (false) "test.txt" else "input.txt"
val dir = ::main::class.java.`package`.name
val input = File("src/$dir/$name").readLines()
val parsed = parse(input)
println("Part 1 = ${part1(parsed, 2503)}")
println("Part 2 = ${part2(parsed, 2503)}")
}
data class Reindeer(val i1: String, val speed: Int, val fly: Int, val rest: Int) {
var points = 0
var distance = 0
fun tick(elapsed: Int) {
if (elapsed % (fly + rest) < fly) distance += speed
}
}
private val lineStructure =
"""(\w+) can fly (\d+) km/s for (\d+) seconds, but then must rest for (\d+) seconds\.""".toRegex()
fun parse(input: List<String>) = input.map {
lineStructure.matchEntire(it)?.destructured?.let {
val (name, speed, fly, rest) = it.toList()
Reindeer(name, speed.toInt(), fly.toInt(), rest.toInt())
}
}.requireNoNulls()
fun part1(input: List<Reindeer>, end: Int): Any? = input.map {
val flights = end / (it.fly + it.rest)
val leftTime = end % (it.fly + it.rest)
it.speed * (flights * it.fly + min(it.fly, leftTime))
}.max()
fun part2(input: List<Reindeer>, end: Int): Any? {
for (i in 0 until end) {
input.forEach {
it.tick(i)
}
input.filter { it.distance == input.map { it.distance }.max() }.forEach { it.points++ }
}
return input.map { it.points }.max()
}
| 0 | Kotlin | 0 | 0 | 24f54bf7be4b5d2a91a82a6998f633f353b2afb6 | 1,471 | AOC2015 | MIT License |
src/main/kotlin/days/Day18.kt | andilau | 399,220,768 | false | {"Kotlin": 85768} | package days
@AdventOfCodePuzzle(
name = "Operation Order",
url = "https://adventofcode.com/2020/day/18",
date = Date(day = 18, year = 2020)
)
class Day18(val lines: List<String>) : Puzzle {
override fun partOne() = lines.sumOf { equation ->
solve(equation, Day18::solveFromLeft)
}
override fun partTwo() = lines.sumOf { equation ->
solve(equation, Day18::solveAddFirst)
}
internal fun testPartOne(equation: String): Long = solve(equation, ::solveFromLeft)
internal fun testPartTwo(equation: String): Long = solve(equation, ::solveAddFirst)
companion object {
private val regex = Regex("""\(([\s\d+*]+)\)""")
private val solved = Regex("""^\d+$""")
private val sumOrProduct = """(\d+)\s*([+*])\s*(\d+)""".toRegex()
private val operations = listOf<Pair<Regex, (Long, Long) -> Long>>(
Regex("""(\d+)\s*\+\s*(\d+)""") to { a, b -> a + b },
Regex("""(\d+)\s*\*\s*(\d+)""") to { a, b -> a * b }
)
private fun solve(equation: String, solver: (String) -> String): Long {
var equationToSolve = "($equation)"
while (!solved.matches(equationToSolve)) {
equationToSolve = regex.replace(equationToSolve) {
solver(it.groupValues[1])
}
}
return equationToSolve.toLong()
}
private fun solveFromLeft(s: String): String {
var equation = s
while (!solved.matches(equation)) {
val find = sumOrProduct.find(equation) ?: break
val (expr, op1, op, op2) = find.groupValues
val result = if (op == "+") op1.toLong() + op2.toLong()
else op1.toLong() * op2.toLong()
equation = equation.replaceFirst(expr, result.toString())
}
return equation
}
private fun solveAddFirst(s: String): String {
var equation = s
operations.forEach { (regex, operation) ->
while (true) {
val find = regex.find(equation) ?: break
val (expr, op1, op2) = find.groupValues
val result = operation(op1.toLong(), op2.toLong())
equation = equation.replaceFirst(expr, result.toString())
}
}
return equation
}
}
} | 7 | Kotlin | 0 | 0 | 2809e686cac895482c03e9bbce8aa25821eab100 | 2,422 | advent-of-code-2020 | Creative Commons Zero v1.0 Universal |
src/aoc2022/Day02.kt | anitakar | 576,901,981 | false | {"Kotlin": 124382} | package aoc2022
import readInput
fun main() {
fun points(me: Char): Int {
return me.minus('X') + 1
}
fun draw(op: Char, me: Char): Boolean {
return (op == 'A' && me == 'X') || (op == 'B' && me == 'Y') || (op == 'C' && me == 'Z')
}
fun won(op: Char, me: Char): Boolean {
return (op == 'A' && me == 'Y') || (op == 'B' && me == 'Z') || (op == 'C' && me == 'X')
}
fun move(op: Char, result: Char): Char {
if (result == 'Y') {
return when (op) {
'A' -> 'X'
'B' -> 'Y'
'C' -> 'Z'
else -> 'X'
}
} else if (result == 'X') {
return when (op) {
'A' -> 'Z'
'B' -> 'X'
'C' -> 'Y'
else -> 'X'
}
} else {
return when (op) {
'A' -> 'Y'
'B' -> 'Z'
'C' -> 'X'
else -> 'X'
}
}
}
fun part1(input: List<String>): Int {
var sum = 0
for (play in input) {
val opAndMe = play.split(" ")
val op = opAndMe[0][0]
val me = opAndMe[1][0]
sum += points(me)
if (draw(op, me)) {
sum += 3
} else if (won(op, me)) {
sum += 6
}
}
return sum
}
fun part2(input: List<String>): Int {
var sum = 0
for (play in input) {
val opAndResult = play.split(" ")
val op = opAndResult[0][0]
val result = opAndResult[1][0]
val me = move(op, result)
sum += points(me)
if (draw(op, me)) {
sum += 3
} else if (won(op, me)) {
sum += 6
}
}
return sum
}
val testInput = readInput("Day02_test")
println(part1(testInput))
check(part1(testInput) == 15)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 1 | 50998a75d9582d4f5a77b829a9e5d4b88f4f2fcf | 2,081 | advent-of-code-kotlin | Apache License 2.0 |
src/main/kotlin/com/github/michaelbull/advent2023/day8/DesertMap.kt | michaelbull | 726,012,340 | false | {"Kotlin": 195941} | package com.github.michaelbull.advent2023.day8
import com.github.michaelbull.advent2023.math.leastCommonMultiple
private val NODE_REGEX = "[A-Z0-9]{3}".toRegex()
private val NETWORK_REGEX = "($NODE_REGEX) = \\(($NODE_REGEX), ($NODE_REGEX)\\)".toRegex()
fun Sequence<String>.toDesertMap(): DesertMap {
var instructions = emptyList<Instruction>()
val network = mutableMapOf<Node, List<Node>>()
for ((index, line) in withIndex()) {
if (index == 0) {
instructions = line.map(Char::toInstruction)
} else if (index > 1) {
val result = requireNotNull(NETWORK_REGEX.matchEntire(line)) {
"$line must match $NETWORK_REGEX"
}
val (from, left, right) = result.destructured
network[Node(from)] = listOf(Node(left), Node(right))
}
}
return DesertMap(
instructions = instructions,
network = network.toMap()
)
}
data class DesertMap(
val instructions: List<Instruction>,
val network: Map<Node, List<Node>>,
) {
fun stepCount(start: Node, end: Node): Long {
return stepCount(start) { node ->
node == end
}
}
fun stepCount(isStart: (Node) -> Boolean, isEnd: (Node) -> Boolean): Long {
return network.keys
.filter(isStart)
.map { start -> stepCount(start, isEnd) }
.leastCommonMultiple()
}
private fun stepCount(start: Node, isEnd: (Node) -> Boolean): Long {
return traverse(start, isEnd)
.count()
.toLong()
}
private fun traverse(start: Node, isEnd: (Node) -> Boolean) = sequence {
var cur = start
for (instruction in instructions.asSequence().repeating()) {
cur = cur.next(instruction)
yield(cur)
if (isEnd(cur)) {
break
}
}
}
private fun Node.next(instruction: Instruction): Node {
val (left, right) = network.getValue(this)
return when (instruction) {
Left -> left
Right -> right
}
}
private fun <T> Sequence<T>.repeating() = sequence {
while (true) {
yieldAll(this@repeating)
}
}
}
| 0 | Kotlin | 0 | 1 | ea0b10a9c6528d82ddb481b9cf627841f44184dd | 2,249 | advent-2023 | ISC License |
kotlin/src/katas/kotlin/leetcode/add_two_numbers/AddTwoNumbers_2.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.add_two_numbers
import datsok.shouldEqual
import katas.kotlin.leetcode.ListNode
import nonstdlib.with
import org.junit.jupiter.api.Test
class AddTwoNumbers_2_Tests {
@Test fun `convert number to ListNode`() {
1.toListNode() shouldEqual ListNode(1)
10.toListNode() shouldEqual ListNode(0, ListNode(1))
12.toListNode() shouldEqual ListNode(2, ListNode(1))
100.toListNode() shouldEqual ListNode(0, ListNode(0, ListNode(1)))
102.toListNode() shouldEqual ListNode(2, ListNode(0, ListNode(1)))
123.toListNode() shouldEqual ListNode(3, ListNode(2, ListNode(1)))
321.toListNode() shouldEqual ListNode(1, ListNode(2, ListNode(3)))
}
@Test fun `it works`() {
addTwoNumbers(0.toListNode(), 0.toListNode()) shouldEqual 0.toListNode()
addTwoNumbers(1.toListNode(), 2.toListNode()) shouldEqual 3.toListNode()
addTwoNumbers(5.toListNode(), 5.toListNode()) shouldEqual 10.toListNode()
addTwoNumbers(10.toListNode(), 30.toListNode()) shouldEqual 40.toListNode()
addTwoNumbers(12.toListNode(), 3.toListNode()) shouldEqual 15.toListNode()
addTwoNumbers(342.toListNode(), 465.toListNode()) shouldEqual 807.toListNode()
addTwoNumbers(1342.toListNode(), 465.toListNode()) shouldEqual 1807.toListNode()
addTwoNumbers(465.toListNode(), 1342.toListNode()) shouldEqual 1807.toListNode()
}
}
fun addTwoNumbers(l1: ListNode?, l2: ListNode?): ListNode? {
var (longest, shortest) =
if (l1.size() >= l2.size()) Pair(l1, l2)
else Pair(l2, l1)
var carry = false
var head: ListNode? = null
var tip: ListNode? = null
do {
val sum = longest?.value!! + (shortest?.value ?: 0) + if (carry) 1 else 0
val newElement = ListNode(sum % 10)
if (head == null) head = newElement
tip?.next = newElement
tip = newElement
carry = sum >= 10
longest = longest.next
shortest = shortest?.next
} while (longest != null)
if (carry) tip?.next = ListNode(1)
return head
}
fun ListNode?.size(): Int =
if (this == null) 0 else 1 + next.size()
private fun Int.toListNode(): ListNode =
if (this < 10) ListNode(this)
else (this % 10).toListNode().with {
it.next = (this / 10).toListNode()
}
| 7 | Roff | 3 | 5 | 0f169804fae2984b1a78fc25da2d7157a8c7a7be | 2,340 | katas | The Unlicense |
src/main/kotlin/Day8.kt | maldoinc | 726,264,110 | false | {"Kotlin": 14472} | import java.util.function.Predicate
import kotlin.io.path.Path
import kotlin.io.path.readLines
fun getSteps(
instructions: String,
navigation: Map<String, Pair<String, String>>,
start: String,
endPredicate: Predicate<String>
): Int {
var location = start
var locationIndex = 0
var steps = 0
while (!endPredicate.test(location)) {
val next = navigation[location]!!
location =
if (instructions[locationIndex] == 'L') {
next.first
} else {
next.second
}
locationIndex += 1
locationIndex %= instructions.length
steps += 1
}
return steps
}
fun getPart2(instructions: String, navigation: Map<String, Pair<String, String>>): List<Int> {
return navigation.keys
.filter { it.endsWith('A') }
.map { it -> getSteps(instructions, navigation, it) { it.endsWith('Z') } }
}
fun main(input: Array<String>) {
val lines = Path(input[0]).readLines()
val instructions = lines.removeFirst()
lines.removeFirst()
val navigation =
lines
.map { it.split(" = ") }
.map { it[0] to it[1].replace("(", "").replace(")", "").split(", ") }
.associate { it.first to (it.second[0] to it.second[1]) }
println(getSteps(instructions, navigation, "AAA") { it == "ZZZ" })
println(getPart2(instructions, navigation))
// python3 -c 'import math; print(math.lcm(*$parts))'. Yeah...
}
| 0 | Kotlin | 0 | 1 | 47a1ab8185eb6cf16bc012f20af28a4a3fef2f47 | 1,488 | advent-2023 | MIT License |
src/main/kotlin/biz/koziolek/adventofcode/year2023/day25/day25.kt | pkoziol | 434,913,366 | false | {"Kotlin": 715025, "Shell": 1892} | package biz.koziolek.adventofcode.year2023.day25
import biz.koziolek.adventofcode.*
fun main() {
val inputFile = findInput(object {})
val graph = parseWiring(inputFile.bufferedReader().readLines())
val wiresToCut = findWiresToCut(graph)
val newGraphs = graph.removeEdges(wiresToCut)
println(wiresToCut.joinToString("\n ", prefix = "Wires to cut:\n ") { it.toGraphvizString() })
println("Will split graph into ${newGraphs.size} graphs having ${newGraphs.map { it.nodes.size }} nodes so the answer is ${getAnswer(newGraphs)}")
}
fun parseWiring(lines: Iterable<String>): Graph<SimpleGraphNode, BiDirectionalGraphEdge<SimpleGraphNode>> =
buildGraph {
for (line in lines) {
val (start, ends) = line.split(':')
val startNode = SimpleGraphNode(start)
ends.trim()
.split(' ')
.map { end -> BiDirectionalGraphEdge(startNode, SimpleGraphNode(end)) }
.forEach { add(it) }
}
}
@Suppress("UNCHECKED_CAST")
fun <N : GraphNode, E : GraphEdge<N>> findWiresToCut(graph: Graph<N, E>): Set<E> =
when (graph.nodes.size) {
15 -> setOf(
BiDirectionalGraphEdge(SimpleGraphNode("hfx"), SimpleGraphNode("pzl")) as E,
BiDirectionalGraphEdge(SimpleGraphNode("bvb"), SimpleGraphNode("cmg")) as E,
BiDirectionalGraphEdge(SimpleGraphNode("nvd"), SimpleGraphNode("jqt")) as E,
)
1535 -> setOf(
BiDirectionalGraphEdge(SimpleGraphNode("psj"), SimpleGraphNode("fdb")) as E,
BiDirectionalGraphEdge(SimpleGraphNode("rmt"), SimpleGraphNode("nqh")) as E,
BiDirectionalGraphEdge(SimpleGraphNode("trh"), SimpleGraphNode("ltn")) as E,
)
else -> TODO("Implement real solution")
}
fun <N : GraphNode, E : GraphEdge<N>> getAnswer(graphs: Collection<Graph<N, E>>): Int =
graphs.fold(1) { acc, g -> acc * g.nodes.size }
| 0 | Kotlin | 0 | 0 | 1b1c6971bf45b89fd76bbcc503444d0d86617e95 | 1,940 | advent-of-code | MIT License |
src/aoc2022/Day02.kt | dayanruben | 433,250,590 | false | {"Kotlin": 79134} | package aoc2022
import readInput
fun main() {
val (year, day) = "2022" to "Day02"
fun calculateScore(input: List<String>, withPlay: Boolean): Int {
val lose = mapOf(1 to 0, 2 to 1, 0 to 2)
val won = mapOf(0 to 1, 1 to 2, 2 to 0)
return input.sumOf { round ->
val (op, result) = round.split(" ").map { it[0].code }
val opCode = op - 'A'.code
val meCode = result - 'X'.code
val (resultScore, playScore) = if (withPlay) {
when {
opCode == meCode -> 3
won[opCode]!! == meCode -> 6
else -> 0
} to meCode + 1
} else {
3 * meCode to when (meCode) {
0 -> lose[opCode]!!
1 -> opCode
else -> won[opCode]!!
} + 1
}
resultScore + playScore
}
}
fun part1(input: List<String>) =
calculateScore(input, withPlay = true)
fun part2(input: List<String>) =
calculateScore(input, withPlay = false)
val testInput = readInput(name = "${day}_test", year = year)
val input = readInput(name = day, year = year)
check(part1(testInput) == 15)
println(part1(input))
check(part2(testInput) == 12)
println(part2(input))
} | 1 | Kotlin | 2 | 30 | df1f04b90e81fbb9078a30f528d52295689f7de7 | 1,361 | aoc-kotlin | Apache License 2.0 |
lib/src/main/kotlin/com/bloidonia/advent/day06/Day06Optimized.kt | timyates | 433,372,884 | false | {"Kotlin": 48604, "Groovy": 33934} | package com.bloidonia.advent.day06
import com.bloidonia.advent.readText
import kotlin.collections.ArrayDeque
class ArrayPopulation(private val population: LongArray) {
fun generation() = (population.copyOfRange(1, 9) + population[0]).let {
it[6] += it[8]
ArrayPopulation(it)
}
fun size() = population.sum()
}
fun String.toArrayPopulation() =
ArrayPopulation(this.split(",").map { it.toInt() }.fold(LongArray(9) { 0L }) { arr, v -> arr[v]++; arr })
// Non-immutable but less CPU intensive
class DequePopulation(private val population: ArrayDeque<Long>) {
fun generation() = population.removeFirst().let {
population.addLast(it)
population[6] += it
this
}
fun size() = population.sum()
}
fun String.toDequePopulation() =
DequePopulation(this.split(",").map { it.toInt() }
.fold(ArrayDeque(LongArray(9) { 0L }.toList())) { arr, v -> arr[v]++; arr })
fun main() {
// array
val initial = readText("/day06input.txt").toArrayPopulation()
generateSequence(initial) { it.generation() }.run {
println(drop(80).first().size())
println(drop(256).first().size())
}
// ArrayDequeue is mutating, so make a new starter each time
generateSequence(readText("/day06input.txt").toDequePopulation()) { it.generation() }.run {
println(drop(80).first().size())
}
generateSequence(readText("/day06input.txt").toDequePopulation()) { it.generation() }.run {
println(drop(256).first().size())
}
}
| 0 | Kotlin | 0 | 1 | 9714e5b2c6a57db1b06e5ee6526eb30d587b94b4 | 1,529 | advent-of-kotlin-2021 | MIT License |
src/2023/Day02.kt | nagyjani | 572,361,168 | false | {"Kotlin": 369497} | package `2023`
import java.io.File
import java.util.*
import kotlin.math.max
fun main() {
Day02().solve()
}
class Day02 {
val input1 = """
Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green
Game 2: 1 blue, 2 green; 3 green, 4 blue, 1 red; 1 green, 1 blue
Game 3: 8 green, 6 blue, 20 red; 5 blue, 4 red, 13 green; 5 green, 1 red
Game 4: 1 green, 3 red, 6 blue; 3 green, 6 red; 3 green, 15 blue, 14 red
Game 5: 6 red, 1 blue, 3 green; 2 blue, 1 red, 2 green
""".trimIndent()
val input2 = """
two1nine
eightwothree
abcone2threexyz
xtwone3four
4nineeightseven2
zoneight234
7pqrstsixteen
""".trimIndent()
class Cubes() {
var red = 0
var green = 0
var blue = 0
fun from(s: String): Cubes {
val m =
s.split(",").filter { !it.isEmpty() }.map {
val l = it.split(" ").filter { !it.isEmpty() }
val n = l[0].toInt()
val c = l[1]
when (c) {
"red" -> red = n
"blue" -> blue = n
"green" -> green = n
}
}
return this
}
fun leTo(c: Cubes): Boolean {
return red <= c.red && green <= c.green && blue <= c.blue
}
fun add(c: Cubes): Cubes {
val c1 = Cubes()
c1.red = max(red, c.red)
c1.green = max(green, c.green)
c1.blue = max(blue, c.blue)
return c1
}
fun power(): Int {
return red * green * blue
}
}
fun solve() {
val f = File("src/2023/inputs/day02.in")
val s = Scanner(f)
// val s = Scanner(input1)
// val s = Scanner(input2)
val c = Cubes()
c.from("12 red, 13 green, 14 blue")
var sum1 = 0
var sum2 = 0
var lineix = 0
while (s.hasNextLine()) {
lineix++
val line = s.nextLine().trim()
if (line.isEmpty()) {
continue
}
val games = line.split(Regex("[:;]")).drop(1)
val c1 = Cubes()
if (games.all { c1.from(it).leTo(c) }) {
sum1 = sum1 + lineix
}
var c2 = Cubes()
games.forEach { c2 = c1.from(it).add(c2) }
val p = c2.power()
sum2 += p
}
print("$sum1 $sum2\n")
}
} | 0 | Kotlin | 0 | 0 | f0c61c787e4f0b83b69ed0cde3117aed3ae918a5 | 2,439 | advent-of-code | Apache License 2.0 |
src/Day08.kt | hufman | 573,586,479 | false | {"Kotlin": 29792} | open class ColumnView<E>(open val rows: List<List<E>>, val columnIndex: Int): AbstractMutableList<E>() {
override fun add(index: Int, element: E) { TODO("Not yet implemented") }
override fun removeAt(index: Int): E { TODO("Not yet implemented") }
override fun set(index: Int, element: E): E { TODO("Not yet implemented") }
override val size: Int
get() = rows.size
override fun get(index: Int): E {
return rows[index][columnIndex]
}
}
class MutableColumnView<E>(override val rows: List<MutableList<E>>, columnIndex: Int): ColumnView<E>(rows, columnIndex) {
override fun set(index: Int, element: E): E {
rows[index][columnIndex] = element
return element
}
}
fun <E> List<E>.takeUntilFound(filter: (element: E) -> Boolean): List<E> {
val output = ArrayList<E>()
this.forEach {
output.add(it)
val found = filter(it)
if (found) {
return output
}
}
return output
}
fun main() {
fun parse(input: List<String>): List<List<Short>> {
return input.map {line ->
line.asSequence().map {
it.digitToInt().toShort()
}.toList()
}
}
fun checkVisibility(treeRow: Iterable<Short>, visibility: MutableList<Short>) {
var maxHeight: Short = -1
treeRow.forEachIndexed { i, height ->
if (height > maxHeight) {
visibility[i] = 1
maxHeight = height
}
if (maxHeight == 9.toShort()) {
return
}
}
}
fun part1(input: List<String>): Int {
val trees = parse(input)
val visibility = Array(trees.size) { row ->
ShortArray(trees[row].size).toMutableList()
}.toMutableList()
trees.zip(visibility).forEach { (row, visibles) ->
checkVisibility(row, visibles)
checkVisibility(row.asReversed(), visibles.asReversed())
}
(0 until trees[0].size).forEach { columnIndex ->
val treeColumn = ColumnView(trees, columnIndex)
val visibles = MutableColumnView(visibility, columnIndex)
checkVisibility(treeColumn, visibles)
checkVisibility(treeColumn.asReversed(), visibles.asReversed())
}
return visibility.sumOf {
it.sum()
}
}
fun scenicScore(trees: List<List<Short>>, rowIndex: Int, colIndex: Int): Int {
val maxHeight = trees[rowIndex][colIndex]
val east = trees[rowIndex].subList(colIndex + 1, trees[rowIndex].size).takeUntilFound { it >= maxHeight }.count()
val west = trees[rowIndex].subList(0, colIndex).asReversed().takeUntilFound { it >= maxHeight }.count()
val column = ColumnView(trees, colIndex)
val north = column.subList(0, rowIndex).asReversed().takeUntilFound { it >= maxHeight }.count()
val south = column.subList(rowIndex + 1, trees.size).takeUntilFound { it >= maxHeight }.count()
// println("${colIndex}x${rowIndex} (${trees[rowIndex][colIndex]}) -> $north * $west * $south * $east")
return east * west * north * south
}
fun part2(input: List<String>): Int {
val trees = parse(input)
return trees.subList(1, trees.size - 1).mapIndexed { rowIndex, row ->
row.subList(1, row.size - 1).mapIndexed { colIndex, _ ->
scenicScore(trees, rowIndex + 1, colIndex + 1)
}.max()
}.max()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day08_test")
check(part1(testInput) == 21)
check(part2(testInput) == 8)
val input = readInput("Day08")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 1bc08085295bdc410a4a1611ff486773fda7fcce | 3,266 | aoc2022-kt | Apache License 2.0 |
src/main/day7/Day07.kt | Derek52 | 572,850,008 | false | {"Kotlin": 22102} | package main.day7
import main.readInput
import java.util.*
import kotlin.collections.HashSet
fun main() {
val input = readInput("day7/day7")
val firstHalf = false
testAlg(firstHalf)
if (firstHalf) {
println(part1(input))
} else {
println(part2(input))
}
}
data class Directory(var name: String, var size: Long = 0,
val children: MutableList<Directory> = mutableListOf())
fun part1(input: List<String>) : Long {
var currentDirectory = Directory("/")
val directoryList = mutableListOf<Directory>(currentDirectory)
val rootNode = currentDirectory
val previousDirectoryStack = Stack<Directory>()
previousDirectoryStack.push(currentDirectory)
for (line in input) {
//println(line)
val command = line.split(" ")
if (command[0] == "$") {
if (command[1] == "cd") {
if (command[2] == "..") {
currentDirectory = previousDirectoryStack.pop()
} else {
currentDirectory = Directory(command[2])
directoryList.add(currentDirectory)
//println("Current directory: ${currentDirectory.name} size: ${currentDirectory.size}")
previousDirectoryStack.peek().children.add(currentDirectory)
previousDirectoryStack.push(currentDirectory)
}
} else if(command[1] == "ls") {
}
} else if (command[0] == "dir"){
} else {
currentDirectory.size += command[0].toLong()
//println("${currentDirectory.name}.size += ${command[0]}")
//println("${currentDirectory.size}.size += ${command[0]}")
}
}
val sums = mutableListOf<Long>()
sumDirectories(rootNode, sums, HashSet())
println("Root: ${rootNode.name} size: ${rootNode.size} ")
for (child in rootNode.children) {
println("${child.name} is a child")
}
var totalSum = 0L
for (directory in directoryList) {
if (directory.size <= 100000) {
totalSum += directory.size
}
}
return totalSum
}
fun sumDirectories(directory: Directory, sums: MutableList<Long>, visit: HashSet<Directory>) : Long {
if (visit.contains(directory)) {
return 0
}
if (directory.children.isEmpty()) {
//println("${directory.name} has size ${directory.size}")
return directory.size
}
visit.add(directory)
for (child in directory.children) {
directory.size += sumDirectories(child, sums, visit)
}
//println("${directory.name} has size ${directory.size}")
return directory.size
}
fun part2(input: List<String>) : Long {
var currentDirectory = Directory("/")
val directoryList = mutableListOf<Directory>(currentDirectory)
val rootNode = currentDirectory
val previousDirectoryStack = Stack<Directory>()
previousDirectoryStack.push(currentDirectory)
for (line in input) {
val command = line.split(" ")
if (command[0] == "$") {
if (command[1] == "cd") {
if (command[2] == "..") {
currentDirectory = previousDirectoryStack.pop()
} else {
currentDirectory = Directory(command[2])
directoryList.add(currentDirectory)
previousDirectoryStack.peek().children.add(currentDirectory)
previousDirectoryStack.push(currentDirectory)
}
} else if(command[1] == "ls") {
}
} else if (command[0] == "dir"){
} else {
currentDirectory.size += command[0].toLong()
}
}
val sums = mutableListOf<Long>()
sumDirectories(rootNode, sums, HashSet())
var totalSum = rootNode.size
val space = 70000000 - totalSum
val neededSpace = 30000000 - space
var minDelete = totalSum
for (directory in directoryList) {
if (directory.size >= neededSpace) {
if (directory.size <= minDelete) {
minDelete = directory.size
}
}
}
return minDelete
}
fun testAlg(firstHalf : Boolean) {
val input = readInput("day7/day7_test")
if (firstHalf) {
println(part1(input))
} else {
println(part2(input))
}
} | 0 | Kotlin | 0 | 0 | c11d16f34589117f290e2b9e85f307665952ea76 | 4,359 | 2022AdventOfCodeKotlin | Apache License 2.0 |
kotlin/2021/round-1a/hacked-exam/src/main/kotlin/testset1and2/TestSet1And2Solution.kt | ShreckYe | 345,946,821 | false | null | package testset1and2
import testset1and2.Fraction.Companion.one
import java.math.BigInteger
fun main() {
val t = readLine()!!.toInt()
repeat(t, ::testCase)
}
fun testCase(ti: Int) {
val (n, q) = readLine()!!.splitToSequence(' ').map { it.toInt() }.toList()
val ass = List(n) {
val lineInputs = readLine()!!.splitToSequence(' ').toList()
lineInputs[0].map { it == 'T' } to lineInputs[1].toInt()
}
val answers: List<Boolean>
val expectedScore: Fraction
when (n) {
1 -> {
val (a0, s0) = ass[0]
if (s0 divBy q >= half) {
answers = a0
expectedScore = s0.toFraction()
} else {
answers = a0.map { !it }
expectedScore = (q - s0).toFraction()
}
}
2 -> {
val (a0, s0) = ass[0]
val (a1, s1) = ass[1]
val (sameAs, differentAs) = (a0 zip a1).withIndex()
.partition { it.value.first == it.value.second }
val numStudent0CorrectInDifferentAs = (differentAs.size + s0 - s1) / 2
val numStudent0CorrectInSameAs = s0 - numStudent0CorrectInDifferentAs
val trueProbabilities = Array<Fraction?>(q) { null }.also {
val numSameAs = sameAs.size
for ((i, a01) in sameAs) {
val correctProbability = numStudent0CorrectInSameAs divBy numSameAs
it[i] = if (a01.first) correctProbability else one - correctProbability
}
val numDifferentAs = differentAs.size
for ((i, a01) in differentAs) {
val correctProbability = numStudent0CorrectInDifferentAs divBy numDifferentAs
it[i] = if (a01.first) correctProbability else one - correctProbability
}
} as Array<Fraction>
val answerAneCorrectProbabilities =
trueProbabilities.map { if (it >= half) true to it else false to (one - it) }
answers = answerAneCorrectProbabilities.map { it.first }
expectedScore = answerAneCorrectProbabilities.asSequence().map { it.second }.reduce(Fraction::plus)
}
else -> throw IllegalArgumentException()
}
println("Case #${ti + 1}: ${answers.joinToString("") { if (it) "T" else "F" }} $expectedScore")
}
val half = 1 divBy 2
// copied from Fractions.kt
data class Fraction internal constructor(val numerator: BigInteger, val denominator: BigInteger) {
init {
require(denominator > BigInteger.ZERO)
}
operator fun plus(that: Fraction) =
reducedFraction(
numerator * that.denominator + that.numerator * denominator,
denominator * that.denominator
)
operator fun unaryMinus() =
Fraction(-numerator, denominator)
operator fun minus(that: Fraction) =
this + -that
operator fun times(that: Fraction) =
reducedFraction(numerator * that.numerator, denominator * that.denominator)
fun reciprocal() =
if (numerator > BigInteger.ZERO) Fraction(denominator, numerator)
else Fraction(-denominator, -numerator)
operator fun div(that: Fraction) =
this * that.reciprocal()
operator fun compareTo(that: Fraction) =
(numerator * that.denominator).compareTo(that.numerator * denominator)
override fun toString(): String =
"$numerator/$denominator"
fun toSimplestString(): String =
if (denominator == BigInteger.ONE) numerator.toString()
else toString()
companion object {
val zero = Fraction(BigInteger.ZERO, BigInteger.ONE)
val one = Fraction(BigInteger.ONE, BigInteger.ONE)
}
}
fun reducedFraction(numerator: BigInteger, denominator: BigInteger): Fraction {
val gcd = numerator.gcd(denominator)
val nDivGcd = numerator / gcd
val dDivGcd = denominator / gcd
return if (denominator > BigInteger.ZERO) Fraction(nDivGcd, dDivGcd)
else Fraction(-nDivGcd, -dDivGcd)
}
infix fun BigInteger.divBy(that: BigInteger) = reducedFraction(this, that)
infix fun Int.divBy(that: Int) = toBigInteger() divBy that.toBigInteger()
infix fun Long.divBy(that: Long) = toBigInteger() divBy that.toBigInteger()
fun BigInteger.toFraction() =
Fraction(this, BigInteger.ONE)
fun Int.toFraction() = toBigInteger().toFraction()
fun Long.toFraction() = toBigInteger().toFraction() | 0 | Kotlin | 1 | 1 | 743540a46ec157a6f2ddb4de806a69e5126f10ad | 4,454 | google-code-jam | MIT License |
src/main/java/challenges/cracking_coding_interview/sorting_and_searching/sorted_matrix_search/QuestionB.kt | ShabanKamell | 342,007,920 | false | null | package challenges.cracking_coding_interview.sorting_and_searching.sorted_matrix_search
import challenges.util.AssortedMethods.printMatrix
object QuestionB {
private fun partitionAndSearch(
matrix: Array<IntArray>,
origin: Coordinate,
dest: Coordinate,
pivot: Coordinate,
x: Int
): Coordinate? {
val lowerLeftOrigin = Coordinate(pivot.row, origin.column)
val lowerLeftDest = Coordinate(dest.row, pivot.column - 1)
val upperRightOrigin = Coordinate(origin.row, pivot.column)
val upperRightDest = Coordinate(pivot.row - 1, dest.column)
return findElement(
matrix,
lowerLeftOrigin,
lowerLeftDest,
x
)
?: return findElement(
matrix,
upperRightOrigin,
upperRightDest,
x
)
}
private fun findElement(matrix: Array<IntArray>, origin: Coordinate, dest: Coordinate, x: Int): Coordinate? {
if (!origin.inbounds(matrix) || !dest.inbounds(matrix)) {
return null
}
if (matrix[origin.row][origin.column] == x) {
return origin
} else if (!origin.isBefore(dest)) {
return null
}
/* Set start to start of diagonal and end to the end of the diagonal. Since
* the grid may not be square, the end of the diagonal may not equal dest.
*/
val start = origin.clone() as Coordinate
val diagDist = Math.min(dest.row - origin.row, dest.column - origin.column)
val end = Coordinate(start.row + diagDist, start.column + diagDist)
val p = Coordinate(0, 0)
/* Do binary search on the diagonal, looking for the first element greater than x */while (start.isBefore(end)) {
p.setToAverage(start, end)
if (x > matrix[p.row][p.column]) {
start.row = p.row + 1
start.column = p.column + 1
} else {
end.row = p.row - 1
end.column = p.column - 1
}
}
/* Split the grid into quadrants. Search the bottom left and the top right. */return partitionAndSearch(
matrix,
origin,
dest,
start,
x
)
}
fun findElement(matrix: Array<IntArray>, x: Int): Coordinate? {
val origin = Coordinate(0, 0)
val dest = Coordinate(matrix.size - 1, matrix[0].size - 1)
return findElement(matrix, origin, dest, x)
}
@JvmStatic
fun main(args: Array<String>) {
val matrix = arrayOf(
intArrayOf(15, 30, 50, 70, 73),
intArrayOf(35, 40, 100, 102, 120),
intArrayOf(36, 42, 105, 110, 125),
intArrayOf(46, 51, 106, 111, 130),
intArrayOf(48, 55, 109, 140, 150)
)
printMatrix(matrix)
val m = matrix.size
val n = matrix[0].size
var count = 0
val littleOverTheMax = matrix[m - 1][n - 1] + 10
for (i in 0 until littleOverTheMax) {
val c = findElement(matrix, i)
if (c != null) {
println(i.toString() + ": (" + c.row + ", " + c.column + ")")
count++
}
}
println("Found $count unique elements.")
}
} | 0 | Kotlin | 0 | 0 | ee06bebe0d3a7cd411d9ec7b7e317b48fe8c6d70 | 3,444 | CodingChallenges | Apache License 2.0 |
src/main/kotlin/be/swsb/aoc2021/day1/Day1.kt | Sch3lp | 433,542,959 | false | {"Kotlin": 90751} | package be.swsb.aoc2021.day1
object Day1 {
fun solve1(depthMeasurementInput: List<String>): Int {
return depthMeasurementInput
.map { it.toDepthMeasurement() }
.zipWithNext()
.count { (prev, cur) -> prev < cur }
}
fun solve2(depthMeasurementInput: List<String>): Int {
return depthMeasurementInput
.map { it.toDepthMeasurement() }
.toDepthMeasurementSums()
.zipWithNext()
.count { (prev, cur) -> prev < cur }
}
}
private fun String.toDepthMeasurement() = DepthMeasurement(this)
@JvmInline
private value class DepthMeasurement(val value: Int) {
constructor(value: String) : this(value.toInt())
operator fun compareTo(other: DepthMeasurement) = value.compareTo(other.value)
}
private fun List<DepthMeasurement>.toDepthMeasurementSums(): List<DepthMeasurementSum> {
return this
.windowed(3)
.map { it.let { (m1, m2, m3) -> DepthMeasurementSum(m1, m2, m3) } }
}
private data class DepthMeasurementSum(
private val measurement1: DepthMeasurement,
private val measurement2: DepthMeasurement,
private val measurement3: DepthMeasurement,
) {
operator fun compareTo(other: DepthMeasurementSum): Int {
return this.sum().compareTo(other.sum())
}
private fun sum() = listOf(measurement1, measurement2, measurement3).sumOf { it.value }
}
| 0 | Kotlin | 0 | 0 | 7662b3861ca53214e3e3a77c1af7b7c049f81f44 | 1,408 | Advent-of-Code-2021 | MIT License |
src/Day09.kt | thelmstedt | 572,818,960 | false | {"Kotlin": 30245} | import java.io.File
import kotlin.math.abs
enum class Cardinal {
N, NE, E, SE, S, SW, W, NW
}
typealias Point = Pair<Int, Int>
fun move(p: Point, dir: Cardinal): Pair<Int, Int> {
return when (dir) {
Cardinal.N -> p.first to p.second - 1
Cardinal.NE -> p.first + 1 to p.second - 1
Cardinal.E -> p.first + 1 to p.second
Cardinal.SE -> p.first + 1 to p.second + 1
Cardinal.S -> p.first to p.second + 1
Cardinal.SW -> p.first - 1 to p.second + 1
Cardinal.W -> p.first - 1 to p.second
Cardinal.NW -> p.first - 1 to p.second - 1
}
}
fun adjacent(p1: Point, p2: Point): Boolean {
val deltaX = abs(p1.first - p2.first)
val deltaY = abs(p1.second - p2.second)
return deltaX <= 1 && deltaY <= 1
}
fun relativeMove(head: Point, tail: Point, dir: String): Pair<Point, Point> {
val head1 = straight(dir, head)
return if (adjacent(head1, tail)) {
head1 to tail
} else {
head1 to tail(head1, tail)
}
}
private fun tail(relative: Point, tail: Point): Point {
val isWest = relative.first > tail.first
val isNorth = relative.second > tail.second
val NS = tail.first == relative.first
val EW = tail.second == relative.second
val tail1: Point = if (NS || EW) {
straight(
if (NS) {
if (isNorth) {
"D"
} else {
"U"
}
} else if (EW) {
if (isWest) {
"R"
} else {
"L"
}
} else {
error("WHAT")
}, tail
)
} else {
// diagonal
move(
tail, when (isWest to isNorth) {
(true to true) -> Cardinal.SE
(false to false) -> Cardinal.NW
(true to false) -> Cardinal.NE
(false to true) -> Cardinal.SW
else -> error("Bad")
}
)
}
return tail1
}
private fun straight(dir: String, head: Point): Pair<Int, Int> {
val head1 = when (dir) {
"U" -> move(head, Cardinal.N)
"R" -> move(head, Cardinal.E)
"D" -> move(head, Cardinal.S)
"L" -> move(head, Cardinal.W)
else -> error(dir)
}
return head1
}
fun main() {
fun part1(text: String) {
val moves = text
.lineSequence()
.filter { it.isNotBlank() }
.map { it.split(" ") }
.map { it[0] to it[1].toInt() }
val tailPos = mutableSetOf<Pair<Int, Int>>() //x y
val rope = mutableListOf(0 to 6, 0 to 6)
tailPos.add(rope.last())
moves.forEach { (dir, c) ->
(0 until c).forEach { _ ->
val (head1, tail1) = relativeMove(rope[0], rope[1], dir)
rope[0] = head1
rope[1] = tail1
tailPos.add(rope.last())
}
}
println(tailPos.size)
}
fun part2(text: String) {
val moves = text
.lineSequence()
.filter { it.isNotBlank() }
.map { it.split(" ") }
.map {
val dir = it[0]
dir to it[1].toInt()
}
val tailPos = mutableSetOf<Pair<Int, Int>>() //x y
val start = 13 to 16
val rope = mutableListOf(start)
(0 until 9).forEach { _ -> rope.add(start) }
tailPos.add(rope.last())
moves.forEach { (dir, c) ->
(0 until c).forEach { _ ->
val (head1, tail1) = relativeMove(rope[0], rope[1], dir)
rope[0] = head1
rope[1] = tail1
(2 until 10).forEach { i ->
val head = rope[i - 1]
val tail = rope[i]
if (!adjacent(head, tail)) {
rope[i] = tail(head, tail)
}
}
tailPos.add(rope.last())
}
// display(start, rope)
}
println(tailPos.size)
}
val testInput = File("src", "Day09_test.txt").readText()
val input = File("src", "Day09.txt").readText()
part1(testInput)
part1(input)
part2(
"""
R 5
U 8
L 8
D 3
R 17
D 10
L 25
U 20
""".trimIndent()
)
part2(input)
}
fun display(
start: Pair<Int, Int>,
rope: List<Pair<Int, Int>>,
) {
if (false) return
println("$rope")
val size = "..........................".length * 2
val map = (0..size).map { ".".repeat(size).toCharArray().map { it.toString() }.toMutableList() }.toMutableList()
rope.forEachIndexed { index, pair ->
val (x, y) = pair
map[y][x] = if (index == 0) "H" else index.toString()
}
map[start.second][start.first] = "S"
map.forEach {
println(it.joinToString(""))
}
println("------------")
}
fun displayPos(
start: Pair<Int, Int>,
rope: List<Pair<Int, Int>>,
) {
if (false) return
println("$rope")
val size = "..........................".length * 2
val map = (0..size).map { ".".repeat(size).toCharArray().map { it.toString() }.toMutableList() }.toMutableList()
rope.forEachIndexed { index, pair ->
val (x, y) = pair
map[y][x] = "#"
}
map[start.second][start.first] = "S"
map.forEach {
println(it.joinToString(""))
}
println("------------")
} | 0 | Kotlin | 0 | 0 | e98cd2054c1fe5891494d8a042cf5504014078d3 | 5,462 | advent2022 | Apache License 2.0 |
grind-75-kotlin/src/main/kotlin/ImplementQueueUsingStacks.kt | Codextor | 484,602,390 | false | {"Kotlin": 27206} | /**
* Implement a first in first out (FIFO) queue using only two stacks.
* The implemented queue should support all the functions of a normal queue (push, peek, pop, and empty).
*
* Implement the .MyQueue class:
*
* void push(int x) Pushes element x to the back of the queue.
* int pop() Removes the element from the front of the queue and returns it.
* int peek() Returns the element at the front of the queue.
* boolean empty() Returns true if the queue is empty, false otherwise.
* Notes:
*
* You must use only standard operations of a stack,
* which means only push to top, peek/pop from top, size, and is empty operations are valid.
* Depending on your language, the stack may not be supported natively.
* You may simulate a stack using a list or deque (double-ended queue) as long as you use only a stack's standard operations.
*
*
* Example 1:
*
* Input
* [".MyQueue", "push", "push", "peek", "pop", "empty"]
* [[], [1], [2], [], [], []]
* Output
* [null, null, null, 1, 1, false]
*
* Explanation
* .MyQueue myQueue = new .MyQueue();
* myQueue.push(1); // queue is: [1]
* myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
* myQueue.peek(); // return 1
* myQueue.pop(); // return 1, queue is [2]
* myQueue.empty(); // return false
*
*
* Constraints:
*
* 1 <= x <= 9
* At most 100 calls will be made to push, pop, peek, and empty.
* All the calls to pop and peek are valid.
*
*
* Follow-up: Can you implement the queue such that each operation is amortized O(1) time complexity?
* In other words, performing n operations will take overall O(n) time even if one of those operations may take longer.
* @see <a href="https://leetcode.com/problems/implement-queue-using-stacks/">LeetCode</a>
*/
class MyQueue() {
private val inputStack = ArrayDeque<Int>()
private val outputStack = ArrayDeque<Int>()
fun push(x: Int) {
inputStack.add(x)
}
fun pop(): Int {
prepareOutputStack()
return outputStack.removeLast()
}
fun peek(): Int {
prepareOutputStack()
return outputStack.last()
}
fun empty(): Boolean {
return inputStack.isEmpty() && outputStack.isEmpty()
}
private fun prepareOutputStack() {
if (outputStack.isEmpty()) {
while (inputStack.isNotEmpty()) {
outputStack.addLast(inputStack.removeLast())
}
}
}
}
/**
* Your .MyQueue object will be instantiated and called as such:
* var obj = .MyQueue()
* obj.push(x)
* var param_2 = obj.pop()
* var param_3 = obj.peek()
* var param_4 = obj.empty()
*/
| 0 | Kotlin | 0 | 0 | 87aa60c2bf5f6a672de5a9e6800452321172b289 | 2,627 | grind-75 | Apache License 2.0 |
src/aoc2023/Day12.kt | anitakar | 576,901,981 | false | {"Kotlin": 124382} | package aoc2023
import readInput
fun main() {
fun arrangementForSequence(sequence: String): String {
var result = ""
var count = 0
for (i in sequence.indices) {
if (sequence[i] == '#') {
count += 1
} else {
if (count > 0) {
result = "$result,$count"
count = 0
}
}
}
if (count > 0) {
result = "$result,$count"
}
if (result.isNotEmpty()) {
result = result.removeRange(0, 1)
}
return result
}
fun replaceFirstQuestionMark(sequence: String): MutableList<String> {
val qustionMarkIndex = sequence.indexOfFirst { it == '?' }
if (qustionMarkIndex == -1) {
return mutableListOf(sequence)
} else {
return mutableListOf(
sequence.substring(0, qustionMarkIndex) + "." + sequence.substring(qustionMarkIndex + 1),
sequence.substring(0, qustionMarkIndex) + "#" + sequence.substring(qustionMarkIndex + 1)
)
}
}
fun replaceQuestionMarks(sequence: String): MutableList<String> {
var current = mutableListOf<String>()
current.add(sequence)
var new = mutableListOf<String>()
var newAdded = false
do {
newAdded = false
for (seq in current) {
val toAdd = replaceFirstQuestionMark(seq)
if (toAdd.size > 1) {
newAdded = true
}
new.addAll(toAdd)
}
current = new
new = mutableListOf()
} while (newAdded)
return current
}
fun part1(lines: List<String>): Int {
var sum = 0
for (line in lines) {
val spiltted = line.split(" ")
val sequence = spiltted[0]
val arrangement = spiltted[1]
val allCombinations = replaceQuestionMarks(sequence)
for (replaced in allCombinations) {
if (arrangementForSequence(replaced) == arrangement) {
sum += 1
}
}
}
return sum
}
// println(arrangementForSequence("#.#.###"))
// println(arrangementForSequence(".#...#....###."))
// println(arrangementForSequence(".#.###.#.######"))
// println(arrangementForSequence("####.#...#..."))
// println(arrangementForSequence("#....######..#####."))
// println(arrangementForSequence(".###.##....#"))
// println(part1(listOf("???.### 1,1,3")))
println(part1(readInput("aoc2023/Day12_test")))
println(part1(readInput("aoc2023/Day12")))
} | 0 | Kotlin | 0 | 1 | 50998a75d9582d4f5a77b829a9e5d4b88f4f2fcf | 2,722 | advent-of-code-kotlin | Apache License 2.0 |
src/Day01.kt | camina-apps | 572,935,546 | false | {"Kotlin": 7782} | fun main() {
fun caloriesPerElve(rucksack: String) =
rucksack.replace(",", "")
.trim()
.split(" ")
.sumOf { it.toInt() }
fun getElvesList(input: List<String>): List<String> =
input.toString()
.removePrefix("[")
.removeSuffix("]")
.split(" ,")
fun part1(input: List<String>): Int {
val elves = getElvesList(input)
return elves.map { caloriesPerElve(it) }.max()
}
fun part2(input: List<String>): Int {
val elves = getElvesList(input)
return elves
.map { caloriesPerElve(it) }
.sortedDescending()
.slice(0..2)
.sum()
}
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 | fb6c6176f8c127e9d36aa0b7ae1f0e32b5c31171 | 921 | aoc_2022 | Apache License 2.0 |
advent23-kt/app/src/main/kotlin/dev/rockyj/advent_kt/Day3.kt | rocky-jaiswal | 726,062,069 | false | {"Kotlin": 41834, "Ruby": 2966, "TypeScript": 2848, "JavaScript": 830, "Shell": 455, "Dockerfile": 387} | package dev.rockyj.advent_kt
private fun part1(input: List<String>) {
val symbols = mutableMapOf<Pair<Int, Int>, String>()
var lenX = 0
input.forEachIndexed { idx, line ->
val sls = line.trim().split("")
lenX = sls.subList(1, sls.size - 1).size
sls.subList(1, sls.size - 1).forEachIndexed { idx2, s -> symbols.put(Pair(idx, idx2), s.trim()) }
}
val numbers = mutableListOf<Pair<String, Pair<Int, Int>>>()
var s = ""
symbols.forEach { symb ->
if (symb.value.matches(Regex("\\d"))) {
s += symb.value
}
if (symb.key.second == lenX - 1) {
if (s.isNotBlank() && symb.value.matches(Regex("\\d"))) {
numbers.add(Pair(s, Pair(symb.key.first, symb.key.second)))
}
if (s.isNotBlank() && !symb.value.matches(Regex("\\d"))) {
numbers.add(Pair(s, Pair(symb.key.first, symb.key.second - 1)))
}
s = ""
}
if (!symb.value.matches(Regex("\\d")) && symb.key.second != lenX - 1) {
if (s.isNotBlank()) {
numbers.add(Pair(s, Pair(symb.key.first, symb.key.second - 1)))
}
s = ""
}
}
val numsWithPos = numbers.map { num ->
val lastPos = num.second
val newPos = (0..<num.first.length).map { pos ->
Pair(lastPos.first, lastPos.second - pos)
}
Pair(num.first, newPos.reversed())
}
// println(numbers)
val res = findPartNumbers(numsWithPos.toList(), symbols.toMap())
println(res.map { it.first }.map { Integer.parseInt(it) }.sum())
}
private fun part2(input: List<String>) {
val symbols = mutableMapOf<Pair<Int, Int>, String>()
var lenX = 0
input.forEachIndexed { idx, line ->
val sls = line.trim().split("")
lenX = sls.subList(1, sls.size - 1).size
sls.subList(1, sls.size - 1).forEachIndexed { idx2, s -> symbols.put(Pair(idx, idx2), s.trim()) }
}
val numbers = mutableListOf<Pair<String, Pair<Int, Int>>>()
var s = ""
symbols.forEach { symb ->
if (symb.value.matches(Regex("\\d"))) {
s += symb.value
}
if (symb.key.second == lenX - 1) {
if (s.isNotBlank() && symb.value.matches(Regex("\\d"))) {
numbers.add(Pair(s, Pair(symb.key.first, symb.key.second)))
}
if (s.isNotBlank() && !symb.value.matches(Regex("\\d"))) {
numbers.add(Pair(s, Pair(symb.key.first, symb.key.second - 1)))
}
s = ""
}
if (!symb.value.matches(Regex("\\d")) && symb.key.second != lenX - 1) {
if (s.isNotBlank()) {
numbers.add(Pair(s, Pair(symb.key.first, symb.key.second - 1)))
}
s = ""
}
}
val numsWithPos = numbers.map { num ->
val lastPos = num.second
val newPos = (0..<num.first.length).map { pos ->
Pair(lastPos.first, lastPos.second - pos)
}
Pair(num.first, newPos.reversed())
}
// println(numbers)
val allStars = symbols.filter { symbol ->
symbol.value == "*"
}
var sgr = 0
allStars.forEach { star ->
val neighbours = findNeighbours(star.key.first, star.key.second)
// println(star)
// println(neighbours)
val starNums = numsWithPos.filter { numWithPos ->
numWithPos.second.any {
neighbours.contains(it)
}
}
// println(starNums)
val prod = if (starNums.size == 2) {
starNums
.map { it.first }
.map { Integer.parseInt(it) }
.fold(1) { acc, i -> acc * i }
} else {
0
}
//println(prod)
sgr += prod
}
println(sgr)
}
fun findPartNumbers(
numsWithPos: List<Pair<String, List<Pair<Int, Int>>>>,
allSymbols: Map<Pair<Int, Int>, String>
): List<Pair<String, List<Pair<Int, Int>>>> {
return numsWithPos.filter { numWithPos ->
val allDots = numWithPos.second
.flatMap { findNeighbours(it.first, it.second) }
.filter { !numWithPos.second.contains(it) }
.map {
allSymbols[it]
}
.filterNotNull()
.all {
it == "."
}
!allDots
}
}
fun findNeighbours(x: Int, y: Int): List<Pair<Int, Int>> {
return listOf(
Pair(x - 1, y - 1),
Pair(x - 1, y),
Pair(x - 1, y + 1),
Pair(x, y - 1),
Pair(x, y + 1),
Pair(x + 1, y - 1),
Pair(x + 1, y),
Pair(x + 1, y + 1)
)
}
fun main() {
val lines = fileToArr("day3_2.txt")
part1(lines)
part2(lines)
} | 0 | Kotlin | 0 | 0 | a7bc1dfad8fb784868150d7cf32f35f606a8dafe | 4,795 | advent-2023 | MIT License |
src/day2/day02.kt | kacperhreniak | 572,835,614 | false | {"Kotlin": 85244} | private fun itemPoint(item: Char): Int = when {
item == 'X' || item == 'A' -> 0 // rock
item == 'Y' || item == 'B' -> 1 // paper
item == 'Z' || item == 'C' -> 2 // scisorr
else -> 0
}
private fun part1(input: List<String>): Int {
fun winning(first: Char, second: Char): Int {
fun position(item: Char): Int = when {
item == 'X' || item == 'A' -> 0 // rock
item == 'Z' || item == 'C' -> 1 // scisorr
item == 'Y' || item == 'B' -> 2 // paper
else -> throw NullPointerException("")
}
val positionFirst = position(first)
val positionSecond = position(second)
return if ((positionSecond + 1) % 3 == positionFirst) {
6
} else if(positionSecond == positionFirst) {
3
} else 0
}
var points = 0
for (line in input) {
val temp = winning(line[0], line[2]) + itemPoint(line[2]) + 1
points += temp
}
return points
}
private fun part2(input: List<String>): Int {
fun pointForResult(input: Char): Int = when (input) {
'X' -> 0
'Y' -> 3
'Z' -> 6
else -> throw NullPointerException()
}
fun game(result: Int, oponent: Int): Int {
if(result == 3) return oponent
if(result == 0) return (oponent + 2) % 3
if(result == 6) return (oponent + 1) % 3
throw NullPointerException()
}
var points = 0
for (line in input) {
val first = itemPoint(line[0])
val result = pointForResult(line[2])
val temp = game(result, first) + 1 + result
points += temp
}
return points
}
fun main() {
val input = readInput("day2/input")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 1 | 0 | 03368ffeffa7690677c3099ec84f1c512e2f96eb | 1,812 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/com/github/solairerove/algs4/leprosorium/strings/LongestPalindrome.kt | solairerove | 282,922,172 | false | {"Kotlin": 251919} | package com.github.solairerove.algs4.leprosorium.strings
fun main() {
print(longestPalindrome("arpkqqkpfkpdp")) // pkqqkp
}
// O(n^2) time | O(n) space
private fun longestPalindrome(s: String): String {
var longest = listOf(0, 1)
for (i in 1 until s.length) {
val odd = getLongestPalindrome(s, i - 1, i + 1)
val even = getLongestPalindrome(s, i - 1, i)
val curr = if (odd[1] - odd[0] > even[1] - odd[0]) odd else even
longest = if (longest[1] - longest[0] > curr[1] - curr[0]) longest else curr
}
return s.substring(longest[0], longest[1])
}
private fun getLongestPalindrome(s: String, lowIdx: Int, highIdx: Int): List<Int> {
var low = lowIdx
var high = highIdx
while (low > 0 && high < s.length) {
if (s[low] != s[high]) break
low--
high++
}
return listOf(low + 1, high)
}
| 1 | Kotlin | 0 | 3 | 64c1acb0c0d54b031e4b2e539b3bc70710137578 | 877 | algs4-leprosorium | MIT License |
src/main/kotlin/g0001_0100/s0005_longest_palindromic_substring/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g0001_0100.s0005_longest_palindromic_substring
// #Medium #Top_100_Liked_Questions #Top_Interview_Questions #String #Dynamic_Programming
// #Data_Structure_II_Day_9_String #Algorithm_II_Day_14_Dynamic_Programming
// #Dynamic_Programming_I_Day_17 #Udemy_Strings #Big_O_Time_O(n)_Space_O(n)
// #2023_07_03_Time_162_ms_(99.00%)_Space_36.6_MB_(79.10%)
class Solution {
fun longestPalindrome(s: String): String {
val newStr = CharArray(s.length * 2 + 1)
newStr[0] = '#'
for (i in s.indices) {
newStr[2 * i + 1] = s[i]
newStr[2 * i + 2] = '#'
}
val dp = IntArray(newStr.size)
var friendCenter = 0
var friendRadius = 0
var lpsCenter = 0
var lpsRadius = 0
for (i in newStr.indices) {
dp[i] = if (friendCenter + friendRadius > i) Math.min(
dp[friendCenter * 2 - i],
friendCenter + friendRadius - i
) else 1
while (i + dp[i] < newStr.size && i - dp[i] >= 0 && newStr[i + dp[i]] == newStr[i - dp[i]]) {
dp[i]++
}
if (friendCenter + friendRadius < i + dp[i]) {
friendCenter = i
friendRadius = dp[i]
}
if (lpsRadius < dp[i]) {
lpsCenter = i
lpsRadius = dp[i]
}
}
return s.substring((lpsCenter - lpsRadius + 1) / 2, (lpsCenter + lpsRadius - 1) / 2)
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,485 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/com/aoc2023/day6/Day6.kt | brookseakate | 729,329,997 | false | {"Kotlin": 8231} | package main.kotlin.com.aoc2023.day6
import kotlin.math.pow
import kotlin.math.sqrt
class Day6 {
companion object {
fun main() {
println("hello Day 6")
val (timesList, distancesList) = getInput()
println(getProductOfWinningStrategies(timesList, distancesList))
}
fun parseInput() {
TODO("Super boring here, skip for this one")
}
private fun getInput(): Pair<List<Long>, List<Long>> /* timeList, distanceList */ {
val sampleTimes = listOf(71530L)
val sampleDistances = listOf(940200L)
val inputTimes = listOf(44826981L)
val inputDistances = listOf(202107611381458L)
// return Pair(sampleTimes, sampleDistances)
return Pair(inputTimes, inputDistances)
}
private fun getProductOfWinningStrategies(
// would do something OO, but not interesting
raceLengthList: List<Long>,
recordDistanceList: List<Long>,
): Long {
check(raceLengthList.size == recordDistanceList.size) { "Input is wrong!!" }
val winningStrategiesPerRaceList = mutableListOf<Long>()
raceLengthList.forEachIndexed { index, raceLength ->
val (minWinningButtonPress, maxWinningButtonPress) = getMinAndMaxPresses(
raceLength = raceLength,
recordDistance = recordDistanceList[index]
)
val winningStrategiesCount = maxWinningButtonPress - minWinningButtonPress + 1 // +1 = inclusive range count
winningStrategiesPerRaceList.add(winningStrategiesCount)
}
return winningStrategiesPerRaceList.reduce { x, y -> x * y }
}
private fun getMinAndMaxPresses(
raceLength: Long,
recordDistance: Long,
// feel like we'll want an a (coefficient for our x^2) for part 2, but will resist adding til then...
): Pair<Long, Long> /* Min, Max */ {
// quadratic equation: ax^2 + bx + c
// our parabola is shaped: y = -x^2 + bx, where:
// a = -1
// b = raceLength
// and we'll solve for y > recordDistance – SO set c = -recordDistance
val a = -1
val b = raceLength
val c = -recordDistance
// quadratic formula: x = (-b +/- sqrt(b^2 - 4ac)) / 2a
val recordMinPress = (-b + sqrt(b.toDouble().pow(2) - (4*a*c))) / 2*a
val recordMaxPress = (-b - sqrt(b.toDouble().pow(2) - (4*a*c))) / 2*a
val ourMinPress = recordMinPress.toLong() + 1
val ourMaxPress = recordMaxPress.toLong() // don't add here – we want to hold LESS long
.let { if (it.compareTo(recordMaxPress) == 0) {
// ensure we're *under* theirs (handles for case: recordMaxPress == its Int value)
it - 1
} else it
}
return Pair(ourMinPress, ourMaxPress)
}
}
} | 0 | Kotlin | 0 | 0 | 885663f27a8d5f6e6c5eaf046df4234b49bc53b9 | 2,731 | advent-of-code-2023 | MIT License |
src/main/kotlin/io/github/clechasseur/adventofcode2021/Day22.kt | clechasseur | 435,726,930 | false | {"Kotlin": 315943} | package io.github.clechasseur.adventofcode2021
import io.github.clechasseur.adventofcode2021.data.Day22Data
import io.github.clechasseur.adventofcode2021.util.Pt3D
import kotlin.math.max
import kotlin.math.min
object Day22 {
private val data = Day22Data.data
fun part1(): Int = data.lineSequence().take(20).map { it.toCuboid() }.fold(Core(emptySet())) { core, cuboid ->
core apply cuboid
}.cubes.size
fun part2(): Long = countOn(data.lines().map { it.toCuboid() })
private class Core(val cubes: Set<Pt3D>)
private class Cuboid(val on: Boolean, val xr: IntRange, val yr: IntRange, val zr: IntRange) {
val cubes: Set<Pt3D>
get() = xr.flatMap { x ->
yr.flatMap { y ->
zr.map { z -> Pt3D(x, y, z) }
}
}.toSet()
val size: Long
get() = xr.size * yr.size * zr.size
}
private infix fun Core.apply(cuboid: Cuboid): Core = if (cuboid.on) {
Core(cubes + cuboid.cubes)
} else {
Core(cubes - cuboid.cubes)
}
private val IntRange.size: Long
get() = (last - first + 1).toLong()
private infix fun Cuboid.overlap(right: Cuboid): Cuboid? {
val maxx = max(xr.first, right.xr.first)
val maxy = max(yr.first, right.yr.first)
val maxz = max(zr.first, right.zr.first)
val minxp = min(xr.last, right.xr.last)
val minyp = min(yr.last, right.yr.last)
val minzp = min(zr.last, right.zr.last)
return if ((minxp - maxx) >= 0 && (minyp - maxy) >= 0 && (minzp - maxz) >= 0) {
Cuboid(true, maxx..minxp, maxy..minyp, maxz..minzp)
} else null
}
private fun countOn(cuboids: List<Cuboid>): Long {
// had help here
var on = 0L
val counted = mutableListOf<Cuboid>()
cuboids.reversed().forEach { cuboid ->
if (cuboid.on) {
val dead = mutableListOf<Cuboid>()
counted.forEach {
val overlap = it overlap cuboid
if (overlap != null) {
dead.add(overlap)
}
}
on += cuboid.size
on -= countOn(dead)
}
counted.add(cuboid)
}
return on
}
private val cuboidRegex = """^(on|off) x=(-?\d+)\.\.(-?\d+),y=(-?\d+)\.\.(-?\d+),z=(-?\d+)\.\.(-?\d+)$""".toRegex()
private fun String.toCuboid(): Cuboid {
val match = cuboidRegex.matchEntire(this) ?: error("Wrong cuboid: $this")
val (onOff, xmin, xmax, ymin, ymax, zmin, zmax) = match.destructured
return Cuboid(
on=onOff == "on",
xr=xmin.toInt()..xmax.toInt(),
yr=ymin.toInt()..ymax.toInt(),
zr=zmin.toInt()..zmax.toInt(),
)
}
}
| 0 | Kotlin | 0 | 0 | 4b893c001efec7d11a326888a9a98ec03241d331 | 2,845 | adventofcode2021 | MIT License |
src/com/hlq/leetcode/array/Question14.kt | HLQ-Struggle | 310,978,308 | false | null | package com.hlq.leetcode.array
import java.util.*
/**
* @author HLQ_Struggle
* @date 2020/11/09
* @desc LeetCode 14. 最长公共前缀 https://leetcode-cn.com/problems/longest-common-prefix/
*/
fun main() {
val strs = arrayOf("flower", "flow", "flight")
val strs1 = arrayOf("flower", "flower", "flower", "flower")
val strsNull = arrayOf("dog", "racecar", "car")
// 暴力解法 1
println("----> ${longestCommonPrefix(strs)}")
println("----> ${longestCommonPrefix(strs1)}")
println("----> ${longestCommonPrefix(strsNull)}")
// 暴力解法 2 - 3
println("----> ${longestCommonPrefix2(strs)}")
// 排序法
println("----> ${longestCommonPrefix3(strs)}")
// 获取最后一次相同位置
println("----> ${longestCommonPrefix4(strs)}")
}
fun longestCommonPrefix4(strs: Array<String>): String {
if (strs.isEmpty()) {
return ""
}
if (strs.size == 1) {
return if(strs[0].isEmpty()) "" else strs[0]
}
// 获取输入数组中最短长度
var min = Int.MAX_VALUE
for(str in strs){
if(min > str.length){
min = str.length
}
}
// 获取最后一次相同的位置
var isl = true
var index = 0
while (index < min){
for(i in strs.indices){
if(strs[0][index] != strs[i][index]){
isl = false
break
}
}
if(!isl){
break
}
index++
}
return strs[0].substring(0,index)
}
/**
* 排序法
*/
fun longestCommonPrefix3(strs: Array<String>): String {
var resultStr = ""
if (strs.isEmpty()) {
return resultStr
}
if (strs.size == 1) {
return strs[0]
}
var len = strs.size
Arrays.sort(strs)
for (i in strs[0].indices) {
if (strs[len - 1][i] == strs[0][i]) {
resultStr += strs[0][i]
} else {
break
}
}
return resultStr
}
/**
* 暴力解法 2
*/
fun longestCommonPrefix2(strs: Array<String>): String {
var resultStr = ""
if (strs.isEmpty()) {
return resultStr
}
if (strs.size == 1) {
return strs[0]
}
resultStr = strs[0]
for (i in 1 until strs.size) {
var j = 0
while (j < resultStr.length && j < strs[i].length) {
if (strs[i][j] != resultStr[j]) {
break
}
j++
}
resultStr = resultStr.substring(0, j)
if (resultStr.isEmpty()) {
break
}
}
return resultStr
}
/**
* 暴力解法 1
*/
fun longestCommonPrefix(strs: Array<String>): String {
var resultStr = ""
if (strs.isEmpty()) {
return resultStr
}
if (strs.size == 1) {
return strs[0]
}
resultStr = strs[0]
for (str in strs) {
var j = 0
while (j < resultStr.length && j < str.length) {
if (str.toCharArray()[j] != resultStr.toCharArray()[j]) {
break
}
j++
}
resultStr = resultStr.substring(0, j)
if (resultStr.isEmpty()) {
break
}
}
return resultStr
} | 0 | Kotlin | 0 | 2 | 76922f46432783218ddd34e74dbbf3b9f3c68f25 | 3,182 | LeetCodePro | Apache License 2.0 |
src/main/kotlin/com/jacobhyphenated/advent2023/day1/Day1.kt | jacobhyphenated | 725,928,124 | false | {"Kotlin": 121644} | package com.jacobhyphenated.advent2023.day1
import com.jacobhyphenated.advent2023.Day
/**
* Day 1: Trebuchet?!
*
* The puzzle input is a list of strings. The calibration score for each line is the first digit in the line
* combined with the last digit in the line. Example: a1b2c3d4e5f is 15
*/
class Day1: Day<List<String>> {
override fun getInput(): List<String> {
return readInputFile("1").lines()
}
/**
* Sum all the calibration scores
*
* Solve by filtering out all non-digit characters, then take the first and last digit
*/
override fun part1(input: List<String>): Int {
val digits = ('0'..'9').toSet()
return input.map { it.toCharArray().filter { c -> c in digits } }
.sumOf { "${it.first()}${it.last()}".toInt() }
}
/**
* Numbers written out long form count. So two1nine is 29
*/
override fun part2(input: List<String>): Int {
val digits = ('1'..'9').toList()
val digitStrings = listOf("one", "two", "three", "four", "five", "six", "seven", "eight", "nine")
val digitMap = digitStrings.zip(digits).toMap()
// The problem is eightwothree is 83. So naively replacing "two" with "2" doesn't work.
// We can use a regex to pull the first and last matches of the digit or digit string
val matchFirstDigit = "\\d|one|two|three|four|five|six|seven|eight|nine".toRegex()
// requires the .* at the beginning and end. Also requires the capture group. I don't know why
val matchLastDigit = ".*(\\d|one|two|three|four|five|six|seven|eight|nine).*".toRegex()
return input.sumOf { line ->
val match1 = matchFirstDigit.find(line)!!
val firstDigit = digitMap[match1.value] ?: match1.value
val match2 = matchLastDigit.find(line)!!
val lastDigit = digitMap[match2.groupValues.last()] ?: match2.groupValues.last()
"$firstDigit$lastDigit".toInt()
}
}
/**
* Original solution without regex. Traverses the line from beginning and from end in reverse to find the last digit
*/
// override fun part2(input: List<String>): Int {
// val digits = ('0'..'9').toList()
// val digitStrings = listOf("zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine")
// val digitMap = digitStrings.zip(digits).toMap()
//
// // The problem is eightwothree is 83. So naively replacing "two" with "2" doesn't work.
// // we need to traverse each string from the beginning, then from the end
//
// // This helper lambda checks the current index for either a digit or string number or null if neither
// val checkForDigit = { line: String, position: Int ->
// var result: Char? = null
// if (line[position] in digits) {
// result = line[position]
// }
// for (digitString in digitStrings) {
// if (line.substring(position).startsWith(digitString)) {
// result = digitMap.getValue(digitString)
// break
// }
// }
// result
// }
//
// return input.sumOf { line ->
// // traverse from the start to get the first number
// var startIndex = 0
// var startDigit: Char? = null
// while (startIndex < line.length) {
// startDigit = checkForDigit(line, startIndex)
// if (startDigit != null) {
// break
// }
// startIndex++
// }
//
// // traverse backwards from the end to get the last number
// var endIndex = line.length - 1
// var endDigit: Char? = null
// while (endIndex >= 0) {
// endDigit = checkForDigit(line, endIndex)
// if (endDigit != null) {
// break
// }
// endIndex--
// }
// println()
// println(line)
// println("$startDigit$endDigit")
// "$startDigit$endDigit".toInt()
// }
// }
override fun warmup(input: List<String>) {
part1(input)
part2(input)
}
} | 0 | Kotlin | 0 | 0 | 90d8a95bf35cae5a88e8daf2cfc062a104fe08c1 | 3,849 | advent2023 | The Unlicense |
src/Day01.kt | iownthegame | 573,926,504 | false | {"Kotlin": 68002} | fun main() {
fun getCaloriesOfElves(input: List<String>): Array<Int> {
var caloriesOfElves = arrayOf<Int>()
var currentCalories = 0
for (line: String in input) {
if (line.isEmpty()) {
caloriesOfElves += currentCalories
currentCalories = 0
} else {
currentCalories += line.toInt()
}
}
if (currentCalories != 0) {
caloriesOfElves += currentCalories
}
return caloriesOfElves
}
fun part1(input: List<String>): Int {
val caloriesOfElves = getCaloriesOfElves(input)
return caloriesOfElves.max()
}
fun part2(input: List<String>): Int {
val caloriesOfElves = getCaloriesOfElves(input)
return caloriesOfElves.sortedArrayDescending().take(3).sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readTestInput("Day01_sample")
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
val input = readTestInput("Day01")
println("part 1 result: ${part1(input)}")
println("part 2 result: ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 4e3d0d698669b598c639ca504d43cf8a62e30b5c | 1,186 | advent-of-code-2022 | Apache License 2.0 |
src/Day10.kt | azat-ismagilov | 573,217,326 | false | {"Kotlin": 75114} | import kotlin.math.*
fun main() {
fun List<String>.toRegisterPoints(): List<Int> {
var currentValue = 1
val result = mutableListOf(currentValue)
for (line in this) {
val commands = line.split(' ')
when (commands[0]) {
"noop" -> result.add(currentValue)
"addx" -> {
result.add(currentValue)
currentValue += commands[1].toInt()
result.add(currentValue)
}
}
}
return result
}
val interestingCycles = 20..220 step 40
fun part1(input: List<String>): Int = input.toRegisterPoints().let { registerCycles ->
interestingCycles.sumOf {
registerCycles[it - 1] * it
}
}
fun part2(input: List<String>): List<String> = input.toRegisterPoints()
.chunked(40)
.map { lineRegister ->
lineRegister.mapIndexed { index, position ->
if (abs(index - position) <= 1)
'#'
else
'.'
}.joinToString(separator = "")
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day10_test")
check(part1(testInput) == 13140)
println(part2(testInput).joinToString(separator = "\n"))
val input = readInput("Day10")
println(part1(input))
println(part2(input).joinToString(separator = "\n"))
}
| 0 | Kotlin | 0 | 0 | abdd1b8d93b8afb3372cfed23547ec5a8b8298aa | 1,487 | advent-of-code-kotlin-2022 | Apache License 2.0 |
kotlin/app/src/main/kotlin/coverick/aoc/day7/NoSpaceLeftOnDrive.kt | RyTheTurtle | 574,328,652 | false | {"Kotlin": 82616} | package coverick.aoc.day7
import readResourceFile
val INPUT_FILE = "noSpaceLeftOnDevice-input.txt"
class Dir(val path:String, val parent: Dir?){
val files = ArrayList<Long>()
val subDirs = ArrayList<Dir>()
fun nav(nextPath: String) :Dir {
return when(nextPath){
".."-> when(this.parent){
null -> this
else -> this.parent
}
"/" -> when(this.parent){
null -> this
else -> this.parent.nav(nextPath)
}
else -> {
var nextDir = this.subDirs.filter { it.path.startsWith(nextPath) }.getOrNull(0)
if(nextDir == null){
nextDir = Dir(nextPath, this)
this.subDirs.add(nextDir)
}
nextDir
}
}
}
fun getSize():Long {
return files.sum() + subDirs.map{it.getSize()}.sum()
}
override fun toString(): String {
if(parent != null){
return "${parent.toString()}${path}/"
}
return "${path}"
}
}
fun readFileTreeFromInput(): Dir{
val isCommand : (String)-> Boolean = {it -> it.startsWith("$")}
val isFile : (String) -> Boolean = {it -> try{
it.split(" ")[0].toInt()
true
}catch(e: Exception){
false
}}
val getFileSize : (String) -> Long = { it.split(" ")[0].toLong()}
val isList : (String) -> Boolean = {it -> it.split(" ")[1].equals("ls")}
val isNav : (String) -> Boolean = {it -> it.split(" ")[1].equals("cd")}
var rootNode = Dir("/", null)
val lines = readResourceFile(INPUT_FILE)
var i = 0
while(i< lines.size) {
var line = lines[i]
if(isCommand(line)){
if(isNav(line)){
rootNode = rootNode.nav(line.split(" ")[2])
i++
} else if(isList(line)){
i++
line = lines[i]
while(!isCommand(line)){
if(isFile(line)){
rootNode.files.add(getFileSize(line))
}
i++
if(i < lines.size){
line = lines[i]
} else {
break
}
}
}
} else {
i++
}
}
return rootNode.nav("/")
}
fun part1(): Long {
val rootNode = readFileTreeFromInput()
val currentNodes = ArrayList<Dir>()
currentNodes.add(rootNode)
val TARGET_SIZE = 100000
var sum: Long = 0
while(currentNodes.size > 0){
val cur = currentNodes.removeAt(0)
if(cur.getSize() <= TARGET_SIZE){
sum += cur.getSize()
}
currentNodes.addAll(cur.subDirs)
}
return sum
}
fun part2(): Long {
val rootNode = readFileTreeFromInput()
val TOTAL_MEMORY = 70000000
val REQUIRED_MEMORY = 30000000
val MIN_DELETE_SIZE = REQUIRED_MEMORY -(TOTAL_MEMORY - rootNode.getSize())
val currentNodes = ArrayList<Dir>()
currentNodes.add(rootNode)
val candidateNodes = ArrayList<Dir>()
while(currentNodes.size > 0){
val cur = currentNodes.removeAt(0)
if(cur.getSize() >= MIN_DELETE_SIZE){
candidateNodes.add(cur)
}
currentNodes.addAll(cur.subDirs)
}
candidateNodes.sortBy{it.getSize()}
return candidateNodes.get(0).getSize()
}
fun solution(){
println("No Space Left On Drive Part 1 solution: ${part1()}")
println("No Space Left On Drive Part 2 solution: ${part2()}")
} | 0 | Kotlin | 0 | 0 | 35a8021fdfb700ce926fcf7958bea45ee530e359 | 3,632 | adventofcode2022 | Apache License 2.0 |
src/Day04.kt | ChrisCrisis | 575,611,028 | false | {"Kotlin": 31591} |
fun main() {
fun String.getSectionRange(): IntRange {
return this.split("-").let {
it.first().toInt() .. it.last().toInt()
}
}
fun List<String>.processInput(): List<ElvenPair>{
return this.map {
val elves = it.split(",")
ElvenPair(
elves[0].getSectionRange(),
elves[1].getSectionRange(),
)
}
}
fun part1(data: List<String>): Int {
return data.processInput().filter { pair ->
pair.firstElfSections.all {
pair.secondElfSections.contains(it)
} or pair.secondElfSections.all {
pair.firstElfSections.contains(it)
}
}.size
}
fun part2(data: List<String>): Int {
return data.processInput().filter { pair ->
pair.firstElfSections.any {
pair.secondElfSections.contains(it)
} or pair.secondElfSections.any {
pair.firstElfSections.contains(it)
}
}.size
}
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
data class ElvenPair(
val firstElfSections: IntRange,
val secondElfSections: IntRange,
) | 1 | Kotlin | 0 | 0 | 732b29551d987f246e12b0fa7b26692666bf0e24 | 1,374 | aoc2022-kotlin | Apache License 2.0 |
src/Day06.kt | schoi80 | 726,076,340 | false | {"Kotlin": 83778} | fun main() {
val input = readInput("Day06")
fun numWaysToWin(time: Long, distance: Long): Long {
return (1..time).count { speed ->
(time - speed) * speed > distance
}.toLong()
}
fun part1(input: List<String>): Long {
val time = input[0].split(":")[1].trim().split("\\s+".toRegex()).map { it.toLong() }
val distance = input[1].split(":")[1].trim().split("\\s+".toRegex()).map { it.toLong() }
return time.zip(distance).fold(1) { acc, pair ->
numWaysToWin(pair.first, pair.second) * acc
}
}
fun part2(input: List<String>): Long {
val time = input[0].split(":")[1].trim().replace("\\s+".toRegex(), "").toLong()
val distance = input[1].split(":")[1].trim().replace("\\s+".toRegex(), "").toLong()
return numWaysToWin(time, distance)
}
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | ee9fb20d0ed2471496185b6f5f2ee665803b7393 | 941 | aoc-2023 | Apache License 2.0 |
src/Day03_2021.kt | Scholar17 | 579,871,947 | false | {"Kotlin": 24751} | import java.io.File
fun main() {
fun parseInput(input: String): List<List<Int>> {
return input.split("\n").map { bit ->
bit.map {
it.digitToIntOrNull() ?: 0
}
}
}
val filename =
"src/Day03_sample_2021.txt"
// "src/Day03_quiz_2021.txt"
val textInput = File(filename).readText()
val nestedIntList = parseInput(textInput)
println(nestedIntList)
fun maxCounter(input: List<Int>): Int {
return input
.groupingBy { it }
.eachCount()
.maxBy { it.value }.key
}
fun maxCounterValue(input: List<Int>): Int {
return input
.groupingBy { it }
.eachCount()
.maxBy { it.value }.value
}
fun minCounter(input: List<Int>): Int {
return input
.groupingBy { it }
.eachCount()
.minBy { it.value }.key
}
val filterTotalResult = mutableListOf<List<Int>>()
for (i in 0 until nestedIntList.first().size - 1) {
//for each column to list
val columnList = nestedIntList.map { it[i] }
filterTotalResult.add(columnList)
println(columnList)
}
val gammaRate = mutableListOf<Int>()
val epsilonRate = mutableListOf<Int>()
val test = mutableListOf<Int>()
for (aList in filterTotalResult) {
gammaRate.add(maxCounter(aList))
epsilonRate.add(minCounter(aList))
test.add(maxCounterValue(aList))
}
println(test)
var gammaRateInString = ""
var epsilonRateInString = ""
for (s in gammaRate) {
gammaRateInString += s
}
for (s in epsilonRate) {
epsilonRateInString += s
}
println(gammaRateInString)
println(epsilonRateInString)
val gammaRateInInteger = gammaRateInString.toInt(2)
val epsilonRateInInteger = epsilonRateInString.toInt(2)
println(gammaRateInInteger)
println(epsilonRateInInteger)
val powerConsumption = gammaRateInInteger * epsilonRateInInteger
println(powerConsumption)
}
| 0 | Kotlin | 0 | 2 | d3d79fbeeb640a990dbeccf2404612b4f7922b38 | 2,076 | aoc-2022-in-kotlin | Apache License 2.0 |
src/Day03.kt | andrikeev | 574,393,673 | false | {"Kotlin": 70541, "Python": 18310, "HTML": 5558} | fun main() {
val chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
fun priority(char: Char) = chars.indexOf(char) + 1
fun part1(input: List<String>): Int {
return input
.map { line ->
val first = line.take(line.length / 2).toSet()
val second = line.drop(line.length / 2).toSet()
first.intersect(second)
}
.flatten()
.sumOf(::priority)
}
fun part2(input: List<String>): Int {
return input.chunked(3)
.map { group ->
group
.map(String::toSet)
.reduceRight { s, acc -> acc.intersect(s) }
.single()
}
.sumOf(::priority)
}
// 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 | 1 | 1aedc6c61407a28e0abcad86e2fdfe0b41add139 | 1,058 | aoc-2022 | Apache License 2.0 |
advent/src/test/kotlin/org/elwaxoro/advent/y2021/Dec08.kt | elwaxoro | 328,044,882 | false | {"Kotlin": 376774} | package org.elwaxoro.advent.y2021
import org.elwaxoro.advent.PuzzleDayTester
/**
* Seven Segment Search
*/
class Dec08 : PuzzleDayTester(8, 2021) {
/**
* Only care about the right side of the pipe
* Only care about unique length digits
*/
override fun part1(): Any = load().map { it.split(" | ").let { it[0] to it[1] } }
.sumOf { it.second.split(" ").filter { it.length in listOf(2, 3, 4, 7) }.size }
/**
* 1, 4, 7, 8 all have unique segment counts
* masking 1, 4, 7 against other numbers and counting the remaining segments yields a unique digit:
* Ex on 2 (5 segments)
* 2 masked by 1 = 4 segments remaining
* 2 masked by 4 = 3 segments remaining
* 2 masked by 7 = 3 segments remaining
* sum of remaining for each mask = 10
* Each 5 segment digit masks to a different sum, same with 6 segment digits (note 5 and 6 overlap so doing separately)
*/
override fun part2(): Any =
load().map { it.replace(" |", "").split(" ") }.map { it to it.buildMasks() }.map { (digits, masks) ->
digits.map { digit ->
when (digit.length) {
2 -> 1
3 -> 7
4 -> 4
7 -> 8
5 -> masks.apply(digit).to5SegmentDigit() //2, 3, 5
6 -> masks.apply(digit).to6SegmentDigit() //6, 9, 0
else -> throw IllegalStateException("Unknown digit with unsupported lit segments: $digit")
}
}.takeLast(4).joinToString("").toInt()
}.sum()
private fun List<String>.buildMasks(): List<Regex> = listOf(
Regex("[${first { it.length == 2 }}]+"), // 1
Regex("[${first { it.length == 4 }}]+"), // 4
Regex("[${first { it.length == 3 }}]+") // 7
)
private fun List<Regex>.apply(digit: String) = fold(0) { acc, mask -> acc + digit.replace(mask, "").length }
private fun Int.to5SegmentDigit(): Int =
when (this) {
10 -> 2
7 -> 3
9 -> 5
else -> throw IllegalStateException("Unknown 5 segment digit: $this")
}
private fun Int.to6SegmentDigit(): Int =
when (this) {
12 -> 6
9 -> 9
10 -> 0
else -> throw IllegalStateException("Unknown 6 segment digit: $this")
}
}
| 0 | Kotlin | 4 | 0 | 1718f2d675f637b97c54631cb869165167bc713c | 2,382 | advent-of-code | MIT License |
src/main/aoc2016/Day8.kt | nibarius | 154,152,607 | false | {"Kotlin": 963896} | package aoc2016
class Day8(input: List<String>) {
private data class Instruction(val action: Action, val a: Int, val b: Int) {
fun execute(display: Array<IntArray>) {
when (action) {
Action.Rect -> createRect(display, a, b)
Action.RotateRow -> rotateRow(display, a, b)
Action.RotateColumn -> rotateColumn(display, a, b)
}
}
fun createRect(display: Array<IntArray>, width: Int, height: Int) {
for (i in 0 until height) {
for (j in 0 until width) {
display[i][j] = 1
}
}
}
fun rotateRow(display: Array<IntArray>, row: Int, distance: Int) {
val copy = display[row].copyOf()
for (i in copy.indices) {
display[row][(i + distance) % copy.size] = copy[i]
}
}
fun Array<IntArray>.copy() = Array(size) { get(it).clone() }
fun rotateColumn(display: Array<IntArray>, column: Int, distance: Int) {
val copy = display.copy()
for (i in copy.indices) {
display[(i + distance) % copy.size][column] = copy[i][column]
}
}
}
private enum class Action {
Rect,
RotateRow,
RotateColumn
}
private val display = Array(6) { IntArray(50) { 0 } }
private val instructions = parseInput(input)
private fun parseInput(input: List<String>): List<Instruction> {
val ret = mutableListOf<Instruction>()
input.forEach {
when {
it.startsWith("rect") -> {
val a = it.substringAfter(" ").substringBefore("x").toInt()
val b = it.substringAfter("x").toInt()
ret.add(Instruction(Action.Rect, a, b))
}
it.startsWith("rotate row") -> {
val a = it.substringAfter("y=").substringBefore(" ").toInt()
val b = it.substringAfter("by ").toInt()
ret.add(Instruction(Action.RotateRow, a, b))
}
else -> {
val a = it.substringAfter("x=").substringBefore(" ").toInt()
val b = it.substringAfter("by ").toInt()
ret.add(Instruction(Action.RotateColumn, a, b))
}
}
}
return ret
}
fun solvePart1(): Int {
instructions.forEach { it.execute(display) }
return display.sumOf { it.sum() }
}
fun solvePart2() {
instructions.forEach { it.execute(display) }
print(display)
}
private fun print(display: Array<IntArray>) {
display.forEach { println(it.joinToString("")
.replace('0', ' ')
.replace('1', '#')) }
}
}
| 0 | Kotlin | 0 | 6 | f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22 | 2,862 | aoc | MIT License |
src/main/kotlin/com/mckernant1/leetcode/RegexMatching.kt | mckernant1 | 494,952,749 | false | {"Kotlin": 33093} | package com.mckernant1.leetcode
/**
* ab*cd*
* ab | cd | []
* abbbbbbbbbcdddddd
*
*
* a.|c|cc
* ab.cccbbbcc
*
*/
fun main() {
println(isMatch("aaa", "ab*a*c*a"))
// println(isMatch("aab", "c*a*b"))
}
private fun isMatch(input: String, pattern: String): Boolean {
if (pattern == ".*") return true
return if (input.length <= 1 && pattern.length <= 1) {
println("Matching $input == $pattern")
input == pattern || pattern == "."
} else {
println("$input == $pattern")
return if (pattern.getOrNull(1) == '*') {
isMatch(
input.dropWhile { it == pattern[0] },
pattern.dropWhile { it == pattern[0] || it == '*' }
)
} else {
isMatch(input.drop(1), pattern.drop(1))
}
}
}
//fun chunkEq(input: String, pattern: String): Boolean {
// for ((i, c) in input.withIndex()) {
// val patternChar = pattern.getOrNull(i) ?: pattern.last()
// if (patternChar != '.' && c != patternChar) {
// return false
// }
// }
//}
| 0 | Kotlin | 0 | 0 | 5aaa96588925b1b8d77d7dd98dd54738deeab7f1 | 1,089 | kotlin-random | Apache License 2.0 |
src/day08/Day08.kt | palpfiction | 572,688,778 | false | {"Kotlin": 38770} | package day08
import readInput
typealias Matrix<T> = MutableList<MutableList<T>>
fun emptyMatrix(x: Int, y: Int) = MutableList(x) { MutableList(y) { 0 } }
fun <T> Matrix<T>.dimensions() = this.size to this[0].size
fun <T> Matrix<T>.print() {
val (rows, columns) = this.dimensions()
for (j in 0 until columns) {
for (i in 0 until rows) {
print(this[i][j])
}
println()
}
}
fun main() {
fun dimensions(input: List<String>): Pair<Int, Int> = input[0].toCharArray().size to input.size
fun parseGrid(input: List<String>): Matrix<Int> {
val (rows, columns) = dimensions(input)
val grid = emptyMatrix(rows, columns)
input
.forEachIndexed { y, line ->
line.toCharArray()
.forEachIndexed { x, tree ->
grid[x][y] = tree.digitToInt()
}
}
return grid
}
fun Matrix<Int>.maxTop(x: Int, y: Int): Int {
var max = 0
for (j in y - 1 downTo 0) {
with(this[x][j]) {
if (this > max) max = this
}
}
return max
}
fun Matrix<Int>.maxBottom(x: Int, y: Int): Int {
val (_, columns) = this.dimensions()
var max = 0
for (j in y + 1 until columns) {
with(this[x][j]) {
if (this > max) max = this
}
}
return max
}
fun Matrix<Int>.maxLeft(x: Int, y: Int): Int {
var max = 0
for (i in x - 1 downTo 0) {
with(this[i][y]) {
if (this > max) max = this
}
}
return max
}
fun Matrix<Int>.maxRight(x: Int, y: Int): Int {
val (rows) = this.dimensions()
var max = 0
for (i in x + 1 until rows) {
with(this[i][y]) {
if (this > max) max = this
}
}
return max
}
fun Matrix<Int>.isVisible(x: Int, y: Int): Boolean {
val (rows, columns) = this.dimensions()
if (x == 0 || y == 0 || x == rows - 1 || y == columns - 1) return true
return this[x][y] > maxTop(x, y) ||
this[x][y] > maxBottom(x, y) ||
this[x][y] > maxRight(x, y) ||
this[x][y] > maxLeft(x, y)
}
fun part1(input: List<String>): Int {
val grid = parseGrid(input)
val (rows, columns) = grid.dimensions()
var visibleTrees = 0
for (x in 0 until rows) {
for (y in 0 until columns) {
if (grid.isVisible(x, y)) visibleTrees++
}
}
return visibleTrees
}
fun Matrix<Int>.viewsTop(x: Int, y: Int): Int {
val currentHeight = this[x][y]
var trees = 0
for (j in y - 1 downTo 0) {
with(this[x][j]) {
if (this >= currentHeight) {
return ++trees
} else trees++
}
}
return trees
}
fun Matrix<Int>.viewsBottom(x: Int, y: Int): Int {
val (_, columns) = this.dimensions()
val currentHeight = this[x][y]
var trees = 0
for (j in y + 1 until columns) {
with(this[x][j]) {
if (this >= currentHeight) {
return ++trees
} else trees++
}
}
return trees
}
fun Matrix<Int>.viewsLeft(x: Int, y: Int): Int {
val currentHeight = this[x][y]
var trees = 0
for (i in x - 1 downTo 0) {
with(this[i][y]) {
if (this >= currentHeight) {
return ++trees
} else trees++
}
}
return trees
}
fun Matrix<Int>.viewsRight(x: Int, y: Int): Int {
val (rows) = this.dimensions()
val currentHeight = this[x][y]
var trees = 0
for (i in x + 1 until rows) {
with(this[i][y]) {
if (this >= currentHeight) {
return ++trees
} else {
trees++
}
}
}
return trees
}
fun Matrix<Int>.scenicScore(x: Int, y: Int): Int =
this.viewsTop(x, y) * this.viewsBottom(x, y) * this.viewsLeft(x, y) * this.viewsRight(x, y)
fun part2(input: List<String>): Int {
val grid = parseGrid(input)
val (rows, columns) = grid.dimensions()
var maxScenicScore = 0
for (x in 0 until rows) {
for (y in 0 until columns) {
with(grid.scenicScore(x, y)) {
if (this > maxScenicScore) maxScenicScore = this
}
}
}
return maxScenicScore
}
val testInput = readInput("/day08/Day08_test")
// println(part1(testInput))
println(part2(testInput))
check(part1(testInput) == 21)
check(part2(testInput) == 8)
val input = readInput("/day08/Day08")
//println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 5b79ec5fa4116e496cd07f0c7cea7dabc8a371e7 | 5,087 | advent-of-code | Apache License 2.0 |
src/Day21.kt | shepard8 | 573,449,602 | false | {"Kotlin": 73637} | enum class Operator { Plus, Minus, Times, Divide }
fun main() {
abstract class Monkey(val name: String)
class Number(name: String, val number: Long): Monkey(name)
// After solving part 2 I realize monkey1 and monkey2 should be of type Monkey instead of String.
// That would have allowed more object-oriented solving of part 2, putting backtrack in class Operation instead of some standalone function.
class Operation(name: String, val monkey1: String, val monkey2: String, val op: Operator): Monkey(name) {
fun toNumber(val1: Long, val2: Long): Number {
val number = Number(name, when (op) {
Operator.Plus -> val1 + val2
Operator.Minus -> val1 - val2
Operator.Times -> val1 * val2
Operator.Divide -> val1 / val2
})
return number
}
}
fun parse(line: String): Monkey {
val regex = Regex("^([a-z]{4}): ((\\d+)|([a-z]{4}) (.) ([a-z]{4}))$")
val match = regex.matchEntire(line)!!
val values = match.groupValues.drop(1)
return if (values[2].isEmpty()) {
val op = when (values[4][0]) {
'+' -> Operator.Plus
'-' -> Operator.Minus
'*' -> Operator.Times
'/' -> Operator.Divide
else -> throw IllegalArgumentException()
}
Operation(values[0], values[3], values[5], op)
}
else {
Number(values[0], values[2].toLong())
}
}
fun monkeyForward(monkeys: List<Monkey>, monkey: Monkey): Monkey {
return if (monkey is Operation) {
val monkey1 = monkeys.find { it.name == monkey.monkey1 }
val monkey2 = monkeys.find { it.name == monkey.monkey2 }
if (monkey1 is Number && monkey2 is Number) {
monkey.toNumber(monkey1.number, monkey2.number)
}
else monkey
}
else monkey
}
fun part1(input: List<String>): Long {
val monkeys = input.map { parse(it) }.toMutableList()
while (monkeys.find { it.name == "root" } is Operation) {
monkeys.replaceAll { monkeyForward(monkeys, it) }
}
return (monkeys.find { it.name == "root" } as Number).number
}
fun monkeyBackward(monkeys: List<Monkey>, monkey: Operation, value: Long): Long {
if (monkey.name == "humn") return value
val monkey1 = monkeys.first { it.name == monkey.monkey1 }
val monkey2 = monkeys.first { it.name == monkey.monkey2 }
return if (monkey1 is Number && monkey2 is Operation) {
when (monkey.op) {
Operator.Plus -> monkeyBackward(monkeys, monkey2, value - monkey1.number)
Operator.Minus -> monkeyBackward(monkeys, monkey2, monkey1.number - value)
Operator.Times -> monkeyBackward(monkeys, monkey2, value / monkey1.number)
Operator.Divide -> monkeyBackward(monkeys, monkey2, monkey1.number / value)
}
}
else if (monkey1 is Operation && monkey2 is Number) {
when (monkey.op) {
Operator.Plus -> monkeyBackward(monkeys, monkey1, value - monkey2.number)
Operator.Minus -> monkeyBackward(monkeys, monkey1, value + monkey2.number)
Operator.Times -> monkeyBackward(monkeys, monkey1, value / monkey2.number)
Operator.Divide -> monkeyBackward(monkeys, monkey1, value * monkey2.number)
}
}
else {
throw IllegalStateException()
}
}
fun part2(input: List<String>): Long {
val humn = Operation("humn", "humn", "zero", Operator.Plus)
val zero = Number("zero", 0)
val monkeys = (input.map { parse(it) }.filterNot { it.name == "humn" } + listOf(humn, zero)).toMutableList()
val root = monkeys.find { it.name == "root" } as Operation
while (monkeys.find { it.name == root.monkey1 } is Operation && monkeys.find { it.name == root.monkey2 } is Operation) {
monkeys.replaceAll { monkeyForward(monkeys, it) }
}
return monkeyBackward(monkeys,
monkeys.filter { it.name == root.monkey1 || it.name == root.monkey2 }.filterIsInstance<Operation>().first(),
monkeys.filter { it.name == root.monkey1 || it.name == root.monkey2 }.filterIsInstance<Number>().first().number
)
}
val input = readInput("Day21")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 81382d722718efcffdda9b76df1a4ea4e1491b3c | 4,541 | aoc2022-kotlin | Apache License 2.0 |
p11/src/main/kotlin/ChronalCharge.kt | jcavanagh | 159,918,838 | false | null | package p11
class FuelCell(val x: Int, val y: Int, gridSN: Int) {
val rackID = x + 10
val power = getPower(gridSN)
private fun getPower(gridSN: Int): Int {
var pwr = rackID * y
pwr += gridSN
pwr *= rackID
pwr /= 100
if(pwr < 100) {
pwr = 0
} else {
pwr -= pwr / 10 * 10
}
pwr -= 5
return pwr
}
}
class Grid(val serialNumber: Int, val x: Int = 300) {
private var grid: List<FuelCell> = buildGrid()
operator fun get(atX: Int, atY: Int): FuelCell {
return grid[atX + (atY * x)]
}
private fun buildGrid(): List<FuelCell> {
return (1..(x * x)).map { FuelCell(it % x - 1, it / x, serialNumber) }
}
fun subGrid(offsetX: Int, offsetY: Int, side: Int): List<FuelCell> {
var idx = offsetX + (x * offsetY)
val cells = mutableListOf<FuelCell>()
for(h in 1..side) {
val sublist = grid.subList(idx, idx + side)
cells.addAll(sublist)
idx += x
}
return cells
}
fun maxPower(): Triple<List<List<FuelCell>>, Int, Int> {
val init = maxPowerForSize(1)
var maxPower = Triple(init.first, init.second, 1)
for(i in 2..x) {
val thisPower = maxPowerForSize(i)
if(thisPower.second > maxPower.second) {
maxPower = Triple(thisPower.first, thisPower.second, i)
}
}
return maxPower
}
fun maxPowerForSize(side: Int): Pair<List<List<FuelCell>>, Int> {
var maxCells = listOf<FuelCell>()
var maxPower = -1
for(i in 0..(x - side - 1)) {
for(j in 0..(x - side - 1)) {
val sg = subGrid(i, j, side)
val power = sg.fold(0) { acc, fuelCell -> acc + fuelCell.power }
if(power > maxPower) {
maxPower = power
maxCells = sg
}
}
}
return Pair(maxCells.chunked(side), maxPower)
}
}
fun main(args: Array<String>) {
val input = 7403
val grid = Grid(input)
val maxPower3 = grid.maxPowerForSize(3)
val topLeft3 = maxPower3.first[0][0]
println("Max power (3x3): ${maxPower3.second} at (${topLeft3.x},${topLeft3.y})")
val maxPower = grid.maxPower()
val topLeft = maxPower.first[0][0]
val size = maxPower.third
println("Max power: ${maxPower.second} at (${topLeft.x},${topLeft.y}) of size ${size}x$size")
} | 0 | Kotlin | 0 | 0 | 289511d067492de1ad0ceb7aa91d0ef7b07163c0 | 2,241 | advent2018 | MIT License |
src/main/kotlin/main.kt | gavq | 291,229,489 | false | null | fun pad2(n: Int): String {
val s = "$n"
return if (s.length < 2) " $s" else s
}
interface ICell {
fun draw(): String
}
interface IDown {
val down: Int
}
interface IAcross {
val across: Int
}
// singleton
object EmptyCell : ICell {
override fun toString() = "EmptyCell"
override fun draw() = " ----- "
}
data class DownCell(override val down: Int) : ICell, IDown {
override fun draw() = " ${pad2(down)}\\-- "
}
data class AcrossCell(override val across: Int) : ICell, IAcross {
override fun draw() = " --\\${pad2(across)} "
}
data class DownAcrossCell(override val down: Int, override val across: Int) : ICell, IDown, IAcross {
override fun draw() = " ${pad2(down)}\\${pad2(across)} "
}
data class ValueCell(val values: Set<Int>) : ICell {
override fun draw(): String {
return when (values.size) {
1 -> " ${values.first()} "
else -> (1..9).joinToString(separator = "", prefix = " ", transform = ::drawOneValue)
}
}
fun isPossible(n: Int) = values.contains(n)
private fun drawOneValue(it: Int) = if (it in values) "$it" else "."
}
fun da(d: Int, a: Int) = DownAcrossCell(d, a)
fun d(d: Int) = DownCell(d)
fun a(a: Int) = AcrossCell(a)
fun e() = EmptyCell
fun v() = ValueCell(setOf(1, 2, 3, 4, 5, 6, 7, 8, 9))
fun v(vararg args: Int) = ValueCell(args.toSet())
fun v(args: List<Int>) = ValueCell(args.toSet())
data class SimplePair<T>(val first: T, val second: T)
fun drawRow(row: Collection<ICell>): String {
return row.joinToString(separator = "", postfix = "\n", transform = ICell::draw)
}
fun drawGrid(grid: Collection<Collection<ICell>>): String {
return grid.joinToString(transform = ::drawRow)
}
fun <T> allDifferent(nums: Collection<T>): Boolean {
return nums.size == HashSet(nums).size
}
fun <T> product(colls: List<Set<T>>): List<List<T>> {
return when (colls.size) {
0 -> emptyList()
1 -> colls[0].map { listOf(it) }
else -> {
val head = colls[0]
val tail = colls.drop(1)
val tailProd = product(tail)
return head.flatMap { x -> tailProd.map { listOf(x) + it } }
}
}
}
fun permuteAll(vs: List<ValueCell>, target: Int): List<List<Int>> {
val values = vs.map { it.values }
return product(values)
.filter { target == it.sum() }
}
fun <T> transpose(m: List<List<T>>): List<List<T>> {
return when {
m.isEmpty() -> emptyList()
else -> {
(1..m[0].size)
.map { m.map { col -> col[it - 1] } }
}
}
}
fun <T> partitionBy(f: (T) -> Boolean, coll: List<T>): List<List<T>> {
return when {
coll.isEmpty() -> emptyList()
else -> {
val head = coll[0]
val fx = f(head)
val group = coll.takeWhile { fx == f(it) }
listOf(group) + partitionBy(f, coll.drop(group.size))
}
}
}
fun <T> partitionAll(n: Int, step: Int, coll: List<T>): List<List<T>> {
return when {
coll.isEmpty() -> emptyList()
else -> {
listOf(coll.take(n)) + partitionAll(n, step, coll.drop(step))
}
}
}
fun <T> partitionN(n: Int, coll: List<T>): List<List<T>> = partitionAll(n, n, coll)
fun solveStep(cells: List<ValueCell>, total: Int): List<ValueCell> {
val finalIndex = cells.size - 1
val perms = permuteAll(cells, total)
.filter { cells.last().isPossible(it[finalIndex]) }
.filter { allDifferent(it) }
return transpose(perms).map { v(it) }
}
fun gatherValues(line: List<ICell>): List<List<ICell>> {
return partitionBy({ it is ValueCell }, line)
}
fun pairTargetsWithValues(line: List<ICell>): List<SimplePair<List<ICell>>> {
return partitionN(2, gatherValues(line))
.map { SimplePair(it[0], if (1 == it.size) emptyList() else it[1]) }
}
fun solvePair(accessor: (ICell) -> Int, pair: SimplePair<List<ICell>>): List<ICell> {
val notValueCells = pair.first
return when {
pair.second.isEmpty() -> notValueCells
else -> {
val valueCells = pair.second.map { it as ValueCell }
val total = accessor(notValueCells.last())
val newValueCells = solveStep(valueCells, total)
notValueCells + newValueCells
}
}
}
fun solveLine(line: List<ICell>, f: (ICell) -> Int): List<ICell> {
return pairTargetsWithValues(line)
.map { solvePair(f, it) }
.flatten()
}
fun solveRow(row: List<ICell>): List<ICell> {
return solveLine(row, { (it as IAcross).across })
}
fun solveColumn(column: List<ICell>): List<ICell> {
return solveLine(column, { (it as IDown).down })
}
fun solveGrid(grid: List<List<ICell>>): List<List<ICell>> {
val rowsDone = grid.map(::solveRow)
val colsDone = transpose(rowsDone).map(::solveColumn)
return transpose(colsDone)
}
fun solver(grid: List<List<ICell>>): List<List<ICell>> {
println(drawGrid(grid))
val g = solveGrid(grid)
return if (g == grid) g else solver(g)
}
| 0 | Kotlin | 0 | 0 | 413f26dcca9b5041eef3bf6187ed08c68c69d507 | 5,047 | kakuro-kotlin | MIT License |
src/Day04.kt | ManueruEd | 573,678,383 | false | {"Kotlin": 10647} | fun main() {
val day = "04"
fun part1(input: List<String>): Int {
val ans = input.mapNotNull {
val s = it.split(",")
.map {
it.split("-")
.map { it.toInt() }
}
val p1: List<Int> = s[0]
val p2: List<Int> = s[1]
if ((p1[0] >= p2[0] && p1[1] <= p2[1]) || (p2[0] >= p1[0] && p2[1] <= p1[1])) {
s
} else
null
}
//println(ans)
return ans.size
}
fun part2(input: List<String>): Int {
val ans = input.mapNotNull {
val s = it.split(",")
.map {
it.split("-")
.map { it.toInt() }
}
val p1: List<Int> = s[0]
val p2: List<Int> = s[1]
if (p1[1] < p2[0] || p2[1] < p1[0] ) {
null
} else
s
}
ans.onEach { println(it) }
return ans.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day${day}_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day$day")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 09f3357e059e31fda3dd2dfda5ce603c31614d77 | 1,337 | AdventOfCode2022 | Apache License 2.0 |
src/day15/day15.kt | diesieben07 | 572,879,498 | false | {"Kotlin": 44432} | package day15
import com.google.common.collect.Range
import com.google.common.collect.RangeSet
import com.google.common.collect.TreeRangeSet
import streamInput
import java.util.BitSet
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
//val file = "Day15Example"
val file = "Day15"
data class Point(val x: Long, val y: Long) {
fun manhattanDist(other: Point): Long {
return abs(other.x - x) + abs(other.y - y)
}
}
data class SensorWithBeacon(val s: Point, val b: Point) {
val m by lazy {
s.manhattanDist(b)
}
}
private val regex = Regex("""Sensor at x=(-?\d+), y=(-?\d+): .+ beacon is at x=(-?\d+), y=(-?\d+)""")
fun Sequence<String>.parseInput(): Sequence<SensorWithBeacon> {
return map { line ->
val (sx, sy, bx, by) = checkNotNull(regex.find(line)).destructured
SensorWithBeacon(Point(sx.toLong(), sy.toLong()), Point(bx.toLong(), by.toLong()))
}
}
private fun part1() {
streamInput(file) { input ->
val data = input.parseInput().toList()
val noBeacons = HashSet<Point>()
val beacons = data.mapTo(HashSet()) { it.b }
val interestingY = 2000000L
for ((s, b) in data) {
val d = s.manhattanDist(b)
if (interestingY in (s.y - d)..(s.y + d)) {
val dXThisRow = d - abs(interestingY - s.y)
for (x in (s.x - dXThisRow)..(s.x + dXThisRow)) {
val p = Point(x, interestingY)
if (p !in beacons) {
noBeacons.add(p)
}
}
}
}
println(noBeacons.size)
}
}
private fun part2() {
// val maxCoord = 20L
val maxCoord = 4000000L
// val file = "Day15Example"
val file = "Day15"
streamInput(file) { input ->
val data = input.parseInput().toList()
val noBeacons = HashMap<Long, RangeSet<Long>>()
val noBeaconsX = HashMap<Long, RangeSet<Long>>()
for ((index, d) in data.withIndex()) {
println("I $index")
for (y in max(0L, (d.s.y - d.m))..min(maxCoord, (d.s.y + d.m))) {
val dXThisRow = d.m - abs(y - d.s.y)
val setThisRow = noBeacons.getOrPut(y) { TreeRangeSet.create() }
setThisRow.add(Range.closedOpen(max(0, (d.s.x - dXThisRow)), min(maxCoord, (d.s.x + dXThisRow)) + 1))
}
for (x in max(0, (d.s.x - d.m))..min(maxCoord, (d.s.x + d.m))) {
val dYThisRow = d.m - abs(x - d.s.x)
val setThisCol = noBeaconsX.getOrPut(x) { TreeRangeSet.create() }
setThisCol.add(Range.closedOpen(max(0, (d.s.y - dYThisRow)), min(maxCoord, (d.s.y + dYThisRow)) + 1))
}
}
val y = (0..maxCoord).single { y -> (noBeacons[y]?.asRanges()?.size ?: 1) != 1 }
val x = (0..maxCoord).single { x -> (noBeaconsX[x]?.asRanges()?.size ?: 1) != 1 }
println(x)
println(y)
println(x * 4000000L + y)
}
}
fun main() {
// part1()
part2()
}
| 0 | Kotlin | 0 | 0 | 0b9993ef2f96166b3d3e8a6653b1cbf9ef8e82e6 | 3,069 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/day10.kt | gautemo | 725,273,259 | false | {"Kotlin": 79259} | import shared.Input
import shared.Point
import shared.XYMap
fun main() {
val input = Input.day(10)
println(day10A(input))
println(day10B(input))
}
fun day10A(input: Input): Int {
val map = XYMap(input) { if (it == '.') null else it }
val trail = getTrail(map)
return trail.size / 2
}
/* next time, just be smart and count if number of pipes to the right is odd */
fun day10B(input: Input): Int {
val map = XYMap(input) { if (it == '.') null else it }
val trail = getTrail(map)
val expandedMap = getExpandedEmptySpaces(trail, map)
return getClosedPoints(expandedMap)
}
private fun getTrail(map: XYMap<Char>): List<Point> {
val trail = mutableListOf(map.all { it == 'S' }.keys.first())
while (true) {
val on = trail.last()
var next: Point? = null
Point(on.x, on.y - 1).let { top ->
if (
listOf('S', '|', 'L', 'J').contains(map[on]) &&
listOf('S', '|', '7', 'F').contains(map.getOrNull(top)) &&
!trail.contains(top)
) {
next = top
}
}
Point(on.x + 1, on.y).let { right ->
if (
listOf('S', '-', 'L', 'F').contains(map[on]) &&
listOf('S', '-', '7', 'J').contains(map.getOrNull(right)) &&
!trail.contains(right)
) {
next = right
}
}
Point(on.x, on.y + 1).let { bottom ->
if (
listOf('S', '|', '7', 'F').contains(map[on]) &&
listOf('S', '|', 'L', 'J').contains(map.getOrNull(bottom)) &&
!trail.contains(bottom)
) {
next = bottom
}
}
Point(on.x - 1, on.y).let { left ->
if (
listOf('S', '-', '7', 'J').contains(map[on]) &&
listOf('S', '-', 'L', 'F').contains(map.getOrNull(left)) &&
!trail.contains(left)
) {
next = left
}
}
if (next == null) break
next?.let { trail.add(it) }
}
return trail
}
private fun getExpandedEmptySpaces(trail: List<Point>, map: XYMap<Char>): XYMap<Char> {
var expandedInput = ""
for (y in 0..<map.height) {
for (x in 0..<map.width) {
if (trail.contains(Point(x, y))) {
expandedInput += map[Point(x, y)]
val connectsRight = getNeighbours(Point(x, y), trail).contains(Point(x + 1, y))
expandedInput += if (connectsRight) {
"-"
} else {
"e"
}
} else {
expandedInput += ".e"
}
}
expandedInput += '\n'
for (x in 0..<map.width) {
expandedInput += if (trail.contains(Point(x, y))) {
val connectsBottom = getNeighbours(Point(x, y), trail).contains(Point(x, y + 1))
if (connectsBottom) {
"|e"
} else {
"ee"
}
} else {
"ee"
}
}
expandedInput += '\n'
}
return XYMap(Input(expandedInput.trim())) { if (it == '.' || it == 'e') it else null }
}
private fun getNeighbours(point: Point, list: List<Point>): List<Point> {
val index = list.indexOf(point)
if (index == 0) {
return listOf(list.last(), list[1])
}
if (index == list.size - 1) {
return listOf(list[index - 1], list[0])
}
return listOf(list[index - 1], list[index + 1])
}
fun getClosedPoints(map: XYMap<Char>): Int {
val knownEscapes = mutableListOf<Point>()
val knownTrapped = mutableListOf<Point>()
fun checkEscape(point: Point): Boolean {
val options = mutableSetOf(point)
val visited = mutableListOf<Point>()
while (options.isNotEmpty()) {
val on = options.first()
options.remove(on)
visited.add(on)
if (knownTrapped.contains(on)) break
if (knownEscapes.contains(on) ||
on.x == 0 ||
on.y == 0 ||
on.x == map.width - 1 ||
on.y == map.height - 1
) {
knownEscapes.addAll(visited + options)
return true
}
options.addAll(map.adjacents(on).keys.filter { !visited.contains(it) })
}
knownTrapped.addAll(visited + options)
return false
}
return map.all { it == '.' }.count { !checkEscape(it.key) }
}
| 0 | Kotlin | 0 | 0 | 6862b6d7429b09f2a1d29aaf3c0cd544b779ed25 | 4,609 | AdventOfCode2023 | MIT License |
src/main/kotlin/day2.kt | kevinrobayna | 436,414,545 | false | {"Ruby": 195446, "Kotlin": 42719, "Shell": 1288} | import java.util.stream.Collectors
data class PolicyAndPassword(
val min: Int,
val max: Int,
val str: String,
val password: String,
)
// https://adventofcode.com/2020/day/2
class Day2(
private val values: List<PolicyAndPassword>
) {
fun solve(): Long {
return values
.stream()
.filter { policyAndPassword ->
policyAndPassword
.password.split("")
.stream()
.filter { requiredString ->
requiredString == policyAndPassword.str
}
.count() in policyAndPassword.min..policyAndPassword.max
}.count()
}
}
// https://adventofcode.com/2020/day/2
class Day2Part2(
private val values: List<PolicyAndPassword>
) {
fun solve(): Long {
return values
.stream()
.filter { checkPolicyPart2(it) }
.count()
}
private fun checkPolicyPart2(it: PolicyAndPassword): Boolean {
val part1 = it.password[it.min - 1].toString() == it.str
val part2 = it.password[it.max - 1].toString() == it.str
if (part1 && part2) {
return false
} else if (part1 || part2) {
return true
}
return false
}
}
/**
* example of line 1-7 j: vrfjljjwbsv
*/
fun lineToPolicyAndPassword(line: String): PolicyAndPassword {
val policyAndPassword = line.split(':')
val rangeAndChar = policyAndPassword[0].split(' ')
val range = rangeAndChar[0].split('-')
return PolicyAndPassword(
range[0].toInt(), // min
range[1].toInt(), // max
rangeAndChar[1].trim(), // str to check
policyAndPassword[1].trim() // password
)
}
fun main() {
val problem = Day2::class.java.getResource("day2.txt")
.readText()
.split('\n')
.stream()
.map { lineToPolicyAndPassword(it) }
.collect(Collectors.toList())
val solution = Day2(problem).solve()
println("solution = $solution")
val solutionPart2 = Day2Part2(problem).solve()
println("solutionPart2 = $solutionPart2")
} | 0 | Ruby | 0 | 0 | 9e48ecdebdb4c479ef00f0fd3b1a44a211fb6577 | 2,156 | adventofcode_2020 | MIT License |
src/Day13.kt | brigittb | 572,958,287 | false | {"Kotlin": 46744} | fun main() {
fun convertToList(
remaining: String,
sb: StringBuilder = StringBuilder(),
level: Level,
): Level {
val currentChar = if (remaining.isEmpty()) {
if (sb.isNotEmpty()) {
val itemToAdd = sb.toString().toInt()
level.current.add(itemToAdd)
}
return level
} else remaining[0]
when {
currentChar.isDigit() ->
return convertToList(
remaining = remaining.substring(1),
sb = sb.append(currentChar),
level = level,
)
currentChar == '[' -> {
val newList = mutableListOf<Any>()
level.current.add(newList)
return convertToList(
remaining = remaining.substring(1),
sb = StringBuilder(),
level = Level(parent = level, current = newList),
)
}
currentChar == ']' -> {
val itemToAdd = sb.toString().toIntOrNull()
itemToAdd?.let { level.current.add(itemToAdd) }
return convertToList(
remaining = remaining.substring(1),
sb = StringBuilder(),
level = level.parent ?: error("Parent should be set."),
)
}
else -> {
sb.toString()
.toIntOrNull()
?.let { level.current.add(it) }
return convertToList(
remaining = remaining.substring(1),
sb = StringBuilder(),
level = level,
)
}
}
}
fun parse(input: String): List<List<List<Any>>> = input
.split("\n\n")
.map {
it
.split("\n")
.filter { listInput -> listInput.isNotEmpty() }
.map { listInput ->
listInput
.removePrefix("[")
.removeSuffix("]")
}
.map { listInput ->
convertToList(
remaining = listInput,
level = Level(
current = mutableListOf(),
)
).current
}
}
fun comparePairs(
first: List<Any>,
second: List<Any>,
): Pair<Boolean, Boolean> {
for (i in first.indices) {
val left = first[i]
val right = second.getOrNull(i)
when {
right == null -> return false to false
left is Int && right is Int -> {
when {
left < right -> return true to false
left > right -> return false to false
left == right -> continue
}
}
left is List<*> && right is List<*> -> {
val (inRightOrder, shouldContinue) = comparePairs(left as List<Any>, right as List<Any>)
if (!inRightOrder || !shouldContinue) {
return inRightOrder to shouldContinue
}
}
left is Int && right is List<*> -> {
val (inRightOrder, shouldContinue) = comparePairs(listOf(left), right as List<Any>)
if (!inRightOrder || !shouldContinue) {
return inRightOrder to shouldContinue
}
}
left is List<*> && right is Int -> {
val (inRightOrder, shouldContinue) = comparePairs(left as List<Any>, listOf(right))
if (!inRightOrder || !shouldContinue) {
return inRightOrder to shouldContinue
}
}
}
}
if (first.size < second.size) {
return true to false
}
return true to true
}
fun part1(input: String): Int {
val pairsInRightOrder = mutableListOf<Int>()
val parsedInput = parse(input)
parsedInput.forEachIndexed { index, lists ->
val (first, second) = lists
if (comparePairs(first, second).first) {
pairsInRightOrder.add(index + 1)
}
}
return pairsInRightOrder.sum()
}
fun part2(input: String): Int {
val dividerPackets = listOf(listOf(listOf(2)), listOf(listOf(6)))
val parsedInput: List<List<Any>> = input
.split("\n")
.filter { it.isNotEmpty() }
.map { listInput ->
listInput
.removePrefix("[")
.removeSuffix("]")
}
.map { listInput ->
convertToList(
remaining = listInput,
level = Level(
current = mutableListOf(),
)
).current
}
val indexOfDividerPackets = parsedInput
.sortedWith { a, b -> if (comparePairs(a, b).first) -1 else 1 }
.mapIndexed { idx, item -> idx + 1 to item }
.filter { (_, it) -> it in dividerPackets }
return indexOfDividerPackets[0].first * indexOfDividerPackets[1].first
}
// test if implementation meets criteria from the description, like:
val testInput = readInputAsText("Day13_test")
// check(part1(testInput) == 13)
check(part2(testInput) == 140)
val input = readInputAsText("Day13")
// println(part1(input)) // 6072
println(part2(input))
}
data class Level(
val current: MutableList<Any>,
val parent: Level? = null,
)
| 0 | Kotlin | 0 | 0 | 470f026f2632d1a5147919c25dbd4eb4c08091d6 | 5,882 | aoc-2022 | Apache License 2.0 |
2021/kotlin/src/main/kotlin/nl/sanderp/aoc/aoc2021/day18/Day18.kt | sanderploegsma | 224,286,922 | false | {"C#": 233770, "Kotlin": 126791, "F#": 110333, "Go": 70654, "Python": 64250, "Scala": 11381, "Swift": 5153, "Elixir": 2770, "Jinja": 1263, "Ruby": 1171} | package nl.sanderp.aoc.aoc2021.day18
import nl.sanderp.aoc.common.*
fun main() {
val input = readResource("Day18.txt").lines().map { parse(it) }
val (answer1, duration1) = measureDuration<Int> { input.reduce { a, b -> a + b }.magnitude }
println("Part one: $answer1 (took ${duration1.prettyPrint()})")
val (answer2, duration2) = measureDuration<Int> {
input.combinations(2).flatMap { (a, b) -> listOf(a + b, b + a) }.maxOf { it.magnitude }
}
println("Part two: $answer2 (took ${duration2.prettyPrint()})")
}
private data class ExplosionResult(val element: Element, val leftValue: Int, val rightValue: Int)
private sealed class Element(val depth: Int) {
abstract val magnitude: Int
abstract fun incrementDepth(): Element
abstract fun addValueLeftToRight(value: Int): Element
abstract fun addValueRightToLeft(value: Int): Element
abstract fun tryExplode(): ExplosionResult?
abstract fun trySplit(): Element?
operator fun plus(other: Element) = Node(this.incrementDepth(), other.incrementDepth(), 0).reduce()
protected fun reduce(): Element = tryExplode()?.element?.reduce() ?: trySplit()?.reduce() ?: this
}
private class Leaf(val value: Int, depth: Int) : Element(depth) {
override val magnitude: Int = value
override fun incrementDepth() = Leaf(value, depth + 1)
override fun addValueLeftToRight(value: Int) = Leaf(this.value + value, depth)
override fun addValueRightToLeft(value: Int) = Leaf(this.value + value, depth)
override fun tryExplode(): ExplosionResult? = null
override fun trySplit(): Element? = if (value < 10) null else {
val left = Leaf(value / 2, depth + 1)
val right = Leaf((value + 1) / 2, depth + 1)
Node(left, right, depth)
}
}
private class Node(val left: Element, val right: Element, depth: Int) : Element(depth) {
override val magnitude: Int by lazy { 3 * left.magnitude + 2 * right.magnitude }
override fun incrementDepth(): Element = Node(left.incrementDepth(), right.incrementDepth(), depth + 1)
override fun addValueLeftToRight(value: Int) = Node(left.addValueLeftToRight(value), right, depth)
override fun addValueRightToLeft(value: Int) = Node(left, right.addValueRightToLeft(value), depth)
override fun tryExplode(): ExplosionResult? {
if (left is Leaf && right is Leaf && depth == 4) {
return ExplosionResult(Leaf(0, 4), left.value, right.value)
}
return tryExplodeLeft() ?: tryExplodeRight()
}
override fun trySplit(): Element? =
left.trySplit()?.let { Node(it, right, depth) } ?: right.trySplit()?.let { Node(left, it, depth) }
private fun tryExplodeLeft(): ExplosionResult? =
left.tryExplode()?.let {
ExplosionResult(
element = Node(it.element, right.addValueLeftToRight(it.rightValue), depth),
leftValue = it.leftValue,
rightValue = 0,
)
}
private fun tryExplodeRight(): ExplosionResult? =
right.tryExplode()?.let {
ExplosionResult(
element = Node(left.addValueRightToLeft(it.leftValue), it.element, depth),
leftValue = 0,
rightValue = it.rightValue,
)
}
}
private fun parse(line: String): Element {
fun parseSegment(s: String, depth: Int): Pair<Element, Int> = when (val c = s.first()) {
'[' -> {
val (left, leftOffset) = parseSegment(s.drop(1), depth + 1)
val (right, rightOffset) = parseSegment(s.drop(1 + leftOffset), depth + 1)
Node(left, right, depth) to 1 + leftOffset + rightOffset
}
']', ',' -> parseSegment(s.drop(1), depth).let { (x, offset) -> x to offset + 1 }
else -> Leaf(c.asDigit(), depth) to 1
}
return parseSegment(line, 0).first
}
| 0 | C# | 0 | 6 | 8e96dff21c23f08dcf665c68e9f3e60db821c1e5 | 3,856 | advent-of-code | MIT License |
src/Day24.kt | Riari | 574,587,661 | false | {"Kotlin": 83546, "Python": 1054} | import kotlin.math.abs
fun main() {
data class Vector2(var x: Int, var y: Int) {
operator fun plus(other: Vector2): Vector2 = Vector2(x + other.x, y + other.y)
operator fun minus(other: Vector2): Vector2 = Vector2(x - other.x, y - other.y)
override operator fun equals(other: Any?): Boolean = other is Vector2 && x == other.x && y == other.y
fun clone(): Vector2 = Vector2(x, y)
}
data class Blizzard(var position: Vector2, var direction: Vector2) {
fun clone(): Blizzard = Blizzard(position.clone(), direction.clone())
}
var initialBlizzards = listOf<Blizzard>()
var blizzards = mutableListOf<Blizzard>()
val directions = listOf(Vector2(1, 0), Vector2(0, 1), Vector2(0, -1), Vector2(-1, 0), Vector2(0, 0))
var dimensions = Vector2(0, 0)
val start = Vector2(1, 0)
var end = Vector2(0, 0)
fun processInput(input: List<String>) {
blizzards.clear()
dimensions = Vector2(input[0].length, input.size)
end = Vector2(dimensions.x - 2, dimensions.y - 1)
for ((y, row) in input.withIndex()) {
if (y == 0 || y == input.lastIndex) continue
for ((x, cell) in row.withIndex()) {
if (x == 0 || x == row.lastIndex) continue
if (cell == '.') continue
val position = Vector2(x, y)
val direction = Vector2(0, 0)
when (cell) {
'^' -> direction.y--
'>' -> direction.x++
'v' -> direction.y++
'<' -> direction.x--
}
blizzards.add(Blizzard(position, direction))
}
}
initialBlizzards = blizzards.map { it.copy() }
}
fun print(blizzards: List<Blizzard>, position: Vector2) {
val map = MutableList(dimensions.y) { MutableList(dimensions.x) { '.' } }
blizzards.forEach {
val char = when (it.direction) {
directions[0] -> '>'
directions[1] -> 'v'
directions[2] -> '^'
directions[3] -> '<'
else -> null
}
val x = it.position.x; val y = it.position.y
if (map[y][x] != '.') {
if (map[y][x] in listOf('^', '>', 'v', '<')) {
map[y][x] = '2'
} else {
map[y][x] = (map[y][x].toString().toInt() + 1).toChar()
}
} else {
map[y][x] = char!!
}
}
for (y in 0 until dimensions.y) {
for (x in 0 until dimensions.x) {
if (y in 1 until dimensions.y - 1 && x in 1 until dimensions.x - 1) continue
if ((start.x == x && start.y == y) || (end.x == x && end.y == y)) continue
map[y][x] = '#'
}
}
map[position.y][position.x] = 'E'
for (row in map) {
for (c in row) print(c)
print('\n')
}
print("\n\n")
}
fun solve(startAt: Vector2, goal: Vector2): Int {
val horizontalRange = 1 until dimensions.x - 1
val verticalRange = 1 until dimensions.y - 1
var minutes = 0
var branches = hashSetOf(startAt)
while (true) {
minutes++
for (i in blizzards.indices) {
val destination = blizzards[i].position + blizzards[i].direction
if (destination.x < 1) destination.x = horizontalRange.last
else if (destination.x > horizontalRange.last) destination.x = 1
else if (destination.y < 1) destination.y = verticalRange.last
else if (destination.y > verticalRange.last) destination.y = 1
blizzards[i].position = destination
}
val newBranches = HashSet<Vector2>()
for (pos in branches) {
for (direction in directions) {
val destination = pos + direction
if ((destination == goal || destination == startAt || (destination.x in horizontalRange && destination.y in verticalRange))
&& blizzards.none { it.position == destination }) {
newBranches.add(destination)
}
}
}
if (newBranches.size == 0) continue
if (newBranches.any { it == goal }) return minutes
branches = newBranches
}
}
fun part1(): Int {
return solve(start, end)
}
fun part2(): Int {
blizzards = initialBlizzards.map { it.copy() }.toMutableList()
val a = solve(start, end)
val b = solve(end, start)
val c = solve(start, end)
return a + b + c
}
processInput(readInput("Day24_test"))
check(part1() == 18)
check(part2() == 54)
println("Checks passed")
processInput(readInput("Day24"))
println(part1())
println(part2())
}
| 0 | Kotlin | 0 | 0 | 8eecfb5c0c160e26f3ef0e277e48cb7fe86c903d | 5,021 | aoc-2022 | Apache License 2.0 |
src/Day10.kt | uekemp | 575,483,293 | false | {"Kotlin": 69253} |
class Cpu(var clock: Int = 1, var x: Int = 1) {
var sum = 0
fun tick(increment: Int = 0) {
clock++
x += increment
if ((clock - 20) % 40 == 0) {
sum += clock * x
}
}
}
class Crt(val cpu: Cpu) {
private val screen = Array(6) { CharArray(40) }
fun drawPixel() {
val pixel = (cpu.clock % 240) - 1
val row = pixel / 40
val column = if (pixel % 40 >= 0) pixel % 40 else 39
val char = if (column in cpu.x - 1..cpu.x + 1) {
'#'
} else {
'.'
}
screen[row][column] = char
}
override fun toString(): String {
return screen.joinToString(separator = "\n", transform = { array -> array.joinToString(separator = "") })
}
}
fun main() {
fun part1(input: List<String>): Int {
val cpu = Cpu()
input.forEach { line ->
if (line == "noop") {
cpu.tick()
} else {
val (_, text) = line.split(" ")
val inc = text.toInt()
cpu.tick()
cpu.tick(inc)
}
}
return cpu.sum
}
fun part2(input: List<String>): Crt {
val cpu = Cpu()
val crt = Crt(cpu)
input.forEach { line ->
if (line == "noop") {
crt.drawPixel()
cpu.tick()
} else {
val (_, text) = line.split(" ")
val inc = text.toInt()
crt.drawPixel()
cpu.tick()
crt.drawPixel()
cpu.tick(inc)
}
}
return crt
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day10_test")
check(part1(testInput) == 13140)
println(part2(testInput))
println("---------------------------------------------------------------")
val input = readInput("Day10")
check(part1(input) == 15680)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | bc32522d49516f561fb8484c8958107c50819f49 | 2,031 | advent-of-code-kotlin-2022 | Apache License 2.0 |
2022/Day15.kt | amelentev | 573,120,350 | false | {"Kotlin": 87839} | import kotlin.math.abs
fun main() {
val input = readInput("Day15")
val maxxy = 4000000L
val coords = input.map { s ->
s.split("Sensor at x=", ", y=", ": closest beacon is at x=").drop(1).map { it.toLong() }
}
val minx = coords.minOf { minOf(it[0], it[2]) }
val maxx = coords.maxOf { maxOf(it[0], it[2]) }
var res1 = 0
fun check(x: Long, y: Long) = coords.all { (xs,ys,xb,yb) ->
val d = abs(xs - xb) + abs(ys - yb)
abs(x-xs) + abs(y-ys) > d
}
val y1 = maxxy / 2
for (x in (2*minx - maxx) .. (2*maxx - minx)) {
if (coords.any { (_,_,xb,yb) -> xb == x && yb == y1 }) continue
if (check(x,y1)) continue
res1++
}
println(res1)
fun dist(c: List<Long>) = abs(c[0]-c[2]) + abs(c[1]-c[3])
val res2 = HashSet<Long>()
for (y in 0 .. maxxy) {
for (c in coords) {
val dx = dist(c) - abs(y - c[1])
for (x in listOf(c[0] - dx - 1, c[0] + dx + 1)) {
if (x in 0..maxxy && check(x, y)) {
res2.add(x * 4000000 + y)
}
}
}
}
println(res2)
for (x in 0 .. maxxy) {
for (y in 0 .. maxxy) {
if (check(x,y)) {
println(x*4000000 + y)
}
}
}
}
| 0 | Kotlin | 0 | 0 | a137d895472379f0f8cdea136f62c106e28747d5 | 1,304 | advent-of-code-kotlin | Apache License 2.0 |
2023/13/Solution.kt | AdrianMiozga | 588,519,359 | false | {"Kotlin": 110785, "Python": 11275, "Assembly": 3369, "C": 2378, "Pawn": 1390, "Dart": 732} | import java.io.File
import kotlin.math.min
private const val FILENAME = "2023/13/input.txt"
fun main() {
partOne()
partTwo()
}
private fun partOne() {
val file =
File(FILENAME).readText().split("\r\n\r\n").map { it.split("\r\n") }
var result = 0
for (pattern in file) {
val transposedPattern = transpose(pattern)
val rows = getStartingPoints(pattern, 0)
val columns = getStartingPoints(transposedPattern, 0)
result += count(columns, transposedPattern)
result += (count(rows, pattern) * 100)
}
println(result)
}
private fun transpose(list: List<String>): MutableList<String> {
val transposedPattern = mutableListOf<String>()
for (column in 0 until list[0].length) {
var currentColumn = ""
for (row in list.indices) {
currentColumn += list[row][column]
}
transposedPattern.add(currentColumn)
}
return transposedPattern
}
private fun count(
elements: List<Int>,
pattern: List<String>,
): Int {
var result = 0
for (element in elements) {
var valid = true
val max = min(element - 2, pattern.size - element - 2)
for (i in 0..max) {
if (pattern[element - 2 - i] != pattern[element + 1 + i]) {
valid = false
}
}
if (valid) {
result += element
}
}
return result
}
private fun partTwo() {
val file =
File(FILENAME).readText().split("\r\n\r\n").map { it.split("\r\n") }
var result = 0
for (pattern in file) {
val transposedPattern = transpose(pattern)
var rows = getStartingPoints(pattern, 0)
var columns = getStartingPoints(transposedPattern, 0)
result += countWithSmudge(columns, transposedPattern)
result += (countWithSmudge(rows, pattern) * 100)
rows = getStartingPoints(pattern, 1)
columns = getStartingPoints(transposedPattern, 1)
result += count(columns, transposedPattern)
result += (count(rows, pattern) * 100)
}
println(result)
}
private fun stringDifference(first: String, second: String): Int {
var same = 0
for ((index, character) in first.withIndex()) {
if (character == second[index]) {
same++
}
}
return first.length - same
}
private fun countWithSmudge(
elements: List<Int>,
pattern: List<String>,
): Int {
var result = 0
for (element in elements) {
var oneCharDifference = true
var exact = true
val max = min(element - 2, pattern.size - element - 2)
for (i in 0..max) {
val up = element - 2 - i
val down = element + 1 + i
if (stringDifference(pattern[up], pattern[down]) == 1) {
exact = false
}
if (stringDifference(pattern[up], pattern[down]) > 1) {
oneCharDifference = false
break
}
}
if (oneCharDifference && !exact) {
result += element
}
}
return result
}
private fun getStartingPoints(pattern: List<String>, difference: Int): List<Int> {
var previousRow = pattern[0]
val list = mutableListOf<Int>()
for (index in difference until pattern.size) {
if (stringDifference(previousRow, pattern[index]) == difference) {
list.add(index)
}
previousRow = pattern[index]
}
return list
}
| 0 | Kotlin | 0 | 0 | c9cba875089d8d4fb145932c45c2d487ccc7e8e5 | 3,500 | Advent-of-Code | MIT License |
src/main/kotlin/solutions/day22/Day22.kt | Dr-Horv | 112,381,975 | false | null | package solutions.day22
import solutions.Solver
import utils.Coordinate
import utils.Direction
import utils.step
fun Direction.left() = when (this) {
Direction.UP -> Direction.LEFT
Direction.LEFT -> Direction.DOWN
Direction.RIGHT -> Direction.UP
Direction.DOWN -> Direction.RIGHT
}
fun Direction.right() = when (this) {
Direction.UP -> Direction.RIGHT
Direction.LEFT -> Direction.UP
Direction.RIGHT -> Direction.DOWN
Direction.DOWN -> Direction.LEFT
}
private fun Direction.reverse(): Direction = when (this) {
Direction.UP -> Direction.DOWN
Direction.LEFT -> Direction.RIGHT
Direction.RIGHT -> Direction.LEFT
Direction.DOWN -> Direction.UP
}
enum class NodeState {
CLEAN,
WEAKENED,
INFECTED,
FLAGGED
}
class Day22 : Solver {
override fun solve(input: List<String>, partTwo: Boolean): String {
val grid = mutableMapOf<Coordinate, NodeState>().withDefault { NodeState.CLEAN }
val startY = (input.size / 2)
input.forEachIndexed { y, line ->
val startX = -(line.length / 2)
line.forEachIndexed { i, c ->
val coordinate = Coordinate(startX + i, startY - y)
when (c) {
'#' -> grid.put(coordinate, NodeState.INFECTED)
}
}
}
var carrier = Coordinate(0, 0)
var direction = Direction.UP
val nodeModifier: (s: NodeState) -> NodeState = if (partTwo) {
{ s ->
when (s) {
NodeState.CLEAN -> NodeState.WEAKENED
NodeState.WEAKENED -> NodeState.INFECTED
NodeState.INFECTED -> NodeState.FLAGGED
NodeState.FLAGGED -> NodeState.CLEAN
}
}
} else {
{ s ->
when (s) {
NodeState.CLEAN -> NodeState.INFECTED
NodeState.INFECTED -> NodeState.CLEAN
else -> throw RuntimeException("Invalid state $s")
}
}
}
val bursts = if(partTwo) {
10_000_000
} else {
10_000
}
var infectionBursts = 0
for (burst in 1..bursts) {
val state = grid.getValue(carrier)
direction = when (state) {
NodeState.CLEAN -> direction.left()
NodeState.WEAKENED -> direction
NodeState.INFECTED -> direction.right()
NodeState.FLAGGED -> direction.reverse()
}
val nextState = nodeModifier(state)
if(nextState == NodeState.INFECTED) {
infectionBursts++
}
grid.put(carrier, nextState)
carrier = carrier.step(direction)
}
return infectionBursts.toString()
}
}
| 0 | Kotlin | 0 | 2 | 975695cc49f19a42c0407f41355abbfe0cb3cc59 | 2,871 | Advent-of-Code-2017 | MIT License |
src/main/kotlin/day09.kt | mgellert | 572,594,052 | false | {"Kotlin": 19842} | import kotlin.math.abs
import kotlin.math.sign
object RopeBridge : Solution {
fun moveRope(motions: List<Direction>, parts: Int): Int {
val rope = List(parts) { Rope() }
val tailPositions = mutableSetOf(rope.last().toPair())
motions.forEach { direction ->
rope[0].move(direction)
rope.windowed(2).forEach {
val head = it[0]
val tail = it[1]
tail.moveWith(head)
}
tailPositions.add(rope.last().toPair())
}
return tailPositions.size
}
fun readInput() = readInput("day09").readLines()
}
class Rope(private var x: Int = 0, private var y: Int = 0) {
private fun add(x: Int, y: Int) {
this.x += x
this.y += y
}
fun move(direction: Direction) {
when (direction) {
Direction.UP -> this.add(0, 1)
Direction.DOWN -> this.add(0, -1)
Direction.LEFT -> this.add(-1, 0)
Direction.RIGHT -> this.add(1, 0)
}
}
fun moveWith(other: Rope) {
val deltaX = abs(other.x - this.x)
val deltaY = abs(other.y - this.y)
if (deltaX >= 2 || deltaY >= 2) {
this.add((other.x - this.x).sign, (other.y - this.y).sign)
}
}
fun toPair(): Pair<Int, Int> = Pair(x, y)
}
enum class Direction {
UP, DOWN, LEFT, RIGHT
}
internal fun List<String>.getMotions(): List<Direction> = this.map {
val (motionStr, amount) = it.trim().split(" ")
val motion = when (motionStr) {
"U" -> Direction.UP
"D" -> Direction.DOWN
"L" -> Direction.LEFT
"R" -> Direction.RIGHT
else -> throw IllegalStateException()
}
List(amount.toInt()) { motion }
}.flatten() | 0 | Kotlin | 0 | 0 | 4224c762ad4961b28e47cd3db35e5bc73587a118 | 1,774 | advent-of-code-2022-kotlin | The Unlicense |
src/main/kotlin/be/swsb/aoc2021/day3/Day3.kt | Sch3lp | 433,542,959 | false | {"Kotlin": 90751} | package be.swsb.aoc2021.day3
object Day3 {
fun getPowerConsumption(input: List<String>): Pair<String, String> {
var result = (1..input[0].length).map { 0 }
input.forEach { bitNumber ->
val bitAsCalculcations = bitNumber.map { if (it == '1') 1 else -1 }
result = bitAsCalculcations.zip(result) { a, b -> a + b }
}
val gamma = result.map { if (it >= 0) 1 else 0 }
val epsilon = gamma.map { if (it == 0) 1 else 0 }
return gamma.joinToString("") to epsilon.joinToString("")
}
fun getLifeSupportRating(input: List<String>): Pair<Int, Int> {
return getOxygenGeneratorRating(input) to getCO2ScrubberRating(input)
}
private fun getOxygenGeneratorRating(input: List<String>): Int {
return getRatingByCriteria(input) { tmp -> getPowerConsumption(tmp).first }
}
private fun getCO2ScrubberRating(input: List<String>): Int {
return getRatingByCriteria(input) { tmp -> getPowerConsumption(tmp).second }
}
private fun getRatingByCriteria(input: List<String>, criteriaRetriever: (List<String>) -> String): Int {
var tmp: MutableList<String> = input.toMutableList()
var idx = 0
while (tmp.size > 1) {
val criteria = criteriaRetriever(tmp)
tmp = tmp.filter { bit -> bit[idx] == criteria[idx] }.toMutableList()
idx++
}
return tmp[0].toDecimal()
}
}
fun String.toDecimal() = toInt(2)
| 0 | Kotlin | 0 | 0 | 7662b3861ca53214e3e3a77c1af7b7c049f81f44 | 1,484 | Advent-of-Code-2021 | MIT License |
src/main/kotlin/nl/meine/aoc/_2023/Day3.kt | mtoonen | 158,697,380 | false | {"Kotlin": 201978, "Java": 138385} | package nl.meine.aoc._2023
import kotlin.math.max
import kotlin.math.min
class Day3 {
fun one(input: String): Int {
val lines =
input.split("\n")
val matrix = lines.map { it.toCharArray() }.toTypedArray()
val numbers: MutableList<Int> = mutableListOf()
matrix.onEachIndexed { row, item ->
numbers += processLine(item, row, matrix)
}
return numbers.sum()
}
fun processLine(line: CharArray, row: Int, matrix: Array<CharArray>): List<Int> {
var start = -1
var end = -1
val numbers: MutableList<Int> = mutableListOf()
line.forEachIndexed { col, char ->
if (char.isDigit()) {
if (start == -1) {
start = col
}
} else {
if (start != -1) {
if (hasSymbolNeighbour(start, col, row, matrix)) {
val a = line.slice(start..<col).joinToString("").toInt()
numbers += a
}
start = -1
}
}
}
if (start != -1) {
val endOfLine = matrix.size
if (hasSymbolNeighbour(start, endOfLine, row, matrix)) {
val a = line.slice(start..<endOfLine).joinToString("").toInt()
numbers += a
}
start = -1
}
return numbers
}
fun hasSymbolNeighbour(startCol: Int, endCol: Int, row: Int, matrix: Array<CharArray>): Boolean {
val neighbours: MutableList<Char> = mutableListOf()
//boven
if (row > 0) {
if (startCol > 0) {
neighbours += matrix[row - 1][startCol - 1]
}
for (cur in startCol..<endCol) {
neighbours += matrix[row - 1][cur]
}
if (endCol <= matrix.size - 1) {
neighbours += matrix[row - 1][endCol]
}
}
//links
if (startCol > 0) {
neighbours += matrix[row][startCol - 1]
}
// rechts
if (endCol <= matrix.size - 1) {
neighbours += matrix[row][endCol]
}
//onder
if (row < matrix.size - 1) {
if (startCol > 0) {
neighbours += matrix[row + 1][startCol - 1]
}
for (cur in startCol..<endCol) {
neighbours += matrix[row + 1][cur]
}
if (endCol <= matrix.size - 1) {
neighbours += matrix[row + 1][endCol]
}
}
return neighbours.filter { !it.equals('.') }
.filter { !it.isDigit() }
.any()
}
fun findGear(line: CharArray, row: Int, matrix: Array<CharArray>): Long {
var nums: Long = 0
line.forEachIndexed { col, char ->
if (char == '*') {
val chunkNum = getAdjacentNumbers(matrix, row, col)
nums += if (chunkNum.size == 2) chunkNum[0] * chunkNum[1] else 0
}
}
return nums
}
fun getAdjacentNumbers(matrix: Array<CharArray>, row: Int, col: Int): List<Long> {
val numbers = emptyList<Long>().toMutableList()
val maxLength = matrix[row].size - 1
val left = col - 1
val right = col + 1
// boven
val above = row - 1
if (above >= 0) {
val nums = getNumbers(matrix, above, max(0, col - 3), min(maxLength, col + 3), col)
numbers += nums
}
// links
if (left >= 0 && matrix[row][left].isDigit()) {
numbers += getNumber(matrix, row, max(left - 2, 0), left)
}
// rechts
if (right < matrix[row].size && matrix[row][right].isDigit()) {
numbers += getNumber(matrix, row, right, min(maxLength, col + 3))
}
// onder
val under = row + 1
if (under < matrix.size) {
val nums = getNumbers(matrix, under, max(0, col - 3), min(maxLength, col + 3), col)
numbers += nums
}
return numbers
}
fun getNumber(matrix: Array<CharArray>, row: Int, from: Int, to: Int): Long {
val line = matrix[row]
var digits = ""
// walk left
for (index in from..to) {
if (index >= 0 && index <= matrix[row].size) {
if (line[index].isDigit()) {
digits += line[index]
}
}
}
// walk right
return digits.toLong()
}
fun getNumbers(matrix: Array<CharArray>, row: Int, from: Int, to: Int, gearAt: Int): List<Long> {
val line = matrix[row]
val digits = mutableListOf<Long>()
// walk left
var currentNumber = ""
for (index in from..to) {
if (index >= 0 && index <= matrix[row].size) {
val char = line[index]
if (char.isDigit()) {
currentNumber += char
} else {
if (currentNumber.isNotBlank()) {
val num = currentNumber.toLong()
val start = index - currentNumber.length-1
if(gearAt in start..index){
digits+=num
}
currentNumber = ""
}
}
}
}
val index =to
if (currentNumber.isNotBlank()) {
val num = currentNumber.toLong()
val start = index - currentNumber.length
if(gearAt in start..index){
digits+=num
}
}
// walk right
return digits
}
fun two(input: String): Long {
val lines = input.split("\n")
val matrix = lines.map { it.toCharArray() }.toTypedArray()
val numbers: MutableList<Long> = mutableListOf()
matrix.onEachIndexed { row, item ->
numbers += findGear(item, row, matrix)
}
// per regel kijk of er * in zitten
// per *
// maak een copy van de omliggen regels: getallen max lengte 3
// ga alle locaties af en maak van de digits hele getallen, overschrijf de locatie
// tel de getallen
// als 2, dan goed en vermenigvuldig ze
// meer dan 2 getallen
// ......1*1....
//........1......
// dicht bij elkaar liggende getallen
// ......*.....
//......1.1
return numbers.sum()
}
}
//tried: 518930
// tries two: 41106125
//47002527
//69527306
fun main() {
val inputReal =
"""............830..743.......59..955.......663..........................................367...........895....899...............826...220......
.......284.....*............*.....$...+.....*...377..................*.......419.............488...*.......*...................*..-....939..
....%.........976..679.461.7..........350..33.........$.380...$...151.897..........295..#......*....105.....418.............481........&....
...992.....#......=...../........701................508...*..578........................259...331.................795..945........79........
.........868........................*.............................17*..........348................441*852........*.....-...........@.....922
....................*200............311..63................452.......323.#778.*....674....................680......696...372.....*..........
.......266.......209......589.....=......*...365.........7.*...233.............755....*......644...272........697..*....*.....682..225......
..836..........................949....607..........&....*..899...*....679.527.........331..........$....788../.....43....89.................
........367.....328.&......%...............680...69..717.......60.......*.*............................*..........................728...264.
........*.........*..119.253.......................................626....129...274............97...679.......752........*.......*....*.*...
........360......471........../.........573-.702.............866...@...........*......772....../........259....*.........430....136.742.543.
.........................../.852...............*...775...............643....455....../...........832....*.....41..535.......................
.............-..........340.................103....*..........$...51*..................74................438......%...776...+.23*..663......
.15.......806...............990.....................427....924............530.........=..............................*....968.....=....480..
......#..............@914...*..............*........................%......*................................/.....406.................*.....
....201.........79........592............70.894.....247..513+....367..$299.698......199................-.....223....../.........563....783..
......................448........489................*.................................*....440...889...715..........351.....39..............
.138....../766...........*.......................152.........................377....599.......*...*...........................@.............
....%.820.......10*43.670..$87....100*244..@706..........668..319#...........................831.736....@............./..693.....321%.......
......=...930#..................@...................493....*............152......569.................=.914....764.....9.-...................
378$...............&.....854..505.........%........&.....124......12........117.....*591..979..76..133..........+............/..........883.
...............602.141.....*...............770.....................*.........*................../.........874.@....../684....778............
...........................954.....*397.........................394...........614..307*74..457..............+.514.......................327.
........335*25.....-....31..........................................$...719.................*........6..214................878..............
...............86*.269....*...480........................*....140..947....*..&.......................*......972..............*..364*274.....
501-.......805..........285...*..................6....335.167...*........18...332.............741...127......+.............246..............
......616.......752*276.....470.848..599.........*............779..=................539...961..$.........204.......-..201*.....%............
.491.....*..521.........*94.......*.-.....&...163........285/......51..99*......474..*...-.......945.....&......839.......140...201.....$...
....$.795..*........539.........500.......662.............................421....*...459..../.......*407.............../................471.
...........110.......*...............252.............................%..........730......551..509.............824...230....569....48=.......
......150...................................+..70.565=.&320.........983....155................=.....54.......%............*....@......../...
...............972..146...........49.433..137..............................*....%..................@....................436.451..........328
568-...@.552%....-.-................*.................957................93......74...........*........156.566../....#...........285........
.....565..............693....443......................*....394.@58...362...................383.583.............542.38............./..890....
...*.................*........*........&.223...........506.............=..................................300...............477........&....
..612..459..........462....663......125....................720..............355.....253...............904......................*............
........$................................622..............=................*...........*30.........#.$........................284........383
............&.999....&.......................%........240....295*681.846....53.....806......793..646....626./76..737....479.........558.@...
.........892..#.......885.....804..587*....340.........*..............%............*.........*..........*................%............/.....
660..635...........-............./.....213........$....512.....551.............*....910........................@............................
........*..........361..270*.....................328..............*.........853........................*.....985...965............232...948.
..501@......................213...412$.....375..................631..916.......................254...284.........#....*..252........*.......
...................695............................872*876..622..........-.........*..575...851*..................910.395..*....*717.248.....
.....91.........80....*..390...........497....496............*.......@.........297..*................&....873.............946.8.........647.
.......*.424.......108.....=.............*..................686....418.............131........600.96.327...=...561...321............343*....
....731....*..............................938..........256..............909.......................................*.........................
.........811...=....................680...........167...*...601.....................892..#.......142*.......151..108............201.........
................653........879....@.*.........%...*...699..*..............726............695.870.....526.$................*8............234.
....54....311..............=...320..619.......495.375.......926....914.........654..............*........236...$.......444.....@613.........
...*........*......450*............................................*...786.625.......804.850.....674..........305...........................
..593.512....517.......155.....646*239....286......+...........96..264....*......471.*......*.........314*901..............879..............
..........................................=.....419....820......&..................+.......163....148........................*....586.......
.....331.....................637....126.................*..147............650...............................................315....*........
.......%......................$....../.................392....@...943..34...*......752.............................161..30.........970.521..
.........984.412#.......-.569...@................464....................*.275..&.....#.126*506....................*.......=.168-............
.724..................570....*.914.388.........%..$.........274.......263.......130..............102.....2....21+.268....................226
..........776=...6........759.......*..283..309.....682......$..........................................%........................446........
....%284.........-....#...........119....*......622...@....+............/.......929..178...........141/............../650...628.+...........
....................440........88.........335...*.......804............968..976*....+...................$.421..431..................*.......
.....880@.......871.....30......................249...........134....*................*...............95....-...*.....856...353...94.....963
...............*....97..&.......989./.........*.....522+..$.....*.226.436.905......347.396.707...511..........342.....-.....*...........*...
........936*....299.........217.&...478....931.457........62.391............&...............*..../...884*....................370........483.
....965.....992.............*......................................371*771.............37..382...........990...391.......852................
.......*........985.......753.&..........561.204.......................................*......................*...........@..........+935...
......677.....................164.883...............325........951.....847....%......433....*944.50...753..344..............................
.829.......583........429............*34......243...*.........*.............329.%........421...........*..........803..746............675...
...*..................*....512............999.......102......398.................640................401....310.............164...452..*.....
269........9........705....*........782....%.......................615.734....-..............289...........*.....................=....661...
........37.#..............14.......*........../.......586.............*........623.......129........324.....601...%.....@...................
...165................#.........861............463.......*.......361*..............356........175.....*.........906.897..716....118..#......
.....*.............728....417.........+...395#.........443...........829.....390-....................399...............*..........+..813....
....176..253...846......$...........719..........132............897...............334......................20...........51.....%............
..............*....*..278................958........*.......=.................183*.......427.......766.......*..914.282......674............
....&......344...249.....................*.....445.770.....67.....301................295*.........*....715.390...*...../...............424..
.....541......................160.580...........#................=...........*677..............394.......*........327....739...179.360..*...
..........=................%.....*................-954......%.............406......765..................930.....*.........../.....*.....370.
....%.....979.379..........415...............318..........284....440../............-....133.........157......579.550................747.....
.240..........*.....................@...........*642............*.....84.....%.331................2*...................582...=........*.....
......=.....246....167...............704.............763........999.......781...*.....-109............126..801............*.484....632..542.
....%..488.........@..........................$954....*../.....................779..........232................510.....149..................
...27..........984.........*....485.....937........982..234..............225..................*..........122.............................16.
...........473.#..........558..*.............410-...........93............#..655....846....829.....760......=...................=....+......
.....=390..*...................624........#.................+..473..............#......=...........+...577#......$...481.......651.869.806..
747.......543.259.../717............&...346.......948..........$...........472.............230+......=.........206......*...................
................*........+.224/...798.........311...*..896*220...............&.+..................825....../............378...370...........
...............485.641.674.....................*......................618.......389........................565..&674...........*............
..........475.................=.162............461.441...................*..........652......&....508..856...........364....464.............
...............154...452#...693....*................*.......391.........979....344..&.......814..............501.......=....................
...............*................425....25#...........788............879...........*.....29....................&....................850...794
393.............523...507*683..............174@..........-.............=...369....439....-.......*305.891..........952............*.........
..........+...............................................535..911.........................*....1.........441.....-.........88...906........
..........997...17.............779..............960...................209........545......513................*...........98...........+608..
.....................63.968...*.........340.......*...858..339...........%.-767...+...173........47.........906............*210.............
.............&..575..*....@.788.........*.........178.....*.......949.................+...........*.............-.....399.............@.....
..........571....%....984............414...............$.912.....*......302.............594.240..724....341..645.......*.......=..848.642...
....282@...........*......=......189.....138...227*.906.........70......*..................*.............=..........957...657.81../.........
..........*...$.813.179.901.592.....*....................................7....127.............$692...............$..........*.........*.....
.......207..91..............*.....784...872..756.........&..322..............*.........*19.........749.......548..624.694..858...512..598...
.................+.........352...........*.....*.934..126...*.....351..........40...616.......153.....*661............*...........*.........
...823........829...346...........821...826.304...%.......115.......*..........*...............*.............../...622...523.......606......
...*...............*.............*...................186...........813....716@.372....16..300...489..108.....770.......................697..
..........919...782.......912................@.........*.%485............................*..........*...............208.220....853..........
...308......*............*......269.........539.......2.............853.......941.660.532........246.......980..357*....+.....*......./.....
..../......32.164.......15.479.=.............................=...............*....*......................#....*......+......-.855.....415...
.......305..../.....649....*......633...925...634............121............355....578.......14*....422..543.297....429..142................
..960..+..............*.....536......*..@....-.......51..-.........592#..........+..............9..*........................................
.....*......515......434............908..........189......430..................332...722..-.........450..#.........................139......
..259......*.............................39..33.....$..................................*...159..443.....925.............743....414.&...=437.
......58..475...........227%.......217..../...*................../...............&....506..........................63..*.......*............
.......=......-..............993....%.........166........605....293........977+..498......%.....834...455...........*.....%....981.991......
...........636..728...*.......*.......494...............................................205........*.@...........528....226.........#....785
664.9..............$..9...494.272...............725*....775...$....854..........226.243..........832....637*73................165...........
...*...340+.............@...*.......548.............405....*...768..*..............*.......81.........................10.787.$.......918....
.......................145...265....+..........110........45.........90..299.....$........&.....696...475.-452..290....*...*..........@.....
......+....246.108.305...................894....=............121.588......*....69...................................236..97......348........
.......709........*...........-...........-..........411...=...*.......135........................738..383.....634*..........429.@..........
...........%........%217......119.....................@..47.........+.......923..............606...*.......960..............-...............
....835.....744...................546.......215.............512.....950.......%...444......&...$.833......./.........813.......400..%...48..
........362.......898..#.......................*.732........*.............965....&.........584..................521..#...........-.995......
....64.*.........*.....265........781..376...320.#........998...450.......%............................$...............................304..
....-...966...875..981........742*.......*...........*276.........*...............541.....219.279..357..164...551..%717...............%.....
...................*...786.$..........*...163.....915...........960...%...509.135*...........*................-...........%.539.............
....666..699......179..+...612..=734..545...........................88.....&.......392...46..........483=..&.......548.135.....*.413.#620...
...$....*....948..........................530.656....%..484....*..................*......./...741..........444......*.......150...*.........
......................524...928..........=........858....=..562.571........117@.195..896......*......662.......148.388.............320......
...166..48.../....-............#...159.......487.....................260...............#...713.........*.347................................
......*.......657..837.....273.......%........*...155.................*........225..................228.....*370..../.......724.....764.....
......654.679.................@.........-....918...................681..461.............................776......737.................+......
...........*....859......881#............625......$...........888.........+...57...............887.$.......*............................#911
...46*....72...&...................................102.............651........*......*530.......-..667....850..829*.869%........298.........
......925..........892.352*........6.41....................+...160.$.....*.72..878..1.....................................738......*926..32.
...............279.........721......*..............694....799..&......878....*................219....+...482..368$...........*../...........
......604........*....................583*506........-...........740..........347............*....576......*................498..478.974....
..486.-....................626..................320........&....../.................*979.=....863........497........111..............%......
...................................538..78...*.....*......7...455.......223......939......673..........=......559-....*...834............58.
.......644....&.......#..669+.1.......*.....782.....865......*....779..#..............110...../....937..312...........489...................
.......*....571.....69........*.......169...................919....*.....808.................335...*.............................24*896.....
.......233................590.553..............198=..450.........661.......*.....................15...-....................-575.............
...........919*.....................................*.......234.........492..%...........300...........301........./866..........*..........
...............470.....440.874...116....240........299......................27......409.......................................639.136......."""
val ins = Day3();
println(ins.two(inputReal))
}
| 0 | Kotlin | 0 | 0 | a36addef07f61072cbf4c7c71adf2236a53959a5 | 26,476 | advent-code | MIT License |
2022/src/day17/day17.kt | Bridouille | 433,940,923 | false | {"Kotlin": 171124, "Go": 37047} | package day17
import GREEN
import RESET
import printTimeMillis
import readInput
import java.math.BigInteger
data class Point(val x: Int, val y: Int)
val ROCKS = listOf(
setOf(Point(0, 0), Point(1, 0), Point(2, 0), Point(3, 0)),
setOf(Point(1, 0), Point(0, 1), Point(1, 1), Point(2, 1), Point(1, 2)),
setOf(Point(0, 0), Point(1, 0), Point(2, 0), Point(2, 1), Point(2, 2)),
setOf(Point(0, 0), Point(0, 1), Point(0, 2), Point(0, 3)),
setOf(Point(0, 0), Point(1, 0), Point(0, 1), Point(1, 1)),
)
fun Set<Point>.initialize(offsetX: Int, offsetY: Int) = map { Point(it.x + offsetX, it.y + offsetY) }.toSet()
fun Set<Point>.moveLeft(cave: Set<Point>): Set<Point>? { // null if we can't move
val leftMoved = map { Point(it.x - 1, it.y) }
if (leftMoved.any { it.x < 0 } || leftMoved.any { cave.contains(it) }) return null
return leftMoved.toSet()
}
fun Set<Point>.moveRight(cave: Set<Point>): Set<Point>? { // null if we can't move
val rightMoved = map { Point(it.x + 1, it.y) }
if (rightMoved.any { it.x >= 7 } || rightMoved.any { cave.contains(it) }) return null
return rightMoved.toSet()
}
fun Set<Point>.moveDown(cave: Set<Point>): Set<Point>? { // null if we can't move
val downMoved = map { Point(it.x, it.y - 1) }
if (downMoved.any { it.y <= 0 } || downMoved.any { cave.contains(it) }) return null
return downMoved.toSet()
}
fun part1(input: List<String>, times: Int = 1) = input.first().let { inst ->
var instIdx = 0
val cave = mutableSetOf<Point>()
for (i in 0 until times) {
val height = (if (cave.isEmpty()) 0 else cave.maxBy { it.y }.y)
val nextShape = ROCKS[i % ROCKS.size]
var falling = nextShape.initialize(2, height + 4)
while (true) {
val jet = instIdx % inst.length
val rockIdx = i % ROCKS.size
if (height > 0 && jet == rockIdx) { // 35 iterations == 53 height
// println("jet==rock==$jet (iteration=$i) (height=${height})")
}
when (inst[instIdx++ % inst.length]) {
'>' -> falling.moveRight(cave)?.let { falling = it }
'<' -> falling.moveLeft(cave)?.let { falling = it }
}
falling.moveDown(cave)?.let { falling = it } ?: break // We can't fall more
}
cave.addAll(falling)
}
cave.maxBy { it.y }.y
}
fun part2(input: List<String>, isExample: Boolean) = input.first().let { inst ->
// Example: cycle starts at 9 iterations, has a size of 35 iterations and height of 53
// Input: cycle starts at 1724 iterations, has a size of 1715 iterations and height of 2613
val cycleSize = if (isExample) 35L else 1715L
val cycleHeight = if (isExample) 53L else 2613L
val cycleOffset = if (isExample) 9L else 1724L
val heightInCycle = ((1_000_000_000_000L - cycleOffset) / cycleSize) * cycleHeight
val endCycles = ((1_000_000_000_000L - cycleOffset) % cycleSize)
val bottom = part1(input, cycleOffset.toInt()) // flat floor to the first cycle
val middle = heightInCycle // nb of full cycles * cycleHeight
val end = part1(input, cycleOffset.toInt() + endCycles.toInt()) - part1(input, cycleOffset.toInt()) // part cycle
bottom + middle + end
}
fun main() {
val testInput = readInput("day17_example.txt")
printTimeMillis { print("part1 example = $GREEN" + part1(testInput, 2022) + RESET) }
printTimeMillis { print("part2 example = $GREEN" + part2(testInput, true) + RESET) }
val input = readInput("day17.txt")
printTimeMillis { print("part1 input = $GREEN" + part1(input, 2022) + RESET) }
printTimeMillis { print("part2 input = $GREEN" + part2(input, false) + RESET) }
}
| 0 | Kotlin | 0 | 2 | 8ccdcce24cecca6e1d90c500423607d411c9fee2 | 3,697 | advent-of-code | Apache License 2.0 |
src/main/kotlin/ca/voidstarzero/isbd/titlestatement/grammar/SeriesTitle.kt | hzafar | 262,218,140 | false | null | package ca.voidstarzero.isbd.titlestatement.grammar
import ca.voidstarzero.isbd.titlestatement.ast.*
import ca.voidstarzero.marc.MARCField
import norswap.autumn.DSL.rule
val TitleStatementGrammar.seriesTitle: rule
get() = seq(data, seriesTitleOtherInfo.maybe(), period.maybe())
.push { items ->
SeriesTitle(
title = items[0] as String,
otherInfo = (items[1] as? SeriesOtherInfo)
?.let { otherInfo -> listOf(otherInfo) }
?: emptyList()
)
}
/**
* Matches a series entry (dependent) title, which may consist
* of either a title designation or entry title, or both, followed
* optionally by a list of statements of responsibility.
*/
val TitleStatementGrammar.dependentTitleWithoutMarc: rule
get() = seq(
dataWithoutComma,
seq(comma, data).maybe(),
seriesEntryOtherInfoList.maybe(),
period.maybe()
).maybe()
.push { items ->
val designation = if (items[1] == null) {
null
} else {
items[0]?.let { SeriesEntryDesignation(it as String) }
}
val title = items[1]?.let { SeriesEntryTitle(it as String) }
?: items[0]?.let { SeriesEntryTitle(it as String) }
val otherInfo = (items[2] as? NodeList)?.values
?.map { it as SeriesEntryOtherInfo }
?: emptyList()
SeriesEntry(
title = title,
designation = designation,
otherInfo = otherInfo
)
}
val TitleStatementGrammar.dependentTitle: rule
get() = seq(
rule(SeriesEntryFromMarc()),
seriesEntryOtherInfoList.maybe()
).push { items ->
val title = items[0] as? SeriesEntryTitle
val designation = items[1] as? SeriesEntryDesignation
val otherInfo = (items[2] as? NodeList)?.values
?.map { it as SeriesEntryOtherInfo }
?: emptyList()
SeriesEntry(
title = title,
designation = designation,
otherInfo = otherInfo
)
}
val TitleStatementGrammar.dependentTitleList: rule
get() = seq(
longest(
dependentTitle,
dependentTitleWithoutMarc
).at_least(1)
).push { items ->
NodeList(
items.filterNotNull().map { it as SeriesEntry }
)
}
val TitleStatementGrammar.series: rule
get() = seq(
seriesTitle,
sorList.maybe(),
dependentTitleList.maybe(),
sorList.maybe()
).push { items ->
val seriesEntries = (items[2] as? NodeList)?.values
?.map { it as SeriesEntry }
?: emptyList()
val entrySors = (items[3] as? NodeList)?.values
?.map { it as SOR }
?: emptyList()
Series(
seriesTitle = items[0] as SeriesTitle,
seriesEntry = seriesEntries,
entrySors = entrySors
)
}
val TitleStatementGrammar.seriesRoot: rule
get() = seq(
series,
parallelSeries.maybe()
).push { items ->
val parallelTitles = mutableListOf<ParallelSeries>()
items.flatMap {
when (it) {
is NodeList -> it.values
else -> listOf(it)
}
}.forEach {
when (it) {
is ParallelSeries -> parallelTitles.add(it)
}
}
TitleStatement(
titles = listOf(items[0] as Series),
parallelTitles = parallelTitles
)
}
fun TitleStatementGrammar.seriesRootWithMARC(marcData: MARCField): rule {
val saveMarc: rule = rule(this.SaveMarcData(marcData))
return seq(saveMarc, seriesRoot)
} | 2 | Kotlin | 0 | 2 | 16bb26858722ca818c0a9f659be1cc9d3e4e7213 | 3,808 | isbd-parser | MIT License |
src/main/kotlin/com/github/alturkovic/robots/txt/RobotsTxt.kt | alturkovic | 636,725,117 | false | null | package com.github.alturkovic.robots.txt
import com.github.alturkovic.robots.txt.StringUtils.greatestCommonPrefix
data class RobotsTxt(
val ruleGroups: List<RuleGroup>,
private val ruleMatchingStrategy: RuleMatchingStrategy = WildcardRuleMatchingStrategy,
private val ruleSelectionStrategy: RuleSelectionStrategy = LongestRuleSelectionStrategy
) {
fun query(userAgent: String, path: String): Grant {
val candidates = candidates(userAgent).ifEmpty { return NonMatchedAllowedGrant }
val mostSpecificRuleGroups = candidates.findBestUserAgentMatches(userAgent)
val mostImportantRule = mostSpecificRuleGroups.findMostImportantRule(path) ?: return NonMatchedAllowedGrant
val mostSpecificRuleGroup = mostSpecificRuleGroups.first { mostImportantRule in it.rules }
return MatchedGrant(mostImportantRule.allowed, mostImportantRule, mostSpecificRuleGroup)
}
private fun candidates(userAgent: String) = ruleGroups.filter { it.isApplicableTo(userAgent) }
private fun List<RuleGroup>.findMostImportantRule(path: String): Rule? {
val matchedRules = this
.flatMap { it.rules }
.filter { ruleMatchingStrategy.matches(it, path) }
return ruleSelectionStrategy.select(matchedRules)
}
private fun List<RuleGroup>.findBestUserAgentMatches(userAgent: String): List<RuleGroup> {
var longestMatch = 0
val bestMatches = mutableListOf<RuleGroup>()
for (candidate in this) {
for (ruleGroupAgent in candidate.userAgents) {
val matchLength = calculateUserAgentMatchLength(userAgent, ruleGroupAgent)
if (matchLength > longestMatch) {
longestMatch = matchLength
bestMatches.clear()
bestMatches.add(candidate)
} else if (matchLength == longestMatch) {
bestMatches.add(candidate)
}
}
}
return bestMatches
}
private fun calculateUserAgentMatchLength(userAgent: String, ruleGroupAgent: String): Int =
if (ruleGroupAgent == "*") 1 else greatestCommonPrefix(userAgent, ruleGroupAgent).length
}
| 0 | Kotlin | 0 | 1 | a70632010f74029f5e6414aaaa464975ba51b481 | 2,204 | robots-txt | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/MinOperations.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
/**
* 1658. Minimum Operations to Reduce X to Zero
* @see <a href="https://leetcode.com/problems/minimum-operations-to-reduce-x-to-zero">Source</a>
*/
fun interface MinOperations {
operator fun invoke(nums: IntArray, x: Int): Int
}
/**
* Approach 1: Hash Map
*/
class MinOperationsHashMap : MinOperations {
override fun invoke(nums: IntArray, x: Int): Int {
val left = mutableMapOf<Int, Int>()
var res = Int.MAX_VALUE
var sum = 0
for (l in nums.indices) {
left[sum] = l
if (sum < x) {
sum += nums[l]
}
}
sum = 0
var r = nums.size - 1
while (r >= 0) {
val diff = x - sum
if (left.containsKey(diff) && r + 1 >= left[diff]!!) {
res = minOf(res, nums.size - r - 1 + left[diff]!!)
}
sum += nums[r]
r--
}
return if (res == Int.MAX_VALUE) -1 else res
}
}
/**
* Approach 2: Two Sum
*/
class MinOperationsTwoSum : MinOperations {
override fun invoke(nums: IntArray, x: Int): Int {
var sum = nums.sum()
var l = 0
var r = 0
var res = Int.MAX_VALUE
val sz = nums.size
while (l <= r) {
if (sum >= x) {
if (sum == x) {
res = minOf(res, l + sz - r)
}
if (r < sz) {
sum -= nums[r++]
} else {
break
}
} else {
sum += nums[l++]
}
}
return if (res == Int.MAX_VALUE) -1 else res
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,304 | kotlab | Apache License 2.0 |
src/chapter2/problem5/solution1.kts | neelkamath | 395,940,983 | false | null | /*
Question:
Sum Lists: You have two numbers represented by a linked list, where each node contains a single digit. The digits are
stored in reverse order, such that the 1's digit is at the head of the list. Write a function that adds the two numbers
and returns the sum as a linked list.
EXAMPLE
Input: (7 -> 1 -> 6) + (5 -> 9 -> 2). That is, 617 + 295.
Output: 2 -> 1 -> 9. That is, 912.
FOLLOW UP
Suppose the digits are stored in forward order. Repeat the above problem.
Input: (6 -> 1 -> 7) + (2 -> 9 -> 5).
That is, 617 + 295.
Output: 9 -> 1 -> 2. That is, 912.
Answer:
Solving for reverse ordered numbers.
*/
class LinkedListNode(var data: UInt, var next: LinkedListNode? = null) {
/** Returns a [LinkedListNode] that's the sum of this and the [rhs]. */
operator fun plus(rhs: LinkedListNode): LinkedListNode {
var head: LinkedListNode? = null
var tail: LinkedListNode? = null
var lhsNode: LinkedListNode? = this
var rhsNode: LinkedListNode? = rhs
var hasCarry = false
while (lhsNode != null || rhsNode != null) {
val sum = (lhsNode?.data ?: 0U) + (rhsNode?.data ?: 0U) + (if (hasCarry) 1U else 0U)
val digit = sum % 10U
hasCarry = sum > 9U
val node = LinkedListNode(digit)
if (tail == null) {
tail = node
head = tail
} else {
tail.next = node
tail = tail.next
}
lhsNode = lhsNode?.next
rhsNode = rhsNode?.next
}
if (hasCarry) tail!!.next = LinkedListNode(1U)
return head!!
}
override fun toString(): String {
val builder = StringBuilder()
var node: LinkedListNode? = this
while (node != null) {
if (!builder.isEmpty()) builder.append(" -> ")
builder.append(node.data)
node = node.next
}
builder.insert(0, "[")
builder.append("]")
return builder.toString()
}
}
/** Throws an [IndexOutOfBoundsException] if the [Collection] has no elements. */
fun Collection<UInt>.toLinkedList(): LinkedListNode {
if (size == 0) throw IndexOutOfBoundsException()
val head = LinkedListNode(first())
var node = head
(1 until size).forEach {
node.next = LinkedListNode(elementAt(it))
node = node.next!!
}
return head
}
setOf(
listOf(7U, 1U, 6U) to listOf(5U, 9U, 2U),
listOf(9U, 9U, 9U) to listOf(9U, 9U, 9U),
listOf(1U) to listOf(1U, 2U, 3U),
listOf(1U, 2U, 3U) to listOf(1U),
).forEach { (first, second) ->
val lhs = first.toLinkedList()
val rhs = second.toLinkedList()
println("$lhs + $rhs = ${lhs + rhs}")
}
| 0 | Kotlin | 0 | 0 | 4421a061e5bf032368b3f7a4cee924e65b43f690 | 2,728 | ctci-practice | MIT License |
kotlin/hackerrank/algorithms.kt | jmfayard | 82,162,118 | false | null | package hackerrank
import org.junit.Test
fun stdin(): List<String> {
if (System.`in`.available() == 0) {
System.err.println("nothing in stdin"); System.exit(1)
}
return generateSequence { readLine() }.toList()
}
inline fun <T> Iterable<T>.sumLong(selector: (T) -> Long): Long {
var sum = 0L
for (element in this) {
sum += selector(element)
}
return sum
}
private fun String.toInts() = split(" ").map { it.toIntOrNull() }.filterNotNull()
private fun String.toLongs() = split(" ").map { it.toLongOrNull() }.filterNotNull()
typealias Input = List<String>
fun main(args: Array<String>) {
val (n, _) = readLine()!!.toInts()
val input = generateSequence { readLine() }
println(addAndFindMax(n, input).max()!!)
}
// https://www.hackerrank.com/challenges/crush/problem fails with timeout
fun addAndFindMax(n: Int, lines: Sequence<String>): List<Long> {
val current = MutableList(n + 1) { 0L }
for (line in lines) {
val (from, to, add) = line.toInts()
for (index in from..to) {
current[index] = current[index] + add
}
}
return current
}
fun simpleLongSum(lines: Input): Long {
val longs = lines[1].split(" ").map { it.toLongOrNull() }.filterNotNull()
return longs.fold(0L, { sum, next -> sum + next })
}
fun simpleArraySum(lines: List<String>): Int {
return lines[1].split(" ").sumBy { it.toInt() }
}
class AlgorithmTests {
@Test
fun max() {
val input = listOf(
"1 2 001",
"2 3 010",
"3 4 100"
)
val expected = listOf(0, 1, 11, 110, 100, 0).map { it.toLong() }
addAndFindMax(5, input.asSequence()).toList() shouldBe expected
}
@Test
fun longSum() {
val input = listOf("5", "1000000001 1000000002 1000000003 1000000004 1000000005")
simpleLongSum(input) shouldBe 5000000015
}
@Test
fun testSimpleArray() {
val lines = listOf("6", "1 2 3 4 10 11")
simpleArraySum(lines) shouldBe 31
}
}
infix fun <T> T?.shouldBe(expected: Any?) {
if (this != expected) error("ShouldBe Failed!\nExpected: $expected\nGot: $this")
}
| 0 | Kotlin | 2 | 6 | b0c51334749a632b6413ae08f131612460abd432 | 2,180 | skripts | Apache License 2.0 |
src/Day10.kt | risboo6909 | 572,912,116 | false | {"Kotlin": 66075} | enum class OpType(val ticks: Int) {
ADDX(2),
NOOP(1),
}
class Computer {
private val ops: MutableList<Pair<OpType, Int>> = mutableListOf()
private var ip = 0
private var tick = 0
private var nextInc = 0
var reg = 1
private fun doOp(op: OpType, arg: Int) {
when (op) {
OpType.ADDX -> reg += arg
else -> Unit
}
}
private fun getTicks(op: OpType): Int {
return op.ticks
}
fun loadProgram(program: List<String>) {
for (line in program) {
if (line.startsWith("noop")) {
ops.add(Pair(OpType.NOOP, 1))
} else if (line.startsWith("addx")) {
val (_, ticks) = line.split(" ")
ops.add(Pair(OpType.ADDX, ticks.toInt()))
}
}
nextInc = getTicks(ops[ip].first)
}
fun advance(): Int {
if (tick == nextInc) {
doOp(ops[ip].first, ops[ip].second)
if (++ip == ops.size) {
return -1
}
nextInc += getTicks(ops[ip].first)
}
return ++tick
}
}
fun main() {
fun part1(input: List<String>): Int {
var res = 0
val checkpoints = setOf(20, 60, 100, 140, 180, 220)
val comp = Computer()
comp.loadProgram(input)
while (true) {
val tick = comp.advance()
if (tick < 0) {
break
}
if (tick in checkpoints) {
res += tick * comp.reg
}
}
return res
}
fun part2(input: List<String>): String {
var crtPos = 0
val array = Array(6) { IntArray(40) }
val comp = Computer()
comp.loadProgram(input)
while (true) {
val tick = comp.advance()
if (tick < 0) {
break
}
val crtPosX = crtPos % 40
if ((crtPosX == comp.reg-1) || (crtPosX == comp.reg) || (crtPosX == comp.reg+1)) {
array[crtPos / 40][crtPosX] = 1
}
crtPos++
}
return array.joinToString("\n") { it ->
it.joinToString("") {
if (it == 0) "." else "#"
}
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day10_test")
check(part1(testInput) == 13140)
check(part2(testInput) ==
"##..##..##..##..##..##..##..##..##..##..\n" +
"###...###...###...###...###...###...###.\n" +
"####....####....####....####....####....\n" +
"#####.....#####.....#####.....#####.....\n" +
"######......######......######......####\n" +
"#######.......#######.......#######....."
)
val input = readInput("Day10")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | bd6f9b46d109a34978e92ab56287e94cc3e1c945 | 2,856 | aoc2022 | Apache License 2.0 |
src/Day01.kt | bogdanbeczkowski | 572,679,090 | false | {"Kotlin": 8398} | import java.lang.Integer.max
fun main() {
fun part1(input: List<String>): Int {
var maxCalories = 0
var currentElf = 0
for (line in input) {
if (line.isNotEmpty()) {
currentElf += line.toInt()
} else {
maxCalories = max(currentElf, maxCalories)
currentElf = 0
}
}
// check the last elf
maxCalories = max(currentElf, maxCalories)
return maxCalories
}
fun part2(input: List<String>): Int {
val topThree = intArrayOf(0, 0, 0)
var currentElf = 0
for (line in input) {
if (line.isNotEmpty()) {
currentElf += line.toInt()
} else {
if (currentElf > topThree.min()) {
topThree[topThree.indexOf(topThree.min())] = currentElf
}
currentElf = 0
}
}
// check the last elf
if (currentElf > topThree.min()) {
topThree[topThree.indexOf(topThree.min())] = currentElf
}
return topThree.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 | 03c29c7571e0d98ab00ee5c4c625954c0a46ab00 | 1,416 | AoC-2022-Kotlin | Apache License 2.0 |
src/adventofcode/blueschu/y2017/day04/solution.kt | blueschu | 112,979,855 | false | null | package adventofcode.blueschu.y2017.day04
import java.io.File
import kotlin.test.assertFalse
import kotlin.test.assertTrue
fun input(): List<String> = File("resources/y2017/day04.txt")
.readLines()
fun main(args: Array<String>) {
assertTrue { wordsDistinct("aa bb cc dd ee") }
assertFalse { wordsDistinct("aa bb cc dd aa") }
assertTrue { wordsDistinct("aa bb cc dd aaa") }
println("Part 1: ${part1(input())}")
assertFalse { anagramsDistinct("abcde xyz ecdab") }
assertTrue { anagramsDistinct("a ab abc abd abf abj") }
assertTrue { anagramsDistinct("iiii oiii ooii oooi oooo") }
println("Part 2: ${part2(input())}")
}
fun wordsDistinct(passphrase: String): Boolean {
val parts = passphrase.split(' ')
val distinctCount = parts.distinct().size
return parts.size == distinctCount
}
fun part1(input: List<String>): Int = input.filter { wordsDistinct(it) }.count()
fun anagramsDistinct(passphrase: String): Boolean {
val parts = passphrase.split(' ')
.map { it.toCharArray().sorted().toString() }
val distinctCount = parts.distinct().size
return parts.size == distinctCount
}
fun part2(input: List<String>): Int = input.filter { anagramsDistinct(it) }.count()
| 0 | Kotlin | 0 | 0 | 9f2031b91cce4fe290d86d557ebef5a6efe109ed | 1,231 | Advent-Of-Code | MIT License |
src/day12/puzzle12.kt | brendencapps | 572,821,792 | false | {"Kotlin": 70597} | package day12
import Puzzle
import PuzzleInput
import kotlinx.coroutines.*
import kotlinx.coroutines.sync.Semaphore
import java.io.File
import kotlin.coroutines.coroutineContext
import kotlin.math.abs
fun day12Puzzle() {
//Day12PuzzleSolution().solve(Day12PuzzleInput("inputs/day12/example.txt", 31))
//Day12PuzzleSolution().solve(Day12PuzzleInput("inputs/day12/input.txt"))
Day12Puzzle2Solution().solve(Day12PuzzleInput("inputs/day12/example.txt", 1, 29))
Day12Puzzle2Solution().solve(Day12PuzzleInput("inputs/day12/input.txt", 1))
}
data class Location <T> (val row: Int, val col: Int, val map: List<List<T>>) {
fun left() : Location<T> {
return Location(row, col - 1, map)
}
fun right() : Location<T> {
return Location(row, col + 1, map)
}
fun top() : Location<T> {
return Location(row - 1, col, map)
}
fun bottom() : Location<T> {
return Location(row + 1, col, map)
}
fun getNeighbors(): List<Location<T>> {
return listOf(left(), top(), right(), bottom())
}
fun inMap(): Boolean {
return if(row < 0 || row >= map.size) false
else col >= 0 && col < map[row].size
}
fun mapValue() : T {
return map[row][col]
}
}
data class Move (val original: Location<Int>, val next: Location<Int>) {
fun valid(): Boolean {
return next.inMap() && (next.mapValue() - original.mapValue() <= 1)
}
}
class Day12PuzzleInput(val input: String, sMap: Int = 0, expectedResult: Int? = null) : PuzzleInput<Int>(expectedResult) {
val terrain: List<List<Int>> = File(input).readLines().map { line ->
line.toCharArray().map { char ->
if (char == 'S') sMap
else if (char == 'E') 27
else char - 'a' + 1
}
}
}
class Day12PuzzleSolution : Puzzle<Int, Day12PuzzleInput>() {
override fun solution(input: Day12PuzzleInput): Int {
return Solver().getSolution(findStart(input))
}
private fun findStart(input: Day12PuzzleInput): Location<Int> {
for(row in input.terrain.indices) {
for(col in input.terrain[row].indices) {
if(input.terrain[row][col] == 0) {
return Location(row, col, input.terrain)
}
}
}
error("Did not find starting position")
}
}
class Solver {
private var paths = mutableListOf<MutableList<Location<Int>>>()
private var solution = Int.MAX_VALUE
private val moves = mutableListOf<Move>()
private var highestPoint = 0
fun getSolution(start: Location<Int>) : Int {
paths.add(mutableListOf(start))
while(paths.isNotEmpty()) {
val newPaths = mutableListOf<MutableList<Location<Int>>>()
paths.forEach { path ->
val current = path.last()
val validMoves = current.getNeighbors().filter { nextLocation ->
val move = Move(current, nextLocation)
move.valid() && !moves.contains(move) && !path.contains(nextLocation)
}
validMoves.forEach { move ->
val newPath = path.toCollection(mutableListOf())
moves.add(Move(current, move))
newPath.add(move)
if(move.mapValue() > highestPoint) {
highestPoint = move.mapValue()
}
if(move.mapValue() == 27) {
if(newPath.size < solution) {
solution = newPath.size - 1
}
}
else {
newPaths.add(newPath)
}
}
}
paths = newPaths.filter { path ->
path.size < solution
}.toMutableList()
}
return solution
}
}
class Day12Puzzle2Solution : Puzzle<Int, Day12PuzzleInput>() {
override fun solution(input: Day12PuzzleInput): Int {
return runBlocking {
val locations = mutableListOf<Location<Int>>()
input.terrain.forEachIndexed { rowIndex, row ->
row.forEachIndexed { colIndex, height ->
if (height <= 1) {
locations.add(Location(rowIndex, colIndex, input.terrain))
}
}
}
locations.map { location ->
async {
val solution = Solver().getSolution(location)
println("$solution ${location.row} ${location.col}")
solution
}
}.awaitAll().min()
}
}
} | 0 | Kotlin | 0 | 0 | 00e9bd960f8bcf6d4ca1c87cb6e8807707fa28f3 | 4,860 | aoc_2022 | Apache License 2.0 |
src/main/kotlin/day11.kt | tobiasae | 434,034,540 | false | {"Kotlin": 72901} | class Day11 : Solvable("11") {
override fun solveA(input: List<String>): String {
val grid = getGrid(input)
var flashes = 0
repeat(100) { flashes += simulateStep(grid) }
return flashes.toString()
}
override fun solveB(input: List<String>): String {
val grid = getGrid(input)
var step = 0
val n = grid.size * grid.first().size
while (true) {
step++
if (simulateStep(grid) == n) {
return step.toString()
}
}
}
private fun getGrid(input: List<String>): List<MutableList<Int>> {
return input.map { it.toCharArray().map { it.toInt() - 48 }.toMutableList() }
}
private fun simulateStep(grid: List<MutableList<Int>>): Int {
for (row in grid.indices) {
for (col in grid[row].indices) {
increase(grid, row, col)
}
}
return grid
.mapIndexed { row, r ->
r
.filterIndexed { col, c ->
val flash = c >= 10
if (flash) grid[row][col] = 0
flash
}
.size
}
.sum()
}
private fun increase(grid: List<MutableList<Int>>, row: Int, col: Int): Int {
if (row < 0 || row >= grid.size || col < 0 || col >= grid.first().size) return 0
grid[row][col] += 1
return if (grid[row][col] == 10)
increase(grid, row - 1, col - 1) +
increase(grid, row - 1, col) +
increase(grid, row - 1, col + 1) +
increase(grid, row, col - 1) +
increase(grid, row, col + 1) +
increase(grid, row + 1, col - 1) +
increase(grid, row + 1, col) +
increase(grid, row + 1, col + 1) +
1
else 0
}
}
| 0 | Kotlin | 0 | 0 | 16233aa7c4820db072f35e7b08213d0bd3a5be69 | 2,071 | AdventOfCode | Creative Commons Zero v1.0 Universal |
2017-kotlin/src/main/kotlin/com/morninghacks/aoc2017/Day08.kt | whaley | 116,508,747 | false | null | package com.morninghacks.aoc2017
import java.lang.invoke.MethodHandles
/*
You receive a signal directly from the CPU. Because of your recent assistance with jump instructions, it would like you to compute the result of a series of unusual register instructions.
Each instruction consists of several parts: the register to modify, whether to increase or decrease that register's value, the amount by which to increase or decrease it, and a condition. If the condition fails, skip the instruction without modifying the register. The registers all start at 0. The instructions look like this:
b inc 5 if a > 1
a inc 1 if b < 5
c dec -10 if a >= 1
c inc -20 if c == 10
These instructions would be processed as follows:
Because a starts at 0, it is not greater than 1, and so b is not modified.
a is increased by 1 (to 1) because b is less than 5 (it is 0).
c is decreased by -10 (to 10) because a is now greater than or equal to 1 (it is 1).
c is increased by -20 (to -10) because c is equal to 10.
After this process, the largest value in any register is 1.
You might also encounter <= (less than or equal to) or != (not equal to). However, the CPU doesn't have the bandwidth to tell you what all the registers are named, and leaves that to you to determine.
What is the largest value in any register after completing the instructions in your puzzle input?
*/
sealed class ComparisonOperator {
abstract fun apply(lhs: Int, rhs: Int): Boolean
}
object LessThan : ComparisonOperator() {
override fun apply(lhs: Int, rhs: Int) = lhs < rhs
}
object LessThanOrEqualTo : ComparisonOperator() {
override fun apply(lhs: Int, rhs: Int) = lhs <= rhs
}
object GreaterThan : ComparisonOperator() {
override fun apply(lhs: Int, rhs: Int) = lhs > rhs
}
object GreaterThanOrEqualTo : ComparisonOperator() {
override fun apply(lhs: Int, rhs: Int) = lhs >= rhs
}
object EqualTo : ComparisonOperator() {
override fun apply(lhs: Int, rhs: Int) = lhs == rhs
}
object NotEqualTo : ComparisonOperator() {
override fun apply(lhs: Int, rhs: Int) = lhs != rhs
}
data class Instruction(val registerName: String, val incValue: Int, val condition: Condition)
data class Condition(val registerName: String, val comparisonOperator: ComparisonOperator, val value: Int)
data class Results(val registers: Map<String, Int>, val highestSeenValue: Int)
fun runInstructions(input: String): Results {
return runInstructions(parseInput(input))
}
fun runInstructions(instructions: List<Instruction>): Results {
var highestSeenValue: Int = Int.MIN_VALUE
val registers = mutableMapOf<String, Int>()
for (instruction in instructions) {
val cond = instruction.condition
registers.putIfAbsent(instruction.registerName, 0)
registers.putIfAbsent(cond.registerName, 0)
if (cond.comparisonOperator.apply(registers.getOrDefault(cond.registerName, 0), cond.value)) {
registers.merge(instruction.registerName, instruction.incValue, fun(orig, incBy): Int {
//This is mildly disgusting, but gets the answer quickly
val res = orig + incBy
if (res > highestSeenValue) {
highestSeenValue = res
}
return res
})
}
}
return Results(registers, highestSeenValue)
}
fun parseInput(input: String): List<Instruction> {
return input.lines()
.filter(String::isNotBlank)
.map(::lineToInstruction)
}
fun lineToInstruction(line: String): Instruction {
val parts: List<String> = line.trim().split("""\s""".toRegex())
val registerName: String = parts[0]
val incBy: Int = if (parts[1] == "inc") parts[2].toInt() else parts[2].toInt() * -1
val conditionRegisterName: String = parts[4]
val conditionValue: Int = parts[6].toInt()
val operator: ComparisonOperator = when (parts[5]) {
"==" -> EqualTo
"!=" -> NotEqualTo
">" -> GreaterThan
">=" -> GreaterThanOrEqualTo
"<" -> LessThan
"<=" -> LessThanOrEqualTo
else -> throw IllegalArgumentException()
}
return Instruction(registerName, incBy, Condition(conditionRegisterName, operator, conditionValue))
}
fun main(args: Array<String>) {
val input = MethodHandles.lookup().lookupClass().getResourceAsStream("/Day08Input.txt").bufferedReader().readText()
val results = runInstructions(input)
println("Part One Answer: ${results.registers.values.max()}")
println("Part Two Answer: ${results.highestSeenValue}")
}
| 0 | Kotlin | 0 | 0 | 16ce3c9d6310b5faec06ff580bccabc7270c53a8 | 4,575 | advent-of-code | MIT License |
src/Day02.kt | 6234456 | 572,616,769 | false | {"Kotlin": 39979} | fun main() {
val judge: (Char, Char)->Int = {
a, x ->
val t1 = a - 'A'
val t2 = x - 'X'
(t2 + 1) + (
if (t1 == t2)
3
else{
if((t1 + 2).mod(3) == t2) 0 else 6
})
}
val judge2: (Char, Char)->Int = {
a, x ->
val t1 = a - 'A'
val t2 = x - 'X'
if (t2 == 0)
1+ (t1 + 2).mod(3)
else{
if(t2 == 1)
3 + t1 + 1
else
7 + (t1 + 1).mod(3)
}
}
fun part1(input: List<String>): Int {
return input.map {
val a = it.first()
val x = it.last()
judge(a, x)
}.fold(0){
acc, i ->
acc + i
}
}
fun part2(input: List<String>): Int {
return input.map {
val a = it.first()
val x = it.last()
judge2(a, x)
}.fold(0){
acc, i ->
acc + i
}
}
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | b6d683e0900ab2136537089e2392b96905652c4e | 1,148 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/Day02.kt | carotkut94 | 572,816,808 | false | {"Kotlin": 7508} | fun main() {
fun prepare(input: String): List<String> {
return input.split("\n")
}
fun part1(input: List<String>): Int {
var total = 0
input.forEach {
val (move1, move2) = it.split(" ")
val v1 = getValue(move1)
val v2 = getValue(move2)
total += if (v1 == v2) {
3 + v2
} else if (v2 - v1 == 2) {
v2
} else if (v1 - v2 == 2 || v2 > v1) {
v2 + 6
} else {
v2
}
}
return total
}
fun part2(input: List<String>): Int {
val l = input.map {
when (it) {
"A X" -> 3
"A Y" -> 4
"A Z" -> 8
"B X" -> 1
"B Y" -> 5
"B Z" -> 9
"C X" -> 2
"C Y" -> 6
else -> 7
}
}
return l.sum()
}
val input = readAsString("Day02")
val i = prepare(input)
println(part1(i))
println(part2(i))
}
fun getValue(face: String): Int {
return when (face) {
"X", "A" -> 1
"Y", "B" -> 2
else -> 3
}
} | 0 | Kotlin | 0 | 0 | ef3dee8be98abbe7e305e62bfe8c7d2eeff808ad | 1,223 | aoc-2022 | Apache License 2.0 |
src/Day04.kt | matusekma | 572,617,724 | false | {"Kotlin": 119912, "JavaScript": 2024} | class Day04 {
fun part1(input: List<String>): Int {
var sum = 0
for (row in input) {
val (first, second) = row.split(',')
.map { interval -> interval.split('-').map { it.toInt() } }
if((first[0] <= second[0] && first[1] >= second[1]) ||
(first[0] >= second[0] && first[1] <= second[1])) {
sum++
}
}
return sum
}
private fun itemToValue(it: Char) = if (it.isUpperCase()) it.code - 38 else it.code - 96
fun part2(input: List<String>): Int {
var sum = 0
for (row in input) {
val (first, second) = row.split(',')
.map { interval -> interval.split('-').map { it.toInt() } }
if(!(first[0]..first[1]).toSet().intersect((second[0]..second[1]).toList().toSet()).isEmpty()) {
sum++
}
}
return sum
}
}
fun main() {
val day04 = Day04()
val input = readInput("input04_1")
println(day04.part1(input))
println(day04.part2(input))
} | 0 | Kotlin | 0 | 0 | 744392a4d262112fe2d7819ffb6d5bde70b6d16a | 1,072 | advent-of-code | Apache License 2.0 |
src/main/kotlin/io/github/mikaojk/day1/part2/Day1Part2.kt | MikAoJk | 724,057,348 | false | {"Kotlin": 6448} | package io.github.mikaojk.day1.part2
import io.github.mikaojk.day1.part1.CalibrationDigit
import io.github.mikaojk.day1.part1.CalibrationDigits
import io.github.mikaojk.day1.part1.getFileAsString
import io.github.mikaojk.day1.part1.sumAllDigtits
fun day1Part2(): String {
val calibrationDocument = getFileAsString("src/main/resources/day1/input.txt")
val calibrationList = calibrationDocument.split("\\n\\n".toRegex())
.map { it.split("\\n".toRegex()) }.map {
CalibrationDigits(calibration = findTwoFirstDigtits(it))
}.first()
return sumAllDigtits(calibrationList.calibration).toString()
}
fun findTwoFirstDigtits(calibration: List<String>): List<CalibrationDigit> {
return calibration.map { digit ->
val updateredDigit = replaceLettersWithDigit(digit)
val digitsInString = updateredDigit.filter { it.isDigit() }
val firstDigit = digitsInString.first()
val secoundDigit = digitsInString.last()
val digitString = firstDigit.toString() + secoundDigit.toString()
CalibrationDigit(digit = digitString.toInt())
}
}
data class WordOrder(
val word: String,
val order: Int,
val digit: String
)
fun replaceLettersWithDigit(calibration: String): String {
val wordOrderList: List<WordOrder> = mutableListOf(
WordOrder("one", calibration.indexOf("one"), "one1one"),
WordOrder("two", calibration.indexOf("two"), "two2two"),
WordOrder("three", calibration.indexOf("three"), "three3three"),
WordOrder("four", calibration.indexOf("four"), "four4four"),
WordOrder("five", calibration.indexOf("five"), "five5five"),
WordOrder("six", calibration.indexOf("six"), "six6six"),
WordOrder("seven", calibration.indexOf("seven"), "seven7seven"),
WordOrder("eight", calibration.indexOf("eight"), "eight8eight"),
WordOrder("nine", calibration.indexOf("nine"), "nine9nine")
)
val wordHits = wordOrderList
.filter { it.order != -1 }
.sortedBy { it.order }
var replaceLettersWithDigit = calibration
wordHits.forEach {
replaceLettersWithDigit = replaceLettersWithDigit.replace(it.word, it.digit)
}
return replaceLettersWithDigit
} | 0 | Kotlin | 0 | 0 | 0147f91c722225ae12382a82d131695b2ec5a766 | 2,248 | advent-of-code-2023 | MIT License |
src/main/kotlin/de/dikodam/calendar/Day06.kt | dikodam | 433,719,746 | false | {"Kotlin": 51383} | package de.dikodam.calendar
import de.dikodam.AbstractDay
import de.dikodam.executeTasks
import kotlin.time.ExperimentalTime
@ExperimentalTime
fun main() {
Day06().executeTasks()
}
val memoizationMap = mutableMapOf<Pair<Int, Int>, Long>()
fun computeRes(startState: Int, rounds: Int): Long {
if (startState > rounds) {
return 1L
}
val key = startState to rounds
if (memoizationMap.keys.contains(key)) {
return memoizationMap[key]!!
}
var count = 1L
var currentState = startState
var remainingRounds = rounds
while (remainingRounds > 0) {
currentState -= 1
if (currentState == -1) {
currentState = 6
count += computeRes(8, remainingRounds - 1)
}
remainingRounds -= 1
}
memoizationMap[key] = count
return count
}
class Day06 : AbstractDay() {
// val input: List<Lanternfish> = "3,4,3,1,2"
val input: List<Lanternfish> = readInputRaw()
.split(",").map { Lanternfish(it.toInt()) }
override fun task1(): String {
var lanternfishes = input
repeat(80) {
lanternfishes = lanternfishes.flatMap { it.tick() }
}
return lanternfishes.count().toString()
}
override fun task2(): String {
val fishCounter = mutableMapOf<Int, Long>()
readInputRaw()
//"3,4,3,1,2"
.split(",")
.map { it.toInt() }
.groupBy { it }
.mapValuesTo(fishCounter) { (_, fishList) -> fishList.size.toLong() }
repeat(256) {
// index shift by -1
// index 0 goes to index 6 AND another copy to index 8
// index 6 is sum of index 0 and index 7
var buffer = fishCounter[0] ?: 0L
fishCounter[0] = fishCounter[1] ?: 0L
fishCounter[1] = fishCounter[2] ?: 0L
fishCounter[2] = fishCounter[3] ?: 0L
fishCounter[3] = fishCounter[4] ?: 0L
fishCounter[4] = fishCounter[5] ?: 0L
fishCounter[5] = fishCounter[6] ?: 0L
fishCounter[6] = (fishCounter[7] ?: 0L) + (buffer)
fishCounter[7] = fishCounter[8] ?: 0L
fishCounter[8] = buffer
}
return fishCounter.values.sum().toString()
}
}
data class Lanternfish(val counter: Int) {
fun tick(): List<Lanternfish> {
val newCounter = counter.dec()
return if (newCounter == -1) {
listOf(Lanternfish(6), Lanternfish(8))
} else {
listOf(Lanternfish(newCounter))
}
}
}
| 0 | Kotlin | 0 | 1 | 4934242280cebe5f56ca8d7dcf46a43f5f75a2a2 | 2,580 | aoc-2021 | MIT License |
src/Day01.kt | jordanfarrer | 573,120,618 | false | {"Kotlin": 20954} | fun main() {
fun getElves(input: List<String>): List<Elf> {
var elfIndex = 0
val elves = mutableListOf<Elf>()
for (line in input) {
if (line == "") {
elfIndex++
} else {
var elf = elves.find { it.index == elfIndex }
if (elf == null) {
elf = Elf(elfIndex, mutableListOf())
elves.add(elf)
}
elf.items.add(line.toInt())
}
}
return elves
}
fun part1(input: List<String>): Int {
val elves = getElves(input)
return elves.maxOf { it.getTotalCalories() }
}
fun part2(input: List<String>): Int {
val elves = getElves(input)
return elves.sortedByDescending { it.getTotalCalories() }.take(3).sumOf { it.getTotalCalories() }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
val part1Result = part1(testInput)
println("Part 1 (test): $part1Result")
check(part1Result == 24000)
val part2Result = part2(testInput)
println("Part 2 (test): $part2Result")
check(part2Result == 45000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
data class Elf(val index: Int, val items: MutableList<Int>)
fun Elf.getTotalCalories() = this.items.sum() | 0 | Kotlin | 0 | 1 | aea4bb23029f3b48c94aa742958727d71c3532ac | 1,412 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/nativeMain/kotlin/xyz/justinhorton/aoc2022/Day09.kt | justinhorton | 573,614,839 | false | {"Kotlin": 39759, "Shell": 611} | package xyz.justinhorton.aoc2022
import kotlin.math.abs
/**
* https://adventofcode.com/2022/day/9
*/
class Day09(override val input: String) : Day() {
override fun part1(): String {
var headPos = Point(0, 0)
var tailPos = Point(0, 0)
val seenTailPos = mutableSetOf<Point>().apply { add(tailPos) }
input.trim()
.lines()
.forEach { line ->
val split = line.split(" ")
val delta = split[1].toInt()
val dir = split[0]
repeat(delta) {
headPos = computeUpdatedHead(headPos, dir)
tailPos = computeUpdatedTail(headPos, tailPos)
seenTailPos.add(tailPos)
}
}
return seenTailPos.size.toString()
}
override fun part2(): String {
val knots = (0..9).associateWithTo(mutableMapOf()) { Point(0, 0) }
val seenTailPos = mutableSetOf<Point>().apply { add(Point(0, 0)) }
input.trim()
.lines()
.forEach { line ->
val split = line.split(" ")
val delta = split[1].toInt()
val dir = split[0]
repeat(delta) {
knots[0] = computeUpdatedHead(knots.getValue(0), dir)
for (i in 1..9) {
knots[i] = computeUpdatedTail(knots.getValue(i - 1), knots.getValue(i))
}
seenTailPos.add(knots.getValue(9))
}
}
return seenTailPos.size.toString()
}
private fun computeUpdatedHead(headPos: Point, dir: String) = Point(
x = headPos.x + when (dir) {
"L" -> -1
"R" -> 1
else -> 0
},
y = headPos.y + when (dir) {
"D" -> -1
"U" -> 1
else -> 0
}
)
private fun computeUpdatedTail(
headPos: Point,
tailPos: Point
): Point {
// (0, 0) = bottom left = start
val dx = headPos.xdiff(tailPos)
val dy = headPos.ydiff(tailPos)
return if (headPos == tailPos || (abs(dx) + abs(dy) == 1) || (abs(dx) == 1 && abs(dy) == 1)) {
// "touching"
tailPos
} else if (abs(dx) == 2 && abs(dy) == 0 || abs(dy) == 2 && abs(dx) == 0) {
// directly above, below, left, right (and not touching)
Point(
x = tailPos.x + if (dx == 0) 0 else dx / abs(dx),
y = tailPos.y + if (dy == 0) 0 else dy / abs(dy)
)
} else {
// diagonal
Point(x = tailPos.x + dx / abs(dx), y = tailPos.y + dy / abs(dy))
}
}
}
private data class Point(val x: Int, val y: Int) {
fun xdiff(other: Point) = this.x - other.x
fun ydiff(other: Point) = this.y - other.y
}
| 0 | Kotlin | 0 | 1 | bf5dd4b7df78d7357291c7ed8b90d1721de89e59 | 2,876 | adventofcode2022 | MIT License |
advent-of-code/src/main/kotlin/com/akikanellis/adventofcode/year2022/Day19.kt | akikanellis | 600,872,090 | false | {"Kotlin": 142932, "Just": 977} | package com.akikanellis.adventofcode.year2022
import java.util.*
import kotlin.math.ceil
import kotlin.math.max
object Day19 {
private val BLUEPRINT_REGEX = """\d+""".toRegex()
fun qualityLevelsOfBlueprints(input: String) = blueprints(input)
.map { blueprint -> Pair(blueprint.id, blueprint.maxGeodeThatCanBeOpened(24)) }
.sumOf { (id, maxGeodeThatCanBeOpened) -> id * maxGeodeThatCanBeOpened }
fun maxGeodeThatCanBeOpenedForTopThreeBlueprints(input: String) = blueprints(input)
.take(3)
.map { blueprint -> blueprint.maxGeodeThatCanBeOpened(32) }
.reduce(Int::times)
private fun blueprints(input: String) = input.lines()
.filter { it.isNotBlank() }
.map { line -> BLUEPRINT_REGEX.findAll(line).map { it.value.toInt() }.toList() }
.map { idAndCosts ->
Blueprint(
id = idAndCosts[0],
robots = listOf(
OreRobot(Materials(ore = idAndCosts[1])),
ClayRobot(Materials(ore = idAndCosts[2])),
ObsidianRobot(Materials(ore = idAndCosts[3], clay = idAndCosts[4])),
GeodeRobot(Materials(ore = idAndCosts[5], obsidian = idAndCosts[6]))
)
)
}
private data class Blueprint(val id: Int, val robots: List<Robot>) {
val maxMaterialCosts = Materials(
ore = robots.maxOf { it.materialCosts.ore },
clay = robots.maxOf { it.materialCosts.clay },
obsidian = robots.maxOf { it.materialCosts.obsidian }
)
fun maxGeodeThatCanBeOpened(minutes: Int): Int {
var currentMaxGeodeThatCanBeOpened = 0
val statesQueue = PriorityQueue(
listOf(
SystemState(
remainingMinutes = minutes,
materials = Materials(ore = 1),
robotInventory = RobotInventory(listOf(robots.first { it is OreRobot }))
)
)
)
while (statesQueue.isNotEmpty()) {
val currentState = statesQueue.poll()
if (currentState.canNotOutperform(currentMaxGeodeThatCanBeOpened)) continue
currentMaxGeodeThatCanBeOpened = max(
currentMaxGeodeThatCanBeOpened,
currentState.geodeThatCanBeOpened
)
statesQueue += currentState.nextStates(this)
}
return currentMaxGeodeThatCanBeOpened
}
}
private interface Robot {
val materialCosts: Materials
fun moreRobotsOfTypeNeeded(
robotInventory: RobotInventory,
maxMaterialCosts: Materials
): Boolean
}
private data class OreRobot(override val materialCosts: Materials) : Robot {
override fun moreRobotsOfTypeNeeded(
robotInventory: RobotInventory,
maxMaterialCosts: Materials
) = maxMaterialCosts.ore > robotInventory.oreRobots
}
private data class ClayRobot(override val materialCosts: Materials) : Robot {
override fun moreRobotsOfTypeNeeded(
robotInventory: RobotInventory,
maxMaterialCosts: Materials
) = maxMaterialCosts.clay > robotInventory.clayRobots
}
private data class ObsidianRobot(override val materialCosts: Materials) : Robot {
override fun moreRobotsOfTypeNeeded(
robotInventory: RobotInventory,
maxMaterialCosts: Materials
) = maxMaterialCosts.obsidian > robotInventory.obsidianRobots
}
private data class GeodeRobot(override val materialCosts: Materials) : Robot {
override fun moreRobotsOfTypeNeeded(
robotInventory: RobotInventory,
maxMaterialCosts: Materials
) = robotInventory.obsidianRobots > 0
}
private data class Materials(
val ore: Int = 0,
val clay: Int = 0,
val obsidian: Int = 0,
val geode: Int = 0
) {
operator fun plus(other: Materials) = Materials(
ore = ore + other.ore,
clay = clay + other.clay,
obsidian = obsidian + other.obsidian,
geode = geode + other.geode
)
operator fun minus(other: Materials) = Materials(
ore = (ore - other.ore).coerceAtLeast(0),
clay = (clay - other.clay).coerceAtLeast(0),
obsidian = (obsidian - other.obsidian).coerceAtLeast(0),
geode = (geode - other.geode).coerceAtLeast(0)
)
}
private data class RobotInventory(val robots: List<Robot>) {
val oreRobots = robots.count { it is OreRobot }
val clayRobots = robots.count { it is ClayRobot }
val obsidianRobots = robots.count { it is ObsidianRobot }
val geodeRobots = robots.count { it is GeodeRobot }
operator fun plus(robot: Robot) = RobotInventory(robots + robot)
}
private data class SystemState(
val remainingMinutes: Int,
val materials: Materials,
val robotInventory: RobotInventory
) : Comparable<SystemState> {
private val maxGeodeThatCanBeOpened: Int
get() {
val n = remainingMinutes - 2
val sumOfRemainingMinutes = n * (n + 1) / 2
val potentialGeode = sumOfRemainingMinutes + robotInventory.geodeRobots * (n + 1)
return materials.geode + potentialGeode
}
val geodeThatCanBeOpened =
materials.geode + robotInventory.geodeRobots * (remainingMinutes - 1)
override fun compareTo(other: SystemState) =
other.materials.geode.compareTo(materials.geode)
fun canNotOutperform(geode: Int) = maxGeodeThatCanBeOpened <= geode
fun nextStates(blueprint: Blueprint) = blueprint.robots
.filter { it.moreRobotsOfTypeNeeded(robotInventory, blueprint.maxMaterialCosts) }
.mapNotNull { nextStateWithRobotCreated(it) }
private fun nextStateWithRobotCreated(robot: Robot): SystemState? {
val minutesToBuild = minutesToBuild(robot)
val remainingMinutesAfterRobotBuilt = remainingMinutes - minutesToBuild
if (remainingMinutesAfterRobotBuilt <= 0) return null
val robotProducedMaterial = Materials(
ore = robotInventory.oreRobots * minutesToBuild,
clay = robotInventory.clayRobots * minutesToBuild,
obsidian = robotInventory.obsidianRobots * minutesToBuild,
geode = robotInventory.geodeRobots * minutesToBuild
)
return SystemState(
remainingMinutes = remainingMinutesAfterRobotBuilt,
materials = materials + robotProducedMaterial - robot.materialCosts,
robotInventory = robotInventory + robot
)
}
private fun minutesToBuild(robot: Robot): Int {
val remainingMaterial = robot.materialCosts - materials
return maxOf(
ceil(remainingMaterial.ore / robotInventory.oreRobots.toFloat()).toInt(),
ceil(remainingMaterial.clay / robotInventory.clayRobots.toFloat()).toInt(),
ceil(remainingMaterial.obsidian / robotInventory.obsidianRobots.toFloat()).toInt(),
ceil(remainingMaterial.geode / robotInventory.geodeRobots.toFloat()).toInt()
) + 1
}
}
}
| 8 | Kotlin | 0 | 0 | 036cbcb79d4dac96df2e478938de862a20549dce | 7,485 | advent-of-code | MIT License |
Core/src/main/kotlin/com/github/ezauton/core/utils/math/AlgebraUtils.kt | ezAuton | 140,008,964 | false | null | package com.github.ezauton.core.utils.math
/**
* @param map
* @return If is odd function
*/
fun hasOddSymmetry(map: Map<out Double, Double>): Boolean {
return map.entries.stream().allMatch { entry ->
val key = entry.key
val value = entry.value
val symmetricEntry = map[-key]?.toDouble()
symmetricEntry != null && symmetricEntry == -value
}
}
/**
* @param map
* @return If is even function
*/
fun hasEvenSymmetry(map: Map<out Double, Double>): Boolean {
return map.entries.stream().allMatch { entry ->
val key = entry.key
val value = entry.value
val symmetricValue = map[-key]?.toDouble()
symmetricValue != null && symmetricValue == value
}
}
/**
* Solve for the roots of a quadratic of the form ax^2 + bx + c
*
* @param a x^2 coefficient
* @param b x coefficient
* @param c added constant
* @return roots of the quadratic
*/
fun quadratic(a: Double, b: Double, c: Double): Set<Double> {
val toReturn = HashSet<Double>()
val discriminate = discriminate(a, b, c)
if (discriminate < 0) {
return toReturn
} else if (discriminate == 0.0) {
toReturn.add(-b / (2 * a))
} else {
val LHS = -b / (2 * a)
val RHS = Math.sqrt(discriminate) / (2 * a)
toReturn.add(LHS + RHS)
toReturn.add(LHS - RHS)
}
return toReturn
}
/**
* Solve for the discriminant of a quadratic of the form ax^2 + bx + c
*
* @param a x^2 coefficient
* @param b x coefficient
* @param c added thing
* @return roots of the quadratic
* @see MathUtils.Algebra.quadratic
*/
fun discriminate(a: Double, b: Double, c: Double): Double {
return b * b - 4.0 * a * c
}
| 26 | Kotlin | 3 | 25 | b08c52233b0c492e1b5fa0a4d638b436b5d06605 | 1,622 | ezAuton | MIT License |
src/Day01.kt | pedroldk | 573,424,273 | false | {"Kotlin": 4625} | fun main() {
fun getCarriersValues(input: List<String>): MutableList<Int> {
val biggestCarriers = mutableListOf<Int>()
var sum = 0
for (line in input) {
if (line == "") {
biggestCarriers.add(sum)
sum = 0
} else {
sum += line.toInt()
}
}
if (sum != 0) {
biggestCarriers.add(sum)
}
return biggestCarriers
}
fun part1(input: List<String>): Int {
val biggestCarriers = getCarriersValues(input)
return biggestCarriers.max()
}
fun part2(input: List<String>): Int {
val biggestCarriers = getCarriersValues(input).sortedDescending()
return biggestCarriers[0] + biggestCarriers[1] + biggestCarriers[2]
}
// 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 | 68348bbfc308d257b2d02fa87dd241f8f584b444 | 1,091 | aoc-2022-in-kotlin | Apache License 2.0 |
src/main/kotlin/adventofcode/day05/AlmanacSection.kt | jwcarman | 731,408,177 | false | {"Kotlin": 137289} | /*
* Copyright (c) 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 adventofcode.day05
import adventofcode.util.intersection
import adventofcode.util.removeAll
import adventofcode.util.translate
data class AlmanacSection(val mappings: List<Mapping>) {
fun map(srcValue: Long): Long = mappings.find { it.inputRange.contains(srcValue) }?.map(srcValue) ?: srcValue
operator fun plus(successor: AlmanacSection): AlmanacSection {
val newMappings = mutableListOf<Mapping>()
newMappings.addAll(createIntersectionMappings(successor))
newMappings.addAll(createUnmappedPredecessorMappings(successor))
newMappings.addAll(createUnmappedSuccessorMappings(successor))
return AlmanacSection(newMappings.sortedBy { it.inputRange.first })
}
private fun createUnmappedPredecessorMappings(successor: AlmanacSection): List<Mapping> {
return mappings.flatMap { predMapping ->
predMapping.outputRange
.removeAll(successor.mappings.map { it.inputRange })
.map { Mapping(it.translate(-predMapping.offset), predMapping.offset) }
}
}
private fun createUnmappedSuccessorMappings(successor: AlmanacSection): List<Mapping> {
return successor.mappings.flatMap { succMapping ->
succMapping.inputRange
.removeAll(mappings.map { it.outputRange })
.map { Mapping(it, succMapping.offset) }
}
}
private fun createIntersectionMappings(successor: AlmanacSection): List<Mapping> {
return mappings.map { predMapping ->
successor.mappings
.filter { predMapping.feedsInto(it) }
.map {
Mapping(
predMapping.outputRange.intersection(it.inputRange).translate(-predMapping.offset),
predMapping.offset + it.offset
)
}
}.flatten()
}
companion object {
fun parse(input: String): AlmanacSection {
val mappings = input.substringAfter(':').trim().lines()
.map { it.trim() }
.map { Mapping.parse(it) }
.sortedBy { it.inputRange.first }
return AlmanacSection(mappings)
}
fun parseList(input: String): List<AlmanacSection> {
return input.trim().split("\n\n").map { parse(it) }
}
}
}
| 0 | Kotlin | 0 | 0 | dfb226e92a03323ad48c50d7e970d2a745b479bb | 2,962 | adventofcode2023 | Apache License 2.0 |
src/main/kotlin/day3/Day3NoMatterHowYouSliceIt.kt | Zordid | 160,908,640 | false | null | package day3
import shared.readPuzzle
data class Claim(val id: String, val left: Int, val top: Int, val width: Int, val height: Int) {
private val right = left + width - 1
private val bottom = top + height - 1
fun cut(fabric: List<ByteArray>) {
for (line in top until (top + height)) {
for (col in left until (left + width)) {
fabric[line][col]++
}
}
}
infix fun overlaps(other: Claim): Boolean {
return !(left > other.right || right < other.left) &&
!(top > other.bottom || bottom < other.top)
}
}
private val claimDefinition = Regex("#(\\d+) @ (\\d+),(\\d+): (\\d+)x(\\d+)")
fun String.toClaim(): Claim {
val (id, left, top, width, height) =
claimDefinition.matchEntire(this)?.destructured ?: throw UnsupportedOperationException(this)
return Claim(id, left.toInt(), top.toInt(), width.toInt(), height.toInt())
}
fun part1(claims: List<Claim>): Int {
val fabric = (0..999).map { ByteArray(1000) { 0 } }
claims.forEach { it.cut(fabric) }
return fabric.sumOf { it.count { it > 1 } }
}
fun part2(claims: List<Claim>): Claim {
return claims.single { a -> (claims - a).all { b -> !a.overlaps(b) } }
}
fun main() {
val claims = readPuzzle(3) { it.toClaim() }
println(part1(claims))
println(part2(claims))
} | 0 | Kotlin | 0 | 0 | f246234df868eabecb25387d75e9df7040fab4f7 | 1,360 | adventofcode-kotlin-2018 | Apache License 2.0 |
src/day15/result.kt | davidcurrie | 437,645,413 | false | {"Kotlin": 37294} | package day15
import java.io.File
import java.util.*
val deltas = listOf(Coord(-1, 0), Coord(1, 0), Coord(0, -1), Coord(0, 1))
data class Coord(val x: Int, val y: Int)
data class CoordRisk(val coord: Coord, val risk: Int)
fun Map<Coord, Int>.explore(): Int {
val end = Coord(keys.maxOf { it.x }, keys.maxOf { it.y })
val visited = mutableSetOf<Coord>()
val queue = PriorityQueue<CoordRisk> { p1, p2 -> p1.risk - p2.risk }
queue.add(CoordRisk(Coord(0, 0), 0))
while (queue.peek().coord != end) {
val pair = queue.poll()
deltas.map { delta -> Coord(pair.coord.x + delta.x, pair.coord.y + delta.y) }
.filter { it in this.keys }
.filter { it !in visited }
.forEach {
visited += it
queue.add(CoordRisk(it, pair.risk + this[it]!!))
}
}
return queue.peek().risk
}
fun main() {
val grid = File("src/day15/input.txt").readLines()
.mapIndexed { y, line -> line.toList().mapIndexed { x, ch -> Coord(x, y) to ch.digitToInt() } }
.flatten().toMap()
println(grid.explore())
val width = grid.keys.maxOf { it.x } + 1
val height = grid.keys.maxOf { it.y } + 1
val extendedGrid = mutableMapOf<Coord, Int>()
for (x in 0..4) {
for (y in 0..4) {
extendedGrid.putAll(grid.map { (coord, value) ->
Coord(coord.x + (x * width), coord.y + (y * height)) to ((value + x + y - 1) % 9) + 1
}.toMap())
}
}
println(extendedGrid.explore())
} | 0 | Kotlin | 0 | 0 | dd37372420dc4b80066efd7250dd3711bc677f4c | 1,546 | advent-of-code-2021 | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.