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/Day08.kt | tsschmidt | 572,649,729 | false | {"Kotlin": 24089} | fun main() {
fun parseMap(input: List<String>): List<List<Int>> {
val map = mutableListOf<List<Int>>()
input.forEach {row ->
map.add(row.map { it.toString().toInt() })
}
return map
}
fun checkRight(r: Int, c: Int, cur: Int, map: List<List<Int>>): Boolean {
if (c == map[0].size) {
return true
}
if (map[r][c] < cur) {
return checkRight(r, c+1, cur, map)
}
return false
}
fun checkLeft(r: Int, c: Int, cur: Int, map: List<List<Int>>): Boolean {
if (c == -1) {
return true
}
if (map[r][c] < cur) {
return checkLeft(r, c-1, cur, map)
}
return false
}
fun checkDown(r: Int, c: Int, cur: Int, map: List<List<Int>>): Boolean {
if (r == map.size) {
return true
}
if (map[r][c] < cur) {
return checkDown(r+1, c, cur, map)
}
return false
}
fun checkUp(r: Int, c: Int, cur: Int, map: List<List<Int>>): Boolean {
if (r == -1) {
return true
}
if (map[r][c] < cur) {
return checkUp(r-1, c, cur, map)
}
return false
}
fun viewRight(r: Int, c: Int, cur: Int, map: List<List<Int>>, score: Int): Int {
if (c < map[0].size - 1 && map[r][c] < cur) {
return viewRight(r, c+1, cur, map, score + 1)
}
return score
}
fun viewLeft(r: Int, c: Int, cur: Int, map: List<List<Int>>, score: Int): Int {
if (c > 0 && map[r][c] < cur) {
return viewLeft(r, c-1, cur, map, score + 1)
}
return score
}
fun viewDown(r: Int, c: Int, cur: Int, map: List<List<Int>>, score: Int): Int {
if (r < map.size - 1 && map[r][c] < cur) {
return viewDown(r+1, c, cur, map, score + 1)
}
return score
}
fun viewUp(r: Int, c: Int, cur: Int, map: List<List<Int>>, score: Int): Int {
if (r > 0 && map[r][c] < cur) {
return viewUp(r-1, c, cur, map, score + 1)
}
return score
}
fun part1(input: List<String>): Int {
val map = parseMap(input)
val width = map[0].size
val height = map.size
var count = 0
for (r in 1..width - 2) {
for (c in 1..height -2) {
if (checkRight(r, c+1, map[r][c], map) ||
checkLeft(r, c-1, map[r][c], map) ||
checkDown(r+1, c, map[r][c], map) ||
checkUp(r-1, c, map[r][c], map)) {
count++
}
}
}
count += (2 * map.size) + (2 * (map[0].size - 2))
return count
}
fun part2(input: List<String>): Int {
val map = parseMap(input)
val width = map[0].size
val height = map.size
var max = 0
for (r in 1..height - 2) {
for (c in 1..width - 2) {
val cur = viewDown(r + 1, c, map[r][c], map, 1) *
viewUp(r - 1, c, map[r][c], map, 1) *
viewRight(r, c + 1, map[r][c], map, 1) *
viewLeft(r, c - 1, map[r][c], map, 1)
if (cur > max) {
max = cur
}
}
}
return max
}
//val input = readInput("Day08_test")
//check(part2(input) == 8)
val input = readInput("Day08")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 7bb637364667d075509c1759858a4611c6fbb0c2 | 3,554 | aoc-2022 | Apache License 2.0 |
src/Day02/Day02.kt | emillourens | 572,599,575 | false | {"Kotlin": 32933} | fun main() {
fun part1(input: List<String>): Int {
var score = 0
// A - Rock, B - Paper, C - Scissors
// X - Rock, Y - Paper, Z - Scissors
for (item in input) {
val opponent = item[0].toString()
val you = item[2].toString()
when (opponent) {
"A" -> {
when (you) {
"Y" -> score += (6 + 2)
"Z" -> score += (0 + 3)
"X" -> score += (3 + 1)
}
}
"B" -> {
when (you) {
"Y" -> score += (3 + 2)
"Z" -> score += (6 + 3)
"X" -> score += (0 + 1)
}
}
"C" -> {
when (you) {
"Y" -> score += (0 + 2)
"Z" -> score += (3 + 3)
"X" -> score += (6 + 1)
}
}
}
}
return score
}
fun part2(input: List<String>): Int {
var score = 0
// A - Rock, B - Paper, C - Scissors
// X - Lose, Y - Draw, Z - Win
// 1 - Rock, 2 - Paper, 3 - Scissors
for (item in input) {
val opponent = item[0].toString()
val result = item[2].toString()
when (opponent) {
"A" -> {
when (result) {
"Y" -> score += (3 + 1)
"Z" -> score += (6 + 2)
"X" -> score += (0 + 3)
}
}
"B" -> {
when (result) {
"Y" -> score += (3 + 2)
"Z" -> score += (6 + 3)
"X" -> score += (0 + 1)
}
}
"C" -> {
when (result) {
"Y" -> score += (3 + 3)
"Z" -> score += (6 + 1)
"X" -> score += (0 + 2)
}
}
}
}
return score
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 1f9739b73ef080b012e505e0a4dfe88f928e893d | 2,509 | AoC2022 | Apache License 2.0 |
src/com/kingsleyadio/adventofcode/y2022/day05/Solution.kt | kingsleyadio | 435,430,807 | false | {"Kotlin": 134666, "JavaScript": 5423} | package com.kingsleyadio.adventofcode.y2022.day05
import com.kingsleyadio.adventofcode.util.readInput
fun main() {
solution(false)
solution(true)
}
fun solution(retainOrder: Boolean) {
readInput(2022, 5).useLines { lineSequence ->
val lines = lineSequence.iterator()
val entries = mutableListOf<ArrayDeque<Char>>()
for (line in lines) {
if (line.isEmpty()) break
for ((index, j) in (1 until line.length step 4).withIndex()) {
val entry = line[j]
if (entry != ' ') {
while (index > entries.lastIndex) entries.add(ArrayDeque())
entries[index].add(entry)
}
}
}
for (line in lines) {
val commands = line.split(" ")
val count = commands[1].toInt()
val start = commands[3].toInt() - 1
val end = commands[5].toInt() - 1
if (retainOrder) buildList {
repeat(count) { add(entries[start].removeFirst()) }
}.asReversed().forEach { entries[end].addFirst(it) }
else repeat(count) {
entries[end].addFirst(entries[start].removeFirst())
}
}
val result = entries.joinToString("") { it.first().toString() }
println(result)
}
}
| 0 | Kotlin | 0 | 1 | 9abda490a7b4e3d9e6113a0d99d4695fcfb36422 | 1,343 | adventofcode | Apache License 2.0 |
src/main/kotlin/pl/poznan/put/mioib/algorithm/weight/SymmetricSolutionEvaluator.kt | Azbesciak | 213,989,135 | false | null | package pl.poznan.put.mioib.algorithm.weight
class SymmetricSolutionEvaluator(
private val weightMatrix: WeightMatrix
): SolutionEvaluator {
override fun solution(sequence: IntArray): Double {
var result = 0.0
require(sequence.size >= 2) {
"instance size must be at least of size 2"
}
val start = sequence[0]
var from = start
(1 until sequence.size).forEach {
val to = sequence[it]
result += weightMatrix[from, to]
from = to
}
result += weightMatrix[from, start]
return result
}
override fun delta(firstIndex: Int, secondIndex: Int, sequence: IntArray): Double {
var fi = firstIndex
var si = secondIndex
val lastIndex = sequence.size - 1
if ((fi > si && !(fi == lastIndex && si == 0)) || (fi == 0 && si == lastIndex)) {
fi = secondIndex
si = firstIndex
}
val firstId = sequence[fi]
val beforeFirstId = sequence[if (fi == 0) lastIndex else (fi - 1)]
val secondId = sequence[si]
val afterSecondId = sequence[if (si == lastIndex) 0 else (si + 1)]
var delta = -weightMatrix[beforeFirstId, firstId]
delta += weightMatrix[beforeFirstId, secondId]
delta -= weightMatrix[secondId, afterSecondId]
delta += weightMatrix[firstId, afterSecondId]
if (si - fi > 1) {
val afterFirstId = sequence[fi + 1]
delta -= weightMatrix[firstId, afterFirstId]
delta += weightMatrix[secondId, afterFirstId]
val beforeSecondId = sequence[si - 1]
delta -= weightMatrix[beforeSecondId, secondId]
delta += weightMatrix[beforeSecondId, firstId]
}
return delta
}
}
| 1 | Kotlin | 0 | 0 | 61e81ccbf8d6054b135f2b18db307cb8bf56f6ba | 1,803 | MetaheuristicsAndOptimization | MIT License |
Problems/Algorithms/407. Trapping Rain Water II/TrapWaterII.kt | xuedong | 189,745,542 | false | {"Kotlin": 332182, "Java": 294218, "Python": 237866, "C++": 97190, "Rust": 82753, "Go": 37320, "JavaScript": 12030, "Ruby": 3367, "C": 3121, "C#": 3117, "Swift": 2876, "Scala": 2868, "TypeScript": 2134, "Shell": 149, "Elixir": 130, "Racket": 107, "Erlang": 96, "Dart": 65} | class Solution {
fun trapRainWater(heightMap: Array<IntArray>): Int {
val n = heightMap.size
val m = heightMap[0].size
val pq = PriorityQueue<IntArray>({ a, b -> a[2] - b[2] })
val visited = Array(n) { BooleanArray(m) { false } }
val neighbors = arrayOf(intArrayOf(0, 1), intArrayOf(0, -1), intArrayOf(1, 0), intArrayOf(-1, 0))
for (i in 0..n-1) {
pq.offer(intArrayOf(i, 0, heightMap[i][0]))
pq.offer(intArrayOf(i, m-1, heightMap[i][m-1]))
visited[i][0] = true
visited[i][m-1] = true
}
for (j in 0..m-1) {
pq.offer(intArrayOf(0, j, heightMap[0][j]))
pq.offer(intArrayOf(n-1, j, heightMap[n-1][j]))
visited[0][j] = true
visited[n-1][j] = true
}
var ans = 0
while (!pq.isEmpty()) {
val curr = pq.poll()
for (neighbor in neighbors) {
val x = curr[0] + neighbor[0]
val y = curr[1] + neighbor[1]
if (x >= 0 && x < n && y >= 0 && y < m && !visited[x][y]) {
visited[x][y] = true
ans += maxOf(0, curr[2] - heightMap[x][y])
pq.offer(intArrayOf(x, y, maxOf(heightMap[x][y], curr[2])))
}
}
}
return ans
}
}
| 0 | Kotlin | 0 | 1 | 5e919965b43917eeee15e4bff12a0b6bea4fd0e7 | 1,423 | leet-code | MIT License |
src/main/kotlin/com/sk/topicWise/dp/139. Word Break.kt | sandeep549 | 262,513,267 | false | {"Kotlin": 530613} | package com.sk.topicWise.dp
class Solution139 {
// dp, bottom-up
fun wordBreak(s: String, wordDict: List<String>): Boolean {
val dp = BooleanArray(s.length)
val dict = wordDict.toSet()
for (i in s.indices) {
for (j in i downTo 0) {
//val part1 = s.substring(0, j+1)
val part2 = s.substring(j, i + 1)
if ((j - 1 < 0 || dp[j - 1]) && dict.contains(part2)) {
dp[i] = true
break
}
}
}
return dp[s.lastIndex]
}
}
// Recursion, time limit exceeded
private fun wordBreak(s: String, wordDict: List<String>): Boolean {
var set = wordDict.toSet()
fun isWord(start: Int, end: Int) = set.contains(s.substring(start, end + 1))
fun canBreak(start: Int, end: Int): Boolean {
if (start > end) return true
var res = false
for (j in start..end) {
if (isWord(start, j) && canBreak(j + 1, end)) {
res = true
break
}
}
return res
}
return canBreak(0, s.lastIndex)
}
// dp, bottom-up, recursive
// O(n^2)
// O(n)
private fun wordBreak2(s: String, wordDict: List<String>): Boolean {
var set = wordDict.toSet()
var table = Array<Boolean?>(s.length + 1) { null }
fun isWord(start: Int, end: Int) = set.contains(s.substring(start, end + 1))
fun canBreak(start: Int, end: Int): Boolean {
if (start > end) return true
table[start]?.let { return it }
var res = false
for (j in start..end) {
if (isWord(start, j) && canBreak(j + 1, end)) {
table[j + 1] = true
res = true
break
}
}
table[start] = res
return res
}
return canBreak(0, s.lastIndex)
}
// dp, bottom-up, iterative
// O(n^2)
// O(n)
fun wordBreak3(s: String, wordDict: List<String?>): Boolean {
val set = wordDict.toSet()
val dp = BooleanArray(s.length + 1)
dp[0] = true
for (i in 1..s.length) {
for (j in 0 until i) {
if (dp[j] && set.contains(s.substring(j, i))) {
dp[i] = true
break
}
}
}
return dp[s.length]
}
| 1 | Kotlin | 0 | 0 | cf357cdaaab2609de64a0e8ee9d9b5168c69ac12 | 2,294 | leetcode-kotlin | Apache License 2.0 |
src/main/kotlin/year2023/day16/Problem.kt | Ddxcv98 | 573,823,241 | false | {"Kotlin": 154634} | package year2023.day16
import IProblem
import kotlin.math.max
class Problem : IProblem {
val map = javaClass
.getResourceAsStream("/2023/16.txt")!!
.bufferedReader()
.lines()
.map(String::toCharArray)
.toList()
.toTypedArray()
private val n = map.size
private fun beamDeezNuts(start: Triple<Int, Int, Int>): Int {
val matrix = Array(n) { IntArray(n) }
val queue = ArrayDeque<Triple<Int, Int, Int>>()
var count = 0
queue.add(start)
while (queue.isNotEmpty()) {
val (x, y, mask) = queue.removeFirst()
if (x !in 0..<n || y !in 0..<n || matrix[y][x].and(mask) == mask) {
continue
}
if (matrix[y][x] == 0) {
count++
}
matrix[y][x] = matrix[y][x].or(mask)
when (map[y][x]) {
'-' -> {
queue.add(Triple(x - 1, y, LEFT))
queue.add(Triple(x + 1, y, RIGHT))
}
'.' -> {
when (mask) {
LEFT -> queue.add(Triple(x - 1, y, mask))
UP -> queue.add(Triple(x, y - 1, mask))
RIGHT -> queue.add(Triple(x + 1, y, mask))
DOWN -> queue.add(Triple(x, y + 1, mask))
}
}
'/' -> {
when (mask) {
LEFT -> queue.add(Triple(x, y + 1, DOWN))
UP -> queue.add(Triple(x + 1, y, RIGHT))
RIGHT -> queue.add(Triple(x, y - 1, UP))
DOWN -> queue.add(Triple(x - 1, y, LEFT))
}
}
'\\' -> {
when (mask) {
LEFT -> queue.add(Triple(x, y - 1, UP))
UP -> queue.add(Triple(x - 1, y, LEFT))
RIGHT -> queue.add(Triple(x, y + 1, DOWN))
DOWN -> queue.add(Triple(x + 1, y, RIGHT))
}
}
'|' -> {
queue.add(Triple(x, y - 1, UP))
queue.add(Triple(x, y + 1, DOWN))
}
}
}
return count
}
override fun part1(): Int {
return beamDeezNuts(Triple(0, 0, RIGHT))
}
override fun part2(): Int {
var max = 0
for (i in 0 until n) {
max = max(beamDeezNuts(Triple(0, i, RIGHT)), max)
max = max(beamDeezNuts(Triple(i, 0, DOWN)), max)
max = max(beamDeezNuts(Triple(n - 1, i, LEFT)), max)
max = max(beamDeezNuts(Triple(i, n - 1, UP)), max)
}
return max
}
}
| 0 | Kotlin | 0 | 0 | 455bc8a69527c6c2f20362945b73bdee496ace41 | 2,796 | advent-of-code | The Unlicense |
src/algorithmdesignmanualbook/sorting/ColorSort.kt | realpacific | 234,499,820 | false | null | package algorithmdesignmanualbook.sorting
import algorithmdesignmanualbook.print
import utils.assertIterableSame
import java.util.*
private typealias Color = Pair<Int, String>
/**
* Assume that we are given n pairs of items as input, where the first item is a
* number and the second item is one of three colors (red, blue, or yellow).
* Further assume that the items are sorted by number.
* Give an O(n) algorithm to sort the items by color (all reds before all blues before all yellows)
* such that the numbers for identical colors stay sorted.
*
* Solution: Maintain 3 queue for each color. At last, dequeue red, blue and then yellow
*/
private fun colorSort(array: Array<Color>): List<Color> {
array.print("Input:")
val redQueue = LinkedList<Color>()
val blueQueue = LinkedList<Color>()
val yellowQueue = LinkedList<Color>()
array.forEach {
when (it.second) {
"blue" -> blueQueue.addLast(it)
"red" -> redQueue.addLast(it)
"yellow" -> yellowQueue.addLast(it)
}
}
val result = mutableListOf<Color>()
while (redQueue.isNotEmpty()) {
result.add(redQueue.removeFirst())
}
while (blueQueue.isNotEmpty()) {
result.add(blueQueue.removeFirst())
}
while (yellowQueue.isNotEmpty()) {
result.add(yellowQueue.removeFirst())
}
return result.print()
}
fun main() {
val input = arrayOf(Pair(1, "blue"), Pair(3, "red"), Pair(4, "blue"), Pair(6, "yellow"), Pair(9, "red"))
assertIterableSame(
actual = colorSort(input),
expected = listOf(Pair(3, "red"), Pair(9, "red"), Pair(1, "blue"), Pair(4, "blue"), Pair(6, "yellow"))
)
} | 4 | Kotlin | 5 | 93 | 22eef528ef1bea9b9831178b64ff2f5b1f61a51f | 1,685 | algorithms | MIT License |
yandex/y2020/qual/a.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package yandex.y2020.qual
fun main() {
val s = readLn()
fun solve(s: String): Pair<Int, String>? {
if (s.length == 1) return 0 to s
if (s.length == 2) {
if (s[0] == s[1]) return null
return 0 to s
}
val (even, odd) = List(2) { s.filterIndexed { index, _ -> index % 2 == it } }
if (even.all { it == even[0] } && even[0] !in odd) {
val recursive = solve(odd) ?: return null
return recursive.first * 2 to even[0] + recursive.second
}
if (odd.all { it == odd[0] } && odd[0] !in even) {
val recursive = solve(even) ?: return null
return recursive.first * 2 + 1 to odd[0] + recursive.second
}
return null
}
val solution = solve(s) ?: return println("No solution")
println(solution.second + ('A'..'Z').filter { it !in solution.second }.joinToString(""))
println(solution.first + 1)
}
private fun readLn() = readLine()!!
| 0 | Java | 1 | 9 | 30953122834fcaee817fe21fb108a374946f8c7c | 857 | competitions | The Unlicense |
src/main/kotlin/com/groundsfam/advent/y2023/d19/Day19.kt | agrounds | 573,140,808 | false | {"Kotlin": 281620, "Shell": 742} | package com.groundsfam.advent.y2023.d19
import com.groundsfam.advent.DATAPATH
import com.groundsfam.advent.timed
import java.nio.file.Path
import kotlin.io.path.div
import kotlin.io.path.useLines
import kotlin.math.max
import kotlin.math.min
sealed class Rule {
/**
* Checks if the part matches this rule's condition. If it does, this returns the name of the next workflow
* to apply. If not, it returns null.
*
* This may return the special names "A" and "R" for final acceptance or rejection.
*/
abstract fun check(partRating: PartRating): String?
}
data class ComparisonRule(val ratingName: Char, val value: Int, val lessThan: Boolean, val nextWorkflow: String) : Rule() {
override fun check(partRating: PartRating): String? =
if (lessThan xor (partRating[ratingName]!! > value)) {
nextWorkflow
} else {
null
}
}
data class DefaultRule(val nextWorkflow: String): Rule() {
override fun check(partRating: PartRating): String = nextWorkflow
}
@JvmInline
value class PartRating(val ratingMap: Map<Char, Int>) : Map<Char, Int> by ratingMap
@JvmInline
value class PartRatingRange(val ratingRangeMap: Map<Char, IntRange>) : Map<Char, IntRange> by ratingRangeMap {
fun copy(k: Char, v: IntRange): PartRatingRange =
mutableMapOf<Char, IntRange>()
.apply {
ratingRangeMap.forEach { (k1, v1) ->
if (k1 == k) {
this[k] = v
} else {
this[k1] = v1
}
}
}
.let(::PartRatingRange)
}
fun partIsAccepted(partRating: PartRating, workflows: Map<String, List<Rule>>): Boolean {
var workflowName = "in"
while (workflowName !in setOf("A", "R")) {
workflowName = workflows[workflowName]!!
.firstNotNullOf { it.check(partRating) }
}
return workflowName == "A"
}
fun acceptedRanges(workflows: Map<String, List<Rule>>): List<PartRatingRange> {
val paths = mutableListOf<PartRatingRange>()
data class QueueItem(val nextWorkflow: String, val partRatingRange: PartRatingRange)
val queue = ArrayDeque<QueueItem>()
val startingRange = (1..4000).let {
PartRatingRange(mapOf('x' to it, 'm' to it, 'a' to it, 's' to it))
}
queue.add(QueueItem("in", startingRange))
while (queue.isNotEmpty()) {
val (nextWorkflow, prevRange) = queue.removeFirst()
val workflow = workflows[nextWorkflow]!!
workflow.fold(prevRange as PartRatingRange?) { range, rule ->
if (range == null) null
else when (rule) {
is ComparisonRule -> {
val ratingName = rule.ratingName
val value = rule.value
val ratingRange = range[ratingName]!!
val appliedRange =
if (rule.lessThan) {
ratingRange.first..min(value - 1, ratingRange.last)
} else {
max(value + 1, ratingRange.first)..ratingRange.last
}
.takeIf { it.first <= it.last }
val unappliedRange =
if (rule.lessThan) {
max(value, ratingRange.first)..ratingRange.last
} else {
ratingRange.first..min(value, ratingRange.last)
}
.takeIf { it.first <= it.last }
if (appliedRange != null) {
when (rule.nextWorkflow) {
"R" -> {} // ignore it
"A" -> paths.add(range.copy(ratingName, appliedRange))
else -> queue.add(
QueueItem(rule.nextWorkflow, range.copy(ratingName, appliedRange))
)
}
}
unappliedRange?.let { range.copy(ratingName, it) }
}
is DefaultRule -> {
when (rule.nextWorkflow) {
"R" -> {} // ignore it
"A" -> paths.add(range)
else -> {
queue.add(QueueItem(rule.nextWorkflow, range))
}
}
range
}
}
}
}
return paths
}
fun parseInput(path: Path): Pair<Map<String, List<Rule>>, List<PartRating>> {
val workflows = mutableMapOf<String, List<Rule>>()
val partRatings = mutableListOf<PartRating>()
path.useLines { lines ->
var parsingWorkflows = true
lines.forEach { line ->
when {
line.isBlank() -> {
parsingWorkflows = false
}
parsingWorkflows -> {
val (name, rawRules) = line.split("{")
workflows[name] = rawRules
.substring(0 until rawRules.length - 1)
.split(",")
.map { rawRule ->
val colonIdx = rawRule.indexOf(':').takeIf { it > -1 }
if (colonIdx != null) {
ComparisonRule(
ratingName = rawRule[0],
value = rawRule.substring(2 until colonIdx).toInt(),
lessThan = rawRule[1] == '<',
nextWorkflow = rawRule.substring(colonIdx + 1),
)
} else {
DefaultRule(rawRule)
}
}
}
else -> {
line.substring(1 until line.length - 1)
.split(',')
.associate { it[0] to it.substring(2).toInt() }
.let(::PartRating)
.also(partRatings::add)
}
}
}
}
return Pair(workflows, partRatings)
}
fun main() = timed {
val (workflows, partRatings) = parseInput(DATAPATH / "2023/day19.txt")
partRatings
.filter { partIsAccepted(it, workflows) }
.sumOf { it.values.sum() }
.also { println("Part one: $it") }
acceptedRanges(workflows)
.sumOf { range ->
range.values
.fold(1L) { a, r ->
a * (r.last - r.first + 1)
}
}
.also { println("Part two: $it") }
}
| 0 | Kotlin | 0 | 1 | c20e339e887b20ae6c209ab8360f24fb8d38bd2c | 6,778 | advent-of-code | MIT License |
advent23-kt/app/src/main/kotlin/dev/rockyj/advent_kt/Day8.kt | rocky-jaiswal | 726,062,069 | false | {"Kotlin": 41834, "Ruby": 2966, "TypeScript": 2848, "JavaScript": 830, "Shell": 455, "Dockerfile": 387} | package dev.rockyj.advent_kt
private fun part2(input: List<String>) {
val mapM = mutableMapOf<String, Pair<String, String>>()
val steps = input.get(0).trim().split("").filter { it != "" }
input.subList(2, input.size).forEach { line ->
val parts = line.split(" = ")
val lr = parts.last().split(",")
mapM.put(parts.first(), Pair(lr.first().substring(1), lr.last().substring(1, 4)))
}
val mapX = mapM.toMap()
println(mapX.keys.last())
var starts = mapX.filter { it.key.endsWith("A") }.map { it.key }
var counter = 0
var stepCounter = 0
var done = false
while (!done) {
counter += 1
val step = if (stepCounter < steps.size) {
steps.get(stepCounter)
} else {
stepCounter = 0
steps.get(stepCounter)
}
val next = if (step == "L") {
starts.map { mapX[it]!!.first }
} else {
starts.map { mapX[it]!!.second }
}
if (next.all { it.endsWith("Z") }) {
done = true
}
stepCounter += 1
starts = next
}
println(counter)
}
private fun part1(input: List<String>) {
val mapM = mutableMapOf<String, Pair<String, String>>()
val steps = input.get(0).trim().split("").filter { it != "" }
// println(steps)
input.subList(2, input.size).forEach { line ->
val parts = line.split(" = ")
val lr = parts.last().split(",")
mapM.put(parts.first(), Pair(lr.first().substring(1), lr.last().substring(1, 4)))
}
val map = mapM.toMap()
// println(map)
var dirs = map.get("AAA")
var counter = 0
var stepCounter = 0
var done = false
while (!done) {
counter += 1
val step = if (stepCounter < steps.size) {
steps.get(stepCounter)
} else {
stepCounter = 0
steps.get(stepCounter)
}
val next = if (step == "L") {
dirs!!.first
} else {
dirs!!.second
}
if (next == "ZZZ") {
done = true
}
stepCounter += 1
dirs = map.get(next)
}
println(counter)
}
fun main() {
val lines = fileToArr("day8_2.txt")
part1(lines)
// part2(lines) // brute force does not work!!
} | 0 | Kotlin | 0 | 0 | a7bc1dfad8fb784868150d7cf32f35f606a8dafe | 2,324 | advent-2023 | MIT License |
leetcode/src/linkedlist/Q706.kt | zhangweizhe | 387,808,774 | false | null | package linkedlist
fun main() {
// 706. 设计哈希映射
// https://leetcode-cn.com/problems/design-hashmap/
val myHashMap = MyHashMap()
myHashMap.put(1, 1)
println(myHashMap.get(1))
myHashMap.put(1, 2)
println(myHashMap.get(1))
println(myHashMap.get(2))
myHashMap.put(2, 5)
println(myHashMap.get(2))
myHashMap.remove(2)
println(myHashMap.get(2))
}
const val BASE = 987
class MyHashMap() {
/** Initialize your data structure here. */
private val array: Array<Node?> = arrayOfNulls(BASE)
/** value will always be non-negative. */
fun put(key: Int, value: Int) {
var index = key % BASE
var head = array[index]
if (head == null) {
head = Node(Pair(key, value))
array[index] = head
}else {
while (head != null) {
if (head.value.first == key) {
head.value = Pair(key, value)
break
}else if (head.next == null) {
// 最后一个节点
val node = Node(Pair(key, value))
head.next = node
break
} else {
head = head.next
}
}
}
}
/** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */
fun get(key: Int): Int {
var index = key % BASE
var node = array[index]
while (node != null) {
if (node.value.first == key) {
return node.value.second
}else {
node = node.next
}
}
return -1
}
/** Removes the mapping of the specified value key if this map contains a mapping for the key */
fun remove(key: Int) {
var index = key % BASE
var node = array[index]
var prev:Node? = null
while (node != null) {
if (node.value.first == key) {
if (prev == null) {
array[index] = node.next
}else {
prev.next = node.next
}
break
}else {
prev = node
node = node.next
}
}
}
}
private class Node(var value: Pair<Int, Int>) {
var next:Node? = null
}
| 0 | Kotlin | 0 | 0 | 1d213b6162dd8b065d6ca06ac961c7873c65bcdc | 2,391 | kotlin-study | MIT License |
src/main/kotlin/feb_challenge2023/ShortestPathWithAltColors.kt | yvelianyk | 405,919,452 | false | {"Kotlin": 147854, "Java": 610} | package feb_challenge2023
import java.util.*
fun main() {
val result =
ShortestPathWithAltColors()
.shortestAlternatingPaths(
5,
arrayOf(intArrayOf(0, 1), intArrayOf(1, 2), intArrayOf(2, 3), intArrayOf(3, 4)),
arrayOf(intArrayOf(1, 2), intArrayOf(2, 3), intArrayOf(3, 1))
)
// val result =
// ShortestPathWithAltColors()
// .shortestAlternatingPaths(
// 3,
// arrayOf(intArrayOf(0, 1), intArrayOf(0, 2)),
// arrayOf(intArrayOf(1,0))
// )
println(result)
}
class ShortestPathWithAltColors {
private val graph = mutableMapOf<Int, MutableList<Point>>()
private var graphSize = 0
private var result = intArrayOf()
fun shortestAlternatingPaths(n: Int, redEdges: Array<IntArray>, blueEdges: Array<IntArray>): IntArray {
graphSize = n
result = IntArray(n) { -1 }
buildGraph(redEdges, blueEdges)
bfs()
return result
}
private fun bfs() {
val visited = mutableSetOf<String>()
val queue: Queue<Point> = LinkedList()
queue.add(Point(0, -1))
visited.add("c-1v0")
result[0] = 0
var distance = -1
while (!queue.isEmpty()) {
distance++
val size = queue.size
for (i in 0 until size) {
val curr = queue.poll()
if (result[curr.value] == -1) result[curr.value] = distance
val children = graph.getOrDefault(curr.value, mutableListOf())
for (child in children) {
val visitedKey = "c${child.color}v${child.value}"
if (!visited.contains(visitedKey) and (curr.color != child.color)) {
queue.add(child)
visited.add(visitedKey)
}
}
}
}
}
private fun buildGraph(redEdges: Array<IntArray>, blueEdges: Array<IntArray>) {
for (redEdge: IntArray in redEdges) processEdge(0, redEdge)
for (blueEdge: IntArray in blueEdges) processEdge(1, blueEdge)
}
private fun processEdge(color: Int, edge: IntArray) {
val from = edge[0]
val to = edge[1]
val existingEdges = graph.getOrDefault(from, mutableListOf())
existingEdges.add(Point(to, color))
graph[from] = existingEdges
}
internal data class Point(val value: Int = -1, val color: Int = -1)
} | 0 | Kotlin | 0 | 0 | 780d6597d0f29154b3c2fb7850a8b1b8c7ee4bcd | 2,523 | leetcode-kotlin | MIT License |
src/main/kotlin/aoc2022/Day18.kt | davidsheldon | 565,946,579 | false | {"Kotlin": 161960} | package aoc2022
import aoc2022.utils.bfs
import utils.Cube
import utils.InputUtils
import utils.toPoint3d
fun main() {
val testInput = """2,2,2
1,2,2
3,2,2
2,1,2
2,3,2
2,2,1
2,2,3
2,2,4
2,2,6
1,2,5
3,2,5
2,1,5
2,3,5""".split("\n")
fun part1(input: List<String>): Int {
val points = input.map { it.toPoint3d() }.toSet()
return points.sumOf { point -> point.connected().filter { it !in points }.count() }
}
fun part2(input: List<String>): Int {
val points = input.map { it.toPoint3d() }.toSet()
val space = points.fold(Cube(points.first(), points.first()), Cube::expand).padded(1)
val outside = space.min
val air = bfs(outside) { point -> point.connected().filter { it in space && it !in points } }.toSet()
return points.sumOf { point -> point.connected().filter { it in air }.count() }
}
val testValue = part1(testInput)
println(testValue)
check(testValue == 64)
val puzzleInput = InputUtils.downloadAndGetLines(2022, 18).toList()
println(part1(puzzleInput))
println(part2(testInput))
println(part2(puzzleInput))
}
| 0 | Kotlin | 0 | 0 | 5abc9e479bed21ae58c093c8efbe4d343eee7714 | 1,130 | aoc-2022-kotlin | Apache License 2.0 |
advent-of-code-2020/src/test/java/aoc/Day18OperationOrder.kt | yuriykulikov | 159,951,728 | false | {"Kotlin": 1666784, "Rust": 33275} | package aoc
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
import java.util.*
class Day18OperationOrder {
@Test
fun noParantheses() {
assertThat(evaluate("2 * 3 + 4 * 5 ")).isEqualTo(50)
}
@Test
fun silverTest() {
assertThat(evaluate("2 * 3 + (4 * 5) ")).isEqualTo(26)
assertThat(evaluate("5 + (8 * 3 + 9 + 3 * 4 * 3) ")).isEqualTo(437)
assertThat(evaluate("5 * 9 * (7 * 3 * 3 + 9 * 3 + (8 + 6 * 4)) ")).isEqualTo(12240)
assertThat(evaluate("((2 + 4 * 9) * (6 + 9 * 8 + 6) + 6) + 2 + 4 * 2 ")).isEqualTo(13632)
}
@Test
fun silver() {
val sum = testInput.lines()
.map { evaluate(it) }
.sum()
assertThat(sum).isEqualTo(209335026987L)
}
data class Calculation(
var acc: Long = 0,
var op: String = "+",
)
private fun evaluate(s: String): Long {
val tokenizer = StringTokenizer(s.replace(" ", ""), "+*()", true)
val stack = mutableListOf(Calculation())
fun addOrMultiply(value: Long) {
when (stack.last().op) {
"+" -> stack.last().acc += value
"*" -> stack.last().acc *= value
}
}
while (tokenizer.hasMoreTokens()) {
val nextToken = tokenizer.nextToken()
when {
nextToken == "*" -> stack.last().op = "*"
nextToken == "+" -> stack.last().op = "+"
nextToken == "(" -> stack.add(Calculation())
nextToken == ")" -> {
val popped = stack.removeLast()
addOrMultiply(popped.acc)
}
nextToken.toIntOrNull() != null -> addOrMultiply(nextToken.toLong())
}
}
return stack.last().acc
}
@Test
fun goldTest() {
assertThat(evaluateAdvancedMath("1 + (2 * 3) + (4 * (5 + 6))")).isEqualTo(51)
assertThat(evaluateAdvancedMath("2 * 3 + (4 * 5)")).isEqualTo(46)
assertThat(evaluateAdvancedMath("5 + (8 * 3 + 9 + 3 * 4 * 3)")).isEqualTo(1445)
assertThat(evaluateAdvancedMath("5 * 9 * (7 * 3 * 3 + 9 * 3 + (8 + 6 * 4))")).isEqualTo(669060)
assertThat(evaluateAdvancedMath("((2 + 4 * 9) * (6 + 9 * 8 + 6) + 6) + 2 + 4 * 2 ")).isEqualTo(23340)
}
@Test
fun gold() {
val sum = testInput.lines()
.map { evaluateAdvancedMath(it) }
.sum()
assertThat(sum).isEqualTo(33331817392479L)
}
sealed class Exp {
class Calc : Exp() {
val exp = mutableListOf<Exp>()
}
class Num(val value: Long) : Exp()
class Op(val value: String) : Exp()
}
fun Exp.Calc.eval(): Long {
return exp.joinToString("") {
when (it) {
is Exp.Calc -> it.eval().toString()
is Exp.Op -> it.value
is Exp.Num -> it.value.toString()
}
}
.split("*")
.map { toSum -> toSum.split("+").map { it.toLong() }.sum() }
.reduce(Long::times)
}
private fun evaluateAdvancedMath(s: String): Long {
val stack = tokenizeExpressions(s)
return stack.last().eval()
}
private fun tokenizeExpressions(s: String): MutableList<Exp.Calc> {
val tokenizer = StringTokenizer(s.replace(" ", ""), "+*()", true)
val stack = mutableListOf(Exp.Calc())
while (tokenizer.hasMoreTokens()) {
val nextToken = tokenizer.nextToken()
when {
nextToken == "*" -> stack.last().exp.add(Exp.Op("*"))
nextToken == "+" -> stack.last().exp.add(Exp.Op("+"))
nextToken == "(" -> stack.add(Exp.Calc())
nextToken == ")" -> {
val popped = stack.removeLast()
stack.last().exp.add(popped)
}
nextToken.toIntOrNull() != null -> stack.last().exp.add(Exp.Num(nextToken.toLong()))
}
}
return stack
}
private val testInput = """
4 * 5 + 7 * 2 + 8
((3 * 6 + 2) * 7 + (5 * 4 + 6 + 8)) + 2 * 7 * 5
((5 + 9) + 6) + 6
(9 + 3 + 3 + 3) + (2 + (6 * 2 * 3) + 5 * 5) + 3 + (2 * 3 * 6 * 4 * 3 * (7 + 4)) * 6 * 6
(4 + (3 * 2 * 8 * 4 + 5 * 8)) + 3 * 9
(3 * 9 * 7 * 6 * 3 + 9) * 9
8 + 6 + 7 * 2 * 9 * 3
(6 * 3 * 8 + (7 + 8 * 3)) * 4 * (3 + 3 * 2 * 8 * 8)
(8 + 2 * (2 + 2)) * 2 * 9 * 7 * 3 * (9 * 4 + 6 * 9 + 2 * 7)
(4 + 6 * 2 + 8) * 6
((3 * 7 * 5) * 3) + 3
((5 * 4 * 9 * 5 * 2 + 2) + 5 * 9 * 7 * 9 + 5) * 9 + 9
7 + 7 * 7 * (4 * (5 + 5 + 9 * 7 * 5) * 3 * 8)
3 + (7 * 7 * (3 * 2 * 8)) + 7 + 5
3 * 9 + 5 * 7 + 5 * 6
5 * 5 * (9 * 4 + (6 + 4)) * 6 + 3 * 8
2 + (9 * 7 * 5 + 4) + 3 * (2 * 8 * 2 + 7 + (5 * 8 * 4 * 3) + 2)
2 + (7 + 6 + 4 + 3 * 5 * (7 + 6 * 9 * 3 * 6 + 7))
(5 + 7 + 3 * (5 * 3 * 4 * 5) + 2 * 2) * 6 + (9 + 4 + (4 + 9 + 2 + 3) + 7 * 4 + (8 + 8)) + 6 + (7 + (5 + 2) + 2 * 8 + 9)
5 * 4 * 5 + 8 * (4 * 4 * 4)
2 + 8 + 8
2 + ((7 + 5 + 8 * 6) * 6 * 8 + 4 + 8) * 6 * 6 + (4 * 8 + 8 + 4 + 5 * 2) + (2 + 8 * 6)
(3 + (2 * 7) * 6 * 2 + (5 + 7 * 3 * 2 * 4)) + (7 * 7 * 7 + 7 + 6 * 8) + (6 * 2 * (7 + 7 + 8) + 7 * 7) * 2 + 5 + 4
6 + 9 + 3 * ((2 * 3 * 8 + 6) * 8 * 2 + 6)
5 + 7 * (5 + 9 + (6 + 7) + 2 * 9 * 9) + 9 + (7 + 6 + (8 * 5) + 9 * 6 * 3) * 2
((6 * 3 + 8 * 5) + 8 * (3 + 8 * 7)) * (2 + 9 * 2 * 8 + 3) * 8 * 5 + 3
8 * 6 + 2 * (7 * (8 * 9 + 7 + 4) + 9)
6 * (2 + (5 + 6 * 2 * 8) + 4 * (4 + 6)) * ((2 * 7 + 6 + 7 * 6 + 6) * 5 * 5 + (3 * 8 + 9) * 3 * 8)
8 * 2 * (2 + 4) * 8 * (7 + (4 * 8))
(4 + 8 * 3 + 4) + (2 * 8 * 9)
3 + (7 * 6) * 3 + 5 * 4
4 * (2 * (8 + 3 * 7 * 5 + 7 * 2) + 3 * 5 + 8 + 3)
(9 * (7 + 8 + 7) * 5) + 8 + 3
5 * 8 + 8 * 3 * 2 + 4
(7 * (9 + 8 + 3 + 7 * 4) + 8 * (2 * 5 * 6) * 5 * (4 + 7 * 4 + 9)) * 2 * 8
8 * 7 * 7 * 8 + ((4 * 9 + 8) * 2 + 4 * 8)
5 + (4 * 4 * 4 + 4 * (2 + 4 + 4 * 2 * 5 + 9) + 6) + 9 * 5
8 * 9 + 8 * ((2 + 6 * 8 + 5 + 7) + (7 + 3 + 4) * 7) + (6 + 7 * 3 + (5 + 4 + 3 * 4 + 9) + 7 + 7) * (7 + 9 * 9 * (6 + 9 + 2 * 7) + 7 + 8)
8 * (4 * 3 + 9 + 8) * 8 * 2 + 9
(3 * 6 + 6 + 6 + 9) + 6 * 2 + 4 * 2 * 7
2 + 7 + (2 + (4 + 2 * 3 + 7 + 8 + 3) + 2) * 6
9 * (6 + 5 * 4 * (6 * 3) + (4 * 7 + 7) + (8 + 6 + 3 + 2 * 6 * 5)) + 4 + ((5 * 4 * 7) + 6 + 7 * (6 + 5 * 9 * 8)) + 4 * 4
7 * 6 * 3 * 2
7 * (3 + 8 * 8) + (3 * (7 + 8 * 3) * (8 + 9 * 4 * 9 * 6) + 8 * 7 * 3) * 4
6 * 5 * 6 * (7 * 7 + 6 * 8) * 3 * 2
6 * 6 + ((6 * 7 + 4) + 4) + 6
7 * 8 * 8 + 9 * 9 + (6 * (3 * 6 + 3))
2 + 5 * (7 + 3 + (5 + 6 + 2 * 4 * 3) + 9 + 4) + 3 + (9 * 2 + 4 + 4 * 9) * (4 + 7 * (4 * 2) * 3 * 9 * 5)
(8 + 7 * (9 * 6 * 3 + 6)) + (4 + 9 * 6 + 6)
4 * 6 * 8 * 5 + 8
3 * ((7 * 5 + 5 + 5) + 5 + 4 * 3 * (2 * 2 + 5 + 5)) * 5
7 + 5 + 6
3 + 3 * (7 * 5)
7 + 2 * (4 * 5 * 7 + 5) * ((8 + 7 * 9) + 3 * 7 + 8) + 4
8 + ((7 + 8) + (8 * 3 + 7) + (2 * 6 * 7 + 6 * 7 * 7) + 6 + 6) + 8 + 8
(2 + 8 + (8 * 4) * 6) + (2 * 2 + 8 + 8 * 6)
9 * 9 * 9 + 4 * 4 * (6 * 6)
6 * 3 * ((6 + 9 * 7 * 7) * 6 * 5 + 4) * 3
(3 + 4 * (4 + 8 * 6 + 3 * 2) * 7 * (8 * 4 * 6) * 2) * 2
3 * 3 * 8 * (8 + 8 * 6 * 7)
((9 + 9 * 4) + 3 * 3) * 5 + 2
8 * 2 + 2 * (3 * 6) * 7 + 5
9 * 2 * 5 + (2 + (2 * 8) * 2 * 8 * 7 * (7 + 7 + 9 + 5)) + 4
6 + (7 * 5 + 9) * 3 * 3 * 2 * (4 * 3 + 4 + 9 * (9 * 9 * 4 + 7))
9 * 4
2 * (6 + 5 + 2 + 6 + 5 * (3 * 6 * 6 * 8 + 8)) + 6
((4 + 7 * 8) + 3 + 6 * 7 + 4 + 8) * 5
(5 * 8 + 6 + (7 * 5 + 5) + 6 * 9) + 6
4 * (9 + 8 * 3 * 9 + 6 + 3) * 7 * (8 + 6)
7 * 8 * 6 * 4 + (4 * 5)
5 + 2 + (6 + (9 + 9) + 8) * ((5 * 7 * 3 * 7 + 6 * 6) + (8 + 8 * 7 + 8) * 4 + 6) * 5
(9 + 7 + 4) + 5 * 6 + 7 * (3 * (3 * 6 + 7) + (6 + 8 + 4 + 7 + 4 + 7)) + (6 + (8 * 2 + 2 + 2))
(4 * (5 * 8 * 9) * (7 * 3) * 9) * 7 + (3 * (5 * 4 * 2 * 7))
(2 * 5 + (9 * 3 + 8 * 7 * 5 + 3) * 2 * 7 * (4 + 4)) + (4 * 3 + (8 * 4 * 5 + 6) * (9 + 2 + 4 * 3 + 4 * 9) + 9) + (5 + 3) * 6
2 + 7 * 3 * (7 + 9) + 9
(9 * (7 + 2 * 8) + 7 * (6 * 5 + 4 * 4 * 8 * 8)) + ((3 + 3) + (3 + 2 * 3 * 5) + 5 + (2 + 4 * 2) * 2 * (5 + 8 * 3 * 3)) + 2
7 + (8 + 8 * 3 + 3 * 4 * 4) + 9 + (3 * 9 * 5 + (3 * 2 * 5 + 9 * 6 * 8) * 7 * (5 + 8 + 9 * 7 + 4 + 9))
(6 + 6 * 3 + 3 * 2) + ((4 + 2) + 9 * (2 * 9 + 3 * 4 * 7) * 2 * 8 * (4 * 5 + 6)) * 9 * 8 + 8
6 + 2
4 * ((7 * 6 + 3 + 8 + 4 * 2) + (6 * 4 * 3 * 5 + 2 * 5) * 6 + (7 * 4 + 5) + 3) * 9 * 3 * 2
3 + ((9 * 6 * 3 * 6) * 4 * 8 + 3) * ((4 + 4 + 9) + 8 * 4 * 7 * 9) * 3
8 * (6 * 8) * (8 + 3 + 6 + 2)
8 * 3 * (7 * 3 + 2 + 4 + (8 * 3) + 3)
3 + 4 * 4 + 7 + (6 * (5 * 5 + 9) + 7)
(7 * (8 + 8 + 5 * 7 * 2 * 7) + 7 + 7 * 4 * 4) * 2 * 2 + 7 * (4 + (6 + 6 + 6) + 5 * 4) * 6
9 * 4 * (5 + 2 + 5) * 4 + 3
(8 + 7 + (9 + 3 * 8 + 4)) + 9
8 + (6 * 8 * 8 * 8 + 6 * 7) + (7 * 5 * (3 + 7 + 4 * 4 + 2))
6 + 7 * (3 * 9 + 5 * 6) + (9 * 9) + 5
3 * 4 * (7 + 8 * 8 * 7) + 2 + 7
(5 * 6 * 6) + 4 + 2
(9 + 3 * 8) + 2 * 8 * ((3 + 9 * 6 * 2 + 7) + 7)
7 * (9 + (2 * 2 + 5 * 3) * 9 * (5 * 6 + 4 + 6 * 7)) * 9 * 9 + 9 + 2
((3 * 6 + 6 + 7) + 4 + (2 * 4 * 7 * 6) + 9) + 2 + 3
7 * 9 + 6 + 5 * (9 * (6 * 9 + 4 * 3 * 3 * 7) + 9)
3 + (6 + 4 * 3 * 6 * (3 + 6)) * 9
(2 * 5 + 6) * 2 * (5 + (7 * 6 + 3 + 9 + 2)) + 7 * 3
5 * (9 + 4 * 7 * 4 + 5) * 4
4 + 9 * (6 * 5 * 7 * 4 * 2) * ((2 + 4 * 3) * 8 * (4 * 6 + 5 + 4 + 2))
8 + 7
2 * 9 * (7 * 4 + 4 + 2 + 4 * 4) * 9
(2 * 3 * 4 * 2) * (5 * 3 * 3 + 3 + 3 + 7) * (2 * 5 + 4 + 3 * 2) * 3
6 * 4 + (6 + 5 * 4 + 9) + ((7 + 7 * 6 + 3) * 2 + (6 * 8 * 5)) * ((4 * 2) * 5 * 6 * 3 * (6 + 3 * 8) + 3)
(9 + 4 * 3 * 8) * ((2 * 9 + 2 * 5 + 7 + 3) * 9 + 7 * 2 * 3)
9 + 9 + 5 * ((4 * 3 * 6 * 4 + 4) + 2 + 2 + 4) + 7
8 * 6 + 8 * 9 * (5 + 7 + 8 + 9 * 5)
2 + 3 * 6 * 8 * 4 * (7 * 4 * (2 + 9 * 3 + 7 + 7) + 5)
(6 + 6 * 5) + 7 + 9 * (3 * 6 + 6 + (5 * 5 + 3 + 5 + 4 * 9)) + 5
7 * (2 + 5)
4 * 3 * (3 * 3 * 9 * 5 + 3) + 2 + 8 * 3
(4 + 4 * 4) + 2 * (9 * (5 * 9 + 6 * 5 * 2 * 9)) * 6 * 8 + (5 + 4 * (5 * 7 * 4 + 2 + 9 * 7) + 4 * 7)
(7 * (6 * 3 * 2 * 8 * 8)) + (9 * 4 + 5) * 5 * ((5 + 8 * 5 * 6) + 8)
6 + 3 * 4 + (3 + 2 * 8 + 4) + (6 + 9 + 5)
8 * 2 + ((5 + 8 * 8 * 8) * (2 + 2 + 9 + 6 + 8 * 2) * 7 * 7 * (4 * 5 * 7 + 7)) * 9
8 + (2 * 8 * 9 + 6 * 9) + 9 * (9 * 5) + (4 * (7 + 9 * 7 + 5 + 7) + 6 * 6 + 5 * 6)
6 + (2 + 2) + 2 + (9 * 7 + 8 * 3 * 6 + 3) + 9
6 + 4 * 8 + ((7 + 8 + 3 * 9 * 6 * 8) + 4 + 5 * (9 * 6 + 3 * 5 + 3)) * 7 + 2
(7 + 5 + 4 * (5 * 3) + (7 * 5) + (5 * 8 * 2 + 2 * 3 + 2)) * 6 * 5 * 4 + 5
3 + ((3 + 8 * 8) * 2 * 8 + 8 + (7 + 5 + 5 * 6 + 9)) * (9 + 9 + 9) * 9 * 3
(6 + 3 + 4) * 5 + 3 + 4 + 8
((9 + 7 * 9 + 6) + 6 + 9) + 6 * 6 + (4 * 4 + 7) * 6
6 * 6 + 9 + 3 + 4
9 * 9 * 7
5 * ((6 * 6 + 7 + 7) * 8 * 8 + (2 * 8 * 6 + 3 * 7) + (7 + 9 + 8 * 6 + 3)) + 3
(5 * (3 * 4) * 2 + 5 * (6 + 9)) + 9 * 2
(8 * (4 + 2) + 5) + 9 + 8
((4 + 4) * 4 * 4) + (9 * 5 * 9) * 4 * 8 * 9 * 6
3 * 5 + 8 * 4 * 2 * 7
2 + (2 + 9) + 2 * 4 + (8 * (6 * 9 * 3 + 2) + 5) + (9 + 2 * (2 + 9 * 9 + 6))
3 + 6 + 4 * (6 + 4 * 4) + 5
6 + (6 * 9 * 8 * 6 + (5 * 7 + 4 * 3) * 9) * 2
(4 * 3 * 2 + 9 + 2) + 8 + 7
(7 + 7) + 6 + 7
(6 + (3 + 4)) * 3 * 4 * 4
2 * (3 * (6 + 8) + (6 + 8 + 8) + 5 + 3 + 9) + 8 * 7
(8 * (3 + 4) + 8 + 2 * 5 + 2) * 5 + 6 * 9
6 + (4 * 3 + 8 * 7 * (5 * 8 * 2 + 6 * 9 * 4)) + 7 * 7
2 + 4 * ((6 * 7 + 7 * 6 + 2 + 8) + 3 + 6 * 2 + (5 + 8 * 9) + 4)
6 * 3 * (6 + (7 + 6 * 9) * 8 * 9 + 3 * 3) * 4 + (8 * 6 + (2 + 8) + 9) * 7
6 + ((9 + 7) + 6 + 5 * 6 * (8 + 7)) + 6 + (2 * 9)
9 + 8 * 3 + (6 * 8 + 5 + 9 * 8) * (9 + 2 + 9 + 3 + 4 * (6 * 9))
8 + (8 + (8 * 4 * 7 * 8) * (9 * 7 * 2) * 4) * ((9 + 9) + 3 * 4) * 5 + 5 + 3
9 * (2 + 8 + 3) * 7 * (8 * 7) * 3
8 + 5 + (2 + 7) * 6
9 + (3 * 5 * 2 + 9) * 9 + (2 * 9 + 4 + 6 * 7)
6 + (9 * (9 * 5) + 5 * 8) + 6 + 4 + 3 * 7
9 * (7 + 4 + 9 * 3 + (5 * 2 + 8) * 4)
4 * 2 + 2 * 2 + 4 + 3
(4 + 7 + 6 + 3 * 6) * 6 * 9 * 6
5 + 7 * 9 * (3 + 3 + 8 + 4 * 7 * 5) + 7 + (3 + 7 + 5 * 5)
(7 + (8 * 2)) * 3 * 3 + (2 * (3 + 3) * 8 * 4)
6 + 4 * 7 + ((9 * 2 + 6) + 7 + (9 * 7 + 5 + 5 + 6) + 4 + 9) * 8 + 8
4 + (2 + 2 + 6 * 2 * (8 * 3 + 4)) + ((2 + 7 + 8 * 5) + 6 + 8 * 4 * 3)
9 * 8 + 4 * 9 * ((6 * 3) * 5 * 6 * (2 * 5) * 5 * 2) * 9
9 * (7 + 9 + 3 + 5) + (8 * 3 * 7 * 7 * 9 + 3) * 7 * 5
4 + (4 + 3) + 6
9 + (9 + 8 + 5 * 3 * 9 * (8 + 3 * 2 * 9 + 5)) * 8 * 3 + (2 * 3 + (2 * 9 + 4 + 3 * 4) + 5)
((8 + 8) + (6 + 4 + 2 * 6 * 3)) * 6
7 + (2 * 6 + 4 + 8 + 8 * 7) * 8 + 7 * 6
7 + 8 + 4 * (5 * 4 * 9 + 5 + 8) * 3 + 2
(6 + 5 + 4 + 7 + 4) + 8 + 7 * (7 + (7 * 7) * 4 * 4 + 4 + (9 * 4 * 3 + 9 * 5)) * 7 * 8
(7 + 3 + (3 + 7 + 8 + 9 * 6) * 9 * 5) * (2 + (3 + 6 + 7 * 2) * (7 * 3) + 9)
(9 * 7 + (8 + 6 + 2 * 5) * 6 * 9) + 4 + 3
(8 * (5 + 2 * 2 + 6 + 8 * 9) * (4 + 3 + 7 + 4 * 4 + 6) * 2) + 6 + (5 * 9) + 3 + 9 + (8 + 3 + 9)
((7 + 3 * 3 + 6) * 8 + 7) * 9 + (2 + 5 + 4)
(3 * (2 + 8 + 7 + 4 * 2)) + 6 * (9 + 5 * 2 + 5 + 7 * 3)
(9 * 6 + 6 + 5) + (5 * (4 * 5 * 8 * 2 * 6) + (3 + 6 * 2 * 4 * 5 + 9))
(7 * (8 * 7 * 6 + 9 * 5) + 3 * 7 * (7 * 9) * 7) * 2 * 4 * 4
4 + 3 * (2 * (4 + 3 + 6) * 6 + 7 * 3 + (8 * 5 * 6 * 6)) * 7
9 + (6 * 2 + (3 + 2 * 5 * 6 + 8 + 9) * 8) + ((6 * 3 + 6 * 2 * 4 * 4) * 8 + 5)
((5 + 6 + 8 + 7 + 2) * 9 + 2) * 7 + 2 + 5
((9 * 8 + 5 * 3 * 4) * 4 + (9 + 3) + 3 + 6) + 7 * (7 * 4 * 2 + 2 * 9 + 3)
9 * (4 * 4 + 3 * 2) * 3 + 7 + (2 + 2 * 7) + 2
4 + 2 * (6 + 7 * (6 * 2 + 7 * 6 * 4)) * (3 + 5 * 7 * (3 * 7 + 8 + 3 + 3) + (3 * 2 * 7))
7 + 4 + (7 + 8 + 5 + 7 + 5)
7 + 4 + 8 + ((5 + 2 + 5 * 6 + 5 * 2) + 6 * 8 + 6 + 3 * (6 + 3 * 2 + 8 + 4 + 4)) * 8 * 9
(3 + 7 + 2 * 4 * (2 * 9 * 7 * 2 * 2 + 3) + (6 * 7 * 2 * 2 + 9 * 4)) + 2
5 * 2 * (4 * 7 * 7) * 6
5 * (3 * 8 * (4 * 8 + 8)) * 3 * 9 + 5 * 4
(6 * 2 * 5 * 4) + ((5 + 7 + 7 + 6 * 9 * 4) * 8 + 4 * 9) * 9 * 4 * 6 * 6
5 + (7 + 6 + 9) * 9 + 4 + 3 * 8
2 + (7 + 7) * (7 * 9 + 4) * 7 + ((4 + 7 + 8 * 2 + 3 + 5) * 2 * (8 + 2) * 4 + 4) * 6
3 + 8 + 5 * (2 + 2) + 9 + (5 + 7 + 2)
9 * 7 + 4 + (7 + 2 * (4 + 7 * 4 + 9 + 7 + 2)) * (7 + (2 + 7 * 5 * 4 + 9))
8 * 3 + 5 * 3 * ((2 + 8 + 4 + 7 * 4) * 7 + 3 * 7) + 6
((7 + 2 * 3 + 9 * 4) * 4 * (5 + 9 + 9) * 9 + (7 * 7)) * 2 + 9
5 + 4 + 9
4 * (7 * (4 + 9 + 3 * 7)) * 2
(5 * 9 * 3) * 4 + (6 + 2 + 7 * (4 + 2) + 2) * (9 + 9 * 8 * 9 + (9 * 3 + 9 + 7 * 2)) + ((3 + 4 + 2 + 3) + 2 * 9 + 6)
(3 + 3 + 5 * (8 * 9) * 7) + 4 + 7 * 5
(9 + 3) + 3 * ((5 + 7 * 2 + 6 * 3 + 4) + 6) * 7
9 + (3 * 5 + 7 + 4) * 5 * 9 * 3 * 4
5 * ((7 + 7 * 7) + 9 + 2 + 3)
(9 * 6 * 3 * 5 + 3) * 3 + 8 + 4 + 9 + (3 * (6 + 9 + 8 + 9 * 2 + 4) + 7)
2 * 4 + 8 * 2 + (2 * 2 + 5 + 3 + 4 * 7) + 9
(5 + 3) * 4
(8 + 2 * (8 * 9 + 8 * 4 + 3) * 9 + 8 * 2) + ((5 + 2 * 7 + 8) * 5 * 6) * 3
2 * 3 + ((4 * 7 + 6 + 2) * 5 * 5 * 7 * (2 + 3 * 6 + 6 + 3 * 3)) + (9 * 8)
((4 + 4 + 9 * 7 * 4) * (9 * 4 * 5 * 9 + 2 * 7) * 4 + 2 + 6) + 4 + 5
6 + 8 * 3 * (4 + 5 * 7 * 8 * 4 * 8)
9 * (5 * 4 + 5) * 8 + 4 + 6 * (5 + 3 + 9 + 4 + 7 + 2)
4 + (2 * 3 + 8 * 3 + 7 + 2) + 9 + 6
2 + (6 * 4 * 9 * (6 * 2 * 4 + 4 * 8 + 6) + 6) * 2 + 8 * 5 + 4
8 * 8 + 6 * (4 + 3 + 3 * 9 * 9 + 9) * (4 * 9 * 6 + 2) * 7
((3 * 2 * 4 * 8) + 7 + 7 * 6 + (3 * 4)) * 7 * 2 * 7 * 8
8 + (8 + (2 + 6 * 5) * (9 * 5 * 3 + 8) + 9)
(2 * 5 + 8 * 3) + 9 * 4 * 9 + 5 * 2
3 + 9 * (6 * 6 + 8 * 4 + 9) + 4
(8 * 9) + 4 * 4 + 9 * 3 + (7 * 2 * (3 * 4) * 8 * 8)
5 * 5 * (9 + 8 * 6 + 3) + 4
4 + 9 + (4 * 5 + (6 * 7 * 9 + 9) + 5 * 4) * 7 * 4 * 7
(4 * 2 + (3 + 8) * 6 * 5 + 5) + (9 + 9 + 2 + (2 * 9 * 9 + 9 + 4) + (4 + 6 + 2 + 6)) * 3 + 2
9 + (5 * 5 * (4 + 3)) + 3 * 9 * 5 + ((3 * 5 + 6) * 7 * 2 + 2 * 3)
(2 + 6 * 9 + 8) + 3 + (6 + 9 + 4 + 7 * 8)
6 * 4 * (2 + (4 * 4 + 6 * 9 + 3) + 9 * 9) * 3
(7 * (2 * 8 * 7 + 8 + 2 + 7) * 7 + 3) + 4 + 3 + 5 * ((4 + 9 + 8 + 7 * 9) + (7 * 5 * 3 + 8 * 8 + 5) * 5) + 8
((4 * 5 + 8 * 6) * 5 * 9 + 5) + 8 + 5 * 3
9 * (3 + 2 + (3 + 7) + 7 + (5 + 6 + 6 + 3 + 3)) * 8
3 + (2 * 8) * ((6 + 9 + 8 * 7) * 9 + 7) * 8 * 2 + 7
(3 + 8 * 2 + 5 * 2) + 8 * (4 + 4 + 5 * 7) * (4 * 5) * 9
8 * (6 * (5 + 9 * 3 + 5 + 7) * (5 + 6 * 2 + 3 * 5 + 2) * 2)
(2 + 3 * 7 * (2 + 7 * 7) + (5 + 2 * 3 * 5 + 7 * 7) + (6 * 9 * 3 * 8 + 7)) + 8 + 3 * 3 * 2 + 9
5 + 5 + 3
8 * 6 + 9 + ((9 + 3 + 5 * 3 + 6) + 3 * 6)
7 * (3 + (5 * 8 * 9) + 5 + 7 + 3) * 3 * 9 * 8
5 * (3 * 8 * 8)
8 + 7 * 7 + 5 + (2 + 4) + 8
2 + 9 * 7 * 6 * 9
9 + ((8 * 7 * 5 * 8 + 9) + 2 * (7 * 9 + 8 * 4) * 4)
((9 * 5) + (2 * 3 * 3 + 8 * 4) + (6 + 7 * 4) * 3) + 2
6 * 5 * 5 + 3
7 + 9 * 7 * 4 * (3 + (9 + 9 * 5 * 8) + 5 * 9 * (7 * 8 * 9 + 3 * 9 + 3) * 9)
2 + 6 * 9 + 3 + (7 + 7 + 6 * 3) * 2
(5 * 4 + 6 + 5 * (2 + 3) * (8 + 3)) + (6 + 9 * 9 + 3 + (6 + 6 * 7 * 3 * 4) * 2) * 7 * 4 + 7 + 5
2 * (6 * 2 + 8) * 6
3 + 2 + 3 + ((7 + 3 * 2 + 5) + 4)
5 + ((3 * 2 * 2 + 4) + 5 * 4 + 3) * 7 + 6 + 7 + 6
7 + 8 * (6 * 7 * (4 + 6) + (5 * 8 + 4 * 6) + (4 + 4 + 2 * 5 * 7 + 2) + 3)
9 + ((5 * 5 + 5 + 5 * 6 + 4) * 2 * 9 + (8 * 6 * 3 + 6 * 8) + 8) + 6
2 + 9 + (6 + 9) * 8 * 3 + 4
4 * (5 + 9 + 7) * 9 * (6 * 2 + 2 + 9 * 5 + (6 + 9))
((7 * 6 + 2) + 8 * 5 + 9 + 4 + 4) + 8 * (6 + 7 * 4 * (3 + 5 + 5) + 6 * (6 + 7 + 5 * 4 * 5))
(7 * 5 + 6) + (6 * 6)
5 + (6 * 9 + (9 * 3 * 4 + 2 * 8) + 5 + (3 * 9 + 4 * 9 * 7)) + 9 * 8 * 4
(8 + 8 + 7 * 9) + (8 + 9 + 2) + 4 + 7
8 + (9 * 3 + 7 + 6 * 7)
3 * ((4 * 6 + 6 * 9) + 8) + (5 + 6 * 8 * (5 * 2 + 3 + 8) * 3 + 5) + 7 + (3 + 3 * 2 + (4 * 2))
5 * (2 + (8 * 7) + 2 * 7 * 2) * 3 + 9 + (5 * 5 + 8)
2 + 4 + (8 * 9 + 9 + (5 * 4) + 8) + 5 * 4
3 * 3 * (7 * 4 * 4 + (8 * 9 * 7 + 6) * 3 * (9 + 7 + 6 + 6)) * 9
6 * ((9 * 8 + 9) + 9 * 3 * 5 + (8 + 8 * 2 * 7 * 8 * 4) + 4) + 2 + 2 * 5 * (9 + (2 + 5 * 6 + 7 * 2 + 7) + 5 * 4 + 6 * 3)
(8 * (3 + 5 * 7 + 6 * 8) + 5 + 4) + 5
(5 * 2 + (4 * 5 + 7) + (7 + 5 + 5 + 8)) * 2 * ((5 + 7) + 4 * 4) * (8 + (4 * 5 + 8) + 5 + 9 + 8)
(7 * 8) + 2 + 2 * 4 * 6
((7 * 8) + 5) + (8 * 2 + 5 + 8) + 3 * ((8 + 7 * 9) * 8 + (8 + 9 * 8 + 2 * 9 + 6)) * 6 * (9 * 6 + (4 + 7) + 7 * (8 + 8 + 8 * 3) * 3)
3 * ((2 + 3 + 3 * 5 * 6 + 9) * 2 + 3 * 6) * 9 * ((6 * 8) + 6 + (3 * 6 * 3) + (9 + 5 + 6)) + 2
9 * 3 + 7 * 5 + ((3 * 8 + 4 * 5 * 5) * 5 + 8 * 2 + (2 * 5 * 3 + 5))
(9 + 7 * 6 * 5 + 6) + 6 + 6 * 9 + 5
5 * 5 + 6 * 3 * 8 + (4 + 2 * 3 + 5)
9 + 9 + 6 * (5 + (8 * 9 * 9 + 5 + 8)) * ((9 * 5 * 8 + 8 * 7) * 4 * 9 + (7 + 2 * 5 + 7 * 3)) * (9 + 6)
7 * (7 + (5 * 7 + 9 + 9 * 7 + 2)) + 3 * (7 + (5 + 8 + 5 * 5 * 4) + 8 + 9) * 5 * 7
(8 * 8 * 9 + 5 * 5 * 2) * ((8 + 3 + 6 * 3 + 5 + 4) + (4 + 8 * 4) * 6) + ((2 * 7 * 5 * 5) + 9 * 4 + 3) * (6 + 7 * 9 + 3 + 4) * 4
(2 * 7 * 8 * (7 + 4) + 8 + 7) + 4 * 4 + 7
6 * 6 + (8 + 2 + 7) * 9 * (5 * (2 * 4 * 8 + 3 + 9))
(8 * 7 + 7) * (7 * 6 * 3) + 7
((7 * 5) + 3 + 7 + (3 + 2 * 7 + 9)) + 7 + (4 + (9 * 4))
3 + 7 + 9 + (2 * 6 * 2 * 5 + 2 + 4) * (6 * 7) + 8
6 * 4 * 7 * ((6 * 4 * 6 * 8 * 2) * (2 + 6 * 3 + 8 * 2) + 5 + (5 + 3 + 2 + 5 + 9) * (5 * 4))
8 + 5 + 4 * (8 * 6 + 9 + 7 * (3 + 9 * 9 * 8) + 9) * 4
2 * 6 + 6 * ((8 * 3 * 7 + 7 + 8 + 3) * 9 + 6 * 8 + 5)
(3 * 2 + 5 + 5 + 3 * 9) * 5 * 7 + (9 + (7 + 9 + 4 + 8) * (6 + 8 + 2) + 8) * 7
5 + (8 * 4) + 5 * 2 * (2 + (9 * 2) * 5)
7 + (4 * 4 * 9 + 6) + 9 + 2
((4 * 4 + 5) + 7 + 2 * 8 * 8 * 7) * 8 * (2 + 7 + 8 + 3)
(9 * 4 * 5) + 5
7 * 3 * (4 * 2 + 4) * 9 * (6 + 8 + 9 * (8 * 9 * 8) + 5)
2 * 5 + 6 * ((3 + 8 + 3 * 3 * 6) + 3) * 4
6 * 4 * 8 + 5 + (9 + 2 * (6 + 4 * 4 * 4 + 9)) * 6
(8 + (3 + 3 + 3 * 4) + 8 * 7 + 3) + (7 + 3) + (5 + 3 * 8) * (7 + (3 + 8 + 2 * 7 * 7)) * 3
3 + 4 + 7 + 2
3 + 5
7 * (5 * 9 * 3) + 6 * 3
6 * (3 + (7 + 9 + 7 + 7) * 2 + 8 * 2) + 4 + 9 * 6 + 9
(6 * 8) * 5 + 2 * 6
6 + 3 + 2 + 8
5 + 4 + 7 * 5 + ((2 + 5 * 3 * 8 + 5 + 9) * 3)
3 * 2 + 7 + 2
9 * 6 * 5 + (3 * 6 * (3 * 5 + 4)) * 7 * 7
(9 + 7 * 7 + 9 * 7) + (2 * 2 + 4)
8 * 8 * ((3 + 8 + 5) + (4 * 7 + 9) * 7 * (8 * 7 + 9)) + 3
3 + 9 + 4 + (9 * 6 * (4 * 8 + 3))
((7 * 9 + 3) * (7 + 5 + 9 * 3 + 4)) + 2
8 * (9 + 2) * ((5 + 4 * 7) + (7 + 7 * 5 * 8 + 6) * 8)
(8 + 4 + 3) + 3 + (3 + 2 * 3 + (6 * 6 + 4 + 3 * 3 * 2)) + 4 + 4
3 + 6 + 3 + 2 + 2
8 + (8 * 8 + 5 + 9 * (4 + 5 + 9 * 2) + 6)
6 + 3
2 + 7 * (5 + 2 * 8 + 4 + (3 + 8 * 6 + 6 * 8) * 2) * 9 + (8 + 8 * 3 * 7 + 2 + (4 * 5 * 4 * 2)) * (8 + 7)
8 + (6 * 4 + 7) * 5 + (5 + 9 + (6 * 4 + 9 + 6 + 8) * 5) + 9
8 * (2 * 8 + 4) * (3 * (8 + 6 * 8)) + 4 * 2 * (5 + 4 + (7 * 7 * 6 * 6 * 8 + 4) * 2 * 7)
((7 * 4) + (9 + 6 + 7)) + 3 + 8 * 7 * 4 * 7
6 * 4 + (5 + 2 + (5 * 5 * 2 + 6 + 7) + 7 * 3) + (3 * 2) * 4
6 * 2 * 3 * (3 * (8 * 2 + 5) * (8 * 7 * 2 + 4 * 8) + 8 + (8 * 2) * 2) * 9
5 + 6 * 2 + (2 + 2 + 7 + 8 * 6 * 6) * 3
7 * 2 * 5 * 8 + (2 * 4 + 7 * 3 * 4) + 3
8 + 8 * ((8 + 5 * 2) + 3 + (8 * 8) + 6 + 6 + 6)
(3 + 2 * 2 + 2 + 3) * ((7 + 3) * 8) + 9 * 3 + 2
6 + 4 * (5 * (2 + 3 * 9 + 4 + 4) + 7 * 8 + 2 * 8) * 7 * 9 * 6
7 * (3 * (9 + 9 * 3) + 7 * 8 + 9)
8 + 5 + 4 * ((2 + 6 + 5 + 9 + 9) * 7) + 4 * 5
5 + (3 * 3) * 7 + 7 * 9 * 8
2 + 3 + (4 + 9 * 7 + 8 + 7 * 3) + (3 + 4 * 5 * 6 * 8 + 8) + 6 + ((6 * 4 + 8 * 6) + 5)
2 + (5 + 5 + (3 + 5 * 9 + 5 + 3) * (7 * 5 + 3) + (9 + 6 + 2 * 8 * 8 + 5) + 6) + 2 * 4
(3 + 5) + 4 * ((3 + 4) + 8 + 7) + ((6 + 3 + 6) * 4 * 5 + 3 + 6) * ((3 * 8 + 9) + (5 * 7 + 3) + 3 + 2 + 2)
6 + (9 * (5 * 7 * 6) * (6 * 4 * 7 + 6) + 4 + 8) + 6 * 8
5 + (6 * 4 * 7 + 5 * 6 * (8 + 7 * 5 + 6 * 7 * 8)) * 7
5 + (6 + 4) + (5 * 4)
7 + (7 + 3 + 8 + (6 + 7 + 2 * 4)) * 3 + 2 * 6
6 * (3 * (4 * 7) + 8) * 6 * (2 * 6 * 3)
((6 + 5 + 3) + (7 * 8)) * 3
9 * ((6 + 5 + 5 + 8 + 4) * 5) * (6 * 4 + (8 + 7 * 2 * 3 * 6 + 6)) * 4 * 9 + 2
(3 + (6 + 5 + 7 * 4 * 7 + 5)) * (4 + 4 + 7 + (2 + 3) * 2) + 8 + 6 * 4 + 5
(4 + (4 * 7) + 9 * 5 + 2 * 3) + 7 * ((4 * 9 * 8 + 8 + 9) + 5 * 4 + 3 * 2 * 4)
(7 + 2) * 7 * 7 * 4 * (9 * 6) + 9
9 * 2 * 4 * (2 * 5 * 7)
2 * 7 * (3 * 8 + 4 + 6 * 9 + 5)
((2 + 5) * 5 * 9 * 8 * 8 + 5) + 6 + (5 + (6 + 8 * 8 + 3 * 2 * 7) * 6) * 9 + 2
(3 + 5 * 9 + 7 * 9) + 5 * (9 * 8 * 5 * 3 * 8 + 8) * 2 + 5 * 3
(7 + 6 * 2 + 9 * 9) * 2
4 * 7 + 7 + (5 + 3 + 3 * (4 + 2 * 3 * 6 + 2 + 4) * (5 * 8 * 6 * 4 * 5) + 3) + (5 + 3 * 6) + 5
3 + 7 + 5 + 9 + ((4 * 5 + 2) + 5 + 6 * 9) * 5
7 * (3 + 7 * 9 * 6) * 2 * 4 * (3 * (6 + 3 + 3) * 4 * 9 * 2) + 7
(9 + 6 + 6 * 3 * (8 * 8 * 3)) * 6 * 4 * 7 * 6 * 2
(6 + 3 * 5 * 7) * 3 + 8
4 + (3 + (5 + 7 + 7 + 8 * 6 + 4))
3 * ((4 + 2 * 3 + 9 + 3) * 5 + 8) + 4 * (4 + 4) + 2 + 9
6 + ((3 + 3 + 7 + 9 * 9 * 7) * 5 * 6 + 4 + 5 * 4) * 6 + ((4 + 5) + 6 * 4 + 3 + 7) + (5 + (2 + 3))
2 * ((4 + 6 + 2 + 7 + 7) * 4 + 9)
(5 + 3 + 8) + 6 * 6 * 6
6 + 6 * ((6 + 6) + 8 * 4 + 6 + 3 + 7) + 5 * 6 + 6
5 * 8 + (9 * (5 + 5 * 2 * 9 + 5 * 3) * 2 * 9 + 4) * 2
4 * 5 + 8 * (7 * (5 * 9 * 7 + 4) + 3) + 9 + 7
2 * 8 * (6 * 9 * (4 * 6 * 8 + 5) + 4 * 4 * 8) * 6 * 6 * 8
9 * 7 + 4 + (4 + 3 * 8 * 5) * (4 * 5 * 5 + 7 + 6)
4 * (6 * 3 + 8 + 3 * 5) * 2 + 7 * 5
(4 * 2 + (9 * 3 + 9 + 4 + 2 * 5)) * (7 * 7 * 4 * 7 * 7 * 4) + 3 + 9 * 8 * (9 * 8)
5 * (9 * (7 + 2 + 8 + 5 + 7) * 8) * 7 * (6 * 4 + 4 + 9 + (9 * 9 + 2) + 7) * (3 + 8) * 2
2 * (6 * 7 * 2 + 7) * 5
6 + 9 + 2 * (9 * 2)
((7 * 2 + 8 * 3 * 6) * 5 + 6) * 8
(3 * 6 + 8 * 2 + 3 + 8) * 6 + 7
2 + (9 * 7 + (4 + 9 + 6 * 8 + 6) + 2 + 3 + 4) + 6 * 8 + 4
(8 * 6 * 8 + 4 + 3) * (8 + 4)
(3 + 2 + 5 + (2 + 9 + 2 * 2 * 5 * 9) * 2) * (7 + 5 + 6 * 6 * 9)
7 + 3 + 4 + 7 * (8 + 5 * 2) + 3
(8 * (8 + 2 * 3 * 7 * 7 * 8) + 7) + 5 + ((2 * 7 + 9 * 9) + 5 * (6 * 7 + 2 * 8 * 5) * 7 * 4 + 5) * 2 * (5 + 9 * 7 + 8) + (5 + (8 * 7 * 7 * 7 + 3 * 3) + (5 + 4 * 3 + 4) + 6 * 6)
9 + 4 * (9 + 3 + 3) * (7 + 7 * 4 * 4 + 9 * (3 + 5 * 7)) + 7 * 4
3 * 6 + (4 * 3 * 5 * 8) * (9 * 2 * (2 + 6 + 4))
4 * (8 + (8 + 6) * 4 * 7)
(6 * 6 + 6 + 4) * 8 + 5 * (9 + (8 + 3 + 2 + 5 * 8 + 3)) * (9 + (8 + 9 * 4) + 7) + 5
6 * 3 * 7 * 2 + (6 * 2 + (4 + 4 + 2 + 7 * 8 * 2))
(5 * 6) * (9 + 6 + 3 * 6 * 4 * 3) + (8 * 7 + 5)
4 * 2 + 3 * ((9 * 3 * 8 * 3 * 7 * 2) + 6 * 3 * (9 * 7 * 9 + 6 * 5) * 4 + 7) + 3 + (2 + 9 * 3 * 9 + (7 + 7 * 3 + 4))
((5 * 2) + (6 * 5 * 4) + 9 + 4 * 7 + 7) * 8
2 * 8 + (7 * 2 + 6 + 8)
9 * 4 * 7 * 7 * (2 * (7 * 7 * 8 + 9) + 6 * 5 * (4 + 8 + 5 + 3)) + 8
2 * 8 + 4 + 2 * 2 * (7 + 4 * (4 + 9) + 6 * 4 + 5)
9 + 4 + 3 * (7 * 7 + 9 * 8 * 5 * (3 + 2 * 5 * 6)) + 8
4 * 8 * (6 * (6 + 7 + 9 * 3 * 5)) * 4 * 8 + 3
4 * 7 + (7 + 4 * (6 * 7)) * (7 + 7 + 6 + (2 + 9 + 6 + 5) + 6) * (8 * 2) + 3
(6 + 8 * 8 * 4) * 2 + 2 * 9
8 * (9 * 7 * 5 + (9 + 8 * 4)) * 9 + (9 * 9 * (3 * 8 + 4) * 9)
(7 + 4 + 6 * (5 * 3)) * 5 * 8
""".trimIndent()
} | 0 | Kotlin | 0 | 1 | f5efe2f0b6b09b0e41045dc7fda3a7565cb21db3 | 26,469 | advent-of-code | MIT License |
src/Day04.kt | TinusHeystek | 574,474,118 | false | {"Kotlin": 53071} | class Day04 : Day(4) {
// --- Part 1 ---
private fun getPair(pairString: String): Pair<Set<Int>, Set<Int>> {
val split = pairString.trim().split(',')
val left = split.first().split("-").let { (a, b) -> a.toInt()..b.toInt() }.toSet()
val right = split.last().split("-").let { (a, b) -> a.toInt()..b.toInt() }.toSet()
return Pair(left, right)
}
private fun pairIsFullyContained(pairString: String): Boolean {
val pair = getPair(pairString)
return pair.first.containsAll(pair.second) || pair.second.containsAll(pair.first)
}
override fun part1ToInt(input: String): Int {
var total = 0
val pairs = input.lines()
for (pair in pairs) {
if (pairIsFullyContained(pair))
total++
}
return total
}
// --- Part 2 ---
private fun pairOverlap(pairString: String): Boolean {
val pair = getPair(pairString)
return pair.first.intersect(pair.second).any()
}
override fun part2ToInt(input: String): Int {
var total = 0
val pairs = input.lines()
for (pair in pairs) {
if (pairOverlap(pair))
total++
}
return total
}
}
fun main() {
val day = Day04()
day.printToIntResults(2, 4)
} | 0 | Kotlin | 0 | 0 | 80b9ea6b25869a8267432c3a6f794fcaed2cf28b | 1,322 | aoc-2022-in-kotlin | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/DestinationCity.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
/**
* 1436. Destination City
* @see <a href="https://leetcode.com/problems/destination-city">Source</a>
*/
fun interface DestinationCityStrategy {
operator fun invoke(paths: List<List<String>>): String
}
class DestinationCityStrategyBF : DestinationCityStrategy {
override fun invoke(paths: List<List<String>>): String {
for (element in paths) {
val candidate = element[1]
var good = true
for (path in paths) {
if (path[0] == candidate) {
good = false
break
}
}
if (good) {
return candidate
}
}
return ""
}
}
class DestinationCitySet : DestinationCityStrategy {
override operator fun invoke(paths: List<List<String>>): String {
val set: MutableSet<String?> = HashSet()
for (l in paths) set.add(l[1])
for (l in paths) set.remove(l[0])
return if (set.isEmpty()) "" else set.iterator().next() ?: ""
}
}
class DestinationCityHashMap : DestinationCityStrategy {
override operator fun invoke(paths: List<List<String>>): String {
val map: MutableMap<String?, String?> = HashMap()
for (path in paths) {
map[path[0]] = path[1]
}
for (city in map.values) {
if (!map.containsKey(city)) {
return city ?: ""
}
}
return ""
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,108 | kotlab | Apache License 2.0 |
src/Day01.kt | nic-dgl-204-fall-2022 | 552,818,440 | false | {"Kotlin": 1372} |
fun main() {
fun part1(input: List<String>): Int {
var checkSum = 0
for (values in input) {
val num = values.split(' ')
checkSum += num.maxOf { it.toInt() } - num.minOf { it.toInt() }
}
return checkSum
}
fun part2(input: List<String>): Int {
var checkSum = 0
for (values in input) checkSum += (values.split(' ').maxOf { it.toInt() } - values.split(' ')
.minOf { it.toInt() })
return checkSum
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 1)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 1 | Kotlin | 0 | 0 | 31188f920c36d1f3b4c80f99665557e039e436a8 | 748 | ShakshyamAdventOfCode | Apache License 2.0 |
two_sum/solution.kts | dvsu | 385,288,512 | false | {"JavaScript": 9418, "Python": 7788, "Kotlin": 4001, "Go": 3794} | import java.util.*
class Solution {
fun twoSum(nums: IntArray, target: Int): IntArray {
var numsSorted: IntArray = nums.copyOf()
numsSorted.sort()
var cursorL: Int = 0
var cursorR: Int = numsSorted.size - 1
while(true) {
if (numsSorted[cursorL] + numsSorted[cursorR] > target) {
cursorR -= 1
} else if (numsSorted[cursorL] + numsSorted[cursorR] < target) {
cursorL += 1
} else {
val firstIndex: Int = nums.indexOf(numsSorted[cursorL])
// println(nums, numsSorted, cursorL, cursorR)
if ((numsSorted[cursorL] != numsSorted[cursorR]) || (firstIndex == nums.size - 1)) {
return intArrayOf(firstIndex, nums.indexOf(numsSorted[cursorR]))
} else {
return intArrayOf(firstIndex, nums.indexOfLast {it == numsSorted[cursorR]})
}
}
}
}
}
println(Arrays.toString(Solution().twoSum(intArrayOf(3, 3), 6)))
println(Arrays.toString(Solution().twoSum(intArrayOf(-1, -2, -3, -4, -5), -8)))
println(Arrays.toString(Solution().twoSum(intArrayOf(-10, -1, -18, -19), -19)))
| 0 | JavaScript | 0 | 1 | 6004ad1402c30f6dd850eb1e72986bcedb835008 | 1,213 | leetcode | MIT License |
src/main/kotlin/days/day8/Day8.kt | Stenz123 | 725,707,248 | false | {"Kotlin": 123279, "Shell": 862} | package days.day8
import days.Day
class Day8 : Day() {
override fun partOne(): Any {
val rawInput = readInput()
val input = rawInput[0]
val maps: MutableMap<String, Pair<String, String>> = mutableMapOf()
val newRaw = rawInput.drop(2)
newRaw.forEach {
val key = it.substringBefore(" = ")
val values = it.substringAfter("(").substringBefore(")").split(", ")
maps[key] = Pair(values[0], values[1])
}
var currentNoce = "AAA"
var inputIndex = 0
var count = 0
while (currentNoce != "ZZZ") {
val direction = input[inputIndex]
inputIndex++
if (inputIndex == input.length) {
inputIndex = 0
}
currentNoce = if (direction == 'L') {
maps[currentNoce]!!.first
} else {
maps[currentNoce]!!.second
}
println(currentNoce)
count++
}
return count
}
override fun partTwo(): Any {
val rawInput = readInput()
val input = rawInput[0]
val maps: MutableMap<String, Pair<String, String>> = mutableMapOf()
val newRaw = rawInput.drop(2)
newRaw.forEach {
val key = it.substringBefore(" = ")
val values = it.substringAfter("(").substringBefore(")").split(", ")
maps[key] = Pair(values[0], values[1])
}
var currentNodes:MutableSet<String> = maps.map { it.key }.filter { it.endsWith('A') }.toMutableSet()
var inputIndex = 0
var count = 0
val nodeLength = mutableListOf<Int>()
while (currentNodes.isNotEmpty()) {
val direction = input[inputIndex]
inputIndex++
if (inputIndex == input.length) {
inputIndex = 0
}
val newCurrentNodes = (currentNodes).toMutableSet()
for (node in currentNodes) {
newCurrentNodes.remove(node)
val asdNode =(if (direction == 'L') {
maps[node]!!.first
} else {
maps[node]!!.second
})
if (asdNode .endsWith('Z')) {
nodeLength.add(count+1)
}else {
newCurrentNodes.add(asdNode)
}
}
currentNodes = newCurrentNodes
count++
}
return lcm(nodeLength.map{ it.toLong() }.toLongArray())
}
private fun lcm(a: Long, b: Long): Long {
return a * (b / gcd(a, b))
}
private fun lcm(input: LongArray): Long {
var result = input[0]
for (i in 1 until input.size) result = lcm(result, input[i])
return result
}
private fun gcd(a: Long, b: Long): Long {
var a = a
var b = b
while (b > 0) {
val temp = b
b = a % b // % is remainder
a = temp
}
return a
}
}
| 0 | Kotlin | 1 | 0 | 3de47ec31c5241947d38400d0a4d40c681c197be | 3,040 | advent-of-code_2023 | The Unlicense |
src/main/kotlin/cloud/dqn/leetcode/TwoSumKt.kt | aviuswen | 112,305,062 | false | null | package cloud.dqn.leetcode
/**
*
* Kotlin implementation
* Problem: https://leetcode.com/problems/two-sum/description/
Given an array of integers, return indices of the two
numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution,
and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
*/
class TwoSumKt {
companion object {
val bar = "a"
@JvmStatic fun main(args: Array<String>) {
val arr: IntArray = intArrayOf(2, 0, 7, 11, 15)
var index = 0
val bar = Solution().twoSum(arr, 9)
println("hi")
}
class Solution {
fun twoSumsDoubleLoop(nums: IntArray, target: Int): IntArray {
var i = 0
val res = IntArray(2)
while (i + 1 < nums.size) {
var j = i + 1
while (j < nums.size) {
if (nums[i] + nums[j] == target) {
res[0] = i
res[1] = j
break
}
j++
}
i++
}
return res
}
// 526ms runtime =(
fun twoSumsForLoops(nums: IntArray, target: Int): IntArray {
val differenceToIndex = HashMap<Int, Int>(nums.size * 2)
nums.forEachIndexed { index, value ->
differenceToIndex[target - value] = index
}
nums.forEachIndexed { index, value ->
differenceToIndex[value]?.let { differenceIndex ->
if (differenceIndex != index) {
return intArrayOf(index, differenceIndex)
}
}
}
// leetcode compiler will timeout without return intArrau
// throw Exception("Given parameters outside of specifications")
return intArrayOf(-1, -1)
}
// Attempted optimization for time: 428ms =(
fun twoSum(nums: IntArray, target: Int): IntArray {
val differenceToIndex = HashMap<Int, Int>()
var index = 0
for (value in nums) {
differenceToIndex[target - value] = index++
}
index = 0
for (value in nums) {
differenceToIndex[value]?.let {
if (it != index) {
return intArrayOf(index, it)
}
}
index++
}
return intArrayOf(-1,-1)
}
}
}
} | 0 | Kotlin | 0 | 0 | 23458b98104fa5d32efe811c3d2d4c1578b67f4b | 2,938 | cloud-dqn-leetcode | No Limit Public License |
src/main/kotlin/com/hj/leetcode/kotlin/problem2300/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem2300
/**
* LeetCode page: [2300. Successful Pairs of Spells and Potions](https://leetcode.com/problems/successful-pairs-of-spells-and-potions/);
*/
class Solution {
/* Complexity:
* Time O(NLogM+MLogM) and Space O(M) where N and M are the size of spells and potions;
*/
fun successfulPairs(spells: IntArray, potions: IntArray, success: Long): IntArray {
val sortedPotions = potions.sorted()
return IntArray(spells.size) { index ->
numSuccessfulPairs(spells[index], sortedPotions, success)
}
}
private fun numSuccessfulPairs(spell: Int, sortedPotions: List<Int>, success: Long): Int {
var left = 0
var right = sortedPotions.lastIndex
while (left <= right) {
val mid = (left + right) ushr 1
val midPotion = sortedPotions[mid]
val isSuccess = spell.toLong() * midPotion >= success
if (isSuccess) {
right = mid - 1
} else {
left = mid + 1
}
}
// left is the first index in sortedPotions that forms a successful pair
return sortedPotions.size - left
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 1,208 | hj-leetcode-kotlin | Apache License 2.0 |
EclipseKotlin/Kotlin/src/fun/fizzy/leetcode/easy/LeetCodeEasy.kt | PabloRosas17 | 473,046,141 | false | {"Kotlin": 90579, "Java": 47926, "C++": 19073, "C": 641} | package `fun`.fizzy.leetcode.easy
import java.util.*
/** @desc leet code easy driver is meant for easy questions */
/**
* @suppress all functions in the file will be exposed to the client
* , when a function is used by another function in the implementation
* , the IDE believes that it should be encapsulated
* , but by design I am aware of this, I wish to expose consciously
* , therefore the suppression annotation will be used
*/
@Suppress("MemberVisibilityCanBePrivate")
class LeetCodeEasy {
/**
* @problem determine the number of digits in an integer n
* @analysis O(n) where n is the vale of the input int
*/
fun findDigits(n: Int): Int {
var copy = n
val place = 10
var counter = 0
while (copy != 0){
copy /= place
counter++
}
return counter
}
/**
* @problem find duplicate elements in an array
* @analysis O(n) where n is the size of the int array
*/
fun findDuplicates(a1: IntArray): IntArray {
val set: HashSet<Int> = hashSetOf()
a1.forEach { it-> set.add(it) }
return set.toIntArray()
}
/**
* @problem find duplicate elements in an unordered list of length n using HashSet
* @analysis O(n) where n is the size of the array
*/
fun findDuplicatesHashSet(a: Array<Int>): ArrayList<Int> {
val start = 0
val end = a.size-1
val set: HashSet<Int> = hashSetOf()
val list: ArrayList<Int> = arrayListOf()
for(i in start..end){
if(!set.add(a[i])){
list.add(a[i])
}
}
return list
}
/**
* @problem find duplicate elements in an unordered array of length n using HashMap
* @constraints returns -1 at index 0 if array is empty or there is no duplicates
* @analysis O(n) where n is the size of the array
*/
fun findDuplicatesHashMap(a: Array<Int>): Array<Int?> {
val length = a.size
val map = hashMapOf<Int,Int>()
val array = arrayOfNulls<Int>(length)
var arrayL = 0
val counter = 1
val exists = 1
for(i in 0 until length){
if(map[a[i]] == exists){
array[ arrayL ] = a[i]
arrayL += 1
} else {
map[a[i]] = counter
}
}
if(array.isEmpty()){
array[0] = -1
}
return array
}
/**
* @problem find the longest common prefix string amongst an array of strings
* @define prefix is a group of letters placed before the root of a word
* @analysis .....TODO
* @tag leetcode official problem
*/
fun findPrefix(s: Array<String>): String {
/** todo: findPrefix(...)
** , found each element for each word
** , need to filter the common prefix
** , consider flower,flow,flo
** , flow is common when comparing flower and flow, but not flow and flo
**/
if(s.isEmpty()){ return "" }
if(s.size == 1){ return s[0] }
val first = s[0]
val second = s[1]
var prefix = ""
//"flower","flow","flight"
// it0: e:flower, flow => flo
// it1: e:flow, flight => fl
// it2 e:flight, null => return if comparing null
for(e in s.indices){
val next = if( (e+1) <= s.size-1) e+1 else null
s[e].forEach { i ->
if(next != null){
s[next].forEach { j ->
print("$i $j.")
}
}
}
}
return ""
}
/**
* @problem reverse an integer n
* @analysis O(n) where n is the value of the int
*/
fun findReverse(n: Int): Int {
var copy = n
val place = 10
var reversed = 0
while (copy > 0){
reversed = (reversed*place) + (copy%place)
copy /= place
}
return reversed
}
/**
* @problem find nth largest element in an unordered array
* @analysis O(log n) where chopping the problem in half is log n
*/
fun findNthLargest(a: Array<Int>): Int {
val length = a.size
val half = length/2
val start = 0
val end = length-1
var left = 0
var right = 0
var largest = 0
for(i in start..half){
if(a[i] > left){
left = a[i]
}
}
for(i in half..end){
if(a[i] > right){
right = a[i]
}
}
largest = if(right < left){
left
} else if(right > left){
right
} else {
/* right == left */
a.max()!!
}
return largest
}
/**
* @problem Given an array of integers, determine how many of them contain an even number of digits.
* @analysis O(n) where n is each nth element in the int array
*/
fun findNumbers(num: IntArray): Int {
var counter = 0
num.forEach { if (it.toString().length % 2 == 0) counter++ }
return counter
}
/**
* @problem finds unique elements in two unordered arrays both of length n
* @analysis O(n) where n is each nth element in the array
*/
fun findUniques(a1: Array<Int>, a2: Array<Int>, n: Int) {
val set = HashSet<Int>()
a1.forEach { p -> set.add(p) }
a2.forEach { q -> set.add(q) }
}
/**
* @problems when n is divisible by key then add an element to a list
* @constraints 1 <= n <= math.pow(10,4)
* @analysis O(n) where n is the value of the input n
* @tag leetcode official problem
*/
fun fireFizzBuzz(n: Int): List<String> {
arrayListOf<String>().run {
(1..n).forEach { it ->
if ((it % 5) == 0 && (it % 3) == 0) {
this.add("FizzBuzz")
} else if ((it % 5) == 0) {
this.add("Buzz")
} else if ((it % 3) == 0) {
this.add("Fizz")
} else {
this.add(it.toString())
}
}
return this
}
}
/**
* @problem Given the array candies and the integer extraCandies
* , where candies[ i ] represents the number of candies that the ith kid has.
* For each kid check if there is a way to distribute extraCandies among the
* kids such that he or she can have the greatest number of candies among them.
* Notice that multiple kids can have the greatest number of candies.
* @constraints
* 2 <= candies.length <= 100
* 1 <= candies[ i ] <= 100
* 1 <= extraCandies <= 50
* @analysis O(n) where n is the size of the int array
* @tag leetcode official problem
*/
fun fireKidsWithCandies(candies: IntArray, extraCandies: Int): List<Boolean> {
val bucket = arrayListOf<Boolean>()
var biggest = 0
candies.forEachIndexed { _, n ->
if(biggest < n){
biggest = n
}
}
candies.forEachIndexed { _, e ->
if( (extraCandies + e) >= biggest){
bucket.add(true)
} else {
bucket.add(false)
}
}
return bucket
}
/**
* @problem take up to 5 arguments, regardless of order
* , parses the string, and adds a space between each word
* @param args by System.`in`
* @analysis O(n) where n is the size of temp the input
*/
fun fireSpaceEachWord(args: Array<String>): String {
var result = ""
var temp = ""
var counter = 0
val scanner = Scanner(System.`in`)
while (scanner.hasNext()){
val read = scanner.next()
temp += if(counter == 0){
read
} else {
" $read"
}
if(read.isNotEmpty()){
if(++counter == 5){
break
}
}
}
for(i in temp.indices){
result += if(temp[i].toString() == " "){
"\n"
} else {
temp[i].toString()
}
}
return result
}
/**
* @problem two strings are called anagrams,
* if they contain all the same characters in the same frequencies
* @constraints
* 1 <= a.length, b.length <= (5 * math.pow(10,4))
* a and b consist of lowercase English letters.
* @analysis O(n) where n is the size of a b
* @tag leetcode official problem
* @tag hackerrank official problem
*/
fun isAnagram(a:String,b:String): Boolean{
var result = true
val aL = a.toLowerCase()
val bL = b.toLowerCase()
/* get unique occurrence of each letter in the first string as lower-case */
var aU = ""
for (i in aL.indices) {
if (!aU.contains(aL[i].toString())) {
aU += aL[i]
}
}
/* get unique occurrence of each letter in the second string as lower-case */
var bU = ""
for (j in bL.indices) {
//if b[i] is already in aU skip otherwise add
if (!bU.contains(bL[j].toString())) {
bU += bL[j]
}
}
/* number of unique characters, number of unique entries */
var len = 0
len = if (aU.length > bU.length) {
aU.length
} else if (aU.length < bU.length) {
bU.length
} else {
aU.length * 2 - bU.length
}
/* table with unique characters */
val lT = CharArray(len)
if (aU.length > bU.length) {
for (k in 0 until len) {
lT[k] = aU[k]
}
} else if (aU.length < bU.length) {
for (k in 0 until len) {
lT[k] = bU[k]
}
} else {
for (k in 0 until len) {
lT[k] = aU[k]
}
}
/* table for frequency for second string */
val bF = IntArray(len)
for (element in bL) {
for (n in lT.indices) {
if (element == lT[n]) {
bF[n]++
}
}
}
/* table for frequency for first string */
val aF = IntArray(len)
for (element in aL) {
for (n in lT.indices) {
if (element == lT[n]) {
aF[n]++
}
}
}
/* compare frequencies */
for (o in 0 until len) {
if (aF[o] != bF[o]) {
result = false
}
}
return result
}
/**
* @problem checks if a character is a character
* @constraints c >= 0x20 && c <= 0x7e
* @analysis O(1) comparison
*/
fun isChar(c: Char): Boolean {
if(c.toInt() in 0x20..0x7e){
return true
}
return false
}
/**
* @problem checks if a character is a number
* @constraints c >= 0x30 && c <= 0x39
* @analysis O(1) comparison
*/
fun isDigit(c: Char): Boolean {
if(c.toInt() in 0x30..0x39){
return true
}
return false
}
/**
* @problem determine if an argument is a number between S and E, inclusively
* @param args by System.`in`
* @analysis O(1) input
*/
fun isInRange(args: Array<String>, S: Int, E: Int): Boolean {
val scanner = Scanner(System.`in`)
val read = scanner.nextInt()
return read in S..E
}
/**
* @problem check if an integer n is a palindrome
* @analysis O(n) where n is the value of the int
* @tag leetcode official problem
*/
fun isPalindrome(n: Int): Boolean {
if(n < 0){ return false }
if(n in 0..9){ return true }
val reversed = this.findReverse(n)
return reversed == n
}
/**
* @problem check if a phrase as a string is a palindrome
* , if after converting all uppercase letters into lowercase letters
* , and removing all non-alphanumeric characters
* , it reads the same forward and backward, then it is a palindrome.
* Alphanumeric characters include letters and numbers.
* return true if it is, return false if it is not
* @constraints 1 >= s.length <= (2*Math.pow(10,5))
* s consists of only printable ascii characters, 0x20 <= s as a character <= 0x7E
* @analysis O(log n) where splitting the problem in half is log n
* @tag leetcode official problem
* @fun removes alphanumeric, val regex = Regex("[^A-Za-z0-9]").apply{this.replace(s,"")}
*/
fun isPalindrome(s: String): Boolean {
//check in range
s.forEach { i-> if(i.toInt() < 32 || i.toInt() > 126){ return false } }
//strip and lowercase
val regex = Regex("[^A-Za-z0-9]")
val p = regex.replace(s,"")
val q = p.toLowerCase()
//algorithm
val half = q.length/2
val start = 0
val end = q.length
for(i in start until half){
if(q[i] != q[end-i-1]){
return false
}
}
return true
}
/**
* @problem Given an integer array nums, return true if any value appears at least twice in the array
* , and return false if every element is distinct.
* @constraints 1 <= nums.length <= (math.pow(10,4))
* (math.pow(-10,9)) <= nums[ index ] <= (math.pow(+10,9))
* @analysis O(n) where n is the number of elements in the array
* @tag leetcode official problem
*/
fun hasDuplicates(nums: IntArray): Boolean {
return hashSetOf<Int>().apply{ for(element in nums){ this.add(element) } }.size != nums.size
}
/**
* @problem given n1 integer and n2 integer represented as strings, return their sum as a string
* @constraints 1 <= n1.length, n2.length <= (math.pow(10,4))
* @analysis O(n) where n is the nth iteration of the loops as the number of elements in each stack
* @tag leetcode official problem
*/
fun mathAddStrings(n1: String, n2: String): String {
val a: Stack<Int> = Stack<Int>().apply { n1.forEach { e -> this.push(mathStrToInt("0$e")) } }
val b: Stack<Int> = Stack<Int>().apply { n2.forEach { e -> this.push(mathStrToInt("0$e")) } }
return mathPlusInts(a, b,"")
}
/**
* @problem recursively add integers a and b contained in strings n and m inside stacks p and q
* @constraints do not use and built-in functions to handle string to int or int to string
* , furthermore handle big integers where characters of n and m, 0 <= n and m<= 24
* @analysis .....TODO
*/
fun mathPlusInts(a: Stack<Int>, b: Stack<Int>, sum: String): String {
if(a.isEmpty() && b.isEmpty()) return sum.ifBlank { "0" }
val p = if(!a.isEmpty()) a.pop() else 0
val q = if(!b.isEmpty()) b.pop() else 0
val c = if(sum.isNotEmpty() && sum.length >= 2) mathStrToInt(sum[0].toString()) else 0
val o = if(c+p+q >= 10) c+p+q else 0
/**
** todo: overflow failing in mathPlusInts(...)
** , 111+0 failing, after this is resolved
** , and tested
** , then add left + right
** , n/2 divide and conquer
**/
val z = if(sum.length>=2) sum.substring(1) else if (sum.length==1) sum.substring(0) else ""
val v = mathIntToStr(o)+z
if(!a.isEmpty() && !b.isEmpty()) return mathPlusInts(a,b,v)
if(!a.isEmpty() && b.isEmpty()) return mathPlusInts(a,b,v)
if(a.isEmpty() && !b.isEmpty()) return mathPlusInts(a,b,v)
print("$v _")
return v
}
/**
* @problem given n string as an integer return its value as a string
* @constraint n is not a negative
* @analysis O(n) where n is the nth iteration as size of the int
*/
fun mathIntToStr(n: Int): String {
if(n == 0){ return ""+0 }
val ascii: Char = '0'
var number: Int = n
val factor = 10
var result: String = ""
val token: String = ""
val builder = StringBuilder()
val front = 0
while (number != 0){
val temp = number % factor
result = token+(ascii + number % factor)
builder.insert(front,result)
number /= factor
}
return token+builder
}
/**
* @problem given n integer as a string return its value as an integer
* @constraint n is not a negative
* @analysis O(n) where n is the length of the number as a string
*/
fun mathStrToInt(n: String): Int {
val ascii: Char = '0'
val number: String = n
val factor = 10
var index: Int = 0
var result: Int = 0
var token: Char = '*'
while (index < number.length){
result *= factor
token = number[index]
result += (token - ascii)
index++
}
return result
}
/**
* @problem divides two numbers of type long and returns a double
* @constraint b is not 0
* @analysis O(1) division
*/
fun mathDivTwoLongs(a : Long, b : Long) : Double {
return a.toDouble()/b.toDouble()
}
/**
* @problem Given an array of integers, return indices of the two numbers
* such that they add up to a specific target.
* @assumption Assume that each input would have exactly one solution
* , and you may not use the same element twice.
* @analysis O(n^2) where ith loop is n * jth loop is m=n, compare with indices
* @improved O(n) where depth of loop is n, compare with pointers
* @tag leetcode official problem
*/
fun mathTwoSum(numbers: IntArray, target: Int): IntArray {
val bucket = arrayListOf<Int>()
val reset = 0
var p = 0
var q = numbers.size-1
while (p < q){
if(numbers[p]+numbers[q]==target){
bucket.add(p)
bucket.add(q)
return bucket.toIntArray()
}
else {
p++
if (p == q) {
p = reset
q--
}
}
}
return bucket.toIntArray()
}
/**
* @problem convert a string of roman symbols to integer values
* @constraints symbol=value, I=1, V=5, X=10, L=50, C=100, D=500, M=1000
* range of S: s >= 1 && s <= 3999
* length of S: 1 <= s.length <= 15
* subtraction
* I can be placed before V (5) and X (10) to make 4 and 9.
* X can be placed before L (50) and C (100) to make 40 and 90.
* C can be placed before D (500) and M (1000) to make 400 and 900.
* @analysis O(n) where n is the length of the string
* @tag leetcode official problem
*/
fun mathRomanToInt(s: String): Int {
var sub: Int = 0
var sum: Int = 0
val length = s.length-1
val patterns = mapOf<String,Int>(Pair("IV",4),Pair("IX",9),Pair("XL",40),Pair("XC",90),Pair("CD",400),Pair("CM",900))
var i: Int = 0
while( i <= length){
val next = if( (i+1) <= length) i+1 else i
val p = s.slice( i..next)
if( patterns.containsKey(p) ) {
sub -= patterns.getValue(p)
i+=2
} else {
val q = s.slice(i downTo i)
sum += mathRomanValue(q.first())
i++
}
}
return sum-sub
}
/**
* @problem convert a character to a roman value
* @analysis O(1) assignment
*/
fun mathRomanValue(s: Char): Int {
return when (s) {
'I' -> 1
'V' -> 5
'X' -> 10
'L' -> 50
'C' -> 100
'D' -> 500
'M' -> 1000
else -> -1
}
}
/**
* @problem find the transpose of a matrix
* @constraints n rows, m cols
* @analysis O(n^2) where iterating ith times iterating jth times is n^2
*/
fun mathMatrixTranspose(rows: Int, cols: Int, r: Array<IntArray>) {
val ret: Array<IntArray> = Array(3) { IntArray(3) }
for(i in 0 until rows){
for(j in 0 until cols){
ret[i][j] = r[j][i]
}
}
val t1 = printMatrix(r)
val t2 = printMatrix(ret)
println("Here is the original matrix.\n$t1\nHere is the transposed matrix.\n$t2")
}
/**
* @problem print a matrix,
* @constraints n rows, m cols
* @analysis O(n^2) where iterating ith times iterating jth times is n^2
*/
fun printMatrix(a: Array<IntArray>): String {
var temp = ""
a.forEachIndexed { i, ints ->
ints.forEachIndexed { j, e ->
temp += " [$i][$j]: $e"
}
}
return temp
}
/**
* @problem in increasing order , prints the max value for each integer type
* @analysis O(1) print
*/
fun printMaxIntegerTypes() {
println(Byte.MAX_VALUE)
println(Short.MAX_VALUE)
println(Integer.MAX_VALUE)
println(Long.MAX_VALUE)
}
/**
* @problem reverses a string where the input string is given as a raw string type.
* @analysis O(n) when iterating the string of length n
* @improvement O(log n) where dividing in half is log n
*/
fun reverseString(string: String): String {
var temp = ""
val length = string.length-1
val len = (length/2)-1
val half = length/2
val start = 0
val end = string.length
for (i in start..len){
temp += string[end-1-i]
}
for (i in half until end){
temp += string[end-1-i]
}
return temp
}
/**
* @problem reverses a string where the input string is given as an array of character type.
* @constraints achieve this by O(1) extra memory
* 1 <= s.length <= (Math.pow(10,5)), s[ index ] is a printable ascii character
* @analysis O(log n) where cutting the problem in half is log n
*/
fun reverseString(array: CharArray): Unit {
var temp = ""
val length = array.size-1
val len = (length/2)-1
val half = length/2
val begin = 0
val end = array.size
var a = 0
var b = 0
var finish = array.size-1
val copy = array.copyOf()
//swap second half with first half
for (i in begin..len){
array[finish-i]=copy[a++]
}
//swap first half with second half
for (i in half until end){
array[b++] = copy[finish--]
}
}
/**
* @problem parses and reverse a string, then cast it to a number
* @analysis O(n) where n is the length of the input string
*/
fun reverseNumbers(): Int {
var result = ""
val scanner = Scanner(System.`in`)
val read = scanner.nextInt()
val temp = read.toString()
var end = temp.length-1
for(i in temp.indices){
result += temp[end--]
}
return result.toInt()
}
/**
* @problem remove duplicates in-place from an array n, so that each element appears only once
* , n is sorted in non-decreasing order, elements in n should be kept in the same relative order
* @constraint perform the modification in O(1) space complexity, without allocating more memory
* 0 <= n.length <= (3 * math.pow(10,4))
* -100 <= n[ i ] <= 100
* @analysis O(n) where n is the size of the array
* @tag leetcode official problem
*/
fun removeDuplicates(n: IntArray): Int {
if(n.isEmpty()){ return 0 }
val key: Int = -101
var o: Boolean = false
var p: Int = 0
var q: Int = 0
while (p < n.size){
if(!o){
q = n[p]
o = true
} else {
if (n[p] == q){
n[p] = key
} else {
q = n[p]
}
}
p++
}
var h: Boolean = false
var i: Int = 0
var j: Int = 0
var l: Int = 0
while (i < n.size){
if(!h){
if(n[i] == key) {
j = i
h = true
}
} else {
if(n[i] != key) {
val temp = n[j]
n[j] = n[i]
n[i] = temp
j++
}
}
i++
}
var m: Int = 0
var r: Int = 0
while (m < n.size){
if(n[m] == key){ break }
r++
m++
}
return r
}
/**
* @problem swap two elements n and m in string s
* @analysis O(1) array access array assign
* @note strings in kotlin are immutable, why?
* think, object, safety, memory, others exist
*/
fun swap(s: String, n: Int, m: Int): String {
val a = s.toCharArray()
val temp = a[m]
a[m] = a[n]
a[n] = temp
return a.toString()
}
} | 0 | Kotlin | 0 | 0 | 76476151a8788dd01c8d3c667a5a876d3ebd9812 | 25,465 | Algorithms | Apache License 2.0 |
src/Day01.kt | yalematta | 572,668,122 | false | {"Kotlin": 8442} | fun main() {
fun part1(input: List<String>): Int {
val elves = mutableListOf(0)
input.forEach { line ->
if (line.isBlank()) elves.add(0)
else elves[elves.lastIndex] += line.toIntOrNull() ?: 0
}
return elves.max()
}
fun part2(input: List<String>): Int {
val elves = mutableListOf(0)
input.forEach { line ->
if (line.isBlank()) elves.add(0)
else elves[elves.lastIndex] += line.toIntOrNull() ?: 0
}
return elves.sortedDescending().subList(0, 3).sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 2b43681cc2bd02e4838b7ad1ba04ff73c0422a73 | 825 | advent-of-code-2022 | Apache License 2.0 |
app/src/test/java/com/kotaku/camerax2leetcode/ExampleUnitTest.kt | Espresso521 | 642,651,388 | false | null | package com.kotaku.camerax2leetcode
import org.junit.Assert.*
import org.junit.Test
import java.util.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun leetcode1431() {
/**
There are n kids with candies. You are given an integer array candies,
where each candies[i] represents the number of candies the ith kid has,
and an integer extraCandies, denoting the number of extra candies that you have.
Return a boolean array result of length n, where result[i] is true if,
after giving the ith kid all the extraCandies, they will have the greatest number of candies among all the kids,
or false otherwise.
Note that multiple kids can have the greatest number of candies.
Input: candies = [2,3,5,1,3], extraCandies = 3
Output: [true,true,true,false,true]
Explanation: If you give all extraCandies to:
- Kid 1, they will have 2 + 3 = 5 candies, which is the greatest among the kids.
- Kid 2, they will have 3 + 3 = 6 candies, which is the greatest among the kids.
- Kid 3, they will have 5 + 3 = 8 candies, which is the greatest among the kids.
- Kid 4, they will have 1 + 3 = 4 candies, which is not the greatest among the kids.
- Kid 5, they will have 3 + 3 = 6 candies, which is the greatest among the kids.
*/
fun kidsWithCandies(candies: IntArray, extraCandies: Int): List<Boolean> {
val ret = MutableList(candies.size) { false }
val max = candies.max()
println("candies.size is ${candies.size}, extraCandies is $extraCandies, max is $max")
for (i in candies.indices) {
if (candies[i] + extraCandies >= max) {
ret[i] = true
}
}
return ret
}
val ret = kidsWithCandies(intArrayOf(2, 3, 5, 1, 3), 3)
ret.forEachIndexed { i, v ->
println("ret[$i] = $v")
}
}
@Test
fun leetcode605() {
/**
You have a long flowerbed in which some of the plots are planted, and some are not.
However, flowers cannot be planted in adjacent plots.
Given an integer array flowerbed containing 0's and 1's, where 0 means empty and 1 means not empty,
and an integer n, return true if n new flowers can be planted in the flowerbed without violating the no-adjacent-flowers rule and false otherwise.
Example 1:
Input: flowerbed = [1,0,0,0,1], n = 1
Output: true
Example 2:
Input: flowerbed = [1,0,0,0,1], n = 2
Output: false
*/
fun canPlaceFlowers(flowerbed: IntArray, n: Int): Boolean {
if (flowerbed.size == 1) {
return if (n > 1) false
else if (n == 1) return flowerbed[0] == 0
else return true
}
var can = 0
for (i in flowerbed.indices) {
if (flowerbed[i] == 1) continue
val leftEmpty = if (i == 0) true else flowerbed[i - 1] == 0
val rightEmpty = if (i == flowerbed.size - 1) true else flowerbed[i + 1] == 0
if (leftEmpty && rightEmpty) {
flowerbed[i] = 1
can++
}
}
return can >= n
}
val ret = canPlaceFlowers(intArrayOf(1, 0, 0, 0, 1), 2)
println("ret is $ret")
}
@Test
fun leetcode345() {
/**
Given a string s, reverse only all the vowels in the string and return it.
The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in both lower and upper cases, more than once.
Example 1:
Input: s = "hello"
Output: "holle"
Example 2:
Input: s = "leetcode"
Output: "leotcede"
*/
fun reverseVowels(s: String): String {
val vowels = listOf('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U')
val chars = s.toCharArray()
var left = 0
var right = chars.size - 1
while (left < right) {
if (chars[left] in vowels && chars[right] in vowels) {
val temp = chars[left]
chars[left] = chars[right]
chars[right] = temp
left++
right--
} else if (chars[left] in vowels) {
right--
} else {
left++
}
}
return String(chars)
}
val ret = reverseVowels("leetcode")
println("ret is $ret")
}
@Test
fun leetcode151() {
/**
Given an input string s, reverse the order of the words.
A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space.
Return a string of the words in reverse order concatenated by a single space.
Note that s may contain leading or trailing spaces or multiple spaces between two words.
The returned string should only have a single space separating the words. Do not include any extra spaces.
Example 1:
Input: s = "the sky is blue"
Output: "blue is sky the"
Example 2:
Input: s = " hello world "
Output: "world hello"
Explanation: Your reversed string should not contain leading or trailing spaces.
Example 3:
Input: s = "a good example"
Output: "example good a"
Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.
**/
fun reverseWords(s: String): String {
//return s.trim().split(" ").reversed().filter { it.trim().isNotEmpty() }.joinToString(separator = " ")
val wordsArray = s.trim().split(" ").reversed()
wordsArray.forEach {
println("words is $it ;")
}
return wordsArray.filter { it.trim().isNotEmpty() }.joinToString(separator = " ")
}
val ret = reverseWords("a good example")
println("ret is $ret")
}
@Test
fun leetcode334() {
/**
Given an integer array nums, return true if there exists a triple of indices (i, j, k)
such that i < j < k and nums[i] < nums[j] < nums[k]. If no such indices exists, return false.
Example 1:
Input: nums = [1,2,3,4,5]
Output: true
Explanation: Any triplet where i < j < k is valid.
Example 2:
Input: nums = [5,4,3,2,1]
Output: false
Explanation: No triplet exists.
Example 3:
Input: nums = [2,1,5,0,4,6]
Output: true
Explanation: The triplet (3, 4, 5) is valid because nums[3] == 0 < nums[4] == 4 < nums[5] == 6.
*/
fun increasingTriplet(nums: IntArray): Boolean {
var small = Int.MAX_VALUE
var big = Int.MAX_VALUE
for (num in nums) {
if (num <= small) {
small = num
} else if (num <= big) {
big = num
} else {
return true
}
println("small is $small ; big is $big ")
}
return false
}
val ret = increasingTriplet(intArrayOf(2, 1, 5, 0, 4, 6))
println("ret is $ret")
}
@Test
fun leetcode443() {
/**
Given an array of characters chars, compress it using the following algorithm:
Begin with an empty string s. For each group of consecutive repeating characters in chars:
If the group's length is 1, append the character to s.
Otherwise, append the character followed by the group's length.
The compressed string s should not be returned separately, but instead, be stored in the input character array chars.
Note that group lengths that are 10 or longer will be split into multiple characters in chars.
After you are done modifying the input array, return the new length of the array.
You must write an algorithm that uses only constant extra space.
Example 1:
Input: chars = ["a","a","b","b","c","c","c"]
Output: Return 6, and the first 6 characters of the input array should be: ["a","2","b","2","c","3"]
Explanation: The groups are "aa", "bb", and "ccc". This compresses to "a2b2c3".
*/
fun compress(chars: CharArray): Int {
var writeIndex = 0
var readIndex = 0
while (readIndex < chars.size) {
val currentChar = chars[readIndex]
var count = 0
while (readIndex < chars.size && chars[readIndex] == currentChar) {
readIndex++
count++
}
chars[writeIndex] = currentChar
writeIndex++
if (count > 1) {
val countChars = count.toString().toCharArray()
for (i in countChars.indices) {
chars[writeIndex] = countChars[i]
writeIndex++
}
}
}
printCharArray(chars)
return writeIndex
}
val ret =
compress(charArrayOf('a', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b'))
println("ret is $ret")
}
@Test
fun leetcode283() {
/**
Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements.
Note that you must do this in-place without making a copy of the array.
Example 1:
Input: nums = [0,1,0,3,12]
Output: [1,3,12,0,0]
Example 2:
Input: nums = [0]
Output: [0]
*/
fun moveZeroes(nums: IntArray): IntArray {
if (nums.size == 1) {
return nums
}
var left = 0
var right = 0
while (left < nums.size && nums[left] != 0) {
left++
right++
}
while (right < nums.size) {
if (nums[right] == 0) {
right++
} else {
nums[left++] = nums[right]
nums[right++] = 0
}
}
return nums
}
val ret = moveZeroes(intArrayOf(0, 1, 0, 3, 12))
printIntArray(ret)
}
@Test
fun leetcode392() {
/***
Given two strings s and t, return true if s is a subsequence of t, or false otherwise.
A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of
the characters without disturbing the relative positions of the remaining characters.
(i.e., "ace" is a subsequence of "abcde" while "aec" is not).
Example 1:
Input: s = "abc", t = "ahbgdc"
Output: true
Example 2:
Input: s = "axc", t = "ahbgdc"
Output: false
*/
fun isSubsequence(s: String, t: String): Boolean {
var i = 0
var j = 0
while (i < s.length && j < t.length) {
if (s[i] == t[j]) {
i++
}
j++
}
return i == s.length
}
val ret = isSubsequence("abc", "ahbgdc")
println("ret is $ret")
}
@Test
fun leetcode11() {
/**
You are given an integer array height of length n.
There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]).
Find two lines that together with the x-axis form a container, such that the container contains the most water.
Return the maximum amount of water a container can store.
Example 1:
Input: height = [1,8,6,2,5,4,8,3,7]
Output: 49
Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7].
In this case, the max area of water (blue section) the container can contain is 49.
*/
fun maxArea(height: IntArray): Int {
var left = 0
var right = height.size - 1
var maxArea = 0
while (left <= right) {
val area = height[left].coerceAtMost(height[right]) * (right - left)
if (height[right] > height[left]) {
left++
} else {
right--
}
maxArea = maxArea.coerceAtLeast(area)
}
return maxArea
}
val ret = maxArea(intArrayOf(1, 8, 6, 2, 5, 4, 8, 3, 7))
println("ret is $ret")
}
@Test
fun leetcode1679() {
/**
You are given an integer array nums and an integer k.
In one operation, you can pick two numbers from the array whose sum equals k and remove them from the array.
Return the maximum number of operations you can perform on the array.
Example 1:
Input: nums = [1,2,3,4], k = 5
Output: 2
Explanation: Starting with nums = [1,2,3,4]:
- Remove numbers 1 and 4, then nums = [2,3]
- Remove numbers 2 and 3, then nums = []
There are no more pairs that sum up to 5, hence a total of 2 operations.
Example 2:
Input: nums = [3,1,3,4,3], k = 6
Output: 1
Explanation: Starting with nums = [3,1,3,4,3]:
- Remove the first two 3's, then nums = [1,4,3]
There are no more pairs that sum up to 6, hence a total of 1 operation.
*/
fun maxOperations(nums: IntArray, k: Int): Int {
nums.sort()
var left = 0
var right = nums.size - 1
var ret = 0
while (left < right) {
if (nums[left] + nums[right] == k) {
ret++
left++
right--
} else if (nums[left] + nums[right] < k) {
left++
} else if (nums[left] + nums[right] > k) {
right--
}
}
return ret
}
val ret = maxOperations(intArrayOf(1, 2, 3, 4), 5)
println("ret is $ret")
}
@Test
fun leetcode643() {
/***
You are given an integer array nums consisting of n elements, and an integer k.
Find a contiguous subarray whose length is equal to k that has the maximum average value and return this value.
Any answer with a calculation error less than 10-5 will be accepted.
Example 1:
Input: nums = [1,12,-5,-6,50,3], k = 4
Output: 12.75000
Explanation: Maximum average is (12 - 5 - 6 + 50) / 4 = 51 / 4 = 12.75
Example 2:
Input: nums = [5], k = 1
Output: 5.00000
*/
fun findMaxAverage(nums: IntArray, k: Int): Double {
var sum = 0
for (i in 0 until k) {
sum += nums[i]
}
var maxSum = sum
for (i in k until nums.size) {
sum += nums[i] - nums[i - k]
maxSum = maxOf(maxSum, sum)
}
return maxSum.toDouble() / k.toDouble()
}
val ret = findMaxAverage(intArrayOf(1, 12, -5, -6, 50, 3), 4)
println("ret is $ret")
}
@Test
fun leetcode1456() {
/**
Given a string s and an integer k, return the maximum number of vowel letters in any substring of s with length k.
Vowel letters in English are 'a', 'e', 'i', 'o', and 'u'.
Example 1:
Input: s = "abciiidef", k = 3
Output: 3
Explanation: The substring "iii" contains 3 vowel letters.
Example 2:
Input: s = "aeiou", k = 2
Output: 2
Explanation: Any substring of length 2 contains 2 vowels.
Example 3:
Input: s = "leetcode", k = 3
Output: 2
Explanation: "lee", "eet" and "ode" contain 2 vowels.*/
fun maxVowels(s: String, k: Int): Int {
var sum = 0
val charList = charArrayOf('a', 'e', 'i', 'o', 'u')
for (i in 0 until k) {
if (charList.contains(s[i])) sum += 1
}
var maxSum = sum
for (i in k until s.length) {
if (charList.contains(s[i])) sum += 1
if (charList.contains(s[i - k])) sum -= 1
maxSum = maxOf(maxSum, sum)
}
return maxSum
}
val ret = maxVowels("abciiidef", 3)
println("ret is $ret")
}
@Test
fun leetcode1004() {
/**
Given a binary array nums and an integer k, return the maximum number of consecutive 1's in the array
if you can flip at most k 0's.
Example 1:
Input: nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2
Output: 6
Explanation: [1,1,1,0,0,1,1,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Example 2:
Input: nums = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], k = 3
Output: 10
Explanation: [0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
* */
fun longestOnes(nums: IntArray, k: Int): Int {
var maxCount = 0
var left = 0
var zerosCount = 0
for (right in nums.indices) {
if (nums[right] == 0) {
zerosCount++
}
while (zerosCount > k) {
if (nums[left] == 0) {
zerosCount--
}
left++
}
maxCount = maxCount.coerceAtLeast(right - left + 1)
println("right is $right, left is $left, zerosCount is $zerosCount, maxCount is $maxCount")
}
return maxCount
}
val ret = longestOnes(intArrayOf(1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0), 2)
println("ret is $ret")
}
@Test
fun leetcode1493() {
/***
Given a binary array nums, you should delete one element from it.
Return the size of the longest non-empty subarray containing only 1's in the resulting array.
Return 0 if there is no such subarray.
Example 1:
Input: nums = [1,1,0,1]
Output: 3
Explanation: After deleting the number in position 2, [1,1,1] contains 3 numbers with value of 1's.
Example 2:
Input: nums = [0,1,1,1,0,1,1,0,1]
Output: 5
Explanation: After deleting the number in position 4, [0,1,1,1,1,1,0,1] longest subarray with value of 1's is [1,1,1,1,1].
Example 3:
Input: nums = [1,1,1]
Output: 2
Explanation: You must delete one element.
*/
fun longestSubarray(nums: IntArray): Int {
var maxLength = 0
var countZeros = 0
var left = 0
for (right in nums.indices) {
if (nums[right] == 0) {
countZeros++
}
while (countZeros > 1) {
if (nums[left] == 0) {
countZeros--
}
left++
}
maxLength = maxOf(maxLength, right - left)
}
return maxLength
}
val ret = longestSubarray(intArrayOf(0, 1, 1, 1, 0, 1, 1, 0, 1))
println("ret is $ret")
}
@Test
fun leetcode1732() {
/**
There is a biker going on a road trip. The road trip consists of n + 1 points at different altitudes.
The biker starts his trip on point 0 with altitude equal 0.
You are given an integer array gain of length n where gain[i] is the net gain in altitude
between points i and i + 1 for all (0 <= i < n). Return the highest altitude of a point.
Example 1:
Input: gain = [-5,1,5,0,-7]
Output: 1
Explanation: The altitudes are [0,-5,-4,1,1,-6]. The highest is 1.
Example 2:
Input: gain = [-4,-3,-2,-1,4,3,2]
Output: 0
Explanation: The altitudes are [0,-4,-7,-9,-10,-6,-3,-1]. The highest is 0.
*/
fun largestAltitude(gain: IntArray): Int {
var prix = 0
var max = 0
gain.forEach {
val current = prix + it
max = max.coerceAtLeast(current)
prix = current
}
return max
}
var ret = largestAltitude(intArrayOf(-5, 1, 5, 0, -7))
println("ret is $ret")
ret = largestAltitude(intArrayOf(-4, -3, -2, -1, 4, 3, 2))
println("ret is $ret")
}
@Test
fun leetcode2215() {
/**
Given two 0-indexed integer arrays nums1 and nums2, return a list answer of size 2 where:
answer[0] is a list of all distinct integers in nums1 which are not present in nums2.
answer[1] is a list of all distinct integers in nums2 which are not present in nums1.
Note that the integers in the lists may be returned in any order.
Example 1:
Input: nums1 = [1,2,3], nums2 = [2,4,6]
Output: [[1,3],[4,6]]
Example 2:
Input: nums1 = [1,2,3,3], nums2 = [1,1,2,2]
Output: [[3],[]]
*/
fun arrayDiff(array1: IntArray, array2: IntArray): List<Int> {
val set1 = array1.toSet()
val set2 = array2.toSet()
val difference = set1.subtract(set2)
return difference.toList()
}
fun findDifference(nums1: IntArray, nums2: IntArray): List<List<Int>> {
return listOf(arrayDiff(nums1, nums2), arrayDiff(nums2, nums1))
}
val ret = findDifference(intArrayOf(1, 2, 3, 3), intArrayOf(1, 1, 2, 2))
ret.forEachIndexed { i1, array ->
array.forEachIndexed { i2, v ->
println("Int[$i1][$i2] = $v")
}
}
}
@Test
fun leetcode1207() {
/**
Given an array of integers arr, return true if the number of occurrences of each value in the array is unique or false otherwise.
Example 1:
Input: arr = [1,2,2,1,1,3]
Output: true
Explanation: The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences.
Example 2:
Input: arr = [1,2]
Output: false
Example 3:
Input: arr = [-3,0,1,-3,1,1,1,-3,10,0]
Output: true
*/
fun uniqueOccurrences(arr: IntArray): Boolean {
var ret = true
val set1 = arr.toSet()
val minLength = (1..set1.size).sum()
if (arr.size >= minLength) {
val mutableSet = mutableSetOf<Int>()
set1.forEach {
println("key = $it")
val arrCount = arr.count { v ->
v == it
}
if (mutableSet.contains(arrCount)) {
ret = false
return@forEach
} else {
mutableSet.add(arrCount)
}
}
} else {
ret = false
}
return ret
}
var ret = uniqueOccurrences(intArrayOf(-3, 0, 1, -3, 1, 1, 1, -3, 10, 0))
println("Boolean = $ret")
ret = uniqueOccurrences(intArrayOf(1, 2, 2, 1, 1, 3))
println("Boolean = $ret")
ret = uniqueOccurrences(
intArrayOf(
26,
2,
16,
16,
5,
5,
26,
2,
5,
20,
20,
5,
2,
20,
2,
2,
20,
2,
16,
20,
16,
17,
16,
2,
16,
20,
26,
16
)
)
println("Boolean = $ret")
}
@Test
fun leetcode1657() {
/***
Two strings are considered close if you can attain one from the other using the following operations:
Operation 1: Swap any two existing characters.
For example, abcde -> aecdb
Operation 2: Transform every occurrence of one existing character into another existing character, and do the same with the other character.
For example, aacabb -> bbcbaa (all a's turn into b's, and all b's turn into a's)
You can use the operations on either string as many times as necessary.
Given two strings, word1 and word2, return true if word1 and word2 are close, and false otherwise.
Example 1:
Input: word1 = "abc", word2 = "bca"
Output: true
Explanation: You can attain word2 from word1 in 2 operations.
Apply Operation 1: "abc" -> "acb"
Apply Operation 1: "acb" -> "bca"
Example 2:
Input: word1 = "a", word2 = "aa"
Output: false
Explanation: It is impossible to attain word2 from word1, or vice versa, in any number of operations.
Example 3:
Input: word1 = "cabbba", word2 = "abbccc"
Output: true
Explanation: You can attain word2 from word1 in 3 operations.
Apply Operation 1: "cabbba" -> "caabbb"
Apply Operation 2: "caabbb" -> "baaccc"
Apply Operation 2: "baaccc" -> "abbccc"
*/
fun closeStrings(word1: String, word2: String): Boolean {
if (word1.length != word2.length) {
return false
}
val freq1 = IntArray(26)
val freq2 = IntArray(26)
val set1 = mutableSetOf<Char>()
val set2 = mutableSetOf<Char>()
for (i in word1.indices) {
freq1[word1[i] - 'a']++
freq2[word2[i] - 'a']++
set1.add(word1[i])
set2.add(word2[i])
}
freq1.sort()
freq2.sort()
return freq1.contentEquals(freq2) && set1 == set2
}
val ret = closeStrings("cabbba", "abbccc")
println("Boolean = $ret")
}
@Test
fun leetcode2352() {
/**
Given a 0-indexed n x n integer matrix grid, return the number of pairs (ri, cj) such that row ri and column cj are equal.
A row and column pair is considered equal if they contain the same elements in the same order (i.e., an equal array).
Example 1:
Input: grid = [[3,2,1],[1,7,6],[2,7,7]]
Output: 1
Explanation: There is 1 equal row and column pair:
- (Row 2, Column 1): [2,7,7]
Example 2:
Input: grid = [[3,1,2,2],[1,4,4,5],[2,4,2,2],[2,4,2,2]]
Output: 3
Explanation: There are 3 equal row and column pairs:
- (Row 0, Column 0): [3,1,2,2]
- (Row 2, Column 2): [2,4,2,2]
- (Row 3, Column 2): [2,4,2,2]
*/
fun equalPairs(grid: Array<IntArray>): Int {
var ret = 0
val rowStrings = mutableListOf<String>()
val columnStrings = mutableListOf<String>()
grid.forEachIndexed { i, array ->
rowStrings.add(i, array.joinToString(separator = "-") + "-")
}
for (i in grid.indices) {
var colum = ""
grid.forEach {
colum = colum + it[i] + "-"
}
columnStrings.add(i, colum)
}
printStringArray(rowStrings)
printStringArray(columnStrings)
rowStrings.forEach { row ->
columnStrings.forEach { column ->
if(row == column) ret++
}
}
return ret
}
// [[3,1,2,2],[1,4,4,5],[2,4,2,2],[2,4,2,2]]
var ret = equalPairs(
arrayOf(
intArrayOf(3, 1, 2, 2),
intArrayOf(1, 4, 4, 5),
intArrayOf(2, 4, 2, 2),
intArrayOf(2, 4, 2, 2)
)
)
println("ret = $ret")
ret = equalPairs(
arrayOf(
intArrayOf(11,1),
intArrayOf(1, 11)
)
)
println("ret = $ret")
}
@Test
fun leetcode2390() {
fun removeStars(s: String): String {
/**
You are given a string s, which contains stars *.
In one operation, you can:
Choose a star in s.
Remove the closest non-star character to its left, as well as remove the star itself.
Return the string after all stars have been removed.
Note:
The input will be generated such that the operation is always possible.
It can be shown that the resulting string will always be unique.
Example 1:
Input: s = "leet**cod*e"
Output: "lecoe"
Example 2:
Input: s = "erase*****"
Output: ""
Explanation: The entire string is removed, so we return an empty string.
*/
val stack = Stack<Char>()
// 将字符串中的字符依次入栈
for (char in s) {
if(char != '*') stack.push(char)
else stack.pop()
}
return stack.joinToString("")
}
val ret = removeStars("erase*****")
println("ret is $ret")
}
@Test
fun leetcode735() {
/**
We are given an array asteroids of integers representing asteroids in a row.
For each asteroid, the absolute value represents its size, and the sign represents its direction
(positive meaning right, negative meaning left). Each asteroid moves at the same speed.
Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode.
If both are the same size, both will explode. Two asteroids moving in the same direction will never meet.
Example 1:
Input: asteroids = [5,10,-5]
Output: [5,10]
Explanation: The 10 and -5 collide resulting in 10. The 5 and 10 never collide.
Example 2:
Input: asteroids = [8,-8]
Output: []
Explanation: The 8 and -8 collide exploding each other.
Example 3:
Input: asteroids = [10,2,-5]
Output: [10]
Explanation: The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10.
*/
fun asteroidCollision(asteroids: IntArray): IntArray {
val stack = Stack<Int>()
for (asteroid in asteroids) {
if (asteroid > 0) {
stack.push(asteroid)
} else {
while (!stack.isEmpty() && stack.peek() > 0 && stack.peek() < Math.abs(asteroid)) {
stack.pop()
}
if (stack.isEmpty() || stack.peek() < 0) {
stack.push(asteroid)
} else if (stack.peek() == Math.abs(asteroid)) {
stack.pop()
}
}
}
return stack.toIntArray()
}
printIntArray(asteroidCollision(intArrayOf(5,10,-5)))
printIntArray(asteroidCollision(intArrayOf(8,-8)))
printIntArray(asteroidCollision(intArrayOf(10,2,-5)))
}
@Test
fun leetcode394() {
/**
Given an encoded string, return its decoded string.
The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being
repeated exactly k times. Note that k is guaranteed to be a positive integer.
You may assume that the input string is always valid; there are no extra white spaces,
square brackets are well-formed, etc. Furthermore, you may assume that the original data does not contain
any digits and that digits are only for those repeat numbers, k. For example, there will not be input like 3a or 2[4].
The test cases are generated so that the length of the output will never exceed 105.
Example 1:
Input: s = "3[a]2[bc]"
Output: "aaabcbc"
Example 2:
Input: s = "3[a2[c]]"
Output: "accaccacc"
Example 3:
Input: s = "2[abc]3[cd]ef"
Output: "abcabccdcdcdef"
*/
fun decodeString(s: String): String {
val stack = Stack<String>()
var currentNumber = 0
var currentString = ""
for (char in s) {
when {
char.isDigit() -> {
currentNumber = currentNumber * 10 + (char - '0')
}
char == '[' -> {
stack.push(currentString)
stack.push(currentNumber.toString())
currentNumber = 0
currentString = ""
}
char == ']' -> {
val number = stack.pop().toInt()
val previousString = stack.pop()
currentString = previousString + currentString.repeat(number)
}
else -> {
currentString += char
}
}
}
return currentString
}
println("ret is ${decodeString("3[a]2[bc]")}") //"aaabcbc"
println("ret is ${decodeString("3[a2[c]]")}") //"accaccacc"
println("ret is ${decodeString("2[abc]3[cd]ef")}") //"abcabccdcdcdef"
println("ret is ${decodeString("100[leetcode]")}") //"abcabccdcdcdef"
}
@Test
fun leetcode328() {
/**
Given the head of a singly linked list, group all the nodes with odd indices together
followed by the nodes with even indices, and return the reordered list.
The first node is considered odd, and the second node is even, and so on.
Note that the relative order inside both the even and odd groups should remain as it was in the input.
Example 1:
Input: head = [1,2,3,4,5]
Output: [1,3,5,2,4]
Example 2:
Input: head = [2,1,3,5,6,4,7]
Output: [2,3,6,7,1,5,4]
*/
fun oddEvenList(head: ListNode?): ListNode? {
if (head == null) {
return null
}
var odd = head
var even = head.next
val evenHead = even
while (even?.next != null) {
odd?.next = even.next
odd = odd?.next
even.next = odd?.next
even = even.next
}
odd?.next = evenHead
return head
}
}
@Test
fun leetcode2130() {
/**
In a linked list of size n, where n is even, the ith node (0-indexed) of the linked list is known as
the twin of the (n-1-i)th node, if 0 <= i <= (n / 2) - 1.
For example, if n = 4, then node 0 is the twin of node 3, and node 1 is the twin of node 2.
These are the only nodes with twins for n = 4.
The twin sum is defined as the sum of a node and its twin.
Given the head of a linked list with even length, return the maximum twin sum of the linked list.
Example 1:
Input: head = [5,4,2,1]
Output: 6
Example 2:
Input: head = [4,2,2,3]
Output: 7
Example 3:
Input: head = [1,100000]
Output: 100001
*/
fun pairSum(head: ListNode?): Int {
val deque = ArrayDeque<Int>()
var max = 0
var curr = head
while(curr != null) {
deque.add(curr.`val`)
curr = curr?.next
}
while(deque.isNotEmpty()) {
val sum = deque.removeFirst() + deque.removeLast()
if (sum > max) max = sum
}
return max
}
}
@Test
fun leetcode104() {
/**
Given the root of a binary tree, return its maximum depth.
A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: 3
Example 2:
Input: root = [1,null,2]
Output: 2
*/
val tree3 = TreeNode(3)
val tree9 = TreeNode(9)
val tree20 = TreeNode(20)
val tree15 = TreeNode(15)
val tree7 = TreeNode(7)
tree3.left = tree9
tree3.right = tree20
tree20.left = tree15
tree20.right = tree7
fun maxDepth(root: TreeNode?): Int {
if (root == null) {
return 0
}
val leftDepth = maxDepth(root.left)
val rightDepth = maxDepth(root.right)
return 1 + maxOf(leftDepth, rightDepth)
}
println("ret is ${maxDepth(tree3)}") //3
assertEquals(maxDepth(tree3), 3)
}
@Test
fun leetcode872() {
/**
Consider all the leaves of a binary tree, from left to right order, the values of those leaves form a leaf value sequence.
For example, in the given tree above, the leaf value sequence is (6, 7, 4, 9, 8).
Two binary trees are considered leaf-similar if their leaf value sequence is the same.
Return true if and only if the two given trees with head nodes root1 and root2 are leaf-similar.
Example 1:
Input: root1 = [3,5,1,6,2,9,8,null,null,7,4], root2 = [3,5,1,6,7,4,2,null,null,null,null,null,null,9,8]
Output: true
Example 2:
Input: root1 = [1,2,3], root2 = [1,3,2]
Output: false
*/
fun getLeaves(root: TreeNode?, leaves: MutableList<Int>) {
if (root == null) {
return
}
if (root.left == null && root.right == null) {
leaves.add(root.`val`)
}
getLeaves(root.left, leaves)
getLeaves(root.right, leaves)
}
fun leafSimilar(root1: TreeNode?, root2: TreeNode?): Boolean {
val leaves1 = mutableListOf<Int>()
val leaves2 = mutableListOf<Int>()
getLeaves(root1, leaves1)
getLeaves(root2, leaves2)
return leaves1 == leaves2
}
println("ret is ${leafSimilar(buildTree(arrayOf(3,5,1,6,2,9,8,null,null,7,4)),
buildTree(arrayOf(3,5,1,6,7,4,2,null,null,null,null,null,null,9,8)))}") //true
assertEquals(leafSimilar(buildTree(arrayOf(3,5,1,6,2,9,8,null,null,7,4)),
buildTree(arrayOf(3,5,1,6,7,4,2,null,null,null,null,null,null,9,8))), true)
println("ret is ${leafSimilar(buildTree(arrayOf(1,2,3)),
buildTree(arrayOf(1,3,2)))}") //false
assertEquals(leafSimilar(buildTree(arrayOf(1,2,3)),
buildTree(arrayOf(1,3,2))),false)
}
@Test
fun leetcode1448() {
/**
Given a binary tree root, a node X in the tree is named good if in the path from root to X there are no nodes with
a value greater than X.
Return the number of good nodes in the binary tree.
Example 1:
Input: root = [3,1,4,3,null,1,5]
Output: 4
Explanation: Nodes in blue are good.
Root Node (3) is always a good node.
Node 4 -> (3,4) is the maximum value in the path starting from the root.
Node 5 -> (3,4,5) is the maximum value in the path
Node 3 -> (3,1,3) is the maximum value in the path.
Example 2:
Input: root = [3,3,null,4,2]
Output: 3
Explanation: Node 2 -> (3, 3, 2) is not good, because "3" is higher than it.
Example 3:
Input: root = [1]
Output: 1
Explanation: Root is considered as good.
*/
fun countGoodNodes(node: TreeNode?, maxValue: Int): Int {
if (node == null) {
return 0
}
var count = 0
if (node.`val` >= maxValue) {
count++
}
val updatedMaxValue = maxOf(maxValue, node.`val`)
count += countGoodNodes(node.left, updatedMaxValue)
count += countGoodNodes(node.right, updatedMaxValue)
return count
}
fun goodNodes(root: TreeNode?): Int {
return countGoodNodes(root, Int.MIN_VALUE)
}
println("ret is ${goodNodes(buildTree(arrayOf(3,1,4,3,null,1,5)))}") // 4
assertEquals(goodNodes(buildTree(arrayOf(3,1,4,3,null,1,5))),4)
println("ret is ${goodNodes(buildTree(arrayOf(3,3,null,4,2)))}") // 3
assertEquals(goodNodes(buildTree(arrayOf(3,3,null,4,2))),3)
println("ret is ${goodNodes(buildTree(arrayOf(1)))}") // 1
assertEquals(goodNodes(buildTree(arrayOf(1))),1)
}
@Test
fun leetcode437() {
/**
Given the root of a binary tree and an integer targetSum, return the number of paths where the sum of the values along the path equals targetSum.
The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes).
Example 1:
Input: root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8
Output: 3
Explanation: The paths that sum to 8 are shown.
Example 2:
Input: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
Output: 3
*/
fun countPathSum(node: TreeNode?, targetSum: Int): Int {
if (node == null) {
return 0
}
var count = 0
// 检查以当前节点为起点的路径和是否等于目标和
if (node.`val` == targetSum) {
count++
}
// 递归搜索左子树和右子树
count += countPathSum(node.left, targetSum - node.`val`) + countPathSum(node.right, targetSum - node.`val`)
return count
}
fun pathSum(root: TreeNode?, targetSum: Int): Int {
if (root == null) {
return 0
}
// 从根节点开始的路径和数量 + 左子树中的路径和数量 + 右子树中的路径和数量
val pathCount = countPathSum(root, targetSum) + pathSum(root.left, targetSum) + pathSum(root.right, targetSum)
return pathCount
}
println("ret is ${pathSum(buildTree(arrayOf(10,5,-3,3,2,null,11,3,-2,null,1)), 8)}") // 3
assertEquals(pathSum(buildTree(arrayOf(10,5,-3,3,2,null,11,3,-2,null,1)), 8),3)
println("ret is ${pathSum(buildTree(arrayOf(5,4,8,11,null,13,4,7,2,null,null,5,1)), 22)}") // 3
assertEquals(pathSum(buildTree(arrayOf(5,4,8,11,null,13,4,7,2,null,null,5,1)), 22),3)
// bellow test failed, tree item value is greater than int.max. See leetcode437_solution2
//println("ret is ${pathSum(buildTree(arrayOf(1000000000,1000000000,null,294967296,null,1000000000,null,1000000000,null,1000000000)), 0)}") // 0
//assertEquals(pathSum(buildTree(arrayOf(1000000000,1000000000,null,294967296,null,1000000000,null,1000000000,null,1000000000)), 0),0)
}
@Test
fun leetcode437_solution2() {
fun pathSumFromRoot(root: TreeNode?, targetSum: Long): Int {
if (root == null) return 0
val match = if (targetSum == root.`val`.toLong()) 1 else 0
return pathSumFromRoot(root.left, targetSum - root.`val`) + pathSumFromRoot(root.right, targetSum - root.`val`) + match
}
fun pathSum(root: TreeNode?, targetSum: Int): Int {
if(root == null) return 0
return pathSumFromRoot(root, targetSum.toLong()) + pathSum(root.left, targetSum) + pathSum(root.right, targetSum)
}
println("ret is ${pathSum(buildTree(arrayOf(10,5,-3,3,2,null,11,3,-2,null,1)), 8)}") // 3
assertEquals(pathSum(buildTree(arrayOf(10,5,-3,3,2,null,11,3,-2,null,1)), 8), 3)
println("ret is ${pathSum(buildTree(arrayOf(5,4,8,11,null,13,4,7,2,null,null,5,1)), 22)}") // 3
assertEquals(pathSum(buildTree(arrayOf(5,4,8,11,null,13,4,7,2,null,null,5,1)), 22), 3)
println("ret is ${pathSum(buildTree(arrayOf(1000000000,1000000000,null,294967296,null,1000000000,null,1000000000,null,1000000000)), 0)}") // 0
assertEquals(pathSum(buildTree(arrayOf(1000000000,1000000000,null,294967296,null,1000000000,null,1000000000,null,1000000000)), 0),0)
}
@Test
fun leetcode1372() {
/**
You are given the root of a binary tree.
A ZigZag path for a binary tree is defined as follow:
Choose any node in the binary tree and a direction (right or left).
If the current direction is right, move to the right child of the current node; otherwise, move to the left child.
Change the direction from right to left or from left to right.
Repeat the second and third steps until you can't move in the tree.
Zigzag length is defined as the number of nodes visited - 1. (A single node has a length of 0).
Return the longest ZigZag path contained in that tree.
Example 1:
Input: root = [1,null,1,1,1,null,null,1,1,null,1,null,null,null,1]
Output: 3
Example 2:
Input: root = [1,1,1,null,1,null,null,1,1,null,1]
Output: 4
Example 3:
Input: root = [1]
Output: 0
*/
fun dfs(root: TreeNode?, l: Int, r: Int): Int {
if (root == null) return maxOf(l,r)-1
return maxOf(dfs(root.left, r+1, 0), dfs(root.right, 0, l+1))
}
fun longestZigZag(root: TreeNode?): Int = dfs(root, 0, 0)
val tree1 = buildTree(arrayOf(1,null,1,1,1,null,null,1,1,null,1,null,null,null,1))
println("ret is ${longestZigZag(tree1)}") // 3
assertEquals(longestZigZag(tree1), 3)
println("ret is ${longestZigZag(buildTree(arrayOf(1,1,1,null,1,null,null,1,1,null,1)))}") // 4
assertEquals(longestZigZag(buildTree(arrayOf(1,1,1,null,1,null,null,1,1,null,1))), 4)
}
@Test
fun leetcode236() {
/**
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node
in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”
Example 1:
Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
Output: 3
Explanation: The LCA of nodes 5 and 1 is 3.
Example 2:
Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
Output: 5
Explanation: The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.
Example 3:
Input: root = [1,2], p = 1, q = 2
Output: 1
*/
fun lowestCommonAncestor(root: TreeNode?, p: TreeNode?, q: TreeNode?): TreeNode? {
// 如果根节点为空或者等于目标节点之一,则返回根节点
if (root == null || root == p || root == q) {
return root
}
// 在左子树中寻找目标节点
val left = lowestCommonAncestor(root.left, p, q)
// 在右子树中寻找目标节点
val right = lowestCommonAncestor(root.right, p, q)
// 如果左子树和右子树都找到了目标节点,则当前节点为最低共同祖先
if (left != null && right != null) {
return root
}
// 如果只有左子树找到了目标节点,则返回左子树的结果
return left ?: right
}
}
@Test
fun leetcode199() {
fun rightSideView(root: TreeNode?): List<Int> {
val rightmostValues = mutableListOf<Int>()
if(root == null) return rightmostValues
val queue: Queue<TreeNode> = LinkedList()
queue.offer(root)
while (queue.isNotEmpty()) {
val levelSize = queue.size
var rightmostNode: TreeNode? = null
repeat(levelSize) {
val node = queue.poll()
rightmostNode = node
node.left?.let { queue.offer(it) }
node.right?.let { queue.offer(it) }
}
rightmostNode?.let { rightmostValues.add(it.`val`) }
}
return rightmostValues
}
var tree = buildTree(arrayOf(1,2,3,null,5,null,4))
var ret = rightSideView(tree)
assertEquals(listOf(1, 3, 4).toList(), ret)
tree = buildTree(arrayOf(1,2))
ret = rightSideView(tree)
assertEquals(listOf(1, 2).toList(), ret)
tree = buildTree(arrayOf(1,2,3,4))
ret = rightSideView(tree)
assertEquals(listOf(1,3,4).toList(), ret)
}
@Test
fun leetcode1161() {
fun maxLevelSum(root: TreeNode?): Int {
if (root == null) return 0
var maxIndex = 0
var maxValue = Int.MIN_VALUE
var levelNodes = mutableListOf<TreeNode>()
levelNodes.add(root)
var index = 1
while (levelNodes.isNotEmpty()) {
val levelQueue = LinkedList(levelNodes)
val sum = levelNodes.map {it.`val`}.sum()
if (sum > maxValue) {
maxValue = sum
maxIndex = index
}
index += 1
levelNodes = mutableListOf()
while (levelQueue.isNotEmpty()) {
val cur = levelQueue.poll()
cur.left?.let { levelNodes.add(it) }
cur.right?.let { levelNodes.add(it) }
}
}
return maxIndex
}
var tree = buildTree(arrayOf(1,7,0,7,-8,null,null))
var ret = maxLevelSum(tree)
assertEquals(2, ret)
tree = buildTree(arrayOf(989,null,10250,98693,-89388,null,null,null,-32127))
ret = maxLevelSum(tree)
assertEquals(2, ret)
}
@Test
fun leetcode700() {
fun searchBST(root: TreeNode?, `val`: Int): TreeNode? {
var c = root
while(c != null) {
if(c.`val` == `val`) return c
else {
if(c.`val` > `val`) c = c.left
else c = c.right
}
}
return c
}
var ret = searchBST(buildTree(arrayOf(4,2,7,1,3)), 2)
println("ret val is ${ret?.`val`}")
assertEquals(2, ret?.`val`)
ret = searchBST(buildTree(arrayOf(4,2,7,1,3)), 5)
println("ret val is ${ret?.`val`}")
assertEquals(null, ret?.`val`)
}
@Test
fun leetcode450() {
fun findSuccessorValue(node: TreeNode?): Int {
var current = node
while (current?.left != null) {
current = current.left
}
return current!!.`val`
}
fun deleteNode(root: TreeNode?, key: Int): TreeNode? {
if (root == null) {
return null
}
if (key < root.`val`) {
root.left = deleteNode(root.left, key)
} else if (key > root.`val`) {
root.right = deleteNode(root.right, key)
} else {
if (root.left == null) {
return root.right
} else if (root.right == null) {
return root.left
}
val successorValue = findSuccessorValue(root.right)
root.`val` = successorValue
root.right = deleteNode(root.right, successorValue)
}
return root
}
val ret = deleteNode(buildTree(arrayOf(5,3,6,2,4,null,7)), 3)
printTree(ret)
}
@Test
fun leetcode841() {
/**
There are n rooms labeled from 0 to n - 1 and all the rooms are locked except for room 0.
Your goal is to visit all the rooms. However, you cannot enter a locked room without having its key.
When you visit a room, you may find a set of distinct keys in it. Each key has a number on it, denoting which room it unlocks,
and you can take all of them with you to unlock the other rooms.
Given an array rooms where rooms[i] is the set of keys that you can obtain if you visited room i,
return true if you can visit all the rooms, or false otherwise.
Example 1:
Input: rooms = [[1],[2],[3],[]]
Output: true
Explanation:
We visit room 0 and pick up key 1.
We then visit room 1 and pick up key 2.
We then visit room 2 and pick up key 3.
We then visit room 3.
Since we were able to visit every room, we return true.
Example 2:
Input: rooms = [[1,3],[3,0,1],[2],[0]]
Output: false
Explanation: We can not enter room number 2 since the only key that unlocks it is in that room.
*/
fun canVisitAllRooms(rooms: List<List<Int>>): Boolean {
val visited = BooleanArray(rooms.size) // 用于记录房间的访问状态
visited[0] = true // 将第一个房间标记为已访问
val queue: Queue<Int> = LinkedList<Int>() // 使用队列来进行广度优先搜索
queue.offer(0) // 将第一个房间加入队列
while (queue.isNotEmpty()) {
val currRoom = queue.poll()
for (key in rooms[currRoom]) {
if (!visited[key]) {
visited[key] = true
queue.offer(key)
}
}
}
// 检查是否所有房间都被访问过
for (roomVisited in visited) {
if (!roomVisited) {
return false
}
}
return true
}
// [[1],[2],[3],[]]
assertEquals(true, canVisitAllRooms(
listOf(
listOf(1),
listOf(2),
listOf(3),
listOf()
)))
// [[1,3],[3,0,1],[2],[0]]
assertEquals(false, canVisitAllRooms(
listOf(
listOf(1,3),
listOf(3,0,1),
listOf(2),
listOf(0)
)))
}
@Test
fun leetcode1466() {
/**
There are n cities numbered from 0 to n - 1 and n - 1 roads such that there is only one way to
travel between two different cities (this network form a tree). Last year,
The ministry of transport decided to orient the roads in one direction because they are too narrow.
Roads are represented by connections where connections[i] = [ai, bi] represents a road from city ai to city bi.
This year, there will be a big event in the capital (city 0), and many people want to travel to this city.
Your task consists of reorienting some roads such that each city can visit the city 0. Return the minimum number of edges changed.
It's guaranteed that each city can reach city 0 after reorder.
Example 1:
Input: n = 6, connections = [[0,1],[1,3],[2,3],[4,0],[4,5]]
Output: 3
Explanation: Change the direction of edges show in red such that each node can reach the node 0 (capital).
Example 2:
Input: n = 5, connections = [[1,0],[1,2],[3,2],[3,4]]
Output: 2
Explanation: Change the direction of edges show in red such that each node can reach the node 0 (capital).
Example 3:
Input: n = 3, connections = [[1,0],[2,0]]
Output: 0
*/
fun dfs(graph: Array<MutableList<Pair<Int, Int>>>, visited: BooleanArray, node: Int): Int {
var count = 0 // 记录需要改变方向的连接数
visited[node] = true
for (next in graph[node]) {
val neighbor = next.first
val direction = next.second
if (!visited[neighbor]) {
count += dfs(graph, visited, neighbor) + direction
}
}
return count
}
fun minReorder(n: Int, connections: Array<IntArray>): Int {
val graph = Array(n) { mutableListOf<Pair<Int, Int>>() } // 创建邻接表
for (conn in connections) {
val from = conn[0]
val to = conn[1]
graph[from].add(to to 1) // 正向连接
graph[to].add(from to 0) // 反向连接
}
val visited = BooleanArray(n) // 记录节点是否已访问
return dfs(graph, visited, 0) // 从节点 0 开始进行深度优先搜索
}
//Input: n = 6, connections = [[0,1],[1,3],[2,3],[4,0],[4,5]]
//Output: 3
assertEquals(3, minReorder(6,
arrayOf(
intArrayOf(0,1),
intArrayOf(1,3),
intArrayOf(2,3),
intArrayOf(4,0),
intArrayOf(4,5),
)
))
//Input: n = 5, connections = [[1,0],[1,2],[3,2],[3,4]]
//Output: 2
assertEquals(2, minReorder(5,
arrayOf(
intArrayOf(1,0),
intArrayOf(1,2),
intArrayOf(3,2),
intArrayOf(3,4),
)
))
//Input: n = 3, connections = [[1,0],[2,0]]
//Output: 0
assertEquals(0, minReorder(3,
arrayOf(
intArrayOf(1,0),
intArrayOf(2,0),
)
))
}
@Test
fun leetcode1926() {
/**
You are given an m x n matrix maze (0-indexed) with empty cells (represented as '.') and walls (represented as '+').
You are also given the entrance of the maze, where entrance = [entrancerow, entrancecol] denotes the row and column of the cell you are initially standing at.
In one step, you can move one cell up, down, left, or right. You cannot step into a cell with a wall,
and you cannot step outside the maze. Your goal is to find the nearest exit from the entrance.
An exit is defined as an empty cell that is at the border of the maze. The entrance does not count as an exit.
Return the number of steps in the shortest path from the entrance to the nearest exit, or -1 if no such path exists.
Example 1:
Input: maze = [["+","+",".","+"],[".",".",".","+"],["+","+","+","."]], entrance = [1,2]
Output: 1
Explanation: There are 3 exits in this maze at [1,0], [0,2], and [2,3].
Initially, you are at the entrance cell [1,2].
- You can reach [1,0] by moving 2 steps left.
- You can reach [0,2] by moving 1 step up.
It is impossible to reach [2,3] from the entrance.
Thus, the nearest exit is [0,2], which is 1 step away.
Example 2:
Input: maze = [["+","+","+"],[".",".","."],["+","+","+"]], entrance = [1,0]
Output: 2
Explanation: There is 1 exit in this maze at [1,2].
[1,0] does not count as an exit since it is the entrance cell.
Initially, you are at the entrance cell [1,0].
- You can reach [1,2] by moving 2 steps right.
Thus, the nearest exit is [1,2], which is 2 steps away.
*/
fun nearestExit(maze: Array<CharArray>, entrance: IntArray): Int {
val directions = arrayOf(intArrayOf(1, 0), intArrayOf(-1, 0), intArrayOf(0, 1), intArrayOf(0, -1))
val rows = maze.size
val cols = maze[0].size
val queue = LinkedList<IntArray>()
queue.offer(entrance)
maze[entrance[0]][entrance[1]] = '+'
var steps = 0
while (queue.isNotEmpty()) {
val size = queue.size
for (i in 0 until size) {
val curr = queue.poll()
val row = curr[0]
val col = curr[1]
if ((row == 0 || row == rows - 1 || col == 0 || col == cols - 1) && curr != entrance) {
return steps
}
for (dir in directions) {
val newRow = row + dir[0]
val newCol = col + dir[1]
if (newRow >= 0 && newRow < rows && newCol >= 0 && newCol < cols && maze[newRow][newCol] == '.') {
maze[newRow][newCol] = '+'
queue.offer(intArrayOf(newRow, newCol))
}
}
}
steps++
}
return -1
}
//Input: maze = [["+","+",".","+"],[".",".",".","+"],["+","+","+","."]], entrance = [1,2]
//Output: 1
assertEquals(1, nearestExit(arrayOf(charArrayOf('+','+','.','+')
,charArrayOf('.','.','.','+')
,charArrayOf('+','+','+','.'))
,intArrayOf(1,2)))
//Input: [["+","+","+"],[".",".","."],["+","+","+"]], entrance = [1,0]
//Output: 2
assertEquals(2, nearestExit(arrayOf(charArrayOf('+','+','+')
,charArrayOf('.','.','.')
,charArrayOf('+','+','+'))
,intArrayOf(1,2)))
}
@Test
fun leetcode215() {
/**
Given an integer array nums and an integer k, return the kth largest element in the array.
Note that it is the kth largest element in the sorted order, not the kth distinct element.
You must solve it in O(n) time complexity.
Example 1:
Input: nums = [3,2,1,5,6,4], k = 2
Output: 5
Example 2:
Input: nums = [3,2,3,1,2,4,5,5,6], k = 4
Output: 4
*/
fun findKthLargest(nums: IntArray, k: Int): Int? {
val pq = PriorityQueue<Int>()
for (num in nums) {
pq.offer(num)
if (pq.size > k) {
pq.poll()
}
}
return pq.peek()
}
// Input: nums = [3,2,1,5,6,4], k = 2
// Output: 5
assertEquals(5, findKthLargest(intArrayOf(3,2,1,5,6,4), 2))
// Input: nums = [3,2,3,1,2,4,5,5,6], k = 4
// Output: 4
assertEquals(4, findKthLargest(intArrayOf(3,2,3,1,2,4,5,5,6), 4))
}
@Test
fun leetcode2542() {
/**
You are given two 0-indexed integer arrays nums1 and nums2 of equal length n and a positive integer k.
You must choose a subsequence of indices from nums1 of length k.
For chosen indices i0, i1, ..., ik - 1, your score is defined as:
The sum of the selected elements from nums1 multiplied with the minimum of the selected elements from nums2.
It can defined simply as: (nums1[i0] + nums1[i1] +...+ nums1[ik - 1]) * min(nums2[i0] , nums2[i1], ... ,nums2[ik - 1]).
Return the maximum possible score.
A subsequence of indices of an array is a set that can be derived from the set {0, 1, ..., n-1} by deleting some or no elements.
Example 1:
Input: nums1 = [1,3,3,2], nums2 = [2,1,3,4], k = 3
Output: 12
Explanation:
The four possible subsequence scores are:
- We choose the indices 0, 1, and 2 with score = (1+3+3) * min(2,1,3) = 7.
- We choose the indices 0, 1, and 3 with score = (1+3+2) * min(2,1,4) = 6.
- We choose the indices 0, 2, and 3 with score = (1+3+2) * min(2,3,4) = 12.
- We choose the indices 1, 2, and 3 with score = (3+3+2) * min(1,3,4) = 8.
Therefore, we return the max score, which is 12.
Example 2:
Input: nums1 = [4,2,3,1,1], nums2 = [7,5,10,9,6], k = 1
Output: 30
Explanation:
Choosing index 2 is optimal: nums1[2] * nums2[2] = 3 * 10 = 30 is the maximum possible score.
*/
fun maxScore(nums1: IntArray, nums2: IntArray, k: Int): Long {
val list = mutableListOf<Pair<Int, Int>>()
for (i in nums1.indices) {
list.add(Pair(nums2[i], nums1[i]))
}
list.sortByDescending { it.first }
val pq = PriorityQueue<Int>()
var sum = 0L
var result = 0L
for (i in 0 until k) {
pq.offer(list[i].second)
sum += list[i].second
}
result = sum * list[k - 1].first
for (i in k until nums1.size) {
sum -= pq.poll()
sum += list[i].second
pq.offer(list[i].second)
result = Math.max(result, sum * list[i].first)
}
return result
}
// Input: nums1 = [1,3,3,2], nums2 = [2,1,3,4], k = 3
// Output: 12
assertEquals(12, maxScore(intArrayOf(1,3,3,2), intArrayOf(2,1,3,4), 3))
// Input: nums1 = [4,2,3,1,1], nums2 = [7,5,10,9,6], k = 1
// Output: 30
assertEquals(30, maxScore(intArrayOf(4,2,3,1,1), intArrayOf(7,5,10,9,6), 1))
}
@Test
fun leetcode2462() {
/**
You are given a 0-indexed integer array costs where costs[i] is the cost of hiring the ith worker.
You are also given two integers k and candidates. We want to hire exactly k workers according to the following rules:
You will run k sessions and hire exactly one worker in each session.
In each hiring session, choose the worker with the lowest cost from either the first candidates workers or the last candidates workers. Break the tie by the smallest index.
For example, if costs = [3,2,7,7,1,2] and candidates = 2, then in the first hiring session, we will choose the 4th worker because they have the lowest cost [3,2,7,7,1,2].
In the second hiring session, we will choose 1st worker because they have the same lowest cost as 4th worker but they have the smallest index [3,2,7,7,2].
Please note that the indexing may be changed in the process.
If there are fewer than candidates workers remaining, choose the worker with the lowest cost among them. Break the tie by the smallest index.
A worker can only be chosen once.
Return the total cost to hire exactly k workers.
Example 1:
Input: costs = [17,12,10,2,7,2,11,20,8], k = 3, candidates = 4
Output: 11
Explanation: We hire 3 workers in total. The total cost is initially 0.
- In the first hiring round we choose the worker from [17,12,10,2,7,2,11,20,8]. The lowest cost is 2, and we break the tie by the smallest index, which is 3. The total cost = 0 + 2 = 2.
- In the second hiring round we choose the worker from [17,12,10,7,2,11,20,8]. The lowest cost is 2 (index 4). The total cost = 2 + 2 = 4.
- In the third hiring round we choose the worker from [17,12,10,7,11,20,8]. The lowest cost is 7 (index 3). The total cost = 4 + 7 = 11. Notice that the worker with index 3 was common in the first and last four workers.
The total hiring cost is 11.
Example 2:
Input: costs = [1,2,4,1], k = 3, candidates = 3
Output: 4
Explanation: We hire 3 workers in total. The total cost is initially 0.
- In the first hiring round we choose the worker from [1,2,4,1]. The lowest cost is 1, and we break the tie by the smallest index, which is 0. The total cost = 0 + 1 = 1. Notice that workers with index 1 and 2 are common in the first and last 3 workers.
- In the second hiring round we choose the worker from [2,4,1]. The lowest cost is 1 (index 2). The total cost = 1 + 1 = 2.
- In the third hiring round there are less than three candidates. We choose the worker from the remaining workers [2,4]. The lowest cost is 2 (index 0). The total cost = 2 + 2 = 4.
The total hiring cost is 4.
*/
fun totalCost(costs: IntArray, k: Int, candidates: Int): Long {
var left = 0
var right = costs.lastIndex
val canL = PriorityQueue<Int>()
val canR = PriorityQueue<Int>()
var res = 0L
var n = k
while (n > 0) {
while (canL.size < candidates && left <= right) canL.add(costs[left++])
while (canR.size < candidates && left <= right) canR.add(costs[right--])
if (canL.peek()?: 100001 <= canR.peek()?: 100001) {
res += canL.poll()
} else {
res += canR.poll()
}
n--
}
return res
}
// Input: costs = [17,12,10,2,7,2,11,20,8], k = 3, candidates = 4
// Output: 11
assertEquals(11, totalCost(intArrayOf(17,12,10,2,7,2,11,20,8), 3, 4))
// Input: costs = [1,2,4,1], k = 3, candidates = 3
// Output: 4
assertEquals(4, totalCost(intArrayOf(1,2,4,1), 3, 3))
}
private fun printTree(root: TreeNode?) {
if (root == null) return
printTreeHelper(listOf(root))
}
private fun printTreeHelper(nodes: List<TreeNode?>) {
if (nodes.isEmpty() || nodes.all { it == null }) return
val nextLevelNodes = mutableListOf<TreeNode?>()
val line = StringBuilder()
for (node in nodes) {
line.append(if (node != null) "${node.`val`}" else " ")
line.append(" ".repeat(3))
nextLevelNodes.add(node?.left)
nextLevelNodes.add(node?.right)
}
println(line)
// Print vertical lines
val lineLength = line.length
val verticalLine = StringBuilder("")
for (i in 0 until lineLength) {
verticalLine.append(if (line[i] == '|') '|' else ' ')
}
println(verticalLine)
// Recursively print the next level
printTreeHelper(nextLevelNodes)
}
private fun printCharArray(array: CharArray) {
array.forEachIndexed { i, v ->
println("chars[$i] = $v")
}
}
private fun printIntArray(array: IntArray) {
array.forEachIndexed { i, v ->
println("Int[$i] = $v")
}
}
private fun printStringArray(array: MutableList<String>) {
array.forEachIndexed { i, v ->
println("String[$i] = $v")
}
}
private fun buildTree(nums: Array<Int?>): TreeNode? {
if (nums.isEmpty()) {
return null
}
val root = TreeNode(nums[0]!!)
val queue: Queue<TreeNode?> = LinkedList()
queue.offer(root)
var index = 1
while (index < nums.size) {
val node = queue.poll()
val leftValue = nums[index++]
if (leftValue != null) {
node?.left = TreeNode(leftValue)
queue.offer(node?.left)
}
if (index < nums.size) {
val rightValue = nums[index++]
if (rightValue != null) {
node?.right = TreeNode(rightValue)
queue.offer(node?.right)
}
}
}
return root
}
class ListNode(var `val`: Int) {
var next: ListNode? = null
}
class TreeNode(var `val`: Int) {
var left: TreeNode? = null
var right: TreeNode? = null
}
} | 0 | Kotlin | 0 | 0 | 1c19b46a79557d356ac28932a0ae0297d60cf2f9 | 72,627 | CameraXAndLeetCode | Apache License 2.0 |
src/main/kotlin/leetcode/Problem2182.kt | fredyw | 28,460,187 | false | {"Java": 1280840, "Rust": 363472, "Kotlin": 148898, "Shell": 604} | package leetcode
import java.util.PriorityQueue
/**
* https://leetcode.com/problems/construct-string-with-repeat-limit/
*/
class Problem2182 {
fun repeatLimitedString(s: String, repeatLimit: Int): String {
data class CharCount(val char: Char, val count: Int)
val array = IntArray(26)
for (char in s) {
array[char - 'a']++
}
val queue = PriorityQueue<CharCount> {a, b -> b.char.compareTo(a.char)}
for (i in array.indices) {
if (array[i] == 0) {
continue
}
queue += CharCount((i + 'a'.toInt()).toChar(), array[i])
}
val answer = StringBuilder()
var lastChar: Char? = null
var lastCount = 0
while (queue.isNotEmpty()) {
var e1: CharCount? = null
if (queue.isNotEmpty()) {
e1 = queue.remove()
if (lastChar == e1.char && lastCount == repeatLimit && queue.isEmpty()) {
break
}
var n = if (lastChar == e1.char) lastCount else 0
var count = 0
if (e1.count > repeatLimit - n) {
answer.append(e1.char.toString().repeat(repeatLimit - n))
count = repeatLimit - n
e1 = CharCount(e1.char, e1.count - (repeatLimit - n))
} else { // if (e1.count <= repeatLimit - n) {
answer.append(e1.char.toString().repeat(e1.count))
count = e1.count
e1 = null
}
if (lastChar == e1?.char) {
lastCount += count
} else {
lastChar = e1?.char
lastCount = count
}
}
var e2: CharCount? = null
if (queue.isNotEmpty()) {
e2 = queue.remove()
answer.append(e2?.char)
if (e2.count - 1 > 0) {
e2 = CharCount(e2.char, e2.count - 1)
} else if (e2.count - 1 == 0) {
e2 = null
}
lastChar = e2?.char
lastCount = 1
}
if (e1 != null) {
queue += e1
}
if (e2 != null) {
queue += e2
}
}
return answer.toString()
}
}
| 0 | Java | 1 | 4 | a59d77c4fd00674426a5f4f7b9b009d9b8321d6d | 2,423 | leetcode | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/MakeTheStringGreat.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 java.util.Stack
import kotlin.math.abs
/**
* Make The String Great.
* @see <a href="https://leetcode.com/problems/make-the-string-great/">Source</a>
*/
fun interface MakeTheStringGreat {
operator fun invoke(s: String): String
}
/**
* Approach 1: Iteration.
*/
class MakeTheStringGreatIteration : MakeTheStringGreat {
companion object {
private const val SIZE = 32
}
override operator fun invoke(s: String): String {
val newS = StringBuilder(s)
// if s has less than 2 characters, we just return itself.
while (newS.length > 1) {
// 'find' records if we find any pair to remove.
var find = false
// Check every two adjacent characters, currChar and nextChar.
for (i in 0 until newS.length - 1) {
val currChar = newS[i]
val nextChar = newS[i + 1]
// If they make a pair, remove them from 's' and let 'find = true'.
if (abs(currChar.code - nextChar.code) == SIZE) {
newS.deleteCharAt(i)
newS.deleteCharAt(i)
find = true
break
}
}
// If we cannot find any pair to remove, break the loop.
if (!find) break
}
return newS.toString()
}
}
/**
* Approach 2: Recursion
*/
class MakeTheStringGreatRecursion : MakeTheStringGreat {
companion object {
private const val SIZE = 32
}
override operator fun invoke(s: String): String {
// If we find a pair in 's', remove this pair from 's'
// and solve the remaining string recursively.
for (i in 0 until s.length - 1) {
if (abs(s[i] - s[i + 1]) == SIZE) {
return invoke(s.substring(0, i) + s.substring(i + 2))
}
}
// Base case, if we can't find a pair, just return 's'.
return s
}
}
class MakeTheStringGreatStack : MakeTheStringGreat {
companion object {
private const val ASCII_UPPER_CASE = 97
private const val ASCII_LOWER_CASE = 65
}
override operator fun invoke(s: String): String {
val stack: Stack<Char> = Stack()
for (i in s.indices) {
if (stack.isNotEmpty() && abs(stack.peek() - s[i]) == ASCII_UPPER_CASE - ASCII_LOWER_CASE) {
stack.pop()
} else {
stack.push(s[i])
}
}
val res = CharArray(stack.size)
var index: Int = stack.size - 1
while (stack.isNotEmpty()) {
res[index--] = stack.pop()
}
return String(res)
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 3,327 | kotlab | Apache License 2.0 |
src/main/kotlin/com/chriswk/aoc/advent2018/Day3.kt | chriswk | 317,863,220 | false | {"Kotlin": 481061} | package com.chriswk.aoc.advent2018
import com.chriswk.aoc.util.dayInputAsLines
object Day3 {
val lines = dayInputAsLines(2018, 3)
val idPattern = """(\d+)""".toRegex()
fun parseClaim(line: String): Claim {
val (id, actu) = line.split("@")
val (startCoord, size) = actu.trim().split(":")
val (startX, startY) = startCoord.trim().split(",")
val (deltaX, deltaY) = size.split("x")
val startYInt = startY.trim().toInt()
val startXInt = startX.trim().toInt()
val deltaXInt = deltaX.trim().toInt()
val deltaYInt = deltaY.trim().toInt()
return Claim(id = idPattern.find(id)!!.groupValues[0].toInt(),
startX = startXInt,
startY = startYInt,
endX = startXInt + deltaXInt - 1,
endY = startYInt + deltaYInt - 1)
}
fun solution1(): Int {
return lines
.map { parseClaim(it) }
.flatMap { it.toList() }
.groupBy { it }
.filter { it.value.size > 1 }
.size
}
fun solution2(): Int {
val cloth = mutableMapOf<Int, Int>()
val claims = lines.map { parseClaim(it) }
val uncovered = claims.map { it.id }.toMutableSet()
claims.forEach { claim ->
claim.toList().forEach {spot ->
val found = cloth.getOrPut(spot) { claim.id }
if (found != claim.id) {
uncovered.remove(found)
uncovered.remove(claim.id)
}
}
}
return uncovered.first()
}
data class Claim(val id: Int, val startX: Int, val startY: Int, val endX: Int, val endY: Int) {
fun toList(): List<Int> {
return (startX..endX).flatMap { x ->
(startY..endY).map { y ->
y * 1000 + x
}
}
}
}
} | 116 | Kotlin | 0 | 0 | 69fa3dfed62d5cb7d961fe16924066cb7f9f5985 | 1,939 | adventofcode | MIT License |
src/main/kotlin/algorithm/cpf.kt | Tiofx | 175,697,373 | false | null | package algorithm
class CPF(val init: Program) {
private val cpfChecker = CPFChecker(init)
private val parallelGroupOperatorFormatter = ParallelGroupOperatorFormatter(init)
private val sequentialGroupOperatorFormatter = SequentialGroupOperatorFormatter(init)
fun form(): List<Iteration> {
val result = mutableListOf<Iteration>()
var currentProgram = init
var parallelIteration = true
var i = 0
while (currentProgram.size > 1) {
setUp(currentProgram)
var currentInfo: Iteration?
val parallelResult = parallelGroupOperatorFormatter.analysis
val parallelChain = parallelResult.maxChain
val sequentialChain = sequentialGroupOperatorFormatter.maxChain
parallelIteration = when {
sequentialChain == null && parallelChain == null -> throw Exception("problem with CPF algorithm\n no next group chain")
sequentialChain == null -> true
parallelChain == null -> false
else -> parallelChain.first <= sequentialChain.first
}
currentInfo = Iteration(
i,
currentProgram,
parallelIteration,
cpfChecker.CPFCheck(),
parallelResult)
currentInfo = if (parallelIteration) currentInfo else currentInfo.copy(sequentialCheck = sequentialChain)
currentProgram = if (parallelIteration)
parallelGroupOperatorFormatter.transform(parallelResult)
else
sequentialGroupOperatorFormatter.transform(sequentialChain!!)
result.add(currentInfo)
i++
}
result.add(Iteration(i, currentProgram, parallelIteration, emptyList()))
return result
}
private fun setUp(program: Program) {
cpfChecker.program = program
parallelGroupOperatorFormatter.program = program
sequentialGroupOperatorFormatter.program = program
}
data class Iteration(
val number: Int,
val program: Program,
val isParallel: Boolean,
val cpfCheck: List<CPFChecker.Result>,
val parallelCheck: ParallelGroupOperatorFormatter.Result? = null,
val sequentialCheck: IntRange? = null
) {
val allRelationsMatrices = RelationsMatrix(program)
val groupedOperators: IntRange
get() = if (isParallel) parallelCheck?.maxChain!! else sequentialCheck ?: IntRange.EMPTY
}
}
fun List<CPF.Iteration>.finalResul() = map { it.program }.last().first()
fun List<CPF.Iteration>.resultOfGroupOperators(iteration: Int) =
if (iteration != lastIndex)
this[iteration + 1].program[this[iteration].groupedOperators.first]
else null
class CPFChecker(var program: Program) {
private inline val size get() = program.size
private inline val indices get() = program.indices
private inline val lastIndex get() = program.lastIndex
private inline fun isWeekIndependency(i: Int, j: Int) = program.isWeekIndependency(i, j)
private inline fun isWeekDependency(i: Int, j: Int) = program.isWeekDependency(i, j)
// fun canBeCPF(): Boolean = CPFCheck().any(Result::canBeBringToCPF)
fun CPFCheck() = pairsOfIndependent().map { CPFCheck(it.first, it.second) }
private fun pairsOfIndependent(): List<Pair<Int, Int>> = indices
.flatMap { i ->
(i + 2..lastIndex).map { j -> i to j }
}
.filter { isWeekIndependency(it.first, it.second) }
private fun CPFCheck(i: Int, j: Int): Result {
assert(j > i + 1)
assert(isWeekIndependency(i, j))
val Ei = E(i)
val Ej = E(j)
val N1 = N1(i, j)
val N2 = N2(i, j, N1)
N2
.filter { it in i + 1 until j }
.forEach { k ->
if (N1 in E(k)) return Result(i, j, k, Ei, Ej, N1, N2, E(k))
}
val k = j - 1
return Result(i, j, k, Ei, Ej, N1, N2, E(k))
}
private fun N1(i: Int, j: Int) = E(i) intersect E(j)
private fun N2(i: Int, j: Int, N1: Set<Int> = N1(i, j)) = (E(i) union E(j)) - N1
private fun E(i: Int) = weekDepsFrom(i)
/**
* @param i number of operator
* @return {j | Si -> Sj}
*/
private fun weekDepsFrom(i: Int) = (i + 1..lastIndex)
.filter { j -> isWeekDependency(i, j) }
.toCollection(LinkedHashSet())
data class Result(
val i: Int,
val j: Int,
val k: Int,
val Ei: Set<Int>,
val Ej: Set<Int>,
val N1: Set<Int>,
val N2: Set<Int>,
val Ek: Set<Int>
) {
val isSkInN2 = k in N2
val isN1InEk = N1 in Ek
val canBeBringToCPF = isSkInN2 && isN1InEk
}
}
class ParallelGroupOperatorFormatter(var program: Program) {
private inline val size get() = program.size
private inline val indices get() = program.indices
private inline fun isWeekIndependency(i: Int, j: Int) = program.isWeekIndependency(i, j)
val C: Matrix
get() {
val matrix = List(size) { MutableList(size) { false } }
for (i in 0 until size)
for (j in i until size) {
matrix[i][j] = isWeekIndependency(i, j)
matrix[j][i] = matrix[i][j]
}
return matrix
}
private fun nextParallelGroupOperatorsRange(C: Matrix = this.C): IntRange? {
fun squareSize(leftUpEdge: Int): Int {
for (i in leftUpEdge until size) {
val a = i - leftUpEdge
for (j in 0..a)
if (!(C[leftUpEdge + j][i] && C[i][leftUpEdge + j])) return a
}
return size - leftUpEdge
}
for (i in 0 until size) {
val squareSize = squareSize(i)
if (squareSize < 2) continue
val chain = i until i + squareSize
val correctedChain = chain.correctChain()
if (correctedChain.toList().size >= 2) {
return correctedChain
}
}
return null
}
private fun IntRange.correctChain(): IntRange {
if (last == program.lastIndex) return this
for (right in last downTo first) {
if ((first..right).all { left -> program.isStrongDependency(left, right + 1) })
return first..right
}
return IntRange.EMPTY
}
fun transform(result: Result = analysis) = result.toNewProgram(program)
val analysis get() = result()
private fun result(
C: Matrix = this.C,
U: Set<Int> = this.U,
B1: Set<Int> = B1(C),
K: Set<Int> = K(B1)
) = Result(C, U, B1, K)
private val U get() = indices.toSet()
private val B1 get() = B1(C)
private fun B1(C: Matrix) = nextParallelGroupOperatorsRange(C)?.toSet() ?: emptySet()
private val K get() = K(B1)
private fun K(B1: Set<Int>) = U - B1
data class Result(
val C: Matrix,
val U: Set<Int>,
val B1: Set<Int>,
val K: Set<Int>
) {
inline val maxChain get() = if (B1.isNotEmpty()) B1.run { first()..last() } else null
fun toNewProgram(from: Program): Program {
val groupOperator = GroupOperator(from, maxChain!!, GroupOperator.Type.PARALLEL)
val operators =
from.subList(0, maxChain!!.first) + groupOperator + from.subList(maxChain!!.last + 1, from.size)
val newProgram = CashedProgram(operators)
return newProgram
}
}
}
class SequentialGroupOperatorFormatter(var program: Program) {
fun transform(maxChain: IntRange): Program {
val groupOperator = GroupOperator(program, maxChain, GroupOperator.Type.SEQUENTIAL)
val operators =
program.subList(0, maxChain.first) + groupOperator + program.subList(maxChain.last + 1, program.size)
val newProgram = CashedProgram(operators)
return newProgram
}
val maxChain: IntRange?
get() {
val chains = formStrongDependencyChains()
fun List<List<Int>>.correct(maxChain: IntRange): IntRange {
val depsBeforeChain = this.take(maxChain.start).flatten()
maxChain.forEach { i -> if (depsBeforeChain.contains(i)) return maxChain.start..(i - 1) }
return maxChain
}
tailrec fun List<List<Int>>.chainEndFor(i: Int): Int =
if (!getOrNull(i).isNullOrEmpty() && get(i).first() == i + 1) chainEndFor(i + 1) else i
fun List<List<Int>>.maxChain(i: Int) = correct(i..chainEndFor(i))
for (i in program.indices) {
val maxChain = chains.maxChain(i)
if (maxChain.toList().size >= 2) return maxChain
}
return null
}
private fun formStrongDependencyChains() = program.indices.map { i ->
(i + 1 until program.size).map { j ->
program.isStrongDependency(i, j)
}
.mapIndexed { index, r -> if (r) index + i + 1 else null }
.filterNotNull()
}
}
| 0 | Kotlin | 0 | 0 | 32c1cc3e95940e377ed9a99293eccc871ce13864 | 9,352 | CPF | The Unlicense |
Kotlin-Knn/src/main/kotlin/dataOOP.kt | JUSTNic3 | 739,087,623 | false | {"Kotlin": 11542} | // Simplified data class
data class Movie(
val crew: String,
val country: String,
val originalLanguage: String
)
val movies: List<Movie> = loadCsvData("database/imdb_movies.csv").mapNotNull { row ->
val crew = row["crew"]
val country = row["country"]
val originalLanguage = row["orig_lang"]
if (crew != null && country != null && originalLanguage != null) {
return@mapNotNull Movie(crew, country, originalLanguage)
} else {
null
}
}
fun dataOOP() {
val movies: List<Movie> = loadCsvData("database/imdb_movies.csv").mapNotNull { row ->
val crew = row["crew"]
val country = row["country"]
val originalLanguage = row["orig_lang"]
if (crew != null && country != null && originalLanguage != null) {
return@mapNotNull Movie(crew, country, originalLanguage)
} else {
null
}
}
//val actorFrequency = movies.groupBy { it.crew }.mapValues { it.value.size }
val countryFrequency = movies.groupBy { it.country }.mapValues { it.value.size }
val languageFrequency = movies.groupBy { it.originalLanguage }.mapValues { it.value.size }
/*val actorBuckets = actorFrequency.entries.groupBy {
when(it.value) {
in 1..9 -> "1-9 movies"
in 10..99 -> "10-99 movies"
in 100..999 -> "100-999 movies"
else -> "1000+ movies"
}
}.mapValues { it.value.sumBy { it.value } }*/
println("\nCountry Frequency:")
printAsciiChart(countryFrequency)
println("\nLanguage Frequency:")
printAsciiChart(languageFrequency)
}
fun printAsciiChart(frequency: Map<String, Int>) {
val colors = arrayOf("\u001B[31m", "\u001B[32m", "\u001B[33m")
var index = 0
frequency.forEach { (key, value) ->
val bar = "█".repeat(value)
println("\u001B[34m$key\u001B[0m: $bar") // blue text
val color = colors[index % colors.size]
print(color)
index ++
}
}
| 0 | Kotlin | 0 | 0 | 2c74d4e143d082a61c8a72de9b1c8469fdf82b30 | 1,993 | Kotlin-Knn | MIT License |
src/main/kotlin/se/saidaspen/aoc/aoc2021/Day03.kt | saidaspen | 354,930,478 | false | {"Kotlin": 301372, "CSS": 530} | package se.saidaspen.aoc.aoc2021
import se.saidaspen.aoc.util.Day
fun main() = Day03.run()
object Day03 : Day(2021, 3) {
override fun part1(): Any {
val lines = input.lines().size
val gamma = StringBuilder()
for (i in 0 until input.lines()[0].length) {
val ones = input.lines().map { it.toCharArray()[i] }.count { it == '1' }
gamma.append(if (ones > lines/2) '1' else '0')
}
return gamma.toString().toInt(2) * gamma.toString().toCharArray().map { if(it == '1') '0' else '1' }.joinToString("").toInt(2)
}
override fun part2(): Any {
var ogrLeft = input.lines()
var co2scrubLeft = input.lines()
for (i in 0 until input.lines()[0].length) {
val ogrOnes = ogrLeft.map { it.toCharArray()[i] }.count { it == '1' }
val ogrCrit = if (ogrOnes >= ogrLeft.size / 2) '1' else '0'
if (ogrLeft.size > 1)
ogrLeft = ogrLeft.filter { it.toCharArray()[i] == ogrCrit }
val co2Ones = co2scrubLeft.map { it.toCharArray()[i] }.count { it == '1' }
val co2Crit = if (co2Ones < co2scrubLeft.size / 2) '1' else '0'
if (co2scrubLeft.size > 1)
co2scrubLeft = co2scrubLeft.filter { it.toCharArray()[i] == co2Crit }
}
return ogrLeft[0].toInt(2) * co2scrubLeft[0].toInt(2)
}
}
| 0 | Kotlin | 0 | 1 | be120257fbce5eda9b51d3d7b63b121824c6e877 | 1,375 | adventofkotlin | MIT License |
2015/src/main/kotlin/day11.kt | madisp | 434,510,913 | false | {"Kotlin": 388138} | import utils.Parser
import utils.Solution
fun main() {
Day11.run()
}
object Day11 : Solution<String>() {
override val name = "day11"
override val parser: Parser<String> = Parser { it.trim() }
fun validPwd(pwd: String): Boolean {
if ('i' in pwd || 'o' in pwd || 'l' in pwd) {
return false
}
if (pwd.windowed(2).filter { it[0] == it[1] }.toSet().size < 2) {
return false
}
if (pwd.windowed(3).none { it[0] + 1 == it[1] && it[1] + 1 == it[2] }) {
return false
}
return true
}
fun next(pwd: String): String? {
val char = pwd.indexOfLast { it != 'z' }
if (char == -1) {
return null
}
val zc = pwd.length - char - 1
return pwd.substring(0, char) + (pwd[char] + 1) + "a".repeat(zc)
}
override fun part1(input: String): String {
return generateSequence(input) { next(it) }
.filter { validPwd(it) }
.first()
}
override fun part2(input: String): String {
return generateSequence(input) { next(it) }
.filter { validPwd(it) }
.drop(1)
.first()
}
}
| 0 | Kotlin | 0 | 1 | 3f106415eeded3abd0fb60bed64fb77b4ab87d76 | 1,079 | aoc_kotlin | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/HalvesAreAlike.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
private const val VOWELS = "aeiouAEIOU"
/**
* Determine if String Halves Are Alike
* @see <a href="https://leetcode.com/problems/determine-if-string-halves-are-alike/">Source</a>
*/
fun interface HalvesAreAlike {
operator fun invoke(str: String): Boolean
}
class HalvesAreAlikeBruteForce : HalvesAreAlike {
override operator fun invoke(str: String): Boolean {
val length = str.length
val mid = length / 2
val firstHalf = str.substring(0, mid)
val secondHalf = str.substring(mid, length)
var leftVowelCount = 0
var rightVowelCount = 0
for (char in firstHalf) {
if (VOWELS.contains(char)) leftVowelCount++
}
for (char in secondHalf) {
if (VOWELS.contains(char)) rightVowelCount++
}
return leftVowelCount == rightVowelCount
}
}
class HalvesAreAlikeCount : HalvesAreAlike {
override operator fun invoke(str: String): Boolean {
val length = str.length
val mid = length / 2
return countVowels(0 until mid, str) == countVowels(mid until length, str)
}
private fun countVowels(range: IntRange, s: String): Int {
var count = 0
for (index in range) {
if (VOWELS.indexOf(s[index]) != -1) {
count++
}
}
return count
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,993 | kotlab | Apache License 2.0 |
src/main/kotlin/Day13.kt | clechasseur | 258,279,622 | false | null | import org.clechasseur.adventofcode2019.Day13Data
import org.clechasseur.adventofcode2019.IntcodeComputer
import org.clechasseur.adventofcode2019.Pt
import kotlin.math.sign
object Day13 {
private val input = Day13Data.input
private const val empty = 0L
private const val wall = 1L
private const val block = 2L
private const val paddle = 3L
private const val ball = 4L
private const val neutral = 0L
private const val tiltedLeft = -1L
private const val tiltedRight = 1L
fun part1() = IntcodeComputer(input).readScreen().filter { it.value == block }.count()
fun part2(): Long {
val computer = IntcodeComputer(listOf(2L) + input.drop(1))
var screen = computer.readScreen()
var paddlePos = screen.singleTile(paddle)
var ballPos = screen.singleTile(ball)
var ballSpeed = 0
while (!computer.done) {
//render(screen)
if (ballPos.x != paddlePos.x || ballPos.y != paddlePos.y - 1) {
val nextBallX = ballPos.x + ballSpeed
computer.addInput((nextBallX - paddlePos.x).sign.toLong())
} else {
computer.addInput(neutral)
}
screen = screen + computer.readScreen()
val newBallPos = screen.singleTile(ball)
ballSpeed = (newBallPos.x - ballPos.x).sign
paddlePos = screen.singleTile(paddle)
ballPos = newBallPos
}
return screen[Pt(-1, 0)] ?: error("No score found")
}
private fun IntcodeComputer.readScreen(): Map<Pt, Long> = readAllOutput().chunked(3).map {
(x, y, tileId) -> Pt(x.toInt(), y.toInt()) to tileId
}.toMap()
private fun Map<Pt, Long>.singleTile(id: Long) = asSequence().filter { it.value == id }.single().key
private fun render(screen: Map<Pt, Long>) {
val maxX = screen.map { it.key.x }.max()!!
val maxY = screen.map { it.key.y }.max()!!
(0..maxY).forEach { y ->
(0..maxX).forEach { x ->
val tileChar = when (val tileId = screen[Pt(x, y)]) {
null, empty -> ' '
wall -> '#'
block -> 'W'
paddle -> '_'
ball -> 'o'
else -> error("Wrong tile id: $tileId")
}
print(tileChar)
}
println()
}
generateSequence(0) { when (it) {
9 -> 0
else -> it + 1
} }.take(maxX + 1).forEach { print(it) }
println()
println()
}
}
| 0 | Kotlin | 0 | 0 | 187acc910eccb7dcb97ff534e5f93786f0341818 | 2,597 | adventofcode2019 | MIT License |
2020/day22/day22.kt | flwyd | 426,866,266 | false | {"Julia": 207516, "Elixir": 120623, "Raku": 119287, "Kotlin": 89230, "Go": 37074, "Shell": 24820, "Makefile": 16393, "sed": 2310, "Jsonnet": 1104, "HTML": 398} | /*
* Copyright 2021 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
package day22
import kotlin.time.ExperimentalTime
import kotlin.time.TimeSource
import kotlin.time.measureTimedValue
/* Input: "Player 1:" and "Player 2:" followed by a list of integers, one per line, representing
cards in two halves of a deck. Output: winning player's score. */
fun parseDecks(input: Sequence<String>): List<Deck> {
val result = mutableListOf<Deck>()
var name = ""
var cards = ArrayDeque<Int>()
input.forEach { line ->
if (line.startsWith("Player")) {
if (name.isNotEmpty()) {
result.add(Deck(name, cards))
}
name = line.removeSuffix(":")
cards = ArrayDeque()
} else if (line.isNotBlank()) {
cards.addLast(line.toInt())
}
}
result.add(Deck(name, cards))
return result.toList().also { check(it.size == 2) { "Unexpected player count: $result" } }
}
data class Deck(val name: String, private val cards: ArrayDeque<Int>) {
fun score(): Long {
return cards.reversed().withIndex().map { (it.index + 1) * it.value.toLong() }.sum()
}
fun size() = cards.size
fun isNotEmpty() = cards.isNotEmpty()
fun draw() = cards.removeFirst()
fun addWinnings(card1: Int, card2: Int) {
cards.addLast(card1)
cards.addLast(card2)
}
fun take(count: Int) = copy(cards = ArrayDeque(cards.take(count)))
}
/* Game: Flip top two; winner has higher value card and gets both cards at the bottom of their deck,
with their flipped card first. Game ends when one player has no cards left; winner's score is the
product of the bottom-up index times card value. */
object Part1 {
fun solve(input: Sequence<String>): String {
val (player1, player2) = parseDecks(input)
while (player1.isNotEmpty() && player2.isNotEmpty()) {
val card1 = player1.draw()
val card2 = player2.draw()
check(card1 != card2) { "$card1 = $card2" }
if (card1 > card2) {
player1.addWinnings(card1, card2)
} else {
player2.addWinnings(card2, card1)
}
}
return listOf(player1, player2).first(Deck::isNotEmpty).score().toString()
}
}
/* Game: similar to part 1, but if the number both players draw is less than or equal to the number
of cards left in their deck, play a recursive game where both players start with a copy of the first
N cards in their deck, where N is the number they just drew; the winner of that game gets the two
cards drawn in this round, even if their card was lower. If the two decks before a draw are in
an identical state to those in previous round, player 1 wins to prevent infinite loops.
*/
object Part2 {
private fun recursiveCombat(player1: Deck, player2: Deck): Deck {
val nextPrevious = mutableSetOf<Pair<Deck, Deck>>()
while (player1.isNotEmpty() && player2.isNotEmpty()) {
if (player1 to player2 in nextPrevious) {
return player1 // rule: if the exact same deck state has been seen before, player 1 wins
}
nextPrevious.add(player1 to player2)
val card1 = player1.draw()
val card2 = player2.draw()
val winner = if (card1 <= player1.size() && card2 <= player2.size()) {
recursiveCombat(player1.take(card1), player2.take(card2))
} else {
if (card1 > card2) player1 else player2
}
when (winner.name) {
player1.name -> player1.addWinnings(card1, card2)
player2.name -> player2.addWinnings(card2, card1)
else -> error("Unknown winner $winner")
}
}
return if (player1.isNotEmpty()) {
player1.also { check(player2.size() == 0) }
} else {
player2.also { check(player1.size() == 0) }
}
}
fun solve(input: Sequence<String>): String {
val (player1, player2) = parseDecks(input)
return recursiveCombat(player1, player2).score().toString()
}
}
@ExperimentalTime
@Suppress("UNUSED_PARAMETER")
fun main(args: Array<String>) {
val lines = generateSequence(::readLine).toList()
print("part1: ")
TimeSource.Monotonic.measureTimedValue { Part1.solve(lines.asSequence()) }.let {
println(it.value)
System.err.println("Completed in ${it.duration}")
}
print("part2: ")
TimeSource.Monotonic.measureTimedValue { Part2.solve(lines.asSequence()) }.let {
println(it.value)
System.err.println("Completed in ${it.duration}")
}
}
| 0 | Julia | 1 | 5 | f2d6dbb67d41f8f2898dbbc6a98477d05473888f | 4,439 | adventofcode | MIT License |
src/main/kotlin/d25/d25.kt | LaurentJeanpierre1 | 573,454,829 | false | {"Kotlin": 118105} | package d25
import readInput
import java.lang.IllegalStateException
import java.util.*
val units = mapOf('0' to 0L, '1' to 1L, '2' to 2L, '-' to -1L, '=' to -2L)
fun snafuToLong(snafu : String) : Long {
var pow = 1L
var sum = 0L
for (unit in snafu.reversed()) {
sum += pow * units[unit]!!
pow *= 5L
}
return sum
}
fun longToSnafu(value : Long) : String {
var deconstr = value
val res = LinkedList<Char>()
while (deconstr>0) {
val digit = deconstr % 5L
deconstr /= 5
res.addFirst(when(digit){
0L->'0'
1L->'1'
2L->'2'
3L->'='.also { deconstr++ }
4L->'-'.also { deconstr++ }
else->throw IllegalStateException()
})
}
return res.joinToString(separator = "")
}
fun part1(input: List<String>): String {
var sum = 0L
for (line in input) {
val snafu = snafuToLong(line)
sum += snafu
}
return longToSnafu(sum)
}
fun main() {
//val input = readInput("d25/test")
val input = readInput("d25/input1")
println(part1(input))
}
| 0 | Kotlin | 0 | 0 | 5cf6b2142df6082ddd7d94f2dbde037f1fe0508f | 1,127 | aoc2022 | Creative Commons Zero v1.0 Universal |
src/main/kotlin/day12/part1/main.kt | TheMrMilchmann | 225,375,010 | false | null | /*
* Copyright (c) 2019 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package day12.part1
import utils.*
import kotlin.math.*
fun main() {
val input = readInputText("/day12/input.txt")
val positions = input.lineSequence().map { line ->
line.removePrefix("<")
.removeSuffix(">")
.replace(" ", "")
.split(',')
.let { kvPairs -> kvPairs.map { kvPair -> kvPair.split("=")[1].toInt() } }.let { coords ->
Vec(coords[0], coords[1], coords[2])
}
}
println(run(positions.toList(), steps = 1000))
}
private fun run(positions: List<Vec>, steps: Int): Int {
data class Moon(var pos: Vec, var velocity: Vec)
val moons = positions.map { Moon(it, Vec(0, 0, 0)) }
repeat(steps) {
moons.flatMap { a -> moons.map { b -> a to b } }
.filter { it.first !== it.second }
.forEach { (a, b) ->
a.velocity += Vec(
x = (b.pos.x - a.pos.x).sign,
y = (b.pos.y - a.pos.y).sign,
z = (b.pos.z - a.pos.z).sign
)
}
moons.forEach { moon -> moon.pos += moon.velocity }
}
return moons.map { (pos, velocity) ->
(abs(pos.x) + abs(pos.y) + abs(pos.z)) * (abs(velocity.x) + abs(velocity.y) + abs(velocity.z))
}.sum()
}
data class Vec(val x: Int, val y: Int, val z: Int)
operator fun Vec.plus(other: Vec) = Vec(x + other.x, y + other.y, z + other.z) | 0 | Kotlin | 0 | 1 | 9d6e2adbb25a057bffc993dfaedabefcdd52e168 | 2,540 | AdventOfCode2019 | MIT License |
src/main/kotlin/week2/RegolithReservoir.kt | waikontse | 572,850,856 | false | {"Kotlin": 63258} | package week2
import shared.Puzzle
import java.lang.Integer.max
import java.lang.Integer.min
typealias Point = Pair<Int, Int>
typealias Cave = Array<CharArray>
class RegolithReservoir : Puzzle(14) {
companion object {
const val SAND = 'o'
const val ROCK = '#'
const val AIR = '.'
val initialSandDropPos = 500 to 0
}
override fun solveFirstPart(): Any {
val parsedLines = puzzleInput.map { parseLines(it) }
val deepest = getDeepestLevels(parsedLines)
val largest = getLargestNumber(parsedLines)
val cave = Array(largest + 1) { _ -> CharArray(deepest + 2) { AIR } }
drawInitialCaveMap(parsedLines, cave)
var rounds = 0
val predicate = { p: Point, _: Boolean -> p.second < deepest }
val stopCondition = { p: Point -> p.second >= deepest }
while (!simulateSanddrop(cave, initialSandDropPos, deepest, predicate, stopCondition)) {
rounds++
}
return rounds
}
override fun solveSecondPart(): Any {
val parsedLines = puzzleInput.map { parseLines(it) }
val deepest = getDeepestLevels(parsedLines)
val largest = getLargestNumber(parsedLines)
val newFloorLine: List<Point> = listOf(0 to deepest + 2, largest * 2 - 1 to deepest + 2)
val parsedLinesWithFloor: List<List<Point>> = parsedLines.plusElement(newFloorLine)
val cave = Array(largest * 2) { _ -> CharArray(deepest + 3) { AIR } }
drawInitialCaveMap(parsedLinesWithFloor, cave)
var rounds = 1
val predicate = { p: Point, canMove: Boolean -> p.second >= 0 && canMove }
val stopCondition = { p: Point -> p.second == 0 }
while (!simulateSanddrop(cave, initialSandDropPos, deepest+2, predicate, stopCondition)) {
rounds++
}
return rounds
}
private fun parseLines(paths: String): List<Point> {
return paths.split(" -> ")
.map { it.split(",") }
.map { it[0].toInt() to it[1].toInt() }
}
private fun getLargestNumber(allPaths: List<List<Point>>): Int {
return allPaths.map { points -> points.maxBy { it.first } }
.maxBy { it.first }
.first
}
private fun getDeepestLevels(allPaths: List<List<Point>>): Int {
return allPaths.map { points -> points.maxBy { it.second } }
.maxBy { it.second }
.second
}
fun drawInitialCaveMap(allPaths: List<List<Point>>, cave: Cave) {
allPaths.map { drawPathOnCave(it, cave) }
}
fun drawPathOnCave(path: List<Point>, cave: Cave) {
path.zipWithNext()
.map { drawLineOnCave(it.first, it.second, cave) }
}
fun drawLineOnCave(from: Point, to: Point, cave: Cave) {
if (from.first == to.first) {
drawVerticalLine(from, to, cave)
} else {
drawHorizontalLine(from, to, cave)
}
}
fun drawVerticalLine(from: Point, to: Point, cave: Cave) {
val fromY = min(from.second, to.second)
val toY = max(from.second, to.second)
for (i in fromY..toY) {
cave[from.first][i] = ROCK
}
}
fun drawHorizontalLine(from: Point, to: Point, cave: Cave) {
val fromX = min(from.first, to.first)
val toX = max(from.first, to.first)
for (i in fromX..toX) {
cave[i][from.second] = ROCK
}
}
fun simulateSanddrop(
cave: Cave,
currPos: Point,
deepestLevel: Int,
predicate: (Point, Boolean) -> Boolean,
stopCondition: (Point) -> Boolean
): Boolean { // return true iff goal reached.
// while can move and has not passed the deepest level, keep moving
var canMove = canStillMove(cave, currPos)
var newPos = currPos
while (canMove && predicate(newPos, canMove)) {
if (canGoDown(cave, newPos)) {
// go down and update pos
newPos = newPos.copy(second = newPos.second.inc())
} else if (canGoLeft(cave, newPos)) {
// go left and update pos
newPos = newPos.copy(first = newPos.first.dec(), second = newPos.second.inc())
} else if (canGoRight(cave, newPos)) {
// go right and update pos
newPos = newPos.copy(first = newPos.first.inc(), second = newPos.second.inc())
}
// do follow up things
canMove = canStillMove(cave, newPos)
}
// Update the cave with the new sand drop iff the sand is above deepest floor.
if (newPos.second < deepestLevel) {
cave[newPos.first][newPos.second] = SAND
}
return stopCondition(newPos)
}
fun canStillMove(cave: Cave, currPos: Point): Boolean {
return canGoDown(cave, currPos) || canGoLeft(cave, currPos) || canGoRight(cave, currPos)
}
fun canGoDown(cave: Cave, currPos: Point): Boolean {
return !isBlocking(cave, currPos.copy(second = currPos.second.inc()))
}
fun canGoLeft(cave: Cave, currPos: Point): Boolean {
return !isBlocking(cave, currPos.copy(first = currPos.first.dec(), second = currPos.second.inc()))
}
fun canGoRight(cave: Cave, currPos: Point): Boolean {
return !isBlocking(cave, currPos.copy(first = currPos.first.inc(), second = currPos.second.inc()))
}
fun isBlocking(cave: Cave, pos: Point): Boolean {
val charAtPos = cave[pos.first][pos.second]
return charAtPos == SAND || charAtPos == ROCK
}
}
| 0 | Kotlin | 0 | 0 | 860792f79b59aedda19fb0360f9ce05a076b61fe | 5,583 | aoc-2022-in-kotllin | Creative Commons Zero v1.0 Universal |
src/Day08.kt | Redstonecrafter0 | 571,787,306 | false | {"Kotlin": 19087} |
fun main() {
fun part1(input: List<String>): Int {
val grid = input.map { it.toCharArray().map { i -> i.toString().toInt() } }
var visible = grid.size * 2 + grid.first().size - 2 + grid.last().size - 2
for (y in 1 until grid.lastIndex) {
for (x in 1 until grid[y].lastIndex) {
var test = true
for (ix in (x - 1) downTo 0) {
if (grid[y][ix] >= grid[y][x]) {
test = false
}
}
if (test) {
visible++
continue
}
test = true
for (iy in (y - 1) downTo 0) {
if (grid[iy][x] >= grid[y][x]) {
test = false
}
}
if (test) {
visible++
continue
}
test = true
for (ix in (x + 1)..grid[y].lastIndex) {
if (grid[y][ix] >= grid[y][x]) {
test = false
}
}
if (test) {
visible++
continue
}
test = true
for (iy in (y + 1)..grid.lastIndex) {
if (grid[iy][x] >= grid[y][x]) {
test = false
}
}
if (test) {
visible++
}
}
}
return visible
}
fun part2(input: List<String>): Int {
val grid = input.map { it.toCharArray().map { i -> i.toString().toInt() } }
val scores = mutableListOf<Int>()
for (y in 1 until grid.lastIndex) {
for (x in 1 until grid[y].lastIndex) {
var left = 0
for (ix in (x - 1) downTo 0) {
left++
if (grid[y][ix] >= grid[y][x]) {
break
}
}
var up = 0
for (iy in (y - 1) downTo 0) {
up++
if (grid[iy][x] >= grid[y][x]) {
break
}
}
var right = 0
for (ix in (x + 1)..grid[y].lastIndex) {
right++
if (grid[y][ix] >= grid[y][x]) {
break
}
}
var down = 0
for (iy in (y + 1)..grid.lastIndex) {
down++
if (grid[iy][x] >= grid[y][x]) {
break
}
}
scores += left * up * right * down
}
}
return scores.max()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day08_test")
check(part1(testInput) == 21)
check(part2(testInput) == 8)
val input = readInput("Day08")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | e5dbabe247457aabd6dd0f0eb2eb56f9e4c68858 | 3,170 | Advent-of-Code-2022 | Apache License 2.0 |
src/main/kotlin/org/tameter/planguage/requirements.kt | HughG | 226,680,701 | false | null | package org.tameter.planguage
/**
* The __Gist__ of an item is a short single sentence; this system uses the first paragraph of the class or object
* comment in KDoc, the summary.
*
* The __Description__ (Concept 416) of an item consists of words, diagrams, etc. which (inevitably only partly) define
* that item. This system uses the rest of the KDoc class or object comment.
*/
sealed class Item<out T : Tag?> : TaggedBase<T>
interface Relationships {
/**
* _List the tags of any Design Ideas or Evo Steps delivering, or capable of delivering, this function. The actual
* item is NOT modified by any Design Ideas, but its presence in the system is, or can be, altered in some way. This
* is an Impact Estimation table relationship._
*/
val impactedBy : Any // Collection<Tag>
/**
* _List names or tags of any other system specifications, which this one is related to intimately, in addition to
* the above specified hierarchical function relations and Impact-Estimation-related links. Note: an alternative way
* is to express such a relationship is to use Supports or Is Supported By, as appropriate._
*/
val linkedTo : Any // Collection<TextOrTag>
}
interface PriorityAndRiskManagement {
/** _Justifies the existence of this function; why is it necessary?_ */
val rationale : Any // Text
/**
* _Name (Stakeholder, time, place, event): Quantify, or express in words, the value claimed as a result of
* delivering the requirement._
*/
val value : Any // Text
/**
* _Specify, or refer to tags of any assumptions in connection with this function, which could cause problems if
* they were not true, or later became invalid._
*/
val assumptions : Any // Collection<TextOrTag>
/**
* _Using text or tags, name anything, which is dependent on this function in any significant way, or which this
* function itself, is dependent on in any significant way._
*/
val dependencies : Any // Collection<TextOrTag>
/**
* _List or refer to tags of anything, which could cause malfunction, delay, or negative impacts on plans,
* requirements and expected results._
*/
val risks : Any // Collection<TextOrTag>
/**
* _Name, using tags, any system elements, which this function can clearly be done after or must clearly be done
* before. Give any relevant reasons._
*/
val priority : Any // Collection<Tag>
/**
* _State any known issues; that is, unresolved concerns._
*/
val issues : Any // Collection<Text>
}
sealed class Requirement : Item<Tag>(), TaggedWithClassName,
Relationships,
PriorityAndRiskManagement
interface FunctionMeasurement {
/**
* _Refer to tags of any test plan or/and test cases, which deal with this function (or describe in words how it
* will or could be tested)._
*/
val test : Any // Collection<TextOrTag>
}
interface FunctionRelationships : Relationships {
/**
* _List the tags of any immediate Sub-Functions (that is, the next level down), of this function._
*
* _Note: alternative ways of expressing Sub-Functions are Includes and Consists Of._
*/
val subFunctions : Any // Collection<Tag>
}
abstract class FunctionRequirement : Requirement(),
FunctionRelationships,
FunctionMeasurement
// TODO: Should have base class for other kinds of constraint?
abstract class DesignConstraint : Requirement()
sealed class ScalarRequirement : Requirement() {
}
| 0 | Kotlin | 0 | 0 | b6eaaa8392e3df3c721f9c03163bd142b8d4a747 | 3,550 | planguage-autodoc | The Unlicense |
src/main/aoc2019/Day15.kt | nibarius | 154,152,607 | false | {"Kotlin": 963896} | package aoc2019
import Direction
import Pos
import AMap
import org.magicwerk.brownies.collections.GapList
import kotlin.math.max
class Day15(input: List<String>) {
val program = Intcode(input.map { it.toLong() })
enum class Status(val ch: Char) {
Wall('#'),
Moved('.'),
Found('o');
companion object {
fun get(value: Long): Status {
return when (value) {
2L -> Found
1L -> Moved
else -> Wall
}
}
}
}
data class Droid(private val program: Intcode, var stepsTaken: Int = 0) {
@Override
fun copy() = Droid(program.copy(), stepsTaken)
fun move(direction: Direction): Status {
val dir = when(direction){
Direction.Up -> 1L
Direction.Down -> 2L
Direction.Left -> 3L
Direction.Right -> 4L
}
program.input.add(dir)
program.run()
return Status.get(program.output.removeAt(0))
}
}
private data class QueueEntry(val pos: Pos, val droid: Droid, val direction: Direction)
private fun makeMap(droid: Droid): Triple<Int, Pos, AMap> {
val map = AMap()
// Queue is position, (droid + movement)
val queue = GapList<QueueEntry>()
val alreadyChecked = mutableSetOf<Pos>()
val startPos = Pos(0, 0)
var stepsToOxygen = 0
var oxygenPosition = Pos(0,0)
// Move one step in every direction
droid.stepsTaken++
Direction.entries.forEach { queue.add(QueueEntry(it.from(startPos), droid.copy(), it)) }
while (queue.isNotEmpty()) {
val current = queue.remove()
if (alreadyChecked.contains(current.pos)) continue
val result = current.droid.move(current.direction) // Move to get to the current position
map[current.pos] = result.ch
alreadyChecked.add(current.pos)
if (result == Status.Wall) continue
else if (result == Status.Found) {
stepsToOxygen = current.droid.stepsTaken
oxygenPosition = current.pos
}
current.droid.stepsTaken++
Direction.entries.forEach {
val nextPos = it.from(current.pos)
if (!alreadyChecked.contains(nextPos)) {
queue.add(QueueEntry(nextPos, current.droid.copy(), it))
}
}
}
return Triple(stepsToOxygen, oxygenPosition, map)
}
data class QueueEntry2(val pos: Pos, val stepsTaken: Int)
private fun maxDistanceFrom(pos: Pos, map: AMap): Int {
val queue = GapList<QueueEntry2>()
val alreadyChecked = mutableSetOf<Pos>()
var maxDistance = 0
// Move one step in every direction
Direction.entries.forEach { queue.add(QueueEntry2(it.from(pos), 1)) }
while (queue.isNotEmpty()) {
val current = queue.remove()
if (alreadyChecked.contains(current.pos)) continue
val result = map[current.pos]!!
alreadyChecked.add(current.pos)
if (result == '#') continue
maxDistance = max(maxDistance, current.stepsTaken)
Direction.entries.forEach {
val nextPos = it.from(current.pos)
if (!alreadyChecked.contains(nextPos)) {
queue.add(QueueEntry2(nextPos, current.stepsTaken + 1))
}
}
}
return maxDistance
}
fun solvePart1(): Int {
return makeMap(Droid(program)).first
}
fun solvePart2(): Int {
return makeMap(Droid(program)).let { maxDistanceFrom(it.second, it.third) }
}
} | 0 | Kotlin | 0 | 6 | f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22 | 3,816 | aoc | MIT License |
src/main/kotlin/days/Day4.kt | felix-ebert | 433,847,657 | false | {"Kotlin": 12718} | package days
class Day4 : Day(4) {
private val scores = getScores()
override fun partOne(): Any {
return scores.first
}
override fun partTwo(): Any {
return scores.second
}
private fun parseDrawnNumbers(str: String): List<Int> {
val regex = Regex("\\d+")
return regex.findAll(str).map { it.value.toInt() }.toList()
}
private fun parseBoards(): List<List<MutableList<Pair<Int, Boolean>>>> {
val boards = arrayListOf<List<MutableList<Pair<Int, Boolean>>>>()
var board = arrayListOf<MutableList<Pair<Int, Boolean>>>()
for (i in 2 until inputList.size) {
if (inputList[i].isEmpty()) {
boards.add(board)
board = arrayListOf()
continue
}
val numbersWithBoolean = parseDrawnNumbers(inputList[i]).map { Pair(it, false) }.toMutableList()
board.add(numbersWithBoolean)
}
boards.add(board)
return boards
}
private fun getScores(): Pair<Int, Int> {
val drawnNumbers = parseDrawnNumbers(inputList[0])
val boards = parseBoards()
val boardsWon = mutableSetOf<Int>()
val scores = mutableListOf<Int>()
drawnNumbers.forEach { drawnNumber ->
boards.forEachIndexed { boardNumber, board ->
board.forEach { row ->
row.forEachIndexed { x, number ->
if (number.first == drawnNumber) {
row[x] = row[x].copy(second = true)
}
if (board.map { it[x] }.all { it.second } || row.all { it.second }) {
if (boardsWon.add(boardNumber)) {
scores.add(board.flatten().filter { !it.second }.sumOf { it.first } * drawnNumber)
}
}
}
}
}
}
return Pair(scores.first(), scores.last())
}
}
| 0 | Kotlin | 0 | 2 | cf7535d1c4f8a327de19660bb3a9977750894f30 | 2,041 | advent-of-code-2021 | Creative Commons Zero v1.0 Universal |
src/main/kotlin/dayfour/DayFour.kt | Sasikuttan2163 | 434,187,872 | false | {"Kotlin": 7716} | package dayfour
import myutilities.Utils
import java.util.*
import kotlin.collections.ArrayList
fun main(){
val data = Utils.readFile("dayfour.txt")
val order = data[0].split(",").map { it.toInt() }.toList()
val matrix = Array(5) { IntArray(5) }
val matrices = ArrayList<Array<IntArray>>()
var index = 0
for (i in 1 until data.size) {
val line = data[i]
if(line == "") continue
val arr = line.chunked(3).stream().mapToInt { it.trim().toInt() }.toArray()
matrix[index++] = arr
if(index == 5) {
index = 0
matrices.add(matrix.clone())
}
}
val checkList = ArrayList<Int>()
var markedMatrixIndex = 0
first@ for(i in order.indices) {
val current = order[i]
checkList.add(current)
if(i < 5) continue
for(j in matrices.indices) {
if(isMarked(matrices[j], checkList)) {
markedMatrixIndex = j
break@first
}
}
}
var sum = 0
for(i in 0 until 5) {
for( j in 0 until 5){
val value = matrices[markedMatrixIndex][i][j]
if(!checkList.contains(value)) {
sum += value
}
}
}
println(sum * checkList[checkList.size - 1])
}
fun isMarked(matrix: Array<IntArray>, search: ArrayList<Int>): Boolean {
return hasMarkedRow(matrix, search) || hasMarkedColumn(matrix,search)
}
fun hasMarkedRow(matrix: Array<IntArray>, search: ArrayList<Int>): Boolean {
for(row in matrix) {
if(search.containsAll(row.toList())) {
return true
}
}
return false
}
fun hasMarkedColumn(matrix: Array<IntArray>, search: ArrayList<Int>): Boolean {
for(i in 0 until 5) {
val column = ArrayList<Int>()
for(j in 0 until 5) {
column.add(matrix[j][i])
}
if(search.containsAll(column)) {
return true
}
}
return false
} | 0 | Kotlin | 0 | 1 | 2894d4a5753472e5759b8d74d7480a611d0f05e5 | 1,985 | AoC-2021-Solutions-In-Kotlin | MIT License |
solver/src/commonMain/kotlin/org/hildan/sudoku/solver/HumanSolver.kt | joffrey-bion | 9,559,943 | false | {"Kotlin": 51198, "HTML": 187} | package org.hildan.sudoku.solver
import org.hildan.sudoku.model.Grid
import org.hildan.sudoku.model.removeValueFromSistersCandidates
import org.hildan.sudoku.solver.techniques.*
data class SolveResult(
val solved: Boolean,
val steps: List<Step>,
) {
override fun toString(): String = steps.joinToString("\n") {
"${it.techniqueName}:\n" + it.actions.joinToString("\n").prependIndent(" - ")
}
}
class HumanSolver(
private val orderedTechniques: List<Technique> = listOf(
NakedSingles,
HiddenSingles,
NakedPairs,
NakedTriples,
NakedQuads,
HiddenPairs,
HiddenTriples,
HiddenQuads,
PointingTuples,
BoxLineReduction,
XWing,
Swordfish,
Jellyfish,
Squirmbag,
)
) {
fun solve(grid: Grid): SolveResult {
val stillValid = grid.removeImpossibleCandidates()
require(stillValid) { "Incorrect clues in the given grid." }
val steps = mutableListOf<Step>()
while (!grid.isComplete) {
val result = orderedTechniques.firstApplicableTo(grid) ?: return SolveResult(solved = false, steps)
steps.addAll(result)
grid.performActions(result.flatMap { it.actions })
}
return SolveResult(solved = true, steps)
}
private fun List<Technique>.firstApplicableTo(grid: Grid) = asSequence()
.map { it.attemptOn(grid) }
.firstOrNull { it.isNotEmpty() }
}
fun Grid.performActions(actions: List<Action>) {
actions.forEach(::performAction)
}
private fun Grid.performAction(action: Action) {
when(action) {
is Action.PlaceDigit -> {
val cell = cells[action.cellIndex]
cell.value = action.digit
cell.removeValueFromSistersCandidates()
emptyCells.remove(cell)
}
is Action.RemoveCandidate -> {
val cell = cells[action.cellIndex]
cell.candidates.remove(action.candidate)
}
}
}
| 0 | Kotlin | 0 | 0 | 441fbb345afe89b28df9fe589944f40dbaccaec5 | 2,014 | sudoku-solver | MIT License |
src/Day06.kt | dmarcato | 576,511,169 | false | {"Kotlin": 36664} | fun main() {
fun findPacket(input: List<String>, numOfDistinct: Int): Int {
return input.first().asSequence().windowed(numOfDistinct, 1, true) { chunk ->
chunk.any { c ->
chunk.count { it == c } > 1
}
}.indexOfFirst { !it } + numOfDistinct
}
fun part1(input: List<String>): Int {
return findPacket(input, 4)
}
fun part2(input: List<String>): Int {
return findPacket(input, 14)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day06_test")
check(part1(testInput) == 7) { "part1 check failed" }
check(part2(testInput) == 19) { "part2 check failed" }
val input = readInput("Day06")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | 6abd8ca89a1acce49ecc0ca8a51acd3969979464 | 804 | aoc2022 | Apache License 2.0 |
src/chapter5/section2/ex8_OrderedOperationsForTries.kt | w1374720640 | 265,536,015 | false | {"Kotlin": 1373556} | package chapter5.section2
import chapter3.section1.OrderedST
import chapter5.section1.Alphabet
import edu.princeton.cs.algs4.Queue
/**
* 单词查找树的有序性操作
* 为TrieST实现floor()、ceiling()、rank()和select()方法(来自第3章标准有序符号表的API)
*/
class OrderedTrieST<V : Any>(alphabet: Alphabet) : TrieST<V>(alphabet), OrderedST<String, V> {
override fun min(): String {
return min(root, "") ?: throw NoSuchElementException()
}
private fun min(node: Node, key: String): String? {
if (node.value != null) return key
for (i in node.next.indices) {
if (node.next[i] != null) {
return min(node.next[i]!!, key + alphabet.toChar(i))
}
}
return null
}
override fun max(): String {
return max(root, "") ?: throw NoSuchElementException()
}
private fun max(node: Node, key: String): String? {
for (i in node.next.size - 1 downTo 0) {
if (node.next[i] != null) {
return max(node.next[i]!!, key + alphabet.toChar(i))
}
}
return if (node.value != null) key else null
}
override fun floor(key: String): String {
return floor(root, key, 0) ?: throw NoSuchElementException()
}
private fun floor(node: Node, key: String, d: Int): String? {
if (d == key.length) {
return if (node.value == null) null else key
}
val index = alphabet.toIndex(key[d])
val nextNode = node.next[index]
if (nextNode != null) {
val result = floor(nextNode, key, d + 1)
if (result != null) return result
}
for (i in index - 1 downTo 0) {
if (node.next[i] != null) {
return max(node.next[i]!!, key.substring(0, d) + alphabet.toChar(i))
}
}
return if (node.value == null) null else key.substring(0, d)
}
override fun ceiling(key: String): String {
return ceiling(root, key, 0) ?: throw NoSuchElementException()
}
private fun ceiling(node: Node, key: String, d: Int): String? {
if (d == key.length) {
return if (node.value == null) null else key
}
val index = alphabet.toIndex(key[d])
val nextNode = node.next[index]
if (nextNode == null) {
for (i in index + 1 until node.next.size) {
if (node.next[i] != null) {
return min(node.next[i]!!, key.substring(0, d) + alphabet.toChar(i))
}
}
return null
} else {
return ceiling(nextNode, key, d + 1) ?: min(nextNode, key.substring(0, d + 1))
}
}
override fun rank(key: String): Int {
return rank(root, key, 0)
}
private fun rank(node: TrieST<V>.Node, key: String, d: Int): Int {
if (d == key.length) return 0
val index = alphabet.toIndex(key[d])
var count = 0
for (i in 0 until index) {
val nextNode = node.next[i]
if (nextNode != null) {
count += size(nextNode)
}
}
if (node.value != null) count++
val nextNode = node.next[index]
if (nextNode != null) {
count += rank(nextNode, key, d + 1)
}
return count
}
private fun size(node: Node): Int {
var count = 0
node.next.forEach { nextNode ->
if (nextNode != null) {
count += size(nextNode)
}
}
return if (node.value == null) count else count + 1
}
override fun select(k: Int): String {
return select(root, k, "")
}
private fun select(node: Node, k: Int, key: String): String {
var count = if (node.value == null) 0 else 1
if (k == count - 1) return key
for (i in node.next.indices) {
val nextNode = node.next[i]
if (nextNode != null) {
val size = size(nextNode)
if (k < count + size) {
return select(nextNode, k - count, key + alphabet.toChar(i))
}
count += size
}
}
throw NoSuchElementException()
}
override fun deleteMin() {
delete(min())
}
override fun deleteMax() {
delete(max())
}
override fun size(low: String, high: String): Int {
if (low > high) return 0
return if (contains(high)) {
rank(high) - rank(low) + 1
} else {
rank(high) - rank(low)
}
}
override fun keys(low: String, high: String): Iterable<String> {
val queue = Queue<String>()
if (low > high) return queue
// 也可以先调用keys()方法获取所有键,再遍历依次所有元素判断是否在范围内
// 这里实现的方法比较麻烦,但效率较高
keys(root, queue, "", low, high, 0)
return queue
}
private fun keys(node: Node, queue: Queue<String>, key: String, low: String, high: String, d: Int) {
val minLength = minOf(low.length, high.length)
if (d == minLength) {
if (low.length > high.length) return
if (low.length == high.length) {
if (node.value != null) {
queue.enqueue(key)
}
return
}
val highIndex = alphabet.toIndex(high[d])
val highNode = node.next[highIndex]
if (highNode != null) {
keysLessThan(highNode, queue, key + alphabet.toChar(highIndex), high, d + 1)
}
return
}
val lowIndex = alphabet.toIndex(low[d])
val highIndex = alphabet.toIndex(high[d])
if (lowIndex == highIndex) {
// 跳过所有相同的前缀
val nextNode = node.next[lowIndex] ?: return
keys(nextNode, queue, key + alphabet.toChar(lowIndex), low, high, d + 1)
} else {
val lowNode = node.next[lowIndex]
if (lowNode != null) {
// 以lowNode为根结点,将所有大于low的元素加入队列
keysGreaterThan(lowNode, queue, key + alphabet.toChar(lowIndex), low, d + 1)
}
// 将lowIndex和highIndex范围内(不包含边界)的所有元素加入队列
for (i in lowIndex + 1 until highIndex) {
val nextNode = node.next[i]
if (nextNode != null) {
keys(nextNode, queue, key + alphabet.toChar(i))
}
}
val highNode = node.next[highIndex]
if (highNode != null) {
// 以highNode为根结点,将所有小于high的元素加入队列
keysLessThan(highNode, queue, key + alphabet.toChar(highIndex), high, d + 1)
}
}
}
private fun keysGreaterThan(node: Node, queue: Queue<String>, key: String, low: String, d: Int) {
if (d == low.length) {
keys(node, queue, key)
return
}
val index = alphabet.toIndex(low[d])
val nextNode = node.next[index]
if (nextNode != null) {
keysGreaterThan(nextNode, queue, key + low[d], low, d + 1)
}
for (i in index + 1 until node.next.size) {
val greaterNode = node.next[i]
if (greaterNode != null) {
keys(greaterNode, queue, key + alphabet.toChar(i))
}
}
}
private fun keysLessThan(node: Node, queue: Queue<String>, key: String, high: String, d: Int) {
if (d == high.length) {
if (node.value != null) {
queue.enqueue(key)
}
return
}
val index = alphabet.toIndex(high[d])
for (i in 0 until index) {
val lessNode = node.next[i]
if (lessNode != null) {
keys(lessNode, queue, key + alphabet.toChar(i))
}
}
if (node.value != null) queue.enqueue(key)
val nextNode = node.next[index]
if (nextNode != null) {
keysLessThan(nextNode, queue, key + high[d], high, d + 1)
}
}
}
fun main() {
testStringST { OrderedTrieST(Alphabet.EXTENDED_ASCII) }
testOrderedStringST { OrderedTrieST(Alphabet.EXTENDED_ASCII) }
} | 0 | Kotlin | 1 | 6 | 879885b82ef51d58efe578c9391f04bc54c2531d | 8,427 | Algorithms-4th-Edition-in-Kotlin | MIT License |
src/Day01.kt | irshea846 | 576,767,042 | false | null | fun main() {
fun part1(input: List<String>): Int {
return input.size
}
fun part2(input: List<List<Int>>): Int {
return input.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 1)
val input = readListCollection("Day01")
val bagsOfCalories: MutableList<Int> = mutableListOf()
input.forEach {
var sum = 0
it.forEach { sum += it }
bagsOfCalories.add(sum)
}
println(bagsOfCalories)
bagsOfCalories.sort()
var sumOfTop3Bags = 0
for (i in bagsOfCalories.size - 1 downTo bagsOfCalories.size -3) {
sumOfTop3Bags += bagsOfCalories[i]
}
println(bagsOfCalories[bagsOfCalories.size - 1])
println(sumOfTop3Bags)
}
| 0 | Kotlin | 0 | 0 | b48414d0cf9aedbb68e7423b7a01399b9a709659 | 813 | AoC | Apache License 2.0 |
src/cn/ancono/math/algebra/DecomposedPoly.kt | 140378476 | 105,762,795 | false | {"Java": 1912158, "Kotlin": 1243514} | package cn.ancono.math.algebra
import cn.ancono.math.numberModels.api.RealCalculator
import cn.ancono.math.numberModels.structure.Polynomial
/**
* Describes a polynomial that has the form of
* > (p1)^n1 * (p2)^n2 ... * (p^k)^nk
* where pi is a polynomial.
*
* Created at 2018/12/13 18:51
* @author liyicheng
*/
open class DecomposedPoly<T>(val decomposed: List<Pair<Polynomial<T>, Int>>) {
private var expandedBackingField: Polynomial<T>? = null
constructor(expanded: Polynomial<T>?, decomposed: List<Pair<Polynomial<T>, Int>>) : this(decomposed) {
expandedBackingField = expanded
}
/**
* The expanded form of this polynomial.
*/
val expanded: Polynomial<T>
get() {
if (expandedBackingField == null) {
expandedBackingField = decomposed.asSequence().map { (p, n) ->
p.pow(n.toLong())
}.reduce(Polynomial<T>::add)
}
return expandedBackingField!!
}
val degree: Int
get() {
return decomposed.sumOf { (p, n): Pair<Polynomial<T>, Int> -> p.degree * n }
}
fun compute(x: T): T {
val mc = decomposed.first().first.calculator
// var r = mc.one
return decomposed.asSequence().map { (p, n) ->
mc.pow(p.compute(x), n.toLong())
}.reduce(mc::multiply)
}
fun <N> map(newCalculator: RealCalculator<N>, mapper: (T) -> N): DecomposedPoly<N> {
val mp = java.util.function.Function(mapper)
val re = DecomposedPoly(decomposed.map { (poly, n) -> poly.mapTo(newCalculator, mp) to n })
re.expandedBackingField = expandedBackingField?.mapTo(newCalculator, mp)
return re
}
override fun toString(): String = decomposed.joinToString(separator = "*") { (x, p) ->
val t = "($x)"
if (p == 1) {
t
} else {
"$t^$p"
}
}
}
/**
* Describes a polynomial that has the form of
* > (p)^n
* where expanded is a polynomial.
*/
class SinglePoly<T>(expanded: Polynomial<T>?, base: Polynomial<T>, pow: Int) : DecomposedPoly<T>(expanded, listOf(base to pow)) {
constructor(base: Polynomial<T>) : this(base, base, 1)
val base: Polynomial<T>
get() = decomposed[0].first
val pow: Int
get() = decomposed[0].second
} | 0 | Java | 0 | 6 | 02c2984c10a95fcf60adcb510b4bf111c3a773bc | 2,348 | Ancono | MIT License |
src/Day05.kt | hrach | 572,585,537 | false | {"Kotlin": 32838} | @file:Suppress("NAME_SHADOWING")
fun main() {
data class Command(
val amount: Int,
val from: Int,
val to: Int,
)
fun parse(input: List<String>): Pair<List<MutableList<Char>>, List<Command>> {
val input = input.toMutableList()
val state = MutableList(
((input[0].length + 1) / 4) + 1
) { mutableListOf<Char>() }
while (input[0].isNotBlank()) {
if (input[0].contains("[").not()) {
input.removeAt(0)
break
}
repeat(state.size) {
val c = input[0].getOrNull(it * 4 + 1) ?: ' '
if (c != ' ') {
state[it].add(c)
}
}
input.removeAt(0)
}
input.removeAt(0)
val commands = input
.map {
val numbers = "\\d+".toRegex().findAll(it).toList()
Command(
amount = numbers[0].value.toInt(),
from = numbers[1].value.toInt(),
to = numbers[2].value.toInt(),
)
}
state.forEach { it.reverse() }
return state to commands
}
fun part1(input: List<String>): String {
val (state, command) = parse(input)
command.forEach {
val from = state[it.from - 1]
val to = state[it.to - 1]
val what = from.takeLast(it.amount)
repeat(it.amount) { from.removeLast() }
to.addAll(what.reversed())
}
return state.mapNotNull { it.lastOrNull() }.joinToString("")
}
fun part2(input: List<String>): String {
val (state, command) = parse(input)
command.forEach {
val from = state[it.from - 1]
val to = state[it.to - 1]
val what = from.takeLast(it.amount)
repeat(it.amount) { from.removeLast() }
to.addAll(what)
}
return state.mapNotNull { it.lastOrNull() }.joinToString("")
}
val testInput = readInput("Day05_test")
check(part1(testInput), "CMZ")
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 40b341a527060c23ff44ebfe9a7e5443f76eadf3 | 2,214 | aoc-2022 | Apache License 2.0 |
src/pl/shockah/aoc/y2019/Day4.kt | Shockah | 159,919,224 | false | null | package pl.shockah.aoc.y2019
import pl.shockah.aoc.AdventTask
class Day4: AdventTask<IntRange, Int, Int>(2019, 4) {
override fun parseInput(rawInput: String): IntRange {
val split = rawInput.split("-")
return split[0].toInt()..split[1].toInt()
}
private fun <T> Iterable<T>.groupDuplicates(): List<Pair<T, Int>> {
var last: T? = null
var count = 0
val results = mutableListOf<Pair<T, Int>>()
for (element in this) {
when {
count == 0 -> count++
last == element -> count++
else -> {
results += last!! to count
count = 1
}
}
last = element
}
results += last!! to count
return results
}
private fun isValid(password: String, range: IntRange, allowsTripleDigit: Boolean): Boolean {
fun containsDoubleDigit(): Boolean {
val results = password.toList().groupDuplicates()
if (allowsTripleDigit)
return results.any { it.second >= 2 }
else
return results.any { it.second == 2 }
}
fun isInRange(): Boolean {
return password.toInt() in range
}
return containsDoubleDigit() && isInRange()
}
private fun buildPasswords(current: String, digitsLeft: Int): List<String> {
fun getAllowedDigits(password: String): CharRange {
return if (password.isEmpty()) '0'..'9' else password.last()..'9'
}
if (digitsLeft == 0)
return listOf(current)
return getAllowedDigits(current).flatMap { buildPasswords(current + it, digitsLeft - 1) }
}
private fun task(input: IntRange, allowsTripleDigit: Boolean): Int {
return buildPasswords("", 6).filter { isValid(it, input, allowsTripleDigit) }.size
}
override fun part1(input: IntRange): Int {
return task(input, true)
}
override fun part2(input: IntRange): Int {
return task(input, false)
}
// TODO: tests
} | 0 | Kotlin | 0 | 0 | 9abb1e3db1cad329cfe1e3d6deae2d6b7456c785 | 1,755 | Advent-of-Code | Apache License 2.0 |
src/main/kotlin/Amphipod_23.kt | Flame239 | 433,046,232 | false | {"Kotlin": 64209} | import AmphipodType.valueOf
import kotlin.math.abs
import kotlin.math.min
private fun getAmphipodsState(filename: String, roomSize: Int): List<Amphipod> {
return readFile(filename).split("\n").drop(2).take(roomSize).flatMapIndexed { roomPos, s ->
s.filter { it != '#' && it != ' ' }.mapIndexed { room, c -> Amphipod(valueOf(c.toString()), room, roomPos) }
}
}
private val roomIdToPositionsInHallway = mapOf(
0 to 2,
1 to 4,
2 to 6,
3 to 8
) //(+ 1) * 2
private val roomPositionsInHallway = roomIdToPositionsInHallway.values
fun main() {
// TODO: mark amphs that are already in place
// None in my input
println(findMinEnergy(getAmphipodsState("Amphipod", 2)))
println(findMinEnergy(getAmphipodsState("Amphipod_full", 4)))
}
fun findMinEnergy(initState: List<Amphipod>): Int {
var minEnergySpent = Integer.MAX_VALUE
val visitedStates = hashMapOf(State(initState) to 0)
var states = listOf(State(initState))
while (states.isNotEmpty()) {
val nextStates = states.flatMap { nextStates(it, visitedStates) }
val (finished, notFinished) = nextStates.partition { it.finished }
val curMinEnergySpent = finished.minOfOrNull { it.energySpent } ?: Integer.MAX_VALUE
minEnergySpent = min(minEnergySpent, curMinEnergySpent)
states = notFinished
println("${states.size}")
}
return minEnergySpent
}
fun nextStates(state: State, visitedStates: HashMap<State, Int>): List<State> {
val nextStates = mutableListOf<State>()
state.amphipods.forEachIndexed { aIndex, a ->
if (a.inInitRoom && canGetOutOfTheRoom(state, a)) {
val initHallwayPos = roomIdToPositionsInHallway[a.initRoom]!!
val targetHallwayPos = roomIdToPositionsInHallway[a.type.targetRoom]!!
// shortcut: right to target room
if (canMoveToTargetRoom(state, a, initHallwayPos, targetHallwayPos)) {
val nextState = moveToTargetRoom(state, a, aIndex, initHallwayPos, targetHallwayPos, a.position + 1)
addStateIfNeeded(nextState, nextStates, visitedStates)
return@forEachIndexed
}
// can move only to hallway
for (hallwayPos in (initHallwayPos + 1) until 11) {
if (state.isHallwayPosOccupied(hallwayPos)) break
if (hallwayPos in roomPositionsInHallway) continue
val nextState = moveToHall(state, a, aIndex, initHallwayPos, hallwayPos)
addStateIfNeeded(nextState, nextStates, visitedStates)
}
for (hallwayPos in (initHallwayPos - 1) downTo 0) {
if (state.isHallwayPosOccupied(hallwayPos)) break
if (hallwayPos in roomPositionsInHallway) continue
val nextState = moveToHall(state, a, aIndex, initHallwayPos, hallwayPos)
addStateIfNeeded(nextState, nextStates, visitedStates)
}
} else if (a.inHallway) {
// can move only to target room
val targetHallwayPos = roomIdToPositionsInHallway[a.type.targetRoom]!!
if (!canMoveToTargetRoom(state, a, a.position, targetHallwayPos)) {
return@forEachIndexed
}
val nextState = moveToTargetRoom(state, a, aIndex, a.position, targetHallwayPos, 0)
addStateIfNeeded(nextState, nextStates, visitedStates)
} else if (a.inTargetRoom) {
// nothing to do here
}
}
return nextStates
}
fun moveToHall(state: State, a: Amphipod, aIndex: Int, initHallwayPos: Int, hallwayPos: Int): State {
val newAmphipodsState = state.amphipods.toMutableList()
newAmphipodsState[aIndex] = a.moveToHallway(hallwayPos)
val energySpend = ((a.position + 1) + abs(hallwayPos - initHallwayPos)) * a.type.energyPerMove
return State(newAmphipodsState, state.energySpent + energySpend)
}
fun moveToTargetRoom(
state: State,
a: Amphipod,
aIndex: Int,
initHallwayPos: Int,
targetHallwayPos: Int,
additionalSteps: Int
): State {
val newAmphipodsState = state.amphipods.toMutableList()
val siblings = state.amphipods.filter { s -> a.type == s.type && s.inTargetRoom }
val targetRoomPos = state.roomSize - 1 - siblings.size
newAmphipodsState[aIndex] = a.moveToTargetRoom(targetRoomPos)
val energySpent =
(additionalSteps + abs(targetHallwayPos - initHallwayPos) + (targetRoomPos + 1)) * a.type.energyPerMove
return State(newAmphipodsState, state.energySpent + energySpent)
}
fun canMoveToTargetRoom(state: State, a: Amphipod, initHallwayPos: Int, targetHallwayPos: Int): Boolean {
for (hallwayPos in initHallwayPos towardExclusiveFrom targetHallwayPos) {
if (state.isHallwayPosOccupied(hallwayPos)) return false
}
return canEnterTargetRoom(state, a)
}
fun canEnterTargetRoom(state: State, a: Amphipod) =
state.amphipods.none { it.inInitRoom && (it.initRoom == a.type.targetRoom) }
fun canGetOutOfTheRoom(state: State, a: Amphipod) =
state.amphipods.none { it.inInitRoom && it.initRoom == a.initRoom && it.position < a.position }
fun addStateIfNeeded(nextState: State, nextStates: MutableList<State>, visitedStates: HashMap<State, Int>) {
val energySpentInPrev = visitedStates[nextState]
// if we haven't yet reached this position or we reached it now with less spend energy than before
if (energySpentInPrev == null || nextState.energySpent < energySpentInPrev) {
visitedStates[nextState] = nextState.energySpent
nextStates.add(nextState)
}
}
class State(val amphipods: List<Amphipod>, val energySpent: Int = 0) {
val rooms = 4
val roomSize = amphipods.size / rooms
val finished: Boolean
get() = amphipods.all { it.inTargetRoom }
fun isHallwayPosOccupied(pos: Int) = amphipods.any { a -> a.inHallway && a.position == pos }
override fun equals(other: Any?): Boolean = amphipods.containsAll((other as State).amphipods)
override fun hashCode(): Int = amphipods.sumOf { it.hashCode() }
private fun repr(room: Int, pos: Int): String {
val occupants =
amphipods.filter { it.inInitRoom && it.initRoom == room || it.inTargetRoom && it.type.targetRoom == room }
.filter { it.position == pos }
return if (occupants.isEmpty()) " " else occupants[0].type.toString()
}
private val hallwayString: String
get() {
val template = StringBuilder("...........")
amphipods.filter { it.inHallway }.forEach { template[it.position] = it.type.toString()[0] }
return template.toString()
}
override fun toString(): String {
val s = StringBuilder(
"""
#${hallwayString}#
###${repr(0, 0)}#${repr(1, 0)}#${repr(2, 0)}#${repr(3, 0)}###
""".trimIndent()
)
for (row in 1 until roomSize) {
s.appendLine(" #${repr(0, row)}#${repr(1, row)}#${repr(2, row)}#${repr(3, row)}#")
}
return s.toString()
}
}
// hallway posititions are 0..10
// room positions are 0(upper) and 1 (lower)
data class Amphipod(
val type: AmphipodType,
val initRoom: Int,
val position: Int,
val inInitRoom: Boolean = true,
val inHallway: Boolean = false,
val inTargetRoom: Boolean = false,
) {
fun moveToHallway(hallwayPos: Int): Amphipod =
Amphipod(type, initRoom, hallwayPos, inInitRoom = false, inHallway = true, inTargetRoom = false)
fun moveToTargetRoom(roomPos: Int): Amphipod =
Amphipod(type, initRoom, roomPos, inInitRoom = false, inHallway = false, inTargetRoom = true)
}
enum class AmphipodType(val energyPerMove: Int, val targetRoom: Int) {
A(1, 0), B(10, 1), C(100, 2), D(1000, 3)
} | 0 | Kotlin | 0 | 0 | ef4b05d39d70a204be2433d203e11c7ebed04cec | 7,794 | advent-of-code-2021 | Apache License 2.0 |
src/advent/of/code/ThirdPuzzle.kt | 1nco | 725,911,911 | false | {"Kotlin": 112713, "Shell": 103} | package advent.of.code
import java.io.File
class ThirdPuzzle {
companion object {
private val day = "3";
private var input: MutableList<String> = arrayListOf();
private var sum = 0;
private var sumSecond = 0;
private var adjacentList = arrayListOf<Adjacent>();
fun solve() {
input.addAll(Reader.readInput(day));
var lineNum = 0;
input.forEach {
val lineSplit = it.split(".", "*", "/", "%", "+", "=", "-", "&", "#", "$", "@").filter { el -> el != "" };
var minIdx = 0;
lineSplit.forEach { lineSplitIter ->
var isThereSpecChar = false;
if (Regex("^[0-9]+\$").matches(lineSplitIter)) {
val firstIdx = it.indexOf(lineSplitIter, minIdx);
val lastIdx = firstIdx + lineSplitIter.length - 1
if (lineNum != 0) {
if (isThereSpecCharacter(input[lineNum - 1], firstIdx - 1, lastIdx + 1, lineNum - 1, Integer.parseInt(lineSplitIter))) {
isThereSpecChar = true;
};
}
if (isThereSpecCharacter(input[lineNum], firstIdx - 1, lastIdx + 1, lineNum, Integer.parseInt(lineSplitIter))) {
isThereSpecChar = true;
};
if (lineNum != input.size - 1) {
if (isThereSpecCharacter(input[lineNum + 1], firstIdx - 1, lastIdx + 1, lineNum + 1, Integer.parseInt(lineSplitIter))) {
isThereSpecChar = true;
};
}
if (isThereSpecChar) {
sum += Integer.parseInt(lineSplitIter);
}
minIdx = firstIdx;
}
}
lineNum++;
minIdx = 0;
}
var itemsToRemove = arrayListOf<Adjacent>();
adjacentList.forEach { el ->
if (adjacentList.filter { ele -> ele.pos == el.pos }.size != 2) {
itemsToRemove.addAll(adjacentList.filter { ele -> ele.pos == el.pos });
}
}
adjacentList.removeAll(itemsToRemove);
var alreadyMultiplied = arrayListOf<String>()
adjacentList.forEach { el ->
if (adjacentList.filter { ele -> ele.pos == el.pos }.size > 1 && !alreadyMultiplied.contains(el.pos)) {
val filteredList = adjacentList.filter { elem -> elem.pos == el.pos };
sumSecond += filteredList.first().value * filteredList.last().value
alreadyMultiplied.add(el.pos);
}
}
// I don't know why my code didn't consider these gears, so adding them manually :D
sumSecond += (530*664) + (664*121) + (552*94) + (993*9) +(540*434) + (834*817) + (4*719);
System.out.println("sumSecond: " + sumSecond);
var output = arrayListOf<String>();
val file = File("out/production/advent-of-code/advent/of/code/" + "inputs/" + "test" + ".txt")
var inpline = 0;
input.forEach { inp ->
var line = inp;
alreadyMultiplied.forEach { already ->
// var inp = input[Integer.parseInt(alreadyMultiplied.split(",")[0])]
val idx = Integer.parseInt(already.split(",")[1]);
if (line[idx].toString().contains("*") && inpline == Integer.parseInt(already.split(",")[0])) {
line = line.replaceRange(idx, idx + 1, "T");
}
}
output.add(line);
inpline++;
}
file.printWriter().use { out ->
output.forEach { line ->
out.println(line);
}
};
}
private fun isThereSpecCharacter(line: String, firstIdx: Int, secondIdx: Int, lineNum: Int, number: Int): Boolean {
val substr = line.substring(if (firstIdx < 0) 0 else firstIdx, if (secondIdx > line.length - 1) line.length else secondIdx + 1);
val containsSpecial = substr.contains(Regex("[^0-9.]+"));
if (substr.contains("*")) {
var posOffset = 0;
substr.forEach {
if (it.toString().contains("*")) {
val pos = ((if (firstIdx < 0) 0 else firstIdx) + posOffset);
// if (adjacentList.filter { eloo -> eloo.pos == "$lineNum,$pos" && eloo.value == number }.size == 0) {
adjacentList.add(Adjacent("$lineNum,$pos", number));
// }
}
posOffset++
}
}
return containsSpecial;
}
}
}
class Adjacent(pos: String, value: Int) {
var pos: String;
var value: Int;
init {
this.pos = pos;
this.value = value;
}
} | 0 | Kotlin | 0 | 0 | 0dffdeba1ebe0b44d24f94895f16f0f21ac8b7a3 | 5,207 | advent-of-code | Apache License 2.0 |
problems/binary-search-tree-check/binary-search-tree-check.kt | mre | 14,571,395 | false | {"Python": 149850, "JavaScript": 52163, "Rust": 22731, "Java": 18047, "Kotlin": 17919, "C++": 16563, "CoffeeScript": 16079, "PHP": 14313, "C#": 14295, "Shell": 11341, "Go": 8067, "Ruby": 5883, "C": 4745, "F#": 4418, "Swift": 1811, "Haskell": 1585, "TypeScript": 1405, "Scala": 1394, "Dart": 1025, "LOLCODE": 647, "Julia": 559, "Makefile": 521} | import java.util.Stack
import kotlin.test.assertFalse
import kotlin.test.assertTrue
class TreeStack<T : Comparable<T>>(treeNode: TreeNode<T>) : Stack<Triple<TreeNode<T>, T?, T?>>() {
init {
push(treeNode)
}
inline fun drain(action: TreeStack<T>.(node: TreeNode<T>, min: T?, max: T?) -> Unit) {
while (isNotEmpty()) pop().also { (node, min, max) -> action(node, min, max) }
}
fun push(node: TreeNode<T>, min: T? = null, max: T? = null) = apply {
push(Triple(node, min, max))
}
}
data class TreeNode<T : Comparable<T>>(
val value: T,
val left: TreeNode<T>? = null,
val right: TreeNode<T>? = null
) {
fun isBalancedBinarySearchTree(duplicates: Boolean = false): Boolean {
if (!(left == null && right == null)) {
TreeStack(this).drain { node, min, max ->
min?.let { if (it >= node.value) return false }
max?.let { if ((!duplicates && it == node.value) || it < node.value) return false }
node.left?.let { push(it, max = node.value) }
node.right?.let { push(it, min = node.value) }
}
}
return true
}
}
fun main(args: Array<String>) {
assertTrue(TreeNode(1).isBalancedBinarySearchTree())
assertTrue(TreeNode(2, TreeNode(1)).isBalancedBinarySearchTree())
assertTrue(TreeNode(2, right = TreeNode(3)).isBalancedBinarySearchTree())
assertFalse(TreeNode(4, TreeNode(4)).isBalancedBinarySearchTree())
assertTrue(TreeNode(4, TreeNode(4)).isBalancedBinarySearchTree(duplicates = true))
// right node cannot be equal to parent
assertFalse(TreeNode(4, right = TreeNode(4)).isBalancedBinarySearchTree(duplicates = true))
// degenerated trees are still balanced
assertTrue(TreeNode(4, TreeNode(3, TreeNode(2, TreeNode(1)))).isBalancedBinarySearchTree())
TreeNode(
300,
TreeNode(
200,
TreeNode(100, TreeNode(50), TreeNode(150)),
TreeNode(250, right = TreeNode(275))
),
TreeNode(
400,
TreeNode(350),
TreeNode(500, TreeNode(450), TreeNode(600))
)
).apply { assertTrue(isBalancedBinarySearchTree()) }
}
| 8 | Python | 413 | 1,636 | e879e0949a24da5ebc80e9319683baabf8bb0a37 | 2,225 | the-coding-interview | MIT License |
src/main/kotlin/day4/Day4.kt | jakubgwozdz | 571,298,326 | false | {"Kotlin": 85100} | package day4
import execute
import parseRecords
import readAllText
fun main() {
val input = readAllText("local/day2_input.txt")
val test = """
2-4,6-8
2-3,4-5
5-7,7-9
2-8,3-7
6-6,4-6
2-6,4-8
""".trimIndent()
execute(::part1, test, 157)
execute(::part1, input)
execute(::part2, test, 70)
execute(::part2, input)
}
private val regex = "(\\d+)-(\\d+),(\\d+)-(\\d+)".toRegex()
private fun buildRecord(matchResult: MatchResult) =
matchResult.destructured.let { (a, b, c, d) ->
(a.toInt()..b.toInt()) to (c.toInt()..d.toInt())
}
fun part1(input: String) = input.parseRecords(regex, ::buildRecord)
.count { (s1, s2) -> s1 isInside s2 || s2 isInside s1 }
private infix fun IntRange.isInside(other: IntRange) = first in other && last in other
fun part2(input: String) = input.parseRecords(regex, ::buildRecord)
.count { (s1, s2) -> s1 overlaps s2 }
private infix fun IntRange.overlaps(other: IntRange) =
first in other || last in other || other.first in this || other.last in this
| 0 | Kotlin | 0 | 0 | 7589942906f9f524018c130b0be8976c824c4c2a | 1,083 | advent-of-code-2022 | MIT License |
src/me/bytebeats/algo/kt/Solution12.kt | bytebeats | 251,234,289 | false | null | package me.bytebeats.algo.kt
import me.bytebeats.algs.ds.TreeNode
/**
* @Author bytebeats
* @Email <<EMAIL>>
* @Github https://github.com/bytebeats
* @Created on 2020/12/14 20:31
* @Version 1.0
* @Description TO-DO
*/
class Solution12 {
fun findSubArray(arr: IntArray, target: Int): Int {
var minL = Int.MAX_VALUE
val size = arr.size
for (i in 0 until size) {
var sum = arr[i]
var tmp = 1
for (j in i + 1 until size) {
if (sum >= target && tmp < minL) {
minL = tmp
break
}
sum += arr[j]
tmp += 1
}
if (sum >= target && tmp < minL) {
minL = tmp
}
}
return minL
}
fun findSubArray1(arr: IntArray, target: Int): Int {
var minL = Int.MAX_VALUE
var i = 0
var j = 0
var sum = 0
while (j < arr.size) {
sum += arr[j]
if (sum >= target) {
if (j - i + 1 < minL) {
minL = j - i + 1
}
while (sum >= target) {
sum -= arr[i++]
}
}
j++
}
return minL
}
fun lengthOfLongestSubstring(s: String): Int {//3
var max = 0
if (s.isNotEmpty()) {
val set = mutableSetOf<Char>()
var j = 0
val size = s.length
for (i in 0 until size) {
if (i != 0) {
set.remove(s[i - 1])
}
while (j < size && !set.contains(s[j])) {
set.add(s[j])
j += 1
}
if (set.size > max) {
max = set.size
}
}
}
return max
}
fun arrayStringsAreEqual(word1: Array<String>, word2: Array<String>): Boolean {//1662
return word1.joinToString(separator = "") == word2.joinToString(separator = "")
}
fun getMaximumGenerated(n: Int): Int {//1646
if (n < 2) {
return n
}
val arr = IntArray(n + 1)
arr[0] = 0
arr[1] = 1
var max = 1
for (i in 2..n) {
if (i and 1 == 0) {
arr[i] = arr[i / 2]
} else {
arr[i] = arr[i / 2] + arr[i / 2 + 1]
}
max = max.coerceAtLeast(arr[i])
}
return max
}
fun countVowelStrings(n: Int): Int {//1641
return (n + 4) * (n + 3) * (n + 2) * (n + 1) / 24
}
fun halvesAreAlike(s: String): Boolean {//1704
val half = s.length / 2
var vowels1 = 0
var vowels2 = 0
for (i in 0 until half) {
if (isVowel(s[i].toLowerCase())) {
vowels1 += 1
}
if (isVowel(s[i + half])) {
vowels2 += 1
}
}
return vowels1 == vowels2
}
private fun isVowel(ch: Char): Boolean {
return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u'
|| ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U'
}
fun closeStrings(word1: String, word2: String): Boolean {//1657
val length = word1.length
if (length != word2.length) return false
val arr1 = IntArray(26)
val arr2 = IntArray(26)
for (i in 0 until length) {
arr1[word1[i] - 'a'] += 1
arr2[word2[i] - 'a'] += 1
}
for (i in 0 until 26) {
if (arr1[i] != 0 && arr2[i] == 0 || arr1[i] == 0 && arr2[i] != 0) {
return false
}
}
arr1.sort()
arr2.sort()
for (i in 0 until 26) {
if (arr1[i] != arr2[i]) {
return false
}
}
return true
}
fun concatenatedBinary(n: Int): Int {//1680
val mod = 1000000007
var res = 0
var shift = 0
for (i in 1..n) {
if (i and (i - 1) == 0) {
shift += 1
}
res = (((res.toLong() shl shift) + i) % mod).toInt()
}
return res
}
fun getSmallestString(n: Int, k: Int): String {//1663
val ans = CharArray(n) { 'a' }
val bound = (k - n) / 25
val rest = (k - n) % 25
if (n - bound - 1 >= 0) ans[n - bound - 1] = 'a' + rest
for (i in n - bound until n) {
ans[i] = 'z'
}
return String(ans)
}
fun medianSlidingWindow(nums: IntArray, k: Int): DoubleArray {//480
val size = nums.size
val window = mutableListOf<Int>()
val ans = DoubleArray(size - k + 1)
for (i in 0 until k - 1) {
window.add(nums[i])
}
window.sort()
for (i in 0..size - k) {
val e = nums[i + k - 1]
if (window.isEmpty()) {
window.add(e)
} else if (e <= window.first()) {
window.add(0, e)
} else if (e >= window.last()) {
window.add(e)
} else {
for (j in 0 until k - 1) {
if (e <= window[j]) {
window.add(j, e)
break
}
}
}
if (k and 1 == 0) {
ans[i] = (window[(k - 1) / 2].toDouble() + window[(k - 1) / 2 + 1].toDouble()) / 2.0
} else {
ans[i] = window[(k - 1) / 2].toDouble()
}
for (j in 0 until k) {
if (window[j] == nums[i]) {
window.removeAt(j)
break
}
}
}
return ans
}
fun simplifyPath(path: String): String {//71
val stack = mutableListOf<String>()
for (p in path.split("/")) {
if (p.isEmpty()) {
continue
} else if (p == ".") {
continue
} else if (p == "..") {
if (stack.isNotEmpty()) {
stack.removeAt(stack.lastIndex)
}
} else {
stack.add(p)
}
}
return stack.joinToString(separator = "/", prefix = "/")
}
fun validateStackSequences(pushed: IntArray, popped: IntArray): Boolean {//946
val stack = mutableListOf<Int>()
val size = pushed.size
var j = 0
for (i in 0 until size) {
stack.add(pushed[i])
while (stack.isNotEmpty() && j < size && stack.last() == popped[j]) {
stack.removeAt(stack.lastIndex)
j++
}
}
return j == size
}
fun evalRPN(tokens: Array<String>): Int {//150
val stack = mutableListOf<Int>()
var first = 0
var second = 0
for (token in tokens) {
if (token == "+") {
second = stack.removeAt(stack.lastIndex)
first = stack.removeAt(stack.lastIndex)
stack.add(first + second)
} else if (token == "-") {
second = stack.removeAt(stack.lastIndex)
first = stack.removeAt(stack.lastIndex)
stack.add(first - second)
} else if (token == "*") {
second = stack.removeAt(stack.lastIndex)
first = stack.removeAt(stack.lastIndex)
stack.add(first * second)
} else if (token == "/") {
second = stack.removeAt(stack.lastIndex)
first = stack.removeAt(stack.lastIndex)
stack.add(first / second)
} else {
stack.add(token.toInt())
}
}
return stack.last()
}
fun wordSubsets(A: Array<String>, B: Array<String>): List<String> {//916
val ans = mutableListOf<String>()
val bmax = count("")
for (s in B) {
val bCount = count(s)
for (i in 0 until 26) {
bmax[i] = bmax[i].coerceAtLeast(bCount[i])
}
}
for (s in A) {
val aCount = count(s)
var toAdd = true
for (i in 0 until 26) {
if (aCount[i] < bmax[i]) {
toAdd = false
break
}
}
if (toAdd) {
ans.add(s)
}
}
return ans
}
private fun count(s: String): IntArray {
val ans = IntArray(26)
for (c in s) {
ans[c - 'a'] += 1
}
return ans
}
fun clumsy(N: Int): Int {//1006
var ans = 0
var n = N
var plus = true
while (n > 3) {
val tmp = n * (n - 1) / (n - 2)
if (plus) {
plus = !plus
ans += tmp
} else {
ans -= tmp
}
ans += n - 3
n -= 4
}
if (plus)
when (n) {
3 -> ans += 3 * 2 / 1
2 -> ans += 2 * 1
1 -> ans += 1
}
else
when (n) {
3 -> ans -= 3 * 2 / 1
2 -> ans -= 2 * 1
1 -> ans -= 1
}
return ans
}
fun trap(height: IntArray): Int {//17.21, 48
var ans = 0
var left = 0
var right = height.size - 1
var leftMax = 0
var rightMax = 0
while (left < right) {
leftMax = leftMax.coerceAtLeast(height[left])
rightMax = rightMax.coerceAtLeast(height[right])
if (height[left] < height[right]) {
ans += leftMax - height[left]
left += 1
} else {
ans += rightMax - height[right]
right -= 1
}
}
return ans
}
fun findMaxForm(strs: Array<String>, m: Int, n: Int): Int {//474
val dp = Array(m + 1) { IntArray(n + 1) }
for (str in strs) {
val cs = countDigits(str)
for (zeros in m downTo cs[0]) {
for (ones in n downTo cs[1]) {
dp[zeros][ones] = dp[zeros][ones].coerceAtLeast(1 + dp[zeros - cs[0]][ones - cs[1]])
}
}
}
return dp[m][n]
}
private fun countDigits(str: String): IntArray {
val cs = IntArray(2)
for (c in str) {
cs[c - '0']++
}
return cs
}
fun purchasePlans(nums: IntArray, target: Int): Int {
val mod = 1000000007
var ans = 0
nums.sort()
var i = 0
var j = nums.lastIndex
while (i < j) {
var icount = 1
while (i + 1 < j && nums[i + 1] == nums[i]) {
i += 1
icount += 1
}
var jcount = 1
while (i < j - 1 && nums[j - 1] == nums[j]) {
j -= 1
jcount += 1
}
if (nums[i] + nums[j] <= target) {
ans += icount * jcount
ans %= mod
ans = (ans + mod) % mod
i += 1
j -= 1
} else {
j -= 1
}
}
return ans
}
fun purchasePlans2(nums: IntArray, target: Int): Int {
val mod = 1000000007
var ans = 0
val size = nums.size
for (i in 0 until size - 1) {
for (j in i + 1 until size) {
if (nums[i] + nums[j] <= target) {
ans += 1
} else break
}
}
return (ans % mod + mod) % mod
}
fun minOperations(n: Int): Int {//1551
var ans = 0
for (i in 0 until n) {
val x = 2 * i + 1
if (x > n) {
ans += x - n
}
}
return ans
}
fun checkIfPangram(sentence: String): Boolean {//1832
val counts = IntArray(26)
for (c in sentence) {
counts[c - 'a'] += 1
}
return counts.all { it > 0 }
}
fun countConsistentStrings(allowed: String, words: Array<String>): Int {//1684
val allowedCounts = count(allowed)
var count = 0
for (word in words) {
val wordCounts = count(word)
if (greaterOrEqual(allowedCounts, wordCounts)) {
count += 1
}
}
return count
}
private fun greaterOrEqual(allowed: IntArray, word: IntArray): Boolean {
for (i in 0 until 26) {
if (allowed[i] == 0 && word[i] != 0) {
return false
}
}
return true
}
fun minDistance(word1: String, word2: String): Int {//583
val m = word1.length
val n = word2.length
val dp = Array(m + 1) { IntArray(n + 1) }
for (i in 1..m) {
for (j in 1..n) {
dp[i][j] = if (word1[i - 1] == word2[j - 1]) {
dp[i - 1][j - 1] + 1
} else {
dp[i - 1][j].coerceAtLeast(dp[i][j - 1])
}
}
}
return m + n - 2 * dp[m][n]
}
fun xorOperation(n: Int, start: Int): Int {//1486
var ans = 0
for (i in 0 until n) {
ans = ans xor (start + i * 2)
}
return ans
}
fun sumOfUnique(nums: IntArray): Int {//1748
val counts = mutableMapOf<Int, Int>()
for (num in nums) {
counts.compute(num) { _, v -> if (v == null) 1 else v + 1 }
}
return counts.entries.filter { it.value == 1 }.map { it.key }.sum()
}
fun truncateSentence(s: String, k: Int): String {//1816
var count = 0
var idx = -1
for (i in s.indices) {
if (s[i] == ' ') {
count += 1
}
if (count >= k) {
idx = i
break
}
}
if (idx == -1) {
return s
} else {
return s.substring(0, idx)
}
}
fun sumBase(n: Int, k: Int): Int {//1837
var nn = n
var sum = 0
while (nn != 0) {
sum += nn % k
nn /= k
}
return sum
}
fun specialArray(nums: IntArray): Int {//1608
for (i in 0..nums.size) {
var count = 0
for (j in 0 until nums.size) {
if (nums[j] >= i) {
count++
}
}
if (count == i) {
return i
}
}
return -1
}
fun frequencySort(nums: IntArray): IntArray {//1636
val freqs = mutableMapOf<Int, Int>()
for (num in nums) {
freqs.compute(num) { _, v -> if (v == null) 1 else v + 1 }
}
val comparator = Comparator<Int> { o1, o2 ->
val f1 = freqs[o1]!!
val f2 = freqs[o2]!!
if (f1 == f2) {
return@Comparator if (o1 > o2) -1 else if (o1 == o2) 0 else 1
} else {
return@Comparator if (f1 > f2) 1 else if (f1 == f2) 0 else -1
}
}
return nums.sortedWith(comparator).toIntArray()
}
fun slowestKey(releaseTimes: IntArray, keysPressed: String): Char {//1629
val n = releaseTimes.size
var max = 0
var code = ' '
for (i in 0 until n) {
val k = keysPressed[i]
val time = if (i == 0) releaseTimes[0] else releaseTimes[i] - releaseTimes[i - 1]
if (max < time || (max == time && code < k)) {
max = time
code = k
}
}
return code
}
fun decode(encoded: IntArray): IntArray {//1734
val size = encoded.size
val perm = IntArray(size + 1)
var total = 0
for (i in 1..size + 1) {
total = total xor i
}
var odd = 0
for (i in 1 until size step 2) {
odd = odd xor encoded[i]
}
perm[0] = total xor odd
for (i in 0 until size) {
perm[i + 1] = perm[i] xor encoded[i]
}
return perm
}
fun xorQueries(arr: IntArray, queries: Array<IntArray>): IntArray {//1310
val ansSize = queries.size
val size = arr.size
for (i in 1 until size) {
arr[i] = arr[i] xor arr[i - 1]
}
val ans = IntArray(ansSize)
for (i in 0 until ansSize) {
val left = queries[i][0]
val right = queries[i][1]
if (left > 0) {
ans[i] = arr[left - 1] xor arr[right]
} else {
ans[i] = arr[right]
}
}
return ans
}
fun countGoodRectangles(rectangles: Array<IntArray>): Int {//1725
var maxLength = 0
var maxCount = 0
for (r in rectangles) {
val min = r[0].coerceAtMost(r[1])
if (min > maxLength) {
maxLength = min
maxCount = 1
} else if (min == maxLength) {
maxCount++
}
}
return maxCount
}
fun numDifferentIntegers(word: String): Int {//1805
val nums = mutableSetOf<String>()
var left = -1
var right = 0
while (right < word.length) {
if (word[right].isDigit()) {
if (left == -1) {
left = right
}
right++
} else {
if (left == -1) {
right++
} else {
while (left < right && word[left] == '0') {
left++
}
if (left <= right) {
nums.add(word.substring(left, right))
}
left = -1
right++
}
}
}
if (left != -1) {
while (left < right && word[left] == '0') {
left++
}
if (left <= right) {
nums.add(word.substring(left, right))
}
}
return nums.size
}
private var count = 0
fun findTargetSumWays(nums: IntArray, target: Int): Int {//494
count = 0
findTargetSumWays(nums, target, 0, 0)
return count
}
fun findTargetSumWays(nums: IntArray, target: Int, sum: Int, index: Int) {//494
if (index >= nums.size) return
if (index == nums.size - 1) {
if (sum + nums[index] == target) count++
if (sum - nums[index] == target) count++
} else {
findTargetSumWays(nums, target, sum + nums[index], index + 1)
findTargetSumWays(nums, target, sum - nums[index], index + 1)
}
}
fun minOperations(logs: Array<String>): Int {//1598
var count = 0
for (log in logs) {
if (log == "../") {
if (count > 0) {
count--
} else {
continue
}
} else if (log == "./") {
continue
} else {
count++
}
}
return count
}
fun maxDepth(s: String): Int {//1614
var max = 0
var depth = 0
for (c in s) {
if (c == '(') {
depth++
max = max.coerceAtLeast(depth)
} else if (c == ')') {
depth--
}
}
return max
}
fun trimMean(arr: IntArray): Double {//1619
val count2Remove = arr.size / 20
arr.sort()
return arr.drop(count2Remove).dropLast(count2Remove).average()
}
fun maxLengthBetweenEqualCharacters(s: String): Int {//1624
var max = -1
var width = -1
for (i in 0 until s.lastIndex) {
width = -1
for (j in i + 1 until s.length) {
if (s[i] == s[j]) {
width = j - i - 1
max = max.coerceAtLeast(width)
}
}
}
return max
}
fun decrypt(code: IntArray, k: Int): IntArray {//1652
val size = code.size
val ans = IntArray(size) { 0 }
if (k != 0) {
for (i in 0 until size) {
var s = 0
var e = 0
if (k > 0) {
s = i + 1
e = i + k
} else {
s = i + k
e = i - 1
}
for (j in s..e) {
ans[i] += code[(j % size + size) % size]
}
}
}
return ans
}
fun maxRepeating(sequence: String, word: String): Int {//1668
var count = 0
val container = StringBuilder(word)
while (sequence.contains(container)) {
count++
container.append(word)
}
return count
}
fun maximumWealth(accounts: Array<IntArray>): Int {//1672
var maxAssets = 0
for (account in accounts) {
val assets = account.sum()
if (assets > maxAssets) {
maxAssets = assets
}
}
return maxAssets
}
fun interpret(command: String): String {//1678
return command.replace("()", "").replace("(al)", "al")
}
fun numberOfMatches(n: Int): Int {//1688
var loop = 0
var nn = n
while (nn > 1) {
if (nn and 1 == 0) {
nn = nn shr 1
loop += nn
} else {
nn = (nn + 1) shr 1
loop += nn - 1
}
}
return loop
}
fun grayCode(n: Int): List<Int> {//89
val ans = mutableListOf<Int>()
ans.add(0)
var head = 1
for (i in 0 until n) {
for (j in ans.lastIndex downTo 0) {
ans.add(head + ans[j])
}
head = head shl 1
}
return ans
}
fun maxIceCream(costs: IntArray, coins: Int): Int {//1833
var ans = 0
costs.sort()
var left = coins
for (cost in costs) {
if (left >= cost) {
ans += 1
left -= cost
} else {
break
}
}
return ans
}
fun minPairSum(nums: IntArray): Int {//1877
nums.sort()
var max = nums.first() + nums.last()
for (i in 1 until nums.size / 2) {
max = max.coerceAtLeast(nums[i] + nums[nums.size - 1 - i])
}
return max
}
fun pruneTree(root: TreeNode?): TreeNode? {//814
return if (contains1(root)) root else null
}
private fun contains1(node: TreeNode?): Boolean {
if (node == null) return false
val hasLeft = contains1(node.left)
val hasRight = contains1(node.right)
if (!hasLeft) node.left = null
if (!hasRight) node.right = null
return node.`val` == 1 || hasLeft || hasRight
}
fun isCovered(ranges: Array<IntArray>, left: Int, right: Int): Boolean {//1893
val diff = IntArray(52)
for (range in ranges) {
diff[range[0]]++
diff[range[1] + 1]--
}
var preSum = 0
for (i in 1..50) {
preSum += diff[i]
if (i in left..right && preSum <= 0) {
return false
}
}
return true
}
fun beautifulArray(n: Int): IntArray {//932
val map = mutableMapOf<Int, IntArray>()
return f(n, map)
}
private fun f(n: Int, map: MutableMap<Int, IntArray>): IntArray {
if (map.containsKey(n)) return map[n]!!
val ans = IntArray(n)
if (n == 1) {
ans[0] = 1
} else {
var t = 0
for (x in f((n + 1) / 2, map)) {
ans[t++] = x * 2 - 1
}
for (x in f(n / 2, map)) {
ans[t++] = x * 2
}
}
map[n] = ans
return ans
}
private val parents = mutableMapOf<Int, TreeNode>()
val ans = mutableListOf<Int>()
fun distanceK(root: TreeNode?, target: TreeNode?, k: Int): List<Int> {//863
findParents(root)
findAns(target, null, 0, k)
return ans
}
private fun findParents(node: TreeNode?) {
if (node?.left != null) {
parents[node.left.`val`] = node
findParents(node.left)
}
if (node?.right != null) {
parents[node.right.`val`] = node
findParents(node.right)
}
}
private fun findAns(node: TreeNode?, from: TreeNode?, depth: Int, k: Int) {
if (node == null) return
if (depth == k) {
ans.add(node.`val`)
return
}
if (node.left != from) {
findAns(node.left, node, depth + 1, k)
}
if (node.right != null) {
findAns(node.right, node, depth + 1, k)
}
if (parents[node.`val`] != from) {
findAns(parents[node.`val`], node, depth + 1, k)
}
}
fun findUnsortedSubarray(nums: IntArray): Int {//581
val n = nums.size
var maxn = Int.MIN_VALUE
var right = -1
var minn = Int.MAX_VALUE
var left = -1
for (i in 0 until n) {
if (maxn > nums[i]) {
right = i
} else {
maxn = nums[i]
}
if (minn < nums[n - 1 - i]) {
left = n - i - 1
} else {
minn = nums[n - i - 1]
}
}
return if (right == -1) 0 else right - left + 1
}
fun eventualSafeNodes(graph: Array<IntArray>): List<Int> {//802
val n = graph.size
val rg = Array<MutableList<Int>>(n) { mutableListOf() }
val inDegrees = IntArray(n){ 0 }
for (i in graph.indices) {
for (j in graph[i]) {
rg[j].add(i)
}
inDegrees[i] = graph[i].size
}
val queue = mutableListOf<Int>()
for (i in inDegrees.indices) {
if (inDegrees[i] == 0) {
queue.add(i)
}
}
while (queue.isNotEmpty()) {
val p = queue.removeAt(0)
for (i in rg[p]) {
if (--inDegrees[i] == 0) {
queue.add(i)
}
}
}
val ans = mutableListOf<Int>()
for (i in 0 until n) {
if (inDegrees[i] == 0) {
ans.add(i)
}
}
return ans
}
} | 0 | Kotlin | 0 | 1 | 7cf372d9acb3274003bb782c51d608e5db6fa743 | 27,003 | Algorithms | MIT License |
src/main/kotlin/recursion/AndroidUnlockPatterns.kt | e-freiman | 471,473,372 | false | {"Kotlin": 78010} | package recursion
private val visited = BooleanArray(9) {false}
fun valid(i: Int, j: Int, ni: Int, nj: Int): Boolean {
val di = Math.abs(i - ni)
val dj = Math.abs(j - nj)
return if ((di == 2 && dj == 2) || (di == 0 && dj == 2) || (di == 2 && dj == 0)) {
val mi = (i + ni) / 2
val mj = (j + nj) / 2
visited[3 * mi + mj]
} else {
true
}
}
fun traverse(i: Int, j: Int, m: Int, n: Int, length: Int): Int {
visited[3 * i + j] = true
var counter = 0
if (length >= m && length <= n) {
counter++
}
for (ni in 0..2) {
for (nj in 0..2) {
if (!visited[3 * ni + nj] && valid(i, j, ni, nj)) {
counter += traverse(ni, nj, m, n, length + 1)
}
}
}
visited[3 * i + j] = false
return counter
}
fun numberOfPatterns(m: Int, n: Int): Int {
var counter = 0
for (i in 0..2) {
for (j in 0..2) {
counter += traverse(i, j, m, n, 1)
}
}
return counter
}
fun main() {
println(numberOfPatterns(1, 2))
}
| 0 | Kotlin | 0 | 0 | fab7f275fbbafeeb79c520622995216f6c7d8642 | 1,080 | LeetcodeGoogleInterview | Apache License 2.0 |
src/main/kotlin/Day03.kt | gijs-pennings | 573,023,936 | false | {"Kotlin": 20319} | fun main() {
val lines = readInput(3)
println(part1(lines.map { it.chunked(it.length / 2) }))
println(part1(lines.chunked(3).map { listOf(it[0].intersect(it[1]), it[2]) }))
}
private fun part1(rucksacks: List<List<String>>) = rucksacks
.map { it[0].intersect(it[1]).first() }
.sumOf { if (it.isLowerCase()) it - 'a' + 1 else it - 'A' + 27 }
private fun String.intersect(s: String) = toList().intersect(s.toSet()).joinToString("")
| 0 | Kotlin | 0 | 0 | 8ffbcae744b62e36150af7ea9115e351f10e71c1 | 452 | aoc-2022 | ISC License |
src/main/kotlin/com/hj/leetcode/kotlin/problem2224/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem2224
/**
* LeetCode page: [2224. Minimum Number of Operations to Convert Time](https://leetcode.com/problems/minimum-number-of-operations-to-convert-time/);
*/
class Solution {
private val incrementInMinutesDescending = listOf(60, 15, 5, 1)
/* Complexity:
* Time O(1) and Space O(1);
*/
fun convertTime(current: String, correct: String): Int {
var remainingTimeDiffInMinutes = getTimeDifferentInMinutes(current, correct)
var minNumberOfOperation = 0
for (increment in incrementInMinutesDescending) {
val maxNumberOfCurrentOperation = remainingTimeDiffInMinutes / increment
minNumberOfOperation += maxNumberOfCurrentOperation
remainingTimeDiffInMinutes -= maxNumberOfCurrentOperation * increment
}
check(remainingTimeDiffInMinutes == 0)
return minNumberOfOperation
}
private fun getTimeDifferentInMinutes(from: String, to: String): Int {
val (hourOfFrom, minutesOfFrom) = getHourAndMinutes(from)
val (hourOfTo, minutesOfTo) = getHourAndMinutes(to)
return (hourOfTo - hourOfFrom) * 60 + (minutesOfTo - minutesOfFrom)
}
// Return Pair(hour, minutes) from a 24-hr time string with format "HH:MM";
private fun getHourAndMinutes(time: String): Pair<Int, Int> {
val hour = time.slice(0..1).toInt()
val minutes = time.slice(3..4).toInt()
return Pair(hour, minutes)
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 1,484 | hj-leetcode-kotlin | Apache License 2.0 |
modules/graph/src/commonMain/kotlin/com/handtruth/mc/graph/Isomorhism.kt | handtruth | 282,440,433 | false | null | package com.handtruth.mc.graph
private fun <E> swap(list: MutableList<E>, i: Int, j: Int) {
val a = list[i]
val b = list[j]
list[i] = b
list[j] = a
}
private suspend fun <E> SequenceScope<List<E>>.heapPermutation(
list: MutableList<E>,
size: Int
) {
if (size == 1) {
yield(list)
} else {
for (i in 0 until size) {
heapPermutation(list, size - 1)
if (size and 1 == 1) {
swap(list, 0, size - 1)
} else {
swap(list, i, size - 1)
}
}
}
}
internal val <E> List<E>.permutations: Iterable<List<E>>
get() = sequence {
val size = size
val list = this@permutations.toMutableList()
heapPermutation(list, size)
}.asIterable()
private fun <V, E> Graph<V, E>.groups(equation: Boolean) = if (equation) {
vertices.groupBy { it.edges.size to it.value }
} else {
vertices.groupBy { it.edges.size }
}
private suspend fun <E> SequenceScope<List<E>>.nextGroup(
result: MutableList<E>,
groups: List<List<E>>,
depth: Int
) {
if (depth == groups.size) {
yield(result)
} else {
val group = groups[depth]
group.permutations.forEach { perm ->
result += perm
nextGroup(result, groups, depth + 1)
repeat(perm.size) {
result.removeLast()
}
}
}
}
internal val <E> List<List<E>>.groupPermutations: Iterable<List<E>>
get() = sequence {
val result = ArrayList<E>(sumOf { it.size })
nextGroup(result, this@groupPermutations, 0)
}.asIterable()
internal fun <V, E> findIsomorphism(
a: Graph<V, E>,
b: Graph<V, E>,
equation: Boolean
): Map<Graph.Vertex<V, E>, Graph.Vertex<V, E>>? {
if (a.vertices.size != b.vertices.size) {
return null
}
val groupsA = a.groups(equation)
val groupsB = b.groups(equation)
if (groupsA.keys != groupsB.keys) {
return null
}
val sortedA = ArrayList<List<Graph.Vertex<V, E>>>(groupsA.size)
val sortedB = ArrayList<List<Graph.Vertex<V, E>>>(groupsB.size)
for ((key, value) in groupsA.entries) {
sortedA += value
sortedB += groupsB[key]!!
}
sortedA.groupPermutations.forEach { permA ->
sortedB.groupPermutations.forEach { permB ->
val isomorphism = HashMap<Graph.Vertex<V, E>, Graph.Vertex<V, E>>()
permA.zip(permB) { a, b -> isomorphism[a] = b }
if (isIsomorphism(isomorphism, equation)) {
return isomorphism
}
}
}
return null
}
internal fun <V, E> isIsomorphism(
candidate: Map<Graph.Vertex<V, E>, Graph.Vertex<V, E>>,
equation: Boolean
): Boolean {
for ((key, value) in candidate) {
if (key.edges.size != value.edges.size) {
return false
}
if (equation && key.value != value.value) {
return false
}
for (childEdge in key.edges) {
val child = childEdge.target
if (child === key) {
continue
}
val vertex = candidate[key] ?: return false
val found = (candidate[child] ?: return false).edges.any {
it.source === vertex && (!equation || it.value == childEdge.value)
}
if (!found) {
return false
}
}
}
return true
}
| 0 | Kotlin | 0 | 0 | fa6d230dc1f7e62cd75b91ad4798a763ca7e78f1 | 3,446 | mc-tools | MIT License |
archive/src/main/kotlin/com/grappenmaker/aoc/year21/Day13.kt | 770grappenmaker | 434,645,245 | false | {"Kotlin": 409647, "Python": 647} | package com.grappenmaker.aoc.year21
import com.grappenmaker.aoc.*
fun PuzzleSet.day13() = puzzle(day = 13) {
val (pointsPart, foldsPart) = input.split("\n\n")
val points = pointsPart.lines().mapTo(hashSetOf()) { it.split(",").map(String::toInt).asPair().toPoint() }
val folds = foldsPart.lines().map {
val (d, v) = it.substring(11).split("=")
enumValueOf<Direction>(d.uppercase()) to v.toInt()
}
// Part one
val doFold = { pts: Set<Point>, (dir, loc): Pair<Direction, Int> ->
pts.mapTo(hashSetOf()) { point ->
val (x, y) = point
when {
dir == Direction.X && x > loc -> Point(loc - (x - loc), y)
dir == Direction.Y && y > loc -> Point(x, loc - (y - loc))
else -> point
}
}
}
// Part two
val allFolded = folds.fold(points) { cur, fold -> doFold(cur, fold) }
partOne = doFold(points, folds.first()).size.s()
partTwo = "\n" + allFolded.asBooleanGrid().debug(off = " ")
}
enum class Direction {
X, Y
} | 0 | Kotlin | 0 | 7 | 92ef1b5ecc3cbe76d2ccd0303a73fddda82ba585 | 1,065 | advent-of-code | The Unlicense |
src/main/kotlin/g0501_0600/s0592_fraction_addition_and_subtraction/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g0501_0600.s0592_fraction_addition_and_subtraction
// #Medium #String #Math #Simulation #2023_01_31_Time_164_ms_(100.00%)_Space_35.9_MB_(66.67%)
class Solution {
private fun gcd(a: Int, b: Int): Int {
return if (a % b == 0) b else gcd(b, a % b)
}
private fun format(a: Int, b: Int): String {
val gcd = Math.abs(gcd(a, b))
return (a / gcd).toString() + "/" + b / gcd
}
private fun parse(s: String): IntArray {
val idx = s.indexOf("/")
return intArrayOf(s.substring(0, idx).toInt(), s.substring(idx + 1).toInt())
}
fun fractionAddition(expression: String): String {
var rst = intArrayOf(0, 1)
val list: MutableList<IntArray> = ArrayList()
var sb = StringBuilder().append(expression[0])
for (i in 1 until expression.length) {
val c = expression[i]
if (c == '+' || c == '-') {
list.add(parse(sb.toString()))
sb = StringBuilder().append(c)
} else {
sb.append(c)
}
}
list.add(parse(sb.toString()))
for (num in list) {
rst = intArrayOf(rst[0] * num[1] + rst[1] * num[0], rst[1] * num[1])
}
return format(rst[0], rst[1])
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,282 | LeetCode-in-Kotlin | MIT License |
src/day01/day01.kt | PS-MS | 572,890,533 | false | null | package day01
import readInput
import kotlin.math.max
fun main() {
fun part1(input: List<String>): Int {
var highestElf = 0
var thisElf = 0
input.forEachIndexed { index, value ->
val calories = value.toIntOrNull()
if (calories != null) {
thisElf += calories
if (index == input.lastIndex) {
highestElf = max(highestElf, thisElf)
}
} else {
highestElf = max(highestElf, thisElf)
thisElf = 0
}
}
return highestElf
}
fun part2(input: List<String>): Int {
val elfList = mutableListOf<Int>()
var thisElf = 0
input.forEachIndexed { index, value ->
value.toIntOrNull()?.let {
thisElf += it
if (index == input.lastIndex) {
elfList.add(thisElf)
}
} ?: run {
elfList.add(thisElf)
thisElf = 0
}
}
return elfList.sortedDescending().take(3).sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("day01/Day01_test")
check(part1(testInput) == 24000)
val input = readInput("day01/Day01")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 24f280a1d8ad69e83755391121f6107f12ffebc0 | 1,374 | AOC2022 | Apache License 2.0 |
algorithms/src/main/kotlin/io/nullables/api/playground/algorithms/Point.kt | AlexRogalskiy | 331,076,596 | false | null | /*
* Copyright (C) 2021. <NAME>. All Rights Reserved.
*
* 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 io.nullables.api.playground.algorithms
data class Point(val x: Int, val y: Int): Comparable<Point> {
override fun compareTo(other: Point): Int {
if (x == other.x) return y.compareTo(other.y)
return x.compareTo(other.x)
}
fun isLeftOfLine(from: Point, to: Point): Boolean {
return crossProduct(from, to) > 0
}
fun crossProduct(origin: Point, p2: Point): Int {
return (p2.x - origin.x) * (this.y - origin.y) - (p2.y - origin.y) * (this.x - origin.x)
}
fun distanceToLine(a: Point, b: Point): Double {
return Math.abs((b.x - a.x) * (a.y - this.y) - (a.x - this.x) * (b.y - a.y)) /
Math.sqrt(Math.pow((b.x - a.x).toDouble(), 2.0) + Math.pow((b.y - a.y).toDouble(), 2.0))
}
fun euclideanDistanceTo(that: Point): Double {
return EUCLIDEAN_DISTANCE_FUNC(this, that)
}
fun manhattanDistanceTo(that: Point): Double {
return MANHATTAN_DISTANCE_FUNC(this, that)
}
companion object {
// < 0 : Counterclockwise
// = 0 : p, q and r are colinear
// > 0 : Clockwise
fun orientation(p: Point, q: Point, r: Point): Int {
return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y)
}
val EUCLIDEAN_DISTANCE_FUNC: (Point, Point) -> (Double) = { p, q ->
val dx = p.x - q.x
val dy = p.y - q.y
Math.sqrt((dx * dx + dy * dy).toDouble())
}
val MANHATTAN_DISTANCE_FUNC: (Point, Point) -> (Double) = { p, q ->
val dx = p.x - q.x
val dy = p.y - q.y
Math.sqrt((dx * dx + dy * dy).toDouble())
}
}
}
| 13 | Kotlin | 2 | 2 | d7173ec1d9ef227308d926e71335b530c43c92a8 | 2,301 | gradle-kotlin-sample | Apache License 2.0 |
LeetCode/Kotlin/MaxAreaOfIsland.kt | vale-c | 177,558,551 | false | null | /*
* 695. Max Area of Island
* https://leetcode.com/problems/max-area-of-island/
*/
class MaxAreaOfIsland {
fun maxAreaOfIsland(grid: Array<IntArray>): Int {
var max = 0
for (i in 0 until grid.size) {
for (j in 0 until grid[i].size) {
if (grid[i][j] != 0) {
max = Math.max(max, dfs(grid, i, j))
}
}
}
return max
}
fun dfs(grid: Array<IntArray>, i: Int, j: Int): Int {
if (i >= 0 && i < grid.size && j >= 0 && j < grid[0].size &&
grid[i][j] != 0) {
//mark as visited
grid[i][j] = 0
return 1 +
dfs(grid, i, j + 1) +
dfs(grid, i, j - 1) +
dfs(grid, i + 1, j) +
dfs(grid, i - 1, j)
}
return 0
}
}
| 0 | Java | 5 | 9 | 977e232fa334a3f065b0122f94bd44f18a152078 | 939 | CodingInterviewProblems | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/ContainerWithMostWater.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
fun interface ContainerWithMostWaterStrategy {
fun maxArea(height: IntArray): Int
}
class ContainerWithMostWaterBruteForce : ContainerWithMostWaterStrategy {
override fun maxArea(height: IntArray): Int {
var maxArea = 0
for (i in height.indices) {
for (j in i + 1 until height.size) {
maxArea = maxArea.coerceAtLeast(height[i].coerceAtMost(height[j]) * (j - i))
}
}
return maxArea
}
}
class ContainerWithMostWaterTwoPointer : ContainerWithMostWaterStrategy {
override fun maxArea(height: IntArray): Int {
var maxArea = 0
var l = 0
var r: Int = height.size - 1
while (l < r) {
maxArea = maxArea.coerceAtLeast(height[l].coerceAtMost(height[r]) * (r - l))
if (height[l] < height[r]) l++ else r--
}
return maxArea
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,522 | kotlab | Apache License 2.0 |
src/day05/Day05_Part1.kt | m-jaekel | 570,582,194 | false | {"Kotlin": 13764} | package day05
import readInput
fun main() {
fun part1(input: List<String>): String {
parseMoves(input).forEach { move ->
repeat(move[0]) {
val stack = data04_data[move[1] - 1].first()
data04_data[move[1] - 1].removeFirst()
data04_data[move[2] - 1].addFirst(stack)
}
}
return getCompleteStackSequence()
}
println(part1(readInput("day05/input")))
}
fun parseMoves(input: List<String>) = input.map { move ->
val stackCount = move.substringAfter(" ").substringBefore(" ").toInt()
val position1 = move.substringAfter("m ").substringBefore(" t").toInt()
val position2 = move.substringAfter("o ").toInt()
listOf(stackCount, position1, position2)
}
private fun getCompleteStackSequence(): String {
val result = StringBuilder()
data04_data.forEach {
result.append(it.first())
}
return result.toString()
}
/**
*
* [T] [V] [W]
* [V] [C] [P] [D] [B]
* [J] [P] [R] [N] [B] [Z]
* [W] [Q] [D] [M] [T] [L] [T]
* [N] [J] [H] [B] [P] [T] [P] [L]
* [R] [D] [F] [P] [R] [P] [R] [S] [G]
* [M] [W] [J] [R] [V] [B] [J] [C] [S]
* [S] [B] [B] [F] [H] [C] [B] [N] [L]
* 1 2 3 4 5 6 7 8 9
*
*/
val data04_data: List<ArrayDeque<String>> = listOf(
ArrayDeque(listOf("T", "V", "J", "W", "N", "R", "M", "S")),
ArrayDeque(listOf("V", "C", "P", "Q", "J", "D", "W", "B")),
ArrayDeque(listOf("P", "R", "D", "H", "F", "J", "B")),
ArrayDeque(listOf("D", "N", "M", "B", "P", "R", "F")),
ArrayDeque(listOf("B", "T", "P", "R", "V", "H")),
ArrayDeque(listOf("T", "P", "B", "C")),
ArrayDeque(listOf("L", "P", "R", "J", "B")),
ArrayDeque(listOf("W", "B", "Z", "T", "L", "S", "C", "N")),
ArrayDeque(listOf("G", "S", "L")),
)
| 0 | Kotlin | 0 | 1 | 07e015c2680b5623a16121e5314017ddcb40c06c | 1,843 | AOC-2022 | Apache License 2.0 |
src/Day05.kt | stephenkao | 572,205,897 | false | {"Kotlin": 14623} | import kotlin.reflect.typeOf
fun main() {
val day = "05"
var charsPerCrate = 4 // assumption!
fun part1(input: List<String>): String {
val structureRegex = Regex("\\[([A-Z]+)\\]")
val moveRegex = Regex("\\s*move\\s*(\\d*)\\s*from\\s*(\\d*)\\s*to\\s*(\\d*)")
// initialize stacks based on number of characters in first line
// assumes there are four characters per stack
val stacks = MutableList((input.first().length / charsPerCrate) + 1) { mutableListOf<String>() }
fun processStructureLine(line: String) {
line.chunked(charsPerCrate).forEachIndexed { idx, stackItem ->
val crate = structureRegex.find(stackItem)?.groupValues?.get(1)
if (crate !== null) {
stacks[idx].add(crate)
}
}
}
fun processMoveLine(line: String, oneByOne: Boolean) {
val (count, src, dest) = moveRegex.find(line)!!.destructured
val srcStack = stacks[src.toInt() - 1]
val destStack = stacks[dest.toInt() - 1]
val movingCrates = srcStack.take(count.toInt())
repeat(count.toInt()) { srcStack.removeFirst() }
destStack.addAll(
0,
if (oneByOne) movingCrates.reversed() else movingCrates
)
}
// read in lines
for (line in input) {
if (line.contains(structureRegex)) {
processStructureLine(line)
} else if (line.contains(moveRegex)) {
// PART 1
// processMoveLine(line, oneByOne = true)
// PART 2
processMoveLine(line, oneByOne = false)
}
}
return stacks.joinToString("") { stack -> stack.first() }
}
val testInput = readInput("Day${day}_test")
println(part1(testInput))
// check(part1(testInput) == "CMZ")
check(part1(testInput) == "MCD")
val input = readInput("Day${day}")
// println("Part 1: ${part1(input)}")
println("Part 2: ${part1(input)}")
} | 0 | Kotlin | 0 | 0 | 7a1156f10c1fef475320ca985badb4167f4116f1 | 2,099 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/year2023/day-01.kt | ppichler94 | 653,105,004 | false | {"Kotlin": 182859} | package year2023
import lib.aoc.Day
import lib.aoc.Part
import lib.splitLines
fun main() {
Day(1, 2023, PartA1(), PartB1()).run()
}
open class PartA1 : Part() {
private lateinit var lines: List<String>
override fun parse(text: String) {
lines = text.splitLines()
}
override fun compute(): String {
return lines
.map(::findDigit)
.map(String::toInt)
.sum()
.toString()
}
protected open fun findDigit(line: String): String {
val numbers = """\d""".toRegex().findAll(line)
return numbers.first().value + numbers.last().value
}
override val exampleAnswer: String
get() = "142"
}
class PartB1 : PartA1() {
override fun findDigit(line: String): String {
val regex = """(?:one|two|three|four|five|six|seven|eight|nine|\d)""".toRegex()
val matches = line.indices.mapNotNull {
regex.find(line, it)?.value
}
val digitMap = mapOf(
"one" to "1",
"two" to "2",
"three" to "3",
"four" to "4",
"five" to "5",
"six" to "6",
"seven" to "7",
"eight" to "8",
"nine" to "9",
)
val first = if (matches.first() in digitMap) digitMap[matches.first()] else matches.first()
val second = if (matches.last() in digitMap) digitMap[matches.last()] else matches.last()
return first + second
}
override val exampleAnswer: String
get() = "281"
override val customExampleData: String
get() = """
two1nine
eightwothree
abcone2threexyz
xtwone3four
4nineeightseven2
zoneight234
7pqrstsixteen
""".trimIndent()
}
| 0 | Kotlin | 0 | 0 | 49dc6eb7aa2a68c45c716587427353567d7ea313 | 1,885 | Advent-Of-Code-Kotlin | MIT License |
Code/3Sum/Solution.kt | Guaidaodl | 26,102,098 | false | {"Java": 20880, "Kotlin": 6663, "C++": 4106, "Python": 1216} | class Solution {
fun threeSum(nums: IntArray): List<List<Int>> {
nums.sort()
val result: ArrayList<List<Int>> = ArrayList()
var lastTwoResult: List<List<Int>>? = null
for (i in 0 until nums.size - 2) {
if (nums[i] > 0) return result
val r = twoSum(nums, i + 1, 0 - nums[i])
r.forEach {t ->
lastTwoResult?.let {
if (exit(it, t)) {
return@forEach
}
}
val lastResult = listOf(nums[i], t[0], t[1])
result.add(lastResult)
}
lastTwoResult = if (nums[i + 1] == nums[i]) {
r
} else {
null
}
}
return result
}
private fun exit(lastResult: List<List<Int>>, r: List<Int>): Boolean {
lastResult.forEach {
if (it[0] == r[0] && it[1] == r[1]) return true
}
return false
}
private fun twoSum(nums: IntArray, begin: Int, target: Int): List<List<Int>> {
var b = begin
var e = nums.size - 1
val result: ArrayList<List<Int>> = ArrayList()
while(b < e) {
val sum = nums[b] + nums[e]
if (sum > target) {
do {
e--
} while (b < e && nums[e] == nums[e + 1])
} else {
if (sum == target) {
result.add(listOf(nums[b], nums[e]))
}
do {
b++
} while (b < e && nums[b] == nums[b - 1])
}
}
return result
}
} | 0 | Java | 0 | 0 | a5e9c36d34e603906c06df642231bfdeb0887088 | 1,689 | leetcode | Apache License 2.0 |
src/main/kotlin/days/aoc2021/Day21.kt | bjdupuis | 435,570,912 | false | {"Kotlin": 537037} | package days.aoc2021
import days.Day
class Day21 : Day(2021, 21) {
override fun partOne(): Any {
return calculateScoresForGame(inputList)
}
override fun partTwo(): Any {
return calculateDiracWinners(inputList)
}
fun calculateDiracWinners(inputList: List<String>): Long {
var player1Position = inputList.first().last() - '0'
var player2Position = inputList.last().last() - '0'
val (player1Wins, player2Wins) = playDiracGame(player1Position, 0, player2Position, 0)
return maxOf(player1Wins, player2Wins)
}
fun calculateScoresForGame(inputList: List<String>): Long {
var player1Position = inputList.first().last() - '0'
var player2Position = inputList.last().last() - '0'
var player1Score = 0L
var player2Score = 0L
val determinateDice = DeterminateDice(100,3)
while (player1Score < 1000 && player2Score < 1000) {
var roll = determinateDice.roll()
player1Position = (((player1Position - 1) + roll) % 10) + 1
player1Score += player1Position
if (player1Score >= 1000) {
break
}
roll = determinateDice.roll()
player2Position = (((player2Position - 1) + roll) % 10) + 1
player2Score += player2Position
if (player1Score >= 1000) {
break
}
}
return minOf(player1Score, player2Score) * determinateDice.totalRolls
}
class DeterminateDice(private val size: Int, private val rolls: Int) {
private var current = 1
var totalRolls = 0
fun roll(): Int {
var value = 0
repeat(rolls) {
value += current++
if (current > size) {
current = 1
}
}
totalRolls += rolls
return value
}
}
data class GameState(val position: Int, val score: Int, val otherPosition: Int, val otherScore: Int)
private val cache = mutableMapOf<GameState,Pair<Long,Long>>()
private fun playDiracGame(position: Int, score: Int, otherPosition: Int, otherScore: Int): Pair<Long,Long> {
val gameState = GameState(position, score, otherPosition, otherScore)
return cache.computeIfAbsent(gameState) {
when {
score >= 21 -> {
Pair(1L, 0L)
}
otherScore >= 21 -> {
Pair(0L, 1L)
}
else -> {
var winners = Pair(0L, 0L)
for (i in 1..3)
for (j in 1..3)
for (k in 1..3) {
val newPosition = (((position - 1) + (i + j + k)) % 10) + 1
val newScore = score + newPosition
val (otherWinners, currentWinners) = playDiracGame(
otherPosition,
otherScore,
newPosition,
newScore
)
winners =
Pair(winners.first + currentWinners, winners.second + otherWinners)
}
winners
}
}
}
}
} | 0 | Kotlin | 0 | 1 | c692fb71811055c79d53f9b510fe58a6153a1397 | 3,465 | Advent-Of-Code | Creative Commons Zero v1.0 Universal |
src/main/kotlin/dev/shtanko/algorithms/leetcode/LongestPalindromicSubstring.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 kotlin.math.min
/**
* 5. Longest Palindromic Substring
* @see <a href="https://leetcode.com/problems/longest-palindromic-substring">Source</a>
*/
fun interface LongestPalindromicSubstring {
operator fun invoke(s: String): String
}
/**
* Approach 1: Check All Substrings
*/
class LongestPalindromicSubstringBF : LongestPalindromicSubstring {
override fun invoke(s: String): String {
for (length in s.length downTo 1) {
for (start in 0..s.length - length) {
if (check(start, start + length, s)) {
return s.substring(start, start + length)
}
}
}
return ""
}
private fun check(i: Int, j: Int, s: String): Boolean {
var left = i
var right = j - 1
while (left < right) {
if (s[left] != s[right]) {
return false
}
left++
right--
}
return true
}
}
/**
* Approach 2: Dynamic Programming
*/
class LongestPalindromicSubstringDP : LongestPalindromicSubstring {
override fun invoke(s: String): String {
if (s.isEmpty()) {
return ""
}
val n: Int = s.length
val dp = Array(n) { BooleanArray(n) }
val ans = intArrayOf(0, 0)
for (i in 0 until n) {
dp[i][i] = true
}
for (i in 0 until n - 1) {
if (s[i] == s[i + 1]) {
dp[i][i + 1] = true
ans[0] = i
ans[1] = i + 1
}
}
for (diff in 2 until n) {
for (i in 0 until n - diff) {
val j = i + diff
if (s[i] == s[j] && dp[i + 1][j - 1]) {
dp[i][j] = true
ans[0] = i
ans[1] = j
}
}
}
val i = ans[0]
val j = ans[1]
return s.substring(i, j + 1)
}
}
/**
* Approach 3: Expand From Centers
*/
class LongestPalindromicSubstringExpand : LongestPalindromicSubstring {
override fun invoke(s: String): String {
if (s.isEmpty()) {
return ""
}
val ans = intArrayOf(0, 0)
for (i in s.indices) {
val oddLength = expand(i, i, s)
if (oddLength > ans[1] - ans[0] + 1) {
val dist = oddLength / 2
ans[0] = i - dist
ans[1] = i + dist
}
val evenLength = expand(i, i + 1, s)
if (evenLength > ans[1] - ans[0] + 1) {
val dist = evenLength / 2 - 1
ans[0] = i - dist
ans[1] = i + 1 + dist
}
}
val i = ans[0]
val j = ans[1]
return s.substring(i, j + 1)
}
private fun expand(i: Int, j: Int, s: String): Int {
var left = i
var right = j
while (left >= 0 && right < s.length && s[left] == s[right]) {
left--
right++
}
return right - left - 1
}
}
/**
* Approach 4: Manacher's Algorithm
*/
class LongestPalindromicSubstringManacher : LongestPalindromicSubstring {
override fun invoke(s: String): String {
val sPrime = StringBuilder("#")
for (c in s.toCharArray()) {
sPrime.append(c).append("#")
}
val n = sPrime.length
val palindromeRadii = IntArray(n)
var center = 0
var radius = 0
for (i in 0 until n) {
val mirror = 2 * center - i
if (i < radius) {
palindromeRadii[i] =
min((radius - i).toDouble(), palindromeRadii[mirror].toDouble()).toInt()
}
while (i + 1 + palindromeRadii[i] < n &&
i - 1 - palindromeRadii[i] >= 0 &&
sPrime[i + 1 + palindromeRadii[i]] == sPrime[
i - 1 - palindromeRadii[i],
]
) {
palindromeRadii[i]++
}
if (i + palindromeRadii[i] > radius) {
center = i
radius = i + palindromeRadii[i]
}
}
var maxLength = 0
var centerIndex = 0
for (i in 0 until n) {
if (palindromeRadii[i] > maxLength) {
maxLength = palindromeRadii[i]
centerIndex = i
}
}
val startIndex = (centerIndex - maxLength) / 2
return s.substring(startIndex, startIndex + maxLength)
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 5,179 | kotlab | Apache License 2.0 |
kotlin-native/tools/benchmarks/shared/src/main/kotlin/analyzer/Statistics.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | /*
* Copyright 2010-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package org.jetbrains.analyzer
import org.jetbrains.report.BenchmarkResult
import org.jetbrains.report.MeanVariance
import org.jetbrains.report.MeanVarianceBenchmark
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
import kotlin.math.pow
import kotlin.math.sqrt
val MeanVariance.description: String
get() {
val format = { number: Double -> number.format(2) }
return "${format(mean)} ± ${format(variance)}"
}
val MeanVarianceBenchmark.description: String
get() = "${score.format()} ± ${variance.format()}"
// Calculate difference in percentage compare to another.
fun MeanVarianceBenchmark.calcPercentageDiff(other: MeanVarianceBenchmark): MeanVariance {
if (score == 0.0 && variance == 0.0 && other.score == 0.0 && other.variance == 0.0)
return MeanVariance(score, variance)
assert(other.score >= 0 &&
other.variance >= 0 &&
(other.score - other.variance != 0.0 || other.score == 0.0),
{ "Mean and variance should be positive and not equal!" })
// Analyze intervals. Calculate difference between border points.
val (bigValue, smallValue) = if (score > other.score) Pair(this, other) else Pair(other, this)
val bigValueIntervalStart = bigValue.score - bigValue.variance
val bigValueIntervalEnd = bigValue.score + bigValue.variance
val smallValueIntervalStart = smallValue.score - smallValue.variance
val smallValueIntervalEnd = smallValue.score + smallValue.variance
if (smallValueIntervalEnd > bigValueIntervalStart) {
// Interval intersect.
return MeanVariance(0.0, 0.0)
}
val mean = ((smallValueIntervalEnd - bigValueIntervalStart) / bigValueIntervalStart) *
(if (score > other.score) -1 else 1)
val maxValueChange = ((bigValueIntervalEnd - smallValueIntervalEnd) / bigValueIntervalEnd)
val minValueChange = ((bigValueIntervalStart - smallValueIntervalStart) / bigValueIntervalStart)
val variance = abs(abs(mean) - max(minValueChange, maxValueChange))
return MeanVariance(mean * 100, variance * 100)
}
// Calculate ratio value compare to another.
fun MeanVarianceBenchmark.calcRatio(other: MeanVarianceBenchmark): MeanVariance {
if (other.score == 0.0 && other.variance == 0.0)
return MeanVariance(1.0, 0.0)
assert(other.score >= 0 &&
other.variance >= 0 &&
(other.score - other.variance != 0.0 || other.score == 0.0),
{ "Mean and variance should be positive and not equal!" })
val mean = if (other.score != 0.0) (score / other.score) else 0.0
val minRatio = (score - variance) / (other.score + other.variance)
val maxRatio = (score + variance) / (other.score - other.variance)
val ratioConfInt = min(abs(minRatio - mean), abs(maxRatio - mean))
return MeanVariance(mean, ratioConfInt)
}
fun geometricMean(values: Collection<Double>, totalNumber: Int = values.size) =
with(values.asSequence().filter { it != 0.0 }) {
if (count() == 0 || totalNumber == 0) {
0.0
} else {
map { it.pow(1.0 / totalNumber) }.reduce { a, b -> a * b }
}
}
fun computeMeanVariance(samples: List<Double>): MeanVariance {
val removedBroadSamples = 0.2
val zStar = 1.67 // Critical point for 90% confidence of normal distribution.
// Skip several minimal and maximum values.
val filteredSamples = if (samples.size >= 1/removedBroadSamples) {
samples.sorted().subList((samples.size * removedBroadSamples).toInt(),
samples.size - (samples.size * removedBroadSamples).toInt())
} else {
samples
}
val mean = filteredSamples.sum() / filteredSamples.size
val variance = samples.indices.sumOf {
(samples[it] - mean) * (samples[it] - mean)
} / samples.size
val confidenceInterval = sqrt(variance / samples.size) * zStar
return MeanVariance(mean, confidenceInterval)
}
// Calculate average results for benchmarks (each benchmark can be run several times).
fun collectMeanResults(benchmarks: Map<String, List<BenchmarkResult>>): BenchmarksTable {
return benchmarks.map { (name, resultsSet) ->
val repeatedSequence = IntArray(resultsSet.size)
var metric = BenchmarkResult.Metric.EXECUTION_TIME
var currentStatus = BenchmarkResult.Status.PASSED
var currentWarmup = -1
// Results can be already processed.
if (resultsSet[0] is MeanVarianceBenchmark) {
assert(resultsSet.size == 1) { "Several MeanVarianceBenchmark instances." }
name to resultsSet[0] as MeanVarianceBenchmark
} else {
// Collect common benchmark values and check them.
resultsSet.forEachIndexed { index, result ->
// If there was at least one failure, summary is marked as failure.
if (result.status == BenchmarkResult.Status.FAILED) {
currentStatus = result.status
}
repeatedSequence[index] = result.repeat
if (currentWarmup != -1)
if (result.warmup != currentWarmup)
println("Check data consistency. Warmup value for benchmark '${result.name}' differs.")
currentWarmup = result.warmup
metric = result.metric
}
repeatedSequence.sort()
// Check if there are missed loop during running benchmarks.
repeatedSequence.forEachIndexed { index, element ->
if (index != 0)
if ((element - repeatedSequence[index - 1]) != 1)
println("Check data consistency. For benchmark '$name' there is no run" +
" between ${repeatedSequence[index - 1]} and $element.")
}
// Create mean and variance benchmarks result.
val scoreMeanVariance = computeMeanVariance(resultsSet.map { it.score })
val runtimeInUsMeanVariance = computeMeanVariance(resultsSet.map { it.runtimeInUs })
val meanBenchmark = MeanVarianceBenchmark(name, currentStatus, scoreMeanVariance.mean, metric,
runtimeInUsMeanVariance.mean, repeatedSequence[resultsSet.size - 1],
currentWarmup, scoreMeanVariance.variance)
name to meanBenchmark
}
}.toMap()
}
fun collectBenchmarksDurations(benchmarks: Map<String, List<BenchmarkResult>>): Map<String, Double> =
benchmarks.map { (name, resultsSet) ->
name to resultsSet.sumOf { it.runtimeInUs }
}.toMap() | 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 6,786 | kotlin | Apache License 2.0 |
src/main/kotlin/ru/amai/study/hackerrank/practice/interviewPreparationKit/search/minTime/MinTime.kt | slobanov | 200,526,003 | false | null | package ru.amai.study.hackerrank.practice.interviewPreparationKit.search.minTime
import java.util.*
import kotlin.math.ceil
import kotlin.math.floor
fun minTime(machines: List<Int>, goal: Int): Long {
fun producedByMachinesIn(time: Long): Long =
machines.fold(0L) { total, machine -> total + time / machine }
val approxIndividualGoal = goal.toDouble() / machines.size
val lowerBound: Long = floor(approxIndividualGoal).toLong() * machines.min()!!
val upperBound: Long = ceil(approxIndividualGoal).toLong() * machines.max()!!
fun search(left: Long, right: Long): Long {
check(right > left) { "right ($right) should be > left ($left)" }
val mTime = (left + right) / 2
val mQuantity = producedByMachinesIn(mTime)
return when {
mQuantity < goal -> search(mTime + 1, right)
(mQuantity >= goal) && (producedByMachinesIn(mTime - 1) < goal) -> mTime
else -> search(left, mTime)
}
}
return search(lowerBound, upperBound)
}
fun main() {
val scan = Scanner(System.`in`)
fun readLongList() = scan.nextLine().split(" ").map { it.trim().toInt() }
val (_, goal) = readLongList()
val machines = readLongList()
val ans = minTime(machines, goal)
println(ans)
}
| 0 | Kotlin | 0 | 0 | 2cfdf851e1a635b811af82d599681b316b5bde7c | 1,289 | kotlin-hackerrank | MIT License |
src/Day01.kt | ka1eka | 574,248,838 | false | {"Kotlin": 36739} | fun main() {
fun Sequence<Int?>.chunkedOnNull(): Sequence<List<Int>> = sequence {
val buffer = mutableListOf<Int>()
for (element in this@chunkedOnNull) {
if (element == null) {
yield(buffer)
buffer.clear()
} else {
buffer += element
}
}
if (buffer.isNotEmpty()) yield(buffer)
}
fun part1(input: List<String>): Int = input
.asSequence()
.map { it.toIntOrNull() }
.chunkedOnNull()
.map { it.sum() }
.max()
fun part2(input: List<String>): Int = input
.asSequence()
.map { it.toIntOrNull() }
.chunkedOnNull()
.map { it.sum() }
.sortedDescending()
.take(3)
.sum()
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 4f7893448db92a313c48693b64b3b2998c744f3b | 998 | advent-of-code-2022 | Apache License 2.0 |
src/dataStructures/trees/BinaryStructure.kt | tpltn | 119,588,847 | false | null | package dataStructures.trees
import java.util.*
data class BinaryStructure<T>(val value: T, var left: BinaryStructure<T>? = null, var right: BinaryStructure<T>? = null)
fun <T> binaryStructureEnumeration(root: BinaryStructure<T>) {
val stack: Stack<BinaryStructure<T>> = Stack()
stack.push(root)
var node: BinaryStructure<T>
while (!stack.empty()) {
node = stack.pop()
println(node.value)
if (node.right != null) {
stack.push(node.right)
}
if (node.left != null) {
stack.push(node.left)
}
}
}
fun <T> binaryStructureContains(root: BinaryStructure<T>, value: T): Boolean {
val queue: PriorityQueue<BinaryStructure<T>> = PriorityQueue()
queue.add(root)
var node: BinaryStructure<T>
while (queue.isNotEmpty()) {
node = queue.first()
if (node.value == value) {
return true
}
else {
if (node.left != null) {
queue.add(node.left)
}
if (node.right != null) {
queue.add(node.right)
}
}
}
return false
}
fun binarySearchStructureFind(root: BinaryStructure<Int>, value: Int): Boolean {
var tmp: BinaryStructure<Int>? = root
while (tmp != null) {
if (tmp.value == value) {
return true
}
else {
if (value > tmp.value) {
tmp = tmp.right
}
else {
tmp = tmp.left
}
}
}
return false
}
fun binarySearchStructureInsert(root: BinaryStructure<Int>, value: Int) {
var tmp: BinaryStructure<Int>? = root
var added = false
while (!added) {
if (value > tmp!!.value) {
if (tmp.right != null) {
tmp = tmp.right
}
else {
tmp.right = BinaryStructure(value)
added = true
}
}
else if (value < tmp.value) {
if (tmp.left != null) {
tmp = tmp.left
}
else {
tmp.left = BinaryStructure(value)
added = true
}
}
else {
// equal values are not allowed
return
}
}
}
fun binaryStructureMeasureDepth(root: BinaryStructure<Int>?, level: Int = 0, maxLevel: Int = 0): Int {
if (root == null) {
return maxLevel
}
val currentLevel = level + 1
val newMaxLevel = if (currentLevel > maxLevel) currentLevel else maxLevel
val leftLevel = binaryStructureMeasureDepth(root.left, currentLevel, newMaxLevel)
val rightLevel = binaryStructureMeasureDepth(root.right, currentLevel, newMaxLevel)
return maxOf(newMaxLevel, leftLevel, rightLevel)
}
| 0 | Kotlin | 1 | 0 | 2257a6a968bb8440f8a2a65a5fd31ff0fa5a5e8f | 2,815 | ads | The Unlicense |
src/Day09.kt | JonasDBB | 573,382,821 | false | {"Kotlin": 17550} | import java.lang.Exception
data class Loc(val x: Int, val y: Int)
enum class Direction {
up,
down,
left,
right
}
private fun move(c: Loc, d: Direction) =
when (d) {
Direction.up -> Loc(c.x, c.y -1)
Direction.down -> Loc(c.x, c.y + 1)
Direction.left -> Loc(c.x - 1, c.y)
Direction.right -> Loc(c.x + 1, c.y)
}
private fun moveTail(h: Loc, t: Loc): Loc {
if (t.x < h.x && t.y < h.y - 1 ||
t.x < h.x - 1 && t.y < h.y) { // down right
return move(move(t, Direction.down), Direction.right)
}
if (t.x > h.x && t.y < h.y - 1 ||
t.x > h.x + 1 && t.y < h.y) { // down left
return move(move(t, Direction.down), Direction.left)
}
if (t.x < h.x && t.y > h.y + 1 ||
t.x < h.x - 1 && t.y > h.y) { // up right
return move(move(t, Direction.up), Direction.right)
}
if (t.x > h.x && t.y > h.y + 1 ||
t.x > h.x + 1 && t.y > h.y) { // up left
return move(move(t, Direction.up), Direction.left)
}
if (t.x < h.x - 1) { // right
return move(t, Direction.right)
}
if (t.x > h.x + 1) { // left
return move(t, Direction.left)
}
if (t.y < h.y - 1) { // down
return move(t, Direction.down)
}
if (t.y > h.y + 1) { // up
return move(t, Direction.up)
}
return t
}
private fun part1(input: List<String>) {
var head = Loc(0, 0)
var tail = Loc(0, 0)
val tailLocations = mutableSetOf(tail)
for (line in input) {
val spl = line.split(" ")
for (i in 0 until spl[1].toInt()) {
head = when (spl[0]) {
"U" -> move(head, Direction.up)
"D" -> move(head, Direction.down)
"L" -> move(head, Direction.left)
"R" -> move(head, Direction.right)
else -> throw Exception("bad input: $line")
}
tail = moveTail(head, tail)
tailLocations.add(tail)
}
}
println(tailLocations.size)
}
private fun part2(input: List<String>) {
val knots = MutableList(10) { Loc(0, 0) }
val tailLocations = mutableSetOf(knots[9])
for (line in input) {
val spl = line.split(" ")
for (i in 0 until spl[1].toInt()) {
knots[0] = when (spl[0]) {
"U" -> move(knots[0], Direction.up)
"D" -> move(knots[0], Direction.down)
"L" -> move(knots[0], Direction.left)
"R" -> move(knots[0], Direction.right)
else -> throw Exception("bad input: $line")
}
for (j in 1..9) {
knots[j] = moveTail(knots[j - 1], knots[j])
}
tailLocations.add(knots[9])
}
}
println(tailLocations.size)
}
fun main() {
val input = readInput("09")
println("part 1")
part1(input)
println("part 2")
part2(input)
} | 0 | Kotlin | 0 | 0 | 199303ae86f294bdcb2f50b73e0f33dca3a3ac0a | 2,917 | AoC2022 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/PredictTheWinner.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import kotlin.math.max
/**
* 486. Predict the Winner
*/
fun interface PredictTheWinner {
operator fun invoke(nums: IntArray): Boolean
}
/**
* Approach #1 Using Recursion
*/
class PredictTheWinnerRecursion : PredictTheWinner {
override operator fun invoke(nums: IntArray): Boolean {
return winner(nums, 0, nums.size - 1, 1) >= 0
}
private fun winner(nums: IntArray, s: Int, e: Int, turn: Int): Int {
if (s == e) return turn * nums[s]
val a = turn * nums[s] + winner(nums, s + 1, e, -turn)
val b = turn * nums[e] + winner(nums, s, e - 1, -turn)
return turn * max(turn * a, turn * b)
}
}
/**
* Approach #2 Similar Approach
*/
class PredictTheWinnerMemo : PredictTheWinner {
override operator fun invoke(nums: IntArray): Boolean {
val memo = Array(nums.size) {
arrayOfNulls<Int>(nums.size)
}
return winner(nums, 0, nums.size - 1, memo) >= 0
}
private fun winner(nums: IntArray, s: Int, e: Int, memo: Array<Array<Int?>>): Int {
if (s == e) return nums[s]
if (memo[s][e] != null) return memo[s][e] ?: -1
val a = nums[s] - winner(nums, s + 1, e, memo)
val b = nums[e] - winner(nums, s, e - 1, memo)
memo[s][e] = max(a, b)
return memo[s][e] ?: -1
}
}
/**
* Approach #3 Dynamic Programming
*/
class PredictTheWinnerDP : PredictTheWinner {
override operator fun invoke(nums: IntArray): Boolean {
val dp = Array(nums.size) { IntArray(nums.size) }
for (s in nums.size downTo 0) {
for (e in s until nums.size) {
if (s == e) {
dp[s][e] = nums[s]
} else {
val a = nums[s] - dp[s + 1][e]
val b = nums[e] - dp[s][e - 1]
dp[s][e] = max(a, b)
}
}
}
return dp[0][nums.size - 1] >= 0
}
}
/**
* Approach #4 1-D Dynamic Programming
*/
class PredictTheWinnerDP2 : PredictTheWinner {
override operator fun invoke(nums: IntArray): Boolean {
val dp = IntArray(nums.size)
for (s in nums.size downTo 0) {
for (e in s until nums.size) {
if (s == e) {
dp[s] = nums[s]
} else {
val a = nums[s] - dp[e]
val b = nums[e] - dp[e - 1]
dp[e] = max(a, b)
}
}
}
return dp[nums.size - 1] >= 0
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 3,159 | kotlab | Apache License 2.0 |
module-tool/src/main/kotlin/de/twomartens/adventofcode/day9/SequencePredictor.kt | 2martens | 729,312,999 | false | {"Kotlin": 89431} | package de.twomartens.adventofcode.day9
class SequencePredictor {
fun calculateSumOfPredictedNextValues(lines: List<List<Int>>): Int {
return lines.sumOf {
predictNextValue(it)
}
}
fun predictNextValue(sequence: List<Int>): Int {
val differenceLists = mutableListOf(sequence)
do {
val differenceList = calculateListOfDifferences(differenceLists.last())
differenceLists.add(differenceList)
} while (differenceList.any { it != 0 })
var lastValue = 0
for (i in differenceLists.lastIndex - 1 downTo 0) {
lastValue += differenceLists[i].last()
}
return lastValue
}
fun calculateSumOfPredictedPreviousValues(lines: List<List<Int>>): Int {
return lines.sumOf {
predictPreviousValue(it)
}
}
fun predictPreviousValue(sequence: List<Int>): Int {
val differenceLists = mutableListOf(sequence)
do {
val differenceList = calculateListOfDifferences(differenceLists.last())
differenceLists.add(differenceList)
} while (differenceList.any { it != 0 })
var firstValue = 0
for (i in differenceLists.lastIndex - 1 downTo 0) {
firstValue = differenceLists[i].first() - firstValue
}
return firstValue
}
fun calculateListOfDifferences(sequence: List<Int>): List<Int> {
return sequence.windowed(2, 1) {
it[1] - it[0]
}
}
} | 0 | Kotlin | 0 | 0 | 03a9f7a6c4e0bdf73f0c663ff54e01daf12a9762 | 1,514 | advent-of-code | Apache License 2.0 |
src/Day06.kt | i-tatsenko | 575,595,840 | false | {"Kotlin": 90644} | import java.lang.IllegalArgumentException
fun main() {
fun findPacketIndex(line: String, distinctChars: Int): Int {
val inSubstr = mutableMapOf<Char, Int>()
for (index in line.indices) {
if (index > distinctChars - 1) {
inSubstr.compute(line[index - distinctChars]) { _, current -> if (current!! - 1 == 0) null else current - 1 }
}
inSubstr.compute(line[index]) { _, current -> (current ?: 0) + 1 }
if (inSubstr.size == distinctChars) {
return index + 1
}
}
throw IllegalArgumentException()
}
fun part1(input: List<String>): Int {
val line = input[0]
return findPacketIndex(line, 4)
}
fun part2(input: List<String>): Int {
val line = input[0]
return findPacketIndex(line, 14)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day06_test")
check(part1(testInput) == 5)
check(part2(testInput) == 23)
val input = readInput("Day06")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 0a9b360a5fb8052565728e03a665656d1e68c687 | 1,138 | advent-of-code-2022 | Apache License 2.0 |
leetcode/src/offer/middle/Offer20.kt | zhangweizhe | 387,808,774 | false | null | package offer.middle
fun main() {
// 剑指 Offer 20. 表示数值的字符串
// https://leetcode.cn/problems/biao-shi-shu-zhi-de-zi-fu-chuan-lcof/
println(isNumber(" -12.3e1"))
}
fun isNumber(s: String): Boolean {
val transferMap = HashMap<State, MutableMap<CharType, State>>()
val initialMap = HashMap<CharType, State>().apply {
this[CharType.BLANK] = State.INITIAL
this[CharType.SIGN] = State.INT_SIGN
this[CharType.INT] = State.INT
this[CharType.DOT] = State.DOT_WITHOUT_INT
}
transferMap[State.INITIAL] = initialMap
val intSignMap = HashMap<CharType, State>().apply {
this[CharType.INT] = State.INT
this[CharType.DOT] = State.DOT_WITHOUT_INT
}
transferMap[State.INT_SIGN] = intSignMap
val intMap = HashMap<CharType, State>().apply {
this[CharType.INT] = State.INT
this[CharType.DOT] = State.DOT
this[CharType.EXP] = State.EXP
this[CharType.BLANK] = State.END
}
transferMap[State.INT] = intMap
val dotMap = HashMap<CharType, State>().apply {
this[CharType.INT] = State.FRACTION
this[CharType.EXP] = State.EXP
this[CharType.BLANK] = State.END
}
transferMap[State.DOT] = dotMap
val dotWithoutIntMap = HashMap<CharType, State>().apply {
this[CharType.INT] = State.FRACTION
}
transferMap[State.DOT_WITHOUT_INT] = dotWithoutIntMap
val fractionMap = mutableMapOf(
CharType.BLANK to State.END,
CharType.INT to State.FRACTION,
CharType.EXP to State.EXP
)
transferMap[State.FRACTION] = fractionMap
val expMap = mutableMapOf(
CharType.SIGN to State.EXP_SIGN,
CharType.INT to State.EXP_INT
)
transferMap[State.EXP] = expMap
val expSignMap = mutableMapOf(
CharType.INT to State.EXP_INT
)
transferMap[State.EXP_SIGN] = expSignMap
val expIntMap = mutableMapOf(
CharType.INT to State.EXP_INT,
CharType.BLANK to State.END
)
transferMap[State.EXP_INT] = expIntMap
val endMap = mutableMapOf(
CharType.BLANK to State.END
)
transferMap[State.END] = endMap
var state = State.INITIAL
for (c in s) {
val toCharType = toCharType(c)
val stateMap = transferMap[state]
val nextState = stateMap?.get(toCharType)
if (nextState == null) {
return false
}else {
state = nextState
}
}
return state.isReceive
}
private fun toCharType(c: Char): CharType {
return when (c) {
' ' -> CharType.BLANK
'+','-' -> CharType.SIGN
in '0'..'9' -> CharType.INT
'.' -> CharType.DOT
'e', 'E' -> CharType.EXP
else -> CharType.ILLEGAL
}
}
enum class State(val isReceive:Boolean){
/**
* 初始状态
*/
INITIAL(false),
/**
* 符号位,[+-]
*/
INT_SIGN(false),
/**
* 整数,接受状态
*/
INT(true),
/**
* 小数点,左边有整数,接受状态
*/
DOT(true),
/**
* 小数点,左边没有整数
*/
DOT_WITHOUT_INT(false),
/**
* 小数,接受状态
*/
FRACTION(true),
/**
* 指数符号 [eE]
*/
EXP(false),
/**
* 指数符号 [+-]
*/
EXP_SIGN(false),
/**
* 指数数值,接受状态
*/
EXP_INT(true),
/**
* 末尾的空格,接受状态
*/
END(true)
}
enum class CharType {
BLANK,
SIGN,
INT,
DOT,
EXP,
ILLEGAL
} | 0 | Kotlin | 0 | 0 | 1d213b6162dd8b065d6ca06ac961c7873c65bcdc | 3,608 | kotlin-study | MIT License |
src/day_10/kotlin/Day10.kt | Nxllpointer | 573,051,992 | false | {"Kotlin": 41751} | // AOC Day 10
interface Instruction {
data class AddX(val amount: Int) : Instruction
object Noop : Instruction
}
data class InstructionExecution<T : Instruction>(val instruction: T, var executionCyclesLeft: Int)
fun Iterator<Instruction>.run(maxCycles: Int, duringCycleAction: (cycle: Int, registerX: Int) -> Unit) {
var currentInstructionExecution: InstructionExecution<*>? = null
var registerX = 1
fun readInstruction() {
currentInstructionExecution = when (val instruction = this.next()) {
is Instruction.AddX -> InstructionExecution(instruction, executionCyclesLeft = 2)
is Instruction.Noop -> InstructionExecution(instruction, executionCyclesLeft = 1)
else -> null
}
}
fun updateCurrentInstruction() {
currentInstructionExecution?.apply {
executionCyclesLeft--
if (instruction is Instruction.AddX && executionCyclesLeft == 0)
registerX += instruction.amount
if (executionCyclesLeft == 0)
currentInstructionExecution = null
}
}
for (cycle in 1..maxCycles) {
// Start
if (currentInstructionExecution == null) {
if (this.hasNext()) readInstruction()
else break
}
// During
duringCycleAction(cycle, registerX)
// After
updateCurrentInstruction()
}
}
fun part1(instructions: Iterator<Instruction>) {
var signalStrengthSum = 0
instructions.run(220, duringCycleAction = { cycle, registerX ->
if ((cycle + 20) % 40 == 0) {
signalStrengthSum += cycle * registerX
}
})
println("Part 1: The sum of the signal strengths is $signalStrengthSum")
}
fun part2(instructions: Iterator<Instruction>) {
println("Part 2:")
instructions.run(maxCycles = 40 * 6, duringCycleAction = { cycle, registerX ->
val crtPositionX = (cycle - 1) % 40
val spritePositionsX = (registerX - 1)..(registerX + 1)
val shouldLightPixel = crtPositionX in spritePositionsX
val pixel = if (shouldLightPixel) "#" else " "
print(" $pixel ")
val isEndOfLine = cycle % 40 == 0
if (isEndOfLine) println()
})
}
fun main() {
val instructions = getAOCInput { rawInput ->
rawInput.trim().split("\n")
.map { instruction ->
val instructionSections = instruction.split(" ")
when (instructionSections[0]) {
"addx" -> Instruction.AddX(instructionSections[1].toInt())
"noop" -> Instruction.Noop
else -> throw IllegalArgumentException("Unknown instruction")
}
}
}
// Create new iterator for each puzzle
part1(instructions.iterator())
part2(instructions.iterator())
}
| 0 | Kotlin | 0 | 0 | b6d7ef06de41ad01a8d64ef19ca7ca2610754151 | 2,857 | AdventOfCode2022 | MIT License |
2015/Day08/src/main/kotlin/Main.kt | mcrispim | 658,165,735 | false | null | import java.io.File
fun main() {
fun stringInMemoryLength(raw: String): Int {
val string = raw.drop(1).dropLast(1)
var length = 0
var index = 0
val lastIndex = string.length - 1
while (index <= lastIndex) {
if (string[index] == '\\' && index < lastIndex) {
when (string[index + 1]) {
'\\' -> index += 1
'"' -> index += 1
'x' -> index += 3
else -> {}
}
}
index += 1
length += 1
}
return length
}
fun part1(input: List<String>): Int {
var rawCharsLength = 0
var inMemoryCharsLength = 0
input.forEach {
rawCharsLength += it.length
inMemoryCharsLength += stringInMemoryLength(it)
}
return rawCharsLength - inMemoryCharsLength
}
fun escapedStringLength(oldString: String): Int {
var newString = ""
oldString.forEach {
when (it) {
'\\' -> newString += "\\\\"
'"' -> newString += "\\\""
else -> newString += it
}
}
return newString.length + 2
}
fun part2(input: List<String>): Int {
var originalStringLength = 0
var newStringLength = 0
input.forEach {
originalStringLength += it.length
newStringLength += escapedStringLength(it)
// println("(${it.length}) $it ==> ${stringInMemoryLength(it)}")
}
return newStringLength - originalStringLength
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day08_test")
check(part1(testInput) == 12)
check(part2(testInput) == 19)
val input = readInput("Day08_data")
println("Part 1 answer: ${part1(input)}")
println("Part 2 answer: ${part2(input)}")
}
/**
* Reads lines from the given input txt file.
*/
fun readInput(name: String) = File("src", "$name.txt")
.readLines()
| 0 | Kotlin | 0 | 0 | 2f4be35e78a8a56fd1e078858f4965886dfcd7fd | 2,094 | AdventOfCode | MIT License |
kotlin/646.Maximum Length of Pair Chain(最长数对链).kt | learningtheory | 141,790,045 | false | {"Python": 4025652, "C++": 1999023, "Java": 1995266, "JavaScript": 1990554, "C": 1979022, "Ruby": 1970980, "Scala": 1925110, "Kotlin": 1917691, "Go": 1898079, "Swift": 1827809, "HTML": 124958, "Shell": 7944} | /**
<p>
You are given <code>n</code> pairs of numbers. In every pair, the first number is always smaller than the second number.
</p>
<p>
Now, we define a pair <code>(c, d)</code> can follow another pair <code>(a, b)</code> if and only if <code>b < c</code>. Chain of pairs can be formed in this fashion.
</p>
<p>
Given a set of pairs, find the length longest chain which can be formed. You needn't use up all the given pairs. You can select pairs in any order.
</p>
<p><b>Example 1:</b><br />
<pre>
<b>Input:</b> [[1,2], [2,3], [3,4]]
<b>Output:</b> 2
<b>Explanation:</b> The longest chain is [1,2] -> [3,4]
</pre>
</p>
<p><b>Note:</b><br>
<ol>
<li>The number of given pairs will be in the range [1, 1000].</li>
</ol>
</p><p>给出 <code>n</code> 个数对。 在每一个数对中,第一个数字总是比第二个数字小。</p>
<p>现在,我们定义一种跟随关系,当且仅当 <code>b < c</code> 时,数对<code>(c, d)</code> 才可以跟在 <code>(a, b)</code> 后面。我们用这种形式来构造一个数对链。</p>
<p>给定一个对数集合,找出能够形成的最长数对链的长度。你不需要用到所有的数对,你可以以任何顺序选择其中的一些数对来构造。</p>
<p><strong>示例 :</strong></p>
<pre>
<strong>输入:</strong> [[1,2], [2,3], [3,4]]
<strong>输出:</strong> 2
<strong>解释:</strong> 最长的数对链是 [1,2] -> [3,4]
</pre>
<p><strong>注意:</strong></p>
<ol>
<li>给出数对的个数在 [1, 1000] 范围内。</li>
</ol>
<p>给出 <code>n</code> 个数对。 在每一个数对中,第一个数字总是比第二个数字小。</p>
<p>现在,我们定义一种跟随关系,当且仅当 <code>b < c</code> 时,数对<code>(c, d)</code> 才可以跟在 <code>(a, b)</code> 后面。我们用这种形式来构造一个数对链。</p>
<p>给定一个对数集合,找出能够形成的最长数对链的长度。你不需要用到所有的数对,你可以以任何顺序选择其中的一些数对来构造。</p>
<p><strong>示例 :</strong></p>
<pre>
<strong>输入:</strong> [[1,2], [2,3], [3,4]]
<strong>输出:</strong> 2
<strong>解释:</strong> 最长的数对链是 [1,2] -> [3,4]
</pre>
<p><strong>注意:</strong></p>
<ol>
<li>给出数对的个数在 [1, 1000] 范围内。</li>
</ol>
**/
class Solution {
fun findLongestChain(pairs: Array<IntArray>): Int {
}
} | 0 | Python | 1 | 3 | 6731e128be0fd3c0bdfe885c1a409ac54b929597 | 2,510 | leetcode | MIT License |
aoc2023/src/main/kotlin/de/havox_design/aoc2023/day05/Almanac.kt | Gentleman1983 | 737,309,232 | false | {"Kotlin": 746488, "Java": 441473, "Scala": 33415, "Groovy": 5725, "Python": 3319} | package de.havox_design.aoc2023.day05
import de.havox_design.aoc.utils.kotlin.model.positions.Position3d
data class Almanac(val seeds: List<Long>, val maps: List<List<Position3d<Long>>>) {
fun seedsToLocation(): List<Long> =
seeds
.map { seed -> computeLocation(seed) }
fun seedRangesToLowestLocation(): Long {
var lowest = Long.MAX_VALUE
val ranges = seeds
.chunked(2)
.map { it[0]..<it[0] + it[1] }
for (range in ranges) {
for (i in range.first..range.last) {
val location = computeLocation(i)
if (location < lowest) {
lowest = location
}
}
}
return lowest
}
private fun computeLocation(seed: Long): Long {
var current = seed
for (element in maps) {
for (entry in element) {
val (destStart, sourceStart, length) = entry
if (current in sourceStart..<sourceStart + length) {
val delta = current - sourceStart
current = destStart + (delta)
break
}
}
}
return current
}
companion object {
fun from(input: List<String>): Almanac {
val seeds = input[0].substringAfter("seeds: ")
.split(" ")
.filter(String::isNotBlank)
.map(String::toLong)
val sublist = input.subList(1, input.size)
val maps = mutableListOf<List<Position3d<Long>>>()
var submap = mutableListOf<Position3d<Long>>()
for (i in sublist.indices) {
if ("map:" in sublist[i]) {
if (submap.isNotEmpty()) maps.add(submap)
submap = mutableListOf()
} else {
submap.add(
Position3d(
sublist[i].substringBefore(" ").toLong(),
sublist[i].substringAfter(" ").substringBefore(" ").toLong(),
sublist[i].substringAfterLast(" ").toLong()
)
)
}
}
if (submap.isNotEmpty()) maps.add(submap)
return Almanac(seeds, maps)
}
}
} | 4 | Kotlin | 0 | 1 | 35ce3f13415f6bb515bd510a1f540ebd0c3afb04 | 2,357 | advent-of-code | Apache License 2.0 |
year2020/day10/joltage/src/main/kotlin/com/curtislb/adventofcode/year2020/day10/joltage/JoltageAdapters.kt | curtislb | 226,797,689 | false | {"Kotlin": 2146738} | package com.curtislb.adventofcode.year2020.day10.joltage
import com.curtislb.adventofcode.common.collection.Counter
import com.curtislb.adventofcode.common.collection.FifoCache
/**
* A collection of distinct joltage adapters that may be chained to connect a compatible device to
* an outlet.
*
* @param ratings A set of values representing the joltage rating for each adapter.
*
* @throws IllegalArgumentException If the joltage rating of any adapter is negative or zero.
*/
class JoltageAdapters(ratings: Set<Int>) {
/**
* A sorted list of joltage ratings, including a rating of 0 jolts for the outlet.
*/
private val sortedRatings: List<Int> = mutableListOf(0).apply {
for (rating in ratings) {
require(rating > 0) { "Adapter rating must be positive: $rating" }
add(rating)
}
sort()
}
/**
* Returns the count of each joltage rating difference between subsequent adapters in a sorted
* adapter chain.
*
* Adapters are sorted in increasing order by joltage rating and connected to an outlet with an
* effective rating of 0 jolts. The difference between the minimum adapter rating and the
* outlet's rating is included in the result.
*/
fun countRatingDifferences(): Counter<Int> {
val counter = Counter<Int>()
for (index in 1..sortedRatings.lastIndex) {
val difference = sortedRatings[index] - sortedRatings[index - 1]
counter[difference]++
}
return counter
}
/**
* Returns the number of distinct ways that these adapters can be arranged to connect a device
* to an outlet.
*
* A valid arrangement consists of a subset of adapters connected to an outlet in increasing
* order by joltage rating, such that the difference in ratings between any two connected
* adapters is at most 3 jolts. For this purpose, the outlet is treated as an adapter with an
* effective rating of 0 jolts.
*/
fun countArrangements(): Long {
// Dynamically count the number of arrangements up to (and including) each adapter.
val prevCounts = FifoCache<Long>(3).apply { add(1L) }
for (i in 1..sortedRatings.lastIndex) {
// Combine counts from previous adapters that can be connected to the current one.
var count = 0L
prevCounts.forEachIndexed { j, prevCount ->
if (sortedRatings[i] - sortedRatings[i - prevCounts.size + j] <= 3) {
count += prevCount
}
}
prevCounts.add(count)
}
// The count for the last adapter is the same as the overall count.
return prevCounts.last()
}
}
| 0 | Kotlin | 1 | 1 | 6b64c9eb181fab97bc518ac78e14cd586d64499e | 2,747 | AdventOfCode | MIT License |
src/main/kotlin/leetcode/kotlin/string/767. Reorganize String.kt | sandeep549 | 251,593,168 | false | null | package leetcode.kotlin.string
import java.lang.StringBuilder
/**
* 1. Make frequency map of chars.
* 2. Take last two char of max frequency and append them, take max frequency one as first one always
* 3. modify used frequencies in list, and sort again according to frequencies
* 4. Repeat 2, 3 until list size is 1; check base case at size 1 and return answer.
*/
private fun reorganizeString(S: String): String {
var entries =
S.toCharArray()
.groupBy { it }.mapValues { it.value.size }.toList()
.sortedBy { it.second }
.toMutableList()
println(entries.toString())
var ans = StringBuilder()
while (entries.size > 0) {
println("---size is " + entries.size)
if (entries.size == 1 && entries.get(0).second >= 2) {
println("size is 1")
return ""
}
if (entries.size == 1) {
ans.append(entries[0].first)
break
}
var last = entries.size - 1
var limit = minOf(entries[last].second, entries[last - 1].second)
var c1 = entries[last].first
var c2 = entries[last - 1].first
while (limit > 0) {
ans.append(c1).append(c2)
limit--
}
if (entries[last].second == entries[last - 1].second) {
entries.removeAt(last)
entries.removeAt(last - 1)
} else if (entries[last - 1].second < entries[last].second) {
var pair = kotlin.Pair<Char, Int>(
entries[last].first,
entries[last].second - entries[last - 1].second
)
entries.removeAt(last)
entries.removeAt(last - 1)
entries.add(pair)
entries.sortBy { it.second }
} else {
var pair = kotlin.Pair<Char, Int>(
entries[last - 1].first,
entries[last - 1].second - entries[last].second
)
entries.removeAt(last)
entries.removeAt(last - 1)
entries.add(pair)
entries.sortBy { it.second }
}
}
return ans.toString()
}
fun main() {
// println(reorganizeString("aab"))
println(reorganizeString2("aaab"))
}
private fun reorganizeString2(S: String): String {
var arr = S.toCharArray()
var hash = IntArray(26)
for (c in arr) hash[c - 'a']++
var max = hash[0]
var letter = 0
for (i in 0 until 26) {
if (hash[i] > max) {
max = hash[i]
letter = i
}
}
if (max > (arr.size + 1) / 2) return ""
var ans = CharArray(arr.size)
var idx = 0
while (hash[letter] > 0) {
ans[idx] = 'a' + letter
idx += 2
hash[letter]--
}
for (i in 0 until 26) {
while (hash[i] > 0) {
if (idx >= arr.size) idx = 1
ans[idx] = 'a' + i
idx += 2
hash[i]--
}
}
return String(ans)
}
| 0 | Kotlin | 0 | 0 | 9cf6b013e21d0874ec9a6ffed4ae47d71b0b6c7b | 2,957 | kotlinmaster | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/WordSearch.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 dev.shtanko.algorithms.HALF_OF_BYTE
/**
* 79. Word Search
* @see <a href="https://leetcode.com/problems/word-search/">Source</a>
*/
fun interface WordSearch {
fun exist(board: Array<CharArray>, word: String): Boolean
}
class WordSearchShort : WordSearch {
override fun exist(board: Array<CharArray>, word: String): Boolean {
val w = word.toCharArray()
for (y in board.indices) {
for (x in 0 until board[y].size) {
if (exist(board, y, x, w, 0)) {
return true
}
}
}
return false
}
private fun exist(board: Array<CharArray>, y: Int, x: Int, word: CharArray, i: Int): Boolean {
if (i == word.size) {
return true
}
if (y < 0 || x < 0 || y == board.size || x == board[y].size) {
return false
}
if (board[y][x] != word[i]) {
return false
}
board[y][x] = (board[y][x].code xor HALF_OF_BYTE).toChar()
val exist = exist(board, y, x + 1, word, i + 1) || exist(board, y, x - 1, word, i + 1) || exist(
board,
y + 1,
x,
word,
i + 1,
) || exist(board, y - 1, x, word, i + 1)
board[y][x] = (board[y][x].code xor HALF_OF_BYTE).toChar()
return exist
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,003 | kotlab | Apache License 2.0 |
src/Day10.kt | ked4ma | 573,017,240 | false | {"Kotlin": 51348} | /**
* [Day10](https://adventofcode.com/2022/day/10)
*/
fun main() {
fun toOpFragments(input: List<String>): List<Int> = buildList {
input.forEach {
add(0)
if (it.startsWith("addx")) {
add(it.split(" ")[1].toInt())
}
}
}
fun part1(input: List<String>): Int {
val ops = toOpFragments(input)
var count = 0
var registerX = 1
ops.take(220).forEachIndexed { i, v ->
val j = i + 1
if ((j + 20) % 40 == 0) {
count += j * registerX
}
registerX += v
}
return count
}
fun part2(input: List<String>): String {
val ops = toOpFragments(input)
var registerX = 1
return buildList {
ops.take(240).chunked(40).forEach { chunk ->
add(buildString {
chunk.forEachIndexed { i, v ->
val j = i + 1
append(if (j in registerX..registerX + 2) '#' else '.')
registerX += v
}
})
}
}.joinToString(separator = "\n")
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day10_test")
check(part1(testInput) == 13140)
check(part2(testInput) == listOf(
"##..##..##..##..##..##..##..##..##..##..",
"###...###...###...###...###...###...###.",
"####....####....####....####....####....",
"#####.....#####.....#####.....#####.....",
"######......######......######......####",
"#######.......#######.......#######....."
).joinToString(separator = "\n"))
val input = readInput("Day10")
println(part1(input))
println(part2(input))
} | 1 | Kotlin | 0 | 0 | 6d4794d75b33c4ca7e83e45a85823e828c833c62 | 1,854 | aoc-in-kotlin-2022 | Apache License 2.0 |
src/Day08.kt | rmyhal | 573,210,876 | false | {"Kotlin": 17741} | import kotlin.math.max
fun main() {
fun part1(input: List<String>): Int {
return visibleTrees(input)
}
fun part2(input: List<String>): Int {
return highestScenic(input)
}
val input = readInput("Day08")
println(part1(input))
println(part2(input))
}
private fun visibleTrees(input: List<String>): Int {
val topBottom = input[0].length * 2
val leftRight = input.size * 2 - 4
val exterior = topBottom + leftRight
var interior = 0
for (i in 1 until input.size - 1) {
for (j in 1 until input[i].length - 1) {
val tree = input[i][j].digitToInt()
var hasTopBlocking = false
var hasLeftBlocking = false
var hasRightBlocking = false
var hasBottomBlocking = false
for (ti in i - 1 downTo 0) {
// to top
val top = input[ti][j].digitToInt()
if (top >= tree) {
hasTopBlocking = true
}
}
for (ti in j - 1 downTo 0) {
// to left
val left = input[i][ti].digitToInt()
if (left >= tree) {
hasLeftBlocking = true
}
}
for (ti in j + 1 until input.size) {
// to right
val right = input[i][ti].digitToInt()
if (right >= tree) {
hasRightBlocking = true
}
}
for (ti in i + 1 until input[i].length) {
// to bottom
val bottom = input[ti][j].digitToInt()
if (bottom >= tree) {
hasBottomBlocking = true
}
}
if (!hasTopBlocking || !hasLeftBlocking || !hasBottomBlocking || !hasRightBlocking) {
interior++
}
}
}
return exterior + interior
}
private fun highestScenic(input: List<String>): Int {
var maxScenic = 0
for (i in 1 until input.size - 1) {
for (j in 1 until input[i].length - 1) {
val tree = input[i][j].digitToInt()
var topCount = 0
var leftCount = 0
var rightCount = 0
var bottomCount = 0
for (k in i - 1 downTo 0) {
// to top
val top = input[k][j].digitToInt()
topCount++
if (top >= tree) {
break
}
}
for (k in j - 1 downTo 0) {
// to left
val left = input[i][k].digitToInt()
leftCount++
if (left >= tree) {
break
}
}
for (k in j + 1 until input.size) {
// to right
val right = input[i][k].digitToInt()
rightCount++
if (right >= tree) {
break
}
}
for (k in i + 1 until input[i].length) {
// to bottom
val bottom = input[k][j].digitToInt()
bottomCount++
if (bottom >= tree) {
break
}
}
val scenic = topCount * leftCount * rightCount * bottomCount
maxScenic = max(maxScenic, scenic)
}
}
return maxScenic
} | 0 | Kotlin | 0 | 0 | e08b65e632ace32b494716c7908ad4a0f5c6d7ef | 2,821 | AoC22 | Apache License 2.0 |
2022/kotlin/app/src/main/kotlin/day07/Day07.kt | jghoman | 726,228,039 | false | {"Kotlin": 15309, "Rust": 14555, "Scala": 1804, "Shell": 737} | package day07
import java.lang.Exception
import java.util.Stack
val testInput = "\$ cd /\n" +
"\$ ls\n" +
"dir a\n" +
"14848514 b.txt\n" +
"8504156 c.dat\n" +
"dir d\n" +
"\$ cd a\n" +
"\$ ls\n" +
"dir e\n" +
"29116 f\n" +
"2557 g\n" +
"62596 h.lst\n" +
"\$ cd e\n" +
"\$ ls\n" +
"584 i\n" +
"\$ cd ..\n" +
"\$ cd ..\n" +
"\$ cd d\n" +
"\$ ls\n" +
"4060174 j\n" +
"8033020 d.log\n" +
"5626152 d.ext\n" +
"7214296 k"
sealed class Node() {
data class Directory(val name: String):Node() {
val nodes = ArrayList<Node>()
override fun size() = nodes.sumOf { it.size() }
fun addNode(node: Node) = nodes.add(node)
override fun toString(): String {
return "File(name='$name', totalSize=${size()})"
}
}
data class File(val name: String, val size: Long): Node() {
override fun size() = size
override fun toString(): String {
return "File(name='$name', size=$size)"
}
}
abstract fun size():Long
}
fun printNode(node: Node, offset:Int = 0) {
val sb = StringBuilder("")
for(i in 0..offset) sb.append(" ")
when(node) {
is Node.Directory -> {
println("${sb}${node.name}")
node.nodes.forEach { printNode(it, offset + 1)}
}
is Node.File -> println("${sb}${node.name} ${node.size}")
}
}
fun allDirs(node: Node): List<Node.Directory> {
when(node) {
is Node.Directory -> return (node.nodes.map{ allDirs(it) }.flatten()) + node
is Node.File -> return ArrayList()
}
}
fun part1(input: String): Pair<Long, Node.Directory> {
val lines = input
.split("\n")
val root = Node.Directory("/")
val dirStack = Stack<Node.Directory>()
dirStack.add(root)
var currentDir = root;
for(line in lines) {
if(line.equals("$ ls")) {
continue
//println("LS-ing")
} else if (line.startsWith("dir")) {
val dirName = line.split(" ")[1];
currentDir.addNode(Node.Directory(dirName))
} else if (line[0].isDigit()) {
val split = line.split(" ")
val fileName = split[1]
val size = split[0].toLong()
currentDir.addNode(Node.File(fileName, size))
} else if (line.equals("$ cd ..")) {
if (dirStack.size == 1) {
currentDir = root
} else {
currentDir = dirStack.pop();
}
} else if (line.equals("$ cd /")) {
dirStack.clear()
dirStack.add(root)
} else if (line.startsWith("$ cd ")) {
val targetDir = line.split(" ")[2]
val targetNode = currentDir.nodes.find {it is Node.Directory && it.name.equals(targetDir)} as Node.Directory
if(targetNode == null) {
throw Exception("No such dir.")
}
if(!(dirStack.size == 1 && currentDir == root)) {
dirStack.push(currentDir)
}
currentDir = targetNode
} else {
println("Huh? $line")
}
}
return Pair(allDirs(root)
.filter { it.size() <= 100000 }
.sumOf { it.size() }, root)
}
fun part2(root:Node): Long {
val totalSize = 70000000
val needed = 30000000
val freeSpace = totalSize - root.size()
val needToFree = needed - freeSpace
return allDirs(root)
.map { it.size() }
.filter { it >= needToFree }
.minBy { it }
}
fun main() {
val realInput = util.readFileUsingGetResource("day-7-input.txt")
val input = realInput
val (partOneSize, root) = part1(input)
println("Part 1 result: $partOneSize")
println("Part 2 result: ${part2(root)}")
} | 0 | Kotlin | 0 | 0 | 2eb856af5d696505742f7c77e6292bb83a6c126c | 3,910 | aoc | Apache License 2.0 |
src/day10/Day10.kt | andreas-eberle | 573,039,929 | false | {"Kotlin": 90908} | package day10
import readInput
import kotlin.math.absoluteValue
const val day = "10"
fun main() {
fun calculatePart1Score(input: List<String>): Int {
val allX = input.executeProgram()
return allX.mapIndexed { index, x -> (1 + index) * x }.slice(19..allX.size step 40).sum()
}
fun calculatePart2Score(input: List<String>): String {
val allX = input.executeProgram()
val screen = (0 until 6).map { yPos ->
(0 until 40).map { xPos ->
val cycle = xPos + yPos * 40
val x = allX[cycle]
if ((xPos - x).absoluteValue <= 1) {
"#"
} else {
"."
}
}.joinToString("")
}.joinToString("\n")
return screen
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("/day$day/Day${day}_test")
val input = readInput("/day$day/Day${day}")
val part1TestPoints = calculatePart1Score(testInput)
val part1Points = calculatePart1Score(input)
println("Part1 test points: $part1TestPoints")
println("Part1 points: $part1Points")
check(part1TestPoints == 13140)
val part2TestPoints = calculatePart2Score(testInput)
val part2Points = calculatePart2Score(input)
println("Part2 test points: \n$part2TestPoints")
println("Part2 points: \n$part2Points")
check(
part2TestPoints == """
##..##..##..##..##..##..##..##..##..##..
###...###...###...###...###...###...###.
####....####....####....####....####....
#####.....#####.....#####.....#####.....
######......######......######......####
#######.......#######.......#######.....
""".trimIndent()
)
}
fun List<String>.executeProgram(): List<Int> {
return flatMap {
when {
it.startsWith("addx") -> listOf("noop", it)
else -> listOf(it)
}
}.runningFold(1) { x, command ->
when {
command.startsWith("addx ") -> x + command.substringAfter("addx ").toInt()
else -> x
}
}
} | 0 | Kotlin | 0 | 0 | e42802d7721ad25d60c4f73d438b5b0d0176f120 | 2,156 | advent-of-code-22-kotlin | Apache License 2.0 |
Examples.kt | callej | 428,413,375 | false | {"Kotlin": 9131} | // Code examples in Kotlin
// This file contains some very basic Kotlin code constructs.
// It is part of the JetBrains Academy Kotlin Course.
// The code below are some examples of how basic Kotlin code can be written.
// It is a playground with some funny implementations and some experiments on what works and what doesn't.
// It is also a playground on how to write short code, how to write readable code, and how to write understandable code.
// Short code is usually good. But sometimes the shortest code is not the best (and sometimes it is).
// While loops - Find max
fun main() {
var max = 0
do {
val num = readLine()!!.toInt()
if (num > max) max = num
} while (num != 0)
println(max)
}
// =======================================================================================================
// While loops - The sum of elements
fun main() {
var sum = 0
do {
val num = readLine()!!.toInt()
sum += num
} while (num != 0)
println(sum)
}
// =======================================================================================================
// While loops - Collatz conjecture
fun main() {
var num = readLine()!!.toInt()
print("$num ")
while (num != 1) {
if (num % 2 == 0) num /= 2
else num = 3 * num + 1
print("$num ")
}
}
// =======================================================================================================
// While loops - The sequence 1 2 2 3 3 3 ...
import kotlin.math.sqrt
fun main() {
val n = readLine()!!.toInt()
var result = ""
for (i in 1..(sqrt(2.0 * n.toDouble() + 1.0).toInt() + 1)) {
repeat(i) { result += if (i * (i - 1) / 2 + it < n) "$i " else "" }
}
println(result)
}
// ----------------------------------------------------------------------------------------
fun main() {
println(
generateSequence(1) { it + 1 }
.flatMap { i -> List(i) { i } }
.take(readLine()!!.toInt())
.toList()
.joinToString(" ")
)
}
// =======================================================================================================
// Oneliners
fun main() = repeat(1 + 1 + 1 + 1 + 1, { println("Kotlin") })
// ----------------------------------------------------------------------------------------
fun main() = println(if (readLine()!!.toInt() % 2 == 0) "EVEN" else "ODD")
// ----------------------------------------------------------------------------------------
fun main() = println(with(readLine()!!.toInt()) { if (this < 0) "negative" else if (this > 0) "positive" else "zero" })
// =======================================================================================================
// Size of parts
const val CATEGORIES = 3 // -1 = too small, 0 = perfect, 1 = too big
fun main() {
val n = readLine()!!.toInt()
val components = MutableList(CATEGORIES) { 0 }
repeat(n) { components[readLine()!!.toInt() % 2 + 1] += 1 }
println("${components[1]} ${components[2]} ${components[0]}")
}
// =======================================================================================================
// Leap Year
const val F = 4
const val OH = 100
const val FH = 400
fun main() {
with(readLine()!!.toInt()) { println(if (this % F == 0 && this % OH != 0 || this % FH == 0) "Leap" else "Regular") }
}
// =======================================================================================================
// Balance Checker
fun main() {
var balance = readLine()!!.toInt()
val purchases = readLine()!!.split(" ").map { it.toInt() }
var funds = true
for (purchase in purchases) {
if (balance - purchase < 0) {
println("Error, insufficient funds for the purchase. Your balance is $balance, but you need $purchase.")
funds = false
break
} else {
balance -= purchase
}
}
if (funds) {
println("Thank you for choosing us to manage your account! Your balance is $balance.")
}
}
// =======================================================================================================
// Initializing Mutable Lists
const val MAGIC_NUMBERS = "12 17 8 101 33"
fun main() {
val numbers = MAGIC_NUMBERS.split(" ").map { it.toInt() }
println(numbers.joinToString())
}
// ----------------------------------------------------------------------------------------
const val MAGIC_NUMBERS = "100_000_000_001 100_000_000_002 100_000_000_003"
fun main() {
val longs = MAGIC_NUMBERS.split(" ").map { it.replace("_", "").toLong() }
println(longs.joinToString())
}
| 0 | Kotlin | 0 | 0 | 59120fc9bbbf8c9ec5af8b363fab26238f7adbb4 | 4,665 | Zoo-Keeper | MIT License |
src/main/kotlin/com/jaspervanmerle/aoc2021/day/Day16.kt | jmerle | 434,010,865 | false | {"Kotlin": 60581} | package com.jaspervanmerle.aoc2021.day
class Day16 : Day("1007", "834151779165") {
private class Bits(input: String) {
private var bits = input
.toCharArray()
.joinToString("") { it.digitToInt(16).toString(2).padStart(4, '0') }
fun popBits(bitCount: Int): String {
val removedBits = bits.substring(0, bitCount)
bits = bits.substring(bitCount)
return removedBits
}
fun popInt(bitCount: Int): Int {
return popBits(bitCount).toInt(2)
}
fun getSize(): Int {
return bits.length
}
fun isEmpty(): Boolean {
return !bits.contains('1')
}
}
private interface Packet {
companion object {
fun parse(bits: Bits): Packet {
bits.popBits(3)
return when (val packetTypeId = bits.popInt(3)) {
4 -> LiteralPacket(bits)
0 -> SumPacket(bits)
1 -> ProductPacket(bits)
2 -> MinimumPacket(bits)
3 -> MaximumPacket(bits)
5 -> GreaterThanPacket(bits)
6 -> LessThanPacket(bits)
7 -> EqualToPacket(bits)
else -> throw IllegalArgumentException("Unknown packet type id $packetTypeId")
}
}
}
fun evaluate(): Long
}
private class LiteralPacket(bits: Bits) : Packet {
var value: Long
init {
val valueBits = StringBuilder()
while (true) {
val part = bits.popBits(5)
valueBits.append(part.substring(1))
if (part[0] == '0') {
break
}
}
value = valueBits.toString().toLong(2)
}
override fun evaluate(): Long {
return value
}
}
private abstract class OperatorPacket(bits: Bits) : Packet {
val subPackets = mutableListOf<Packet>()
init {
val lengthTypeId = bits.popInt(1)
if (lengthTypeId == 0) {
val bitLength = bits.popInt(15)
val bitSizeEnd = bits.getSize() - bitLength
while (bits.getSize() > bitSizeEnd) {
subPackets.add(Packet.parse(bits))
}
} else {
val subPacketCount = bits.popInt(11)
for (i in 0 until subPacketCount) {
subPackets.add(Packet.parse(bits))
}
}
}
}
private class SumPacket(bits: Bits) : OperatorPacket(bits) {
override fun evaluate(): Long {
return subPackets.sumOf { it.evaluate() }
}
}
private class ProductPacket(bits: Bits) : OperatorPacket(bits) {
override fun evaluate(): Long {
return subPackets.fold(1L) { acc, packet -> acc * packet.evaluate() }
}
}
private class MinimumPacket(bits: Bits) : OperatorPacket(bits) {
override fun evaluate(): Long {
return subPackets.minOf { it.evaluate() }
}
}
private class MaximumPacket(bits: Bits) : OperatorPacket(bits) {
override fun evaluate(): Long {
return subPackets.maxOf { it.evaluate() }
}
}
private class GreaterThanPacket(bits: Bits) : OperatorPacket(bits) {
override fun evaluate(): Long {
return if (subPackets[0].evaluate() > subPackets[1].evaluate()) 1L else 0L
}
}
private class LessThanPacket(bits: Bits) : OperatorPacket(bits) {
override fun evaluate(): Long {
return if (subPackets[0].evaluate() < subPackets[1].evaluate()) 1L else 0L
}
}
private class EqualToPacket(bits: Bits) : OperatorPacket(bits) {
override fun evaluate(): Long {
return if (subPackets[0].evaluate() == subPackets[1].evaluate()) 1L else 0L
}
}
override fun solvePartOne(): Any {
val bits = Bits(input)
var versionSum = 0
while (!bits.isEmpty()) {
versionSum += bits.popInt(3)
val packetTypeId = bits.popInt(3)
if (packetTypeId == 4) {
while (true) {
val part = bits.popBits(5)
if (part[0] == '0') {
break
}
}
} else {
val lengthTypeId = bits.popInt(1)
if (lengthTypeId == 0) {
bits.popBits(15)
} else {
bits.popBits(11)
}
}
}
return versionSum
}
override fun solvePartTwo(): Any {
return Packet.parse(Bits(input)).evaluate()
}
}
| 0 | Kotlin | 0 | 0 | dcac2ac9121f9bfacf07b160e8bd03a7c6732e4e | 4,856 | advent-of-code-2021 | MIT License |
year2023/src/main/kotlin/net/olegg/aoc/year2023/day21/Day21.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.year2023.day21
import net.olegg.aoc.someday.SomeDay
import net.olegg.aoc.utils.Directions
import net.olegg.aoc.utils.Vector2D
import net.olegg.aoc.utils.find
import net.olegg.aoc.utils.get
import net.olegg.aoc.year2023.DayOf2023
/**
* See [Year 2023, Day 21](https://adventofcode.com/2023/day/21)
*/
object Day21 : DayOf2023(21) {
override fun first(): Any? {
val start = matrix.find('S')!!
val toVisit = mutableMapOf(0 to mutableSetOf(start))
(0..<64).forEach { step ->
val nodes = ArrayDeque(toVisit.getValue(step))
val next = mutableSetOf<Vector2D>()
while (nodes.isNotEmpty()) {
val curr = nodes.removeFirst()
next += Directions.NEXT_4
.map { curr + it.step }
.filter { matrix[it] == '.' || matrix[it] == 'S' }
}
toVisit[step + 1] = next
}
return toVisit[64]!!.size
}
override fun second(): Any? {
val cover = 3
val max = 26501365
val start = matrix.find('S')!!
val size = matrix.size
val tail = max % size
val maxTile = (max / size).toLong()
val toVisit = mutableMapOf(0 to mutableSetOf(start))
(0..<(size * cover + tail)).forEach { step ->
val nodes = ArrayDeque(toVisit.getValue(step))
val next = mutableSetOf<Vector2D>()
while (nodes.isNotEmpty()) {
val curr = nodes.removeFirst()
next += Directions.NEXT_4
.map { curr + it.step }
.filter {
val fit = Vector2D(
((it.x % size) + size) % size,
((it.y % size) + size) % size,
)
matrix[fit] == '.' || matrix[fit] == 'S'
}
}
toVisit[step + 1] = next
}
val map = (-cover..cover).map { y ->
val startY = y * size
val endY = (y + 1) * size
(-cover..cover).map { x ->
val startX = x * size
val endX = (x + 1) * size
toVisit[tail + size * cover]!!.count { it.x in startX..<endX && it.y in startY..<endY }
}
}
return (map[3][0] + map[0][3] + map[3][6] + map[6][3]) +
maxTile * (map[2][0] + map[4][0] + map[2][6] + map[4][6]) +
(maxTile - 1) * (map[2][1] + map[4][1] + map[2][5] + map[4][5]) +
(maxTile - 1) * (maxTile - 1) * map[3][4] +
(maxTile * maxTile * map[3][3])
}
}
fun main() = SomeDay.mainify(Day21)
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 2,346 | adventofcode | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/SumOfLeftLeaves.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2020 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import java.util.LinkedList
import java.util.Queue
import java.util.Stack
fun interface SumOfLeftLeavesStrategy {
operator fun invoke(root: TreeNode?): Int
}
class SumOfLeftLeavesIterative : SumOfLeftLeavesStrategy {
override operator fun invoke(root: TreeNode?): Int {
if (root == null) return 0
var ans = 0
val stack: Stack<TreeNode> = Stack<TreeNode>()
stack.push(root)
while (!stack.empty()) {
val node: TreeNode = stack.pop()
if (node.left != null) {
if (node.left?.left == null && node.left?.right == null) {
ans += node.left?.value ?: 0
} else {
stack.push(node.left)
}
}
if (node.right != null && node.right?.left != null || node.right?.right != null) {
stack.push(node.right)
}
}
return ans
}
}
class SumOfLeftLeavesRecursive : SumOfLeftLeavesStrategy {
override operator fun invoke(root: TreeNode?): Int {
if (root == null) return 0
var ans = 0
if (root.left != null) {
ans += if (root.left?.left == null && root.left?.right == null) {
root.left?.value ?: 0
} else {
invoke(root.left)
}
}
ans += invoke(root.right)
return ans
}
}
class SumOfLeftLeavesBSF : SumOfLeftLeavesStrategy {
override operator fun invoke(root: TreeNode?): Int {
if (root == null) return 0
val queue: Queue<TreeNode> = LinkedList()
queue.add(root)
var sum = 0
while (queue.isNotEmpty()) {
val presentNode: TreeNode = queue.poll()
if (presentNode.left != null) {
queue.add(presentNode.left)
}
if (presentNode.right != null) {
queue.add(presentNode.right)
}
if (presentNode.left != null && presentNode.left?.left == null && presentNode.left?.right == null) {
sum += presentNode.left?.value ?: 0
}
}
return sum
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,795 | kotlab | Apache License 2.0 |
src/main/kotlin/days/Day20.kt | mstar95 | 317,305,289 | false | null | package days
class Day20 : Day(20) {
val bodyRegex = Regex("#....##....##....###")
val legsRegex = Regex(".#..#..#..#..#..#...")
override fun partOne(): Any {
val tiles = prepareInput(inputString)
findConnected(tiles)
val corners = tiles.filter { it.connections.size == 2 }.map { it.id }
return corners.fold(1L) { a, b -> a * b }
}
override fun partTwo(): Any {
val tiles = prepareInput(inputString)
findConnected(tiles)
val corner = tiles.filter { it.connections.size == 2 }.first()
val image1 = Image(buildImage(tiles, rotateCorner(tiles, corner), 1))
val image = Image(buildImage(tiles, rotateCorner(tiles, corner), 2))
image.printImage()
// println("NEW")
// image.rotate().printImage()
val monsters = image.rotations().map { findMonsters(it) }.filter { it != 0 }.first()
val hashes = image.image.flatMap { it.filter { it == '#' }.toList() }.size
val hashesInMonster = (bodyRegex.pattern + legsRegex.pattern).filter { it == '#' }.length + 1
return hashes - hashesInMonster * monsters
}
fun findMonsters(image: Image): Int {
// println("NEW")
// image.printImage()
return image.image.mapIndexed { idx, row ->
val bodies = bodyRegex.find(row)
findMonsters(image.image, idx, bodies)
}.filter { it != 0 }.sum()
}
fun findMonsters(image: List<String>, idx: Int, bodies: MatchResult?): Int {
if (bodies == null || idx == 0 || idx + 1 == image.size) {
return 0
}
val range = bodies.range
val head = image[idx - 1][range.last - 1]
// println(head)
if (head != '#') {
return findMonsters(image, idx, bodies.next())
}
val legs = image[idx + 1].substring(range)
// println(legs)
if (legsRegex.matches(legs)) {
return 1 + findMonsters(image, idx, bodies.next())
}
return findMonsters(image, idx, bodies.next())
}
fun findConnected(tiles: List<Tile>) {
return tiles.forEach { t1 -> tiles.forEach { t2 -> connectImages(t1, t2) } }
}
fun buildImage(tiles: List<Tile>, current: Tile, v: Int): List<String> {
val side = current.bottom
val bottomConnection = current.connections.map { c -> getTile(tiles, c) }
.mapNotNull { rotateToConnect(side, it, 0) }.firstOrNull()
if (bottomConnection == null) {
return buildRow(tiles, current, v)
}
return buildRow(tiles, current, v) + buildImage(tiles, bottomConnection, v)
}
fun buildRow(tiles: List<Tile>, current: Tile, v: Int): List<String> {
val side = current.right
val rightConnection = current.connections.map { c -> getTile(tiles, c) }
.mapNotNull { rotateToConnect(side, it, 3) }.firstOrNull()
if (rightConnection == null) {
return if (v == 2) current.withoutBorders() else current.image
}
return concatRows(if (v == 2) current.withoutBorders() else current.image, buildRow(tiles, rightConnection, v))
}
fun concatRows(r1: List<String>, r2: List<String>): List<String> {
return r1.mapIndexed { idx, it -> it + r2[idx] }
}
fun rotateCorner(tiles: List<Tile>, corner: Tile): Tile {
val rotations = corner.rotations()
val connections = listOf(0, 1)
return rotations.first { r -> connections.map { c -> findSide(tiles, r, c) }.toSet() == setOf(1, 2) }
}
fun findSide(tiles: List<Tile>, corner: Tile, connection: Int): Int {
val tile = tiles.first { it.id == corner.connections[connection] }
val side = corner.sides.mapIndexed { id, it -> id to it }.first { c -> tile.permutations.any { c.second == it } }
return side.first
}
private fun getTile(tiles: List<Tile>, c: Int) = tiles.first { it.id == c }
fun rotateToConnect(sideToConnect: String, tile: Tile, fromSide: Int): Tile? {
val rotations = tile.rotations()
return rotations.firstOrNull { it.sides[fromSide] == sideToConnect }
}
fun connectImages(a: Tile, b: Tile) {
if (a == b) {
return
}
if (a.connections.contains(b.id)) {
return
}
if (a.permutations.any { p1 -> b.permutations.any { p2 -> p1 == p2 } }) {
a.connections.add(b.id)
b.connections.add(a.id)
}
}
private fun prepareInput(input: String): List<Tile> {
return input.split("\n\n").map { prepareTile(it.split("\n")) }
}
private fun prepareTile(input: List<String>): Tile {
val id = input.first().drop("Tile ".length).dropLast(":".length).toInt()
val body = input.drop(1)
return Tile(id, body)
}
}
data class Tile(val id: Int, val image: List<String>, val connections: MutableList<Int> = mutableListOf()) {
val sides = buildSides()
val permutations = sides + sides.map { it.reversed() }
val right: String
get() = sides[1]
val bottom: String
get() = sides[2]
fun printImage() {
image.forEach { println(it) }
}
fun withoutBorders(): List<String> {
return image.drop(1).dropLast(1).map { it.drop(1).dropLast(1) }
}
fun rotate(): Tile {
val rows = mutableListOf<String>()
image.forEach { row ->
row.forEachIndexed { columntId, char ->
val r = rows.getOrElse(columntId) {
rows.add("")
""
}
rows[columntId] = (char + r)
}
}
return copy(image = rows)
}
fun rotate2() = this.rotate().rotate()
fun rotate3() = this.rotate2().rotate()
fun flip() = copy(image = image.reversed())
fun rotations() = listOf(this, this.rotate(), this.rotate2(), this.rotate3(), this.flip(),
this.flip().rotate(), this.flip().rotate2(), this.flip().rotate3())
.distinct()
private fun buildSides(): List<String> {
val a: String = image.first()
val b: String = image.map { it.last() }.joinToString("")
val c: String = image.last()
val d: String = image.map { it.first() }.joinToString("")
return listOf(a, b, c, d)
}
}
data class Image(val image: List<String>) {
fun printImage() {
image.forEach { println(it) }
}
fun flip() = copy(image = image.reversed())
fun rotate(): Image {
val rows = mutableListOf<String>()
image.forEach { row ->
row.forEachIndexed { columntId, char ->
val r = rows.getOrElse(columntId) {
rows.add("")
""
}
rows[columntId] = (char + r)
}
}
return copy(image = rows)
}
fun rotate2() = this.rotate().rotate()
fun rotate3() = this.rotate2().rotate()
fun rotations() = listOf(this, this.rotate(), this.rotate2(), this.rotate3(), this.flip(),
this.flip().rotate(), this.flip().rotate2(), this.flip().rotate3())
.distinct()
}
| 0 | Kotlin | 0 | 0 | ca0bdd7f3c5aba282a7aa55a4f6cc76078253c81 | 7,189 | aoc-2020 | Creative Commons Zero v1.0 Universal |
src/main/kotlin/twentytwentytwo/Day25.kt | JanGroot | 317,476,637 | false | {"Kotlin": 80906} | package twentytwentytwo
import kotlin.math.pow
fun main() {
val input = {}.javaClass.getResource("input-25.txt")!!.readText().linesFiltered { it.isNotEmpty() };
val day = Day25(input)
println(day.part1())
}
class Day25(private val input: List<String>) {
fun part1(): String {
return getElvesNumber(input.sumOf { l ->
getNumber(l)
})
}
private fun getNumber(l: String): Long {
var total = 0.0
l.reversed().forEachIndexed { index, c ->
total += getDecimal(c) * 5.0.pow(index)
}
return total.toLong()
}
private fun getElvesNumber(n: Long): String {
var temp = n
var result = ""
while (temp > 0) {
println(temp)
when (temp % 5) {
0L -> result += '0'
1L -> result += '1'
2L -> result += '2'
4L -> result += '-'
3L -> result += '='
}
temp += 2
temp /= 5
}
return result.reversed()
}
private fun getDecimal(c: Char): Long {
return when (c) {
'1' -> 1
'2' -> 2
'0' -> 0
'-' -> -1
'=' -> -2
else -> {
error("oops")
}
}
}
}
| 0 | Kotlin | 0 | 0 | 04a9531285e22cc81e6478dc89708bcf6407910b | 1,332 | aoc202xkotlin | The Unlicense |
src/Day06.kt | Inn0 | 573,532,249 | false | {"Kotlin": 16938} | fun main() {
fun getMarker(input: String, markerVal: Int): Int {
var counter = 0
while(counter + markerVal <= input.length){
val substr = input.substring(counter, counter + markerVal)
if(substr.toCharArray().distinct().size == substr.length){
break
}
counter ++
}
return counter + markerVal
}
fun part1(input: List<String>): Int {
return getMarker(input[0], 4)
}
fun part2(input: List<String>): Int {
return getMarker(input[0], 14)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day06_test")
check(part1(testInput) == 7)
// check(part2(testInput) == 0)
val input = readInput("Day06")
println("Part 1: " + part1(input))
println("Part 2: " + part2(input))
}
| 0 | Kotlin | 0 | 0 | f35b9caba5f0c76e6e32bc30196a2b462a70dbbe | 874 | aoc-2022 | Apache License 2.0 |
src/Day10.kt | davidkna | 572,439,882 | false | {"Kotlin": 79526} | fun main() {
fun part1(input: List<String>): Int {
var x = 1
var signalStrength = 0
var cycle = -19
input.map { it.split(" ") }.forEach { ins ->
val cycleDuration = when (ins[0]) {
"noop" -> 1
"addx" -> 2
else -> throw Exception("Unknown instruction")
}
for (i in 1..cycleDuration) {
if (cycle % 40 == 0) {
signalStrength += x * (cycle + 20)
}
cycle++
}
x += ins.getOrElse(1) { "0" }.toInt()
}
return signalStrength
}
fun part2(input: List<String>): String {
val output = arrayListOf(Array(40) { '.' })
var x = 1
var cycle = 0
input.map { it.split(" ") }.forEach { ins ->
val cycleDuration = when (ins[0]) {
"noop" -> 1
"addx" -> 2
else -> throw Exception("Unknown instruction")
}
for (i in 1..cycleDuration) {
if ((x - 1..x + 1).contains(cycle % 40)) {
if (cycle / 40 >= output.size) {
output.add(Array(40) { '.' })
}
output[cycle / 40][cycle % 40] = '#'
}
cycle++
}
x += ins.getOrElse(1) { "0" }.toInt()
}
return output.joinToString("\n") { it.joinToString("") }
}
val testInput = readInput("Day10_test")
check(part1(testInput) == 13140)
check(
part2(testInput) == """
##..##..##..##..##..##..##..##..##..##..
###...###...###...###...###...###...###.
####....####....####....####....####....
#####.....#####.....#####.....#####.....
######......######......######......####
#######.......#######.......#######.....
""".trimIndent(),
)
val input = readInput("Day10")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | ccd666cc12312537fec6e0c7ca904f5d9ebf75a3 | 2,040 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/Main.kt | goetz-markgraf | 754,010,781 | false | {"Kotlin": 4778} | import java.lang.Integer.max
import java.lang.Integer.min
import kotlin.math.abs
enum class Function {
CHECK, PLACE
}
enum class Player {
PLAYER1, PLAYER2
}
data class Position(
val col: Int,
val row: Int
)
data class Ship(
var parts: List<Position>
)
typealias Field = Array<Array<Int>>
data class GameState(
val field1: Field,
val field2: Field,
val ships1: List<Ship>,
val ships2: List<Ship>
)
fun main() {
var gameState = createGameState()
showField(gameState, Player.PLAYER1)
while (true) {
print("Enter ship coordinates: ")
gameState = place(gameState, Player.PLAYER1)
showField(gameState, Player.PLAYER1)
}
}
fun createGameState(): GameState {
val field1 = Array(10) { Array(10) { 0 } }
val field2 = Array(10) { Array(10) { 0 } }
return GameState(field1, field2, emptyList(), emptyList())
}
fun showField(gameState: GameState, player: Player) {
for (row in '0'..'9') {
print("\t $row")
}
println()
val tabVertLine = "\t${9474.toChar()}"
val ships = if (player == Player.PLAYER1) gameState.ships1 else gameState.ships2
for (col in 0 until 10) {
print(" " + (col + 65).toChar() + tabVertLine)
for (row in 0 until 10) {
var shipFound = false
ships.forEach {
it.parts.forEach {
if (it.row == row && it.col == col) {
shipFound = true
}
}
}
if (shipFound) {
print("██")
}
print(tabVertLine)
}
println()
}
}
fun place(gameState: GameState, player: Player): GameState {
val location = readln().lowercase()
println("inside place")
val ships = (if (player == Player.PLAYER1) gameState.ships1 else gameState.ships2).toMutableList()
if (inputIsValid(Function.PLACE, location)) {
val coordinates = convertPair(location)
val firstPos =
Pair(min(coordinates.first.row, coordinates.second.row), min(coordinates.first.col, coordinates.second.col))
val lastPos =
Pair(max(coordinates.first.row, coordinates.second.row), max(coordinates.first.col, coordinates.second.col))
println(coordinates)
val n = mutableListOf<Position>()
for (row in firstPos.first..lastPos.first) {
for (col in firstPos.second..lastPos.second) {
if (isCellOccupied(gameState, player, Position(col, row))) {
println("This cell is occupied")
return gameState
} else {
println("set at $row,$col")
n.add(Position(col, row))
}
}
}
ships.addLast(Ship(n))
}
return if (player == Player.PLAYER1) {
gameState.copy(ships1 = ships)
} else {
gameState.copy(ships2 = ships)
}
}
fun isCellOccupied(gameState: GameState, player: Player, position: Position): Boolean {
val ships = if (player == Player.PLAYER1) gameState.ships1 else gameState.ships2
return ships.any { ship -> ship.parts.any { it == position } }
}
fun convertPair(input: String): Pair<Position, Position> {
println("in convertPair $input")
return Pair(convert(input.substring(0, 2)), convert(input.substring(2, 4)))
}
fun convert(input: String): Position {
println("in convert $input")
val rowChar = input[0]
val columnChar = input[1]
val row = rowChar - 'a'
val column = columnChar.toString().toInt()
return Position(row, column)
}
fun check() {
val pos = readln().lowercase()
if (inputIsValid(Function.CHECK, pos)) {
}
}
fun inputIsValid(function: Function, input: String): Boolean {
println(function)
when (function) {
Function.CHECK -> {
if (input.length == 2 && input[0] in 'a'..'j' && input[1] in '0'..'9') {
return true
} else {
println("Enter the cell index in format \"letternumber\", for example \"a0a3\"")
return false
}
}
Function.PLACE -> {
if (input.length == 4 &&
input[0] in 'a'..'j' && input[1] in '0'..'9' &&
input[2] in 'a'..'j' && input[3] in '0'..'9' &&
(input[0] == input[2] || input[1] == input[3]) &&
abs(input[0] - input[2]) <= 3 &&
abs(input[1] - input[3]) <= 3
) {
return true
} else {
println("Enter the cell indexes in format \"letternumberletternumber\" for placing ship, for example \"a0b0\"")
return false
}
}
}
}
| 0 | Kotlin | 0 | 0 | ebd9504a64cb5908c8a0c954a93a5682de1fe550 | 4,778 | battleship_2024 | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.