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/Day12.kt | Kbzinho-66 | 572,299,619 | false | {"Kotlin": 34500} | import kotlin.properties.Delegates
private typealias Adjacencies = MutableList<Int>
private class Graph(input: List<String>) {
private var rows by Delegates.notNull<Int>()
private var cols by Delegates.notNull<Int>()
private var start by Delegates.notNull<Int>()
private var end by Delegates.notNull<Int>()
private var heights: Array<IntArray>
private var graph: Array<Adjacencies>
private var inverted: Array<Adjacencies>
init {
rows = input.size
cols = input.first().length
heights = Array(rows) { IntArray(cols) }
graph = Array(rows * cols) { mutableListOf() }
inverted = Array(rows * cols) { mutableListOf() }
input.forEachIndexed { row, s ->
s.forEachIndexed { col, height ->
heights[row][col] = when (height) {
'S' -> 'a'.also { start = row * cols + col }
'E' -> 'z'.also { end = row * cols + col }
else -> height
} - 'a'
}
}
buildGraph()
}
private fun buildGraph() {
val deltaX = arrayOf(0, 1, 0, -1)
val deltaY = arrayOf(-1, 0, 1, 0)
for (i in 0 until rows) {
for (j in 0 until cols) {
val current = i * cols + j
val currentHeight = heights[i][j]
for (d in 0 until 4) {
val u = i + deltaY[d]
val v = j + deltaX[d]
val dest = u * cols + v
if (u in 0 until rows && v in 0 until cols) {
val destHeight = heights[u][v]
if (currentHeight >= destHeight || destHeight == currentHeight + 1) {
graph[current].add(dest)
inverted[dest].add(current)
}
}
}
}
}
}
fun part1(): Int {
// Aqui dá pra fazer uma BFS normal
val distance = IntArray(graph.size) { -1 }
distance[start] = 0
val queue = ArrayDeque<Int>()
queue.addLast(start)
while (distance[end] == -1) {
val curr = queue.removeFirst()
val dist = distance[curr] + 1
for (adj in graph[curr]) {
if (distance[adj] == -1) {
distance[adj] = dist
queue.addLast(adj)
}
}
}
return distance[end]
}
fun part2(): Int {
// Aqui, precisa de uma BFS modificada, partindo do destino, o lugar mais alto e parando
// quando encontrar um lugar de elevação 0
val distance = IntArray(graph.size) { -1 }
distance[end] = 0
val queue = ArrayDeque<Int>()
queue.addLast(end)
while (true) {
val curr = queue.removeFirst()
val dist = distance[curr]
if (heights[curr/cols][curr%cols] == 0) return dist
for (adj in inverted[curr]) {
if (distance[adj] == -1) {
distance[adj] = dist + 1
queue.addLast(adj)
}
}
}
}
}
fun main() {
// Testar os casos básicos
val testGraph = Graph(readInput("../inputs/Day12_test"))
sanityCheck(testGraph.part1(), 31)
sanityCheck(testGraph.part2(), 29)
val graph = Graph(readInput("../inputs/Day12"))
println("Parte 1 = ${graph.part1()}")
println("Parte 2 = ${graph.part2()}")
} | 0 | Kotlin | 0 | 0 | e7ce3ba9b56c44aa4404229b94a422fc62ca2a2b | 3,549 | advent_of_code_2022_kotlin | Apache License 2.0 |
src/main/kotlin/com/staricka/adventofcode2022/Day2.kt | mathstar | 569,952,400 | false | {"Kotlin": 77567} | package com.staricka.adventofcode2022
import java.lang.Exception
class Day2 : Day {
override val id = 2
enum class Choice(val score: Int) {
ROCK(1), PAPER(2), SCISSORS(3);
fun outcome(vs: Choice) : Int{
if (this == vs) return 3
if (this == ROCK && vs == SCISSORS) return 6
if (this == PAPER && vs == ROCK) return 6
if (this == SCISSORS && vs == PAPER) return 6
return 0
}
fun makeChoice(desiredResult: Char): Choice =
when(desiredResult) {
'X' -> when(this) {
ROCK -> SCISSORS
PAPER -> ROCK
SCISSORS -> PAPER
}
'Y' -> this
'Z' -> when(this) {
ROCK -> PAPER
PAPER -> SCISSORS
SCISSORS -> ROCK
}
else -> throw Exception()
}
}
private fun String.toChoice() : Choice =
when (this[0]) {
'A' -> Choice.ROCK
'B' -> Choice.PAPER
'C' -> Choice.SCISSORS
'X' -> Choice.ROCK
'Y' -> Choice.PAPER
'Z' -> Choice.SCISSORS
else -> throw Exception()
}
private fun String.lineToPart1Choices() : Pair<Choice, Choice> {
val split = this.split(" ")
return Pair(split[0].toChoice(), split[1].toChoice())
}
private fun String.lineToPart2Choices() : Pair<Choice, Choice> {
val split = this.split(" ")
val opponent = split[0].toChoice()
return Pair(opponent, opponent.makeChoice(split[1][0]))
}
override fun part1(input: String): Any {
return input.lines().filter { it.isNotBlank() }.map {
val (opponent, mine) = it.lineToPart1Choices()
mine.score + mine.outcome(opponent)
}.sum()
}
override fun part2(input: String): Any =
input.lines().filter { it.isNotBlank() }.map {
val (opponent, mine) = it.lineToPart2Choices()
mine.score + mine.outcome(opponent)
}.sum()
} | 0 | Kotlin | 0 | 0 | 2fd07f21348a708109d06ea97ae8104eb8ee6a02 | 1,845 | adventOfCode2022 | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/NthMagicalNumber.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2020 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import dev.shtanko.algorithms.MOD
import dev.shtanko.algorithms.math.gcd
import kotlin.math.ceil
import kotlin.math.min
fun interface NthMagicalNumber {
operator fun invoke(n: Int, a: Int, b: Int): Int
}
class NthMagicalNumberMath : NthMagicalNumber {
override operator fun invoke(n: Int, a: Int, b: Int): Int {
val lcm = a * b / gcd(a, b)
val cntPerLcm = lcm / a + lcm / b - 1
val cntLcm = n / cntPerLcm
val remain = n % cntPerLcm
val nearest: Double = remain.div(1.0.div(a).plus(1.0.div(b)))
val remainIdx = min(ceil(nearest / a) * a, ceil(nearest / b) * b).toInt()
return cntLcm.times(lcm).plus(remainIdx) % MOD
}
}
class NthMagicalNumberBS : NthMagicalNumber {
override operator fun invoke(n: Int, a: Int, b: Int): Int {
val l: Int = a / gcd(a, b) * b
var lo: Long = 0
var hi: Long = n.toLong() * min(a, b)
while (lo < hi) {
val mi = lo + hi.minus(lo) / 2
if (mi / a + mi / b - mi / l < n) lo = mi + 1 else hi = mi
}
return (lo % MOD).toInt()
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,748 | kotlab | Apache License 2.0 |
src/year2022/05/Day05.kt | Vladuken | 573,128,337 | false | {"Kotlin": 327524, "Python": 16475} | package year2022.`05`
import java.util.Stack
import readInput
fun main() {
fun part1(input: List<String>): String {
val (mutableStacks, listOfCommands) = prepareStacksToCommands(input)
applyCommandsToStacks(
mutableStacks = mutableStacks,
commands = listOfCommands
)
return peekListOfStacks(mutableStacks).joinToString("")
}
fun part2(input: List<String>): String {
val (mutableStacks, listOfCommands) = prepareStacksToCommands(input)
applyCommandsToStacksPart2(
mutableStacks = mutableStacks,
commands = listOfCommands
)
return peekListOfStacks(mutableStacks).joinToString("")
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
val part1Test = part1(testInput)
//println(part1Test)
check(part1Test == "CMZ")
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
/**
* Class for working with moving commands
*/
data class Command(
val amount: Int,
val from: Int,
val to: Int
)
/**
* Build list of stacks from input
*/
fun buildListOfStacks(
amountOfStacks: Int,
lines: List<List<String?>>
): List<Stack<String>> {
// Build initial empty stacks
val stacks = mutableListOf<Stack<String>>()
repeat(amountOfStacks) {
stacks.add(Stack<String>())
}
// Fill stacks with values
for (item in lines.reversed()) {
repeat(amountOfStacks) {
// Workaround for cases, when input line is not full
try {
val crate = item[it]
if (crate != null) {
stacks[it].add(crate)
}
} catch (e: Exception) {
return@repeat
}
}
}
return stacks
}
/**
* Parse string "[W] [W] [N] [L] [V] [W] [C] "
* to list of [W,W,null,N,L,V,W,C,null]
*/
fun cratesInputToLists(input: List<String>): List<List<String?>> {
return input.map {
it.windowed(3, 4)
.map { crateString ->
if (crateString.isBlank()) {
null
} else {
crateString[1].toString()
}
}
}
}
/**
* Parse list of stack amount and fetch max amount
*/
fun crateAmountToInt(amountLine: String): Int {
return amountLine.split(" ")
.last { it.isNotEmpty() }
.toInt()
}
/**
* Move "Crates" one by one
*/
fun applyCommandsToStacks(
mutableStacks: List<Stack<String>>,
commands: List<Command>
) {
commands.forEach { (amount, from, to) ->
val fromStack = mutableStacks[from - 1]
val toStack = mutableStacks[to - 1]
repeat(amount) {
val itemToMove = fromStack.pop()
toStack.push(itemToMove)
}
}
}
/**
* Move "Crates" all together
*/
fun applyCommandsToStacksPart2(
mutableStacks: List<Stack<String>>,
commands: List<Command>
) {
commands.forEach { (amount, from, to) ->
val fromStack = mutableStacks[from - 1]
val toStack = mutableStacks[to - 1]
val listToMove = mutableListOf<String>()
repeat(amount) {
listToMove.add(fromStack.pop())
}
toStack.addAll(listToMove.reversed())
}
}
/**
* Parse strings to list of [Command]
*/
fun buildListOfCommands(
lines: List<String>
): List<Command> {
return lines.map {
val keys = it.split(" ")
Command(keys[1].toInt(), keys[3].toInt(), keys[5].toInt())
}
}
/**
* Peek list of stacks and return top items
*/
fun peekListOfStacks(
stacks: List<Stack<String>>
): List<String> {
return stacks.map { it.peek() }
}
/**
* Parse all input to data
*/
fun prepareStacksToCommands(
input: List<String>
): Pair<List<Stack<String>>, List<Command>> {
// Part 1
val firstPart = input.takeWhile { it.isNotBlank() }
val crates = firstPart.dropLast(1)
val cratesAmountInput = firstPart.last()
val mutableStacks = buildListOfStacks(
amountOfStacks = crateAmountToInt(cratesAmountInput),
lines = cratesInputToLists(crates)
)
// Part 2
val listOfCommands = buildListOfCommands(
lines = input.reversed().takeWhile { it.isNotBlank() }.reversed()
)
return mutableStacks to listOfCommands
}
| 0 | Kotlin | 0 | 5 | c0f36ec0e2ce5d65c35d408dd50ba2ac96363772 | 4,415 | KotlinAdventOfCode | Apache License 2.0 |
src/day01/Day01.kt | zoricbruno | 573,440,038 | false | {"Kotlin": 13739} | fun findCalories(input: List<String>): List<Int> {
val calories = mutableListOf<Int>()
var currentCalories = 0
var index = 0
while (index < input.size) {
if (input[index] == "") {
calories.add(currentCalories)
currentCalories = 0;
} else if (index == input.size - 1) {
currentCalories += input[index].toInt()
calories.add(currentCalories)
} else {
currentCalories += input[index].toInt()
}
index++
}
return calories
}
fun part1(input: List<String>): Int {
return findCalories(input).max()
}
fun part2(input: List<String>): Int {
return findCalories(input).sorted().takeLast(3).sum()
}
fun main() {
val day = "Day01"
val testInput = readInput(day, "Day01_test")
val input = readInput(day, day)
val testFirst = part1(testInput)
println(testFirst)
check(testFirst == 24000)
println(part1(input))
val testSecond = part2(testInput)
println(testSecond)
check(testSecond == 45000)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 16afa06aff0b6e988cbea8081885236e4b7e0555 | 1,081 | kotlin_aoc_2022 | Apache License 2.0 |
grind-75-kotlin/src/main/kotlin/ValidParentheses.kt | Codextor | 484,602,390 | false | {"Kotlin": 27206} | /**
* Given a string s containing just the characters '(', ')', '{', '}', '[' and ']',
* determine if the input string is valid.
*
* An input string is valid if:
*
* Open brackets must be closed by the same type of brackets.
* Open brackets must be closed in the correct order.
*
*
* Example 1:
*
* Input: s = "()"
* Output: true
* Example 2:
*
* Input: s = "()[]{}"
* Output: true
* Example 3:
*
* Input: s = "(]"
* Output: false
*
*
* Constraints:
*
* 1 <= s.length <= 10^4
* s consists of parentheses only '()[]{}'.
* @see <a href="https://leetcode.com/problems/valid-parentheses/">LeetCode</a>
*/
fun isValid(s: String): Boolean {
if (s.length % 2 == 1) return false
val deque = ArrayDeque<Char>()
for (parenthesis in s) {
when (parenthesis) {
in openingParenthesesSet -> parenthesesMap[parenthesis]?.let { deque.addLast(it) }
in closingParenthesesSet -> if (deque.lastOrNull() == parenthesis) deque.removeLast() else return false
}
}
return deque.isEmpty()
}
val parenthesesMap = mapOf('(' to ')', '{' to '}', '[' to ']')
val openingParenthesesSet = setOf('(', '{', '[')
val closingParenthesesSet = setOf(')', '}', ']')
| 0 | Kotlin | 0 | 0 | 87aa60c2bf5f6a672de5a9e6800452321172b289 | 1,216 | grind-75 | Apache License 2.0 |
src/main/kotlin/days/Day8.kt | mir47 | 433,536,325 | false | {"Kotlin": 31075} | package days
class Day8 : Day(8) {
override fun partOne(): Int {
val r = inputList.map { it.split(" | ") }
.map { it[1] }
.flatMap { it.split(" ") }
return r.count { it.length == 2 || it.length == 3 || it.length == 4 || it.length == 7 }
}
override fun partTwo(): Long {
var result: Long = 0
inputList.map { it.split(" | ") }
.map { entry ->
val entryPatterns: List<String> = entry[0].split(" ")
.map { it.toCharArray().sorted().joinToString("") }
val entryOutputs: List<String> = entry[1].split(" ")
.map { it.toCharArray().sorted().joinToString("") }
val map = mutableMapOf<Int, String>()
entryPatterns.forEach { seg ->
when (seg.length) {
2 -> map[1] = seg
3 -> map[7] = seg
4 -> map[4] = seg
7 -> map[8] = seg
}
}
entryPatterns.forEach { seg ->
if (seg.length == 6) { // 0, 6, 9
var d1 = 0
map[4]!!.forEach { if (!seg.contains(it)) d1++ }
if (d1 == 0) {
map[9] = seg
} else {
var d2 = 0
map[1]!!.forEach { if (!seg.contains(it)) d2++ }
if (d2 == 0) {
map[0] = seg
} else {
map[6] = seg
}
}
}
}
entryPatterns.forEach { seg ->
when (seg.length) {
// 2, 3, 5
5 -> {
var d1 = 0
map[7]!!.forEach { if(!seg.contains(it)) d1++ }
if (d1 == 0) {
map[3] = seg
} else {
var d2 = 0
map[6]!!.forEach { if(!seg.contains(it)) d2++ }
if (d2 == 1) {
map[5] = seg
} else {
map[2] = seg
}
}
}
}
}
var output = ""
entryOutputs.forEach { entryOutput ->
map.forEach { seg ->
if (seg.value == entryOutput) {
output += seg.key.toString()
}
}
}
result += output.toLong()
}
return result
}
} | 0 | Kotlin | 0 | 0 | 686fa5388d712bfdf3c2cc9dd4bab063bac632ce | 2,991 | aoc-2021 | Creative Commons Zero v1.0 Universal |
2021/src/Day03.kt | Bajena | 433,856,664 | false | {"Kotlin": 65121, "Ruby": 14942, "Rust": 1698, "Makefile": 454} | // https://adventofcode.com/2021/day/3
import java.io.File
import kotlin.math.pow
fun main() {
fun readLines(fileName: String): List<String>
= File(fileName).bufferedReader().readLines()
fun part1() {
val ones = sortedMapOf<Int, Int>()
val zeros = sortedMapOf<Int, Int>()
for (line in readLines("src/Day03.txt")) {
line.forEachIndexed { index, c ->
when(c) {
'1' -> ones[index] = ones.getOrDefault(index, 0) + 1
'0' -> zeros[index] = zeros.getOrDefault(index, 0) + 1
}
}
}
println(ones)
println(zeros)
var gamma = ""
var epsilon = ""
ones.values.toList().zip(zeros.values.toList()) { onesInBit, zerosInBit -> if (onesInBit > zerosInBit) { gamma += '1'; epsilon += '0' } else { gamma += '0'; epsilon += '1' } }
println(gamma)
println(epsilon)
println(gamma.toInt(2) * epsilon.toInt(2))
}
fun part2() {
var decimals = mutableListOf<Int>()
var numbers = mutableListOf<String>()
var positions = 0
for (line in readLines("src/Day03.txt")) {
decimals.add(line.toInt(2))
numbers.add(line)
positions = line.length
}
var leftNumbers = numbers.toList()
var i = 0
while (leftNumbers.size > 1 && i < positions) {
val withBit = leftNumbers.filter { it[i] == '1' }
val withoutBit = leftNumbers.filter { it[i] == '0' }
if (withBit.size >= withoutBit.size) {
leftNumbers = withBit
} else {
leftNumbers = withoutBit
}
i++
}
var oxygen = leftNumbers.first().toInt(2)
leftNumbers = numbers.toList()
i = 0
while (leftNumbers.size > 1 && i < positions) {
val withBit = leftNumbers.filter { it[i] == '1' }
val withoutBit = leftNumbers.filter { it[i] == '0' }
if (withBit.size < withoutBit.size) {
leftNumbers = withBit
} else {
leftNumbers = withoutBit
}
i++
}
val co2 = leftNumbers.first().toInt(2)
println(oxygen * co2)
}
part1()
part2()
}
| 0 | Kotlin | 0 | 0 | a5ca56b7ac8d9d48f82dc079c8ea0cf06d17109a | 2,041 | advent-of-code | Apache License 2.0 |
src/main/java/com/booknara/problem/bfs/RottingOrangesKt.kt | booknara | 226,968,158 | false | {"Java": 1128390, "Kotlin": 177761} | package com.booknara.problem.bfs
import java.util.*
/**
* 994. Rotting Oranges (Medium)
* https://leetcode.com/problems/rotting-oranges/
*/
class RottingOrangesKt {
// T:O(n^2), S:O(n^2)
fun orangesRotting(grid: Array<IntArray>): Int {
// input check, m, n >= 1
// finding rotten oranges
var count = 0
val queue = LinkedList<Pair<Int, Int>>()
for (i in grid.indices) {
val array = grid[i]
for (j in array.indices) {
if (array[j] == 1) {
count++
} else if (array[j] == 2) {
queue.offer(Pair(i, j))
}
}
}
if (count == 0) return 0
val dirs = arrayOf(
intArrayOf(0, -1),
intArrayOf(0, 1),
intArrayOf(-1, 0),
intArrayOf(1, 0)
)
var min = -1
while (!queue.isEmpty()) {
val size = queue.size
for (i in 0 until size) {
val p = queue.poll()
for (d in dirs) {
val r = p.first + d[0]
val c = p.second + d[1]
if (r < 0 || c < 0 || r >= grid.size || c == grid[0].size || grid[r][c] != 1) {
continue
}
queue.offer(Pair(r, c))
grid[r][c] = 2
}
}
min++
}
// checking fresh oranges
for (array in grid) {
for (element in array) {
if (element == 1) return -1
}
}
return min
}
}
| 0 | Java | 1 | 1 | 04dcf500ee9789cf10c488a25647f25359b37a53 | 1,374 | playground | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/NumberOfClosedIslands.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import java.util.LinkedList
import java.util.Queue
/**
* 1254. Number of Closed Islands
* @see <a href="https://leetcode.com/problems/number-of-closed-islands/">Source</a>
*/
fun interface NumberOfClosedIslands {
fun closedIsland(grid: Array<IntArray>): Int
}
/**
* Approach 1: Breadth First Search
*/
class NumberOfClosedIslandsBFS : NumberOfClosedIslands {
override fun closedIsland(grid: Array<IntArray>): Int {
val m: Int = grid.size
val n: Int = grid[0].size
val visit = Array(m) { BooleanArray(n) }
var count = 0
for (i in 0 until m) {
for (j in 0 until n) {
if (grid[i][j] == 0 && !visit[i][j] && bfs(i, j, m, n, grid, visit)) {
count++
}
}
}
return count
}
private fun bfs(x: Int, y: Int, m: Int, n: Int, grid: Array<IntArray>, visit: Array<BooleanArray>): Boolean {
var x1 = x
var y1 = y
val q: Queue<IntArray> = LinkedList()
q.offer(intArrayOf(x1, y1))
visit[x1][y1] = true
var isClosed = true
val dirX = intArrayOf(0, 1, 0, -1)
val dirY = intArrayOf(-1, 0, 1, 0)
while (q.isNotEmpty()) {
val temp: IntArray = q.poll()
x1 = temp[0]
y1 = temp[1]
for (i in 0..3) {
val r = x1 + dirX[i]
val c = y1 + dirY[i]
if (r < 0 || r >= m || c < 0 || c >= n) {
// (x, y) is a boundary cell.
isClosed = false
} else if (grid[r][c] == 0 && !visit[r][c]) {
q.offer(intArrayOf(r, c))
visit[r][c] = true
}
}
}
return isClosed
}
}
/**
* Approach 2: Depth First Search
*/
class NumberOfClosedIslandsDFS : NumberOfClosedIslands {
override fun closedIsland(grid: Array<IntArray>): Int {
val m: Int = grid.size
val n: Int = grid[0].size
val visit = Array(m) { BooleanArray(n) }
var count = 0
for (i in grid.indices) {
for (j in 0 until grid[0].size) {
if (grid[i][j] == 0 && !visit[i][j] && dfs(i, j, m, n, grid, visit)) {
count++
}
}
}
return count
}
private fun dfs(x: Int, y: Int, m: Int, n: Int, grid: Array<IntArray>, visit: Array<BooleanArray>): Boolean {
if (x < 0 || x >= grid.size || y < 0 || y >= grid[0].size) {
return false
}
if (grid[x][y] == 1 || visit[x][y]) {
return true
}
visit[x][y] = true
var isClosed = true
val dirX = intArrayOf(0, 1, 0, -1)
val dirY = intArrayOf(-1, 0, 1, 0)
for (i in 0..3) {
val r = x + dirX[i]
val c = y + dirY[i]
if (!dfs(r, c, m, n, grid, visit)) {
isClosed = false
}
}
return isClosed
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 3,659 | kotlab | Apache License 2.0 |
2022/src/main/kotlin/day2_fast.kt | madisp | 434,510,913 | false | {"Kotlin": 388138} | import utils.Parser
import utils.Solution
fun main() {
Day2Fast.run()
}
object Day2Fast : Solution<LongArray>() {
override val name = "day2"
// packed longs of plays, where a nibble in each long is
// a game with the bit layout of RRLL
override val parser = Parser.lines.map {
it.chunked(16).map { lines ->
var packed = 0L
lines.forEachIndexed { i, line ->
val play = ((line[0] - 'A' + ((line[2] - 'X') shl 2)) + 1).toLong()
packed = packed or (play shl (i shl 2))
}
packed
}.toLongArray()
}
override fun part1(input: LongArray): Long {
// packed nibbles of scores
val lookup = 0x69302580714 shl 4
var score = 0L
input.forEach { packed ->
(0 until 16).forEach { idx ->
val play = (packed ushr (idx shl 2)).toInt() and 15
score += (lookup ushr (play shl 2)) and 15
}
}
return score
}
override fun part2(input: LongArray): Long {
// packed nibbles of scores
val lookup = 0x79806540213 shl 4
var score = 0L
input.forEach { packed ->
// (0 until 16).forEach { idx ->
// val play = (packed ushr (idx shl 2)).toInt() and 15
// score += (lookup ushr (play shl 2)) and 15
// }
// truly heinous unrolled loop. original rolled one above
score += (((lookup ushr ((packed.toInt() and 15) shl 2)) and 15)
+ ((lookup ushr (((packed ushr 4).toInt() and 15) shl 2)) and 15)
+ ((lookup ushr (((packed ushr 8).toInt() and 15) shl 2)) and 15)
+ ((lookup ushr (((packed ushr 12).toInt() and 15) shl 2)) and 15)
+ ((lookup ushr (((packed ushr 16).toInt() and 15) shl 2)) and 15)
+ ((lookup ushr (((packed ushr 20).toInt() and 15) shl 2)) and 15)
+ ((lookup ushr (((packed ushr 24).toInt() and 15) shl 2)) and 15)
+ ((lookup ushr (((packed ushr 28).toInt() and 15) shl 2)) and 15)
+ ((lookup ushr (((packed ushr 32).toInt() and 15) shl 2)) and 15)
+ ((lookup ushr (((packed ushr 36).toInt() and 15) shl 2)) and 15)
+ ((lookup ushr (((packed ushr 40).toInt() and 15) shl 2)) and 15)
+ ((lookup ushr (((packed ushr 44).toInt() and 15) shl 2)) and 15)
+ ((lookup ushr (((packed ushr 48).toInt() and 15) shl 2)) and 15)
+ ((lookup ushr (((packed ushr 52).toInt() and 15) shl 2)) and 15)
+ ((lookup ushr (((packed ushr 56).toInt() and 15) shl 2)) and 15)
+ ((lookup ushr (((packed ushr 60).toInt() and 15) shl 2)) and 15))
}
return score
}
}
| 0 | Kotlin | 0 | 1 | 3f106415eeded3abd0fb60bed64fb77b4ab87d76 | 2,520 | aoc_kotlin | MIT License |
src/main/kotlin/adventofcode/year2020/Day24LobbyLayout.kt | pfolta | 573,956,675 | false | {"Kotlin": 199554, "Dockerfile": 227} | package adventofcode.year2020
import adventofcode.Puzzle
import adventofcode.PuzzleInput
import adventofcode.year2020.Day24LobbyLayout.Companion.TileColor.BLACK
import adventofcode.year2020.Day24LobbyLayout.Companion.TileColor.WHITE
class Day24LobbyLayout(customInput: PuzzleInput? = null) : Puzzle(customInput) {
private val tileMap by lazy {
input.lines()
.asSequence()
.map { tile -> DIRECTION_REGEX.findAll(tile).toList().map { it.value }.mapNotNull(DIRECTIONS::get) }
.map { it.reduce { tile, direction -> tile.first + direction.first to tile.second + direction.second } }
.fold(emptyMap<Pair<Int, Int>, TileColor>()) { tiles, tile ->
when (tiles[tile]) {
BLACK -> tiles + (tile to WHITE)
else -> tiles + (tile to BLACK)
}
}
}
override fun partOne() = tileMap.values.count { it == BLACK }
override fun partTwo() = generateSequence(tileMap) { previous ->
previous + previous.map { (tile, _) ->
(listOf(tile) + tile.neighbors())
.mapNotNull { position ->
val color = previous.getOrDefault(position, WHITE)
val blackNeighbors = position.neighbors().filter { previous.getOrDefault(it, WHITE) == BLACK }
if (color == BLACK && (blackNeighbors.isEmpty() || blackNeighbors.size > 2)) {
position to WHITE
} else if (color == WHITE && blackNeighbors.size == 2) {
position to BLACK
} else {
null
}
}
.toMap()
}.reduce { tileMap, partialTileMap -> tileMap + partialTileMap }
}
.drop(1)
.take(100)
.last()
.values
.count { it == BLACK }
companion object {
private val DIRECTION_REGEX = "(e|se|sw|w|nw|ne)".toRegex()
private val DIRECTIONS = mapOf(
"e" to Pair(2, 0),
"se" to Pair(1, -1),
"sw" to Pair(-1, -1),
"w" to Pair(-2, 0),
"nw" to Pair(-1, 1),
"ne" to Pair(1, 1)
)
private enum class TileColor {
BLACK,
WHITE
}
private fun Pair<Int, Int>.neighbors() = DIRECTIONS.values.map { first + it.first to second + it.second }
}
}
| 0 | Kotlin | 0 | 0 | 72492c6a7d0c939b2388e13ffdcbf12b5a1cb838 | 2,449 | AdventOfCode | MIT License |
src/Day09.kt | mikemac42 | 573,071,179 | false | {"Kotlin": 45264} | import java.io.File
fun main() {
val testInput = """R 4
U 4
L 3
D 1
R 4
D 1
L 5
R 2"""
val testInput2 = """R 5
U 8
L 8
D 3
R 17
D 10
L 25
U 20"""
val realInput = File("src/Day09.txt").readText()
val part1TestOutput = numPositionsTailVisited(testInput, 2)
println("Part 1 Test Output: $part1TestOutput")
check(part1TestOutput == 13)
val part1RealOutput = numPositionsTailVisited(realInput, 2)
println("Part 1 Real Output: $part1RealOutput")
val part2TestOutput = numPositionsTailVisited(testInput2, 10)
println("Part 2 Test Output: $part2TestOutput")
check(part2TestOutput == 36)
println("Part 2 Real Output: ${numPositionsTailVisited(realInput, 10)}")
}
data class Knot(var x: Int, var y: Int) {
fun follow(leader: Knot) {
val hDiff = leader.x - x
val vDiff = leader.y - y
when {
hDiff < -1 -> when {
vDiff < 0 -> {
x--; y--
}
vDiff > 0 -> {
x--; y++
}
else -> x--
}
hDiff == -1 -> when {
vDiff < -1 -> {
x--;y--
}
vDiff > 1 -> {
x--;y++
}
}
hDiff == 0 -> when {
vDiff < -1 -> y--
vDiff > 1 -> y++
}
hDiff == 1 -> when {
vDiff < -1 -> {
x++; y--
}
vDiff > 1 -> {
x++; y++
}
}
hDiff > 1 -> when {
vDiff < 0 -> {
x++; y--
}
vDiff > 0 -> {
x++; y++
}
else -> x++
}
}
}
}
/**
* Head (H) and tail (T) must always be touching (diagonally adjacent and even overlapping both count as touching).
* If the head is ever two steps directly up, down, left, or right from the tail,
* the tail must also move one step in that direction.
* If the head and tail aren't touching and aren't in the same row or column,
* the tail always moves one step diagonally.
* Head and the tail both start at the same position, overlapping.
*/
fun numPositionsTailVisited(input: String, numKnots: Int): Int {
val knots = (1..numKnots).map { Knot(0, 0) }
val tailPositionsVisited = mutableSetOf(0 to 0)
input.lines().flatMap { line ->
(1..line.substring(2).toInt()).map { line[0] }
}.forEach { dir ->
when (dir) {
'L' -> knots[0].x--
'R' -> knots[0].x++
'U' -> knots[0].y++
else -> knots[0].y--
}
knots.indices.forEach { index ->
if (index > 0) knots[index].follow(knots[index - 1])
}
tailPositionsVisited.add(knots.last().x to knots.last().y)
}
return tailPositionsVisited.size
}
| 0 | Kotlin | 1 | 0 | 909b245e4a0a440e1e45b4ecdc719c15f77719ab | 2,577 | advent-of-code-2022 | Apache License 2.0 |
src/Day02/Day02.kt | ctlevi | 578,257,705 | false | {"Kotlin": 10889} | enum class PlayOption {
ROCK, PAPER, SCISSORS
}
enum class OutcomeOption {
LOSE, DRAW, WIN
}
fun main() {
val LOSE_SCORE = 0
val DRAW_SCORE = 3
val WIN_SCORE = 6
val ROCK_SCORE = 1
val PAPER_SCORE = 2
val SCISSOR_SCORE = 3
fun convertToPlayOption(option: String): PlayOption {
return when (option) {
"A", "X" -> PlayOption.ROCK
"B", "Y" -> PlayOption.PAPER
"C", "Z" -> PlayOption.SCISSORS
else -> throw Exception("bad input: ${option}")
}
}
fun convertToOutcomeOption(option: String): OutcomeOption {
return when (option) {
"X" -> OutcomeOption.LOSE
"Y" -> OutcomeOption.DRAW
"Z" -> OutcomeOption.WIN
else -> throw Exception("bad input: ${option}")
}
}
fun roundScore(opponentPlay: PlayOption, myPlay: PlayOption): Int {
return when (opponentPlay) {
PlayOption.ROCK -> when(myPlay) {
PlayOption.ROCK -> ROCK_SCORE + DRAW_SCORE
PlayOption.PAPER -> PAPER_SCORE + WIN_SCORE
PlayOption.SCISSORS -> SCISSOR_SCORE + LOSE_SCORE
}
PlayOption.PAPER -> when(myPlay) {
PlayOption.ROCK -> ROCK_SCORE + LOSE_SCORE
PlayOption.PAPER -> PAPER_SCORE + DRAW_SCORE
PlayOption.SCISSORS -> SCISSOR_SCORE + WIN_SCORE
}
PlayOption.SCISSORS -> when(myPlay) {
PlayOption.ROCK -> ROCK_SCORE + WIN_SCORE
PlayOption.PAPER -> PAPER_SCORE + LOSE_SCORE
PlayOption.SCISSORS -> SCISSOR_SCORE + DRAW_SCORE
}
}
}
fun part2RoundScore(opponentPlay: PlayOption, myPlay: OutcomeOption): Int {
return when(opponentPlay) {
PlayOption.ROCK -> when(myPlay) {
OutcomeOption.LOSE -> SCISSOR_SCORE + LOSE_SCORE
OutcomeOption.DRAW -> ROCK_SCORE + DRAW_SCORE
OutcomeOption.WIN -> PAPER_SCORE + WIN_SCORE
}
PlayOption.PAPER -> when(myPlay) {
OutcomeOption.LOSE -> ROCK_SCORE + LOSE_SCORE
OutcomeOption.DRAW -> PAPER_SCORE + DRAW_SCORE
OutcomeOption.WIN -> SCISSOR_SCORE + WIN_SCORE
}
PlayOption.SCISSORS -> when(myPlay) {
OutcomeOption.LOSE -> PAPER_SCORE + LOSE_SCORE
OutcomeOption.DRAW -> SCISSOR_SCORE + DRAW_SCORE
OutcomeOption.WIN -> ROCK_SCORE + WIN_SCORE
}
}
}
fun part1(input: List<String>): Int {
val roundScores = input.map {
val (opponentPlay, myPlay) = it.split(" ")
roundScore(convertToPlayOption(opponentPlay), convertToPlayOption(myPlay))
}
return roundScores.sum();
}
fun part2(input: List<String>): Int {
val roundScores = input.map {
val (opponentPlay, myPlay) = it.split(" ")
part2RoundScore(convertToPlayOption(opponentPlay), convertToOutcomeOption(myPlay))
}
return roundScores.sum();
}
val testInput = readInput("Day02/test")
val testResult = part1(testInput)
"Test Result: ${testResult}".println()
val input = readInput("Day02/input")
"Part 1 Result: ${part1(input)}".println()
"Part 2 Result: ${part2(input)}".println()
}
| 0 | Kotlin | 0 | 0 | 0fad8816e22ec0df9b2928983713cd5c1ac2d813 | 3,399 | advent_of_code_2022 | Apache License 2.0 |
src/exercises/Day03.kt | Njko | 572,917,534 | false | {"Kotlin": 53729} | // ktlint-disable filename
package exercises
import readInput
const val ASCII_LOWER_CASE_SHIFT = 96
const val ASCII_UPPER_CASE_SHIFT = 64
const val LOWER_UPPERCASE_OFFSET = 26
fun main() {
fun getItemPriority(equalItem: Char) = if (equalItem.isLowerCase()) {
equalItem.code - ASCII_LOWER_CASE_SHIFT
} else {
equalItem.code - ASCII_UPPER_CASE_SHIFT + LOWER_UPPERCASE_OFFSET
}
fun part1(input: List<String>): Int {
return input.sumOf { rucksack ->
val compartments = rucksack.chunked(rucksack.length / 2)
val equalItem = compartments[0]
.firstNotNullOf { item ->
item.takeIf {
compartments[1].contains(item)
}
}
getItemPriority(equalItem)
}
}
fun part2(input: List<String>): Int {
return input.chunked(3)
.map { group ->
group[0].firstNotNullOf { item ->
item.takeIf {
group[1].contains(item) && group[2].contains(item)
}
}
}
.sumOf { getItemPriority(it) }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
println("Test results:")
println(part1(testInput))
check(part1(testInput) == 157)
println(part2(testInput))
check(part2(testInput) == 70)
val input = readInput("Day03")
println("Final results:")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 2 | 68d0c8d0bcfb81c183786dfd7e02e6745024e396 | 1,591 | advent-of-code-2022 | Apache License 2.0 |
src/day01/Day01.kt | lpleo | 572,702,403 | false | {"Kotlin": 30960} | package day01
import readInput
fun main() {
fun getMaxCaloriesList(input: List<String>): MutableList<Int> {
val maxCaloriesList: MutableList<Int> = mutableListOf(0);
input.forEach {
if (it.isNotEmpty()) {
maxCaloriesList[maxCaloriesList.lastIndex] = maxCaloriesList[maxCaloriesList.lastIndex] + Integer.parseInt(it);
} else {
maxCaloriesList.add(0);
}
}
return maxCaloriesList
}
fun part1(input: List<String>): Int {
val maxCaloriesList: MutableList<Int> = getMaxCaloriesList(input)
return maxCaloriesList.max().or(0)
}
fun part2(input: List<String>): Int {
val maxCaloriesList = getMaxCaloriesList(input)
val maxCaloriesOrderedList = maxCaloriesList.sortedDescending()
return maxCaloriesOrderedList[0] + maxCaloriesOrderedList[1] + maxCaloriesOrderedList[2]
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("files/Day01_test")
check(part1(testInput) == 8)
check(part2(testInput) == 17)
val input = readInput("files/Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 115aba36c004bf1a759b695445451d8569178269 | 1,217 | advent-of-code-2022 | Apache License 2.0 |
src/Day02.kt | tsdenouden | 572,703,357 | false | {"Kotlin": 8295} | fun main() {
var playerScore = 0
val playerMoveMap: Map<Char, Int> = mapOf(
'X' to 1,
'Y' to 2,
'Z' to 3
)
val botMoveMap: Map<Char, Int> = mapOf(
'A' to 1,
'B' to 2,
'C' to 3
)
fun playerWin() {
playerScore += 6
}
// compare player's move (1,2,3) to opponent's move (1,2,3)
// Win -> +6 pts
// Draw -> +3 pts
// Lose -> +0pts
fun compareMoves(playerMove: Int, botMove: Int) {
// add points from the move:
// (Rock -> 1 pt, Paper -> 2pts, Scissors -> 3pts)
playerScore += playerMove
// check for wins
when (playerMove) {
1 -> if (botMove == 3) playerWin()
2 -> if (botMove == 1) playerWin()
3 -> if (botMove == 2) playerWin()
}
// check for draw
if (playerMove == botMove) playerScore += 3
}
fun part1(input: List<String>): Int {
playerScore = 0
input.forEach { line ->
val playerMove: Int? = playerMoveMap[line[2]]
val botMove: Int? = botMoveMap[line[0]]
if (playerMove != null && botMove != null) {
// Compare moves with opponent to update the score
compareMoves(playerMove, botMove)
}
}
return playerScore
}
fun part2(input: List<String>): Int {
playerScore = 0
input.forEach { line ->
var playerMove: Int? = playerMoveMap[line[2]]
val botMove: Int? = botMoveMap[line[0]]
val playerAction = line[2]
if (playerMove != null && botMove != null) {
// Change player's move (1,2,3) depending on the type of action given
// X -> Lose
// Y -> Draw
// Z -> Win
when (playerAction) {
'X' -> {
playerMove = botMove - 1
if (playerMove <= 0) playerMove = 3
}
'Y' -> playerMove = botMove
'Z' -> {
playerMove = botMove + 1
if (playerMove >= 4) playerMove = 1
}
}
// Compare moves with opponent to update the score
compareMoves(playerMove, botMove)
}
}
return playerScore
}
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 68982ebffc116f3b49a622d81e725c8ad2356fed | 2,628 | aoc-2022-kotlin | Apache License 2.0 |
day08/src/Day08.kt | simonrules | 491,302,880 | false | {"Kotlin": 68645} | import com.sun.xml.internal.fastinfoset.util.StringArray
import java.io.File
class Day08(private val path: String) {
fun part1(): Int {
var unique = 0
File(path).forEachLine {
val parts = it.split(" | ")
val output = parts[1].split(' ')
output.forEach { part ->
when (part.length) {
2, 3, 4, 7 -> unique++
}
}
}
return unique
}
fun part2(): Long {
val digits = Array(10) { mutableSetOf<Char>() }
var total = 0L
File(path).forEachLine {
val parts = it.split(" | ")
val pattern = parts[0].split(' ')
// first pass
pattern.forEach { part ->
val set = part.toSortedSet()
when (part.length) {
2 -> digits[1] = set
3 -> digits[7] = set
4 -> digits[4] = set
7 -> digits[8] = set
}
}
// second pass
pattern.forEach { part ->
val set = part.toSortedSet()
when (part.length) {
5 -> {
if (set.containsAll(digits[1])) {
digits[3] = set
} else {
if (set.plus(digits[4]).size == 7) {
digits[2] = set
} else {
digits[5] = set
}
}
}
}
}
// third pass
pattern.forEach { part ->
val set = part.toSortedSet()
when (part.length) {
6 -> {
if (set.containsAll(digits[1])) {
if (set.containsAll(digits[5])) {
digits[9] = set
} else {
digits[0] = set
}
} else {
digits[6] = set
}
}
}
}
val map = mutableMapOf<MutableSet<Char>, Int>()
digits.forEachIndexed { index, mutableSet ->
map[mutableSet] = index
}
val output = parts[1].split(' ')
var value = 0
output.forEach { part ->
val set = part.toSortedSet()
value *= 10
value += map[set]!!
}
total += value
}
return total
}
}
fun main(args: Array<String>) {
val aoc = Day08("day08/input.txt")
println(aoc.part1())
println(aoc.part2())
}
| 0 | Kotlin | 0 | 0 | d9e4ae66e546f174bcf66b8bf3e7145bfab2f498 | 2,866 | aoc2021 | Apache License 2.0 |
Algo_Ds_Notes-master/Algo_Ds_Notes-master/Knuth_Morris_Pratt_Algorithm/KMP.kt | rajatenzyme | 325,100,742 | false | {"C++": 709855, "Java": 559443, "Python": 397216, "C": 381274, "Jupyter Notebook": 127469, "Go": 123745, "Dart": 118962, "JavaScript": 109884, "C#": 109817, "Ruby": 86344, "PHP": 63402, "Kotlin": 52237, "TypeScript": 21623, "Rust": 20123, "CoffeeScript": 13585, "Julia": 2385, "Shell": 506, "Erlang": 385, "Scala": 310, "Clojure": 189} | /*
<NAME> String Searching Algorithm
Given a text txt[0..n-1] and a pattern pat[0..m-1], the algo will find all occurrences of pat[] in txt[]
*/
import java.util.*
internal class KMP {
fun kmpSearch(pat: String, txt: String) {
val m = pat.length
val n = txt.length
// longest_prefix_suffix array
val lps = IntArray(m)
// index for pat[]
var j = 0
//calculate lps[] array
computeLPSArray(pat, m, lps)
//index for txt[]
var i = 0
while (i < n) {
if (pat[j] == txt[i]) {
j++
i++
}
if (j == m) {
println("Found pattern at index" + (i - j))
j = lps[j - 1]
} else if (i < n && pat[j] != txt[i]) {
if (j != 0) j = lps[j - 1] else i += 1
}
}
}
// length of the previous longest prefix suffix
private fun computeLPSArray(pat: String, M: Int, lps: IntArray) {
var len = 0
var i = 1
//lps[0] is always 0
lps[0] = 0
//calculate lps[i] for i=1 to M-1
while (i < M)
{
if (pat[i] == pat[len]) {
len++
lps[i] = len
i++
}
else {
if (len != 0) len = lps[len - 1] else {
lps[i] = len
i++
}
}
}
}
companion object {
//Driver program to test above function
@JvmStatic
fun main(args: Array<String>) {
val sc = Scanner(System.`in`)
val txt = sc.nextLine()
val pat = sc.nextLine()
KMP().kmpSearch(pat, txt)
}
}
}
/*
Sample Input
namanchamanbomanamansanam
aman
Sample Output:
Patterns occur at shift = 1
Patterns occur at shift = 7
Patterns occur at shift = 16
*/
| 0 | C++ | 0 | 0 | 65a0570153b7e3393d78352e78fb2111223049f3 | 1,964 | Coding-Journey | MIT License |
Three_Sum_Closest_v1.kt | xiekch | 166,329,519 | false | {"C++": 165148, "Java": 103273, "Kotlin": 97031, "Go": 40017, "Python": 22302, "TypeScript": 17514, "Swift": 6748, "Rust": 6579, "JavaScript": 4244, "Makefile": 349} | import kotlin.math.absoluteValue
class Solution {
private fun findClosetDiff(nums: IntArray, target: Int, low: Int): Int {
var diff = Int.MAX_VALUE
var high = nums.size - 1
var low = low
// println("$low $high")
while (low <= high) {
val middle = (low + high) / 2
val num = nums[(low + high) / 2]
if (num == target) {
diff = 0
break
} else if (num > target) {
if (num - target < diff.absoluteValue) {
diff = num - target
}
high = middle - 1
} else {
if (target - num < diff.absoluteValue) {
diff = num - target
}
low = middle + 1
}
}
return diff
}
fun threeSumClosest(nums: IntArray, target: Int): Int {
nums.sort()
var diff = Int.MAX_VALUE
for (i in nums.indices) {
for (j in i + 1 until nums.size) {
val t = findClosetDiff(nums, target - (nums[i] + nums[j]), j + 1)
if (t.absoluteValue < diff.absoluteValue) {
// println("${nums[i]} ${nums[j]} $diff $t")
diff = t
if (diff == 0) break
}
}
}
return target + diff
}
}
fun main(args: Array<String>) {
val solution = Solution()
val testset = arrayOf(intArrayOf(-1, 2, 1, -4),//2
intArrayOf(0, 1, 2),//3
intArrayOf(1, -3, 3, 5, 4, 1))//1
val targets = intArrayOf(1, 3, 1)
for (i in testset.indices) {
println(solution.threeSumClosest(testset[i], targets[i]))
}
} | 0 | C++ | 0 | 0 | eb5b6814e8ba0847f0b36aec9ab63bcf1bbbc134 | 1,746 | leetcode | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/VerifyingAlienDictionary.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2021 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import dev.shtanko.algorithms.ALPHABET_LETTERS_COUNT
/**
* Verifying an Alien Dictionary
* @see <a href="https://leetcode.com/problems/verifying-an-alien-dictionary/">Source</a>
*/
fun interface VerifyingAlienDictionary {
operator fun invoke(words: Array<String>, order: String): Boolean
}
class VerifyingAlienDictionaryCompare : VerifyingAlienDictionary {
override fun invoke(words: Array<String>, order: String): Boolean {
val orderMap = IntArray(ALPHABET_LETTERS_COUNT)
for (i in order.indices) {
orderMap[order[i] - 'a'] = i
}
for (i in 0 until words.size - 1) {
for (j in 0 until words[i].length) {
// If we do not find a mismatch letter between words[i] and words[i + 1],
// we need to examine the case when words are like ("apple", "app").
if (j >= words[i + 1].length) return false
if (words[i][j] != words[i + 1][j]) {
val currentWordChar: Int = words[i][j] - 'a'
val nextWordChar: Int = words[i + 1][j] - 'a'
return if (orderMap[currentWordChar] > orderMap[nextWordChar]) {
false
} else {
break
}
}
}
}
return true
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,001 | kotlab | Apache License 2.0 |
src/main/kotlin/g1801_1900/s1856_maximum_subarray_min_product/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g1801_1900.s1856_maximum_subarray_min_product
// #Medium #Array #Stack #Prefix_Sum #Monotonic_Stack
// #2023_06_22_Time_517_ms_(66.67%)_Space_57.4_MB_(66.67%)
class Solution {
fun maxSumMinProduct(nums: IntArray): Int {
val n = nums.size
val mod = (1e9 + 7).toInt()
if (n == 1) {
return (nums[0].toLong() * nums[0].toLong() % mod).toInt()
}
val left = IntArray(n)
left[0] = -1
for (i in 1 until n) {
var p = i - 1
while (p >= 0 && nums[p] >= nums[i]) {
p = left[p]
}
left[i] = p
}
val right = IntArray(n)
right[n - 1] = n
for (i in n - 2 downTo 0) {
var p = i + 1
while (p < n && nums[p] >= nums[i]) {
p = right[p]
}
right[i] = p
}
var res = 0L
val preSum = LongArray(n)
preSum[0] = nums[0].toLong()
for (i in 1 until n) {
preSum[i] = preSum[i - 1] + nums[i]
}
for (i in 0 until n) {
val sum = if (left[i] == -1) preSum[right[i] - 1] else preSum[right[i] - 1] - preSum[left[i]]
val cur = nums[i] * sum
res = Math.max(cur, res)
}
return (res % mod).toInt()
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,326 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/day6.kt | danielfreer | 297,196,924 | false | null | import kotlin.time.ExperimentalTime
@ExperimentalTime
fun day6(input: List<String>): List<Solution> {
return listOf(
solve(6, 1) { countTotalOrbits(input) }
)
}
fun countTotalOrbits(orbitMap: List<String>): Int {
val rootNode = parseRootNode(orbitMap)
val directOrbits = countDirectOrbits(rootNode)
val indirectOrbits = countIndirectOrbits(rootNode)
return directOrbits + indirectOrbits
}
data class Node(val id: String, var parent: Node? = null, val children: MutableList<Node> = mutableListOf()) {
fun allChildren(): List<Node> = children + children.flatMap { it.allChildren() }
fun pathToParent(parentId: String, path: List<Node> = emptyList()): List<Node> {
return if (id == parentId) {
path
} else {
parent?.pathToParent(parentId, path + this) ?: path
}
}
override fun toString() = "Node(id=$id, parent=${parent?.id}, children=$children)"
}
fun parseRootNode(orbitMap: List<String>): Node {
@Suppress("ReplaceGetOrSet")
return orbitMap
.map { it.split(")") }
.fold(mutableMapOf<String, Node>()) { nodes, ids ->
val parentNode = nodes.compute(ids.first()) { id, node -> node ?: Node(id) }!!
val childNode = nodes.compute(ids.last()) { id, node -> node ?: Node(id) }!!
parentNode.children.add(childNode)
childNode.parent = parentNode
nodes
}
.get("COM")
?: throw IllegalStateException("Could not parse root node")
}
fun countDirectOrbits(rootNode: Node) = rootNode.allChildren().size
fun countIndirectOrbits(rootNode: Node): Int {
return rootNode.allChildren().sumBy { node ->
node.pathToParent(rootNode.id).size - 1
}
}
| 0 | Kotlin | 0 | 0 | 74371d15f95492dee1ac434f0bfab3f1160c5d3b | 1,752 | advent2019 | The Unlicense |
year2021/day07/part1/src/main/kotlin/com/curtislb/adventofcode/year2021/day07/part1/Year2021Day07Part1.kt | curtislb | 226,797,689 | false | {"Kotlin": 2146738} | /*
--- Day 7: The Treachery of Whales ---
A giant whale has decided your submarine is its next meal, and it's much faster than you are.
There's nowhere to run!
Suddenly, a swarm of crabs (each in its own tiny submarine - it's too deep for them otherwise) zooms
in to rescue you! They seem to be preparing to blast a hole in the ocean floor; sensors indicate a
massive underground cave system just beyond where they're aiming!
The crab submarines all need to be aligned before they'll have enough power to blast a large enough
hole for your submarine to get through. However, it doesn't look like they'll be aligned before the
whale catches you! Maybe you can help?
There's one major catch - crab submarines can only move horizontally.
You quickly make a list of the horizontal position of each crab (your puzzle input). Crab submarines
have limited fuel, so you need to find a way to make all of their horizontal positions match while
requiring them to spend as little fuel as possible.
For example, consider the following horizontal positions:
```
16,1,2,0,4,2,7,1,2,14
```
This means there's a crab with horizontal position 16, a crab with horizontal position 1, and so on.
Each change of 1 step in horizontal position of a single crab costs 1 fuel. You could choose any
horizontal position to align them all on, but the one that costs the least fuel is horizontal
position 2:
- Move from 16 to 2: 14 fuel
- Move from 1 to 2: 1 fuel
- Move from 2 to 2: 0 fuel
- Move from 0 to 2: 2 fuel
- Move from 4 to 2: 2 fuel
- Move from 2 to 2: 0 fuel
- Move from 7 to 2: 5 fuel
- Move from 1 to 2: 1 fuel
- Move from 2 to 2: 0 fuel
- Move from 14 to 2: 12 fuel
This costs a total of 37 fuel. This is the cheapest possible outcome; more expensive outcomes
include aligning at position 1 (41 fuel), position 3 (39 fuel), or position 10 (71 fuel).
Determine the horizontal position that the crabs can align to using the least fuel possible. How
much fuel must they spend to align to that position?
*/
package com.curtislb.adventofcode.year2021.day07.part1
import com.curtislb.adventofcode.common.number.medianOrNull
import com.curtislb.adventofcode.common.parse.parseInts
import java.nio.file.Path
import java.nio.file.Paths
import kotlin.math.abs
/**
* Returns the solution to the puzzle for 2021, day 7, part 1.
*
* @param inputPath The path to the input file for this puzzle.
*/
fun solve(inputPath: Path = Paths.get("..", "input", "input.txt")): Int {
val positions = inputPath.toFile().readText().parseInts()
val bestPosition = positions.medianOrNull() ?: 0
return positions.sumOf { abs(it - bestPosition) }
}
fun main() {
println(solve())
}
| 0 | Kotlin | 1 | 1 | 6b64c9eb181fab97bc518ac78e14cd586d64499e | 2,672 | AdventOfCode | MIT License |
src/main/kotlin/aoc2022/Day20.kt | davidsheldon | 565,946,579 | false | {"Kotlin": 161960} | package aoc2022
import utils.InputUtils
import kotlin.math.absoluteValue
class DoubleLinkedList<T>(initialContent: List<T>) {
var head: Node<T>
val size = initialContent.size
init {
val nodes = initialContent.map { Node(it) }
nodes.zipWithNext { a,b ->
a.right = b
b.left = a
}
nodes.first().left = nodes.last()
nodes.last().right = nodes.first()
head = nodes.first()
}
class Node<T>(val n: T) {
lateinit var right: Node<T>
lateinit var left: Node<T>
override fun toString(): String {
return n.toString()
}
fun moveRight() {
val l = left;
val r = right;
l.right = r
right.left = l
right = r.right
right.left = this
r.right = this
left = r
}
fun moveLeft() {
val l = left;
val r = right;
r.left = l
left.right = r
left = l.left
left.right = this
l.left = this
right = l
}
}
fun moveRight(node: Node<T>) {
node.moveRight()
if (node == head) head = node.left
}
fun moveLeft(node: Node<T>) {
node.moveLeft()
if (head.left == node) head = node
}
override fun toString(): String {
return asSequence().toList().toString()
}
fun asSequence() = sequence {
var pos = head;
do {
yield(pos)
pos = pos.right
} while (pos != head)
}
fun asValueSequence() = asSequence().map { it.n }
}
fun main() {
val testInput = """1
2
-3
3
-2
0
4""".split("\n")
fun mix(l: DoubleLinkedList<Int>) {
val values = l.asSequence().toList()
values.forEach { n ->
repeat(n.n.absoluteValue % (values.size-1)) {
if (n.n > 0) l.moveRight(n) else l.moveLeft(n)
}
}
}
fun mix(l: DoubleLinkedList<Long>, times: Int) {
val values = l.asSequence().toList()
repeat(times) {
values.forEach { n ->
repeat((n.n.absoluteValue % (values.size-1)).toInt()) {
if (n.n > 0) l.moveRight(n) else l.moveLeft(n)
}
}
}
}
fun part1(input: List<String>): Int {
var list = DoubleLinkedList(input.map { it.toInt() })
mix(list)
val coordinates = list.asValueSequence().repeatForever()
.dropWhile { it != 0 }
.filterIndexed{index, _ -> index % 1000 == 0}.drop(1).take(3).toList()
println(coordinates)
return coordinates.sum()
}
fun part2(input: List<String>): Long {
var list = DoubleLinkedList(input.map { it.toInt() * 811589153L })
mix(list, 10)
val coordinates = list.asValueSequence().repeatForever()
.dropWhile { it != 0L }
.filterIndexed{index, _ -> index % 1000 == 0} .drop(1).take(3).toList()
println(coordinates)
return coordinates.sum()
}
val testValue = part1(testInput)
println(testValue)
check(testValue == 3)
val puzzleInput = InputUtils.downloadAndGetLines(2022, 20).toList()
println(part1(puzzleInput))
println(part2(testInput))
println(part2(puzzleInput))
}
| 0 | Kotlin | 0 | 0 | 5abc9e479bed21ae58c093c8efbe4d343eee7714 | 3,382 | aoc-2022-kotlin | Apache License 2.0 |
src/main/kotlin/com/groundsfam/advent/y2021/d05/Day05.kt | agrounds | 573,140,808 | false | {"Kotlin": 281620, "Shell": 742} | package com.groundsfam.advent.y2021.d05
import com.groundsfam.advent.DATAPATH
import com.groundsfam.advent.points.Point
import com.groundsfam.advent.timed
import kotlin.io.path.div
import kotlin.io.path.useLines
fun range(from: Point, to: Point): List<Point> {
val xStep = when {
from.x < to.x -> 1
from.x > to.x -> -1
else -> 0
}
val yStep = when {
from.y < to.y -> 1
from.y > to.y -> -1
else -> 0
}
return mutableListOf<Point>().apply {
var p = from
add(p)
while (p != to) {
p += Point(xStep, yStep)
add(p)
}
}
}
fun findOverlaps(ventLines: List<Pair<Point, Point>>, includeDiagonals: Boolean): Int {
val ventPoints = mutableSetOf<Point>()
val overlapPoints = mutableSetOf<Point>()
ventLines.forEach { (from, to) ->
if (includeDiagonals || from.x == to.x || from.y == to.y) {
range(from, to).forEach { point ->
if (!ventPoints.add(point)) {
overlapPoints.add(point)
}
}
}
}
return overlapPoints.size
}
fun main() = timed {
val ventLines = (DATAPATH / "2021/day05.txt").useLines { lines ->
lines.toList().map { line ->
val (first, _, second) = line.split(" ")
fun String.toPoint() = this.split(",").map { it.toInt() }.let { (x, y) -> Point(x, y) }
first.toPoint() to second.toPoint()
}
}
println("Part one: ${findOverlaps(ventLines, false)}")
println("Part two: ${findOverlaps(ventLines, true)}")
}
| 0 | Kotlin | 0 | 1 | c20e339e887b20ae6c209ab8360f24fb8d38bd2c | 1,616 | advent-of-code | MIT License |
src/Day25.kt | jordan-thirus | 573,476,470 | false | {"Kotlin": 41711} | import kotlin.math.pow
fun main() {
fun String.toLong(verbose: Boolean): Long {
var num = 0L
this.reversed().forEachIndexed{ index, c ->
val value = 5.0.pow(index).toLong()
when(c) {
'=' -> num -= value * 2
'-' -> num -= value
else -> num += value * c.digitToInt()
}
}
printVerbose("SNAFU: $this, Decimal: $num", verbose)
return num
}
fun Long.toSnafu(verbose: Boolean): String{
val encode = "012=-"
var working = this
var snafu = ""
while(working != 0L){
val rem = (working % 5).toInt()
snafu = encode[rem] + snafu
working = (working + when(rem){
4 -> 1
3 -> 2
else -> 0
}) / 5
}
printVerbose("Decimal: $this, SNAFU: $snafu", verbose)
return snafu
}
fun part1(input: List<String>, verbose: Boolean) =
input.sumOf { it.toLong(verbose) }.toSnafu(verbose)
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day25_test")
check(part1(testInput, false) == "2=-1=0")
val input = readInput("Day25")
println(part1(input, false))
}
| 0 | Kotlin | 0 | 0 | 59b0054fe4d3a9aecb1c9ccebd7d5daa7a98362e | 1,300 | advent-of-code-2022 | Apache License 2.0 |
ceria/03/src/main/kotlin/Solution.kt | VisionistInc | 572,963,504 | false | null | import java.io.File;
val charPriorities = "-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toList()
fun main(args : Array<String>) {
var input = File(args.first()).readLines()
println("Solution 1: ${solution1(input)}")
println("Solution 2: ${solution2(input)}")
}
private fun solution1(input: List<String>) :Int {
return input.map{
it.chunked(it.length / 2)
}.map {
it.first().toList().intersect(it.last().toList()).first()
}.map{
charPriorities.indexOf(it)
}.sum()
}
private fun solution2(input: List<String>) :Int {
var priorities = mutableListOf<Char>()
repeat(input.size / 3) { count ->
var index = count * 3
var elf1 = input.get(index).toList()
var elf2 = input.get(index + 1).toList()
var elf3 = input.get(index + 2).toList()
priorities.add(elf1.intersect(elf2).intersect(elf3).first())
}
return priorities.map { charPriorities.indexOf(it) }.sum()
}
| 0 | Rust | 0 | 0 | 90b348d9c8060a8e967fe1605516e9c126fc7a56 | 984 | advent-of-code-2022 | MIT License |
src/Day11.kt | HaydenMeloche | 572,788,925 | false | {"Kotlin": 25699} | fun main() {
val partTwo = true
val input = readInput("Day11").toMutableList()
val monkeys = mutableMapOf<Int, Monkey>()
input.removeAll { it.isBlank() }
input.windowed(size = 6, step = 6).forEach { entry ->
val id = entry[0].substringBeforeLast(":")
.takeLastUntilSpace()
.toInt()
val startingItems = entry[1].substringAfter(":")
.split(",")
.map { it.trim().toLong() }
.toMutableList()
monkeys[id] = Monkey(id, startingItems, entry[2], entry.slice(3 until 6))
}
val rounds = if (partTwo) 10_000 else 20
repeat(rounds) {
monkeys.forEach { (_, monkey) ->
monkey.inspect(monkeys, partTwo)
}
}
val twoMostActiveMonkey = monkeys.values.sortedByDescending { it.inspectionCount }
if (partTwo) {
println("answer two: ")
} else println("answer one: ")
print("${twoMostActiveMonkey[0].inspectionCount * twoMostActiveMonkey[1].inspectionCount}")
}
class Monkey(var id: Int, var items: MutableList<Long>, operation: String, test: List<String>) {
var inspectionCount = 0L
private var operation: (worry: Long) -> Long
private var test: (worry: Long) -> Boolean
private var targetMonkeyIfTrue: Int
private var targetMonkeyIfFalse: Int
private var divider: Long
init {
val operationSplit = operation.split(" ")
val value = operationSplit[operationSplit.size - 1]
val modifier = operationSplit[operationSplit.size - 2]
this.operation = {
val computeBy = if (value == "old") it else value.toLong()
when (modifier) {
"+" -> it + computeBy
else -> it * computeBy
}
}
divider = test[0].takeLastUntilSpace().toLong()
this.test = {
it % test[0].takeLastUntilSpace().toLong() == 0L
}
targetMonkeyIfTrue = test[1].takeLastUntilSpace().toInt()
targetMonkeyIfFalse = test[2].takeLastUntilSpace().toInt()
}
fun inspect(monkeys: MutableMap<Int, Monkey>, partTwo: Boolean) {
items.forEach { item ->
inspectionCount++
var worryLevel = operation.invoke(item)
worryLevel = if (partTwo) {
val mod = monkeys.values.map { it.divider }.reduce(Long::times)
worryLevel % mod
} else worryLevel / 3
if (test(worryLevel)) {
monkeys[targetMonkeyIfTrue]!!.items.add(worryLevel)
} else monkeys[targetMonkeyIfFalse]!!.items.add(worryLevel)
}
items.clear()
}
} | 0 | Kotlin | 0 | 1 | 1a7e13cb525bb19cc9ff4eba40d03669dc301fb9 | 2,637 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/day08/Day08.kt | kerchen | 573,125,453 | false | {"Kotlin": 137233} | package day08
import readInput
class HeightMap(input: List<String>) {
var rows = mutableListOf<List<Int>>()
var rowCount = 0
var columnCount = 0
init {
for (row in input) {
rows.add(row.map { it.code - '0'.code })
}
rowCount = rows.size
columnCount = rows[0].size
}
fun countVisible(): Int {
var visibleTrees = rowCount * 2 + columnCount * 2 - 4 // Edge trees are visible automatically
for (row in IntRange(1, rowCount - 2)) {
for (column in IntRange(1, columnCount - 2)) {
val height = rows[row][column]
if (height == 0 )
continue
var blocked = false
// Look West
for (i in IntRange(0, column - 1)) {
if (rows[row][i] >= height) {
blocked = true
break
}
}
// Look East
if (blocked) {
blocked = false
for (i in IntRange(column + 1, columnCount - 1)) {
if (rows[row][i] >= height) {
blocked = true
break
}
}
}
// Look North
if (blocked) {
blocked = false
for (j in IntRange(0, row - 1)) {
if (rows[j][column] >= height) {
blocked = true
break
}
}
}
// Look South
if (blocked) {
blocked = false
for (j in IntRange(row + 1, rowCount - 1)) {
if (rows[j][column] >= height) {
blocked = true
break
}
}
}
if (! blocked) {
visibleTrees += 1
}
}
}
return visibleTrees
}
fun computeBestScenicScore(): Int {
var bestScore = 0
for (row in IntRange(1, rowCount - 2)) {
for (column in IntRange(1, columnCount - 2)) {
val height = rows[row][column]
if (height == 0 )
continue
var score = 0
var rangeEnd = 0
// Look West
rangeEnd = column
for (i in IntRange(1, rangeEnd)) {
if (rows[row][column-i] >= height || i == rangeEnd) {
score = i
break
}
}
// Look East
rangeEnd = columnCount - column - 1
for (i in IntRange(1, rangeEnd)) {
if (rows[row][column+i] >= height || i == rangeEnd) {
score *= i
break
}
}
// Look North
rangeEnd = row
for (j in IntRange(1, rangeEnd)) {
if (rows[row-j][column] >= height || j == rangeEnd) {
score *= j
break
}
}
// Look South
rangeEnd = rowCount - row - 1
for (j in IntRange(1, rangeEnd)) {
if (rows[row+j][column] >= height || j == rangeEnd) {
score *= j
break
}
}
if (score > bestScore) {
bestScore = score
}
}
}
return bestScore
}
}
fun main() {
fun part1(input: List<String>): Int = HeightMap(input).countVisible()
fun part2(input: List<String>): Int = HeightMap(input).computeBestScenicScore()
val testInput = readInput("Day08_test")
check(part1(testInput) == 21)
check(part2(testInput) == 8)
val input = readInput("Day08")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | dc15640ff29ec5f9dceb4046adaf860af892c1a9 | 4,269 | AdventOfCode2022 | Apache License 2.0 |
src/Day24/Day24.kt | martin3398 | 436,014,815 | false | {"Kotlin": 63436, "Python": 5921} | fun main() {
fun preprocess(input: List<String>): List<List<String>> {
return input.map { it.split(" ") }
}
fun split(input: List<List<String>>): MutableList<List<List<String>>> {
val blocks = mutableListOf<List<List<String>>>()
var block = mutableListOf<List<String>>()
for (e in input) {
if (e[0] == "inp") {
if (block.isNotEmpty()) {
blocks.add(block)
block = mutableListOf()
}
}
block.add(e)
}
blocks.add(block)
return blocks
}
fun doBackwardStep(block: List<List<String>>, w: Int, z: Int): List<Int> {
val divZ = block[4][2].toInt() // C
val addX = block[5][2].toInt() // A
val addY = block[15][2].toInt() // B
val res = mutableListOf<Int>()
val y0 = z - w - addY
if (y0 % 26 == 0) {
res.add(y0 / 26 * divZ)
}
if (w - addX in 0..25) {
val y1 = z * divZ
res.add(w - addX + y1)
}
return res
}
fun calc(blocks: List<List<List<String>>>, order: IntProgression): Long {
var res = mutableMapOf(0 to "")
for (block in blocks.reversed()) {
val resNew = mutableMapOf<Int, String>()
for ((z, inputStr) in res) for (w in order) {
val newZ = doBackwardStep(block, w, z)
resNew.putAll(newZ.map { it to w.toString() + inputStr })
}
res = resNew
}
return res[0]?.toLong() ?: throw IllegalStateException()
}
fun part1(input: List<List<String>>): Long {
val blocks = split(input)
return calc(blocks, 1..9)
}
fun part2(input: List<List<String>>): Long {
val blocks = split(input)
return calc(blocks, 9 downTo 1)
}
val input = preprocess(readInput(24))
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 085b1f2995e13233ade9cbde9cd506cafe64e1b5 | 1,978 | advent-of-code-2021 | Apache License 2.0 |
src/Day03.kt | rossilor95 | 573,177,479 | false | {"Kotlin": 8837} | fun main() {
fun Char.toPriority(): Int = when {
this.isLowerCase() -> this.code - 96 // UTF-16 codes for lowercase letters are 97..122
this.isUpperCase() -> this.code - 38 // UTF-16 codes for uppercase letters are 65..90
else -> error("Check your inputs!")
}
fun part1(input: List<String>) = input.map { rucksack ->
rucksack.substring(0 until rucksack.length / 2) to rucksack.substring(rucksack.length / 2)
}.flatMap { (first, second) ->
first.toSet() intersect second.toSet()
}.sumOf { it.toPriority() }
fun part2(input: List<String>) = input.chunked(3).flatMap { (rucksack1, rucksack2, rucksack3) ->
rucksack1.toSet() intersect rucksack2.toSet() intersect rucksack3.toSet()
}.sumOf { it.toPriority() }
val testInput = readInput("Day03_test")
val input = readInput("Day03")
check(part1(testInput) == 157)
println("Part 1 Answer: ${part1(input)}")
check(part2(testInput) == 70)
println("Part 2 Answer: ${part2(input)}")
} | 0 | Kotlin | 0 | 0 | 0ed98d0ab5f44b2ccfc625ef091e736c5c748ff0 | 1,036 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/day17/Day17.kt | pocmo | 433,766,909 | false | {"Kotlin": 134886} | package day17
import kotlin.math.max
data class TargetArea(
val xRange: IntRange,
val yRange: IntRange
) {
fun calculateResult(x: Int, y: Int): AreaResult {
return when {
y < yRange.minOrNull()!! -> AreaResult.MissBottom
x > xRange.maxOrNull()!! -> AreaResult.MissRight
xRange.contains(x) && yRange.contains(y) -> AreaResult.Hit
else -> AreaResult.Ongoing
}
}
}
data class Velocity(
val x: Int,
val y: Int
) {
fun simulate(): Velocity {
val newX = if (x > 0) {
x - 1
} else if (x < 0) {
x + 1
} else {
0
}
val newY = y - 1
return Velocity(newX, newY)
}
}
sealed interface AreaResult {
object Hit : AreaResult
object Ongoing : AreaResult
object MissBottom : AreaResult
object MissRight : AreaResult
}
sealed interface Result {
data class Hit(
val maxHeight: Int
) : Result
object MissBottom : Result
object MissRight : Result
}
fun AreaResult.toResult(
maxHeight: Int
): Result {
return when (this) {
is AreaResult.Ongoing -> throw IllegalStateException("Translating ongoing area result")
is AreaResult.Hit -> Result.Hit(maxHeight)
is AreaResult.MissBottom -> Result.MissBottom
is AreaResult.MissRight -> Result.MissRight
}
}
fun launchProbe(initial: Velocity, target: TargetArea): Result {
var x = initial.x
var y = initial.y
var velocity = initial
var maxHeight = initial.y
var areaResult: AreaResult = target.calculateResult(x, y)
while (areaResult is AreaResult.Ongoing) {
velocity = velocity.simulate()
x += velocity.x
y += velocity.y
areaResult = target.calculateResult(x, y)
maxHeight = max(maxHeight, y)
}
return areaResult.toResult(maxHeight)
}
data class VelocityResults(
val maxHeight: Int,
val count: Int
)
fun findAllProbeVelocities(
target: TargetArea,
maxPossibleHeight: Int = 20
): VelocityResults {
val xRange = 1..target.xRange.last // Too large (on the left side)
val yRange = target.yRange.first .. maxPossibleHeight
var count = 0
var maxHeight = Int.MIN_VALUE
for (x in xRange) {
for (y in yRange) {
val result = launchProbe(
Velocity(x, y),
target
)
if (result is Result.Hit) {
maxHeight = max(maxHeight, result.maxHeight)
count++
}
}
}
if (maxHeight == Int.MIN_VALUE) {
throw IllegalStateException("Could not find max height")
}
return VelocityResults(maxHeight, count)
}
fun part1() {
val target = TargetArea(
xRange = 153..199,
yRange = -114..-75
)
val result = findAllProbeVelocities(
target,
maxPossibleHeight = 1500
)
println("Result: $result")
}
fun part2() {
val target = TargetArea(
xRange = 153..199,
yRange = -114..-75
)
val result = findAllProbeVelocities(
target,
maxPossibleHeight = 1000
)
println("Result: $result")
}
fun main() {
part2()
}
| 0 | Kotlin | 1 | 2 | 73bbb6a41229e5863e52388a19108041339a864e | 3,234 | AdventOfCode2021 | Apache License 2.0 |
kotlin/src/com/s13g/aoc/aoc2022/Day19.kt | shaeberling | 50,704,971 | false | {"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245} | package com.s13g.aoc.aoc2022
import com.s13g.aoc.Result
import com.s13g.aoc.Solver
import com.s13g.aoc.mul
import com.s13g.aoc.resultFrom
import kotlin.math.max
import kotlin.math.min
/**
* --- Day 19: Not Enough Minerals ---
* https://adventofcode.com/2022/day/19
*/
class Day19 : Solver {
enum class Bot { ORE, CLAY, OBS, GEODE }
private val cache = mutableMapOf<String, Int>()
override fun solve(lines: List<String>): Result {
val re =
"""Blueprint (\d+): Each ore robot costs (\d+) ore. Each clay robot costs (\d+) ore. Each obsidian robot costs (\d+) ore and (\d+) clay. Each geode robot costs (\d+) ore and (\d+) obsidian.""".toRegex()
val blueprints = mutableListOf<Blueprint>()
for (line in lines) {
val (id, oreOre, clayOre, obsOre, obsCLay, geoOre, geoObs) = re.find(line)!!.destructured
blueprints.add(
Blueprint(
id.toInt(),
mapOf(
Bot.ORE to Cost(oreOre.toInt(), 0, 0),
Bot.CLAY to Cost(clayOre.toInt(), 0, 0),
Bot.OBS to Cost(obsOre.toInt(), obsCLay.toInt(), 0),
Bot.GEODE to Cost(geoOre.toInt(), 0, geoObs.toInt())
)
)
)
}
val partA = blueprints.sumOf { qualityLevel(it) }
val partB = blueprints.subList(0, 3).map { maxGeo(it) }.mul()
return resultFrom(partA, partB)
}
private fun maxGeo(bp: Blueprint): Int {
println("[B] BP ${bp.id}")
cache.clear()
return maxGeodes(bp, 1, mapOf(Bot.ORE to 1), Bank(0, 0, 0, 0), 32)
}
private fun qualityLevel(bp: Blueprint): Int {
println("[A] BP ${bp.id}")
cache.clear()
val maxG = maxGeodes(bp, 1, mapOf(Bot.ORE to 1), Bank(0, 0, 0, 0), 24)
return maxG * bp.id
}
private fun maxGeodes(
bp: Blueprint, time: Int, bots: Map<Bot, Int>, bank: Bank, totalTime: Int
): Int {
val numOreBots = bots[Bot.ORE] ?: 0
val numClayBots = bots[Bot.CLAY] ?: 0
val numObsBots = bots[Bot.OBS] ?: 0
val numGeoBots = bots[Bot.GEODE] ?: 0
// Since we're going DFS, prune branches we've already been to.
val gameKey = "$time-$numObsBots-$numClayBots-$numObsBots-$numGeoBots-$bank"
if (gameKey in cache) return cache[gameKey]!!
// Prune cases where we have too many robots than we need.
if (numOreBots > bp.maxCostOre() ||
numClayBots > bp.maxCostClay() ||
numObsBots > bp.maxCostObs()
) {
cache[gameKey] = 0
return 0
}
var newOre = bank.ore + numOreBots
var newClay = bank.clay + numClayBots
var newObs = bank.obs + numObsBots
val newGeodes = bank.geodes + numGeoBots
if (time == totalTime) return newGeodes
// Prune: We cannot spend all these resources, so cap them, which will dup
// them to other branches and thus reduce the search space.
val timeLeft = totalTime - time
newOre = min(newOre, timeLeft * bp.maxCostOre())
newClay = min(newClay, timeLeft * bp.maxCostClay())
newObs = min(newObs, timeLeft * bp.maxCostObs())
var maxGeodes = 0
for (botType in Bot.values()) {
// Check if we can afford building this robot.
if (bp.costs[botType]!!.ore <= bank.ore &&
bp.costs[botType]!!.clay <= bank.clay &&
bp.costs[botType]!!.obsidian <= bank.obs
) {
val newBots =
bots.toMutableMap().plus(botType to (bots[botType] ?: 0) + 1)
val newBank = Bank(
newOre - bp.costs[botType]!!.ore,
newClay - bp.costs[botType]!!.clay,
newObs - bp.costs[botType]!!.obsidian,
newGeodes
)
maxGeodes =
max(maxGeodes(bp, time + 1, newBots, newBank, totalTime), maxGeodes)
}
}
// The last option: We don't produce any robot.
val newBank = Bank(newOre, newClay, newObs, newGeodes)
maxGeodes =
max(maxGeodes(bp, time + 1, bots, newBank, totalTime), maxGeodes)
cache[gameKey] = maxGeodes
return maxGeodes
}
data class Blueprint(val id: Int, val costs: Map<Bot, Cost>) {
fun maxCostOre() = costs.values.maxOf { it.ore }
fun maxCostClay() = costs.values.maxOf { it.clay }
fun maxCostObs() = costs.values.maxOf { it.obsidian }
}
data class Cost(val ore: Int, val clay: Int, val obsidian: Int)
data class Bank(
val ore: Int,
val clay: Int,
val obs: Int,
val geodes: Int
)
} | 0 | Kotlin | 1 | 2 | 7e5806f288e87d26cd22eca44e5c695faf62a0d7 | 4,314 | euler | Apache License 2.0 |
src/day6/main.kt | jorgensta | 573,824,365 | false | {"Kotlin": 31676} | package day6
import readInput
fun main() {
val day = "day6"
val filename = "Day06"
val testMarkers = mapOf(
"bvwbjplbgvbhsrlpgdmjqwftvncz" to 5,
"nppdvjthqldpwncqszvftbrmjlhg" to 6,
"nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg" to 10,
"zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw" to 11
)
val testMarkersTwo = mapOf(
"mjqjpqmgbljsphdztnvjfqwrcgsmlb" to 19,
"bvwbjplbgvbhsrlpgdmjqwftvncz" to 23,
"nppdvjthqldpwncqszvftbrmjlhg" to 23,
"nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg" to 29,
"zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw" to 26
)
fun testingTwo() {
testMarkersTwo.entries.forEach { entry ->
val datastream = entry.key
val markerTruth = entry.value
var marker = 0
var markerFound = false
datastream
.windowed(14)
.forEachIndexed { index, string ->
if (markerFound) return@forEachIndexed
val allCharsAreDistinct = string.toCharArray().distinct().size == 14
if (allCharsAreDistinct) {
println("Marker found!")
marker = 14 + index
markerFound = true
}
}
println("Marker: $marker. Truth: $markerTruth")
check(marker == markerTruth)
}
}
fun testing() {
testMarkers.entries.forEach { entry ->
val datastream = entry.key
val markerTruth = entry.value
var marker = 0
var markerFound = false
datastream
.windowed(4)
.forEachIndexed { index, string ->
if (markerFound) return@forEachIndexed
val allCharsAreDistinct = string.toCharArray().distinct().size == 4
if (allCharsAreDistinct) {
println("Marker found!")
marker = 4 + index
markerFound = true
}
}
println("Marker: $marker. Truth: $markerTruth")
check(marker == markerTruth)
}
}
// testing()
testingTwo()
fun part1(input: String): Int {
var markerFound = false
var marker = 0
input
.windowed(4)
.forEachIndexed { index, string ->
if (markerFound) return@forEachIndexed
val allCharsAreDistinct = string.toCharArray().distinct().size == 4
if (allCharsAreDistinct) {
println("Marker found!")
marker = 4 + index
markerFound = true
}
}
return marker
}
fun part2(input: String): Int {
var markerFound = false
var marker = 0
input
.windowed(14)
.forEachIndexed { index, string ->
if (markerFound) return@forEachIndexed
val allCharsAreDistinct = string.toCharArray().distinct().size == 14
if (allCharsAreDistinct) {
println("Marker found!")
marker = 14 + index
markerFound = true
}
}
return marker
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("/$day/${filename}_test")
val input = readInput("/$day/$filename")
// val partOneTest = part1(testInput)
// check(partOneTest == 157)
println("Part one: ${part1(input.joinToString(""))}")
// val partTwoTest = part2(testInput)
// check(partTwoTest == 70)
println("Part two: ${part2(input.joinToString(""))}")
}
| 0 | Kotlin | 0 | 0 | 7243e32351a926c3a269f1e37c1689dfaf9484de | 3,790 | AoC2022 | Apache License 2.0 |
src/day04/Day04.kt | veronicamengyan | 573,063,888 | false | {"Kotlin": 14976} | package day04
/**
* Potential improvement:
* * split on both , and -
* * use IntRange
*/
import readInput
fun main() {
fun isContain(input: String): Boolean {
val pair = input.split(",")
val sections1 = pair[0].split("-")
val sections2 = pair[1].split("-")
val start1 = sections1[0].toInt()
val end1 = sections1[1].toInt()
val start2 = sections2[0].toInt()
val end2 = sections2[1].toInt()
return (start1 >= start2 && end1 <= end2) || (start1 <= start2 && end1 >= end2)
}
fun isOverlap(input: String): Boolean {
val pair = input.split(",")
val sections1 = pair[0].split("-")
val sections2 = pair[1].split("-")
val start1 = sections1[0].toInt()
val end1 = sections1[1].toInt()
val start2 = sections2[0].toInt()
val end2 = sections2[1].toInt()
return (end2 in start1..end1) || (end1 in start2..end2)
}
fun findContain(input: List<String>): Int {
return input.count { item -> isContain(item)}
}
fun findOverlap(input: List<String>): Int {
return input.count { item -> isOverlap(item)}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("day04/Day04_test")
println(findContain(testInput))
check(findContain(testInput) == 2)
println(findOverlap(testInput))
check(findOverlap(testInput) == 4)
val input = readInput("day04/Day04")
println(findContain(input))
println(findOverlap(input))
} | 0 | Kotlin | 0 | 0 | d443cfa49e9d8c9f76fdb6303ecf104498effb88 | 1,697 | aoc-2022-in-kotlin | Apache License 2.0 |
CyclicRotation.kt | getnahid | 267,415,396 | false | null | /*
CyclicRotation
Rotate an array to the right by a given number of steps.
An array A consisting of N integers is given. Rotation of the array means that each element is shifted right by one index, and the last element of the array is moved to the first place. For example, the rotation of array A = [3, 8, 9, 7, 6] is [6, 3, 8, 9, 7] (elements are shifted right by one index and 6 is moved to the first place).
The goal is to rotate array A K times; that is, each element of A will be shifted to the right K times.
Write a function:
class Solution { public int[] solution(int[] A, int K); }
that, given an array A consisting of N integers and an integer K, returns the array A rotated K times.
For example, given
A = [3, 8, 9, 7, 6]
K = 3
the function should return [9, 7, 6, 3, 8]. Three rotations were made:
[3, 8, 9, 7, 6] -> [6, 3, 8, 9, 7]
[6, 3, 8, 9, 7] -> [7, 6, 3, 8, 9]
[7, 6, 3, 8, 9] -> [9, 7, 6, 3, 8]
For another example, given
A = [0, 0, 0]
K = 1
the function should return [0, 0, 0]
Given
A = [1, 2, 3, 4]
K = 4
the function should return [1, 2, 3, 4]
Assume that:
N and K are integers within the range [0..100];
each element of array A is an integer within the range [−1,000..1,000].
In your solution, focus on correctness. The performance of your solution will not be the focus of the assessment.*/
fun solution(array: IntArray, k: Int): IntArray {
val arrayLength: Int = array.size
val sol = IntArray(array.size)
for (i in array.indices) {
sol[(i + k) % arrayLength] = array.get(i)
}
//array.forEach { print(it) }
return array
}
| 0 | Kotlin | 0 | 0 | 589c392237334f6c53513dc7b75bd8fa81ad3b79 | 1,630 | programing-problem-solves-kotlin | Apache License 2.0 |
src/Day07.kt | ahmadshabib | 573,197,533 | false | {"Kotlin": 13577} | fun main() {
val input = readInput("Day07")
var currentDirectory: Directory? = null
val directories: MutableList<Directory> = mutableListOf()
for (command in input) {
if (command.startsWith("\$ cd")) {
if (command.startsWith("\$ cd ..")) {
currentDirectory = currentDirectory?.parent
continue
}
if (currentDirectory == null) {
val dir = Directory(command.replace("\$ cd", ""), null)
currentDirectory = dir
directories.add(dir)
} else {
val dir = Directory(command.replace("\$ cd", ""), currentDirectory)
currentDirectory.addEntry(dir)
directories.add(dir)
currentDirectory = dir
}
} else if (!command.startsWith("\$")) {
if (command.startsWith("dir")) {
continue
} else {
val split = command.split(" ")
val file = File(split[1], currentDirectory, split[0].toInt())
currentDirectory?.addEntry(file)
}
}
}
// first
println(directories.filter { it.size() < 100000 }.sumOf { it.size() })
// second
val unusedSpace = 70000000 - directories.first { it.name == " /" }.size()
val spaceNeeded = 30000000 - unusedSpace
println(directories.filter { it.size() >= spaceNeeded }.minBy { it.size() }.size())
}
abstract class Entry(var name: String, directory: Directory?) {
var parent: Directory?
abstract fun size(): Int
init {
parent = directory
}
override fun toString(): String {
return "$name - ${size()}"
}
}
class File(name: String, directory: Directory?, private val size: Int) : Entry(name, directory) {
override fun size(): Int {
return size
}
}
class Directory(name: String, directory: Directory?) : Entry(name, directory) {
private var contents: MutableList<Entry> = mutableListOf()
override fun size(): Int {
var size = 0
for (e in contents) size += e.size()
return size
}
fun addEntry(entry: Entry) {
contents.add(entry)
}
override fun toString(): String {
return "$name + ${contents.joinToString { it.toString() }}"
}
} | 0 | Kotlin | 0 | 0 | 81db1b287ca3f6cae95dde41919bfa539ac3adb5 | 2,329 | advent-of-code-kotlin-22 | Apache License 2.0 |
kotlin/yacht/src/main/kotlin/Yacht.kt | fredyw | 523,079,058 | false | null | object Yacht {
fun solve(category: YachtCategory, vararg dices: Int): Int {
return when (category) {
YachtCategory.ONES -> dices.filter { it == 1 }.sum()
YachtCategory.TWOS -> dices.filter { it == 2 }.sum()
YachtCategory.THREES -> dices.filter { it == 3 }.sum()
YachtCategory.FOURS -> dices.filter { it == 4 }.sum()
YachtCategory.FIVES -> dices.filter { it == 5 }.sum()
YachtCategory.SIXES -> dices.filter { it == 6 }.sum()
YachtCategory.FULL_HOUSE ->
dices.toList().groupingBy { it }.eachCount().let { map ->
if (map.containsValue(3) && map.containsValue(2)) {
map.map { it.key * it.value }.sum()
} else {
0
}
}
YachtCategory.FOUR_OF_A_KIND ->
dices.toList().groupingBy { it }.eachCount().let { map ->
map.filter { it.value >= 4 }.map { it.key * 4 }.sum()
}
YachtCategory.LITTLE_STRAIGHT -> if ((1..5).all { it in dices }) 30 else 0
YachtCategory.BIG_STRAIGHT -> if ((2..6).all { it in dices }) 30 else 0
YachtCategory.CHOICE -> dices.sum()
YachtCategory.YACHT -> if (dices.toSet().size == 1) 50 else 0
}
}
}
| 0 | Kotlin | 0 | 0 | 101a0c849678ebb7d2e15b896cfd9e5d82c56275 | 1,370 | exercism | MIT License |
app/src/main/kotlin/io/github/andrewfitzy/day01/Task02.kt | andrewfitzy | 747,793,365 | false | {"Kotlin": 60159, "Shell": 1211} | package io.github.andrewfitzy.day01
import io.github.andrewfitzy.util.Point
class Task02(puzzleInput: List<String>) {
private val input: List<String> = puzzleInput
private val rotationMapping: Map<Pair<String, String>, String> =
mapOf(
Pair("N", "R") to "E",
Pair("N", "L") to "W",
Pair("E", "R") to "S",
Pair("E", "L") to "N",
Pair("S", "R") to "W",
Pair("S", "L") to "E",
Pair("W", "R") to "N",
Pair("W", "L") to "S",
)
fun solve(): Int {
var heading = "N"
val start = Point(0, 0)
var end = Point(0, 0)
val seen = HashSet<Point>()
var found = false
val moves = input.first().split(", ")
for (move: String in moves) {
val direction: String = move.substring(0, 1)
val distance: Int = move.substring(1).trim().toInt()
heading = rotationMapping[Pair(heading, direction)]!!
val steps = steps(end, heading, distance)
end = steps.last()
for (step in steps) {
if (seen.contains(step)) {
end = step
found = true
break
}
seen.add(step)
}
if (found) {
break
}
}
return start.getManhattanDistance(end)
}
private fun steps(
end: Point,
heading: String,
distance: Int,
): List<Point> {
return when (heading) {
"N" -> (1..distance).map { Point(end.x, end.y + it) }
"E" -> (1..distance).map { Point(end.x + it, end.y) }
"S" -> (1..distance).map { Point(end.x, end.y - it) }
"W" -> (1..distance).map { Point(end.x - it, end.y) }
else -> emptyList()
}
}
}
| 0 | Kotlin | 0 | 0 | 15ac072a14b83666da095b9ed66da2fd912f5e65 | 1,890 | 2016-advent-of-code | Creative Commons Zero v1.0 Universal |
archive/src/main/kotlin/com/grappenmaker/aoc/year23/Day16.kt | 770grappenmaker | 434,645,245 | false | {"Kotlin": 409647, "Python": 647} | package com.grappenmaker.aoc.year23
import com.grappenmaker.aoc.*
import com.grappenmaker.aoc.Direction.*
fun PuzzleSet.day16() = puzzle(day = 16) {
val g = inputLines.asCharGrid()
val sd = mapOf(
'-' to listOf(LEFT, RIGHT),
'|' to listOf(UP, DOWN),
)
val md = mapOf(
'/' to mapOf(
UP to RIGHT,
LEFT to DOWN,
RIGHT to UP,
DOWN to LEFT,
),
'\\' to mapOf(
UP to LEFT,
LEFT to UP,
RIGHT to DOWN,
DOWN to RIGHT,
)
)
data class State(val pos: Point = Point(0, 0), val dir: Direction = RIGHT)
fun State.move(d: Direction = dir) = State(pos + d, d)
fun solve(start: State): Int {
val queue = queueOf(start)
val seen = hashSetOf<Point>()
val seenStates = hashSetOf<State>()
while (queue.isNotEmpty()) {
val p = queue.removeFirst()
if (p.pos !in g) continue
seen += p.pos
if (!seenStates.add(p)) continue
queue += when (val t = g[p.pos]) {
'.' -> listOf(p.move())
in md.keys -> listOf(p.move(md.getValue(g[p.pos]).getValue(p.dir)))
in sd.keys -> {
val ds = sd.getValue(t)
if (p.dir in ds) listOf(p.move()) else ds.map { p.move(it) }
}
else -> error("Impossible")
}
}
return seen.size
}
partOne = solve(State()).s()
partTwo = g.edges.flatMapTo(hashSetOf()) { it.allPoints() }.maxOf { p ->
buildList {
if (p.x == 0) add(RIGHT)
if (p.y == 0) add(DOWN)
if (p.x == g.maxX) add(LEFT)
if (p.y == g.maxY) add(UP)
}.maxOf { solve(State(p, it)) }
}.s()
} | 0 | Kotlin | 0 | 7 | 92ef1b5ecc3cbe76d2ccd0303a73fddda82ba585 | 1,842 | advent-of-code | The Unlicense |
src/main/kotlin/org/example/e3fxgaming/adventOfCode/aoc2023/day02/Day02.kt | E3FxGaming | 726,041,587 | false | {"Kotlin": 38290} | package org.example.e3fxgaming.adventOfCode.aoc2023.day02
import org.example.e3fxgaming.adventOfCode.utility.Day
import org.example.e3fxgaming.adventOfCode.utility.IndividualLineInputParser
import org.example.e3fxgaming.adventOfCode.utility.InputParser
class Day02(inputLines: String) : Day<List<Triple<Int, Int, Int>>, List<Triple<Int, Int, Int>>> {
override val partOneParser: InputParser<List<Triple<Int, Int, Int>>> =
object : IndividualLineInputParser<List<Triple<Int, Int, Int>>>(inputLines) {
override fun parseLine(line: String): List<Triple<Int, Int, Int>> {
return line.substringAfter(": ").split("; ").map { round ->
IntArray(3).also { rgb ->
round.split(", ").forEach { countAndColor ->
val (count, color) = countAndColor.split(" ")
when (color) {
"red" -> rgb[0] = count.toInt()
"green" -> rgb[1] = count.toInt()
"blue" -> rgb[2] = count.toInt()
}
}
}.let { tripleDesc ->
Triple(tripleDesc[0], tripleDesc[1], tripleDesc[2])
}
}
}
}
override val partTwoParser: InputParser<List<Triple<Int, Int, Int>>> = partOneParser
private fun Triple<Int, Int, Int>.allowed() = first <= 12 && second <= 13 && third <= 14
override fun solveFirst(given: List<List<Triple<Int, Int, Int>>>): String {
return given.withIndex().fold(0) { acc, (index, gameRecording) ->
if (gameRecording.any { !it.allowed() }) {
return@fold acc
}
acc + (index + 1)
}.toString()
}
override fun solveSecond(given: List<List<Triple<Int, Int, Int>>>): String {
return given.sumOf { drawingRecordings ->
var r = 0
var g = 0
var b = 0
drawingRecordings.forEach { triple ->
r = r.coerceAtLeast(triple.first)
g = g.coerceAtLeast(triple.second)
b = b.coerceAtLeast(triple.third)
}
r * g * b
}.toString()
}
}
fun main() = Day02(
Day02::class.java.getResource("/2023/day02/realInput1.txt")!!.readText()
).runBoth() | 0 | Kotlin | 0 | 0 | 3ae9e8b60788733d8bc3f6446d7a9ae4b3dabbc0 | 2,409 | adventOfCode | MIT License |
src/Day21.kt | dragere | 440,914,403 | false | {"Kotlin": 62581} | import java.io.File
import java.lang.Integer.max
fun main() {
val debug = false
class Dice {
var last = -1
fun getNext(): Int {
last += 1
return last % 100 +1
}
}
fun part1(playerPositions: List<Int>): Int {
val scores = mutableListOf(0, 0)
val poses = playerPositions.map { it - 1 }.toMutableList()
val d = Dice()
var round = 0
while(true){
val player = round % 2
val moveBy = d.getNext() + d.getNext() + d.getNext()
poses[player] = (poses[player] + moveBy) % 10
scores[player] += poses[player] + 1
if (scores[player] >= 1000){
return scores[player + 1 % 2] * (d.last + 1)
}
round += 1
}
}
fun part2(input: List<String>): Int {
return 0
}
fun preprocessing(input: String): List<Int> {
// val (a, b) = input.split("\r\n\r\n").map { it.split(": ")[0].toInt() }
// return a to b
return input.trim().split("\r\n").map { it.split(": ")[1].toInt() }
}
val realInp = read_testInput("real21")
val testInp = read_testInput("test21")
// val testInp = ""
// println("Test 1: ${part1(preprocessing(testInp))}")
println("Real 1: ${part1(preprocessing(realInp))}")
// println("-----------")
// println("Test 2: ${part2(preprocessing(testInp))}")
// println("Real 2: ${part2(preprocessing(realInp))}")
}
| 0 | Kotlin | 0 | 0 | 3e33ab078f8f5413fa659ec6c169cd2f99d0b374 | 1,497 | advent_of_code21_kotlin | Apache License 2.0 |
day-07/src/main/kotlin/TheTreacheryOfWhales.kt | diogomr | 433,940,168 | false | {"Kotlin": 92651} | import kotlin.math.abs
fun main() {
println("Part One Solution: ${partOne()}")
println("Part Two Solution: ${partTwo()}")
}
private fun partOne(): Int {
val positions = readInputLines()[0].split(",")
.map { it.toInt() }
var minFuel = Int.MAX_VALUE
for (p in positions) {
var fuelForPosition = 0
for (m in positions) {
fuelForPosition += abs(p - m)
}
if (fuelForPosition < minFuel) minFuel = fuelForPosition
}
return minFuel
}
private fun partTwo(): Int {
val positions = readInputLines()[0].split(",")
.map { it.toInt() }
var minFuel = Int.MAX_VALUE
val max = positions.maxOrNull()!!
for (p in 0 until max) {
var fuelForPosition = 0
for (m in positions) {
fuelForPosition += IntRange(0, abs(p - m)).sum()
}
if (fuelForPosition < minFuel) minFuel = fuelForPosition
}
return minFuel
}
private fun readInputLines(): List<String> {
return {}::class.java.classLoader.getResource("input.txt")!!
.readText()
.split("\n")
.filter { it.isNotBlank() }
}
| 0 | Kotlin | 0 | 0 | 17af21b269739e04480cc2595f706254bc455008 | 1,136 | aoc-2021 | MIT License |
scripts/Day2.kts | matthewm101 | 573,325,687 | false | {"Kotlin": 63435} | import java.io.File
enum class Hand(val handScore: Long) {Rock(1), Paper(2), Scissors(3)}
fun charToHand(c: Char) = when(c) {
'A', 'X' -> Hand.Rock
'B', 'Y' -> Hand.Paper
'C', 'Z' -> Hand.Scissors
else -> Hand.Rock
}
enum class Goal(val goalScore: Long) {Loss(0), Tie(3), Win(6)}
fun charToGoal(c: Char) = when(c) {
'X' -> Goal.Loss
'Y' -> Goal.Tie
'Z' -> Goal.Win
else -> Goal.Tie
}
fun judge(yours: Hand, theirs: Hand) = when(yours) {
Hand.Rock -> when(theirs) {
Hand.Rock -> Goal.Tie
Hand.Paper -> Goal.Loss
Hand.Scissors -> Goal.Win
}
Hand.Paper -> when(theirs) {
Hand.Rock -> Goal.Win
Hand.Paper -> Goal.Tie
Hand.Scissors -> Goal.Loss
}
Hand.Scissors -> when(theirs) {
Hand.Rock -> Goal.Loss
Hand.Paper -> Goal.Win
Hand.Scissors -> Goal.Tie
}
}
fun reverseJudge(theirs: Hand, goal: Goal) = when(goal) {
Goal.Win -> when(theirs) {
Hand.Rock -> Hand.Paper
Hand.Paper -> Hand.Scissors
Hand.Scissors -> Hand.Rock
}
Goal.Tie -> theirs
Goal.Loss -> when(theirs) {
Hand.Rock -> Hand.Scissors
Hand.Paper -> Hand.Rock
Hand.Scissors -> Hand.Paper
}
}
data class RoundV1(val opponent: Hand, val player: Hand) {
fun playerScore() = judge(player, opponent).goalScore + player.handScore
}
val roundsV1: List<RoundV1> = File("../inputs/2.txt").readLines().map {
s -> RoundV1(charToHand(s[0]), charToHand(s[2]))
}.toList()
val totalPlayerScoreV1 = roundsV1.map { r -> r.playerScore() }.sum()
println("Using the initial instructions, the player's total score from all rounds is $totalPlayerScoreV1.")
data class RoundV2(val opponent: Hand, val goal: Goal) {
fun playerScore() = goal.goalScore + reverseJudge(opponent, goal).handScore
}
val roundsV2: List<RoundV2> = File("../inputs/2.txt").readLines().map {
s -> RoundV2(charToHand(s[0]), charToGoal(s[2]))
}.toList()
val totalPlayerScoreV2 = roundsV2.map { r -> r.playerScore() }.sum()
println("Using the fixed instructions, the player's total score from all rounds is $totalPlayerScoreV2.") | 0 | Kotlin | 0 | 0 | bbd3cf6868936a9ee03c6783d8b2d02a08fbce85 | 2,158 | adventofcode2022 | MIT License |
src/main/kotlin/g1601_1700/s1681_minimum_incompatibility/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g1601_1700.s1681_minimum_incompatibility
// #Hard #Array #Dynamic_Programming #Bit_Manipulation #Bitmask
// #2023_06_15_Time_162_ms_(100.00%)_Space_36_MB_(100.00%)
class Solution {
private class Node {
var visited: BooleanArray = BooleanArray(17)
var size = 0
var min = 20
var max = 0
}
private lateinit var nodes: Array<Node?>
private var size = 0
private var result = 1000000
private var currentSum = 0
fun minimumIncompatibility(nums: IntArray, k: Int): Int {
size = nums.size / k
nodes = arrayOfNulls(k)
for (i in 0 until k) {
nodes[i] = Node()
}
nums.sort()
currentSum = 0
solve(nums, 0)
return if (result == 1000000) -1 else result
}
private fun solve(nums: IntArray, idx: Int) {
if (idx == nums.size) {
result = currentSum
return
}
var minSize = size
var prevMin: Int
var prevMax: Int
var diff: Int
for (node in nodes) {
if (node!!.size == minSize || node.visited[nums[idx]]) {
continue
}
minSize = node.size
prevMin = node.min
prevMax = node.max
diff = prevMax - prevMin
node.min = Math.min(node.min, nums[idx])
node.max = Math.max(node.max, nums[idx])
node.size++
node.visited[nums[idx]] = true
currentSum += if (prevMin == 20) {
node.max - node.min
} else {
node.max - node.min - diff
}
if (currentSum < result) {
solve(nums, idx + 1)
}
currentSum -= if (prevMin == 20) {
node.max - node.min
} else {
node.max - node.min - diff
}
node.visited[nums[idx]] = false
node.size--
node.min = prevMin
node.max = prevMax
}
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 2,037 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/d17/D17.kt | MTender | 734,007,442 | false | {"Kotlin": 108628} | package d17
import java.util.*
abstract class Location(
open val row: Int,
open val col: Int
) {
abstract fun getNeighbors(): List<Location>
abstract fun isValidTarget(target: Pair<Int, Int>): Boolean
}
fun parseInput(lines: List<String>): List<List<Int>> {
return lines.map { line -> line.toCharArray().map { it.digitToInt() } }
}
fun dijkstra(weights: List<List<Int>>, source: Location, target: Pair<Int, Int>): Int {
val distances = mutableMapOf<Location, Double>()
val previous = mutableMapOf<Location, Location?>()
distances[source] = 0.0
val settledVertices = mutableSetOf<Location>()
val unsettledVertices = mutableSetOf(source)
val unsettledQueue = PriorityQueue<Location>(
compareBy { distances[it] }
)
unsettledQueue.add(source)
while (unsettledQueue.isNotEmpty()) {
val loc = unsettledQueue.remove()
unsettledVertices.remove(loc)
for (neighbor in loc.getNeighbors()) {
if (isOutOfBounds(weights, neighbor)) continue // exclude out of bounds
if (settledVertices.contains(neighbor)) continue // exclude settled
val alt = distances[loc]!! + weights[neighbor.row][neighbor.col]
if (alt < (distances[neighbor] ?: Double.POSITIVE_INFINITY)) {
distances[neighbor] = alt
previous[neighbor] = loc
if (!unsettledVertices.contains(neighbor)) {
unsettledVertices.add(neighbor)
unsettledQueue.add(neighbor)
}
}
}
settledVertices.add(loc)
}
return distances
.filter { it.key.isValidTarget(target) }
.minBy { distances[it.key]!! }.value.toInt()
}
fun isOutOfBounds(weights: List<List<Int>>, loc: Location): Boolean {
return loc.row < 0 ||
loc.row >= weights.size ||
loc.col < 0 ||
loc.col >= weights[0].size
} | 0 | Kotlin | 0 | 0 | a6eec4168b4a98b73d4496c9d610854a0165dbeb | 1,951 | aoc2023-kotlin | MIT License |
src/Day06.kt | razvn | 573,166,955 | false | {"Kotlin": 27208} | fun main() {
val day = "Day06"
tailrec fun findMarker(len: Int, buffer: String, index: Int, string: String): Int {
return when {
buffer.length == len -> index
index >= string.length -> 0
else -> {
val char = string[index]
val idxOf = buffer.indexOf(char)
val newBuffer = "${if (idxOf >= 0) buffer.substring(idxOf + 1) else buffer}$char"
findMarker(len, newBuffer, index +1, string)
}
}
}
fun part1(input: List<String>): List<Int> {
return input.map {
findMarker(4, "", 0, it)
}
}
fun part2(input: List<String>): List<Int> {
return input.map {
findMarker(14, "", 0, it)
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("${day}_test")
println(part1(testInput))
println(part2(testInput))
check(part1(testInput) == listOf(7,5,6,10,11))
check(part2(testInput) == listOf(19,23,23,29,26))
val input = readInput(day)
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 73d1117b49111e5044273767a120142b5797a67b | 1,159 | aoc-2022-kotlin | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/CombinationSum2.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import java.util.LinkedList
/**
* 40. Combination Sum II
* @see <a href="https://leetcode.com/problems/combination-sum-ii/">Source</a>
*/
fun interface CombinationSum2 {
operator fun invoke(candidates: IntArray, target: Int): List<List<Int>>
}
class BacktrackingWithCounters : CombinationSum2 {
override operator fun invoke(candidates: IntArray, target: Int): List<List<Int>> {
// container to hold the final combinations
val results: MutableList<List<Int>> = ArrayList()
val comb = LinkedList<Int>()
val counter: HashMap<Int, Int> = HashMap()
for (candidate in candidates) {
if (counter.containsKey(candidate)) {
counter[candidate] = counter.getOrDefault(candidate, 0) + 1
} else {
counter[candidate] = 1
}
}
// convert the counter table to a list of (num, count) tuples
val counterList: MutableList<IntArray> = ArrayList()
counter.forEach { (key, value) -> counterList.add(intArrayOf(key, value)) }
backtrack(comb, target, 0, counterList, results)
return results
}
private fun backtrack(
comb: LinkedList<Int>,
remain: Int,
curr: Int,
counter: MutableList<IntArray>,
results: MutableList<List<Int>>,
) {
if (remain <= 0) {
if (remain == 0) {
// make a deep copy of the current combination.
results.add(ArrayList(comb))
}
return
}
for (nextCurr in curr until counter.size) {
val entry = counter[nextCurr]
val candidate = entry[0]
val freq = entry[1]
if (freq <= 0) continue
// add a new element to the current combination
comb.addLast(candidate)
counter[nextCurr] = intArrayOf(candidate, freq - 1)
// continue the exploration with the updated combination
backtrack(comb, remain - candidate, nextCurr, counter, results)
// backtrack the changes, so that we can try another candidate
counter[nextCurr] = intArrayOf(candidate, freq)
comb.removeLast()
}
}
}
class BacktrackingWithIndex : CombinationSum2 {
override operator fun invoke(candidates: IntArray, target: Int): List<List<Int>> {
val results: MutableList<List<Int>> = ArrayList()
val comb = LinkedList<Int>()
candidates.sort()
backtrack(candidates, comb, target, 0, results)
return results
}
private fun backtrack(
candidates: IntArray,
comb: LinkedList<Int>,
remain: Int,
curr: Int,
results: MutableList<List<Int>>,
) {
if (remain == 0) {
// copy the current combination to the final list.
results.add(ArrayList(comb))
return
}
for (nextCurr in curr until candidates.size) {
if (nextCurr > curr && candidates[nextCurr] == candidates[nextCurr - 1]) continue
val pick = candidates[nextCurr]
// optimization: early stopping
if (remain - pick < 0) break
comb.addLast(pick)
backtrack(candidates, comb, remain - pick, nextCurr + 1, results)
comb.removeLast()
}
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 3,988 | kotlab | Apache License 2.0 |
2022/src/main/kotlin/de/skyrising/aoc2022/day14/solution.kt | skyrising | 317,830,992 | false | {"Kotlin": 411565} | package de.skyrising.aoc2022.day14
import de.skyrising.aoc.*
private fun parseInput(input: PuzzleInput, floor: Boolean = false): CharGrid {
val lines = input.lines.flatMapTo(mutableListOf()) { line ->
line.split(" -> ").map(Vec2i::parse).zipWithNext { a, b -> a lineTo b }
}
if (floor) {
val floorPos = lines.boundingBox().max.y + 2
lines.add(Vec2i(500 - floorPos - 1, floorPos) lineTo Vec2i(500 + floorPos + 1, floorPos))
}
return lines.boundingBox().expand(Vec2i(500, 0)).charGrid { '.' }.also { it[lines.flatten()] = '#' }
}
private fun CharGrid.dropSand(pos: Vec2i) = pos.iterate {
if (y == Int.MAX_VALUE) return@iterate null
for (below in arrayOf(south, southWest, southEast)) {
if (below.y >= height) return@iterate Vec2i(x, Int.MAX_VALUE)
if (this@dropSand[below] == '.') return@iterate below
}
null
}.also { if (it in this) this[it] = 'o' }
val test = TestInput("""
498,4 -> 498,6 -> 496,6
503,4 -> 502,4 -> 502,9 -> 494,9
""")
@PuzzleName("Regolith Reservoir")
fun PuzzleInput.part1(): Any {
val grid = parseInput(this)
return countWhile {
grid.dropSand(Vec2i(500, 0)) in grid
}
}
fun PuzzleInput.part2(): Any {
val grid = parseInput(this, true)
return 1 + countWhile {
grid.dropSand(Vec2i(500, 0)).y != 0
}
}
| 0 | Kotlin | 0 | 0 | 19599c1204f6994226d31bce27d8f01440322f39 | 1,349 | aoc | MIT License |
src/main/kotlin/Day01.kt | attilaTorok | 573,174,988 | false | {"Kotlin": 26454} | fun main() {
fun findHighestCalorie(fileName: String): Int {
var max = 0; var sum = 0
readInputWithStream(fileName).useLines {
val iterator = it.iterator()
while (iterator.hasNext()) {
val currentLine = iterator.next()
if (currentLine.isNotEmpty()) {
sum += currentLine.toInt()
} else if (sum > max) {
max = sum
sum = 0
} else {
sum = 0
}
}
}
return if (sum > max) sum else max
}
fun findTheSumOfTheThreeHighestCalorie(fileName: String): Int {
val highestCalories = mutableListOf<Int>()
var sum = 0
readInputWithStream(fileName).useLines {
val iterator = it.iterator()
while (iterator.hasNext()) {
val currentLine = iterator.next()
if (currentLine.isNotEmpty()) {
sum += currentLine.toInt()
} else if (highestCalories.size != 3) {
highestCalories.add(sum)
highestCalories.sort()
sum = 0
} else if (sum > highestCalories[0]) {
highestCalories[0] = sum
highestCalories.sort()
sum = 0
} else {
sum = 0
}
}
}
if (sum > highestCalories[0]) highestCalories[0] = sum
return highestCalories.sum()
}
println("Test")
println("Highest calorie: ${findHighestCalorie("Day01_test")}")
println("Highest 3 calorie: ${findTheSumOfTheThreeHighestCalorie("Day01_test")}")
println()
println("Exercise")
println("Highest calorie: ${findHighestCalorie("Day01")}")
println("Highest 3 calorie: ${findTheSumOfTheThreeHighestCalorie("Day01")}")
}
| 0 | Kotlin | 0 | 0 | 1799cf8c470d7f47f2fdd4b61a874adcc0de1e73 | 1,939 | AOC2022 | Apache License 2.0 |
src/day05/Day05.kt | ivanovmeya | 573,150,306 | false | {"Kotlin": 43768} | package day05
import readInput
fun main() {
data class Operation(val from: Int, val to: Int, val quantity: Int)
fun String.toCrates(): List<Char> {
return this.chunked(4).map {
it.trim().ifBlank {
"[0]"
}
}.map { it[1] }
}
fun parseInitialStacks(input: List<String>): MutableMap<Int, ArrayDeque<Char>> {
val cratesStacks: MutableMap<Int, ArrayDeque<Char>> = mutableMapOf()
input.forEach { line ->
line.toCrates().forEachIndexed { index, crate ->
if (crate != '0') {
val fixedIndex = index + 1
val stack = cratesStacks[fixedIndex]
if (stack == null) {
cratesStacks[fixedIndex] = ArrayDeque(listOf(crate))
} else {
stack.addFirst(crate)
}
}
}
}
return cratesStacks
}
fun parseOperationsSafe(input: List<String>): List<Operation> {
val move = "move"
val from = "from"
val to = "to"
return input.map { operationString ->
val quantityStartIndex = operationString.indexOf(move) + move.length + 1
val quantityEndIndex = operationString.indexOf(' ', quantityStartIndex)
val quantity = operationString.substring(quantityStartIndex, quantityEndIndex).toInt()
val fromStartIndex = operationString.indexOf(from) + from.length + 1
val fromEndIndex = operationString.indexOf(' ', fromStartIndex)
val fromStack = operationString.substring(fromStartIndex, fromEndIndex).toInt()
val toStartIndex = operationString.indexOf(to) + to.length + 1
val toStack = operationString.substring(toStartIndex, operationString.length).toInt()
Operation(from = fromStack, to = toStack, quantity = quantity)
}
}
fun parseOperations(input: List<String>): List<Operation> {
return input.map { operationString ->
val split = operationString.split(' ')
Operation(from = split[3].toInt(), to = split[5].toInt(), quantity = split[1].toInt())
}
}
fun performOperationCrane9000(operation: Operation, stacks: MutableMap<Int, ArrayDeque<Char>>) {
repeat(operation.quantity) {
val removed = stacks[operation.from]?.removeLast()
?: throw IllegalStateException("There are no crates in stack ${operation.from}")
stacks[operation.to]?.addLast(removed)
}
}
fun performOperationCrane9001(operation: Operation, stacks: MutableMap<Int, ArrayDeque<Char>>) {
//remove top N crates from
//add removed crates to
//order is preserved
val fromStack = stacks[operation.from]
?: throw IllegalStateException("There are no stack with number ${operation.from}")
val toStack = stacks[operation.to]
?: throw IllegalStateException("There are no stack with number ${operation.to}")
println("performing operation = $operation")
val topNCrates = fromStack.subList(
fromIndex = fromStack.size - operation.quantity,
toIndex = fromStack.size
)
println("topNCrate = $topNCrates")
toStack.addAll(topNCrates)
repeat(operation.quantity) {
fromStack.removeLast()
}
println("toStack = $toStack")
println("fromStack = $fromStack")
}
fun parseInput(input: List<String>): Pair<MutableMap<Int, ArrayDeque<Char>>, List<Operation>> {
val emptyLineIndex = input.indexOfFirst { it.isEmpty() }
val stackInput = input.subList(0, emptyLineIndex - 1)
val operationInput = input.subList(emptyLineIndex + 1, input.size)
val cratesStacks = parseInitialStacks(stackInput)
val operations = parseOperations(operationInput)
return Pair(cratesStacks, operations)
}
fun topCratesOnEachStack(cratesStacks: MutableMap<Int, ArrayDeque<Char>>) =
cratesStacks.toSortedMap().values.map { it.last() }.fold(
initial = "",
operation = { acc: String, char: Char -> acc + char }
)
fun part1(input: List<String>): String {
val (cratesStacks, operations) = parseInput(input)
operations.forEach {
performOperationCrane9000(it, cratesStacks)
}
return topCratesOnEachStack(cratesStacks)
}
fun part2(input: List<String>): String {
val (cratesStacks, operations) = parseInput(input)
operations.forEach {
performOperationCrane9001(it, cratesStacks)
}
return topCratesOnEachStack(cratesStacks)
}
val testInput = readInput("day05/input_test")
val test1Result = part1(testInput)
val test2Result = part2(testInput)
println(test1Result)
println(test2Result)
check(test1Result == "CMZ")
check(test2Result == "MCD")
val input = readInput("day05/input")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 7530367fb453f012249f1dc37869f950bda018e0 | 5,112 | advent-of-code-2022 | Apache License 2.0 |
Kotlin/problems/0059_rotting_oranges.kt | oxone-999 | 243,366,951 | true | {"C++": 961697, "Kotlin": 99948, "Java": 17927, "Python": 9476, "Shell": 999, "Makefile": 187} | //Problem Statement
// In a given grid, each cell can have one of three values:
//
// the value 0 representing an empty cell;
// the value 1 representing a fresh orange;
// the value 2 representing a rotten orange.
// Every minute, any fresh orange that is adjacent (4-directionally) to a rotten orange becomes rotten.
//
// Return the minimum number of minutes that must elapse until no cell has a fresh orange.
// If this is impossible, return -1 instead.
import java.util.ArrayDeque
class Solution constructor() {
private val walkMask:Array<Pair<Int,Int>> = arrayOf(Pair(0,1),Pair(1,0),Pair(-1,0),Pair(0,-1))
fun canWalk(grid: Array<IntArray>,row :Int, col: Int, dir:Pair<Int,Int>) :Boolean{
return row+dir.first>=0 && row+dir.first<grid.size && col+dir.second>=0 && col+dir.second<grid[0].size && grid[row+dir.first][col+dir.second]==1
}
fun orangesRotting(grid: Array<IntArray>): Int {
var bfs:ArrayDeque<Pair<Int,Int>> = ArrayDeque<Pair<Int,Int>>()
var result: Int = -1
for(row in 0..grid.size-1){
for(col in 0..grid[0].size-1){
if(grid[row][col]==2){
bfs.add(Pair(row,col));
}
}
}
while(bfs.isNotEmpty()){
var tam : Int = bfs.size;
for(index in 0..tam-1){
var coord:Pair<Int,Int> = bfs.pollFirst();
for(dir in walkMask){
if(canWalk(grid,coord.first,coord.second,dir)){
val row = coord.first+dir.first
val col = coord.second+dir.second
grid[row][col]=2
bfs.add(Pair(row,col))
}
}
}
result++
}
for(row in 0..grid.size-1){
for(col in 0..grid[0].size-1){
if(grid[row][col]==1){
return -1
}
}
}
if(result<0)
return 0
return result
}
}
fun main(args:Array<String>){
var grid:Array<IntArray> = arrayOf(intArrayOf(2,1,1),intArrayOf(1,1,0),intArrayOf(0,1,1));
var sol: Solution = Solution()
println(sol.orangesRotting(grid))
}
| 0 | null | 0 | 0 | 52dc527111e7422923a0e25684d8f4837e81a09b | 2,248 | algorithms | MIT License |
problems/2020adventofcode19b/submissions/accepted/Stefan.kt | stoman | 47,287,900 | false | {"C": 169266, "C++": 142801, "Kotlin": 115106, "Python": 76047, "Java": 68331, "Go": 46428, "TeX": 27545, "Shell": 3428, "Starlark": 2165, "Makefile": 1582, "SWIG": 722} | import java.util.*
fun main() {
val s = Scanner(System.`in`).useDelimiter("\\n\\n")
val sRules = Scanner(s.next()).useDelimiter("\\n")
val rules = mutableMapOf<Int, Set<List<String>>>()
while (sRules.hasNext()) {
val rule = sRules.next().split(":")
rules[rule[0].toInt()] = rule[1].split("|").map { it.trim().split(" ") }.toSet()
}
val thirtyOne: HashSet<String> = rules[31]!!.flatMap { expand(it, rules) }.toHashSet()
val fortyTwo: HashSet<String> = rules[42]!!.flatMap { expand(it, rules) }.toHashSet()
val sMessages = Scanner(s.next())
var r = 0
while (sMessages.hasNext()) {
if (check(sMessages.next(), thirtyOne, fortyTwo)) {
r++
}
}
println(r)
}
fun check(message: String, thirtyOne: HashSet<String>, fortyTwo: HashSet<String>): Boolean {
val fortyTwoLength = fortyTwo.first().length
val thirtyOneLength = thirtyOne.first().length
if (message.slice(0 until fortyTwoLength) !in fortyTwo) {
return false
}
for (countFortyTwo in 2..(message.length / fortyTwoLength)) {
if (message.slice((countFortyTwo - 1) * fortyTwoLength until countFortyTwo * fortyTwoLength) !in fortyTwo) {
return false
}
if ((message.length - countFortyTwo * fortyTwoLength) % thirtyOneLength == 0) {
val countThirtyOne = (message.length - countFortyTwo * fortyTwoLength) / thirtyOneLength
if (countThirtyOne in 1 until countFortyTwo) {
if ((0 until countThirtyOne).all {
message.slice(
countFortyTwo * fortyTwoLength + it * thirtyOneLength until countFortyTwo * fortyTwoLength + (it + 1) * thirtyOneLength) in thirtyOne
}) {
return true
}
}
}
}
return false
}
fun expand(message: List<String>, rules: Map<Int, Set<List<String>>>): List<String> {
if (message.isEmpty()) {
return listOf("")
}
val next = expand(message.drop(1), rules)
if (message.first().first() == '"') {
return next.map { message.first().drop(1).dropLast(1) + it }
}
val rule = message.first().toInt()
val firstPart = rules[rule]!!.flatMap { expand(it, rules) }
return next.flatMap { firstPart.map { f -> f + it } }
}
| 0 | C | 1 | 3 | ee214c95c1dc1d5e9510052ae425d2b19bf8e2d9 | 2,157 | CompetitiveProgramming | MIT License |
solution/#26 Remove Duplicates from Sorted Array/Solution.kt | enihsyou | 116,918,868 | false | {"Java": 179666, "Python": 36379, "Kotlin": 32431, "Shell": 367} | package leetcode.q26.kotlin;
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.Arguments
import org.junit.jupiter.params.provider.MethodSource
/**
* 26. Remove Duplicates from Sorted Array
*
* [LeetCode](https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array/)
*/
class Solution {
fun removeDuplicates(nums: IntArray): Int {
if (nums.isEmpty()) {
return 0
}
/** 不重复数字的数量,也当作位置指针使用 */
var uniques = 1
for (i in 1 until nums.size) {
val num = nums[i]
val lastUnique = nums[uniques - 1] // uniques - 1 := 上一个不重复数字的位置
if (lastUnique == num) {
/* 跳过重复数字 */
} else {
uniques++
nums[uniques - 1] = num // uniques - 1 := 下一个不重复数字的位置
}
}
return uniques
}
}
class SolutionTest {
private val solution = Solution()
@ParameterizedTest(name = "removeDuplicates({0}) = {1}")
@MethodSource("provider")
fun removeDuplicates(input: IntArray, output: Int) {
Assertions.assertEquals(solution.removeDuplicates(input), output)
// Assertions.assertEquals(input.copyOfRange(0, 2), intArrayOf(1, 2))
}
companion object {
@JvmStatic
fun provider(): List<Arguments> {
return listOf(
Arguments.of(intArrayOf(1, 1, 2), 2),
Arguments.of(intArrayOf(1), 1),
Arguments.of(intArrayOf(), 0)
)
}
}
}
| 1 | Java | 0 | 0 | 230325d1dfd666ee53f304edf74c9c0f60f81d75 | 1,691 | LeetCode | MIT License |
src/main/kotlin/days/Day12.kt | felix-ebert | 317,592,241 | false | null | package days
import kotlin.math.absoluteValue
class Day12 : Day(12) {
override fun partOne(): Any {
val instructions = inputList.map { it.take(1) to it.substring(1).toInt() }.toMutableList()
return simulateInstructions(instructions, false)
}
override fun partTwo(): Any {
val instructions = inputList.map { it.take(1) to it.substring(1).toInt() }.toMutableList()
return simulateInstructions(instructions, true)
}
private fun simulateInstructions(instructions: List<Pair<String, Int>>, moveWaypoint: Boolean): Int {
var ship = Pair(0, 0)
var waypoint = Pair(10, 1)
var direction = 90
for (ins in instructions) {
when (ins.first) {
"N", "S", "E", "W" -> {
if (moveWaypoint) waypoint = updatePosition(waypoint, ins)
else ship = updatePosition(ship, ins) // move ship
}
"L" -> {
if (moveWaypoint) {
when (ins.second) {
90 -> waypoint = Pair(-1 * waypoint.second, waypoint.first)
180 -> waypoint = Pair(-1 * waypoint.first, -1 * waypoint.second)
270 -> waypoint = Pair(waypoint.second, -1 * waypoint.first)
}
waypoint = updatePosition(waypoint, ins)
} else direction = (direction - ins.second) % 360
}
"R" -> {
if (moveWaypoint) {
when (ins.second) {
90 -> waypoint = Pair(waypoint.second, -1 * waypoint.first)
180 -> waypoint = Pair(-1 * waypoint.first, -1 * waypoint.second)
270 -> waypoint = Pair(-1 * waypoint.second, waypoint.first)
}
} else direction = (direction + ins.second) % 360
}
"F" -> {
ship = if (moveWaypoint) Pair(
ship.first + waypoint.first * ins.second,
ship.second + waypoint.second * ins.second
)
else updatePosition(ship, Pair(getDirection(direction), ins.second))
}
}
}
return ship.first.absoluteValue + ship.second.absoluteValue
}
private fun updatePosition(position: Pair<Int, Int>, ins: Pair<String, Int>): Pair<Int, Int> {
var x = position.first
var y = position.second
when (ins.first) {
"N" -> y += ins.second
"S" -> y -= ins.second
"E" -> x += ins.second
"W" -> x -= ins.second
}
return Pair(x, y)
}
private fun getDirection(degrees: Int): String {
return when (if (degrees > 0) degrees else degrees + 360) {
0 -> "N"
90 -> "E"
180 -> "S"
270 -> "W"
else -> "N"
}
}
} | 0 | Kotlin | 0 | 4 | dba66bc2aba639bdc34463ec4e3ad5d301266cb1 | 3,054 | advent-of-code-2020 | Creative Commons Zero v1.0 Universal |
src/main/java/challenges/educative_grokking_coding_interview/two_heaps/_1/MaximizeCapital.kt | ShabanKamell | 342,007,920 | false | null | package challenges.educative_grokking_coding_interview.two_heaps._1
import challenges.util.PrintHyphens
import java.util.*
/**
A busy investor with an initial capital, c, needs an automated investment program. They can select k distinct projects
from a list of n projects with corresponding capitals requirements and expected profits. For a given project
i, its capital requirement is capitals[i]
, and the profit it yields is profits[i].
The goal is to maximize their cumulative capital by selecting a maximum of k distinct projects to invest in,
subject to the constraint that the investor’s current capital must be greater than or equal to the capital
requirement of all selected projects.
When a selected project from the identified ones is finished, the pure profit from the project, along with
the starting capital of that project is returned to the investor. This amount will be added to the total capital
held by the investor. Now, the investor can invest in more projects with the new total capital. It is important
to note that each project can only be invested once.
As a basic risk-mitigation measure, the investor wants to limit the number of projects they invest in.
For example, if k is 2, the program should identify the two projects that maximize
the investor’s profits while ensuring that the investor’s capital is sufficient to invest in the projects.
Overall, the program should help the investor to make informed investment decisions by picking a list
of a maximum of k distinct projects to maximize the final profit while mitigating the risk.
https://www.educative.io/courses/grokking-coding-interview-patterns-java/JEj181o3RJK
*/
object MaximizeCapital {
private fun maximumCapital(c: Int, k: Int, capitals: IntArray, profits: IntArray?): Int {
val capitalMinHeap = PriorityQueue<Int>()
var i = 0
// Insert all capitals values to a min-heap
while (i < capitals.size) {
capitalMinHeap.add(capitals[i])
i++
}
printCapitalsMinHeap(capitalMinHeap)
return 0
}
private fun printCapitalsMinHeap(capitals: PriorityQueue<Int>) {
val l: MutableList<Int> = ArrayList()
while (!capitals.isEmpty()) {
l.add(capitals.peek())
capitals.poll()
}
println("\t" + l.toString())
}
@JvmStatic
fun main(args: Array<String>) {
val c = intArrayOf(1, 2, 1, 7, 2)
val k = intArrayOf(2, 3, 3, 2, 4)
val capitals = arrayOf(
intArrayOf(1, 2, 2, 3),
intArrayOf(1, 3, 4, 5, 6),
intArrayOf(1, 2, 3, 4),
intArrayOf(6, 7, 8, 10),
intArrayOf(2, 3, 5, 6, 8, 12)
)
val profits = arrayOf(
intArrayOf(2, 4, 6, 8),
intArrayOf(1, 2, 3, 4, 5),
intArrayOf(1, 3, 5, 7),
intArrayOf(4, 8, 12, 14),
intArrayOf(1, 2, 5, 6, 8, 9)
)
for (i in k.indices) {
println((i + 1).toString() + ".\tGiven capitals: " + capitals[i].contentToString())
println(" \tAdding capital values...")
maximumCapital(c[i], k[i], capitals[i], profits[i])
println(PrintHyphens.repeat("-", 100))
}
}
} | 0 | Kotlin | 0 | 0 | ee06bebe0d3a7cd411d9ec7b7e317b48fe8c6d70 | 3,256 | CodingChallenges | Apache License 2.0 |
advent-of-code/src/main/kotlin/com/akikanellis/adventofcode/year2022/Day20.kt | akikanellis | 600,872,090 | false | {"Kotlin": 142932, "Just": 977} | package com.akikanellis.adventofcode.year2022
import java.lang.Math.floorMod
object Day20 {
fun sumOfGroveCoordinatesWithWrongDecryptionRoutine(input: String) =
sumOfGroveCoordinates(
input = input,
decryptionKey = 1,
mixes = 1
)
fun sumOfGroveCoordinatesWithCorrectDecryptionRoutine(input: String) =
sumOfGroveCoordinates(
input = input,
decryptionKey = 811_589_153,
mixes = 10
)
private fun sumOfGroveCoordinates(input: String, decryptionKey: Int, mixes: Int): Long {
val originalFileNumbers = originalFileNumbers(input, decryptionKey)
val mixedFileNumbers = originalFileNumbers.toMutableList()
val fileNumbersSize = originalFileNumbers.size - 1
repeat(mixes) {
for (fileNumber in originalFileNumbers) {
val currentFileNumberIndex = mixedFileNumbers.indexOf(fileNumber)
val newFileNumberIndex = floorMod(
currentFileNumberIndex + fileNumber.value,
fileNumbersSize
)
mixedFileNumbers.removeAt(currentFileNumberIndex)
mixedFileNumbers.add(newFileNumberIndex, fileNumber)
}
}
val zeroFileNumberIndex = mixedFileNumbers
.withIndex()
.single { (_, fileNumber) -> fileNumber.value == 0L }
.index
return listOf(
1_000,
2_000,
3_000
).sumOf { groveCoordinateOffset ->
val groveCoordinateFileNumberIndex =
(zeroFileNumberIndex + groveCoordinateOffset) % mixedFileNumbers.size
val groveCoordinateFileNumber = mixedFileNumbers[groveCoordinateFileNumberIndex]
groveCoordinateFileNumber.value
}
}
private fun originalFileNumbers(input: String, decryptionKey: Int) = input.lines()
.filter { it.isNotBlank() }
.mapIndexed { index, line -> FileNumber(index, line.toLong() * decryptionKey) }
private data class FileNumber(val id: Int, val value: Long)
}
| 8 | Kotlin | 0 | 0 | 036cbcb79d4dac96df2e478938de862a20549dce | 2,135 | advent-of-code | MIT License |
src/main/kotlin/warmup/2-recusion.kt | dzca | 581,929,762 | false | {"Kotlin": 75573} | package warmup
/**
* Module 4 is recursion
*/
/**
* binary search
*
* find key from sorted array
*
* example:
* a = arrayOf(-4,2,4,5,9,12)
* key = 5, r = 3
* key = 6, r = -1
*
* learn:
* - Math.round() rounds up to the nearest Integer
* which can be above or below or even equal to the actual value.
* - Math.floor rounds up to the nearest Integer which
* can be equal to or below the actual value.
* - Math.ceil rounds up to the nearest Integer which can
* be equal to or above the actual value.
*/
fun binarySearch(a: Array<Int>, k: Int, l: Int, r: Int): Int{
println("$l, $r")
return if(l > r){
-1
} else {
val m = l + (r-l) / 2
if(a[m] == k ) {
println("found at $m")
m
} else if(a[m] > k){
binarySearch(a, k, l, m - 1)
} else {
binarySearch(a,k, m + 1, r)
}
}
}
/**
* loop implement
*/
fun binarySearchLoop(a: Array<Int>, k: Int, l1: Int, r1: Int): Int{
var l = l1
var r = r1
while(l <= r){
val m = l + (r-l) / 2
if(a[m] == k ) {
println("found at $m")
return m
} else if(a[m] > k){
r = m - 1
} else {
l = m + 1
}
}
return -1
}
/**
* Find maximum in first increasing and then decreasing array
*
* example:
* (18,110,210,452,810,500,101,13) => 810
* (1,2,3,4,5) => 5
*/
fun findMax(a: Array<Int>, l: Int, r: Int): Int{
val m = l + (r-l + 1)/2
val x = a[m]
// println("[$l, $r] => a[$m]=$x")
// terminal condition
return if((m == r && x > a[m-1])|| (x > a[m+1] && x > a[m-1])) {
x
} else if( x < a[m+1]){
findMax(a, m+1, r)
} else {
findMax(a, l, m -1)
}
}
/**
* find the first and last position of a given value form a sorted
* ascending order.
*
* return [-1,-1] if not found
* time complexity is O(log n)
*
* (-1,1,2,2,2,5,6,12,12), 2 => [2,4]
* (21,32,51,70,71), 70 => [3,3]
*/
/**
* find the index of first match
*
* criteria of found:
* 1)v == a[m]
* - m == 0 -> m
* - a[m-1] < v -> m
* 2)a[m] >= v -> find(l,m-1)
* 3)a[m] < v -> find(m+1, r)
* return -1
*
*/
fun findFirst(a:Array<Int>, v: Int, l:Int, r:Int): Int{
if(l > r) return -1
val m = l + (r - l)/2
println("[$l, $r] => a[$m]=${a[m]}")
return if((m==0 || a[m-1] < v) && a[m]==v)
m
else if(a[m] >= v) {
findFirst(a, v, l, m-1)
} else {
findFirst(a, v, m+1, r)
}
}
/**
* find the index of last match
*
* criteria of found:
* 1)v == a[m]
* - m == r -> m
* - a[m+1] > v -> m
* 2)a[m] <= v -> find(m+1, r)
* 3)a[m] > v -> find(l,m-1)
* return -1
*
*/
fun findLast(a:Array<Int>, v: Int, l:Int, r:Int): Int {
if(l > r) return -1
val m = l + (r-l)/2
println("[$l, $r] => a[$m]=${a[m]}")
return if((m==r || a[m+1] > v) && a[m]==v){
m
} else if(a[m] <= v) {
findLast(a, v, m+1, r)
} else {
findLast(a, v, l, m-1)
}
}
fun findFirstLast(a:Array<Int>, v: Int): Array<Int>{
// find left
val l = findFirst(a,v, 0, a.size -1)
println("found l: $l")
// find right
val r = findLast(a,v, l, a.size -1)
println("found r: $r")
println("done")
return arrayOf<Int>(l,r)
}
/**
* Find min value in a rotated array
* Array is rotated by k
* - [n-k, n-1] items increase
* - [0, n-k-1] values increase
* - x[n-k-1]>x[0]>x[n-1]>x[n-k]
*
* example:
* {5,6,7,8,9,1,2,3,4} => 1
* {8,9,3,4,5,6,7} => 3
* {5,6,7,8,9} => 5
* {8,7}=> 7
*/
/**
* a[l] is always greater than a[r] if array is rotated
*
* l < r
* 1) a[l] < a[r] ->a[l]
* 2) a[m] > a[r] -> find(m+1, r)
* 3) a[m] < a[r] -> find(l,m)
*
* space O(1), time O(log n)
*/
fun minInRotatedArray(a: Array<Int>, l1: Int, r1: Int): Int{
var l = l1
var r = r1
while(l < r){
if(a[l]< a[r]) return a[l]
val m = l + (r -l)/2
if(a[m] > a[r]) l=m+1 else r=m
}
return a[l]
}
/**
* Search a key in a sorted 2D [m x n] matrix
*
* examples:
* 1) find 6 => true
* 1, 2, 6, 7
* 12,13,16,21
* 23,35,36,48
*
* 2) find 7 => false
*
* 1, 2, 6
* 12,13,16
* 23,35,36
*
*/
fun findInRow(a: Array<Array<Int>>, y:Int, r1:Int, k: Int): Boolean{
var l = 0
var r = r1
while(l < r){
val m = l + (r -l)/2
println("col $m")
if(a[y][m] == k) {
println("found")
return true
} else if(a[y][m] > k) {
r = m - 1
println("move col r=> $r")
} else {
l = m
println("move col l=> $l")
}
}
return false
}
/**
* find k in which row, then search that row with b search.
* m = l + (r-l)/2
* 1) a[l][0] < k && a[l][n-1] > k => findInRow()
*
*
* 2) a[l][0]
*/
fun findInMatrix(a: Array<Array<Int>>,y:Int, x:Int, k: Int): Boolean {
var l = 0
var r = y - 1
while(l <= r) {
val m = l + (r-l)/2
println("row $m")
if(a[m][0] < k && a[m][x-1] >= k){
return findInRow(a, m, x, k)
} else if(a[m][0] > k ){
r = m - 1
println("move row r=> $r")
} else {
l = m + 1
println("move row l=> $l")
}
}
return false
}
/**
* Median of two sorted arrays
* Merge two array to size x+y=n and find the median
*
* median:
* - if n is odd, mid = middle element
* - if n is even, mid = average of two middle elements
* example:
* A=(1,3,6) B=(2,8,12) => x = 4.5
* A=(1,3,4,6,9) B=(2,5,7,8,10) => x = 5.5
*/
fun medianOfArrays(a: Array<Int>, b:Array<Int>): Float {
return 5.5F
} | 0 | Kotlin | 0 | 0 | b1e7d1cb739e21ed7e8b7484d6efcd576857830f | 5,675 | kotlin-algrithm | MIT License |
src/main/kotlin/com/github/solairerove/algs4/leprosorium/strings/MinimumCharsForWords.kt | solairerove | 282,922,172 | false | {"Kotlin": 251919} | package com.github.solairerove.algs4.leprosorium.strings
import kotlin.math.max
fun main() {
print(minimumCharsForWords(listOf("only", "after", "we", "have", "lost", "everything")))
}
// O(n * l) time | O(c) space
// n is number of words
// l is length of longest word
// c is number of unique chars
private fun minimumCharsForWords(words: List<String>): List<Char> {
val maxCharFreq = mutableMapOf<Char, Int>()
for (word in words) {
val charFreq = mutableMapOf<Char, Int>()
word.forEach { charFreq[it] = charFreq.getOrDefault(it, 0) + 1 }
for ((char, freq) in charFreq) {
if (char in maxCharFreq) {
maxCharFreq[char] = max(freq, maxCharFreq[char]!!)
} else {
maxCharFreq[char] = freq
}
}
}
val chars = mutableListOf<Char>()
for ((char, freq) in maxCharFreq) {
for (i in 0 until freq) {
chars.add(char)
}
}
return chars
}
| 1 | Kotlin | 0 | 3 | 64c1acb0c0d54b031e4b2e539b3bc70710137578 | 989 | algs4-leprosorium | MIT License |
kotlin/src/katas/kotlin/leetcode/palindrome_ignoring_punctuation/NoPunctuationPalindrome.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.palindrome_ignoring_punctuation
import datsok.shouldEqual
import org.junit.Test
/**
* Given a string with punctuations, upper case and lower case letters,
* check if it can be read the same from the start and from the end by ignoring punctuations and capitalization.
*/
class NoPunctuationPalindromeTests {
private val isPalindrome: (String) -> Boolean = ::isPalindrome
@Test fun examples() {
isPalindrome("") shouldEqual true
isPalindrome(",,,") shouldEqual true
isPalindrome(",,,a") shouldEqual true
isPalindrome("aba") shouldEqual true
isPalindrome("abba") shouldEqual true
isPalindrome("abcba") shouldEqual true
isPalindrome("a,bA") shouldEqual true
isPalindrome("a,b,c") shouldEqual false
isPalindrome(",,,abba,") shouldEqual true
isPalindrome(",,,abbx,") shouldEqual false
isPalindrome("--ZZX") shouldEqual false
}
}
private fun isPalindrome(s: String): Boolean {
if (s.isEmpty()) return true
var i = 0
var j = s.length - 1
while (i <= j) {
while (i <= j && !s[i].isLetter()) i++
while (i <= j && !s[j].isLetter()) j--
if (i > j) break
if (s[i++].toLowerCase() != s[j--].toLowerCase()) return false
}
return true
}
private fun isPalindrome_(s: String): Boolean {
val s2 = s.filter { it.isLetter() }.toLowerCase()
val midIndex = s2.length / 2
return s2.substring(0, midIndex) ==
s2.substring(if (s2.length % 2 == 0) midIndex else midIndex + 1).reversed()
}
| 7 | Roff | 3 | 5 | 0f169804fae2984b1a78fc25da2d7157a8c7a7be | 1,576 | katas | The Unlicense |
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2015/2015-03.kt | ferinagy | 432,170,488 | false | {"Kotlin": 787586} | package com.github.ferinagy.adventOfCode.aoc2015
import com.github.ferinagy.adventOfCode.Coord2D
import com.github.ferinagy.adventOfCode.readInputText
fun main() {
val input = readInputText(2015, "03-input")
val test1 = readInputText(2015, "03-test1")
println("Part1:")
println(visitsAtLeastOnce(test1))
println(visitsAtLeastOnce(input))
println()
println("Part2:")
println(visitsAtLeastOnceWithRobot(test1))
println(visitsAtLeastOnceWithRobot(input))
}
private fun visitsAtLeastOnce(input: String): Int {
return visitedHouses(input.toList()).size
}
private fun visitsAtLeastOnceWithRobot(input: String): Int {
val (l1, l2) = input.withIndex().partition { it.index % 2 == 0 }.let { (l1, l2) ->
l1.map { it.value } to l2.map { it.value }
}
val v1 = visitedHouses(l1)
val v2 = visitedHouses(l2)
return (v1 + v2).size
}
private fun visitedHouses(input: List<Char>): Set<Coord2D> {
val map = mapOf(
'^' to Coord2D(0, -1),
'v' to Coord2D(0, 1),
'>' to Coord2D(1, 0),
'<' to Coord2D(-1, 0),
)
var current = Coord2D(0, 0)
val visited = mutableSetOf(current)
input.forEach {
current += map[it]!!
visited += current
}
return visited
}
| 0 | Kotlin | 0 | 1 | f4890c25841c78784b308db0c814d88cf2de384b | 1,280 | advent-of-code | MIT License |
src/trees/SameTree.kt | develNerd | 456,702,818 | false | {"Kotlin": 37635, "Java": 5892} | package trees
/**
*
Given the roots of two binary trees p and q, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.
Example 1:
Input: p = [1,2,3], q = [1,2,3]
Output: true
Example 2:
Input: p = [1,2], q = [1,null,2]
Output: false
Example 3:
Input: p = [1,2,1], q = [1,1,2]
Output: false
Constraints:
The number of nodes in both trees is in the range [0, 100].
-104 <= Node.val <= 104
*
* */
/**
* Example:
* var ti = TreeNode(5)
* var v = ti.`val`
* Definition for a binary tree node.
* class TreeNode(var `val`: Int) {
* var left: TreeNode? = null
* var right: TreeNode? = null
* }
*/
/**
*Solution Summary :
2 Binary Trees are said to be same if their identical and have the same number of nodes
and have same values in those nodes.
So what we do is basically compare the left's(left of both trees) of both trees and compare
each of their rights too.
*
*
* */
class BinaryTreeNode(var `val`: Int) {
var left: BinaryTreeNode? = null
var right: BinaryTreeNode? = null
}
fun isSameTree(p: BinaryTreeNode?, q: BinaryTreeNode?): Boolean {
/**
* 1.
* We need a base condition for when the recursive function should
* terminate.When both treesNodes are null we return a true
* because that'll be the end of the tree
*
*
* */
if(p == null && q== null){
return true
}
/**
* Return a false if treeNodes instances aren't equal
* */
if(p != null && q==null){
return false
}
/**
* Return a false if treeNodes instances aren't equal
* */
if(q != null && p==null){
return false
}
/**
* Return a false if treeNodes values aren't equal
* */
if (p?.`val` != q?.`val`) {
return false;
}
/**
* Recur isSameTree on the left's and right's of both trees
* */
return isSameTree(p?.left,q?.left) && isSameTree(p?.right,q?.right)
}
| 0 | Kotlin | 0 | 0 | 4e6cc8b4bee83361057c8e1bbeb427a43622b511 | 2,054 | Blind75InKotlin | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/MinSwaps.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2021 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import kotlin.math.max
/**
* Minimum Swaps to Group All 1's Together
* @see <a href="https://leetcode.com/problems/minimum-swaps-to-group-all-1s-together/">Source</a>
*/
fun interface MinSwaps {
operator fun invoke(data: IntArray): Int
}
/**
* Approach 1: Sliding Window with Two Pointers
* Time complexity: O(n)
* Space complexity: O(1)
*/
class MinSwapsTwoPointers : MinSwaps {
override operator fun invoke(data: IntArray): Int {
val ones: Int = data.sum()
var cntOne = 0
var maxOne = 0
var left = 0
var right = 0
while (right < data.size) {
// updating the number of 1's by adding the new element
cntOne += data[right++]
// maintain the length of the window to ones
if (right - left > ones) {
// updating the number of 1's by removing the oldest element
cntOne -= data[left++]
}
// record the maximum number of 1's in the window
maxOne = max(maxOne, cntOne)
}
return ones - maxOne
}
}
/**
* Approach 2: Sliding Window with Deque (Double-ended Queue)
* Time complexity: O(n)
* Space complexity: O(n)
*/
class MinSwapsDeque : MinSwaps {
override operator fun invoke(data: IntArray): Int {
val ones: Int = data.sum()
var cntOne = 0
var maxOne = 0
// maintain a deque with the size = ones
val deque = ArrayDeque<Int>()
for (i in data.indices) {
// we would always add the new element into the deque
deque.addLast(data[i])
cntOne += data[i]
// when there are more than ones elements in the deque,
// remove the leftmost one
if (deque.size > ones) {
cntOne -= deque.removeFirst()
}
maxOne = max(maxOne, cntOne)
}
return ones - maxOne
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,569 | kotlab | Apache License 2.0 |
src/main/kotlin/de/dikodam/calendar/Day12.kt | dikodam | 433,719,746 | false | {"Kotlin": 51383} | package de.dikodam.calendar
import de.dikodam.AbstractDay
import de.dikodam.executeTasks
import kotlin.time.ExperimentalTime
@ExperimentalTime
fun main() {
Day12().executeTasks()
}
const val start = "start"
const val end = "end"
class Day12 : AbstractDay() {
val testInput1 = """start-A
start-b
A-c
A-b
b-d
A-end
b-end""".trim().lines()
val testInput2 = """dc-end
HN-start
start-kj
dc-start
dc-HN
LN-dc
HN-end
kj-sa
kj-HN
kj-dc""".trim().lines()
val testInput3 = """fs-end
he-DX
fs-he
start-DX
pj-DX
end-zg
zg-sl
zg-pj
pj-he
RW-he
fs-DX
pj-RW
zg-RW
start-pj
he-WI
zg-he
pj-fs
start-RW""".trim().lines()
val adjacencyList: List<Pair<String, String>> =
// testInput1 // 36 check
// testInput2 // 103 check
// testInput3 // 3509
readInputLines()
.buildAdjacencyList()
fun List<String>.buildAdjacencyList(): List<Pair<String, String>> {
return this.map { it.split("-") }
.map { (parent, child) -> parent to child }
.flatMap { (left, right) -> listOf(left to right, right to left) }
}
override fun task1(): String {
val paths = dfs(start, adjacencyList, currentPath = listOf(start), visited = setOf(start))
return "${paths.size}"
}
fun String.isSmallCave() =
this.all { it.isLowerCase() }
fun dfs(
currentNode: String,
adjacencyList: List<Pair<String, String>>,
currentPath: List<String>,
visited: Set<String>
): List<List<String>> {
if (currentNode == end) {
return listOf(currentPath)
}
val children = adjacencyList.getNeighbors(currentNode)
.filterNot { it in visited }
return if (children.isEmpty()) {
emptyList()
} else {
val newVisited = if (currentNode.isSmallCave()) visited + currentNode else visited
children.flatMap { child -> dfs(child, adjacencyList, currentPath + child, newVisited) }
}
}
fun List<Pair<String, String>>.getNeighbors(parent: String): List<String> {
return this.filter { (parentNode, _) -> parent == parentNode }
.map { it.second }
}
override fun task2(): String {
val paths = dfs2(
currentPath = listOf(start),
adjacencyList
)
return "${paths.size}"
}
fun dfs2(currentPath: List<String>, adjacencyList: List<Pair<String, String>>): List<List<String>> {
val currentNode = currentPath.last()
if (currentNode == end) {
return listOf(currentPath)
}
val wasSmallCaveVisitedTwice = currentPath
.filterNot { it == start }
.filter { it.isSmallCave() }
.groupingBy { it }
.eachCount()
.any { (_, count) -> count == 2 }
val nonVisitableCaves = if (wasSmallCaveVisitedTwice) {
currentPath.filter { it.isSmallCave() }
} else {
listOf(start)
}
val neighbors = adjacencyList.getNeighbors(currentNode)
.filterNot { it in nonVisitableCaves }
return if (neighbors.isEmpty()) {
emptyList()
} else {
neighbors.flatMap { child -> dfs2(currentPath + child, adjacencyList) }
}
}
} | 0 | Kotlin | 0 | 1 | 4934242280cebe5f56ca8d7dcf46a43f5f75a2a2 | 3,309 | aoc-2021 | MIT License |
src/Day03.kt | marvingrewe | 573,069,044 | false | {"Kotlin": 6473} | import kotlin.system.measureTimeMillis
fun main() {
val day = "Day03"
fun Char.priority() = when (code) {
in 'a'.code..'z'.code -> (code - 'a'.code) + 1
in 'A'.code..'Z'.code -> (code - 'A'.code) + 27
else -> error("no priority for $this")
}
fun part1(input: List<String>): Int = input
.sumOf {
it.chunked(it.length / 2, CharSequence::toSet)
.reduce(Set<Char>::intersect)
.single()
.priority()
}
fun part2(input: List<String>): Int = input
.chunked(3)
.sumOf {
it.map(String::toSet)
.reduce(Set<Char>::intersect)
.single()
.priority()
}
val testInput = readInput(day + "_test")
val input = readInput(day)
var result: Any
println("Test 1 solved in ${measureTimeMillis { result = part1(testInput) }}ms with result: $result, expected: 157")
println("Test 2 solved in ${measureTimeMillis { result = part2(testInput) }}ms with result: $result, expected: 70")
println("Part 1 solved in ${measureTimeMillis { result = part1(input) }}ms with result: $result")
println("Part 2 solved in ${measureTimeMillis { result = part2(input) }}ms with result: $result")
}
| 0 | Kotlin | 0 | 0 | adec59f236b5f92cfcaf9e595fb913bf0010ac41 | 1,291 | advent-of-code-2022 | Apache License 2.0 |
src/jvmMain/kotlin/algorithm/graph/WeightedGraphModel.kt | DaniiLBez | 659,158,302 | false | null | package algorithm.graph
import algorithm.dijkstra.Dijkstra
import algorithm.dijkstra.ShortestPath
import java.util.*
class WeightedGraphModel(stream: String, separator: String) {
private var graph: GraphModel? = null
private var vertexNameOfNumber = hashMapOf<String, Int>()
init {
val graphStringRepresentation = prepareGraphStringRepresentation(stream, separator)
val graphSize = graphStringRepresentation.stream().map { obj: List<String> -> obj.size }
.reduce { firstSize: Int, secondSize: Int ->
Integer.sum(
firstSize,
secondSize
)
}.orElse(0)
buildGraphFromStringRepresentation(graphStringRepresentation, graphSize)
}
private fun prepareGraphStringRepresentation(stream: String, separator: String): List<List<String>> {
val graphStringRepresentation = mutableListOf<List<String>>()
val scanner = Scanner(stream)
while (scanner.hasNext()) {
val stringGraph = scanner.nextLine().split(separator).toList()
graphStringRepresentation.add(stringGraph)
}
return graphStringRepresentation
}
private fun buildGraphFromStringRepresentation(graphStringRepresentation: List<List<String>>, graphSize: Int) {
graph = GraphModel(graphSize)
for (graphLine in graphStringRepresentation) {
val sourceVertexName = graphLine[0]
if (graphLine.size > 2) {
val targetVertexName = graphLine[1]
vertexNameOfNumber.putIfAbsent(sourceVertexName, vertexNameOfNumber.size)
vertexNameOfNumber.putIfAbsent(targetVertexName, vertexNameOfNumber.size)
val sourceVertexNumber = vertexNameOfNumber[sourceVertexName]!!
val targetVertexNumber = vertexNameOfNumber[targetVertexName]!!
val weight = graphLine[2].toDouble()
graph!!.addEdge(DirectedEdge(sourceVertexNumber, targetVertexNumber, weight))
} else {
vertexNameOfNumber.putIfAbsent(sourceVertexName, vertexNameOfNumber.size)
}
}
}
fun index(s: String): Int {
return vertexNameOfNumber[s]!!
}
fun name(vertex: Int): String {
return ArrayList(vertexNameOfNumber.keys).stream()
.filter { el: String ->
(
vertexNameOfNumber[el]
== vertex
)
}
.findFirst()
.get()
}
fun shortestPath(source: String, target: String, algorithm: Dijkstra): List<ShortestPath> {
return algorithm.buildWay(graph!!, index(source))
}
}
| 0 | Kotlin | 0 | 2 | 63f4c707869c10f941bde3b5e072a92e3cf068c3 | 2,287 | stud_practice | MIT License |
src/Day10.kt | mandoway | 573,027,658 | false | {"Kotlin": 22353} | fun shouldCheckSignalStrength(cycle: Int) = (cycle + 20) % 40 == 0
fun String.completionTime() = when (this) {
"noop" -> 1
else -> 2
}
fun runSimulation(commands: List<String>, onEachCycle: (cycle: Int, registerValue: Int) -> Unit) {
var cycle = 0
var registerValue = 1
commands.forEach { cmd ->
val cyclesToComplete = cmd.completionTime()
val addParam = if (cmd.startsWith("addx")) {
cmd.split(" ").last().toInt()
} else {
0
}
repeat(cyclesToComplete) {
cycle++
onEachCycle(cycle, registerValue)
}
registerValue += addParam
}
}
fun retrieveSignalStrengths(commands: List<String>): Int {
var totalSignalStrength = 0
runSimulation(commands) { cycle, registerValue ->
if (shouldCheckSignalStrength(cycle)) {
totalSignalStrength += cycle * registerValue
}
}
return totalSignalStrength
}
fun drawCRTScreen(commands: List<String>) {
val pixels = mutableListOf<Char>()
runSimulation(commands) { _, registerValue ->
val nextPixel = if (pixels.size % 40 in registerValue - 1..registerValue + 1) {
'#'
} else {
'.'
}
pixels.add(nextPixel)
}
pixels.chunked(40)
.forEach { println(it.joinToString("")) }
}
fun main() {
fun part1(input: List<String>): Int {
return retrieveSignalStrengths(input)
}
fun part2(input: List<String>) {
drawCRTScreen(input)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day10_test")
check(part1(testInput) == 13140)
val input = readInput("Day10")
println(part1(input))
part2(input)
}
| 0 | Kotlin | 0 | 0 | 0393a4a25ae4bbdb3a2e968e2b1a13795a31bfe2 | 1,778 | advent-of-code-22 | Apache License 2.0 |
2023/src/main/kotlin/net/daams/solutions/11b.kt | Michiel-Daams | 573,040,288 | false | {"Kotlin": 39925, "Nim": 34690} | package net.daams.solutions
import net.daams.Solution
class `11a`(input: String): Solution(input) {
override fun run() {
val splitInput = input.split("\n")
val xToExpand = mutableListOf<Int>()
val yToExpand = mutableListOf<Int>()
splitInput.forEachIndexed { index, s ->
if (s.all { it == '.' }) {
yToExpand.add(index)
}
}
for (x in 0 .. splitInput[0].lastIndex) {
var expand = true
splitInput.forEachIndexed { y, s ->
if (splitInput[y][x] != '.') expand = false
}
if (expand) xToExpand.add(x)
}
val expandedUniverse = mutableListOf<String>()
val galaxyLocations = mutableListOf<Pair<Int, Int>>()
var yExpansion = ""
for (i in 0 .. splitInput[0].lastIndex + xToExpand.size) {
yExpansion += "."
}
splitInput.forEachIndexed{ y, string ->
if (yToExpand.contains(y)) expandedUniverse.add(yExpansion)
var newRow = ""
for (x in 0 .. splitInput[0].lastIndex) {
if (xToExpand.contains(x)) newRow += "."
newRow += splitInput[y][x]
}
expandedUniverse.add(newRow)
}
expandedUniverse.forEachIndexed { y, row ->
row.forEachIndexed { x, c ->
if (c == '#') galaxyLocations.add(Pair(y, x))
}
}
var diff = 0
galaxyLocations.forEach{ pair ->
galaxyLocations.forEach { pair2 ->
diff += getDistance(pair, pair2)
}
}
expandedUniverse.forEach { println(it) }
println(diff / 2)
}
fun getDistance(a: Pair<Int, Int>, b: Pair<Int, Int>): Int {
var diff = 0
diff += if (a.first > b.first) a.first - b.first
else b.first - a.first
diff += if (a.second > b.second) a.second - b.second
else b.second - a.second
return diff
}
}
| 0 | Kotlin | 0 | 0 | f7b2e020f23ec0e5ecaeb97885f6521f7a903238 | 2,024 | advent-of-code | MIT License |
src/cn/leetcode/codes/simple94/Simple94.kt | shishoufengwise1234 | 258,793,407 | false | {"Java": 771296, "Kotlin": 68641} | package cn.leetcode.codes.simple94
import cn.leetcode.codes.common.TreeNode
import cn.leetcode.codes.createTreeNode
import cn.leetcode.codes.out
import java.util.*
import kotlin.collections.ArrayList
fun main() {
val nums = arrayOf<Int?>(1,2)
val treeNode = createTreeNode(nums)
val re = inorderTraversal(treeNode)
val re2 = inorderTraversal2(treeNode)
out("re = $re")
out("re2 = $re2")
}
/*
94. 二叉树的中序遍历
给定一个二叉树的根节点 root ,返回它的 中序 遍历。
示例 1:
输入:root = [1,null,2,3]
输出:[1,3,2]
示例 2:
输入:root = []
输出:[]
示例 3:
输入:root = [1]
输出:[1]
示例 4:
输入:root = [1,2]
输出:[2,1]
示例 5:
输入:root = [1,null,2]
输出:[1,2]
提示:
树中节点数目在范围 [0, 100] 内
-100 <= Node.val <= 100
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
*/
//递归解法 左子树 -> 根节点 -> 右子树
fun inorderTraversal(root: TreeNode?): List<Int> {
val list = ArrayList<Int>()
if (root == null) return list
inorderLoop(root, list)
return list
}
fun inorderLoop(node: TreeNode?, list: ArrayList<Int>) {
if (node == null) return
//先遍历左子树
inorderLoop(node.left, list)
//根节点
list.add(node.`val`)
//后遍历右子树
inorderLoop(node.right, list)
}
//迭代解法
fun inorderTraversal2(root: TreeNode?): List<Int> {
val list = ArrayList<Int>()
if (root == null) return list
var node = root
//借助队列
val deque = LinkedList<TreeNode>()
while (!deque.isEmpty() || node != null){
//持续遍历左子树
while (node != null){
deque.push(node)
node = node.left
}
//从底部抽取出节点 再遍历
node = deque.pop()
list.add(node.`val`)
node = node.right
}
return list
}
| 0 | Java | 0 | 0 | f917a262bcfae8cd973be83c427944deb5352575 | 1,947 | LeetCodeSimple | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/ParallelCourses3.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import java.util.LinkedList
import java.util.Queue
import kotlin.math.max
/**
* 2050. Parallel Courses III
* @see <a href="https://leetcode.com/problems/parallel-courses-iii">Source</a>
*/
fun interface ParallelCourses3 {
operator fun invoke(n: Int, relations: Array<IntArray>, time: IntArray): Int
}
class ParallelCourses3Sort : ParallelCourses3 {
override fun invoke(n: Int, relations: Array<IntArray>, time: IntArray): Int {
val graph: MutableMap<Int, MutableList<Int>> = HashMap()
for (i in 0 until n) {
graph[i] = ArrayList()
}
val indegree = IntArray(n)
for (edge in relations) {
val x = edge[0] - 1
val y = edge[1] - 1
graph[x]!!.add(y)
indegree[y]++
}
val queue: Queue<Int> = LinkedList()
val maxTime = IntArray(n)
for (node in 0 until n) {
if (indegree[node] == 0) {
queue.add(node)
maxTime[node] = time[node]
}
}
while (queue.isNotEmpty()) {
val node: Int = queue.remove()
for (neighbor in graph[node]!!) {
maxTime[neighbor] = max(maxTime[neighbor], maxTime[node] + time[neighbor])
indegree[neighbor]--
if (indegree[neighbor] == 0) {
queue.add(neighbor)
}
}
}
var ans = 0
for (node in 0 until n) {
ans = max(ans, maxTime[node])
}
return ans
}
}
class ParallelCourses3DFS : ParallelCourses3 {
private val graph: MutableMap<Int, MutableList<Int>> = HashMap()
private val memo: MutableMap<Int, Int> = HashMap()
override fun invoke(n: Int, relations: Array<IntArray>, time: IntArray): Int {
for (i in 0 until n) {
graph[i] = ArrayList()
}
for (edge in relations) {
val x = edge[0] - 1
val y = edge[1] - 1
graph[x]?.add(y)
}
var ans = 0
for (node in 0 until n) {
ans = max(ans, dfs(node, time))
}
return ans
}
private fun dfs(node: Int, time: IntArray): Int {
if (memo.containsKey(node)) {
return memo[node] ?: 0
}
if (graph[node]?.size == 0) {
return time[node]
}
var ans = 0
for (neighbor in graph[node]!!) {
ans = max(ans, dfs(neighbor, time))
}
memo[node] = time[node] + ans
return time[node] + ans
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 3,216 | kotlab | Apache License 2.0 |
src/Day03.kt | adrianforsius | 573,044,406 | false | {"Kotlin": 68131} | import org.assertj.core.api.Assertions.assertThat
fun code(it: Char): Int = when (it) {
in 'a'..'z' -> it - 'a' + 1
in 'A'..'Z' -> it - 'A' + 27
else -> throw error("nope")
}
fun main() {
fun part1(input: List<String>): Int = input.map{
it.split("\n")
listOf(it.substring(0, it.length/2), it.substring(it.length/2, it.length))
}.map{ that ->
that.first().filter{
it in (that[1])
}
}.sumOf{
code(it.first())
}
fun part2(input: List<String>): Int = input.map {
it.split("\n")
}.map{
it.first().toSet()
}.chunked(3).flatMap{
it.reduce { acc, next -> acc.intersect(next) }
}.sumOf { code(it) }
// test if implementation meets criteria from the description, like:
// Test
val testInput = readInput("Day03_test")
val output1 = part1(testInput)
assertThat(output1).isEqualTo(157)
// Answer
val input = readInput("Day03")
val outputAnswer1 = part1(input)
assertThat(outputAnswer1).isEqualTo(8088)
// Test
val output2 = part2(testInput)
assertThat(output2).isEqualTo(70)
// Answer
val outputAnswer2 = part2(input)
assertThat(outputAnswer2).isEqualTo(2522)
}
| 0 | Kotlin | 0 | 0 | f65a0e4371cf77c2558d37bf2ac42e44eeb4bdbb | 1,273 | kotlin-2022 | Apache License 2.0 |
src/main/kotlin/com/hj/leetcode/kotlin/problem1161/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem1161
import com.hj.leetcode.kotlin.common.model.TreeNode
/**
* LeetCode page: [1161. Maximum Level Sum of a Binary Tree](https://leetcode.com/problems/maximum-level-sum-of-a-binary-tree/);
*/
class Solution {
/* Complexity:
* Time O(N) and Space O(H) where N and H are the number nodes and height of root;
*/
fun maxLevelSum(root: TreeNode?): Int {
checkNotNull(root)
return minLevelHavingMaxSum(levelSums(root))
}
private fun minLevelHavingMaxSum(levelSums: Map<Int, Int>): Int {
val maxSum = levelSums.values.max()!!
var result: Int? = null
for ((level, sum) in levelSums) {
if (sum == maxSum) {
result = minOf(level, (result ?: level))
}
}
return checkNotNull(result)
}
private fun levelSums(root: TreeNode): Map<Int, Int> {
val result = hashMapOf<Int, Int>() // entry = (level, sum)
root.dfs(currentLevel = 1) { level: Int, value: Int ->
result[level] = (result[level] ?: 0) + value
}
return result
}
private fun TreeNode.dfs(currentLevel: Int, onEachNode: (level: Int, value: Int) -> Unit) {
onEachNode(currentLevel, `val`)
left?.dfs(currentLevel + 1, onEachNode)
right?.dfs(currentLevel + 1, onEachNode)
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 1,368 | hj-leetcode-kotlin | Apache License 2.0 |
src/chapter4/section4/ex20.kt | w1374720640 | 265,536,015 | false | {"Kotlin": 1373556} | package chapter4.section4
import edu.princeton.cs.algs4.In
import edu.princeton.cs.algs4.Queue
import extensions.formatDouble
import extensions.spendTimeMillis
import kotlin.math.E
import kotlin.math.ln
import kotlin.math.min
import kotlin.math.pow
/**
* 从网上或者报纸上找到一张汇率表并用它构造一张套汇表。
* 注意:不要使用根据若干数据计算得出的汇率表,它们的精度有限。
* 附加题:从汇率市场上赚点外快!
*/
fun ex20(digraph: EdgeWeightedDigraph): MinWeightCycleFinder.Path? {
var minPath: MinWeightCycleFinder.Path? = null
for (s in 0 until digraph.V) {
val finder = MinWeightCycleFinder(digraph, s)
val path = finder.getPath()
if (path != null) {
if (minPath == null || path < minPath) {
minPath = path
}
}
}
return minPath
}
/**
* 获取一张真实汇率表
* 原始数据来源:https://www.xe.com/zh-CN/currencytables/?from=USD&date=2021-01-01
* 获取2021年1月1日167种货币之间的兑换比率,
* 处理后的数据放在Github的另一个仓库中,可自行下载后放入data目录中,链接如下:
* https://github.com/w1374720640/utility-room/blob/main/Algorithms/realRates.txt
*/
fun getRealRates(size: Int): Pair<Array<String>, EdgeWeightedDigraph> {
val input = In("./data/realRates.txt")
val V = min(size, input.readLine().toInt())
val names = Array(V) { "" }
val digraph = EdgeWeightedDigraph(V)
repeat(V) { v ->
val list = input.readLine().split(Regex(" +"))
names[v] = list[0]
repeat(V) { w ->
val ratio = list[w + 1].toDouble()
digraph.addEdge(DirectedEdge(v, w, -1.0 * ln(ratio)))
}
}
return names to digraph
}
fun main() {
var size = 0
repeat(9) {
size += 20
val pair = getRealRates(size)
val names = pair.first
val digraph = pair.second
println("V=${names.size}")
val time = spendTimeMillis {
val minPath = ex20(digraph)
if (minPath == null) {
println("Does not contain cycle")
} else {
val iterator = minPath.iterator()
val firstEdge = iterator.next()
val queue = Queue<Int>()
queue.enqueue(firstEdge.from())
queue.enqueue(firstEdge.to())
while (iterator.hasNext()) {
val edge = iterator.next()
queue.enqueue(edge.to())
}
// 计算利润
val profit = E.pow(minPath.weight * -1.0) - 1
println("profit=${formatDouble(profit, 10)} minPath: ${minPath.joinToString()}")
// 打印环中货币的名称,长度最大为V+1
println("size: ${queue.size()} cycle: ${queue.joinToString { names[it] }}")
}
}
println("spend $time ms")
println()
}
} | 0 | Kotlin | 1 | 6 | 879885b82ef51d58efe578c9391f04bc54c2531d | 3,011 | Algorithms-4th-Edition-in-Kotlin | MIT License |
src/main/kotlin/nl/jackploeg/aoc/_2022/calendar/day07/Day07.kt | jackploeg | 736,755,380 | false | {"Kotlin": 318734} | package nl.jackploeg.aoc._2022.calendar.day07
import javax.inject.Inject
import nl.jackploeg.aoc.generators.InputGenerator.InputGeneratorFactory
import nl.jackploeg.aoc.utilities.readStringFile
class Day07 @Inject constructor(
private val generatorFactory: InputGeneratorFactory,
) {
fun partOne(filename: String) =
dirsLessOrEqual(100000, filename)
fun partTwo(filename: String) =
dirSizeForEnoughFreeSpace(70000000, 30000000, filename)
fun dirsLessOrEqual(maxSize: Int, fileName: String): Int {
val input = readStringFile(fileName)
val tree = readTree(input)
return tree.flattened().filter { it.getSize() <= maxSize }.sumOf { it.getSize() }
}
fun dirSizeForEnoughFreeSpace(totalSize: Int, neededFree: Int, fileName: String): Int {
val input = readStringFile(fileName)
val tree = readTree(input)
val freeSpace = totalSize - tree.getSize()
val needed = neededFree - freeSpace
return tree.flattened().filter { it.getSize() >= needed }.minByOrNull { it.getSize() }!!.getSize()
}
fun readTree(lines: List<String>): Directory {
val root = Directory.create("/", null)
var currentDir = root
var i = 0
do {
val line = lines[i]
if (line.startsWith("$")) {
val commandLine = line.substring(2).split(" ")
if (commandLine[0] == "cd") {
if (commandLine[1] == "/") {
currentDir = root
} else if (commandLine[1] == "..") {
if (currentDir != root) {
currentDir = currentDir.parent!!
}
} else {
currentDir = currentDir.children.first { it.name == commandLine[1] } as Directory
}
} else if (commandLine[0] == "ls") {
// do nothing
}
} else {
val entry = line.split(" ")
if (entry[0] == "dir") {
val newDir = Directory.create(entry[1], currentDir)
currentDir.children.add(newDir)
} else {
val newFile = File(entry[1], currentDir, Integer.parseInt(entry[0]))
currentDir.children.add(newFile)
}
}
i++
} while (i < lines.size)
return root
}
open class Node(val name: String, val parent: Directory?)
class File(name: String, parent: Directory, val size: Int) : Node(name, parent)
class Directory(name: String, parent: Directory?, val children: MutableSet<Node>) : Node(name, parent) {
companion object {
fun create(name: String, parent: Directory?) = Directory(name, parent, HashSet())
}
fun getSize(): Int {
return children.filterIsInstance<File>().sumOf { it.size } + children.filterIsInstance<Directory>()
.sumOf { it.getSize() }
}
fun flattened(): List<Directory> {
val allRoles = mutableListOf<Directory>()
this.flattenedTo(allRoles)
return allRoles
}
private fun flattenedTo(destination: MutableCollection<Directory>) {
destination.add(this)
children.filterIsInstance<Directory>().forEach { it.flattenedTo(destination) }
}
}
}
| 0 | Kotlin | 0 | 0 | f2b873b6cf24bf95a4ba3d0e4f6e007b96423b76 | 3,462 | advent-of-code | MIT License |
src/main/kotlin/com/github/vqvu/eulerproject/Problem9.kt | vqvu | 57,861,531 | false | null | package com.github.vqvu.eulerproject
import java.util.ArrayList
/**
* @author victor
*/
fun main(args: Array<String>) {
// The following properties from https://en.wikipedia.org/wiki/Pythagorean_triple#Elementary_properties_of_primitive_Pythagorean_triples are used.
// - Exactly one of a, b is odd
// - c is odd
// - Exactly one of a, b is divisible by 3
// - Exactly one of a, b is divisible by 4
val sum: Int = 1000
var pythaTriples: MutableList<Triple<Int, Int, Int>> = ArrayList()
// Case: a is divisible by 3.
// Since b + c > 2 * a => 3 * a < sum
// Since c > b => b < (sum - a) / 2
// Since b is divisible by 4 and is thus even =>
// a must be odd and not divisible by 4
for (a in 3..(sum / 3) step 3) {
if (a % 4 == 0 || a % 2 == 0) {
continue
}
val initialB = MathFn.roundUp(a, 4)
for (b in initialB..(sum - a) / 2 step 4) {
val c = 1000 - a - b
if (c < b) {
continue
}
if (a * a + b * b == c * c) {
pythaTriples.add(Triple(a, b, c))
}
}
}
// Case: a is divisible by 4
// Since b + c > 2 * a => 3 * a < sum
// Since c > b => b < (sum - a) / 2
// Since a is divisible by 4 and is thus even =>
// b must be odd
for (a in 4..(sum / 3) step 4) {
if (a % 3 == 0) {
continue
}
val closestMultiple3 = MathFn.roundUp(a, 3)
val initialB: Int
if (closestMultiple3 % 2 == 0) {
initialB = closestMultiple3 + 3
} else {
initialB = closestMultiple3
}
for (b in initialB..(sum - a) / 2 step 6) {
val c = 1000 - a - b
if (c < b) {
continue
}
if (a * a + b * b == c * c) {
pythaTriples.add(Triple(a, b, c))
}
}
}
val result = pythaTriples.first().reduce(Int::times)
answer(31875000, result)
}
fun <T> Triple<T, T, T>.reduce(f: (T, T) -> T): T {
return f(f(this.first, this.second), this.third)
}
| 0 | Kotlin | 0 | 0 | 1163894f462045060eda763b3040c0bbb1a68e30 | 2,154 | euler-project | MIT License |
Algorithm/coding_interviews/Kotlin/Questions55.kt | ck76 | 314,136,865 | false | {"HTML": 1420929, "Java": 723214, "JavaScript": 534260, "Python": 437495, "CSS": 348978, "C++": 348274, "Swift": 325819, "Go": 310456, "Less": 203040, "Rust": 105712, "Ruby": 96050, "Kotlin": 88868, "PHP": 67753, "Lua": 52032, "C": 30808, "TypeScript": 23395, "C#": 4973, "Elixir": 4945, "Pug": 1853, "PowerShell": 471, "Shell": 163} | package com.qiaoyuang.algorithm
import kotlin.math.abs
import kotlin.math.max
fun main() {
val a = BinaryTreeNode(1)
val b = BinaryTreeNode(2)
val c = BinaryTreeNode(3)
val d = BinaryTreeNode(4)
val e = BinaryTreeNode(5)
val f = BinaryTreeNode(6)
val g = BinaryTreeNode(7)
a.mLeft = b
a.mRight = c
b.mLeft = d
b.mRight = e
c.mRight = f
e.mLeft = g
println("二叉树的高度为:${a.treeDepth()}")
println()
println(a.isBalanced1())
println(a.isBalanced2())
c.mRight = null
println()
println(a.isBalanced1())
println(a.isBalanced2())
}
// 题目一:二叉树的深度
fun <T> BinaryTreeNode<T>.treeDepth(): Int {
var left = 1
left += mLeft?.treeDepth() ?: 0
var right = 1
right += mRight?.treeDepth() ?: 0
return max(right, left)
}
// 题目二:判断一棵二叉树是否是平衡二叉树
fun <T> BinaryTreeNode<T>.isBalanced1(): Boolean {
val left = mLeft?.treeDepth() ?: 0
val right = mRight?.treeDepth() ?: 0
if (abs(left - right) > 1)
return false
return mLeft?.isBalanced1() ?: true && mRight?.isBalanced1() ?: true
}
fun <T> BinaryTreeNode<T>.isBalanced2(): Boolean = this.isBalancedCore(intArrayOf(0))
private fun <T> BinaryTreeNode<T>.isBalancedCore(depth: IntArray): Boolean {
val left = intArrayOf(0)
val right = intArrayOf(0)
if (mLeft?.isBalancedCore(left) != false && mRight?.isBalancedCore(right) != false) {
if (abs(left[0] - right[0]) <= 1) {
depth[0] = 1 + if (left[0] > right[0])
left[0]
else
right[0]
return true
} else
return false
}
return false
} | 0 | HTML | 0 | 2 | 2a989fe85941f27b9dd85b3958514371c8ace13b | 1,544 | awesome-cs | Apache License 2.0 |
src/main/kotlin/g0501_0600/s0542_01_matrix/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g0501_0600.s0542_01_matrix
// #Medium #Array #Dynamic_Programming #Breadth_First_Search #Matrix
// #Algorithm_I_Day_9_Breadth_First_Search_Depth_First_Search
// #Graph_Theory_I_Day_5_Matrix_Related_Problems
// #2023_01_17_Time_441_ms_(94.06%)_Space_54_MB_(78.22%)
class Solution {
fun updateMatrix(mat: Array<IntArray>): Array<IntArray> {
val dist = Array(mat.size) { IntArray(mat[0].size) }
for (i in mat.indices) {
dist[i].fill(Int.MAX_VALUE - 100000)
}
for (i in mat.indices) {
for (j in mat[0].indices) {
if (mat[i][j] == 0) {
dist[i][j] = 0
} else {
if (i > 0) {
dist[i][j] = Math.min(dist[i][j], dist[i - 1][j] + 1)
}
if (j > 0) {
dist[i][j] = Math.min(dist[i][j], dist[i][j - 1] + 1)
}
}
}
}
for (i in mat.indices.reversed()) {
for (j in mat[0].indices.reversed()) {
if (i < mat.size - 1) {
dist[i][j] = Math.min(dist[i][j], dist[i + 1][j] + 1)
}
if (j < mat[0].size - 1) {
dist[i][j] = Math.min(dist[i][j], dist[i][j + 1] + 1)
}
}
}
return dist
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,399 | LeetCode-in-Kotlin | MIT License |
aoc2023/src/main/kotlin/de/havox_design/aoc2023/day11/CosmicExpansion.kt | Gentleman1983 | 737,309,232 | false | {"Kotlin": 746488, "Java": 441473, "Scala": 33415, "Groovy": 5725, "Python": 3319} | package de.havox_design.aoc2023.day11
import de.havox_design.aoc.utils.kotlin.model.positions.Position2d
import kotlin.math.abs
class CosmicExpansion(private var filename: String) {
private val ICON_GALAXY = "#"
fun solvePart1(): Long =
processSumOfAllDistances(getResourceAsText(filename))
fun solvePart2(expansion: Long = 1000000): Long =
processSumOfAllDistances(getResourceAsText(filename), expansion)
private fun processSumOfAllDistances(input: List<String>, expansion: Long = 2): Long {
val galaxies = input
.flatMapIndexed { y, s ->
s.mapIndexed { x, c -> if (c == ICON_GALAXY.first()) Position2d(x.toLong(), y.toLong()) else null }
}
.filterNotNull()
val emptyRows = input
.withIndex()
.filter { !it.value.contains(ICON_GALAXY) }
.map { it.index.toLong() }
val emptyColumns = input
.map { it.toList() }
.transpose()
.withIndex()
.filter {
!it
.value
.joinToString("") { c -> c.toString() }
.contains(ICON_GALAXY)
}
.map { it.index.toLong() }
val expandedGalaxies = calculateUniverseExpansion(galaxies, emptyRows, emptyColumns, expansion)
val galaxyPairs = expandedGalaxies
.flatMapIndexed { index, galaxy ->
expandedGalaxies
.drop(index + 1)
.map { Pair(galaxy, it) }
}
val distances = galaxyPairs
.map { calculateDistance(it.first, it.second) }
return distances.sumOf { it }
}
private fun calculateUniverseExpansion(
galaxies: List<Position2d<Long>>,
emptyRows: List<Long>,
emptyColumns: List<Long>,
expansion: Long = 2
) =
galaxies
.map {
Position2d(it.x + emptyColumns.count { c -> c < it.x } * (expansion - 1),
it.y + emptyRows.count { r -> r < it.y } * (expansion - 1)
)
}
private fun calculateDistance(galaxy1: Position2d<Long>, galaxy2: Position2d<Long>): Long {
return abs(galaxy2.y - galaxy1.y) + abs(galaxy2.x - galaxy1.x)
}
private fun <T> List<List<T>>.transpose(): List<List<T>> {
return when {
this.isEmpty() -> this
else -> (this[0].indices)
.map { i ->
(this.indices)
.map { j -> this[j][i] }
}
}
}
private fun getResourceAsText(path: String): List<String> =
this.javaClass.classLoader.getResourceAsStream(path)!!.bufferedReader().readLines()
} | 4 | Kotlin | 0 | 1 | 35ce3f13415f6bb515bd510a1f540ebd0c3afb04 | 2,774 | advent-of-code | Apache License 2.0 |
Kotlin/src/main/kotlin/org/algorithm/problems/0008_array_nesting.kt | raulhsant | 213,479,201 | true | {"C++": 1035543, "Kotlin": 114509, "Java": 27177, "Python": 16568, "Shell": 999, "Makefile": 187} | // Proble Statement
//
// A zero-indexed array A of length N contains all integers from 0 to N-1.
// Find and return the longest length of set S,
// where S[i] = {A[i], A[A[i]], A[A[A[i]]], ... } subjected to the rule below.
//
// Suppose the first element in S starts with the selection of element A[i]
// of index = i, the next element in S should be A[A[i]], and then A[A[A[i]]]…
// By that analogy, we stop adding right before a duplicate element occurs in S.
//
// Example:
// Input: A = [5,4,0,3,1,6,2]
// Output: 4
// Explanation:
// A[0] = 5, A[1] = 4, A[2] = 0, A[3] = 3, A[4] = 1, A[5] = 6, A[6] = 2.
//
// One of the longest S[K]:
// S[0] = {A[0], A[5], A[6], A[2]} = {5, 6, 2, 0}
package org.algorithm.problems
class `0008_array_nesting` {
fun arrayNesting(nums: IntArray): Int {
val visited: HashSet<Int> = HashSet<Int>();
var result: Int = 0;
for (index in nums.indices) {
if (!visited.contains(index)) {
val dfs: ArrayList<Int> = ArrayList<Int>();
var actual_counter: Int = 0;
dfs.add(index);
while (!dfs.isEmpty()) {
val last: Int = dfs.last();
dfs.removeAt(dfs.size - 1);
if (!visited.contains(last)) {
visited.add(last);
dfs.add(nums[last]);
actual_counter++;
}
}
result = maxOf(result, actual_counter);
}
}
return result;
}
} | 0 | C++ | 0 | 0 | 1578a0dc0a34d63c74c28dd87b0873e0b725a0bd | 1,572 | algorithms | MIT License |
src/main/kotlin/kr/co/programmers/P154540.kt | antop-dev | 229,558,170 | false | {"Kotlin": 695315, "Java": 213000} | package kr.co.programmers
// https://github.com/antop-dev/algorithm/issues/465
class P154540 {
fun solution(maps: Array<String>): IntArray {
val box = maps.map { StringBuilder(it) }
val answer = mutableListOf<Int>()
// DFS
for (y in box.indices) {
for (x in box[y].indices) {
if (box[y][x] in '1'..'9') {
answer += dfs(box, y, x)
}
}
}
if (answer.isEmpty()) answer += -1
return answer.sorted().toIntArray()
}
private fun dfs(box: List<StringBuilder>, y: Int, x: Int): Int {
// 좌표가 넘처기나 'X' 지역이면 0 리턴
if (y !in 0..box.lastIndex
|| x !in 0..box[y].lastIndex
|| box[y][x] == 'X'
) return 0
val v = box[y][x] - '0' // '1' → 1
box[y][x] = 'X'
return v +
dfs(box, y - 1, x) +
dfs(box, y, x + 1) +
dfs(box, y + 1, x) +
dfs(box, y, x - 1)
}
}
| 1 | Kotlin | 0 | 0 | 9a3e762af93b078a2abd0d97543123a06e327164 | 1,050 | algorithm | MIT License |
src/Day02.kt | raneric | 573,109,642 | false | {"Kotlin": 13043} | const val WIN_SCORE = 6
const val DRAW_SCORE = 3
const val ROCK_SCORE = 1
const val PAPER_SCORE = 2
const val SCISSOR_SCORE = 3
fun main() {
fun part1(input: List<String>): Int {
return input.sumOf { it.checkScore() }
}
fun part2(input: List<String>): Int {
return input.sumOf { it.simulateGameWin() }
}
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
fun String.checkScore(): Int {
return this[2].checkIfWin(this[0])
}
fun Char.checkIfWin(you: Char): Int {
var result = 0
when (this) {
'X' -> {
result = ROCK_SCORE
if (you == 'C') {
result += WIN_SCORE
} else if (you == 'A') {
result += DRAW_SCORE
}
}
'Y' -> {
result = PAPER_SCORE
if (you == 'A') {
result += WIN_SCORE
} else if (you == 'B') {
result += DRAW_SCORE
}
}
'Z' -> {
result = SCISSOR_SCORE
if (you == 'B') {
result += WIN_SCORE
} else if (you == 'C') {
result += DRAW_SCORE
}
}
}
return result
}
fun String.simulateGameWin(): Int {
return this[0].choose(this[2])
}
fun Char.choose(end: Char): Int {
return when (end) {
'X' -> this.loose()
'Y' -> this.draw()
'Z' -> this.win()
else -> 0
}
}
fun Char.loose(): Int {
return when (this) {
'A' -> SCISSOR_SCORE
'B' -> ROCK_SCORE
'C' -> PAPER_SCORE
else -> 0
}
}
fun Char.draw(): Int {
return DRAW_SCORE + when (this) {
'A' -> ROCK_SCORE
'B' -> PAPER_SCORE
'C' -> SCISSOR_SCORE
else -> 0
}
}
fun Char.win(): Int {
return WIN_SCORE + when (this) {
'A' -> PAPER_SCORE
'B' -> SCISSOR_SCORE
'C' -> ROCK_SCORE
else -> 0
}
} | 0 | Kotlin | 0 | 0 | 9558d561b67b5df77c725bba7e0b33652c802d41 | 1,983 | aoc-kotlin-challenge | Apache License 2.0 |
src/main/kotlin/days/aoc2020/Day1.kt | bjdupuis | 435,570,912 | false | {"Kotlin": 537037} | package days.aoc2020
import days.Day
class Day1 : Day(2020, 1) {
override fun partOne(): Any {
return pairs(inputList.map { it.toInt() })
.filter { (one, two) -> one + two == 2020 }
.map { (one, two) -> one * two }
.first()
}
override fun partTwo(): Any {
return triples(inputList.map { it.toInt() })
.filter { (one, two, three) -> one + two + three == 2020 }
.map { (one, two, three) -> one * two * three }
.first()
}
private fun pairs(list: List<Int>): Sequence<Pair<Int,Int>> = sequence {
for (i in list.indices)
for (j in i + 1 until list.size - 1)
yield(Pair(list[i], list[j]))
}
private fun triples(list: List<Int>): Sequence<Triple<Int,Int,Int>> = sequence {
for (i in 0 until list.size - 2)
for (j in i + 1 until list.size - 1)
for (k in j + 1 until list.size)
yield(Triple(list[i], list[j], list[k]))
}
}
| 0 | Kotlin | 0 | 1 | c692fb71811055c79d53f9b510fe58a6153a1397 | 1,056 | Advent-Of-Code | Creative Commons Zero v1.0 Universal |
exercises/practice/minesweeper/src/main/kotlin/Minesweeper.kt | Uberts94 | 470,116,778 | true | {"Kotlin": 440843, "Shell": 13575} | data class MinesweeperBoard(val inputBoard: List<String>) {
fun withNumbers(): List<String> =
inputBoard.mapIndexed { row, str ->
str.mapIndexed { col, cell -> when (cell) {
'.' -> adjacentMines(row, col)
else -> cell
}
}.joinToString("")
}
private fun adjacentMines(row: Int, col: Int): Char {
val count =
(Math.max(0, row - 1)..Math.min(inputBoard.size - 1, row + 1))
.flatMap { i ->
(Math.max(0, col - 1)..Math.min(inputBoard[i].length - 1, col + 1))
.map { j ->
if (inputBoard[i][j] == '*') 1 else 0
}
}
.sum()
return if (count > 0) (count + 48).toChar() else '.'
}
}
fun main(args: Array<String>) {
val a = MinesweeperBoard(
listOf<String>(".", "*", ".", "*", ".", ".", ".", "*", ".", ".",
".", ".", "*", ".", ".", ".", ".", ".", ".", "."))
println("Minesweeper board:")
println(a.withNumbers())
}
| 0 | Kotlin | 0 | 0 | ce5467556e3bb4b0e250011a0a26cbaf63f2bc62 | 1,104 | kotlin | MIT License |
src/main/kotlin/com/colinodell/advent2016/Day07.kt | colinodell | 495,627,767 | false | {"Kotlin": 80872} | package com.colinodell.advent2016
class Day07(private val input: List<String>) {
fun solvePart1() = input.map(::IPv7).count { it.supportsTLS() }
fun solvePart2() = input.map(::IPv7).count { it.supportsSSL() }
private class IPv7(ip: String) {
private val supernets = Regex("(?<!\\[)[a-z]+(?=\\[|$)").findAll(ip).map { it.value }
private val hypernets = Regex("\\[([a-z]+)\\]").findAll(ip).map { it.groups[1]?.value ?: "" }
fun supportsTLS() = supernets.any { hasABBA(it) } && !hypernets.any { hasABBA(it) }
fun supportsSSL() = supernets.flatMap { getABAs(it) }.any { hasBAB(it) }
private fun hasABBA(s: String): Boolean {
return (0 until s.length - 3).any { s[it] == s[it + 3] && s[it + 1] == s[it + 2] && s[it] != s[it + 1] }
}
private fun getABAs(s: String): List<String> {
return (0 until s.length - 2).map { s.substring(it, it + 3) }.filter { it[0] == it[2] && it[0] != it[1] }
}
private fun hasBAB(aba: String) = hypernets.any {
it.contains(
listOf(aba[1], aba[0], aba[1]).joinToString("")
)
}
}
}
| 0 | Kotlin | 0 | 0 | 8a387ddc60025a74ace8d4bc874310f4fbee1b65 | 1,168 | advent-2016 | Apache License 2.0 |
src/Day05.kt | er453r | 572,440,270 | false | {"Kotlin": 69456} | fun main() {
val inputLineRegex = """move (\d+) from (\d+) to (\d+)""".toRegex()
fun partX(input: List<String>, moveLogic: (List<ArrayDeque<Char>>, Int, Int, Int) -> Unit): String {
val stacks = List(9) { ArrayDeque<Char>() }
for (line in input) {
if (line.contains('[')) {
stacks.forEachIndexed { index, chars ->
line.getOrNull(index * 4 + 1)?.takeIf { it.isLetter() }?.let {
chars.addLast(it)
}
}
}
if (line.contains("move")) {
val (count, from, to) = line.destructured(inputLineRegex)
moveLogic(stacks, count.toInt(), from.toInt(), to.toInt())
}
}
return stacks.filter { it.isNotEmpty() }.map { it.first() }.joinToString(separator = "")
}
fun part1(input: List<String>) = partX(input) { stacks, count, from, to ->
for (i in 0 until count)
stacks[to - 1].addFirst(stacks[from - 1].removeFirst())
}
fun part2(input: List<String>) = partX(input) { stacks, count, from, to ->
val queue = ArrayDeque<Char>()
for (i in 0 until count)
queue.add(stacks[from - 1].removeFirst())
while (queue.isNotEmpty())
stacks[to - 1].addFirst(queue.removeLast())
}
test(
day = 5,
testTarget1 = "CMZ",
testTarget2 = "MCD",
part1 = ::part1,
part2 = ::part2,
)
}
| 0 | Kotlin | 0 | 0 | 9f98e24485cd7afda383c273ff2479ec4fa9c6dd | 1,503 | aoc2022 | Apache License 2.0 |
src/Day01.kt | wmichaelshirk | 573,031,182 | false | {"Kotlin": 19037} | fun main() {
fun part1(input: List<String>): Int {
val elfRations = input
.joinToString(",")
.split(",,")
.map {
it.split(',').sumOf { n -> n.toInt() }
}
return elfRations.max()
}
fun part2(input: List<String>): Int {
val elfRations = input
.joinToString(",")
.split(",,")
.map {
it.split(',').sumOf { n -> n.toInt() }
}
return elfRations.sortedDescending().take(3).sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 2 | b748c43e9af05b9afc902d0005d3ba219be7ade2 | 833 | 2022-Advent-of-Code | Apache License 2.0 |
src/main/kotlin/de/dikodam/calendar/Day02.kt | dikodam | 433,719,746 | false | {"Kotlin": 51383} | package de.dikodam.calendar
import de.dikodam.AbstractDay
import de.dikodam.Coordinates2D
import de.dikodam.calendar.CommandType.*
import de.dikodam.executeTasks
import kotlin.time.ExperimentalTime
@ExperimentalTime
fun main() {
Day02().executeTasks()
}
class Day02 : AbstractDay() {
val input = readInputLines()
override fun task1(): String {
return input.map { parseInstructionTask1(it) }
.fold(Coordinates2D(0, 0), Coordinates2D::plus)
.let { (horizontal, depth) -> "${horizontal * depth}" }
}
override fun task2(): String {
return input.map { parseInstructionTask2(it) }
.fold(SubmarineState(0, 0, 0), SubmarineState::process)
.run { "${horizontal * depth}" }
}
private fun parseInstructionTask1(instructionLine: String): Coordinates2D {
val (direction, countString) = instructionLine.split(Regex(" "))
val count = countString.toInt()
return when (direction) {
"forward" -> Coordinates2D(count, 0)
"up" -> Coordinates2D(0, -count)
"down" -> Coordinates2D(0, count)
else -> throw IllegalArgumentException("wtf: $instructionLine")
}
}
private fun parseInstructionTask2(line: String): MoveCommand {
val (direction, countString) = line.split(Regex(" "))
val count = countString.toInt()
return when (direction) {
"forward" -> MoveCommand(FORWARD, count)
"up" -> MoveCommand(UP, count)
"down" -> MoveCommand(DOWN, count)
else -> throw IllegalArgumentException("wtf: $line")
}
}
}
private enum class CommandType {
DOWN, UP, FORWARD
}
private data class MoveCommand(val commandType: CommandType, val amount: Int)
private data class SubmarineState(val horizontal: Int, val depth: Int, val aim: Int) {
fun process(command: MoveCommand): SubmarineState {
val (commandType, amount) = command
return when (commandType) {
DOWN -> this.copy(aim = aim + amount)
UP -> this.copy(aim = aim - amount)
FORWARD -> this.copy(horizontal = horizontal + amount, depth = depth + aim * amount)
}
}
}
| 0 | Kotlin | 0 | 1 | 4934242280cebe5f56ca8d7dcf46a43f5f75a2a2 | 2,223 | aoc-2021 | MIT License |
src/Day09.kt | iownthegame | 573,926,504 | false | {"Kotlin": 68002} | import kotlin.math.abs
import kotlin.math.max
fun main() {
fun moveHeadPos(direction: String, knotPos: Array<Int>): Array<Int> {
// println("move knot ${knotPos.joinToString(", ")} with direction $direction")
when (direction) {
"U" -> knotPos[0] += 1
"D" -> knotPos[0] -= 1
"R" -> knotPos[1] += 1
"L" -> knotPos[1] -= 1
}
return knotPos
}
fun updateNextKnot(headPos: Array<Int>, tailPos: Array<Int>): Array<Int> {
// Don't move if touching
if (headPos[0] == tailPos[0] && headPos[1] == tailPos[1]) {
return tailPos
}
if (headPos[0] == tailPos[0] && abs(headPos[1] - tailPos[1]) == 1) {
return tailPos
}
if (headPos[1] == tailPos[1] && abs(headPos[0] - tailPos[0]) == 1) {
return tailPos
}
if (abs(headPos[0] - tailPos[0]) == 1 && abs(headPos[1] - tailPos[1]) == 1) {
return tailPos
}
// move T close to H
if (headPos[0] == tailPos[0]) {
if (headPos[1] > tailPos[1]) {
tailPos[1] += 1
} else {
tailPos[1] -= 1
}
return tailPos
}
if (headPos[1] == tailPos[1]) {
if (headPos[0] > tailPos[0]) {
tailPos[0] += 1
} else {
tailPos[0] -= 1
}
return tailPos
}
if (headPos[0] > tailPos[0]) {
tailPos[0] += 1
} else {
tailPos[0] -= 1
}
if (headPos[1] > tailPos[1]) {
tailPos[1] += 1
} else {
tailPos[1] -= 1
}
return tailPos
}
fun part1(input: List<String>): Int {
var headPos = Array(2) { 0 }
var tailPos = Array(2) { 0 }
val tailVisitedPoses = mutableSetOf<String>()
tailVisitedPoses.add(tailPos.joinToString(", "))
for (line in input) {
val splits = line.split(" ")
val stepDirection = splits[0]
val steps = splits[1].toInt()
for (i in 1..steps) {
headPos = moveHeadPos(stepDirection, headPos)
// println("head pos updated: ${headPos.joinToString(", ")}")
tailPos = updateNextKnot(headPos, tailPos)
// println("tail pos updated: ${tailPos.joinToString(", ")}")
tailVisitedPoses.add(tailPos.joinToString(", "))
}
}
return tailVisitedPoses.size
}
fun part2(input: List<String>): Int {
// 10 knots, first one is head, last one is tail
val knotPoses = Array(10) { Array(2) { 0 } }
val tailVisitedPoses = mutableSetOf<String>()
var tailPos = knotPoses.last()
tailVisitedPoses.add(tailPos.joinToString(", "))
for (line in input) {
val splits = line.split(" ")
val stepDirection = splits[0]
val steps = splits[1].toInt()
for (i in 1..steps) {
var headPos = knotPoses.first()
headPos = moveHeadPos(stepDirection, headPos)
knotPoses[0] = headPos
for (k in 0..8) {
val currentKnotPos = knotPoses[k]
var currentNextKnotPos = knotPoses[k + 1]
currentNextKnotPos = updateNextKnot(currentKnotPos, currentNextKnotPos)
knotPoses[k + 1] = currentNextKnotPos
// println("next knot pos updated: ${currentNextKnotPos.joinToString(", ")}")
}
tailPos = knotPoses.last()
tailVisitedPoses.add(tailPos.joinToString(", "))
}
}
return tailVisitedPoses.size
}
// test if implementation meets criteria from the description, like:
val testInput = readTestInput("Day09_sample")
check(part1(testInput) == 13)
check(part2(testInput) == 1)
val testInput2 = readTestInput("Day09_sample2")
check(part2(testInput2) == 36)
val input = readTestInput("Day09")
println("part 1 result: ${part1(input)}")
println("part 2 result: ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 4e3d0d698669b598c639ca504d43cf8a62e30b5c | 4,216 | advent-of-code-2022 | Apache License 2.0 |
leetcode/src/daily/mid/Q856.kt | zhangweizhe | 387,808,774 | false | null | package daily.mid
import java.util.*
fun main() {
// 856. 括号的分数
// https://leetcode.cn/problems/score-of-parentheses/
println(scoreOfParentheses("(()(()))"))
}
fun scoreOfParentheses(s: String): Int {
// 影响分数的,只有(),至于一对()能贡献多少分数,要看它位于第几层
// 如 (()) ,()位于第二层,根据题意,可以贡献 1*2 = 2 分
// ((())) ,() 位于第三层,则可以贡献 1*2*2 = 4 分
// 即 () 位于第 n 层,则可以贡献 2^(n-1) 分
// 而没有互相嵌套的 () 之间,则使用加法累计分数,累加到 result 中就可以了
var depth = 0
var result = 0
val one = 1
for (i in s.indices) {
val c = s[i]
if (c == '(') {
depth++
}else {
// c == ')'
depth--
if (s[i-1] == '(') {
// 成对
result += one.shl(depth)
}
}
}
return result
}
fun scoreOfParentheses1(s: String): Int {
var depth = 0
var result = 0
val one = 1
for (i in s.indices) {
if (s[i] == '(') {
depth++
}else if (s[i] == ')') {
depth--
if (i > 0 && s[i-1] == '(') {
result += one.shl(depth)
}
}
}
return result
} | 0 | Kotlin | 0 | 0 | 1d213b6162dd8b065d6ca06ac961c7873c65bcdc | 1,349 | kotlin-study | MIT License |
src/Day05.kt | allwise | 574,465,192 | false | null | import java.io.File
fun main() {
fun part1(input: List<String>): String {
val stacks = Stacking(input)
return stacks.process()
}
fun part2(input: List<String>): String {
val stacks = Stacking(input)
return stacks.process2()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
class Stacking(val input: List<String>) {
// [D]
// [N] [C]
// [Z] [M] [P]
// 1 2 3
//
fun process():String{
val s = input.indexOf("")
println(s)
val rows = ArrayDeque<String>(500)
rows.addAll(input.subList(0,s))
val commands = input.subList(s,input.size)
val stacks =createStacks(rows)
stacks.forEach{println(it)}
commands.forEach { command ->stacks.handleCommand(command)}
stacks.forEach{println(it)}
println("solution 1:" + stacks.getTop())
return stacks.getTop()
}
fun process2():String{
val s = input.indexOf("")
println(s)
val rows = ArrayDeque<String>(500)
rows.addAll(input.subList(0,s))
val commands = input.subList(s,input.size)
val stacks =createStacks(rows)
commands.forEach { command ->stacks.handleCommand2(command);stacks.forEach{println(it)}}
stacks.forEach{println(it)}
println("solution 2:" + stacks.getTop())
return stacks.getTop()
}
fun createStacks(lines:ArrayDeque<String>): List<ArrayDeque<String>> {
val stackline = lines.last().stackline()
val stacks: List<ArrayDeque<String>> = stackline.map { ArrayDeque<String>(50) }
lines.reversed().map { stacks.addList(it.stackline()) }
return stacks
}
fun String.stackline():List<String>{
return this.chunked(4).map { println("chars of ($it)");it[1].toString().trim() }
}
fun List<ArrayDeque<String>>.addList(strings:List<String>){
strings.forEachIndexed{inx, string ->if(string.isNotEmpty())this[inx].addFirst(string)}
}
fun List<ArrayDeque<String>>.handleCommand(command:String){
if(command.isEmpty()){
return
}
val (count,from,to) = ("(\\d+)".toRegex()).findAll(command).map{ it.value.toInt()}.toList()
println(command)
println("""moving $count from $from to $to """)
repeat(count){move(this[from-1],this[to-1])}
}
fun List<ArrayDeque<String>>.handleCommand2(command:String){
if(command.isEmpty()){
return
}
val (count,from,to) = ("(\\d+)".toRegex()).findAll(command).map{ it.value.toInt()}.toList()
println(command)
println("""moving $count from $from to $to """)
val temp = ArrayDeque<String>(20)
repeat(count){move(this[from-1],temp)}
repeat(count){move(temp,this[to-1])}
}
fun move(from:ArrayDeque<String>,to:ArrayDeque<String>){
to.addFirst(from.removeFirst())
}
fun List<ArrayDeque<String>>.getTop():String{
return this.map{it.first()}.joinToString("" )
}
}
| 0 | Kotlin | 0 | 0 | 400fe1b693bc186d6f510236f121167f7cc1ab76 | 3,287 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/SequentialDigits.kt | Codextor | 453,514,033 | false | {"Kotlin": 26975} | /**
* An integer has sequential digits if and only if each digit in the number is one more than the previous digit.
*
* Return a sorted list of all the integers in the range [low, high] inclusive that have sequential digits.
*
*
*
* Example 1:
*
* Input: low = 100, high = 300
* Output: [123,234]
* Example 2:
*
* Input: low = 1000, high = 13000
* Output: [1234,2345,3456,4567,5678,6789,12345]
*
*
* Constraints:
*
* 10 <= low <= high <= 10^9
* @see <a href="https://leetcode.com/problems/sequential-digits/">LeetCode</a>
*/
fun sequentialDigits(low: Int, high: Int): List<Int> {
val result = mutableListOf<Int>()
val lengthOfLow = low.toString().length
val maxStartDigit = 10 - lengthOfLow
val numbersQueue = ArrayDeque<Int>()
for (startDigit in 1..maxStartDigit) {
var number = startDigit
for (index in 1 until lengthOfLow) {
number = number * 10 + startDigit + index
}
numbersQueue.add(number)
}
while (numbersQueue.isNotEmpty()) {
val currentNumber = numbersQueue.removeFirst()
if (currentNumber > high) {
return result
}
if (currentNumber >= low) {
result.add(currentNumber)
}
currentNumber.rem(10).let { lastDigit ->
if (lastDigit != 9) {
numbersQueue.add(currentNumber * 10 + lastDigit + 1)
}
}
}
return result
}
| 0 | Kotlin | 1 | 0 | 68b75a7ef8338c805824dfc24d666ac204c5931f | 1,443 | kotlin-codes | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/sorts/HeapSort.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
/**
* Heap sort is a comparison based sorting technique based on Binary Heap data structure. It is similar to selection
* sort where we first find the maximum element and place the maximum element at the end. We repeat the same process
* for remaining element.
*
* Worst-case performance O(n*log(n))
* Best-case performance O(n*log(n))
* Average-case performance O(n*log(n))
* Worst-case space complexity O(1) (auxiliary)
*/
class HeapSort : AbstractSortStrategy {
override fun <T : Comparable<T>> perform(arr: Array<T>) {
val n = arr.size
for (i in n / 2 - 1 downTo 0) {
heapify(arr, n, i)
}
for (i in n - 1 downTo 0) {
arr.swap(0, i)
heapify(arr, i, 0)
}
}
private fun <T : Comparable<T>> heapify(arr: Array<T>, n: Int, i: Int) {
var largest = i
val l = 2 * i + 1
val r = 2 * i + 2
if (l < n && arr[l] > arr[largest]) {
largest = l
}
if (r < n && arr[r] > arr[largest]) {
largest = r
}
if (largest != i) {
arr.swap(i, largest)
heapify(arr, n, largest)
}
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,891 | kotlab | Apache License 2.0 |
src/problemOfTheDay/problem169_MergeSort/problem196_MergeSort.kt | cunrein | 159,861,371 | false | null | package problemOfTheDay.problem169_MergeSort
data class Node<T : Comparable<T>>(val value: T, var next: Node<T>? = null)
class LinkedList<T : Comparable<T>>(var head: Node<T>?) {
fun push(new_data: T) {
/* allocate node */
val newNode = Node<T>(new_data)
/* link the old list off the new node */
newNode.next = head
/* move the head to point to the new node */
head = newNode
}
// Utility function to print the linked list
fun print() {
println(toString())
}
override fun toString(): String {
var headref = head
var out = ""
while (headref != null) {
out += headref.value.toString() + " "
headref = headref.next
}
return out
}
}
private fun <T : Comparable<T>> sortedMerge(a: Node<T>?, b: Node<T>?): Node<T>? {
val result: Node<T>?
/* Base cases */
if (a == null)
return b
if (b == null)
return a
/* Pick either a or b, and recur */
if (a.value <= b.value) {
result = a
result.next = sortedMerge(a.next, b)
} else {
result = b
result.next = sortedMerge(a, b.next)
}
return result
}
fun <T : Comparable<T>> mergeSort(h: Node<T>?): Node<T>? {
if (h == null || h.next == null)
return h
// get the middle of the list
val middle = getMiddle(h)
val nextOfMiddle = middle?.next
// set the next of middle node to null
middle?.next = null
// Apply mergeSort on left list
val left = mergeSort(h)
// Apply mergeSort on right list
val right = mergeSort(nextOfMiddle)
// Merge the left and right lists
return sortedMerge(left, right)
}
fun <T : Comparable<T>> getMiddle(h: Node<T>?): Node<T>? {
// Base case
if (h == null)
return h
var fastptr = h.next
var slowptr = h
// Move fastptr by two and slow ptr by one
// Finally slowptr will point to middle node
while (fastptr != null) {
fastptr = fastptr.next
if (fastptr != null) {
slowptr = slowptr?.next
fastptr = fastptr.next
}
}
return slowptr
}
fun main() {
val node = Node(-2)
val linkedList = LinkedList(node)
linkedList.push(4)
linkedList.push(0)
linkedList.push(-1)
linkedList.push(10)
linkedList.push(12)
linkedList.push(5)
linkedList.print()
val sorted = LinkedList(mergeSort(linkedList.head))
sorted.print()
} | 0 | Kotlin | 0 | 0 | 3488ccb200f993a84f1e9302eca3fe3977dbfcd9 | 2,501 | ProblemOfTheDay | Apache License 2.0 |
src/days/Day07.kt | EnergyFusion | 572,490,067 | false | {"Kotlin": 48323} | import java.io.BufferedReader
fun main() {
val day = 7
fun getDirMap(inputReader: BufferedReader): Map<String, Int> {
val dirMap = mutableMapOf("/" to 0)
val directoryStack = ArrayDeque<String>()
var currentDir = "/"
var lineNum = 0
inputReader.forEachLine { line ->
if (line.startsWith("$ cd")) {
val split = line.split(" ")
var newDir = split.last()
if (lineNum != 0 && !newDir.equals("..")) {
directoryStack.addLast(currentDir)
}
if (newDir.equals("..")) {
newDir = directoryStack.removeLast()
} else {
newDir = dirMap.keys.findLast { name -> name.startsWith(newDir) }!!
}
currentDir = newDir
} else if (line.equals("$ ls")) {
//Do nothing
} else if (line.startsWith("dir")) {
val split = line.split(" ")
var newDir = split.last()
while (dirMap.containsKey(newDir)) {
newDir += "_"
}
dirMap[newDir] = 0
} else {
// This should be a file now
val split = line.split(" ")
val size = split[0].toInt()
var curSize = dirMap[currentDir] ?: 0
dirMap[currentDir] = curSize + size
directoryStack.forEach { dir ->
curSize = dirMap[dir] ?: 0
dirMap[dir] = curSize + size
}
}
// println(dirMap)
lineNum++
}
return dirMap
}
fun part1(inputReader: BufferedReader): Int {
val dirMap = getDirMap(inputReader)
val sizes = dirMap.values.filter { value -> value <= 100000 }
return sizes.sum()
}
fun part2(inputReader: BufferedReader): Int {
val dirMap = getDirMap(inputReader)
val totalSpace = 70000000
val homeFilled = dirMap["/"]!!
val freeSpace = totalSpace - homeFilled
val spaceNeeded = 30000000 - freeSpace
val directorySizesBigEnough = dirMap.values.filter { value -> value >= spaceNeeded }
return directorySizesBigEnough.sorted().first()
}
val testInputReader = readBufferedInput("tests/Day%02d".format(day))
// check(part1(testInputReader) == 95437)
check(part2(testInputReader) == 24933642)
val input = readBufferedInput("input/Day%02d".format(day))
// println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 06fb8085a8b1838289a4e1599e2135cb5e28c1bf | 2,634 | advent-of-code-kotlin | Apache License 2.0 |
year2020/day07/part2/src/main/kotlin/com/curtislb/adventofcode/year2020/day07/part2/Year2020Day07Part2.kt | curtislb | 226,797,689 | false | {"Kotlin": 2146738} | /*
--- Part Two ---
It's getting pretty expensive to fly these days - not because of ticket prices, but because of the
ridiculous number of bags you need to buy!
Consider again your shiny gold bag and the rules from the above example:
- faded blue bags contain 0 other bags.
- dotted black bags contain 0 other bags.
- vibrant plum bags contain 11 other bags: 5 faded blue bags and 6 dotted black bags.
- dark olive bags contain 7 other bags: 3 faded blue bags and 4 dotted black bags.
So, a single shiny gold bag must contain 1 dark olive bag (and the 7 bags within it) plus 2 vibrant
plum bags (and the 11 bags within each of those): 1 + 1*7 + 2 + 2*11 = 32 bags!
Of course, the actual rules have a small chance of going several levels deeper than this example; be
sure to count all of the bags, even if the nesting becomes topologically impractical!
Here's another example:
shiny gold bags contain 2 dark red bags.
dark red bags contain 2 dark orange bags.
dark orange bags contain 2 dark yellow bags.
dark yellow bags contain 2 dark green bags.
dark green bags contain 2 dark blue bags.
dark blue bags contain 2 dark violet bags.
dark violet bags contain no other bags.
In this example, a single shiny gold bag must contain 126 other bags.
How many individual bags are required inside your single shiny gold bag?
*/
package com.curtislb.adventofcode.year2020.day07.part2
import com.curtislb.adventofcode.year2020.day07.baggage.BagCount
import com.curtislb.adventofcode.year2020.day07.baggage.BagRules
import java.nio.file.Path
import java.nio.file.Paths
/**
* Returns the solution to the puzzle for 2020, day 7, part 2.
*
* @param inputPath The path to the input file for this puzzle.
*/
fun solve(inputPath: Path = Paths.get("..", "input", "input.txt")): Int {
val file = inputPath.toFile()
val rules = BagRules(file.readText())
return rules.countTotalBags(BagCount("shiny gold", 1)) - 1
}
fun main() {
println(solve())
}
| 0 | Kotlin | 1 | 1 | 6b64c9eb181fab97bc518ac78e14cd586d64499e | 1,960 | AdventOfCode | MIT License |
tool/shard/calculate/src/main/kotlin/flank/shard/Internal.kt | Flank | 84,221,974 | false | {"Kotlin": 1748173, "Java": 101254, "Swift": 41229, "Shell": 10674, "Objective-C": 10006, "Dart": 9705, "HTML": 7235, "Gherkin": 4210, "TypeScript": 2717, "Ruby": 2272, "JavaScript": 1764, "SCSS": 1365, "Batchfile": 1183, "EJS": 1061, "Go": 159} | package flank.shard
import kotlin.math.min
// Stage 1
/**
* Create flat and easy to iterate list of [Chunk] without losing info about app and test related to test case.
* @receiver The [List] of [Shard.App].
* @return The [List] of [Chunk] which is just different representation of input data.
*/
internal fun List<Shard.App>.mapToInternalChunks(): List<Chunk> =
mutableListOf<Chunk>().also { result ->
forEach { app ->
app.tests.forEach { test ->
test.cases.forEach { case ->
result.add(
Chunk(
app = app.name,
test = test.name,
case = case.name,
duration = case.duration
)
)
}
}
}
}
/**
* Internal intermediate structure which is representing test case with associated app and test module.
*/
internal class Chunk(
val app: String,
val test: String,
val case: String,
val duration: Long,
)
// Stage 2
/**
* Group the chunks into sub-lists where the standard deviation of group duration should by possibly small.
* @receiver The flat [List] of [Chunk].
* @return The [List] of [Chunk] groups balanced by the summary duration of each.
*/
internal fun List<Chunk>.groupByDuration(maxCount: Int): List<List<Chunk>> {
class Chunks(
var duration: Long = 0,
val list: MutableList<Chunk> = mutableListOf()
)
// The real part of sharding calculations,
// everything else is just a mapping between structures.
// ===================================================
return sortedByDescending(Chunk::duration).fold(
initial = List(min(size, maxCount)) { Chunks() }
) { acc, chunk ->
acc.first().apply {
duration += chunk.duration
list += chunk
}
acc.sortedBy(Chunks::duration)
}.map(Chunks::list)
// ===================================================
}
// Stage 3
/**
* Build the final structure of shards.
*/
internal fun List<List<Chunk>>.mapToShards(): List<List<Shard.App>> {
// Structure the group of chunks mapping them by app and test.
val list: List<Map<String, Map<String, List<Chunk>>>> = map { group ->
group.groupBy { chunk ->
chunk.app
}.mapValues { (_, chunks) ->
chunks.groupBy { chunk ->
chunk.test
}
}
}
// Convert grouped chunks into the output structures.
return list.map { map ->
map.map { (app, tests) ->
Shard.App(
name = app,
tests = tests.map { (test, chunks) ->
Shard.Test(
name = test,
cases = chunks.map { chunk ->
Shard.Test.Case(
name = chunk.case,
duration = chunk.duration
)
}
)
}
)
}
}
}
| 50 | Kotlin | 121 | 658 | e63c612af38a71fbe563a3f6c12192cc91cb3b9a | 3,158 | flank | Apache License 2.0 |
kotlin/src/com/s13g/aoc/aoc2021/Day19.kt | shaeberling | 50,704,971 | false | {"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245} | package com.s13g.aoc.aoc2021
import com.s13g.aoc.Result
import com.s13g.aoc.Solver
import kotlin.math.abs
import kotlin.math.max
/**
* --- Day 19: Beacon Scanner ---
* https://adventofcode.com/2021/day/19
*/
class Day19 : Solver {
override fun solve(lines: List<String>): Result {
val scanners = parseInput(lines)
// Will contain all of the aligned points, relative to scanner 0.
// Start with all of scanner 0's beacons in default orientation
val alignedComposite = mutableSetOf<XYZ>()
alignedComposite.addAll(scanners[0])
// List of scanner indices that have already been aligned.
// Start with scanner as it is our reference.
val aligned = mutableSetOf<Int>()
aligned.add(0)
// Contains the position for every aligned scanner (not idx-matched!).
val scannerPositions = mutableListOf<XYZ>()
scannerPositions.add(XYZ(0, 0, 0))
// Loop until all scanners are aligned.
while (aligned.size != scanners.size) {
// Go through all already aligned points.
for (alignedPoint in alignedComposite.toList()) {
// Go through all unaligned scanners.
for (b in scanners.indices) {
if (aligned.contains(b)) continue
// Compare all permutations from unaligned scanner (b) to the given rotation of the first.
// We don't have to rotate the already aligned points.
for (permB in permutateScanner(scanners[b])) {
// Go through every point of b and see how all other points would be positioned if it
// was the same as the alignedPoint.
for (initialPointB in permB) {
val delta = alignedPoint minus initialPointB
var countMatches = 0
val newPoints = mutableSetOf<XYZ>()
for (pointB in permB) {
val testPoint = pointB plus delta
newPoints.add(testPoint)
if (alignedComposite.contains(testPoint)) countMatches++
}
// If we matched at least 12, the scanner is now aligned.
if (countMatches >= 12) {
alignedComposite.addAll(newPoints)
aligned.add(b)
scannerPositions.add(delta)
}
}
}
}
}
}
// Calculate largest Manhattan distance for partB between all scanners.
var largestDistance = Long.MIN_VALUE
for (a in scannerPositions.indices) {
for (b in a until scannerPositions.size) {
largestDistance = max(largestDistance, scannerPositions[a] distance scannerPositions[b])
}
}
val partA = alignedComposite.size
val partB = largestDistance
return Result("$partA", "$partB")
}
/** Generate all 24 permutations given the list of initial beacons. */
private fun permutateScanner(beacons: Set<XYZ>): List<Set<XYZ>> {
val result = List(24) { mutableSetOf<XYZ>() }
for (b in beacons) {
result[0].add(XYZ(b.x, b.y, b.z))
result[1].add(XYZ(b.x, -b.z, b.y))
result[2].add(XYZ(b.x, -b.y, -b.z))
result[3].add(XYZ(b.x, b.z, -b.y))
result[4].add(XYZ(b.y, -b.x, b.z))
result[5].add(XYZ(b.y, -b.z, -b.x))
result[6].add(XYZ(b.y, b.x, -b.z))
result[7].add(XYZ(b.y, b.z, b.x))
result[8].add(XYZ(-b.x, -b.y, b.z))
result[9].add(XYZ(-b.x, -b.z, -b.y))
result[10].add(XYZ(-b.x, b.y, -b.z))
result[11].add(XYZ(-b.x, b.z, b.y))
result[12].add(XYZ(-b.y, b.x, b.z))
result[13].add(XYZ(-b.y, -b.z, b.x))
result[14].add(XYZ(-b.y, -b.x, -b.z))
result[15].add(XYZ(-b.y, b.z, -b.x))
result[16].add(XYZ(b.z, b.x, b.y))
result[17].add(XYZ(b.z, b.y, -b.x))
result[18].add(XYZ(b.z, -b.x, -b.y))
result[19].add(XYZ(b.z, -b.y, b.x))
result[20].add(XYZ(-b.z, -b.y, -b.x))
result[21].add(XYZ(-b.z, b.x, -b.y))
result[22].add(XYZ(-b.z, b.y, b.x))
result[23].add(XYZ(-b.z, -b.x, b.y))
}
return result
}
private fun parseInput(lines: List<String>): List<Set<XYZ>> {
val result = mutableListOf<MutableSet<XYZ>>()
for (line in lines) {
if (line.contains("---")) {
result.add(mutableSetOf())
continue
}
if (line.isBlank()) continue
result.last().add(parseXYZ(line))
}
return result
}
private fun parseXYZ(str: String): XYZ {
val values = str.split(',').map { it.toLong() }
assert(values.size == 3)
return XYZ(values[0], values[1], values[2])
}
private data class XYZ(val x: Long, val y: Long, val z: Long)
private infix fun XYZ.plus(other: XYZ) = XYZ(x + other.x, y + other.y, z + other.z)
private infix fun XYZ.minus(other: XYZ) = XYZ(x - other.x, y - other.y, z - other.z)
private infix fun XYZ.distance(other: XYZ) = abs(x - other.x) + abs(y - other.y) + abs(z - other.z)
} | 0 | Kotlin | 1 | 2 | 7e5806f288e87d26cd22eca44e5c695faf62a0d7 | 4,834 | euler | Apache License 2.0 |
src/Day04.kt | ked4ma | 573,017,240 | false | {"Kotlin": 51348} | import kotlin.math.max
/**
* [Day04](https://adventofcode.com/2022/day/4)
*/
fun main() {
fun rangeToSet(rangeStr: String): Set<Int> = rangeStr.split("-").let { (s, e) ->
IntRange(s.toInt(), e.toInt())
}.toSet()
fun part1(input: List<String>): Int {
return input.filter {
it.split(",").let { (first, second) ->
val fSet = rangeToSet(first)
val sSet = rangeToSet(second)
max(fSet.size, sSet.size) == (fSet + sSet).size
}
}.size
}
fun part2(input: List<String>): Int {
return input.filter {
it.split(",").let { (first, second) ->
val fSet = rangeToSet(first)
val sSet = rangeToSet(second)
fSet.size + sSet.size != (fSet + sSet).size
}
}.size
}
// 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))
} | 1 | Kotlin | 0 | 0 | 6d4794d75b33c4ca7e83e45a85823e828c833c62 | 1,128 | aoc-in-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/DistanceKTree.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import java.util.LinkedList
import java.util.Queue
/**
* 863. All Nodes Distance K in Binary Tree
* @see <a href="https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/">Source</a>
*/
fun interface DistanceKTree {
fun distanceK(root: TreeNode, target: TreeNode, k: Int): List<Int>
}
/**
* Approach 1: Implementing Parent Pointers
*/
class DistanceKTreeParentPointers : DistanceKTree {
override fun distanceK(root: TreeNode, target: TreeNode, k: Int): List<Int> {
val res: MutableList<Int> = LinkedList()
if (k == 0) {
res.add(target.value)
} else {
dfs(res, root, target.value, k, 0)
}
return res
}
private fun dfs(res: MutableList<Int>, node: TreeNode?, target: Int, k: Int, depth: Int): Int {
if (node == null) return 0
if (depth == k) {
res.add(node.value)
return 0
}
val left: Int
val right: Int
if (node.value == target || depth > 0) {
left = dfs(res, node.left, target, k, depth + 1)
right = dfs(res, node.right, target, k, depth + 1)
} else {
left = dfs(res, node.left, target, k, depth)
right = dfs(res, node.right, target, k, depth)
}
if (node.value == target) return 1
if (left == k || right == k) {
res.add(node.value)
return 0
}
if (left > 0) {
dfs(res, node.right, target, k, left + 1)
return left + 1
}
if (right > 0) {
dfs(res, node.left, target, k, right + 1)
return right + 1
}
return 0
}
}
/**
* Approach 2: Depth-First Search on Equivalent Graph
*/
class DistanceKTreeDFS : DistanceKTree {
private val graph: MutableMap<Int, MutableList<Int>> = HashMap()
private val answer: MutableList<Int> = mutableListOf()
private val visited: MutableSet<Int> = HashSet()
override fun distanceK(root: TreeNode, target: TreeNode, k: Int): List<Int> {
buildGraph(root, null)
visited.add(target.value)
dfs(target.value, 0, k)
return answer
}
// Recursively build the undirected graph from the given binary tree.
private fun buildGraph(cur: TreeNode?, parent: TreeNode?) {
if (cur != null && parent != null) {
graph.computeIfAbsent(cur.value) { ArrayList() }.add(parent.value)
graph.computeIfAbsent(parent.value) { ArrayList() }.add(cur.value)
}
if (cur?.left != null) {
buildGraph(cur.left, cur)
}
if (cur?.right != null) {
buildGraph(cur.right, cur)
}
}
private fun dfs(cur: Int, distance: Int, k: Int) {
if (distance == k) {
answer.add(cur)
return
}
for (neighbor in graph.getOrDefault(cur, ArrayList())) {
if (!visited.contains(neighbor)) {
visited.add(neighbor)
dfs(neighbor, distance + 1, k)
}
}
}
}
/**
* Approach 3: Breadth-First Search on Equivalent Graph
*/
class DistanceKTreeBFS : DistanceKTree {
override fun distanceK(root: TreeNode, target: TreeNode, k: Int): List<Int> {
val graph: MutableMap<Int, MutableList<Int>> = HashMap()
dfsBuild(root, null, graph)
val answer: MutableList<Int> = ArrayList()
val visited: MutableSet<Int> = HashSet()
val queue: Queue<IntArray> = LinkedList()
// Add the target node to the queue with a distance of 0
queue.add(intArrayOf(target.value, 0))
visited.add(target.value)
while (queue.isNotEmpty()) {
val cur: IntArray = queue.poll()
val node = cur[0]
val distance = cur[1]
// If the current node is at distance k from target,
// add it to the answer list and continue to the next node.
if (distance == k) {
answer.add(node)
continue
}
// Add all unvisited neighbors of the current node to the queue.
for (neighbor in graph.getOrDefault(node, ArrayList())) {
if (!visited.contains(neighbor)) {
visited.add(neighbor)
queue.add(intArrayOf(neighbor, distance + 1))
}
}
}
return answer
}
// Recursively build the undirected graph from the given binary tree.
private fun dfsBuild(cur: TreeNode?, parent: TreeNode?, graph: MutableMap<Int, MutableList<Int>>) {
if (cur != null && parent != null) {
val curVal: Int = cur.value
val parentVal: Int = parent.value
graph.putIfAbsent(curVal, ArrayList())
graph.putIfAbsent(parentVal, ArrayList())
graph[curVal]?.add(parentVal)
graph[parentVal]?.add(curVal)
}
if (cur?.left != null) {
dfsBuild(cur.left, cur, graph)
}
if (cur?.right != null) {
dfsBuild(cur.right, cur, graph)
}
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 5,757 | kotlab | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.