kt_path stringlengths 35 167 | kt_source stringlengths 626 28.9k | classes listlengths 1 17 |
|---|---|---|
slobanov__kotlin-hackerrank__2cfdf85/src/main/kotlin/ru/amai/study/hackerrank/practice/interviewPreparationKit/search/candies/MinimumPasses.kt | package ru.amai.study.hackerrank.practice.interviewPreparationKit.search.candies
import java.math.BigDecimal
import java.math.BigDecimal.ONE
import java.math.BigDecimal.ZERO
import java.math.BigDecimal.valueOf
import java.math.RoundingMode.CEILING
import java.math.RoundingMode.FLOOR
import java.util.*
fun minimumPasses(machines: Long, workers: Long, price: Long, targetCnt: Long): Long {
var currentCandies = ZERO
var days = ZERO
val priceDecimal = price.toBigDecimal()
val targetDecimal = targetCnt.toBigDecimal()
var factoryResources = FactoryResources(
valueOf(workers),
valueOf(machines)
)
while (currentCandies < targetDecimal) {
val produced = factoryResources.production
currentCandies += produced
val (newResources, cost) = investPlan(
factoryResources,
currentCandies,
priceDecimal
)
val waitIfStore =
(targetDecimal - currentCandies).divide(produced, CEILING)
if (cost > ZERO) {
val waitIfInvest =
(targetDecimal - currentCandies + cost).divide((newResources.production), CEILING)
if ((waitIfStore > ZERO) && (waitIfInvest <= waitIfStore)) {
factoryResources = newResources
currentCandies -= cost
days++
} else {
days += (waitIfStore + ONE)
currentCandies = targetDecimal
}
} else {
val waitToInvest = (priceDecimal - currentCandies).divide(produced, CEILING)
if (waitIfStore <= waitToInvest) {
days += (waitIfStore + ONE)
currentCandies = targetDecimal
} else {
days += waitToInvest
currentCandies += produced * (waitToInvest - ONE)
}
}
}
return days.toLong()
}
private data class FactoryResources(
val workers: BigDecimal,
val machines: BigDecimal
)
private val FactoryResources.production: BigDecimal
get() = workers * machines
private data class InvestPlan(
val factoryResources: FactoryResources,
val cost: BigDecimal
)
private val TWO = valueOf(2)
private fun investPlan(factoryResources: FactoryResources, candies: BigDecimal, price: BigDecimal): InvestPlan {
val (currentWorkers, currentMachines) = factoryResources
val canBuy = candies.divide(price, FLOOR)
val diff = (currentMachines - currentWorkers).abs()
val toBuyForBalance = diff.min(canBuy)
val leftToBuy = canBuy - toBuyForBalance
var newMachines = currentMachines
var newWorkers = currentWorkers
if (currentMachines > currentWorkers) {
newWorkers += toBuyForBalance
} else if (currentWorkers > currentMachines) {
newMachines += toBuyForBalance
}
if (newMachines == newWorkers) {
newMachines += leftToBuy.divide(TWO, FLOOR)
newWorkers += leftToBuy.divide(TWO, CEILING)
}
val cost = ((newMachines - currentMachines) + (newWorkers - currentWorkers)) * price
return InvestPlan(
FactoryResources(newWorkers, newMachines),
cost
)
}
fun main() {
val scan = Scanner(System.`in`)
val (machines, workers, price, targetCnt) =
scan.nextLine().split(" ").map { it.trim().toLong() }
val result = minimumPasses(machines, workers, price, targetCnt)
println(result)
}
| [
{
"class_path": "slobanov__kotlin-hackerrank__2cfdf85/ru/amai/study/hackerrank/practice/interviewPreparationKit/search/candies/MinimumPassesKt.class",
"javap": "Compiled from \"MinimumPasses.kt\"\npublic final class ru.amai.study.hackerrank.practice.interviewPreparationKit.search.candies.MinimumPassesKt {\n... |
slobanov__kotlin-hackerrank__2cfdf85/src/main/kotlin/ru/amai/study/hackerrank/practice/interviewPreparationKit/search/swap/SwapNodes.kt | package ru.amai.study.hackerrank.practice.interviewPreparationKit.search.swap
import java.util.*
fun swapNodes(indexes: Array<Array<Int>>, queries: Array<Int>): List<List<Int>> {
val root = buildTree(indexes)
return queries.map { swapMultiplier ->
val queryResult = mutableListOf<Int>()
traverseInOrderWithSwaps(root, swapMultiplier) { node ->
queryResult += node.index
}
queryResult
}
}
private fun traverseInOrderWithSwaps(
node: Node,
swapMultiplier: Int,
level: Int = 1,
observer: (Node) -> Unit
) {
if (level % swapMultiplier == 0) node.swapSubTrees()
val (_, left, right) = node
left?.let { traverseInOrderWithSwaps(left, swapMultiplier, level + 1, observer) }
observer(node)
right?.let { traverseInOrderWithSwaps(right, swapMultiplier, level + 1, observer) }
}
private fun buildTree(indexes: Array<Array<Int>>): Node {
val nodeMap = mutableMapOf<Int, Node>()
indexes.forEachIndexed { i, (l, r) ->
val p = i + 1
listOf(p, l, r)
.filter { it != -1 }
.forEach { nodeMap.putIfAbsent(it, Node(it)) }
if (l != -1) nodeMap.getValue(p).left = nodeMap.getValue(l)
if (r != -1) nodeMap.getValue(p).right = nodeMap.getValue(r)
}
return nodeMap.getValue(1)
}
private data class Node(
val index: Int,
var left: Node? = null,
var right: Node? = null
)
private fun Node.swapSubTrees() {
val tmp = left
left = right
right = tmp
}
fun main() {
val scan = Scanner(System.`in`)
val n = scan.nextLine().trim().toInt()
val indexes = Array(n) { Array(2) { 0 } }
for (indexesRowItr in 0 until n) {
indexes[indexesRowItr] = scan.nextLine().split(" ").map { it.trim().toInt() }.toTypedArray()
}
val queriesCount = scan.nextLine().trim().toInt()
val queries = Array(queriesCount) { 0 }
for (queriesItr in 0 until queriesCount) {
val queriesItem = scan.nextLine().trim().toInt()
queries[queriesItr] = queriesItem
}
val result = swapNodes(indexes, queries)
println(result.joinToString("\n") { it.joinToString(" ") })
}
| [
{
"class_path": "slobanov__kotlin-hackerrank__2cfdf85/ru/amai/study/hackerrank/practice/interviewPreparationKit/search/swap/SwapNodesKt.class",
"javap": "Compiled from \"SwapNodes.kt\"\npublic final class ru.amai.study.hackerrank.practice.interviewPreparationKit.search.swap.SwapNodesKt {\n public static fi... |
slobanov__kotlin-hackerrank__2cfdf85/src/main/kotlin/ru/amai/study/hackerrank/practice/interviewPreparationKit/search/triplets/Triplets.kt | package ru.amai.study.hackerrank.practice.interviewPreparationKit.search.triplets
import java.util.*
fun triplets(a: IntArray, b: IntArray, c: IntArray): Long {
val (aSorted, aSize) = sortUniqueToSize(a)
val (bSorted, bSize) = sortUniqueToSize(b)
val (cSorted, cSize) = sortUniqueToSize(c)
val totalSize = aSize + bSize + cSize
var aIndex = 0
var bIndex = 0
var cIndex = 0
var tripletsCnt = 0L
while ((aIndex + bIndex + cIndex) < totalSize) {
if (bIndex == bSize) break
val p = aSorted.getOrMaxValue(aIndex)
val q = bSorted.getOrMaxValue(bIndex)
val r = cSorted.getOrMaxValue(cIndex)
when {
(p <= q) && (p <= r) -> aIndex++
(r <= q) && (r <= p) -> cIndex++
else -> {
bIndex++
tripletsCnt += aIndex.toLong() * cIndex.toLong()
}
}
}
return tripletsCnt
}
private fun IntArray.getOrMaxValue(index: Int) =
if (index < size) get(index) else Int.MAX_VALUE
private fun sortUniqueToSize(array: IntArray): Pair<IntArray, Int> {
val sortedUnique = array.sorted().distinct().toIntArray()
return sortedUnique to sortedUnique.size
}
fun main() {
val scan = Scanner(System.`in`)
scan.nextLine().split(" ")
fun readIntArray(): IntArray =
scan.nextLine().split(" ").map { it.trim().toInt() }.toIntArray()
val a = readIntArray()
val b = readIntArray()
val c = readIntArray()
val ans = triplets(a, b, c)
println(ans)
}
| [
{
"class_path": "slobanov__kotlin-hackerrank__2cfdf85/ru/amai/study/hackerrank/practice/interviewPreparationKit/search/triplets/TripletsKt.class",
"javap": "Compiled from \"Triplets.kt\"\npublic final class ru.amai.study.hackerrank.practice.interviewPreparationKit.search.triplets.TripletsKt {\n public stat... |
slobanov__kotlin-hackerrank__2cfdf85/src/main/kotlin/ru/amai/study/hackerrank/practice/interviewPreparationKit/search/minTime/MinTime.kt | 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)
}
| [
{
"class_path": "slobanov__kotlin-hackerrank__2cfdf85/ru/amai/study/hackerrank/practice/interviewPreparationKit/search/minTime/MinTimeKt.class",
"javap": "Compiled from \"MinTime.kt\"\npublic final class ru.amai.study.hackerrank.practice.interviewPreparationKit.search.minTime.MinTimeKt {\n public static fi... |
slobanov__kotlin-hackerrank__2cfdf85/src/main/kotlin/ru/amai/study/hackerrank/practice/interviewPreparationKit/greedy/luck/LuckBalance.kt | package ru.amai.study.hackerrank.practice.interviewPreparationKit.greedy.luck
import java.lang.IllegalArgumentException
import java.util.*
fun luckBalance(k: Int, contests: List<Contest>): Int {
val (importantContests, unimportanceContests) =
contests.partition { it.importance == Importance.IMPORTANT }
val sortedImportantContests =
importantContests.sortedBy { it.luck }
val lostContestLuck =
(unimportanceContests + sortedImportantContests.takeLast(k)).totalLuck
val importantContestsCnt = importantContests.size
return if (importantContestsCnt > k) {
val winContestsLuck =
sortedImportantContests.take(importantContestsCnt - k).totalLuck
lostContestLuck - winContestsLuck
} else lostContestLuck
}
private val List<Contest>.totalLuck: Int
get() = sumBy { it.luck }
data class Contest(val luck: Int, val importance: Importance)
enum class Importance {
IMPORTANT,
UNIMPORTANT
}
private fun from(importanceValue: Int): Importance = when (importanceValue) {
0 -> Importance.UNIMPORTANT
1 -> Importance.IMPORTANT
else -> throw IllegalArgumentException(
"got illegal importanceValue = $importanceValue; 0 or 1 expected"
)
}
fun main() {
val scan = Scanner(System.`in`)
val (n, k) = scan.nextLine().split(" ").map { it.toInt() }
val contests = (1..n).map {
val (luck, importanceValue) = scan.nextLine().split(" ").map { it.trim().toInt() }
Contest(luck, from(importanceValue))
}
val result = luckBalance(k, contests)
println(result)
}
| [
{
"class_path": "slobanov__kotlin-hackerrank__2cfdf85/ru/amai/study/hackerrank/practice/interviewPreparationKit/greedy/luck/LuckBalanceKt$luckBalance$$inlined$sortedBy$1.class",
"javap": "Compiled from \"Comparisons.kt\"\npublic final class ru.amai.study.hackerrank.practice.interviewPreparationKit.greedy.lu... |
slobanov__kotlin-hackerrank__2cfdf85/src/main/kotlin/ru/amai/study/hackerrank/practice/interviewPreparationKit/sorting/merge/CountInversions.kt | package ru.amai.study.hackerrank.practice.interviewPreparationKit.sorting.merge
import java.util.*
fun countInversions(arr: IntArray): Long =
mergeSortSupport(arr, IntArray(arr.size), 0, arr.size)
fun mergeSortSupport(arr: IntArray, temp: IntArray, left: Int, right: Int): Long =
if (right - left > 1) {
var inversionCnt: Long
val mid = (right + left) / 2
inversionCnt = mergeSortSupport(arr, temp, left, mid)
inversionCnt += mergeSortSupport(arr, temp, mid, right)
inversionCnt += merge(arr, temp, left, mid, right)
inversionCnt
} else 0L
fun merge(arr: IntArray, temp: IntArray, left: Int, mid: Int, right: Int): Long {
var inversionCnt = 0L
var i: Int = left
var j: Int = mid
var k: Int = left
while (i < mid && j < right) {
if (arr[i] <= arr[j]) {
temp[k++] = arr[i++]
} else {
temp[k++] = arr[j++]
inversionCnt += (mid - i)
}
}
(i until mid).forEach { temp[k++] = arr[it] }
(j until right).forEach { temp[k++] = arr[it] }
(left until right).forEach { arr[it] = temp[it] }
return inversionCnt
}
fun main() {
val scan = Scanner(System.`in`)
val t = scan.nextLine().trim().toInt()
for (tItr in 1..t) {
scan.nextLine().trim().toInt()
val arr = scan.nextLine().split(" ").map { it.trim().toInt() }.toIntArray()
val result = countInversions(arr)
println(result)
}
}
| [
{
"class_path": "slobanov__kotlin-hackerrank__2cfdf85/ru/amai/study/hackerrank/practice/interviewPreparationKit/sorting/merge/CountInversionsKt.class",
"javap": "Compiled from \"CountInversions.kt\"\npublic final class ru.amai.study.hackerrank.practice.interviewPreparationKit.sorting.merge.CountInversionsKt... |
slobanov__kotlin-hackerrank__2cfdf85/src/main/kotlin/ru/amai/study/hackerrank/practice/interviewPreparationKit/sorting/fraud/ActivityNotifications.kt | package ru.amai.study.hackerrank.practice.interviewPreparationKit.sorting.fraud
import java.util.*
private const val MAX_EXPENDITURE = 201
fun activityNotifications(expenditure: IntArray, d: Int): Int {
val counts = buildCounts(expenditure, d)
return (d until expenditure.size).count { i ->
val median = median(counts, d)
counts[expenditure[i]] += 1
counts[expenditure[i - d]] -= 1
(expenditure[i] >= 2 * median)
}
}
private fun buildCounts(array: IntArray, size: Int): IntArray {
val counts = IntArray(MAX_EXPENDITURE)
array.take(size).forEach {
counts[it] += 1
}
return counts
}
private fun median(counts: IntArray, size: Int): Double {
fun medianSupport(index: Int): Double {
var currIndex = 0
var value = 0.0
for ((i, count) in counts.withIndex()) {
if (index in (currIndex until (currIndex + count))) {
value = i.toDouble()
break
}
currIndex += count
}
return value
}
return when (size % 2) {
1 -> medianSupport(size / 2)
else -> (medianSupport(size / 2 - 1) + medianSupport(size / 2)) / 2
}
}
fun main() {
val scan = Scanner(System.`in`)
val nd = scan.nextLine().split(" ")
val d = nd[1].trim().toInt()
val expenditure = scan.nextLine().split(" ").map { it.trim().toInt() }.toIntArray()
val result = activityNotifications(expenditure, d)
println(result)
}
| [
{
"class_path": "slobanov__kotlin-hackerrank__2cfdf85/ru/amai/study/hackerrank/practice/interviewPreparationKit/sorting/fraud/ActivityNotificationsKt.class",
"javap": "Compiled from \"ActivityNotifications.kt\"\npublic final class ru.amai.study.hackerrank.practice.interviewPreparationKit.sorting.fraud.Activ... |
antop-dev__algorithm__9a3e762/src/main/kotlin/kr/co/programmers/P86052.kt | package kr.co.programmers
// https://github.com/antop-dev/algorithm/issues/409
class P86052 {
companion object {
const val UP = 0
const val RIGHT = 1
const val DOWN = 2
const val LEFT = 3
}
fun solution(grid: Array<String>): IntArray {
// 각 격자에서 네방향으로 이동한 기록
val memo = Array(grid.size) {
Array(grid[0].length) {
intArrayOf(0, 0, 0, 0)
}
}
val steps = mutableListOf<Int>()
for (i in memo.indices) {
for (j in memo[i].indices) {
for (k in 0 until 4) { // 4방향으로 빛을 쏜다.
var y = i
var x = j
var d = k
var step = 0
while (memo[y][x][d] == 0) {
memo[y][x][d] = 1
step++
// 다음 격자로 이동 했다.
y += when (d) {
UP -> -1
DOWN -> 1
else -> 0
}
if (y < 0) y = memo.lastIndex
if (y > memo.lastIndex) y = 0
x += when (d) {
RIGHT -> 1
LEFT -> -1
else -> 0
}
if (x < 0) x = memo[0].lastIndex
if (x > memo[0].lastIndex) x = 0
// 이동한 격자에서 이동할 방향을 구한다.
when (grid[y][x]) {
'L' -> {
d--
if (d < 0) d = LEFT
}
'R' -> {
d++
if (d > 3) d = UP
}
}
}
if (step > 0) steps += step
}
}
}
return steps.sorted().toIntArray()
}
}
| [
{
"class_path": "antop-dev__algorithm__9a3e762/kr/co/programmers/P86052$Companion.class",
"javap": "Compiled from \"P86052.kt\"\npublic final class kr.co.programmers.P86052$Companion {\n private kr.co.programmers.P86052$Companion();\n Code:\n 0: aload_0\n 1: invokespecial #8 ... |
antop-dev__algorithm__9a3e762/src/main/kotlin/kr/co/programmers/P12952.kt | package kr.co.programmers
import kotlin.math.abs
// https://github.com/antop-dev/algorithm/issues/535
class P12952 {
fun solution(n: Int): Int {
return dfs(IntArray(n), 0)
}
private fun dfs(arr: IntArray, row: Int): Int {
if (row == arr.size) { // n번째 행까지 퀸을 다 놓았다.
return 1
}
var count = 0
for (col in arr.indices) {
// row 행, col 열에 퀸을 배치 시켜놓고 검사한다.
arr[row] = col
if (valid(arr, row)) {
count += dfs(arr, row + 1)
}
}
return count
}
// 현재 행의 퀸 위치와 이전 행들의 퀸 위치를 비교한다.
private fun valid(arr: IntArray, currRow: Int): Boolean {
for (prevRow in 0 until currRow) {
if (arr[currRow] == arr[prevRow]) { // 같은 열이면 안됨
return false
}
// 대각선 위치면 안됨 (기울기로 계산)
if (abs(currRow - prevRow) == abs(arr[currRow] - arr[prevRow])) {
return false
}
}
return true
}
}
| [
{
"class_path": "antop-dev__algorithm__9a3e762/kr/co/programmers/P12952.class",
"javap": "Compiled from \"P12952.kt\"\npublic final class kr.co.programmers.P12952 {\n public kr.co.programmers.P12952();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<... |
antop-dev__algorithm__9a3e762/src/main/kotlin/kr/co/programmers/P67258.kt | package kr.co.programmers
// https://github.com/antop-dev/algorithm/issues/455
class P67258 {
fun solution(gems: Array<String>): IntArray {
// ["AA", "AB", "AC", "AA", "AC"]
// [ 0, 1, 2, 0, 2 ]
val map = mutableMapOf<String, Int>()
val list = mutableListOf<Int>()
var i = 0
for (gem in gems) {
val idx = map[gem] ?: i++
map[gem] = idx
list += idx
}
val counter = IntArray(i)
counter[list[0]]++
// 계산하기
var count = 1
var from = 0
var to = 0
// [가장 짧은 구간 길이, 시작 진열대 번호, 끝 진열대 번호]
val min = intArrayOf(gems.size, 1, gems.size)
while (from < gems.size) {
if (count < counter.size) { // 모든 물건을 사지 않았다
if (to < list.lastIndex) { // to + 1
to++
counter[list[to]]++
if (counter[list[to]] == 1) {
count++
}
} else { // from + 1
counter[list[from]]--
if (counter[list[from]] == 0) {
count--
}
from++
}
} else { // 모든 물건을 샀다
if (to - from + 1 < min[0]) {
min[0] = to - from + 1
min[1] = from + 1
min[2] = to + 1
}
// 완성된 크기가 고유한 물건의 크기와 일치하면 바로 종료
if (min[0] == counter.size) break
counter[list[from]]--
if (counter[list[from]] == 0) {
count--
}
from++
}
}
return intArrayOf(min[1], min[2])
}
}
| [
{
"class_path": "antop-dev__algorithm__9a3e762/kr/co/programmers/P67258.class",
"javap": "Compiled from \"P67258.kt\"\npublic final class kr.co.programmers.P67258 {\n public kr.co.programmers.P67258();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<... |
antop-dev__algorithm__9a3e762/src/main/kotlin/kr/co/programmers/P68936.kt | package kr.co.programmers
// https://github.com/antop-dev/algorithm/issues/240
class P68936 {
fun solution(arr: Array<IntArray>): IntArray {
return recursive(arr, 0, 0, arr.size)
}
private fun recursive(arr: Array<IntArray>, y: Int, x: Int, size: Int): IntArray {
val count = intArrayOf(0, 0);
val n = y + size
val m = x + size
// 시작위치 ~ 크기만큼 0과 1의 개수를 카운트
var zero = 0
var one = 0
for (i in y until n) {
for (j in x until m) {
if (arr[i][j] == 0) zero++ else one++
}
}
when {
// 모두 0인 경우
zero == size * size -> count[0]++
// 모두 1인 경우
one == size * size -> count[1]++
// 최소 크기인 경우
size == 2 -> {
count[0] += zero
count[1] += one
}
// 범위를 반으로 줄여서 다시 카운팅
else -> {
val half = size / 2
for (i in y until n step half) {
for (j in x until m step half) {
val (z, o) = recursive(arr, i, j, half)
count[0] += z
count[1] += o
}
}
}
}
// 카운팅을 위로 올린다.
return count
}
}
| [
{
"class_path": "antop-dev__algorithm__9a3e762/kr/co/programmers/P68936.class",
"javap": "Compiled from \"P68936.kt\"\npublic final class kr.co.programmers.P68936 {\n public kr.co.programmers.P68936();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<... |
antop-dev__algorithm__9a3e762/src/main/kotlin/kr/co/programmers/P150368.kt | package kr.co.programmers
// https://github.com/antop-dev/algorithm/issues/488
class P150368 {
fun solution(users: Array<IntArray>, emoticons: IntArray): IntArray {
val answer = intArrayOf(0, 0)
// 모든 조합으로 구매를 계산한다.
val combinations = combinations(emoticons.size)
for (comb in combinations) {
var subscribe = 0 // 총 이모티콘 플러스 서비스 가입자수
var total = 0 // 총 판매 금액
for (user in users) {
var amount = 0 // 유저의 총 구매 금액
for (i in emoticons.indices) {
// 할인율이 사용자의 기준 이상이면 구매
if (comb[i] >= user[0]) {
amount += emoticons[i] * (100 - comb[i]) / 100
}
// 사용자의 총 구매 금액이 기준 금액을 넘으면 서비스 가입으로 전환
if (amount >= user[1]) {
subscribe++
amount = 0
break
}
}
total += amount // 총 만패 금액에 합산
}
// 교체 기준
if (subscribe > answer[0]) {
answer[0] = subscribe
answer[1] = total
} else if (subscribe == answer[0] && total > answer[1]) {
answer[1] = total
}
}
return answer
}
private fun combinations(n: Int): List<List<Int>> {
val combinations = mutableListOf<List<Int>>()
backtrack(combinations, mutableListOf(), n)
return combinations
}
private fun backtrack(combinations: MutableList<List<Int>>, current: MutableList<Int>, N: Int) {
if (current.size == N) {
combinations.add(current.toList())
return
}
val numbers = listOf(10, 20, 30, 40)
for (number in numbers) {
current.add(number)
backtrack(combinations, current, N)
current.removeAt(current.size - 1)
}
}
}
| [
{
"class_path": "antop-dev__algorithm__9a3e762/kr/co/programmers/P150368.class",
"javap": "Compiled from \"P150368.kt\"\npublic final class kr.co.programmers.P150368 {\n public kr.co.programmers.P150368();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object... |
antop-dev__algorithm__9a3e762/src/main/kotlin/kr/co/programmers/P42861.kt | package kr.co.programmers
// https://github.com/antop-dev/algorithm/issues/530
class P42861 {
fun solution(n: Int, costs: Array<IntArray>): Int {
// 건설 비용이 낮은 순으로 정렬
costs.sortBy { (_, _, cost) -> cost }
// Union-Find
val root = IntArray(n) { it }
var ans = 0
var count = 0
for ((from, to, cost) in costs) {
// 두 정점의 부모 정점이 같다면 패스 (루프)
if (root.find(from) == root.find(to)) continue
// 비용 누적
ans += cost
// 부모를 합쳐준다.
root.union(from, to)
// 간선은 (N-1)개가 만들어진다.
if (count++ >= n) break
}
return ans
}
private fun IntArray.find(x: Int): Int = if (this[x] == x) x else find(this[x])
private fun IntArray.union(x: Int, y: Int) {
this[find(y)] = find(x)
}
}
| [
{
"class_path": "antop-dev__algorithm__9a3e762/kr/co/programmers/P42861.class",
"javap": "Compiled from \"P42861.kt\"\npublic final class kr.co.programmers.P42861 {\n public kr.co.programmers.P42861();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<... |
antop-dev__algorithm__9a3e762/src/main/kotlin/kr/co/programmers/P172927.kt | package kr.co.programmers
// https://github.com/antop-dev/algorithm/issues/481
class P172927 {
fun solution(picks: IntArray, minerals: Array<String>): Int {
// 곡괭이의 수만큼 5칸마다 구간의 합(가중치)을 구한다.
val mines = mutableListOf<IntArray>()
var numOfPick = picks[0] + picks[1] + picks[2]
for (i in minerals.indices step 5) {
// 곡괭이의 수만큼 계산
if (numOfPick <= 0) break
// [0] : 다이아몬드 광석 수
// [1] : 철 광석 수
// [2] : 돌 광석 수
// [3] : 가중치
val mine = IntArray(4)
for (j in i until minOf(i + 5, minerals.size)) {
when (minerals[j]) {
"diamond" -> {
mine[0]++
mine[3] += 25
}
"iron" -> {
mine[1]++
mine[3] += 5
}
"stone" -> {
mine[2]++
mine[3] += 1
}
}
}
mines += mine
numOfPick--
}
// 기중치로 내림차순 정렬
mines.sortByDescending { it[3] }
// 최소 피로도 계산
var answer = 0
for (mine in mines) {
val (diamond, iron, stone) = mine
answer += when {
picks[0] > 0 -> {
picks[0]--
diamond + iron + stone
}
picks[1] > 0 -> {
picks[1]--
(diamond * 5) + iron + stone
}
picks[2] > 0 -> {
picks[0]--
(diamond * 25) + (iron * 5) + stone
}
else -> 0
}
}
return answer
}
}
| [
{
"class_path": "antop-dev__algorithm__9a3e762/kr/co/programmers/P172927$solution$$inlined$sortByDescending$1.class",
"javap": "Compiled from \"Comparisons.kt\"\npublic final class kr.co.programmers.P172927$solution$$inlined$sortByDescending$1<T> implements java.util.Comparator {\n public kr.co.programmers... |
antop-dev__algorithm__9a3e762/src/main/kotlin/kr/co/programmers/P155651.kt | package kr.co.programmers
import java.util.*
// https://github.com/antop-dev/algorithm/issues/489
class P155651 {
fun solution(bookTime: Array<Array<String>>): Int {
// 입(퇴)실 시간으로 정렬
// 시간이 같다면 퇴실 시간이 먼저다.
// first : 시간
// second : 1(입실), 0(퇴실)
val pq = PriorityQueue<Pair<Int, Int>> { a, b ->
if (a.first == b.first) a.second - b.second else a.first - b.first
}
for (book in bookTime) {
val (entrance, leave) = book
pq += convert(entrance) to 1 // 입실
pq += convert(leave, 10) to 0 // 퇴실 + 10분
}
var answer = 0
var now = 0
while (pq.isNotEmpty()) {
val time = pq.poll()
now += if (time.second == 1) 1 else -1
answer = maxOf(answer, now)
}
return answer
}
// 시간 문자열을 숫자로 변경
private fun convert(s: String, plus: Int = 0): Int {
val split = s.split(":")
var hour = split[0].toInt()
var minute = split[1].toInt() + plus
// 분이 넘쳤을 때 시간으로 넘긴다.
if (minute >= 60) {
hour++
minute -= 60
}
return (hour * 60) + minute
}
}
| [
{
"class_path": "antop-dev__algorithm__9a3e762/kr/co/programmers/P155651.class",
"javap": "Compiled from \"P155651.kt\"\npublic final class kr.co.programmers.P155651 {\n public kr.co.programmers.P155651();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object... |
antop-dev__algorithm__9a3e762/src/main/kotlin/kr/co/programmers/P181187.kt | package kr.co.programmers
import kotlin.math.pow
import kotlin.math.sqrt
// https://github.com/antop-dev/algorithm/issues/502
class P181187 {
fun solution(r1: Int, r2: Int): Long {
// y가 0인 점의 개수
var count = 0L + (r2 - r1 + 1) * 4
// x 좌표만 루프
for (x in 1 until r2) {
val minY = if (x < r1) y(x, r1).toCeilInt() else 1
val maxY = y(x, r2).toFloorInt()
count += (maxY - minY + 1) * 4
}
return count
}
// 피타고라스 정리를 이용하여 y값을 구한다.
private fun y(x: Int, r: Int) = sqrt(r.pow(2) - x.pow(2))
}
// Int.제곱근
private fun Int.pow(n: Int) = this.toDouble().pow(n)
// Double -> 올림 Int
private fun Double.toCeilInt(): Int {
var v = this.toInt()
if (this - v > 0) v++
return v
}
// Double -> 내림 Int
private fun Double.toFloorInt() = this.toInt()
| [
{
"class_path": "antop-dev__algorithm__9a3e762/kr/co/programmers/P181187Kt.class",
"javap": "Compiled from \"P181187.kt\"\npublic final class kr.co.programmers.P181187Kt {\n private static final double pow(int, int);\n Code:\n 0: iload_0\n 1: i2d\n 2: iload_1\n 3: i2d\n 4: ... |
antop-dev__algorithm__9a3e762/src/main/kotlin/kr/co/programmers/P60059.kt | package kr.co.programmers
// https://school.programmers.co.kr/learn/courses/30/lessons/60059
class P60059 {
fun solution(k: Array<IntArray>, lock: Array<IntArray>): Boolean {
var key = k
repeat(4) { // 키를 4번 회전면서 체크한다.
if (check(key, lock)) {
return true
}
// 키를 오른쪽으로 90도 회전
key = turn(key)
}
return false
}
private fun check(key: Array<IntArray>, lock: Array<IntArray>): Boolean {
val n = lock.size
val m = key.size
val len = (n + m - 1)
val loop = len * len
var i = 0
while (i < loop) {
val x = (i % len) + n - m + 1
val y = (i / len) + n - m + 1
if (verify(key, lock, y, x)) {
return true
}
i++
}
return false
}
/**
* 자물쇠([lock])와 열쇠([key])에서 겹쳐지는 부분 계산
*/
private fun verify(key: Array<IntArray>, lock: Array<IntArray>, y: Int, x: Int): Boolean {
val m = key.size
val n = lock.size
val copiedLock = lock.map { it.copyOf() }
for (i in y until y + m) {
for (j in x until x + m) {
// 자물쇠에 해당하는 부분만 계산
if (i in n until n + n && j in n until n + n) {
copiedLock[i - n][j - n] += key[i - y][j - x]
}
}
}
// 자물쇠의 모든 칸이 1이면 OK
return copiedLock.all { it.all { v -> v == 1 } }
}
/** 키를 오른쪽으로 90도 회전 */
private fun turn(key: Array<IntArray>): Array<IntArray> {
val n = key.size
val turned = Array(n) { IntArray(n) }
for (r in 0 until n) {
for (c in 0 until n) {
turned[c][n - r - 1] = key[r][c]
}
}
return turned
}
}
| [
{
"class_path": "antop-dev__algorithm__9a3e762/kr/co/programmers/P60059.class",
"javap": "Compiled from \"P60059.kt\"\npublic final class kr.co.programmers.P60059 {\n public kr.co.programmers.P60059();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<... |
antop-dev__algorithm__9a3e762/src/main/kotlin/kr/co/programmers/P92335.kt | package kr.co.programmers
import java.math.BigInteger
// https://github.com/antop-dev/algorithm/issues/403
class P92335 {
companion object {
val TEEN: BigInteger = BigInteger("10")
}
fun solution(n: Int, k: Int): Int {
var answer = 0
val kNumber = decimalToK(n, k) + "0" // n.toString(k) + "0"
var num = BigInteger.ZERO
for (ch in kNumber) { // 한 문자씩 탐색
val n = ch - '0'
num = if (n == 0 && num != BigInteger.ZERO) { // 조건에 맞는 경우
if (isPrime(num)) { // 소수인지 판단
answer++
}
BigInteger.ZERO // 수 초기화
} else { // 숫자를 완성해 나간다.
// num = (num * 10) + n
(num * TEEN) + BigInteger("$n")
}
}
return answer
}
// 10진수를 k진수로 변환
private fun decimalToK(n: Int, k: Int): String {
val sb = StringBuilder()
var num = n
while (num >= k) {
sb.insert(0, num % k)
num /= k
}
sb.insert(0, num)
return sb.toString()
}
// 소수인지 판단
private fun isPrime(num: BigInteger): Boolean {
if (num <= BigInteger.ONE) {
return false
}
for (n in 2 until num.sqrt().toLong() + 1) {
// 나눠지면 소수가 아니다
if (num.mod(BigInteger("$n")) == BigInteger.ZERO) {
return false
}
}
return true
}
}
| [
{
"class_path": "antop-dev__algorithm__9a3e762/kr/co/programmers/P92335$Companion.class",
"javap": "Compiled from \"P92335.kt\"\npublic final class kr.co.programmers.P92335$Companion {\n private kr.co.programmers.P92335$Companion();\n Code:\n 0: aload_0\n 1: invokespecial #8 ... |
antop-dev__algorithm__9a3e762/src/main/kotlin/kr/co/programmers/P92341.kt | package kr.co.programmers
import kotlin.math.ceil
// https://github.com/antop-dev/algorithm/issues/396
class P92341 {
fun solution(fees: IntArray, records: Array<String>): IntArray {
// 차량의 마지막 입차 시간을 가지고 있는 맵
val inMap = mutableMapOf<String, Int>()
// 차량의 누적 주차 시간을 가지고 있는 맵
val timeMap = mutableMapOf<String, Int>()
// 차량의 주차 요금
val moneyMap = mutableMapOf<String, Int>()
// 누적 주차시간 계산
for (record in records) {
val split = record.split(" ")
val t = split[0].split(":")
val time = t[0].toInt() * 60 + t[1].toInt() // 숫자로 변환한 시각
val carNumber = split[1] // 차량번호
val inOut = split[2] // 내역
// 누적 주차 시간 0으로 세팅
if (!timeMap.containsKey(carNumber)) {
timeMap[carNumber] = 0
}
// "OUT" 전에는 반드시 "IN"이 있다.
if (inOut == "IN") {
inMap[carNumber] = time
} else { // "OUT"
timeMap[carNumber] = timeMap[carNumber]!! + (time - inMap.remove(carNumber)!!)
}
}
// 타임맵에 남아있다면 23:59분 출차로 계산한다.
for ((carNumber, time) in inMap.entries) {
timeMap[carNumber] = timeMap[carNumber]!! + (1439 - time)
}
// 주차 요금 계산
for ((carNumber, time) in timeMap.entries) {
var money = 0.0 + fees[1]
if (time - fees[0] > 0) {
money += ceil((time - fees[0]).toDouble() / fees[2]) * fees[3]
}
moneyMap[carNumber] = money.toInt()
}
// 차량번호로 정렬 후 금액만 리턴
return moneyMap.toSortedMap().values.toIntArray()
}
}
| [
{
"class_path": "antop-dev__algorithm__9a3e762/kr/co/programmers/P92341.class",
"javap": "Compiled from \"P92341.kt\"\npublic final class kr.co.programmers.P92341 {\n public kr.co.programmers.P92341();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<... |
antop-dev__algorithm__9a3e762/src/main/kotlin/kr/co/programmers/P12978.kt | package kr.co.programmers
// https://github.com/antop-dev/algorithm/issues/411
class P12978 {
companion object {
const val INF = 500_001 // 최대 시간은 K + 1
}
fun solution(N: Int, road: Array<IntArray>, k: Int): Int {
if (N == 1) return 1
// 행노드 -> 열노드간의 거리를 2차원 배열에 담는다.
val graph = makeGraph(N, road)
// 노드 방문 여부
val visited = BooleanArray(N + 1)
// 이동 시간
val times = IntArray(N + 1) {
if (it >= 2) INF else 0
}
var node = 1 // 1번 마을에서 시작
while (node != INF) {
visited[node] = true
// 갈 수 있는 노드 계산
for (i in 1..N) {
if (visited[i]) continue
if (graph[node][i] == INF) continue
// 시간 갱신
if (times[node] + graph[node][i] < times[i]) {
times[i] = times[node] + graph[node][i]
}
}
// 가장 최소 시간를 가지는 노드를 구한다.
node = run {
var min = INF
var idx = INF
for (i in 1 .. N) {
if (!visited[i] && times[i] < min) {
min = times[i]
idx = i
}
}
idx
}
}
// K 시간 이하로 배달이 가능한 노드 개수 세기
var answer = 0
for (i in 1 until times.size) {
if (times[i] <= k) answer++
}
return answer
}
private fun makeGraph(N: Int, road: Array<IntArray>): Array<IntArray> {
val graph = Array(N + 1) {
IntArray(N + 1)
}
// 디폴트를 0 또는 INF
for (i in 1..N) {
for (j in 1..N) {
if (i == j) continue
graph[i][j] = INF
}
}
// 마을간에 여러개의 길이 있을 수 있으므로 최단 거리만 남긴다.
for (r in road) {
if (r[2] < graph[r[0]][r[1]]) {
graph[r[0]][r[1]] = r[2]
}
if (r[2] < graph[r[1]][r[0]]) {
graph[r[1]][r[0]] = r[2]
}
}
return graph
}
}
| [
{
"class_path": "antop-dev__algorithm__9a3e762/kr/co/programmers/P12978$Companion.class",
"javap": "Compiled from \"P12978.kt\"\npublic final class kr.co.programmers.P12978$Companion {\n private kr.co.programmers.P12978$Companion();\n Code:\n 0: aload_0\n 1: invokespecial #8 ... |
antop-dev__algorithm__9a3e762/src/main/kotlin/kr/co/programmers/P150369.kt | package kr.co.programmers
import java.util.*
// https://github.com/antop-dev/algorithm/issues/491
class P150369 {
fun solution(cap: Int, n: Int, deliveries: IntArray, pickups: IntArray): Long {
val d = Stack<Int>()
val p = Stack<Int>()
var move = 0L // 총 이동거리
for (i in 0 until n) {
if (deliveries[i] > 0) d.push(i)
if (pickups[i] > 0) p.push(i)
}
while (d.isNotEmpty() || p.isNotEmpty()) {
// 배달과 수거중 가장 먼 위치 찾기
val i = maxOf(peek(d), peek(p))
// 왕복 거리 계산
move += (i + 1) * 2
// 배달과 수거 계산하기
calculate(d, deliveries, cap)
calculate(p, pickups, cap)
}
return move
}
private fun calculate(stack: Stack<Int>, arr: IntArray, cap: Int) {
var sum = 0
while (stack.isNotEmpty() && sum < cap) {
val i = stack.pop()
val v = arr[i]
// 배달(수거)할 양이 최대치(cap)보다 클 경우 최대한 차에 실는다.
// 수거해야할 양이 6이고 차에 여유공간이 3일경우 3이라도 실어서 간다.
// 다음에 같은 위치에 와서 남은 3을 수거해간다.
if (sum + v > cap) {
arr[i] = sum + v - cap
stack.push(i)
}
sum += v
}
}
// 스택이 비어 있으면 -1 처리
private fun peek(stack: Stack<Int>) = if (stack.isNotEmpty()) stack.peek() else -1
}
| [
{
"class_path": "antop-dev__algorithm__9a3e762/kr/co/programmers/P150369.class",
"javap": "Compiled from \"P150369.kt\"\npublic final class kr.co.programmers.P150369 {\n public kr.co.programmers.P150369();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object... |
antop-dev__algorithm__9a3e762/src/main/kotlin/kr/co/programmers/P87377.kt | package kr.co.programmers
// https://school.programmers.co.kr/learn/courses/30/lessons/87377
class P87377 {
fun solution(line: Array<IntArray>): Array<String> {
// 교점 좌표를 기록할 Set
val set = mutableSetOf<Pair<Long, Long>>()
// 가장자리 좌표
var minX = Long.MAX_VALUE
var maxX = Long.MIN_VALUE
var minY = Long.MAX_VALUE
var maxY = Long.MIN_VALUE
// Int * Int = Long 이 될 수 있기 때문에 처음부터 Long 변환 후 계산한다.
val rows = line.map { (a, b, c) ->
longArrayOf(a.toLong(), b.toLong(), c.toLong())
}
for (i in 0 until rows.size - 1) {
for (j in i + 1 until rows.size) {
val (a, b, e) = rows[i]
val (c, d, f) = rows[j]
// 교점 계산식
val adbc = (a * d) - (b * c)
val bfed = (b * f) - (e * d)
val ecaf = (e * c) - (a * f)
// 평행하거나 좌표가 정수가 아니면 패스
if (adbc == 0L || bfed % adbc != 0L || ecaf % adbc != 0L) continue
// 교점 기록
val x = bfed / adbc
val y = ecaf / adbc
set += x to y
// 좌표의 최대치
minX = minOf(minX, x)
maxX = maxOf(maxX, x)
minY = minOf(minY, y)
maxY = maxOf(maxY, y)
}
}
// "*" 찍기
val row = (maxY - minY + 1).toInt()
val col = (maxX - minX + 1).toInt()
val arr = Array(row) { CharArray(col) { '.' } }
for ((x, y) in set) {
arr[(maxY - y).toInt()][(x - minX).toInt()] = '*'
}
// List → Array
return arr.map { it.joinToString("") }.toTypedArray()
}
}
| [
{
"class_path": "antop-dev__algorithm__9a3e762/kr/co/programmers/P87377.class",
"javap": "Compiled from \"P87377.kt\"\npublic final class kr.co.programmers.P87377 {\n public kr.co.programmers.P87377();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<... |
antop-dev__algorithm__9a3e762/src/main/kotlin/kr/co/programmers/P83201.kt | package kr.co.programmers
// https://github.com/antop-dev/algorithm/issues/314
class P83201 {
fun solution(scores: Array<IntArray>): String {
val n = scores.size
val answer = StringBuffer()
for (j in 0 until n) {
val arr = Array(n) { i -> scores[i][j] }
var min = Int.MAX_VALUE
var max = Int.MIN_VALUE
var count = 0
var m = n
var sum = 0
for (i in 0 until n) {
val v = scores[i][j]
sum += v
if (v < min) min = v
if (v > max) max = v
if (v == scores[j][j]) count++
}
// 유일한 최고점이거나 최저점
if ((arr[j] == min || arr[j] == max) && count == 1) {
sum -= arr[j]
m--
}
val average = sum.toDouble() / m
answer.append(when {
average >= 90 -> "A"
average >= 80 -> "B"
average >= 70 -> "C"
average >= 50 -> "D"
else -> "F"
})
}
return answer.toString()
}
}
| [
{
"class_path": "antop-dev__algorithm__9a3e762/kr/co/programmers/P83201.class",
"javap": "Compiled from \"P83201.kt\"\npublic final class kr.co.programmers.P83201 {\n public kr.co.programmers.P83201();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<... |
antop-dev__algorithm__9a3e762/src/main/kotlin/kr/co/programmers/P72411.kt | package kr.co.programmers
// https://github.com/antop-dev/algorithm/issues/386
class P72411 {
fun solution(orders: Array<String>, course: IntArray): Array<String> {
val answer = mutableListOf<String>()
// 메뉴조합을 오름차순으로 정렬
val sorted = orders.map { it.toCharArray().sorted() }
// 메뉴별 갯수별 가능한 모든 조합을 구한다.
val combination = mutableListOf<String>()
for (chars in sorted) {
for (c in course) {
combination(combination, chars, BooleanArray(chars.size), 0, c)
}
}
// 문자열의 길이별로 그룹핑
val count = combination.groupBy { it.length }
for (e in count) {
// 문자열별 횟수로 그룹핑
val g = e.value.groupingBy { it }.eachCount()
// 2회 이상 주문되고 가장 많이 주문된 횟수를 구한다.
var max = Int.MIN_VALUE
for (v in g.values) {
if (v >= 2 && v > max) max = v
}
// 최대 주문수가 있다면 주문된 조합을 찾는다.
if (max != Int.MIN_VALUE) {
g.filter { it.value == max }.forEach { (t, _) -> answer += t }
}
}
// 최종 메뉴 조합도 오름차순으로 정렬해서 리턴
return answer.sorted().toTypedArray()
}
private fun combination(result: MutableList<String>, arr: List<Char>, visited: BooleanArray, index: Int, r: Int) {
if (r == 0) {
result += arr.filterIndexed { i, _ -> visited[i] }.joinToString("")
} else if (index == arr.size) {
return
} else {
visited[index] = true // 선택하는 경우
combination(result, arr, visited, index + 1, r - 1)
visited[index] = false // 선택하지 않는 경우
combination(result, arr, visited, index + 1, r)
}
}
}
| [
{
"class_path": "antop-dev__algorithm__9a3e762/kr/co/programmers/P72411$solution$$inlined$groupingBy$1.class",
"javap": "Compiled from \"_Collections.kt\"\npublic final class kr.co.programmers.P72411$solution$$inlined$groupingBy$1 implements kotlin.collections.Grouping<java.lang.String, java.lang.String> {\... |
antop-dev__algorithm__9a3e762/src/main/kotlin/kr/co/programmers/P42579.kt | package kr.co.programmers
class P42579 {
fun solution(genres: Array<String>, plays: IntArray): IntArray {
// 해시 구조로 저장
// 장르 : [<인덱스, 재생 횟수>, ..., ...]
val hash = mutableMapOf<String, MutableList<IntArray>>().apply {
for (i in plays.indices) {
val genre = genres[i]
val play = plays[i]
val data = intArrayOf(i, play)
this[genre] = (this[genre] ?: mutableListOf()).apply { add(data) }
}
}
// 장르의 총 재생 횟수로 내림차순 정렬
val sorted = hash.toList()
.sortedWith(compareByDescending { it -> it.second.sumBy { it[1] } })
// 장르 내에서 재생 횟수로 내림차순 정렬
sorted.forEach { pair -> pair.second.sortByDescending { it[1] } }
// 장르별 두 개씩 추출
var answer = mutableListOf<Int>()
for (pair in sorted) {
answer.addAll(pair.second.take(2).map { it[0] })
}
return answer.toIntArray()
}
}
| [
{
"class_path": "antop-dev__algorithm__9a3e762/kr/co/programmers/P42579$solution$lambda$5$$inlined$sortByDescending$1.class",
"javap": "Compiled from \"Comparisons.kt\"\npublic final class kr.co.programmers.P42579$solution$lambda$5$$inlined$sortByDescending$1<T> implements java.util.Comparator {\n public k... |
antop-dev__algorithm__9a3e762/src/main/kotlin/kr/co/programmers/P49191.kt | package kr.co.programmers
// https://github.com/antop-dev/algorithm/issues/532
class P49191 {
fun solution(n: Int, results: Array<IntArray>): Int {
// 승/패로 초기화
val graph = Array(n) { IntArray(n) }
for ((win, lose) in results) {
graph[win - 1][lose - 1] = 1
graph[lose - 1][win - 1] = -1
}
// 플로이드 와샬
for (k in 0 until n) {
for (i in 0 until n) {
for (j in 0 until n) {
if (graph[i][k] == 1 && graph[k][j] == 1) {
graph[i][j] = 1
graph[j][i] = -1
}
}
}
}
// 경기 결과의 수가 (n-1)개면 이 선수의 순위를 알 수 있다.
return graph.count { p ->
p.count { it != 0 } == n - 1
}
}
}
| [
{
"class_path": "antop-dev__algorithm__9a3e762/kr/co/programmers/P49191.class",
"javap": "Compiled from \"P49191.kt\"\npublic final class kr.co.programmers.P49191 {\n public kr.co.programmers.P49191();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<... |
antop-dev__algorithm__9a3e762/src/main/kotlin/kr/co/programmers/P72412.kt | package kr.co.programmers
// https://github.com/antop-dev/algorithm/issues/374
class P72412 {
fun solution(info: Array<String>, query: Array<String>): IntArray {
val aggregate = mutableMapOf<String, MutableList<Int>>()
// 경우의 수를 집계한다.
for (i in info.indices) {
dfs(aggregate, "", 0, info[i].split(" "))
}
// 이진 탐색으로 숫자를 찾을 것이므로 점수를 오름차순 정렬
for (e in aggregate.entries) {
e.value.sort()
}
// 찾기
val answer = IntArray(query.size)
for (i in query.indices) {
val split = query[i].replace(" and ", "").split(" ")
answer[i] = search(aggregate, split[0], split[1].toInt())
}
return answer
}
private fun dfs(aggregate: MutableMap<String, MutableList<Int>>, key: String, depth: Int, info: List<String>) {
if (depth == 4) {
aggregate[key] = aggregate[key]?.run {
this += info[4].toInt()
this
} ?: mutableListOf(info[4].toInt())
return
}
dfs(aggregate, "$key-", depth + 1, info)
dfs(aggregate, "$key${info[depth]}", depth + 1, info)
}
private fun search(aggregate: MutableMap<String, MutableList<Int>>, key: String, score: Int): Int {
return aggregate[key]?.run {
var start = 0
var end = this.lastIndex
while (start <= end) {
val mid = (start + end) / 2
if (this[mid] < score) {
start = mid + 1
} else {
end = mid - 1
}
}
this.size - start
} ?: 0
}
}
| [
{
"class_path": "antop-dev__algorithm__9a3e762/kr/co/programmers/P72412.class",
"javap": "Compiled from \"P72412.kt\"\npublic final class kr.co.programmers.P72412 {\n public kr.co.programmers.P72412();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<... |
antop-dev__algorithm__9a3e762/src/main/kotlin/kr/co/programmers/P161988.kt | package kr.co.programmers
// https://github.com/antop-dev/algorithm/issues/531
class P161988 {
fun solution(sequence: IntArray): Long {
val pulse1 = max(sequence, 1) // [1, -1, 1, ...]
val pulse2 = max(sequence, -1) // [-1, 1, -1, ...]
return maxOf(pulse1, pulse2)
}
private fun max(sequence: IntArray, start: Int): Long {
val n = sequence.size
val dp = LongArray(n)
var sign = start
for (i in 0 until n) {
dp[i] = sequence[i] * sign * 1L
sign *= -1
}
var max = dp[0]
for (i in 1 until n) {
// dp[n] = n번째 원소를 포함했을 때의 최대값
dp[i] = maxOf(dp[i - 1] + dp[i], dp[i])
max = maxOf(max, dp[i])
}
return max
}
}
| [
{
"class_path": "antop-dev__algorithm__9a3e762/kr/co/programmers/P161988.class",
"javap": "Compiled from \"P161988.kt\"\npublic final class kr.co.programmers.P161988 {\n public kr.co.programmers.P161988();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object... |
antop-dev__algorithm__9a3e762/src/main/kotlin/kr/co/programmers/P72413.kt | package kr.co.programmers
import java.util.*
class P72413 {
companion object {
const val INF = (100_000 * 200) + 1
}
fun solution(n: Int, s: Int, a: Int, b: Int, fares: Array<IntArray>): Int {
// 지점 → (지점들,택시요금)
val paths = paths(n, fares)
// 다익스트라
val office = dijkstra(paths, s) // S → Other
val muzi = dijkstra(paths, a) // A → Other
val apeach = dijkstra(paths, b) // B → Other
// 합승 도착 지점 C를 기준으로 최소 비용 계산
var ans = INF
for (c in 1..n) {
val cost = office[c] + muzi[c] + apeach[c]
ans = minOf(ans, cost)
}
return ans
}
private fun paths(n: Int, fares: Array<IntArray>): Array<MutableList<Point>> {
val paths = Array(n + 1) { mutableListOf<Point>() }
for ((s, e, cost) in fares) {
paths[s] += Point(e, cost)
paths[e] += Point(s, cost)
}
return paths
}
private fun dijkstra(paths: Array<MutableList<Point>>, s: Int): IntArray {
val costs = IntArray(paths.size) { INF }
costs[s] = 0
val pq = LinkedList<Point>()
pq += Point(s, 0)
while (pq.isNotEmpty()) {
val curr = pq.poll()
for (next in paths[curr.n]) {
val nextCost = curr.cost + next.cost
if (nextCost < costs[next.n]) {
costs[next.n] = nextCost
pq += Point(next.n, nextCost)
}
}
}
return costs
}
data class Point(val n: Int, val cost: Int)
}
| [
{
"class_path": "antop-dev__algorithm__9a3e762/kr/co/programmers/P72413$Point.class",
"javap": "Compiled from \"P72413.kt\"\npublic final class kr.co.programmers.P72413$Point {\n private final int n;\n\n private final int cost;\n\n public kr.co.programmers.P72413$Point(int, int);\n Code:\n 0: al... |
antop-dev__algorithm__9a3e762/src/main/kotlin/kr/co/programmers/P67257.kt | package kr.co.programmers
import java.util.*
// https://github.com/antop-dev/algorithm/issues/415
class P67257 {
// 문자열이 숫자인지 판단하는 정규표현식
val number = Regex("^[0-9]*$")
// 연산자 우선 순위 경우의 수
private val ops = listOf(
arrayOf('*', '+', '-'),
arrayOf('*', '-', '+'),
arrayOf('+', '*', '-'),
arrayOf('+', '-', '*'),
arrayOf('-', '*', '+'),
arrayOf('-', '+', '*')
)
fun solution(expression: String): Long {
var answer = 0L
for (op in ops) {
val postfix = toPostfix(expression, op)
var value = calculate(postfix)
if (value < 0) value *= -1
if (value > answer) {
answer = value
}
}
return answer
}
// 중위 표기법 → 후위 표기법
private fun toPostfix(infix: String, op: Array<Char>): List<String> {
val stack = Stack<Char>()
val postfix = mutableListOf<String>()
var num = 0
for (ch in infix) {
if (ch in '0'..'9') {
num = (num * 10) + (ch - '0')
} else {
postfix += "$num"
num = 0
while (stack.isNotEmpty() && op.indexOf(stack.peek()) <= op.indexOf(ch)) {
postfix += "${stack.pop()}"
}
stack += ch
}
}
// 남은 숫자와 연산자들 처리
postfix += "$num"
while (stack.isNotEmpty()) {
postfix += "${stack.pop()}"
}
return postfix
}
// 후위 표기법으로 계산
private fun calculate(postfix: List<String>): Long {
val stack = Stack<Long>()
for (v in postfix) {
stack += if (v.matches(number)) {
v.toLong()
} else {
val b = stack.pop()
val a = stack.pop()
when (v[0]) {
'+' -> a + b
'-' -> a - b
else -> a * b
}
}
}
return stack.pop()
}
}
| [
{
"class_path": "antop-dev__algorithm__9a3e762/kr/co/programmers/P67257.class",
"javap": "Compiled from \"P67257.kt\"\npublic final class kr.co.programmers.P67257 {\n private final kotlin.text.Regex number;\n\n private final java.util.List<java.lang.Character[]> ops;\n\n public kr.co.programmers.P67257()... |
antop-dev__algorithm__9a3e762/src/main/kotlin/kr/co/programmers/P154540.kt | package kr.co.programmers
// https://github.com/antop-dev/algorithm/issues/465
class P154540 {
fun solution(maps: Array<String>): IntArray {
val box = maps.map { StringBuilder(it) }
val answer = mutableListOf<Int>()
// DFS
for (y in box.indices) {
for (x in box[y].indices) {
if (box[y][x] in '1'..'9') {
answer += dfs(box, y, x)
}
}
}
if (answer.isEmpty()) answer += -1
return answer.sorted().toIntArray()
}
private fun dfs(box: List<StringBuilder>, y: Int, x: Int): Int {
// 좌표가 넘처기나 'X' 지역이면 0 리턴
if (y !in 0..box.lastIndex
|| x !in 0..box[y].lastIndex
|| box[y][x] == 'X'
) return 0
val v = box[y][x] - '0' // '1' → 1
box[y][x] = 'X'
return v +
dfs(box, y - 1, x) +
dfs(box, y, x + 1) +
dfs(box, y + 1, x) +
dfs(box, y, x - 1)
}
}
| [
{
"class_path": "antop-dev__algorithm__9a3e762/kr/co/programmers/P154540.class",
"javap": "Compiled from \"P154540.kt\"\npublic final class kr.co.programmers.P154540 {\n public kr.co.programmers.P154540();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object... |
antop-dev__algorithm__9a3e762/src/main/java/kr/co/programmers/P81302.kt | package kr.co.programmers
// https://github.com/antop-dev/algorithm/issues/363
class P81302 {
fun solution(places: Array<Array<String>>): IntArray {
val answer = IntArray(places.size)
for (i in places.indices) answer[i] = place(places[i])
return answer
}
private fun place(place: Array<String>): Int {
val box = Array(9) { CharArray(9) { 'X' } }.apply {
for (r in 0 until 5) {
for (c in 0 until 5) {
this[r + 2][c + 2] = place[r][c]
}
}
}
for (r in 2 until box.size - 2) {
for (c in 2 until box[r].size - 2) {
if (check(box, r, c)) return 0
}
}
return 1
}
private fun check(box: Array<CharArray>, r: Int, c: Int): Boolean {
if (box[r][c] != 'P') return false
return when { // box[r][c] == 'P'
box[r - 1][c] == 'P' -> true
box[r][c + 1] == 'P' -> true
box[r + 1][c] == 'P' -> true
box[r][c - 1] == 'P' -> true
box[r - 2][c] == 'P' && box[r - 1][c] == 'O' -> true
box[r][c + 2] == 'P' && box[r][c + 1] == 'O' -> true
box[r + 2][c] == 'P' && box[r + 1][c] == 'O' -> true
box[r][c - 2] == 'P' && box[r][c - 1] == 'O' -> true
box[r - 1][c - 1] == 'P' && (box[r - 1][c] != 'X' || box[r][c - 1] != 'X') -> return true
box[r - 1][c + 1] == 'P' && (box[r - 1][c] != 'X' || box[r][c + 1] != 'X') -> return true
box[r + 1][c + 1] == 'P' && (box[r + 1][c] != 'X' || box[r][c + 1] != 'X') -> return true
box[r + 1][c - 1] == 'P' && (box[r + 1][c] != 'X' || box[r][c - 1] != 'X') -> return true
else -> false
}
}
}
| [
{
"class_path": "antop-dev__algorithm__9a3e762/kr/co/programmers/P81302.class",
"javap": "Compiled from \"P81302.kt\"\npublic final class kr.co.programmers.P81302 {\n public kr.co.programmers.P81302();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<... |
antop-dev__algorithm__9a3e762/src/main/kotlin/kr/co/programmers/P136797.kt | package kr.co.programmers
// https://github.com/antop-dev/algorithm/issues/537
class P136797 {
// 한 자판에서 다른 자판으로 가는 가중치
private val costs = arrayOf(
intArrayOf(1, 7, 6, 7, 5, 4, 5, 3, 2, 3), // 자판 0
intArrayOf(7, 1, 2, 4, 2, 3, 5, 4, 5, 6),
intArrayOf(6, 2, 1, 2, 3, 2, 3, 5, 4, 5),
intArrayOf(7, 4, 2, 1, 5, 3, 2, 6, 5, 4),
intArrayOf(5, 2, 3, 5, 1, 2, 4, 2, 3, 5),
intArrayOf(4, 3, 2, 3, 2, 1, 2, 3, 2, 3),
intArrayOf(5, 5, 3, 2, 4, 2, 1, 5, 3, 2),
intArrayOf(3, 4, 5, 6, 2, 3, 5, 1, 2, 4),
intArrayOf(2, 5, 4, 5, 3, 2, 3, 2, 1, 2),
intArrayOf(3, 6, 5, 4, 5, 3, 2, 4, 2, 1) // 자판 9
)
fun solution(numbers: String): Int {
// 메모제이션
val memo = Array(numbers.length) {
Array(10) { IntArray(10) { -1 } }
}
// 왼손은 4, 오른손은 6 자판에서 시작
return f(numbers, 0, memo, 4, 6)
}
/**
* @param numbers 눌러야 할 숫자 문자열
* @param i 다음으로 눌러야하는 번호 인덱스
* @param memo 메모제이션
* @param left 현재 왼손의 자판 번호
* @param right 현재 오른손의 자판 번호
*/
private fun f(numbers: String, i: Int, memo: Array<Array<IntArray>>, left: Int, right: Int): Int {
if (i == numbers.length) return 0
// 이미 전에 계산했던 이력이 있다면 더 깊이 내려가지 않고
// 이전 이력 값을 사용한다.
if (memo[i][left][right] != -1) {
return memo[i][left][right]
}
// 눌러야 하는 숫자 자판 번호
val num = numbers[i] - '0'
var min = Int.MAX_VALUE
if (num != right) { // 왼손이 움직일 수 있는 경우 (오른손이 가야할 자판에 있다면 손이 겹치게 된다.)
// (왼손이 num으로 이동) + (다음 자판~마지막 자판까지 누른 최소 가중치)
val cost = costs[left][num] + f(numbers, i + 1, memo, num, right)
min = minOf(min, cost)
}
if (num != left) { // 오른손이 움직일 수 있는 경우
// (오른손이 num으로 이동) + (다음 자판~마지막 자판까지 누른 최소 가중치)
val cost = costs[right][num] + f(numbers, i + 1, memo, left, num)
min = minOf(min, cost)
}
memo[i][left][right] = min // 메모제이션
return min
}
}
| [
{
"class_path": "antop-dev__algorithm__9a3e762/kr/co/programmers/P136797.class",
"javap": "Compiled from \"P136797.kt\"\npublic final class kr.co.programmers.P136797 {\n private final int[][] costs;\n\n public kr.co.programmers.P136797();\n Code:\n 0: aload_0\n 1: invokespecial #8 ... |
antop-dev__algorithm__9a3e762/src/main/kotlin/kr/co/programmers/P77485.kt | package kr.co.programmers
// https://github.com/antop-dev/algorithm/issues/253
class P77485 {
fun solution(rows: Int, columns: Int, queries: Array<IntArray>): IntArray {
// 숫자 채우기
var n = 1
val box = Array(rows + 1) { Array(columns + 1) { 0 } }
for (i in 1 until box.size) {
for (j in 1 until box[i].size) {
box[i][j] = n++
}
}
// 회전
return IntArray(queries.size) { i -> rotate(box, queries[i]) }
}
private fun rotate(box: Array<Array<Int>>, q: IntArray): Int {
var min = Int.MAX_VALUE
val tmp = box[q[0] + 1][q[1]]
for (i in q[0] + 1..q[2]) {
box[i][q[1]] = if (i < q[2]) box[i + 1][q[1]] else box[i][q[1] + 1]
min = minOf(min, box[i][q[1]])
}
for (j in q[1] + 1..q[3]) {
box[q[2]][j] = if (j < q[3]) box[q[2]][j + 1] else box[q[2] - 1][j]
min = minOf(min, box[q[2]][j])
}
for (i in q[2] - 1 downTo q[0]) {
box[i][q[3]] = if (i > q[0]) box[i - 1][q[3]] else box[i][q[3] - 1]
min = minOf(min, box[i][q[3]])
}
for (j in q[3] - 1 downTo q[1]) {
box[q[0]][j] = if (j > q[1]) box[q[0]][j - 1] else tmp
min = minOf(min, box[q[0]][j])
}
return min
}
}
| [
{
"class_path": "antop-dev__algorithm__9a3e762/kr/co/programmers/P77485.class",
"javap": "Compiled from \"P77485.kt\"\npublic final class kr.co.programmers.P77485 {\n public kr.co.programmers.P77485();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<... |
antop-dev__algorithm__9a3e762/src/main/kotlin/kr/co/programmers/P152995.kt | package kr.co.programmers
// https://github.com/antop-dev/algorithm/issues/486
class P152995 {
fun solution(scores: Array<IntArray>): Int {
var rank = 1
val me = scores[0]
var maxScore = 0
// 근무태도 내림차순 정렬.
// 근무태도 동점인 경우 동료평가 오름차순 정렬
scores.sortWith(Comparator { a, b ->
if (a[0] == b[0]) a[1] - b[1] else b[0] - a[0]
})
// 두 점수의 합이 다른 점수의 합보다 크다면
// 근무태도 또는 동료평가 둘 중 하나는 높다
for (score in scores) {
if (score[1] < maxScore) {
if (score.contentEquals(me)) {
return -1
}
} else {
maxScore = maxOf(maxScore, score[1])
if (score[0] + score[1] > me[0] + me[1]) {
rank++
}
}
}
return rank
}
}
| [
{
"class_path": "antop-dev__algorithm__9a3e762/kr/co/programmers/P152995.class",
"javap": "Compiled from \"P152995.kt\"\npublic final class kr.co.programmers.P152995 {\n public kr.co.programmers.P152995();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object... |
antop-dev__algorithm__9a3e762/src/main/kotlin/kr/co/programmers/P1138.kt | package kr.co.programmers
import kotlin.math.abs
// https://leetcode.com/problems/alphabet-board-path/
class P1138 {
fun alphabetBoardPath(target: String): String {
var moves = ""
var p = intArrayOf(0, 0)
for (s in target) {
// 아스키 코드의 특성을 이용한다.
val t = (s - 97).toInt().run { intArrayOf(div(5), rem(5)) }
// Z에서 다른 곳으로 이동하는 경우라면 미리 위로 한칸 간다.
if (p[0] == 5 && p[0] - t[0] > 0) {
moves += 'U'
p = intArrayOf(p[0] - 1, p[1])
}
// 왼쪽 또는 오른쪽으로 이동
if (t[1] - p[1] != 0) {
val c = if (t[1] > p[1]) 'R' else 'L'
repeat(abs(p[1] - t[1])) {
moves += c
}
}
// 위 또는 아래로 이동
if (t[0] - p[0] != 0) {
val c = if (t[0] > p[0]) 'D' else 'U'
repeat(abs(p[0] - t[0])) {
moves += c
}
}
// adds the character
moves += "!"
p = t
}
return moves
}
}
| [
{
"class_path": "antop-dev__algorithm__9a3e762/kr/co/programmers/P1138.class",
"javap": "Compiled from \"P1138.kt\"\npublic final class kr.co.programmers.P1138 {\n public kr.co.programmers.P1138();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init... |
antop-dev__algorithm__9a3e762/src/main/kotlin/kr/co/programmers/P160585.kt | package kr.co.programmers
// https://github.com/antop-dev/algorithm/issues/506
class P160585 {
fun solution(board: Array<String>): Int {
val (oCount, oWin) = check(board, 'O')
val (xCount, xWin) = check(board, 'X')
return when {
// "O"나 "X"의 개수 차이가 나면 안된다.
oCount - xCount > 1 || xCount > oCount -> 0
// "O"와 "X"의 개수가 같을 때, 무승부 이거나 후공인 "X"가 이겨야 된다.
oCount == xCount && ((oWin == 0 && xWin == 0) || (oWin == 0 && xWin > 0)) -> 1
// "O"가 "X"보다 1개만 더 많을 때, 무승부 이거나 선공인 "O"가 이겨야 된다.
oCount > xCount && ((oWin == 0 && xWin == 0) || (oWin > 0 && xWin == 0)) -> 1
// 나머지 경우는 비정상적인 게임
else -> 0
}
}
private fun check(b: Array<String>, ch: Char): IntArray {
val check = intArrayOf(0, 0)
// 개수
for (i in 0 until 3) {
for (j in 0 until 3) {
if (b[i][j] == ch) {
check[0]++
}
}
}
// 가로줄
if (b[0][0] == ch && b[0][1] == ch && b[0][2] == ch) check[1]++
if (b[1][0] == ch && b[1][1] == ch && b[1][2] == ch) check[1]++
if (b[2][0] == ch && b[2][1] == ch && b[2][2] == ch) check[1]++
// 세로중
if (b[0][0] == ch && b[1][0] == ch && b[2][0] == ch) check[1]++
if (b[0][1] == ch && b[1][1] == ch && b[2][1] == ch) check[1]++
if (b[0][2] == ch && b[1][2] == ch && b[2][2] == ch) check[1]++
// 대각선
if (b[0][0] == ch && b[1][1] == ch && b[2][2] == ch) check[1]++
if (b[0][2] == ch && b[1][1] == ch && b[2][0] == ch) check[1]++
return check
}
}
| [
{
"class_path": "antop-dev__algorithm__9a3e762/kr/co/programmers/P160585.class",
"javap": "Compiled from \"P160585.kt\"\npublic final class kr.co.programmers.P160585 {\n public kr.co.programmers.P160585();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object... |
antop-dev__algorithm__9a3e762/src/main/kotlin/kr/co/programmers/P159993.kt | package kr.co.programmers
import java.util.*
// https://github.com/antop-dev/algorithm/issues/497
class P159993 {
fun solution(maps: Array<String>): Int {
// 시작 지점, 레버, 출구 위치를 찾는다
val pos = IntArray(6)
for (i in maps.indices) {
for (j in maps[i].indices) {
when (maps[i][j]) {
'S' -> {
pos[0] = i
pos[1] = j
}
'L' -> {
pos[2] = i
pos[3] = j
}
'E' -> {
pos[4] = i
pos[5] = j
}
}
}
}
// 시작지점 -> 레버
val move1 = move(maps, intArrayOf(pos[0], pos[1]), intArrayOf(pos[2], pos[3]))
if (move1 == -1) return -1
// 레버 -> 출구
val move2 = move(maps, intArrayOf(pos[2], pos[3]), intArrayOf(pos[4], pos[5]))
if (move2 == -1) return -1
return move1 + move2
}
private val dy = intArrayOf(-1, 0, 1, 0)
private val dx = intArrayOf(0, 1, 0, -1)
private fun move(maps: Array<String>, start: IntArray, end: IntArray): Int {
println()
val n = maps.size
val m = maps[0].length
val visited = Array(n) { IntArray(m) }
val queue = LinkedList<IntArray>()
queue.add(start)
var move = 0
while (queue.isNotEmpty()) {
// 큐 안에 들어있는 모든 위치를 다 이동해야 한번 움직인 것이다
val size = queue.size
repeat(size) {
val (y, x) = queue.poll()
// 목적지에 도착
if (y == end[0] && x == end[1]) return move
// 4방향으로 이동 예약
dy.zip(dx) { a, b ->
val nextY = y + a
val nextX = x + b
// 북,동,남,서 방향으로 이동할 수 있는지 체크
if (nextY in 0 until n
&& nextX in 0 until m
&& visited[nextY][nextX] == 0
&& maps[nextY][nextX] != 'X'
) { // 이동할 수 있다
// 방문 체크를 미리 한다.
// 이래야 시간초과가 안난다.
visited[nextY][nextX] = 1
queue += intArrayOf(nextY, nextX)
}
}
}
move++
}
return -1
}
}
| [
{
"class_path": "antop-dev__algorithm__9a3e762/kr/co/programmers/P159993.class",
"javap": "Compiled from \"P159993.kt\"\npublic final class kr.co.programmers.P159993 {\n private final int[] dy;\n\n private final int[] dx;\n\n public kr.co.programmers.P159993();\n Code:\n 0: aload_0\n 1: in... |
antop-dev__algorithm__9a3e762/src/main/kotlin/kr/co/programmers/P67256.kt | package kr.co.programmers
import kotlin.math.abs
// https://programmers.co.kr/learn/courses/30/lessons/67256
class P67256 {
fun solution(numbers: IntArray, hand: String): String {
var answer = ""
val prev = arrayOf(intArrayOf(3, 0), intArrayOf(3, 2)) // 초기 위치
for (n in numbers) {
// 키패드 -> 인덱스
var idx = n - 1
if (idx == -1) idx = 10
// 인덱스 -> 2차원 배열
val p = intArrayOf(idx / 3, idx % 3)
if (p[1] == 0) { // 왼손
answer += "L"
prev[0] = p
} else if (p[1] == 2) { // 오른손
answer += "R"
prev[1] = p
} else {
// 왼손으로부터의 거리
val diffLeft = abs(prev[0][0] - p[0]) + abs(prev[0][1] - p[1])
// 오른손으로부터의 거리
val diffRight = abs(prev[1][0] - p[0]) + abs(prev[1][1] - p[1])
if (diffLeft < diffRight) {
answer += "L"
prev[0] = p
} else if (diffLeft > diffRight) {
answer += "R"
prev[1] = p
} else {
if (hand == "left") {
answer += "L"
prev[0] = p
} else {
answer += "R"
prev[1] = p
}
}
}
}
return answer
}
}
| [
{
"class_path": "antop-dev__algorithm__9a3e762/kr/co/programmers/P67256.class",
"javap": "Compiled from \"P67256.kt\"\npublic final class kr.co.programmers.P67256 {\n public kr.co.programmers.P67256();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<... |
antop-dev__algorithm__9a3e762/src/main/kotlin/com/leetcode/P79.kt | package com.leetcode
// https://github.com/antop-dev/algorithm/issues/316
class P79 {
fun exist(board: Array<CharArray>, word: String): Boolean {
for (i in board.indices) {
for (j in board[i].indices) {
if (dfs(board, i, j, word, 0)) {
return true
}
}
}
return false
}
private fun dfs(board: Array<CharArray>, i: Int, j: Int, word: String, k: Int): Boolean {
if (k == word.length) return true
// 행의 인덱스가 벗어난 경우
if (i !in board.indices) return false
// 열의 인덱스가 벗어난 경우
if (j !in board[0].indices) return false
// 단어가 틀린 경우
if (board[i][j] != word[k]) return false
// 방문 체크
board[i][j] = ' '
return if (dfs(board, i - 1, j, word, k + 1) // ↑
|| dfs(board, i + 1, j, word, k + 1) // ↓
|| dfs(board, i, j - 1, word, k + 1) // ←
|| dfs(board, i, j + 1, word, k + 1) // →
) {
true
} else {
// 지나갔던 경로들이 답이 아니었다면 다시 복구한다.
board[i][j] = word[k]
false
}
}
}
| [
{
"class_path": "antop-dev__algorithm__9a3e762/com/leetcode/P79.class",
"javap": "Compiled from \"P79.kt\"\npublic final class com.leetcode.P79 {\n public com.leetcode.P79();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n 4: retu... |
antop-dev__algorithm__9a3e762/src/main/kotlin/com/leetcode/P447.kt | package com.leetcode
// https://github.com/antop-dev/algorithm/issues/332
class P447 {
fun numberOfBoomerangs(points: Array<IntArray>): Int {
var answer = 0
for (i in points.indices) {
val map = mutableMapOf<Int, Int>()
for (j in points.indices) {
if (i == j) continue
val distance = distance(points[i], points[j])
map[distance] = (map[distance] ?: 0) + 1
}
// combinations of boomerang tuple
for (count in map.values) {
answer += count * (count - 1)
}
}
return answer
}
private fun distance(p1: IntArray, p2: IntArray): Int {
// 두 포인트간에 거리 구하기
// 원래는 제곱과 루트(sqrt)를 계산해야 하지만
// 모든 결과가 동일한 연산을 하므로 생략 가능하다
val dx = p1[0] - p2[0]
val dy = p1[1] - p2[1]
return (dx * dx) + (dy * dy)
}
}
| [
{
"class_path": "antop-dev__algorithm__9a3e762/com/leetcode/P447.class",
"javap": "Compiled from \"P447.kt\"\npublic final class com.leetcode.P447 {\n public com.leetcode.P447();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n 4: ... |
antop-dev__algorithm__9a3e762/src/main/kotlin/com/leetcode/P994.kt | package com.leetcode
import java.util.*
// https://github.com/antop-dev/algorithm/issues/487
class P994 {
fun orangesRotting(grid: Array<IntArray>): Int {
val queue = LinkedList<Pair<Int, Int>>()
val fresh = intArrayOf(0) // 함수에 값을 넘기기위해 참조로 씀
for (y in grid.indices) {
for (x in grid[y].indices) {
when (grid[y][x]) {
1 -> fresh[0]++ // fresh 카운팅
2 -> queue += y to x // rotten 위치 큐에 저장
}
}
}
if (fresh[0] == 0) return 0
var minutes = -1
while (queue.isNotEmpty()) {
repeat(queue.size) {
val (y, x) = queue.poll()
go(queue, grid, fresh, y - 1, x) // 북
go(queue, grid, fresh, y, x + 1) // 동
go(queue, grid, fresh, y + 1, x) // 남
go(queue, grid, fresh, y, x - 1) // 서
}
minutes++
}
return if (fresh[0] == 0) minutes else -1
}
private fun go(queue: LinkedList<Pair<Int, Int>>, grid: Array<IntArray>, fresh: IntArray, y: Int, x: Int) {
if (y >= 0 && y < grid.size && x >= 0 && x < grid[y].size && grid[y][x] == 1) {
queue += y to x
grid[y][x] = 2
fresh[0]--
}
}
}
| [
{
"class_path": "antop-dev__algorithm__9a3e762/com/leetcode/P994.class",
"javap": "Compiled from \"P994.kt\"\npublic final class com.leetcode.P994 {\n public com.leetcode.P994();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n 4: ... |
antop-dev__algorithm__9a3e762/src/main/kotlin/com/leetcode/P539.kt | package com.leetcode
// https://github.com/antop-dev/algorithm/issues/514
class P539 {
fun findMinDifference(timePoints: List<String>): Int {
// 문자열을 분으로 변경
val times = mutableListOf<Int>()
for (s in timePoints) {
val time = time(s)
times += time
// 다음날 시간
if (time < 13 * 60) times += (24 * 60) + time
}
// 오름차순 정렬
times.sort()
// 가장 작은 시간 차이 구하기
var minDiff = 24 * 60
for (i in 1 until times.size) {
val diff = times[i] - times[i - 1]
if (diff < minDiff) minDiff = diff
}
return minDiff
}
/**
* time string to int
*/
private fun time(s: String) =
s.split(":")
.map { it.toInt() }
.let {
val (hh, mm) = it
(hh * 60) + mm
}
}
| [
{
"class_path": "antop-dev__algorithm__9a3e762/com/leetcode/P539.class",
"javap": "Compiled from \"P539.kt\"\npublic final class com.leetcode.P539 {\n public com.leetcode.P539();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n 4: ... |
antop-dev__algorithm__9a3e762/src/main/kotlin/com/leetcode/P131.kt | package com.leetcode
// https://github.com/antop-dev/algorithm/issues/297
class P131 {
fun partition(s: String): List<List<String>> {
// dynamic programming
val dp = Array(s.length) { IntArray(s.length) }.apply {
for (i in s.indices) this[i][i] = 1
for (i in 1 until s.length) {
if (s[i - 1] == s[i]) {
this[i - 1][i] = 1
}
}
for (start in 2 until s.length) {
var i = 0
var j = start
while (j < s.length) {
if (s[i] == s[j] && this[i + 1][j - 1] == 1) {
this[i][j] = 1
}
i++
j++
}
}
}
// backtracking
val answer = mutableListOf<List<String>>()
val pool = mutableListOf<String>()
dfs(dp, answer, pool, s, 0)
return answer
}
private fun dfs(
dp: Array<IntArray>,
answer: MutableList<List<String>>,
pool: MutableList<String>,
s: String,
p: Int
) {
if (p == s.length) {
answer += pool.toList()
return
}
for (i in p until s.length) {
if (dp[p][i] == 1) {
pool.add(s.substring(p, i + 1))
dfs(dp, answer, pool, s, i + 1)
pool.removeAt(pool.lastIndex)
}
}
}
}
| [
{
"class_path": "antop-dev__algorithm__9a3e762/com/leetcode/P131.class",
"javap": "Compiled from \"P131.kt\"\npublic final class com.leetcode.P131 {\n public com.leetcode.P131();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n 4: ... |
antop-dev__algorithm__9a3e762/src/main/kotlin/com/leetcode/P1504.kt | package com.leetcode
// https://leetcode.com/problems/count-submatrices-with-all-ones/
class P1504 {
fun numSubmat(mat: Array<IntArray>): Int {
// For each row i, create an array nums where: if mat[i][j] == 0 then nums[j] = 0 else nums[j] = nums[j-1] +1.
for (i in mat.indices) {
for (j in 1 until mat[i].size) {
mat[i][j] = if (mat[i][j] == 1) mat[i][j - 1] + 1 else 0
}
}
var submatrices = 0;
// In the row i, number of rectangles between column j and k(inclusive) and ends in row i, is equal to SUM(min(nums[j, .. idx])) where idx go from j to k.
// Expected solution is O(n^3).
for (i in mat.lastIndex downTo 0) {
for (j in mat[i].indices) {
submatrices += mat[i][j] + (0 until i).map { k ->
(k..i).map { idx -> mat[idx][j] }.min()!!
}.sum()
}
}
return submatrices
}
}
| [
{
"class_path": "antop-dev__algorithm__9a3e762/com/leetcode/P1504.class",
"javap": "Compiled from \"P1504.kt\"\npublic final class com.leetcode.P1504 {\n public com.leetcode.P1504();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n ... |
antop-dev__algorithm__9a3e762/src/main/kotlin/com/leetcode/P235.kt | package com.leetcode
// https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/
class P235 {
fun lowestCommonAncestor(root: TreeNode?, p: TreeNode?, q: TreeNode?): TreeNode? {
val path1 = path(root!!, p!!)
val path2 = path(root, q!!)
println()
println("path1 = ${path1.contentToString()}, path2 = ${path2.contentToString()}")
for (i in path1.lastIndex downTo 0) {
for (j in path2.lastIndex downTo 0) {
if (path1[i] == path2[j]) return TreeNode(path1[i])
}
}
return null
}
// 재귀의 시작
private fun path(root: TreeNode, target: TreeNode): IntArray {
println()
println("find path = ${target.`val`}")
val list = mutableListOf<Int>()
search(list, root, target.`val`);
return list.toIntArray()
}
// 재귀 (꼬리)
private fun search(list: MutableList<Int>, node: TreeNode?, target: Int): Boolean {
if (node == null) return false
println(" search node = ${node.`val`}")
if (node.`val` == target // 현재 내 노드가 타겟과 같거나
|| search(list, node.left, target) // 내 왼쪽 노드를 탐색해서 참이 나오거나
|| search(list, node.right, target) // 내 오른쪽 노드를 탐색해서 참이 나오거나
) {
list.add(0, node.`val`) // 리스트의 앞에 삽입
return true
}
return false
}
class TreeNode(var `val`: Int = 0) {
var left: TreeNode? = null
var right: TreeNode? = null
}
} | [
{
"class_path": "antop-dev__algorithm__9a3e762/com/leetcode/P235.class",
"javap": "Compiled from \"P235.kt\"\npublic final class com.leetcode.P235 {\n public com.leetcode.P235();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n 4: ... |
antop-dev__algorithm__9a3e762/src/main/kotlin/com/leetcode/P720.kt | package com.leetcode
// https://github.com/antop-dev/algorithm/issues/267
class P720 {
fun longestWord(words: Array<String>): String {
val root = TrieNode()
var answer = ""
words.sortWith(
Comparator<String> { o1, o2 -> o1.length - o2.length }
.then(Comparator { o1, o2 -> if (o1 < o2) -1 else 1 })
)
word@ for (word in words) {
var node = root
for (i in word.indices) {
val idx = word[i] - 'a'
if (node.children[idx] != null) {
node = node.children[idx]!!
continue
}
if (i < word.lastIndex) continue@word
if (i == word.lastIndex) {
if (word.length > answer.length) answer = word
val newNode = TrieNode(word[i])
node.children[idx] = newNode
node = newNode
}
}
}
return answer
}
class TrieNode(val char: Char? = null) {
val children = Array<TrieNode?>(26) { null }
}
}
| [
{
"class_path": "antop-dev__algorithm__9a3e762/com/leetcode/P720.class",
"javap": "Compiled from \"P720.kt\"\npublic final class com.leetcode.P720 {\n public com.leetcode.P720();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n 4: ... |
antop-dev__algorithm__9a3e762/src/main/kotlin/com/leetcode/P130.kt | package com.leetcode
// https://github.com/antop-dev/algorithm/issues/313
class P130 {
fun solve(board: Array<CharArray>) {
val m = board.size
val n = board[0].size
// [0] : 방문 여부
// [1] : 'O' 여부
val visited = Array(m) { Array(n) { IntArray(2) } }
for (j in 0 until n) {
dfs(board, visited, 0, j)
dfs(board, visited, m - 1, j)
}
for (i in 1 until m - 1) {
dfs(board, visited, i, 0)
dfs(board, visited, i, n - 1)
}
// 방문되지 않은 곳을 전부 'X'로 변경
for (i in 0 until m) {
for (j in 0 until n) {
if (visited[i][j][0] == 0) {
board[i][j] = 'X'
}
}
}
}
private fun dfs(board: Array<CharArray>, visited: Array<Array<IntArray>>, i: Int, j: Int) {
if (i !in 0..board.lastIndex) return
if (j !in 0..board[0].lastIndex) return
val here = visited[i][j]
if (here[0] == 1) return
here[0] = 1 // visited
if (board[i][j] == 'X') return
here[1] = 1 // 'O'
dfs(board, visited, i - 1, j) // ↑
dfs(board, visited, i + 1, j) // ↓
dfs(board, visited, i, j - 1) // ←
dfs(board, visited, i, j + 1) // →
}
}
| [
{
"class_path": "antop-dev__algorithm__9a3e762/com/leetcode/P130.class",
"javap": "Compiled from \"P130.kt\"\npublic final class com.leetcode.P130 {\n public com.leetcode.P130();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n 4: ... |
antop-dev__algorithm__9a3e762/src/main/kotlin/com/leetcode/P311.kt | package com.leetcode
import java.util.*
// https://github.com/antop-dev/algorithm/issues/311
class P311 {
private val dy = intArrayOf(-1, +0, +1, +0)
private val dx = intArrayOf(+0, +1, +0, -1)
fun shortestPath(grid: Array<IntArray>, k: Int): Int {
val m = grid.size
val n = grid[0].size
val memo = Array(m) { Array(n) { intArrayOf(m * n, m * n) } }
// [y좌표, x좌표, 장애물제거수]
val queue = LinkedList<IntArray>()
queue += intArrayOf(0, 0, 0)
var move = 0 // 이동 수
loop@ while (queue.isNotEmpty()) {
val size = queue.size
repeat(size) {
val (y, x, eliminate) = queue.poll()
// 목적지 도착
if (y == m - 1 && x == n - 1) { // 도착
return move
}
// 네방향 체크
dy.zip(dx) { a, b ->
val ny = y + a
val nx = x + b
if (ny in 0 until m && nx in 0 until n) {
val next = intArrayOf(ny, nx, eliminate)
if (grid[ny][nx] == 1) { // 벽
if (eliminate < k) { // 장애물 제거 가능
next[2]++
} else { // 장애물 제거 불가능
return@zip
}
}
memo[ny][nx][0] = move
memo[ny][nx][1] = next[2]
queue += next
}
}
}
move++
}
return -1
}
}
| [
{
"class_path": "antop-dev__algorithm__9a3e762/com/leetcode/P311.class",
"javap": "Compiled from \"P311.kt\"\npublic final class com.leetcode.P311 {\n private final int[] dy;\n\n private final int[] dx;\n\n public com.leetcode.P311();\n Code:\n 0: aload_0\n 1: invokespecial #8 ... |
antop-dev__algorithm__9a3e762/src/main/kotlin/com/leetcode/P486.kt | package com.leetcode
// https://leetcode.com/problems/predict-the-winner/
class P486 {
fun PredictTheWinner(nums: IntArray): Boolean {
if (nums.size <= 2) return true
return predict(nums, 0, 0, nums.lastIndex, 1) >= 0
}
private fun predict(nums: IntArray, score: Int, l: Int, r: Int, t: Int): Int {
if (l > r) return score
return if (t % 2 == 0) { // p1
maxOf(
predict(nums, score + nums[l], l + 1, r, t * -1),
predict(nums, score + nums[r], l, r - 1, t * -1)
)
} else { // p2
minOf(
predict(nums, score - nums[l], l + 1, r, t * -1),
predict(nums, score - nums[r], l, r - 1, t * -1)
)
}
}
}
| [
{
"class_path": "antop-dev__algorithm__9a3e762/com/leetcode/P486.class",
"javap": "Compiled from \"P486.kt\"\npublic final class com.leetcode.P486 {\n public com.leetcode.P486();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n 4: ... |
antop-dev__algorithm__9a3e762/src/main/kotlin/com/leetcode/P1314.kt | package com.leetcode
// https://github.com/antop-dev/algorithm/issues/277
class P1314 {
fun matrixBlockSum(mat: Array<IntArray>, k: Int): Array<IntArray> {
val dp = Array(mat.size) { i -> IntArray(mat[i].size) }.apply {
this[0][0] = mat[0][0]
for (i in 1 until mat.size) this[i][0] = this[i - 1][0] + mat[i][0]
for (i in 1 until mat[0].size) this[0][i] = this[0][i - 1] + mat[0][i]
for (i in 1 until mat.size) {
for (j in 1 until mat[i].size) {
this[i][j] = this[i - 1][j] + this[i][j - 1] + mat[i][j] - this[i - 1][j - 1]
}
}
}
return Array(mat.size) { i -> IntArray(mat[i].size) }.apply {
for (i in mat.indices) {
for (j in mat[i].indices) {
val y = minOf(i + k, dp.lastIndex)
val x = minOf(j + k, dp[i].lastIndex)
this[i][j] = dp[y][x]
val r = i - k - 1
val c = j - k - 1
if (r >= 0) this[i][j] -= dp[r][x]
if (c >= 0) this[i][j] -= dp[y][c]
if (r >= 0 && c >= 0) this[i][j] += dp[r][c]
}
}
}
}
}
| [
{
"class_path": "antop-dev__algorithm__9a3e762/com/leetcode/P1314.class",
"javap": "Compiled from \"P1314.kt\"\npublic final class com.leetcode.P1314 {\n public com.leetcode.P1314();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n ... |
antop-dev__algorithm__9a3e762/src/main/kotlin/com/leetcode/P959.kt | package com.leetcode
// https://github.com/antop-dev/algorithm/issues/286
class P959 {
fun regionsBySlashes(grid: Array<String>): Int {
val n = grid.size
val arr = Array(n * 3) { IntArray(n * 3) }
for (i in 0 until (n * n)) {
val p = intArrayOf(i / n * 3, i % n * 3)
when (grid[i / n][i % n]) {
'\\' -> {
arr[p[0]][p[1]] = 1
arr[p[0] + 1][p[1] + 1] = 1
arr[p[0] + 2][p[1] + 2] = 1
}
'/' -> {
arr[p[0]][p[1] + 2] = 1
arr[p[0] + 1][p[1] + 1] = 1
arr[p[0] + 2][p[1]] = 1
}
}
}
var answer = 0
for (i in arr.indices) {
for (j in arr[i].indices) {
if (arr[i][j] == 0) {
dfs(arr, i, j)
answer++
}
}
}
return answer
}
private fun dfs(grid: Array<IntArray>, i: Int, j: Int) {
if (i !in 0..grid.lastIndex) return
if (j !in 0..grid[i].lastIndex) return
if (grid[i][j] == 1) return
grid[i][j] = 1
dfs(grid, i - 1, j)
dfs(grid, i + 1, j)
dfs(grid, i, j - 1)
dfs(grid, i, j + 1)
}
}
| [
{
"class_path": "antop-dev__algorithm__9a3e762/com/leetcode/P959.class",
"javap": "Compiled from \"P959.kt\"\npublic final class com.leetcode.P959 {\n public com.leetcode.P959();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n 4: ... |
antop-dev__algorithm__9a3e762/src/main/kotlin/com/leetcode/P980.kt | package com.leetcode
// https://github.com/antop-dev/algorithm/issues/467
class P980 {
fun uniquePathsIII(grid: Array<IntArray>): Int {
var y = 0
var x = 0
var total = 0 // 갈 수 있는 남은 칸 수
for (i in grid.indices) {
for (j in grid[i].indices) {
val v = grid[i][j]
if (v == 0) { // 이동 가능 칸
total++
} else if (v == 1) { // 출발 칸
y = i
x = j
// 시작 지점을 갈 수 있는 블럭으로 처리
grid[y][x] = 0
total++
}
}
}
return dfs(grid, y, x, total)
}
private fun dfs(grid: Array<IntArray>, y: Int, x: Int, remain: Int): Int {
if (y < 0 || y >= grid.size
|| x < 0 || x >= grid[y].size
|| grid[y][x] == -1 // 벽
) {
return 0
}
// 도착
if (grid[y][x] == 2) {
// 남아있는 칸이 없어야 함
return if (remain == 0) 1 else 0
}
grid[y][x] = -1 // visited
val r = remain - 1
val sum = dfs(grid, y - 1, x, r) + // 북
dfs(grid, y, x + 1, r) + // 동
dfs(grid, y + 1, x, r) + // 남
dfs(grid, y, x - 1, r) // 서
grid[y][x] = 0 // backtracking
return sum
}
}
| [
{
"class_path": "antop-dev__algorithm__9a3e762/com/leetcode/P980.class",
"javap": "Compiled from \"P980.kt\"\npublic final class com.leetcode.P980 {\n public com.leetcode.P980();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n 4: ... |
antop-dev__algorithm__9a3e762/src/main/kotlin/com/leetcode/P241.kt | package com.leetcode
// https://leetcode.com/problems/different-ways-to-add-parentheses/
class P241 {
private val ops = setOf('+', '-', '*')
fun diffWaysToCompute(expression: String): List<Int> {
val values = mutableListOf<Int>()
// 연산자를 만나면 왼쪽 계산식과 오른쪽 계산식을 나눠서 재귀
expression.forEachIndexed { i, ch ->
if (ch in ops) {
val left = diffWaysToCompute(expression.substring(0, i))
val right = diffWaysToCompute(expression.substring(i + 1))
values += merge(left, right, ch)
}
}
// 연산자가 없고 숫자만 있을 경우
if (values.isEmpty()) {
values += expression.toInt()
}
return values
}
private fun merge(left: List<Int>, right: List<Int>, op: Char) = mutableListOf<Int>().apply {
for (l in left) {
for (r in right) {
when (op) {
'+' -> this += l + r
'-' -> this += l - r
'*' -> this += l * r
}
}
}
}
}
| [
{
"class_path": "antop-dev__algorithm__9a3e762/com/leetcode/P241.class",
"javap": "Compiled from \"P241.kt\"\npublic final class com.leetcode.P241 {\n private final java.util.Set<java.lang.Character> ops;\n\n public com.leetcode.P241();\n Code:\n 0: aload_0\n 1: invokespecial #8 ... |
antop-dev__algorithm__9a3e762/src/main/kotlin/com/leetcode/P37.kt | package com.leetcode
// https://github.com/antop-dev/algorithm/issues/459
class P37 {
fun solveSudoku(board: Array<CharArray>) {
solve(board, 0)
}
private fun solve(board: Array<CharArray>, pos: Int): Boolean {
if (pos == 81) {
return true
}
val y = pos / 9
val x = pos % 9
val set = possible(board, y, x)
if (set.isEmpty()) {
return false
}
val before = board[y][x]
for (ch in set) {
board[y][x] = ch
val bool = solve(board, pos + 1)
if (bool) return true
}
board[y][x] = before // backtracking
return false
}
private fun possible(board: Array<CharArray>, y: Int, x: Int): Set<Char> {
if (board[y][x] != '.') {
return setOf(board[y][x])
}
val set = mutableSetOf('1', '2', '3', '4', '5', '6', '7', '8', '9')
// 나와 같은 행의 수 제거
for (i in 0 until 9) {
val ch = board[i][x]
if (ch != '0') {
set -= ch
}
}
// 나와 같은 열의 수 제거
for (i in 0 until 9) {
val ch = board[y][i]
if (ch != '.') {
set -= ch
}
}
// 나와 같은 칸의 수 제거
val startY = (y / 3) * 3
val startX = (x / 3) * 3
for (i in startY until startY + 3) {
for (j in startX until startX + 3) {
val ch = board[i][j]
if (ch != '.') {
set -= ch
}
}
}
return set
}
}
| [
{
"class_path": "antop-dev__algorithm__9a3e762/com/leetcode/P37.class",
"javap": "Compiled from \"P37.kt\"\npublic final class com.leetcode.P37 {\n public com.leetcode.P37();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n 4: retu... |
antop-dev__algorithm__9a3e762/src/main/kotlin/com/leetcode/P473.kt | package com.leetcode
// https://github.com/antop-dev/algorithm/issues/494
class P473 {
fun makesquare(matchsticks: IntArray): Boolean {
val sum = matchsticks.sum()
// 모든 성냥의 길이가 4면으로 떨어지지 않으면 안됨
if (sum % 4 > 0) return false
val length = sum / 4
// 길이가 긴 성냥순으로 정렬
matchsticks.sortDescending()
// 가장 긴 성냥의 길이가 한면의 길이보다 크면 안됨
if (matchsticks[0] > length) return false
// 4면
val square = IntArray(4) { length }
// DFS 탐색
return dfs(matchsticks, 0, square)
}
private fun dfs(matchsticks: IntArray, i: Int, square: IntArray): Boolean {
// 성냥을 모두 사용했을 때 4면을 전부 채웠는지 체크
if (i >= matchsticks.size) {
return square.all { it == 0 }
}
// 현재 성냥을 어느 면에 넣을지 선택
for (j in square.indices) {
if (square[j] >= matchsticks[i]) {
square[j] -= matchsticks[i]
if (dfs(matchsticks, i + 1, square)) {
return true
}
square[j] += matchsticks[i] // backtracking
}
}
// 현재 성냥을 어느 면에도 넣지 못했으면 안됨
return false
}
}
| [
{
"class_path": "antop-dev__algorithm__9a3e762/com/leetcode/P473.class",
"javap": "Compiled from \"P473.kt\"\npublic final class com.leetcode.P473 {\n public com.leetcode.P473();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n 4: ... |
antop-dev__algorithm__9a3e762/src/main/kotlin/com/leetcode/P93.kt | package com.leetcode
// https://github.com/antop-dev/algorithm/issues/331
class P93 {
val answer = mutableListOf<String>()
fun restoreIpAddresses(s: String): List<String> {
if (s.length !in 4..12) return listOf()
dfs(s, 0, 0, StringBuffer())
return answer
}
/**
* @param s 원본 문자열
* @param i 문자열의 현재 인덱스
* @param dots 사용된 쩜(".")의 개수
* @param ip 만들어가고 있는 문자열
*/
fun dfs(s: String, i: Int, dots: Int, ip: StringBuffer) {
// 쩜을 다 사용했지만 문자열을 다 소비 못한 경우
if (dots > 3 && i < s.length) {
return
}
if (i == s.length && dots > 3) { // 완성
answer += ip.toString()
return
}
val prevLength = ip.length // 백트래킹할 이전 문자열 길이
if (i > 0) ip.append(".") // 쩜이 한번 사용됨
var num = 0
// 한자리, 두자리, 세자리 계산
val maxIndex = minOf(s.lastIndex - (3 - dots), i + 2)
for (j in i..maxIndex) {
val c = s[j]
// IP는 0 ~ 225만 허용된다.
num = (num * 10) + (c - '0')
if (num > 255) break
ip.append(c)
dfs(s, j + 1, dots + 1, ip)
// IP의 첫자리가 0이면 두세번째 자리는 패스
if (num == 0) break
}
// 백트래킹
ip.setLength(prevLength)
}
}
| [
{
"class_path": "antop-dev__algorithm__9a3e762/com/leetcode/P93.class",
"javap": "Compiled from \"P93.kt\"\npublic final class com.leetcode.P93 {\n private final java.util.List<java.lang.String> answer;\n\n public com.leetcode.P93();\n Code:\n 0: aload_0\n 1: invokespecial #8 ... |
antop-dev__algorithm__9a3e762/src/main/kotlin/com/leetcode/P48.kt | package com.leetcode
// https://github.com/antop-dev/algorithm/issues/280
class P48 {
fun rotate(matrix: Array<IntArray>) {
var p = 0
var length = matrix.size
while (length > 1) {
rotate(matrix, p++, length)
length -= 2
}
}
private fun rotate(matrix: Array<IntArray>, p: Int, length: Int) {
if (length == 1) return
val max = p + length - 1
val list = mutableListOf<Int>()
for (i in p until p + length) list += matrix[p][i] // 1
for (i in p + 1 until p + length) list += matrix[i][max] // 2
for (i in p + length - 2 downTo p) list += matrix[max][i] // 3
for (i in p + length - 2 downTo p + 1) list += matrix[i][p] // 4
repeat(length - 1) {
list.add(0, list.removeAt(list.lastIndex))
}
var k = 0
for (i in p until p + length) matrix[p][i] = list[k++]
for (i in p + 1 until p + length) matrix[i][max] = list[k++]
for (i in p + length - 2 downTo p) matrix[max][i] = list[k++]
for (i in p + length - 2 downTo p + 1) matrix[i][p] = list[k++]
}
}
| [
{
"class_path": "antop-dev__algorithm__9a3e762/com/leetcode/P48.class",
"javap": "Compiled from \"P48.kt\"\npublic final class com.leetcode.P48 {\n public com.leetcode.P48();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n 4: retu... |
antop-dev__algorithm__9a3e762/src/main/kotlin/com/leetcode/P187.kt | package com.leetcode
// https://leetcode.com/problems/repeated-dna-sequences/
class P187 {
fun findRepeatedDnaSequences(s: String): List<String> {
val answer = mutableSetOf<String>()
if (s.length <= 10) return listOf()
// 해시값들이 들어갈 Set
val seen = mutableSetOf<Int>()
// 처음 10자리를 해싱한다.
var hash = 0
for (i in 0 until 10) {
hash = hash.shl(2) + int(s[i])
}
// 처음 만들어진 해시를 저장
seen += hash
// 나머지 해시값 비교
for (i in 10 until s.length) {
// 해시값을 조정한다.
hash = hash.and(1.shl(18) - 1)
hash = hash.shl(2) + int(s[i])
// Set에 add() 했을 때 false면 이미 값이 있다는 것이다.
if (!seen.add(hash)) {
answer.add(s.substring(i - 9, i + 1))
}
}
return answer.toList()
}
private fun int(ch: Char): Int {
return when (ch) {
'A' -> 0
'C' -> 1
'G' -> 2
'T' -> 3
else -> 0
}
}
}
| [
{
"class_path": "antop-dev__algorithm__9a3e762/com/leetcode/P187.class",
"javap": "Compiled from \"P187.kt\"\npublic final class com.leetcode.P187 {\n public com.leetcode.P187();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n 4: ... |
antop-dev__algorithm__9a3e762/src/main/kotlin/com/leetcode/P167.kt | package com.leetcode
// https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/
class P167 {
fun twoSum(numbers: IntArray, target: Int): IntArray {
// target 보다 작은 수의 조합만 찾으면 된다.
var endOfSearch = numbers.lastIndex - 1
for (i in numbers.indices) {
if (numbers[i] > target) {
endOfSearch = i - 1
break
}
}
// Binary Search
for (i in 0..endOfSearch) {
val j = binarySearch(numbers, i + 1, numbers.lastIndex, target - numbers[i])
if (j > -1) return intArrayOf(i + 1, j + 1)
}
// You may assume that each input would have exactly one solution and you may not use the same element twice.
return IntArray(0)
}
private fun binarySearch(numbers: IntArray, s: Int, e: Int, target: Int): Int {
if (s > e) return -1
val m = (s + e) / 2
return with(numbers[m]) {
when {
target < this -> binarySearch(numbers, s, m - 1, target)
target > this -> binarySearch(numbers, m + 1, e, target)
else -> m
}
}
}
}
| [
{
"class_path": "antop-dev__algorithm__9a3e762/com/leetcode/P167.class",
"javap": "Compiled from \"P167.kt\"\npublic final class com.leetcode.P167 {\n public com.leetcode.P167();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n 4: ... |
scientificCommunity__blog-sample__36e291c/algorithms/src/main/kotlin/org/baichuan/sample/algorithms/leetcode/middle/MaxArea.kt | package org.baichuan.sample.algorithms.leetcode.middle
/**
* @author: tk (<EMAIL>)
* @date: 2022/1/10
*
* leetcode 11 盛最多水的容器
* https://leetcode-cn.com/problems/container-with-most-water/
*/
class MaxArea {
/**
* 解题思路(双指针法思路浅析):
* 题目要求找出盛水最多的容器,那么哪些因素会影响到盛水量呢?首先,盛水量完全取决于底*min(左高, 右高),
* 所以,我们可以从底最大的时候开始遍历数组进行计算,这样的好处是当我们从"两边往中间靠的过程"中就不用考虑存在更大的底而对计算结果造成影响了。
* 接下来是应该怎么往中间靠?答案是哪边"更低"哪边往中间靠,为什么呢?因为从高度上来说,决定盛水量的是最低的那一边。只有这一边变大才有可能使得容器的盛水量增加。
* 最后就是循环这个往中间靠的过程了。
*/
fun maxArea(height: IntArray): Int {
var result = 0
var left = 0
var right = height.size - 1
var i = 1
while (left < right) {
val tmp = if (height[left] > height[right]) {
right--
height[right] * ((height.size - i))
} else {
left++
height[left] * ((height.size - i))
}
result = tmp.coerceAtLeast(result)
i++
}
return result
}
} | [
{
"class_path": "scientificCommunity__blog-sample__36e291c/org/baichuan/sample/algorithms/leetcode/middle/MaxArea.class",
"javap": "Compiled from \"MaxArea.kt\"\npublic final class org.baichuan.sample.algorithms.leetcode.middle.MaxArea {\n public org.baichuan.sample.algorithms.leetcode.middle.MaxArea();\n ... |
scientificCommunity__blog-sample__36e291c/algorithms/src/main/kotlin/org/baichuan/sample/algorithms/leetcode/middle/SwapPairs.kt | package org.baichuan.sample.algorithms.leetcode.middle
/**
* https://leetcode.cn/problems/swap-nodes-in-pairs/
*/
class SwapPairs {
fun swapPairs(head: ListNode?): ListNode? {
if (head?.next == null) {
return head
}
val newHead = head.next
//交换后head变成后面的节点,所以head需要连接递归后的后续链表
head.next = swapPairs(newHead?.next)
//第二个节点变成头节点, 原头节点跟在第二个节点后
newHead?.next = head
return newHead
}
/**
* 非递归解法
*/
fun swapPairs1(head: ListNode?): ListNode? {
if (head?.next == null) {
return head
}
var curr = head
val result = head.next
var pre: ListNode? = null
while (curr?.next != null) {
val newHead = curr.next
val newCurr = newHead?.next
newHead?.next = curr
curr.next = newCurr
pre?.next = newHead
pre = curr
if (newCurr == null) {
break
}
curr = newCurr
}
return result
}
}
fun main() {
val head1 = ListNode(1)
val head2 = ListNode(2)
val head3 = ListNode(3)
// val head4 = ListNode(4)
head1.next = head2
head2.next = head3
// head3.next = head4
SwapPairs().swapPairs1(head1)
} | [
{
"class_path": "scientificCommunity__blog-sample__36e291c/org/baichuan/sample/algorithms/leetcode/middle/SwapPairsKt.class",
"javap": "Compiled from \"SwapPairs.kt\"\npublic final class org.baichuan.sample.algorithms.leetcode.middle.SwapPairsKt {\n public static final void main();\n Code:\n 0: ne... |
scientificCommunity__blog-sample__36e291c/algorithms/src/main/kotlin/org/baichuan/sample/algorithms/leetcode/middle/Divide.kt | package org.baichuan.sample.algorithms.leetcode.middle
/**
* https://leetcode.cn/problems/divide-two-integers/
* 两数相除
* 核心思路: 38/3 = 3*2 + 32 = 3*2*2+26= 3*2*2*2 + 14 = 3*2*2*2 + 3*2*2 +2 = 3(2*2*2 + 2*2) +2 = 3 * 12 + 2 = 12
*/
class Divide {
fun divide(dividend: Int, divisor: Int): Int {
if (dividend == 0) {
return 0
}
if (dividend == Integer.MIN_VALUE) {
if (divisor == 1) {
return Integer.MIN_VALUE;
}
if (divisor == -1) {
return Integer.MAX_VALUE;
}
}
if (divisor == 1) {
return dividend
}
if (divisor == -1) {
return -dividend
}
var result = 1
var sign = 0
var divided1 = if (dividend > 0) {
sign++
-dividend
} else {
sign--
dividend
}
var divisor1 = if (divisor > 0) {
sign++
-divisor
} else {
sign--
divisor
}
val divisor2 = divisor1
if (divided1 > divisor1) {
return 0
}
if (divisor1 == divided1) {
return if (sign == 0) -result else result
}
while (divided1 - divisor1 <= divisor1) {
divisor1 = divisor1 shl 1
result += result
}
divided1 -= divisor1
var tmp1 = result
while (divided1 < divisor2) {
divisor1 = divisor1 shr 1
tmp1 = tmp1 shr 1
if (divided1 - divisor1 <= 0) {
divided1 -= divisor1
result += tmp1
}
}
if (divided1 == divisor2) {
result += 1
}
return if (sign == 0) -result else result
}
}
fun main() {
println(Divide().divide(2147483647, 1))
println(-10 shr 1)
} | [
{
"class_path": "scientificCommunity__blog-sample__36e291c/org/baichuan/sample/algorithms/leetcode/middle/Divide.class",
"javap": "Compiled from \"Divide.kt\"\npublic final class org.baichuan.sample.algorithms.leetcode.middle.Divide {\n public org.baichuan.sample.algorithms.leetcode.middle.Divide();\n C... |
scientificCommunity__blog-sample__36e291c/algorithms/src/main/kotlin/org/baichuan/sample/algorithms/leetcode/middle/ReverseBetween.kt | package org.baichuan.sample.algorithms.leetcode.middle
/**
* @author: kuntang (<EMAIL>)
* @date: 2022/4/12
* https://leetcode-cn.com/problems/reverse-linked-list-ii/
*
* 执行用时:136 ms, 在所有 Kotlin 提交中击败了97.62%的用户
* 内存消耗:32.7 MB, 在所有 Kotlin 提交中击败了100.00%的用户
*/
class ReverseBetween {
fun reverseBetween(head: ListNode?, left: Int, right: Int): ListNode? {
if (head == null) {
return null
}
if (left == right) {
return head
}
var currIndex = 0
var currNode = head
var preNode: ListNode? = null
var leftNode: ListNode? = head
var rightNode: ListNode?
var reverseRightNode: ListNode? = head
var reverseLeftNode: ListNode? = head
while (currNode != null) {
val nextNode = currNode.next
if (currIndex > left - 2 && currIndex < right) {
if (currIndex == left - 1) {
leftNode = preNode
reverseRightNode = currNode
}
if (currIndex == right - 1) {
rightNode = nextNode
reverseRightNode?.next = rightNode
reverseLeftNode = currNode
leftNode?.next = reverseLeftNode
}
currNode.next = preNode
}
preNode = currNode
currNode = nextNode
currIndex++
}
return if (left == 1) {
reverseLeftNode
} else {
head
}
}
private fun doReverse(head: ListNode?) {
if (head == null) {
return
}
var currNode = head
var preNode: ListNode? = null
while (currNode != null) {
val nextNode = currNode.next
currNode.next = preNode
preNode = currNode
currNode = nextNode
}
}
}
fun main() {
//case 1
val a = ListNode(1)
val b = ListNode(2)
val c = ListNode(3)
val d = ListNode(4)
val e = ListNode(5)
a.next = b
b.next = c
c.next = d
d.next = e
val reverseBetween = ReverseBetween()
val reverseBetween1 = reverseBetween.reverseBetween(a, 2, 4)
//case 2
// val a = ListNode(3)
// val b = ListNode(5)
// a.next = b
// val reverseBetween = ReverseBetween()
// val reverseBetween1 = reverseBetween.reverseBetween(a, 1, 2)
println(reverseBetween1)
}
class ListNode(var `val`: Int) {
var next: ListNode? = null
} | [
{
"class_path": "scientificCommunity__blog-sample__36e291c/org/baichuan/sample/algorithms/leetcode/middle/ReverseBetweenKt.class",
"javap": "Compiled from \"ReverseBetween.kt\"\npublic final class org.baichuan.sample.algorithms.leetcode.middle.ReverseBetweenKt {\n public static final void main();\n Code... |
scientificCommunity__blog-sample__36e291c/algorithms/src/main/kotlin/org/baichuan/sample/algorithms/leetcode/middle/Operations.kt | package org.baichuan.sample.algorithms.leetcode.middle
/**
* @author: tk (<EMAIL>)
* @date: 2022/1/11
*/
class Operations {
var negatives = LongArray(32)
var positives = LongArray(32)
var cacheA = LongArray(32)
var cacheB = LongArray(32)
val NEGATIVE_UNIT = -1
fun Operations() {
negatives[0] = NEGATIVE_UNIT.toLong()
positives[0] = 1
for (i in 1..31) {
negatives[i] = negatives[i + NEGATIVE_UNIT] + negatives[i + NEGATIVE_UNIT]
positives[i] = positives[i + NEGATIVE_UNIT] + positives[i + NEGATIVE_UNIT]
}
}
fun minus(a: Int, b: Int): Int {
var aVar = a
var bVar = b
if (aVar == bVar) {
return 0
}
var index = 31
while (index >= 0) {
if (bVar > 0) {
if (bVar >= positives[index]) {
bVar += (negatives[index]).toInt()
aVar += (negatives[index]).toInt()
} else {
index += NEGATIVE_UNIT
}
} else {
if (bVar <= negatives[index]) {
bVar += (positives[index]).toInt()
aVar += (positives[index]).toInt()
} else {
index += NEGATIVE_UNIT
}
}
}
return aVar
}
fun multiply(a: Int, b: Int): Int {
var aVar = a
var bVar = b
if (aVar == 0 || bVar == 0) return 0
if (aVar == 1) return bVar
if (bVar == 1) return aVar
if (aVar == NEGATIVE_UNIT) return minus(0, bVar)
if (bVar == NEGATIVE_UNIT) return minus(0, aVar)
val aSign = aVar > 0
//最终结果的正负,true:正 false:负
val resultSign = aVar > 0 && bVar > 0 || aVar < 0 && bVar < 0
/**
* 转负数是为了简化代码
* 为什么不转正数?因为-2147483648无法转成有效的4字节正数
*/
if (aVar > 0) {
aVar = minus(0, aVar)
}
if (bVar > 0) {
bVar = minus(0, bVar)
}
cacheA[0] = aVar.toLong()
for (i in 1..30) {
cacheA[i] = cacheA[i + NEGATIVE_UNIT] + cacheA[i + NEGATIVE_UNIT]
}
var result = 0
var index = 31
while (index >= 0) {
if (bVar <= negatives[index]) {
bVar += (positives[index]).toInt()
result += (cacheA[index]).toInt()
}
index += NEGATIVE_UNIT
}
//原始结果符号,用来判断计算结果是否溢出
val originalResultSign = result > 0
//确保溢出的情况不会影响结果的正负
if (originalResultSign != aSign) {
result = minus(0, result)
}
//确定最终结果的正负
if (resultSign && result < 0 || !resultSign && result > 0) {
result = minus(0, result)
}
return result
}
fun divide(a: Int, b: Int): Int {
var aVar = a
var bVar = b
if (aVar == 0 || aVar > 0 && aVar < bVar || aVar < 0 && aVar > bVar) return 0
var result = 0
val resultSign = aVar > 0 && bVar > 0 || aVar < 0 && bVar < 0
if (aVar > 0) {
aVar = minus(0, aVar)
}
if (bVar > 0) {
bVar = minus(0, bVar)
}
//cacheB[0] = b* 2^0
cacheB[0] = bVar.toLong()
for (i in 1..31) {
cacheB[i] = cacheB[i + NEGATIVE_UNIT] + cacheB[i + NEGATIVE_UNIT]
}
var index = 31
var preDividedB: Long = 0
while (index >= 0) {
if (aVar <= cacheB[index] + preDividedB) {
preDividedB += cacheB[index]
result += (positives[index]).toInt()
}
index += NEGATIVE_UNIT
}
//确定最终结果的正负
if (resultSign && result < 0 || !resultSign && result > 0) {
result = minus(0, result)
}
return result
}
} | [
{
"class_path": "scientificCommunity__blog-sample__36e291c/org/baichuan/sample/algorithms/leetcode/middle/Operations.class",
"javap": "Compiled from \"Operations.kt\"\npublic final class org.baichuan.sample.algorithms.leetcode.middle.Operations {\n private long[] negatives;\n\n private long[] positives;\n... |
scientificCommunity__blog-sample__36e291c/algorithms/src/main/kotlin/org/baichuan/sample/algorithms/leetcode/middle/Search.kt | package org.baichuan.sample.algorithms.leetcode.middle
/**
* https://leetcode.cn/problems/search-in-rotated-sorted-array/
* 33. 搜索旋转排序数组
*/
class Search {
fun search(nums: IntArray, target: Int): Int {
val first = nums[0]
if (target == first) {
return 0
}
var i = nums.size / 2
var left = 0
var right = nums.size - 1
while (right > left) {
if (target == nums[i]) {
return i
}
if (target > nums[i]) {
if (nums[i] < first && target > first) {
right = i
i = (right + left) / 2
} else {
if (i == nums.size - 1) return -1
left = i + 1
i = (right + left) / 2
}
} else {
if (nums[i] > first) {
if (target > first) {
right = i
i = (right + left) / 2
} else {
if (i == nums.size - 1) return -1
left = i + 1
i = (right + left) / 2
}
} else {
right = i
i = (right + left) / 2
}
}
}
if (nums[left] == target) {
return left
}
return -1
}
}
fun main() {
Search().search(arrayOf(8, 9, 2, 3, 4).toIntArray(), 9)
} | [
{
"class_path": "scientificCommunity__blog-sample__36e291c/org/baichuan/sample/algorithms/leetcode/middle/SearchKt.class",
"javap": "Compiled from \"Search.kt\"\npublic final class org.baichuan.sample.algorithms.leetcode.middle.SearchKt {\n public static final void main();\n Code:\n 0: new ... |
scientificCommunity__blog-sample__36e291c/algorithms/src/main/kotlin/org/baichuan/sample/algorithms/leetcode/hard/NumberToWords.kt | package org.baichuan.sample.algorithms.leetcode.hard
/**
* @author: tk (<EMAIL>)
* @date: 2022/1/10
* https://leetcode-cn.com/problems/english-int-lcci/
* 面试题 16.08. 整数的英语表示
*/
class NumberToWords {
fun numberToWords(num: Int): String {
val unit = arrayOf("Billion", "Million", "Thousand", "Hundred")
val numberOfUnit = arrayOf(1000000000L, 1000000L, 1000L, 100L)
val numberWord = arrayOf(
"One",
"Two",
"Three",
"Four",
"Five",
"Six",
"Seven",
"Eight",
"Nine",
"Ten",
"Eleven",
"Twelve",
"Thirteen",
"Fourteen",
"Fifteen",
"Sixteen",
"Seventeen",
"Eighteen",
"Nineteen",
"Twenty",
"Thirty",
"Forty",
"Fifty",
"Sixty",
"Seventy",
"Eighty",
"Ninety"
)
val numberOfWord =
arrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 30, 40, 50, 60, 70, 80, 90)
/*var i = 0
var result = ""
var numVar = num
while (i < number.size) {
val l = numVar / number[i]
if (l > 0) {
result += findWord(l.toInt())
numVar -= (l * number[i]).toInt()
}
i++
}
return result*/
if (num == 0) {
return "Zero"
}
val result = findResult(num, numberOfUnit, unit, numberOfWord)
return result.substring(0, result.length - 1)
}
fun findResult(
num: Int,
numberOfUnit: Array<Long>,
unit: Array<String>,
numberOfWord: Array<Int>
): String {
var i = 0
var result = ""
var numVar = num
/**
* 100及以上的数通过除法进行单位(百、千)单词查找
* 100以下的数进行减法进行数量(具体数值)单词查找
*/
if (numVar >= 100) {
while (i < numberOfUnit.size) {
val l = numVar / numberOfUnit[i]
if (l > 0) {
result += findResult(l.toInt(), numberOfUnit, unit, numberOfWord) + unit[i] + " "
numVar -= (l * numberOfUnit[i]).toInt()
//如果有余数,且余数小于100则按照减法进行单词查找
if (numVar in 1..99) {
result += findResult(numVar, numberOfUnit, unit, numberOfWord)
}
}
i++
}
} else {
var j = numberOfWord.size - 1
while (j >= 0) {
val l = numVar - numberOfWord[j]
if (l >= 0) {
result += findWord(numberOfWord[j]) + findWord(l)
break
} else {
j--
}
}
}
return result
}
fun findWord(num: Int): String {
return when (num) {
1 -> "One "
2 -> "Two "
3 -> "Three "
4 -> "Four "
5 -> "Five "
6 -> "Six "
7 -> "Seven "
8 -> "Eight "
9 -> "Nine "
10 -> "Ten "
11 -> "Eleven "
12 -> "Twelve "
13 -> "Thirteen "
14 -> "Fourteen "
15 -> "Fifteen "
16 -> "Sixteen "
17 -> "Seventeen "
18 -> "Eighteen "
19 -> "Nineteen "
20 -> "Twenty "
30 -> "Thirty "
40 -> "Forty "
50 -> "Fifty "
60 -> "Sixty "
70 -> "Seventy "
80 -> "Eighty "
90 -> "Ninety "
else -> ""
}
}
}
fun main() {
println(NumberToWords().numberToWords(1234567891))
} | [
{
"class_path": "scientificCommunity__blog-sample__36e291c/org/baichuan/sample/algorithms/leetcode/hard/NumberToWordsKt.class",
"javap": "Compiled from \"NumberToWords.kt\"\npublic final class org.baichuan.sample.algorithms.leetcode.hard.NumberToWordsKt {\n public static final void main();\n Code:\n ... |
scientificCommunity__blog-sample__36e291c/algorithms/src/main/kotlin/org/baichuan/sample/algorithms/leetcode/simple/interview/MajorityElement.kt | package org.baichuan.sample.algorithms.leetcode.simple.interview
/**
* 面试题 17.10. 主要元素
* https://leetcode.cn/problems/find-majority-element-lcci/
*/
class MajorityElement {
/**
* 摩尔投票解法
* 遍历,并对不同的元素进行抵消。
* 核心思路是:
* 1. **如果y的个数超过数组一半大小**,则经过抵消后剩下的数一定是y。
* 2. 如果个数超过一半大小的数不存在。则抵消后最后剩下的数可能是数组中任何一个数。因为抵消是随机的
*
* 所以最后要对这个剩下的数的数目进行验证,就可以判断是否存在满足条件的数以及这个数的值
*/
fun majorityElement(nums: IntArray): Int {
var x = 0
var y = 0
for (num in nums) {
if (x == 0) {
y = num
x = 1
} else {
x += if (y == num) 1 else -1
}
}
x = 0
for (num in nums) if (y == num) x++
return if (nums.size / 2 < x) y else -1
}
} | [
{
"class_path": "scientificCommunity__blog-sample__36e291c/org/baichuan/sample/algorithms/leetcode/simple/interview/MajorityElement.class",
"javap": "Compiled from \"MajorityElement.kt\"\npublic final class org.baichuan.sample.algorithms.leetcode.simple.interview.MajorityElement {\n public org.baichuan.sam... |
scientificCommunity__blog-sample__36e291c/algorithms/src/main/kotlin/org/baichuan/sample/algorithms/leetcode/simple/interview/Massage.kt | package org.baichuan.sample.algorithms.leetcode.simple.interview
/**
* https://leetcode.cn/problems/the-masseuse-lcci/
* 面试题 17.16. 按摩师
*/
class Massage {
/**
* 时间复杂度:O(n)
* 空间复杂度:O(n)
* 状态转移方程: dp[i] = max(dp[i-1],dp[i-2])
*/
fun massage(nums: IntArray): Int {
if (nums.isEmpty()) {
return 0
}
if (nums.size == 1) {
return nums[0]
}
val dp = IntArray(nums.size)
dp[0] = nums[0]
dp[1] = Math.max(nums[0], nums[1])
for (i in 2 until nums.size) {
dp[i] = Math.max(dp[i - 1], dp[i - 2] + nums[i])
}
return dp[nums.size - 1]
}
/**
* 时间复杂度:O(n)
* 空间复杂度:O(1)
* 状态转移方程: dp[i] = max(dp[i-1],dp[i-2])
* 从递推关系来看,每次计算时需要保存的状态只有3个:dp[i] dp[i-1] dp[i-2],所以可以考虑每次循环可以丢弃i-3
* 所以只需要保证每次循环,i i-1 i-2这3个连续的数对应的结果在dp里,并且能通过下表找到对应的值即可。而dp本身只有0,1,2几个空位。
* 而x%3 = (x-3)%3。而且在i连续的情况下取模产生的数也是连续的。所以,dp[i%3] = max(dp[(i-1)%3],dp[(i-2)%3])
*/
fun massage1(nums: IntArray): Int {
if (nums.isEmpty()) {
return 0
}
if (nums.size == 1) {
return nums[0]
}
val dp = IntArray(3)
dp[0] = nums[0]
dp[1] = Math.max(nums[0], nums[1])
for (i in 2 until nums.size) {
dp[i % 3] = Math.max(dp[(i - 1) % 3], dp[(i - 2) % 3] + nums[i])
}
return dp[(nums.size - 1) % 3]
}
}
fun main() {
} | [
{
"class_path": "scientificCommunity__blog-sample__36e291c/org/baichuan/sample/algorithms/leetcode/simple/interview/MassageKt.class",
"javap": "Compiled from \"Massage.kt\"\npublic final class org.baichuan.sample.algorithms.leetcode.simple.interview.MassageKt {\n public static final void main();\n Code:... |
MhmoudAlim__Coding-challanges__31f0b84/src/leetcode_problems/easy/FindGivenDifference.kt | package leetcode_problems.easy
import kotlin.math.*
/*Given an unsorted array,
return 1 if there exists a pair or more of elements in the array whose difference is 1.
else return 0
Examples:
-Input: arr[] = {5, 20, 3, 2, 6}
=Output: 1
-Input: arr[] = {90, 7, 2, 9, 50}
=Output: 0
*/
fun findPairDifference(nums: IntArray): Int {
// O(N*N) Solution
// nums.forEach { i ->
// val list = nums.toMutableList()
// list.remove(i)
// list.forEach { j ->
// if (abs(i - j) == 1)
// return 1
// }
// }
// return 0
val sorted = nums.sorted()
// [2, 7, 20, 21, 22]
var l = 0 //2
var r = nums.size -1 //22
while (l >= r){
val middle = (l + r) / 2 // 20
if (abs(sorted[middle] - sorted[l]) == 1)
return 1
else if (abs(sorted[middle] - sorted[l]) < 1)
r = middle -1
else
l = middle + 1
}
return 0
}
fun main() {
val result = findPairDifference(nums = intArrayOf( 7, 2, 20, 22, 21))
println(result.toString())
}
| [
{
"class_path": "MhmoudAlim__Coding-challanges__31f0b84/leetcode_problems/easy/FindGivenDifferenceKt.class",
"javap": "Compiled from \"FindGivenDifference.kt\"\npublic final class leetcode_problems.easy.FindGivenDifferenceKt {\n public static final int findPairDifference(int[]);\n Code:\n 0: aload... |
MhmoudAlim__Coding-challanges__31f0b84/src/leetcode_problems/hard/MedianOfTwoSortedArrays.kt | package leetcode_problems.hard
/*
https://leetcode.com/problems/median-of-two-sorted-arrays/
*/
fun findMedianSortedArrays(nums1: IntArray, nums2: IntArray): Double {
val maxNumSize = 1000 ; val maxAllNumsSize = 2000
// Lengths of two arrays
val m = nums1.size
val n = nums2.size
val allNums = nums1.plus(nums2).sorted()
// eliminate constraints
if (m > maxNumSize) throw IllegalArgumentException("nums1 can't be larger than $maxNumSize")
if (n > maxNumSize) throw IllegalArgumentException("nums2 can't be larger than $maxNumSize")
if (allNums.size > maxAllNumsSize) throw IllegalArgumentException("nums1 + nums2 can't be larger than $maxAllNumsSize together")
if (allNums.size == 1) return allNums[0].toDouble()
// Check if num1 is smaller than num2
// If not, then we will swap num1 with num2
if (nums1.size > nums2.size) {
return findMedianSortedArrays(nums2, nums1)
}
// Pointers for binary search
var start = 0
var end = m
// Binary search starts from here
while (start <= end) {
// Partitions of both the array
val partitionNums1 = (start + end) / 2
val partitionNums2 = (m + n + 1) / 2 - partitionNums1
// Edge cases
// If there are no elements left on the left side after partition
val maxLeftNums1 = if (partitionNums1 == 0) Int.MIN_VALUE else nums1[partitionNums1 - 1]
// If there are no elements left on the right side after partition
val minRightNums1 = if (partitionNums1 == m) Int.MAX_VALUE else nums1[partitionNums1]
// Similarly for nums2
val maxLeftNums2 = if (partitionNums2 == 0) Int.MIN_VALUE else nums2[partitionNums2 - 1]
val minRightNums2 = if (partitionNums2 == n) Int.MAX_VALUE else nums2[partitionNums2]
// Check if we have found the match
if (maxLeftNums1 <= minRightNums2 && maxLeftNums2 <= minRightNums1) {
// Check if the combined array is of even/odd length
return if ((m + n) % 2 == 0) {
(maxLeftNums1.coerceAtLeast(maxLeftNums2) + minRightNums1.coerceAtMost(minRightNums2)) / 2.0
} else {
maxLeftNums1.coerceAtLeast(maxLeftNums2).toDouble()
}
} else if (maxLeftNums1 > minRightNums2) {
end = partitionNums1 - 1
} else {
start = partitionNums1 + 1
}
}
throw IllegalArgumentException()
}
fun main(){
val nums2 = arrayListOf<Int>()
(1..1000).forEach {
nums2.add(it)
}
val ans = findMedianSortedArrays(intArrayOf() , intArrayOf(1,2,3,4,5))
println(ans)
} | [
{
"class_path": "MhmoudAlim__Coding-challanges__31f0b84/leetcode_problems/hard/MedianOfTwoSortedArraysKt.class",
"javap": "Compiled from \"MedianOfTwoSortedArrays.kt\"\npublic final class leetcode_problems.hard.MedianOfTwoSortedArraysKt {\n public static final double findMedianSortedArrays(int[], int[]);\n... |
MhmoudAlim__Coding-challanges__31f0b84/src/leetcode_problems/medium/PairWithGivenDifference.kt | package leetcode_problems.medium
import java.lang.Exception
import kotlin.math.abs
/*
https://www.geeksforgeeks.org/find-a-pair-with-the-given-difference/
Given an unsorted array and a number n,
find if there exists a pair of elements in the array whose difference is n.
Examples:
-Input: arr[] = {5, 20, 3, 2, 50, 80}, n = 78
=Output: Pair Found: (2, 80)
-Input: arr[] = {90, 70, 20, 80, 50}, n = 45
=Output: No Such Pair*/
fun findPair(nums: IntArray, n: Int): IntArray {
// //<editor-fold desc = "Solution 1">
// /*
// Time Complexity: O(n*n) as two nested for loops are executing both from 1 to n where n is size of input array.
// Space Complexity: O(1) as no extra space has been taken
// */
//
// nums.forEach { i ->
// for (j in i + 1 until nums.size) {
// if (abs(nums[i] - nums[j]) == n) return intArrayOf(nums[i], nums[j])
// }
// }
// throw Exception("no pair found")
// //</editor-fold>
//<editor-fold desc = "Solution 2">
// Time Complexity: O(n*log(n))
val sorted = nums.sorted()
var p1 = 0
var p2 = sorted.size - 1
while (p2 >= p1 && p2 < sorted.size) {
if (abs(sorted[p1] - sorted[p2]) == n && p1 != p2) {
println("p1 = $p1")
println("p2 = $p2")
println("abs diff = ${abs(sorted[p1] - sorted[p2])}")
return intArrayOf(sorted[p1], sorted[p2])
} else {
if (sorted[p1] - sorted[p2] > n) {
println("p1 = $p1")
println("p2 = $p2")
println("n = $n")
println("diff = ${sorted[p1] - sorted[p2]}")
p1++
println("p1++ = ${p1++}")
} else {
p2--
println("p2-- = ${p2--}")
}
}
}
throw Exception("no pair found")
//</editor-fold>
}
fun main() {
val result = findPair(nums = intArrayOf(5, 20, 3, 2, 50, 80, 90, 83), n = 78)
println(result.contentToString())
}
| [
{
"class_path": "MhmoudAlim__Coding-challanges__31f0b84/leetcode_problems/medium/PairWithGivenDifferenceKt.class",
"javap": "Compiled from \"PairWithGivenDifference.kt\"\npublic final class leetcode_problems.medium.PairWithGivenDifferenceKt {\n public static final int[] findPair(int[], int);\n Code:\n ... |
MhmoudAlim__Coding-challanges__31f0b84/src/leetcode_problems/medium/LongestCommonPref.kt | package leetcode_problems.medium//https://leetcode.com/problems/longest-common-prefix/
//best
fun longestCommonPrefix(strs: Array<String>?): String {
if (strs == null || strs.isEmpty()) return ""
for (i in 0 until strs[0].length) {
val c = strs[0][i]
for (j in 1 until strs.size) {
if (i == strs[j].length || strs[j][i] != c) return strs[0].substring(0, i)
}
}
return strs[0]
}
fun longestCommonPrefix1(strs: Array<String>): String {
println(strs.contentToString())
if (strs.isEmpty()) return ""
if (strs.size == 1) return strs[0]
val firstItem = strs[0]
for (i in firstItem.indices) {
strs.forEach {
if (firstItem[i] != it[i])
return firstItem.substring(0, i)
}
}
return ""
}
fun longestCommonPrefix2(strs: Array<String>): String {
println(strs.contentToString())
return if (strs.isNotEmpty()) strs.reduce { accumulator, string ->
accumulator.commonPrefixWith(string)
} else ""
}
fun main() {
val strs = arrayOf("flower", "fla", "flight", "fl")
val strs2 = arrayOf("flower", "fla", "asd", "fl")
val strs3 = arrayOf("a", "ab")
println(longestCommonPrefix(strs))
} | [
{
"class_path": "MhmoudAlim__Coding-challanges__31f0b84/leetcode_problems/medium/LongestCommonPrefKt.class",
"javap": "Compiled from \"LongestCommonPref.kt\"\npublic final class leetcode_problems.medium.LongestCommonPrefKt {\n public static final java.lang.String longestCommonPrefix(java.lang.String[]);\n ... |
MhmoudAlim__Coding-challanges__31f0b84/src/leetcode_problems/medium/AddTwoNumbers.kt | package leetcode_problems.medium
/*
https://leetcode.com/problems/add-two-numbers/
*/
/**
* Example:
* var li = ListNode(5)
* var v = li.`val`
* Definition for singly-linked list.
* class ListNode(var `val`: Int) {
* var next: ListNode? = null
* }
* Example 1:
* Input: l1 = [2,4,3], l2 = [5,6,4]
* Output: [7,0,8]
* Explanation: 342 + 465 = 807.
*
* Example 2:
* Input: l1 = [0], l2 = [0]
* Output: [0]
*
* Example 3:
* Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
* Output: [8,9,9,9,0,0,0,1]
*/
/// 3(4(5))
class ListNode(var value: List<Int>)
fun addTwoNumbers(l1: ListNode?, l2: ListNode?): ListNode {
val ls1 = StringBuilder()
val ls2 = StringBuilder()
val resultNode = mutableListOf<Int>()
(l1?.value?.reversed() ?: listOf()).forEach { i ->
ls1.append(i)
}
for (i in l2?.value?.reversed() ?: listOf()) {
ls2.append(i)
}
val result = ls1.toString().toInt() + ls2.toString().toInt()
result.toString().forEach {
resultNode.add(it.digitToInt())
}
return ListNode(resultNode.reversed())
}
fun main() {
val ans = addTwoNumbers(l1 = ListNode(listOf(9,9,9,9,9,9,9)), l2 = ListNode(listOf(9,9,9,9)))
println(ans.value)
}
| [
{
"class_path": "MhmoudAlim__Coding-challanges__31f0b84/leetcode_problems/medium/AddTwoNumbersKt.class",
"javap": "Compiled from \"AddTwoNumbers.kt\"\npublic final class leetcode_problems.medium.AddTwoNumbersKt {\n public static final leetcode_problems.medium.ListNode addTwoNumbers(leetcode_problems.medium... |
jens-muenker__fuzzywuzzy-kotlin__da452a7/fuzzywuzzy_kotlin/src/main/java/com/frosch2010/fuzzywuzzy_kotlin/algorithms/Utils.kt | package com.frosch2010.fuzzywuzzy_kotlin.algorithms
import java.util.Arrays
import java.util.Collections
import java.util.PriorityQueue
object Utils {
fun tokenize(`in`: String): List<String> {
return Arrays.asList(*`in`.split("\\s+".toRegex()).dropLastWhile { it.isEmpty() }
.toTypedArray())
}
fun tokenizeSet(`in`: String): Set<String> {
return HashSet(tokenize(`in`))
}
fun sortAndJoin(col: List<String?>, sep: String?): String {
val sortedList = col.sortedWith(Comparator { a, b ->
when {
a == null && b == null -> 0
a == null -> -1
b == null -> 1
else -> a.compareTo(b)
}
})
return join(sortedList, sep)
}
fun join(strings: List<String?>, sep: String?): String {
val buf = StringBuilder(strings.size * 16)
for (i in strings.indices) {
if (i < strings.size) {
buf.append(sep)
}
buf.append(strings[i])
}
return buf.toString().trim { it <= ' ' }
}
fun sortAndJoin(col: Set<String?>?, sep: String?): String {
return sortAndJoin(ArrayList(col), sep)
}
fun <T : Comparable<T>?> findTopKHeap(arr: List<T>, k: Int): List<T> {
val pq = PriorityQueue<T>()
for (x in arr) {
if (pq.size < k) pq.add(x) else if (x!!.compareTo(pq.peek()) > 0) {
pq.poll()
pq.add(x)
}
}
val res: MutableList<T> = ArrayList()
for (i in k downTo 1) {
val polled = pq.poll()
if (polled != null) {
res.add(polled)
}
}
return res
}
fun <T : Comparable<T>?> max(vararg elems: T): T? {
if (elems.size == 0) return null
var best = elems[0]
for (t in elems) {
if (t!!.compareTo(best) > 0) {
best = t
}
}
return best
}
} | [
{
"class_path": "jens-muenker__fuzzywuzzy-kotlin__da452a7/com/frosch2010/fuzzywuzzy_kotlin/algorithms/Utils.class",
"javap": "Compiled from \"Utils.kt\"\npublic final class com.frosch2010.fuzzywuzzy_kotlin.algorithms.Utils {\n public static final com.frosch2010.fuzzywuzzy_kotlin.algorithms.Utils INSTANCE;\... |
Const-Grigoryev__LeetCode__cea8e76/Kotlin/src/dev/aspid812/leetcode/problem1854/Solution.kt | package dev.aspid812.leetcode.problem1854
import java.time.Year
/* 1854. Maximum Population Year
* -----------------------------
*
* You are given a 2D integer array `logs` where each `logs[i] = [birth_i, death_i]` indicates the birth and death
* years of the `i`-th person.
*
* The **population** of some year `x` is the number of people alive during that year. The `i`-th person is counted
* in year `x`'s population if `x` is in the **inclusive** range `[birth_i, death_i - 1]`. Note that the person
* is **not** counted in the year that they die.
*
* Return *the **earliest** year with the **maximum population***.
*
* ### Constraints:
*
* * `1 <= logs.length <= 100`
* * `1950 <= birth_i < death_i <= 2050`
*/
import kotlin.math.min
typealias Lifespan = IntArray
data class PopulationRecord(
public val year: Int,
public val population: Int
)
class Solution {
fun maximumPopulation(logs: Array<Lifespan>): Int {
val birthYears = logs.map { log -> log[0] }.toIntArray()
birthYears.sort()
val deathYears = logs.map { log -> log[1] }.toIntArray()
deathYears.sort()
return sequence {
var population = 0
var (i, j) = Pair(0, 0)
while (i < birthYears.size || j < deathYears.size) {
var year = min(
birthYears.getOrNull(i) ?: 2050,
deathYears.getOrNull(j) ?: 2050
)
while (i < birthYears.size && birthYears[i] == year) {
population += 1
i++
}
while (j < deathYears.size && deathYears[j] == year) {
population -= 1
j++
}
yield(PopulationRecord(year, population))
}
}.maxByOrNull(PopulationRecord::population)?.year ?: 1950
}
}
fun makeLogs(vararg lifespans: IntRange): Array<Lifespan> {
return lifespans.map { range -> intArrayOf(range.start, range.endInclusive + 1) }.toTypedArray()
}
fun main() {
val s = Solution()
// The maximum population is 1, and 1993 is the earliest year with this population.
val logs1 = makeLogs(1993 until 1999, 2000 until 2010)
println("${s.maximumPopulation(logs1)} == 1993")
// The maximum population is 2, and it had happened in years 1960 and 1970.
// The earlier year between them is 1960.
val logs2 = makeLogs(1950 until 1961, 1960 until 1971, 1970 until 1981)
println("${s.maximumPopulation(logs2)} == 1960")
val logs3 = makeLogs(1982 until 1998, 2013 until 2042, 2010 until 2035, 2022 until 2050, 2047 until 2048)
println("${s.maximumPopulation(logs3)} == 2022")
}
| [
{
"class_path": "Const-Grigoryev__LeetCode__cea8e76/dev/aspid812/leetcode/problem1854/Solution.class",
"javap": "Compiled from \"Solution.kt\"\npublic final class dev.aspid812.leetcode.problem1854.Solution {\n public dev.aspid812.leetcode.problem1854.Solution();\n Code:\n 0: aload_0\n 1: inv... |
Const-Grigoryev__LeetCode__cea8e76/Kotlin/src/dev/aspid812/leetcode/problem0541/Solution.kt | package dev.aspid812.leetcode.problem0541
/* 541. Reverse String II
* ----------------------
*
* Given a string `s` and an integer `k`, reverse the first `k` characters for every `2k` characters counting
* from the start of the string.
*
* If there are fewer than `k` characters left, reverse all of them. If there are less than `2k` but greater than
* or equal to `k` characters, then reverse the first `k` characters and left the other as original.
*
* ### Constraints:
*
* * `1 <= s.length <= 10^4`
* * `s` consists of only lowercase English letters.
* * `1 <= k <= 10^4`
*/
import kotlin.math.min
class Solution {
fun CharArray.swap(i: Int, j: Int) {
val c = this[i]
this[i] = this[j]
this[j] = c
}
fun CharArray.reverse(start: Int, end: Int) {
var i = start
var j = end - 1
while (i < j) {
swap(i++, j--)
}
}
fun reverseStr(str: String, k: Int): String {
val s = str.toCharArray()
for (i in s.indices.step(2 * k)) {
s.reverse(i, min(i + k, s.size))
}
return String(s)
}
}
fun main() {
val s = Solution()
println("${s.reverseStr(str="abcdefg", k=2)} == \"bacdfeg\"")
println("${s.reverseStr(str="abcd", k=2)} == \"bacd\"")
} | [
{
"class_path": "Const-Grigoryev__LeetCode__cea8e76/dev/aspid812/leetcode/problem0541/Solution.class",
"javap": "Compiled from \"Solution.kt\"\npublic final class dev.aspid812.leetcode.problem0541.Solution {\n public dev.aspid812.leetcode.problem0541.Solution();\n Code:\n 0: aload_0\n 1: inv... |
Const-Grigoryev__LeetCode__cea8e76/Kotlin/src/dev/aspid812/leetcode/problem0056/Solution.kt | package dev.aspid812.leetcode.problem0056
/* 56. Merge Intervals
* -------------------
*
* Given an array of `intervals` where `intervals[i] = [start_i, end_i]`, merge all overlapping intervals, and return
* *an array of the non-overlapping intervals that cover all the intervals in the input*.
*
* ### Constraints:
*
* * `1 <= intervals.length <= 10^4`
* * `intervals[i].length == 2`
* * `0 <= start_i <= end_i <= 10^4`
*/
typealias Interval = IntArray
class Solution {
fun merge(intervals: Array<Interval>): Array<Interval> {
intervals.sortBy { interval -> interval[0] }
var span = intArrayOf(-1, -1)
var (i, j) = Pair(0, 0)
while (j < intervals.size) {
if (span[1] < intervals[j][0]) {
intervals[i] = intervals[j]
span = intervals[i]
i += 1
}
else if (span[1] < intervals[j][1]) {
span[1] = intervals[j][1]
}
j += 1
}
return intervals.copyOfRange(0, i)
}
}
fun makeIntervals(vararg intervals: IntRange): Array<Interval> {
return intervals.map { range -> intArrayOf(range.start, range.endInclusive)}.toTypedArray()
}
fun main() {
val s = Solution()
// Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
val intervals1 = makeIntervals(1..3, 2..6, 8..10, 15..18)
println("${s.merge(intervals1).contentDeepToString()} == [[1,6],[8,10],[15,18]]")
// Intervals [1,4] and [4,5] are considered overlapping.
val intervals2 = makeIntervals(1..4, 4..5)
println("${s.merge(intervals2).contentDeepToString()} == [[1,5]]")
} | [
{
"class_path": "Const-Grigoryev__LeetCode__cea8e76/dev/aspid812/leetcode/problem0056/Solution.class",
"javap": "Compiled from \"Solution.kt\"\npublic final class dev.aspid812.leetcode.problem0056.Solution {\n public dev.aspid812.leetcode.problem0056.Solution();\n Code:\n 0: aload_0\n 1: inv... |
Const-Grigoryev__LeetCode__cea8e76/Kotlin/src/dev/aspid812/leetcode/problem0539/Solution.kt | package dev.aspid812.leetcode.problem0539
/* 539. Minimum Time Difference
* ----------------------------
* Given a list of 24-hour clock time points in **"HH:MM"** format, return the *minimum **minutes** difference
* between any two time-points in the list*.
*
* ### Constraints:
*
* * `2 <= timePoints <= 2 * 10^4`
* * `timePoints[i]` is in the format **"HH:MM"**.
*/
class Solution {
fun findMinDifference(timePoints: List<String>): Int {
return timePoints.asSequence()
.map { timePoint ->
val hours = timePoint.substringBefore(':').toInt()
val minutes = timePoint.substringAfter(':').toInt()
hours * 60 + minutes
}
.sorted()
.let { seq ->
val instant = seq.iterator().next()
seq + (instant + 1440)
}
.zipWithNext { start, end -> end - start }
.minOrNull() ?: 1440
}
}
fun main() {
val s = Solution()
val timePoints1 = listOf("23:59", "00:00")
println("${s.findMinDifference(timePoints1)} == 1")
val timePoints2 = listOf("00:00", "23:59", "00:00")
println("${s.findMinDifference(timePoints2)} == 1")
} | [
{
"class_path": "Const-Grigoryev__LeetCode__cea8e76/dev/aspid812/leetcode/problem0539/Solution.class",
"javap": "Compiled from \"Solution.kt\"\npublic final class dev.aspid812.leetcode.problem0539.Solution {\n public dev.aspid812.leetcode.problem0539.Solution();\n Code:\n 0: aload_0\n 1: inv... |
mledl__aoc23__7949d61/src/main/kotlin/challenges/Day03.kt | package challenges
class Day03(private val input: List<String>) {
private val offset = input[0].length + 1
private val inputStr = input.fold("") { acc, s -> acc.plus("$s.") }
private val regex = "\\d+".toRegex()
fun getPart1(): Int = calcRanges(inputStr, offset, input.size).filter { pair -> pair.second.any { !isDigitOrDot(inputStr[it]) } }.sumOf { it.first }
fun getPart2(): Int {
var sum = 0
val ranges = input.map { regex.findAll(it).flatMap { match -> match.range.toList().map { it to match.value.toInt() } }.toMap() }
for ((lineIdx, line) in input.withIndex()) {
var gearIdx = line.indexOf('*')
while (gearIdx >= 0) {
val factors = arrayListOf<Int>()
// check line above
if (lineIdx > 0) {
if (gearIdx > 0) ranges[lineIdx - 1][gearIdx - 1]?.let { factors.add(it) }
if (ranges[lineIdx - 1][gearIdx - 1] != ranges[lineIdx - 1][gearIdx]) ranges[lineIdx - 1][gearIdx]?.let { factors.add(it) }
if (gearIdx < line.length && ranges[lineIdx - 1][gearIdx] != ranges[lineIdx - 1][gearIdx + 1]) ranges[lineIdx - 1][gearIdx + 1]?.let { factors.add(it) }
}
// check same line
if (gearIdx > 0) ranges[lineIdx][gearIdx - 1]?.let { factors.add(it) }
if (gearIdx < line.length) ranges[lineIdx][gearIdx + 1]?.let { factors.add(it) }
// check below line
if (lineIdx < input.size) {
if (gearIdx > 0) ranges[lineIdx + 1][gearIdx - 1]?.let { factors.add(it) }
if (ranges[lineIdx + 1][gearIdx - 1] != ranges[lineIdx + 1][gearIdx]) ranges[lineIdx + 1][gearIdx]?.let { factors.add(it) }
if (gearIdx < line.length && ranges[lineIdx + 1][gearIdx] != ranges[lineIdx + 1][gearIdx + 1]) ranges[lineIdx + 1][gearIdx + 1]?.let { factors.add(it) }
}
if (factors.size == 2) sum += factors[0] * factors[1]
gearIdx = line.indexOf('*', gearIdx + 1)
}
}
return sum
}
// Part 1 helper
private fun calcRanges(inputStr: String, offset: Int, lines: Int): Sequence<Pair<Int, List<Int>>> = "\\d+".toRegex().findAll(inputStr).map { match ->
var base = match.range.toList()
if (match.range.first % offset != 0) base = base.plus(match.range.first - 1)
if (match.range.last % offset != offset-1) base = base.plus(match.range.last + 1)
var valuesOfInterest = base.map { it - offset }.plus(base.map { it + offset })
if (match.range.first % offset != 0) valuesOfInterest = valuesOfInterest.plus(match.range.first - 1)
if (match.range.last % offset != offset-1) valuesOfInterest = valuesOfInterest.plus(match.range.last + 1)
valuesOfInterest = valuesOfInterest.filter { it >= 0 && it < offset * lines }
match.value.toInt() to valuesOfInterest
}
private fun isDigitOrDot(c: Char): Boolean = c.isDigit() || c == '.'
// Part 2 helper
}
| [
{
"class_path": "mledl__aoc23__7949d61/challenges/Day03.class",
"javap": "Compiled from \"Day03.kt\"\npublic final class challenges.Day03 {\n private final java.util.List<java.lang.String> input;\n\n private final int offset;\n\n private final java.lang.String inputStr;\n\n private final kotlin.text.Reg... |
mledl__aoc23__7949d61/src/main/kotlin/challenges/Day02.kt | package challenges
class Day02(private val input: List<String>) {
private val checkMap = mapOf("red" to 12, "green" to 13, "blue" to 14)
fun getPart1(): Int = input.mapIndexed { index, s -> if (checkGame(s.split(";"))) index + 1 else 0 }.sum()
fun getPart2(): Int = calcPowers(input)
// Part 1 helper
private fun checkGame(draws: List<String>): Boolean = draws.all { checkDraw(it) }
private fun checkDraw(draw: String): Boolean = draw.split(",").all { checkCube(it) }
private fun checkCube(cube: String): Boolean = cube.trim().split(" ").let {
it.isNotEmpty() && it[0].toInt() <= checkMap[it[1]]!!
}
// Part 2 helper
private fun calcPowers(games: List<String>) = games.sumOf {
game -> listOf("red", "green", "blue").map { s ->
"\\d+ $s".toRegex().findAll(game).map {
it.value.trim().split(" ").first().toInt()
}.max()
}.reduce { acc, elem -> acc * elem }
}
}
| [
{
"class_path": "mledl__aoc23__7949d61/challenges/Day02.class",
"javap": "Compiled from \"Day02.kt\"\npublic final class challenges.Day02 {\n private final java.util.List<java.lang.String> input;\n\n private final java.util.Map<java.lang.String, java.lang.Integer> checkMap;\n\n public challenges.Day02(ja... |
ProgramaCatalisa__ResolucaoExerciciosKotlin__e0b994c/modulo4/src/aula14/Exercicio08.kt | package aula14
/*Exercício 04 da parte 'Exercícios gerais'*/
fun main() {
print("Informe a quantidade de alunes a turma tem: ")
val quantidadeAlunos = readln().toInt()
val turma = receberDadosAlune(quantidadeAlunos)
val medias = calcularMedia(quantidadeAlunos, turma)
printarMedias(turma, medias)
}
fun receberDadosAlune(quantidadeAlunos: Int): ArrayList<String> {
val turma = ArrayList<String>()
var contador = 0
while (contador < quantidadeAlunos) {
print("Informe o nome da pessoa número ${contador + 1}: ")
val nome = readln()
turma.add(nome)
contador++
}
return turma
}
fun calcularMedia(quantidadeAlunos: Int, turma: ArrayList<String>): DoubleArray {
val medias = DoubleArray(quantidadeAlunos)
turma.forEachIndexed { index, alune ->
print("Digite a primeira nota de $alune: ")
val nota1 = readln().toDouble()
print("Digite a segunda nota de $alune: ")
val nota2 = readln().toDouble()
print("Digite a terceira nota de $alune: ")
val nota3 = readln().toDouble()
val media = (nota1 + nota2 + nota3) / 3
medias[index] = media
}
return medias
}
fun printarMedias(turma: ArrayList<String>, medias: DoubleArray) {
turma.forEachIndexed { index, alune ->
println("Alune $alune teve média ${medias[index]}")
}
}
| [
{
"class_path": "ProgramaCatalisa__ResolucaoExerciciosKotlin__e0b994c/aula14/Exercicio08Kt.class",
"javap": "Compiled from \"Exercicio08.kt\"\npublic final class aula14.Exercicio08Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String Informe a quantidade ... |
devetude__BOJ-PSJ__4c6acff/src/boj_2206/Kotlin.kt | package boj_2206
import java.util.LinkedList
import java.util.StringTokenizer
val DIRECTIONS = arrayOf(arrayOf(0, 1), arrayOf(0, -1), arrayOf(1, 0), arrayOf(-1, 0))
fun main() {
val st = StringTokenizer(readln())
val n = st.nextToken().toInt()
val m = st.nextToken().toInt()
val map = Array(size = n + 1) { CharArray(size = m + 1) }
for (row in 1..n) {
val input = readln()
for (col in 1..m) {
map[row][col] = input[col - 1]
}
}
val startPoint = Point(row = 1, col = 1, depth = 1, hasBreakChance = true)
val queue = LinkedList<Point>()
queue.offer(startPoint)
val isVisited = Array(size = n + 1) { Array(size = m + 1) { BooleanArray(size = 2) } }
isVisited[1][1][0] = true
while (queue.isNotEmpty()) {
val point = queue.poll()
if (point.row == n && point.col == m) return println(point.depth)
val nextPoints = DIRECTIONS.asSequence()
.map { (rowDiff, colDiff) ->
val nextRow = point.row + rowDiff
val nextCol = point.col + colDiff
val nextDepth = point.depth + 1
Point(nextRow, nextCol, nextDepth, point.hasBreakChance)
}
.filter { it.row in 1..n && it.col in 1..m }
.toList()
nextPoints.forEach { nextPoint ->
if (map[nextPoint.row][nextPoint.col] == '0') {
if (nextPoint.hasBreakChance && !isVisited[nextPoint.row][nextPoint.col][0]) {
isVisited[nextPoint.row][nextPoint.col][0] = true
queue.offer(nextPoint)
} else if (!isVisited[nextPoint.row][nextPoint.col][1]) {
isVisited[nextPoint.row][nextPoint.col][1] = true
queue.offer(nextPoint)
}
} else {
if (nextPoint.hasBreakChance) {
isVisited[nextPoint.row][nextPoint.col][1] = true
queue.offer(nextPoint.copy(hasBreakChance = false))
}
}
}
}
println(-1)
}
data class Point(
val row: Int,
val col: Int,
val depth: Int,
val hasBreakChance: Boolean
)
| [
{
"class_path": "devetude__BOJ-PSJ__4c6acff/boj_2206/KotlinKt.class",
"javap": "Compiled from \"Kotlin.kt\"\npublic final class boj_2206.KotlinKt {\n private static final java.lang.Integer[][] DIRECTIONS;\n\n public static final java.lang.Integer[][] getDIRECTIONS();\n Code:\n 0: getstatic #1... |
devetude__BOJ-PSJ__4c6acff/src/boj_14888/Kotlin.kt | package boj_14888
import java.util.StringTokenizer
import kotlin.math.max
import kotlin.math.min
var maxValue = Int.MIN_VALUE
var minValue = Int.MAX_VALUE
fun main() {
val n = readln().toInt()
var st = StringTokenizer(readln())
val numbers = IntArray(n)
repeat(n) { numbers[it] = st.nextToken().toInt() }
st = StringTokenizer(readln())
val opCounts = IntArray(size = 4)
repeat(opCounts.size) { opCounts[it] = st.nextToken().toInt() }
val opSequences = IntArray(size = n - 1)
dfs(numbers, opSequences, opCounts)
val result = buildString {
appendLine(maxValue)
append(minValue)
}
println(result)
}
fun dfs(numbers: IntArray, opTypes: IntArray, opCounts: IntArray, opSeq: Int = 0) {
if (opSeq == opTypes.size) {
var result = numbers.first()
for (i in 1..numbers.lastIndex) {
val number = numbers[i]
result = when (opTypes[i - 1]) {
0 -> result + number
1 -> result - number
2 -> result * number
else -> result / number
}
}
maxValue = max(maxValue, result)
minValue = min(minValue, result)
return
}
opCounts.forEachIndexed { opType, opCount ->
if (0 < opCount) {
opTypes[opSeq] = opType
--opCounts[opType]
dfs(numbers, opTypes, opCounts, opSeq = opSeq + 1)
++opCounts[opType]
}
}
}
| [
{
"class_path": "devetude__BOJ-PSJ__4c6acff/boj_14888/KotlinKt.class",
"javap": "Compiled from \"Kotlin.kt\"\npublic final class boj_14888.KotlinKt {\n private static int maxValue;\n\n private static int minValue;\n\n public static final int getMaxValue();\n Code:\n 0: getstatic #10 ... |
pocmo__AdventOfCode2021__73bbb6a/src/day4/Day4.kt | package day4
import java.io.File
data class Number(
val value: Int,
var marked: Boolean = false
)
data class Board(
val data: Array<Array<Number>> = Array(5) { Array(5) { Number(0) } }
) {
override fun equals(other: Any?): Boolean {
if (other !is Board) return false
return data.contentEquals(other.data)
}
override fun hashCode(): Int {
return data.contentHashCode()
}
override fun toString(): String {
return data.joinToString("\n") { row ->
row.joinToString(" ") { number ->
if (number.marked) "X" else number.value.toString()
}
}
}
fun mark(value: Int) {
data.forEach { row ->
row.forEach { number ->
if (number.value == value) number.marked = true
}
}
}
fun sumUnmarkedNumbers(): Int {
return data.flatten().filter { !it.marked }.sumBy { it.value }
}
fun isWinner(): Boolean {
return isRowWinner() || isColumnWinner()
}
private fun isRowWinner(): Boolean {
for (y in 0 until 5) {
var winner = true
for (x in 0 until 5) {
if (!data[y][x].marked) {
winner = false
}
}
if (winner) return true
}
return false
}
private fun isColumnWinner(): Boolean {
for (x in 0 until 5) {
var winner = true
for (y in 0 until 5) {
if (!data[y][x].marked) {
winner = false
}
}
if (winner) return true
}
return false
}
}
fun readBoard(data: List<String>, position: Int): Board {
val boardData = data.subList(position, position + 5)
val board = Board()
boardData.forEachIndexed { row, line ->
val rowData = line.split(" ").filter { it.isNotEmpty() }.map { it.toInt() }
rowData.forEachIndexed { column, value ->
board.data[row][column] = Number(value)
}
}
return board
}
fun readData(): Pair<List<Int>, List<Board>> {
val values = File("day4.txt").readLines()
val numbers = values[0].split(",").map { it.toInt() }
val boards = mutableListOf<Board>()
for (i in 2 until values.size step 6) {
val board = readBoard(values, i)
boards.add(board)
}
return Pair(numbers, boards)
}
fun findWinningBoard(numbers: List<Int>, boards: List<Board>): Pair<Int, Board> {
for (number in numbers) {
for (board in boards) {
board.mark(number)
if (board.isWinner()) {
return Pair(number, board)
}
}
}
throw IllegalStateException("No winning board found")
}
fun part1() {
val (numbers, boards) = readData()
val (number, board) = findWinningBoard(numbers, boards)
println("Winning number: $number")
println("Winning board:")
println(board)
val sum = board.sumUnmarkedNumbers()
println("Unmarked numbers sum: $sum")
println()
println("Result: ${sum * number}")
}
fun part2() {
val (numbers, boards) = readData()
val boardCandidates = boards.toMutableList()
while (boardCandidates.size > 1) {
// Find the winning board and remove it from the list
val (number, winningBoard) = findWinningBoard(numbers, boardCandidates)
boardCandidates.remove(winningBoard)
}
val board = boardCandidates[0]
val (number, winningBoard) = findWinningBoard(numbers, listOf(board))
println("Last number: $number")
println("Winning board found:")
println(winningBoard)
val sum = winningBoard.sumUnmarkedNumbers()
println("Unmarked numbers sum: $sum")
println()
println("Result: ${sum * number}")
}
fun main() {
part2()
}
| [
{
"class_path": "pocmo__AdventOfCode2021__73bbb6a/day4/Day4Kt.class",
"javap": "Compiled from \"Day4.kt\"\npublic final class day4.Day4Kt {\n public static final day4.Board readBoard(java.util.List<java.lang.String>, int);\n Code:\n 0: aload_0\n 1: ldc #10 // String... |
pocmo__AdventOfCode2021__73bbb6a/src/day3/Day3.kt | package day3
import java.io.File
data class Count(
var zeros: Int = 0,
var ones: Int = 0
)
fun part1() {
val lines = File("day3.txt").readLines()
val counts: List<Count> = generateSequence {
Count()
}.take(12).toList()
lines.forEach { line ->
line.forEachIndexed { index, character ->
when (character) {
'0' -> counts[index].zeros++
'1' -> counts[index].ones++
}
}
}
val gammaRateRaw = counts.joinToString("") { count ->
if (count.ones > count.zeros) {
"1"
} else if (count.zeros > count.ones) {
"0"
} else {
throw IllegalStateException("No most common bit")
}
}
val epsilonRateRaw = gammaRateRaw.map { character ->
when (character) {
'0' -> '1'
'1' -> '0'
else -> throw IllegalStateException("Unknown character: $character")
}
}.joinToString("")
val gammaRate = Integer.parseInt(gammaRateRaw, 2)
val epsilonRate = Integer.parseInt(epsilonRateRaw, 2)
println("gamma: $gammaRateRaw -> $gammaRate")
println("gamma: $epsilonRateRaw -> $epsilonRate")
println("part1 solution = ${gammaRate * epsilonRate}")
}
fun findCount(values: List<String>, position: Int): Count {
val count = Count()
values.forEach { line ->
val character = line[position]
when (character) {
'0' -> count.zeros++
'1' -> count.ones++
}
}
return count
}
fun findRating(
values: List<String>,
position: Int,
filter: (String, Int, Count) -> Boolean
): String {
val count = findCount(values, position)
val filteredValues = values.filter { value ->
filter(value, position, count)
}
return if (filteredValues.size == 1) {
filteredValues[0]
} else if (filteredValues.size > 1) {
findRating(filteredValues, position + 1, filter)
} else {
throw IllegalStateException("Could not find values")
}
}
fun findOxygenBit(count: Count): Char {
return if (count.ones > count.zeros) {
'1'
} else if (count.zeros > count.ones) {
'0'
} else {
'1'
}
}
fun findCo2Bit(count: Count): Char {
return if (count.ones < count.zeros) {
'1'
} else if (count.zeros < count.ones) {
'0'
} else {
'0'
}
}
fun part2() {
val values = File("day3.txt").readLines()
val oxygenRatingRaw = findRating(values, 0) { value, position, count ->
val valueAtPosition = value[position]
valueAtPosition == findOxygenBit(count)
}
val oxygenRating = Integer.parseInt(oxygenRatingRaw, 2)
println("oxygen $oxygenRatingRaw -> $oxygenRating")
val co2RatingRaw = findRating(values, 0) { value, position, count ->
val valueAtPosition = value[position]
valueAtPosition == findCo2Bit(count)
}
val co2Rating = Integer.parseInt(co2RatingRaw, 2)
println("co2 $co2RatingRaw -> $co2Rating")
println("Solution ${oxygenRating * co2Rating}")
}
fun main() {
part2()
} | [
{
"class_path": "pocmo__AdventOfCode2021__73bbb6a/day3/Day3Kt.class",
"javap": "Compiled from \"Day3.kt\"\npublic final class day3.Day3Kt {\n public static final void part1();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc #10 ... |
pocmo__AdventOfCode2021__73bbb6a/src/day2/Day2.kt | package day2
import java.io.File
sealed interface Command {
data class Forward(
val steps: Int
): Command
data class Down(
val steps: Int
) : Command
data class Up(
val steps: Int
) : Command
}
fun readCourse(): List<Command> {
val lines = File("day2.txt").readLines()
return lines.map { line ->
val (command, steps) = line.split(" ").let { raw ->
Pair(raw[0], raw[1].toInt())
}
when (command) {
"forward" -> Command.Forward(steps)
"down" -> Command.Down(steps)
"up" -> Command.Up(steps)
else -> throw IllegalStateException("Unknown command: $command")
}
}
}
class Submarine {
var horizontalPosition = 0
private set
var depth = 0
private set
var aim = 0
private set
fun process(course: List<Command>) {
course.forEach { command ->
when (command) {
is Command.Forward -> horizontalPosition += command.steps
is Command.Up -> depth -= command.steps
is Command.Down -> depth += command.steps
}
}
}
fun processNew(course: List<Command>) {
course.forEach { command ->
when (command) {
is Command.Forward -> {
horizontalPosition += command.steps
depth += aim * command.steps
}
is Command.Up -> {
aim -= command.steps
}
is Command.Down -> {
aim += command.steps
}
}
}
}
fun getSolution(): Int {
return horizontalPosition * depth
}
}
fun part1() {
val course = readCourse()
println("Size: " + course.size)
val submarine = Submarine()
submarine.process(course)
println("Position: " + submarine.horizontalPosition)
println("Depth: " + submarine.depth)
println(submarine.getSolution())
}
fun part2() {
val course = readCourse()
println("Size: " + course.size)
val submarine = Submarine()
submarine.processNew(course)
println("Position: " + submarine.horizontalPosition)
println("Depth: " + submarine.depth)
println("Aim: " + submarine.aim)
println("Solution: " + submarine.getSolution())
}
fun main() {
part2()
} | [
{
"class_path": "pocmo__AdventOfCode2021__73bbb6a/day2/Day2Kt.class",
"javap": "Compiled from \"Day2.kt\"\npublic final class day2.Day2Kt {\n public static final java.util.List<day2.Command> readCourse();\n Code:\n 0: new #10 // class java/io/File\n 3: dup\n 4... |
pocmo__AdventOfCode2021__73bbb6a/src/day5/Day5.kt | package day5
import java.io.File
data class Line(
val x1: Int,
val y1: Int,
val x2: Int,
val y2: Int
) {
private fun isHorizontal(): Boolean = y1 == y2
private fun isVertical(): Boolean = x1 == x2
private fun isDiagonal(): Boolean = !isHorizontal() && !isVertical()
fun isHorizontalOrVertical(): Boolean = isHorizontal() || isVertical()
fun getPoints(): List<Pair<Int, Int>> {
return if (isHorizontal()) {
val points = mutableListOf<Pair<Int, Int>>()
val startX = x1.coerceAtMost(x2)
val endX = x1.coerceAtLeast(x2)
for (x in startX..endX) {
points.add(Pair(x, y1))
}
points
} else if (isVertical()) {
val points = mutableListOf<Pair<Int, Int>>()
val startY = y1.coerceAtMost(y2)
val endY = y1.coerceAtLeast(y2)
for (y in startY..endY) {
points.add(Pair(x1, y))
}
points
} else if (isDiagonal()) {
getDiagonalPoints(x1, y1, x2, y2)
} else {
throw IllegalStateException("Line is not horizontal, vertical or diagonal")
}
}
}
fun getDiagonalPoints(startX: Int, startY: Int, endX: Int, endY: Int): List<Pair<Int, Int>> {
val points = mutableListOf<Pair<Int, Int>>()
val start = Pair(startX, startY)
val end = Pair(endX, endY)
val xDiff = end.first - start.first
val yDiff = end.second - start.second
val xStep = if (xDiff > 0) 1 else -1
val yStep = if (yDiff > 0) 1 else -1
var x = start.first
var y = start.second
while (x != end.first || y != end.second) {
points.add(Pair(x, y))
x += xStep
y += yStep
}
points.add(Pair(x, y))
return points
}
fun readLines(): List<Line> {
val values = File("day5.txt").readLines()
return values.map { line ->
val (point1, point2) = line.split(" -> ")
val (x1, y1) = point1.split(",")
val (x2, y2) = point2.split(",")
Line(x1.toInt(), y1.toInt(), x2.toInt(), y2.toInt())
}
}
fun List<Pair<Int, Int>>.getDuplicates(): Set<Pair<Int, Int>> {
val counts = mutableMapOf<Pair<Int, Int>, Int>()
for (point in this) {
val count = counts.getOrDefault(point, 0)
counts[point] = count + 1
}
return counts.filter { it.value > 1 }.keys
}
fun part1() {
val points = readLines()
.filter { it.isHorizontalOrVertical() }
.map { it.getPoints() }
.flatten()
.getDuplicates()
println(points.size)
}
fun part2() {
val points = readLines()
.map { it.getPoints() }
.flatten()
.getDuplicates()
// Wong: 22982
// Right: 21406
println(points.size)
}
fun main() {
part2()
}
| [
{
"class_path": "pocmo__AdventOfCode2021__73bbb6a/day5/Day5Kt.class",
"javap": "Compiled from \"Day5.kt\"\npublic final class day5.Day5Kt {\n public static final java.util.List<kotlin.Pair<java.lang.Integer, java.lang.Integer>> getDiagonalPoints(int, int, int, int);\n Code:\n 0: new #10 ... |
pocmo__AdventOfCode2021__73bbb6a/src/day12/Day12.kt | package day12
import java.io.File
data class Cave(
val name: String
) {
fun isEnd() = name == "end"
fun isStart() = name == "start"
fun isLarge(): Boolean = name[0].isUpperCase()
fun isSmall() = !isStart() && !isEnd() && name[0].isLowerCase()
}
fun readCavesFromFile(fileName: String): Map<Cave, MutableList<Cave>> {
return readCavesFromString(File(fileName)
.readText())
}
fun readCavesFromString(input: String): Map<Cave, MutableList<Cave>> {
val caveMap = mutableMapOf<Cave, MutableList<Cave>>()
input.lines()
.map { line ->
val (a, b) = line.split("-")
Pair(a, b)
}
.forEach { (a, b) ->
val caveA = Cave(a)
val caveB = Cave(b)
val connectionsA = caveMap.getOrDefault(caveA, mutableListOf())
connectionsA.add(caveB)
caveMap[caveA] = connectionsA
val connectionB = caveMap.getOrDefault(caveB, mutableListOf())
connectionB.add(caveA)
caveMap[caveB] = connectionB
}
return caveMap
}
fun List<Cave>.visitedOnlyOnce(cave: Cave): Boolean {
return count { current -> current == cave } == 1
}
fun Map<Cave, MutableList<Cave>>.continuePath(
cave: Cave,
path: List<Cave>,
visited: List<Cave>,
smallCaveToVisitAgain: Cave? = null
): List<List<Cave>> {
val newPath = path + cave
if (cave.isEnd()) {
return listOf(newPath)
}
val connections = (get(cave) ?: throw IllegalStateException("No connection from $cave"))
.filter { current ->
val onlyVisitedOnce = visited.visitedOnlyOnce(current)
val isSpecialSmallCave = current == smallCaveToVisitAgain
current.isLarge() || current !in visited || (isSpecialSmallCave && onlyVisitedOnce)
}
if (connections.isEmpty()) {
return emptyList()
}
val paths = mutableListOf<List<Cave>>()
for (current in connections) {
val newPaths = continuePath(
current,
newPath,
visited + cave,
smallCaveToVisitAgain
)
paths.addAll(newPaths)
}
return paths
}
fun Map<Cave, MutableList<Cave>>.findPaths(): List<List<Cave>> {
return continuePath(
Cave("start"),
listOf(),
listOf()
)
}
fun Map<Cave, MutableList<Cave>>.findPathsSpecial(): List<List<Cave>> {
val paths = mutableListOf<List<Cave>>()
keys.filter { cave -> cave.isSmall() }
.forEach { cave ->
val currentPaths = continuePath(
Cave("start"),
listOf(),
listOf(),
cave
)
paths.addAll(currentPaths)
}
return paths.distinct()
}
fun part1() {
val caveMap = readCavesFromFile("day12.txt")
val paths = caveMap.findPaths()
println("Paths = ${paths.size}")
}
fun part2() {
val caveMap = readCavesFromFile("day12.txt")
val paths = caveMap.findPathsSpecial()
println("Paths = ${paths.size}")
}
fun main() {
part2()
}
| [
{
"class_path": "pocmo__AdventOfCode2021__73bbb6a/day12/Day12Kt.class",
"javap": "Compiled from \"Day12.kt\"\npublic final class day12.Day12Kt {\n public static final java.util.Map<day12.Cave, java.util.List<day12.Cave>> readCavesFromFile(java.lang.String);\n Code:\n 0: aload_0\n 1: ldc ... |
pocmo__AdventOfCode2021__73bbb6a/src/day14/Day14.kt | package day14
import java.io.File
fun readFile(fileName: String): Pair<String, Map<String, String>> {
return readFromString(File(fileName)
.readText()
.trim())
}
fun Map<String, String>.toCharacterMap(): Map<String, Char> {
return mapValues { (_, character) -> character[0] }
}
fun performInsertion(template: String, map: Map<String, String>): String {
val insertions = mutableListOf<String>()
val groups = template.windowed(size = 2, step = 1, partialWindows = false)
groups.forEach { group ->
val insertion = map[group] ?: throw IllegalStateException("No mapping for $group")
insertions.add(insertion)
}
return buildString {
insertions.forEachIndexed { index, insertion ->
append(template[index])
append(insertion)
}
append(template.last())
}
}
fun createGroupCount(template: String): Map<String, Long> {
val map = mutableMapOf<String, Long>()
template.windowed(size = 2, step = 1, partialWindows = false).forEach { group ->
map.count(group, 1)
}
return map
}
fun MutableMap<Char, Long>.count(character: Char, count: Long) {
val value = getOrDefault(character, 0L)
val updated = value + count
if (updated < value) {
throw IllegalStateException("Oops, we failed")
}
put(character, updated)
}
fun MutableMap<String, Long>.count(group: String, count: Long = 1L) {
val value = getOrDefault(group, 0L)
val updated = value + count
if (updated < value) {
throw IllegalStateException("Oops, we failed")
}
put(group, updated)
}
fun Map<String, Char>.toInsertionMap(): Map<String, Pair<String, String>> {
return mapValues { (group, character) ->
Pair(
"${group[0]}$character",
"$character${group[1]}"
)
}
}
fun countAllTheThings(
template: String,
times: Int,
characterMap: Map<String, Char>,
insertionMap: Map<String, Pair<String, String>>
): Map<Char, Long> {
val countCharacters = mutableMapOf<Char, Long>() // B -> 0
var groupCount = createGroupCount(template) // AB -> 0
repeat(times) {
val updatedGroupCount = mutableMapOf<String, Long>()
groupCount.forEach { (group, count) ->
val insertion = characterMap[group]
?: throw IllegalStateException("No character mapping for group: $group")
countCharacters.count(insertion, count)
val (first, second) = insertionMap[group]
?: throw IllegalStateException("No group mapping for group: $group")
updatedGroupCount.count(first, count)
updatedGroupCount.count(second, count)
}
groupCount = updatedGroupCount
}
template.toCharArray().forEach { character ->
countCharacters.count(character, 1)
}
return countCharacters
}
fun countQuantities(input: String): Map<Char, Int> {
return input.toCharArray().groupBy { it }
.mapValues { (_, list) -> list.size }
}
fun Map<Char, Int>.max(): Pair<Char, Int> {
return maxByOrNull { (_, count) -> count}!!.toPair()
}
fun Map<Char, Int>.min(): Pair<Char, Int> {
return minByOrNull { (_, count) -> count}!!.toPair()
}
fun Map<Char, Long>.maxLong(): Pair<Char, Long> {
return maxByOrNull { (_, count) -> count}!!.toPair()
}
fun Map<Char, Long>.minLong(): Pair<Char, Long> {
return minByOrNull { (_, count) -> count}!!.toPair()
}
fun readFromString(input: String): Pair<String, Map<String, String>> {
val lines = input.lines()
val template = lines[0]
val map = mutableMapOf<String, String>()
for (line in lines.drop(2)) {
val (from, to) = line.split(" -> ")
map[from] = to
}
return Pair(template, map)
}
fun part1() {
var (template, map) = readFile("day14.txt")
repeat(10) {
template = performInsertion(template, map)
}
val quantities = countQuantities(template)
val (minCharacter, minValue) = quantities.min()
val (maxCharacter, maxValue) = quantities.max()
println("Min: $minCharacter => $minValue")
println("Max: $maxCharacter => $maxValue")
val result = maxValue - minValue
println("Result: $result")
}
fun part2() {
val (template, map) = readFile("day14.txt")
val characterMap = map.toCharacterMap()
val insertionMap = characterMap.toInsertionMap()
val countMap = countAllTheThings(
template,
40,
characterMap,
insertionMap
)
val (maxChar, maxCount) = countMap.maxLong()
val (minChar, minCount) = countMap.minLong()
println("Max $maxChar = $maxCount")
println("Min $minChar = $minCount")
println("Result = ${maxCount - minCount}")
}
fun main() {
println(">> PART 1")
part1()
println(">> PART 2")
part2()
}
| [
{
"class_path": "pocmo__AdventOfCode2021__73bbb6a/day14/Day14Kt.class",
"javap": "Compiled from \"Day14.kt\"\npublic final class day14.Day14Kt {\n public static final kotlin.Pair<java.lang.String, java.util.Map<java.lang.String, java.lang.String>> readFile(java.lang.String);\n Code:\n 0: aload_0\n... |
pocmo__AdventOfCode2021__73bbb6a/src/day13/Day13.kt | package day13
import java.io.File
data class Point(
val x: Int,
val y: Int
)
data class Paper(
val points: Map<Point, Boolean>
) {
fun fold(instruction: Instruction): Paper {
return when (instruction) {
is Instruction.FoldUp -> foldUp(instruction.y)
is Instruction.FoldLeft -> foldLeft(instruction.x)
}
}
fun fold(instructions: List<Instruction>): Paper {
var paper = this
for (instruction in instructions) {
paper = paper.fold(instruction)
}
return paper
}
fun foldLeft(x: Int): Paper {
val newPoints = mutableMapOf<Point, Boolean>()
points.keys.forEach { point ->
if (point.x < x) {
newPoints[point] = true
} else if (point.x > x) {
val steps = point.x - x
val mirroredPoint = Point(
x - steps,
point.y
)
newPoints[mirroredPoint] = true
} else {
throw IllegalStateException("Point on fold line")
}
}
return Paper(newPoints)
}
fun foldUp(y: Int): Paper {
val newPoints = mutableMapOf<Point, Boolean>()
points.keys.forEach { point ->
if (point.y < y) {
newPoints[point] = true
} else if (point.y > y) {
val steps = point.y - y
val mirroredPoint = Point(
point.x,
y - steps
)
newPoints[mirroredPoint] = true
} else {
throw IllegalStateException("Point on fold line")
}
}
return Paper(newPoints)
}
fun countPoints(): Int {
return points.size
}
fun isMarked(x: Int, y: Int): Boolean {
return isMarked(Point(x, y))
}
fun isMarked(point: Point): Boolean {
return points[point] == true
}
fun dump(): String {
val size = size()
return buildString {
for (y in 0..size.y) {
for (x in 0..size.x) {
if (isMarked(x, y)) {
append('#')
} else {
append('.')
}
}
appendLine()
}
}.trim()
}
fun size(): Point {
var x = 0
var y = 0
points.keys.forEach { point ->
x = if (point.x > x) point.x else x
y = if (point.y > y) point.y else y
}
return Point(x, y)
}
}
sealed interface Instruction {
data class FoldUp(
val y: Int
) : Instruction
data class FoldLeft(
val x: Int
) : Instruction
}
fun readFromFile(fileName: String): Pair<Paper, List<Instruction>> {
return readFromString(File(fileName)
.readText())
}
fun parsePoint(line: String): Point {
val (x, y) = line.split(",")
return Point(x.toInt(), y.toInt())
}
fun parseInstruction(line: String): Instruction {
return when {
line.startsWith("fold along x=") -> Instruction.FoldLeft(line.split("=")[1].toInt())
line.startsWith("fold along y=") -> Instruction.FoldUp(line.split("=")[1].toInt())
else -> throw IllegalStateException("Unknown instruction: $line")
}
}
fun readFromString(input: String): Pair<Paper, List<Instruction>> {
var parsingPoints = true
val points = mutableMapOf<Point, Boolean>()
val instructions = mutableListOf<Instruction>()
input.lines().forEach { line ->
when {
line.isEmpty() -> parsingPoints = false
parsingPoints -> points[parsePoint(line)] = true
else -> instructions.add(parseInstruction(line))
}
}
return Pair(Paper(points), instructions)
}
fun part1() {
val (paper, instructions) = readFromFile("day13.txt")
val instruction = instructions[0]
val foldedPaper = paper.fold(instruction)
val points = foldedPaper.countPoints()
println("Points before fold: ${paper.countPoints()}")
println("Points after fold: $points")
}
fun part2() {
val (paper, instructions) = readFromFile("day13.txt")
val foldedPaper = paper.fold(instructions)
println(foldedPaper.dump())
}
fun main() {
part2()
}
| [
{
"class_path": "pocmo__AdventOfCode2021__73bbb6a/day13/Day13Kt.class",
"javap": "Compiled from \"Day13.kt\"\npublic final class day13.Day13Kt {\n public static final kotlin.Pair<day13.Paper, java.util.List<day13.Instruction>> readFromFile(java.lang.String);\n Code:\n 0: aload_0\n 1: ldc ... |
pocmo__AdventOfCode2021__73bbb6a/src/day7/Day7.kt | package day7
import java.io.File
import kotlin.math.absoluteValue
fun readCrabSubmarines(): List<Int> {
return File("day7.txt")
.readLines()[0]
.split(",")
.map { it.toInt() }
}
fun calculateFuelSimple(crabSubmarines: List<Int>, position: Int): Int {
return crabSubmarines.sumOf { current ->
(current - position).absoluteValue
}
}
fun calculateFuelComplex(crabSubmarines: List<Int>, position: Int): Int {
return crabSubmarines.sumOf { current ->
val steps = (current - position).absoluteValue
(steps * (steps + 1)) / 2
}
}
fun List<Int>.findCheapestPosition(
calculateFuel: (List<Int>, Int) -> Int
): Pair<Int, Int> {
val min = minOrNull() ?: throw IllegalStateException("No min")
val max = maxOrNull() ?: throw IllegalStateException("No max")
println("Range: $min - $max")
var cheapestPosition: Int? = null
var fuelNeeded: Int? = null
for (position in min..max) {
val fuel = calculateFuel(this, position)
if (fuelNeeded == null || fuel < fuelNeeded) {
cheapestPosition = position
fuelNeeded = fuel
}
}
return Pair(cheapestPosition!!, fuelNeeded!!)
}
fun part2() {
val crabSubmarines = readCrabSubmarines()
val (position, fuel) = crabSubmarines.findCheapestPosition { submarines, position ->
calculateFuelComplex(submarines, position)
}
println("Position: $position")
println("Fuel: $fuel")
}
fun part1() {
val crabSubmarines = readCrabSubmarines()
val (position, fuel) = crabSubmarines.findCheapestPosition { submarines, position ->
calculateFuelSimple(submarines, position)
}
println("Position: $position")
println("Fuel: $fuel")
}
fun main() {
part2()
} | [
{
"class_path": "pocmo__AdventOfCode2021__73bbb6a/day7/Day7Kt.class",
"javap": "Compiled from \"Day7.kt\"\npublic final class day7.Day7Kt {\n public static final java.util.List<java.lang.Integer> readCrabSubmarines();\n Code:\n 0: new #10 // class java/io/File\n 3: ... |
pocmo__AdventOfCode2021__73bbb6a/src/day9/Day9.kt | package day9
import java.io.File
fun readInput(filename: String = "day9.txt"): List<List<Int>>{
return File(filename)
.readLines()
.map { line -> line.toCharArray().map { character -> character.digitToInt() } }
}
fun List<List<Int>>.neighbours(x: Int, y: Int): List<Int> {
val top = get(x).getOrNull(y - 1)
val bottom = get(x).getOrNull(y + 1)
val left = getOrNull(x - 1)?.get(y)
val right = getOrNull(x + 1)?.get(y)
return listOfNotNull(top, left, right, bottom)
}
fun List<List<Int>>.isValid(x: Int, y: Int): Boolean {
return x in indices && y in get(0).indices
}
fun List<List<Int>>.neighbourPositions(x: Int, y: Int): List<Pair<Int, Int>> {
val top = Pair(x, y - 1)
val bottom = Pair(x, y + 1)
val left = Pair(x - 1, y)
val right = Pair(x + 1, y)
return listOf(top, bottom, left, right).filter { (x, y) -> isValid(x, y) }
}
fun part1() {
val input = readInput()
var riskLevel = 0
for (x in input.indices) {
for (y in input[0].indices) {
val current = input[x][y]
val neighbours = input.neighbours(x, y)
if (neighbours.all { value -> value > current }) {
riskLevel += current + 1
}
}
}
println("Risk level: $riskLevel")
}
fun List<List<Int>>.findLowPoints(): List<Pair<Int, Int>> {
val lowPoints = mutableListOf<Pair<Int, Int>>()
for (x in indices) {
for (y in get(0).indices) {
val current = get(x)[y]
val neighbours = neighbours(x, y)
if (neighbours.all { value -> value > current }) {
lowPoints.add(Pair(x, y))
}
}
}
return lowPoints
}
fun List<List<Int>>.findBasin(x: Int, y: Int): Set<Pair<Int, Int>> {
val visitedPoints = mutableSetOf<Pair<Int, Int>>()
val queue = mutableListOf(Pair(x, y))
while (queue.isNotEmpty()) {
val point = queue.removeFirst()
visitedPoints.add(point)
val neighbours = neighbourPositions(point.first, point.second)
neighbours.forEach { neighbour ->
if (!visitedPoints.contains(neighbour)) {
if (get(neighbour.first)[neighbour.second] != 9) {
queue.add(neighbour)
}
}
}
}
return visitedPoints
}
fun part2() {
val input = readInput("day9.txt")
val lowPoints = input.findLowPoints()
val basins = lowPoints.map { point ->
input.findBasin(point.first, point.second)
}.sortedByDescending { points ->
points.size
}
println("Basins: ${basins.size}")
var result = 1
basins.take(3).forEach { points ->
result *= points.size
}
println("Result: $result")
}
fun main() {
part2()
} | [
{
"class_path": "pocmo__AdventOfCode2021__73bbb6a/day9/Day9Kt.class",
"javap": "Compiled from \"Day9.kt\"\npublic final class day9.Day9Kt {\n public static final java.util.List<java.util.List<java.lang.Integer>> readInput(java.lang.String);\n Code:\n 0: aload_0\n 1: ldc #10 ... |
pocmo__AdventOfCode2021__73bbb6a/src/day8/Day8.kt | package day8
import java.io.File
fun find_one_chars(input: List<List<Char>>): List<Char> {
return input.find { it.size == 2 } ?: throw IllegalStateException("One not found")
}
fun find_four_chars(input: List<List<Char>>): List<Char> {
return input.find { it.size == 4 } ?: throw IllegalStateException("Four not found")
}
fun find_seven_chars(input: List<List<Char>>): List<Char> {
return input.find { it.size == 3 } ?: throw IllegalStateException("Seven not found")
}
fun find_eight_chars(input: List<List<Char>>): List<Char> {
return input.find { it.size == 7 } ?: throw IllegalStateException("Seven not found")
}
fun find_nine_chars(input: List<List<Char>>, four: List<Char>): List<Char> {
return input.filter { it.size == 6 }
.find { it.containsAll(four) }
?: throw IllegalStateException("Nine not found")
}
fun find_zero_chars(input: List<List<Char>>, one: List<Char>, nine: List<Char>): List<Char> {
return input
.filter { it.size == 6 }
.filter { it.containsAll(one) }
.firstOrNull() { it != nine } ?: throw IllegalStateException("Zero not found")
}
fun find_six_chars(input: List<List<Char>>, nine: List<Char>, zero: List<Char>): List<Char> {
return input
.filter { it.size == 6 }
.filter { it != nine }
.firstOrNull() { it != zero } ?: throw IllegalStateException("Six not found")
}
fun find_five_chars(input: List<List<Char>>, six: List<Char>): List<Char> {
return input
.filter { it.size == 5 }
.firstOrNull { six.containsAll(it) }?: throw IllegalStateException("Five not found")
}
fun find_three_chars(input: List<List<Char>>, seven: List<Char>): List<Char> {
return input
.filter { it.size == 5 }
.firstOrNull { it.containsAll(seven) } ?: throw IllegalStateException("Three not found")
}
fun find_two_chars(input: List<List<Char>>, threeChars: List<Char>, fiveChars: List<Char>): List<Char> {
return input
.filter { it.size == 5 }
.firstOrNull { it != threeChars && it != fiveChars } ?: throw IllegalStateException("Three not found")
}
fun findMappings(input: List<List<Char>>): Map<List<Char>, Char> {
val oneChars = find_one_chars(input).sorted()
val fourChars = find_four_chars(input).sorted()
val sevenChars = find_seven_chars(input).sorted()
val eightChars = find_eight_chars(input).sorted()
val nineChars = find_nine_chars(input, fourChars).sorted()
val zeroChars = find_zero_chars(input, oneChars, nineChars).sorted()
val sixChars = find_six_chars(input, nineChars, zeroChars).sorted()
val threeChars = find_three_chars(input, sevenChars).sorted()
val fiveChars = find_five_chars(input, sixChars).sorted()
val twoChars = find_two_chars(input, threeChars, fiveChars).sorted()
val map = mapOf(
zeroChars.sorted() to '0',
oneChars.sorted() to '1',
twoChars.sorted() to '2',
threeChars.sorted() to '3',
fourChars.sorted() to '4',
fiveChars.sorted() to '5',
sixChars.sorted() to '6',
sevenChars.sorted() to '7',
eightChars.sorted() to '8',
nineChars.sorted() to '9'
)
if (map.keys.size != 10) {
map.values.sorted().forEach {
println(it)
}
println("3 = " + map[threeChars])
throw IllegalStateException("Map size is not 10")
}
return map
}
fun translate(input: List<List<Char>>, value: List<List<Char>>): List<Char> {
val mappings = findMappings(input)
return value.map { segments ->
mappings[segments.sorted()] ?: '.'
}
}
/*
aa
b c
b c
dd
e f
e f
gg
[x] 0: 6 abcefg
[x] 1: 2 cf
[x] 2: 5 acdeg
[x] 3: 5 acdfg
[x] 4: 4 bcdf
[x] 5: 5 abdfg
[x] 6: 6 abdefg
[x] 7: 3 acf
[x] 8: 7 abcdefg
[x] 9: 6 abcdfg
[x] 1: 2 cf
[x] 7: 3 acf
[x] 4: 4 bcdf
[x] 2: 5 acdeg
[x] 3: 5 acdfg
[x] 5: 5 abdfg
[x] 6: 6 abdefg
[x] 9: 6 abcdfg
[x] 0: 6 abcefg
[x] 8: 7 abcdefg
0: 1: 2: 3: 4:
aaaa .... aaaa aaaa ....
b c . c . c . c b c
b c . c . c . c b c
.... .... dddd dddd dddd
e f . f e . . f . f
e f . f e . . f . f
gggg .... gggg gggg ....
5: 6: 7: 8: 9:
aaaa aaaa aaaa aaaa aaaa
b . b . . c b c b c
b . b . . c b c b c
dddd dddd .... dddd dddd
. f e f . f e f . f
. f e f . f e f . f
gggg gggg .... gggg gggg
*/
fun readInput(filename: String = "day8.txt"): List<Pair<List<List<Char>>, List<List<Char>>>> {
return File(filename)
.readLines()
.map { line ->
val (rawInput, rawValue) = line.split("|")
Pair(
rawInput.trim().split(" ").map { it.toCharArray().toList().sorted() },
rawValue.trim().split(" ").map { it.toCharArray().toList().sorted() },
)
}
}
fun part1() {
val inputs = readInput()
val sum = inputs.map { (input, value) ->
translate(input, value)
}.sumOf {
it.count { character -> character in listOf('1', '4', '7', '8') }
}
println("Digits: $sum")
}
fun part2() {
val inputs = readInput()
val sum = inputs.map { (input, value) ->
translate(input, value)
}.map {
it.joinToString("").toInt()
}.sum()
print(sum)
}
fun part2_debug() {
val inputs = readInput("day8_debug.txt")
inputs.map { (input, value) ->
translate(input, value)
}.forEach { translation ->
println(translation.joinToString(""))
}
}
fun main() {
part2()
} | [
{
"class_path": "pocmo__AdventOfCode2021__73bbb6a/day8/Day8Kt.class",
"javap": "Compiled from \"Day8.kt\"\npublic final class day8.Day8Kt {\n public static final java.util.List<java.lang.Character> find_one_chars(java.util.List<? extends java.util.List<java.lang.Character>>);\n Code:\n 0: aload_0\... |
pocmo__AdventOfCode2021__73bbb6a/src/day11/Day11.kt | package day11
import java.io.File
data class Position(
val x: Int,
val y: Int
)
data class Octopus(
var energy: Int,
var flashed: Boolean = false
) {
fun canFlash(): Boolean = energy > 9 && !flashed
fun flash() {
energy = 0
flashed = true
}
fun reset() {
if (flashed) {
flashed = false
energy = 0
}
}
}
fun List<List<Octopus>>.dump(): String {
val octopuses = this
return buildString {
octopuses.forEach { row ->
row.forEach { octopus ->
append(octopus.energy)
}
appendLine()
}
}.trim()
}
fun List<List<Octopus>>.increase() {
forEach { row ->
row.forEach { octopus ->
octopus.energy++
}
}
}
fun List<List<Octopus>>.increase(neighbors: List<Position>) {
neighbors.forEach { neighbor ->
get(neighbor.y)[neighbor.x].energy++
}
}
fun List<List<Octopus>>.neighborsOf(x: Int, y: Int): List<Position> {
val candidates = listOf(
Position(x - 1, y - 1),
Position(x, y - 1),
Position(x + 1, y - 1),
Position(x - 1, y),
Position(x + 1, y),
Position(x - 1, y + 1),
Position(x, y + 1),
Position(x + 1, y + 1),
)
return candidates.filter { candidate ->
candidate.y in indices &&
candidate.x in get(0).indices
}
}
fun List<List<Octopus>>.flash(): Pair<Int, List<Position>> {
val neighbors = mutableListOf<Position>()
var flashes = 0
indices.forEach { y ->
get(y).indices.forEach { x ->
val octopus = get(y)[x]
if (octopus.canFlash()) {
octopus.flash()
flashes++
neighbors.addAll(neighborsOf(x, y))
}
}
}
return Pair(flashes, neighbors)
}
fun List<List<Octopus>>.simulate(): Int {
increase()
var (flashes, neighbors) = flash()
while (neighbors.isNotEmpty()) {
increase(neighbors)
val (additionalFlashes, newNeighbors) = flash()
neighbors = newNeighbors
flashes += additionalFlashes
}
reset()
return flashes
}
fun List<List<Octopus>>.simulate(times: Int): Int {
var flashes = 0
repeat(times) {
flashes += simulate()
}
return flashes
}
fun List<List<Octopus>>.reset() {
forEach { row ->
row.forEach { octopus ->
octopus.reset()
}
}
}
fun List<List<Octopus>>.allFlashed(): Boolean {
return all { row ->
row.all { octopus -> octopus.energy == 0 }
}
}
fun List<List<Octopus>>.simulateUntilAllFlashed(): Int {
var step = 0
while (!allFlashed()) {
simulate()
step++
}
return step
}
fun readOctopuses(fileName: String): List<List<Octopus>> {
return readOctopusesFromString(File(fileName)
.readText())
}
fun readOctopusesFromString(input: String): List<List<Octopus>> {
return input
.lines()
.map { line ->
line.toCharArray().map { value -> Octopus(value.digitToInt()) }
}
}
fun part1() {
val octopuses = readOctopuses("day11.txt")
val flashes = octopuses.simulate(100)
println("Flashes = $flashes")
}
fun part2() {
val octopuses = readOctopuses("day11.txt")
val steps = octopuses.simulateUntilAllFlashed()
println("Steps = $steps")
}
fun main() {
part2()
}
| [
{
"class_path": "pocmo__AdventOfCode2021__73bbb6a/day11/Day11Kt.class",
"javap": "Compiled from \"Day11.kt\"\npublic final class day11.Day11Kt {\n public static final java.lang.String dump(java.util.List<? extends java.util.List<day11.Octopus>>);\n Code:\n 0: aload_0\n 1: ldc #10 ... |
pocmo__AdventOfCode2021__73bbb6a/src/day17/Day17.kt | package day17
import kotlin.math.max
data class TargetArea(
val xRange: IntRange,
val yRange: IntRange
) {
fun calculateResult(x: Int, y: Int): AreaResult {
return when {
y < yRange.minOrNull()!! -> AreaResult.MissBottom
x > xRange.maxOrNull()!! -> AreaResult.MissRight
xRange.contains(x) && yRange.contains(y) -> AreaResult.Hit
else -> AreaResult.Ongoing
}
}
}
data class Velocity(
val x: Int,
val y: Int
) {
fun simulate(): Velocity {
val newX = if (x > 0) {
x - 1
} else if (x < 0) {
x + 1
} else {
0
}
val newY = y - 1
return Velocity(newX, newY)
}
}
sealed interface AreaResult {
object Hit : AreaResult
object Ongoing : AreaResult
object MissBottom : AreaResult
object MissRight : AreaResult
}
sealed interface Result {
data class Hit(
val maxHeight: Int
) : Result
object MissBottom : Result
object MissRight : Result
}
fun AreaResult.toResult(
maxHeight: Int
): Result {
return when (this) {
is AreaResult.Ongoing -> throw IllegalStateException("Translating ongoing area result")
is AreaResult.Hit -> Result.Hit(maxHeight)
is AreaResult.MissBottom -> Result.MissBottom
is AreaResult.MissRight -> Result.MissRight
}
}
fun launchProbe(initial: Velocity, target: TargetArea): Result {
var x = initial.x
var y = initial.y
var velocity = initial
var maxHeight = initial.y
var areaResult: AreaResult = target.calculateResult(x, y)
while (areaResult is AreaResult.Ongoing) {
velocity = velocity.simulate()
x += velocity.x
y += velocity.y
areaResult = target.calculateResult(x, y)
maxHeight = max(maxHeight, y)
}
return areaResult.toResult(maxHeight)
}
data class VelocityResults(
val maxHeight: Int,
val count: Int
)
fun findAllProbeVelocities(
target: TargetArea,
maxPossibleHeight: Int = 20
): VelocityResults {
val xRange = 1..target.xRange.last // Too large (on the left side)
val yRange = target.yRange.first .. maxPossibleHeight
var count = 0
var maxHeight = Int.MIN_VALUE
for (x in xRange) {
for (y in yRange) {
val result = launchProbe(
Velocity(x, y),
target
)
if (result is Result.Hit) {
maxHeight = max(maxHeight, result.maxHeight)
count++
}
}
}
if (maxHeight == Int.MIN_VALUE) {
throw IllegalStateException("Could not find max height")
}
return VelocityResults(maxHeight, count)
}
fun part1() {
val target = TargetArea(
xRange = 153..199,
yRange = -114..-75
)
val result = findAllProbeVelocities(
target,
maxPossibleHeight = 1500
)
println("Result: $result")
}
fun part2() {
val target = TargetArea(
xRange = 153..199,
yRange = -114..-75
)
val result = findAllProbeVelocities(
target,
maxPossibleHeight = 1000
)
println("Result: $result")
}
fun main() {
part2()
}
| [
{
"class_path": "pocmo__AdventOfCode2021__73bbb6a/day17/Day17Kt.class",
"javap": "Compiled from \"Day17.kt\"\npublic final class day17.Day17Kt {\n public static final day17.Result toResult(day17.AreaResult, int);\n Code:\n 0: aload_0\n 1: ldc #9 // String <this>\n ... |
achawki__number-sequence-trainer-android__fa47830/app/src/main/java/com/achawki/sequencetrainer/math/Operator.kt | package com.achawki.sequencetrainer.math
import kotlin.math.min
import kotlin.random.Random
interface Operator<T> {
fun apply(t: T): Int
}
enum class BinaryOperator : Operator<Pair<Int, Int>> {
PLUS {
override fun apply(t: Pair<Int, Int>): Int {
return t.first + t.second
}
},
MINUS {
override fun apply(t: Pair<Int, Int>): Int {
return t.first - t.second
}
},
TIMES {
override fun apply(t: Pair<Int, Int>): Int {
return t.first * t.second
}
},
REMAINDER {
override fun apply(t: Pair<Int, Int>): Int {
return t.first % t.second
}
}
}
enum class UnaryOperator : Operator<Int> {
SQUARE {
override fun apply(t: Int): Int {
return t * t
}
},
DIGIT_SUM {
override fun apply(t: Int): Int {
if (t == 0) return 0
val sign = if (t < 0) -1 else 1
var digitSum = 0
var n = t * sign
while (n > 0) {
digitSum += n % 10
n /= 10
}
return digitSum * sign
}
}
}
enum class ListOperator : Operator<List<Int>> {
SUM {
override fun apply(t: List<Int>): Int {
return t.sum()
}
}
}
class WeightedOperator<T>(val operator: Operator<T>, val weight: Int)
fun getRandomOperatorsFromWeightedOperators(
availableOperators: List<WeightedOperator<*>>,
operatorsToSelect: Int
): List<Operator<*>> {
val operators = mutableListOf<Operator<*>>()
val overallWeight = availableOperators.sumOf { it.weight }
val filteredOperators = availableOperators.filter { weightedOperator -> weightedOperator.weight > 0 }
while (operators.size < min(operatorsToSelect, filteredOperators.size)) {
var currentWeight = 0
val targetWeight = Random.nextDouble() * overallWeight
for (operator in filteredOperators) {
currentWeight += operator.weight
if (currentWeight >= targetWeight) {
if (!operators.contains(operator.operator)) {
operators.add(operator.operator)
}
break
}
}
}
return operators
}
| [
{
"class_path": "achawki__number-sequence-trainer-android__fa47830/com/achawki/sequencetrainer/math/OperatorKt.class",
"javap": "Compiled from \"Operator.kt\"\npublic final class com.achawki.sequencetrainer.math.OperatorKt {\n public static final java.util.List<com.achawki.sequencetrainer.math.Operator<?>>... |
kogupta__misc-projects__aabace3/kotlin-java/src/main/kotlin/func/prog/java/recursion/ListExtn.kt | package func.prog.java.recursion
fun main(args: Array<String>) {
println("abc".toList().head())
println(List(1) { 'a' }.mkString())
println(('a'..'z').asSequence().toList().mkString())
println("-- fold left --")
println("Sum of [1..10] : " + sum2((1..10).toList()))
println(List(1) { 'a' }.mkString2())
println(('a'..'z').asSequence().toList().mkString2())
println("-- that's all folds! --")
}
fun <T> List<T>.head(): T {
require(isNotEmpty()) { "`head` of an empty list" }
return first()
}
fun <T> List<T>.tail(): List<T> {
require(isNotEmpty()) { "`tail` of an empty list" }
return drop(1)
}
fun sum(xs: List<Int>): Int =
if (xs.isEmpty()) 0
else xs.head() + sum(xs.tail())
fun sum2(xs: List<Int>): Int = xs.foldLeft(0) { a, b -> a + b }
fun sumCoRec(xs: List<Int>): Int {
tailrec fun helper(ns: List<Int>, acc: Int): Int =
if (ns.isEmpty()) acc
else helper(ns.tail(), ns.head() + acc)
return helper(xs, 0)
}
fun <T> List<T>.mkString(
prefix: String = "[",
delim: String = ",",
suffix: String = "]"): String {
tailrec fun helper(xs: List<T>, acc: String): String =
when {
xs.isEmpty() -> acc
xs.tail().isEmpty() -> acc + xs.head()
else -> helper(xs.tail(), acc + xs.head() + delim)
}
return prefix + helper(this, "") + suffix
}
fun <T> List<T>.mkString2(
prefix: String = "[",
delim: String = ",",
suffix: String = "]"): String {
val s = foldLeft("") { acc, elem ->
if (acc.isEmpty()) elem.toString()
else acc + delim + elem.toString()
}
return prefix + s + suffix
}
/**
* z -> zero value aka seed
*/
fun <T, U> List<T>.foldLeft(z: U, f: (U, T) -> U): U {
tailrec fun helper(xs: List<T>, acc: U): U = when {
xs.isEmpty() -> acc
else -> helper(xs.tail(), f(acc, xs.head()))
}
return helper(this, z)
}
fun <T, U> List<T>.foldRight(z: U, f: (T, U) -> U): U =
reversed().foldLeft(z) { u, t -> f(t, u) }
| [
{
"class_path": "kogupta__misc-projects__aabace3/func/prog/java/recursion/ListExtnKt.class",
"javap": "Compiled from \"ListExtn.kt\"\npublic final class func.prog.java.recursion.ListExtnKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc #9 ... |
SERG-Delft__hyperion__a010d1b/plugin/src/main/kotlin/nl/tudelft/hyperion/plugin/metric/APIMetric.kt | package nl.tudelft.hyperion.plugin.metric
/**
* Represents an element as the result of an /api/v1/metrics API call.
* Contains the aggregated log counts over the specified interval, i.e.
* an interval of 60 represents the logs that happened in the last minute.
*/
data class APIMetricsResult(
val interval: Int,
/**
* A mapping of version to a List of Metrics (all metrics relative to this version).
* The version is represented by a String.
*/
val versions: Map<String, List<APIMetric>>
)
/**
* Represents the response from an /api/v1/metrics/period API call.
*
* @param T signifies if this is project wide or file specific bin metrics.
* @property interval the time in seconds between each [APIBinMetricsResult].
* @property results a list of metrics for each interval which contains a map
* of versions and corresponding line metrics.
*/
data class APIBinMetricsResponse<T : BaseAPIMetric>(
val interval: Int,
val results: List<APIBinMetricsResult<T>>
) {
fun filterVersion(version: String, lineNumber: Int) =
results.map { it.filterVersion(version, lineNumber) }
}
/**
* Represents an element as the result of an /api/v1/metrics/period API call.
* The API call returns a list of bins where each bin is the aggregated log
* counts starting from the given start time.
*
* @param T signifies if this is project wide or file specific bin metrics.
* @property startTime unix epoch time in seconds of the starting time of this
* bin.
* @property versions map of version identifier with metrics.
*/
data class APIBinMetricsResult<T : BaseAPIMetric>(
val startTime: Int,
val versions: MutableMap<String, List<T>>
) {
fun filterVersion(version: String, lineNumber: Int) {
if (version in versions) {
versions[version] = versions[version]?.filter { it.line == lineNumber }!!
}
}
}
/**
* The base class for all metrics.
*
* @property line the log line for which this metrics was triggered.
* @property severity the log severity of this log line.
* @property count the number of times this line has been triggered.
*/
sealed class BaseAPIMetric(
open val line: Int,
open val severity: String,
open val count: Int
)
/**
* Represents a single grouped metric of a (project, file, line, version,
* severity) tuple. Contains the line for which it was triggered, the
* severity of the log and the amount of times that specific log was
* triggered.
*/
data class APIMetric(
override val line: Int,
override val severity: String,
override val count: Int
) : BaseAPIMetric(line, severity, count)
/**
* Represents a single grouped metric of a (project, file, line, version,
* severity) tuple. Contains the line for which it was triggered, the
* severity of the log and the amount of times that specific log was
* triggered.
*/
data class FileAPIMetric(
override val line: Int,
override val severity: String,
override val count: Int,
val file: String
) : BaseAPIMetric(line, severity, count)
| [
{
"class_path": "SERG-Delft__hyperion__a010d1b/nl/tudelft/hyperion/plugin/metric/APIMetric.class",
"javap": "Compiled from \"APIMetric.kt\"\npublic final class nl.tudelft.hyperion.plugin.metric.APIMetric extends nl.tudelft.hyperion.plugin.metric.BaseAPIMetric {\n private final int line;\n\n private final ... |
SeanShubin__condorcet-backend__c6dd3e8/domain/src/main/kotlin/com/seanshubin/condorcet/backend/domain/Ranking.kt | package com.seanshubin.condorcet.backend.domain
import kotlin.math.max
import kotlin.random.Random
data class Ranking(val candidateName: String, val rank: Int?) {
companion object {
fun List<Ranking>.prefers(a: String, b: String): Boolean =
rankingFor(a) < rankingFor(b)
private fun List<Ranking>.rankingFor(candiateName: String): Int =
find { ranking -> ranking.candidateName == candiateName }?.rank ?: Int.MAX_VALUE
fun List<Ranking>.listToString() =
joinToString(" ") { (candidateName, rank) -> "$rank $candidateName" }
fun List<Ranking>.voterBiasedOrdering(random: Random): List<Ranking> {
val rankAscending = Comparator<Ranking> { o1, o2 ->
val rank1 = o1?.rank ?: Int.MAX_VALUE
val rank2 = o2?.rank ?: Int.MAX_VALUE
rank1.compareTo(rank2)
}
val grouped = groupBy { it.rank }
val groupedValues = grouped.values
val shuffled = groupedValues.flatMap { it.shuffled(random) }
val sorted = shuffled.sortedWith(rankAscending)
return sorted
}
fun List<Ranking>.addMissingCandidates(allCandidates: List<String>): List<Ranking> {
val existingCandidates = this.map { it.candidateName }
val isMissing = { candidate: String -> !existingCandidates.contains(candidate) }
val missingCandidates = allCandidates.filter(isMissing)
val newRankings = missingCandidates.map { Ranking(it, null) }
return this + newRankings
}
fun List<Ranking>.normalizeRankingsReplaceNulls(): List<Ranking> {
val distinctOrderedRanks = this.mapNotNull { it.rank }.distinct().sorted()
val normalized = (1..distinctOrderedRanks.size)
val newRankMap = distinctOrderedRanks.zip(normalized).toMap()
val lastRank = distinctOrderedRanks.size + 1
val result = map { (name, rank) ->
val newRank = newRankMap[rank] ?: lastRank
Ranking(name, newRank)
}
return result
}
fun List<Ranking>.normalizeRankingsKeepNulls(): List<Ranking> {
val distinctOrderedRanks = this.mapNotNull { it.rank }.distinct().sorted()
val normalized = (1..distinctOrderedRanks.size)
val newRankMap = distinctOrderedRanks.zip(normalized).toMap()
val result = map { (name, rank) ->
val newRank = newRankMap[rank]
Ranking(name, newRank)
}
return result
}
fun List<Ranking>.effectiveRankings(candidateNames: List<String>): List<Ranking> =
addMissingCandidates(candidateNames).normalizeRankingsReplaceNulls()
fun List<Ranking>.matchOrderToCandidates(candidateNames: List<String>): List<Ranking> {
val byCandidate = this.associateBy { it.candidateName }
return candidateNames.map { byCandidate.getValue(it) }
}
object RankingListComparator : Comparator<List<Ranking>> {
override fun compare(firstRankingList: List<Ranking>, secondRankingList: List<Ranking>): Int {
val firstRankList = firstRankingList.mapNotNull { it.rank }
val secondRankList = secondRankingList.mapNotNull { it.rank }
return RankListComparator.compare(firstRankList, secondRankList)
}
}
object RankListComparator : Comparator<List<Int>> {
override fun compare(firstList: List<Int>, secondList: List<Int>): Int {
val maxSize = max(firstList.size, secondList.size)
var compareResult = 0
var index = 0
while (index < maxSize) {
val firstValue = firstList[index]
val secondValue = secondList[index]
compareResult = RankComparator.compare(firstValue, secondValue)
if (compareResult != 0) break
index++
}
return compareResult
}
}
object RankComparator : Comparator<Int> {
override fun compare(first: Int, second: Int): Int = first.compareTo(second)
}
}
}
| [
{
"class_path": "SeanShubin__condorcet-backend__c6dd3e8/com/seanshubin/condorcet/backend/domain/Ranking$Companion.class",
"javap": "Compiled from \"Ranking.kt\"\npublic final class com.seanshubin.condorcet.backend.domain.Ranking$Companion {\n private com.seanshubin.condorcet.backend.domain.Ranking$Companio... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.