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/day13/day14.kt | HGilman | 572,891,570 | false | {"Kotlin": 109639, "C++": 5375, "Python": 400} | package day13
import readInput
import readTextGroups
import java.util.Stack
import kotlin.math.min
fun main() {
val day = 13
val testInput = readTextGroups("day$day/testInput")
// check(part1(testInput) == 1)
getSubLists("[1,[2,[3,[4,[5,6,7]]]],8,9]")
println()
getSubLists("[[1],[2,3,4]]")
println()
getSubLists("[[10,10,10,4,[8,[8],6,[]]]]")
}
fun part1(input: List<String>): Int {
val pairs: List<Pair<String, String>> = input.map {
val (fl, sl) = it.split("\n")
Pair(fl, sl)
}
val rightOrderIndexes = mutableListOf<Int>()
// pairs.forEach { (f, s) ->
// }
println(pairs)
return 1
}
fun part2(input: List<String>): Int {
return input.size
}
/**
* -1 wrong order
* 0 same
* 1 rightOrder
*/
fun areListsInRightOrder(list1: List<Int>, list2: List<Int>): Int {
val minSize = min(list1.size, list2.size)
for (i in 0 until minSize) {
if (list1[i] < list2[i]) {
return 1
} else if (list1[i] > list2[i]) {
return -1
}
}
return if (list1.size > list2.size) -1 else 1
}
fun getSubLists(s: String) {
val leftBracketsStack = Stack<Int>()
val innerLists = mutableListOf<String>()
s.toCharArray().forEachIndexed { i, c ->
if (c == '[') {
leftBracketsStack.push(i)
} else if (c == ']') {
val lastLeftBracketIndex = leftBracketsStack.pop()
innerLists.add(s.substring(lastLeftBracketIndex + 1, i))
}
}
innerLists.forEach {
println(it)
}
}
//fun getNextInt(s: String): Iterable<Int> {
//
// val leftBracketsStack = Stack<Int>()
// val innerLists = mutableListOf<String>()
//
// s.toCharArray().forEachIndexed { i, c ->
//
// if (c == '[') {
// leftBracketsStack.push(i)
// } else if (c == ']') {
// val lastLeftBracketIndex = leftBracketsStack.pop()
// innerLists.add(s.substring(lastLeftBracketIndex + 1, i))
// }
// }
//
//
// return object : Iterable<Int> {
//
// override fun iterator() = object : Iterator<Int> {
// override fun hasNext(): Boolean {
// }
//
// override fun next(): Int {
// }
// }
// }
//}
fun areInputsInRightOrder(s1: String, s2: String): Boolean {
val s1LeftBracketStack = Stack<Int>()
return true
}
| 0 | Kotlin | 0 | 1 | d05a53f84cb74bbb6136f9baf3711af16004ed12 | 2,429 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/14-jun.kt | aladine | 276,334,792 | false | {"C++": 70308, "Kotlin": 53152, "Java": 10020, "Makefile": 511} |
class Solution14Jun {
fun findCheapestPrice(n: Int, flights: Array<IntArray>, src: Int, dst: Int, K: Int): Int {
val adjList: HashMap<Int, HashSet<Pair<Int, Int>>> = HashMap()
for (f in flights) {
adjList
.computeIfAbsent(f[0]) { HashSet() }
.add(Pair<Int, Int>(f[1], f[2]))
}
var costs = Array(n, { _ -> -1 })
costs[src] = 0
val queue = mutableListOf<Int>()
queue.add(src)
var steps = K + 1
while (!queue.isEmpty()) {
// println("Step: $steps")
if (steps-- == 0) return costs[dst]
val currSize = queue.size
// println("size $currSize")
val tmp = costs.clone()
(0 until currSize).forEach {
val v = queue.removeAt(0)
println("process $v")
adjList.get(v)?.let {
for ((vertex, price) in it) {
println("vertex $vertex, price $price")
queue.add(vertex)
if ((tmp[vertex] == -1) || tmp[vertex] > costs[v] + price)
tmp[vertex] = costs[v] + price
}
}
}
costs = tmp
}
return costs[dst]
}
}
/*
fun findCheapestPrice(n: Int, flights: Array<IntArray>, src: Int, dst: Int, k: Int): Int {
// reorganize flights, ordered by index of departure city
val cities = mutableListOf<MutableList<IntArray>>()
for (i in 0 until n) {
cities.add(mutableListOf<IntArray>())
}
for (flight in flights) {
cities[flight[0]].add(flight)
}
var res = -1
// create a queue of [current location, cost so far, number of stops so far] IntArray states
val queue = LinkedList<IntArray>()
queue.add(intArrayOf(src, 0, 0))
while (!queue.isEmpty()) {
val state = queue.poll()
if (res == -1 || state[1] < res) {
if (state[0] == dst) {
// if we're at the destination, update the best total cost (res).
res = state[1]
} else if (state[2] <= k) {
// if we can still take another flight, add all flights from the current city.
for (flight in cities[state[0]]) {
queue.add(intArrayOf(flight[1], state[1] + flight[2], state[2] + 1))
}
}
}
}
return res
} */
| 0 | C++ | 1 | 1 | 54b7f625f6c4828a72629068d78204514937b2a9 | 2,584 | awesome-leetcode | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/TopKFrequentElements.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import java.util.PriorityQueue
import java.util.Queue
import java.util.Random
/**
* 347. Top K Frequent Elements
* @see <a href="https://leetcode.com/problems/top-k-frequent-elements/">Source</a>
*/
fun interface TopKFrequentElements {
operator fun invoke(nums: IntArray, k: Int): IntArray
}
/**
* Approach 1: Heap
*/
class TopKFrequentElementsHeap : TopKFrequentElements {
override fun invoke(nums: IntArray, k: Int): IntArray {
// O(1) time
if (k == nums.size) {
return nums
}
// 1. build hash map : character and how often it appears
// O(N) time
val count: MutableMap<Int, Int> = HashMap()
for (n in nums) {
count[n] = count.getOrDefault(n, 0) + 1
}
// init heap 'the less frequent element first'
val heap: Queue<Int> = PriorityQueue { n1, n2 -> count[n1]!! - count[n2]!! }
// 2. keep k top frequent elements in the heap
// O(N log k) < O(N log N) time
for (n in count.keys) {
heap.add(n)
if (heap.size > k) heap.poll()
}
// 3. build an output array
// O(k log k) time
// 3. build an output array
// O(k log k) time
val top = IntArray(k)
for (i in k - 1 downTo 0) {
top[i] = heap.poll()
}
return top
}
}
/**
* Approach 2: Quickselect (Hoare's selection algorithm)
*/
class TopKFrequentElementsQuickSelect : TopKFrequentElements {
lateinit var unique: IntArray
var count: MutableMap<Int, Int> = HashMap()
override fun invoke(nums: IntArray, k: Int): IntArray {
// build hash map : character and how often it appears
for (num in nums) {
count[num] = count.getOrDefault(num, 0) + 1
}
// array of unique elements
val n = count.size
unique = IntArray(n)
for ((i, num) in count.keys.withIndex()) {
unique[i] = num
}
// kth top frequent element is (n - k)th less frequent.
// Do a partial sort: from less frequent to the most frequent, till
// (n - k)th less frequent element takes its place (n - k) in a sorted array.
// All element on the left are less frequent.
// All the elements on the right are more frequent.
quickSelect(0, n - 1, n - k)
// Return top k frequent elements
return unique.copyOfRange(n - k, n)
}
fun swap(a: Int, b: Int) {
val tmp = unique[a]
unique[a] = unique[b]
unique[b] = tmp
}
fun partition(left: Int, right: Int, pivotIndex: Int): Int {
val pivotFrequency = count[unique[pivotIndex]]!!
// 1. move pivot to end
swap(pivotIndex, right)
var storeIndex = left
// 2. move all less frequent elements to the left
for (i in left..right) {
if (count[unique[i]]!! < pivotFrequency) {
swap(storeIndex, i)
storeIndex++
}
}
// 3. move pivot to its final place
swap(storeIndex, right)
return storeIndex
}
/**
* Sort a list within left.right till kth less frequent element
* takes its place.
*/
private fun quickSelect(left: Int, right: Int, kSmallest: Int) {
// base case: the list contains only one element
if (left == right) return
// select a random pivot_index
val randomNum = Random()
var pivotIndex: Int = left + randomNum.nextInt(right - left)
// find the pivot position in a sorted list
pivotIndex = partition(left, right, pivotIndex)
// if the pivot is in its final sorted position
if (kSmallest == pivotIndex) {
return
} else if (kSmallest < pivotIndex) {
// go left
quickSelect(left, pivotIndex - 1, kSmallest)
} else {
// go right
quickSelect(pivotIndex + 1, right, kSmallest)
}
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 4,651 | kotlab | Apache License 2.0 |
src/aoc2022/Day03.kt | RobertMaged | 573,140,924 | false | {"Kotlin": 225650} | package aoc2022
fun main() {
fun Set<Char>.calculatePriority(): Int = sumOf { duplicatedItemChar ->
if (duplicatedItemChar.isLowerCase())
(duplicatedItemChar.code % 'a'.code) + 1
else
(duplicatedItemChar.code % 'A'.code) + 27
}
fun part1(input: List<String>): Int = input.sumOf { line ->
val (first, second) = line.chunked(line.length / 2).map { it.toHashSet() }
return@sumOf (first intersect second).calculatePriority()
}
fun part2(input: List<String>): Int = input.chunked(3) { threeElves ->
val (first, second, third) = threeElves.map { it.toHashSet() }
return@chunked (first intersect second intersect third).calculatePriority()
}.sum()
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput).also(::println) == 157)
check(part2(testInput).also(::println) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | e2e012d6760a37cb90d2435e8059789941e038a5 | 1,059 | Kotlin-AOC-2023 | Apache License 2.0 |
src/Day03.kt | jorgecastrejon | 573,097,701 | false | {"Kotlin": 33669} | fun main() {
fun part1(input: List<String>): Int =
input.sumOf { rucksack -> findMisplacedItem(rucksack).priority }
fun part2(input: List<String>): Int =
input.chunked(3).sumOf { group -> findBadge(group).priority }
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
val letters = CharRange('a','z')
val Char.priority: Int
get() = letters.indexOf(lowercaseChar()) + 1 + if (isUpperCase()) 26 else 0
fun findMisplacedItem(rucksack: String): Char =
rucksack.chunked(rucksack.length / 2, CharSequence::toSet).reduce(::intersect).first()
fun findBadge(group: List<String>): Char =
group.map(CharSequence::toSet).reduce(::intersect).first()
fun intersect(one: Set<Char>, another: Set<Char>): Set<Char> = one.intersect(another)
| 0 | Kotlin | 0 | 0 | d83b6cea997bd18956141fa10e9188a82c138035 | 806 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/LongestCommonSubsequence.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import kotlin.math.max
/**
* 1143. Longest Common Subsequence
* @see <a href="https://leetcode.com/problems/longest-common-subsequence">Source</a>
*/
fun interface LongestCommonSubsequence {
operator fun invoke(text1: String, text2: String): Int
}
class LongestCommonSubsequenceDP : LongestCommonSubsequence {
override operator fun invoke(text1: String, text2: String): Int {
if (text1.length < text2.length) {
return calculateLCS(text1, text2)
}
return calculateLCS(text2, text1)
}
private fun calculateLCS(firstString: String, secondString: String): Int {
val dpTable = Array(2) { IntArray(firstString.length + 1) }
// row represents the length of secondString, col represents the length of firstString
for (i in 1..secondString.length) {
// base case
dpTable[i % 2][0] = 0
for (j in 1..firstString.length) {
if (firstString[j - 1] == secondString[i - 1]) {
dpTable[i % 2][j] = dpTable[(i - 1) % 2][j - 1] + 1
} else {
dpTable[i % 2][j] = max(
dpTable[(i - 1) % 2][j - 1],
max(dpTable[(i - 1) % 2][j], dpTable[i % 2][j - 1]),
)
}
}
}
return dpTable[secondString.length % 2][firstString.length]
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,048 | kotlab | Apache License 2.0 |
src/Day09.kt | uekemp | 575,483,293 | false | {"Kotlin": 69253} | import kotlin.math.absoluteValue
import kotlin.math.sign
data class Motion(var dx: Int, var dy: Int) {
fun isDone(): Boolean {
return dx == 0 && dy == 0
}
fun move(knot: Knot) {
if (isDone()) {
error("Motion is exhausted")
}
val sx = dx.sign
val sy = dy.sign
knot.move(sx, sy)
dx -= sx
dy -= sy
}
companion object {
fun from(line: String): Motion {
val (dir, steps) = line.split(" ")
return when (dir) {
"R" -> { Motion(steps.toInt(), 0) }
"L" -> { Motion(-steps.toInt(), 0) }
"U" -> { Motion(0, steps.toInt()) }
"D" -> { Motion(0, -steps.toInt()) }
else -> error("Invalid input: $line")
}
}
}
}
data class Knot(val name: String, var x: Int = 0, var y: Int = 0) {
fun move(dx: Int, dy: Int) {
x += dx
y += dy
}
fun position(x: Int, y: Int) {
this.x = x
this.y = y
}
fun drag(other: Knot): Boolean {
if (!isTouching(other)) {
val (dx, dy) = distanceTo(other)
if ((dx.absoluteValue > 1) && (dy.absoluteValue > 1)) {
other.position(x + dx.sign, y + dy.sign)
} else if (dx.absoluteValue > 1) {
other.position(x + dx.sign, y)
} else if (dy.absoluteValue > 1) {
other.position(x, y + dy.sign)
}
return true
}
return false
}
fun isTouching(other: Knot): Boolean {
return other.x in x-1..x+1 && other.y in y-1..y+1
}
fun rememberMe(visitedPoints: MutableSet<String>) {
visitedPoints.add("$x,$y")
}
fun distanceTo(other: Knot): Pair<Int, Int> {
return (other.x - this.x) to (other.y - this.y)
}
}
fun parseMotions(input: List<String>): List<Motion> {
val result = mutableListOf<Motion>()
input.forEach {
result.add(Motion.from(it))
}
return result
}
fun main() {
fun part1(input: List<String>): Int {
val motions = parseMotions(input)
val visited = HashSet<String>()
val head = Knot("head")
val tail = Knot("tail")
tail.rememberMe(visited)
motions.forEach { motion ->
while (!motion.isDone()) {
motion.move(head)
if (head.drag(tail)) {
tail.rememberMe(visited)
}
}
}
return visited.size
}
fun part2(input: List<String>): Int {
val motions = parseMotions(input)
val visited = HashSet<String>()
val knots = listOf(Knot("head"), Knot("1"), Knot("2"), Knot("3"), Knot("4"), Knot("5"), Knot("6"), Knot("7"), Knot("8"), Knot("9"))
knots.last().rememberMe(visited)
motions.forEach { motion ->
while (!motion.isDone()) {
motion.move(knots.first())
for (i in 1 until knots.size) {
knots[i - 1].drag(knots[i])
}
knots.last().rememberMe(visited)
}
}
return visited.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day09_test")
// check(part1(testInput) == 13)
check(part2(testInput) == 36)
val input = readInput("Day09")
check(part1(input) == 6311)
check(part2(input) == 2482)
}
| 0 | Kotlin | 0 | 0 | bc32522d49516f561fb8484c8958107c50819f49 | 3,496 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/Day05.kt | diesieben07 | 572,879,498 | false | {"Kotlin": 44432} | private val file = "Day05"
private class CrateStack {
private val stack: ArrayDeque<Char> = ArrayDeque()
fun takeTop(): Char {
return stack.removeFirst()
}
fun takeTop(n: Int): List<Char> {
val subList = stack.subList(0, n)
val result = subList.toList()
subList.clear()
return result
}
fun getTop(): Char {
return stack.first()
}
fun addOnTop(crate: Char) {
stack.addFirst(crate)
}
fun addOnTop(crates: List<Char>) {
stack.addAll(0, crates)
}
fun addOnBottom(crate: Char) {
stack.addLast(crate)
}
override fun toString(): String {
return stack.toString()
}
}
private data class MoveInstruction(val from: Int, val to: Int, val amount: Int) {
fun execute(stacks: List<CrateStack>) {
val source = stacks[from - 1]
val target = stacks[to - 1]
repeat(amount) {
target.addOnTop(source.takeTop())
}
}
fun executeWithBulk(stacks: List<CrateStack>) {
val source = stacks[from - 1]
val target = stacks[to - 1]
target.addOnTop(source.takeTop(amount))
}
companion object {
private val regex = Regex("""move (\d+) from (\d+) to (\d+)""")
fun parse(line: String): MoveInstruction {
val match = checkNotNull(regex.matchEntire(line))
val groupValues = match.groupValues
return MoveInstruction(groupValues[2].toInt(), groupValues[3].toInt(), groupValues[1].toInt())
}
}
}
private fun Sequence<String>.parseInput(): Pair<List<CrateStack>, Sequence<MoveInstruction>> {
val crateRegex = Regex("""(?:\[(.)\])|( {3})(?: |${'$'})""")
val stacks = mutableListOf<CrateStack>()
val iterator = iterator()
for (line in iterator) {
if ('[' !in line) break
for ((index, crateMatch) in crateRegex.findAll(line).withIndex()) {
for (i in stacks.size..index) {
stacks.add(CrateStack())
}
val crateValue = crateMatch.groupValues[1]
if (crateValue.isNotEmpty()) {
stacks[index].addOnBottom(crateValue[0])
}
}
}
iterator.next()
val moves = sequence {
for (line in iterator) {
yield(MoveInstruction.parse(line))
}
}
return Pair(stacks, moves)
}
private fun solve(mover: MoveInstruction.(List<CrateStack>) -> Unit) {
streamInput(file) { input ->
val (stacks, moves) = input.parseInput()
for (move in moves) {
move.mover(stacks)
}
println(stacks.joinToString(separator = "") { it.getTop().toString() })
}
}
private fun part1() {
solve(MoveInstruction::execute)
}
private fun part2() {
solve(MoveInstruction::executeWithBulk)
}
fun main() {
part1()
part2()
}
| 0 | Kotlin | 0 | 0 | 0b9993ef2f96166b3d3e8a6653b1cbf9ef8e82e6 | 2,883 | aoc-2022 | Apache License 2.0 |
src/aoc2022/Day06.kt | Playacem | 573,606,418 | false | {"Kotlin": 44779} | package aoc2022
import utils.readInput
object Day06 {
override fun toString(): String {
return this.javaClass.simpleName
}
}
fun main() {
fun findIndexWithPrecedingNUniqueValues(input: String, n: Int): Int {
val res = input.windowed(size = n + 1, step = 1).find {
it.toCharArray().dropLast(1).toSet().size == n
} ?: error("not found")
val index = input.indexOf(res)
println("DEBUG: $res - $index + $n = ${index + n} ")
return index + n
}
fun part1(list: List<String>): Int {
val input = list.first()
return findIndexWithPrecedingNUniqueValues(input, 4)
}
fun part2(list: List<String>): Int {
val input = list.first()
return findIndexWithPrecedingNUniqueValues(input, 14)
}
val testInput01 = readInput(2022, "${Day06}_test01")
val testInput02 = readInput(2022, "${Day06}_test02")
val testInput03 = readInput(2022, "${Day06}_test03")
val testInput04 = readInput(2022, "${Day06}_test04")
val testInput05 = readInput(2022, "${Day06}_test05")
val input = readInput(2022, Day06.toString())
// test if implementation meets criteria from the description, like:
check(part1(testInput01) == 7) { "check 1 part 1" }
check(part1(testInput02) == 5) { "check 2 part 1" }
check(part1(testInput03) == 6) { "check 3 part 1" }
check(part1(testInput04) == 10) { "check 4 part 1" }
check(part1(testInput05) == 11) { "check 5 part 1" }
println(part1(input))
check(part2(testInput01) == 19) { "check 1 part 2" }
check(part2(testInput02) == 23) { "check 2 part 2" }
check(part2(testInput03) == 23) { "check 3 part 2" }
check(part2(testInput04) == 29) { "check 4 part 2" }
check(part2(testInput05) == 26) { "check 5 part 2" }
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 4ec3831b3d4f576e905076ff80aca035307ed522 | 1,835 | advent-of-code-2022 | Apache License 2.0 |
src/Day10.kt | StephenVinouze | 572,377,941 | false | {"Kotlin": 55719} | import java.lang.IllegalArgumentException
data class Instruction(
val cyclesCount: Int,
val value: Int,
)
fun main() {
fun List<String>.toInstructions(): List<Instruction> =
map {
when {
it.startsWith("noop") -> Instruction(1, 0)
it.startsWith("addx") -> Instruction(2, it.split(" ").last().toInt())
else -> throw IllegalArgumentException("Unknown instruction name : $it")
}
}
fun computeCycles(input: List<String>): List<Int> {
var currentCycleRegister = 1
val cycles = mutableListOf(currentCycleRegister)
input.toInstructions().forEach {
when (it.cyclesCount) {
1 -> cycles.add(currentCycleRegister)
2 -> {
val cycleRegister = currentCycleRegister + it.value
cycles.add(currentCycleRegister)
cycles.add(cycleRegister)
currentCycleRegister = cycleRegister
}
}
}
return cycles
}
fun part1(input: List<String>): Int =
computeCycles(input)
.mapIndexedNotNull { index, i ->
if ((index + 1) in listOf(20, 60, 100, 140, 180, 220))
i * (index + 1)
else
null
}
.sum()
fun part2(input: List<String>): String {
var crt = ""
var spritePosition = 0
computeCycles(input)
.drop(1)
.forEachIndexed { index, cycle ->
crt += if (index % 40 in (spritePosition..spritePosition + 2)) "#" else "."
if ((index + 1) in listOf(40, 80, 120, 160, 200, 240)) crt += "\n"
spritePosition = cycle - 1
}
return crt
}
check(part1(readInput("Day10_test")) == 13140)
println(part2(readInput("Day10_test")))
val input = readInput("Day10")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 11b9c8816ded366aed1a5282a0eb30af20fff0c5 | 2,022 | AdventOfCode2022 | Apache License 2.0 |
src/main/kotlin/day3/Day3.kt | stoerti | 726,442,865 | false | {"Kotlin": 19680} | package io.github.stoerti.aoc.day3
import io.github.stoerti.aoc.IOUtils
fun main(args: Array<String>) {
val schematics = Schematics(IOUtils.readInput("day_3_input"))
val result1 = schematics.lines.mapIndexed { index, _ -> schematics.scanForPartNumbers(index) }
.onEach { println(it) }
.map { it.sumOf { it } }
.sumOf { it }
println("Result 1: $result1")
}
data class Schematics(
val lines: List<String>,
) {
val symbols = listOf('!', '$', '%')
fun scanForPartNumbers(lineNumber: Int) : List<Int> {
val line = lines[lineNumber].asSequence().toMutableList()
var isScanningNumber = false
var curDigitString = ""
val partNumbers = ArrayList<String>()
for (curIdx in 0..<line.size) {
val curChar = line[curIdx]
if (curChar.isDigit()) {
isScanningNumber = true
curDigitString += curChar
} else {
if (isScanningNumber) { // digits ended, check if part number
print("$curDigitString ")
if (hasSymbolAdjacent(lineNumber,curIdx - curDigitString.length, curIdx - 1)) {
partNumbers.add(curDigitString)
}
isScanningNumber = false
curDigitString = ""
}
}
}
if (isScanningNumber) { // digits ended, check if part number
print("$curDigitString ")
if (hasSymbolAdjacent(lineNumber, line.size - curDigitString.length, line.size - 1)) {
partNumbers.add(curDigitString)
}
}
return partNumbers.map { it.toInt() }
}
fun hasSymbolAdjacent(line: Int, beginIndex: Int, endIndex: Int) : Boolean {
for (x in beginIndex..endIndex)
if (hasSymbolAdjacent(line, x))
return true
return false
}
private fun hasSymbolAdjacent(line: Int, index: Int) : Boolean {
for (x in -1..1 )
for (y in -1..1 ) {
if (isSymbol(line +y, index+x))
return true
}
return false
}
private fun isSymbol(lineNumber: Int, index: Int): Boolean {
if (lineNumber < 0 || index < 0 || lines.size <= lineNumber || lines[lineNumber].length <= index)
return false
val char = lines[lineNumber][index]
return !(char.isDigit() || char == '.')
}
private fun findDigit(lineNumber: Int, index: Int): Char? {
if (lineNumber < 0 || index < 0 || lines.size <= lineNumber || lines[lineNumber].length <= index)
return null
val char = lines[lineNumber][index]
return if (char.isDigit()) char else null
}
}
class Day3 | 0 | Kotlin | 0 | 0 | 05668206293c4c51138bfa61ac64073de174e1b0 | 2,480 | advent-of-code | Apache License 2.0 |
src/Day10.kt | hrach | 572,585,537 | false | {"Kotlin": 32838} | sealed interface Command {
data class Addx(val n: Int) : Command
object Noop : Command
}
fun main() {
fun parse(input: List<String>): List<Command> =
input
.filter { it.isNotBlank() }
.map {
when (it.substring(0, 4)) {
"addx" -> Command.Addx(it.substring(4).trim().toInt())
"noop" -> Command.Noop
else -> error(it)
}
}
fun part1(input: List<String>): Int {
val commands = parse(input).toMutableList()
var x = 1
var cycle = 1
var command: Command? = null
var commandCounter = 0
var sum = 0
while (commands.isNotEmpty()) {
if (command == null) {
command = commands.removeFirst()
commandCounter = if (command is Command.Addx) 2 else 1
}
commandCounter -= 1
cycle += 1
if (commandCounter == 0) {
when (command) {
is Command.Addx -> x += command.n
is Command.Noop -> {}
}
command = null
}
if (cycle.rem(40) == 20) {
sum += (cycle * x)
}
}
return sum
}
fun part2(input: List<String>): String {
val lines = mutableListOf<String>()
var line = ""
val commands = parse(input).toMutableList()
var x = 1
var sprite = x..x+2
var cycle = 1
var command: Command? = null
var commandCounter = 0
while (commands.isNotEmpty()) {
val pos = cycle.rem(40)
line += if (pos in sprite) "#" else "."
if (cycle.rem(40) == 0) {
lines.add(line)
line = ""
}
if (command == null) {
command = commands.removeFirst()
commandCounter = if (command is Command.Addx) 2 else 1
}
commandCounter -= 1
cycle += 1
if (commandCounter == 0) {
when (command) {
is Command.Addx -> {
x += (command as Command.Addx).n
sprite = x..x+2
}
is Command.Noop -> {}
null -> error("e")
}
command = null
}
}
return lines.joinToString("\n")
}
val testInput = readInput("Day10_test")
check(part1(testInput), 13140)
println(part2(testInput))
val input = readInput("Day10")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 40b341a527060c23ff44ebfe9a7e5443f76eadf3 | 2,710 | aoc-2022 | Apache License 2.0 |
src/lib/Grid.kt | mihassan | 575,356,150 | false | {"Kotlin": 123343} | package lib
import kotlin.math.abs
enum class Direction {
RIGHT, DOWN, LEFT, UP;
fun turnRight(): Direction = rotate(1)
fun turnLeft(): Direction = rotate(3)
fun turnAround(): Direction = rotate(2)
private fun rotate(turn: Int): Direction = Direction.values()[(ordinal + turn) % 4]
}
enum class Adjacency {
HORIZONTAL, VERTICAL, ORTHOGONAL, DIAGONAL, ALL
}
data class Point(val x: Int, val y: Int) : Comparable<Point> {
operator fun plus(other: Point): Point = Point(x + other.x, y + other.y)
operator fun minus(other: Point): Point = this + (-other)
operator fun unaryMinus(): Point = Point(-x, -y)
operator fun times(scale: Int): Point = Point(x * scale, y * scale)
operator fun div(scale: Int): Point = Point(x / scale, y / scale)
fun manhattanDistance(other: Point): Int = abs(x - other.x) + abs(y - other.y)
fun adjacents(adjacency: Adjacency = Adjacency.ORTHOGONAL): List<Point> = when (adjacency) {
Adjacency.HORIZONTAL -> listOf(left(), right())
Adjacency.VERTICAL -> listOf(up(), down())
Adjacency.ORTHOGONAL -> adjacents(Adjacency.HORIZONTAL) + adjacents(Adjacency.VERTICAL)
Adjacency.DIAGONAL -> listOf(upLeft(), upRight(), downLeft(), downRight())
Adjacency.ALL -> adjacents(Adjacency.ORTHOGONAL) + adjacents(Adjacency.DIAGONAL)
}
fun move(direction: Direction): Point = when (direction) {
Direction.RIGHT -> right()
Direction.DOWN -> down()
Direction.LEFT -> left()
Direction.UP -> up()
}
fun left(): Point = this - X_DIRECTION
fun right(): Point = this + X_DIRECTION
fun up(): Point = this - Y_DIRECTION
fun down(): Point = this + Y_DIRECTION
fun upLeft(): Point = up().left()
fun upRight(): Point = up().right()
fun downLeft(): Point = down().left()
fun downRight(): Point = down().right()
companion object {
private val X_DIRECTION = Point(1, 0)
private val Y_DIRECTION = Point(0, 1)
fun parse(pointStr: String): Point {
val (x, y) = pointStr.split(",").map { it.toInt() }
return Point(x, y)
}
}
override fun compareTo(other: Point): Int = compareValuesBy(this, other, { it.x }, { it.y })
}
data class Line(val start: Point, val end: Point) {
init {
require(start.x == end.x || start.y == end.y) { "Line must be horizontal or vertical" }
}
private val xRange: IntRange = if (start.x < end.x) start.x..end.x else end.x..start.x
private val yRange: IntRange = if (start.y < end.y) start.y..end.y else end.y..start.y
fun expand(): List<Point> = xRange.flatMap { x -> yRange.map { y -> Point(x, y) } }
companion object {
fun parse(lineStr: String): Line {
val (start, end) = lineStr.split(" -> ").map(Point.Companion::parse)
return Line(start, end)
}
}
}
data class Path(val points: List<Point>) {
fun expand(): List<Point> = points.zipWithNext(::Line).flatMap(Line::expand)
companion object {
fun parse(pathStr: String): Path {
val points = pathStr.split(" -> ").map(Point.Companion::parse)
return Path(points)
}
}
}
data class Grid<T>(val grid: List<List<T>>) {
private val height: Int = grid.size
private val width: Int = grid.map(List<T>::size).toSet().single()
fun transposed(): Grid<T> = Grid(
List(width) { x ->
List(height) { y ->
grid[y][x]
}
}
)
fun flipVertically(): Grid<T> = Grid(grid.reversed())
fun flipHorizontally(): Grid<T> = Grid(grid.map(List<T>::reversed))
fun rotateCW(): Grid<T> = flipVertically().transposed()
fun rotateCCW(): Grid<T> = flipHorizontally().transposed()
fun rotate180(): Grid<T> = flipVertically().flipHorizontally()
fun <R> mapIndexed(transform: (Point, T) -> R): Grid<R> = Grid(
List(height) { y ->
List(width) { x ->
transform(Point(x, y), grid[y][x])
}
}
)
fun <R> map(transform: (T) -> R): Grid<R> =
mapIndexed { _, value -> transform(value) }
fun forEachIndexed(transform: (Point, T) -> Unit) {
mapIndexed(transform)
}
fun forEach(transform: (T) -> Unit) {
map(transform)
}
fun findAll(predicate: (T) -> Boolean): List<T> =
grid.flatMap { row ->
row.mapNotNull { col ->
if (predicate(col)) col else null
}
}
fun findAll(element: T): List<T> = findAll { it == element }
fun find(predicate: (T) -> Boolean): T = findAll(predicate).first()
fun find(element: T): T = find { it == element }
fun indicesOf(predicate: (T) -> Boolean): List<Point> =
grid.flatMapIndexed { y, row ->
row.mapIndexedNotNull { x, col ->
if (predicate(col)) Point(x, y) else null
}
}
fun indicesOf(element: T): List<Point> = indicesOf { it == element }
fun indexOf(predicate: (T) -> Boolean): Point = indicesOf(predicate).first()
fun indexOf(element: T): Point = indexOf { it == element }
fun zip(other: Grid<T>, transform: (T, T) -> T): Grid<T> = Grid(
grid.zip(other.grid) { x, y -> x.zip(y, transform) }
)
fun count(predicate: (T) -> Boolean): Int = grid.sumOf { it.count(predicate) }
operator fun get(point: Point): T = grid[point.y][point.x]
operator fun contains(point: Point): Boolean =
(point.x in (0 until width)) && (point.y in (0 until height))
fun adjacents(point: Point, adjacency: Adjacency = Adjacency.ORTHOGONAL): List<Point> =
point.adjacents(adjacency).filter { it in this }
companion object {
fun <T : Comparable<T>> Grid<T>.max(): T = grid.maxOf { it.max() }
fun <T : Comparable<T>> Grid<T>.min(): T = grid.minOf { it.min() }
fun parse(gridStr: String): Grid<Char> = Grid(gridStr.lines().map { it.toCharArray().toList() })
}
} | 0 | Kotlin | 0 | 0 | 698316da8c38311366ee6990dd5b3e68b486b62d | 5,627 | aoc-kotlin | Apache License 2.0 |
src/main/kotlin/days/aoc2022/Day7.kt | bjdupuis | 435,570,912 | false | {"Kotlin": 537037} | package days.aoc2022
import days.Day
class Day7 : Day(2022, 7) {
override fun partOne(): Any {
return calculateSumOfDirectoriesUnder100000(inputList)
}
override fun partTwo(): Any {
return calculateSmallestDirectoryThatCanBeDeleted(inputList)
}
fun calculateSmallestDirectoryThatCanBeDeleted(input: List<String>): Int {
val root = buildHierarchy(input)
val neededSpace = 30000000 - (70000000 - root.size())
return childrenSequence(root).map { it.size() }.filter { it > neededSpace }.min()
}
fun calculateSumOfDirectoriesUnder100000(input: List<String>): Int {
val root = buildHierarchy(input)
return childrenSequence(root).filter { it.size() <= 100000 }.sumOf { it.size() }
}
private fun buildHierarchy(input: List<String>): Directory {
val root = Directory("/", null)
var current = root
input.forEach { line ->
when {
line.startsWith("${'$'} cd") -> {
val directoryToMoveTo = line.split(' ').last()!!
current = when (directoryToMoveTo) {
".." -> {
current.parent!!
}
"/" -> {
root
}
else -> {
current.children.first { it.name == directoryToMoveTo }
}
}
}
line.startsWith("${'$'} ls") -> {
// noop
}
line.startsWith("dir ") -> {
current.children.add(Directory(line.split(" ").last(), current))
}
else -> {
val parts = line.split(" ")
current.files.add(File(parts.last(), parts.first().toInt()))
}
}
}
return root
}
class Directory(val name: String, val parent: Directory?) {
val children = mutableListOf<Directory>()
val files = mutableListOf<File>()
fun size(): Int {
return files.sumOf { it.size } + children.sumOf { it.size() }
}
}
private fun childrenSequence(start: Directory): Sequence<Directory> = sequence {
start.children.forEach { child ->
yield(child)
yieldAll(childrenSequence(child))
}
}
data class File(val name: String, val size: Int)
} | 0 | Kotlin | 0 | 1 | c692fb71811055c79d53f9b510fe58a6153a1397 | 2,524 | Advent-Of-Code | Creative Commons Zero v1.0 Universal |
src/main/kotlin/com/hj/leetcode/kotlin/problem912/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem912
/**
* LeetCode page: [912. Sort an Array](https://leetcode.com/problems/sort-an-array/);
*
* TODO : Add Heap Sort solution;
*/
class Solution {
/* Complexity:
* Time O(NLogN) and Space O(N) where N is the size of nums;
*/
fun sortArray(nums: IntArray): IntArray {
MergeSort(nums).run()
return nums
}
private class MergeSort(private val original: IntArray) {
private val elementHolder = IntArray(original.size)
fun run() {
splitAndMerge(original.indices, ::mergeToOriginal)
}
private fun splitAndMerge(indexRange: IntRange, merge: (indexRange: IntRange) -> Unit) {
val shouldSplit = indexRange.let { it.first != it.last }
if (shouldSplit) {
val midIndex = computeMidIndex(indexRange)
splitAndMerge(indexRange.first..midIndex, merge)
splitAndMerge(midIndex + 1..indexRange.last, merge)
}
merge(indexRange)
}
private fun computeMidIndex(indexRange: IntRange): Int {
return indexRange.let { (it.first + it.last) ushr 1 }
}
private fun mergeToOriginal(indexRange: IntRange) {
copyCurrentElementsToHolder(indexRange)
val midIndex = computeMidIndex(indexRange)
var sorted1Index = indexRange.first
var sorted2Index = midIndex + 1
var assignToIndex = indexRange.first
while (assignToIndex <= indexRange.last) {
val shouldAdoptSorted1Index = when {
sorted1Index > midIndex -> false
sorted2Index > indexRange.last -> true
else -> elementHolder[sorted1Index] <= elementHolder[sorted2Index]
}
if (shouldAdoptSorted1Index) {
original[assignToIndex] = elementHolder[sorted1Index]
sorted1Index++
} else {
original[assignToIndex] = elementHolder[sorted2Index]
sorted2Index++
}
assignToIndex++
}
}
private fun copyCurrentElementsToHolder(indexRange: IntRange) {
for (index in indexRange) {
elementHolder[index] = original[index]
}
}
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 2,389 | hj-leetcode-kotlin | Apache License 2.0 |
src/Day05.kt | jinie | 572,223,871 | false | {"Kotlin": 76283} | import java.util.Stack
class Day05(input: String) {
private val stacks = prepareStacks(input.substringBefore("\n\n").lines())
private val pattern = """move (\d+) from (\d+) to (\d+)""".toRegex()
private val commands = input.substringAfter("\n\n").lines()
.map { pattern.matchEntire(it)!!.destructured.toList() }
.map { it.map(String::toInt) }
fun part1(): String {
commands.forEach { (times, from, to) ->
repeat(times) {
stacks[to - 1].push(stacks[from - 1].pop())
}
}
return stacks.map { it.peek() }.joinToString("")
}
fun part2(): String {
commands.forEach { (times, from, to) ->
stacks[to - 1].addAll(
buildList {
repeat(times) {
add(stacks[from - 1].pop())
}
}.reversed()
)
}
return stacks.map { it.peek() }.joinToString("")
}
private fun prepareStacks(definition: List<String>): List<Stack<Char>> {
val numbers = definition.last()
val contents = definition.dropLast(1).reversed()
return numbers.mapIndexedNotNull { index, char ->
if (!char.isDigit()) {
null
} else {
Stack<Char>().apply { addAll(contents.map { it[index] }.filter { it.isLetter() }) }
}
}
}
}
fun main(){
val testInput = readInput("Day05_test").joinToString("")
check(Day05(testInput).part1().compareTo("CMZ")==0)
measureTimeMillisPrint {
val input = readInput("Day05").joinToString("")
println(Day05(input).part1())
println(Day05(input).part2())
}
} | 0 | Kotlin | 0 | 0 | 4b994515004705505ac63152835249b4bc7b601a | 1,727 | aoc-22-kotlin | Apache License 2.0 |
src/com/ncorti/aoc2023/Day03.kt | cortinico | 723,409,155 | false | {"Kotlin": 76642} | package com.ncorti.aoc2023
import kotlin.math.pow
fun main() {
fun part1(): Long {
val matrix = getInputAsText("03") {
split("\n").filter(String::isNotBlank).map { it.toCharArray() }
}.toTypedArray()
var result = 0L
var foundNumberList = mutableListOf<Pair<Int, Int>>()
for (i in matrix.indices) {
for (j in matrix[i].indices) {
if (matrix[i][j].isDigit() && foundNumberList.isEmpty()) {
foundNumberList = scanNumber(matrix, i, j)
if (foundNumberList.isNeighbourOfSymbol(matrix)) {
result += foundNumberList.toNumber(matrix)
}
foundNumberList.remove(i to j)
} else if (i to j in foundNumberList) {
foundNumberList.remove(i to j)
}
}
}
return result
}
fun part2(): Long {
val matrix =
getInputAsText("03") {
split("\n").filter(String::isNotBlank).map { it.toCharArray() }
}.toTypedArray()
var result = 0L
for (i in matrix.indices) {
for (j in matrix[i].indices) {
if (matrix[i][j] != '*') continue
val adjacentNumbersList = mutableListOf<MutableList<Pair<Int, Int>>>()
if (matrix[i][j - 1].isDigit()) {
adjacentNumbersList.add(scanNumber(matrix, i, j - 1))
}
if (matrix[i][j + 1].isDigit()) {
adjacentNumbersList.add(scanNumber(matrix, i, j + 1))
}
adjacentNumbersList.addAll(findAdjacentNumbersInRow(matrix, i - 1, j))
adjacentNumbersList.addAll(findAdjacentNumbersInRow(matrix, i + 1, j))
if (adjacentNumbersList.size == 2) {
result += adjacentNumbersList[0].toNumber(matrix) * adjacentNumbersList[1].toNumber(matrix)
}
}
}
return result.toLong()
}
println(part1())
println(part2())
}
private val neighbours = listOf(
-1 to -1,
-1 to 0,
-1 to 1,
0 to -1,
0 to 1,
1 to -1,
1 to 0,
1 to 1,
)
private fun scanNumber(matrix: Array<CharArray>, i: Int, inputj: Int): MutableList<Pair<Int, Int>> {
var j = inputj
while (j - 1 >= 0 && matrix[i][j - 1].isDigit()) {
j--
}
val result = mutableListOf(i to j)
while (j + 1 < matrix[i].size && matrix[i][j + 1].isDigit()) {
j++
result.add(i to j)
}
return result
}
private fun findAdjacentNumbersInRow(
matrix: Array<CharArray>,
i: Int,
j: Int
): MutableList<MutableList<Pair<Int, Int>>> {
val row = matrix[i]
return when {
row[j - 1].isDigit() && !row[j].isDigit() && row[j + 1].isDigit() -> mutableListOf(
scanNumber(matrix, i, j - 1),
scanNumber(matrix, i, j + 1)
)
row[j - 1].isDigit() -> mutableListOf(scanNumber(matrix, i, j - 1))
row[j].isDigit() -> mutableListOf(scanNumber(matrix, i, j))
row[j + 1].isDigit() -> mutableListOf(scanNumber(matrix, i, j + 1))
else -> mutableListOf()
}
}
private fun List<Pair<Int, Int>>.isNeighbourOfSymbol(matrix: Array<CharArray>): Boolean {
return this.any { (i, j) ->
neighbours.any { (di, dj) ->
i + di >= 0 &&
i + di < matrix.size &&
j + dj >= 0 &&
j + dj < matrix[i].size &&
!matrix[i + di][j + dj].isDigit() &&
matrix[i + di][j + dj] != '.'
}
}
}
private fun List<Pair<Int, Int>>.toNumber(matrix: Array<CharArray>): Long {
var powindex = 0.0
var number = 0L
for (i in this.size - 1 downTo 0) {
val (itemi, itemj) = this[i]
number += matrix[itemi][itemj].digitToInt() * (10.0.pow(powindex)).toLong()
powindex++
}
return number
}
| 1 | Kotlin | 0 | 1 | 84e06f0cb0350a1eed17317a762359e9c9543ae5 | 3,977 | adventofcode-2023 | MIT License |
packages/solutions/src/Day03.kt | ffluk3 | 576,832,574 | false | {"Kotlin": 21246, "Shell": 85} | fun main() {
fun getScore(char: Char): Int {
if (char.isUpperCase()) {
return char.code + 26 - 64
} else {
return char.code - 96
}
}
fun getCommonLetters(str1: String, str: String): List<Char> {
val res = mutableSetOf<Char>()
str1.toList().forEach {
if (str.contains(it, false)) {
res.add(it)
}
}
return res.toList()
}
fun getCommonLetters(chars: List<Char>, str: String): List<Char> {
val res = mutableSetOf<Char>()
chars.forEach {
if (str.contains(it, false)) {
res.add(it)
}
}
return res.toList()
}
fun part1(input: List<String>): Int {
var score = 0
input.forEach {
val front = it.substring(0, it.length / 2)
val back = it.substring(it.length / 2, it.length)
println("$it $front $back")
var scoreAdded = false
front.forEach { it2 ->
if (back.contains(it2, false) && !scoreAdded) {
scoreAdded = true
val scoreToAdd = getScore(it2)
println("$it2 $scoreToAdd")
score += scoreToAdd
}
}
}
return score
}
fun part2(input: List<String>): Int {
var score = 0
for (i in 0 until input.size step 3) {
var commonLetters = getCommonLetters(input[i], input[i + 1])
commonLetters = getCommonLetters(commonLetters, input[i + 2])
score += getScore(commonLetters[0])
}
return score
}
runAdventOfCodeSuite("Day03", ::part1, 157, ::part2, 70)
}
| 0 | Kotlin | 0 | 0 | f9b68a8953a7452d804990e01175665dffc5ab6e | 1,768 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/day05/Solution.kt | TestaDiRapa | 573,066,811 | false | {"Kotlin": 50405} | package day05
import java.io.File
import java.util.*
data class Move(
val qty: Int,
val source: String,
val dest: String
)
fun parseStack(rawInput: List<String>): Map<String, Stack<Char>> =
(1 .. 9).fold(emptyMap()) { acc, it ->
acc + (it.toString() to rawInput
.last()
.indexOf(it.toString())
.let { index ->
rawInput
.reversed()
.subList(1, rawInput.size)
.fold(Stack<Char>()) { stack, line ->
if (line.length > index && line[index] != ' ')
stack.push(line[index])
stack
}
})
}
fun parseCommands(rawCommands: List<String>) =
rawCommands.mapNotNull { line ->
Regex("move ([0-9]+) from ([0-9]+) to ([0-9]+)")
.find(line)
?.groups
?.toList()
?.let {
Move(
it[1]!!.value.toInt(),
it[2]!!.value,
it[3]!!.value
)
}
}
fun parseInputFile() =
File("src/main/kotlin/day05/input.txt")
.readLines()
.fold(Pair<List<String>, List<String>>(emptyList(), emptyList())) { acc, line ->
if (line.startsWith("move")) Pair(acc.first, acc.second + line)
else if (line.isEmpty()) acc
else Pair(acc.first + line, acc.second)
}.let {
Pair(
parseStack(it.first),
parseCommands(it.second)
)
}
fun findFinalConfigurationMovingOneCrateAtTime() =
parseInputFile()
.let { input ->
input.second.forEach {move ->
repeat((1 .. move.qty).count()) {
if (input.first[move.source]!!.isNotEmpty())
input.first[move.dest]!!.push(input.first[move.source]!!.pop())
}
}
(1..9).fold("") { acc, it ->
acc + input.first[it.toString()]!!.peek()
}
}
fun findFinalConfigurationMovingMultipleCratesAtTime() =
parseInputFile()
.let { input ->
input.second.forEach { move ->
(1 .. move.qty).fold(emptyList<Char>()) { acc, _ ->
if (input.first[move.source]!!.isNotEmpty())
acc + input.first[move.source]!!.pop()
else acc
}.reversed().forEach { input.first[move.dest]!!.push(it) }
}
(1..9).fold("") { acc, it ->
acc + input.first[it.toString()]!!.peek()
}
}
fun main() {
println("The top crates at the end using the CrateMover 9000 are: ${findFinalConfigurationMovingOneCrateAtTime()}")
println("The top crates at the end using the CrateMover 9001 are: ${findFinalConfigurationMovingMultipleCratesAtTime()}")
} | 0 | Kotlin | 0 | 0 | b5b7ebff71cf55fcc26192628738862b6918c879 | 2,959 | advent-of-code-2022 | MIT License |
advent-of-code/src/main/kotlin/DayThree.kt | pauliancu97 | 518,083,754 | false | {"Kotlin": 36950} | class DayThree {
enum class Direction(val id: Char) {
North('^'),
South('v'),
East('>'),
West('<');
companion object {
fun getDirection(char: Char) =
Direction.values().firstOrNull { it.id == char }
}
}
fun String.toDirections() =
this.mapNotNull { Direction.getDirection(it) }
fun getNumVisitedPositions(directions: List<Direction>): Int {
val positions: MutableSet<Pair<Int, Int>> = mutableSetOf()
var currentPositions = 0 to 0
positions.add(currentPositions)
for (direction in directions) {
currentPositions = when (direction) {
Direction.North -> currentPositions.first to (currentPositions.second + 1)
Direction.East -> (currentPositions.first + 1) to currentPositions.second
Direction.South -> currentPositions.first to (currentPositions.second - 1)
Direction.West -> (currentPositions.first - 1) to currentPositions.second
}
positions.add(currentPositions)
}
return positions.size
}
fun getNumVisitedPositionsAndRobotSanta(directions: List<Direction>): Int {
val positions: MutableSet<Pair<Int, Int>> = mutableSetOf()
var currentPositions = 0 to 0
positions.add(currentPositions)
val santaDirections = directions.filterIndexed { index, _ -> index % 2 == 0 }
for (direction in santaDirections) {
currentPositions = when (direction) {
Direction.North -> currentPositions.first to (currentPositions.second + 1)
Direction.East -> (currentPositions.first + 1) to currentPositions.second
Direction.South -> currentPositions.first to (currentPositions.second - 1)
Direction.West -> (currentPositions.first - 1) to currentPositions.second
}
positions.add(currentPositions)
}
currentPositions = 0 to 0
val robotSantaDirections = directions.filterIndexed { index, _ -> index % 2 == 1 }
for (direction in robotSantaDirections) {
currentPositions = when (direction) {
Direction.North -> currentPositions.first to (currentPositions.second + 1)
Direction.East -> (currentPositions.first + 1) to currentPositions.second
Direction.South -> currentPositions.first to (currentPositions.second - 1)
Direction.West -> (currentPositions.first - 1) to currentPositions.second
}
positions.add(currentPositions)
}
return positions.size
}
fun solvePartOne() {
val line = readLines("day_three.txt").first()
val directions = line.toDirections()
println(getNumVisitedPositions(directions))
}
fun solvePartTwo() {
val line = readLines("day_three.txt").first()
val directions = line.toDirections()
println(getNumVisitedPositionsAndRobotSanta(directions))
}
}
fun main() {
DayThree().solvePartTwo()
} | 0 | Kotlin | 0 | 0 | 3ba05bc0d3e27d9cbfd99ca37ca0db0775bb72d6 | 3,099 | advent-of-code-2015 | MIT License |
2017/13-packet_scanners/src/main/kotlin/de/qwhon/aoc/PacketScanner.kt | frankschmitt | 227,218,372 | false | {"Elm": 170193, "Python": 143983, "Rust": 116065, "Haskell": 33760, "Clojure": 16809, "Java": 16591, "Crystal": 15064, "R": 12840, "JavaScript": 9484, "Elixir": 5192, "Lua": 5085, "C++": 4720, "Go": 4052, "Raku": 3667, "Kotlin": 3478, "Ruby": 2983, "OCaml": 2957, "F#": 2554, "Shell": 1647, "Julia": 1437, "HTML": 767, "CSS": 256} | package de.qwhon.aoc
import java.io.File
/** A simple helper class for keeping track of scanners.
*
*/
data class ScannerRecord(val depth: Int, val range: Int)
/** parse the input file, and return a List of scanner records.
*
*/
fun parseInputFile(fileName: String): List<ScannerRecord> {
val file = File(fileName)
val tmp = HashMap<Int, Int>()
file.forEachLine {
val contents = it.split(": ")
tmp[contents[0].toInt()] = contents[1].toInt()
}
return tmp.map { ScannerRecord(depth = it.key, range = it.value) }
}
/** compute the minimum delay necessary to pass through the firewall without getting caught.
* we return the first number that fulfills:
* for every scanner N: scanner_N is not at position 0 at timestamp (depth_N + delay)
* since (depth_N + delay) is the timestamp at which our packet reaches level N, this solves our puzzle
*/
fun minimumDelayForInputFile(fileName: String): Int {
val input = parseInputFile(fileName)
return generateSequence(seed = 0) { i -> i + 1 }
.find { i -> input.none { scanner -> (i + scanner.depth) % ((scanner.range - 1) * 2) == 0 } }!!
}
/** compute the severity of the violations for passing through the firewall without initial delay.
* we compute the severity as:
* for every scanner N: violation occurs iff scanner_N is at position 0 at timestamp (depth_N + delay)
* since (depth_N + delay) is the timestamp at which our packet reaches level N, this returns all scanners
* that catch our packet. Computing the severity is then a simple sum of depth*range, which can be computed by a fold.
*/
fun severityOfViolationsForInputFile(fileName: String): Int {
val input = parseInputFile(fileName)
return input.filter { scanner -> scanner.depth % ((scanner.range - 1) * 2) == 0 }
.fold(initial = 0) { accu, scanner -> accu + scanner.depth * scanner.range }
}
| 0 | Elm | 0 | 0 | 69f2dad6ae39a316b13a0d7fb77669d4a66c4da8 | 1,938 | advent_of_code | MIT License |
part-1.kt | shyzus | 733,207,050 | false | {"Kotlin": 3146} | import java.io.File
fun main() {
val lines = File("input.txt").readLines()
val partNumbers = ArrayList<Int>()
lines.forEachIndexed { idx, line ->
val top: String
val mid: String
val bot: String
when (idx) {
0 -> {
top = ""
mid = line
bot = lines[1]
}
lines.size - 1 -> {
top = lines[lines.size - 2]
mid = line
bot = ""
}
else -> {
top = lines[idx - 1]
mid = line
bot = lines[idx + 1]
}
}
println(top)
println(mid)
println(bot)
partNumbers.addAll(getPartNumbers(top, mid, bot))
println()
}
println(partNumbers.sum())
}
fun getPartNumbers(top: String, mid: String, bot: String): ArrayList<Int> {
var topSymbols: ArrayList<Pair<Int, String>>? = null
var botSymbols: ArrayList<Pair<Int, String>>? = null
if (top.isNotEmpty()) {
topSymbols = getSymbols(top)
}
if (bot.isNotEmpty()) {
botSymbols = getSymbols(bot)
}
val midSymbols = getSymbols(mid)
val midNumbers = getNumbers(mid)
val partNumbers = ArrayList<Int>()
println(midNumbers)
midNumbers.forEach { pair ->
val midRes = midSymbols.filter { symPair ->
symPair.first == pair.first - 1 || symPair.first == (pair.first + pair.second.length)
}
val topRes = topSymbols?.filter { symPair ->
symPair.first >= (pair.first - 1) && symPair.first <= (pair.first + pair.second.length + 1)
}
val botRes = botSymbols?.filter { symPair ->
symPair.first >= (pair.first - 1) && symPair.first <= (pair.first + pair.second.length + 1)
}
if (midRes.isNotEmpty() || topRes?.isNotEmpty() == true || botRes?.isNotEmpty() == true) {
partNumbers.add(pair.second.toInt())
}
}
println(partNumbers)
return partNumbers
}
fun getSymbols(line: String): ArrayList<Pair<Int, String>> {
val symbols = ArrayList<Pair<Int, String>>()
line.forEachIndexed { index, char ->
if (!char.isLetterOrDigit() && !char.isWhitespace() && char != '.') {
symbols.add(Pair(index, char.toString()))
}
}
return symbols
}
fun getNumbers(line: String): ArrayList<Pair<Int, String>> {
val numbers = ArrayList<Pair<Int, String>>()
line.forEachIndexed { index, char ->
if (char.isDigit()) {
numbers.add(Pair(index, char.toString()))
}
}
val actualNumbers = ArrayList<Pair<Int, String>>()
var prev: Pair<Int, String>? = null
numbers.forEach { pair ->
if (prev?.first == (pair.first - 1)) {
actualNumbers[actualNumbers.indexOf(actualNumbers.last())] =
Pair(actualNumbers.last().first,
(actualNumbers.last().second + pair.second)
)
} else {
actualNumbers.add(pair)
}
prev = pair
}
return actualNumbers
} | 0 | Kotlin | 0 | 0 | 80f003dbf169168251f2e05639298d4aaa33c02c | 3,146 | AoC2023-Day-3 | MIT License |
src/day12/Day12.kt | pnavais | 574,712,395 | false | {"Kotlin": 54079} | package day12
import readInput
import java.util.*
typealias NodeGrid = MutableList<MutableList<Node>>
data class Id(val x: Int, val y: Int)
data class Path(val cost: Int = 1, val targetNode: Node)
class Node(private val id: Id, private val c: Char) {
var pathValue: Int = -1
var visited: Boolean = false
var sourceNode: Node? = null
var height: Short = 0
val adjacentNodes = mutableListOf<Path>()
init {
height = when (c) {
'S' -> 0
'E' -> ('z' - 'a').toShort()
else -> (c - 'a').toShort()
}
}
companion object {
fun from(x: Int, y: Int, c: Char): Node {
return Node(Id(x, y), c)
}
}
fun isReachable(node: Node): Boolean {
return (height >= node.height) || ((height+1).toShort() == node.height)
}
override fun toString(): String {
return "$id, Height: $height, Path: $pathValue, Val: $c, Visited: $visited"
}
}
class Graph(private var nodes: NodeGrid) {
private var startNode: Node = nodes[0][0]
private var endNode: Node = nodes[0][0]
constructor(startNode: Node, endNode: Node, grid: NodeGrid) : this(grid){
this.startNode = startNode
this.endNode = endNode
}
// Dijkstra's algorithm
fun findShortestPath(startNode: Node = this.startNode, endNode: Node = this.endNode): List<Node> {
val shortestPath = mutableListOf<Node>()
// Step 1: Assign infinity to all vertex except starting node
for (y in 0 until nodes.size) {
for (x in 0 until nodes[y].size) {
nodes[y][x].pathValue = -1
nodes[y][x].visited = false
nodes[y][x].sourceNode = null
}
}
startNode.pathValue = 0
// Step 2: Go to each adjacent vertex and update its path length
val compareByMinPath: Comparator<Node> = compareBy { it.pathValue }
val nodeQueue: PriorityQueue<Node> = PriorityQueue(compareByMinPath)
val nodesAdded = mutableSetOf<Node>()
nodeQueue.add(startNode)
while (nodeQueue.isNotEmpty()) {
val currentNode = nodeQueue.poll()
currentNode.visited = true
for (sibling in currentNode.adjacentNodes) {
val targetNode = sibling.targetNode
if (!targetNode.visited) {
// Only update length is lesser than current
if ((targetNode.pathValue == -1) || (targetNode.pathValue > (currentNode.pathValue + sibling.cost))) {
targetNode.pathValue = currentNode.pathValue + sibling.cost
targetNode.sourceNode = currentNode
}
// Add to queue
if (!nodesAdded.contains(targetNode)) {
nodeQueue.add(targetNode)
nodesAdded.add(targetNode)
}
}
}
}
// Step 3: Backtrack from end node to get the list of source nodes to start
var pathNode: Node? = endNode
while ((pathNode != null) && (pathNode.visited) && (pathNode != startNode)) {
shortestPath.add(pathNode)
pathNode = pathNode.sourceNode
}
return shortestPath
}
fun findLowestNodes(): List<Node> {
val list = mutableListOf<Node>()
for (y in 0 until nodes.size) {
for (x in 0 until nodes[y].size) {
if (nodes[y][x].height == 0.toShort()) {
list.add(nodes[y][x])
}
}
}
return list
}
fun getNode(x: Int, y: Int): Node {
return this.nodes[y][x]
}
}
fun readNodes(input: List<String>): Graph {
var startNode: Node? = null
var endNode: Node? = null
var currentNode: Node? = null
val nodes: NodeGrid = mutableListOf()
for ((y, line) in input.withIndex()) {
val currentRow = mutableListOf<Node>()
nodes.add(currentRow)
line.toCharArray().forEachIndexed{ x, c ->
currentNode = Node.from(x, y, c)
currentRow.add(currentNode!!)
// Add adjacent look-ahead nodes (up, left)
if (y-1>=0) {
if (currentNode!!.isReachable(nodes[y-1][x])) {
currentNode!!.adjacentNodes.add(Path(1, nodes[y-1][x])) // Add upper node
}
if (nodes[y-1][x].isReachable(currentNode!!)) {
nodes[y-1][x].adjacentNodes.add(Path(1, currentNode!!)) // Set current node as adjacent in upper node
}
}
if (x-1>=0) {
if (currentNode!!.isReachable(nodes[y][x-1])) {
currentNode!!.adjacentNodes.add(Path(1, nodes[y][x-1])) // Add left node
}
if (nodes[y][x-1].isReachable(currentNode!!)) {
nodes[y][x-1].adjacentNodes.add(Path(1, currentNode!!)) // Set current node as adjacent in left node
}
}
// Keep Starting & end nodes
if (c == 'S') {
startNode = currentNode
} else if (c == 'E') {
endNode = currentNode
}
}
}
return Graph(startNode!!, endNode!!, nodes)
}
fun part1(input: List<String>): Int {
val nodeGrid = readNodes(input)
return nodeGrid.findShortestPath().size
}
fun part2(input: List<String>): Int {
val nodeGrid = readNodes(input)
val lowestNodes = nodeGrid.findLowestNodes()
var lowestSteps = -1
for (node in lowestNodes) {
val shortestPath = nodeGrid.findShortestPath(node).size
if ((shortestPath>0) && ((lowestSteps == -1) || (shortestPath<lowestSteps))) {
lowestSteps = shortestPath
}
}
return lowestSteps
}
fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day12/Day12_test")
println(part1(testInput))
println(part2(testInput))
}
| 0 | Kotlin | 0 | 0 | ed5f521ef2124f84327d3f6c64fdfa0d35872095 | 6,248 | advent-of-code-2k2 | Apache License 2.0 |
src/main/kotlin/de/niemeyer/aoc2022/Day13.kt | stefanniemeyer | 572,897,543 | false | {"Kotlin": 175820, "Shell": 133} | /**
* Advent of Code 2022, Day 13: Distress Signal
* Problem Description: https://adventofcode.com/2022/day/13
*/
package de.niemeyer.aoc2022
import kotlinx.serialization.*
import kotlinx.serialization.json.*
import de.niemeyer.aoc.utils.Resources.resourceAsText
import de.niemeyer.aoc.utils.getClassName
@Serializable
class Packet(val data: JsonArray) : Comparable<Packet> {
override fun compareTo(other: Packet): Int {
val compResults = data.zip(other.data).map {
val left = it.first
val right = it.second
if (left is JsonPrimitive && right is JsonPrimitive) {
left.int - right.int
} else if (left is JsonArray && right is JsonArray) {
Packet(left).compareTo(Packet(right))
} else {
if (left is JsonPrimitive && right is JsonArray) {
return@map Packet(JsonArray(listOf(left))).compareTo(Packet(right))
} else if (left is JsonArray && right is JsonPrimitive) {
return@map Packet(left).compareTo(Packet(JsonArray(listOf(right))))
} else {
error("Invalid input")
}
}
}
return compResults.firstOrNull { it != 0 } ?: (data.size - other.data.size)
}
}
fun main() {
fun part1(input: String): Int {
val res = input.split("\n\n").map { packets ->
packets.split("\n")
.map { it.toPacket() }
}.mapIndexedNotNull { index, packets ->
if (packets.first() <= packets.last()) {
index + 1
} else {
null
}
}
return res.sum()
}
fun part2(input: String): Int {
val newInput = input.lines().filter { it.isNotBlank() }.map { it.trim().toPacket() }
val dividerPacket1 = "[[2]]".toPacket()
val dividerPacket2 = "[[6]]".toPacket()
val ordered = (newInput + dividerPacket1 + dividerPacket2).sorted()
return (ordered.indexOf(dividerPacket1) + 1) * (ordered.indexOf(dividerPacket2) + 1)
}
val name = getClassName()
val testInput = resourceAsText(fileName = "${name}_test.txt").trim()
val puzzleInput = resourceAsText(fileName = "${name}.txt").trim()
check(part1(testInput) == 13)
val puzzleResult = part1(puzzleInput)
println(puzzleResult)
check(puzzleResult == 5_905)
check(part2(testInput) == 140)
println(part2(puzzleInput))
check(part2(puzzleInput) == 21_691)
}
fun String.toPacket() =
Json.decodeFromString<Packet>("{ \"data\" : ${this} }")
| 0 | Kotlin | 0 | 0 | ed762a391d63d345df5d142aa623bff34b794511 | 2,622 | AoC-2022 | Apache License 2.0 |
src/main/kotlin/adventofcode/y2021/Day14.kt | Tasaio | 433,879,637 | false | {"Kotlin": 117806} | import adventofcode.BigIntegerMap
import adventofcode.countOfEachCharacter
import adventofcode.runDay
fun main() {
val testInput = """
NNCB
CH -> B
HH -> N
CB -> H
NH -> C
HB -> C
HC -> B
HN -> C
NN -> C
BH -> H
NC -> B
NB -> B
BN -> B
BB -> N
BC -> B
CC -> N
CN -> C
""".trimIndent()
runDay(
day = Day14::class,
testInput = testInput,
testAnswer1 = 1588,
testAnswer2 = 2188189693529
)
}
open class Day14(staticInput: String? = null) : Y2021Day(14, staticInput) {
private val input = fetchInput()
private val template = input[0]
private val rules: MutableMap<Pair<Char, Char>, Char> = hashMapOf()
init {
input.filter { it.contains("->") }
.forEach { rules[Pair(it[0], it[1])] = it[6] }
}
override fun reset() {
super.reset()
}
override fun part1(): Number? {
var str = template
for (i in 0..9) {
val nextStr = StringBuffer()
str.indices.forEach { i ->
nextStr.append(str[i])
if (str.length > i + 1) {
val rule = rules.get(Pair(str[i], str[i + 1]))
if (rule != null) {
nextStr.append(rule)
}
}
}
str = nextStr.toString()
}
val map = str.countOfEachCharacter()
return map.maxOf { it.value } - map.minOf { it.value }
}
override fun part2(): Number? {
var dict = BigIntegerMap<Pair<Char, Char>>()
val count = template.countOfEachCharacter()
template.indices.forEach { i ->
if (template.length > i + 1) {
dict.inc(Pair(template[i], template[i + 1]))
}
}
for (i in 1..40) {
val newDict = BigIntegerMap<Pair<Char, Char>>()
dict.forEach { (pair, c) ->
val toInsert = rules[pair]
if (toInsert != null) {
count[toInsert] += c
newDict[Pair(pair.first, toInsert)] += c
newDict[Pair(toInsert, pair.second)] += c
}
}
dict = newDict
}
return count.maxOf { it.value } - count.minOf { it.value }
}
}
| 0 | Kotlin | 0 | 0 | cc72684e862a782fad78b8ef0d1929b21300ced8 | 2,422 | adventofcode2021 | The Unlicense |
src/main/kotlin/aoc2022/Day25.kt | j4velin | 572,870,735 | false | {"Kotlin": 285016, "Python": 1446} | package aoc2022
import readInput
typealias SNAFU = String
object Day25 {
private fun Char.digitFromSNAFU(): Int {
return when (this) {
'=' -> -2
'-' -> -1
else -> this.digitToInt()
}
}
private fun SNAFU.toDecimal(): Long {
val array = this.toCharArray()
var result = 0L
var multiplier = 1L
for (i in array.size - 1 downTo 0) {
val decimalDigit = array[i].digitFromSNAFU()
result += decimalDigit * multiplier
multiplier *= 5
}
return result
}
private fun Long.toSNAFU(): String {
val str = this.toString(5).toCharArray()
var buffer = ""
var carry = 0
for (i in str.size - 1 downTo 0) {
val digit = str[i].digitToInt() + carry
buffer += when {
digit == 3 -> '='
digit == 4 -> '-'
digit > 4 -> digit - 5
else -> digit
}
carry = if (digit >= 3) 1 else 0
}
if (carry > 0) {
buffer += carry
}
return buffer.reversed()
}
fun part1(input: List<String>): String {
val decimalSum = input.sumOf { it.toDecimal() }
return decimalSum.toSNAFU()
}
fun part2(input: List<String>): Int {
return 0
}
}
fun main() {
val testInput = readInput("Day25_test", 2022)
check(Day25.part1(testInput) == "2=-1=0")
check(Day25.part2(testInput) == 0)
val input = readInput("Day25", 2022)
println(Day25.part1(input))
println(Day25.part2(input))
}
| 0 | Kotlin | 0 | 0 | f67b4d11ef6a02cba5b206aba340df1e9631b42b | 1,637 | adventOfCode | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/BinaryTreeCameras.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2020 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import kotlin.math.min
/**
* 968. Binary Tree Cameras
* @see <a href="https://leetcode.com/problems/binary-tree-cameras/">Source</a>
*/
fun interface BinaryTreeCamerasStrategy {
operator fun invoke(root: TreeNode?): Int
}
class BinaryTreeCamerasDFS : BinaryTreeCamerasStrategy {
private var cameras = 0
override operator fun invoke(root: TreeNode?): Int {
if (root == null) return 0
val top = root.dfs()
val local = if (top == NOT_MONITORED) 1 else 0
return cameras + local
}
private fun TreeNode?.dfs(): Int {
if (this == null) return MONITORED_NO_CAM
val left = this.left.dfs()
val right = this.right.dfs()
return if (left == MONITORED_NO_CAM && right == MONITORED_NO_CAM) {
NOT_MONITORED
} else if (left == NOT_MONITORED || right == NOT_MONITORED) {
cameras++
MONITORED_WITH_CAM
} else {
MONITORED_NO_CAM
}
}
companion object {
private const val NOT_MONITORED = 0
private const val MONITORED_NO_CAM = 1
private const val MONITORED_WITH_CAM = 2
}
}
class BinaryTreeCamerasDP : BinaryTreeCamerasStrategy {
override operator fun invoke(root: TreeNode?): Int {
val ans = solve(root)
return min(ans[1], ans[2])
}
// 0: Strict ST; All nodes below this are covered, but not this one
// 1: Normal ST; All nodes below and incl this are covered - no camera
// 2: Placed camera; All nodes below this are covered, plus camera here
private fun solve(node: TreeNode?): IntArray {
if (node == null) return intArrayOf(0, 0, MAX_ARRAY_SIZE)
val l = solve(node.left)
val r = solve(node.right)
val mL12 = min(l[1], l[2])
val mR12 = min(r[1], r[2])
val d0 = l[1] + l[1]
val d1 = min(l[2] + mR12, r[2] + mL12)
val d2 = 1 + min(l[0], mL12) + min(r[0], mR12)
return intArrayOf(d0, d1, d2)
}
companion object {
private const val MAX_ARRAY_SIZE = 99999
}
}
class BinaryTreeCamerasGreedy : BinaryTreeCamerasStrategy {
private var res = 0
override operator fun invoke(root: TreeNode?): Int {
return (if (dfs(root) < 1) 1 else 0) + res
}
private fun dfs(root: TreeNode?): Int {
if (root == null) return 2
val left = dfs(root.left)
val right = dfs(root.right)
if (left == 0 || right == 0) {
res++
return 1
}
return if (left == 1 || right == 1) 2 else 0
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 3,214 | kotlab | Apache License 2.0 |
src/Day03.kt | ambrosil | 572,667,754 | false | {"Kotlin": 70967} | fun main() {
fun Set<Char>.score(): Int {
val c = single()
return if (c.isLowerCase()) {
1 + (c - 'a')
} else {
27 + (c - 'A')
}
}
fun String.halve(): List<String> {
val half = length / 2
return listOf(substring(0, half), substring(half))
}
fun part1(input: List<String>) =
input.sumOf { item ->
val (first, second) = item.halve()
(first intersect second).score()
}
fun part2(input: List<String>) =
input
.chunked(3)
.sumOf {
it.fold(it[0].toSet()) {
acc, s -> acc intersect s
}
.score()
}
val input = readInput("inputs/Day03")
println(part1(input))
println(part2(input))
}
infix fun String.intersect(o: String) = toSet() intersect o.toSet()
infix fun Set<Char>.intersect(o: String) = this intersect o.toSet()
| 0 | Kotlin | 0 | 0 | ebaacfc65877bb5387ba6b43e748898c15b1b80a | 976 | aoc-2022 | Apache License 2.0 |
src/Day20.kt | Fedannie | 572,872,414 | false | {"Kotlin": 64631} | const val DECRYPTION_KEY = 811589153L
fun main() {
fun List<Long>.grove(): Long {
return listOf(1000, 2000, 3000).sumOf { this[(indexOf(0) + it) % size] }
}
fun parseInput(input: List<String>, key: Long = 1): List<Long> {
return input.map { it.toLong() * key }
}
fun mix(order: List<Long>, values: List<Pair<Int, Long>> = order.mapIndexed { i, v -> i to v }): List<Pair<Int, Long>> {
val mixed = values.toMutableList()
for (i in values.indices) {
val index = mixed.indexOfFirst { it.first == i }
val next = mixed[index]
mixed.removeAt(index)
val newPosition = (index + next.second).mod(values.size - 1)
mixed.add(if (newPosition == 0) values.size - 1 else newPosition, next)
}
return mixed
}
fun part1(input: List<String>): Long {
val initial = parseInput(input)
return mix(initial).map { it.second }.grove()
}
fun part2(input: List<String>): Long {
val order = parseInput(input, DECRYPTION_KEY)
var values = order.mapIndexed { i, v -> i to v }
repeat(10) {
values = mix(order, values)
}
return values.map { it.second }.grove()
}
val testInput = readInputLines("Day20_test")
check(part1(testInput) == 3L)
check(part2(testInput) == 1623178306L)
val input = readInputLines(20)
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 1d5ac01d3d2f4be58c3d199bf15b1637fd6bcd6f | 1,348 | Advent-of-Code-2022-in-Kotlin | Apache License 2.0 |
src/questions/SearchRange.kt | realpacific | 234,499,820 | false | null | package questions
import _utils.UseCommentAsDocumentation
import utils.shouldBe
/**
* Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of
* a given target value. If target is not found in the array, return [-1, -1].
*
* [Source](https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/)
*/
@UseCommentAsDocumentation
private fun searchRange(nums: IntArray, target: Int): IntArray {
if (nums.isEmpty() || nums.first() > target || nums.last() < target) return intArrayOf(-1, -1)
if (nums.size <= 2) return intArrayOf(nums.indexOfFirst { it == target }, nums.indexOfLast { it == target })
return findFirstIndex(nums, target, low = 0, high = nums.lastIndex)
}
fun findFirstIndex(nums: IntArray, target: Int, low: Int, high: Int): IntArray {
if (low == high && nums.getOrNull(low) == target) {
return intArrayOf(low, low)
}
if (low < 0 || low > high || high > nums.lastIndex) {
return intArrayOf(-1, -1)
}
val mid = (low + high) / 2
val midValue = nums[mid]
return if (target < midValue) {
findFirstIndex(nums, target, low, mid - 1)
} else if (target > midValue) {
findFirstIndex(nums, target, mid + 1, high)
} else {
var startIndex = mid
while (startIndex >= 0 && nums[startIndex] == midValue) {
startIndex--
}
startIndex++
var endIndex = mid
while (endIndex <= nums.lastIndex && nums[endIndex] == midValue) {
endIndex++
}
endIndex--
intArrayOf(startIndex, endIndex)
}
}
fun main() {
searchRange(nums = intArrayOf(1, 1, 2), target = 1) shouldBe intArrayOf(0, 1)
searchRange(nums = intArrayOf(1, 2, 2), target = 2) shouldBe intArrayOf(1, 2)
searchRange(nums = intArrayOf(1, 2, 3), target = 1) shouldBe intArrayOf(0, 0)
searchRange(nums = intArrayOf(5, 7, 7, 8, 8, 10), target = 8) shouldBe intArrayOf(3, 4)
searchRange(nums = intArrayOf(1, 3), target = 1) shouldBe intArrayOf(0, 0)
searchRange(nums = intArrayOf(1), target = 1) shouldBe intArrayOf(0, 0)
searchRange(nums = intArrayOf(5, 7, 7, 8, 8, 10), target = 6) shouldBe intArrayOf(-1, -1)
} | 4 | Kotlin | 5 | 93 | 22eef528ef1bea9b9831178b64ff2f5b1f61a51f | 2,241 | algorithms | MIT License |
app/src/test/java/com/zwq65/unity/algorithm/unionfind/LeetCode959.kt | Izzamuzzic | 95,655,850 | false | {"Kotlin": 449365, "Java": 17918} | package com.zwq65.unity.algorithm.unionfind
import org.junit.Test
/**
* ================================================
* <p>
* <a href="https://leetcode-cn.com/problems/regions-cut-by-slashes">959. 由斜杠划分区域</a>.
* Created by NIRVANA on 2019/7/15.
* Contact with <<EMAIL>>
* ================================================
*/
class LeetCode959 {
@Test
fun test() {
val array = arrayOf("/\\", "\\/")
val number = regionsBySlashes(array)
print("number:$number")
}
private fun regionsBySlashes(grid: Array<String>): Int {
val size = grid.size
val uf = UF(4 * size * size)
for (i in 0 until size) {
for (j in 0 until size) {
val root = 4 * (size * i + j)
val charr = grid[i][j]
if (charr != '/') {
uf.union(root + 1, root + 0)
uf.union(root + 3, root + 2)
}
if (charr != '\\') {
uf.union(root + 1, root + 2)
uf.union(root + 3, root + 0)
}
if (i != size - 1) {
// 如果不是最后一行,则向下归并
uf.union(root + 2, (root + 4 * size) + 0)
}
if (j != size - 1) {
// 如果不是最后一列,则向右归并
uf.union(root + 1, (root + 4) + 3)
}
}
}
var answer = 0
for (i in 0 until 4 * size * size) {
if (i == uf.find(i)) {
answer++
}
}
return answer
}
class UF(size: Int) {
private var parent = IntArray(size)
init {
//初始化:parent指向本身
for (i in 0 until size) {
parent[i] = i
}
}
fun find(x: Int): Int {
return if (x == parent[x]) {
x
} else {
parent[x] = find(parent[x])
find(parent[x])
}
}
fun union(x: Int, y: Int) {
parent[find(x)] = parent[find(y)]
}
}
}
| 0 | Kotlin | 0 | 0 | 98a9ad7bb298d0b0cfd314825918a683d89bb9e8 | 2,233 | Unity | Apache License 2.0 |
solutions/src/Day05.kt | khouari1 | 573,893,634 | false | {"Kotlin": 132605, "HTML": 175} | fun main() {
fun part1(input: List<String>): String = getTopCrates(input) { from, to, numberToMove ->
for (i in 1..numberToMove) {
val poppedChar = from.removeLast()
to.addLast(poppedChar)
}
}
fun part2(input: List<String>): String = getTopCrates(input) { from, to, numberToMove ->
val fromDeque = ArrayDeque<Char>()
for (i in 1..numberToMove) {
val poppedChar = from.removeLast()
fromDeque.addFirst(poppedChar)
}
fromDeque.toList().forEach { to.add(it) }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
private fun getTopCrates(
input: List<String>,
moveCrates: (from: ArrayDeque<Char>, to: ArrayDeque<Char>, numberToMove: Int) -> Unit,
): String {
val numberOfColumns = input.getNumberOfColumns()
val deques = mutableMapOf<Int, ArrayDeque<Char>>()
for (i in 1..numberOfColumns) {
deques[i] = ArrayDeque()
}
var lineCounter = 0
var rowCharIndex = 1
run outer@{
input.forEach {
for (i in 0 until deques.size) {
if (rowCharIndex > it.length) {
rowCharIndex = 1
lineCounter++
return@forEach
}
val colValue = it[rowCharIndex]
if (colValue == '1') {
lineCounter++
return@outer
}
if (colValue != ' ') {
deques[i + 1]?.addFirst(colValue)
}
rowCharIndex = rowCharIndex.moveToNextColIndex()
}
rowCharIndex = ROW_CHAR_STARTING_INDEX
lineCounter++
}
}
input.drop(lineCounter + 1)
.forEach {
val (_, move, _, from, _, to) = it.split(" ")
val fromDeque = deques[from.toInt()]!!
val toDeque = deques[to.toInt()]!!
moveCrates(fromDeque, toDeque, move.toInt())
}
return deques.values
.filter { it.isNotEmpty() }
.map { it.removeLast() }
.joinToString(separator = "")
}
private fun List<String>.getNumberOfColumns() =
first { it[1] == '1' }
.filterNot { it.isWhitespace() }
.toCharArray()
.last()
.digitToInt()
private fun Int.moveToNextColIndex() = this + 4
private const val ROW_CHAR_STARTING_INDEX = 1
private operator fun <E> List<E>.component6() = this[5]
| 0 | Kotlin | 0 | 1 | b00ece4a569561eb7c3ca55edee2496505c0e465 | 2,690 | advent-of-code-22 | Apache License 2.0 |
src/main/kotlin/com/nibado/projects/advent/y2020/Day14.kt | nielsutrecht | 47,550,570 | false | null | package com.nibado.projects.advent.y2020
import com.nibado.projects.advent.Day
import com.nibado.projects.advent.resourceLines
object Day14 : Day {
private interface Day14Input
private data class Mask(val mask: String) : Day14Input
private data class Mem(val index: Int, val value: Int) : Day14Input
private val maskRegex = "mask = ([01X]{36})".toRegex()
private val memRegex = "mem.([0-9]+). = ([0-9]+)".toRegex()
private val values = resourceLines(2020, 14).map(::parse)
private fun parse(line: String): Day14Input =
when {
maskRegex.matches(line) -> maskRegex.matchEntire(line)!!.groupValues.let { (_, a) -> Mask(a) }
memRegex.matches(line) -> memRegex.matchEntire(line)!!.groupValues.let { (_, a, b) -> Mem(a.toInt(), b.toInt()) }
else -> throw IllegalArgumentException(line)
}
override fun part1(): Long = values.fold(mutableMapOf<Int, Long>() to "") {(regs, mask), inst ->
when (inst) {
is Mask -> regs to inst.mask
is Mem -> { regs[inst.index] = mask(mask, inst.value); regs to mask }
else -> regs to mask
}
}.let { (regs) -> regs.values.sum() }
override fun part2() : Long = values.fold(mutableMapOf<Long, Long>() to "") { (regs, mask), inst ->
when (inst) {
is Mask -> regs to inst.mask
is Mem -> { addresses(mask, inst.index).forEach { regs[it] = inst.value.toLong() }; regs to mask }
else -> regs to mask
}
}.let { (regs) -> regs.values.sum() }
private fun mask(mask: String, value: Int): Long = value
.toString(2).padStart(36, '0')
.zip(mask) { a, b -> if (b == 'X') a else b }.joinToString("").toLong(2)
private fun addresses(mask: String, address: Int) : List<Long> {
val initial = address.toString(2).padStart(36, '0')
.zip(mask) { a, b -> if (b == '0') a else b }.joinToString("")
val bits = initial.count { it == 'X' }
val max = "1".repeat(bits).toInt(2)
val list = (0 .. max).map { it.toString(2).padStart(bits, '0').toMutableList() }.map { chars ->
initial.map { if(it == 'X') chars.removeAt(0) else it }.joinToString("")
}
return list.map { it.toLong(2) }
}
}
| 1 | Kotlin | 0 | 15 | b4221cdd75e07b2860abf6cdc27c165b979aa1c7 | 2,372 | adventofcode | MIT License |
src/main/kotlin/day4/Day4ReposeRecord.kt | Zordid | 160,908,640 | false | null | package day4
import shared.extractAllInts
import shared.readPuzzle
data class Guard(val id: Int) {
private val minuteStatistics = IntArray(60)
val totalMinutesAsleep get() = minuteStatistics.sum()
val maxMinuteAsleepCount get() = minuteStatistics.max()
val maxMinuteAsleep get() = minuteStatistics.indexOf(maxMinuteAsleepCount)
fun asleep(range: IntRange) {
for (i in range) minuteStatistics[i]++
}
}
fun processLogs(log: List<String>): List<Guard> {
val guards = mutableMapOf<Int, Guard>()
var currentGuard: Guard? = null
var fellAsleep: Int? = null
for (logEntry in log.sorted()) {
val lastNumber = logEntry.extractAllInts().last()
when {
"shift" in logEntry -> currentGuard = guards.getOrPut(lastNumber) { Guard(lastNumber) }
"asleep" in logEntry -> fellAsleep = lastNumber
else -> currentGuard!!.asleep(fellAsleep!! until lastNumber)
}
}
return guards.values.toList()
}
fun part1(guards: List<Guard>): Any {
val sleepyGuard = guards.maxBy { it.totalMinutesAsleep }
return "$sleepyGuard * ${sleepyGuard.maxMinuteAsleep} = ${sleepyGuard.id * sleepyGuard.maxMinuteAsleep}"
}
fun part2(guards: List<Guard>): Any {
val masterOfSleep = guards.maxBy { it.maxMinuteAsleepCount }
return "$masterOfSleep * ${masterOfSleep.maxMinuteAsleep} = ${masterOfSleep.id * masterOfSleep.maxMinuteAsleep}"
}
fun main() {
val puzzle = readPuzzle(4)
val guards = processLogs(puzzle)
println(part1(guards))
println(part2(guards))
} | 0 | Kotlin | 0 | 0 | f246234df868eabecb25387d75e9df7040fab4f7 | 1,569 | adventofcode-kotlin-2018 | Apache License 2.0 |
year2023/src/main/kotlin/net/olegg/aoc/year2023/day18/Day18.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.year2023.day18
import net.olegg.aoc.someday.SomeDay
import net.olegg.aoc.utils.Directions
import net.olegg.aoc.utils.Directions.D
import net.olegg.aoc.utils.Directions.L
import net.olegg.aoc.utils.Directions.R
import net.olegg.aoc.utils.Directions.U
import net.olegg.aoc.utils.Vector2D
import net.olegg.aoc.utils.toPair
import net.olegg.aoc.year2023.DayOf2023
/**
* See [Year 2023, Day 18](https://adventofcode.com/2023/day/18)
*/
object Day18 : DayOf2023(18) {
override fun first(): Any? {
val steps = lines.map { it.split(" ").toPair() }
.map { Directions.valueOf(it.first) to it.second.toInt() }
return solve(steps)
}
override fun second(): Any? {
val dirMapping = mapOf(
'0' to R,
'1' to D,
'2' to L,
'3' to U,
)
val steps = lines.map { it.takeLast(7).dropLast(1) }
.map { dirMapping.getValue(it.last()) to it.take(5).toInt(16) }
return solve(steps)
}
private fun solve(steps: List<Pair<Directions, Int>>): Long {
val points = steps.scan(Vector2D()) { acc, (dir, count) ->
acc + dir.step * count
}
val perimeter = steps.sumOf { it.second.toLong() }
val xs = points.map { it.x.toLong() }
val ys = points.map { it.y.toLong() }
return (xs.zip(ys.drop(1), Long::times).sum() - ys.zip(xs.drop(1), Long::times).sum()) / 2 + (perimeter / 2 + 1)
}
}
fun main() = SomeDay.mainify(Day18)
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 1,417 | adventofcode | MIT License |
src/Day03.kt | yeung66 | 574,904,673 | false | {"Kotlin": 8143} | fun main() {
fun getPriority(c: Char): Int = when(c) {
in ('a'..'z') -> c - 'a' + 1
else -> c - 'A' + 27
}
fun part1(input: List<String>): Int {
return input.sumOf { it.subSequence(0, it.length / 2).toSet().intersect(it.subSequence(it.length / 2, it.length).toSet()).map(::getPriority)[0] }
}
fun part2(input: List<String>): Int {
return input.withIndex().groupBy { it.index / 3 }.map {
val (a, b, c) = it.value.map { x -> x.value.toSet() }
a.intersect(b.intersect(c)).map(::getPriority)[0]
}.sum()
}
val input = readInputLines("3")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 554217f83e81021229759bccc8b616a6b270902c | 682 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/main/kotlin/nl/tiemenschut/aoc/y2023/day13.kt | tschut | 723,391,380 | false | {"Kotlin": 61206} | package nl.tiemenschut.aoc.y2023
import nl.tiemenschut.aoc.lib.dsl.aoc
import nl.tiemenschut.aoc.lib.dsl.day
import nl.tiemenschut.aoc.lib.dsl.parser.InputParser
import nl.tiemenschut.aoc.lib.util.grid.CharGridParser
import nl.tiemenschut.aoc.lib.util.grid.Grid
import nl.tiemenschut.aoc.lib.util.points.by
import nl.tiemenschut.aoc.y2023.Type.COL
import nl.tiemenschut.aoc.y2023.Type.ROW
import kotlin.math.min
object MirrorGridParser : InputParser<List<Grid<Char>>> {
override fun parse(input: String) = input.split("\n\n").map {
CharGridParser.parse(it.trim())
}
}
enum class Type { ROW, COL }
data class Reflection(val type: Type, val index: Int)
fun Grid<Char>.getCol(x: Int): String = buildString {
for (y in 0 until height()) append(this@getCol[x by y])
}
fun Grid<Char>.getRow(y: Int): String = buildString {
for (x in 0 until width()) append(this@getRow[x by y])
}
fun Grid<Char>.findReflection(): Reflection {
outer@ for (x in 1 until width()) {
for (offset in 1..min(width() - x, x - 0)) {
if (getCol(x - offset) != getCol(x + offset - 1)) continue@outer
}
return Reflection(COL, x)
}
outer@ for (y in 1 until height()) {
for (offset in 1..min(height() - y, y - 0)) {
if (getRow(y - offset) != getRow(y + offset - 1)) continue@outer
}
return Reflection(ROW, y)
}
throw RuntimeException("wtf")
}
fun Grid<Char>.findReflectionWithSmudge(): Reflection {
outer@ for (x in 1 until width()) {
var differences = 0
for (offset in 1..min(width() - x, x - 0)) {
val a = getCol(x - offset)
val b = getCol(x + offset - 1)
differences += a.mapIndexed { index, c -> if (c == b[index]) 0 else 1 }.sum()
}
if (differences == 1) return Reflection(COL, x)
}
outer@ for (y in 1 until height()) {
var differences = 0
for (offset in 1..min(height() - y, y - 0)) {
val a = getRow(y - offset)
val b = getRow(y + offset - 1)
differences += a.mapIndexed { index, c -> if (c == b[index]) 0 else 1 }.sum()
}
if (differences == 1) return Reflection(ROW, y)
}
throw RuntimeException("wtf")
}
fun main() {
aoc(MirrorGridParser) {
puzzle { 2023 day 13 }
part1 { input ->
input.map { it.findReflection() }.sumOf { if (it.type == COL) it.index else 100 * (it.index) }
}
part2 { input ->
input.map { it.findReflectionWithSmudge() }.sumOf { if (it.type == COL) it.index else 100 * (it.index) }
}
}
}
| 0 | Kotlin | 0 | 1 | a1ade43c29c7bbdbbf21ba7ddf163e9c4c9191b3 | 2,635 | aoc-2023 | The Unlicense |
src/Day14.kt | zfz7 | 573,100,794 | false | {"Kotlin": 53499} | import kotlin.math.abs
fun main() {
println(day14A(readFile("Day14")))
println(day14B(readFile("Day14")))
}
fun generateGrid(input: String, addFloor: Boolean = false ): MutableList<MutableList<Char>> {
val rocks = input.trim().split("\n").flatMap { line ->
line.split(" -> ").windowed(2).flatMap { pair: List<String> ->
val start: Pair<Int, Int> = Pair(pair[0].split(",")[0].toInt(), pair[0].split(",")[1].toInt())
val end: Pair<Int, Int> = Pair(pair[1].split(",")[0].toInt(), pair[1].split(",")[1].toInt())
if (start.first == end.first) {//line moves up/down0
generateSequence(start) {
Pair(
it.first,
if (start.second < end.second) it.second + 1 else it.second - 1
)
}.take(abs(start.second - end.second) + 1).toList()
} else { //if (start.second == end.second) {//line moves left/right
generateSequence(start) {
Pair(
if (start.first < end.first) it.first + 1 else it.first - 1,
it.second
)
}.take(abs(start.first - end.first) + 1).toList()
}
}
}
val ret = Array(1000) { CharArray(1000){'.'}.toMutableList() }.toMutableList()
rocks.forEach {
ret[it.first][it.second] = '#'
}
if(addFloor) {
val floor = rocks.maxBy { it.second }.second + 2
repeat(ret[floor].size) {
ret[it][floor] = '-'
}
}
ret[0][500] = '+'
return ret
}
fun day14B(input: String): Int {
val grid = generateGrid(input,true)
var count = 0
while(dropSand2(grid)){
count++
}
return count
}
fun day14A(input: String): Int {
val grid = generateGrid(input)
var count = 0
while(dropSand(grid)){
count++
}
return count
}
fun dropSand(grid: MutableList<MutableList<Char>>) :Boolean{
var sandPos = Pair(500,0)
var moved = true
while(moved){
if(sandPos.first !in 0 until grid.size-1 || sandPos.second !in 0 until grid[0].size-1)//out of bounds
return false
else if(grid[sandPos.first][sandPos.second+1] == '.'){ //can move down
moved = true
sandPos = Pair(sandPos.first, sandPos.second+1)
}
else if(grid[sandPos.first -1][sandPos.second +1 ] == '.') {//can move down + left
moved = true
sandPos = Pair(sandPos.first -1, sandPos.second+1)
}
else if(grid[sandPos.first +1][sandPos.second +1 ] == '.') {//can move down + right
moved = true
sandPos = Pair(sandPos.first +1, sandPos.second +1)
}else{
moved = false
}
}
grid[sandPos.first][sandPos.second] = '0'
return true
}
fun dropSand2(grid: MutableList<MutableList<Char>>) :Boolean{
var sandPos = Pair(500,0)
var moved = true
if(grid[sandPos.first][sandPos.second] == '0'){
return false
}
while(moved){
if(sandPos.first !in 0 until grid.size-1 || sandPos.second !in 0 until grid[0].size-1)//out of bounds
return false
else if(grid[sandPos.first][sandPos.second+1] == '.'){ //can move down
moved = true
sandPos = Pair(sandPos.first, sandPos.second+1)
}
else if(grid[sandPos.first -1][sandPos.second +1 ] == '.') {//can move down + left
moved = true
sandPos = Pair(sandPos.first -1, sandPos.second+1)
}
else if(grid[sandPos.first +1][sandPos.second +1 ] == '.') {//can move down + right
moved = true
sandPos = Pair(sandPos.first +1, sandPos.second +1)
}else{
moved = false
}
}
grid[sandPos.first][sandPos.second] = '0'
return true
}
| 0 | Kotlin | 0 | 0 | c50a12b52127eba3f5706de775a350b1568127ae | 3,890 | AdventOfCode22 | Apache License 2.0 |
src/main/kotlin/com/github/brpeterman/advent2022/CrateCrane.kt | brpeterman | 573,059,778 | false | {"Kotlin": 53108} | package com.github.brpeterman.advent2022
import java.util.*
class CrateCrane {
data class CrateState(val stacks: MutableMap<Int, LinkedList<Char>>, val moves: List<CrateMove>)
data class CrateMove(val count: Int, val from: Int, val to: Int)
fun reportStacks(stacks: List<LinkedList<Char>>): String {
return stacks.fold("") { output, stack -> output + stack.peek().toString() }
}
enum class CraneMode {
DEFAULT,
HOLD_MULTIPLE
}
fun simulate(state: CrateState, mode: CraneMode = CraneMode.DEFAULT): List<LinkedList<Char>> {
val stacks = state.stacks
val moves = state.moves
moves.forEach { move ->
val from = stacks[move.from]!!
val to = stacks[move.to]!!
val holding = mutableListOf<Char>()
(1..move.count).forEach {
holding.add(from.pop())
}
if (mode == CraneMode.HOLD_MULTIPLE) {
holding.reverse()
}
holding.forEach { crate ->
to.push(crate)
}
}
return stacks.entries
.sortedBy { it.key }
.map { it.value }
}
companion object {
fun parseInput(input: String): CrateState {
val (stateInput, movesInput) = input.split("\n\n")
val stacks = stateInput.split("\n")
.filter { it.matches(""" *\[.*""".toRegex()) }
.fold(mutableMapOf<Int, LinkedList<Char>>().withDefault { LinkedList() }) { stacks, line ->
line.chunked(4)
.withIndex()
.forEach { (index, crate) ->
val matches = """\[([A-Z])] ?""".toRegex().matchEntire(crate)
if (matches != null) {
val stack = stacks.getValue(index + 1)
val (crateName) = matches.destructured
stack.add(crateName[0])
stacks[index + 1] = stack
}
}
stacks
}
val moves = movesInput.split("\n")
.filter { it.isNotBlank() }
.map { line ->
val matches = """move (\d+) from (\d+) to (\d+)""".toRegex().matchEntire(line)
val (count, from, to) = matches!!.destructured
CrateMove(count.toInt(), from.toInt(), to.toInt())
}
return CrateState(stacks, moves)
}
}
}
| 0 | Kotlin | 0 | 0 | 1407ca85490366645ae3ec86cfeeab25cbb4c585 | 2,613 | advent2022 | MIT License |
src/Day05.kt | Feketerig | 571,677,145 | false | {"Kotlin": 14818} | import java.util.InputMismatchException
fun main(){
data class Move(val count: Int, val from: Int, val to: Int)
fun parse(input: List<String>): Pair<List<MutableList<Char>>, List<Move>>{
val emptyLineIndex = input.indexOfFirst { line -> line.isBlank() }
val numberOfStacks = input[emptyLineIndex - 1].last().digitToInt()
val crates = List(size = numberOfStacks){ mutableListOf<Char>() }
input.subList(0, emptyLineIndex - 1).asReversed().forEach { line ->
line.chunked(4).forEachIndexed { index, content ->
content[1].takeIf(Char::isLetter)?.let(crates[index]::plusAssign)
}
}
val moves = input.subList(emptyLineIndex + 1, input.size)
.map {
val split = it.split(" ")
Move(split[1].toInt(), split[3].toInt() - 1, split[5].toInt() - 1)
}
return Pair(crates, moves)
}
fun part1(input: List<String>): String{
val (crates, moves) = parse(input)
moves.forEach { move ->
repeat(move.count) {
crates[move.to] += crates[move.from].removeLast()
}
}
return crates.map { it.last() }.joinToString("")
}
fun part2(input: List<String>): String{
val (crates, moves) = parse(input)
moves.forEach { move ->
val moveObject = crates[move.from].subList(crates[move.from].size - move.count, crates[move.from].size)
crates[move.to] += moveObject
for (i in 0 until move.count) {
crates[move.from].removeLast()
}
}
return crates.map { it.last() }.joinToString("")
}
val testInput = readInput("Day05_test_input")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("Day05_input")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | c65e4022120610d930293788d9584d20b81bc4d7 | 1,921 | Advent-of-Code-2022 | Apache License 2.0 |
src/main/kotlin/com/simiacryptus/util/index/FindCompressionPrefixes.kt | SimiaCryptus | 737,271,270 | false | {"Kotlin": 55470} | package com.simiacryptus.util.index
import com.simiacryptus.util.files.XElements
import com.simiacryptus.util.files.elements
import com.simiacryptus.util.files.until
import java.util.*
fun FileIndexer.findCompressionPrefixes(threshold: Int, count: Int): Array<Pair<String, Int>> {
val returnMap = TreeMap<String, Int>()
val map = TreeMap<String, TreeSet<XElements>>()
for (elementIndex in (0.elements until index.getLength())) {
val lastPtrIdx = if (elementIndex <= 0) null else index.get(elementIndex - 1).tokens
val currentIdx = index.get(elementIndex).tokens
val nextPtrIdx = if (elementIndex >= index.getLength() - 1) null else index.get(elementIndex + 1).tokens
val lastPtr = lastPtrIdx?.run { data.tokenIterator(this) }
val nextPtr = nextPtrIdx?.run { data.tokenIterator(this) }
val currentPtr = data.tokenIterator(currentIdx)
val commonPrefixA = FileIndexer.commonPrefix(lastPtr?.invoke(), currentPtr())
val commonPrefixB = FileIndexer.commonPrefix(currentPtr(), nextPtr?.invoke())
val longestCommonPrefix = if (commonPrefixA.length > commonPrefixB.length) commonPrefixA else commonPrefixB
map.keys.filter { !longestCommonPrefix.startsWith(it) }.toTypedArray().forEach { newPrefix ->
val size = map.remove(newPrefix)!!.size
val fitness = prefixFitness(newPrefix, size)
if (fitness > threshold) {
returnMap[newPrefix] = size
}
map.remove(newPrefix)
}
longestCommonPrefix.indices.forEach { j ->
val substring = longestCommonPrefix.substring(0, j)
map.getOrPut(substring) { TreeSet<XElements>() }.add(elementIndex)
}
}
map.keys.toTypedArray().forEach {
val size = map.remove(it)!!.size
val fitness = prefixFitness(it, size)
if (fitness > threshold) {
returnMap[it] = size
}
}
return collect(returnMap, count).toList().sortedBy { -prefixFitness(it.first, it.second) }.toTypedArray()
}
private fun prefixFitness(string: String, count: Int): Int {
val length = string.encodeToByteArray().size
return (count * length) - (count * 4) - length
}
private fun collect(map: TreeMap<String, Int>, count: Int): Map<String, Int> {
// Iteratively select the top fitness value, add it to the new map, and remove all overlapping entries
val returnMap = TreeMap<String, Int>()
while (map.isNotEmpty() && returnMap.size < count) {
val best = map.entries.maxByOrNull { prefixFitness(it.key, it.value) }!!
returnMap[best.key] = best.value
map.keys.filter { best.key.startsWith(it) || it.startsWith(best.key) }
.toTypedArray().forEach { newPrefix -> map.remove(newPrefix) }
}
return returnMap
} | 0 | Kotlin | 0 | 0 | 685824833817ea5aadd5ba21ccba91b71597adf5 | 2,652 | DataGnome | Apache License 2.0 |
src/Day22.kt | shepard8 | 573,449,602 | false | {"Kotlin": 73637} | enum class Direction { Right, Down, Left, Up }
enum class CellType { OutsideMap, Ground, Wall }
fun main() {
class Position(val row: Int, val column: Int, val direction: Direction): Comparable<Position> {
fun next(): Position {
return when (direction) {
Direction.Right -> Position(row, column + 1, direction)
Direction.Left -> Position(row, column - 1, direction)
Direction.Up -> Position(row - 1, column, direction)
Direction.Down -> Position(row + 1, column, direction)
}
}
override fun compareTo(other: Position): Int {
return (row - other.row) * 1000 + (column - other.column) * 4 + direction.ordinal - other.direction.ordinal
}
override fun toString(): String {
return "($row, $column, $direction)"
}
}
abstract class Map(inputLines: List<String>) {
val cells: List<List<CellType>> = inputLines.map { line ->
line.map { char ->
when (char) {
'.' -> CellType.Ground
'#' -> CellType.Wall
else -> CellType.OutsideMap
}
}
}
fun nextTile(position: Position): Position {
val trivialNext = position.next()
if (cellTypeAt(trivialNext) == CellType.OutsideMap) {
return warp(trivialNext)
}
return trivialNext
}
private fun cellTypeAt(position: Position): CellType {
return cells.getOrNull(position.row)?.getOrNull(position.column) ?: CellType.OutsideMap
}
abstract fun warp(position: Position): Position
fun isWall(position: Position): Boolean {
return cellTypeAt(position) == CellType.Wall
}
fun startingPosition(): Position {
return Position(0, cells[0].indexOfFirst { it != CellType.OutsideMap }, Direction.Right)
}
}
class Step1Map(inputLines: List<String>): Map(inputLines) {
override fun warp(position: Position): Position {
return when (position.direction) {
Direction.Right -> Position(position.row, cells[position.row].indexOfFirst { it != CellType.OutsideMap }, position.direction)
Direction.Left -> Position(position.row, cells[position.row].indexOfLast { it != CellType.OutsideMap }, position.direction)
Direction.Down -> Position(cells.indexOfFirst { (it.getOrNull(position.column) ?: CellType.OutsideMap) != CellType.OutsideMap }, position.column, position.direction)
Direction.Up -> Position(cells.indexOfLast { (it.getOrNull(position.column) ?: CellType.OutsideMap) != CellType.OutsideMap }, position.column, position.direction)
}
}
}
class Step2Map(inputLines: List<String>): Map(inputLines) {
val frontiers = sortedMapOf<Position, Position>()
init {
connect(makeFrontier(0, 2, Direction.Right), makeFrontier(2, 1, Direction.Right), true)
connect(makeFrontier(0, 2, Direction.Down), makeFrontier(1, 1, Direction.Right))
connect(makeFrontier(2, 1, Direction.Down), makeFrontier(3, 0, Direction.Right))
connect(makeFrontier(3, 0, Direction.Down), makeFrontier(0, 2, Direction.Up))
connect(makeFrontier(3, 0, Direction.Left), makeFrontier(0, 1, Direction.Up))
connect(makeFrontier(2, 0, Direction.Left), makeFrontier(0, 1, Direction.Left), true)
connect(makeFrontier(2, 0, Direction.Up), makeFrontier(1, 1, Direction.Left))
}
private fun connect(from: List<Position>, to: List<Position>, reversed: Boolean = false) {
from.zip(if (reversed) to.reversed() else to).forEach {
// println("${it.first} <-> ${it.second}")
frontiers[it.first] = it.second
frontiers[it.second] = it.first
}
}
private fun makeFrontier(squareRow: Int, squareColumn: Int, direction: Direction): List<Position> {
val startRow = squareRow * 50 + when (direction) {
Direction.Right -> 0
Direction.Left -> 0
Direction.Up -> -1
Direction.Down -> 50
}
val startColumn = squareColumn * 50 + when (direction) {
Direction.Right -> 50
Direction.Left -> -1
Direction.Up -> 0
Direction.Down -> 0
}
val deltaRow = if (direction in listOf(Direction.Left, Direction.Right)) 1 else 0
val deltaColumn = 1 - deltaRow
return (0 until 50).map {
Position(startRow + it * deltaRow, startColumn + it * deltaColumn, direction)
}
}
override fun warp(position: Position): Position {
val nextOppositePosition = frontiers[position]!!
val nextPosition = Position(nextOppositePosition.row, nextOppositePosition.column, Direction.values()[(nextOppositePosition.direction.ordinal + 2) % 4]).next()
println("Warping at $position --> $nextPosition.")
return nextPosition
}
}
class Player(val map: Map) {
var position: Position = map.startingPosition()
fun turnLeft() {
position = Position(position.row, position.column, Direction.values()[(position.direction.ordinal + 3) % 4])
}
fun turnRight() {
position = Position(position.row, position.column, Direction.values()[(position.direction.ordinal + 1) % 4])
}
fun moveForward(n: Int) {
for (i in 0 until n) {
if (!moveForward()) {
break
}
}
}
fun moveForward(): Boolean {
val nextPosition = map.nextTile(position)
if (map.isWall(nextPosition)) {
return false
}
position = nextPosition
return true
}
override fun toString(): String {
return "Player at (${position.row}, ${position.column}), facing ${position.direction}"
}
}
fun computeAnswer(player: Player, movesInput: String): Int {
val moves = movesInput.split(Regex("((?=L)|(?<=L)|(?=R)|(?<=R))"))
moves.forEach {
println("${player.position} / $it")
when (it) {
"L" -> player.turnLeft()
"R" -> player.turnRight()
else -> player.moveForward(it.toInt())
}
}
return 1000 * (player.position.row + 1) + 4 * (player.position.column + 1) + player.position.direction.ordinal
}
fun part1(input: List<String>): Int {
val mapInput = input.takeWhile { it.isNotEmpty() }
val movesInput = input.last()
val map = Step1Map(mapInput)
val player = Player(map)
return computeAnswer(player, movesInput)
}
fun part2(input: List<String>): Int {
val mapInput = input.takeWhile { it.isNotEmpty() }
val movesInput = input.last()
val map = Step2Map(mapInput)
val player = Player(map)
return computeAnswer(player, movesInput)
// return 42
}
val input = readInput("Day22")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 81382d722718efcffdda9b76df1a4ea4e1491b3c | 7,410 | aoc2022-kotlin | Apache License 2.0 |
src/Day23.kt | i-tatsenko | 575,595,840 | false | {"Kotlin": 90644} | import Direction23.*
private enum class Direction23 {
NORTH {
override fun safeZone(p: Point): List<Point> = safeRange(p.y) { y -> Point(p.x - 1, y) }
override fun move(p: Point): Point = Point(p.x - 1, p.y)
},
EAST {
override fun safeZone(p: Point): List<Point> = safeRange(p.x) { x -> Point(x, p.y + 1) }
override fun move(p: Point): Point = Point(p.x, p.y + 1)
},
WEST {
override fun safeZone(p: Point): List<Point> = safeRange(p.x) { x -> Point(x, p.y - 1) }
override fun move(p: Point): Point = Point(p.x, p.y - 1)
},
SOUTH {
override fun safeZone(p: Point): List<Point> = safeRange(p.y) { y -> Point(p.x + 1, y) }
override fun move(p: Point): Point = Point(p.x + 1, p.y)
};
abstract fun safeZone(p: Point): List<Point>
abstract fun move(p: Point): Point
fun safeRange(coord: Int, toPoint: (Int) -> Point): List<Point> = (coord - 1..coord + 1).map(toPoint)
}
private fun Point.shouldMove(others: Set<Point>): Boolean =
Direction23.values().flatMap { it.safeZone(this) }.any { others.contains(it) }
fun main() {
fun parseElves(input: List<String>): MutableSet<Point> {
val elves = mutableSetOf<Point>()
input.forEachIndexed { row, line ->
line.forEachIndexed { column, ch -> if (ch == '#') elves.add(Point(row, column)) }
}
return elves
}
fun MutableList<Direction23>.rotate() {
this.add(this.removeFirst())
}
fun part1(input: List<String>): Int {
val directions = mutableListOf(NORTH, SOUTH, WEST, EAST)
val elves = parseElves(input)
val proposedMoves = mutableMapOf<Point, MutableList<Point>>() //where by who
for (i in 1..10) {
proposedMoves.clear()
elves.filter { it.shouldMove(elves) }.forEach { elf ->
directions.firstOrNull { it.safeZone(elf).none { safe -> elves.contains(safe) } }
?.also { direction ->
proposedMoves.compute(direction.move(elf)) { _, presentList ->
if (presentList == null) mutableListOf(elf) else {
presentList.add(elf)
presentList
}
}
}
}
proposedMoves.forEach {
if (it.value.size == 1) {
elves.remove(it.value.first())
elves.add(it.key)
}
}
directions.rotate()
}
val minX = elves.minOf { it.x }
val minY = elves.minOf { it.y }
val maxX = elves.maxOf { it.x }
val maxY = elves.maxOf { it.y }
return (maxX - minX + 1) * (maxY - minY + 1) - elves.size
}
fun part2(input: List<String>): Int {
val directions = mutableListOf(NORTH, SOUTH, WEST, EAST)
val elves = parseElves(input)
val proposedMoves = mutableMapOf<Point, MutableList<Point>>() //where by who
for (i in 1..Int.MAX_VALUE) {
proposedMoves.clear()
elves.filter { it.shouldMove(elves) }.forEach { elf ->
directions.firstOrNull { it.safeZone(elf).none { safe -> elves.contains(safe) } }
?.also { direction ->
proposedMoves.compute(direction.move(elf)) { _, presentList ->
if (presentList == null) mutableListOf(elf) else {
presentList.add(elf)
presentList
}
}
}
}
var moved = false
proposedMoves.forEach {
if (it.value.size == 1) {
elves.remove(it.value.first())
elves.add(it.key)
moved = true
}
}
if (!moved) return i
directions.rotate()
}
return -1
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day23_test")
println(part1(testInput))
check(part1(testInput) == 110)
println(part2(testInput) )
check(part2(testInput) == 20)
val input = readInput("Day23")
println(part1(input))
check(part1(input) == 4075)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 0a9b360a5fb8052565728e03a665656d1e68c687 | 4,433 | advent-of-code-2022 | Apache License 2.0 |
EvoMaster/core/src/main/kotlin/org/evomaster/core/problem/util/StringSimilarityComparator.kt | mitchellolsthoorn | 364,836,402 | false | {"Java": 3999651, "JavaScript": 2621912, "Kotlin": 2157071, "TypeScript": 137702, "CSS": 94780, "HTML": 35418, "Less": 29035, "Python": 25019, "R": 20339, "ANTLR": 12520, "XSLT": 6892, "Shell": 5833, "TeX": 4838, "Dockerfile": 493} | package org.evomaster.core.problem.util
import java.util.ArrayList
/**
* created by manzh on 2019-08-31
*/
object StringSimilarityComparator {
const val SimilarityThreshold = 0.6
fun isSimilar(str1: String, str2: String, algorithm: SimilarityAlgorithm = SimilarityAlgorithm.Trigrams, threshold : Double = SimilarityThreshold) : Boolean{
return stringSimilarityScore(str1, str2, algorithm) >= threshold
}
/**
* TODO Man: need to improve
*/
fun stringSimilarityScore(str1 : String, str2 : String, algorithm : SimilarityAlgorithm =SimilarityAlgorithm.Trigrams): Double{
return when(algorithm){
SimilarityAlgorithm.Trigrams -> trigrams(bigram(str1.toLowerCase()), bigram(str2.toLowerCase()))
//else-> 0.0
}
}
private fun trigrams(bigram1: MutableList<CharArray>, bigram2 : MutableList<CharArray>) : Double{
val copy = ArrayList(bigram2)
var matches = 0
var i = bigram1.size
while (--i >= 0) {
val bigram = bigram1[i]
var j = copy.size
while (--j >= 0) {
val toMatch = copy[j]
if (bigram[0] == toMatch[0] && bigram[1] == toMatch[1]) {
copy.removeAt(j)
matches += 2
break
}
}
}
return matches.toDouble() / (bigram1.size + bigram2.size)
}
private fun bigram(input: String): MutableList<CharArray> {
val bigram = mutableListOf<CharArray>()
for (i in 0 until input.length - 1) {
val chars = CharArray(2)
chars[0] = input[i]
chars[1] = input[i + 1]
bigram.add(chars)
}
return bigram
}
}
enum class SimilarityAlgorithm{
Trigrams
}
| 0 | Java | 1 | 0 | 50e9fb327fe918cc64c6b5e30d0daa2d9d5d923f | 1,816 | ASE-Technical-2021-api-linkage-replication | MIT License |
archive/2022/Day07.kt | mathijs81 | 572,837,783 | false | {"Kotlin": 167658, "Python": 725, "Shell": 57} | private const val EXPECTED_1 = 95437L
private const val EXPECTED_2 = 24933642L
private class Day07(isTest: Boolean) : Solver(isTest) {
fun constructDirSizes(): Map<String, Long> {
val currentDir = mutableListOf<String>()
val sizeMap = mutableMapOf<String, Long>()
readAsLines().forEach { line ->
if (line.startsWith("$ cd ")) {
when (line) {
"$ cd /" -> {
currentDir.clear()
}
"$ cd .." -> {
currentDir.removeLast()
}
else -> {
currentDir.add(line.removePrefix("$ cd "))
}
}
} else if (line[0].isDigit()) {
val size = line.substringBefore(' ').toLong()
val dirCopy = currentDir.toMutableList()
while(true) {
val key = dirCopy.joinToString("/")
sizeMap[key] = size + (sizeMap[key] ?: 0L)
if (dirCopy.isEmpty()) {
break
}
dirCopy.removeLast()
}
}
}
return sizeMap
}
fun part1(): Any {
return constructDirSizes().values.filter { it <= 100000 }.sum()
}
fun part2(): Any {
val sizeMap = constructDirSizes()
val sizeNeeded = 30000000 - (70000000 - sizeMap[""]!!)
return sizeMap.values.filter { it >= sizeNeeded }.min()
}
}
fun main() {
val testInstance = Day07(true)
val instance = Day07(false)
testInstance.part1().let { check(it == EXPECTED_1) { "part1: $it != $EXPECTED_1" } }
println(instance.part1())
testInstance.part2().let { check(it == EXPECTED_2) { "part2: $it != $EXPECTED_2" } }
println(instance.part2())
}
| 0 | Kotlin | 0 | 2 | 92f2e803b83c3d9303d853b6c68291ac1568a2ba | 1,887 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/dev/bogwalk/batch5/Problem53.kt | bog-walk | 381,459,475 | false | null | package dev.bogwalk.batch5
import dev.bogwalk.util.combinatorics.binomialCoefficient
import java.math.BigInteger
/**
* Problem 53: Combinatoric Selections
*
* https://projecteuler.net/problem=53
*
* Goal: Count the values of C(n, r), for 1 <= n <= N, that are greater than K. Values do not
* have to be distinct.
*
* Constraints: 2 <= N <= 1000, 1 <= K <= 1e18
*
* Binomial Coefficient:
*
* C(n, r) = n! / r!(n - r)!, where r <= n.
*
* There are 10 combinations when 3 digits are chosen from 5 digits, with no repetition & order
* not mattering: C(5, 3) = 10. It is not until n = 23 that the amount of combinations first
* exceeds 1e6, namely C(23, 10) = 1_144_066.
*
* e.g.: N = 23, K = 1e6
* answer = 4
*/
class CombinatoricSelections {
/**
* Solution optimised based on the symmetry of Pascal's Triangle:
*
* - C(n, 0) = 1, C(n, 1) = n. k could be less than n, so must start r-loop at 1.
*
* - C(n, r) = C(n, n-r) & peaks for each row at the mid-point.
*
* - So if C(n, r) > k, then all C(n, x) for x in [r+1, n-r] will also be > k. Based on
* the incrementing row count (n + 1), this can be calculated as n - 2r + 1, so the rest of
* the row values do not need to be also calculated.
*
* - Starting from the bottom of the triangle & moving up, if no value in a row is greater
* than k, then no row (of lesser n) will have valid values & the outer loop can be broken.
*
* SPEED (WORSE) 476.40ms for N = 1e3, K = 1e3
*/
fun countLargeCombinatorics(num: Int, k: Long): Int {
val kBI = BigInteger.valueOf(k)
var n = num
var count = 0
nextN@while (n > 0) {
for (r in 1..n / 2) {
if (binomialCoefficient(n, r) > kBI) {
count += n - 2 * r + 1
n--
continue@nextN
}
}
break
}
return count
}
/**
* Solution improved by not depending on factorials to pre-compute the binomial coefficient;
* however, BigInteger is still necessary to assess the branch where the next nCr is
* potentially greater than [k], the latter of which can be as high as 1e18.
*
* Solution is still based on the symmetry of Pascal's Triangle & its rules as detailed in
* the solution above, with some additions:
*
* C(n, r-1) = C(n, r) * (n-r) / (r+1) and
*
* C(n-1, r) = C(n, r) * (n-r) / n
*
* - Movement through the triangle (bottom-up & only checking border values) mimics that
* in the above function, but C(n, r) values when moving right in a row or up a row are
* determined with these formulae, instead of factorials.
*
* - Starting from the bottom of the triangle & moving up, if the value of r is allowed to
* exceed its midline value, then it means no value > k was found and the outer loop can be
* broken.
*
* SPEED (BETTER) 3.42ms for N = 1e3, K = 1e3
*/
fun countLargeCombinatoricsImproved(num: Int, k: Long): Int {
val kBI = BigInteger.valueOf(k)
var count = BigInteger.ZERO
var n = num.toBigInteger()
// start at left-most border
var r = BigInteger.ZERO
var nCr = BigInteger.ONE
while (r <= n / BigInteger.TWO) {
val nextInRow = nCr * (n - r) / (r + BigInteger.ONE)
if (nextInRow > kBI) {
// count formula differs from previous solution above
// because r is 1 less than r in nextInRow
count += n - BigInteger.TWO * r - BigInteger.ONE
nCr = nCr * (n - r) / n
n--
} else {
r++
nCr = nextInRow
}
}
return count.intValueExact()
}
} | 0 | Kotlin | 0 | 0 | 62b33367e3d1e15f7ea872d151c3512f8c606ce7 | 3,892 | project-euler-kotlin | MIT License |
src/commonMain/kotlin/org/jetbrains/packagesearch/packageversionutils/normalization/VeryLenientDateTimeExtractor.kt | JetBrains | 498,634,573 | false | {"Kotlin": 44145} | package org.jetbrains.packagesearch.packageversionutils.normalization
import kotlinx.datetime.*
object VeryLenientDateTimeExtractor {
/**
* This list of patterns is sorted from longest to shortest. It's generated
* by combining these base patterns:
* * `yyyy/MM/dd_HH:mm:ss`
* * `yyyy/MM/dd_HH:mm`
* * `yyyy/MM_HH:mm:ss`
* * `yyyy/MM_HH:mm`
* * `yyyy/MM/dd`
* * `yyyy/MM`
*
* With different dividers:
* * Date dividers: `.`, `-`, `\[nothing]`
* * Time dividers: `.`, `-`, `\[nothing]`
* * Date/time separator: `.`, `-`, `'T'`,`\[nothing]`
*/
val basePatterns = sequenceOf(
"yyyy/MM/dd_HH:mm:ss",
"yyyy/MM/dd_HH:mm",
"yyyy/MM_HH:mm:ss",
"yyyy/MM_HH:mm",
"yyyy/MM/dd",
"yyyy/MM"
)
val dateDividers = sequenceOf(".", "-", "")
val timeDividers = sequenceOf(".", "-", "")
val dateTimeSeparators = sequenceOf(".", "-", "T", "")
val datePatterns = basePatterns.flatMap { basePattern ->
dateDividers.flatMap { dateDivider ->
timeDividers.flatMap { timeDivider ->
dateTimeSeparators.map { dateTimeSeparator ->
basePattern
.replace("/", dateDivider)
.replace("_", dateTimeSeparator)
.replace(":", timeDivider)
}
}
}
}
val formatters by lazy {
datePatterns.map { DateTimeFormatter(it) }.toList()
}
/**
* The current year. Note that this value can, potentially, get out of date
* if the JVM is started on year X and is still running when transitioning
* to year Y. To ensure we don't have such bugs we should always add in a
* certain "tolerance" when checking the year. We also assume the plugin will
* not be left running for more than a few months (we release IDE versions
* much more frequently than that), so having a 1-year tolerance should be
* enough. We also expect the device clock is not more than 1-year off from
* the real date, given one would have to go out of their way to make it so,
* and plenty of things will break.
*
* ...yes, famous last words.
*/
private val currentYear
get() = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()).year
fun extractTimestampLookingPrefixOrNull(versionName: String): String? = formatters
.mapNotNull { it.parseOrNull(versionName) }
.filter { it.year > currentYear + 1 }
.map { versionName.substring(0 until it.toString().length) }
.firstOrNull()
}
expect fun DateTimeFormatter(pattern: String) : DateTimeFormatter
expect class DateTimeFormatter {
fun parse(dateTimeString: String): LocalDateTime
fun parseOrNull(dateTimeString: String): LocalDateTime?
}
| 0 | Kotlin | 2 | 4 | 4a9cf732526a0cd177dbaadb786bd2e41903a33e | 2,881 | package-search-version-utils | Apache License 2.0 |
src/Day20.kt | kpilyugin | 572,573,503 | false | {"Kotlin": 60569} | fun main() {
class PLong(val value: Long) {
override fun toString() = value.toString()
}
fun solve(input: List<String>, key: Long, repeatMix: Int): Long {
val initial = input.map { PLong(it.toLong() * key) }
val n = initial.size
val mixed = initial.toMutableList()
repeat(repeatMix) {
for (pValue in initial) {
val idx = (pValue.value + mixed.indexOf(pValue)).mod(n - 1)
mixed.remove(pValue)
mixed.add(idx, pValue)
}
}
val zeros = initial.filter { it.value == 0L }
check(zeros.size == 1)
val idxZero = mixed.indexOf(zeros[0])
fun get(idx: Int): Long = mixed[(idx + idxZero) % n].value
return get(1000) + get(2000) + get(3000)
}
fun part1(input: List<String>) = solve(input, key = 1, repeatMix = 1)
fun part2(input: List<String>) = solve(input, key = 811589153, repeatMix = 10)
val testInput = readInputLines("Day20_test")
check(part1(testInput), 3L)
check(part2(testInput), 1623178306L)
val input = readInputLines("Day20")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 7f0cfc410c76b834a15275a7f6a164d887b2c316 | 1,184 | Advent-of-Code-2022 | Apache License 2.0 |
src/Day10.kt | punx120 | 573,421,386 | false | {"Kotlin": 30825} | import java.lang.StringBuilder
fun main() {
class Node(val length: Int, val arg: Int) {
var startCycle: Int = -1
}
fun parseInstructions(input: List<String>): ArrayDeque<Node> {
val instructions = ArrayDeque<Node>()
input.map { it.split(" ") }
.map { instructions.add(Node(if (it[0] == "noop") 1 else 2,
if (it.size > 1) it[1].toInt() else 0))
}
return instructions
}
fun part1(instructions: ArrayDeque<Node>): Int {
var strength = 0
var cycle = 1
var register = 1
val crt = Array(6) { _ -> StringBuilder(" ".repeat(40)) }
while (!instructions.isEmpty()) {
val n = instructions.first()
if (n.startCycle == -1) {
n.startCycle = cycle
}
val col = (cycle -1) % 40
val line = crt[(cycle -1) / 40]
line[col] = if (col >= register -1 && col <= register +1) '#' else '.'
if (cycle == 20 || (cycle - 20) % 40 == 0) {
strength += cycle * register
}
++cycle
if (cycle - n.startCycle == n.length) {
register += n.arg
instructions.removeFirst()
}
}
for (l in crt) {
println(l)
}
return strength
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day10_test2")
println(part1(parseInstructions(testInput)))
val input = readInput("Day10")
println(part1(parseInstructions(input)))
}
| 0 | Kotlin | 0 | 0 | eda0e2d6455dd8daa58ffc7292fc41d7411e1693 | 1,653 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/Main.kt | NicLeenknegt | 342,582,751 | false | null | import java.io.File
data class Matrix(
val matrix:Array<ArrayList<String>>,
var row:Int = 0,
var column:Int = 0
)
fun main(args: Array<String>) {
var words:Array<String> = splitStringByDelimiter(readFile("./input.txt"), "\n")
printStringArray(words)
var maxWordLength = words.map{ it:String -> it.length }.max() ?: 0
var maxWord = words.maxBy{ it:String -> it.length }
println(maxWordLength)
println(maxWord)
var wordMatrix: Array<ArrayList<String>> = Array<ArrayList<String>>(maxWordLength) { arrayListOf() }
//Counting sort
for (word in words) {
wordMatrix[word.length-1].add(word)
}
for (array in wordMatrix) {
println("ARRAY")
for (word in array) {
println(word)
}
}
var wordMatrixClass:Matrix = Matrix(wordMatrix)
}
fun readFile(filename:String):String = File(filename).inputStream().readBytes().toString(Charsets.UTF_8)
fun splitStringByDelimiter(input:String, delimiter:String):Array<String> = input.split(delimiter).map { it -> it.trim()}.dropLast(1).toTypedArray()
fun printStringArray(stringArray:Array<String>) {
for (string in stringArray) {
println(string)
}
}
fun isSolutionValid(wordLength:Int, solutionLength:Int, solutionWord:String, referenceWord:String):Boolean = ((wordLength + solutionLength) <= referenceWord.length ) && referenceWord.startsWith(solutionWord)
fun isSolutionComplete(referenceWord:String, solutionWord:String):Boolean = referenceWord == solutionWord
fun buildMatchingWordArrayRec(wordMatrix:Matrix, solutionArrayList:ArrayList<String>, solutionLength:Int, solutionCalculation:String, solutionWord:String, referenceWord:String) {
if (!isSolutionValid(wordMatrix.row, solutionLength, solutionWord, referenceWord)) {
return
}
if (isSolutionComplete(referenceWord, solutionWord)) {
println(solutionWord)
solutionArrayList.add(solutionWord)
}
while (wordMatrix.row < wordMatrix.matrix.size) {
while(wordMatrix.column < wordMatrix.matrix[wordMatrix.row].size) {
//Add current word to word solution
solutionWord.plus(wordMatrix.matrix[wordMatrix.row][wordMatrix.column])
//solutionLength is now equal to the original length + matrixRow
buildMatchingWordArrayRec(wordMatrix, solutionArrayList, solutionLength + wordMatrix.row, solutionCalculation, solutionWord, referenceWord)
wordMatrix.column + 1
}
wordMatrix.row + 1
wordMatrix.column = 0
}
}
| 0 | Kotlin | 0 | 0 | 11081ceafa98be1453f31249b88268a47de2b6e8 | 2,559 | kenze_exercise | Creative Commons Zero v1.0 Universal |
src/main/kotlin/dev/shtanko/algorithms/leetcode/RangeSumOfBinarySearchTreeIterative.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2020 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import java.util.Stack
/**
* 938. Range Sum of BST
* @see <a href="https://leetcode.com/problems/range-sum-of-bst">Source</a>
*/
fun interface RangeSumOfBinarySearchTree {
operator fun invoke(root: TreeNode?, left: Int, right: Int): Int
}
class RangeSumOfBinarySearchTreeIterative : RangeSumOfBinarySearchTree {
override operator fun invoke(root: TreeNode?, left: Int, right: Int): Int {
var ans = 0
val stack: Stack<TreeNode> = Stack()
stack.push(root)
while (stack.isNotEmpty()) {
val node: TreeNode? = stack.pop()
if (node != null) {
if (node.value in left..right) ans += node.value
if (left < node.value) stack.push(node.left)
if (node.value < right) stack.push(node.right)
}
}
return ans
}
}
class RangeSumOfBinarySearchTreeRecursive : RangeSumOfBinarySearchTree {
override operator fun invoke(root: TreeNode?, left: Int, right: Int): Int {
return rangeSumBSTRecursive(root, left, right)
}
private fun rangeSumBSTRecursive(root: TreeNode?, left: Int, right: Int): Int {
return dfs(root, left, right, 0)
}
private fun dfs(node: TreeNode?, left: Int, right: Int, a: Int): Int {
var ans = a
if (node != null) {
if (node.value in left..right) ans += node.value
if (left < node.value) ans = dfs(node.left, left, right, ans)
if (node.value < right) ans = dfs(node.right, left, right, ans)
}
return ans
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,207 | kotlab | Apache License 2.0 |
src/Day06.kt | GreyWolf2020 | 573,580,087 | false | {"Kotlin": 32400} | fun main() {
fun part1(signal: String, n: Int = 4): Int = firstNUniqueCharacters(signal = signal, n = n)
fun part2(signal: String, n: Int = 14): Int = firstNUniqueCharacters(signal = signal, n = n)
// test if implementation meets criteria from the description, like:
// table test of part1
// val testInput01 = readInput("Day06_test_part01")
// val testInput01Solutions = listOf<Int>(7, 5, 6, 10, 11)
// testInput01
// .zip(testInput01Solutions)
// .map {
// check(part1(it.first) == it.second)
// }
//
// // table test of part2
// val testInput02 = readInput("Day06_test_part02")
// val testInput02Solutions = listOf<Int>(19, 23, 23, 29, 26)
// testInput02
// .zip(testInput02Solutions)
// .map {
// check(part2(it.first) == it.second)
// }
//
// val input = readInputAsString("Day06")
// println(part1(input))
// println(part2(input))
}
fun firstNUniqueCharacters(signal: String, n: Int): Int {
val possiblePacketMarkers = signal.windowed(n)
.map { it.toSet() }
var lastPositionOfMarker = n
for (possiblePacketMarker in possiblePacketMarkers) {
if (possiblePacketMarker.size == n) {
break
}
lastPositionOfMarker++
}
return lastPositionOfMarker
}
| 0 | Kotlin | 0 | 0 | 498da8861d88f588bfef0831c26c458467564c59 | 1,325 | aoc-2022-in-kotlin | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/DistantBarcodes.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import java.util.PriorityQueue
/**
* 1054. Distant Barcodes
* @see <a href="https://leetcode.com/problems/distant-barcodes/">Source</a>
*/
fun interface DistantBarcodes {
fun rearrangeBarcodes(barcodes: IntArray): IntArray
}
class DistantBarcodesMap : DistantBarcodes {
override fun rearrangeBarcodes(barcodes: IntArray): IntArray {
val cnt: MutableMap<Int, Int> = HashMap()
for (i in barcodes) {
cnt[i] = cnt.getOrDefault(i, 0) + 1
}
val list: List<Map.Entry<Int, Int>> = ArrayList<Map.Entry<Int, Int>>(cnt.entries).sortedWith(
java.util.Map.Entry.comparingByValue<Int, Int>().reversed(),
)
val l: Int = barcodes.size
var i = 0
val res = IntArray(l)
for (e in list) {
var time = e.value
while (time-- > 0) {
res[i] = e.key
i += 2
if (i >= barcodes.size) i = 1
}
}
return res
}
}
class DistantBarcodesQueue : DistantBarcodes {
override fun rearrangeBarcodes(barcodes: IntArray): IntArray {
val ct: MutableMap<Int, Int> = HashMap()
val pq = PriorityQueue { a: Int, b: Int ->
ct.getOrDefault(b, 0) - ct.getOrDefault(a, 0)
}
for (b in barcodes) {
ct[b] = ct.getOrDefault(b, 0) + 1
}
for (k in ct.keys) {
pq.add(k)
}
var pos = 0
while (pq.isNotEmpty()) {
val el = pq.poll()
val count = ct.getOrDefault(el, 0)
var i = 0
while (i < count) {
if (pos >= barcodes.size) pos = 1
barcodes[pos] = el
i++
pos += 2
}
}
return barcodes
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,441 | kotlab | Apache License 2.0 |
src/main/kotlin/day9.kt | p88h | 317,362,882 | false | null | fun part1(nums: List<Long>): Long {
var sums = HashMap<Long, Long>()
for (a in nums.indices) {
val b = a - 25
if (b >= 0 && nums[a] !in sums) {
println(nums[a])
return nums[a]
}
for (c in b + 1 until a) {
if (b >= 0) {
// remove (b+c)
val s1 = nums[b] + nums[c]
sums.merge(s1, -1, Long::plus)
// cleanup
if (sums.getValue(s1) == 0L) {
sums.remove(s1)
}
}
if (c >= 0) {
// add (c+a)
val s2 = nums[c] + nums[a]
sums.merge(s2, 1, Long::plus)
}
}
}
return 0L
}
fun part2(nums: List<Long>, q: Long): Long {
var tot = 0L
var i = 0
for (j in nums.indices) {
tot += nums[j]
while (i <= j && tot > q) {
tot -= nums[i]
i += 1
}
if (tot == q) {
val found = nums.subList(i, j)
return found.minOrNull()!! + found.maxOrNull()!!
}
}
return 0L
}
fun main(args: Array<String>) {
val nums = allLines(args, "day9.in").map { it.toLong() }.toList()
println(part2(nums, part1(nums)))
} | 0 | Kotlin | 0 | 5 | 846ad4a978823563b2910c743056d44552a4b172 | 1,273 | aoc2020 | The Unlicense |
classroom/src/main/kotlin/com/radix2/algorithms/week3/CountingInversionsV1.kt | rupeshsasne | 190,130,318 | false | {"Java": 66279, "Kotlin": 50290} | package com.radix2.algorithms.week3
fun sort(array: Array<Int>): Long {
return sort(array, Array(array.size) { 0 }, 0, array.size - 1)
}
fun sort(array: Array<Int>, aux: Array<Int>, lo: Int, hi: Int): Long {
if (lo >= hi) return 0
val mid = lo + (hi - lo) / 2
var inversions: Long
inversions = sort(array, aux, lo, mid)
inversions += sort(array, aux, mid + 1, hi)
return inversions + merge(array, aux, lo, mid, hi)
}
fun merge(array: Array<Int>, aux: Array<Int>, lo: Int, mid: Int, hi: Int): Long {
var i = lo
var j = mid + 1
val nextToMid = j
var k = lo
var inversions = 0L
while(i <= mid && j <= hi) {
if (array[i] <= array[j]) {
aux[k++] = array[i++]
} else {
aux[k++] = array[j++]
inversions += nextToMid - i
}
}
while(i <= mid)
aux[k++] = array[i++]
while(j <= hi)
aux[k++] = array[j++]
System.arraycopy(aux, lo, array, lo, (hi - lo) + 1)
return inversions
}
fun main(args: Array<String>) {
val array = arrayOf(7, 5, 3, 1)
val inversions = sort(array)
println(array.joinToString())
println(inversions)
}
| 0 | Java | 0 | 1 | 341634c0da22e578d36f6b5c5f87443ba6e6b7bc | 1,190 | coursera-algorithms-part1 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/GraphConnectivityWithThreshold.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
/**
* 1627. Graph Connectivity With Threshold
* @see <a href="https://leetcode.com/problems/graph-connectivity-with-threshold/">Source</a>
*/
fun interface GraphConnectivityWithThreshold {
fun areConnected(n: Int, threshold: Int, queries: Array<IntArray>): List<Boolean>
}
class GraphConnectivityWithThresholdUnion : GraphConnectivityWithThreshold {
override fun areConnected(n: Int, threshold: Int, queries: Array<IntArray>): List<Boolean> {
val uf = UnionFind(n + 1)
for (z in threshold + 1..n) {
var x = z * 2
while (x <= n) {
uf.union(z, x)
x += z
}
}
val ans: MutableList<Boolean> = ArrayList()
for (q in queries) {
ans.add(uf.find(q[0]) == uf.find(q[1]))
}
return ans
}
// Feel free to copy this class for later reuse!
class UnionFind(n: Int) {
var parent: IntArray
var size: IntArray
init {
parent = IntArray(n)
size = IntArray(n)
for (i in 0 until n) {
parent[i] = i
size[i] = 1
}
}
fun find(x: Int): Int {
return if (x == parent[x]) {
x
} else {
find(parent[x]).also {
parent[x] = it // Path compression
}
}
}
fun union(u: Int, v: Int): Boolean {
val pu = find(u)
val pv = find(v)
if (pu == pv) return false
if (size[pu] > size[pv]) { // Union by larger size
size[pu] += size[pv]
parent[pv] = pu
} else {
size[pv] += size[pu]
parent[pu] = pv
}
return true
}
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,478 | kotlab | Apache License 2.0 |
src/main/aoc2022/Day13.kt | nibarius | 154,152,607 | false | {"Kotlin": 963896} | package aoc2022
import java.util.*
class Day13(input: List<String>) {
sealed class Entry {
data class Value(val value: Int) : Entry()
data class AList(val list: MutableList<Entry> = mutableListOf()) : Entry()
}
private val packetPairs = input
.map { rawPairs ->
rawPairs.split("\n")
.let { parse(it.first()) to parse(it.last()) }
}
private val allPackets = input.let { it + "[[2]]\n[[6]]" }
.flatMap { group -> group.split("\n").map { line -> parse(line) } }
private fun parse(raw: String): Entry {
val stack = Stack<Entry.AList>()
val root = Entry.AList()
var curr: Entry.AList = root
var number = ""
fun finishNumberIfNeeded() {
if (number.isNotEmpty()) {
curr.list.add(Entry.Value(number.toInt()))
number = ""
}
}
// Drop the outermost [ and ] since the root entry is an Entry from the start
for (token in raw.drop(1).dropLast(1)) {
when (token) {
'[' -> {
// Start of a new list, save the current item on the stack and continue with the child
val child = Entry.AList()
curr.list.add(child)
stack.push(curr)
curr = child
}
']' -> {
// List ends, continue processing the parent
finishNumberIfNeeded()
curr = stack.pop()
}
',' -> finishNumberIfNeeded()
else -> number += token
}
}
finishNumberIfNeeded()
return root
}
private fun compareValues(left: Int, right: Int): Boolean? {
return when {
left < right -> true
left > right -> false
else -> null
}
}
private fun isInOrder(left: Entry, right: Entry): Boolean? {
return when {
left is Entry.Value && right is Entry.Value -> compareValues(left.value, right.value)
left is Entry.Value -> isInOrder(Entry.AList(mutableListOf(left)), right)
right is Entry.Value -> isInOrder(left, Entry.AList(mutableListOf(right)))
left is Entry.AList && right is Entry.AList -> {
for ((l, r) in left.list zip right.list) {
val res = isInOrder(l, r)
if (res != null) {
return res
}
}
when {
left.list.size < right.list.size -> true
left.list.size > right.list.size -> false
else -> null
}
}
else -> error("not reachable")
}
}
fun solvePart1(): Int {
return packetPairs.map { isInOrder(it.first, it.second) }
.mapIndexedNotNull { index, b -> if (b!!) index + 1 else null }
.sum()
}
fun solvePart2(): Int {
val ordered = allPackets.sortedWith { a, b ->
when (isInOrder(a, b)) {
true -> -1
false -> 1
else -> 0
}
}
val two = parse("[[2]]")
val six = parse("[[6]]")
val filtered = ordered.withIndex().mapNotNull { (index, value) ->
if (value == two || value == six) index + 1 else null
}
return filtered.reduce(Int::times)
}
} | 0 | Kotlin | 0 | 6 | f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22 | 3,537 | aoc | MIT License |
src/Day02.kt | mrwhoknows55 | 573,993,349 | false | {"Kotlin": 4863} | import java.io.File
fun main() {
val input = File("src/day02_input.txt").readText().split("\n")
println(part1(input))
println(part2(input))
}
fun part1(input: List<String>): Int {
var score = 0
input.forEach {
val oppMove = Move.getMoveObj(it[0]) ?: return@part1 (score)
val myMove = Move.getMoveObj(it[2]) ?: return@part1 (score)
score += myMove.score
when {
myMove.winsTo == oppMove.score -> score += 6
myMove.score == oppMove.score -> score += 3
myMove.losesTo == oppMove.score -> score += 0
}
}
return score
}
fun part2(input: List<String>): Int {
var score = 0
input.forEach {
val oppMove = Move.getMoveObj(it[0]) ?: return@part2 (score)
val myMove = Move.getMoveObj(it[2]) ?: return@part2 (score)
when (myMove) {
is Move.Rock -> {
score += oppMove.winsTo
score += 0
}
is Move.Paper -> {
score += oppMove.score
score += 3
}
is Move.Scissors -> {
score += oppMove.losesTo
score += 6
}
}
}
return score
}
sealed class Move(
val score: Int,
val winsTo: Int,
val losesTo: Int,
) {
object Rock : Move(1, 3, 2)
object Paper : Move(2, 1, 3)
object Scissors : Move(3, 2, 1)
companion object {
fun getMoveObj(moveChar: Char): Move? {
return when (moveChar) {
'A' -> Rock
'X' -> Rock
'B' -> Paper
'Y' -> Paper
'C' -> Scissors
'Z' -> Scissors
else -> null
}
}
}
}
| 0 | Kotlin | 0 | 1 | f307e524412a3ed27acb93b7b9aa6aa7269a6d03 | 1,770 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/com/hj/leetcode/kotlin/problem1913/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem1913
import kotlin.math.max
import kotlin.math.min
/**
* LeetCode page: [1913. Maximum Product Difference Between Two Pairs](https://leetcode.com/problems/maximum-product-difference-between-two-pairs/);
*/
class Solution {
/* Complexity:
* Time O(N) and Space O(1) where N is the size of nums;
*/
fun maxProductDifference(nums: IntArray): Int {
val (largest, secondLargest) = findTwoLargest(nums)
val (smallest, secondSmallest) = findTwoSmallest(nums)
return largest * secondLargest - smallest * secondSmallest
}
private fun findTwoLargest(nums: IntArray): Pair<Int, Int> {
var largest = max(nums[0], nums[1])
var secondLargest = min(nums[0], nums[1])
for (index in 2..<nums.size) {
when {
largest < nums[index] -> {
secondLargest = largest
largest = nums[index]
}
secondLargest < nums[index] -> {
secondLargest = nums[index]
}
}
}
return largest to secondLargest
}
private fun findTwoSmallest(nums: IntArray): Pair<Int, Int> {
var smallest = min(nums[0], nums[1])
var secondSmallest = max(nums[0], nums[1])
for (index in 2..<nums.size) {
when {
nums[index] < smallest -> {
secondSmallest = smallest
smallest = nums[index]
}
nums[index] < secondSmallest -> {
secondSmallest = nums[index]
}
}
}
return smallest to secondSmallest
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 1,715 | hj-leetcode-kotlin | Apache License 2.0 |
src/easy/_14LongestCommonPrefix.kt | ilinqh | 390,190,883 | false | {"Kotlin": 382147, "Java": 32712} | package easy
import kotlin.math.min
/**
* 数据量不大的前提下,用双层 for 循环更加高效
*/
class _14LongestCommonPrefix {
class Solution {
private lateinit var strList: Array<String>
fun longestCommonPrefix(strs: Array<String>): String {
if (strs.isEmpty()) {
return ""
}
strList = strs
return searchCommonPrefix(0, strList.size - 1)
}
private fun searchCommonPrefix(left: Int, right: Int): String {
if (left >= right) {
return strList[left]
}
val middle = left + (right - left) / 2
val lSub = searchCommonPrefix(left, middle)
val rSub = searchCommonPrefix(middle + 1, right)
val minLength = min(lSub.length, rSub.length)
if (minLength == 0) {
return ""
}
val sb = StringBuffer()
for (i in 0 until minLength) {
if (lSub[i] == rSub[i]) {
sb.append(lSub[i])
} else {
break
}
}
return sb.toString()
}
}
// Beat
class BestSolution {
fun longestCommonPrefix(strs: Array<String>): String {
val str: String
if (strs.isNotEmpty()) {
str = strs[0]
} else {
return ""
}
var startString = ""
for (i in str.indices) {
startString = str.substring(0, i + 1)
for (s in strs) {
if (s.startsWith(startString)) {
continue
} else {
return startString.substring(0, i)
}
}
}
return startString
}
}
}
| 0 | Kotlin | 0 | 0 | 8d2060888123915d2ef2ade293e5b12c66fb3a3f | 1,892 | AlgorithmsProject | Apache License 2.0 |
src/Day07.kt | anilkishore | 573,688,256 | false | {"Kotlin": 27023} | class Dir(val par: Dir? = null, var size: Int = 0, val subDirs: HashMap<String, Dir> = hashMapOf())
fun main() {
var part2ans: Int = 7e7.toInt()
fun foldSizes(cur: Dir) {
for (subDir in cur.subDirs.values) {
foldSizes(subDir)
cur.size += subDir.size
}
}
fun findSum(cur: Dir, needSize: Int): Int {
if (cur.size >= needSize) {
part2ans = minOf(part2ans, cur.size)
}
var res = if (cur.size <= 100000) cur.size else 0
for (subDir in cur.subDirs.values) {
res += findSum(subDir, needSize)
}
return res
}
fun solve(commands: List<String>): Int {
val root = Dir()
var cur = root
for (cmd in commands.drop(1)) {
val strs = cmd.split(" ")
if (cmd.startsWith("$ ")) {
if (strs[1] == "cd") {
cur = (if (strs[2] == "..") cur.par else cur.subDirs[strs[2]])!!
}
} else {
if (cmd.startsWith("dir ")) {
cur.subDirs[strs[1]] = Dir(cur)
} else {
cur.size += strs[0].toInt()
}
}
}
foldSizes(root)
val needSize = (3e7 - (7e7 - root.size)).toInt()
return findSum(root, needSize)
}
val input = readInput("Day07")
println(solve(input))
println(part2ans)
} | 0 | Kotlin | 0 | 0 | f8f989fa400c2fac42a5eb3b0aa99d0c01bc08a9 | 1,435 | AOC-2022 | Apache License 2.0 |
kotlin/src/katas/kotlin/sort/mergesort/MergeSort4.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.sort.mergesort
import nonstdlib.listOfInts
import nonstdlib.permutations
import nonstdlib.printed
import datsok.shouldEqual
import org.junit.Test
import java.util.*
import kotlin.collections.ArrayList
import kotlin.random.Random
class MergeSort4Tests {
@Test fun `trivial examples`() {
emptyList<Int>().mergeSort() shouldEqual emptyList()
listOf(1).mergeSort() shouldEqual listOf(1)
}
@Test fun `sort list with two elements`() {
listOf(1, 2).mergeSort() shouldEqual listOf(1, 2)
listOf(2, 1).mergeSort() shouldEqual listOf(1, 2)
}
@Test fun `sort list with three elements`() {
listOf(1, 2, 3).mergeSort() shouldEqual listOf(1, 2, 3)
listOf(1, 3, 2).mergeSort() shouldEqual listOf(1, 2, 3)
listOf(2, 1, 3).mergeSort() shouldEqual listOf(1, 2, 3)
listOf(2, 3, 1).mergeSort() shouldEqual listOf(1, 2, 3)
}
@Test fun `sort list with four elements`() {
listOf(1, 2, 3, 4).permutations().forEach {
it.mergeSort() shouldEqual listOf(1, 2, 3, 4)
}
}
@Test fun `sort random list`() {
fun List<Int>.isSorted() = windowed(size = 2).all { it[0] <= it[1] }
val list = Random.listOfInts(
sizeRange = IntRange(0, 100),
valuesRange = IntRange(0, 100)
).printed()
val sortedList = list.mergeSort().printed()
sortedList.isSorted() shouldEqual true
sortedList.size shouldEqual list.size
}
private fun <E: Comparable<E>> List<E>.mergeSort(): List<E> {
fun merge(left: List<E>, right: List<E>): List<E> {
val result = ArrayList<E>()
var i = 0
var j = 0
while (i < left.size && j < right.size) {
result.add(if (left[i] < right[j]) left[i++] else right[j++])
}
while (i < left.size) result.add(left[i++])
while (j < right.size) result.add(right[j++])
return result
}
val queue = LinkedList<List<E>>()
queue.addAll(this.map { listOf(it) })
while (queue.size > 1) {
val list1 = queue.removeFirst()
val list2 = queue.removeFirst()
queue.add(merge(list1, list2))
}
return queue.firstOrNull() ?: emptyList()
}
private fun <E: Comparable<E>> List<E>.mergeSort_recursive(): List<E> {
fun merge(left: List<E>, right: List<E>): List<E> {
return when {
left.isEmpty() -> right
right.isEmpty() -> left
left[0] < right[0] -> listOf(left[0]) + merge(left.drop(1), right)
else -> listOf(right[0]) + merge(left, right.drop(1))
}
}
if (size <= 1) return this
val midIndex = size / 2
return merge(
left = subList(0, midIndex).mergeSort_recursive(),
right = subList(midIndex, size).mergeSort_recursive()
)
}
}
| 7 | Roff | 3 | 5 | 0f169804fae2984b1a78fc25da2d7157a8c7a7be | 3,009 | katas | The Unlicense |
p03/src/main/kotlin/NoMatterHowYouSliceIt.kt | jcavanagh | 159,918,838 | false | null | package p03
import common.file.readLines
inline fun <reified T> aggregateClaims(claims: List<Claim>, init: () -> T, delegate: (T, Claim) -> T): Array<Array<T>> {
val maxX = claims.maxBy { it.maxX }!!.maxX
val maxY = claims.maxBy { it.maxY }!!.maxY
val claimMap = Array(maxX) { Array(maxY) { init() } }
for(claim in claims) {
if(claim.dy <= 0 || claim.dx <= 0) continue
for(x in (claim.x)..(claim.maxX - 1)) {
for(y in (claim.y)..(claim.maxY - 1)) {
claimMap[x][y] = delegate(claimMap[x][y], claim)
}
}
}
return claimMap
}
fun intersect(claims: List<Claim>): Int {
val claimMap = aggregateClaims(claims, { 0 }) { current, _ -> current + 1 }
return claimMap.map { row -> row.filter { it >= 2 }.size }.sum()
}
fun nonIntersect(claims: List<Claim>): List<Claim> {
val claimMap = aggregateClaims(claims, { mutableListOf<Claim>() }) { current, claim -> current.add(claim); current }
val intersectingClaims = mutableSetOf<Claim>()
claimMap.forEach { row ->
row.forEach { claims ->
if (claims.size > 1) {
intersectingClaims.addAll(claims)
}
}
}
return claims.minus(intersectingClaims)
}
fun main() {
val claims = readLines("input.txt").map { Claim(it) }
println("Intersecting claims: ${intersect(claims)}")
println("Non-intersecting claims: ${nonIntersect(claims).map { it.id }}")
} | 0 | Kotlin | 0 | 0 | 289511d067492de1ad0ceb7aa91d0ef7b07163c0 | 1,380 | advent2018 | MIT License |
src/Day11.kt | risboo6909 | 572,912,116 | false | {"Kotlin": 66075} | var M = 1.toULong()
data class Monkey(var items: ArrayDeque<ULong>, var op: ((ULong) -> ULong)?, var test: ((ULong) -> Int)?, var inspect: ULong,
private val useModulo: Boolean) {
constructor(useModulo: Boolean) : this(ArrayDeque<ULong>(), null, null, 0.toULong(), useModulo)
}
fun main() {
fun parse(input: List<String>, useModulo: Boolean): List<Monkey> {
val res: MutableList<Monkey> = mutableListOf()
val it = input.listIterator()
while (it.hasNext()) {
val line = it.next()
if (line.startsWith("Monkey")) {
res.add(Monkey(useModulo))
continue
}
if (line.startsWith(" Starting items:")) {
val (_, itemsAsStr) = line.split(": ")
res.last().items.addAll(itemsAsStr.split(", ").map{it.toULong()})
} else if (line.startsWith(" Operation:")) {
val (_, whatToDo) = line.split(": ")
if (whatToDo.split("*").size == 2) {
val (_, n) = whatToDo.split(" * ")
if (useModulo) {
if (n == "old") {
res.last().op = { x -> (x % M * x % M) % M }
} else {
res.last().op = { x -> (x % M * n.toULong()) % M }
}
} else {
if (n == "old") {
res.last().op = { x -> (x * x) }
} else {
res.last().op = { x -> (x * n.toULong()) }
}
}
} else if (whatToDo.split("+").size == 2) {
val (_, n) = whatToDo.split(" + ")
if (useModulo) {
if (n == "old") {
res.last().op = { x -> (x % M + x % M) % M }
} else {
res.last().op = { x -> (x % M + n.toULong()) % M }
}
} else {
if (n == "old") {
res.last().op = { x -> (x + x) }
} else {
res.last().op = { x -> (x + n.toULong()) }
}
}
}
} else if (line.startsWith(" Test:")) {
val (_, whatToDo) = line.split(": ")
val (_, _, n) = whatToDo.split(" ")
M *= n.toULong()
val posCond = it.next().filter{ it.isDigit() }.toInt()
val negCond = it.next().filter{ it.isDigit() }.toInt()
res.last().test = {x -> if (x % n.toULong() == 0.toULong()) posCond else negCond}
}
}
return res
}
fun compute(input: List<String>, iterations: Int, divideBy: ULong, useModulo: Boolean): ULong {
M = 1.toULong()
val monkeys = parse(input, useModulo)
for (iter in 0 until iterations) {
for (monkey in monkeys) {
while (monkey.items.size > 0) {
val new = (monkey.op!!(monkey.items.removeFirst()) / divideBy)
val toMonkey = monkey.test!!(new)
monkey.inspect++
monkeys[toMonkey].items.addLast(new)
}
}
}
return monkeys.sortedByDescending { it.inspect }.slice((0..1)).map{it.inspect}.reduce { a, b -> a * b }
}
fun part1(input: List<String>): ULong {
return compute(input, 20, 3.toULong(), false)
}
fun part2(input: List<String>): ULong {
return compute(input, 10000, 1.toULong(), true)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day11_test")
check(part1(testInput) == 10605.toULong())
check(part2(testInput) == 2713310158.toULong())
val input = readInput("Day11")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | bd6f9b46d109a34978e92ab56287e94cc3e1c945 | 4,062 | aoc2022 | Apache License 2.0 |
2022/src/day10/day10.kt | Bridouille | 433,940,923 | false | {"Kotlin": 171124, "Go": 37047} | package day10
import GREEN
import RESET
import printTimeMillis
import readInput
// Hey fab
// returns a map of {cycle -> X register}
fun computeInstructions(input: List<String>): Map<Int, Int> {
var xRegister = 1
var cycle = 1
val memory = mutableMapOf(1 to 1)
input.forEach {
if (it == "noop") {
cycle++
memory[cycle] = xRegister
} else {
memory[cycle + 1] = xRegister
cycle += 2
xRegister += it.split(" ").last().toInt()
memory[cycle] = xRegister
}
}
return memory
}
fun part1(input: List<String>): Int {
val memory = computeInstructions(input)
return (20..220 step(40)).fold(0) { acc, value ->
acc + (value * memory[value]!!)
}
}
// if cycle == xRegister+/-1 = we draw at position cycle on an horizontal line
fun part2(input: List<String>): String {
val memory = computeInstructions(input)
memory.keys.forEach { cycle ->
val xReg = memory[cycle]!!
val letter = if (setOf(xReg - 1, xReg, xReg + 1).contains((cycle - 1) % 40)) '#' else '.'
print(letter)
if (cycle % 40 == 0) println()
}
return "Read output :)"
}
fun main() {
val testInput = readInput("day10_example.txt")
printTimeMillis { print("part1 example = $GREEN" + part1(testInput) + RESET) }
printTimeMillis { print("part2 example = $GREEN" + part2(testInput) + RESET) }
val input = readInput("day10.txt")
printTimeMillis { print("part1 input = $GREEN" + part1(input) + RESET) }
printTimeMillis { print("part2 input = $GREEN" + part2(input) + RESET) }
}
| 0 | Kotlin | 0 | 2 | 8ccdcce24cecca6e1d90c500423607d411c9fee2 | 1,635 | advent-of-code | Apache License 2.0 |
src/main/kotlin/g2901_3000/s2920_maximum_points_after_collecting_coins_from_all_nodes/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g2901_3000.s2920_maximum_points_after_collecting_coins_from_all_nodes
// #Hard #Array #Dynamic_Programming #Depth_First_Search #Tree #Bit_Manipulation
// #2023_12_31_Time_2255_ms_(25.00%)_Space_112.1_MB_(100.00%)
import kotlin.math.max
class Solution {
private lateinit var adjList: Array<MutableList<Int>>
private lateinit var coins: IntArray
private var k = 0
private lateinit var dp: Array<IntArray>
private fun init(edges: Array<IntArray>, coins: IntArray, k: Int) {
val n = coins.size
adjList = Array(n) { ArrayList() }
for (edge in edges) {
val u = edge[0]
val v = edge[1]
adjList[u].add(v)
adjList[v].add(u)
}
this.coins = coins
this.k = k
dp = Array(n) { IntArray(14) }
for (v in 0 until n) {
for (numOfWay2Parents in 0..13) {
dp[v][numOfWay2Parents] = -1
}
}
}
private fun rec(v: Int, p: Int, numOfWay2Parents: Int): Int {
if (numOfWay2Parents >= 14) {
return 0
}
if (dp[v][numOfWay2Parents] == -1) {
val coinsV = coins[v] / (1 shl numOfWay2Parents)
var s0 = coinsV - k
var s1 = coinsV / 2
for (child in adjList[v]) {
if (child != p) {
s0 += rec(child, v, numOfWay2Parents)
s1 += rec(child, v, numOfWay2Parents + 1)
}
}
dp[v][numOfWay2Parents] = max(s0, s1)
}
return dp[v][numOfWay2Parents]
}
fun maximumPoints(edges: Array<IntArray>, coins: IntArray, k: Int): Int {
init(edges, coins, k)
return rec(0, -1, 0)
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,749 | LeetCode-in-Kotlin | MIT License |
kotlin/src/com/daily/algothrim/leetcode/medium/ThreeSum.kt | idisfkj | 291,855,545 | false | null | package com.daily.algothrim.leetcode.medium
/**
* 15. 三数之和
* 给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0 且不重复的三元组。
* 注意:答案中不可以包含重复的三元组。
*/
class ThreeSum {
companion object {
@JvmStatic
fun main(args: Array<String>) {
println(ThreeSum().threeSum(intArrayOf(-1, 0, 1, 2, -1, -4)))
println(ThreeSum().threeSum(intArrayOf(0, 0, 0)))
}
}
fun threeSum(nums: IntArray): List<List<Int>> {
// 排序
nums.sort()
val result = arrayListOf<List<Int>>()
val size = nums.size
var first = 0
while (first < size) {
// first > 0 的判断为了排除【0, 0, 0, 0, ..]的情况
if (first > 0 && nums[first] == nums[first - 1]) { // 排除相同的值
first++
continue
}
var second = first + 1
while (second < size) {
// second > first + 1 的判断为了排除【0, 0, 0, 0, ..]的情况
if (second > first + 1 && nums[second] == nums[second - 1]) { // 排除相同的值
second++
continue
}
var third = size - 1
while (second < third && nums[first] + nums[second] > -nums[third]) { // 三数相加大于零,说明third过大,向前移动,减小third的值
third--
}
// second与third重合,相加一直大于零,说明当前first不存在相加等于零的情况
if (second == third) break
// 存在
if (nums[first] + nums[second] + nums[third] == 0) {
result.add(arrayListOf(nums[first], nums[second], nums[third]))
}
second++
}
first++
}
return result
}
} | 0 | Kotlin | 9 | 59 | 9de2b21d3bcd41cd03f0f7dd19136db93824a0fa | 2,049 | daily_algorithm | Apache License 2.0 |
src/nativeMain/kotlin/com.qiaoyuang.algorithm/round1/Questions46.kt | qiaoyuang | 100,944,213 | false | {"Kotlin": 338134} | package com.qiaoyuang.algorithm.round1
import kotlin.math.abs
fun test46() {
printlnResult(12258)
printlnResult(-12258)
printlnResult(1225825)
printlnResult(0)
printlnResult(-25262526)
}
/**
* Questions 46: Translate integer to string, 0-a, 1-b, 2-c...24-y, 25-z. Find the amount of kinds of translation.
*/
private fun Int.findCountOfTranslation(): Int =
abs(this).toString().findCountOfTranslation(0)
private fun String.findCountOfTranslation(index: Int): Int {
if (index == length)
return 1
val twoNumberCount = if (index + 1 < length && substring(index, index + 2).toInt() <= 25) findCountOfTranslation(index + 2) else 0
return findCountOfTranslation(index + 1) + twoNumberCount
}
private fun Int.findCountOfTranslationForLoop(): Int {
val str = abs(this).toString()
val counts = IntArray(str.length)
for (i in str.lastIndex downTo 0) {
var count = if (i < str.lastIndex)
counts[i + 1]
else
1
if (i < str.lastIndex) {
val digit1 = str[i].digitToInt()
val digit2 = str[i + 1].digitToInt()
val converted = digit1 * 10 + digit2
if (converted in 10..25)
count += if (i < str.length - 2) counts[i + 2] else 1
}
counts[i] = count
}
return counts.first()
}
private fun printlnResult(number: Int) =
println("The number $number has (${number.findCountOfTranslation()}, ${number.findCountOfTranslationForLoop()}) kinds of translation")
| 0 | Kotlin | 3 | 6 | 66d94b4a8fa307020d515d4d5d54a77c0bab6c4f | 1,536 | Algorithm | Apache License 2.0 |
src/day04/Day04.kt | TimberBro | 572,681,059 | false | {"Kotlin": 20536} | package day04
import readInput
import toInt
fun main() {
fun stringToPairs(it: String): Pair<IntRange, IntRange> {
val assignments = it.split(",")
val firstSplit = assignments[0].split("-")
val secondSplit = assignments[1].split("-")
return firstSplit[0].toInt()..firstSplit[1].toInt() to secondSplit[0].toInt()..secondSplit[1].toInt()
}
fun part1(input: List<String>): Int {
val result = input.stream()
.map {
stringToPairs(it)
}
.map {
it.first.toSet().containsAll(it.second.toSet()) ||
it.second.toSet().containsAll(it.first.toSet())
}.filter {
it == true
}.count()
return result.toInt()
}
fun part2(input: List<String>): Int {
val result = input.stream()
.map {
stringToPairs(it)
}
.map {
it.first.toSet().intersect(it.second.toSet()).isNotEmpty() ||
it.second.toSet().intersect(it.first.toSet()).isNotEmpty()
}.filter {
it == true
}.count()
return result.toInt()
}
val testInput = readInput("day04/Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("day04/Day04")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 516a98e5067d11f0e6ff73ae19f256d8c1bfa905 | 1,488 | AoC2022 | Apache License 2.0 |
src/Day10.kt | JanTie | 573,131,468 | false | {"Kotlin": 31854} | import kotlin.math.absoluteValue
fun main() {
fun parseInput(input: List<String>): List<Int> {
return input.map { it.split(" ") }
.flatMap {
when (it.first()) {
"noop" -> listOf(0)
"addx" -> listOf(0, it[1].toInt())
else -> emptyList()
}
}
.let { listOf(0) + it } // fix initial offset, as we only represent the result of a cycle
.let { list ->
var currentRegistrarValue = 1
list.map {
currentRegistrarValue += it
currentRegistrarValue
}
}
}
fun part1(input: List<String>): Int {
return parseInput(input)
.let { list -> (20 until list.size step 40).map { list[it - 1] * it } }
.sum()
}
fun part2(input: List<String>): Int {
parseInput(input)
.dropLast(1) // drop post-last, as we don't care about that
.chunked(40)
.map { ints ->
ints.mapIndexed { index, registrar -> (index - registrar).absoluteValue < 2 }
.joinToString("") { if (it) "#" else "." }
}
.onEach { line -> println(line) }
return 0
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day10_test")
val input = readInput("Day10")
check(part1(testInput) == 13140)
println(part1(input))
check(part2(testInput) == 0)
println()
part2(input)
} | 0 | Kotlin | 0 | 0 | 3452e167f7afe291960d41b6fe86d79fd821a545 | 1,601 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/com/colinodell/advent2022/Extensions.kt | colinodell | 572,710,708 | false | {"Kotlin": 105421} | package com.colinodell.advent2022
import kotlin.math.max
fun <T> Iterable<T>.chunkedBy(separator: (T) -> Boolean): List<List<T>> =
fold(mutableListOf(mutableListOf<T>())) { acc, t ->
if (separator(t)) {
acc.add(mutableListOf())
} else {
acc.last().add(t)
}
acc
}
/**
* Counts through the first matching element.
*/
fun <T> Sequence<T>.countUntil(predicate: (T) -> Boolean): Int {
var count = 0
for (t in this@countUntil) {
count++
if (predicate(t)) {
break
}
}
return count
}
fun <T> Iterable<T>.productOf(predicate: (T) -> Int) = fold(1) { acc, t -> acc * predicate(t) }
fun Int.clamp(min: Int, max: Int) = maxOf(min, minOf(max, this))
fun String.containsInt() = toIntOrNull() != null
/**
* Returns a new list with the ranges condensed into the smallest possible set of ranges.
*
* For example, given the ranges [4..6, 1..3, 7..9], this will return [1..9].
*/
fun Iterable<IntRange>.simplify(): List<IntRange> {
val sortedRanges = sortedBy { it.first }
val nonOverlappingRanges = mutableListOf<IntRange>()
for (range in sortedRanges) {
if (nonOverlappingRanges.isEmpty()) {
nonOverlappingRanges.add(range)
} else {
val lastRange = nonOverlappingRanges.last()
if (lastRange.last >= range.first) {
nonOverlappingRanges[nonOverlappingRanges.lastIndex] = lastRange.first..max(lastRange.last, range.last)
} else {
nonOverlappingRanges.add(range)
}
}
}
return nonOverlappingRanges
}
/**
* Returns a new list with the ranges clamped to the given min and max values.
*
* Any ranges that are completely outside the min/max range will be excluded.
*/
fun Iterable<IntRange>.clamp(min: Int, max: Int) =
filter { it.first <= max && it.last >= min }
.map { it.first.coerceAtLeast(min)..it.last.coerceAtMost(max) }
| 0 | Kotlin | 0 | 1 | 32da24a888ddb8e8da122fa3e3a08fc2d4829180 | 1,986 | advent-2022 | MIT License |
codeforces/round680/a.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package codeforces.round680
private fun solve(): Long {
val (p, q) = readLongs()
if (p % q != 0L) return p
val xs = primeFactorization(q)
var ans = 1L
for (i in xs) {
var pp = p
while (pp % q == 0L && pp % i == 0L) pp /= i
if (pp % q != 0L) ans = maxOf(ans, pp)
}
return ans
}
fun primeFactorization(n: Long): LongArray {
var m = n
val tempLong = mutableListOf<Long>()
run {
var i: Long = 2
while (m > 1 && i * i <= m) {
while (m % i == 0L) {
tempLong.add(i)
m /= i
}
i++
}
}
if (m > 1) tempLong.add(m)
val factors = LongArray(tempLong.size)
for (i in factors.indices) {
factors[i] = tempLong[i]
}
return factors
}
fun main() = repeat(readInt()) { println(solve()) }
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readLongs() = readStrings().map { it.toLong() }
| 0 | Java | 1 | 9 | 30953122834fcaee817fe21fb108a374946f8c7c | 903 | competitions | The Unlicense |
solutions/src/main/kotlin/fr/triozer/aoc/y2022/Day09.kt | triozer | 573,964,813 | false | {"Kotlin": 16632, "Shell": 3355, "JavaScript": 1716} | package fr.triozer.aoc.y2022
import fr.triozer.aoc.utils.readInput
import kotlin.math.absoluteValue
import kotlin.math.sign
// #region other-type
private typealias IntPair = Pair<Int, Int>
// #endregion other-type
// #region other-parse-input
private fun parse(input: List<String>) = sequence {
var x = 0
var y = 0
yield(IntPair(x, y))
for (line in input) {
val (direction, steps) = line.split(" ")
repeat(steps.toInt()) {
when (direction) {
"L" -> x--
"R" -> x++
"U" -> y++
"D" -> y--
}
yield(IntPair(x, y))
}
}
}
// #endregion other-parse-input
// #region other-follow
private fun Sequence<IntPair>.follow(): Sequence<IntPair> = scan(IntPair(0, 0)) { tail, head ->
// returns the x, y distance between the two points
val dx = head.first - tail.first
val dy = head.second - tail.second
when {
// if the distance is less or equals to 1 nothing changes
dx.absoluteValue <= 1 && dy.absoluteValue <= 1 -> tail
// if the dy is greater than dx, then same line, we move the tail on the y-axis
dx.absoluteValue < dy.absoluteValue -> IntPair(head.first, head.second - dy.sign)
// if the dx is greater than dy, then same column, we move the tail on the x-axis
dx.absoluteValue > dy.absoluteValue -> IntPair(head.first - dx.sign, head.second)
// otherwise we move the tail on both axis (diagonally)
else -> IntPair(head.first - dx.sign, head.second - dy.sign)
}
}
// #endregion other-follow
// #region part1
private fun part1(input: List<String>) = parse(input).follow().toSet().size
// #endregion part1
// #region part2
private fun part2(input: List<String>): Int {
var seq = parse(input)
repeat(9) {
seq = seq.follow()
}
return seq.toSet().size
}
// #endregion part2
fun main() {
val testInput = readInput(2022, 9, "test")
check(part1(testInput) == 13)
check(part2(testInput) == 1)
val testInput2 = readInput(2022, 9, "test2")
check(part2(testInput2) == 36)
println("Checks passed ✅")
val input = readInput(2022, 9, "input")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | a9f47fa0f749a40e9667295ea8a4023045793ac1 | 2,266 | advent-of-code | Apache License 2.0 |
src/Day04.kt | MT-Jacobs | 574,577,538 | false | {"Kotlin": 19905} |
fun main() {
fun part1(input: List<String>): Int {
return input.count {
val (elf1, elf2) = it.toSectionAssignmentPairs()
elf2.within(elf1) || elf1.within(elf2)
}
}
fun part2(input: List<String>): Int {
return input.count {
val (elf1, elf2) = it.toSectionAssignmentPairs()
elf1.overlaps(elf2)
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
val part1Result = part1(testInput)
check(part1Result == 2)
val part2Resut = part2(testInput)
check(part2Resut == 3)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
private fun String.toSectionAssignmentPairs(): Pair<IntRange, IntRange> {
val assignments = this.split(',')
val firstAssignment = assignments[0].toSectionAssignment()
val secondAssignment = assignments[1].toSectionAssignment()
return firstAssignment to secondAssignment
}
private fun String.toSectionAssignment(): IntRange {
val rangeEnds = this.split('-').map { it.toInt() }
return IntRange(rangeEnds[0], rangeEnds[1])
} | 0 | Kotlin | 0 | 0 | 2f41a665760efc56d531e56eaa08c9afb185277c | 1,181 | advent-of-code-2022 | Apache License 2.0 |
core/src/main/kotlin/in/specmatic/core/pattern/CombinationSpec.kt | znsio | 247,710,440 | false | {"Kotlin": 2742865, "Shell": 3975, "Python": 2412, "Nix": 391, "Dockerfile": 367} | package `in`.specmatic.core.pattern
import kotlin.math.min
/**
* Provides utility access to all combinations of multiple sets of candidate values. Represented as the cartesian
* product of all sets where each combination is represented as a numerical index from 0 to (MAX_COMBOS - 1).
*
* Supports sequential iteration over all combinations, which is used to test as many combinations as possible.
*
* Supports translating a combination of candidate values to an index, which is used to first test priority combinations
* (and to remember these when later iterating remaining combinations to not double-include these priority combinations)
*
* See <a href="https://softwareengineering.stackexchange.com/questions/228478/testing-all-combinations"> this
* stackoverflow article</a> accepted answer. A notable difference is that our representation is reversed such that
* a sequential iteration produces all combinations with the first candidate value of the first set before producing
* all combinations using the second candidate value of the first set, and so on for each subsequent value and set.
*/
class CombinationSpec<ValueType>(
keyToCandidatesOrig: Map<String, List<ValueType>>,
private val maxCombinations: Int,
) {
init {
if (maxCombinations < 1) throw IllegalArgumentException("maxCombinations must be > 0 and <= ${Int.MAX_VALUE}")
}
// Omit entries without any candidate values
private val keyToCandidates = keyToCandidatesOrig.filterValues { it.isNotEmpty() }
private val indexToKeys = keyToCandidates.keys.toList()
private val indexToCandidates = keyToCandidates.values
private val maxCandidateCount = indexToCandidates.maxOfOrNull { it.size } ?: 0
private val allCombosCount = indexToCandidates.map { it.size.toLong()}.reduceOrNull{ acc, cnt -> acc * cnt} ?: 0
private val reversedIndexToKeys = indexToKeys.reversed()
private val reversedIndexToCandidates = indexToCandidates.reversed()
private val lastCombination = min(maxCombinations, min(allCombosCount, Int.MAX_VALUE.toLong()).toInt()) - 1
private val prioritizedComboIndexes = calculatePrioritizedComboIndexes()
val selectedCombinations = toSelectedCombinations()
private fun calculatePrioritizedComboIndexes(): List<Int> {
// Prioritizes using each candidate value as early as possible so uses first candidate of each set,
// then second candidate, and so on.
val prioritizedCombos = (0 until maxCandidateCount).map { lockStepOffset ->
val fullComboIndex = indexToCandidates.fold(0) {acc, candidates ->
// Lower-cardinality sets run out of candidates first so are reused round-robin until other sets finish
val candidateOffset = lockStepOffset % candidates.size
toComboIndex(candidates.size, candidateOffset, acc)
}
// val combo = toCombo(finalComboIndex)
fullComboIndex
}
return prioritizedCombos
}
// Combo index is based on each candidate set size and offset, plus any index accumulated so far
private fun toComboIndex(candidateSetSize: Int, candidateOffset: Int, comboIndexSoFar: Int) =
(comboIndexSoFar * candidateSetSize) + candidateOffset
private fun toSelectedCombinations(): List<Map<String, ValueType>> {
val prioritizedCombos = prioritizedComboIndexes.map { toCombo(it) }
val remainingCombos = (0..lastCombination)
.filterNot { prioritizedComboIndexes.contains(it) }
.map { toCombo(it) }
val combined = prioritizedCombos.plus(remainingCombos)
return if (combined.size > maxCombinations)
combined.subList(0, maxCombinations)
else combined
}
private fun toCombo(comboIndex: Int): Map<String, ValueType> {
var subIndex = comboIndex
return reversedIndexToCandidates.mapIndexed{ reversedIndex, candidates ->
val candidateOffset = subIndex % candidates.size
subIndex /= candidates.size
reversedIndexToKeys[reversedIndex] to candidates[candidateOffset]
}.toMap()
}
}
| 36 | Kotlin | 44 | 175 | 6b8e2defe4fcafb6f522f5d271fbfb46dc1089d1 | 4,147 | specmatic | MIT License |
src/Day09.kt | askeron | 572,955,924 | false | {"Kotlin": 24616} | import Point.Companion.DOWN
import Point.Companion.LEFT
import Point.Companion.RIGHT
import Point.Companion.UP
class Day09 : Day<Int>(13, 1, 6236, 2449) {
private fun parseInput(input: List<String>): List<Point> {
return input.map { it.split(" ").toPair() }
.map { (a,b) ->
mapOf("L" to LEFT, "R" to RIGHT, "U" to UP, "D" to DOWN)[a]!! to b.toInt()
}
.flatMap { (direction, count) -> (1..count).map { direction } }
}
private class State(val tailCount: Int) {
val positions = Array(tailCount + 1) { Point(0,0) }
val lastTailPositions = mutableSetOf(positions.last())
fun moveHead(direction: Point) {
positions[0] += direction
(0 until tailCount).forEach { i ->
if (positions[i+1] !in positions[i].neighboursWithItself) {
positions[i+1] += (positions[i] - positions[i+1]).sign
}
}
lastTailPositions += positions.last()
}
}
fun partCommon(input: List<String>, tailCount: Int): Int {
return State(tailCount).also { state -> parseInput(input).forEach { state.moveHead(it) } }
.lastTailPositions.size
}
override fun part1(input: List<String>): Int {
return partCommon(input, 1)
}
override fun part2(input: List<String>): Int {
return partCommon(input, 9)
}
}
| 0 | Kotlin | 0 | 1 | 6c7cf9cf12404b8451745c1e5b2f1827264dc3b8 | 1,427 | advent-of-code-kotlin-2022 | Apache License 2.0 |
solutions/aockt/y2021/Y2021D20.kt | Jadarma | 624,153,848 | false | {"Kotlin": 435090} | package aockt.y2021
import io.github.jadarma.aockt.core.Solution
object Y2021D20 : Solution {
/**
* Represents a finite slice of an infinite image, with a maximum size of 2^15 * 2^15 pixels.
* @property width The finite width of this slice.
* @property height The finite height of this slice.
* @property defaultValue The value of pixels outside the bounds of this slice.
*/
private class InfiniteImageSlice(
val width: Int,
val height: Int,
val defaultValue: Boolean = false,
private val imageData: BooleanArray,
) {
init {
require(width > 0 && height > 0) { "Image dimensions need to be positive." }
require(width <= Short.MAX_VALUE && height <= Short.MAX_VALUE) { "Image maximum size exceeded." }
require(imageData.size == width * height) { "Image dimensions and data size do not match." }
}
operator fun get(x: Int, y: Int): Boolean =
if (x in 0 until height && y in 0 until width) imageData[x * width + y] else defaultValue
operator fun set(x: Int, y: Int, value: Boolean) {
if (x in 0 until height && y in 0 until width) imageData[x * width + y] = value
}
/** Returns the number of set pixels in this slice (ignoring the surrounding infinity). */
fun countSetPixels(): Int = imageData.count { it }
}
/** An advanced image enhancement algorithm able to process slices of infinite images. */
private class ImageEnhancer(enhancementData: BooleanArray) {
private val enhancement = enhancementData.copyOf()
init {
require(enhancement.size == 512) { "Not enough enhancement values." }
}
/** Process the [image] and return a new enhanced copy. */
fun enhance(image: InfiniteImageSlice): InfiniteImageSlice = InfiniteImageSlice(
width = image.width + 2,
height = image.height + 2,
defaultValue = if (enhancement[0]) !image.defaultValue else image.defaultValue,
imageData = BooleanArray((image.width + 2) * (image.height + 2)),
).apply {
for (x in 0 until height) {
for (y in 0 until width) {
val kernelValue = buildString(9) {
for (i in -1..1) {
for (j in -1..1) {
append(if (image[x + i - 1, y + j - 1]) '1' else '0')
}
}
}.toInt(2)
this[x, y] = enhancement[kernelValue]
}
}
}
}
/** Parse the [input] and return the [ImageEnhancer] algorithm instance and the initial [InfiniteImageSlice]. */
private fun parseInput(input: String): Pair<ImageEnhancer, InfiniteImageSlice> = runCatching {
val lines = input.lineSequence().iterator()
val enhancementData = lines.next().map { it == '#' }.toBooleanArray()
lines.next()
var width = -1
var height = 0
val imageData = lines.asSequence()
.onEach { if (width == -1) width = it.length else require(it.length == width) }
.onEach { height++ }
.flatMap { line -> line.map { it == '#' } }
.toList()
.toBooleanArray()
ImageEnhancer(enhancementData) to InfiniteImageSlice(width, height, false, imageData)
}.getOrElse { throw IllegalArgumentException("Invalid input.", it) }
override fun partOne(input: String): Any {
val (enhancement, image) = parseInput(input)
val enhanced = (1..2).fold(image) { acc, _ -> enhancement.enhance(acc) }
return enhanced.countSetPixels()
}
override fun partTwo(input: String): Any {
val (enhancement, image) = parseInput(input)
val enhanced = (1..50).fold(image) { acc, _ -> enhancement.enhance(acc) }
return enhanced.countSetPixels()
}
}
| 0 | Kotlin | 0 | 3 | 19773317d665dcb29c84e44fa1b35a6f6122a5fa | 3,974 | advent-of-code-kotlin-solutions | The Unlicense |
src/main/kotlin/day4.kt | Gitvert | 725,292,325 | false | {"Kotlin": 97000} | fun day4 (lines: List<String>) {
day4part1(lines)
day4part2(lines)
println()
}
fun day4part2(lines: List<String>) {
val winsPerCard = mutableMapOf<Int, Int>()
val noOfCards = mutableListOf<Int>()
lines.forEachIndexed { index, line ->
winsPerCard[index] = findMatches(line)
noOfCards.add(1)
}
for (i in lines.indices) {
for (j in 0..<noOfCards[i]) {
for (k in 1..winsPerCard[i]!!) {
noOfCards[i + k]++
}
}
}
val noOfCardsSum = noOfCards.sum()
println("Day 4 part 2: $noOfCardsSum")
}
fun day4part1(lines: List<String>) {
var points = 0
lines.forEach { line ->
val noOfWinningNumbers = findMatches(line)
var cardScore = 0
if (noOfWinningNumbers > 0) {
cardScore = 1
for (i in 1..<noOfWinningNumbers) {
cardScore*=2
}
}
points += cardScore
}
println("Day 4 part 1: $points")
}
fun findMatches(card: String): Int {
val winningNumbers = card.replace(" ", " ").split(": ")[1].split(" | ")[0].split(" ").map { Integer.parseInt(it) }
val myNumbers = card.replace(" ", " ").split(": ")[1].split(" | ")[1].split(" ").map { Integer.parseInt(it) }
val myWinningNumbers = winningNumbers.intersect(myNumbers.toSet())
return myWinningNumbers.count()
} | 0 | Kotlin | 0 | 0 | f204f09c94528f5cd83ce0149a254c4b0ca3bc91 | 1,418 | advent_of_code_2023 | MIT License |
src/Day11.kt | lassebe | 573,423,378 | false | {"Kotlin": 33148} | fun main() {
data class Monkey(
val id: Int,
val items: MutableList<Long>,
val operation: (Long) -> Long,
val divisor: Long,
val test: (Long) -> Boolean,
val testTrueId: Int,
val testFalseId: Int
)
fun monkeys(input: List<String>): MutableList<Monkey> {
val monkeys = mutableListOf<Monkey>()
var i = 0
var monkeyId = 0
while (i < input.size) {
i++
val startingItems = input[i].split("Starting items: ").last().split(", ").map { it.toLong() }
i++
val op = input[i].split("Operation: new = ").last()
i++
val test = input[i].split("Test: divisible by ").last().toInt()
i++
val nextIfTrue = input[i].split("If true: throw to monkey ").last().toInt()
i++
val nextIfFalse = input[i].split("If false: throw to monkey ").last().toInt()
i++
i++
val func = op.split(" ")
val monkey = Monkey(
monkeyId,
startingItems.toMutableList(),
{
val a = if (func[0] == "old") {
it
} else {
func[0].toLong()
}
val b = if (func[2] == "old") {
it
} else {
func[2].toLong()
}
when (func[1]) {
"*" -> a * b
"+" -> a + b
"-" -> a - b
"/" -> a / b
else -> throw IllegalStateException("invalid op ${func[1]}")
}
},
test.toLong(),
{
(it % test == 0L)
},
nextIfTrue,
nextIfFalse
)
monkeys.add(
monkey
)
monkeyId++
}
return monkeys
}
fun part1(input: List<String>): Int {
val monkeys = monkeys(input)
val roundToMonkeys = mutableMapOf<Int, Int>()
for (round in (1..20)) {
for (monkey in monkeys) {
roundToMonkeys[monkey.id] = roundToMonkeys.getOrDefault(monkey.id, 0) + monkey.items.size
while (monkey.items.isNotEmpty()) {
val newWorry = monkey.operation(monkey.items.removeFirst())
val bored = (newWorry / 3)
val resultOfTest = monkey.test(bored)
monkeys[if (resultOfTest) monkey.testTrueId else monkey.testFalseId].items.add(bored)
}
}
}
val x = roundToMonkeys.map { it.value }.sorted()
return x[x.size - 1] * x[x.size - 2]
}
fun part2(input: List<String>): Long {
val monkeys = monkeys(input)
val roundToMonkeys = mutableMapOf<Int, Long>()
val product = monkeys.map { it.divisor }.reduce { acc, p -> acc * p }
for (round in (1..10000)) {
for (monkey in monkeys) {
roundToMonkeys[monkey.id] = roundToMonkeys.getOrDefault(monkey.id, 0) + monkey.items.size
while (monkey.items.isNotEmpty()) {
val newWorry = monkey.operation(monkey.items.removeFirst()) % product
val resultOfTest = monkey.test(newWorry)
monkeys[if (resultOfTest) monkey.testTrueId else monkey.testFalseId].items.add(newWorry)
}
}
}
val x = roundToMonkeys.map { it.value }.sorted()
return x[x.size - 1] * x[x.size - 2]
}
val testInput = readInput("Day11_test")
expect(10605, part1(testInput))
val input = readInput("Day11")
println(part1(input))
expect(78960, part1(input))
expect(
2713310158,
part2(testInput)
)
expect(
14561971968,
part2(input)
)
} | 0 | Kotlin | 0 | 0 | c3157c2d66a098598a6b19fd3a2b18a6bae95f0c | 4,065 | advent_of_code_2022 | Apache License 2.0 |
src/main/kotlin/de/soniro/nonogramsolver/Nonogram.kt | soniro | 228,921,836 | false | {"Kotlin": 7386} | package de.soniro.nonogramsolver
import de.soniro.nonogramsolver.Cell.*
enum class Cell(val char: Char) {
FILL('\u2588'),
EMPTY(' '),
NOT_FILLED('X'),
UNKNOWN('?');
override fun toString(): String = "$char"
}
class Nonogram(val rows: Array<IntArray>, val columns: Array<IntArray>) {
val grid: Array<Array<Any>>
private val columnOffset: Int
private val rowOffset: Int
init {
columnOffset = longestSubArray(rows)
rowOffset = longestSubArray(columns)
grid = Array(numberOfRows()) { row ->
Array<Any>(numberOfColumns()) { column ->
if (row > columnOffset && column > rowOffset) UNKNOWN else EMPTY
}
}
writeColumns()
writeRows()
}
private fun writeColumns() =
(rowOffset downTo 1).forEach { i ->
(0..columns.size - 1).forEach { j ->
if (columns[j].size >= i) {
grid[rowOffset - i][columnOffset + j] = columns[j][columns[j].size - i]
}
}
}
private fun writeRows() =
(columnOffset downTo 1).forEach { i ->
(0..rows.size - 1).forEach { j ->
if (rows[j].size >= i) {
grid[rowOffset + j][columnOffset - i] = rows[j][rows[j].size - i]
}
}
}
private fun numberOfColumns(): Int = columnOffset + columns.size
private fun numberOfRows(): Int = rowOffset + rows.size
private fun longestSubArray(array: Array<IntArray>): Int = array.maxBy { it.size }!!.size
fun print() = grid.forEach { row ->
row.forEach { cell -> print("$cell ") }
println()
}
fun fillTrivialRows() =
rows.forEachIndexed { index, row -> fillRowIfTrivial(index, row) }
fun fillRowIfTrivial(currentRowIndex: Int, row: IntArray) {
if (row.sum() + row.size - 1 == columns.size) {
var index = columnOffset
val rowIndex = rowOffset + currentRowIndex
row.forEach { value ->
repeat(value) {
grid[rowIndex][index] = FILL
index++
}
if (index < numberOfColumns() - 1) {
grid[rowIndex][index] = NOT_FILLED
index++
}
}
}
}
fun fillTrivialColumns() {
for ((currentColumnIndex, column) in columns.withIndex()) {
if (column.sum() + column.size - 1 == rows.size) {
var index = rowOffset
val columnIndex = columnOffset + currentColumnIndex
for (value in column) {
repeat(value) {
grid[index][columnIndex] = FILL
index++
}
if (index < numberOfRows() - 1) {
grid[index][columnIndex] = NOT_FILLED
index++
}
}
}
}
}
fun writeColumn(columnWithContent: Array<Cell>, columnIndex: Int) {
columnWithContent.forEachIndexed { cellIndex, cell ->
grid[cellIndex + rowOffset][columnIndex] = cell
}
}
} | 0 | Kotlin | 0 | 0 | 6cc0f04715a3e0c2dc87db6ecd5dee1925704ff9 | 3,246 | nonogram-solver | Apache License 2.0 |
src/main/kotlin/day04/Day04.kt | qnox | 575,581,183 | false | {"Kotlin": 66677} | package day04
import readInput
typealias Range = List<Int>
fun Range.includes(range: Range): Boolean = this[0] <= range[0] && this[1] >= range[1]
fun Range.overlap(range: Range): Boolean = this[1] >= range[0] && this[0] <= range[1]
fun main() {
fun part1(input: List<String>): Int {
return input.count {line ->
val (r1: Range, r2: Range) = line.split(",").map { it.split("-").map { it.toInt() } }
r1.includes(r2) || r2.includes(r1)
}
}
fun part2(input: List<String>): Int {
return input.count {line ->
val (r1: Range, r2: Range) = line.split(",").map { it.split("-").map { it.toInt() } }
r1.overlap(r2)
}
}
val testInput = readInput("day04", "test")
val input = readInput("day04", "input")
check(part1(testInput) == 2)
println(part1(input))
check(part2(testInput) == 4)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 727ca335d32000c3de2b750d23248a1364ba03e4 | 921 | aoc2022 | Apache License 2.0 |
src/main/kotlin/aoc2018/day6/Manhattan.kt | arnab | 75,525,311 | false | null | package aoc2018.day6
import kotlin.math.abs
data class Point(val id: Int?, val x: Int, val y: Int) {
fun distanceTo(other: Point): Int {
return abs(x - other.x) + abs(y - other.y)
}
}
object Manhattan {
fun largestArea(points: List<Point>): Int {
val closestPoint: MutableMap<Point, Point> = mutableMapOf()
val maxX = points.maxBy { it.x }!!.x
val maxY = points.maxBy { it.y }!!.y
for (i in 0..maxX) {
for (j in 0..maxY) {
val currentGridPoint = Point(null, i, j)
val closestPoints = points.map { Pair(it, it.distanceTo(currentGridPoint)) }
.groupBy { it.second }
.map { it.toPair() }
.minBy { it.first }
?.second
if (closestPoints?.size == 1) {
closestPoint[currentGridPoint] = closestPoints.first().first
}
}
}
val pointsWithMaxNeighbors = closestPoint.toList()
.groupBy { it.second }
.map { Pair(it.key, it.value.size) }
.toMutableList()
for (i in 0..maxX) {
val j = 0
val closestPointToExclude = closestPoint[Point(null, i, j)]
pointsWithMaxNeighbors.removeIf { it.first == closestPointToExclude }
}
for (i in 0..maxX) {
val j = maxY
val closestPointToExclude = closestPoint[Point(null, i, j)]
pointsWithMaxNeighbors.removeIf { it.first == closestPointToExclude }
}
for (j in 0..maxY) {
val i = 0
val closestPointToExclude = closestPoint[Point(null, i, j)]
pointsWithMaxNeighbors.removeIf { it.first == closestPointToExclude }
}
for (j in 0..maxY) {
val i = maxX
val closestPointToExclude = closestPoint[Point(null, i, j)]
pointsWithMaxNeighbors.removeIf { it.first == closestPointToExclude }
}
val pointWithMaxNeighbors = pointsWithMaxNeighbors.maxBy { it.second }
return pointWithMaxNeighbors!!.second
}
fun safeRegionSize(points: List<Point>, safeRegionThreshold: Int): Int {
val maxX = points.maxBy { it.x }!!.x
val maxY = points.maxBy { it.y }!!.y
var safeRegionSize = 0
for (i in 0..maxX) {
for (j in 0..maxY) {
val currentGridPoint = Point(null, i, j)
val distancesSum = points.map { it.distanceTo(currentGridPoint) }.sum()
if (distancesSum < safeRegionThreshold) {
safeRegionSize++
}
}
}
return safeRegionSize
}
} | 0 | Kotlin | 0 | 0 | 1d9f6bc569f361e37ccb461bd564efa3e1fccdbd | 2,752 | adventofcode | MIT License |
src/Day02.kt | rromanowski-figure | 573,003,468 | false | {"Kotlin": 35951} | object Day02 : Runner<Int, Int>(2, 15, 12) {
override fun part1(input: List<String>): Int {
val results = input.map {
val values = it.split(" ")
val them = Shape.them(values[0])
val me = Shape.me(values[1])
me.vs(them)
}
return results.sum()
}
override fun part2(input: List<String>): Int {
val results = input.map {
val values = it.split(" ")
val them = Shape.them(values[0])
val intendedResult = RpsResult.of(values[1])
val me = when (intendedResult) {
RpsResult.Win -> them.loses
RpsResult.Tie -> them
RpsResult.Loss -> them.beats
}
intendedResult.points + me.points
}
return results.sum()
}
sealed class Shape(val points: Int) {
companion object {
fun them(s: String) = when (s) {
"A" -> Rock
"B" -> Paper
"C" -> Scissors
else -> error("Invalid input: $s")
}
fun me(s: String) = when (s) {
"X" -> Rock
"Y" -> Paper
"Z" -> Scissors
else -> error("Invalid input: $s")
}
}
abstract val beats: Shape
abstract val loses: Shape
private fun resultAgainst(other: Shape): RpsResult {
return when {
this.beats == other -> RpsResult.Win
other.beats == this -> RpsResult.Loss
else -> RpsResult.Tie
}
}
fun vs(other: Shape): Int = this.resultAgainst(other).points + this.points
override fun toString(): String = this::class.simpleName ?: "Unknown Shape"
}
object Rock : Shape(1) {
override val beats: Shape
get() = Scissors
override val loses: Shape
get() = Paper
}
object Paper : Shape(2) {
override val beats: Shape
get() = Rock
override val loses: Shape
get() = Scissors
}
object Scissors : Shape(3) {
override val beats: Shape
get() = Paper
override val loses: Shape
get() = Rock
}
enum class RpsResult(val points: Int) {
Win(6),
Tie(3),
Loss(0);
companion object {
fun of(s: String) = when (s) {
"X" -> Loss
"Y" -> Tie
"Z" -> Win
else -> error("Invalid input: $s")
}
}
}
}
| 0 | Kotlin | 0 | 0 | 6ca5f70872f1185429c04dcb8bc3f3651e3c2a84 | 2,617 | advent-of-code-2022-kotlin | Apache License 2.0 |
java/app/src/main/kotlin/com/github/ggalmazor/aoc2021/day21/Day21Kt.kt | ggalmazor | 434,148,320 | false | {"JavaScript": 80092, "Java": 33594, "Kotlin": 14508, "C++": 3077, "CMake": 119} | package com.github.ggalmazor.aoc2021.day21
class Day21Kt {
enum class Turn {
PLAYER1, PLAYER2;
fun next(): Turn {
return when (this) {
PLAYER1 -> PLAYER2
PLAYER2 -> PLAYER1
}
}
}
private val rollFrequencies = mapOf(3 to 1, 4 to 3, 5 to 6, 6 to 7, 7 to 6, 8 to 3, 9 to 1)
private val cache = mutableMapOf<GameState, WinCount>()
fun solvePart2(): Long {
val p1State = PlayerState(9, 0)
val p2State = PlayerState(6, 0)
val gameState = GameState(p1State, p2State)
return playWithDiracDice(gameState).maxWins()
}
private fun playWithDiracDice(gameState: GameState): WinCount = when {
gameState.p1Wins() -> WinCount(1, 0)
gameState.p2Wins() -> WinCount(0, 1)
else -> cache.getOrPut(gameState) {
rollFrequencies.map { (roll, frequency) -> playWithDiracDice(gameState.next(roll)) * frequency }.reduce(WinCount::plus)
}
}
data class GameState(val p1State: PlayerState, val p2State: PlayerState, val turn: Turn = Turn.PLAYER1, val winScore: Int = 21) {
fun next(roll: Int): GameState = when (turn) {
Turn.PLAYER1 -> GameState(p1State.next(roll), p2State, turn.next())
Turn.PLAYER2 -> GameState(p1State, p2State.next(roll), turn.next())
}
fun p1Wins() = p1State.score >= winScore
fun p2Wins() = p2State.score >= winScore
}
data class PlayerState(val position: Int, val score: Int) {
fun next(roll: Int): PlayerState = PlayerState((position + roll) % 10, score + (position + roll) % 10 + 1)
}
class WinCount(private val player1Wins: Long, private val player2Wins: Long) {
operator fun plus(other: WinCount): WinCount = WinCount(player1Wins + other.player1Wins, player2Wins + other.player2Wins)
operator fun times(other: Int): WinCount = WinCount(player1Wins * other, player2Wins * other)
fun maxWins(): Long = maxOf(player1Wins, player2Wins)
}
}
| 0 | JavaScript | 0 | 0 | 7a7ec831ca89de3f19d78f006fe95590cc533836 | 2,045 | aoc2021 | Apache License 2.0 |
src/Day25.kt | abeltay | 572,984,420 | false | {"Kotlin": 91982, "Shell": 191} | fun main() {
fun convertToNum(snafu: Char): Int {
return when (snafu) {
'-' -> -1
'=' -> -2
else -> snafu.digitToInt()
}
}
fun convertToSNAFU(num: Int): Char {
return when (num) {
-1 -> '-'
-2 -> '='
else -> Character.forDigit(num, 10)
}
}
fun snafuToList(snafu: String): List<Int> {
val output = mutableListOf<Int>()
for (it in snafu) {
output.add(convertToNum(it))
}
return output
}
fun snafuAdder(snafu1: List<Int>, snafu2: List<Int>): List<Int> {
if (snafu2.size > snafu1.size) {
return snafuAdder(snafu2, snafu1)
}
val output = snafu1.toMutableList()
var pointer = output.size - 1
for (it in snafu2.reversed()) {
output[pointer] += it
pointer--
}
return output
}
fun normalise(base: Int, snafu: MutableList<Int>): String {
val output = mutableListOf<Char>()
for (i in snafu.indices.reversed()) {
val original = snafu[i] + 2
var dividend = original / base
var remainder = (original % base) - 2
if (remainder < -2) {
remainder += base
dividend--
}
output.add(0, convertToSNAFU(remainder))
if (i - 1 >= 0)
snafu[i - 1] += dividend
}
return String(output.toCharArray())
}
fun part1(input: List<String>): String {
var result = listOf(0)
for (it in input) {
result = snafuAdder(result, snafuToList(it))
}
return normalise(5, result.toMutableList())
}
val testInput = readInput("Day25_test")
check(part1(testInput) == "2=-1=0")
val input = readInput("Day25")
println(part1(input))
}
| 0 | Kotlin | 0 | 0 | a51bda36eaef85a8faa305a0441efaa745f6f399 | 1,900 | advent-of-code-2022 | Apache License 2.0 |
src/Day05_part2.kt | lowielow | 578,058,273 | false | {"Kotlin": 29322} | class Stack2 {
val input = readInput("Day05")
private val rawList = mutableListOf<MutableList<Char>>()
private val newList = mutableListOf<MutableList<Char>>()
fun addStack(str: String) {
var raw = ""
for (i in 1 until str.length step 4) {
raw += str[i].toString()
}
rawList.add(raw.toMutableList())
}
fun arrangeStack() {
for (j in 0 until rawList[0].size) {
var new = ""
for (i in 0 until rawList.size) {
if (rawList[i][j] == ' ') {
continue
} else {
new = rawList[i][j] + new
}
}
newList.add(new.toMutableList())
}
}
fun handleMove(regex: Regex, str: String) {
val match = regex.find(str)!!
val (a, b, c) = match.destructured
when (a.toInt()) {
1 -> repeat(a.toInt()) {newList[c.toInt() - 1].add(newList[b.toInt() - 1][newList[b.toInt() - 1].size - 1]) }
else -> newList[c.toInt() - 1].addAll(newList[b.toInt() - 1].takeLast(a.toInt()))
}
repeat(a.toInt()) {newList[b.toInt() - 1].removeAt(newList[b.toInt() - 1].size - 1)}
}
fun printTopStack(): String {
var str = ""
for (i in newList.indices) {
str += newList[i][newList[i].size - 1].toString()
}
return str
}
}
fun main() {
val stack = Stack2()
val regexStack = Regex(".*[A-Z].*")
val regexMove = Regex("\\D*(\\d+)\\D*(\\d)\\D*(\\d)")
fun part2(input: List<String>): String {
for (i in input.indices) {
if (regexStack.matches(input[i])) {
stack.addStack(input[i])
} else if (input[i].isEmpty()) {
stack.arrangeStack()
} else if (regexMove.matches(input[i])) {
stack.handleMove(regexMove, input[i])
}
}
return stack.printTopStack()
}
part2(stack.input).println()
}
| 0 | Kotlin | 0 | 0 | acc270cd70a8b7f55dba07bf83d3a7e72256a63f | 2,024 | aoc2022 | Apache License 2.0 |
advent/src/test/kotlin/org/elwaxoro/advent/y2020/Dec19.kt | elwaxoro | 328,044,882 | false | {"Kotlin": 376774} | package org.elwaxoro.advent.y2020
import org.elwaxoro.advent.PuzzleDayTester
class Dec19 : PuzzleDayTester(19, 2020) {
override fun part1(): Any = parse().let { rulesToMessages ->
// first arg is the rule map, second is the list of messages
rulesToMessages.second.filter {
val maxIdxMatches = rulesToMessages.first["0"]!!.find(it, 0, rulesToMessages.first)
//println("Puzzle1: $it len: ${it.length} matches: $maxIdxMatches ${if (maxIdxMatches.contains(it.length)) "SUCCESS" else "failed"}")
// if there's a max idx equal to the message length, we did it!
maxIdxMatches.contains(it.length)
}.size
}
override fun part2(): Any = parse().let { rulesToMessages ->
// first arg is the rule map, second is the list of messages
val rules = rulesToMessages.first.toMutableMap()
// add the 2 custom rules
rules["8"] = Rule("8", listOf(listOf("42"), listOf("42", "8")))
rules["11"] = Rule("11", listOf(listOf("42", "31"), listOf("42", "11", "31")))
rulesToMessages.second.filter {
val maxIdxMatches = rules["0"]!!.find(it, 0, rules)
//println("Puzzle2: $it len: ${it.length} matches: $maxIdxMatches ${if (maxIdxMatches.contains(it.length)) "SUCCESS" else "failed"}")
// if there's a max idx equal to the message length, we did it!
maxIdxMatches.contains(it.length)
}.size
}
private data class Rule(val name: String, var subRules: List<List<String>> = listOf(), var value: Char? = null) {
/**
* Recursive thingy!
* Move thru the message, one char at a time and see how many possible matches there are (even partial)
* Little nasty since the rule carries the rule map along with it into the recursive steps
*/
fun find(message: String, messageIdx: Int, ruleMap: Map<String, Rule>): List<Int> =
if (value == null) {
// recurse case: check all of the subRule lists and generate a list of max matching index from that
subRules.fold(listOf()) { subRuleIdxAcc, subRule ->
// note: this running orMessageIdxList accumulator is almost ALWAYS empty or size one
// adding empty list to empty list just results in an empty list, so that's nice
subRule.fold(listOf(messageIdx)) { messageIdxList, ruleName ->
// messageIdxList is the list of index that have perfectly matched so far
// recurse into each rule and try to get more matches
// flatten deals with multiple empty lists naturally
// ex: [[], [32], []] becomes [32]
messageIdxList.flatMap { testIdx ->
ruleMap[ruleName]!!.find(message, testIdx, ruleMap)
}
}.plus(subRuleIdxAcc)
}
} else if (messageIdx < message.length && message[messageIdx] == value) {
// base case: success! increase the running index
// note: offset can run off the end of the message (ask me how I know)
listOf(messageIdx + 1) // total message match so far, increase the index by 1
} else {
// base case: failure
listOf()
}
}
// parse to pair: first is the map of rule name to rule, second is the list of messages
private fun parse(): Pair<Map<String, Rule>, List<String>> = load(delimiter = "\n\n").let { initial ->
val rules = initial[0].split("\n").map { ruleLine ->
ruleLine.split(": ").let {
it[0] to Rule(it[0]).also { rule ->
if (it[1].contains("\"")) {
rule.value = it[1].replace("\"", "").single()
} else {
rule.subRules = it[1].split(" | ").map { it.split(" ") }
}
}
}
}.toMap()
val messages = initial[1].split("\n")
rules to messages
}
}
| 0 | Kotlin | 4 | 0 | 1718f2d675f637b97c54631cb869165167bc713c | 4,149 | advent-of-code | MIT License |
gcj/y2022/round1b/c_easy.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package gcj.y2022.round1b
private fun solve(m: Int = 8) {
fun ask(asked: Int): Int {
println(asked.toString(2).padStart(m, '0'))
return readInt()
}
val masks = 1 shl m
fun rotate(mask: Int, shift: Int): Int {
return (((mask shl m) or mask) shr shift) and (masks - 1)
}
val initOnes = ask(0)
var ones = initOnes
if (ones == 0) return; if (ones == m) { ask(masks - 1); return }
val possible = BooleanArray(masks) { mask ->
mask.countOneBits() == initOnes
}
val memo = mutableMapOf<Int, List<Int>>()
while (true) {
val possibleBefore = possible.count { it }
var bestWorstGroup = masks + 1
var bestTries: List<Int>? = null
val id = possible.contentHashCode()
if (id !in memo) {
for (tried in 0 until masks / 2) /*for (tried2 in possible.indices)*/ {
val receivable = mutableSetOf<Int>()
for (secret in possible.indices) {
if (!possible[secret]) continue
for (shift in 0 until m) for (shift2 in 0 until m) {
receivable.add(secret xor rotate(tried, shift) /*xor rotate(tried2, shift2)*/)
}
}
val worstGroup = receivable.groupBy { it.countOneBits() }.maxOf { it.value.size }
if (worstGroup < bestWorstGroup) {
bestWorstGroup = worstGroup
bestTries = listOf(tried/*, tried2*/)
}
}
memo[id] = bestTries!!
}
bestTries = memo[id]!!
if (ones % 2 == 0) bestTries = listOf(1)
if (possibleBefore == m) {
bestTries = listOf(1)
}
for (tried in bestTries) {
val coincidence = ask(tried)
ones = coincidence
if (ones == 0) return; if (ones == m) { ask(masks - 1); return }
val receivable = mutableSetOf<Int>()
for (secret in possible.indices) {
if (!possible[secret]) continue
for (shift in 0 until m) {
val new = secret xor rotate(tried, shift)
if (new.countOneBits() == coincidence) receivable.add(new)
}
}
for (mask in possible.indices) {
possible[mask] = mask in receivable
}
}
}
}
fun main() {
repeat(readInt()) { solve() }
}
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
| 0 | Java | 1 | 9 | 30953122834fcaee817fe21fb108a374946f8c7c | 2,054 | competitions | The Unlicense |
src/main/kotlin/com/tonnoz/adventofcode23/day9/Nine.kt | tonnoz | 725,970,505 | false | {"Kotlin": 78395} | package com.tonnoz.adventofcode23.day9
import com.tonnoz.adventofcode23.utils.readInput
import kotlin.system.measureTimeMillis
object Nine {
@JvmStatic
fun main(args: Array<String>) {
val input = "inputNine.txt".readInput()
problemOne(input)
problemTwo(input)
}
private fun problemTwo(input: List<String>) {
val time = measureTimeMillis {
input.sumOf { aLine ->
val numbers = aLine.split(" ").map { it.toLong() }
buildNumbersSequenceLeft(numbers).map { it.first() }.sum()
}.let { println(it) }
}
println("Time p2: $time ms")
}
private fun problemOne(input: List<String>) {
val time = measureTimeMillis {
input.sumOf { aLine ->
val numbers = aLine.split(" ").map { it.toLong() }
buildNumbersSequenceRight(numbers).map { it.last() }.sum()
}.let { println(it) }
}
println("Time p1: $time ms")
}
private fun buildNumbersSequenceRight(numbers: List<Long>): Sequence<List<Long>> = numbers.buildNumbersSequences(::rtl)
private fun buildNumbersSequenceLeft(numbers: List<Long>): Sequence<List<Long>> = numbers.buildNumbersSequences(::ltr)
private fun List<Long>.buildNumbersSequences(windowedArg: (List<Long>) -> Long)= generateSequence(this) {
nums -> nums.windowed(2) { windowedArg(it) }.takeIf { !it.all { num -> num == 0L } }
}
private fun ltr(longs: List<Long>) = longs[0] - longs[1]
private fun rtl(longs: List<Long>) = longs[1] - longs[0]
private fun problemOneIter(input:List<String>){
val time = measureTimeMillis {
input.sumOf { s ->
var numbers = s.split(" ").map { it.toLong() }
val zeros = ArrayList<Long>()
do {
zeros.add(numbers.last())
numbers = numbers.windowed(2) { it[1] - it[0] }
} while (!numbers.all { it == 0L })
zeros.sum()
}.let { println(it) }
}
println("Time p1: $time ms")
}
} | 0 | Kotlin | 0 | 0 | d573dfd010e2ffefcdcecc07d94c8225ad3bb38f | 1,914 | adventofcode23 | MIT License |
src/day22/Board3D.kt | g0dzill3r | 576,012,003 | false | {"Kotlin": 172121} | package day22
import java.lang.IllegalStateException
class Board3D (board: Board) : Board (board.grid, board.steps) {
val cubeMap = CubeMap (board)
/**
*
*/
override val nextPoint: Point
get () {
val newPoint = pos.move (facing)
if (grid.containsKey (newPoint)) {
return newPoint
}
val current = cubeMap.pointToRegion (pos)
val adj = current.getAdjacency (facing)!!
val target = cubeMap.getRegion (adj.region)
val sides = cubeMap.sides
var offset = when (facing) {
Facing.LEFT, Facing.RIGHT -> pos.y % sides
Facing.UP, Facing.DOWN -> pos.x % sides
}
if (! adj.same) {
offset = sides - offset -1
}
val other = when (adj.side) {
Facing.LEFT -> Point (target.max.x, target.min.y + offset)
Facing.RIGHT -> Point (target.min.x, target.min.y + offset)
Facing.DOWN -> Point (target.min.x + offset, target.min.y)
Facing.UP -> Point (target.min.x + offset, target.max.y)
}
if (grid[other] == Tile.FLOOR) {
facing = adj.side
}
return other
}
fun dumpRegions () {
for (y in 0 .. ys) {
for (x in 0 .. xs) {
val point = Point (x, y)
val tile = grid [point]
if (tile != null) {
print (cubeMap.pointToRegion (point).index)
} else {
print (' ')
}
}
println ()
}
}
}
data class Adjacency (val region: Int, val side: Facing, val same: Boolean)
data class Region (val index: Int, val min: Point, val max: Point) {
val adjacencies = mutableMapOf<Facing, Adjacency> ()
fun contains (point: Point): Boolean {
val (x, y) = point
return x in min.x .. max.x && y in min.y .. max.y
}
fun hasAdjacency (dir: Facing): Boolean = adjacencies.containsKey (dir)
fun getAdjacency (dir: Facing): Adjacency? = adjacencies.get (dir)
fun setAdjacency (dir: Facing, adjacency: Adjacency) {
if (index == adjacency.region) {
throw IllegalStateException ("Can't be adjacent to yourself: $index")
}
val already = adjacencies.get (dir)
if (already != null) {
if (already != adjacency) {
println (adjacency)
println (already)
throw IllegalStateException ("Adjacency already registered: $dir")
} else {
return
}
}
adjacencies.values.forEach {
if (it.region == adjacency.region) {
throw IllegalStateException ("Adjacent region already registered: ${it.region}")
}
}
adjacencies[dir] = adjacency
return
}
fun dump () = println (toString ())
override fun toString (): String {
return StringBuffer ().apply {
append ("Region($index, $min-$max)")
adjacencies.forEach {
append (" ${it}")
}
}.toString ()
}
}
data class CubeMap (val board: Board) {
val longest = Math.max (board.xs, board.ys)
val sides = longest / 4
val xw = board.xs / sides
val yw = board.ys / sides
val regions = mutableListOf<Region> ()
val populated = mutableListOf<Region?> ().apply {
var index = 0
for (y in 0 until yw) {
for (x in 0 until xw) {
val min = Point (x * sides, y * sides)
if (board.grid.containsKey (min)) {
val max = min.add (Point(sides - 1, sides - 1))
val region = Region (index++, min, max)
regions.add (region)
add (region)
} else {
add (null)
}
}
}
}
val firstPopulated: Point
get () {
for (y in 0 until yw) {
for (x in 0 until xw) {
if (isPopulated(x, y)) {
return Point (x, y)
}
}
}
throw Exception ()
}
init {
fixedAdjacencies()
analyzeAdjacencies()
analyzeAdjacencies()
}
private fun toPopulatedIndex (x: Int, y: Int): Int = y * xw +x
fun isPopulated (x: Int, y: Int): Boolean = populated[toPopulatedIndex(x, y)] != null
fun getRegion (x: Int, y: Int): Region? = populated[toPopulatedIndex(x, y)]
fun getRegion (index: Int): Region = regions[index]
fun pointToRegion (point: Point): Region {
for (region in regions) {
if (region.contains (point)) {
return region
}
}
throw Exception ()
}
fun dumpRegion (region: Region){
println ("Region [${region.index}] - ${region.min}-${region.max}")
region.adjacencies.forEach {
println (" $it")
}
return
}
fun dumpRegions () {
for (region in regions) {
dumpRegion (region)
}
return
}
fun dump () = println (toString ())
override fun toString (): String {
return StringBuffer ().apply {
append ("CubeMap dim=($xw x $yw), sides=$sides\n")
for (y in 0 until yw){
for (x in 0 until xw) {
if (isPopulated (x, y)) {
append (getRegion(x, y)?.index)
} else {
append ('.')
}
}
append ("\n")
}
regions.forEach {
append ("${it.index}: $it\n")
}
}.toString ()
}
/**
* Utility method to add both mirror adjacencies with one call.
*/
private fun addAdjacency (from: Int, fromFacing: Facing, to: Int, toFacing: Facing, same: Boolean) {
getRegion (from).setAdjacency (fromFacing, Adjacency (to, toFacing, same))
getRegion (to).setAdjacency (toFacing.invert, Adjacency (from, fromFacing.invert, same))
return
}
/**
* Calculates the fixed adjacencies resulting from the abutting regions.
*/
fun fixedAdjacencies () {
for (y in 0 until yw) {
for (x in 0 until xw) {
getRegion (x, y)?.let { region ->
if (x != 0) {
getRegion (x - 1, y)?.let { other ->
addAdjacency (region.index, Facing.LEFT, other.index, Facing.LEFT, true)
}
}
if (y != 0) {
getRegion (x, y - 1)?.let { other ->
addAdjacency (region.index, Facing.UP, other.index, Facing.UP, true)
}
}
if (x != xw - 1) {
getRegion (x + 1, y)?.let { other ->
addAdjacency (region.index, Facing.RIGHT, other.index, Facing.RIGHT, true)
}
}
if (y != yw - 1) {
getRegion (x, y + 1)?.let { other ->
addAdjacency (region.index, Facing.DOWN, other.index, Facing.DOWN, true)
}
}
}
}
}
return
}
fun analyzeAdjacencies () {
// And now we need to derive the rest by walking around the cube
for (region in regions) {
Facing.values ().forEach { facing ->
if (! region.hasAdjacency (facing)) {
region.getAdjacency (facing.left)?.let { adjacent ->
val otherRegion = getRegion (adjacent.region)
val shift = adjacent.side.right
val maybe = otherRegion.getAdjacency (shift)
if (maybe != null) {
val direction = maybe.side.right.invert
val same = facing.same (direction)
addAdjacency (region.index, facing, maybe.region, direction, same)
}
}
}
}
}
return
}
}
fun main (args: Array<String>) {
val example = true
val board = Board3D (loadBoard (example))
val cubeMap = CubeMap (board)
println (cubeMap)
return
}
// EOF | 0 | Kotlin | 0 | 0 | 6ec11a5120e4eb180ab6aff3463a2563400cc0c3 | 8,684 | advent_of_code_2022 | Apache License 2.0 |
src/main/kotlin/aoc/day2/RockPaperScissors.kt | hofiisek | 573,543,194 | false | {"Kotlin": 17421} | package aoc.day2
import aoc.loadInput
import java.io.File
/**
* https://adventofcode.com/2022/day/2
*
* @author <NAME>
*/
sealed class Outcome(val score: Int)
object Lose : Outcome(0)
object Draw : Outcome(3)
object Win : Outcome(6)
sealed class Shape(val score: Int)
object Rock : Shape(1)
object Paper : Shape(2)
object Scissors : Shape(3)
fun String.asShape() = when (this) {
"A", "X" -> Rock
"B", "Y" -> Paper
"C", "Z" -> Scissors
else -> throw IllegalArgumentException("Invalid shape: $this")
}
fun String.asOutcome(): Outcome = when (this) {
"X" -> Lose
"Y" -> Draw
"Z" -> Win
else -> throw IllegalArgumentException("Invalid shape: $this")
}
infix fun Shape.fight(opponent: Shape): Int = when {
this == opponent -> score + Draw.score
this is Rock && opponent is Scissors -> score + Win.score
this is Paper && opponent is Rock -> score + Win.score
this is Scissors && opponent is Paper -> score + Win.score
else -> score + Lose.score
}
infix fun Shape.yourShapeFor(outcome: Outcome): Shape = when {
outcome is Draw -> this
this is Paper && outcome == Win -> Scissors
this is Paper && outcome == Lose -> Rock
this is Rock && outcome == Win -> Paper
this is Rock && outcome == Lose -> Scissors
this is Scissors && outcome == Win -> Rock
this is Scissors && outcome == Lose -> Paper
else -> throw IllegalArgumentException("Invalid combination of shape $this and outcome $outcome")
}
fun File.part1() = readLines()
.map { it.split(" ").map(String::asShape) }
.sumOf { (opponent, you) -> you fight opponent }
.also(::println)
fun File.part2() = readLines()
.map { it.split(" ") }
.map { (opponent, outcome) -> opponent.asShape() to outcome.asOutcome() }
.sumOf { (opponent, outcome) -> outcome.score + (opponent yourShapeFor outcome).score }
.also(::println)
fun main() {
with(loadInput(day = 2)) {
part1()
part2()
}
} | 0 | Kotlin | 0 | 2 | 5908a665db4ac9fc562c44d6907f81cd3cd8d647 | 1,978 | Advent-of-code-2022 | MIT License |
src/aoc2017/kot/Day25.kt | Tandrial | 47,354,790 | false | null | package aoc2017.kot
import getNumbers
import getWords
import java.io.File
object Day25 {
data class Rule(val write: Int, val move: Int, val nextState: String)
fun solve(input: List<String>): Int {
val rules = mutableMapOf<Pair<String, Int>, Rule>()
val rulesText = input.drop(3)
for ((idx, line) in rulesText.withIndex()) {
if (line.contains("In state ")) {
val words = line.dropLast(1).split(" ")
val state = words.last()
for (value in 0..1) {
val values = generateSequence(idx + 2 + value * 4) { it + 1 }.take(3).map { rulesText[it].dropLast(1).split(" ").last() }.toList()
val write = values[0].toInt()
val move = if (values[1] == "right") 1 else -1
val nextState = values[2]
rules[Pair(state, value)] = Rule(write, move, nextState)
}
}
}
val checkAfter = input[1].getNumbers().first()
var currState = input[0].getWords().last()
val tape = mutableListOf(0)
var pos = 0
repeat(checkAfter) {
val rule = rules[Pair(currState, tape[pos])]!!
tape[pos] = rule.write
pos += rule.move
if (pos < 0) {
tape.add(0, 0)
pos = 0
} else if (pos >= tape.size) {
tape.add(0)
}
currState = rule.nextState
}
return tape.sum()
}
}
fun main(args: Array<String>) {
val input = File("./input/2017/Day25_input.txt").readLines()
println("Part One = ${Day25.solve(input)}")
}
| 0 | Kotlin | 1 | 1 | 9294b2cbbb13944d586449f6a20d49f03391991e | 1,476 | Advent_of_Code | MIT License |
src/Day18.kt | frozbiz | 573,457,870 | false | {"Kotlin": 124645} | import java.util.BitSet
class Point3D(val x: Int, val y: Int, val z: Int) {
fun adjacentPoints() = sequence {
yield(Point3D(x - 1, y, z))
yield(Point3D(x + 1 , y, z))
yield(Point3D(x, y - 1, z))
yield(Point3D(x, y + 1, z))
yield(Point3D(x, y, z - 1))
yield(Point3D(x, y, z + 1))
}
fun adjacentPointsList() = adjacentPoints().toList()
infix fun notGreaterThan(point: Point3D): Boolean {
return x <= point.x && y <= point.y && z <= point.z
}
companion object {
fun fromString(string: String): Point3D {
val (x,y,z) = string.split(',').map { it.trim().toInt() }
return Point3D(x, y, z)
}
}
override fun toString(): String {
return "Point($x, $y, $z)"
}
override fun hashCode(): Int {
return x + y.rotateLeft(Int.SIZE_BITS/3) + z.rotateRight(Int.SIZE_BITS/3)
}
override fun equals(other: Any?): Boolean {
return super.equals(other) || (
other is Point3D && (
x == other.x &&
y == other.y &&
z == other.z
)
)
}
}
class Grid3D {
val grid = mutableMapOf<Pair<Int, Int>, BitSet>()
operator fun contains(point: Point3D): Boolean {
if (point.x < 0) return false
return grid[point.y to point.z]?.get(point.x) == true
}
operator fun set(point: Point3D, value: Boolean) {
grid.putIfAbsent(point.y to point.z, BitSet())
val bitSet = grid[point.y to point.z] ?: throw IllegalStateException("WTF")
bitSet[point.x] = value
}
operator fun get(point3D: Point3D): Boolean {
return contains(point3D)
}
fun addPoint(point: Point3D) {
grid.putIfAbsent(point.y to point.z, BitSet())
val bitSet = grid[point.y to point.z] ?: throw IllegalStateException("WTF")
bitSet.set(point.x)
}
}
fun main() {
fun part1(input: List<String>): Int {
val grid = Grid3D()
var sides = 0
for (point in input.asSequence().map { Point3D.fromString(it) }) {
sides += 6
for (adjPoint in point.adjacentPoints()) {
if (adjPoint in grid) sides -= 2
}
grid.addPoint(point)
}
return sides
}
fun part2(input: List<String>): Int {
val grid = Grid3D()
var minPoint = Point3D(0, 0, 0)
var maxPoint = minPoint
for (point in input.asSequence().map { Point3D.fromString(it) }) {
maxPoint = Point3D(maxOf(maxPoint.x, point.x + 1), maxOf(maxPoint.y, point.y + 1), maxOf(maxPoint.z, point.z + 1))
minPoint = Point3D(minOf(minPoint.x, point.x - 1), minOf(minPoint.y, point.y - 1), minOf(minPoint.z, point.z - 1))
grid.addPoint(point)
}
var sides = 0
val testedPoints = mutableSetOf(minPoint)
val pointList = ArrayDeque(testedPoints)
while (pointList.isNotEmpty()) {
val point = pointList.removeFirst()
for (adjPoint in point.adjacentPoints().filter { it !in testedPoints && minPoint notGreaterThan it && it notGreaterThan maxPoint }) {
if (adjPoint in grid) {
++sides
} else {
pointList.add(adjPoint)
testedPoints.add(adjPoint)
}
}
}
return sides
}
// test if implementation meets criteria from the description, like:
val testInput = listOf(
"2,2,2\n",
"1,2,2\n",
"3,2,2\n",
"2,1,2\n",
"2,3,2\n",
"2,2,1\n",
"2,2,3\n",
"2,2,4\n",
"2,2,6\n",
"1,2,5\n",
"3,2,5\n",
"2,1,5\n",
"2,3,5\n",
)
check(part1(testInput) == 64)
check(part2(testInput) == 58)
val input = readInput("day18")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 4feef3fa7cd5f3cea1957bed1d1ab5d1eb2bc388 | 3,964 | 2022-aoc-kotlin | Apache License 2.0 |
src/year2022/19/Day19.kt | Vladuken | 573,128,337 | false | {"Kotlin": 327524, "Python": 16475} | package year2022.`19`
import java.util.LinkedList
import java.util.PriorityQueue
import readInput
import utils.doWithPrintedTime
data class Resources(
val ore: Int,
val clay: Int,
val obsidian: Int,
val geode: Int
) {
infix operator fun minus(resources: Resources): Resources {
return Resources(
ore = ore - resources.ore,
clay = clay - resources.clay,
obsidian = obsidian - resources.obsidian,
geode = geode - resources.geode
)
}
}
/**
* Factory blueprint for building robots
*/
data class Blueprint(
val index: Int,
val oreRobotResources: Resources,
val clayRobotResources: Resources,
val obsidianRobotResources: Resources,
val geodeRobotResources: Resources
)
/**
* Data class representing currently created robots
*/
data class RobotAmount(
val oreRobots: Int,
val clayRobots: Int,
val obsidianRobots: Int,
val geodeRobots: Int,
) {
fun plusOreRobots(amount: Int): RobotAmount = copy(oreRobots = oreRobots + amount)
fun plusClayRobots(amount: Int): RobotAmount = copy(clayRobots = clayRobots + amount)
fun plusObsidianRobots(amount: Int): RobotAmount =
copy(obsidianRobots = obsidianRobots + amount)
fun plusGeodeRobots(amount: Int): RobotAmount = copy(geodeRobots = geodeRobots + amount)
}
/**
* Tuple of currently collected [Resources], robots and remaining time
*/
data class State(
val resources: Resources,
val robotAmount: RobotAmount,
val remainingTime: Int
) : Comparable<State> {
override fun compareTo(other: State) = compareValuesBy(this, other) {
it.robotAmount.clayRobots +
it.robotAmount.oreRobots +
it.robotAmount.obsidianRobots +
it.robotAmount.geodeRobots
}
fun isBetterThan(other: State): Boolean =
resources.ore >= other.resources.ore && resources.clay >= other.resources.clay
&& resources.obsidian >= other.resources.obsidian
&& resources.geode >= other.resources.geode
&& robotAmount.oreRobots >= other.robotAmount.oreRobots
&& robotAmount.clayRobots >= other.robotAmount.clayRobots
&& robotAmount.obsidianRobots >= other.robotAmount.obsidianRobots
&& robotAmount.geodeRobots >= other.robotAmount.geodeRobots
}
/**
* Parse input and return list of [Blueprint]
*/
fun parseInput(input: List<String>): List<Blueprint> {
fun List<Int>.toBlueprint(): Blueprint {
return Blueprint(
index = get(0),
oreRobotResources = Resources(get(1), 0, 0, 0),
clayRobotResources = Resources(get(2), 0, 0, 0),
obsidianRobotResources = Resources(get(3), get(4), 0, 0),
geodeRobotResources = Resources(get(5), 0, get(6), 0),
)
}
return input
.map { line ->
line.split(" ", ":")
.mapNotNull { it.toIntOrNull() }
.toBlueprint()
}
}
/**
* Provide Initial State with remaining [time]
*/
fun partOneInitialState(time: Int): State = State(
resources = Resources(ore = 0, clay = 0, obsidian = 0, geode = 0),
robotAmount = RobotAmount(oreRobots = 1, clayRobots = 0, obsidianRobots = 0, geodeRobots = 0),
remainingTime = time
)
/**
* Calculate if there is enough resources to create robot
*/
fun Resources.isEnough(robotRequirements: Resources): Boolean {
return ore >= robotRequirements.ore
&& clay >= robotRequirements.clay
&& obsidian >= robotRequirements.obsidian
&& geode >= robotRequirements.geode
}
/**
* Small optimisation:
* We should not build robot of type A when there are resources of type A that enough for every robot.
*/
private fun decideWhatShouldWeBuild(
initialState: State,
blueprint: Blueprint
): Triple<Boolean, Boolean, Boolean> {
val shouldBuildObsidian = initialState.robotAmount.obsidianRobots < listOf(
blueprint.clayRobotResources.obsidian,
blueprint.obsidianRobotResources.obsidian,
blueprint.oreRobotResources.obsidian,
blueprint.geodeRobotResources.obsidian,
).max()
val shouldBuildClay = initialState.robotAmount.clayRobots < listOf(
blueprint.clayRobotResources.clay,
blueprint.obsidianRobotResources.clay,
blueprint.oreRobotResources.clay,
blueprint.geodeRobotResources.clay,
).max()
val shouldBuildOre = initialState.robotAmount.oreRobots < listOf(
blueprint.clayRobotResources.ore,
blueprint.obsidianRobotResources.ore,
blueprint.oreRobotResources.ore,
blueprint.geodeRobotResources.ore,
).max()
return Triple(shouldBuildObsidian, shouldBuildClay, shouldBuildOre)
}
/**
* Create set of possible next States given current initial data
* @param initialState - current state we are in
* @param afterMinute - same as current state but with resources mined and one minute spent
* @param blueprint - factory blueprint for producing robots
*/
fun buildNextStepsOfRobots(
initialState: State,
afterMinute: State,
blueprint: Blueprint
): Set<State> {
val mutableStates = mutableSetOf<State>()
val initialResources = initialState.resources
val afterResources = afterMinute.resources
/**
* Try to add state when Geode Robot is build
*/
if (initialResources.isEnough(blueprint.geodeRobotResources)) {
initialState.copy(
resources = afterResources - blueprint.geodeRobotResources,
robotAmount = initialState.robotAmount.plusGeodeRobots(1),
remainingTime = afterMinute.remainingTime
).let(mutableStates::add)
} else {
val (shouldBuildObsidian, shouldBuildClay, shouldBuildOre) = decideWhatShouldWeBuild(
initialState = initialState,
blueprint = blueprint
)
/**
* Try to add state when Obsidian Robot is build
*/
if (initialResources.isEnough(blueprint.obsidianRobotResources) && shouldBuildObsidian) {
initialState.copy(
resources = afterResources - blueprint.obsidianRobotResources,
robotAmount = initialState.robotAmount.plusObsidianRobots(1),
remainingTime = afterMinute.remainingTime
).let(mutableStates::add)
}
/**
* Try to add state when Clay Robot is build
*/
if (initialResources.isEnough(blueprint.clayRobotResources) && shouldBuildClay) {
initialState.copy(
resources = afterResources - blueprint.clayRobotResources,
robotAmount = initialState.robotAmount.plusClayRobots(1),
remainingTime = afterMinute.remainingTime
).let(mutableStates::add)
}
/**
* Try to add state when Ore Robot is build
*/
if (initialResources.isEnough(blueprint.oreRobotResources) && shouldBuildOre) {
initialState.copy(
resources = afterResources - blueprint.oreRobotResources,
robotAmount = initialState.robotAmount.plusOreRobots(1),
remainingTime = afterMinute.remainingTime
).let(mutableStates::add)
}
/**
* Add state when nothing is build
*/
mutableStates.add(afterMinute)
}
return mutableStates
}
/**
* Create new state with mined resources and 1 minute spent
*/
fun State.mineAllOre(): State {
return copy(
resources = resources.copy(
ore = resources.ore + robotAmount.oreRobots,
clay = resources.clay + robotAmount.clayRobots,
obsidian = resources.obsidian + robotAmount.obsidianRobots,
geode = resources.geode + robotAmount.geodeRobots,
),
remainingTime = remainingTime - 1
)
}
/**
* Calculate max geodes for current [Blueprint]
*/
fun calculateMaxGeodes(initialState: State, blueprint: Blueprint): Int {
val stateQueue = LinkedList<State>().also { it.add(initialState) }
val visitedStates = mutableSetOf<State>()
val bestStates = PriorityQueue<State>()
fun tryAddState(state: State) {
if (state in visitedStates) return
visitedStates.add(state)
if (bestStates.any { it.isBetterThan(state) }) return
bestStates.add(state)
if (bestStates.size > 1000) bestStates.poll()
stateQueue.add(state)
}
var maxGeodes = 0
while (stateQueue.isNotEmpty()) {
val currentState = stateQueue.remove()
val stateWithMinedOres = currentState.mineAllOre()
if (stateWithMinedOres.remainingTime == 0) {
maxGeodes = maxOf(maxGeodes, stateWithMinedOres.resources.geode)
continue
}
buildNextStepsOfRobots(currentState, stateWithMinedOres, blueprint)
.forEach { newState -> tryAddState(newState) }
}
return maxGeodes
}
fun main() {
fun part1(input: List<String>): Int {
val blueprints = parseInput(input)
val createInitialState = partOneInitialState(24)
return blueprints.sumOf { it.index * calculateMaxGeodes(createInitialState, it) }
}
fun part2(input: List<String>): Int {
val first3Blueprints = parseInput(input).take(3)
val createInitialState = partOneInitialState(32)
return first3Blueprints
.map { calculateMaxGeodes(createInitialState, it) }
.fold(1) { left, right -> left * right }
}
val testInput = readInput("Day19_test")
val input = readInput("Day19")
doWithPrintedTime("Test 1") { part1(testInput) }
doWithPrintedTime("Part 1") { part1(input) }
doWithPrintedTime("Part 2") { part2(input) }
}
| 0 | Kotlin | 0 | 5 | c0f36ec0e2ce5d65c35d408dd50ba2ac96363772 | 9,733 | KotlinAdventOfCode | Apache License 2.0 |
src/day18/Day18.kt | easchner | 572,762,654 | false | {"Kotlin": 104604} | package day18
import readInputString
import java.lang.Integer.max
import java.lang.Math.abs
import kotlin.system.measureNanoTime
data class Point(val x: Int, val y: Int, val z: Int, var visited: Boolean = false)
fun main() {
fun part1(input: List<String>): Int {
val cubes = mutableListOf<Point>()
var totalExposed = 0
for (line in input) {
// 2,2,2
val nums = line.split(",").map { it.toInt() }
cubes.add(Point(nums[0], nums[1], nums[2]))
}
for (cube in cubes) {
val checks = listOf(-1, 1)
for (check in checks) {
// Check X
if (cubes.filter { it.x == cube.x + check && it.y == cube.y && it.z == cube.z }.isEmpty()) {
totalExposed++
}
// Check Y
if (cubes.filter { it.x == cube.x && it.y == cube.y + check && it.z == cube.z }.isEmpty()) {
totalExposed++
}
// Check Z
if (cubes.filter { it.x == cube.x && it.y == cube.y && it.z == cube.z + check }.isEmpty()) {
totalExposed++
}
}
}
return totalExposed
}
fun part2(input: List<String>): Int {
val cubes = mutableListOf<Point>()
for (line in input) {
// 2,2,2
val nums = line.split(",").map { it.toInt() }
cubes.add(Point(nums[0], nums[1], nums[2]))
}
val minX = cubes.minOf { it.x } - 1
val maxX = cubes.maxOf { it.x } + 1
val minY = cubes.minOf { it.y } - 1
val maxY = cubes.maxOf { it.y } + 1
val minZ = cubes.minOf { it.z } - 1
val maxZ = cubes.maxOf { it.z } + 1
// Fill entire possible void with water
val void = mutableListOf<Point>()
for (x in minX..maxX) {
for (y in minY..maxY) {
for (z in minZ..maxZ) {
void.add(Point(x, y, z))
}
}
}
// Remove from void all spaces occupied by cubes
for (cube in cubes) {
void.remove(cube)
}
// Traverse void from outer point
val first = void.find { it.x == minX }
val q = mutableListOf<Point>()
q.add(first!!)
while(q.isNotEmpty()) {
val next = q.removeFirst()
if (!next.visited) {
next.visited = true
val checks = listOf(-1, 1)
for (check in checks) {
// Check X
var neighbor = void.find { it.x == next.x + check && it.y == next.y && it.z == next.z }
if (neighbor != null) {
q.add(neighbor)
}
// Check Y
neighbor = void.find { it.x == next.x && it.y == next.y + check && it.z == next.z }
if (neighbor != null) {
q.add(neighbor)
}
// Check Z
neighbor = void.find { it.x == next.x && it.y == next.y && it.z == next.z + check }
if (neighbor != null) {
q.add(neighbor)
}
}
}
}
var totalExposed = 0
// Find all places where a void touches a cube
for (v in void.filter { it.visited }) {
for (c in cubes) {
if (kotlin.math.abs(v.x - c.x) == 1 && v.y == c.y && v.z == c.z) {
totalExposed++
}
if (v.x == c.x && kotlin.math.abs(v.y - c.y) == 1 && v.z == c.z) {
totalExposed++
}
if (v.x == c.x && v.y == c.y && kotlin.math.abs(v.z - c.z) == 1 ) {
totalExposed++
}
}
}
// // Alternatively, find all exposed surfaces of the void the same way we did in part 1
// // Remember to subtract out the outside of the cube, but that's easy math!
// void.removeIf { !it.visited }
// for (v in void) {
// val checks = listOf(-1, 1)
// for (check in checks) {
// // Check X
// if (void.filter { it.x == v.x + check && it.y == v.y && it.z == v.z }.isEmpty()) {
// totalExposed++
// }
//
// // Check Y
// if (void.filter { it.x == v.x && it.y == v.y + check && it.z == v.z }.isEmpty()) {
// totalExposed++
// }
//
// // Check Z
// if (void.filter { it.x == v.x && it.y == v.y && it.z == v.z + check }.isEmpty()) {
// totalExposed++
// }
// }
// }
// val sx = maxX - minX + 1
// val sy = maxY - minY + 1
// val sz = maxZ - minZ + 1
// val totalOutsideSides = (sx * sy + sx * sz + sy * sz) * 2
// totalExposed -= totalOutsideSides
return totalExposed
}
val testInput = readInputString("day18/test")
val input = readInputString("day18/input")
check(part1(testInput) == 64)
val time1 = measureNanoTime { println(part1(input)) }
println("Time for part 1 was ${"%,d".format(time1)} ns")
check(part2(testInput) == 58)
val time2 = measureNanoTime { println(part2(input)) }
println("Time for part 2 was ${"%,d".format(time2)} ns")
} | 0 | Kotlin | 0 | 0 | 5966e1a1f385c77958de383f61209ff67ffaf6bf | 5,523 | Advent-Of-Code-2022 | Apache License 2.0 |
src/day10/Day10.kt | henrikrtfm | 570,719,195 | false | {"Kotlin": 31473} | package day10
import utils.Resources.resourceAsListOfString
private const val ROWLENGTH = 40
private val INTERVALS = listOf(20,60,100,140,180,220)
fun main(){
val input = resourceAsListOfString("src/day10/Day10.txt")
val commands = ArrayDeque<Command>().apply { addAll(input.map{parseInput(it)})}
var register = 1
var cycle = 0
var crt = ""
var signalStrength = 0
fun part1(commands: ArrayDeque<Command>): Int{
while(commands.isNotEmpty()){
cycle +=1
val command = commands.removeFirst()
if(cycle in INTERVALS){
signalStrength += (cycle * register)
}
when{
command.instruction == "noop" -> {}
command.cycles == 0 -> register += command.value
else -> {
command.reduceCycle()
commands.addFirst(command)
}
}
}
return signalStrength
}
fun part2(commands: ArrayDeque<Command>): String{
while(commands.isNotEmpty()){
val command = commands.removeFirst()
crt += when (cycle % ROWLENGTH) {
in sprites(register) -> "#"
else -> "."
}
cycle +=1
when{
command.instruction == "noop" -> {}
command.cycles == 0 -> register += command.value
else -> {
command.reduceCycle()
commands.addFirst(command)
}
}
}
return crt
}
println(part1(commands))
part2(commands).chunked(40).forEach { println(it) }
}
fun sprites(register: Int): List<Int>{
return listOf(register-1,register,register+1)
}
fun parseInput(line: String): Command {
val instruction = line.substringBefore(" ")
val value = line.substringAfter(" ").toIntOrNull() ?: 0
val cycles = when(instruction){
"addx" -> 1
else -> 0
}
return Command(instruction, value, cycles)
}
class Command(val instruction: String, val value: Int, var cycles: Int) {
fun reduceCycle(){
this.cycles -= 1
}
}
| 0 | Kotlin | 0 | 0 | 20c5112594141788c9839061cb0de259f242fb1c | 2,201 | aoc2022 | Apache License 2.0 |
src/chapter5/section2/ex22_TypingMonkeys.kt | w1374720640 | 265,536,015 | false | {"Kotlin": 1373556} | package chapter5.section2
import chapter5.section1.Alphabet
import edu.princeton.cs.algs4.StdRandom
import extensions.formatDouble
import extensions.formatInt
/**
* 打字的猴子
* 假设有一只会打字的猴子,它打出每个字母的概率为p,结束一个单词的概率为1-26p。
* 编写一个程序,计算产生各种长度的单词的概率分布。
* 其中如果"abc"出现了多次,只计算一次。
*
* 解:p的大小应该小于1/26,才会有概率结束单词
* 根据给定概率生成索引可以可以参考StdRandom的discrete()方法或练习1.1.36
*/
fun ex22_TypingMonkeys(p: Double, N: Int): Array<Double> {
require(p > 0.0 && p < 1.0 / 26)
val probabilities = DoubleArray(27) {
if (it == 26) {
1.0 - 26 * p
} else {
p
}
}
val alphabet = Alphabet.LOWERCASE
val st = TrieST<Int>(alphabet)
val stringBuilder = StringBuilder()
repeat(N) {
val index = StdRandom.discrete(probabilities)
if (index == 26) {
st.put(stringBuilder.toString(), 0)
stringBuilder.clear()
} else {
stringBuilder.append(alphabet.toChar(index))
}
}
if (stringBuilder.isNotEmpty()) {
st.put(stringBuilder.toString(), 0)
}
val iterable = st.keys()
var maxLength = 0
iterable.forEach {
if (it.length > maxLength) {
maxLength = it.length
}
}
val array = Array(maxLength + 1) { 0.0 }
var count = 0
iterable.forEach {
array[it.length]++
count++
}
for (i in array.indices) {
array[i] = array[i] / count
}
return array
}
fun main() {
// 1/26 约等于 0.03846
val p = 0.02
val N = 100_0000
val array = ex22_TypingMonkeys(p, N)
var length = 0
println(array.joinToString(separator = "\n") { "length=${formatInt(length++, 3, alignLeft = true)} ${formatDouble(it, 10)}" })
}
| 0 | Kotlin | 1 | 6 | 879885b82ef51d58efe578c9391f04bc54c2531d | 1,967 | Algorithms-4th-Edition-in-Kotlin | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/ReduceArraySizeToTheHalf.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2020 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import java.util.PriorityQueue
/**
* Given an array arr. You can choose a set of integers and remove all the occurrences of these integers in the array.
* Return the minimum size of the set so that at least half of the integers of the array are removed.
*/
fun interface MinSetSize {
operator fun invoke(arr: IntArray): Int
}
class MinSetSizeHashMap : MinSetSize {
override operator fun invoke(arr: IntArray): Int {
return arr.minSetSize()
}
private fun IntArray.minSetSize(): Int {
val map = hashMapOf<Int, Int>()
val list: Array<MutableList<Int>?> = Array(size + 1) { mutableListOf<Int>() }
var steps = 0
var res = 0
for (num in this) {
map[num] = map.getOrDefault(num, 0) + 1
}
for (num in map.keys) {
val count = map[num]
if (list[count!!] == null) {
list[count] = ArrayList<Int>()
}
list[count]?.add(num)
}
for (i in size downTo 0) {
val cur = list[i]
if (cur.isNullOrEmpty()) continue
for (num in cur) {
steps += i
res++
if (steps >= size / 2) {
return res
}
}
}
return this.size
}
}
class MinSetSizePriorityQueue : MinSetSize {
override operator fun invoke(arr: IntArray): Int {
return arr.minSetSize2()
}
private fun IntArray.minSetSize2(): Int {
val map = hashMapOf<Int, Int>()
var res = 0
var sum = 0
for (num in this) {
map[num] = map.getOrDefault(num, 0) + 1
}
val pq = PriorityQueue<Int> { c, d -> d - c }
for (n in map.keys) {
pq.offer(map[n])
}
while (pq.isNotEmpty()) {
sum += pq.poll()
res++
val local = size + 1
if (sum >= local / 2) return res
}
return 0
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,643 | kotlab | Apache License 2.0 |
src/main/kotlin/aoc2022/Day22.kt | j4velin | 572,870,735 | false | {"Kotlin": 285016, "Python": 1446} | package aoc2022
import Point
import readInput
object Day22 {
private enum class Rotation {
COUNTERCLOCKWISE, CLOCKWISE, NONE;
companion object {
fun fromChar(c: Char) = when (c) {
'R' -> CLOCKWISE
'L' -> COUNTERCLOCKWISE
else -> NONE
}
}
}
private data class Movement(val distance: Int, val rotation: Rotation)
private class Input(val grid: Array<CharArray>, val movements: List<Movement>) {
companion object {
fun fromString(input: List<String>): Input {
val grid = input.takeWhile { it.isNotEmpty() }.map { it.toCharArray() }.toTypedArray()
val movements =
input.dropWhile { it.isNotEmpty() }.drop(1).take(1).first().split(Regex("(?<=[RL])")).map {
if (it.endsWith("R") || it.endsWith("L")) {
Movement(
it.substring(0, it.length - 1).toInt(),
Rotation.fromChar(it.takeLast(1).toCharArray().first())
)
} else {
// no rotation on last movement
Movement(it.toInt(), Rotation.NONE)
}
}
return Input(grid, movements)
}
}
}
private enum class Direction(val value: Int) {
UP(3), RIGHT(0), DOWN(1), LEFT(2);
fun rotate(rotation: Rotation) = when (rotation) {
Rotation.CLOCKWISE -> values()[((this.ordinal + 1) % values().size)]
Rotation.COUNTERCLOCKWISE -> values()[((this.ordinal - 1 + values().size) % values().size)]
Rotation.NONE -> this
}
}
private data class Position(val coords: Point, val direction: Direction) {
fun move(movement: Movement, grid: Array<CharArray>): Position {
val diff = when (direction) {
Direction.UP -> Point(0, -1)
Direction.DOWN -> Point(0, 1)
Direction.LEFT -> Point(-1, 0)
Direction.RIGHT -> Point(1, 0)
}
var newCoordinates = coords
repeat(movement.distance) {
var newTile = ' '
var newPoint = newCoordinates
while (newTile == ' ') {
if (direction == Direction.UP || direction == Direction.DOWN) {
newPoint = Point(coords.x, (newPoint.y + diff.y + grid.size) % grid.size)
// new line might not be as "width" as the current one (there is no ' '-padding on the right side)
if (newPoint.x >= grid[newPoint.y].size) {
newTile = ' '
continue
}
} else {
newPoint = Point((newPoint.x + diff.x + grid[coords.y].size) % grid[coords.y].size, coords.y)
}
newTile = grid[newPoint.y][newPoint.x]
}
when (newTile) {
'.' -> newCoordinates = newPoint
'#' -> return@repeat
else -> throw IllegalStateException("Invalid grid: ${newPoint.x}, ${newPoint.y} == ${grid[newPoint.y][newPoint.x]}")
}
}
val newDirection = direction.rotate(movement.rotation)
return Position(newCoordinates, newDirection)
}
}
fun part1(input: List<String>): Int {
val data = Input.fromString(input)
val startY = data.grid.indexOfFirst { it.contains('.') }
val startX = data.grid[startY].indexOfFirst { it == '.' }
var currentPosition = Position(Point(startX, startY), Direction.RIGHT)
data.movements.forEach {
currentPosition = currentPosition.move(it, data.grid)
}
println(currentPosition)
return 1000 * (currentPosition.coords.y + 1) + 4 * (currentPosition.coords.x + 1) + currentPosition.direction.value
}
fun part2(input: List<String>): Int {
return 0
}
}
fun main() {
val testInput = readInput("Day22_test", 2022)
check(Day22.part1(testInput) == 6032)
check(Day22.part2(testInput) == 5031)
val input = readInput("Day22", 2022)
println(Day22.part1(input))
println(Day22.part2(input))
}
| 0 | Kotlin | 0 | 0 | f67b4d11ef6a02cba5b206aba340df1e9631b42b | 4,458 | adventOfCode | Apache License 2.0 |
src/Day09.kt | rmyhal | 573,210,876 | false | {"Kotlin": 17741} | import java.lang.IllegalArgumentException
import kotlin.math.absoluteValue
fun main() {
fun part1(input: List<String>): Int {
return first(input)
}
fun part2(input: List<String>): Int {
return second(input)
}
val input = readInput("Day09")
println(part1(input))
println(part2(input))
}
private fun first(input: List<String>): Int {
val uniqueTailsPosition = mutableSetOf<Pair<Int, Int>>()
var headPosition = 0 to 0
var tailPosition = 0 to 0
input.forEach { move ->
val line = move.split(" ")
val direction = line[0].toDir()
val amount = line[1].toInt()
for (i in 0 until amount) {
headPosition = when (direction) {
Dir.UP -> headPosition.copy(second = headPosition.second - 1)
Dir.RIGHT -> headPosition.copy(first = headPosition.first + 1)
Dir.LEFT -> headPosition.copy(first = headPosition.first - 1)
Dir.DOWN -> headPosition.copy(second = headPosition.second + 1)
}
val headX = headPosition.first
val headY = headPosition.second
val tailX = tailPosition.first
val tailY = tailPosition.second
if ((tailX - headX).absoluteValue > 1 || (tailY - headY).absoluteValue > 1) {
tailPosition = tailX + headX.compareTo(tailX) to tailY + headY.compareTo(tailY)
}
uniqueTailsPosition.add(tailPosition)
}
}
return uniqueTailsPosition.size
}
private fun second(input: List<String>): Int {
val uniqueTailsPosition = mutableSetOf<Pair<Int, Int>>()
val rope = mutableListOf<Pair<Int, Int>>()
for (i in 0 until 10) {
rope.add(0 to 0)
}
input.forEach { move ->
val line = move.split(" ")
val direction = line[0].toDir()
val amount = line[1].toInt()
for (i in 0 until amount) {
var headPosition = rope[0]
headPosition = when (direction) {
Dir.UP -> headPosition.copy(second = headPosition.second - 1)
Dir.RIGHT -> headPosition.copy(first = headPosition.first + 1)
Dir.LEFT -> headPosition.copy(first = headPosition.first - 1)
Dir.DOWN -> headPosition.copy(second = headPosition.second + 1)
}
rope[0] = headPosition
val iterator = rope.listIterator()
var first = iterator.next()
while (iterator.hasNext()) {
var second = iterator.next()
if (first == second) break
val headX = first.first
val headY = first.second
val tailX = second.first
val tailY = second.second
if ((tailX - headX).absoluteValue > 1 || (tailY - headY).absoluteValue > 1) {
val temp = tailX + headX.compareTo(tailX) to tailY + headY.compareTo(tailY)
iterator.set(temp)
second = temp
}
first = second
}
uniqueTailsPosition.add(rope.last())
}
}
return uniqueTailsPosition.size
}
private fun String.toDir(): Dir {
return when (this) {
"U" -> Dir.UP
"R" -> Dir.RIGHT
"L" -> Dir.LEFT
"D" -> Dir.DOWN
else -> throw IllegalArgumentException()
}
}
private enum class Dir {
UP,
RIGHT,
LEFT,
DOWN
} | 0 | Kotlin | 0 | 0 | e08b65e632ace32b494716c7908ad4a0f5c6d7ef | 3,062 | AoC22 | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.