path
stringlengths
5
169
owner
stringlengths
2
34
repo_id
int64
1.49M
755M
is_fork
bool
2 classes
languages_distribution
stringlengths
16
1.68k
content
stringlengths
446
72k
issues
float64
0
1.84k
main_language
stringclasses
37 values
forks
int64
0
5.77k
stars
int64
0
46.8k
commit_sha
stringlengths
40
40
size
int64
446
72.6k
name
stringlengths
2
64
license
stringclasses
15 values
src/Day02.kt
pmellaaho
573,136,030
false
{"Kotlin": 22024}
enum class Weapon(private val char: Char) { Rock('A'), // 'X' Paper('B'), // 'Y' Scissors('C'); // 'Z' companion object { fun getByChar(char: Char): Weapon { values().forEach { if (it.char == char) return it } return Rock } fun getByResult(other: Weapon, result: Result): Weapon { return when (other) { Rock -> when (result) { Result.Lose -> Scissors Result.Draw -> Rock Result.Win -> Paper } Paper -> when (result) { Result.Lose -> Rock Result.Draw -> Paper Result.Win -> Scissors } Scissors -> when (result) { Result.Lose -> Paper Result.Draw -> Scissors Result.Win -> Rock } } } } } enum class Result(private val char: Char) { Lose('X'), Draw('Y'), Win('Z'); companion object { fun getByChar(char: Char): Result { values().forEach { if (it.char == char) return it } return Lose } } } data class Round(val opponent: Weapon, val you: Weapon) { fun score() = when (opponent) { Weapon.Rock -> when (you) { Weapon.Rock -> 1 + 3 // 1 for Rock and 3 for tie Weapon.Paper -> 2 + 6 // 2 for Paper and 6 for win Weapon.Scissors -> 3 // 3 for Scissors and 0 losing } Weapon.Paper -> when (you) { Weapon.Rock -> 1 Weapon.Paper -> 2 + 3 Weapon.Scissors -> 3 + 6 } Weapon.Scissors -> when (you) { Weapon.Rock -> 1 + 6 Weapon.Paper -> 2 Weapon.Scissors -> 3 + 3 } } companion object { fun newInstance(input: String) : Round { val opponent = Weapon.getByChar(input[0]) val you = Weapon.getByResult(opponent, Result.getByChar(input[2])) return Round(opponent, you) } } } fun main() { fun part1(input: List<String>) = input.fold(0) { total, t -> total + Round.newInstance(t).score() } /** * the second column says how the round needs to end: X means you need to lose, * Y means you need to end the round in a draw, * and Z means you need to win. */ fun part2(input: List<String>) = input.fold(0) { total, t -> total + Round.newInstance(t).score() } // test if implementation meets criteria from the description, like: // val testInput = readInput("Day02_test") // val res = part2(testInput) // check(res == 12) val input = readInput("Day02") // println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
cd13824d9bbae3b9debee1a59d05a3ab66565727
2,923
AoC_22
Apache License 2.0
leetcode/src/array/Q350.kt
zhangweizhe
387,808,774
false
null
package array fun main() { // 350. 两个数组的交集 II // https://leetcode-cn.com/problems/intersection-of-two-arrays-ii/ println(intersect(intArrayOf(1,2,2,1), intArrayOf(2,2)).contentToString()) } /** * 哈希法 */ fun intersect(nums1: IntArray, nums2: IntArray): IntArray { val list = ArrayList<Int>(nums1.size) for (i in nums1) { list.add(i) } val result = ArrayList<Int>(Math.min(nums2.size, nums1.size)) for (i in nums2) { if (list.contains(i)) { result.add(i) list.remove(i) } } return result.toIntArray() } /** * 双指针法,数组需要排序 * 定义两个指针分别指向两个数组的头结点 * 如果两个指针指向的值不相等,则小指针右移一步; * 如果两个指针指向的值相等,则把值添加到结果集中,两个指针同时右移一步 * 时间复杂度O(mlogm+nlogn),排序的时间复杂度是 O(mlogm+nlogn) * 空间复杂度是O(min(m,n)) */ fun intersect1(nums1: IntArray, nums2: IntArray): IntArray { nums1.sort() nums2.sort() var p1 = 0 var p2 = 0 val result = ArrayList<Int>(Math.min(nums1.size, nums2.size)) while (p1 < nums1.size && p2 < nums2.size) { when { nums1[p1] == nums2[p2] -> { result.add(nums1[p1]) p1++ p2++ } nums1[p1] < nums2[p2] -> { p1++ } else -> { p2++ } } } return result.toIntArray() }
0
Kotlin
0
0
1d213b6162dd8b065d6ca06ac961c7873c65bcdc
1,575
kotlin-study
MIT License
src/Day05.kt
GreyWolf2020
573,580,087
false
{"Kotlin": 32400}
import java.io.File import java.util.Stack typealias Stacks<E> = List<Stack<E>> typealias StacksOfChar = Stacks<Char> fun main() { fun part1(input: String) = findCratesOnTopOfAllStacks( input, StacksOfChar::moveOneStackAtTime ) fun part2(input: String) = findCratesOnTopOfAllStacks( input, StacksOfChar::moveAllStacksOnce ) // test if implementation meets criteria from the description, like: // val testInput = readInputAsString("Day05_test") // check(part1(testInput) == "CMZ") // check(part2(testInput) == "MCD") // // val input = readInputAsString("Day05") // println(part1(input)) // println(part2(input)) } fun findCratesOnTopOfAllStacks( input: String, moveOneOrAllAtATime: StacksOfChar.(Int, Int, Int) -> StacksOfChar ): String { val (stackData, proceduresData) = input .split("\n\r\n") // separate the information of stacks from that of procedures val stackSize = stackData .toIntStackSize() // get the last number of the stacks which is in turn the size of stacks val listOfStacks = buildList { repeat(stackSize) { add(Stack<Char>()) } } stackData .lines() // get the cranes at each level of the stacks from the top .dropLast(2) // the line with the numbering of the stacks .map { it .chunked(4) .map { it[1] } } // remove the clutter such as the space and the brackets, take only the character content of the cranes .foldRight(listOfStacks) { cranes, stacks -> cranes.forEachIndexed { craneStackNum, crane -> if (crane.toString().isNotBlank()) { stacks[craneStackNum].push(crane) // push the crates into the list of stacks } } // build the initial state of the states stacks } proceduresData .lines() // get the lines of the procedures .map { it.split(" ") } .fold(listOfStacks) { stacks, procedure -> stacks .moveOneOrAllAtATime( procedure[1].toInt(), // the number of cranes to move procedure[3].toInt() - 1, // the stack to move the cranes from procedure[5].toInt() - 1 // the stack to move the cranes to ) } return buildString { listOfStacks.forEach { if (it.isEmpty()) append(" ") else append(it.pop()) } } } private fun <E> Stacks<E>.moveOneStackAtTime(crates: Int, fromStack: Int, toStack: Int): Stacks<E> = apply { repeat(crates) { if (this[fromStack].isNotEmpty()) { this[toStack].push(this[fromStack].pop()) } else this.map { println(it) } } } private fun <E> Stacks<E>.moveAllStacksOnce(crates: Int, fromStack: Int, toStack: Int): Stacks<E> = apply { val tempStack = Stack<E>() repeat(crates) { if (this[fromStack].isNotEmpty()) { tempStack.push(this[fromStack].pop()) } else this.map { println(it) } } repeat(crates) { if (tempStack.isNotEmpty()) { this[toStack].push(tempStack.pop()) } } } private fun String.toIntStackSize() = split("\n") .last()// get the labels of all the stack .split(" ")// get the list of each stack's label .last() // get the last stack's label .trim() // remove any characters around the label .toInt() // return the label as an Int
0
Kotlin
0
0
498da8861d88f588bfef0831c26c458467564c59
3,478
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/com/github/solairerove/algs4/leprosorium/matrix/BiggestNumberOfLengthFromMatrix.kt
solairerove
282,922,172
false
{"Kotlin": 251919}
package com.github.solairerove.algs4.leprosorium.matrix import kotlin.math.max import kotlin.math.pow /** * You are given a matrix of N rows and M columns. * Each field of the matrix contains a single digit (0-9). * * You want to find a path consisting of four neighboring fields. * Two fields are neighboring if they share a common side. * Also, the fields in your path should be distinct (you can't visit the same field twice). * * Return the biggest integer that you can achieve values in a path of length four. * * 1. Given the following matrix (N=3, M=5): * [ * [9, 1, 1, 0, 7], * [1, 0, 2, 1, 0], * [1, 9, 1, 1, 0] * ] * 9121. * * 2. Given the following matrix (N=3, M=3): * [ * [1, 1, 1], * [1, 3, 4], * [1, 4, 3] * ] * 4343. * * 3. Given the following matrix (N=1, M=5): * [ * [0, 1, 5, 0, 0] * ] * 1500. * * N and M are integers within the range [1..100]; * each element of matrix matrix is an integer within the range [0..9]; * there exist a path of length 4 which doesn't start with 0. * */ // O(n * m) time | O(n + m) space fun biggestNumberFromMatrix(matrix: Array<IntArray>): Int { val row = matrix.size val col = matrix[0].size // TODO: should improve dfs to delete this if (row == 1) { var ans = 0 for (i in 0 until col - 3) ans = max( ans, "${matrix[0][i]}${matrix[0][i + 1]}${matrix[0][i + 2]}${matrix[0][i + 3]}".toInt() ) for (i in col - 1 downTo 3) ans = max( ans, "${matrix[0][i]}${matrix[0][i - 1]}${matrix[0][i - 2]}${matrix[0][i - 3]}".toInt() ) return ans } // TODO: should improve dfs to delete this if (col == 1) { var ans = 0 for (i in 0 until row - 3) ans = max( ans, "${matrix[i][0]}${matrix[i + 1][0]}${matrix[i + 2][0]}${matrix[i + 3][0]}".toInt() ) for (i in row - 1 downTo 3) ans = max( ans, "${matrix[i][0]}${matrix[i - 1][0]}${matrix[i - 2][0]}${matrix[i - 3][0]}".toInt() ) return ans } var maxNumber = 0 for (r in 0 until row) { for (c in 0 until col) { maxNumber = max(maxNumber, matrix[r][c]) } } var ans = 0 val visited = Array(row) { IntArray(col) { 0 } } for (r in 0 until row) { for (c in 0 until col) { if (maxNumber == matrix[r][c]) { val shit = dsf(matrix, r, c, 4, visited) ans = max(ans, shit) } } } return ans } private fun dsf(matrix: Array<IntArray>, row: Int, col: Int, length: Int, visited: Array<IntArray>): Int { if (row < 0 || col < 0 || row >= matrix.size || col >= matrix[0].size || length == 0 || visited[row][col] == 1) return 0 val ans = matrix[row][col] * 10.0.pow(length - 1) visited[row][col] = 1 var ret = ans ret = max(ret, ans + dsf(matrix, row + 1, col, length - 1, visited)) ret = max(ret, ans + dsf(matrix, row - 1, col, length - 1, visited)) ret = max(ret, ans + dsf(matrix, row, col + 1, length - 1, visited)) ret = max(ret, ans + dsf(matrix, row, col - 1, length - 1, visited)) visited[row][col] = 0 return ret.toInt() }
1
Kotlin
0
3
64c1acb0c0d54b031e4b2e539b3bc70710137578
3,247
algs4-leprosorium
MIT License
common/graph/src/main/kotlin/com/curtislb/adventofcode/common/graph/UnweightedGraph.kt
curtislb
226,797,689
false
{"Kotlin": 2146738}
package com.curtislb.adventofcode.common.graph /** * A graph consisting of unique nodes of type [V], connected by directed edges. */ abstract class UnweightedGraph<V> { /** * Returns all nodes in the graph to which there is a directed edge from the given [node]. */ protected abstract fun getNeighbors(node: V): Iterable<V> /** * Performs a breadth-first search from [source] and applies the [process] function to each node * that is reached in order, along with the shortest distance from [source] to that node. * * This function continues searching until all nodes reachable from [source] have been processed * or until [process] returns `true`, indicating that the search should be terminated early. */ fun bfsApply(source: V, process: (node: V, distance: Long) -> Boolean) { val searchQueue = ArrayDeque<Pair<V, Long>>().apply { addLast(Pair(source, 0L)) } val visited = mutableSetOf<V>() while (searchQueue.isNotEmpty()) { val (node, distance) = searchQueue.removeFirst() // Ignore this node if it was previously visited if (node in visited) { continue } // Process this node, terminating the search if necessary if (process(node, distance)) { return } // Enqueue all unvisited neighboring nodes with distances visited.add(node) for (neighbor in getNeighbors(node)) { if (neighbor !in visited) { searchQueue.addLast(Pair(neighbor, distance + 1L)) } } } } /** * Performs a breadth-first search from [source] and returns the shortest distance to any * reachable node for which [isGoal] returns `true`. * * If no goal node is reachable from [source], this function instead returns `null`. */ fun bfsDistance(source: V, isGoal: (node: V) -> Boolean): Long? { var result: Long? = null bfsApply(source) { node, distance -> if (isGoal(node)) { result = distance true // Done searching } else { false // Not done searching } } return result } /** * Performs a depth-first search from [source] and returns a map from each reachable node for * which [isGoal] returns `true` to a list of all paths from [source] to that node. * * Each path can pass through a node at most once and is represented by an ordered list of all * nodes along the path from [source] (exclusive) to the goal node (inclusive). */ fun dfsPaths(source: V, isGoal: (node: V) -> Boolean): Map<V, List<List<V>>> { val paths = mutableMapOf<V, MutableList<List<V>>>() // If source is a goal node, add the zero-length path to it if (isGoal(source)) { paths[source] = mutableListOf(emptyList()) } dfsPathsRecursive( node = source, paths = paths, visited = mutableSetOf(), pathPrefix = mutableListOf(), isGoal = isGoal ) return paths } /** * Populates the [paths] map with all paths from [node] to any goal node, prepending the given * [pathPrefix] and ignoring any nodes that have already been [visited] along the current path. */ private fun dfsPathsRecursive( node: V, paths: MutableMap<V, MutableList<List<V>>>, visited: MutableSet<V>, pathPrefix: MutableList<V>, isGoal: (node: V) -> Boolean ) { visited.add(node) for (neighbor in getNeighbors(node)) { // Ignore visited nodes to prevent unnecessary backtracking if (neighbor in visited) { continue } // If neighbor is a goal node, record the current path to it pathPrefix.add(neighbor) if (isGoal(neighbor)) { paths.getOrPut(neighbor) { mutableListOf() }.add(pathPrefix.toList()) } // Continue searching recursively from neighbor dfsPathsRecursive( node = neighbor, paths = paths, visited = visited, pathPrefix = pathPrefix, isGoal = isGoal ) pathPrefix.removeLast() } visited.remove(node) } }
0
Kotlin
1
1
6b64c9eb181fab97bc518ac78e14cd586d64499e
4,502
AdventOfCode
MIT License
src/Day04.kt
pimts
573,091,164
false
{"Kotlin": 8145}
fun main() { fun String.ranges(): Pair<IntRange, IntRange> { val (range1Start, range1End) = substringBefore(",").split("-") val (range2Start, range2End) = substringAfter(",").split("-") return range1Start.toInt()..range1End.toInt() to range2Start.toInt()..range2End.toInt() } fun part1(input: List<String>): Int { return input.map { it.ranges() } .count { it.first.toSet().containsAll(it.second.toSet()) || it.second.toSet().containsAll(it.first.toSet()) } } fun part2(input: List<String>): Int { return input.map { it.ranges() } .count { (it.first.toSet() intersect it.second.toSet()).isNotEmpty() } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
dc7abb10538bf6ad9950a079bbea315b4fbd011b
1,024
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/sorts/SelectionSorts.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.sorts import dev.shtanko.algorithms.extensions.swap /** * Selection sort is a simple sorting algorithm dividing the input list into two parts: the sublist of items already * sorted, which is built up from left to right at the front (left) of the list, and the sublist of items remaining * to be sorted that occupy the rest of the list. Initially, the sorted sublist is empty and the unsorted sublist * is the entire input list. The algorithm proceeds by finding the smallest (or largest, depending on sorting order) * element in the unsorted sublist, exchanging (swapping) it with the leftmost unsorted element * (putting it in sorted order), and moving the sublist boundaries one element to the right. * * Worst-case performance O(n^2) * Best-case performance O(n^2) * Average performance O(n^2) * Worst-case space complexity O(1) */ class SelectionSort : AbstractSortStrategy { override fun <T : Comparable<T>> perform(arr: Array<T>) { for (i in arr.indices) { var min = i for (j in i + 1 until arr.size) { if (arr[j] < arr[min]) { min = j } } if (min != i) arr.swap(min, i) } } } class StableSelectionSort : AbstractSortStrategy { override fun <T : Comparable<T>> perform(arr: Array<T>) { for (i in arr.indices) { var min = i for (j in i + 1 until arr.size) { if (arr[j] < arr[min]) { min = j } } // Move minimum element at current i. val key = arr[min] while (min > i) { arr[min] = arr[min - 1] min-- } arr[i] = key } } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,426
kotlab
Apache License 2.0
aoc/src/main/kotlin/com/bloidonia/aoc2023/day04/Main.kt
timyates
725,647,758
false
{"Kotlin": 45518, "Groovy": 202}
package com.bloidonia.aoc2023.day04 import com.bloidonia.aoc2023.lines import kotlin.math.pow private const val example = """Card 1: 41 48 83 86 17 | 83 86 6 31 17 9 48 53 Card 2: 13 32 20 16 61 | 61 30 68 82 17 32 24 19 Card 3: 1 21 53 59 44 | 69 82 63 72 16 21 14 1 Card 4: 41 92 73 84 69 | 59 84 76 51 58 5 54 83 Card 5: 87 83 26 28 32 | 88 30 70 12 93 22 82 36 Card 6: 31 18 13 56 72 | 74 77 10 23 35 67 36 11""" private data class Card(val id: Int, val winners: List<Int>, val chosen: List<Int>, var count: Int = 1) { constructor(line: String) : this( line.split(":")[0].split(" ").last().toInt(), line.split(":")[1].split("|")[0].split(" ").filter { it.isNotEmpty() }.map { it.toInt() }.toList(), line.split(":")[1].split("|")[1].split(" ").filter { it.isNotEmpty() }.map { it.toInt() }.toList() ) fun score() = chosen.count { winners.contains(it) }.let { matches -> if (matches == 0) 0 else 2.0.pow(matches - 1).toInt() } fun win(cards: List<Card>) = chosen.count { winners.contains(it) }.let { matches -> generateSequence(id) { it + 1 }.take(matches).forEach { cards[it].count += count } } } fun main() { val exampleCards = example.lines().map(::Card) println("Example: ${exampleCards.sumOf(Card::score)}") val input = lines("/day04.input").map(::Card).toList() println("Part 1: ${input.sumOf(Card::score)}") exampleCards.forEach { it.win(exampleCards) } println("Example: ${exampleCards.sumOf(Card::count)}") input.forEach { it.win(input) } println("Part 2: ${input.sumOf(Card::count)}") }
0
Kotlin
0
0
158162b1034e3998445a4f5e3f476f3ebf1dc952
1,629
aoc-2023
MIT License
src/Day03.kt
polbins
573,082,325
false
{"Kotlin": 9981}
fun main() { fun part1(input: List<String>): Int { val charPriority = buildCharPriority() var result = 0 for (s in input) { val left = s.substring(0, s.length / 2).toSet() val right = s.substring(s.length / 2, s.length).toSet() val intersection = left.intersect(right).first() result += charPriority[intersection]!! } return result } fun part2(input: List<String>): Int { val charPriority = buildCharPriority() var result = 0 val group: MutableList<Set<Char>> = mutableListOf() group.clear() for (s in input) { group.add(s.toSet()) if (group.size == 3) { val intersection = group[0].intersect(group[1]).intersect(group[2]).first() result += charPriority[intersection]!! group.clear() } } return result } // test if implementation meets criteria from the description, like: val testInput1 = readInput("Day03_test") check(part1(testInput1) == 157) val input1 = readInput("Day03") println(part1(input1)) val testInput2 = readInput("Day03_test") check(part2(testInput2) == 70) val input2 = readInput("Day03") println(part2(input2)) } fun buildCharPriority(): Map<Char, Int> { var num = 1 val result = mutableMapOf<Char, Int>() for (c in 'a'..'z') { result[c] = num++ } for (c in 'A'..'Z') { result[c] = num++ } return result }
0
Kotlin
0
0
fb9438d78fed7509a4a2cf6c9ea9e2eb9d059f14
1,397
AoC-2022
Apache License 2.0
src/Day04.kt
HenryCadogan
574,509,648
false
{"Kotlin": 12228}
fun main() { fun part1(input: List<String>) = checkRanges(input, IntRange::isInRange) fun part2(input: List<String>) = checkRanges(input, IntRange::overLapsWith) val input = readInput("Day04") println(part1(input)) println(part2(input)) } fun checkRanges(input: List<String>, func: IntRange.(IntRange) -> Boolean): Int{ return input.count{ ranges -> val (firstRange, secondRange) = ranges.split(',').map{it.toRange()} if (firstRange.length() > secondRange.length()){ secondRange.func(firstRange) } else { firstRange.func(secondRange) } } } fun String.toRange(): IntRange{ val bounds = split('-').map{it.toInt()} return bounds.first()..bounds[1] } fun IntRange.isInRange(otherRange: IntRange): Boolean = first in otherRange && last in otherRange fun IntRange.overLapsWith(otherRange: IntRange): Boolean = first in otherRange || last in otherRange fun IntRange.length() = last - first
0
Kotlin
0
0
0a0999007cf16c11355fcf32fc8bc1c66828bbd8
985
AOC2022
Apache License 2.0
kotlin/src/com/daily/algothrim/leetcode/RegionsBySlashes.kt
idisfkj
291,855,545
false
null
package com.daily.algothrim.leetcode /** * 959. 由斜杠划分区域 * 在由 1 x 1 方格组成的 N x N 网格 grid 中,每个 1 x 1 方块由 /、\ 或空格构成。这些字符会将方块划分为一些共边的区域。 * * (请注意,反斜杠字符是转义的,因此 \ 用 "\\" 表示。)。 * * 返回区域的数目。 */ class RegionsBySlashes { companion object { @JvmStatic fun main(args: Array<String>) { println(RegionsBySlashes().solution(arrayOf("\\/", "/\\"))) } } //输入: //[ // "\\/", // "/\\" //] //输出:4 // 每一个网格基于对角线拆分成4个三角形 fun solution(grid: Array<String>): Int { val n = grid.size // 拆分的三角形的个数 val size = 4 * n * n val unionFound = UnionFound(size) grid.forEachIndexed { i, s -> s.toCharArray().forEachIndexed { j, c -> val index = 4 * (i * n + j) when (c) { '/' -> { // 合并0 3, 1 2 unionFound.setUnion(index, index + 3) unionFound.setUnion(index + 1, index + 2) } '\\' -> { // 合并0 1, 2 3 unionFound.setUnion(index, index + 1) unionFound.setUnion(index + 2, index + 3) } else -> { // 合并0 1 2 3 unionFound.setUnion(index, index + 1) unionFound.setUnion(index + 1, index + 2) unionFound.setUnion(index + 2, index + 3) } } // 从左向右 合并单元格 if (j + 1 < n) { unionFound.setUnion(index + 1, 4 * (i * n + j + 1) + 3) } // 从上到下 合并单元格 if (i + 1 < n) { unionFound.setUnion(index + 2, 4 * ((i + 1) * n + j)) } } } return unionFound.count } class UnionFound(n: Int) { private val p = Array(n) { it } var count = n private fun find(index: Int): Int = if (index == p[index]) index else find(p[index]) fun setUnion(x: Int, y: Int) { val xP = find(x) val yP = find(y) if (xP == yP) return p[xP] = yP count-- } } }
0
Kotlin
9
59
9de2b21d3bcd41cd03f0f7dd19136db93824a0fa
2,578
daily_algorithm
Apache License 2.0
advent-of-code/src/main/kotlin/com/akikanellis/adventofcode/year2022/Day18.kt
akikanellis
600,872,090
false
{"Kotlin": 142932, "Just": 977}
package com.akikanellis.adventofcode.year2022 object Day18 { fun surfaceAreaOfScannedLavaDroplet(input: String): Int { val cubes = cubes(input) return cubes .flatMap { cube -> cube.neighbours } .count { potentialNeighbour -> potentialNeighbour !in cubes } } fun surfaceAreaOfScannedLavaDropletWithoutAirPockets(input: String): Int { val cubes = cubes(input) val minToMaxDimensionBounds = minToMaxDimensionBounds(cubes) val visitedCubes = mutableSetOf<Point3D>() val cubesToVisit = mutableListOf( Point3D( minToMaxDimensionBounds.first, minToMaxDimensionBounds.first, minToMaxDimensionBounds.first ) ) var surfaceArea = 0 while (cubesToVisit.isNotEmpty()) { val nextCube = cubesToVisit.removeFirst() if (nextCube in visitedCubes) continue visitedCubes += nextCube nextCube .neighbours .filter { potentialNeighbour -> potentialNeighbour.withinBounds(minToMaxDimensionBounds) } .forEach { potentialNeighbour -> if (potentialNeighbour in cubes) { surfaceArea++ } else { cubesToVisit += potentialNeighbour } } } return surfaceArea } private fun cubes(input: String) = input.lines() .filter { it.isNotBlank() } .map { it.split(",") } .map { Point3D( it[0].toInt(), it[1].toInt(), it[2].toInt() ) }.toSet() private fun minToMaxDimensionBounds(cubes: Set<Point3D>): IntRange { val minDimension = cubes.minOf { it.minDimension } val maxDimension = cubes.maxOf { it.maxDimension } return minDimension - 1..maxDimension + 1 } private data class Point3D(val x: Int, val y: Int, val z: Int) { val minDimension = minOf(x, y, z) val maxDimension = maxOf(x, y, z) val neighbours by lazy { listOf( copy(x = x - 1), copy(y = y - 1), copy(z = z - 1), copy(x = x + 1), copy(y = y + 1), copy(z = z + 1) ) } fun withinBounds(bounds: IntRange) = x in bounds && y in bounds && z in bounds } }
8
Kotlin
0
0
036cbcb79d4dac96df2e478938de862a20549dce
2,547
advent-of-code
MIT License
hoon/HoonAlgorithm/src/main/kotlin/programmers/lv01/Lv1_86051.kt
boris920308
618,428,844
false
{"Kotlin": 137657, "Swift": 35553, "Java": 1947, "Rich Text Format": 407}
package main.kotlin.programmers.lv01 /** * * https://school.programmers.co.kr/learn/courses/30/lessons/86051?language=kotlin * * 문제 설명 * 0부터 9까지의 숫자 중 일부가 들어있는 정수 배열 numbers가 매개변수로 주어집니다. * numbers에서 찾을 수 없는 0부터 9까지의 숫자를 모두 찾아 더한 수를 return 하도록 solution 함수를 완성해주세요. * * 제한사항 * 1 ≤ numbers의 길이 ≤ 9 * 0 ≤ numbers의 모든 원소 ≤ 9 * numbers의 모든 원소는 서로 다릅니다. * 입출력 예 * numbers result * [1,2,3,4,6,7,8,0] 14 * [5,8,4,0,6,7,9] 6 * 입출력 예 설명 * 입출력 예 #1 * * 5, 9가 numbers에 없으므로, 5 + 9 = 14를 return 해야 합니다. * 입출력 예 #2 * * 1, 2, 3이 numbers에 없으므로, 1 + 2 + 3 = 6을 return 해야 합니다. * */ fun main() { solution(intArrayOf(1,2,3,4,6,7,8,0)) } private fun solution(numbers: IntArray): Int { var answer: Int = 0 for (i in 0..9) { if (!(numbers.contains(i))) { answer += i } } println("answer = $answer") return answer } private fun solution_1(numbers: IntArray): Int = (0..9).filterNot(numbers::contains).sum() private fun solution_2(numbers: IntArray): Int = 45 - numbers.sum()
1
Kotlin
1
2
88814681f7ded76e8aa0fa7b85fe472769e760b4
1,313
HoOne
Apache License 2.0
leetcode/src/offer/middle/Offer47.kt
zhangweizhe
387,808,774
false
null
package offer.middle fun main() { // 剑指 Offer 47. 礼物的最大价值 // https://leetcode.cn/problems/li-wu-de-zui-da-jie-zhi-lcof/ } fun maxValue(grid: Array<IntArray>): Int { /** * 关键点:grid[i][j] 的最大值,只能来自于它上边grid[i][j-1] 的元素,或者它左边grid[i-1][j] 的元素 * 对于首行、首列的元素,上一个礼物最大价值,只能来自于它的左边(首行)、上边(首列) */ val rowCount = grid.size val columnCount = grid[0].size val dp = Array<IntArray>(rowCount) { IntArray(columnCount) } dp[0][0] = grid[0][0] for (i in 0 until rowCount) { for (j in 0 until columnCount) { if (i == 0 && j == 0) { // 左上角第一个元素,不用计算 continue } if (i == 0) { // 首行的元素,上一个礼物价值总量,只能来自于它左边的元素 dp[i][j] = dp[i][j-1] + grid[i][j] continue } if (j == 0) { // 首列的元素,上一个礼物价值总量,只能来自于它上边的元素 dp[i][j] += dp[i-1][j] + grid[i][j] continue } // 不是首行,也不是首列,取它左边或者上边中价值量较大的一个 dp[i][j] = grid[i][j] + Math.max(dp[i][j-1], dp[i-1][j]) } } return dp[rowCount-1][columnCount-1] } fun maxValue1(grid: Array<IntArray>): Int { // 优化版本,使用原来的 grid 数组作为 dp 数组,空间复杂度降到O(1) val rowCount = grid.size val columnCount = grid[0].size for (i in 0 until rowCount) { for (j in 0 until columnCount) { if (i == 0 && j == 0) { // 左上角第一个元素 continue }else if (i == 0) { // 首行 grid[i][j] += grid[i][j-1] }else if (j == 0) { // 首列 grid[i][j] += grid[i-1][j] }else { // 不是首行或首列 grid[i][j] += Math.max(grid[i][j-1], grid[i-1][j]) } } } return grid[rowCount-1][columnCount-1] }
0
Kotlin
0
0
1d213b6162dd8b065d6ca06ac961c7873c65bcdc
2,300
kotlin-study
MIT License
src/main/kotlin/de/niemeyer/aoc2022/Day15.kt
stefanniemeyer
572,897,543
false
{"Kotlin": 175820, "Shell": 133}
/** * Advent of Code 2022, Day 15: Beacon Exclusion Zone * Problem Description: https://adventofcode.com/2022/day/15 */ package de.niemeyer.aoc2022 import de.niemeyer.aoc.points.Point2D import de.niemeyer.aoc.utils.Resources.resourceAsList import de.niemeyer.aoc.utils.getClassName import de.niemeyer.aoc.utils.intersects import de.niemeyer.aoc.utils.union import kotlin.math.absoluteValue val inputSensorLineRegex = """Sensor at x=([-]?\d+), y=([-]?\d+): closest beacon is at x=([-]?\d+), y=([-]?\d+)""".toRegex() fun String.toSensorBeacon(): Pair<Point2D, Point2D> { val (sensorX, sensorY, beaconX, beaconY) = inputSensorLineRegex .matchEntire(this) ?.destructured ?: throw IllegalArgumentException("Incorrect move input line $this") return Point2D(sensorX.toInt(), sensorY.toInt()) to Point2D(beaconX.toInt(), beaconY.toInt()) } fun main() { val sensors = mutableMapOf<Point2D, Int>() val beacons = mutableSetOf<Point2D>() fun parseInput(input: List<String>) { sensors.clear() beacons.clear() input.map { it.toSensorBeacon() } .forEach { (sensor, beacon) -> sensors[sensor] = sensor manhattanDistanceTo beacon beacons += beacon } } fun part1(input: List<String>, row: Int): Int { parseInput(input) val sensorCandidates = sensors.filter { (it.key.y - row).absoluteValue <= it.value } val numBeaconsInRos = beacons.filter { it.y == row }.size val beaconFree = mutableSetOf<Int>() sensorCandidates.forEach { (sensor, distance) -> val xdist = distance - (sensor.y - row).absoluteValue (sensor.x - xdist..sensor.x + xdist).forEach { beaconFree += it } } return beaconFree.size - numBeaconsInRos } fun part2(input: List<String>, maxCoord: Int): Long { parseInput(input) for (y in 0..maxCoord) { val sensorCandidates = sensors.filter { (it.key.y - y).absoluteValue <= it.value } val sensorRanges = sensorCandidates.map { sensor -> val xdist = sensor.value - (sensor.key.y - y).absoluteValue maxOf(0, sensor.key.x - xdist)..minOf(maxCoord, sensor.key.x + xdist) }.sortedBy { it.first } val allIntersect = sensorRanges.reduce { acc, range -> val (union, distinct) = unionOrMissing(acc, range) if (distinct != IntRange.EMPTY) { return@part2 distinct.first.toLong() * 4_000_000L + y } union } if (allIntersect.first != 0 || allIntersect.last != maxCoord) { error("something strange happened") } } return 0L } val name = getClassName() val testInput = resourceAsList(fileName = "${name}_test.txt") val puzzleInput = resourceAsList(fileName = "${name}.txt") check(part1(testInput, 10) == 26) val puzzleResultPart1 = part1(puzzleInput, 2_000_000) println(puzzleResultPart1) check(puzzleResultPart1 == 4_827_924) check(part2(testInput, 20) == 56_000_011L) val puzzleResultPart2 = part2(puzzleInput, 4_000_000) println(puzzleResultPart2) check(puzzleResultPart2 == 12_977_110_973_564L) } fun unionOrMissing(a: IntRange, b: IntRange): Pair<IntRange, IntRange> { if (a intersects b) { return (a union b) to IntRange.EMPTY } if (a.first < b.first) { // 0..10 12..20 return IntRange.EMPTY to ((a.last + 1) until b.first) } // 12..20 0..10 return IntRange.EMPTY to ((b.last + 1) until a.first) }
0
Kotlin
0
0
ed762a391d63d345df5d142aa623bff34b794511
3,689
AoC-2022
Apache License 2.0
src/Day14.kt
makohn
571,699,522
false
{"Kotlin": 35992}
fun main() { val day = "14" data class Pos(val x: Int, val y: Int) data class Path(val from: Pos, val to: Pos) { operator fun contains(other: Pos) = ((other.x in from.x .. to.x) && (other.y in from.y .. to.y)) || ((other.x in to.x .. from.x) && (other.y in to.y .. from.y)) } fun Map<Pos, Char>.bounds() = this.keys.maxOf { it.x } to this.keys.maxOf { it.y } fun Map<Pos, Char>.visualize() { val (x, y) = bounds() for (i in 0..y) { for (j in 0..x) { print(getOrDefault(Pos(j, i), '.')) } println() } } operator fun Pos.minus(other: Pos) = Pos(this.x - other.x, this.y - other.y) fun simulateSand(map: Map<Pos, Char>, sandSource: Pos, bottom: Int): Pos { var sandPos = sandSource dropSand@while (sandPos.y <= bottom && map[sandPos] == null) { for (pos in arrayOf( Pos(sandPos.x, sandPos.y+1), Pos(sandPos.x-1, sandPos.y+1), Pos(sandPos.x+1, sandPos.y+1) )) { if (map[pos] == null) { sandPos = pos continue@dropSand } } return sandPos } return sandPos } fun parseInput(input: List<String>): Pair<MutableMap<Pos, Char>, Pos> { val rockCoordinates = input .map { line -> line.split(" -> ") .map { coord -> coord.split(",") } .map { (x, y) -> Pos(x.toInt(), y.toInt()) } } val yMax = rockCoordinates.maxOf { it.maxOf { it.y } } val xMin = rockCoordinates.minOf { it.minOf { it.x } } val xMax = rockCoordinates.maxOf { it.maxOf { it.x } } val refPos = Pos(xMin, 0) val rockPaths = rockCoordinates.flatMap { it.zipWithNext().map { (a, b) -> Path(a - refPos, b - refPos) } } return buildMap { for (i in 0..yMax) { for (j in 0..xMax - xMin) { val p = Pos(j, i) if (rockPaths.any { p in it }) put(p, '#') } } }.toMutableMap() to Pos(500 - xMin, 0) } fun part1(input: List<String>): Int { val (map, source) = parseInput(input) val (_, y) = map.bounds() var sandPos = simulateSand(map, source, y) var c = 0 while (sandPos.y < y) { map[sandPos] = 'o' c++ sandPos = simulateSand(map, source, y) // map.visualize() // println() } return c } fun part2(input: List<String>): Int { val (map, source) = parseInput(input) val (_, y) = map.bounds() var sandPos = Pos(0, 0) var c = 0 while (sandPos != source) { sandPos = simulateSand(map, source, y) map[sandPos] = 'o' c++ // map.visualize() // println() } return c } // test if implementation meets criteria from the description, like: val testInput = readInput("Day${day}_test") check(part1(testInput).also { println(it) } == 24) check(part2(testInput).also { println(it) } == 93) val input = readInput("Day${day}") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
2734d9ea429b0099b32c8a4ce3343599b522b321
3,385
aoc-2022
Apache License 2.0
src/main/kotlin/com/github/davio/aoc/y2023/Day7.kt
Davio
317,510,947
false
{"Kotlin": 405939}
package com.github.davio.aoc.y2023 import com.github.davio.aoc.general.Day import com.github.davio.aoc.general.getInputAsList import com.github.davio.aoc.y2023.Day7.Card.Companion.toCard import com.github.davio.aoc.y2023.Day7.Hand.Companion.toHand /** * See [Advent of Code 2023 Day 6](https://adventofcode.com/2023/day/6#part2]) */ class Day7(exampleNumber: Int? = null) : Day(exampleNumber) { private val input = getInputAsList() private val hands = input.map { line -> val (handPart, bidPart) = line.split(' ') val hand = handPart.toHand() HandWithBid(hand, bidPart.toInt()) } override fun part1(): Long { return hands.sortedBy { it.hand }.withIndex().sumOf { (index, handWithBid) -> handWithBid.bid.toLong() * (index + 1) } } override fun part2(): Long { return hands.sortedWith(Comparator { h1, h2 -> var comparison = Comparator.naturalOrder<Rank>().compare(h1.hand.handRankPart2, h2.hand.handRankPart2) if (comparison != 0) return@Comparator comparison val cardComparator = Comparator.naturalOrder<Card>() h1.hand.cards.zip(h2.hand.cards).forEach { (myCard, otherCard) -> if (myCard == Card.JACK && otherCard != Card.JACK) return@Comparator -1 if (otherCard == Card.JACK && myCard != Card.JACK) return@Comparator 1 comparison = cardComparator.compare(myCard, otherCard) if (comparison != 0) return@Comparator comparison } 0 }).withIndex().sumOf { (index, handWithBid) -> println("${handWithBid.hand} ${handWithBid.hand.handRankPart2}") handWithBid.bid.toLong() * (index + 1) } } private enum class Rank { HIGH_CARD, ONE_PAIR, TWO_PAIR, THREE_OF_A_KIND, FULL_HOUSE, FOUR_OF_A_KIND, FIVE_OF_A_KIND } private enum class Card(val symbol: Char) { TWO('2'), THREE('3'), FOUR('4'), FIVE('5'), SIX('6'), SEVEN('7'), EIGHT('8'), NINE('9'), TEN('T'), QUEEN('Q'), JACK('J'), KING('K'), ACE('A'); companion object { fun Char.toCard() = enumValues<Card>().first { it.symbol == this } } } private data class Hand(val cards: MutableList<Card>) : Comparable<Hand> { val handRankPart1 = determineHandRankPart1() val handRankPart2 = determineHandRankPart2() fun determineHandRankPart1(): Rank { val cardsInOrder = cards.sorted() return when { cardsInOrder.first() == cardsInOrder.last() -> Rank.FIVE_OF_A_KIND cardsInOrder[0] == cardsInOrder[3] || cardsInOrder[1] == cardsInOrder[4] -> Rank.FOUR_OF_A_KIND (cardsInOrder[0] == cardsInOrder[2] && cardsInOrder[3] == cardsInOrder[4]) || (cardsInOrder[0] == cardsInOrder[1] && cardsInOrder[2] == cardsInOrder[4]) -> Rank.FULL_HOUSE cardsInOrder[0] == cardsInOrder[2] || cardsInOrder[1] == cardsInOrder[3] || cardsInOrder[2] == cardsInOrder[4] -> Rank.THREE_OF_A_KIND (cardsInOrder[0] == cardsInOrder[1] && cardsInOrder[2] == cardsInOrder[3]) || (cardsInOrder[0] == cardsInOrder[1] && cardsInOrder[3] == cardsInOrder[4]) || (cardsInOrder[1] == cardsInOrder[2] && cardsInOrder[3] == cardsInOrder[4]) -> Rank.TWO_PAIR (0..<cardsInOrder.lastIndex).any { cardsInOrder[it] == cardsInOrder[it + 1] } -> Rank.ONE_PAIR else -> Rank.HIGH_CARD } } fun determineHandRankPart2(): Rank { return Card.entries.reversed().maxOf { replacedCard -> val cardsWithWildCardReplaced = cards.map { if (it == Card.JACK) replacedCard else it } val cardsInOrder = cardsWithWildCardReplaced.sorted() when { cardsInOrder.drop(1).all { it == cardsInOrder.first() } -> Rank.FIVE_OF_A_KIND cardsInOrder[0] == cardsInOrder[3] || cardsInOrder[1] == cardsInOrder[4] -> Rank.FOUR_OF_A_KIND (cardsInOrder[0] == cardsInOrder[2] && cardsInOrder[3] == cardsInOrder[4]) || (cardsInOrder[0] == cardsInOrder[1] && cardsInOrder[2] == cardsInOrder[4]) -> Rank.FULL_HOUSE cardsInOrder[0] == cardsInOrder[2] || cardsInOrder[1] == cardsInOrder[3] || cardsInOrder[2] == cardsInOrder[4] -> Rank.THREE_OF_A_KIND (cardsInOrder[0] == cardsInOrder[1] && cardsInOrder[2] == cardsInOrder[3]) || (cardsInOrder[0] == cardsInOrder[1] && cardsInOrder[3] == cardsInOrder[4]) || (cardsInOrder[1] == cardsInOrder[2] && cardsInOrder[3] == cardsInOrder[4]) -> Rank.TWO_PAIR (0..<cardsInOrder.lastIndex).any { cardsInOrder[it] == cardsInOrder[it + 1] } -> Rank.ONE_PAIR else -> Rank.HIGH_CARD } } } infix fun Card.matches(other: Card) = this == other || this == Card.JACK || other == Card.JACK override fun compareTo(other: Hand): Int { var comparison = Comparator.naturalOrder<Rank>().compare(handRankPart1, other.handRankPart1) if (comparison != 0) return comparison val cardComparator = Comparator.naturalOrder<Card>() cards.zip(other.cards).forEach { (myCard, otherCard) -> comparison = cardComparator.compare(myCard, otherCard) if (comparison != 0) return comparison } return 0 } override fun toString() = cards.joinToString("") { it.symbol.toString() } companion object { fun String.toHand() = Hand(this.map { it.toCard() }.toMutableList()) } } private data class HandWithBid(val hand: Hand, val bid: Int) }
1
Kotlin
0
0
4fafd2b0a88f2f54aa478570301ed55f9649d8f3
6,141
advent-of-code
MIT License
src/Day04.kt
halirutan
575,809,118
false
{"Kotlin": 24802}
fun getPairOfRange(s: String): Pair<IntRange, IntRange> { val split = s.split(",").map { val lowHigh = it.split("-") IntRange(lowHigh[0].toInt(), lowHigh[1].toInt()) } return Pair(split[0], split[1]) } fun IntRange.encloses(other: IntRange): Boolean { return this.first <= other.first && this.last >= other.last } fun main() { fun part1(input: List<String>): Int { var result = 0 input.map { getPairOfRange(it) }.forEach { if (it.first.encloses(it.second) || it.second.encloses(it.first)) { result++ } } return result } fun part2(input: List<String>): Int { var result = 0 input.map { getPairOfRange(it) }.forEach { if (it.first.contains(it.second.first) || it.first.contains(it.second.last) || it.second.contains(it.first.first) || it.second.contains(it.first.last)) { result++ } } return result } val testInput = readInput("Day04_test") println("Part 1 test: ${part1(testInput)}") val realInput = readInput("Day04") println("Part 1 real: ${part1(realInput)}") println("Part 2 test: ${part2(testInput)}") println("Part 2 real: ${part2(realInput)}") }
0
Kotlin
0
0
09de80723028f5f113e86351a5461c2634173168
1,292
AoC2022
Apache License 2.0
src/main/kotlin/dp/MaxValueWord.kt
yx-z
106,589,674
false
null
package dp import util.OneArray import util.toCharOneArray // consider a solitaire game described as follows // given an array of (Char, Int), and at the start of the game, // we draw seven such tuples into our hand // in each turn, we form an English word from some or all of the tuples // we have in our hand and receive the sum of their points // if we cannot form an English word, the game ends immediately // then we repeatedly draw next tuple in the array until EITHER we have seven // tuples in our hand OR the input array is empty (using up all the tuples) // find the maximum points we can get given input Letter[1..n] containing // letters from 'a' to 'z' and Value['a'..'z'] represents the value for them // assume you can find all English words in a set of size <= 7 in O(1) time // and the Value lookup also costs O(1) time fun main(args: Array<String>) { genSets('a', 7).forEach(::println) val Letter = "adogbookalgorithm".toCharOneArray() val Value = HashMap<Char, Int>(26) ('a'..'z').forEach { Value.put(it, it - 'a' + 1) } println(Letter.maxPoint(Value)) } fun OneArray<Char>.maxPoint(Value: Map<Char, Int>): Int { val Letter = this val n = size // dp(s, i): max points when we are given A[i..n], and with s as a set of // characters currently in hand // memoization structure: HashMap<Set<Char>, Int> dp[1..26C7, 1..n + 1] : // (dp[s])[i] = dp(s, i) val dp = HashMap<Set<Char>, OneArray<Int>>() // space complexity: O(n) since 26C7 = 26! / (7! * (26 - 7)!) ~ O(1) still // base case: // dp(s, i) = score(s), i > n // how can we enumerate 26C7 sets of characters? // see genSets below // due to such a large constant (as a brute force method) // i cannot actually run the code and get the result... // better idea is appreciated // recursive case: // dp(s, i) = max_s{ score(s) + dp(s', i') } // where s', i' is determined by which subset of characters we have used // dependency: dp(s, i) depends on dp(s', i') where i' > i // evaluation order: outer loop for i from n + 1 down to 1 for (i in n + 1 downTo 1) { // inner loop for s has no specific order } // we want max_s { dp(s, 1) } return dp.map { (_, v) -> v[1] }.max() ?: 0 } fun genSets(start: Char, num: Int): Set<HashSet<Char>> { if (start > 'z' || num <= 0) { return emptySet() } if (num == 1) { return (start..'z').map { hashSetOf(it) }.toSet() } val notIncludeStart = genSets(start + 1, num) val includeStart = genSets(start + 1, num - 1) includeStart.filter { it.isNotEmpty() }.forEach { it.add(start) } return includeStart + notIncludeStart }
0
Kotlin
0
1
15494d3dba5e5aa825ffa760107d60c297fb5206
2,612
AlgoKt
MIT License
src/main/kotlin/de/nilsdruyen/aoc/Day02.kt
nilsjr
571,758,796
false
{"Kotlin": 15971}
package de.nilsdruyen.aoc fun main() { fun part1(input: List<String>): Int { val gameScore = input.map { it.first() to it[2] }.sumOf { val result = it.first.fight(it.second) getScore(result, it.second) } return gameScore } fun part2(input: List<String>): Int { val gameScore = input.map { it.first() to it[2] }.sumOf { val predicted = it.second.predictedEnd(it.first) val result = it.first.fight(predicted) getScore(result, predicted) } return gameScore } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") println("$testInput = ${part2(testInput)}") check(part2(testInput) == 12) val input = readInput("Day02") println(part1(input)) println(part2(input)) } private fun Char.predictedEnd(opponent: Char): Char { return when { this == 'X' -> when (opponent) { 'A' -> 'Z' 'B' -> 'X' 'C' -> 'Y' else -> error("unknown") } this == 'Y' -> when (opponent) { 'A' -> 'X' 'B' -> 'Y' 'C' -> 'Z' else -> error("unknown") } this == 'Z' -> when (opponent) { 'A' -> 'Y' 'B' -> 'Z' 'C' -> 'X' else -> error("unknown") } else -> error("unknown") } } private fun Char.score(): Int = when (this) { 'A' -> 1 'B' -> 2 'C' -> 3 'X' -> 1 'Y' -> 2 'Z' -> 3 else -> 0 } // won 6, draw 3, loss 0 private fun getScore(result: Int, choosed: Char): Int { val score = when (result) { 1 -> 6 0 -> 3 -1 -> 0 else -> 0 } return score + choosed.score() } // A X rock, B Y paper, C Z scissors private fun Char.fight(other: Char): Int { return when { this == 'B' && other == 'Z' -> 1 this == 'C' && other == 'X' -> 1 this == 'A' && other == 'Y' -> 1 this == 'A' && other == 'Z' -> -1 this == 'B' && other == 'X' -> -1 this == 'C' && other == 'Y' -> -1 this == 'A' && other == 'X' -> 0 this == 'B' && other == 'Y' -> 0 this == 'C' && other == 'Z' -> 0 else -> 0 } }
0
Kotlin
0
0
1b71664d18076210e54b60bab1afda92e975d9ff
2,322
advent-of-code-2022
Apache License 2.0
src/DaySeven.kt
P-ter
572,781,029
false
{"Kotlin": 18422}
import java.util.* data class File(val name: String, val size: Int) data class Folder(val name: String, val files: MutableList<File>, val folders: MutableList<Folder>) fun main() { fun parseCommand(commands: List<String>): Folder { val root = Folder("/", mutableListOf(), mutableListOf()) var currentFolder = root var folderList = mutableListOf(currentFolder) commands.subList(1, commands.size).forEach { command -> if(command == ("$ ls")) { } else if (command.contains("dir")) { val folderName = command.split(" ").last() currentFolder.folders.add(Folder(folderName, mutableListOf(), mutableListOf())) } else if (command.split(" ").first().toIntOrNull() != null) { val (size, fileName) = command.split(" ") currentFolder.files.add(File(fileName, size.toInt())) } else if (command.contains("$ cd") && !command.contains("..")) { val folderName = command.split(" ").last() currentFolder = currentFolder.folders.first { it.name == folderName } folderList.add(currentFolder) } else if (command == "$ cd ..") { currentFolder = folderList[folderList.size - 2] folderList.removeAt(folderList.size - 1) } } return root } fun partOne(fileStructure: Folder): Int { var grandTotal = 0 fun calculateSize(folder: Folder): Int { var total = 0 folder.files.forEach { total += it.size } folder.folders.forEach { total += calculateSize(it) } if(total <= 100000) { grandTotal += total } return total } calculateSize(fileStructure) return grandTotal } fun partTwo(fileStructure: Folder): Int { var grandTotal = 0 var totalList = mutableListOf<Int>() var spaceUnused = 70000000 - 46728267 var spaceRequired = 30000000 - spaceUnused fun calculateSize(folder: Folder): Int { var total = 0 folder.files.forEach { total += it.size } folder.folders.forEach { total += calculateSize(it) } if(total >= spaceRequired) { totalList.add(total) } return total } val rootSize = calculateSize(fileStructure) return totalList.min() } val input = readInput("dayseven") // val input = readInput("example") val commands = parseCommand(input) println(partOne(commands)) println(partTwo(commands)) }
0
Kotlin
0
1
e28851ee38d6de5600b54fb884ad7199b44e8373
2,663
advent-of-code-kotlin-2022
Apache License 2.0
src/year_2021/day_10/Day10.kt
scottschmitz
572,656,097
false
{"Kotlin": 240069}
package year_2021.day_10 import readInput import java.util.Stack object Day10 { /** * @return */ fun solutionOne(text: List<String>): Int { return text.sumOf { line -> findFirstIllegalCharacter(line) } } /** * @return */ fun solutionTwo(text: List<String>): Long { val solutionValues = text .filter { line -> findFirstIllegalCharacter(line) == 0 } .map { line -> completeLine(line) } .sorted() return solutionValues[solutionValues.size / 2] } private fun findFirstIllegalCharacter(text: String): Int { val leftStack = Stack<Char>() text.toCharArray().forEach { char -> when (char) { '(', '[', '{', '<' -> leftStack.push(char) ')' -> { if (leftStack.peek() == '(') { leftStack.pop() } else { return 3 } } ']' -> { if (leftStack.peek() == '[') { leftStack.pop() } else { return 57 } } '}' -> { if (leftStack.peek() == '{') { leftStack.pop() } else { return 1197 } } '>' -> { if (leftStack.peek() == '<') { leftStack.pop() } else { return 25137 } } } } return 0 } private fun completeLine(text: String): Long { val leftStack = Stack<Char>() text.toCharArray().forEach { char -> when (char) { '(', '[', '{', '<' -> leftStack.push(char) ')' -> { if (leftStack.peek() == '(') { leftStack.pop() } } ']' -> { if (leftStack.peek() == '[') { leftStack.pop() } } '}' -> { if (leftStack.peek() == '{') { leftStack.pop() } } '>' -> { if (leftStack.peek() == '<') { leftStack.pop() } } } } var score :Long = 0 val solution = mutableListOf<Char>() while (leftStack.isNotEmpty()) { when (leftStack.pop()) { '(', -> solution.add(')') '[', -> solution.add(']') '{' -> solution.add('}') '<' -> solution.add('>') } } solution.forEach { val value = when (it) { ')' -> 1 ']' -> 2 '}' -> 3 '>' -> 4 else -> 0 } score = (score * 5) + value } return score } } fun main() { val inputText = readInput("year_2021/day_10/Day10.txt") val solutionOne = Day10.solutionOne(inputText) println("Solution 1: $solutionOne") val solutionTwo = Day10.solutionTwo(inputText) println("Solution 2: $solutionTwo") }
0
Kotlin
0
0
70efc56e68771aa98eea6920eb35c8c17d0fc7ac
3,487
advent_of_code
Apache License 2.0
src/Grid2D.kt
jwklomp
572,195,432
false
{"Kotlin": 65103}
import kotlin.math.abs class Grid2D<T>(private val grid: List<List<T>>) { private val rowLength: Int = grid.size private val columnLength: Int = grid.first().size private val surrounding: List<Pair<Int, Int>> = listOf(Pair(-1, -1), Pair(-1, 0), Pair(-1, 1), Pair(0, -1), Pair(0, 1), Pair(1, -1), Pair(1, 0), Pair(1, 1)) private val adjacent: List<Pair<Int, Int>> = listOf(Pair(-1, 0), Pair(0, -1), Pair(0, 1), Pair(1, 0)) fun getNrOfRows(): Int = rowLength fun getCell(x: Int, y: Int): Cell<T> = Cell(value = grid[y][x], x = x, y = y) fun getAllCells(): List<Cell<T>> = grid.flatMapIndexed { y, row -> row.mapIndexed { x, v -> Cell(value = v, x = x, y = y) } } fun getCellsFiltered(filterFn: (Cell<T>) -> (Boolean)): List<Cell<T>> = getAllCells().filter { filterFn(it) } fun getSurrounding(x: Int, y: Int): List<Cell<T>> = filterPositions(surrounding, x, y) fun getAdjacent(x: Int, y: Int): List<Cell<T>> = filterPositions(adjacent, x, y) fun getRow(rowNr: Int): List<Cell<T>> = getCellsFiltered { it.y == rowNr }.sortedBy { it.x } // row: x variable, y fixed fun getCol(colNr: Int): List<Cell<T>> = getCellsFiltered { it.x == colNr }.sortedBy { it.y } // row: y variable,x fixed fun getNonEdges() = getCellsFiltered { it.x > 0 && it.y > 0 && it.x < rowLength && it.y < columnLength } private fun filterPositions(positions: List<Pair<Int, Int>>, x: Int, y: Int): List<Cell<T>> = positions .map { Pair(it.first + x, it.second + y) } .filter { it.first >= 0 && it.second >= 0 } .filter { it.first < rowLength && it.second < columnLength } .map { getCell(it.first, it.second) } } data class Cell<T>(val value: T, val x: Int, val y: Int) typealias Node<T> = Cell<T> //Determine if two cells are direct neighbors fun <T> Cell<T>.isNeighborOf(u: Cell<T>): Boolean { val xDist = abs(this.x - u.x) val yDist = abs(this.y - u.y) return xDist + yDist == 1 }
0
Kotlin
0
0
1b1121cfc57bbb73ac84a2f58927ab59bf158888
2,019
aoc-2022-in-kotlin
Apache License 2.0
src/main/aoc2022/Day13.kt
Clausr
575,584,811
false
{"Kotlin": 65961}
package aoc2022 class Day13(val input: String) { sealed class Packets : Comparable<Packets> { data class Single(val value: Int) : Packets() data class Multi(val packets: List<Packets>) : Packets() private fun Single.toList() = Multi(listOf(this)) override fun compareTo(other: Packets): Int { when { this is Single && other is Single -> { return this.value.compareTo(other.value) } this is Multi && other is Multi -> { repeat(minOf(this.packets.size, other.packets.size)) { i -> val comparison = this.packets[i].compareTo(other.packets[i]) if (comparison != 0) { return comparison } } return this.packets.size.compareTo(other.packets.size) } else -> when { this is Single -> return this.toList().compareTo(other) other is Single -> return this.compareTo(other.toList()) } } throw IllegalStateException("Bad comparison: $this :: $other") } companion object { fun parse(input: String): Packets { val list = input.substring(1, input.lastIndex) return Multi( if (list.isEmpty()) { emptyList() } else { buildList { var index = 0 while (index < list.length) { if (list[index] == '[') { val parenthesis = ArrayDeque<Unit>() parenthesis.addLast(Unit) var p = index + 1 while (parenthesis.isNotEmpty()) { if (list[p] == '[') { parenthesis.addLast(Unit) } else if (list[p] == ']') { parenthesis.removeLast() } p++ } add(parse(list.substring(index, p))) index = p + 1 } else { var nextIndex = list.indexOf(',', startIndex = index + 1) if (nextIndex == -1) { nextIndex = list.lastIndex + 1 } add(Single(list.substring(index, nextIndex).toInt())) index = nextIndex + 1 } } } } ) } } } private fun String.parseInputPairs(): List<Pair<Packets, Packets>> { val pairs = this.split("\n\n").map { it.split("\n") } return pairs.map { Pair(Packets.parse(it[0]), Packets.parse(it[1])) } } private fun String.parseInput(): List<Packets> { return this.split("\n").filter(String::isNotEmpty).map { Packets.parse(it) } } fun solvePart1(): Int { val res = input.parseInputPairs().mapIndexed { index, pair -> if (pair.first < pair.second) { index + 1 } else { 0 } }.sum() return res } fun solvePart2(): Int { val firstDivider = Packets.parse("[[2]]") val secondDivider = Packets.parse("[[6]]") val packets = input.parseInput().plus(listOf(firstDivider, secondDivider)).sorted() return (packets.indexOf(firstDivider) + 1) * (packets.indexOf(secondDivider) + 1) } }
1
Kotlin
0
0
dd33c886c4a9b93a00b5724f7ce126901c5fb3ea
4,050
advent_of_code
Apache License 2.0
src/Day07.kt
wgolyakov
572,463,468
false
null
fun main() { fun parse(input: List<String>): Map<List<String>, Int> { val dirSizes = mutableMapOf<List<String>, Int>() val path = mutableListOf<String>() for (line in input) { if (line[0] == '$') { if (line.startsWith("\$ cd ")) { val dir = line.substringAfter("\$ cd ") if (dir == "..") path.removeLast() else path.add(dir) } } else { if (!line.startsWith("dir ")) { val fileSize = line.substringBefore(' ').toInt() for (i in path.indices) { val dir = path.subList(0, i + 1).toList() dirSizes[dir] = (dirSizes[dir] ?: 0) + fileSize } } } } return dirSizes } fun part1(input: List<String>) = parse(input).values.filter { it <= 100000 }.sum() fun part2(input: List<String>): Int { val dirSizes = parse(input) val used = dirSizes[listOf("/")] ?: 0 val unused = 70000000 - used val toDelete = 30000000 - unused return dirSizes.values.filter { it >= toDelete }.min() } val testInput = readInput("Day07_test") check(part1(testInput) == 95437) check(part2(testInput) == 24933642) val input = readInput("Day07") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
789a2a027ea57954301d7267a14e26e39bfbc3c7
1,165
advent-of-code-2022
Apache License 2.0
src/main/kotlin/Day08.kt
gtruitt
574,758,122
false
{"Kotlin": 16663}
@file:Suppress("PackageDirectoryMismatch") package day08 import head import tail fun readForest(input: List<String>) = input .filter { it.isNotEmpty() } .map { trees -> trees.toCharArray().map { it.digitToInt() } } fun isVisible(x: Int, y: Int, forest: List<List<Int>>) = x == 0 || y == 0 || x == forest.size.dec() || y == forest.head.size.dec() || (0..x.dec()).none { forest[it][y] >= forest[x][y] } || (x.inc()..forest.size.dec()).none { forest[it][y] >= forest[x][y] } || (0..y.dec()).none { forest[x][it] >= forest[x][y] } || (y.inc()..forest.head.size.dec()).none { forest[x][it] >= forest[x][y] } fun visibleTreeCount(input: List<String>) = readForest(input).let { forest -> (forest.indices).flatMap { x -> (forest.head.indices).map { y -> isVisible(x, y, forest) } }.count { it } } tailrec fun visibleTreeCount(myHeight: Int, trees: List<Int>, count: Int = 0): Int = when { trees.isEmpty() -> count trees.head >= myHeight -> count.inc() else -> visibleTreeCount(myHeight, trees.tail, count.inc()) } fun toTheLeft(x: Int, y: Int, forest: List<List<Int>>) = (x.dec() downTo 0).map { forest[it][y] } fun toTheRight(x: Int, y: Int, forest: List<List<Int>>) = (x.inc() until forest.size).map { forest[it][y] } fun toTheTop(x: Int, y: Int, forest: List<List<Int>>) = (y.inc() until forest.head.size).map { forest[x][it] } fun toTheBottom(x: Int, y: Int, forest: List<List<Int>>) = (y.dec() downTo 0).map { forest[x][it] } fun scenicScore(x: Int, y: Int, forest: List<List<Int>>) = listOf(::toTheLeft, ::toTheRight, ::toTheTop, ::toTheBottom) .map { visibleTreeCount(forest[x][y], it(x, y, forest)) } .reduce { acc, it -> acc * it } fun maxScenicScore(input: List<String>) = readForest(input).let { forest -> (forest.indices).flatMap { x -> (forest.head.indices).map { y -> scenicScore(x, y, forest) } }.max() }
0
Kotlin
0
2
1c9940faaf7508db275942feeb38d3e57aef413f
2,112
aoc-2022-kotlin
MIT License
src/main/kotlin/de/nosswald/aoc/days/Day07.kt
7rebux
722,943,964
false
{"Kotlin": 34890}
package de.nosswald.aoc.days import de.nosswald.aoc.Day // https://adventofcode.com/2023/day/7 object Day07 : Day<Int>(7, "Camel Cards") { private const val JOKER_PART_TWO = '1' private data class Hand(val cards: String, val bidAmount: Int): Comparable<Hand> { var groups = cards .groupBy { it } .map { it.key to it.value.size } .sortedByDescending { it.second } .toMutableList() fun handleJokerCards() { cards.count { it == JOKER_PART_TWO }.let { jokerCards -> if (jokerCards in 1..4) { groups.removeIf { it.first == JOKER_PART_TWO } groups[0] = groups[0].first to groups[0].second + jokerCards } } } override fun compareTo(other: Hand): Int { return compareBy( { it.groups[0].second }, { it.groups.getOrNull(1)?.second }, Hand::cards ).compare(this, other) } } private fun parseInput(input: List<String>, partTwo: Boolean = false): List<Hand> { return input.map { line -> val (cards, bidAmount) = line.split(" ") val betterCards = cards .replace('A', Char('9'.code + 5)) .replace('K', Char('9'.code + 4)) .replace('Q', Char('9'.code + 3)) .replace('J', if (partTwo) JOKER_PART_TWO else Char('9'.code + 2)) .replace('T', Char('9'.code + 1)) return@map Hand(betterCards, bidAmount.toInt()) } } private fun calculateWinnings(hands: List<Hand>): Int { return hands .sorted() .mapIndexed { i, (_, bidAmount) -> (i + 1) * bidAmount } .sum() } override fun partOne(input: List<String>): Int = calculateWinnings(parseInput(input)) override fun partTwo(input: List<String>): Int { return parseInput(input, partTwo = true) .onEach(Hand::handleJokerCards) .run(::calculateWinnings) } @Suppress("spellCheckingInspection") override val partOneTestExamples: Map<List<String>, Int> = mapOf( listOf( "32T3K 765", "T55J5 684", "KK677 28", "KTJJT 220", "QQQJA 483", ) to 6440 ) @Suppress("spellCheckingInspection") override val partTwoTestExamples: Map<List<String>, Int> = mapOf( listOf( "32T3K 765", "T55J5 684", "KK677 28", "KTJJT 220", "QQQJA 483", ) to 5905 ) }
0
Kotlin
0
1
398fb9873cceecb2496c79c7adf792bb41ea85d7
2,643
advent-of-code-2023
MIT License
src/aoc2022/Day15_.kt
RobertMaged
573,140,924
false
{"Kotlin": 225650}
package aoc2022 import utils.Vertex import utils.checkEquals import utils.sendAnswer import kotlin.math.abs import kotlin.math.max import kotlin.math.min fun main() { fun part1(input: List<String>, y: Int): Int { val sToBMap = input.associate { line -> val (s, b) = line.split(" closest ").take(2).map { val x = it.substringAfter("x=").takeWhile { it.isDigit() || it == '-' } val y = it.substringAfter("y=").takeWhile { it.isDigit() || it == '-' } Vertex(x.toInt(), y = y.toInt()) } s to b } val counted = mutableSetOf<Int>() val becons = mutableSetOf<Int>() // steps from s to its becon , then add s+steps see it is in y val score = sToBMap/*.filter { it.key == utils.Vertex(8, 7) }*/.forEach { (s, b) -> val xSteps = abs(s.x - b.x) val ySteps = abs(s.y - b.y) if (y == b.y) { becons += b.x counted += (s.x - xSteps..s.x+xSteps)//.filter { it !in becons } return@forEach } // val steps = xSteps + ySteps if (/*ySteps == 0 && */s.y == y) { counted += (s.x-xSteps..s.x+xSteps)//.filter { it !in becons } }else if (/*xSteps == 0 &&*/ y in s.y - (ySteps+xSteps)..s.y + (ySteps+xSteps)) { // counted += (s.x - xSteps..s.x+ySteps).filterNot { it in becons } counted += (s.x-xSteps..s.x+xSteps)//.filter { it !in becons } } else{ val x = 0 } } return (counted -becons) .size } fun part1D(input: List<String>, y: Int): Int { var score = 0 var yRange = (-100..100) // (-431081..4114070) val xrange = (-100..100)//(-138_318..4_000_000) var xR = (0..0) var yR = (0..0) val sVers = mutableListOf<Vertex>() val bVers = mutableListOf<Vertex>() val map = Array(yRange.count()) { IntArray(xrange.count()) { 0 } } for (line in input) { val (s, b) = line.split(" closest ").take(2).map { val x = it.substringAfter("x=").takeWhile { it.isDigit() || it == '-' } val y = it.substringAfter("y=").takeWhile { it.isDigit() || it == '-' } Vertex(x.toInt(), y = y.toInt()) } if (min(s.x, b.x) < xR.first) xR = min(s.x, b.x)..xR.last else if (max(s.x, b.x) > xR.last) xR = xR.first..max(s.x, b.x) if (min(s.y, b.y) < yR.first) yR = min(s.y, b.y)..yR.last else if (max(s.y, b.y) > yR.last) yR = yR.first..max(s.y, b.y) sVers.add(s) bVers.add(b) } val sToBMap = sVers.zip(bVers).toMap() val sScannedVer = mutableMapOf<Vertex, Set<Vertex>>() var inBounds = { s: Vertex -> // listOf( // utils.Vertex(xR.first, yR.first), utils.Vertex(xR.last, yR.first), // utils.Vertex(xR.first, yR.last), utils.Vertex(xR.last, yR.last) // ) s.y in yR && s.x in xR } sToBMap.filter { it.key == Vertex(8, 7) }.map { (s, b) -> val stepsTaken = abs(b.x - s.x) + abs(b.y - s.y) val list = mutableListOf<Vertex>() val que = ArrayDeque<Vertex>() while (que.any()) t@ for (row in -stepsTaken..stepsTaken) { for (col in -abs(stepsTaken % if (row == 0) 1 else row)..abs(stepsTaken % if (row == 0) 1 else row)) { if (s.x + col == b.x && s.y + row == b.y) break@t list += Vertex(s.x + col, s.y + row) } } val x = 0 } /* sToBMap.forEach { s, b -> val que = ArrayDeque<utils.Vertex>(listOf(s).filter(inBounds)) val visted = mutableSetOf<utils.Vertex>() while (que.any()) { val v = que.removeFirst() if (v in visted) continue visted += v if (v == b) { visted sScannedVer[s] = visted//.take(visted.size -1).toSet() println("one s finish") return@forEach } else { listOf(v.up(), v.down(), v.left(), v.right()).filter(inBounds).forEach(que::addLast) } } } val s = (sScannedVer.keys.filter { it.y == y } + sScannedVer.values.flatten().filter { it.y == y }) .toSet()*/ // //val s = visted.filter { it.y == y } // .filter { it !in sToBMap.values } return 0// s.size// map[y].let { it.size - it.count{it != 1} } } fun part2(input: List<String>): Int { return input.size } // parts execution val testInput = readInput("Day15_test") val input = readInput("Day15") part1(testInput, 10).checkEquals(26) // part1D(input, 2_000_000).alsoPrintln() // .sendAnswer(part = 1, day = "15", year = 2022) part2(testInput).checkEquals(TODO()) part2(input) .sendAnswer(part = 2, day = "15", year = 2022) } /* import kotlin.math.abs fun main() { fun findDistressedBeacon(sensorToDistance: List<Day15Input>, maxSize: Int): YPoint { (0..maxSize).forEach { y -> val ranges = sensorToDistance.toReverseRanges(y, maxSize) if (ranges.isNotEmpty()) { return ranges.first().start } } error("Can't find distressed beacon") } fun utils.readInput(input: List<String>): List<Day15Input> { val sensorToDistance = input.map { s -> val (sensor, beacon) = "(x=|y=)(-?\\d+)" .toRegex().findAll(s) .map { it.groups[2]!!.value.toInt() } .chunked(2) .map { (x, y) -> YPoint(x, y) } .toList() val distance = sensor.dist(beacon) Day15Input(sensor, distance, beacon) } return sensorToDistance } fun part1(input: List<String>, row: Int): Int { val sensorToBeacon = utils.readInput(input) val sensors = sensorToBeacon.map { it.sensor }.toSet() val beacons = sensorToBeacon.map { it.beacon }.toSet() val ranges = sensorToBeacon.toRanges(row) val minX = ranges.map { it.start.x }.min() val maxX = ranges.map { it.endInclusive.x }.max() return (minX..maxX).filter { x -> val point = YPoint(x, row) !sensors.contains(point) && !beacons.contains(point) }.size } fun part2(input: List<String>, maxSize: Int): Long { val sensorToDistance = utils.readInput(input) val (x, y) = findDistressedBeacon(sensorToDistance, maxSize) return x * 4000000L + y } // test if implementation meets criteria from the description, like: val testInput = utils.readInput("Day15_test") println(part1(testInput, 10)) // println(part2(testInput, 20)) check(part1(testInput, 10) == 26) // check(part2(testInput, 20) == 56000011L) val input = utils.readInput("Day15") println(part1(input, 2000000)) // println(part2(input, 4000000)) } private fun YPoint.dist(other: YPoint): Int { return abs(x - other.x) + abs(y - other.y) } private data class Day15Input(val sensor: YPoint, val distance: Int, val beacon: YPoint) private data class YPoint(val x: Int, val y: Int): Comparable<YPoint> { override fun compareTo(other: YPoint): Int { return x - other.x } } private fun YPoint.prev(): YPoint { return YPoint(x - 1, y) } private fun YPoint.next(): YPoint { return YPoint(x + 1, y) } private fun List<Day15Input>.toRanges(row: Int): List<ClosedRange<YPoint>> { return mapNotNull { (sensor, distance) -> val delta = distance - abs(sensor.y - row) if (delta >= 0) { YPoint(sensor.x - delta, row)..YPoint(sensor.x + delta, row ) } else { null } } } private fun List<Day15Input>.toReverseRanges(row: Int, maxSize: Int): List<ClosedRange<YPoint>> { val ranges = toRanges(row) return ranges.fold(listOf(YPoint(0, row)..YPoint(maxSize, row))) { acc, range -> acc.subtract(range) } } private fun List<ClosedRange<YPoint>>.subtract(range: ClosedRange<YPoint>): List<ClosedRange<YPoint>> { return filter { !(range.contains(it.start) && range.contains(it.endInclusive)) }.flatMap { if (range.contains(it.start)) { listOf(range.endInclusive.next()..it.endInclusive) } else if (range.contains(it.endInclusive)) { listOf(it.start..range.start.prev()) } else if (it.contains(range.start)) { listOf( it.start..range.start.prev(), range.endInclusive.next()..it.endInclusive ) } else { listOf(it) } } } */
0
Kotlin
0
0
e2e012d6760a37cb90d2435e8059789941e038a5
9,178
Kotlin-AOC-2023
Apache License 2.0
src/main/kotlin/org/deafsapps/adventofcode/day15/part02/Main.kt
pablodeafsapps
733,033,603
false
{"Kotlin": 6685}
package org.deafsapps.adventofcode.day15.part02 import org.deafsapps.adventofcode.day15.part01.stringHash import java.io.File import java.util.HashMap import java.util.Scanner fun main() { val input = Scanner(File("src/main/resources/day15-data.txt")) val steps = input.nextLine().split(",").map { step -> getLensByStep(step = step) } val lensConfiguration = mutableMapOf<Int, MutableList<Lens>>() steps.forEach { step -> val index = stringHash(string = step.label) if (lensConfiguration[index]?.map { it.label }?.contains(step.label) == true) { if (step.focalLength != null) { lensConfiguration[index]!!.replaceAll { if (it.label == step.label) step else it } } else { lensConfiguration[index]!!.removeAt(lensConfiguration[index]!!.indexOfFirst { it.label == step.label }) } } else { lensConfiguration[index] = ((lensConfiguration[index] ?: listOf()) + (step.takeIf { it.focalLength != null }?.let { listOf(it) } ?: run { listOf() })).toMutableList() } } println(lensConfiguration.getFocusingPower()) } private fun getLensByStep(step: String): Lens { val (label, focalLength) = step.split("""[=\-]""".toRegex()) return Lens(label = label, focalLength = focalLength.toIntOrNull()) } private fun Map<Int, MutableList<Lens>>.getFocusingPower(): Int { var result = 0 entries.forEach { box -> result += box.getFocusingPower() } return result } private tailrec fun Map.Entry<Int, List<Lens>>.getFocusingPower( acc: Int = 0, slot: Int = 1, lensList: List<Lens> = component2() ): Int = if (lensList.isEmpty()) { acc } else { val initial = lensList.first() val rest = lensList.drop(1) val partialAcc = acc + ((component1() + 1) * slot * (initial.focalLength ?: 1)) getFocusingPower(acc = partialAcc, slot = slot + 1, lensList = rest) } private data class Lens(val label: String, val focalLength: Int?)
0
Kotlin
0
0
3a7ea1084715ab7c2ab1bfa8a1a7e357aa3c4b40
2,030
advent-of-code_2023
MIT License
2023/3/solve-2.kts
gugod
48,180,404
false
{"Raku": 170466, "Perl": 121272, "Kotlin": 58674, "Rust": 3189, "C": 2934, "Zig": 850, "Clojure": 734, "Janet": 703, "Go": 595}
import java.io.File class EngineSchemata( val engineSchematic: List<String>, ) { private fun CharSequence.indicesOfNextNumOrNull ( startIndex: Int, ) : IntRange? { if (startIndex > this.lastIndex) throw IllegalStateException("Your index is not my index.") val begin = (startIndex..this.lastIndex).firstOrNull { this[it].isDigit() } if (begin == null) return null val end = (begin..this.lastIndex).firstOrNull { ! this[it].isDigit() } ?: this.lastIndex+1 return IntRange(begin,end-1) } private fun <T> cartesianProductOf (ys: List<T>, xs: List<T>) : List<Pair<T,T>> = ys.flatMap { y -> xs.map { x -> Pair(y,x) } } private fun rowEnd() = engineSchematic.lastIndex private fun colEnd() = engineSchematic[0].lastIndex private fun rowRange(xs: IntRange) = maxOf(0, xs.start) .. minOf(rowEnd(), xs.endInclusive) private fun colRange(xs: IntRange) = maxOf(0, xs.start) .. minOf(colEnd(), xs.endInclusive) private fun surrounding( lineIndex: Int, colIndices: IntRange, ) : List<Triple<Char,Int,Int>> = cartesianProductOf( rowRange(lineIndex - 1 .. lineIndex + 1).toList(), colRange(colIndices.start -1 .. colIndices.endInclusive + 1).toList(), ) .filter { (j,i) -> ! ( j == lineIndex && i in colIndices ) && engineSchematic[j][i] != '.' }.map { (j,i) -> Triple(engineSchematic[j][i],j,i) } fun gearRatioSum() = engineSchematic .flatMapIndexed { j, line -> var partNumberInThisLine = mutableListOf<Pair<Int,Triple<Char,Int,Int>>>() var offset = 0 while (offset < line.lastIndex) { val indices = line.indicesOfNextNumOrNull(offset) if (indices == null) break offset = indices.endInclusive + 1 val gearNearby = surrounding(j, indices).firstOrNull { it.first == '*' } if (gearNearby != null) { val partNum = line.substring(indices).toInt() partNumberInThisLine.add(Pair(partNum,gearNearby)) } } partNumberInThisLine } .groupBy { (modelNum, gear) -> "${gear.second} ${gear.third}" } .entries .filter { (k, partNums) -> partNums.size == 2 } .map { (k, partNums) -> partNums[0].first * partNums[1].first } .sum() fun play () { println( gearRatioSum().toString() ) } } val machine = EngineSchemata( File("input").readLines().toList<String>() ) machine.play()
0
Raku
1
5
ca0555efc60176938a857990b4d95a298e32f48a
2,678
advent-of-code
Creative Commons Zero v1.0 Universal
src/main/kotlin/dev/bogwalk/batch2/Problem30.kt
bog-walk
381,459,475
false
null
package dev.bogwalk.batch2 import dev.bogwalk.util.combinatorics.combinationsWithReplacement import kotlin.math.pow /** * Problem 30: Digit Fifth Powers * * https://projecteuler.net/problem=30 * * Goal: Calculate the sum of all numbers that can be written as the sum of the Nth power of * their digits. * * Constraints: 3 <= N <= 6 * * e.g.: N = 4 * 1634 = 1^4 + 6^4 + 3^4 + 4^4 * 8208 = 8^4 + 2^4 + 0^4 + 8^4 * 9474 = 9^4 + 4^4 + 7^4 + 4^4 * sum = 1634 + 8208 + 9474 = 19316 */ class DigitFifthPowers { /** * SPEED (WORSE) 88.60ms for N = 6 */ fun digitNthPowersBrute(n: Int): List<Int> { val nums = mutableListOf<Int>() val powers = List(10) { (1.0 * it).pow(n).toInt() } val start = maxOf(100, 10.0.pow(n - 2).toInt()) val end = minOf(999_999, (9.0.pow(n) * n).toInt()) for (num in start until end) { var digits = num var sumOfPowers = 0 while (digits > 0) { sumOfPowers += powers[digits % 10] if (sumOfPowers > num) break digits /= 10 } if (sumOfPowers == num) nums.add(num) } return nums } /** * Considers all combinations of digits (0-9 with replacement) for max number of * digits that allow valid candidates, using a combinatorics algorithm. * * This algorithm returns all possible subsets, allowing element repetitions, but not * allowing arrangements that are identical except for order. This produces significantly * fewer subsets than a Cartesian product algorithm, which would not differ between, e.g., * 122 and 212. It is redundant to check both these numbers as both would return the same * comboSum (due to commutative addition). * * Instead, if the generated comboSum itself produces an identical comboSum, then it is a * valid number to include in the sum. * * SPEED (BETTER) 56.97ms for N = 6 */ fun digitNthPowers(n: Int): List<Int> { val nums = mutableListOf<Int>() val powers = List(10) { (1.0 * it).pow(n).toInt() } val maxDigits = if (n < 5) n else 6 for (digits in combinationsWithReplacement(0..9, maxDigits)) { val comboSum = digits.sumOf { powers[it] } val comboSum2 = comboSum.toString().sumOf { powers[it.digitToInt()] } if (comboSum == comboSum2 && comboSum > 9) nums.add(comboSum) } return nums.sorted() } }
0
Kotlin
0
0
62b33367e3d1e15f7ea872d151c3512f8c606ce7
2,535
project-euler-kotlin
MIT License
src/Day01/Day01.kt
Nathan-Molby
572,771,729
false
{"Kotlin": 95872, "Python": 13537, "Java": 3671}
package Day01 import readInput fun main() { class Elf(var calories: MutableList<Int>) { fun addCalorie(calorie: Int) { calories.add(calorie) } fun totalCalories() = calories.sum() } fun readElves(input: List<String>): MutableList<Elf> { var elves = mutableListOf<Elf>() var mostRecentElf = Elf(arrayListOf()) for (row in input) { if (row.isBlank() && mostRecentElf.calories.isNotEmpty()) { elves.add(mostRecentElf) mostRecentElf = Elf(arrayListOf()) } else { val calorieInt = row.toInt() mostRecentElf.addCalorie(calorieInt) } } elves.add(mostRecentElf) return elves } fun part1(input: List<String>): Int { val elves = readElves(input) return elves.maxOf { it.totalCalories() } } fun part2(input: List<String>): Int { val elves = readElves(input) val sortedElves = elves.sortedByDescending { it.totalCalories() } val topThreeElves = sortedElves.subList(0, 3) return topThreeElves.sumOf { it.totalCalories() } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01","Day01_test") check(part1(testInput) == 24000) val input = readInput("Day01","Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
750bde9b51b425cda232d99d11ce3d6a9dd8f801
1,447
advent-of-code-2022
Apache License 2.0
kotlin/src/main/kotlin/RefreshRecord.kt
funfunStudy
93,757,087
false
null
fun main(args: Array<String>) { solve(listOf(10, 5, 20, 20, 4, 5, 2, 25, 1), 9) solve2(listOf(10, 5, 20, 20, 4, 5, 2, 25, 1)) solve3(listOf(10, 5, 20, 20, 4, 5, 2, 25, 1)) solve3(listOf(3, 4, 21, 36, 10, 28, 35, 5, 24, 42)) } data class RecordedScore(val minScore: Int = 0, val maxScore: Int = 0, val min: Int = 0, val max: Int = 0) tailrec fun solve( scoreList: List<Int>, size: Int, minScore: Int = 0, maxScore: Int = 0, min: Int = 0, max: Int = 0 ) { when { scoreList.isEmpty() -> println("$max $min") scoreList.size == size -> { val score = scoreList.first() solve(scoreList.drop(1), 9, score, score) } scoreList.size != size -> { val score = scoreList.first() solve( scoreList.drop(1), size, if (score < minScore) score else minScore, if (score > maxScore) score else maxScore, if (score < minScore) min + 1 else min, if (score > maxScore) max + 1 else max ) } } } private tailrec fun solve2( scoreList: List<Int>, minScore: Int, maxScore: Int, min: Int = 0, max: Int = 0 ) { when (scoreList.isEmpty()) { true -> println("$max $min") false -> { val score = scoreList.first() val scoreLessThenMinScore = score < minScore val scoreGreaterThenMinScore = score > maxScore solve2( scoreList.drop(1), if (scoreLessThenMinScore) score else minScore, if (scoreGreaterThenMinScore) score else maxScore, if (scoreLessThenMinScore) min + 1 else min, if (scoreGreaterThenMinScore) max + 1 else max ) } } } fun solve2(scoreList: List<Int>) { val init = scoreList.first() solve2(scoreList.drop(1), init, init) } fun solve3(scoreList: List<Int>) = scoreList.foldIndexed(RecordedScore()) { i, record, score -> when (i) { 0 -> RecordedScore(score, score) else -> RecordedScore( Math.min(score, record.minScore), Math.max(score, record.maxScore), if (score < record.minScore) record.min + 1 else record.min, if (score > record.maxScore) record.max + 1 else record.max ) } }.also { println("${it.max} ${it.min}") }
0
Kotlin
3
14
a207e4db320e8126169154aa1a7a96a58c71785f
2,533
algorithm
MIT License
src/main/kotlin/TransparentOrigami_13.kt
Flame239
433,046,232
false
{"Kotlin": 64209}
fun getOrigamiInput(): OrigamiInput { val lines = readFile("TransparentOrigami").split("\n") val paper = lines.takeWhile { s -> s.isNotEmpty() }.map { s -> s.split(",").map { it.toInt() }.zipWithNext()[0] } val maxX = paper.maxOf { it.first } val maxY = paper.maxOf { it.second } val paperArray = Array(maxY + 1) { BooleanArray(maxX + 1) } paper.forEach { paperArray[it.second][it.first] = true } val foldings = lines.takeLastWhile { s -> s.isNotEmpty() }.map { val split = it.substring(11).split("=") Folding(if (split[0] == "y") FoldingDirection.UP else FoldingDirection.LEFT, split[1].toInt()) } return OrigamiInput(paperArray, foldings) } fun applyFolding(paper: Array<BooleanArray>, w: Int, h: Int, folding: Folding): Pair<Int, Int> { if (folding.direction == FoldingDirection.UP) { for (x in 0 until w) { for (y in folding.position + 1 until h) { val newY = 2 * folding.position - y paper[newY][x] = paper[newY][x] || paper[y][x] } } return Pair(w, folding.position) } else { for (x in folding.position + 1 until w) { for (y in 0 until h) { val newX = 2 * folding.position - x paper[y][newX] = paper[y][newX] || paper[y][x] } } return Pair(folding.position, h) } } fun countPoints(): Int { val (paper, folding) = getOrigamiInput() val (newW, newH) = applyFolding(paper, paper[0].size, paper.size, folding[0]) var dotsCount = 0 for (x in 0 until newW) { for (y in 0 until newH) { if (paper[y][x]) { dotsCount++ } } } return dotsCount } fun printPaperAfterFolding() { val (paper, foldings) = getOrigamiInput() var w = paper[0].size var h = paper.size foldings.forEach { val (newW, newH) = applyFolding(paper, w, h, it) w = newW h = newH } for (y in 0 until h) { for (x in 0 until w) { print(if (paper[y][x]) "█ " else " ") } println() } } fun main() { println(countPoints()) printPaperAfterFolding() } data class OrigamiInput(val paper: Array<BooleanArray>, val folding: List<Folding>) data class Folding(val direction: FoldingDirection, val position: Int) enum class FoldingDirection { UP, LEFT }
0
Kotlin
0
0
ef4b05d39d70a204be2433d203e11c7ebed04cec
2,422
advent-of-code-2021
Apache License 2.0
src/main/kotlin/Day02.kt
joostbaas
573,096,671
false
{"Kotlin": 45397}
import RockPaperScissors.PAPER import RockPaperScissors.ROCK import RockPaperScissors.SCISSORS enum class RockPaperScissors( private val scoreForUsing: Int, ) { ROCK(1), PAPER(2), SCISSORS(3); fun beats() = when (this) { ROCK -> SCISSORS PAPER -> ROCK SCISSORS -> PAPER } fun isBeatenBy() = values().first { it.beats(this) } private infix fun beats(other: RockPaperScissors) = beats() == other fun scoreAgainst(other: RockPaperScissors) = when { other beats this -> 0 this == other -> 3 this beats other -> 6 else -> throw IllegalArgumentException() } + scoreForUsing } fun Char.parse() = when (this) { 'A' -> ROCK 'B' -> PAPER 'C' -> SCISSORS else -> throw IllegalArgumentException("not a valid char: $this") } fun List<String>.scoreAllRounds(extractYou: (Char, RockPaperScissors) -> RockPaperScissors) = this.sumOf { line -> val other = line[0].parse() val you = extractYou(line[2], other) you.scoreAgainst(other) } fun day02Part1(input: List<String>): Int = input.scoreAllRounds { yourMoveChar, _ -> when (yourMoveChar) { 'X' -> ROCK 'Y' -> PAPER 'Z' -> SCISSORS else -> throw IllegalArgumentException() } } fun day02Part2(input: List<String>): Int = input.scoreAllRounds { yourMoveChar, other -> when (yourMoveChar) { 'X' -> other.beats() 'Y' -> other 'Z' -> other.isBeatenBy() else -> throw IllegalArgumentException() } }
0
Kotlin
0
0
8d4e3c87f6f2e34002b6dbc89c377f5a0860f571
1,686
advent-of-code-2022
Apache License 2.0
src/main/kotlin/days/Day11.kt
hughjdavey
159,955,618
false
null
package days import util.cartesianProduct class Day11 : Day(11) { override fun partOne(): Any { val grid = FuelCell.getFuelCellGrid() return highestPowerInGrid(grid, inputString.trim().toInt()) } override fun partTwo(): Any { val serialNumber = inputString.trim().toInt() var max: Pair<Pair<Int, Int>, Int> = 0 to 0 to 0 var maxSize = 0 var i = 1 //while (i <= 300) { // todo improve performance such that we can run the whole thing while (i <= 12) { val new = highestPowerInGrid(FuelCell.getFuelCellGrid(), serialNumber, i) if (new.second > max.second) { max = new maxSize = i } i++ } return "${max.first.first},${max.first.second},$maxSize" } data class FuelCell(val coord: Pair<Int, Int>) { private val rackId = coord.first + 10 private val initialPowerLevel = rackId * coord.second private var cachedPowerLevel = Int.MIN_VALUE fun powerLevel(serialNumber: Int): Int { if (cachedPowerLevel == Int.MIN_VALUE) { val increasedPowerLevel = ((initialPowerLevel + serialNumber) * rackId).toString() val hundreds = if (increasedPowerLevel.length >= 3) increasedPowerLevel[increasedPowerLevel.length - 3] else '0' cachedPowerLevel = hundreds.toString().toInt() - 5 } return cachedPowerLevel } companion object { fun getFuelCellGrid(): Array<Array<FuelCell>> { val grid = Array(300) { Array(300) { FuelCell(0 to 0) } } for (y in 0..299) { for (x in 0..299) { grid[y][x] = FuelCell(x + 1 to y + 1) } } return grid } } } companion object { fun highestPowerInGrid(grid: Array<Array<FuelCell>>, serialNumber: Int): Pair<Int, Int> { return (0..grid.size).flatMap { y -> (0..grid[0].size).map { x -> val index = x to y val square = getSquare(grid, index, 3) val power = square.map { it.powerLevel(serialNumber) }.sum() x + 1 to y + 1 to power } }.maxBy { it.second }?.first ?: 0 to 0 } fun highestPowerInGrid(grid: Array<Array<FuelCell>>, serialNumber: Int, gridSize: Int): Pair<Pair<Int, Int>, Int> { return (0..grid.size).flatMap { y -> (0..grid[0].size).map { x -> val index = x to y val square = getSquare(grid, index, gridSize) val power = square.map { it.powerLevel(serialNumber) }.sum() x + 1 to y + 1 to power } }.maxBy { it.second } ?: 0 to 0 to 0 } fun <T> getSquare(grid: Array<Array<T>>, topLeft: Pair<Int, Int>, size: Int): List<T> { val indices = getIndices(topLeft, size) if (indices.any { it.second >= grid.size || it.first >= grid[0].size }) { return emptyList() } return indices.map { grid[it.second][it.first] } } fun getIndices(topLeft: Pair<Int, Int>, size: Int): List<Pair<Int, Int>> { val (x, y) = topLeft return cartesianProduct((x until x + size), (y until y + size)) } } }
0
Kotlin
0
0
4f163752c67333aa6c42cdc27abe07be094961a7
3,527
aoc-2018
Creative Commons Zero v1.0 Universal
day11/src/main/kotlin/App.kt
ascheja
317,918,055
false
null
package net.sinceat.aoc2020.day11 import kotlin.math.abs import kotlin.math.sign import net.sinceat.aoc2020.day11.Part1EvolutionRules.evolveUntilStable fun main() { with (Part1EvolutionRules) { run { val fullyEvolvedGrid = readGrid("testinput.txt").evolveUntilStable().last() Grid.compare( readGrid("testoutput.txt"), fullyEvolvedGrid ) println(fullyEvolvedGrid.occupiedSeats) } run { val fullyEvolvedGrid = readGrid("input.txt").evolveUntilStable().last() println(fullyEvolvedGrid.occupiedSeats) } } with (Part2EvolutionRules) { run { val fullyEvolvedGrid = readGrid("testinput.txt").evolveUntilStable().last() Grid.compare( readGrid("testoutputp2.txt"), fullyEvolvedGrid ) println(fullyEvolvedGrid.occupiedSeats) } run { val fullyEvolvedGrid = readGrid("input.txt").evolveUntilStable().last() println(fullyEvolvedGrid.occupiedSeats) } } } private fun readGrid(fileName: String): Grid { return ClassLoader.getSystemResourceAsStream(fileName)!!.bufferedReader().useLines { lines -> Grid(lines.filter(String::isNotBlank).map(String::toList).toList()) } } private class Grid(val data: List<List<Char>>) { companion object { fun compare(grid1: Grid, grid2: Grid) { if (grid1.width != grid2.width || grid1.data.size != grid2.data.size) { println("grid dimensions not equal") return } for ((a, b) in grid1.data.zip(grid2.data)) { val aString = a.joinToString("") val bString = b.joinToString("") println("$aString $bString ${if (aString == bString) "OK" else "ERROR"}") } } } val width = data[0].size val occupiedSeats by lazy { data.sumBy { row -> row.count { it == '#' } } } override fun toString(): String { return data.joinToString("\n") { it.joinToString("") } } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is Grid) return false if (width != other.width) return false if (data != other.data) return false return true } override fun hashCode(): Int { var result = data.hashCode() result = 31 * result + width return result } } private data class Point(val row: Int, val column: Int) { operator fun plus(v: Vector) = Point(row + v.rowDir, column + v.colDir) } private data class Vector(val rowDir: Int, val colDir: Int) { fun extend(): Vector { return Vector( rowDir.sign * (abs(rowDir) + 1), colDir.sign * (abs(colDir) + 1) ) } } private abstract class GridEvolutionRules { protected abstract val acceptableNeighbors: Int protected abstract fun Grid.hasVisibleNeighbor(start: Point, vector: Vector): Boolean private fun Grid.countNeighbors(rowNr: Int, columnNr: Int): Int { val vectors = listOf( Vector(-1, -1), Vector(-1, 0), Vector(-1, 1), Vector(0, -1), Vector(0, 1), Vector(1, -1), Vector(1, 0), Vector(1, 1), ) val p = Point(rowNr, columnNr) return vectors.count { vector -> hasVisibleNeighbor(p, vector) } } fun Grid.evolve(): Grid { return Grid( List(data.size) { rowNr -> List(width) { columnNr -> val status = data[rowNr][columnNr] if (status == '.') { '.' } else { val neighbors = countNeighbors(rowNr, columnNr) when { neighbors == 0 -> '#' neighbors > acceptableNeighbors -> 'L' else -> status } } } } ) } fun Grid.evolveUntilStable(): Sequence<Grid> = sequence { var current = this@evolveUntilStable while (true) { val next = current.evolve() if (current == next) { break } current = next yield(current) } } } private object Part1EvolutionRules : GridEvolutionRules() { override val acceptableNeighbors: Int = 3 override fun Grid.hasVisibleNeighbor(start: Point, vector: Vector): Boolean { val p = start + vector if (p.row !in data.indices || p.column !in 0 until width) { return false } return when (data[p.row][p.column]) { '#' -> true else -> false } } } private object Part2EvolutionRules : GridEvolutionRules() { override val acceptableNeighbors: Int = 4 override tailrec fun Grid.hasVisibleNeighbor(start: Point, vector: Vector): Boolean { val p = start + vector if (p.row !in data.indices || p.column !in 0 until width) { return false } return when (data[p.row][p.column]) { '#' -> true 'L' -> false else -> hasVisibleNeighbor(start, vector.extend()) } } }
0
Kotlin
0
0
f115063875d4d79da32cbdd44ff688f9b418d25e
5,450
aoc2020
MIT License
src/Day07.kt
mihansweatpants
573,733,975
false
{"Kotlin": 31704}
import kotlin.math.min private const val PARENT_DIR = ".." private const val TOTAL_DISK_SPACE = 70000000 private const val SPACE_REQUIRED_FOR_UPDATE = 30000000 fun main() { fun part1(input: List<String>): Int { val rootDir = buildFilesystemTree(input) var sum = 0 rootDir.walkTree { val dirSize = it.size if (dirSize <= 100_000) { sum += dirSize } } return sum } fun part2(input: List<String>): Int { val rootDir = buildFilesystemTree(input) val totalFreeSpace = TOTAL_DISK_SPACE - rootDir.size var minSizeToDelete = rootDir.size rootDir.walkTree { val dirSize = it.size if (totalFreeSpace + dirSize >= SPACE_REQUIRED_FOR_UPDATE) { minSizeToDelete = min(minSizeToDelete, dirSize) } } return minSizeToDelete } val input = readInput("Day07").lines() println(part1(input)) println(part2(input)) } interface Node { val size: Int val name: String } class Directory( override val name: String, private val parent: Directory? = null, private val children: MutableList<Node> = mutableListOf(), ) : Node { override val size: Int get() = children.sumOf { it.size } override fun toString(): String { return "$name (dir)" } fun ls() { println("Reading directory $this contents") } fun cd(dirName: String): Directory { val newDir = when (dirName) { PARENT_DIR -> this.parent ?: throw IllegalArgumentException("Dir $this doesn't have parent") else -> findChildDirectory(dirName) } println("Changing directory to $newDir") return newDir } private fun findChildDirectory(name: String): Directory { val child = children.find { it.name == name } if (child == null || child !is Directory) { throw IllegalArgumentException("Directory ${this.name} doesn't contain child directory $name") } return child } fun add(node: Node) { println("Enumerating $node in $this") children.add(node) } fun walkTree(callback: (dir: Directory) -> Unit) { val queue = ArrayDeque<Directory>() queue.add(this) while (queue.isNotEmpty()) { val currDir = queue.removeFirst() callback(currDir) currDir.children .filterIsInstance<Directory>() .forEach(queue::addLast) } } } class File( override val size: Int, override val name: String ) : Node { override fun toString(): String { return "$name (file, size=$size)" } } // go through input // keep a pointer to rootDir & parentDir & currentDir // for each command: // ls: // for each item in list create a node in current dir // cd: // ..: set currentDir to parentDir // X: set parentDir to currentDir, currentDir = X fun buildFilesystemTree(input: List<String>): Directory { val rootDir = Directory("/") var currentDir = rootDir for (currentLineIndex in 1..input.indices.last) { val currentLine = input[currentLineIndex] when { currentLine.startsWith("$ ls") -> currentDir.ls() currentLine.startsWith("$ cd") -> currentDir = currentDir.cd(parseDirName(currentLine)) else -> currentDir.add(parseNode(currentLine, currentDir)) } } return rootDir } fun parseNode(line: String, parent: Directory): Node { val components = line.split(" ") return if (components.first() == "dir") { Directory(name = components.last(), parent) } else { File(size = components.first().toInt(), name = components.last()) } } fun parseDirName(line: String) = line.split(" ").last()
0
Kotlin
0
0
0de332053f6c8f44e94f857ba7fe2d7c5d0aae91
3,899
aoc-2022
Apache License 2.0
src/main/kotlin/se/saidaspen/aoc/aoc2017/Day20.kt
saidaspen
354,930,478
false
{"Kotlin": 301372, "CSS": 530}
package se.saidaspen.aoc.aoc2017 import se.saidaspen.aoc.util.Day import se.saidaspen.aoc.util.ints import kotlin.math.pow import kotlin.math.sqrt fun main() = Day20.run() object Day20 : Day(2017, 20) { class Tuple<T: Number>(val x: T, val y: T, val z: T) operator fun Tuple<Int>.plus(a: Tuple<Int>): Tuple<Int> { return Tuple(this.x + a.x, this.y + a.y, this.z + a.z) } class Part(var p: Tuple<Int>, var v: Tuple<Int>, var a: Tuple<Int>) override fun part1(): String { val t = 1000.0 return input.lines() .asSequence() .mapIndexed { idx, it -> Pair(idx, ints(it)) } .filter { it.second.isNotEmpty() } .map { Pair( it.first, Part( Tuple(it.second[0], it.second[1], it.second[2]), Tuple(it.second[3], it.second[4], it.second[5]), Tuple(it.second[6], it.second[7], it.second[8]) ) ) } .map { Pair( it.first, Tuple( 0.5 * it.second.a.x.toDouble() * t.pow(2) + it.second.v.x.toDouble() * t + it.second.p.x, 0.5 * it.second.a.y.toDouble() * t.pow(2) + it.second.v.y.toDouble() * t + it.second.p.x, 0.5 * it.second.a.z.toDouble() * t.pow(2) + it.second.v.z.toDouble() * t + it.second.p.x ) ) }.map { Pair(it.first, sqrt(it.second.x.pow(2) + it.second.y.pow(2) + it.second.z.pow(2))) } .minByOrNull { it.second }!!.first.toString() } override fun part2(): String { val state = input.lines() .asSequence() .mapIndexed { idx, it -> Pair(idx, ints(it)) } .filter { it.second.isNotEmpty() } .map { it.first to Part(Tuple(it.second[0], it.second[1], it.second[2]), Tuple(it.second[3], it.second[4], it.second[5]), Tuple(it.second[6], it.second[7], it.second[8]))} .toMap().toMutableMap() val cDetect = mutableMapOf<String, Int>() val toRemove = mutableSetOf<Int>() for (t in 0 until 500) { for ((i, part) in state) { part.v = part.v + part.a part.p = part.p + part.v val key = "${part.p.x}_${part.p.y}_${part.p.z}" if (cDetect.containsKey(key)) { //Collision toRemove.add(cDetect[key]!!) toRemove.add(i) } cDetect[key] = i } for (id in toRemove) state.remove(id) toRemove.clear() cDetect.clear() } return state.size.toString() } }
0
Kotlin
0
1
be120257fbce5eda9b51d3d7b63b121824c6e877
2,856
adventofkotlin
MIT License
src/Day03.kt
baghaii
573,918,961
false
{"Kotlin": 11922}
fun main() { fun part1(input: List<String>): Int { var totalScore = 0 input.forEach { val firstHalf = it.substring(0, it.length / 2) val secondHalf = it.substring(it.length / 2, it.length ) val inBoth = mutableListOf<Char>() firstHalf.forEach { ch -> if (secondHalf.contains(ch) && !inBoth.contains(ch)) { inBoth.add(ch) } } val score = inBoth.map { ch -> scoreChar(ch) }.sum() totalScore += score } return totalScore } fun part2(input: List<String>): Int { var score = 0 for(i in 0 .. input.size - 3 step 3) { val elf1 = input[i] val elf2 = input[i+1] val elf3 = input[i+2] val badge = elf1.find{ch -> elf2.contains(ch) && elf3.contains(ch)}!! score += scoreChar(badge) } return score } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("Day03") println(part1(input)) println(part2(input)) } fun scoreChar(ch: Char): Int { return if (ch in 'a'..'z') { ch - 'a' + 1 } else { ch - 'A' + 27 } }
0
Kotlin
0
0
8c66dae6569f4b269d1cad9bf901e0a686437469
1,401
AdventOfCode2022
Apache License 2.0
src/day04/Day04.kt
zoricbruno
573,440,038
false
{"Kotlin": 13739}
package day04 import readInput fun getSetFromInput(input: String): Set<Int> { val start = input.takeWhile { it != '-' }.toInt() val end = input.takeLastWhile { it != '-' }.toInt() return (start..end).toSet() } fun isFullOverlap(left: Set<Int>, right: Set<Int>): Boolean { return left.containsAll(right) || right.containsAll(left) } fun doesOverlapExist(left: Set<Int>, right: Set<Int>): Boolean { return left.intersect(right).isNotEmpty() } fun part1(input: List<String>): Int { var total = 0; for (line in input) { val left = getSetFromInput(line.takeWhile { it != ',' }) val right = getSetFromInput(line.takeLastWhile { it != ',' }) if (isFullOverlap(left, right)) total++ } return total } fun part2(input: List<String>): Int { var total = 0 for (line in input) { val left = getSetFromInput(line.takeWhile { it != ',' }) val right = getSetFromInput(line.takeLastWhile { it != ',' }) if (doesOverlapExist(left, right)) total++ } return total } fun main() { val day = "Day04" val test = "${day}_test" val testInput = readInput(day, test) val input = readInput(day, day) val testFirst = part1(testInput) println(testFirst) check(testFirst == 2) println(part1(input)) val testSecond = part2(testInput) println(testSecond) check(testSecond == 4) println(part2(input)) }
0
Kotlin
0
0
16afa06aff0b6e988cbea8081885236e4b7e0555
1,449
kotlin_aoc_2022
Apache License 2.0
src/main/kotlin/day19/Day19.kt
TheSench
572,930,570
false
{"Kotlin": 128505}
package day19 import runDay fun main() { fun part1(input: List<String>) = input .map(String::toBlueprint) .mapIndexed { index, blueprint -> (index + 1) to blueprint.findBest(24) }.sumOf { (id, best) -> id * best } fun part2(input: List<String>) = input .take(3) .map(String::toBlueprint) .map { it.findBest(32) }.reduce { product, next -> product * next } (object {}).runDay( part1 = ::part1, part1Check = 33, part2 = ::part2, part2Check = 3472, ) } private fun Blueprint.findBest(iterations: Int): Int { var states = listOf(State()) for (i in (1..iterations)) { states = states.flatMap { it.toOptions(this) }.fold(mutableMapOf<Int, MutableSet<State>>()) { cache, state -> val best = cache.computeIfAbsent(state.signatureFor(this)) { mutableSetOf() } best.forEach { next -> if (next hasStrictlyMoreThan state) { return@fold cache } else if (state hasStrictlyMoreThan next) { best.remove(next) best.add(state) return@fold cache } } best.add(state) cache }.values.flatten() .sortedWith(compareByDescending<State> { it.geodes }.thenByDescending { it.geodeCollectingRobots } .thenByDescending { it.obsidian }.thenByDescending { it.obsidianCollectingRobots } .thenByDescending { it.clay }.thenByDescending { it.clayCollectingRobots } .thenByDescending { it.ore }.thenByDescending { it.oreCollectingRobots }) .take(2500) } return states.maxOf { it.geodes } } data class State( val ore: Int = 0, val clay: Int = 0, val obsidian: Int = 0, val geodes: Int = 0, val oreCollectingRobots: Int = 1, val clayCollectingRobots: Int = 0, val obsidianCollectingRobots: Int = 0, val geodeCollectingRobots: Int = 0, ) fun State.signatureFor(blueprint: Blueprint) = ((geodeCollectingRobots * blueprint.max.obsidian + obsidianCollectingRobots) * blueprint.max.clay + clayCollectingRobots) * blueprint.max.ore + oreCollectingRobots infix fun State.hasStrictlyMoreThan(other: State) = ore >= other.ore && clay >= other.clay && obsidian >= other.obsidian && geodes >= other.geodes fun State.toOptions(blueprint: Blueprint): List<State> { val afterCollecting = this.copy( ore = ore + oreCollectingRobots, clay = clay + clayCollectingRobots, obsidian = obsidian + obsidianCollectingRobots, geodes = geodes + geodeCollectingRobots, ) val options = mutableListOf<State>() var canSave = false if (canBuy(blueprint.geode)) { options.add(afterCollecting.purchase(blueprint.geode)) } else if (obsidianCollectingRobots > 0) { canSave = true } if (obsidianCollectingRobots < blueprint.max.obsidian) { if (canBuy(blueprint.obsidian)) { options.add(afterCollecting.purchase(blueprint.obsidian)) } else if (clayCollectingRobots > 0) { canSave = true } } if (clayCollectingRobots < blueprint.max.clay) { if (canBuy(blueprint.clay)) { options.add(afterCollecting.purchase(blueprint.clay)) } else { canSave = true } } if (oreCollectingRobots < blueprint.max.ore) { if (canBuy(blueprint.ore)) { options.add(afterCollecting.purchase(blueprint.ore)) } else canSave = true } if (canSave) { options.add(afterCollecting) } return options } fun State.canBuy(cost: Cost) = ore >= cost.ore && clay >= cost.clay && obsidian >= cost.obsidian fun State.purchase(cost: Cost) = copy( ore = ore - cost.ore, clay = clay - cost.clay, obsidian = obsidian - cost.obsidian, oreCollectingRobots = oreCollectingRobots + cost.oreCollectingRobots, clayCollectingRobots = clayCollectingRobots + cost.clayCollectingRobots, obsidianCollectingRobots = obsidianCollectingRobots + cost.obsidianCollectingRobots, geodeCollectingRobots = geodeCollectingRobots + cost.geodeCollectingRobots, ) val oreRegex = Regex("""Each ore robot costs (\d+) ore.""") val clayRegex = Regex("""Each clay robot costs (\d+) ore.""") val obsidianRegex = Regex("""Each obsidian robot costs (\d+) ore and (\d+) clay.""") val geodeRegex = Regex("""Each geode robot costs (\d+) ore and (\d+) obsidian""") fun String.toBlueprint() = Blueprint( ore = oreRegex.find(this)!!.destructured.let { (ore) -> Cost( ore = ore.toInt(), oreCollectingRobots = 1, ) }, clay = clayRegex.find(this)!!.destructured.let { (ore) -> Cost( ore = ore.toInt(), clayCollectingRobots = 1, ) }, obsidian = obsidianRegex.find(this)!!.destructured.let { (ore, clay) -> Cost( ore = ore.toInt(), clay = clay.toInt(), obsidianCollectingRobots = 1, ) }, geode = geodeRegex.find(this)!!.destructured.let { (ore, obsidian) -> Cost( ore = ore.toInt(), obsidian = obsidian.toInt(), geodeCollectingRobots = 1, ) } ) data class Blueprint( val ore: Cost, val clay: Cost, val obsidian: Cost, val geode: Cost, ) { private val allCosts get() = listOf(ore, clay, obsidian, geode) val max = Cost( ore = allCosts.maxOf { it.ore }, clay = allCosts.maxOf { it.clay }, obsidian = allCosts.maxOf { it.obsidian }, ) } data class Cost( val ore: Int = 0, val clay: Int = 0, val obsidian: Int = 0, val oreCollectingRobots: Int = 0, val clayCollectingRobots: Int = 0, val obsidianCollectingRobots: Int = 0, val geodeCollectingRobots: Int = 0, )
0
Kotlin
0
0
c3e421d75bc2cd7a4f55979fdfd317f08f6be4eb
5,444
advent-of-code-2022
Apache License 2.0
src/Day04.kt
mandoway
573,027,658
false
{"Kotlin": 22353}
fun main() { fun String.toRange() = split("-") .map { it.toInt() } .let { it[0] .. it[1] } fun String.toRangePair() = split(",") .let { it[0].toRange() to it[1].toRange() } infix operator fun IntRange.contains(other: IntRange) = first <= other.first && last >= other.last infix fun IntRange.overlaps(other: IntRange) = first <= other.last && last >= other.first fun part1(input: List<String>): Int { return input .asSequence() .map { it.toRangePair() } .count { (first, second) -> first in second || second in first } } fun part2(input: List<String>): Int { return input .asSequence() .map { it.toRangePair() } .count { (first, second) -> first overlaps second} } // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
0393a4a25ae4bbdb3a2e968e2b1a13795a31bfe2
1,088
advent-of-code-22
Apache License 2.0
src/Day17.kt
catcutecat
572,816,768
false
{"Kotlin": 53001}
import kotlin.system.measureTimeMillis fun main() { measureTimeMillis { Day17.run { solve1(3068L) // 3133L solve2(1514285714288L) // 1547953216393L } }.let { println("Total: $it ms") } } object Day17 : Day.RowInput<Day17.Data, Long>("17") { data class Data(private val directions: List<Direction>) { private val rockSequence = listOf( Rock(listOf(0 to 0, 0 to 1, 0 to 2, 0 to 3), 1), Rock(listOf(1 to 1, 0 to 1, 2 to 1, 1 to 0, 1 to 2), 3), Rock(listOf(0 to 0, 0 to 1, 0 to 2, 1 to 2, 2 to 2), 3), Rock(listOf(0 to 0, 1 to 0, 2 to 0, 3 to 0), 4), Rock(listOf(0 to 0, 0 to 1, 1 to 0, 1 to 1), 2), ) fun fallingRocks(targetRockCount: Long): Long { var directionIndex = 0 fun nextDirection() = directions[directionIndex].also { directionIndex = (directionIndex + 1) % directions.size } var rockIndex = 0 fun nextRock() = rockSequence[rockIndex].also { rockIndex = (rockIndex + 1) % rockSequence.size } var rockCount = 0L var totalHeight = 0 val chamber = mutableListOf<BooleanArray>() fun fallRock() { val rock = nextRock() while (chamber.size < totalHeight + rock.height + 3) chamber.add(BooleanArray(7)) val position = intArrayOf(totalHeight + 3, 2) rock.move(position, Direction.INIT, chamber) do { rock.move(position, nextDirection(), chamber) } while (rock.move(position, Direction.DOWN, chamber)) totalHeight = maxOf(totalHeight, position[0] + rock.height) ++rockCount } val records = mutableMapOf<Int, Pair<Int, Long>>() // [directionIndex] = (diff, rockCount) var prevTotalHeight = 0 fun findPattern(): Boolean { val diff = totalHeight - prevTotalHeight if (rockIndex != 0) return false if (records[directionIndex]?.first == diff) return true records[directionIndex] = diff to rockCount prevTotalHeight = totalHeight return false } while (rockCount < targetRockCount && !findPattern()) { fallRock() } val patternRockCount = rockCount - records[directionIndex]!!.second val patternHeight = records.values .filter { (_, prevRockCount) -> prevRockCount >= records[directionIndex]!!.second } .sumOf { it.first } val remainRockCount = targetRockCount - rockCount val needPatternRound = remainRockCount / patternRockCount val needSingleRockCount = (remainRockCount % patternRockCount).toInt() repeat(needSingleRockCount) { fallRock() } return totalHeight.toLong() + patternHeight * needPatternRound } } override fun parse(input: String) = Data(input.map { if (it == '<') Direction.LEFT else Direction.RIGHT }) override fun part1(data: Data) = data.fallingRocks(2022L) override fun part2(data: Data) = data.fallingRocks(1000000000000L) enum class Direction(val dy: Int, val dx: Int) { LEFT(0, -1), RIGHT(0, 1), DOWN(-1, 0), INIT(0, 0); } class Rock(private val points: List<Pair<Int, Int>>, val height: Int) { fun move(position: IntArray, direction: Direction, chamber: List<BooleanArray>): Boolean { set(position, chamber, false) val canMove = canMove(position, direction, chamber) if (canMove) { position[0] += direction.dy position[1] += direction.dx } set(position, chamber, true) return canMove } private fun canMove(position: IntArray, direction: Direction, chamber: List<BooleanArray>) = points .map { (dy, dx) -> position[0] + dy + direction.dy to position[1] + dx + direction.dx } .all { (newY, newX) -> newY in chamber.indices && newX in chamber[newY].indices && !chamber[newY][newX] } private fun set(position: IntArray, chamber: List<BooleanArray>, put: Boolean) { val (y, x) = position for ((dy, dx) in points) { chamber[y + dy][x + dx] = put } } } }
0
Kotlin
0
2
fd771ff0fddeb9dcd1f04611559c7f87ac048721
4,505
AdventOfCode2022
Apache License 2.0
src/Day03.kt
jordanfarrer
573,120,618
false
{"Kotlin": 20954}
fun main() { val day = "Day03" fun findItemInBoth(first: Iterable<Char>, second: Iterable<Char>): Char { return first.intersect(second.toSet()).first() } fun findCommonItem(groups: List<Iterable<Char>>): Char { return groups.reduce { a, b -> a.intersect(b.toSet()) }.first() } fun getPriorityForItem(item: Char): Int { return if (item.isUpperCase()) item.code - 'A'.code + 27 else item.code - 'a'.code + 1 } fun part1(input: List<String>): Int { return input.map { line -> findItemInBoth( line.take(line.length / 2).asIterable(), line.takeLast(line.length / 2).asIterable() ) }.sumOf { getPriorityForItem(it) } } fun part2(input: List<String>): Int { return input.map { it.asIterable() }.chunked(3).map { findCommonItem(it) }.sumOf { getPriorityForItem(it) } } println("a: ${'a'.code}") println("A: ${'A'.code}") // test if implementation meets criteria from the description, like: val testInput = readInput("${day}_test") val part1Result = part1(testInput) println("Part 1 (test): $part1Result") check(part1Result == 157) val part2Result = part2(testInput) println("Part 2 (test): $part2Result") check(part2Result == 70) val input = readInput(day) println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
aea4bb23029f3b48c94aa742958727d71c3532ac
1,402
advent-of-code-2022-kotlin
Apache License 2.0
src/twentythree/Day03.kt
Monkey-Matt
572,710,626
false
{"Kotlin": 73188}
package twentythree fun main() { val day = "03" // test if implementation meets criteria from the description: println("Day$day Test Answers:") val testInput = readInputLines("Day${day}_test") val part1 = part1(testInput) part1.println() check(part1 == 4361) val part2 = part2(testInput) part2.println() check(part2 == 467835) println("---") println("Solutions:") val input = readInputLines("Day${day}_input") part1(input).println() part2(input).println() } private fun part1(input: List<String>): Int { var sum = 0 input.forEachIndexed { yIndex, line -> var endOfCurrentNumber = -1 line.forEachIndexed name@ { xIndex, char -> if (xIndex > endOfCurrentNumber) { if (char.isDigit()) { val (counts, value, endX) = checkIfThisOneCounts(input, yIndex, xIndex) endOfCurrentNumber = endX if (counts) sum += value } } } } return sum } private fun checkIfThisOneCounts(input: List<String>, yIndex: Int, xIndex: Int): Triple<Boolean, Int, Int> { val digits = mutableListOf<Char>() var xPosition = xIndex val finalXIndex: Int while (true) { if (xPosition <= input.first().lastIndex && input[yIndex][xPosition].isDigit()) { digits.add(input[yIndex][xPosition]) } else { finalXIndex = xPosition-1 break } xPosition++ } val countsTriple = Triple(true, digits.joinToString("").toInt(), finalXIndex) // check above if (yIndex != 0) { for (x in xIndex-1..finalXIndex+1) { val xCoerced = x.coerceIn(0, input.first().lastIndex) if (input[yIndex-1][xCoerced] != '.') return countsTriple } } // check before if (xIndex != 0) { if (input[yIndex][xIndex-1] != '.') return countsTriple } // check after if (finalXIndex != input.first().lastIndex) { if (input[yIndex][finalXIndex+1] != '.') return countsTriple } // check below if (yIndex != input.lastIndex) { for (x in xIndex-1..finalXIndex+1) { val xCoerced = x.coerceIn(0, input.first().lastIndex) if (input[yIndex+1][xCoerced] != '.') return countsTriple } } return Triple(false, 0, finalXIndex) } private fun part2(input: List<String>): Int { var sum = 0 input.forEachIndexed { yIndex, line -> line.forEachIndexed name@ { xIndex, char -> if (char == '*') { // need to check for adjacent numbers val (counts, value) = checkIfThisStarCountsPart2(input, yIndex, xIndex) if (counts) sum += value } } } return sum } private fun checkIfThisStarCountsPart2(input: List<String>, yIndex: Int, xIndex: Int): Pair<Boolean, Int> { val connectedDirections = getAdjacentNumberPositions(input, yIndex, xIndex) return if (connectedDirections.size == 2) { val number1 = getNumberInPosition(input, connectedDirections[0].getYX(yIndex, xIndex)) val number2 = getNumberInPosition(input, connectedDirections[1].getYX(yIndex, xIndex)) Pair(true, number1*number2) } else { Pair(false, 0) } } private fun getAdjacentNumberPositions(input: List<String>, yIndex: Int, xIndex: Int): List<NumberDirection> { val maxXIndex = input.first().lastIndex val connectedDirections = mutableListOf<NumberDirection>() // check top if (yIndex > 0) { // check top middle if (input[yIndex-1][xIndex].isDigit()) { connectedDirections.add(NumberDirection.TOP_MIDDLE) } else { // if not number in top middle there could be ones diagonally // check top left if (xIndex > 0) { if (input[yIndex - 1][xIndex - 1].isDigit()) connectedDirections.add(NumberDirection.TOP_LEFT) } // check top right if (xIndex < maxXIndex) { if (input[yIndex-1][xIndex+1].isDigit()) connectedDirections.add(NumberDirection.TOP_RIGHT) } } } // check left if (xIndex > 0) { if (input[yIndex][xIndex-1].isDigit()) connectedDirections.add(NumberDirection.LEFT) } // check right if (xIndex < maxXIndex) { if (input[yIndex][xIndex+1].isDigit()) connectedDirections.add(NumberDirection.RIGHT) } // check bottom if (yIndex < input.lastIndex) { // check bottom middle if (input[yIndex+1][xIndex].isDigit()) { connectedDirections.add(NumberDirection.BOTTOM_MIDDLE) } else { // if not number in top middle there could be ones diagonally // check bottom left if (xIndex > 0) { if (input[yIndex+1][xIndex-1].isDigit()) connectedDirections.add(NumberDirection.BOTTOM_LEFT) } // check top right if (xIndex < maxXIndex) { if (input[yIndex+1][xIndex+1].isDigit()) connectedDirections.add(NumberDirection.BOTTOM_RIGHT) } } } return connectedDirections } private fun getNumberInPosition(input: List<String>, yx: Pair<Int, Int>): Int { val (y, x) = yx var startX = x var endX = x while (true) { if (startX > 0 && input[y][startX-1].isDigit()) { startX-- } else { break } } while (true) { if (endX < input.first().lastIndex && input[y][endX+1].isDigit()) { endX++ } else { break } } return input[y].substring(startX, endX+1).toInt() } enum class NumberDirection { TOP_LEFT, TOP_MIDDLE, TOP_RIGHT, LEFT, RIGHT, BOTTOM_LEFT, BOTTOM_MIDDLE, BOTTOM_RIGHT, ; fun getYX(sourceY: Int, sourceX: Int): Pair<Int, Int> { return when (this) { TOP_LEFT -> Pair(sourceY-1, sourceX-1) TOP_MIDDLE -> Pair(sourceY-1, sourceX) TOP_RIGHT -> Pair(sourceY-1, sourceX+1) LEFT -> Pair(sourceY, sourceX-1) RIGHT -> Pair(sourceY, sourceX+1) BOTTOM_LEFT -> Pair(sourceY+1, sourceX-1) BOTTOM_MIDDLE -> Pair(sourceY+1, sourceX) BOTTOM_RIGHT -> Pair(sourceY+1, sourceX+1) } } }
1
Kotlin
0
0
600237b66b8cd3145f103b5fab1978e407b19e4c
6,372
advent-of-code-solutions
Apache License 2.0
src/Day02.kt
MSchu160475
573,330,549
false
{"Kotlin": 5456}
fun main() { fun part1(input: List<String>): Int { val game = RockPaperScissors() return input.map { game.score(it) }.sum() } fun part2(input: List<String>): Int { val game = RockPaperScissors() return input.map { game.scoreFake(it) }.sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("Day02") println(part1(input)) println(part2(input)) } class RockPaperScissors { private val rules = mapOf( "A X" to 4, "A Y" to 8, "A Z" to 3, "B X" to 1, "B Y" to 5, "B Z" to 9, "C X" to 7, "C Y" to 2, "C Z" to 6 ) //Rock defeats Scissors, Scissors defeats Paper, and Paper defeats Rock //A Rock, B Paper, C Scissors //X loose, Y draw, Z win private val fakeRules = mapOf( "A X" to 3, "A Y" to 4, "A Z" to 8, "B X" to 1, "B Y" to 5, "B Z" to 9, "C X" to 2, "C Y" to 6, "C Z" to 7 ) fun score(gamePlayerChoice: String): Int { return rules[gamePlayerChoice]!! } fun scoreFake(gamePlayerChoice: String): Int{ return fakeRules[gamePlayerChoice]!! } }
0
Kotlin
0
0
c6f9a0892a28f0f03b95768b6611e520c85db75c
1,417
advent-of-code-2022-kotlin
Apache License 2.0
2022/src/main/kotlin/day21.kt
madisp
434,510,913
false
{"Kotlin": 388138}
import utils.Parser import utils.Solution import utils.badInput import utils.cut import utils.mapItems fun main() { Day21.run() } object Day21 : Solution<Map<String, Day21.Expr>>() { override val name = "day21" override val parser = Parser.lines.mapItems { line -> val (name, exprString) = line.cut(": ") name to when { exprString.indexOf(' ') == -1 -> Expr.Number(exprString.toLong()) else -> { val parts = exprString.split(' ', limit = 3) Expr.MathExpr(parts[1][0], parts[0], parts[2]) } } }.map { it.toMap() } sealed class Expr { abstract fun calculate(others: Map<String, Expr>): Long data class Number(var value: Long) : Expr() { override fun calculate(others: Map<String, Expr>) = value } data class MathExpr(val oper: Char, val left: String, val right: String) : Expr() { override fun calculate(others: Map<String, Expr>): Long { val l = others[left]!! val r = others[right]!! return when (oper) { '+' -> l.calculate(others) + r.calculate(others) '-' -> l.calculate(others) - r.calculate(others) '*' -> l.calculate(others) * r.calculate(others) '/' -> l.calculate(others) / r.calculate(others) else -> badInput() } } } } override fun part1(input: Map<String, Expr>): Long { return input["root"]!!.calculate(input) } override fun part2(input: Map<String, Expr>): Long { // solved by hand return if (input.size < 20) { 301 } else { 3665520865940 } } }
0
Kotlin
0
1
3f106415eeded3abd0fb60bed64fb77b4ab87d76
1,582
aoc_kotlin
MIT License
src/main/kotlin/aoc/year2023/Day02.kt
SackCastellon
573,157,155
false
{"Kotlin": 62581}
package aoc.year2023 import aoc.Puzzle /** * [Day 2 - Advent of Code 2023](https://adventofcode.com/2023/day/2) */ object Day02 : Puzzle<Int, Int> { private val bagContents = mapOf( "red" to 12, "green" to 13, "blue" to 14, ) override fun solvePartOne(input: String): Int { fun getValidGameId(string: String): Int? { val (game, subsets) = string.split(':') val gameId = game.removePrefix("Game ").toInt() val isValid = subsets.splitToSequence(';', ',') .map(String::trim) .map { it.split(' ') } .map { (a, b) -> a to b } .groupBy({ it.second }, { it.first.toInt() }) .all { (color, counts) -> val max = bagContents.getValue(color) counts.all { it <= max } } return gameId.takeIf { isValid } } return input.lineSequence().mapNotNull(::getValidGameId).sum() } override fun solvePartTwo(input: String): Int { fun getPowerOfMinimumSet(string: String): Int = string.substringAfter(':') .splitToSequence(';', ',') .map(String::trim) .map { it.substringBefore(' ') to it.substringAfterLast(' ') } .groupBy({ it.second }, { it.first.toInt() }) .mapValues { it.value.max() } .values .reduce(Int::times) return input.lineSequence().map(::getPowerOfMinimumSet).sum() } }
0
Kotlin
0
0
75b0430f14d62bb99c7251a642db61f3c6874a9e
1,565
advent-of-code
Apache License 2.0
graph/MinimumCostMaximumFlow.kt
wangchaohui
737,511,233
false
{"Kotlin": 36737}
class MinimumCostMaximumFlow(vertexSize: Int, private val s: Int, private val t: Int) { data class Edge( val u: Int, val v: Int, var capacity: Int, var cost: Int, var flow: Int = 0, ) { lateinit var reverse: Edge val remaining: Int get() = capacity - flow } private val costs = IntArray(vertexSize) private val edges = Array(vertexSize) { mutableListOf<Edge>() } private val currentEdges = IntArray(vertexSize) private val visited = BooleanArray(vertexSize) fun addEdge(u: Int, v: Int, capacity: Int, cost: Int, reversedCapacity: Int = 0): Edge { val edge = Edge(u, v, capacity, cost).also { edges[u] += it } edge.reverse = Edge(v, u, reversedCapacity, -cost).apply { reverse = edge }.also { edges[v] += it } return edge } fun dinic(): Pair<Long, Long> { var f = 0L var c = 0L while (spfa()) { currentEdges.fill(0) val (flow, cost) = dfs(s, Int.MAX_VALUE) f += flow c += cost } return f to c } private fun spfa(): Boolean { costs.fill(Int.MAX_VALUE) costs[s] = 0 val q = ArrayDeque<Int>() q.add(s) visited[s] = true while (q.isNotEmpty()) { val u = q.removeFirst() visited[u] = false for (edge in edges[u]) { val v = edge.v if (edge.remaining > 0 && costs[v] > costs[u] + edge.cost) { costs[v] = costs[u] + edge.cost if (!visited[v]) { q.add(v) visited[v] = true } } } } return costs[t] < Int.MAX_VALUE } private fun dfs(u: Int, flowLimit: Int): Pair<Int, Int> { if (u == t || flowLimit == 0) return flowLimit to 0 visited[u] = true var pushedFlow = 0 var pushedCost = 0 while (pushedFlow < flowLimit) { val edge = edges[u].getOrNull(currentEdges[u]++) ?: break val v = edge.v if (visited[v] || edge.remaining == 0 || costs[v] != costs[u] + edge.cost) continue val (pathFlow, pathCost) = dfs(v, min(flowLimit - pushedFlow, edge.remaining)) pushedFlow += pathFlow pushedCost += pathCost + pathFlow * edge.cost edge.flow += pathFlow edge.reverse.flow -= pathFlow } visited[u] = false return pushedFlow to pushedCost } }
0
Kotlin
0
0
241841f86fdefa9624e2fcae2af014899a959cbe
2,591
kotlin-lib
Apache License 2.0
src/main/kotlin/days/Day12.kt
hughjdavey
433,597,582
false
{"Kotlin": 53042}
package days class Day12 : Day(12) { private val caveMap = parseInput(inputList) override fun partOne(): Any { return getPaths(caveMap, true).size } override fun partTwo(): Any { return getPaths(caveMap, false).size } data class Path(val onlyVisitSmallCavesOnce: Boolean, val path: List<String> = listOf("start")) { fun isEnded() = currentLocation() == "end" fun fork(caveMap: Map<String, List<String>>): List<Path> { return (caveMap[currentLocation()] ?: emptyList()) .filter(::canVisit) .map { copy(path = path.plus(it)) } } private fun canVisit(location: String): Boolean { if (onlyVisitSmallCavesOnce) { return !isSmallCave(location) || pastVisits(location) < 1 } if (location == "start") { return false } else if (isSmallCave(location)) { return if (path.any { isSmallCave(it) && pastVisits(it) == 2 }) pastVisits(location) < 1 else pastVisits(location) < 2 } return true } private fun isSmallCave(location: String) = location == location.lowercase() private fun currentLocation() = path.last() private fun pastVisits(location: String) = path.count { it == location } } fun getPaths(caveMap: Map<String, List<String>>, onlyVisitSmallCavesOnce: Boolean): Set<Path> { return getPaths(caveMap, Path(onlyVisitSmallCavesOnce)) } private fun getPaths(caveMap: Map<String, List<String>>, path: Path, paths: Set<Path> = setOf(path)): Set<Path> { if (path.isEnded()) { return setOf(path) } return path.fork(caveMap).flatMap { getPaths(caveMap, it, paths.plus(it)) }.toSet() } fun parseInput(connections: List<String>): Map<String, List<String>> { return connections.fold(mutableMapOf()) { map, connection -> val (start, end) = connection.split("-") map.merge(start, listOf(end), List<String>::plus) map.merge(end, listOf(start), List<String>::plus) map } } }
0
Kotlin
0
0
a3c2fe866f6b1811782d774a4317457f0882f5ef
2,186
aoc-2021
Creative Commons Zero v1.0 Universal
src/day04/Day04.kt
Klaus-Anderson
572,740,347
false
{"Kotlin": 13405}
package day04 import readInput fun main() { fun parseElfSection(it: String): List<Int> { return it.split("-").let { (it[0].toInt() until it[1].toInt() + 1).toList() } } fun part1(input: List<String>): Int { return input.map { it.split(",") }.sumOf { val elfString0 = it[0] val elfString1 = it[1] val elfSections0 = parseElfSection(elfString0) val elfSections1 = parseElfSection(elfString1) if (elfSections0.containsAll(elfSections1) || elfSections1.containsAll(elfSections0)) { 1 } else { 0 }.toInt() } } fun part2(input: List<String>): Int { return input.map { it.split(",") }.sumOf { val elfString0 = it[0] val elfString1 = it[1] val elfSections0 = parseElfSection(elfString0) val elfSections1 = parseElfSection(elfString1) if (elfSections0.intersect(elfSections1.toSet()).isNotEmpty()) { 1 } else { 0 }.toInt() } } // test if implementation meets criteria from the description, like: 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
faddc2738011782841ec20475171909e9d4cee84
1,471
harry-advent-of-code-kotlin-template
Apache License 2.0
src/Day02.kt
jbotuck
573,028,687
false
{"Kotlin": 42401}
import java.time.Duration import java.time.Instant fun main() { val started = Instant.now() val lines = readInput("Day02") println("part 1 ${lines.sumOf { score1(it) }}") println("part 2 ${lines.sumOf { score2(it) }}") println(Duration.between(started, Instant.now()).toMillis()) } private val rules = setOf(0 to 2, 1 to 0, 2 to 1)//who beats who private fun Pair<Int, Int>.score(opponent: Int) = 1 + first + when (opponent) { second -> 6 first -> 3 else -> 0 } private fun score1(line: String) = rules .find { it.first == line.last().code % 'X'.code }!! .score(line.first().code % 'A'.code) private fun score2(line: String): Int { val opponent = line.first().code % 'A'.code return when (line.last()) { 'X' -> rules.find { it.first == opponent }!!.second.let { self -> rules.find { it.first == self } } 'Y' -> rules.find { it.first == opponent } else -> rules.find { it.second == opponent } }!!.score(opponent) }
0
Kotlin
0
0
d5adefbcc04f37950143f384ff0efcd0bbb0d051
995
aoc2022
Apache License 2.0
src/day3/Day03.kt
dinoolivo
573,723,263
false
null
package day3 import readInput fun main() { //subtract the code of 'a' if lowercase or 'A' if uppercase then sum the known priority range (a to z priorities 1 through 26 and A to Z priorities 27 through 52) fun computePriority(itemType:Char) = if(itemType.isUpperCase()) itemType.code -'A'.code + 27 else itemType.code - 'a'.code + 1 /* * divide the string containing the list of items in the two compartments by using a substring * then transform the string in a set of characters since we are interested only on distinct chars * that are contained in both compartments not the number of occurrences. * Then intersect the two sets and get only the chars contained in both and compute the score for each row. * Last step is to sum all the computed priorities, first for each row and then for all the rows */ fun part1(input: List<String>): Int = input.sumOf {row -> val sect1 = row.substring(0, row.length/2).toSet() val sect2 = row.substring(row.length/2).toSet() sect1.intersect(sect2).sumOf(::computePriority) } /* Same as part 1. The only difference is regarding the input that in this case is chunked in groups of three rows */ fun part2(input: List<String>): Int = input.chunked(3).sumOf { group -> group[0].toSet().intersect(group[1].toSet()).intersect(group[2].toSet()).sumOf(::computePriority) } val testInput = readInput("inputs/Day03_test") println("Test Part 1: " + part1(testInput)) println("Test Part 2: " + part2(testInput)) //execute the two parts on the real input val input = readInput("inputs/Day03") println("Part1: " + part1(input)) println("Part2: " + part2(input)) }
0
Kotlin
0
0
6e75b42c9849cdda682ac18c5a76afe4950e0c9c
1,754
aoc2022-kotlin
Apache License 2.0
src/main/kotlin/adventofcode/year2015/Day06ProbablyAFireHazard.kt
pfolta
573,956,675
false
{"Kotlin": 199554, "Dockerfile": 227}
package adventofcode.year2015 import adventofcode.Puzzle import adventofcode.PuzzleInput import adventofcode.common.cartesianProduct import adventofcode.year2015.Day06ProbablyAFireHazard.Companion.Action.TOGGLE import adventofcode.year2015.Day06ProbablyAFireHazard.Companion.Action.TURN_OFF import adventofcode.year2015.Day06ProbablyAFireHazard.Companion.Action.TURN_ON import kotlin.math.max class Day06ProbablyAFireHazard(customInput: PuzzleInput? = null) : Puzzle(customInput) { override val name = "Probably a Fire Hazard" private val instructions by lazy { input .lines() .map { val (action, left, top, right, bottom) = INPUT_REGEX.find(it)!!.destructured Instruction(Action(action), left.toInt(), top.toInt(), right.toInt(), bottom.toInt()) } } override fun partOne() = instructions.fold(mutableMapOf<Pair<Int, Int>, Boolean>()) { lights, instruction -> when (instruction.action) { TURN_ON -> instruction.lights.forEach { light -> lights[light] = true } TURN_OFF -> instruction.lights.forEach { light -> lights[light] = false } TOGGLE -> instruction.lights.forEach { light -> lights[light] = !lights.getOrDefault(light, false) } } lights }.count { (_, state) -> state } override fun partTwo() = instructions.fold(mutableMapOf<Pair<Int, Int>, Int>()) { lights, instruction -> when (instruction.action) { TURN_ON -> instruction.lights.forEach { light -> lights[light] = lights.getOrDefault(light, 0) + 1 } TURN_OFF -> instruction.lights.forEach { light -> lights[light] = max(0, lights.getOrDefault(light, 0) - 1) } TOGGLE -> instruction.lights.forEach { light -> lights[light] = lights.getOrDefault(light, 0) + 2 } } lights }.values.sum() companion object { private val INPUT_REGEX = """(turn on|turn off|toggle) (\d+),(\d+) through (\d+),(\d+)""".toRegex() private data class Instruction( val action: Action, val left: Int, val top: Int, val right: Int, val bottom: Int ) { val lights by lazy { listOf((left..right).toList(), (top..bottom).toList()).cartesianProduct().map { it.first() to it.last() } } } private enum class Action(val action: String) { TURN_ON("turn on"), TURN_OFF("turn off"), TOGGLE("toggle"); companion object { operator fun invoke(action: String) = entries.associateBy(Action::action)[action]!! } } } }
0
Kotlin
0
0
72492c6a7d0c939b2388e13ffdcbf12b5a1cb838
2,669
AdventOfCode
MIT License
year2021/src/main/kotlin/net/olegg/aoc/year2021/day14/Day14.kt
0legg
110,665,187
false
{"Kotlin": 511989}
package net.olegg.aoc.year2021.day14 import net.olegg.aoc.someday.SomeDay import net.olegg.aoc.utils.toPair import net.olegg.aoc.year2021.DayOf2021 import java.math.BigInteger /** * See [Year 2021, Day 14](https://adventofcode.com/2021/day/14) */ object Day14 : DayOf2021(14) { override fun first(): Any? { return solve(10) } override fun second(): Any? { return solve(40) } private fun solve(steps: Int): BigInteger { val (rawStart, rawPatterns) = data.split("\n\n") val patterns = rawPatterns.lines() .map { it.split(" -> ").toPair() } .associate { it.first to setOf("${it.first.first()}${it.second}", "${it.second}${it.first.last()}") } val start = rawStart.windowed(2) .groupingBy { it } .eachCount() .mapValues { it.value.toBigInteger() } val end = (1..steps).fold(start) { acc, _ -> val next = mutableMapOf<String, BigInteger>() acc.forEach { (chunk, size) -> (patterns[chunk] ?: setOf(chunk)).forEach { newChunk -> next[newChunk] = next.getOrDefault(newChunk, BigInteger.ZERO) + size } } next.toMap() } val chars = end.toList() .flatMap { listOf(it.first.first() to it.second, it.first.last() to it.second) } val doubleChars = chars + listOf(rawStart.first() to BigInteger.ONE, rawStart.last() to BigInteger.ONE) val charMap = doubleChars.groupBy { it.first } .mapValues { entry -> entry.value.sumOf { it.second } } return (charMap.maxOf { it.value } - charMap.minOf { it.value }).divide(BigInteger.TWO) } } fun main() = SomeDay.mainify(Day14)
0
Kotlin
1
7
e4a356079eb3a7f616f4c710fe1dfe781fc78b1a
1,613
adventofcode
MIT License
src/main/kotlin/nl/jackploeg/aoc/_2023/calendar/day23/Day23.kt
jackploeg
736,755,380
false
{"Kotlin": 318734}
package nl.jackploeg.aoc._2023.calendar.day23 import nl.jackploeg.aoc.generators.InputGenerator.InputGeneratorFactory import nl.jackploeg.aoc.utilities.readStringFile import javax.inject.Inject import kotlin.math.max class Day23 @Inject constructor( private val generatorFactory: InputGeneratorFactory, ) { fun partOne(fileName: String): Int { val input = readStringFile(fileName) val grid = input.map { row -> row.toList() }.toList() val start = Location(0, grid[0].indexOf('.')) val goal = Location(grid.lastIndex, grid[grid.lastIndex].indexOf('.')) return dfs(grid, start, goal) } fun partTwo(fileName: String): Int { val input = readStringFile(fileName) val grid = input.map { row -> row.toList() }.toList() val adjacencyGraph = makeAdjacencies(grid) val start = Location(0, grid[0].indexOf('.')) val goal = Location(grid.lastIndex, grid[grid.lastIndex].indexOf('.')) return dfsWithAdjacencies(adjacencyGraph, start, goal) } private fun dfs( grid: List<List<Char>>, current: Location, goal: Location, visited: MutableSet<Location> = mutableSetOf(), steps: Int = 0 ): Int { if (current == goal) { return steps } visited.add(current) val theirSteps = getNavigableNeighbors(grid, current) .filter { it !in visited } .map { dfs(grid, it, goal, visited, steps + 1) } .maxOfOrNull { it } ?: -1 visited.remove(current) return max(theirSteps, steps) } private fun makeAdjacencies(grid: List<List<Char>>): Map<Location, Map<Location, Int>> { // create a list of every location, and their direct neighbors val adjacencies = grid.indices.flatMap { rowIndex -> grid[rowIndex].indices.filter { grid[rowIndex][it] != '#' }.map { colIndex -> val neighbors = DIRECTIONS .map { deltas -> rowIndex + deltas.first to colIndex + deltas.second } .filter { (row, col) -> row in grid.indices && col in grid[0].indices && grid[row][col] != '#' } .associateTo(mutableMapOf()) { (row, col) -> Location(row, col) to 1 } Location(rowIndex, colIndex) to neighbors } }.toMap(mutableMapOf()) // collapse all the nodes that have "two neighbors" (not a branching location) adjacencies.keys.toList().forEach { location -> adjacencies[location]?.takeIf { it.size == 2 }?.let { neighbors -> val first = neighbors.keys.first() val last = neighbors.keys.last() val totalSteps = neighbors[first]!! + neighbors[last]!! adjacencies.getOrPut(first) { mutableMapOf() }.merge(last, totalSteps, ::maxOf) adjacencies.getOrPut(last) { mutableMapOf() }.merge(first, totalSteps, ::maxOf) listOf(first, last).forEach { adjacencies[it]?.remove(location) } adjacencies.remove(location) } } return adjacencies } private fun dfsWithAdjacencies( adjacencyGraph: Map<Location, Map<Location, Int>>, current: Location, goal: Location, visited: MutableMap<Location, Int> = mutableMapOf() ): Int { if (current == goal) { return visited.values.sum() } var myBest = 0 (adjacencyGraph[current] ?: emptyMap()).forEach { (neighbor, steps) -> if (neighbor !in visited) { visited[neighbor] = steps val neighborsBest = dfsWithAdjacencies(adjacencyGraph, neighbor, goal, visited) myBest = max(myBest, neighborsBest) visited.remove(neighbor) } } return myBest } private fun getNavigableNeighbors(grid: List<List<Char>>, current: Location): List<Location> { val cur = grid[current.row][current.col] return DIRECTIONS_WITH_SLOPE .map { (deltas, slope) -> (deltas.first + current.row to deltas.second + current.col) to slope } .filter { (coords, slope) -> val (row, col) = coords row in grid.indices && col in grid[0].indices && grid[row][col] != '#' && (cur == '.' || cur == slope) }.map { (coords, _) -> Location(coords.first, coords.second) } } data class Location(val row: Int, val col: Int) val NORTH = (-1 to 0) val SOUTH = (1 to 0) val EAST = (0 to 1) val WEST = (0 to -1) val DIRECTIONS = listOf(NORTH, SOUTH, EAST, WEST) val NORTH_SLOPE = NORTH to '^' val SOUTH_SLOPE = SOUTH to 'v' val EAST_SLOPE = EAST to '>' val WEST_SLOPE = WEST to '<' val DIRECTIONS_WITH_SLOPE = listOf(NORTH_SLOPE, SOUTH_SLOPE, EAST_SLOPE, WEST_SLOPE) }
0
Kotlin
0
0
f2b873b6cf24bf95a4ba3d0e4f6e007b96423b76
4,455
advent-of-code
MIT License
src/main/kotlin/com/ginsberg/advent2023/Day05.kt
tginsberg
723,688,654
false
{"Kotlin": 112398}
/* * Copyoutgoing (c) 2023 by <NAME> */ /** * Advent of Code 2023, Day 5 - If You Give A Seed A Fertilizer * Problem Description: http://adventofcode.com/2023/day/5 * Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2023/day5/ */ package com.ginsberg.advent2023 class Day05(input: List<String>) { private val seedsPart1: List<Long> = parsePart1Seeds(input) private val seedsPart2: Set<LongRange> = parsePart2Seeds(input) private val ranges = parseRanges(input) fun solvePart1(): Long = seedsPart1.minOf { seed -> ranges.fold(seed) { acc, ranges -> ranges.firstOrNull { acc in it }?.translate(acc) ?: acc } } fun solvePart2(): Long { val rangesReversed = ranges.map { range -> range.map { it.flip() } }.reversed() return generateSequence(0L, Long::inc).first { location -> val seed = rangesReversed.fold(location) { acc, ranges -> ranges.firstOrNull { acc in it }?.translate(acc) ?: acc } seedsPart2.any { seedRange -> seed in seedRange } } } private fun parseRanges(input: List<String>): List<Set<RangePair>> = input.drop(2).joinToString("\n").split("\n\n").map { it.split("\n").drop(1).map { line -> RangePair.of(line) }.toSet() } private fun parsePart1Seeds(input: List<String>): List<Long> = input.first().substringAfter(":").trim().split(" ").map { it.toLong() } private fun parsePart2Seeds(input: List<String>): Set<LongRange> = input.first().substringAfter(":").trim().split(" ") .map { it.toLong() }.chunked(2).map { it.first()..<it.first() + it.last() }.toSet() private data class RangePair( private val source: LongRange, private val destination: LongRange ) { fun flip(): RangePair = RangePair(destination, source) fun translate(num: Long): Long = destination.first + (num - source.first) operator fun contains(num: Long): Boolean = num in source companion object { fun of(row: String): RangePair { val parts = row.split(" ").map { it.toLong() } return RangePair( parts[1]..<(parts[1] + parts[2]), parts[0]..<(parts[0] + parts[2]) ) } } } }
0
Kotlin
0
12
0d5732508025a7e340366594c879b99fe6e7cbf0
2,462
advent-2023-kotlin
Apache License 2.0
src/Day02.kt
karlwalsh
573,854,263
false
{"Kotlin": 32685}
import Result.* import Shape.* fun main() { fun part1(input: List<String>): Int = input.asInputForPart1() .sumOf { (opponentsShape, yourShape) -> val result = yourShape.against(opponentsShape) yourShape.score() + result.score() } fun part2(input: List<String>): Int = input.asInputForPart2() .sumOf { (opponentsShape, result) -> val yourShape = when (result) { WIN -> opponentsShape.losesAgainst() LOSE -> opponentsShape.winsAgainst() DRAW -> opponentsShape } yourShape.score() + result.score() } val input = readInput("Day02") with(::part1) { val exampleResult = this(example()) check(exampleResult == 15) { "Part 1 result was $exampleResult" } println("Part 1: ${this(input)}") } with(::part2) { val exampleResult = this(example()) check(exampleResult == 12) { "Part 2 result was $exampleResult" } println("Part 2: ${this(input)}") } } private enum class Shape(private val score: Int) { ROCK(1) { override fun losesAgainst() = PAPER override fun winsAgainst() = SCISSORS }, PAPER(2) { override fun losesAgainst() = SCISSORS override fun winsAgainst() = ROCK }, SCISSORS(3) { override fun losesAgainst() = ROCK override fun winsAgainst() = PAPER }; abstract fun losesAgainst(): Shape abstract fun winsAgainst(): Shape fun against(other: Shape): Result = when (other) { winsAgainst() -> WIN losesAgainst() -> LOSE else -> DRAW } fun score(): Int = score } private enum class Result(private val score: Int) { WIN(6), LOSE(0), DRAW(3); fun score(): Int = score } private fun List<String>.asInputForPart1(): List<Pair<Shape, Shape>> = this .map { val opponent = when (it[0]) { 'A' -> ROCK 'B' -> PAPER 'C' -> SCISSORS else -> throw IllegalArgumentException("Unknown Play ${it[0]}") } val you = when (it[2]) { 'X' -> ROCK 'Y' -> PAPER 'Z' -> SCISSORS else -> throw IllegalArgumentException("Unknown Play ${it[2]}") } opponent to you } private fun List<String>.asInputForPart2(): List<Pair<Shape, Result>> = this .map { val opponent = when (it[0]) { 'A' -> ROCK 'B' -> PAPER 'C' -> SCISSORS else -> throw IllegalArgumentException("Unknown Play ${it[0]}") } val expectedResult = when (it[2]) { 'X' -> LOSE 'Y' -> DRAW 'Z' -> WIN else -> throw IllegalArgumentException("Unknown Result ${it[2]}") } opponent to expectedResult } private fun example() = """ A Y B X C Z """.trimIndent().lines()
0
Kotlin
0
0
f5ff9432f1908575cd23df192a7cb1afdd507cee
3,026
advent-of-code-2022
Apache License 2.0
src/main/kotlin/Main.kt
xrrocha
715,337,265
false
{"Kotlin": 4981}
import info.debatty.java.stringsimilarity.Damerau import java.io.File import kotlin.math.max fun main(args: Array<String>) { val maxScore = 0.4 val damerau = Damerau() val baseDir = File("src/test/resources") val words = File(baseDir, "words.txt") .bufferedReader() .lineSequence() .map { it.split("\t")[0] } .toList() .distinct() println("Loaded ${words.size} words") val startTime = System.currentTimeMillis() class Score(val first: String, val second: String, val distance: Double) { val str by lazy { "$first $second $distance" } override fun toString() = str } val matrix = words.indices .flatMap { i -> (i + 1..<words.size) .map { j -> Score( words[i], words[j], damerau.distance(words[i], words[j]) / max(words[i].length, words[j].length).toDouble() ) } .filter { it.distance < maxScore } .flatMap { listOf( it, Score(it.second, it.first, it.distance) ) } } .groupBy { it.first } .mapValues { (word, values) -> values.associate { it.second to it.distance } + (word to 0.0) } File(baseDir, "word-matrix.txt").printWriter().use { out -> matrix .toList() .sortedBy { it.first } .forEach { (word, neighbors) -> val neighborStr = neighbors .toList() .sortedBy { (_, s) -> s } .joinToString(" ") { (w, s) -> "$w:$s" } out.println("$word $neighborStr") } out.flush() } val endTime = System.currentTimeMillis() println("Wrote ${matrix.size} scores in ${endTime - startTime} milliseconds") fun intraDistances(cluster: Collection<String>): List<Pair<String, Double>> = cluster .map { first -> first to cluster .map { second -> matrix[first]!![second]!! } .average() } .sortedBy { it.second } fun analyzeCluster(cluster: Collection<String>): Triple<List<String>, List<String>, Double> = intraDistances(cluster) .let { intraDistances -> val bestIntraDistance = intraDistances.first().second val medoids = intraDistances .takeWhile { it.second == bestIntraDistance } .map { it.first } .sorted() val avgIntraDistance = intraDistances.map { it.second }.average() val orderedCluster = intraDistances.sortedBy { it.second }.map { it.first } Triple(orderedCluster, medoids, avgIntraDistance) } class DistanceClusters( distance: Double, orderedCluster: List<String>, intraDistance: Double, medoids: List<String>, others: List<String> ) { val str by lazy { listOf( distance, intraDistance, medoids.size, medoids.joinToString(","), orderedCluster.size, orderedCluster.joinToString(","), others.size, others.joinToString(","), ) .joinToString(" ") } override fun toString() = str } val distances = matrix.values .flatMap { it.values.toSet() } .toSet().toList().sorted() val distanceClusters = distances .filter { it > 0.0 } .map { threshold -> threshold to matrix .map { (word, neighbors) -> word to neighbors .filter { (_, distance) -> distance <= threshold } .map { it.key } .toSet() } .groupBy { (_, profile) -> profile } .toList() .map { (profile, values) -> values.map { it.first }.toSet() to profile } .sortedBy { -it.first.size } } .flatMap { (distance, pairs) -> pairs .map { (cluster, profile) -> val others = profile.minus(cluster).sorted() val (orderedCluster, medoids, intraDistance) = analyzeCluster(cluster) DistanceClusters(distance, orderedCluster, intraDistance, medoids, others) } } File(baseDir, "word-distance-clusters.txt").printWriter().use { out -> distanceClusters.forEach(out::println) out.flush() } }
0
Kotlin
0
0
c571546a4ab09ec41be737d39524cec06fb9a213
4,981
grappolo-pg
Apache License 2.0
src/Day10.kt
MatthiasDruwe
571,730,990
false
{"Kotlin": 47864}
fun main() { fun calculateValue(cycle:Int, v: Int): Int{ if(cycle%40==20){ return cycle*v } return 0 } fun part1(input: List<String>): Int { var cycle = 1 var value = 1 var sum = 0 input.forEach { val split = it.split(" ") if(split[0]=="addx"){ val v = split[1].toInt() cycle++ sum+=calculateValue(cycle, value) cycle++ value+=v sum+=calculateValue(cycle, value) } else { cycle++ sum+=calculateValue(cycle,value) } } return sum } fun draw(cycle: Int, v: Int ): String{ if(cycle%40 in v-1..v+1){ return "#" } else { return "." } } fun part2(input: List<String>): List<String> { var cycle = 0 var value = 1 var sum = "" input.forEach { val split = it.split(" ") if(split[0]=="addx"){ val v = split[1].toInt() sum+=draw(cycle, value) cycle++ sum+=draw(cycle, value) cycle++ value+=v } else { sum+=draw(cycle,value) cycle++ } } return sum.windowed(40, 40) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day10_example") check(part1(testInput) == 13140) val solutionPart2 = listOf("##..##..##..##..##..##..##..##..##..##..", "###...###...###...###...###...###...###.", "####....####....####....####....####....", "#####.....#####.....#####.....#####.....", "######......######......######......####", "#######.......#######.......#######....." ) check(part2(testInput) == solutionPart2) val input = readInput("Day10") println(part1(input)) println(part2(input)) part2(input).forEach { println(it) } }
0
Kotlin
0
0
f35f01cea5075cfe7b4a1ead9b6480ffa57b4989
2,136
Advent-of-code-2022
Apache License 2.0
src/Day03.kt
lsimeonov
572,929,910
false
{"Kotlin": 66434}
fun main() { val az = ('a'..'z').toList() + ('A'..'Z').toList() fun part1(input: List<String>): Int { return input.map { it.chunked(it.length / 2) .reduce { acc, string -> string.toList().intersect(acc.toList().toSet()).first().toString() }.first() }.fold(0) { acc: Int, c: Char -> acc + az.indexOf(c) + 1 } } fun part2(input: List<String>): Int { return input.chunked(3).sumOf { az.indexOf(it[0].toList().filter { ch -> it.slice(1 until it.lastIndex + 1).filter { s -> s.toList().contains(ch) }.size == 2 }.distinct().first()) + 1 } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
9d41342f355b8ed05c56c3d7faf20f54adaa92f1
941
advent-of-code-2022
Apache License 2.0
src/main/kotlin/biz/koziolek/adventofcode/year2021/day20/day20.kt
pkoziol
434,913,366
false
{"Kotlin": 715025, "Shell": 1892}
package biz.koziolek.adventofcode.year2021.day20 import biz.koziolek.adventofcode.* fun main() { val inputFile = findInput(object {}) val lines = inputFile.bufferedReader().readLines() val lookupTable = parseLookupTable(lines) val image0 = parseInputImage(lines) val image2 = enhanceNTimes(image0, lookupTable, n = 2) println("Lit pixels on 2nd image: ${image2.countLitPixels()}") val image50 = enhanceNTimes(image0, lookupTable, n = 50) println("Lit pixels on 50th image: ${image50.countLitPixels()}") } data class InfiniteImage( val finitePixels: Map<Coord, Boolean>, val infinitePixels: Boolean, ) { val finiteWidth: Int = finitePixels.getWidth() val finiteHeight: Int = finitePixels.getHeight() operator fun get(coord: Coord): Boolean = finitePixels.getOrDefault(coord, infinitePixels) fun countLitPixels(): Int = finitePixels.count { it.value } fun enhance(lookupTable: BooleanArray): InfiniteImage = InfiniteImage( finitePixels = enhanceFinitePixels(lookupTable), infinitePixels = enhanceInfinitePixels(lookupTable), ) private fun enhanceFinitePixels(lookupTable: BooleanArray) = buildMap { for (newY in 0 until finiteHeight + 2) { for (newX in 0 until finiteWidth + 2) { val newCoord = Coord(newX, newY) val lookupIndex = getLookupIndex(newCoord) val newValue = lookupTable[lookupIndex] put(newCoord, newValue) } } } private fun enhanceInfinitePixels(lookupTable: BooleanArray): Boolean = when (infinitePixels) { // Off infinite pixels map to 000000000(2) == 0(10) false -> lookupTable[0] // On infinite pixels map to 111111111(2) == 511(10) true -> lookupTable[511] } private fun getLookupIndex(newCoord: Coord): Int = listOf( Coord(-1, -1), Coord(0, -1), Coord(1, -1), Coord(-1, 0), Coord(0, 0), Coord(1, 0), Coord(-1, 1), Coord(0, 1), Coord(1, 1), ) .map { newCoord + it + Coord(-1, -1) } .fold(0) { lookupIndex, oldCoord -> lookupIndex * 2 + if (get(oldCoord)) 1 else 0 } override fun toString(): String = buildString { val infiniteBorder = 3 for (y in -infiniteBorder until finiteHeight + infiniteBorder) { for (x in -infiniteBorder until finiteWidth + infiniteBorder) { val coord = Coord(x, y) if (get(coord)) { append('#') } else { append('.') } } if (y < finiteHeight + infiniteBorder - 1) { append("\n") } } } } fun parseLookupTable(lines: Iterable<String>): BooleanArray = lines.first() .map { it == '#' } .toBooleanArray() fun parseInputImage(lines: Iterable<String>): InfiniteImage = InfiniteImage( finitePixels = lines .drop(2) .parse2DMap { it == '#' } .toMap(), infinitePixels = false, ) fun enhanceNTimes(image: InfiniteImage, lookupTable: BooleanArray, n: Int) = (1..n).fold(image) { img, _ -> img.enhance(lookupTable) }
0
Kotlin
0
0
1b1c6971bf45b89fd76bbcc503444d0d86617e95
3,536
advent-of-code
MIT License
src/Day08.kt
jamie23
573,156,415
false
{"Kotlin": 19195}
import Direction.* import kotlin.math.max fun main() { fun part1(input: List<String>): Int { val height = input.size val width = input[0].length val set: HashSet<Pair<Int, Int>> = hashSetOf() for (i in 0 until height) { var currMaxX = -1 var currMaxY = -1 var currMaxXReverse = -1 var currMaxYReverse = -1 for (j in 0 until width) { val currValX = input[i][j].digitToInt() val currValY = input[j][i].digitToInt() val currValXReverse = input[height - 1 - i][width - 1 - j].digitToInt() val currValYReverse = input[width - 1 - j][height - 1 - i].digitToInt() if (currValX > currMaxX) { set.add(Pair(i, j)) currMaxX = currValX } if (currValY > currMaxY) { set.add(Pair(j, i)) currMaxY = currValY } if (currValXReverse > currMaxXReverse) { set.add(Pair(width - i - 1, height - j - 1)) currMaxXReverse = currValXReverse } if (currValYReverse > currMaxYReverse) { set.add(Pair(height - j - 1, width - i - 1)) currMaxYReverse = currValYReverse } } } return set.size } fun List<String>.parseToDigitList() = map { row -> row.map { char -> char.digitToInt() } } fun pathToFirstBlocker(list: List<Int>, currentHeight: Int): Int { val firstBlocker = list.indexOfFirst { it >= currentHeight } + 1 if (firstBlocker == 0) return list.size return firstBlocker } fun List<List<Int>>.colSubList(col: Int, start: Int, direction: Direction): List<Int> { val list = mutableListOf<Int>() val range = if (direction == DOWN) { start until get(col).size } else { start downTo 0 } for (i in range) list.add(get(i)[col]) return list } fun List<Int>.scenicScore(): Int { val start = get(0) val score = this.drop(1).takeWhile { it < start }.size if (score + 1 == size) return score return score + 1 } fun List<List<Int>>.maxScenicScore(): Int { // For each element in middle of list, get left, right, up, down scenic scores and multiply them // return max val range = 1 until size - 1 var max = -1 for (i in range) { for (j in range) { val right = get(i).subList(j, size).scenicScore() val left = get(i).subList(0, j + 1).reversed().scenicScore() val top = colSubList(j, i, UP).scenicScore() val down = colSubList(j, i, DOWN).scenicScore() val total = right * left * top * down max = max(total, max) } } return max } fun checkUtils() { // Part 2 tests check(pathToFirstBlocker(listOf(4, 2, 3), 3) == 1) check(pathToFirstBlocker(listOf(3, 9, 9), 4) == 2) check(pathToFirstBlocker(listOf(5, 2, 3), 6) == 3) val listTest = listOf( "123", "456", "789" ) check( listTest .parseToDigitList() .colSubList(0, 0, DOWN) == listOf(1, 4, 7) ) check( listTest .parseToDigitList() .colSubList(1, 1, DOWN) == listOf(5, 8) ) check( listTest .parseToDigitList() .colSubList(2, 2, UP) == listOf(9, 6, 3) ) check( listTest .parseToDigitList() .colSubList(1, 1, UP) == listOf(5, 2) ) check( listOf(5, 2, 9).scenicScore() == 2 ) check(listOf(2, 5, 9).scenicScore() == 1) } fun part2(input: List<String>) = input .parseToDigitList() .maxScenicScore() val testInput = readInput("Day08_test") check(part1(testInput) == 21) check(part2(testInput) == 8) checkUtils() val input = readInput("Day08") println(part1(input)) println(part2(input)) } private enum class Direction { UP, DOWN }
0
Kotlin
0
0
cfd08064654baabea03f8bf31c3133214827289c
4,414
Aoc22
Apache License 2.0
src/com/wd/algorithm/leetcode/ALGO0001.kt
WalkerDenial
327,944,547
false
null
package com.wd.algorithm.leetcode import com.wd.algorithm.test /** * 1. 两数之和 * * 给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 的那两个整数,并返回它们的数组下标。 * 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。 * 你可以按任意顺序返回答案。 */ class ALGO0001 { /** * 方式一 * 冒泡方式 * 时间复杂度 T(n²) */ fun twoSum1(num: IntArray, target: Int): IntArray { for (i in 0 until (num.size - 1)) { // 从剩余的数据中查找能相加等于 target 的数,如果存在,则返回 for (j in (i + 1) until num.size) { if (num[i] + num[j] == target) return intArrayOf(i, j) } } return intArrayOf(0, 0) } /** * 方式二 * 采用 Map 作为缓存的方式 * 时间复杂度 T(n) */ fun twoSum2(nums: IntArray, target: Int): IntArray { val paramMap = mutableMapOf<Int, Int>() for ((i, n) in nums.withIndex()) { val index = paramMap[target - n] if (index != null) return intArrayOf(index, i) paramMap[nums[i]] = i } return intArrayOf(0, 0) } } fun main() { val clazz = ALGO0001() val data = intArrayOf(42, 34, 1, 6, 7, 87, 45, 7, 4, 9, 2, 423, 126) val target = 127 (clazz::twoSum1).test(data, target) (clazz::twoSum2).test(data, target) }
0
Kotlin
0
0
245ab89bd8bf467625901034dc1139f0a626887b
1,552
AlgorithmAnalyze
Apache License 2.0
src/Day20.kt
wgolyakov
572,463,468
false
null
fun main() { fun part1(input: List<String>): Int { val numbers = input.map { it.toInt() }.toMutableList() val indToCurrInd = numbers.indices.associateWith { it }.toMutableMap() val n = numbers.size for ((ind, x) in numbers.toList().withIndex()) { val i = indToCurrInd[ind]!! numbers.removeAt(i) for (entry in indToCurrInd.entries) if (entry.value > i) entry.setValue(entry.value - 1) var j = (i + x) % (n - 1) if (j < 0) j += n - 1 numbers.add(j, x) for (entry in indToCurrInd.entries) if (entry.value >= j) entry.setValue(entry.value + 1) indToCurrInd[ind] = j } val zero = numbers.indexOf(0) val n1 = numbers[(zero + 1000) % n] val n2 = numbers[(zero + 2000) % n] val n3 = numbers[(zero + 3000) % n] return n1 + n2 + n3 } fun part2(input: List<String>): Long { val premixedNumbers = input.map { it.toLong() * 811589153 } val numbers = premixedNumbers.toMutableList() val indToCurrInd = numbers.indices.associateWith { it }.toMutableMap() val n = numbers.size for (t in 0 until 10) { for ((ind, x) in premixedNumbers.withIndex()) { val i = indToCurrInd[ind]!! numbers.removeAt(i) for (entry in indToCurrInd.entries) if (entry.value > i) entry.setValue(entry.value - 1) var j = ((x + i) % (n - 1)).toInt() if (j < 0) j += n - 1 numbers.add(j, x) for (entry in indToCurrInd.entries) if (entry.value >= j) entry.setValue(entry.value + 1) indToCurrInd[ind] = j } } val zero = numbers.indexOf(0) val n1 = numbers[(zero + 1000) % n] val n2 = numbers[(zero + 2000) % n] val n3 = numbers[(zero + 3000) % n] return n1 + n2 + n3 } val testInput = readInput("Day20_test") check(part1(testInput) == 3) check(part2(testInput) == 1623178306L) val input = readInput("Day20") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
789a2a027ea57954301d7267a14e26e39bfbc3c7
1,841
advent-of-code-2022
Apache License 2.0
src/Day01.kt
diesieben07
572,879,498
false
{"Kotlin": 44432}
import kotlin.math.max private val file = "Day01" private fun Sequence<String>.parseInput(): Sequence<Int?> { return map { it.toIntOrNull() } + null } private fun part1() { data class State(val maxSoFar: Int = Integer.MIN_VALUE, val accumulator: Int = 0) val max = streamInput(file) { lines -> lines .parseInput() .fold(State()) { state, amount -> if (amount == null) { State(max(state.maxSoFar, state.accumulator), 0) } else { state.copy(accumulator = state.accumulator + amount) } }.maxSoFar } println("Max 1 is $max") } private fun part2(topN: Int = 3) { data class State(val maxEntries: List<Int> = listOf(), val accumulator: Int = 0) { fun endOfGroup(): State { val index = maxEntries.binarySearch(accumulator) if (index < 0) { val insertionPoint = -(index + 1) val newList = maxEntries.toMutableList() newList.add(insertionPoint, accumulator) if (newList.size > topN) { newList.removeAt(0) } return State(newList, 0) } return copy(accumulator = 0) } fun addEntry(amount: Int): State { return copy(accumulator = amount + accumulator) } } val max = streamInput(file) { lines -> lines .parseInput() .fold(State()) { state, amount -> if (amount == null) { state.endOfGroup() } else { state.addEntry(amount) } }.maxEntries.sum() } println("Max 2 is $max") } fun main() { part1() part2(1) part2(3) }
0
Kotlin
0
0
0b9993ef2f96166b3d3e8a6653b1cbf9ef8e82e6
1,832
aoc-2022
Apache License 2.0
src/main/kotlin/day-02.kt
warriorzz
728,357,548
false
{"Kotlin": 15609, "PowerShell": 237}
package com.github.warriorzz.aoc class Day2 : Day(2) { var games: List<Game> = listOf() var testGames: List<Game> = listOf() override fun init() { games = input.map { line -> val id = line.split(": ")[0].split(" ")[1].toInt() val sets = line.split(": ")[1].split("; ").map { set -> var green = 0 var blue = 0 var red = 0 set.split(", ").forEach { when (it.split(" ")[1]) { "green" -> green = it.split(" ")[0].toInt() "red" -> red = it.split(" ")[0].toInt() "blue" -> blue = it.split(" ")[0].toInt() } } CubeSet(blue, green, red) } Game(id, sets) } testGames = testInput.map { line -> val id = line.split(": ")[0].split(" ")[1].toInt() val sets = line.split(": ")[1].split("; ").map { set -> var green = 0 var blue = 0 var red = 0 set.split(", ").forEach { when (it.split(" ")[1]) { "green" -> green = it.split(" ")[0].toInt() "red" -> red = it.split(" ")[0].toInt() "blue" -> blue = it.split(" ")[0].toInt() } } CubeSet(blue, green, red) } Game(id, sets) } } override val partOne: (List<String>, Boolean) -> String = { _, testing -> (if (testing) testGames else games).filter { game -> game.sets.all { it.green <= 13 && it.blue <= 14 && it.red <= 12 } }.map { it.id }.reduce { acc, i -> acc + i }.toString() } override val partTwo: (List<String>, Boolean) -> String = { _, testing -> (if (testing) testGames else games).sumOf { var minRed = 0 var minGreen = 0 var minBlue = 0 it.sets.forEach { set -> if (set.red > minRed) minRed = set.red if (set.blue > minBlue) minBlue = set.blue if (set.green > minGreen) minGreen = set.green } minRed * minGreen * minBlue }.toString() } } data class Game(val id: Int, val sets: List<CubeSet>) data class CubeSet(val blue: Int, val green: Int, val red: Int)
0
Kotlin
0
1
502993c1cd414c0ecd97cda41475401e40ebb8c1
2,419
aoc-23
MIT License
src/year2021/Day2.kt
drademacher
725,945,859
false
{"Kotlin": 76037}
package year2021 import readLines fun main() { val input = readLines("2021", "day2").map { Movement.fromString(it) } val testInput = readLines("2021", "day2_test").map { Movement.fromString(it) } check(part1(testInput) == 150) println("Part 1:" + part1(input)) check(part2(testInput) == 900) println("Part 2:" + part2(input)) } private fun part1(input: List<Movement>): Int { var horizontal = 0 var depth = 0 for (movement in input) { when (movement) { is Movement.Forward -> horizontal += movement.number is Movement.Up -> depth -= movement.number is Movement.Down -> depth += movement.number } } return horizontal * depth } private fun part2(input: List<Movement>): Int { var horizontal = 0 var aim = 0 var depth = 0 for (movement in input) { when (movement) { is Movement.Forward -> { horizontal += movement.number depth += aim * movement.number } is Movement.Up -> aim -= movement.number is Movement.Down -> aim += movement.number } } return horizontal * depth } sealed class Movement { data class Forward(val number: Int) : Movement() data class Up(val number: Int) : Movement() data class Down(val number: Int) : Movement() companion object { fun fromString(string: String): Movement { val parts = string.split(" ") return when (parts[0]) { "forward" -> Forward(parts[1].toInt()) "up" -> Up(parts[1].toInt()) "down" -> Down(parts[1].toInt()) else -> throw RuntimeException("should not happen: '$string'") } } } }
0
Kotlin
0
0
4c4cbf677d97cfe96264b922af6ae332b9044ba8
1,782
advent_of_code
MIT License
src/main/aoc2018/Day11.kt
nibarius
154,152,607
false
{"Kotlin": 963896}
package aoc2018 class Day11(input: String) { private val serialNumber = input.toInt() private val grid = List(300) { x -> List(300) { y -> getPowerLevel(x + 1, y + 1) } } fun getPowerLevel(x: Int, y: Int): Int { val rackId = x + 10 var powerLevel = rackId * y powerLevel += serialNumber powerLevel *= rackId powerLevel = powerLevel.toString().takeLast(3).take(1).toInt() powerLevel -= 5 return powerLevel } // The sum of all the numbers inside the given square private fun squareValue(x: Int, y: Int, size: Int): Int { var sum = 0 for (dx in 0 until size) { for (dy in 0 until size) { sum += grid[x + dx - 1][y + dy - 1] } } return sum } // The sum of all numbers in a given row with the given start x coordinate and row length private fun rowSum(row: Int, start: Int, size: Int): Int { var sum = 0 for (x in start until start + size) { sum += grid[x - 1][row - 1] } return sum } // The sum of all numbers in a given column starting from the top and with the given length private fun colSum(col: Int, size: Int): Int { var sum = 0 for (y in 1..size) { sum += grid[col - 1][y - 1] } return sum } // Find the square with the largest value with the given size // To make things faster calculate the full square value only for // the top left square. For all other squares calculate the value // based on the previous square and the columns/rows that differs. private fun findMaxSquare(size: Int): Pair<String, Int> { var address = "" var previousXSquare = squareValue(1, 1, size) var previousYSquare = previousXSquare var max = previousXSquare for (x in 1..300 - size) { if (x != 1) { // x = 1 is the initial value calculated outside the loop // Calculate the value of the square to the right of the previously calculated square at y=1 // previous value - column to the left + column to the right val currentSquare = previousXSquare - colSum(x - 1, size) + colSum(x + size - 1, size) if (currentSquare > max) { max = currentSquare address = "$x,0,$size" } previousYSquare = currentSquare previousXSquare = currentSquare } for (y in 2..300 - size) { // y = 1 is calculated outside this loop // Calculate the value of the square of the given size starting at (x,y) based on the previously calculate square above this one // previous value - row above + row below val currentSquare = previousYSquare - rowSum(y - 1, x, size) + rowSum(y + size - 1, x, size) if (currentSquare > max) { max = currentSquare address = "$x,$y,$size" } previousYSquare = currentSquare } } return Pair(address, max) } fun solvePart1(): String { return findMaxSquare(3).first.substringBeforeLast(",") } fun solvePart2(): String { return (1..300).map { findMaxSquare(it) }.maxByOrNull { it.second }!!.first } }
0
Kotlin
0
6
f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22
3,406
aoc
MIT License
src/main/kotlin/g2501_2600/s2538_difference_between_maximum_and_minimum_price_sum/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2501_2600.s2538_difference_between_maximum_and_minimum_price_sum // #Hard #Array #Dynamic_Programming #Depth_First_Search #Tree // #2023_07_04_Time_1054_ms_(100.00%)_Space_106.6_MB_(100.00%) class Solution { private lateinit var tree: Array<ArrayList<Int>?> private lateinit var price: IntArray private var res: Long = 0 private lateinit var visited: BooleanArray fun maxOutput(n: Int, edges: Array<IntArray>, price: IntArray): Long { if (n == 1) { return 0 } this.price = price tree = arrayOfNulls(n) for (i in 0 until n) { tree[i] = ArrayList() } for (e in edges) { tree[e[0]]?.add(e[1]) tree[e[1]]?.add(e[0]) } visited = BooleanArray(n) visited[0] = true dfs(0) return res } // return long[]{longest path with leaf, longest path without leaf} private fun dfs(node: Int): LongArray { if (tree[node]?.size == 1 && node != 0) { return longArrayOf(price[node].toLong(), 0) } var i0 = -1 var i1 = -1 var l0: Long = 0 var l1: Long = 0 var s0: Long = 0 var s1: Long = 0 for (child in tree[node]!!) { if (visited[child]) { continue } visited[child] = true val sub = dfs(child) if (sub[0] >= l0) { s0 = l0 l0 = sub[0] i0 = child } else if (sub[0] > s0) { s0 = sub[0] } if (sub[1] >= l1) { s1 = l1 l1 = sub[1] i1 = child } else if (sub[1] > s1) { s1 = sub[1] } } res = if (s0 == 0L) { // only one child. case: example 2 Math.max(res, Math.max(l0, l1 + price[node])) } else { val path = if (i0 != i1) price[node] + l0 + l1 else price[node] + Math.max(l0 + s1, s0 + l1) Math.max(res, path) } return longArrayOf(l0 + price[node], l1 + price[node]) } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
2,171
LeetCode-in-Kotlin
MIT License
src/Day04.kt
arnoutvw
572,860,930
false
{"Kotlin": 33036}
fun main() { fun toRange(str: String): IntRange = str .split("-") .let { (a, b) -> a.toInt()..b.toInt() } fun part1(input: List<String>): Int { var sum = 0 input.forEach { val split = it.split(",") val first = toRange(split.get(0)) val second = toRange(split.get(1)) val intersection = first.intersect(second) if(intersection.isNotEmpty() && (intersection == first.toSet() || intersection == second.toSet())) { sum++ } } return sum } fun part2(input: List<String>): Int { var sum = 0 input.forEach { val split = it.split(",") val first = toRange(split.get(0)) val second = toRange(split.get(1)) val intersection = first.intersect(second) if(intersection.isNotEmpty()) { sum++ } } return sum } // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_test") println("Test") println(part1(testInput)) println(part2(testInput)) check(part1(testInput) == 2) check(part2(testInput) == 4) println("Waarde") val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
0cee3a9249fcfbe358bffdf86756bf9b5c16bfe4
1,349
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/org/sjoblomj/adventofcode/day2/Day2.kt
sjoblomj
161,537,410
false
null
package org.sjoblomj.adventofcode.day2 import org.sjoblomj.adventofcode.readFile import java.util.stream.IntStream import kotlin.system.measureTimeMillis private const val inputFile = "src/main/resources/inputs/day2.txt" fun day2() { println("== DAY 2 ==") val timeTaken = measureTimeMillis { calculateAndPrintDay2() } println("Finished Day 2 in $timeTaken ms\n") } private fun calculateAndPrintDay2() { val content = readFile(inputFile) println("Resulting checksum is ${calculateChecksum(content)}") println("Common part of the strings where exactly one character differs between them: ${findCommonPartOfStringsWithOneCharDifferences(content)}") } internal fun containsExactlyTwoIdenticalLetters(line: String) = containsExactlyNIdenticalLetters(line, 2) internal fun containsExactlyThreeIdenticalLetters(line: String) = containsExactlyNIdenticalLetters(line, 3) private fun containsExactlyNIdenticalLetters(line: String, n: Int): Boolean { val charMap = mutableMapOf<Char, Int>() for (char: Char in line.toCharArray()) charMap[char] = charMap[char]?.plus(1) ?: 1 return charMap.containsValue(n) } internal fun calculateChecksum(input: List<String>): Int { val twos = input.filter { containsExactlyTwoIdenticalLetters(it) }.size val threes = input.filter { containsExactlyThreeIdenticalLetters(it) }.size return twos * threes } internal fun exactlyOneCharDiffers(s0: String, s1: String): Boolean { var numberOfDifferences = 0 for (i in s0.indices) { if (s0[i] != s1[i]) numberOfDifferences++ if (numberOfDifferences > 1) return false } return numberOfDifferences == 1 } internal fun findCommonPartOfStringsWithOneCharDifferences(input: List<String>): String? { if (input.map { it.length }.distinct().size != 1) throw IllegalArgumentException("Expected all lines to have the same length") for (i in input.indices) for (j in i + 1 until input.size) if (exactlyOneCharDiffers(input[i], input[j])) return findCommonPart(input[i], input[j]) return null } private fun findCommonPart(s0: String, s1: String): String { return IntStream.range(0, s0.length) .filter { s0[it] == s1[it] } .mapToObj { s0[it] } .toArray() .joinToString("") }
0
Kotlin
0
0
80db7e7029dace244a05f7e6327accb212d369cc
2,249
adventofcode2018
MIT License
src/test/kotlin/nl/dirkgroot/adventofcode/year2022/Day14Test.kt
dirkgroot
317,968,017
false
{"Kotlin": 187862}
package nl.dirkgroot.adventofcode.year2022 import io.kotest.core.spec.style.StringSpec import io.kotest.matchers.shouldBe import nl.dirkgroot.adventofcode.util.input import nl.dirkgroot.adventofcode.util.invokedWith import java.lang.Integer.max import kotlin.math.min private fun solution1(input: String) = createCave(input, withFloor = false).solve() private fun solution2(input: String) = createCave(input, withFloor = true).solve() private fun createCave(input: String, withFloor: Boolean) = Cave(input.lineSequence().map { "(\\d+),(\\d+)".toRegex().findAll(it).map { match -> match.groupValues.drop(1) } .map { (first, second) -> first.toInt() to second.toInt() } }, withFloor) private class Cave(lines: Sequence<Sequence<Pair<Int, Int>>>, withFloor: Boolean = false) { private val rocks = fillRocks(lines) private val maxY = rocks.maxOf { (_, y) -> y }.let { if (withFloor) it + 2 else it } private val stop = Int.MAX_VALUE to Int.MAX_VALUE init { if (withFloor) (0..1000).forEach { x -> rocks.add(x to maxY) } } private fun fillRocks(lines: Sequence<Sequence<Pair<Int, Int>>>) = lines.flatMap { it.windowed(2) } .flatMap { (a, b) -> sequence { for (x in min(a.first, b.first)..max(a.first, b.first)) for (y in min(a.second, b.second)..max(a.second, b.second)) yield(x to y) } }.toMutableSet() fun solve() = generateSequence { dropSand() }.takeWhile { it }.count() private fun dropSand(): Boolean { val (x, y) = generateSequence(500 to 0) { (x, y) -> val nextY = y + 1 when { !rocks.contains(x to nextY) -> x to nextY !rocks.contains(x - 1 to nextY) -> x - 1 to nextY !rocks.contains(x + 1 to nextY) -> x + 1 to nextY else -> stop } }.takeWhile { it != stop && it.second <= maxY }.last() return if (y < maxY) rocks.add(x to y) else false } } //===============================================================================================\\ private const val YEAR = 2022 private const val DAY = 14 class Day14Test : StringSpec({ "example part 1" { ::solution1 invokedWith exampleInput shouldBe 24 } "part 1 solution" { ::solution1 invokedWith input(YEAR, DAY) shouldBe 763 } "example part 2" { ::solution2 invokedWith exampleInput shouldBe 93 } "part 2 solution" { ::solution2 invokedWith input(YEAR, DAY) shouldBe 23921 } }) private val exampleInput = """ 498,4 -> 498,6 -> 496,6 503,4 -> 502,4 -> 502,9 -> 494,9 """.trimIndent()
1
Kotlin
1
1
ffdffedc8659aa3deea3216d6a9a1fd4e02ec128
2,686
adventofcode-kotlin
MIT License
src/Day03.kt
RobvanderMost-TomTom
572,005,233
false
{"Kotlin": 47682}
fun main() { fun String.splitRucksack() = toCharArray(0, length / 2) to toCharArray(length / 2) fun Char.toPriority() = if (this in 'a'..'z') { this - 'a' + 1 } else { this - 'A' + 27 } fun part1(input: List<String>): Int { return input.map { it.splitRucksack() } .map { it.first.intersect(it.second.asList().toSet()) } .sumOf { it.sumOf { c -> c.toPriority() }} } fun part2(input: List<String>): Int { return input .map { it.toCharArray().toSet() } .chunked(3) .flatMap { it.reduce { acc, s -> acc.intersect(s) }} .sumOf { it.toPriority() } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("Day03") println(part1(input)) println(part2(input)) }
5
Kotlin
0
0
b7143bceddae5744d24590e2fe330f4e4ba6d81c
992
advent-of-code-2022
Apache License 2.0
src/Day05.kt
dizney
572,581,781
false
{"Kotlin": 105380}
object Day05 { const val dayNumber = "05" const val EXPECTED_PART1_CHECK_ANSWER = "CMZ" const val EXPECTED_PART2_CHECK_ANSWER = "MCD" const val STACK_SETUP_ENTRY_WITH_SPACE_SIZE = 4 const val STACK_SETUP_ENTRY_SIZE = 3 } fun main() { fun List<String>.parseStackSetup(): List<MutableList<Char>> { val stacks = mutableListOf<MutableList<Char>>() for (lineIdx in this.size - 2 downTo 0) { val line = this[lineIdx] var stackIndex = 0 var stackEntryStartPosition = 0 while (stackEntryStartPosition < line.length) { if (stacks.size < stackIndex + 1) { stacks += mutableListOf<Char>() } val stackEntry = line.substring( stackEntryStartPosition until (stackEntryStartPosition + Day05.STACK_SETUP_ENTRY_SIZE) ) if (stackEntry.isNotBlank()) { stacks[stackIndex].add(stackEntry[1]) } stackIndex++ stackEntryStartPosition = stackIndex * Day05.STACK_SETUP_ENTRY_WITH_SPACE_SIZE } } return stacks } fun parseAndApplyMoves( input: List<String>, applyMove: (stacks: List<MutableList<Char>>, move: Triple<Int, Int, Int>) -> Unit ): String { val indexOfEmptyLine = input.indexOf("") val stackSetup = input.subList(0, indexOfEmptyLine).parseStackSetup() val moves = input.subList(indexOfEmptyLine + 1, input.size) val moveTemplate = Regex("move (\\d+) from (\\d+) to (\\d+)") moves.forEach { move -> moveTemplate.matchEntire(move)?.apply { val (amount, from, to) = this.destructured applyMove(stackSetup, Triple(amount.toInt(), from.toInt(), to.toInt())) } } return stackSetup.map { stack -> stack.last() }.joinToString(separator = "") } fun part1(input: List<String>): String { return parseAndApplyMoves(input) { stacks, (amount, from, to) -> repeat(amount) { _ -> val toMove = stacks[from - 1].removeLast() stacks[to - 1].add(toMove) } } } fun part2(input: List<String>): String { return parseAndApplyMoves(input) { stacks, (amount, from, to) -> val removedChars = (1..amount).map { _ -> stacks[from - 1].removeLast() } stacks[to - 1].addAll(removedChars.reversed()) } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day${Day05.dayNumber}_test") check(part1(testInput) == Day05.EXPECTED_PART1_CHECK_ANSWER) { "Part 1 failed" } check(part2(testInput) == Day05.EXPECTED_PART2_CHECK_ANSWER) { "Part 2 failed" } val input = readInput("Day${Day05.dayNumber}") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
f684a4e78adf77514717d64b2a0e22e9bea56b98
2,947
aoc-2022-in-kotlin
Apache License 2.0
src/year2021/Day11.kt
drademacher
725,945,859
false
{"Kotlin": 76037}
package year2021 import Point import readLines fun main() { val input = parseInput(readLines("2021", "day11")) val testInput = parseInput(readLines("2021", "day11_test")) check(part1(testInput.clone()) == 1656) println("Part 1:" + part1(input.clone())) check(part2(testInput.clone()) == 195) println("Part 2:" + part2(input.clone())) } private fun parseInput(lines: List<String>): Day11Input { return Day11Input( lines .map { it.split("").filter { it != "" }.map { it.toInt() }.toMutableList() } .toMutableList(), ) } private fun part1(input: Day11Input): Int { var totalFlashes = 0 repeat(100) { input.getAllPoints().forEach { input.grid[it.y][it.x] += 1 } val hasFlashed = mutableSetOf<Point>() val flashingNeighbors = input.getAllPoints() .filter { input.getPoint(it)!! == 10 } .toMutableList() while (flashingNeighbors.isNotEmpty()) { val next = flashingNeighbors.removeFirst() if (hasFlashed.contains(next)) { continue } hasFlashed.add(next) incrementNeighbors(input, next) flashingNeighbors.addAll(getFlashingNeighbors(input, next)) } totalFlashes += hasFlashed.size hasFlashed.forEach { input.grid[it.y][it.x] = 0 } } return totalFlashes } private fun part2(input: Day11Input): Int { for (day in 1..Int.MAX_VALUE) { for (y in input.grid.indices) { for (x in input.grid[y].indices) { input.grid[y][x] += 1 } } val hasFlashed = mutableSetOf<Point>() val flashingNeighbors = input.grid.indices.flatMap { y -> input.grid[y].indices.map { Point(y, it) } } .filter { input.getPoint(it)!! == 10 } .toMutableList() while (flashingNeighbors.isNotEmpty()) { val next = flashingNeighbors.removeFirst() if (hasFlashed.contains(next)) { continue } hasFlashed.add(next) incrementNeighbors(input, next) flashingNeighbors.addAll(getFlashingNeighbors(input, next)) } hasFlashed.forEach { input.grid[it.y][it.x] = 0 } if (hasFlashed.size == input.grid.size * input.grid[0].size) { return day } } return -1 } private fun getNeighbors( input: Day11Input, point: Point, ): List<Point> = (-1..+1).flatMap { x -> (-1..+1).map { y -> Point(x, y) } } .filter { it != Point(0, 0) } .map { it.add(point) } .filter { input.getOrNull(it.y)?.getOrNull(it.x) != null } private fun getFlashingNeighbors( input: Day11Input, point: Point, ) = getNeighbors(input, point) .filter { input.getPoint(it) == 10 } private fun incrementNeighbors( input: Day11Input, point: Point, ) { getNeighbors(input, point) .forEach { input.grid[it.y][it.x] += 1 } } data class Day11Input(val grid: MutableList<MutableList<Int>>) { fun print() = grid.forEach { println(it.joinToString("")) } fun getPoint(point: Point): Int? = grid.getOrNull(point.y)?.getOrNull(point.x) fun getAllPoints() = grid.indices.flatMap { y -> grid[y].indices.map { x -> Point(y, x) } } fun clone(): Day11Input = Day11Input(grid.map { it.toMutableList() }.toMutableList()) fun getOrNull(y: Int) = grid.getOrNull(y) }
0
Kotlin
0
0
4c4cbf677d97cfe96264b922af6ae332b9044ba8
3,573
advent_of_code
MIT License
kotlin/src/katas/kotlin/leetcode/contiguous_sum/ContiguousSum.kt
dkandalov
2,517,870
false
{"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221}
package katas.kotlin.leetcode.contiguous_sum import datsok.shouldEqual import org.junit.Test /** * Given an array of integers and a target, check if there is a contiguous sequence that sums to that target. */ class ContiguousSumTests { @Test fun examples() { findRange(arrayOf(2, 5, 7), target = 2) shouldEqual IntRange(0, 0) findRange(arrayOf(2, 5, 7), target = 5) shouldEqual IntRange(1, 1) findRange(arrayOf(2, 5, 7), target = 7) shouldEqual IntRange(0, 1) findRange(arrayOf(2, 5, 7), target = 12) shouldEqual IntRange(1, 2) findRange(arrayOf(2, 5, 7), target = 14) shouldEqual IntRange(0, 2) findRange(arrayOf(2, 5, 7), target = 100) shouldEqual null findRange(arrayOf(-2, 5, -2, -3, -8, 1), target = -12) shouldEqual IntRange(2, 5) } } private fun findRange(array: Array<Int>, target: Int): IntRange? { var sum = 0 val sums = array.map { n -> sum += n sum } (0 until array.size).forEach { from -> (from until array.size).forEach { to -> val rangeSum = sums[to] - (if (from > 0) sums[from - 1] else 0) if (rangeSum == target) return from..to } } return null } private fun findRange_(array: Array<Int>, target: Int): IntRange? { (0 until array.size).forEach { from -> (from until array.size).forEach { to -> val range = from..to if (range.sumBy { array[it] } == target) return range } } return null }
7
Roff
3
5
0f169804fae2984b1a78fc25da2d7157a8c7a7be
1,507
katas
The Unlicense
src/day08/Day08.kt
pnavais
574,712,395
false
{"Kotlin": 54079}
package day08 import readInput import kotlin.math.max typealias Grid = MutableList<List<TreeInfo>> class TreeInfo(val height: Short, var visible: Boolean, var scenicScore: Long) fun buildGrid(input: List<String>): Grid { val grid = mutableListOf<List<TreeInfo>>() for (line in input) { grid.add(line.toCharArray().map { c -> val height = Character.getNumericValue(c).toShort() val visible = true TreeInfo(height, visible, -1L) }.toList()) } return grid } fun computeVisibility(grid: Grid): Pair<Long, Long> { var innerVisible = 0L var maxScenicScore = -1L for (x in 1 until grid.size - 1) { for (y in 1 until grid[x].size - 1) { val visibleLeft = checkHigherLeft(x, y, grid) val visibleRight = checkHigherRight(x, y, grid) val visibleUp = checkHigherUp(x, y, grid) val visibleDown = checkHigherDown(x, y, grid) grid[x][y].visible = visibleLeft || visibleUp || visibleDown || visibleRight if (grid[x][y].visible) { innerVisible++ } maxScenicScore = max(maxScenicScore, grid[x][y].scenicScore) } } return innerVisible to maxScenicScore } private fun checkHigherLeft(x: Int, y: Int, grid: Grid): Boolean { return checkHigherMove(x, y, grid, { _, b -> 0 to b - 1 }, { _, rY, _ -> rY >= 0 }, {a, _, _, rB, g, h -> g[a][rB].height >= h}, { _, rY -> 0 to rY - 1 }) } private fun checkHigherRight(x: Int, y: Int, grid: Grid): Boolean { return checkHigherMove(x, y, grid, { _, b -> 0 to b + 1 }, { _, rY, g -> rY < g[x].size }, {a, _, _, rB, g, h -> g[a][rB].height >= h}, { _, rY -> 0 to rY + 1 }) } private fun checkHigherUp(x: Int, y: Int, grid: Grid): Boolean { return checkHigherMove(x, y, grid, { a, _ -> a - 1 to 0 }, { rX, _, _ -> rX >= 0 }, { _, b, rA, _, g, h -> g[rA][b].height >= h }, { rX, _ -> rX - 1 to 0 }) } private fun checkHigherDown(x: Int, y: Int, grid: Grid): Boolean { return checkHigherMove(x, y, grid, { a, _ -> a + 1 to 0 }, { rX, _, g -> rX < g.size }, { _, b, rA, _, g, h -> g[rA][b].height >= h }, { rX, _ -> rX + 1 to 0}) } private fun checkHigherMove(x: Int, y: Int, grid: Grid, initializer: (x: Int, y: Int) -> Pair<Int, Int>, checker: (rX: Int, rY: Int, grid: Grid) -> Boolean, visibleChecker: (x: Int, y: Int, rX: Int, rY: Int, grid: Grid, height: Short) -> Boolean, incrementer: (rX: Int, rY: Int) -> Pair<Int, Int>): Boolean { var visible = true val height = grid[x][y].height var (rX, rY) = initializer(x, y) var numTrees = 0L while (checker(rX, rY, grid)) { numTrees++ if (visibleChecker(x, y, rX, rY, grid, height)) { visible = false break } incrementer(rX, rY).let { rX = it.first rY = it.second } } val currentScore = grid[x][y].scenicScore grid[x][y].scenicScore = if (currentScore <=0 ) { numTrees } else { currentScore * numTrees } return visible } fun part1(input: List<String>): Long { val grid = buildGrid(input) var totalVisible = ((grid.size - 2) * 2).toLong() + (grid[0].size * 2).toLong() totalVisible += computeVisibility(grid).first return totalVisible } fun part2(input: List<String>): Long { val grid = buildGrid(input) return computeVisibility(grid).second } fun main() { // test if implementation meets criteria from the description, like: val testInput = readInput("Day08/Day08_test") println(part1(testInput)) println(part2(testInput)) }
0
Kotlin
0
0
ed5f521ef2124f84327d3f6c64fdfa0d35872095
3,818
advent-of-code-2k2
Apache License 2.0
src/Day02.kt
laricchia
434,141,174
false
{"Kotlin": 38143}
private const val CMD_FWD = "forward" private const val CMD_UP = "up" private const val CMD_DWN = "down" fun firstPart02(commands : List<Pair<String, Int>>) { val fwds = commands.filter { it.first == CMD_FWD } val ups = commands.filter { it.first == CMD_UP } val downs = commands.filter { it.first == CMD_DWN } val finalFwd = fwds.sumOf { it.second } val finalUp = ups.sumOf { it.second } val finalDown = downs.sumOf { it.second } val finalDepth = finalDown - finalUp println("${(finalFwd * finalDepth)}") } fun secondPart02(commands: List<Pair<String, Int>>) { var aim = 0 var depth = 0 var position = 0 commands.map { when (it.first) { CMD_FWD -> { position += it.second depth += (it.second * aim) } CMD_UP -> { aim -= it.second } CMD_DWN -> { aim += it.second } } } println("${depth * position}") } fun main() { val input : List<String> = readInput("Day02") val commands = input.filter { it.isNotEmpty() }.map { it.split(" ") }.map { it[0] to it[1].toInt() } firstPart02(commands) secondPart02(commands) }
0
Kotlin
0
0
7041d15fafa7256628df5c52fea2a137bdc60727
1,245
Advent_of_Code_2021_Kotlin
Apache License 2.0
14/kotlin/src/main/kotlin/se/nyquist/Transformer.kt
erinyq712
437,223,266
false
{"Kotlin": 91638, "C#": 10293, "Emacs Lisp": 4331, "Java": 3068, "JavaScript": 2766, "Perl": 1098}
package se.nyquist class Transformer(private val rules: Rules) { fun transform(i: Int, input: String): String { return when (i) { 0 -> { input } 1 -> { next(input) } else -> { transform(i-1, next(input)) } } } fun next(template: String) : String { val pairs = getPairs(template).toList() return pairs.joinToString("") { it[0] + rules.getValue(it) } + pairs[pairs.lastIndex][1] } fun getDistribution(depth : Int, input: String): Map<Char, Long> { val pairs = getPairs(input).groupingBy { it }.fold(0L){ it, _ -> it + 1L} val lastChar = input.last() return if (depth == 0) { pairs .map { it.key.first() to it.value } .groupBy({ it.first }, { it.second }) .mapValues { it.value.sum() + if (it.key == lastChar) 1 else 0 } } else { val newPairs = getNewPairs(pairs) getDistribution(depth-1, lastChar, newPairs) } } private fun getDistribution(depth : Int, lastChar: Char, pairs: Map<String, Long>): Map<Char, Long> { return if (depth == 0) { pairs.entries.groupBy ({ it.key.first() }, {it.value }) .mapValues { it.value.sum() + if (it.key == lastChar) 1 else 0 } } else { val newPairs = getNewPairs(pairs) getDistribution(depth-1, lastChar, newPairs) } } private fun getNewPairs(pairs: Map<String, Long>) = pairs.entries.flatMap { (it, value) -> listOf( Pair(it.first() + rules.getValue(it), value), Pair(rules.getValue(it) + it.last(), value) ) }.groupBy({ it.first }, { it.second }).mapValues { it.value.sum() } }
0
Kotlin
0
0
b463e53f5cd503fe291df692618ef5a30673ac6f
1,880
adventofcode2021
Apache License 2.0
src/Day02.kt
rtperson
434,792,067
false
{"Kotlin": 6811}
fun main() { fun mapToPairs(input: List<String>) : List<Pair<String, Int>> = input.map { val (d, x) = it.split(" ") Pair(d, x.toInt()) } fun computeDistance(orders: List<String>): List<Int> { var horizontalPosition = 0 var depth = 0 for (dir in orders) { val d = dir.split(" ") val n = d[1].toInt() when(d.first()) { "down" -> { depth += n } "up" -> { depth -= n } "forward" -> { horizontalPosition += n } } } return listOf(horizontalPosition, depth) } fun computeAim(orders: List<String>): List<Int> { var horizontalPosition = 0 var depth = 0 var aim = 0 for (dir in orders) { val d = dir.split(" ") val n = d[1].toInt() when (d.first()) { "down" -> { aim += n } "up" -> { aim -= n } "forward" -> { horizontalPosition += n depth += ( aim * n ) } } } return listOf(horizontalPosition, depth) } fun part1(input: List<String>): Int { val res = computeDistance(input) return res[0] * res[1] } fun part2(input: List<String>): Int { val res = computeAim(input) return res[0] * res[1] } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") println(part1(testInput) ) check(part1(testInput) == 150) println(part2(testInput)) check(part2(testInput) == 900) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
ae827a46c8aba336a7d46762f4e1a94bc1b9d850
1,954
Advent_of_Code_Kotlin
Apache License 2.0
day-23/src/main/kotlin/Amphipod.kt
diogomr
433,940,168
false
{"Kotlin": 92651}
import kotlin.math.abs import kotlin.system.measureTimeMillis fun main() { val partOneMillis = measureTimeMillis { println("Part One Solution: ${partOne()}") } println("Part One Solved in: $partOneMillis ms") val partTwoMillis = measureTimeMillis { println("Part Two Solution: ${partTwo()}") } println("Part Two Solved in: $partTwoMillis ms") } private fun partOne(): Int { val lines = readInputLines() .mapIndexed { lineIdx, line -> line.toCharArray() .mapIndexed { charIdx, char -> Cell(lineIdx, charIdx, char.toString()) } } var arrangements = setOf(Arrangement(lines, 2..3)) while (true) { arrangements = arrangements.flatMap { it.getNextPossible() }.toSet() if (arrangements.all { it.isFinished() }) { break } } val result = arrangements.minByOrNull { it.totalEnergy } println(result) return result!!.totalEnergy } private fun partTwo(): Int { val lines = readInputLines2() .mapIndexed { lineIdx, line -> line.toCharArray() .mapIndexed { charIdx, char -> Cell(lineIdx, charIdx, char.toString()) } } var arrangements = setOf(Arrangement(lines, 2..5)) while (true) { arrangements = arrangements.flatMap { it.getNextPossible() }.toSet() if (arrangements.all { it.isFinished() }) { break } } val result = arrangements.minByOrNull { it.totalEnergy } println(result) return result!!.totalEnergy } data class Cell( val x: Int, val y: Int, var value: String, ) data class Arrangement( val lines: List<List<Cell>>, val xRange: IntRange, val totalEnergy: Int = 0, ) { companion object { private val ENERGY_MAP = mapOf( "A" to 1, "B" to 10, "C" to 100, "D" to 1000, ) private val ROOMS = mapOf( "A" to 3, "B" to 5, "C" to 7, "D" to 9, ) } fun isFinished() = ROOMS.keys.all { isRoomDone(it) } fun getNextPossible(): Set<Arrangement> { if (isFinished()) { return setOf(this) } val possibilities = mutableSetOf<Arrangement>() getMovableAmphipods().forEach { c -> findPossiblePositions(c).forEach { (x, y) -> val copy = lines.map { it.map { c -> c.copy() }.toMutableList() } copy[x][y].value = c.value copy[c.x][c.y].value = "." val energy = (abs(x - c.x) + abs(y - c.y)) * ENERGY_MAP[c.value]!! possibilities.add(Arrangement(copy, xRange, totalEnergy + energy)) } } return possibilities } private fun getMovableAmphipods(): Set<Cell> { val hallwayAmphipods = getHallway().filter { it.value != "." } val roomAmphipods = mutableSetOf<Cell>() ROOMS.keys.forEach { if (!isRoomDone(it) && !isRoomReady(it)) { getFirstAmphipod(it)?.let { (x, y) -> roomAmphipods.add(lines[x][y]) } } } return roomAmphipods.apply { addAll(hallwayAmphipods) } } private fun findPossiblePositions(cell: Cell): Set<Pair<Int, Int>> { return if (cell.x in xRange) { getHallwayPositions(cell) } else { getRoomPositions(cell) } } private fun getRoomPositions(cell: Cell): Set<Pair<Int, Int>> { if (isRoomDone(cell.value)) return emptySet() if (!isRoomReady(cell.value)) return emptySet() val destination = getDeepestAvailablePosition(cell.value) val yRange = if (cell.y > destination.second) destination.second until cell.y else cell.y + 1..destination.second return if (isHallwayEmpty(yRange)) setOf(destination) else emptySet() } private fun getHallwayPositions(cell: Cell): Set<Pair<Int, Int>> = setOf( Pair(1, 1), Pair(1, 2), Pair(1, 4), Pair(1, 6), Pair(1, 8), Pair(1, 10), Pair(1, 11), ).filter { val (x, y) = it if (lines[x][y].value != ".") { false } else if (isHallwayEmpty()) { true } else { if (y < cell.y) { getHallway() .filter { pos -> pos.value != "." } .none { c -> c.y < cell.y && c.y > y } } else { getHallway() .filter { pos -> pos.value != "." } .none { c -> c.y > cell.y && c.y < y } } } }.toSet() private fun isRoomDone(room: String): Boolean { val roomNumber = ROOMS[room]!! return xRange.all { lines[it][roomNumber].value == room } } private fun isRoomReady(room: String): Boolean { val roomNumber = ROOMS[room]!! return xRange.all { lines[it][roomNumber].value == room || lines[it][roomNumber].value == "." } } private fun getDeepestAvailablePosition(room: String): Pair<Int, Int> { val roomNumber = ROOMS[room]!! val result = xRange.last { lines[it][roomNumber].value == "." } return Pair(result, roomNumber) } private fun getFirstAmphipod(room: String): Pair<Int, Int>? { val roomNumber = ROOMS[room]!! val result = xRange.firstOrNull { lines[it][roomNumber].value != "." } return result?.let { Pair(it, roomNumber) } } private fun isHallwayEmpty() = getHallway().all { it.value == "." } private fun isHallwayEmpty(range: IntRange) = getHallway().all { if (it.y !in range) true else it.value == "." } private fun getHallway() = lines[1].subList(1, 12) override fun toString(): String { return "totalEnergy: $totalEnergy\n" + lines.joinToString("\n") { line -> line.joinToString("") { it.value } } } } private fun readInputLines(): List<String> { return {}::class.java.classLoader.getResource("input.txt")!! .readText() .split("\n") .filter { it.isNotBlank() } } private fun readInputLines2(): List<String> { return {}::class.java.classLoader.getResource("input2.txt")!! .readText() .split("\n") .filter { it.isNotBlank() } }
0
Kotlin
0
0
17af21b269739e04480cc2595f706254bc455008
6,576
aoc-2021
MIT License
src/main/kotlin/dk/lessor/Day12.kt
aoc-team-1
317,571,356
false
{"Java": 70687, "Kotlin": 34171}
package dk.lessor import kotlin.math.absoluteValue fun main() { val directions = readFile("day_12.txt").map { parseDirectionInput(it) } val option1 = navigateStorm(directions, Ship::move) println(option1.distance) val option2 = navigateStorm(directions, Ship::moveWithWaypoint) println(option2.distance) } fun navigateStorm(directions: List<Direction>, move: (Ship, Direction) -> Unit): Ship { val ship = Ship() directions.forEach { move(ship, it) } return ship } fun parseDirectionInput(line: String): Direction { val amount = line.drop(1).toInt() return when (line.first()) { 'N' -> Direction.North(amount) 'E' -> Direction.East(amount) 'S' -> Direction.South(amount) 'W' -> Direction.West(amount) 'R' -> Direction.Right(amount) 'L' -> Direction.Left(amount) 'F' -> Direction.Forwards(amount) else -> Direction.North(0) } } class Ship { private var x = 0 private var y = 0 private var direction = 1 to 0 private var waypoint = 10 to 1 val distance get() = x.absoluteValue + y.absoluteValue fun move(d: Direction) { when (d) { is Direction.North -> y += d.amount is Direction.East -> x += d.amount is Direction.South -> y -= d.amount is Direction.West -> x -= d.amount is Direction.Forwards -> { x += (direction.first * d.amount) y += (direction.second * d.amount) } is Direction.Left -> direction = turnPoint(d.amount, direction) is Direction.Right -> direction = turnPoint(-d.amount, direction) } } fun moveWithWaypoint(d: Direction) { when (d) { is Direction.North -> waypoint = waypoint.copy(second = waypoint.second + d.amount) is Direction.East -> waypoint = waypoint.copy(first = waypoint.first + d.amount) is Direction.South -> waypoint = waypoint.copy(second = waypoint.second - d.amount) is Direction.West -> waypoint = waypoint.copy(first = waypoint.first - d.amount) is Direction.Forwards -> { x += (waypoint.first * d.amount) y += (waypoint.second * d.amount) } is Direction.Left -> waypoint = turnPoint(d.amount, waypoint) is Direction.Right -> waypoint = turnPoint(-d.amount, waypoint) } } private fun turnPoint(degrees: Int, point: Pair<Int, Int>): Pair<Int, Int> { return if (degrees == 90 || degrees == -270) point.copy(-point.second, point.first) else if (degrees == 180 || degrees == -180) point.copy(-point.first, -point.second) else point.copy(point.second, -point.first) } } sealed class Direction { data class North(val amount: Int) : Direction() data class East(val amount: Int) : Direction() data class South(val amount: Int) : Direction() data class West(val amount: Int) : Direction() data class Left(val amount: Int) : Direction() data class Right(val amount: Int) : Direction() data class Forwards(val amount: Int) : Direction() }
0
Java
0
0
48ea750b60a6a2a92f9048c04971b1dc340780d5
3,173
lessor-aoc-comp-2020
MIT License
src/Day04.kt
defvs
572,381,346
false
{"Kotlin": 16089}
fun main() { fun part1(input: List<String>) = input.count { assignment -> val (range1, range2) = assignment.split(",") val (lower1, upper1) = range1.split("-").map { it.toInt() } val (lower2, upper2) = range2.split("-").map { it.toInt() } lower1 <= lower2 && upper1 >= upper2 || lower2 <= lower1 && upper2 >= upper1 } fun part2(input: List<String>) = input.count { assignment -> val (range1, range2) = assignment.split(",") val (lower1, upper1) = range1.split("-").map { it.toInt() } val (lower2, upper2) = range2.split("-").map { it.toInt() } upper1 >= lower2 && lower1 <= upper2 } // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_test") check(part1(testInput).also { println("Test 1 result was: $it") } == 2) check(part2(testInput).also { println("Test 2 result was: $it") } == 4) val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
caa75c608d88baf9eb2861eccfd398287a520a8a
952
aoc-2022-in-kotlin
Apache License 2.0
src/Day12.kt
zfz7
573,100,794
false
{"Kotlin": 53499}
import java.util.* fun main() { println(day12A(readFile("Day12"))) println(day12B(readFile("Day12"))) } val heightMap = listOf( 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' ) fun day12A(input: String): Int { var start: Pair<Int, Int> = Pair(-1, -1) var end: Pair<Int, Int> = Pair(-1, -1) val heights: List<List<Int>> = input.trim().split("\n") .mapIndexed { i, line -> line.mapIndexed { j, it -> when (it) { 'S' -> { start = Pair(i, j);0 } 'E' -> { end = Pair(i, j);25 } else -> heightMap.indexOf(it) } } } val priorityQueue = PriorityQueue<Path> { a, b -> a.depth - b.depth } val visited = mutableSetOf<Pair<Int, Int>>() priorityQueue.add(Path(pos = start, depth = 0)) while (!priorityQueue.isEmpty()) { val current = priorityQueue.remove()!! if (current.pos == end) { return current.depth } //up val up = Pair(current.pos.first - 1, current.pos.second) if (heights[current.pos.first][current.pos.second] + 1 >= (heights.getOrNull(up.first) ?.getOrNull(up.second) ?: Int.MAX_VALUE) && !visited.contains(up) ) { visited.add(up) priorityQueue.add(Path(pos = up, depth = current.depth + 1)) } //down val down = Pair(current.pos.first + 1, current.pos.second) if (heights[current.pos.first][current.pos.second] + 1 >= (heights.getOrNull(down.first) ?.getOrNull(down.second) ?: Int.MAX_VALUE) && !visited.contains(down) ) { visited.add(down) priorityQueue.add(Path(pos = down, depth = current.depth + 1)) } //left val left = Pair(current.pos.first, current.pos.second - 1) if (heights[current.pos.first][current.pos.second] + 1 >= (heights.getOrNull(left.first) ?.getOrNull(left.second) ?: Int.MAX_VALUE) && !visited.contains(left) ) { visited.add(left) priorityQueue.add(Path(pos = left, depth = current.depth + 1)) } //right val right = Pair(current.pos.first, current.pos.second + 1) if (heights[current.pos.first][current.pos.second] + 1 >= (heights.getOrNull(right.first) ?.getOrNull(right.second) ?: Int.MAX_VALUE) && !visited.contains(right) ) { visited.add(right) priorityQueue.add(Path(pos = right, depth = current.depth + 1)) } } return -1 } fun day12B(input: String): Int { val start: MutableList<Pair<Int, Int>> = mutableListOf() var end: Pair<Int, Int> = Pair(-1, -1) val heights: List<List<Int>> = input.trim().split("\n") .mapIndexed { i, line -> line.mapIndexed { j, it -> when (it) { 'S','a' -> { start.add(Pair(i, j));0 } 'E' -> { end = Pair(i, j);25 } else -> heightMap.indexOf(it) } } } val priorityQueue = PriorityQueue<Path> { a, b -> a.depth - b.depth } val visited = start.toSet().toMutableSet() visited.forEach { priorityQueue.add(Path(pos = it, depth = 0)) } while (!priorityQueue.isEmpty()) { val current = priorityQueue.remove()!! if (current.pos == end) { return current.depth } //up val up = Pair(current.pos.first - 1, current.pos.second) if (heights[current.pos.first][current.pos.second] + 1 >= (heights.getOrNull(up.first) ?.getOrNull(up.second) ?: Int.MAX_VALUE) && !visited.contains(up) ) { visited.add(up) priorityQueue.add(Path(pos = up, depth = current.depth + 1)) } //down val down = Pair(current.pos.first + 1, current.pos.second) if (heights[current.pos.first][current.pos.second] + 1 >= (heights.getOrNull(down.first) ?.getOrNull(down.second) ?: Int.MAX_VALUE) && !visited.contains(down) ) { visited.add(down) priorityQueue.add(Path(pos = down, depth = current.depth + 1)) } //left val left = Pair(current.pos.first, current.pos.second - 1) if (heights[current.pos.first][current.pos.second] + 1 >= (heights.getOrNull(left.first) ?.getOrNull(left.second) ?: Int.MAX_VALUE) && !visited.contains(left) ) { visited.add(left) priorityQueue.add(Path(pos = left, depth = current.depth + 1)) } //right val right = Pair(current.pos.first, current.pos.second + 1) if (heights[current.pos.first][current.pos.second] + 1 >= (heights.getOrNull(right.first) ?.getOrNull(right.second) ?: Int.MAX_VALUE) && !visited.contains(right) ) { visited.add(right) priorityQueue.add(Path(pos = right, depth = current.depth + 1)) } } return -1 } data class Path( val pos: Pair<Int, Int>, val depth: Int )
0
Kotlin
0
0
c50a12b52127eba3f5706de775a350b1568127ae
5,466
AdventOfCode22
Apache License 2.0
Taxi Park/src/taxipark/TaxiParkTask.kt
Sharkaboi
258,941,707
false
null
package taxipark /* * Task #1. Find all the drivers who performed no trips. */ fun TaxiPark.findFakeDrivers(): Set<Driver> { return this.allDrivers.minus(this.trips.map { it.driver }).toSet() } /* * Task #2. Find all the clients who completed at least the given number of trips. */ fun TaxiPark.findFaithfulPassengers(minTrips: Int): Set<Passenger> = this.allPassengers.filter { p-> this.trips.filter { p in it.passengers }.count()>=minTrips }.toSet() /* * Task #3. Find all the passengers, who were taken by a given driver more than once. */ fun TaxiPark.findFrequentPassengers(driver: Driver): Set<Passenger> = this.allPassengers.filter {p-> this.trips.filter { it.driver==driver && it.passengers.contains(p) }.count()>1 }.toSet() /* * Task #4. Find the passengers who had a discount for majority of their trips. */ fun TaxiPark.findSmartPassengers(): Set<Passenger> = this.allPassengers.filter {p-> this.trips.filter { it.passengers.contains(p) && it.discount!=null }.count()>this.trips.filter { it.passengers.contains(p) && it.discount==null }.count() }.toSet() /* * Task #5. Find the most frequent trip duration among minute periods 0..9, 10..19, 20..29, and so on. * Return any period if many are the most frequent, return `null` if there're no trips. */ fun TaxiPark.findTheMostFrequentTripDurationPeriod(): IntRange? { return if (this.trips.isEmpty()) null else { val longestTrip = this.trips.map { it.duration }.max() ?: 0 var maxFrequencyIntRange = Pair(IntRange(0, 9), 0) for (i in 0..longestTrip step 10) { val currIntRange = IntRange(i, i + 9) val currRangeFrequency = this.trips.filter { it.duration in currIntRange }.count() if (currRangeFrequency > maxFrequencyIntRange.second) maxFrequencyIntRange = Pair(currIntRange, currRangeFrequency) } maxFrequencyIntRange.first } } /* * Task #6. * Check whether 20% of the drivers contribute 80% of the income. */ fun TaxiPark.checkParetoPrinciple(): Boolean { if(this.trips.isEmpty()) return false else{ val totalIncomeOfAllDrivers=this.trips.map { it.cost }.sum() val eightPercentOfTotal=totalIncomeOfAllDrivers*0.8 val sortedListOfDriversAndIncome= this.trips.groupBy { it.driver } .mapValues {(_,trip)-> trip.sumByDouble { it.cost } } .toList() .sortedByDescending {(_,price)->price }.toMap() var noOfDriversForEightPercent=0 var currentTotalIncome=0.0 for (i in sortedListOfDriversAndIncome.values){ noOfDriversForEightPercent++ currentTotalIncome+=i if(currentTotalIncome>=eightPercentOfTotal) break } return noOfDriversForEightPercent<=allDrivers.size*0.2 } }
0
Kotlin
0
0
977968b41ecc0ed1b62b50784bfebc3fa9d95a11
3,000
Kotlin-for-java-devs-course
MIT License
src/day02/Day02.kt
Mini-Stren
573,128,699
false
null
package day02 import readInputLines fun main() { val day = 2 fun part1(input: List<String>): Int { return Day02_part1.gameRounds(input).sumOf(Day02.GameRound::score) } fun part2(input: List<String>): Int { return Day02_part2.gameRounds(input).sumOf(Day02.GameRound::score) } val testInput = readInputLines("/day%02d/input_test".format(day)) val input = readInputLines("/day%02d/input".format(day)) check(part1(testInput) == 15) println("part1 answer is ${part1(input)}") check(part2(testInput) == 12) println("part2 answer is ${part2(input)}") } object Day02 { data class GameRound( val opponentShape: HandShape, val playerShape: HandShape, val gameResult: GameResult, ) { companion object } enum class HandShape { Rock, Paper, Scissors; val score: Int get() = when (this) { Rock -> 1 Paper -> 2 Scissors -> 3 } companion object { fun fromOpponent(value: Char): HandShape = when (value) { 'A' -> Rock 'B' -> Paper 'C' -> Scissors else -> throw IllegalArgumentException("Unknown opponent value '$value'") } } } enum class GameResult { Draw, PlayerWins, PlayerLose; val score: Int get() = when (this) { Draw -> 3 PlayerWins -> 6 PlayerLose -> 0 } companion object } } private val Day02.GameRound.score: Int get() = playerShape.score + gameResult.score
0
Kotlin
0
0
40cb18c29089783c9b475ba23c0e4861d040e25a
1,680
aoc-2022-kotlin
Apache License 2.0
2021/src/main/kotlin/aoc/day2.kt
daf276
433,385,608
false
null
package aoc.day2 sealed class Instruction { data class FORWARD(val value: Int) : Instruction() data class DOWN(val value: Int) : Instruction() data class UP(val value: Int) : Instruction() } fun parseInstructions(input: List<String>): List<Instruction> = input.map { it.split(" ") }.map { (instruction, value) -> when (instruction) { "forward" -> Instruction.FORWARD(value.toInt()) "down" -> Instruction.DOWN(value.toInt()) "up" -> Instruction.UP(value.toInt()) else -> throw Exception("This when is exhaustive") } } fun part1(input: List<Instruction>): Int { val (pos, depth) = input.fold(Pair(0, 0)) { sum, add -> when (add) { is Instruction.FORWARD -> sum.copy(first = sum.first + add.value) is Instruction.DOWN -> sum.copy(second = sum.second + add.value) is Instruction.UP -> sum.copy(second = sum.second - add.value) } } return pos * depth } fun part2(input: List<Instruction>): Int { val (pos, depth, aim) = input.fold(Triple(0, 0, 0)) { sum, add -> when (add) { is Instruction.FORWARD -> sum.copy( first = sum.first + add.value, second = sum.second + sum.third * add.value ) is Instruction.DOWN -> sum.copy(third = sum.third + add.value) is Instruction.UP -> sum.copy(third = sum.third - add.value) } } return pos * depth }
0
Rust
0
0
d397cfe0daab24604615d551cbdb7c6ae145ae74
1,495
AdventOfCode
MIT License
src/Day04.kt
AlexeyVD
575,495,640
false
{"Kotlin": 11056}
fun main() { fun part1(input: List<String>): Int { return input.map { toSections(it) }.count { it.fullyCovered() } } fun part2(input: List<String>): Int { return input.map { toSections(it) }.count { it.intersected() } } val testInput = readInput("Day04_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInput("Day04") println(part1(input)) println(part2(input)) } fun toSections(input: String): Pair<Section, Section> { val (first, second) = input.split(',').map { Section.of(it) } return Pair(first, second) } fun Pair<Section, Section>.fullyCovered(): Boolean { return first.contains(second) || second.contains(first) } fun Pair<Section, Section>.intersected(): Boolean { return first.intersect(second) } class Section( private val start: Int, private val end: Int ) { fun intersect(other: Section): Boolean { return start <= other.end && end >= other.start } fun contains(other: Section): Boolean { return start <= other.start && end >= other.end } companion object { fun of(input: String): Section { val (first, second) = input.split('-') return Section(first.toInt(), second.toInt()) } } }
0
Kotlin
0
0
ec217d9771baaef76fa75c4ce7cbb67c728014c0
1,294
advent-kotlin
Apache License 2.0
src/main/kotlin/io/github/clechasseur/adventofcode2021/Day15.kt
clechasseur
435,726,930
false
{"Kotlin": 315943}
package io.github.clechasseur.adventofcode2021 import io.github.clechasseur.adventofcode2021.data.Day15Data import io.github.clechasseur.adventofcode2021.dij.Dijkstra import io.github.clechasseur.adventofcode2021.dij.Graph import io.github.clechasseur.adventofcode2021.util.Direction import io.github.clechasseur.adventofcode2021.util.Pt object Day15 { private val data = Day15Data.data private val riskLevels = data.lines().map { line -> line.map { it.toString().toInt() } } fun part1(): Int { val out = Dijkstra.build(RiskGraph(riskLevels), Pt.ZERO) return out.dist[Pt(riskLevels[0].indices.last, riskLevels.indices.last)]!!.toInt() } fun part2(): Int { val tiles = (0..4).map { yDisp -> (0..4).map { xDisp -> displacedRiskLevels(xDisp + yDisp) } } val graph = (0 until (riskLevels.indices.last + 1) * 5).map { y -> (0 until (riskLevels[0].indices.last + 1) * 5).map { x -> val tile = tiles[y / (riskLevels.indices.last + 1)][x / (riskLevels[0].indices.last + 1)] tile[y % (riskLevels.indices.last + 1)][x % (riskLevels[0].indices.last + 1)] } } val out = Dijkstra.build(RiskGraph(graph), Pt.ZERO) return out.dist[Pt(graph[0].indices.last, graph.indices.last)]!!.toInt() } private class RiskGraph(val graph: List<List<Int>>) : Graph<Pt> { override fun allPassable(): List<Pt> = graph.indices.flatMap { y -> graph[y].indices.map { x -> Pt(x, y) } } override fun neighbours(node: Pt): List<Pt> = Direction.displacements.mapNotNull { move -> val pt = node + move if (pt.y in graph.indices && pt.x in graph[pt.y].indices) pt else null } override fun dist(a: Pt, b: Pt): Long = graph[b.y][b.x].toLong() } private fun displacedRiskLevels(disp: Int): List<List<Int>> = riskLevels.map { yList -> yList.map { it.displacedRisk(disp) } } private fun Int.displacedRisk(disp: Int) = if (this + disp <= 9) this + disp else this + disp - 9 }
0
Kotlin
0
0
4b893c001efec7d11a326888a9a98ec03241d331
2,139
adventofcode2021
MIT License
2015/kt/src/test/kotlin/org/adventofcode/Day21.kt
windmaomao
225,344,109
false
{"JavaScript": 538717, "Ruby": 89779, "Kotlin": 58408, "Rust": 21350, "Go": 19106, "TypeScript": 9930, "Haskell": 8908, "Dhall": 3201, "PureScript": 1488, "HTML": 1307, "CSS": 1092}
package org.adventofcode data class Item( val name: String, val cost: Int, val damage: Int, val armor: Int ) {} data class Profile(val items: List<Item>) { fun name() = items.map { it.name }.joinToString("/") fun cost() = items.sumBy { it.cost } fun damage() = items.sumBy { it.damage } fun armor() = items.sumBy { it.armor } fun toItem() = Item(name(), cost(), damage(), armor()) } class Day21 { val weapons = listOf( Item("D", 8, 4, 0), Item("S", 10, 5, 0), Item("W", 25, 6, 0), Item("L", 40, 7, 0), Item("G", 74, 8, 0) ) val armors = listOf( Item("N", 0, 0, 0), Item("L", 13, 0, 1), Item("C", 31, 0, 2), Item("S", 53, 0, 3), Item("B", 75, 0, 4), Item("P", 102, 0, 5) ) val rings = listOf( Item("NNNN", 0, 0, 0), Item("W1NN", 25, 1, 0), Item("W2NN", 50, 2, 0), Item("W3NN", 100, 3, 0), Item("A1NN", 20, 0, 1), Item("A2NN", 40, 0, 2), Item("A3NN", 80, 0, 3), Item("W1W2", 75, 3, 0), Item("W1W3", 125, 4, 0), Item("W1A1", 45, 1, 1), Item("W1A2", 65, 1, 2), Item("W1A3", 105, 1, 3), Item("W2W3", 125, 4, 0), Item("W2A1", 70, 2, 1), Item("W2A2", 90, 2, 2), Item("W2A3", 130, 2, 3), Item("W3A1", 120, 3, 1), Item("W3A2", 140, 3, 2), Item("W3A3", 180, 3, 3), Item("A1A2", 60, 0, 3), Item("A1A3", 100, 0, 4), Item("A2A3", 120, 0, 5) ) fun getProfiles(): List<Profile> { val profiles = mutableListOf<Profile>() weapons.forEach { w -> armors.forEach { a -> rings.forEach { r -> profiles.add(Profile(listOf(w, a, r))) } } } return profiles } fun fight( me: Item, meMaxHp: Int, boss: Item, bossMaxHp: Int ): Boolean { var meHp = meMaxHp var bossHp = bossMaxHp while (true) { val bossLoss = me.damage - boss.armor bossHp -= if (bossLoss > 1) bossLoss else 1 if (bossHp <= 0) return true val meLoss = boss.damage - me.armor meHp -= if (meLoss > 1) meLoss else 1 if (meHp <= 0) return false } } fun part1(): Int { val profiles = getProfiles() val boss = Item("Boss", 0, 8, 1) val bossMaxHp = 104 val meMaxHp = 100 val s = profiles .map { it.toItem() } .filter { fight(it, meMaxHp, boss, bossMaxHp) } .minBy { it.cost } return s?.cost ?: 0 } fun part2(): Int { val profiles = getProfiles() val boss = Item("Boss", 0, 8, 1) val bossMaxHp = 104 val meMaxHp = 100 val s = profiles .map { it.toItem() } .filter { !fight(it, meMaxHp, boss, bossMaxHp) } .maxBy { it.cost } return s?.cost ?: 0 } }
5
JavaScript
0
0
1d64d7fffa6fcfc6825e6aa9322eda76e790700f
2,667
adventofcode
MIT License
src/main/kotlin/Day8.kt
vw-anton
574,945,231
false
{"Kotlin": 33295}
fun main() { part1() part2() } private fun part1() { val trees = readFile("input/8.txt") .map { line -> line.toList().toTypedArray() } .toTypedArray() val size = trees.size val visible = Array(size) { i -> Array(size) { j -> 0 } } for (row in 1 until size - 1) { for (col in 1 until size - 1) { val height = trees.get(col, row) var visibleLeft = true for (left in 0 until col) { if (trees.get(row, left) >= height) { visibleLeft = false break } } var visibleRight = true for (right in col + 1 until size) { if (trees.get(row, right) >= height) { visibleRight = false break } } var visibleBottom = true for (bottom in row + 1 until size) { if (trees.get(bottom, col) >= height) { visibleBottom = false break } } var visibleTop = true for (top in 0 until row) { if (trees.get(top, col) >= height) { visibleTop = false break } } visible[col][row] = if (visibleLeft || visibleTop || visibleRight || visibleBottom) 1 else 0 } } val outer = size * 4 - 4 println("sum: ${visible.sumOf { array -> array.sum() } + outer}") } private fun Array<Array<Char>>.get(x: Int, y: Int, default: Int = -1): Int { return if ((x in indices) && (y in indices)) get(x)[y].digitToInt() else default } fun part2() { val trees = readFile("input/8.txt") .map { it.toCharArray().map { char -> Tree(char.digitToInt()) } } val rowSize = trees.size val colSize = trees.size for (row in 1 until rowSize - 1) { for (col in 1 until colSize - 1) { val currentHeight = trees[row][col].height var leftScore = 0 for (left in col - 1 downTo 0) { if (trees[row][left].height <= currentHeight) leftScore++ if (trees[row][left].height >= currentHeight) break } var rightScore = 0 for (right in col + 1 until colSize) { if (trees[row][right].height <= currentHeight) rightScore++ if (trees[row][right].height >= currentHeight) break } var topScore = 0 for (top in row - 1 downTo 0) { if (trees[top][col].height <= currentHeight) topScore++ if (trees[top][col].height >= currentHeight) break } var bottomScore = 0 for (top in row + 1 until rowSize) { if (trees[top][col].height <= currentHeight) bottomScore++ if (trees[top][col].height >= currentHeight) break } val totalScore = leftScore * rightScore * topScore * bottomScore trees[row][col].score = totalScore } } val result = trees.maxOf { it.maxOf { tree -> tree.score } } println(result) } data class Tree(val height: Int, var score: Int = 0)
0
Kotlin
0
0
a823cb9e1677b6285bc47fcf44f523e1483a0143
3,281
aoc2022
The Unlicense
src/Day03.kt
rafael-ribeiro1
572,657,838
false
{"Kotlin": 15675}
fun main() { fun part1(input: List<String>): Int { return input.map { it.toList().windowed(it.length / 2, it.length / 2) } .sumOf { it[0].intersect(it[1]).sumOf { letter -> letter.priority } } } fun part2(input: List<String>): Int { return input.map { it.toList() } .windowed(3, 3) .sumOf { it[0].intersect(it[1]).intersect(it[2]).sumOf { letter -> letter.priority } } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("Day03") println(part1(input)) println(part2(input)) } val Char.priority: Int get() = LETTERS.indexOf(this) + 1 val LETTERS = (('a'..'z')+('A'..'Z'))
0
Kotlin
0
0
5cae94a637567e8a1e911316e2adcc1b2a1ee4af
818
aoc-kotlin-2022
Apache License 2.0
src/main/kotlin/aoc2015/ItHangsInTheBalance.kt
komu
113,825,414
false
{"Kotlin": 395919}
package komu.adventofcode.aoc2015 import komu.adventofcode.utils.nonEmptyLines import komu.adventofcode.utils.product fun itHangsInTheBalance1(input: String): Long { val weights = input.nonEmptyLines().map { it.toLong() }.reversed() val expectedWeight = weights.sum() / 3 var bestSize = Integer.MAX_VALUE var bestEntanglement = Long.MAX_VALUE for (a in candidates(weights, IndexSet.empty, expectedWeight, allowedSize = 1..weights.size / 3, maxCount = 1)) { val maxSize = weights.size - 2 * a.size if (hasMatch(weights, a, expectedWeight, allowedSize = a.size..maxSize)) { if (a.size <= bestSize && weights.withIndices(a).product() < bestEntanglement) { bestSize = a.size bestEntanglement = weights.withIndices(a).product() } } } return bestEntanglement } fun itHangsInTheBalance2(input: String): Long { val weights = input.nonEmptyLines().map { it.toLong() }.reversed() val expectedWeight = weights.sum() / 4 var bestSize = Integer.MAX_VALUE var bestEntanglement = Long.MAX_VALUE for (a in candidates(weights, IndexSet.empty, expectedWeight, allowedSize = 0..weights.size / 4, maxCount = 100)) { val allowedSize = a.size..weights.size - 3 * a.size for (b in candidates(weights, a, expectedWeight, allowedSize, maxCount = 1)) { if (hasMatch(weights, b, expectedWeight, allowedSize)) { if (a.size <= bestSize && weights.withIndices(a).product() < bestEntanglement) { bestSize = a.size bestEntanglement = weights.withIndices(a).product() } } } } return bestEntanglement } private fun candidates( weights: List<Long>, taken: IndexSet, expectedWeight: Long, allowedSize: IntRange, maxCount: Int ): Set<IndexSet> { val result = mutableSetOf<IndexSet>() var count = 0 fun add(taken: IndexSet) { count++ result += taken } fun recurse(taken: IndexSet, remainingSum: Long, items: Int) { if (remainingSum == 0L && items >= allowedSize.first) add(taken) val remainingItems = allowedSize.last - items if (remainingItems > 1 && count < maxCount) { for ((i, w) in weights.withIndex()) { if (w <= remainingSum && i !in taken) recurse(taken + i, remainingSum - w, items + 1) } } } recurse(taken, expectedWeight, 0) return result } private fun hasMatch(weights: List<Long>, taken: IndexSet, expectedWeight: Long, allowedSize: IntRange): Boolean { fun recurse(taken: IndexSet, remainingSum: Long, items: Int): Boolean { if (remainingSum == 0L) return items in allowedSize if (items > allowedSize.last) return false for ((i, w) in weights.withIndex()) { if (w <= remainingSum && i !in taken) if (recurse(taken + i, remainingSum - w, items + 1)) return true } return false } return recurse(taken, expectedWeight, 0) } @JvmInline private value class IndexSet(private val bits: Int) { operator fun contains(index: Int) = (bits and (1 shl index)) != 0 operator fun plus(index: Int) = IndexSet(bits or (1 shl index)) operator fun minus(index: Int) = IndexSet(bits and (1 shl index).inv()) operator fun minus(rhs: IndexSet) = IndexSet(bits and rhs.bits.inv()) override fun toString(): String = (0..31).filter { it in this }.toString() val size: Int get() = Integer.bitCount(bits) companion object { val empty = IndexSet(0) } } private fun <T> List<T>.withIndices(indexSet: IndexSet): List<T> = withIndex().filter { it.index in indexSet }.map { it.value }
0
Kotlin
0
0
8e135f80d65d15dbbee5d2749cccbe098a1bc5d8
3,864
advent-of-code
MIT License
2023/src/main/kotlin/day18_fast.kt
madisp
434,510,913
false
{"Kotlin": 388138}
import utils.Parser import utils.Solution import utils.Vec2l import utils.mapItems import kotlin.math.absoluteValue fun main() { Day18Fast.run() } object Day18Fast : Solution<List<Day18.Line>>() { override val name = "day18" override val parser = Parser.lines.mapItems { Day18.parseLine(it) } private fun solve(insns: List<Day18.Instruction>): Long { val (area, pts, _) = insns.fold(Triple(0L, 0L, 0L)) { (area, pts, y), i -> Triple(area + i.direction.x * i.len * y, pts + i.len, y + i.direction.y * i.len) } return area.absoluteValue + (pts / 2) + 1 } override fun part1(): Long { val insns = input.map { line -> val direction = when (line.direction) { "R" -> Vec2l.RIGHT "D" -> Vec2l.DOWN "U" -> Vec2l.UP "L" -> Vec2l.LEFT else -> throw IllegalStateException("Unknown direction char ${line.direction}") } Day18.Instruction(direction, line.len) } return solve(insns) } override fun part2(): Long { val directions = listOf(Vec2l.RIGHT, Vec2l.DOWN, Vec2l.LEFT, Vec2l.UP) val corrected = input.map { line -> val direction = directions[line.color.last() - '0'] val len = line.color.substring(0, line.color.length - 1).toLong(16) Day18.Instruction(direction, len) } return solve(corrected) } }
0
Kotlin
0
1
3f106415eeded3abd0fb60bed64fb77b4ab87d76
1,335
aoc_kotlin
MIT License
src/Day04.kt
WilsonSunBritten
572,338,927
false
{"Kotlin": 40606}
fun main() { fun part1(input: List<String>): Int { return input.map { row -> val split = row.split(",").map { val split = it.split("-") split[0].toInt() to split[1].toInt() } val firstPair = split[0] val secondPair = split[1] if (firstPair.first <= secondPair.first && firstPair.second >= secondPair.second) { 1 } else if (secondPair.first <= firstPair.first && secondPair.second >= firstPair.second) { 1 } else { 0 } }.sum() } fun part2(input: List<String>): Int { return input.map { row -> val split = row.split(",").map { val split = it.split("-") split[0].toInt() to split[1].toInt() } val firstPair = split[0] val secondPair = split[1] if (firstPair.first <= secondPair.first && firstPair.second >= secondPair.first) { 1 } else if (secondPair.first <= firstPair.first && secondPair.second >= firstPair.first) { 1 } else { 0 } }.sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_test") val input = readInput("Day04") val p1TestResult = part1(testInput) println(p1TestResult) check(part1(testInput) == 2) println(part1(input)) val p2TestResult = part2(testInput) println(p2TestResult) check(part2(testInput) == 4) println(part2(input)) }
0
Kotlin
0
0
363252ffd64c6dbdbef7fd847518b642ec47afb8
1,648
advent-of-code-2022-kotlin
Apache License 2.0
src/main/kotlin/day12/Day12.kt
TheSench
572,930,570
false
{"Kotlin": 128505}
package day12 import Lines import runDay import utils.Point fun main() { fun part1(input: List<String>) = input.toGrid().shortestPath() fun part2(input: List<String>) = input.toGrid().let { grid -> grid.shortestPath( startingPoint = grid.end, isDestination = { grid[this] == 0 }, canHandle = { it >= -1 } ) } (object {}).runDay( part1 = ::part1, part1Check = 31, part2 = ::part2, part2Check = 29, ) } typealias Elevations = List<List<Int>> operator fun Elevations.get(point: Point) = this[point.y][point.x] data class Grid( val start: Point, val end: Point, val elevations: Elevations, ) { operator fun get(point: Point) = elevations[point] operator fun contains(point: Point) = point.x in (elevations[0].indices) && point.y in elevations.indices } fun Lines.toGrid(): Grid = this.let { lateinit var start: Point lateinit var end: Point val elevations = mapIndexed { top, row -> row.mapIndexed { left, char -> when (char) { in 'a'..'z' -> char.code - 'a'.code 'S' -> 0.also { start = Point(left, top) } 'E' -> 25.also { end = Point(left, top) } else -> throw IllegalArgumentException("Invalid character: $char") } } } Grid( start, end, elevations, ) } fun Grid.shortestPath( startingPoint: Point = this.start, isDestination: Point.() -> Boolean = { this == this@shortestPath.end }, canHandle: (elevationChange: Int) -> Boolean = { it <= 1 } ): Int { val grid = this val visited = mutableMapOf<Point, Int>().apply { this[startingPoint] = 0 } val paths = ArrayDeque<Point>().apply { add(startingPoint) } while (paths.size > 0) { val point = paths.removeFirst() val currentElevation = grid[point] val newDistance = visited[point]!! + 1 point.neighbors .filter { it in grid && (it !in visited || newDistance < visited[it]!!) && canHandle(grid[it] - currentElevation) } .forEach { nextPoint -> when { nextPoint.isDestination() -> return newDistance else -> { visited[nextPoint] = newDistance paths.addLast(nextPoint) } } } } throw IllegalArgumentException("Grid did not contain valid path") } val Point.neighbors get() = listOf( this + Point(0, -1), this + Point(0, 1), this + Point(-1, 0), this + Point(1, 0) )
0
Kotlin
0
0
c3e421d75bc2cd7a4f55979fdfd317f08f6be4eb
2,754
advent-of-code-2022
Apache License 2.0
kotlin/problems/src/solution/NumberProblems.kt
lunabox
86,097,633
false
{"Kotlin": 146671, "Python": 38767, "JavaScript": 19188, "Java": 13966}
package solution import java.math.BigInteger import java.util.* import kotlin.collections.ArrayList import kotlin.collections.HashMap import kotlin.collections.HashSet import kotlin.math.* class NumberProblems { /** * https://leetcode-cn.com/problems/k-diff-pairs-in-an-array/ * 给定一个整数数组和一个整数 k, 你需要在数组里找到不同的 k-diff 数对。这里将 k-diff 数对定义为一个整数对 (i, j), 其中 i 和 j 都是数组中的数字,且两数之差的绝对值是 k */ fun findPairs(nums: IntArray, k: Int): Int { if (k < 0) { return 0 } val view = HashSet<Int>() val diff = HashSet<Int>() nums.forEach { if (view.contains(it + k)) { diff.add(it + k) } if (view.contains(it - k)) { diff.add(it) } view.add(it) } return diff.size } /** * https://leetcode-cn.com/problems/diet-plan-performance/ */ fun dietPlanPerformance(calories: IntArray, k: Int, lower: Int, upper: Int): Int { var s = 0 var score = 0 repeat(k) { s += calories[it] } repeat(calories.size - k + 1) { when { s < lower -> score-- s > upper -> score++ } if (it + k < calories.size) { s = s - calories[it] + calories[it + k] } } return score } fun maxCount(m: Int, n: Int, ops: Array<IntArray>): Int { var mm = m var nn = n ops.forEach { mm = min(mm, it[0]) nn = min(nn, it[1]) } return mm * nn } /** * https://leetcode-cn.com/problems/can-place-flowers/ */ fun canPlaceFlowers(flowerbed: IntArray, n: Int): Boolean { var count = 0 repeat(flowerbed.size) { if (it == 0) { if ((flowerbed.size > 1 && flowerbed[0] == 0 && flowerbed[1] == 0) || (flowerbed.size == 1 && flowerbed[0] == 0)) { count++ flowerbed[it] = 1 } } else if (it == flowerbed.size - 1) { if (flowerbed[it] == 0 && flowerbed[it - 1] == 0) { count++ flowerbed[it] = 1 } } else if (flowerbed[it] == 0 && flowerbed[it - 1] == 0 && flowerbed[it + 1] == 0) { count++ flowerbed[it] = 1 } if (count >= n) { return true } } return count >= n } /** * https://leetcode-cn.com/problems/asteroid-collision/ * 对于数组中的每一个元素,其绝对值表示行星的大小,正负表示行星的移动方向(正表示向右移动,负表示向左移动)。每一颗行星以相同的速度移动。 * 找出碰撞后剩下的所有行星。碰撞规则:两个行星相互碰撞,较小的行星会爆炸。如果两颗行星大小相同,则两颗行星都会爆炸。两颗移动方向相同的行星,永远不会发生碰撞。 */ fun asteroidCollision(asteroids: IntArray): IntArray { val list = asteroids.toMutableList() var i = 0 while (i < list.size - 1) { if (list[i] > 0 && list[i + 1] < 0) { when { list[i] + list[i + 1] > 0 -> { list.removeAt(i + 1) } list[i] + list[i + 1] == 0 -> { list.removeAt(i) list.removeAt(i) i = if (i == 0) 0 else i - 1 } else -> { list.removeAt(i) i = if (i == 0) 0 else i - 1 } } } else { i++ } } return list.toIntArray() } /** * https://leetcode-cn.com/problems/find-minimum-in-rotated-sorted-array/ */ fun findMin(nums: IntArray): Int { return nums.min()!! } /** * https://leetcode-cn.com/problems/search-in-rotated-sorted-array/ */ fun search(nums: IntArray, target: Int): Boolean { return nums.indexOf(target) >= 0 } /** * https://leetcode-cn.com/problems/compare-version-numbers/ */ fun compareVersion(version1: String, version2: String): Int { val v1 = version1.split(".") val v2 = version2.split(".") repeat(max(v1.size, v2.size)) { val subVersion1 = if (it < v1.size) v1[it].toInt() else 0 val subVersion2 = if (it < v2.size) v2[it].toInt() else 0 when { subVersion1 > subVersion2 -> return 1 subVersion1 < subVersion2 -> return -1 else -> return@repeat } } return 0 } /** * https://leetcode-cn.com/problems/pairs-of-songs-with-total-durations-divisible-by-60/ */ fun numPairsDivisibleBy60(time: IntArray): Int { val count = IntArray(60) var sum = 0 time.map { val value = it % 60 count[value]++ value }.forEach { if (it != 0 && it != 30) { sum += count[60 - it] } } // 上面除了0和30之外,都计算了两次,成对出现,需要去掉一半 sum /= 2 // 0 sum += if (count[0] > 1) count[0] * (count[0] - 1) / 2 else 0 // 30 sum += if (count[30] > 1) count[30] * (count[30] - 1) / 2 else 0 return sum } /** * https://leetcode-cn.com/problems/product-of-array-except-self/ * 给定长度为 n 的整数数组 nums,其中 n > 1,返回输出数组 output ,其中 output[i] 等于 nums 中除 nums[i] 之外其余各元素的乘积 */ fun productExceptSelf(nums: IntArray): IntArray { val left = IntArray(nums.size) { 1 } val right = IntArray(nums.size) { 1 } val result = IntArray(nums.size) for (i in 1 until nums.size) { left[i] = left[i - 1] * nums[i - 1] } for (i in nums.size - 2 downTo 0) { right[i] = right[i + 1] * nums[i + 1] } for (i in nums.indices) { result[i] = left[i] * right[i] } return result } /** * https://leetcode-cn.com/problems/array-partition-i/ * 给定长度为 2n 的数组, 你的任务是将这些数分成 n 对, 例如 (a1, b1), (a2, b2), ..., (an, bn) ,使得从1 到 n 的 min(ai, bi) 总和最大 */ fun arrayPairSum(nums: IntArray): Int { var sum = 0 nums.sort() for (i in nums.indices step 2) { sum += nums[i] } return sum } /** * https://leetcode-cn.com/problems/maximum-product-of-three-numbers/ */ fun maximumProduct(nums: IntArray): Int { nums.sort() if (nums[0] < 0 && nums[1] < 0) { val a = nums[0] * nums[1] * nums.last() val b = nums[nums.size - 3] * nums[nums.size - 2] * nums[nums.size - 1] return if (a > b) a else b } return nums[nums.size - 3] * nums[nums.size - 2] * nums[nums.size - 1] } /** * https://leetcode-cn.com/problems/merge-intervals/ * 给出一个区间的集合,请合并所有重叠的区间 */ fun merge(intervals: Array<IntArray>): Array<IntArray> { val result = ArrayList<IntArray>() intervals.sortBy { it[0] } intervals.forEach { if (result.isNotEmpty() && result.last()[1] >= it[0]) { if (result.last()[1] <= it[1]) { result.last()[1] = it[1] } } else { result.add(it) } } val array = Array(result.size) { intArrayOf() } return result.toArray(array) } /** * https://leetcode-cn.com/problems/shortest-unsorted-continuous-subarray/ */ fun findUnsortedSubarray(nums: IntArray): Int { var left = 0 var right = nums.size - 1 var minValue = -1 var maxValue = -1 for (i in nums.indices) { if (i == 0) { maxValue = nums[i] } else { if (maxValue > nums[i]) { left = i } maxValue = max(maxValue, nums[i]) } } for (i in nums.size - 1 downTo 0) { if (i == nums.lastIndex) { minValue = nums.last() } else { if (minValue < nums[i]) { right = i } minValue = min(minValue, nums[i]) } } return if (left - right + 1 > 0) left - right + 1 else 0 } /** * https://leetcode-cn.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/ */ fun subtractProductAndSum(n: Int): Int { var num = n var multi = 1 var sum = 0 while (num != 0) { val last = num % 10 multi *= last sum += last num /= 10 } return multi - sum } /** * https://leetcode-cn.com/problems/sum-of-square-numbers/ */ fun judgeSquareSum(c: Int): Boolean { var i = 0 var j = sqrt(c.toDouble()).toInt() while (i <= j) { val r = i * i + j * j when { r == c -> return true r < c -> i++ r > c -> j-- } } return false } /** * https://leetcode-cn.com/problems/non-decreasing-array/ */ fun checkPossibility(nums: IntArray): Boolean { var change = 0 if (nums.size > 1 && nums[0] > nums[1]) { nums[0] = nums[1] change++ } for (i in 1 until nums.lastIndex) { if (nums[i] <= nums[i + 1]) { continue } change++ if (change >= 2) { return false } if (nums[i - 1] > nums[i + 1]) { nums[i + 1] = nums[i] } else { nums[i] = nums[i - 1] } } return true } /** * 你正在和你的朋友玩 猜数字(Bulls and Cows)游戏:你写下一个数字让你的朋友猜。每次他猜测后,你给他一个提示,告诉他有多少位数字和确切位置都猜对了(称为“Bulls”, 公牛),有多少位数字猜对了但是位置不对(称为“Cows”, 奶牛)。你的朋友将会根据提示继续猜,直到猜出秘密数字。 * 请写出一个根据秘密数字和朋友的猜测数返回提示的函数,用 A 表示公牛,用 B 表示奶牛。 * 请注意秘密数字和朋友的猜测数都可能含有重复数字。 */ fun getHint(secret: String, guess: String): String { if (secret.isBlank() || guess.isBlank()) { return "0A0B" } var a = 0 var b = 0 val nums = IntArray(10) val flags = IntArray(secret.length) secret.forEach { nums[it.toInt() - '0'.toInt()]++ } secret.forEachIndexed { index, c -> if (c == guess[index]) { a++ nums[c.toInt() - '0'.toInt()]-- flags[index]++ } } guess.forEachIndexed { index, c -> if (flags[index] == 0 && nums[c.toInt() - '0'.toInt()] > 0) { b++ nums[c.toInt() - '0'.toInt()]-- } } return "${a}A${b}B" } /** * https://leetcode-cn.com/problems/maximum-average-subarray-i/ */ fun findMaxAverage(nums: IntArray, k: Int): Double { var s = nums.filterIndexed { index, _ -> index < k }.sum() var m = s for (i in k until nums.size) { s += nums[i] s -= nums[i - k] m = if (s > m) s else m } return m.toDouble() / k.toDouble() } fun findLengthOfLCIS(nums: IntArray): Int { var cur = Int.MIN_VALUE var curLength = 0 var maxLength = 0 nums.forEach { if (it > cur) { curLength++ } else { curLength = 1 } cur = it if (curLength > maxLength) { maxLength = curLength } } return maxLength } /** * https://leetcode-cn.com/problems/binary-number-with-alternating-bits/ */ fun hasAlternatingBits(n: Int): Boolean { val m = n.xor(n.shr(1)) return m.and(m + 1) == 0 } /** * https://leetcode-cn.com/problems/duplicate-zeros/ */ fun duplicateZeros(arr: IntArray): Unit { var i = 0 while (i < arr.size) { if (arr[i] != 0) { i++ continue } for (j in arr.size - 1 downTo i + 1) { arr[j] = arr[j - 1] } if (i + 1 < arr.size) { arr[i + 1] = 0 } i += 2 } } /** * https://leetcode-cn.com/problems/next-permutation/ */ fun nextPermutation(nums: IntArray): Unit { var n: Int = -1 for (i in nums.lastIndex downTo 1) { if (nums[i - 1] < nums[i]) { n = i - 1 break } } if (n == -1) { nums.sort() } else { var m: Int = nums.lastIndex for (j in n + 1 until nums.size) { if (nums[j] <= nums[n]) { // find just larger than nums[n] m = j - 1 break } } // swap m and n val temp = nums[n] nums[n] = nums[m] nums[m] = temp // reverse nums.slice(IntRange(n + 1, nums.lastIndex)).reversed().forEachIndexed { index, i -> nums[n + index + 1] = i } } } /** * https://leetcode-cn.com/problems/permutations/ */ fun permute(nums: IntArray): List<List<Int>> { val result = ArrayList<List<Int>>() permuteItem(result, nums, 0) return result } private fun permuteItem(result: MutableList<List<Int>>, nums: IntArray, index: Int) { if (index == nums.lastIndex) { result.add(nums.toList()) } else { for (i in index until nums.size) { swap(nums, index, i) permuteItem(result, nums, index + 1) swap(nums, index, i) } } } private fun swap(nums: IntArray, i: Int, j: Int) { if (i != j) { val temp = nums[i] nums[i] = nums[j] nums[j] = temp } } /** * https://leetcode-cn.com/problems/degree-of-an-array/ */ fun findShortestSubArray(nums: IntArray): Int { val left = HashMap<Int, Int>() val right = HashMap<Int, Int>() val countItem = HashMap<Int, Int>() nums.forEachIndexed { index, i -> if (i !in left.keys) { left[i] = index } right[i] = index countItem[i] = countItem.getOrDefault(i, 0) + 1 } var ins = nums.size val degree = countItem.values.max() countItem.filterValues { it == degree }.forEach { if (right[it.key]!! - left[it.key]!! + 1 < ins) { ins = right[it.key]!! - left[it.key]!! + 1 } } return ins } /** * https://leetcode-cn.com/problems/find-pivot-index/ */ fun pivotIndex(nums: IntArray): Int { val arraySum = nums.sum() var leftSum = 0 nums.forEachIndexed { index, i -> if (leftSum == arraySum - i - leftSum) { return index } leftSum += i } return -1 } /** * https://leetcode-cn.com/problems/subsets/ */ fun subsets(nums: IntArray): List<List<Int>> { val result = mutableListOf<List<Int>>() dfsSubSets(nums, IntArray(nums.size), 0, result) return result } private fun dfsSubSets(nums: IntArray, flag: IntArray, index: Int, result: MutableList<List<Int>>) { if (index > nums.lastIndex) { result.add(nums.filterIndexed { m, _ -> flag[m] == 1 }.toList()) return } flag[index] = 0 dfsSubSets(nums, flag, index + 1, result) flag[index] = 1 dfsSubSets(nums, flag, index + 1, result) } /** * https://leetcode-cn.com/problems/self-dividing-numbers/ */ fun selfDividingNumbers(left: Int, right: Int): List<Int> { return (left..right).filter { checkSelfNumber(it) } } private fun checkSelfNumber(n: Int): Boolean { n.toString().map { it.toInt() - '0'.toInt() }.forEach { if (it == 0 || n % it != 0) { return false } } return true } /** * https://leetcode-cn.com/problems/set-mismatch/ */ fun findErrorNums(nums: IntArray): IntArray { val result = IntArray(2) if (nums.isEmpty()) { return result } for (i in nums.indices) { if (nums[abs(nums[i]) - 1] < 0) { result[0] = abs(nums[i]) } else { nums[abs(nums[i]) - 1] *= -1 } } nums.forEachIndexed missing@{ index, i -> if (i > 0) { result[1] = index + 1 return@missing } } return result } /** * https://leetcode-cn.com/problems/rotated-digits/ */ fun rotatedDigits(N: Int): Int { var count = 0 repeat(N) N@{ val n = (it + 1).toString().toCharArray() n.forEachIndexed check@{ index, c -> when (c.toInt() - '0'.toInt()) { 0, 1, 8 -> return@check 2 -> n[index] = '5' 5 -> n[index] = '2' 6 -> n[index] = '9' 9 -> n[index] = '6' else -> return@N } } if (String(n).toInt() != it + 1) { count++ } } return count } /** * https://leetcode-cn.com/problems/find-lucky-integer-in-an-array/ */ fun findLucky(arr: IntArray): Int { val n = arr.sorted().reversed() var current = n[0] var count = 1 for (i in 1..n.lastIndex) { if (n[i] == current) { count++ } else { if (count == current) { return current } current = n[i] count = 1 } } return if (count == current) current else -1 } /** * https://leetcode-cn.com/problems/cells-with-odd-values-in-a-matrix/ */ fun oddCells(n: Int, m: Int, indices: Array<IntArray>): Int { val data = Array(n) { IntArray(m) { 0 } } indices.forEach { loc -> repeat(m) { data[loc[0]][it]++ } repeat(n) { data[it][loc[1]]++ } } var count = 0 for (i in 0 until n) { for (j in 0 until m) { if (data[i][j] % 2 == 1) { count++ } } } return count } /** * https://leetcode-cn.com/problems/string-to-integer-atoi/ */ fun myAtoi(str: String): Int { var s = str.trim() if (s.isEmpty()) { return 0 } if (s[0] != '+' && s[0] != '-' && !s[0].isDigit()) { return 0 } val nav = if (s[0] == '+' || s[0].isDigit()) 1L else -1L s = if (s[0] == '-' || s[0] == '+') s.substring(1) else s if (s.isEmpty() || !s[0].isDigit()) { return 0 } var index = s.lastIndex for (i in s.indices) { if (!s[i].isDigit()) { break } index = i } return try { val r = s.substring(0, index + 1).toBigInteger().multiply(BigInteger.valueOf(nav)) when { r > BigInteger.valueOf(Int.MAX_VALUE.toLong()) -> { Int.MAX_VALUE } r < BigInteger.valueOf(Int.MIN_VALUE.toLong()) -> { Int.MIN_VALUE } else -> { r.toInt() } } } catch (e: Exception) { 0 } } /** * 双周赛 */ fun countLargestGroup(n: Int): Int { val count = IntArray(36) { 0 } for (i in 1..n) { var sum = 0 i.toString().forEach { sum += it - '0' } if (sum > 0) { count[sum - 1]++ } } val m = count.max() var result = 0 count.forEach { if (it == m) { result++ } } return result } /** * https://leetcode-cn.com/problems/number-of-steps-to-reduce-a-number-in-binary-representation-to-one/ */ fun numSteps(s: String): Int { var binNum = BigInteger(s, 2) var count = 0 val one = BigInteger.valueOf(1L) while (binNum > one) { if (binNum.and(one) == one) { binNum++ } else { binNum = binNum.shr(1) } count++ } return count } /** * https://leetcode-cn.com/problems/minimum-subsequence-in-non-increasing-order/ */ fun minSubsequence(nums: IntArray): List<Int> { val numSum = nums.sum() var subSum = 0 val result = mutableListOf<Int>() nums.sorted().reversed().forEach { subSum += it result.add(it) if (subSum > numSum - subSum) { return result.sorted().reversed() } } return result } fun multiply(num1: String, num2: String): String { val result = StringBuffer() val n1 = num1.reversed() val n2 = num2.reversed() val addNum: (StringBuffer, StringBuffer) -> Unit = { result, s -> var addCarry = 0 s.map { it - '0' }.forEachIndexed { index, c -> if (index < result.length) { val m = (result[index] - '0' + c + addCarry) addCarry = m / 10 result.setCharAt(index, ((m % 10) + '0'.toInt()).toChar()) } else { val m = c + addCarry addCarry = m / 10 result.append(m % 10) } } if (addCarry > 0) { result.append(addCarry) } } n1.map { it - '0' }.forEachIndexed { i, n -> val lineBuffer = StringBuffer() var carry = 0 repeat(i) { lineBuffer.append(0) } n2.map { it - '0' }.forEach { m -> val s = n * m + carry carry = s / 10 lineBuffer.append(s % 10) } if (carry > 0) { lineBuffer.append(carry) } addNum(result, lineBuffer) } if (result.count { it == '0' } == result.length) { return "0" } return result.reverse().toString() } fun rotate(matrix: Array<IntArray>): Unit { var temp = 0 val n = matrix.size for (i in 0 until n / 2) { for (j in i until n - i - 1) { temp = matrix[i][j] matrix[i][j] = matrix[n - j - 1][i] matrix[n - j - 1][i] = matrix[n - 1 - i][n - j - 1] matrix[n - 1 - i][n - j - 1] = matrix[j][n - 1 - i] matrix[j][n - 1 - i] = temp } } } /** * https://leetcode-cn.com/problems/search-a-2d-matrix/ */ fun searchMatrix(matrix: Array<IntArray>, target: Int): Boolean { matrix.forEach { if (it.isNotEmpty() && target <= it.last()) { val index = it.indexOf(target) if (index >= 0) { return true } } } return false } /** * https://leetcode-cn.com/problems/single-number-ii/ */ fun singleNumber(nums: IntArray): Int { val set = HashSet<Long>() var sum = 0L nums.forEach { set.add(it.toLong()) sum += it } return ((3 * set.sum() - sum) / 2).toInt() } /** * https://leetcode-cn.com/problems/shu-zu-zhong-chu-xian-ci-shu-chao-guo-yi-ban-de-shu-zi-lcof/ */ fun majorityElement(nums: IntArray): Int { var vote = 0 var target = 0 nums.forEach { if (vote == 0) { target = it } vote += if (it == target) 1 else -1 } return if (nums.count { it == target } > nums.size / 2) target else 0 } fun processQueries(queries: IntArray, m: Int): IntArray { val ans = IntArray(queries.size) val p = ArrayList<Int>(m) repeat(m) { p.add(it + 1) } queries.forEachIndexed { index, i -> val pos = p.indexOf(i) if (pos >= 0) { ans[index] = pos p.removeAt(pos) p.add(0, i) } } return ans } /** * https://leetcode-cn.com/problems/number-of-ways-to-paint-n-x-3-grid/ */ fun numOfWays(n: Int): Int { var a = 6L var b = 6L repeat(n - 1) { val tempA = 3 * a + 2 * b b = (2 * a + 2 * b) % 1000000007L a = tempA % 1000000007L } return ((a + b) % 1000000007L).toInt() } /** * https://leetcode-cn.com/problems/missing-number-lcci/ */ fun missingNumber(nums: IntArray): Int { return nums.size * (nums.size + 1) / 2 - nums.sum() } /** * https://leetcode-cn.com/problems/er-wei-shu-zu-zhong-de-cha-zhao-lcof/ */ fun findNumberIn2DArray(matrix: Array<IntArray>, target: Int): Boolean { if (matrix.isEmpty() || matrix[0].isEmpty()) { return false } var row = 0 var col = matrix[0].lastIndex while (row < matrix.size && col >= 0) { when { target == matrix[row][col] -> return true target > matrix[row][col] -> row++ else -> col-- } } return false } /** * https://leetcode-cn.com/problems/jump-game/ */ fun canJump(nums: IntArray): Boolean { var step = 0 nums.forEachIndexed { index, i -> step = if (index == 0) { i } else { max(step - 1, i) } if (step == 0 && index < nums.lastIndex) { return false } } return step >= 0 } /** * https://leetcode-cn.com/contest/biweekly-contest-24/problems/minimum-value-to-get-positive-step-by-step-sum/ */ fun minStartValue(nums: IntArray): Int { var m = Int.MAX_VALUE var sum = 0 nums.forEach { sum += it if (sum < m) { m = sum } } return if (m < 0) 1 - m else 1 } /** * https://leetcode-cn.com/contest/biweekly-contest-24/problems/find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/ */ fun findMinFibonacciNumbers(k: Int): Int { val fibonacci = mutableListOf<Int>() var a = 1 var b = 1 fibonacci.add(a) fibonacci.add(b) while (fibonacci.last() < k) { val n = a + b fibonacci.add(n) a = b b = n } var count = 0 var sum = k for (i in fibonacci.lastIndex downTo 0) { if (fibonacci[i] <= sum) { sum -= fibonacci[i] count++ if (sum == 0) { return count } } } return count } /** * https://leetcode-cn.com/problems/1-bit-and-2-bit-characters/ */ fun isOneBitCharacter(bits: IntArray): Boolean { var index = 0 while (index < bits.size) { if (index == bits.lastIndex && bits[index] == 0) { return true } when (bits[index]) { 0 -> index++ 1 -> index += 2 } } return false } /** * https://leetcode-cn.com/problems/largest-number-at-least-twice-of-others/ */ fun dominantIndex(nums: IntArray): Int { var maxNum = 0 var maxIndex = 0 nums.forEachIndexed { index, i -> if (i > maxNum) { maxNum = i maxIndex = index } } nums.forEachIndexed { index, i -> if (index != maxIndex && i * 2 > maxNum) { return -1 } } return maxIndex } /** * https://leetcode-cn.com/problems/lucky-numbers-in-a-matrix/ */ fun luckyNumbers(matrix: Array<IntArray>): List<Int> { val ans = mutableListOf<Int>() val minNumberIndex = IntArray(matrix.size) matrix.forEachIndexed { index, ints -> var m = Int.MAX_VALUE ints.forEachIndexed { j, n -> if (n < m) { m = n minNumberIndex[index] = j } } } minNumberIndex.forEachIndexed { index, i -> for (j in matrix.indices) { if (matrix[j][i] > matrix[index][i]) { return@forEachIndexed } } ans.add(matrix[index][i]) } return ans } /** * https://leetcode-cn.com/problems/sort-array-by-parity-ii/ */ fun sortArrayByParityII(A: IntArray): IntArray { var even = 0 var odd = 1 while (odd < A.size || even < A.size) { while (even < A.size && A[even] % 2 == 0) { even += 2 } while (odd < A.size && A[odd] % 2 == 1) { odd += 2 } if (odd < A.size && even < A.size) { val temp = A[odd] A[odd] = A[even] A[even] = temp } } return A } /** * https://leetcode-cn.com/problems/relative-sort-array/ */ fun relativeSortArray(arr1: IntArray, arr2: IntArray): IntArray { val ans = mutableListOf<Int>() val nums = IntArray(1001) { 0 } arr1.forEach { nums[it]++ } arr2.forEach { while (nums[it] != 0) { nums[it]-- ans.add(it) } } for (i in 1..1000) { while (nums[i] != 0) { nums[i]-- ans.add(i) } } return ans.toIntArray() } /** * https://leetcode-cn.com/problems/squares-of-a-sorted-array/ */ fun sortedSquares(A: IntArray): IntArray { val ans = IntArray(A.size) val positive = A.filter { it >= 0 }.map { it * it } var right = 0 val negative = A.filter { it < 0 }.map { it * it } var left = negative.size - 1 for (i in ans.indices) { ans[i] = when { right == positive.size -> negative[left--] left == -1 -> positive[right++] positive[right] >= negative[left] -> negative[left--] else -> positive[right++] } } return ans } /** * https://leetcode-cn.com/problems/sum-of-even-numbers-after-queries/ * 暴力会超时 */ fun sumEvenAfterQueries(A: IntArray, queries: Array<IntArray>): IntArray { val ans = IntArray(queries.size) var base = A.filter { it % 2 == 0 }.sum() queries.forEachIndexed { index, ints -> val before = A[ints[1]] A[ints[1]] += ints[0] val after = A[ints[1]] if (before % 2 == 0) { // 偶数 if (after % 2 == 0) { ans[index] = base - before + after } else { ans[index] = base - before } } else if (after % 2 == 0) { ans[index] = base + after } else { ans[index] = base } base = ans[index] } return ans } /** * https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array/ */ fun searchRange(nums: IntArray, target: Int): IntArray { var left = 0 var right = nums.lastIndex var mid: Int var index = -1 while (left <= right) { mid = (left + right) / 2 if (nums[mid] > target) { right = mid - 1 } else if (nums[mid] < target) { left = mid + 1 } else { index = mid break } } if (index > -1) { left = index while (left >= 0 && nums[left] == target) { left-- } if (left == -1) { left = 0 } else { left++ } right = index while (right < nums.size && nums[right] == target) { right++ } if (right == nums.size) { right = nums.lastIndex } else { right-- } return intArrayOf(left, right) } return intArrayOf(-1, -1) } /** * https://leetcode-cn.com/problems/powerful-integers/ */ fun powerfulIntegers(x: Int, y: Int, bound: Int): List<Int> { val ans = HashSet<Int>() for (i in 0 until 20) { for (j in 0 until 20) { val n = x.toDouble().pow(i) + y.toDouble().pow(j) if (n <= bound) { ans.add(n.toInt()) } } } return ans.toList() } /** * https://leetcode-cn.com/problems/sliding-window-maximum/ */ fun maxSlidingWindow(nums: IntArray, k: Int): IntArray { val queueIndex = LinkedList<Int>() val ans = IntArray(nums.size - k + 1) nums.forEachIndexed { index, i -> while (queueIndex.isNotEmpty() && nums[queueIndex.last] < i) { queueIndex.removeLast() } queueIndex.addLast(index) if (queueIndex.first == index - k) { queueIndex.removeFirst() } if (index >= k - 1) { ans[index - k + 1] = nums[queueIndex.first] } } return ans } }
0
Kotlin
0
0
cbb2e3ad8f2d05d7cc54a865265561a0e391a9b9
35,791
leetcode
Apache License 2.0
aoc-2018/src/main/kotlin/nl/jstege/adventofcode/aoc2018/days/Day12.kt
JStege1206
92,714,900
false
null
package nl.jstege.adventofcode.aoc2018.days import nl.jstege.adventofcode.aoccommon.days.Day import nl.jstege.adventofcode.aoccommon.utils.extensions.head import nl.jstege.adventofcode.aoccommon.utils.extensions.sumBy class Day12 : Day(title = "Subterranean Sustainability") { private companion object Configuration { private const val FIRST_GENERATIONS = 20L private const val SECOND_GENERATIONS = 50_000_000_000L } override fun first(input: Sequence<String>): Any = input.parse().let { (initial, reps) -> initial.solve(FIRST_GENERATIONS, reps) } override fun second(input: Sequence<String>): Any = input.parse().let { (initial, reps) -> initial.solve(SECOND_GENERATIONS, reps) } private fun String.solve(generations: Long, replacements: Set<String>): Long { tailrec fun String.solveRecursive(currentGen: Long, shift: Long): Long { val (nextState, nextShift) = this.next(shift, replacements) if (nextState == this || currentGen == generations) { val absoluteShift = shift + (nextShift - shift) * (generations - currentGen) return this .withIndex() .filter { it.value == '#' } .sumBy { it.index + absoluteShift } } return nextState.solveRecursive(currentGen + 1, nextShift) } return this.solveRecursive(0, 0) } private fun String.next(shift: Long, replacements: Set<String>): Pair<String, Long> = "....$this...." .windowed(5, 1) .joinToString("") { if (it in replacements) "#" else "." } .let { state -> Pair(state.trim('.'), shift - 2 + state.indexOf('#')) } private fun Sequence<String>.parse(): Pair<String, Set<String>> = Pair( head.removePrefix("initial state: "), drop(2) .map { it.split(" => ") } .filter { (_, s) -> s != "." } .map { it.first() } .toSet() ) }
0
Kotlin
0
0
d48f7f98c4c5c59e2a2dfff42a68ac2a78b1e025
2,119
AdventOfCode
MIT License