kt_path stringlengths 35 167 | kt_source stringlengths 626 28.9k | classes listlengths 1 17 |
|---|---|---|
AnushaSankara__icfp-2019__93fb25e/kotlin/src/main/kotlin/icfp2019/app.kt | package icfp2019
import java.io.File
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
fun main() {
val workingDir: Path = Paths.get("")
val solutions = mutableListOf<Solution>()
readZipFile(File("problems.zip"))
.filter { it.file.isFile }
.forEach {
val problem = parseDesc(it)
val solution = solve(problem)
encodeSolution(solution, workingDir)
}
writeZip(workingDir, solutions)
}
fun writeZip(workingDir: Path, solutions: MutableList<Solution>) {
TODO("not implemented")
}
fun readZipFile(file: File): List<ProblemDescription> {
TODO("not implemented")
}
enum class Boosters {
B, F, L, X
}
data class Point(val x: Int, val y: Int)
data class Node(val point: Point, val isObstacle: Boolean, val booster: Boosters)
data class ProblemId(val id: Int)
data class ProblemDescription(val problemId: ProblemId, val file: File)
data class Problem(val problemId: ProblemId, val startingPosition: Point, val map: Array<Array<Node>>)
/*
Task:
1. Open Zip file
2. parse a problem at a time: prob_NNN.desc
3. solve problem
4. encode solution
5. output to file prob_NNN.sol (use checker to validate?) https://icfpcontest2019.github.io/solution_checker/
6. add solution to another zip (script/program)
*/
fun parseDesc(file: ProblemDescription): Problem {
// Read lines
/*
1. Read lines
2. Parse map
Grammar:
x,y: Nat
point ::= (x,y)
map ::= repSep(point,”,”)
BoosterCode ::= B|F|L|X
boosterLocation ::= BoosterCode point
obstacles ::= repSep(map,”; ”)
boosters ::= repSep(boosterLocation,”; ”)
task ::= map # point # obstacles # boosters
*/
return Problem(ProblemId(0), Point(0, 0), arrayOf())
}
/*
A solution for a task
prob-NNN.desc
is a sequence of actions encoded as a single-line text file named
prob-NNN.sol
for the corresponding numberNNN.
The actions are encoded as follows:
action ::=
W(move up)
| S(move down)
| A(move left)
| D(move right)
| Z(do nothing)
| E(turn manipulators 90°clockwise)
| Q(turn manipulators 90°counterclockwise)
| B(dx,dy)(attach a new manipulator with relative coordinates(dx,dy))
| F(attach fast wheels)
| L(start using a drill)
solution ::= rep(action)
A solution isvalid, if it does not force the worker-wrapper to go through the walls and obstacles
(unless it uses a drill), respects the rules of using boosters, and, upon finishing,
leaves all reachablesquares of the map wrapped.
*/
enum class Actions {
W, S, A, D, Z, E, Q, B, F, L
}
data class Solution(val problemId: ProblemId, val actions: List<Actions>)
fun solve(problem: Problem): Solution {
return Solution(problem.problemId, listOf())
}
fun encodeSolution(solution: Solution, directory: Path): File {
val file = Files.createFile(directory.resolve("prob-${solution.problemId.id}.sol"))
// TODO
return file.toFile()
}
| [
{
"class_path": "AnushaSankara__icfp-2019__93fb25e/icfp2019/AppKt.class",
"javap": "Compiled from \"app.kt\"\npublic final class icfp2019.AppKt {\n public static final void main();\n Code:\n 0: ldc #8 // String\n 2: iconst_0\n 3: anewarray #10 ... |
toukovk__24-solver__2c87897/src/main/kotlin/solver/model.kt | package solver
import java.lang.RuntimeException
import kotlin.math.abs
interface ExpressionItem
enum class Operator : ExpressionItem {
ADD { override fun apply(a1: Double, a2: Double) = a1 + a2 },
MINUS { override fun apply(a1: Double, a2: Double) = a1 - a2 },
TIMES { override fun apply(a1: Double, a2: Double) = a1 * a2 },
DIVIDE { override fun apply(a1: Double, a2: Double) = a1 / a2 };
abstract fun apply(a1: Double, a2: Double): Double
}
data class Scalar(
val value: Double
): ExpressionItem
fun evalPrefixExpression(expression: List<ExpressionItem>): Double {
var index = 0
fun evalNext(): Double {
return when (val current = expression[index++]) {
is Scalar -> current.value
is Operator -> current.apply(evalNext(), evalNext())
else -> throw RuntimeException("Unexpected type: $current")
}
}
return evalNext()
}
fun solve(values: List<Double>, target: Double): List<ExpressionItem>? {
fun recur(expressionSoFar: List<ExpressionItem>, remainingComponents: List<Double>): List<ExpressionItem>? {
if (remainingComponents.isEmpty()) {
return if (abs(evalPrefixExpression(expressionSoFar) - target) < 0.001) {
expressionSoFar
} else {
null
}
}
val numbersSoFar = expressionSoFar.filterIsInstance<Scalar>().count()
val operatorsSoFar = expressionSoFar.filterIsInstance<Operator>().count()
// Try out all operators if operator can be added
if (operatorsSoFar < values.size - 1) {
for (op in Operator.values()) {
val result = recur(expressionSoFar + op, remainingComponents)
if (result != null) {
return result
}
}
}
// Try out all operators if number can be added
if (numbersSoFar < operatorsSoFar || (numbersSoFar == operatorsSoFar && remainingComponents.size == 1)) {
for (number in remainingComponents) {
val result = recur(
expressionSoFar + Scalar(number),
remainingComponents - number
)
if (result != null) {
return result
}
}
}
return null
}
return recur(listOf(), values)
}
| [
{
"class_path": "toukovk__24-solver__2c87897/solver/ModelKt.class",
"javap": "Compiled from \"model.kt\"\npublic final class solver.ModelKt {\n public static final double evalPrefixExpression(java.util.List<? extends solver.ExpressionItem>);\n Code:\n 0: aload_0\n 1: ldc #10 ... |
hairyOwl__AndroidStudy__278c8d7/Kotlin/code/FirstAPP/app/src/main/java/com/example/firstapp/lesson/Caculator.kt | package com.example.firstapp.lesson
import java.lang.Exception
/**
*@author: hairly owl
*@time:2021/10/13 21:22
*@version: 1.00
*@description: 一次四则运算计算机器
*/
fun main() {
while(true){
println("==========请输入你的表达式==========")
//接受控制台输入数据
val input:String? = readLine() //判空的校验
try {
input?.let {
val res = calculate(it)
println("${input} = ${res}")
println("是否继续使用(y/n)")
val cmd = readLine()
cmd?.let{
if(it.equals("n")){
System.exit(-1) //强制退出程序
}else{
//继续使用
}
}
}
}catch (ex:Exception){
ex.printStackTrace() //打印异常
}
}
}
//四则运算函数
fun calculate(input: String): String {
if(input.contains("+")){ //加法
//数据处理
val nums = input.trim().split("+") //去掉空格 分割操作符左右
return operate(nums[0].toDouble(),nums[1].toDouble(),"+").toString()
}else if (input.contains("-")){ //减法
val nums = input.trim().split("-")
return operate(nums[0].toDouble(),nums[1].toDouble(),"-").toString()
}else if (input.contains("*")){ //减法
val nums = input.trim().split("*")
return operate(nums[0].toDouble(),nums[1].toDouble(),"*").toString()
}else if (input.contains("/")){ //减法
val nums = input.trim().split("/")
return operate(nums[0].toDouble(),nums[1].toDouble(),"/").toString()
}else{
return "error: 您输入的表达式有误"
}
}
//计算函数
fun operate(num1: Double, num2: Double, operator: String): Double {
return when(operator){ //kotlin中的when代替 java中的switch-case
"+" -> num1 + num2
"-" -> num1 - num2
"*" -> num1 * num2
"/" -> num1 / num2
else -> 0.0
}
}
| [
{
"class_path": "hairyOwl__AndroidStudy__278c8d7/com/example/firstapp/lesson/CaculatorKt.class",
"javap": "Compiled from \"Caculator.kt\"\npublic final class com.example.firstapp.lesson.CaculatorKt {\n public static final void main();\n Code:\n 0: nop\n 1: ldc #10 /... |
pope__advent-of-code-2023-kotlin__cb2862a/day01/src/main/kotlin/com/shifteleven/adventofcode2023/day01/App.kt | package com.shifteleven.adventofcode2023.day01
import kotlin.math.min
fun main() {
part1()
part2()
}
fun part1() {
val lines = object {}.javaClass.getResourceAsStream("/input.txt")!!.bufferedReader().readLines()
val sum =
lines
.stream()
.mapToInt({ line ->
var tens: Int? = null
var ones = 0
for (c in line) {
when (c) {
in CharRange('0', '9') -> {
ones = c.code - 0x30
tens = tens ?: ones * 10
}
}
}
tens!! + ones
})
.sum()
println("Part 1: " + sum)
}
fun part2() {
val lines = object {}.javaClass.getResourceAsStream("/input.txt")!!.bufferedReader().readLines()
val sum =
lines
.stream()
.mapToInt({ line ->
var tens: Int? = null
var ones = 0
for ((i, c) in line.withIndex()) {
var num: Int? = null
when (c) {
in CharRange('0', '9') -> {
num = c.code - 0x30
}
'o' -> {
if (matchesWord(line, i, "one")) {
num = 1
}
}
't' -> {
if (matchesWord(line, i, "two")) {
num = 2
} else if (matchesWord(line, i, "three")) {
num = 3
}
}
'f' -> {
if (matchesWord(line, i, "four")) {
num = 4
} else if (matchesWord(line, i, "five")) {
num = 5
}
}
's' -> {
if (matchesWord(line, i, "six")) {
num = 6
} else if (matchesWord(line, i, "seven")) {
num = 7
}
}
'e' -> {
if (matchesWord(line, i, "eight")) {
num = 8
}
}
'n' -> {
if (matchesWord(line, i, "nine")) {
num = 9
}
}
}
if (num != null) {
ones = num
tens = tens ?: num * 10
}
}
tens!! + ones
})
.sum()
println("Part 2: " + sum)
}
fun matchesWord(
line: String,
idx: Int,
word: String,
): Boolean {
return line.subSequence(idx, min(idx + word.length, line.length)) == word
}
| [
{
"class_path": "pope__advent-of-code-2023-kotlin__cb2862a/com/shifteleven/adventofcode2023/day01/AppKt.class",
"javap": "Compiled from \"App.kt\"\npublic final class com.shifteleven.adventofcode2023.day01.AppKt {\n public static final void main();\n Code:\n 0: invokestatic #9 //... |
pope__advent-of-code-2023-kotlin__cb2862a/day02/src/main/kotlin/com/shifteleven/adventofcode2023/day02/App.kt | package com.shifteleven.adventofcode2023.day02
import java.io.StreamTokenizer
import java.io.StringReader
import kotlin.assert
import kotlin.math.max
data class Game(val id: Int, val views: List<IntArray>)
fun main() {
val lines = object {}.javaClass.getResourceAsStream("/input.txt")!!.bufferedReader().readLines()
val games = lines.map { processLine(it) }
part1(games)
part2(games)
}
fun part1(games: List<Game>) {
val sum =
games
.filter { game -> game.views.all { it[0] <= 12 && it[1] <= 13 && it[2] <= 14 } }
.map { it.id }
.sum()
println("Part 1: " + sum)
}
fun part2(games: List<Game>) {
val sum =
games
.map { game ->
var r = 1
var g = 1
var b = 1
for (dice in game.views) {
r = max(dice[0], r)
g = max(dice[1], g)
b = max(dice[2], b)
}
r * g * b
}
.sum()
println("Part 2: " + sum)
}
fun processLine(line: String): Game {
val r = StringReader(line)
val t = StreamTokenizer(r)
t.nextToken()
assert(t.sval == "Game")
t.nextToken()
assert(t.ttype == StreamTokenizer.TT_NUMBER)
val gameId = t.nval.toInt()
val cur = t.nextToken() // :
assert(cur.toChar() == ':')
val views = mutableListOf<IntArray>()
do {
val dice = IntArray(3)
do {
t.nextToken()
assert(t.ttype == StreamTokenizer.TT_NUMBER)
val curColor = t.nval.toInt()
t.nextToken()
assert(t.ttype == StreamTokenizer.TT_WORD)
when (t.sval) {
"red" -> dice[0] = curColor
"green" -> dice[1] = curColor
"blue" -> dice[2] = curColor
else -> assert(false)
}
} while (isRgbGroupActive(t))
views.add(dice)
} while (isGameContinued(t))
assert(t.nextToken() == StreamTokenizer.TT_EOF)
return Game(gameId, views)
}
fun isRgbGroupActive(t: StreamTokenizer): Boolean {
val tok = t.nextToken()
if (tok.toChar() == ',') {
return true
}
t.pushBack()
return false
}
fun isGameContinued(t: StreamTokenizer): Boolean {
val tok = t.nextToken()
if (tok.toChar() == ';') {
return true
}
t.pushBack()
return false
}
| [
{
"class_path": "pope__advent-of-code-2023-kotlin__cb2862a/com/shifteleven/adventofcode2023/day02/AppKt.class",
"javap": "Compiled from \"App.kt\"\npublic final class com.shifteleven.adventofcode2023.day02.AppKt {\n public static final void main();\n Code:\n 0: new #8 //... |
tpoujol__aoc-2021__6d474b3/src/main/kotlin/puzzle13/OrigamiSolver.kt | package puzzle13
import kotlin.system.measureTimeMillis
fun main() {
val origamiSolver = OrigamiSolver()
val time = measureTimeMillis {
println("number of dots after one fold: ${origamiSolver.countDotsAfterFirstFold()}")
println("Final Layout is:\n${origamiSolver.foldLayoutEntirely()}")
}
println("time: $time")
}
fun List<List<Boolean>>.printLayout(
fold: FoldInstruction? = null
): String = buildString {
for ((i, line) in this@printLayout.withIndex()) {
for ((j, b) in line.withIndex()) {
if (b) {
append("#")
} else if (fold is VerticalFoldInstruction && j == fold.x) {
append("|")
} else if (fold is HorizontalFoldInstruction && i == fold.y) {
append("—")
} else {
append(" ")
}
}
appendLine()
}
}
data class Position(val x: Int, val y: Int)
sealed interface FoldInstruction {
fun performFold(layout: List<List<Boolean>>): List<List<Boolean>>
}
data class VerticalFoldInstruction(val x: Int): FoldInstruction {
override fun performFold(layout: List<List<Boolean>>): List<List<Boolean>> {
val newLayout = MutableList(layout.size) { MutableList(x) { false } }
for (j in 0 until x) {
val verticallySymmetricColumn = layout[0].size - j - 1
for (i in layout.indices) {
newLayout[i][j] = layout[i][j] || layout[i][verticallySymmetricColumn]
}
}
return newLayout
.map { it.toList() }
.toList()
}
}
data class HorizontalFoldInstruction(val y: Int): FoldInstruction {
override fun performFold(layout: List<List<Boolean>>): List<List<Boolean>> {
val newLayout = MutableList(y) { MutableList(layout[0].size) { false } }
for (i in y downTo 1){
val above = y - i
val under = y + i
for (j in layout[0].indices) {
newLayout[y - i][j] = layout.getOrNull(under)?.getOrNull(j)?: false || layout.getOrNull(above)?.getOrNull(j) ?: false
}
}
return newLayout
.map { it.toList() }
.toList()
}
}
fun List<Position>.createLayout(): List<List<Boolean>> = MutableList(this.maxOf { it.y } + 1) {
MutableList(this.maxOf { it.x } + 1) { false }
}
.apply {
this@createLayout.forEach {
this[it.y][it.x] = true
}
}
.map { it.toList() }
.toList()
class OrigamiSolver {
private val input = OrigamiSolver::class.java.getResource("/input/puzzle13.txt")
?.readText()
?: ""
private val dotPosition = input
.split("\n\n")[0]
.split("\n")
.map {
val (x, y) = it.split(",")
Position(x.toInt(), y.toInt())
}
private val foldingInstructions = input
.split("\n\n")[1]
.split("\n")
.map { s: String ->
val (axis, value) = s.removePrefix("fold along ").split("=")
when (axis) {
"y" -> HorizontalFoldInstruction(value.toInt())
"x" -> VerticalFoldInstruction(value.toInt())
else -> error(axis)
}
}
fun countDotsAfterFirstFold(): Int = foldingInstructions[0]
.performFold(dotPosition.createLayout())
.flatten()
.count { it }
fun foldLayoutEntirely(): String = foldingInstructions
.fold(dotPosition.createLayout()) { acc, foldInstruction -> foldInstruction.performFold(acc) }.printLayout()
} | [
{
"class_path": "tpoujol__aoc-2021__6d474b3/puzzle13/OrigamiSolverKt.class",
"javap": "Compiled from \"OrigamiSolver.kt\"\npublic final class puzzle13.OrigamiSolverKt {\n public static final void main();\n Code:\n 0: new #8 // class puzzle13/OrigamiSolver\n 3: dup\... |
tpoujol__aoc-2021__6d474b3/src/main/kotlin/puzzle3/BinaryDiagnostic.kt | package puzzle3
import kotlin.math.pow
import kotlin.math.roundToInt
fun main() {
println("Hello World!")
val binaryDiagnostic = BinaryDiagnostic()
println("Power consumption is: ${binaryDiagnostic.findPowerConsumption()}, ${binaryDiagnostic.findLifeSupportRating()}")
}
class BinaryDiagnostic {
private val input: List<List<Int>> = BinaryDiagnostic::class.java.getResource("/input/puzzle3.txt")
?.readText()
?.split("\n")
?.filter { it.isNotEmpty() }
?.map { it.fold(MutableList(0) { 0 }) { acc, c -> acc.apply { this.add(c.digitToInt()) } }.toList() }
?: listOf()
fun findPowerConsumption():Int {
val sums = input.fold(MutableList(input[0].size) { 0 }) { acc: MutableList<Int>, list: List<Int> ->
list.forEachIndexed { index, value -> acc[index] += value }
acc
}
println(sums)
val binaryGamma = sums
.map { (it.toDouble() / input.size).roundToInt() }
val binaryEpsilon = sums
.map { ((input.size - it).toDouble() / input.size ).roundToInt() }
val gamma = convertBinaryToDecimal(binaryGamma)
val epsilon = convertBinaryToDecimal(binaryEpsilon)
println("binaryGamma: $binaryGamma, gamma: $gamma")
println("binaryEpsilon: $binaryEpsilon, epsilon: $epsilon")
return epsilon * gamma
}
fun findLifeSupportRating(): Int{
val oxygenRatingBinary = filterOutInputForLifeSupportValue(input, 0, true)
val co2RatingBinary = filterOutInputForLifeSupportValue(input, 0, false)
val oxygenRating = convertBinaryToDecimal(oxygenRatingBinary)
val co2Rating = convertBinaryToDecimal(co2RatingBinary)
println("oxygenRatingBinary: $oxygenRatingBinary, oxygen: $oxygenRating")
println("co2RatingBinary: $co2RatingBinary, co2: $co2Rating")
return oxygenRating * co2Rating
}
companion object {
private fun convertBinaryToDecimal(binaryValue: List<Int>) = binaryValue
.reversed()
.foldIndexed(0.0) { index: Int, acc: Double, digit: Int -> acc + 2.0.pow(index) * digit }
.toInt()
private fun filterOutInputForLifeSupportValue(
valuesList: List<List<Int>>,
indexOfDiscriminant: Int,
shouldTakeMostCommon: Boolean
): List<Int> {
val sum = valuesList.fold(0) { acc, list -> acc + list[indexOfDiscriminant] }
val discriminant: Int = if (shouldTakeMostCommon) {
if (sum > valuesList.size / 2.0) 1 else if (sum < valuesList.size / 2.0) 0 else 1
} else {
if (sum > valuesList.size / 2.0) 0 else if (sum < valuesList.size / 2.0) 1 else 0
}
val resultList = valuesList.filter { it[indexOfDiscriminant] == discriminant }
println("initial size: ${valuesList.size}, sum: $sum, index: $indexOfDiscriminant, discriminant: $discriminant size: ${resultList.size}, $resultList")
return if (resultList.size == 1) resultList[0] else filterOutInputForLifeSupportValue(
resultList, indexOfDiscriminant + 1, shouldTakeMostCommon
)
}
}
} | [
{
"class_path": "tpoujol__aoc-2021__6d474b3/puzzle3/BinaryDiagnosticKt.class",
"javap": "Compiled from \"BinaryDiagnostic.kt\"\npublic final class puzzle3.BinaryDiagnosticKt {\n public static final void main();\n Code:\n 0: ldc #8 // String Hello World!\n 2: getsta... |
tpoujol__aoc-2021__6d474b3/src/main/kotlin/puzzle2/SubCommand.kt | package puzzle2
fun main() {
println("Hello World!")
val subCommand = SubCommand()
println("Result is: ${subCommand.pilotSub()}, ${subCommand.pilotSubWithAim()}")
}
enum class Command {
forward,
down,
up
}
data class Position (val horizontal: Int, val depth: Int, val aim: Int = 0)
class SubCommand {
private val input: List<Pair<Command, Int>> = SubCommand::class.java.getResource("/input/puzzle2.txt")
?.readText()
?.split("\n")
?.filter { it.isNotEmpty() }
?.map {
val values = it.split(" ")
Pair(Command.valueOf(values[0]), values[1].toInt())
}
?: listOf()
fun pilotSub(): Int {
val position = input.fold(Position(0, 0)) { currentPos, pair ->
when (pair.first) {
Command.forward -> currentPos.copy(horizontal = currentPos.horizontal + pair.second)
Command.down -> currentPos.copy(depth = currentPos.depth + pair.second)
Command.up -> currentPos.copy(depth = currentPos.depth - pair.second)
}
}
return position.horizontal * position.depth
}
fun pilotSubWithAim(): Int {
val position = input.fold(Position(0, 0, 0)) { currentPos, pair ->
when (pair.first) {
Command.forward -> currentPos.copy(
horizontal = currentPos.horizontal + pair.second,
depth = currentPos.depth + currentPos.aim * pair.second
)
Command.down -> currentPos.copy(aim = currentPos.aim + pair.second)
Command.up -> currentPos.copy(aim = currentPos.aim - pair.second)
}
}
return position.horizontal * position.depth
}
} | [
{
"class_path": "tpoujol__aoc-2021__6d474b3/puzzle2/SubCommandKt.class",
"javap": "Compiled from \"SubCommand.kt\"\npublic final class puzzle2.SubCommandKt {\n public static final void main();\n Code:\n 0: ldc #8 // String Hello World!\n 2: getstatic #14 ... |
tpoujol__aoc-2021__6d474b3/src/main/kotlin/puzzle10/SyntaxScorer.kt | package puzzle10
import java.lang.IllegalStateException
import kotlin.system.measureTimeMillis
fun main() {
val syntaxScorer = SyntaxScorer()
val time = measureTimeMillis {
println("Bad line scoring: ${syntaxScorer.fixBrokenLines()}")
println("Incomplete line scoring: ${syntaxScorer.fixIncompleteLines()}")
}
println("time: $time")
}
sealed interface SyntaxCharacter{
fun produceMatchingCharacter(): SyntaxCharacter
}
enum class OpeningSyntaxCharacter: SyntaxCharacter {
Parenthesis,
CurlyBracket,
AngleBracket,
SquareBracket;
override fun produceMatchingCharacter(): ClosingSyntaxCharacter = when(this) {
Parenthesis -> ClosingSyntaxCharacter.Parenthesis
CurlyBracket -> ClosingSyntaxCharacter.CurlyBracket
AngleBracket -> ClosingSyntaxCharacter.AngleBracket
SquareBracket -> ClosingSyntaxCharacter.SquareBracket
}
}
enum class ClosingSyntaxCharacter: SyntaxCharacter {
Parenthesis,
CurlyBracket,
AngleBracket,
SquareBracket;
override fun produceMatchingCharacter(): OpeningSyntaxCharacter = when(this) {
Parenthesis -> OpeningSyntaxCharacter.Parenthesis
CurlyBracket -> OpeningSyntaxCharacter.CurlyBracket
AngleBracket -> OpeningSyntaxCharacter.AngleBracket
SquareBracket -> OpeningSyntaxCharacter.SquareBracket
}
fun toSyntaxErrorScore(): Int = when(this) {
Parenthesis -> 3
CurlyBracket -> 1197
AngleBracket -> 25137
SquareBracket -> 57
}
fun toAutocompleteScore(): Int = when(this) {
Parenthesis -> 1
CurlyBracket -> 3
AngleBracket -> 4
SquareBracket -> 2
}
}
fun Char.toSyntaxCharacter():SyntaxCharacter = when(this){
'(' -> OpeningSyntaxCharacter.Parenthesis
'{' -> OpeningSyntaxCharacter.CurlyBracket
'<' -> OpeningSyntaxCharacter.AngleBracket
'[' -> OpeningSyntaxCharacter.SquareBracket
')' -> ClosingSyntaxCharacter.Parenthesis
'}' -> ClosingSyntaxCharacter.CurlyBracket
'>' -> ClosingSyntaxCharacter.AngleBracket
']' -> ClosingSyntaxCharacter.SquareBracket
else -> { throw IllegalArgumentException("unknown opening Character") }
}
class SyntaxScorer {
private val input = SyntaxScorer::class.java.getResource("/input/puzzle10.txt")
?.readText()
?.split("\n")
?.map {
it.fold(mutableListOf()) { acc: MutableList<SyntaxCharacter>, c: Char ->
acc.apply { add(c.toSyntaxCharacter()) }
}.toList()
}
?: listOf()
fun fixBrokenLines(): Int {
return input.fold(mutableListOf()) { acc: MutableList<LineProblem.SyntaxErrorProblem>, line: List<SyntaxCharacter> ->
acc.apply {
findProblemInLine(line)
.takeIf { it is LineProblem.SyntaxErrorProblem }
?.also { add(it as LineProblem.SyntaxErrorProblem) }
}
}
.sumOf { it.illegalClosingCharacter.toSyntaxErrorScore() }
}
fun fixIncompleteLines(): Long {
val lineProblems = input.fold(mutableListOf()) { acc: MutableList<LineProblem.IncompleteLineProblem>, line: List<SyntaxCharacter> ->
acc.apply {
findProblemInLine(line)
.takeIf { it is LineProblem.IncompleteLineProblem }
?.also { add(it as LineProblem.IncompleteLineProblem) }
}
}.toList()
val result = lineProblems.map {
it.orphanedOpeningCharacterList
.reversed()
.fold(0L) { acc: Long, openingSyntaxCharacter: OpeningSyntaxCharacter ->
acc * 5 + openingSyntaxCharacter.produceMatchingCharacter().toAutocompleteScore()
}
}
.sortedBy { it }
return result[result.size.floorDiv(2)]
}
private companion object {
sealed class LineProblem{
data class SyntaxErrorProblem(val illegalClosingCharacter: ClosingSyntaxCharacter): LineProblem()
data class IncompleteLineProblem(val orphanedOpeningCharacterList: List<OpeningSyntaxCharacter>): LineProblem()
}
private fun findProblemInLine(line: List<SyntaxCharacter>): LineProblem {
val openingCharacters = mutableListOf<OpeningSyntaxCharacter>()
for (character in line){
if (character is ClosingSyntaxCharacter) {
if (openingCharacters.isEmpty()){
return LineProblem.SyntaxErrorProblem(character)
} else if (openingCharacters.last().produceMatchingCharacter() != character) {
return LineProblem.SyntaxErrorProblem(character)
} else {
openingCharacters.removeLast()
}
}
else if (character is OpeningSyntaxCharacter) {
openingCharacters.add(character)
}
else {
throw IllegalStateException("character: $character is neither an opening nor a closing syntax char")
}
}
return LineProblem.IncompleteLineProblem(openingCharacters.toList())
}
}
} | [
{
"class_path": "tpoujol__aoc-2021__6d474b3/puzzle10/SyntaxScorer$Companion$LineProblem$IncompleteLineProblem.class",
"javap": "Compiled from \"SyntaxScorer.kt\"\npublic final class puzzle10.SyntaxScorer$Companion$LineProblem$IncompleteLineProblem extends puzzle10.SyntaxScorer$Companion$LineProblem {\n pri... |
tpoujol__aoc-2021__6d474b3/src/main/kotlin/puzzle7/WhaleBuster.kt | package puzzle7
import kotlin.math.abs
import kotlin.math.floor
import kotlin.math.roundToInt
import kotlin.system.measureTimeMillis
fun main() {
val whaleBuster = WhaleBuster()
val time = measureTimeMillis {
println("Minimal fuel consumption is: ${whaleBuster.findCrabAlignment()}")
println("Total fuel consumption with cost increased by distance is: ${whaleBuster.findCrabAlignmentWithCostProblems()}")
}
println("Time: ${time}ms")
}
class WhaleBuster {
private val input = WhaleBuster::class.java.getResource("/input/puzzle7.txt")
?.readText()
?.split(",")
?.map { it.toInt() }
?: listOf()
fun findCrabAlignment(): Int {
val distanceValues = (0..input.maxOf { it }).associateWith { position ->
input.sumOf { crabPosition ->
abs(crabPosition - position)
}
}
println(distanceValues)
val inputNumber = input.size
val sortedInput = input.sorted()
val median = if (inputNumber % 2 == 1) {
sortedInput[floor(inputNumber / 2.0).toInt()]
} else {
(sortedInput[inputNumber / 2] + sortedInput[inputNumber / 2]) / 2
}
println("median is: $median")
return sortedInput.sumOf { abs(it - median) }
}
fun findCrabAlignmentWithCostProblems(): Int {
val distanceValues = (0..input.maxOf { it }).associateWith { position ->
input.sumOf { crabPosition ->
val distance = abs(crabPosition - position)
(distance * (distance + 1) / 2.0).roundToInt()
}
}
val optimalPosition = distanceValues.minByOrNull { it.value }
println("Optimal Position is: $optimalPosition")
return optimalPosition?.value ?: 0
}
} | [
{
"class_path": "tpoujol__aoc-2021__6d474b3/puzzle7/WhaleBusterKt.class",
"javap": "Compiled from \"WhaleBuster.kt\"\npublic final class puzzle7.WhaleBusterKt {\n public static final void main();\n Code:\n 0: new #8 // class puzzle7/WhaleBuster\n 3: dup\n 4: ... |
tpoujol__aoc-2021__6d474b3/src/main/kotlin/puzzle8/SevenSegmentsDemystifier.kt | package puzzle8
import kotlin.math.pow
import kotlin.system.measureTimeMillis
fun main() {
val sevenSegmentsDemystifier = SevenSegmentsDemystifier()
val basicDigitWiring = DigitWiring()
val time = measureTimeMillis {
println("test: ${basicDigitWiring.findNumber("acf")}")
println("Part 1 solution is: ${sevenSegmentsDemystifier.countEasyDigits()}")
println("Part 2 solution is: ${sevenSegmentsDemystifier.findAllDigits()}")
}
println("Time: $time")
}
data class InputEntry(val patterns: List<String>, val output: List<String>)
data class DigitWiring(
private val one: String = "a",
private val two: String = "b",
private val three: String = "c",
private val four: String = "d",
private val five: String = "e",
private val six: String = "f",
private val seven: String = "g"
) {
private fun produceDisplayForInt(value: Int): List<String> {
return when (value) {
0 -> listOf(one, two, three, five, six, seven)
1 -> listOf(three, six)
2 -> listOf(one, three, four, five, seven)
3 -> listOf(one, three, four, six, seven)
4 -> listOf(two, three, four, six)
5 -> listOf(one, two, four, six, seven)
6 -> listOf(one, two, four, five, six, seven)
7 -> listOf(one, three, six)
8 -> listOf(one, two, three, four, five, six, seven)
9 -> listOf(one, two, three, four, six, seven)
else -> throw IllegalArgumentException("This is not a single digit number")
}
}
fun findNumber(toFind: String): Int {
// has to be checked in that order otherwise an 8 could be caught by a 0 for example
val splitString = toFind.toList().map { it.toString() }
return when {
splitString.containsAll(produceDisplayForInt(8)) -> 8
splitString.containsAll(produceDisplayForInt(0)) -> 0
splitString.containsAll(produceDisplayForInt(9)) -> 9
splitString.containsAll(produceDisplayForInt(6)) -> 6
splitString.containsAll(produceDisplayForInt(2)) -> 2
splitString.containsAll(produceDisplayForInt(3)) -> 3
splitString.containsAll(produceDisplayForInt(5)) -> 5
splitString.containsAll(produceDisplayForInt(4)) -> 4
splitString.containsAll(produceDisplayForInt(7)) -> 7
splitString.containsAll(produceDisplayForInt(1)) -> 1
else -> -1
}
}
fun findNumberForList(toFind: List<String>): Int {
return toFind
.reversed()
.foldIndexed(0) {index: Int, acc: Int, s: String ->
acc + findNumber(s) * 10.0.pow(index).toInt()
}
}
}
class SevenSegmentsDemystifier {
private val input = SevenSegmentsDemystifier::class.java.getResource("/input/puzzle8.txt")
?.readText()
?.split("\n")
?.filter { it.isNotBlank() }
?.map { s: String ->
val (patterns, output) = s.split("|").map { it.trim() }
InputEntry(
patterns.split(" ").map { it.trim() },
output.split(" ").map { it.trim() }
)
}
?: listOf()
fun countEasyDigits(): Int {
var counter = 0
input.forEach { entry: InputEntry ->
counter += entry.output.sumOf {
val result = when(it.length) {
2, 3, 4, 7 -> 1
else -> 0
}
result
}
}
return counter
}
private fun decryptPattern(patterns: List<String>): DigitWiring {
val dividedPatterns = patterns.groupBy { it.length }
val segmentOne: Char
val segmentTwo: Char
val segmentThree: Char
val segmentFour: Char
val segmentFive: Char
val segmentSix: Char
val segmentSeven: Char
// Extract possibilities for the obvious digits
val patternForOne = dividedPatterns.getOrDefault(2, null)?.get(0)?.toList()
val patternForSeven = dividedPatterns.getOrDefault(3, null)?.get(0)?.toList()
val patternForFour = dividedPatterns.getOrDefault(4, null)?.get(0)?.toList()
if (patternForSeven == null || patternForOne == null || patternForFour == null ) {
return DigitWiring()
}
segmentOne = patternForSeven.filterNot { patternForOne.contains(it) }[0]
val possibilitiesForSegments3And6 = patternForSeven.filter { patternForOne.contains(it) }
val possibilitiesForSegment2And4 = patternForFour.filterNot { patternForOne.contains(it) || it == segmentOne }
// Find a 3 in the patterns, this will be a number
// with 5 segments,
// with all the possibilities for 3 and 6,
// with the segment 1,
// and with one of the possibilities of the 2 and 4
val patternForThree = dividedPatterns
.getOrDefault(5, null)
?.map { it.toList() }
?.filter { it.contains(segmentOne) }
?.filter { it.containsAll(possibilitiesForSegments3And6) }
?.filter { chars ->
possibilitiesForSegment2And4.any { chars.contains(it) }
}
?.getOrNull(0)
if (patternForThree == null) {
println("no pattern for 3")
return DigitWiring()
}
segmentFour = patternForThree.filter { possibilitiesForSegment2And4.contains(it) }[0]
segmentTwo = possibilitiesForSegment2And4.filterNot { it == segmentFour }[0]
segmentSeven = patternForThree.filterNot {
it == segmentOne || it == segmentFour || patternForOne.contains(it)
}[0]
// Next, we find a segment representing a 5, this will be a number with
// 5 segments
// the segments 1, 2, 4 and 7 in it
// one of the segments from the possibilities for 3 and 6
val patternForFive = dividedPatterns
.getOrDefault(5, null)
?.map { it.toList()}
?.filter{ it.containsAll(listOf(segmentOne, segmentTwo, segmentFour, segmentSeven)) }
?.filter { list: List<Char> ->
possibilitiesForSegments3And6.any { list.contains(it) }
}
?.getOrNull(0)
if (patternForFive == null) {
println("no pattern for 5")
return DigitWiring()
}
segmentSix = patternForFive.filter { possibilitiesForSegments3And6.contains(it) }[0]
segmentThree = possibilitiesForSegments3And6.filterNot { it == segmentSix }[0]
// Finally, we deduce the last segment
segmentFive = "abcdefg".toList().filterNot {
listOf(segmentOne, segmentTwo, segmentThree, segmentFour, segmentSix, segmentSeven).contains(it)
}[0]
return DigitWiring(
segmentOne.toString(),
segmentTwo.toString(),
segmentThree.toString(),
segmentFour.toString(),
segmentFive.toString(),
segmentSix.toString(),
segmentSeven.toString()
)
}
fun findAllDigits(): Int {
val display = decryptPattern(input[0].patterns)
println("$display -> ${display.findNumberForList(input[0].output)}")
return input.fold(0) { acc, inputEntry ->
val digitWiring = decryptPattern(inputEntry.patterns)
acc + digitWiring.findNumberForList(inputEntry.output)
}
}
} | [
{
"class_path": "tpoujol__aoc-2021__6d474b3/puzzle8/SevenSegmentsDemystifier.class",
"javap": "Compiled from \"SevenSegmentsDemystifier.kt\"\npublic final class puzzle8.SevenSegmentsDemystifier {\n private final java.util.List<puzzle8.InputEntry> input;\n\n public puzzle8.SevenSegmentsDemystifier();\n ... |
hudsonb__turf.kt__e39bf4f/src/main/kotlin/turfkt/Conversions.kt | package turfkt
/**
* Earth Radius used with the Harvesine formula and approximates using a spherical (non-ellipsoid) Earth.
*/
const val EARTH_RADIUS = 6371008.8
/**
* Unit of measurement factors using a spherical (non-ellipsoid) earth radius.
*/
private val factors = mapOf(
"centimeters" to EARTH_RADIUS * 100,
"centimetres" to EARTH_RADIUS * 100,
"degrees" to EARTH_RADIUS / 111325,
"feet" to EARTH_RADIUS * 3.28084,
"inches" to EARTH_RADIUS * 39.370,
"kilometers" to EARTH_RADIUS / 1000,
"kilometres" to EARTH_RADIUS / 1000,
"meters" to EARTH_RADIUS,
"metres" to EARTH_RADIUS,
"miles" to EARTH_RADIUS / 1609.344,
"millimeters" to EARTH_RADIUS * 1000,
"millimetres" to EARTH_RADIUS * 1000,
"nauticalmiles" to EARTH_RADIUS / 1852,
"radians" to 1.0,
"yards" to EARTH_RADIUS / 1.0936
)
/**
* Convert a distance measurement (assuming a spherical Earth) from radians to a more friendly unit.
* Valid units: miles, nauticalmiles, inches, yards, meters, metres, kilometers, centimeters, feet
*
* @param radians Radians across the sphere
* @param units The length units to convert to. Can be degrees, radians, miles, or kilometers inches, yards, metres,
* meters, kilometres, kilometers. Default to kilometers.
* @returns The length in the given units.
*/
fun radiansToLength(radians: Double, units: String = "kilometers"): Double {
if(!factors.containsKey(units)) throw IllegalArgumentException("Unrecognized units: $units")
val factor = factors[units] ?: throw IllegalStateException("Factor for units $units was null")
return radians * factor
}
/**
* Convert a distance measurement (assuming a spherical Earth) from a real-world unit into radians
* Valid units: miles, nauticalmiles, inches, yards, meters, metres, kilometers, centimeters, feet
*
* @param distance The distance in real units
* @param units The units of the given distance. Can be degrees, radians, miles, or kilometers inches, yards, metres,
* meters, kilometres, kilometers. Defaults to kilometers.
* @returns The length in radians.
*/
fun lengthToRadians(distance: Double, units: String = "kilometers"): Double {
if(!factors.containsKey(units)) throw IllegalArgumentException("Unrecognized units: $units")
val factor = factors[units] ?: throw IllegalStateException("Factor for units $units was null")
return distance / factor
}
/**
* Converts a length to the requested unit.
* Valid units: miles, nauticalmiles, inches, yards, meters, metres, kilometers, centimeters, feet
*
* @param length length to be converted
* @param originalUnit [originalUnit="kilometers"] of the length
* @param finalUnit [finalUnit="kilometers"] returned unit
* @return the converted length
*/
fun convertLength(length: Double, originalUnit: String = "kilometers", finalUnit: String = "kilometers"): Double {
require(length >= 0) { "length must be a positive number" }
return radiansToLength(lengthToRadians(length, originalUnit), finalUnit)
} | [
{
"class_path": "hudsonb__turf.kt__e39bf4f/turfkt/ConversionsKt.class",
"javap": "Compiled from \"Conversions.kt\"\npublic final class turfkt.ConversionsKt {\n public static final double EARTH_RADIUS;\n\n private static final java.util.Map<java.lang.String, java.lang.Double> factors;\n\n public static fi... |
aesdeef__kotlin-basics-projects__1475a20/simple-tic-tac-toe/Main.kt | package tictactoe
import kotlin.math.abs
typealias Board = List<List<Char>>
enum class GameState {
IMPOSSIBLE,
X_WINS,
O_WINS,
DRAW,
NOT_FINISHED,
}
fun main() {
val input = "_________"
var board = input.chunked(3).map { it.toList() }
printBoard(board)
for (player in "XOXOXOXOX") {
board = promptForMove(board, player)
printBoard(board)
if (
evaluateState(board) in listOf(
GameState.X_WINS, GameState.O_WINS
)
) break
}
printState(board)
}
fun updateBoard(board: Board, newCharacter: Char, coordinates: Pair<Int, Int>): Board {
val (rowNumber, columnNumber) = coordinates
return board.mapIndexed { r, row ->
row.mapIndexed { c, square ->
if (r == rowNumber && c == columnNumber) newCharacter else square
}
}
}
fun parseCoordinates(board: Board, input: String): Pair<Int, Int> {
val (rowNumber, columnNumber) = try {
input.split(" ").map { it.toInt() - 1 }
} catch (e: Exception) {
throw Exception("You should enter numbers!")
}
if (rowNumber !in 0..2 || columnNumber !in 0..2) {
throw Exception("Coordinates should be from 1 to 3")
}
if (board[rowNumber][columnNumber] != '_') {
throw Exception("This cell is occupied!")
}
return Pair(rowNumber, columnNumber)
}
fun promptForMove(board: Board, player: Char): Board {
while (true) {
print("Enter the coordinates: ")
val input = readLine()!!
try {
val coordinates = parseCoordinates(board, input)
return updateBoard(board, player, coordinates)
} catch (e: Exception) {
println(e.message)
}
}
}
fun evaluateState(board: Board): GameState {
val countX = board.sumOf { row -> row.count { it == 'X' } }
val countO = board.sumOf { row -> row.count { it == 'O' } }
if (abs(countX - countO) > 1) return GameState.IMPOSSIBLE
val rows = board
val columns = board[0]
.indices.map { i ->
board.map { row -> row[i] }
}
val diagonals = listOf(
board.indices.map { board[it][it] },
board.indices.map { board[it][board.lastIndex - it] },
)
val lines = (rows + columns + diagonals)
.map { it.joinToString("") }
val winners = lines
.filter { it in listOf("XXX", "OOO") }
.map { it.first() }
.toSet()
return when (winners.size) {
0 -> if (countX + countO == 9) GameState.DRAW else GameState.NOT_FINISHED
1 -> if ('X' in winners) GameState.X_WINS else GameState.O_WINS
else -> GameState.IMPOSSIBLE
}
}
fun printState(board: Board) {
val state = evaluateState(board)
println(
when (state) {
GameState.IMPOSSIBLE -> "Impossible"
GameState.X_WINS -> "X wins"
GameState.O_WINS -> "O wins"
GameState.DRAW -> "Draw"
GameState.NOT_FINISHED -> "Game not finished"
}
)
}
fun printBoard(board: Board) {
println("---------")
board.forEach { row ->
val marks = row.map { if (it in "XO") it else ' ' }
println("| ${marks.joinToString(" ")} |")
}
println("---------")
}
| [
{
"class_path": "aesdeef__kotlin-basics-projects__1475a20/tictactoe/MainKt$WhenMappings.class",
"javap": "Compiled from \"Main.kt\"\npublic final class tictactoe.MainKt$WhenMappings {\n public static final int[] $EnumSwitchMapping$0;\n\n static {};\n Code:\n 0: invokestatic #14 /... |
Onuchin-Artem__k-Loops__ee076b3/src/main/kotlin/kLoops/examples/island.kt | package kLoops.examples
typealias Point = Pair<Int, Int>
data class World(val landPoints: Set<Point>, val height: Int, val width: Int) {
fun print() {
(0 until height).forEach { row ->
(0 until width).forEach { column ->
val value = if (landPoints.contains(Point(row, column))) 1 else 0
print("$value ")
}
println()
}
}
fun neighbours(point: Point): List<Point> {
val neighbours = mutableListOf<Point>()
if (point.first > 0) neighbours.add(point.copy(first = point.first - 1))
if (point.first < height - 1) neighbours.add(point.copy(first = point.first + 1))
if (point.second > 0) neighbours.add(point.copy(second = point.second - 1))
if (point.second > width - 1) neighbours.add(point.copy(second = point.second + 1))
return neighbours.toList()
}
}
fun isPerfectIsland(world: World): Boolean {
val visitedPoint = mutableListOf(world.landPoints.first())
fun traverseIsland() {
world.neighbours(visitedPoint.last()).forEach { neighbour ->
if (world.landPoints.contains(neighbour) && !visitedPoint.contains(neighbour)) {
visitedPoint.add(neighbour)
traverseIsland()
}
}
}
traverseIsland()
return visitedPoint.containsAll(world.landPoints)
}
val memmoization = mutableMapOf<World, Int>()
fun findNumberOfSwitches(world: World, path: List<World>): Int {
memmoization[world] = -1
if (memmoization[world]?: -1 > 0 ) {
return memmoization[world]!!
}
val numberOfSwitches = if (isPerfectIsland(world)) {
0
} else {
1 + world.landPoints.flatMap { point ->
world.neighbours(point).map { neighbour ->
world.copy(landPoints = world.landPoints - point + neighbour)
}.filter {newWorld ->
!path.contains(newWorld)
}.map { newWorld ->
val sw = findNumberOfSwitches(newWorld, path + world)
sw
}
}.min()!!
}
memmoization.put(world, numberOfSwitches)
return numberOfSwitches
}
fun main() {
val worldArray = listOf(
listOf(0, 1, 0),
listOf(0, 0, 1),
listOf(1, 0, 0)
)
val height = worldArray.size
val width = worldArray[0].size
val landPoints = (0 until height).flatMap { row ->
(0 until width).flatMap { column ->
if (worldArray[row][column] == 1) listOf(Point(row, column)) else listOf()
}
}.toSet()
val world = World(landPoints, height, width)
world.print()
println("Fuck ${findNumberOfSwitches(world, listOf())}")
println("Fuck ${findNumberOfSwitches(world, listOf())}")
} | [
{
"class_path": "Onuchin-Artem__k-Loops__ee076b3/kLoops/examples/IslandKt.class",
"javap": "Compiled from \"island.kt\"\npublic final class kLoops.examples.IslandKt {\n private static final java.util.Map<kLoops.examples.World, java.lang.Integer> memmoization;\n\n public static final boolean isPerfectIslan... |
ghonix__Problems__25d4ba0/src/main/kotlin/graph/Graph.kt | package graph
import java.util.*
import kotlin.collections.HashMap
import kotlin.collections.HashSet
class Graph {
companion object {
@JvmStatic
fun createAdjacencyList(edges: Array<Pair<String, String>>): Map<String, Set<String>> {
val graph = HashMap<String, MutableSet<String>>()
for (edge in edges) {
if (!graph.containsKey(edge.first)) {
graph[edge.first] = HashSet()
}
if (!graph.containsKey(edge.second)) {
graph[edge.second] = HashSet()
}
graph[edge.first]?.add(edge.second)
graph[edge.second]?.add(edge.first)
}
return graph
}
@JvmStatic
fun main(args: Array<String>) {
val graph = Graph()
// graph.breadthFirst()
// graph.findPath()
// println(graph.findPathUndirected())
println(graph.connectedComponents())
}
}
private fun connectedComponents(): Int {
// val edges = arrayOf(Pair("1", "2"), Pair("4", "6"), Pair("5", "6"), Pair("6", "7"), Pair("6", "8"), Pair("3"))
val graph = HashMap<String, Set<String>>()
graph["1"] = setOf("2")
graph["2"] = setOf("1")
graph["3"] = emptySet()
graph["4"] = setOf("6")
graph["5"] = setOf("6")
graph["6"] = setOf("4", "5", "7", "8")
graph["7"] = setOf("6")
graph["8"] = setOf("6")
val visited = HashSet<String>()
return connectedComponents(graph, visited)
}
private fun connectedComponents(
graph: HashMap<String, Set<String>>,
visited: HashSet<String>
): Int {
var connectedComponents = 0
for (node in graph.keys) {
if (!visited.contains(node)) {
connectedComponents++
explore(graph, node, visited)
}
}
return connectedComponents
}
private fun explore(
graph: HashMap<String, Set<String>>,
node: String,
visited: HashSet<String>
) {
if (!visited.contains(node)) {
visited.add(node)
graph[node]?.let {
for (neighbor in it) {
explore(graph, neighbor, visited)
}
}
}
}
fun findPathUndirected(): Boolean {
val edges = arrayOf(Pair("i", "j"), Pair("k", "i"), Pair("m", "k"), Pair("k", "l"), Pair("o", "n"))
val graph = createAdjacencyList(edges)
println(graph.toString())
return findPathUndirected(graph, "i", "j")
}
private fun findPathUndirected(graph: Map<String, Set<String>>, src: String, dst: String): Boolean {
val queue: Queue<String> = LinkedList()
queue.add(src)
val visited = HashSet<String>()
while (queue.isNotEmpty()) {
val current = queue.poll()
if (current.equals(dst)) {
return true
}
if (!visited.contains(current)) {
visited.add(current)
graph[current]?.let {
for (neighbor in graph[current]!!) {
queue.add(neighbor)
}
}
}
}
return false
}
fun depthFirst(graph: HashMap<String, Set<String>>, source: String) {
val stack = Stack<String>()
stack.push(source)
while (stack.isNotEmpty()) {
val current = stack.pop()
println(current)
graph[current]?.let {
for (neighbor in graph[current]!!) {
stack.push(neighbor)
}
}
}
}
fun breadthFirst() {
val graph = HashMap<String, Set<String>>()
graph["a"] = setOf("b", "c")
graph["b"] = setOf("d")
graph["c"] = setOf("e")
graph["d"] = setOf("f")
graph["e"] = emptySet()
graph["f"] = emptySet()
breadthFirst(graph, "a")
}
fun breadthFirst(graph: HashMap<String, Set<String>>, source: String) {
val queue: Queue<String> = LinkedList()
queue.add(source)
while (queue.isNotEmpty()) {
val current = queue.poll()
println(current)
graph[current]?.let {
for (neighbor in graph[current]!!) {
queue.add(neighbor)
}
}
}
}
private fun findPath() {
val graph = HashMap<String, Set<String>>()
graph["f"] = setOf("g", "i")
graph["g"] = setOf("h")
graph["h"] = emptySet()
graph["i"] = setOf("g", "k")
graph["j"] = setOf("i")
graph["k"] = emptySet()
println(this.findPath(graph, "j", "h"))
}
private fun findPath(graph: java.util.HashMap<String, Set<String>>, src: String, dst: String): Boolean {
val queue: Queue<String> = LinkedList()
queue.add(src)
while (queue.isNotEmpty()) {
val current = queue.poll()
if (current.equals(dst)) {
return true
}
graph[current]?.let {
for (neighbor in graph[current]!!) {
queue.add(neighbor)
}
}
}
return false
}
} | [
{
"class_path": "ghonix__Problems__25d4ba0/graph/Graph$Companion.class",
"javap": "Compiled from \"Graph.kt\"\npublic final class graph.Graph$Companion {\n private graph.Graph$Companion();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n... |
ghonix__Problems__25d4ba0/src/main/kotlin/arrays/NumberOfIslands.kt | package arrays
import java.util.LinkedList
import java.util.Queue
class NumberOfIslands {
data class Coordinate(val row: Int, val col: Int)
fun numIslands(grid: Array<CharArray>): Int {
val visited = HashSet<Coordinate>()
var islandsFound = 0
for (row in grid.indices) {
for (col in grid[row].indices) {
val current = grid[row][col]
if (current == '0' || visited.contains(Coordinate(row, col))) {
continue
}
exploreIterative(grid, row, col, visited)
islandsFound++
}
}
return islandsFound
}
private fun exploreRecursive(grid: Array<CharArray>, row: Int, col: Int, visited: java.util.HashSet<Coordinate>) {
if (visited.contains(Coordinate(row, col))) {
return
}
visited.add(Coordinate(row, col))
val dr = arrayOf(0, 1, 0, -1)
val dc = arrayOf(1, 0, -1, 0)
for (i in dr.indices) {
val newRow = row + dr[i]
val newCol = col + dc[i]
if (isValid(grid, newRow, newCol)) {
exploreRecursive(grid, newRow, newCol, visited)
}
}
}
private fun exploreIterative(grid: Array<CharArray>, row: Int, col: Int, visited: java.util.HashSet<Coordinate>) {
val queue: Queue<Coordinate> = LinkedList()
queue.add(Coordinate(row, col))
while (queue.isNotEmpty()) {
val current = queue.poll()
if (visited.contains(current)) {
continue
}
visited.add(current)
val dr = arrayOf(0, 1, 0, -1)
val dc = arrayOf(1, 0, -1, 0)
for (i in dr.indices) {
val newRow = current.row + dr[i]
val newCol = current.col + dc[i]
if (isValid(grid, newRow, newCol)) {
queue.add(Coordinate(newRow, newCol))
}
}
}
}
private fun isValid(grid: Array<CharArray>, row: Int, col: Int): Boolean {
return row >= 0 && row < grid.size && col >= 0 && col < grid[row].size && grid[row][col] == '1'
}
}
fun main() {
println(
NumberOfIslands().numIslands(
arrayOf(
charArrayOf('1', '1', '0', '0', '0'),
charArrayOf('1', '1', '0', '0', '0'),
charArrayOf('0', '0', '1', '0', '0'),
charArrayOf('0', '0', '0', '1', '1')
)
)
)
} | [
{
"class_path": "ghonix__Problems__25d4ba0/arrays/NumberOfIslands.class",
"javap": "Compiled from \"NumberOfIslands.kt\"\npublic final class arrays.NumberOfIslands {\n public arrays.NumberOfIslands();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<i... |
ghonix__Problems__25d4ba0/src/main/kotlin/string/IsNumer.kt | package string
/**
* https://leetcode.com/problems/valid-number/description/
*/
class IsNumer {
enum class TokenType {
DIGIT,
SIGN,
DOT,
EXPONENT,
INVALID
}
private val dfa = hashMapOf(
Pair(0, hashMapOf(Pair(TokenType.DIGIT, 1), Pair(TokenType.SIGN, 2), Pair(TokenType.DOT, 3))), // Start
Pair(1, hashMapOf(Pair(TokenType.DIGIT, 1), Pair(TokenType.DOT, 4), Pair(TokenType.EXPONENT, 5))), // digit
Pair(2, hashMapOf(Pair(TokenType.DIGIT, 1), Pair(TokenType.DOT, 3))), // optional sign
Pair(3, hashMapOf(Pair(TokenType.DIGIT, 4))), // dot
Pair(
4,
hashMapOf(Pair(TokenType.DIGIT, 4), Pair(TokenType.EXPONENT, 5))
), // this is the digit state after a dot
Pair(5, hashMapOf(Pair(TokenType.DIGIT, 7), Pair(TokenType.SIGN, 6))), // exponent
Pair(6, hashMapOf(Pair(TokenType.DIGIT, 7))), // sign after exponent e+
Pair(7, hashMapOf(Pair(TokenType.DIGIT, 7))) // digit after exponent e7
)
private val validStates = setOf(1, 4, 7)
fun isNumber(s: String): Boolean {
var state = 0
for (token in s) {
val tokenType = getTokenType(token)
if (tokenType == TokenType.INVALID) {
return false
} else {
val tempState = transition(state, tokenType)
if (tempState == null) {
return false
} else {
state = tempState
}
}
}
return isValidEndState(state)
}
private fun isValidEndState(state: Int): Boolean {
return validStates.contains(state)
}
private fun transition(state: Int, tokenType: TokenType): Int? {
val currentState = dfa[state]
return currentState?.let { it[tokenType] }
}
private fun getTokenType(token: Char): TokenType {
return when (token) {
'+' -> TokenType.SIGN
'-' -> TokenType.SIGN
'.' -> TokenType.DOT
in '0'..'9' -> TokenType.DIGIT
in "eE" -> TokenType.EXPONENT
else -> TokenType.INVALID
}
}
}
fun main() {
println(IsNumer().isNumber("a+1"))
println(IsNumer().isNumber("1"))
println(IsNumer().isNumber("+123"))
println(IsNumer().isNumber(".1"))
println(IsNumer().isNumber("+1e3"))
println(IsNumer().isNumber("+1e3.5"))
println(IsNumer().isNumber("+1E3.5"))
println(IsNumer().isNumber("+1E-356"))
println(IsNumer().isNumber("+1E+3"))
println(IsNumer().isNumber("+1.0E+3"))
println(IsNumer().isNumber("+1.234E+3"))
println(IsNumer().isNumber(".E3"))
} | [
{
"class_path": "ghonix__Problems__25d4ba0/string/IsNumerKt.class",
"javap": "Compiled from \"IsNumer.kt\"\npublic final class string.IsNumerKt {\n public static final void main();\n Code:\n 0: new #8 // class string/IsNumer\n 3: dup\n 4: invokespecial #11 ... |
ghonix__Problems__25d4ba0/src/main/kotlin/string/MinimumWindowSubstring.kt | package string
/*
https://leetcode.com/problems/minimum-window-substring/
*/
class MinimumWindowSubstring {
val tMap = HashMap<Char, Int>()
private fun isAcceptable(map: HashMap<Char, Int>): Boolean {
for (key in map.keys) {
if (map[key]!! > 0) {
return false
}
}
return true
}
private fun shouldShrinkWindow(map: java.util.HashMap<Char, Int>): Boolean {
if (isAcceptable(map)) {
return true
}
for (key in map.keys) {
if (map[key]!! > 0) {
return false
}
}
return true
}
fun minWindow(src: String, t: String): String {
for (char in t) { // hash the count of chars in t
if (tMap.containsKey(char)) {
tMap[char] = tMap[char]!!.inc()
} else {
tMap[char] = 1
}
}
var l = 0
var r = l
var minLength = Int.MAX_VALUE
var rangeStart = 0
var rangeEnd = 0
while (r < src.length) {
val end = src[r]
if (tMap.containsKey(end)) {
tMap[end] = tMap[end]!!.dec()
r++
} else {
r++
}
while (l <= r && shouldShrinkWindow(map = tMap)) {
if ((r - l) < minLength) {
minLength = r - l
rangeStart = l
rangeEnd = r
}
// try to shrink the window
val start = src[l]
if (tMap.containsKey(start)) {
if (tMap[start]!!.inc() <= 0) {
tMap[start] = tMap[start]!!.inc()
l++
continue
} else {
break
}
} else {
l++
}
}
}
return src.substring(startIndex = rangeStart, endIndex = rangeEnd)
}
}
fun main() {
println(
MinimumWindowSubstring().minWindow("ADOBECODEBANC", "ABC")
)
}
/*
1- Hour debug (java, js, python)
* Code with issues
* Find the bugs and fix them
2- 2 hours take home
* Algorithm coding problem
* Data infra (schema design)
* System design proposal
*/ | [
{
"class_path": "ghonix__Problems__25d4ba0/string/MinimumWindowSubstring.class",
"javap": "Compiled from \"MinimumWindowSubstring.kt\"\npublic final class string.MinimumWindowSubstring {\n private final java.util.HashMap<java.lang.Character, java.lang.Integer> tMap;\n\n public string.MinimumWindowSubstrin... |
ghonix__Problems__25d4ba0/src/main/kotlin/prefixSum/MinSubArrayLen.kt | package prefixSum
import kotlin.math.min
/*
https://leetcode.com/problems/minimum-size-subarray-sum/
*/
class MinSubArrayLen {
fun minSubArrayLen(target: Int, nums: IntArray): Int {
if (nums.isEmpty()) {
return 0
}
var minSize = Int.MAX_VALUE
val prefixSums = IntArray(nums.size)
prefixSums[0] = nums[0]
for (i in 1 until nums.size) {
prefixSums[i] = prefixSums[i - 1] + nums[i]
}
for (i in prefixSums.indices) {
val remainder = prefixSums[i] - target
if (remainder < 0) {
continue
}
val lowerBound = search(prefixSums, 0, i - 1, prefixSums[i], target)
if (lowerBound != -1) {
minSize = min(minSize, i - lowerBound + 1)
}
}
return if (minSize == Int.MAX_VALUE) {
0
} else {
minSize
}
}
private fun search(array: IntArray, low: Int, hi: Int, prefixSum: Int, target: Int): Int {
var start = low
var end = hi
var mid = (start + end) / 2
while (start <= end) {
mid = (start + end) / 2
if (prefixSum - array[mid] == target) {
return mid + 1
} else if (prefixSum - array[mid] > target) {
start = mid + 1
} else {
end = mid - 1
}
}
return mid
}
}
fun main() {
val m = MinSubArrayLen()
println(
m.minSubArrayLen(20, intArrayOf(1, 2, 0, 6, 14, 15))
) // 2
// println(
// m.minSubArrayLen(20, intArrayOf(2, 16, 14, 15))
// ) // 2
//
// println(
// m.minSubArrayLen(7, intArrayOf(2, 3, 1, 2, 4, 3))
// ) // 2
//
// println(
// m.minSubArrayLen(4, intArrayOf(1, 4, 4))
// ) // 1
//
// println(
// m.minSubArrayLen(15, intArrayOf(1, 2, 3, 4, 5))
// ) // 5
//
// println(
// m.minSubArrayLen(11, intArrayOf(1, 1, 1, 1, 1, 1, 1, 1))
// ) // 0
} | [
{
"class_path": "ghonix__Problems__25d4ba0/prefixSum/MinSubArrayLenKt.class",
"javap": "Compiled from \"MinSubArrayLen.kt\"\npublic final class prefixSum.MinSubArrayLenKt {\n public static final void main();\n Code:\n 0: new #8 // class prefixSum/MinSubArrayLen\n 3... |
ghonix__Problems__25d4ba0/src/main/kotlin/tree/segmentTree/SubsetSum.kt | package tree.segmentTree
import kotlin.math.*
class SubsetSum(list: Array<Int>) {
private var segmentTree: IntArray
override fun toString(): String {
return segmentTree.contentToString()
}
init {
val height = ceil(log(list.size.toDouble(), 2.0))
val maxSize = (height + 1).pow(2) - 1
segmentTree = IntArray(maxSize.toInt())
constructTree(list, 0, 0, list.size - 1)
}
private fun constructTree(list: Array<Int>, current: Int, start: Int, end: Int): Int {
if (start == end) {
segmentTree[current] = list[start]
return segmentTree[current]
}
val middle = (start + end) / 2
val left = constructTree(list, current * 2 + 1, start, middle)
val right = constructTree(list, current * 2 + 2, middle + 1, end)
segmentTree[current] = left + right
return segmentTree[current]
}
fun getSum(start: Int, end: Int): Int {
val queryS = max(start, 0)
val queryE = min(end, segmentTree.size - 1)
return _getSum(queryS, queryE, 0, segmentTree.size - 1)
}
private fun _getSum(queryS: Int, queryE: Int, segmentS: Int, segmentE: Int): Int {
return if (segmentS == segmentE) {
if (segmentS > queryS && segmentE <= queryE) {
segmentTree[segmentS]
} else {
0
}
} else {
val segmentM = (segmentS + segmentE) / 2
val left = _getSum(queryS, queryE, segmentS, segmentM)
val right = _getSum(queryS, queryE, segmentM + 1, segmentE)
left + right
}
}
companion object {
@JvmStatic
fun main(args: Array<String>) {
val sum = SubsetSum(arrayOf(1, 3, 5, 7, 9, 11))
println(sum.toString())
// println(sum.getSum(1, 3))
}
}
} | [
{
"class_path": "ghonix__Problems__25d4ba0/tree/segmentTree/SubsetSum.class",
"javap": "Compiled from \"SubsetSum.kt\"\npublic final class tree.segmentTree.SubsetSum {\n public static final tree.segmentTree.SubsetSum$Companion Companion;\n\n private int[] segmentTree;\n\n public tree.segmentTree.SubsetSu... |
jabrena__advent-of-code-2019__60f2e41/src/main/kotlin/day1/RocketEquation.kt | package day1
import kotlin.math.floor
/**
*
* --- Day 1: The Tyranny of the Rocket Equation ---
* Santa has become stranded at the edge of the Solar System while delivering presents to other planets! To accurately calculate his position in space, safely align his warp drive, and return to Earth in time to save Christmas, he needs you to bring him measurements from fifty stars.
*
* Collect stars by solving puzzles. Two puzzles will be made available on each day in the Advent calendar; the second puzzle is unlocked when you complete the first. Each puzzle grants one star. Good luck!
* The Elves quickly load you into a spacecraft and prepare to launch.
* At the first Go / No Go poll, every Elf is Go until the Fuel Counter-Upper. They haven't determined the amount of fuel required yet.
* Fuel required to launch a given module is based on its mass. Specifically, to find the fuel required for a module, take its mass, divide by three, round down, and subtract 2.
*
* For example:
*
* For a mass of 12, divide by 3 and round down to get 4, then subtract 2 to get 2.
* For a mass of 14, dividing by 3 and rounding down still yields 4, so the fuel required is also 2.
* For a mass of 1969, the fuel required is 654.
* For a mass of 100756, the fuel required is 33583.
*
* The Fuel Counter-Upper needs to know the total fuel requirement. To find it, individually calculate the fuel needed for the mass of each module (your puzzle input), then add together all the fuel values.
* What is the sum of the fuel requirements for all of the modules on your spacecraft?
*
*/
class RocketEquation {
private val FUEL_INPUT_FILE = "/day1/input.txt"
private val readInputFile = this::class.java.getResourceAsStream(FUEL_INPUT_FILE).bufferedReader().readLines()
/**
* Fuel required to launch a given module is based on its mass.
* Specifically, to find the fuel required for a module,
* take its mass, divide by three, round down, and subtract 2.
*/
val calculateFuel = { mass : Int -> (floor(mass / 3.0).toInt()) - 2 }
/**
* The Fuel Counter-Upper needs to know the total fuel requirement. To find it, individually calculate
* the fuel needed for the mass of each module (your puzzle input), then add together all the fuel values.
* What is the sum of the fuel requirements for all of the modules on your spacecraft?
*/
fun getTotalFuelRequeriment() : Int {
return readInputFile
.map { it.toInt() }
.map { calculateFuel(it) }
.sum()
}
}
| [
{
"class_path": "jabrena__advent-of-code-2019__60f2e41/day1/RocketEquation.class",
"javap": "Compiled from \"RocketEquation.kt\"\npublic final class day1.RocketEquation {\n private final java.lang.String FUEL_INPUT_FILE;\n\n private final java.util.List<java.lang.String> readInputFile;\n\n private final ... |
leokash__neuralnet__d243588/src/main/kotlin/com/nlkprojects/neuralnet/math/rational/Rational.kt | package com.nlkprojects.neuralnet.math.rational
import java.lang.RuntimeException
data class Rational(val numerator: Long, val denominator: Long): Number(), Comparable<Rational> {
constructor(num: Int): this(num, num)
constructor(num: Long): this(num, num)
constructor(num: Int, den: Int): this(num.toLong(), den.toLong())
operator fun div(that: Rational): Rational {
return from(numerator * that.denominator, denominator * that.numerator)
}
operator fun plus(that: Rational): Rational {
return from((numerator * that.denominator) + (denominator + that.numerator), denominator * that.denominator)
}
operator fun minus(that: Rational): Rational {
return from((numerator * that.denominator) - (denominator + that.numerator), denominator * that.denominator)
}
operator fun times(that: Rational): Rational {
return from(numerator * that.numerator, denominator * that.denominator)
}
override fun toInt(): Int {
return (if (denominator == 0L) 0L else numerator / denominator).toInt()
}
override fun toByte(): Byte {
return (if (denominator == 0L) 0L else numerator / denominator).toByte()
}
override fun toChar(): Char {
throw RuntimeException("Rational does not fit into a Char")
}
override fun toLong(): Long {
return if (denominator == 0L) 0L else numerator / denominator
}
override fun toShort(): Short {
return (if (denominator == 0L) 0L else numerator / denominator).toShort()
}
override fun toFloat(): Float {
return if (denominator == 0L) .0f else numerator / denominator.toFloat()
}
override fun toDouble(): Double {
return if (denominator == 0L) .0 else numerator / denominator.toDouble()
}
override fun compareTo(other: Rational): Int {
if (this == other)
return 0
val lhs = numerator * other.denominator
val rhs = denominator * other.numerator
return if (lhs < rhs) -1 else 1
}
override fun toString(): String {
return "($numerator/$denominator)"
}
companion object {
val ONE = Rational(1, 1)
val ZERO = Rational(0, 0)
val EMPTY = Rational(0, 1)
fun from(num: Float): Rational {
return if (num == .0f) return ZERO else from(num.toString())
}
fun from(num: Double): Rational {
return if (num == .0) return ZERO else from(num.toString())
}
fun from(lhs: Int, rhs: Int): Rational {
return from(lhs.toLong(), rhs.toLong())
}
fun from(lhs: Long, rhs: Long): Rational {
if (rhs == 0L)
return ZERO
if (lhs == 0L)
return Rational(0L, rhs)
val d = gcd(lhs, rhs)
return Rational(lhs / d, rhs / d)
}
private fun from(string: String): Rational {
val arr = string.split(".").map { it.trim() }
val clean = arr[1].dropLastWhile { it == '0' }
if (clean.isEmpty())
return Rational(arr[0].toLong(), 1L)
val num = clean.toLong()
val exc = arr[0].toLong()
val den = clean.indices.fold("1") { acc, _ -> "${acc}0" }.toLong()
val gcd = gcd(num, den)
val nDen = den / gcd
return Rational((exc * nDen) + (num / gcd), den / gcd)
}
fun gcd(lhs: Int, rhs: Int): Long {
return gcd(lhs.toLong(), rhs.toLong())
}
fun gcd(lhs: Long, rhs: Long): Long {
var a = lhs
var b = rhs
var t: Long
while (b != 0L) {
t = a % b
a = b
b = t
}
return if (a < 0L) -a else a
}
}
}
fun main() {
println(Rational.from(3/7.0).toDouble())
}
| [
{
"class_path": "leokash__neuralnet__d243588/com/nlkprojects/neuralnet/math/rational/RationalKt.class",
"javap": "Compiled from \"Rational.kt\"\npublic final class com.nlkprojects.neuralnet.math.rational.RationalKt {\n public static final void main();\n Code:\n 0: getstatic #12 ... |
BenjiDayan__hello_kotlin__cde700c/src/pj_euler/pj57.kt | package pj_euler
import kotlin.math.floor
import kotlin.math.sqrt
import kotlin.comparisons.minOf
import kotlin.comparisons.maxOf
import java.math.BigInteger
import kotlin.Boolean
//TODO pj 64
fun main(args: Array<String>) {
val frac = Fraction(BigInteger.valueOf(6), BigInteger.valueOf(4))
println(frac)
frac.reduce()
println(frac)
val frac2 = Fraction(BigInteger.valueOf(1),BigInteger.valueOf(3))
println(frac.add(frac2))
var idk = CFE(sqrt(2.0))
idk.convergents.add(1)
var num = 0
var outputs = mutableListOf(Fraction(BigInteger.valueOf(1),BigInteger.valueOf(4)))
for (i in 1..1000) {
println(i)
//idk.addNextConvergent() //this is inacurrate
idk.convergents.add(2)
val frac = idk.getFrac()
//println(frac)
if (frac.top.toString().length > frac.bot.toString().length) {
num += 1
outputs.add(frac)
println("$i frac was up")
}
}
println("Found $num fractions with top more digits than bot")
println(outputs.subList(0, 9))
println(outputs.lastIndex)
println(idk.convergents)
}
class CFE(val target: Double) {
var theta_i = target
var convergents: MutableList<Int> = mutableListOf()
fun addNextConvergent() {
convergents.add(floor(theta_i).toInt())
theta_i = 1/(theta_i - convergents.last())
}
fun add_many(rep_list: List<Int>, times: Int=1) {
for (i in 1..times) {
convergents.addAll(rep_list)
}
}
//Returns the approximation of target given by the convergents
fun getApproxDouble(): Double {
var result = convergents.last().toDouble()
for (conv in convergents.subList(0, convergents.lastIndex).reversed()) {
result = conv.toDouble() + (1/(result))
}
return result
}
fun getFrac(): Fraction {
var result = Fraction(BigInteger(convergents.last().toString()))
for (conv in convergents.subList(0, convergents.lastIndex).reversed()) {
result = Fraction(BigInteger(conv.toString())).add(result.flipped())
}
return result
}
}
class Fraction(var top: BigInteger, var bot: BigInteger = BigInteger.ONE) {
fun add(frac: Fraction): Fraction {
val topNew = top * frac.bot + bot * frac.top
val botNew = bot * frac.bot
val newFrac = Fraction(topNew, botNew)
newFrac.reduce()
return newFrac
}
fun reduce() {
val d = hcf(top, bot)
top = top/d
bot = bot/d
}
fun flipped(): Fraction {
return Fraction(bot, top)
}
override fun toString(): String{
return "$top/$bot"
}
}
fun hcf(a: BigInteger, b: BigInteger): BigInteger {
var a_i = maxOf(a, b)
var b_i = minOf(a, b)
while (!b_i.equals(BigInteger.ZERO)) {
val q = a_i/b_i
val r = a_i - q * b_i
a_i = b_i
b_i = r
}
return a_i
}
fun getFracExplicit(cfe: CFE): Fraction {
var result = Fraction(BigInteger(cfe.convergents.last().toString()))
println(result)
val lastIndex = cfe.convergents.lastIndex
for ((i, conv) in cfe.convergents.subList(0, lastIndex).reversed().withIndex()) {
println("conv index ${lastIndex-i-1}: $conv + 1/frac = ")
result = Fraction(BigInteger(conv.toString())).add(result.flipped())
println(result)
}
return result
} | [
{
"class_path": "BenjiDayan__hello_kotlin__cde700c/pj_euler/Pj57Kt.class",
"javap": "Compiled from \"pj57.kt\"\npublic final class pj_euler.Pj57Kt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc #9 // String args\n 3: invo... |
intresrl__kata-pulta__0531086/kotlin/src/Wardrobe/sal/SalWardrobe.kt | package wardrobe.sal
typealias Width = Int
typealias Price = Int
fun combinations(
goal: Width = 250,
availableSizes: List<Width> = listOf(50, 75, 100, 120)
): Set<List<Width>> =
if (goal == 0)
setOf(emptyList())
else
availableSizes
.filter { it <= goal }
.flatMap { width ->
val rest = goal - width
val partial = combinations(rest, availableSizes)
partial.map { it + width }
}
.map { it.sorted() }
.toSet()
fun Collection<List<Width>>.cheapest(
costs: Map<Width, Price>
): Pair<List<Width>, Price> =
map { it to (it priced costs) }
.minByOrNull { (_, cost) -> cost }!!
private infix fun List<Width>.priced(costs: Map<Width, Price>) =
sumOf { costs[it] ?: throw IllegalArgumentException("Invalid cost $it") }
fun main() {
val ikea = combinations()
ikea
.toList()
.sortedByDescending { it.maxOf { list -> list } }
.sortedByDescending { it.size }
.forEachIndexed { i, list ->
println("#${(i + 1).toString().padStart(3)}: $list")
}
val costs = mapOf(50 to 59, 75 to 62, 100 to 90, 120 to 111)
val (best, price) = ikea.cheapest(costs)
println("The cheapest combinations costs $price USD: $best")
}
| [
{
"class_path": "intresrl__kata-pulta__0531086/wardrobe/sal/SalWardrobeKt$main$$inlined$sortedByDescending$1.class",
"javap": "Compiled from \"Comparisons.kt\"\npublic final class wardrobe.sal.SalWardrobeKt$main$$inlined$sortedByDescending$1<T> implements java.util.Comparator {\n public wardrobe.sal.SalWar... |
vubogovich__kickstart__fc694f8/src/kickstart2022/g/CuteLittleButterfly.kt | package kickstart2022.g
// TODO
fun main() {
val inputFileName = "src/kickstart2022/g/CuteLittleButterfly.in"
java.io.File(inputFileName).takeIf { it.exists() }?.also { System.setIn(it.inputStream()) }
for (case in 1..readLine()!!.toInt()) {
val (n, e) = readLine()!!.split(' ').map { it.toInt() }
val f = Array(n) {
val (x, y, c) = readLine()!!.split(' ').map { it.toInt() }
Flower(x, y, c)
}.toList()
val res = findBestWay(0, 500, 1, f, e)
println("Case #$case: $res")
}
}
data class Flower(val x: Int, val y: Int, val c: Int)
fun findBestWay(x: Int, y: Int, d: Int, f: List<Flower>, e: Int): Int {
val g = f.filter { it.y <= y }
return g.mapIndexed { i, it ->
when {
g.size == 1 && it.x * d >= x * d -> it.c
g.size == 1 && it.x * d <= x * d && it.c > e -> it.c - e
g.size > 1 && it.x * d >= x * d -> it.c + findBestWay(it.x, it.y, d, g.filterIndexed { j, _ -> i != j }, e)
g.size > 1 && it.x * d <= x * d && it.c > e -> it.c - e + findBestWay(it.x, it.y, -d, g.filterIndexed { j, _ -> i != j }, e)
else -> 0
}
}.maxOrNull() ?: 0
}
| [
{
"class_path": "vubogovich__kickstart__fc694f8/kickstart2022/g/CuteLittleButterflyKt.class",
"javap": "Compiled from \"CuteLittleButterfly.kt\"\npublic final class kickstart2022.g.CuteLittleButterflyKt {\n public static final void main();\n Code:\n 0: ldc #8 // String s... |
vubogovich__kickstart__fc694f8/src/kickstart2022/c/AntsOnStick.kt | package kickstart2022.c
// TODO test set 2
fun main() {
val inputFileName = "src/kickstart2022/c/AntsOnStick.in"
java.io.File(inputFileName).takeIf { it.exists() }?.also { System.setIn(it.inputStream()) }
for (case in 1..readLine()!!.toInt()) {
val (n, len) = readLine()!!.split(' ').map { it.toInt() }
val ants = Array(n) {
val (p, d) = readLine()!!.split(' ').map { it.toInt() }
Ant(it + 1, p, if (d == 1) Direction.RIGHT else Direction.LEFT)
}
.sortedBy { it.pos }
.toMutableList()
var time = 0L
val drops = mutableListOf<Drop>()
while (ants.size > 0) {
while (ants.size > 0 && ants[0].dir == Direction.LEFT) {
drops.add(Drop(ants[0].num, time + ants[0].pos))
ants.removeAt(0)
}
while (ants.size > 0 && ants.last().dir == Direction.RIGHT) {
drops.add(Drop(ants.last().num, time + len - ants.last().pos))
ants.removeLast()
}
var minLen = Int.MAX_VALUE
for (i in 0 until ants.size - 1) {
if (ants[i].dir == Direction.RIGHT
&& ants[i + 1].dir == Direction.LEFT
&& ants[i + 1].pos - ants[i].pos < minLen
) {
minLen = ants[i + 1].pos - ants[i].pos
}
}
if (minLen < Int.MAX_VALUE) {
val move = (minLen + 1) / 2
for (k in ants.indices) {
ants[k].pos += if (ants[k].dir == Direction.RIGHT) move else -move
}
for (k in 0 until ants.size - 1) {
if (ants[k].pos > ants[k + 1].pos
&& ants[k].dir == Direction.RIGHT
&& ants[k + 1].dir == Direction.LEFT
) {
ants[k].pos--
ants[k].dir = Direction.LEFT
ants[k + 1].pos++
ants[k + 1].dir = Direction.RIGHT
}
}
for (k in 0 until ants.size - 1) {
if (ants[k].pos == ants[k + 1].pos
&& ants[k].dir == Direction.RIGHT
&& ants[k + 1].dir == Direction.LEFT
) {
ants[k].dir = Direction.LEFT
ants[k + 1].dir = Direction.RIGHT
}
}
time += move
}
}
val res = drops.sortedWith(compareBy(Drop::time, Drop::num))
.map { it.num }
.joinToString(" ")
println("Case #$case: $res")
}
}
enum class Direction {
LEFT,
RIGHT
}
data class Ant(var num: Int, var pos: Int, var dir: Direction)
data class Drop(val num: Int, val time: Long)
| [
{
"class_path": "vubogovich__kickstart__fc694f8/kickstart2022/c/AntsOnStickKt$main$$inlined$sortedBy$1.class",
"javap": "Compiled from \"Comparisons.kt\"\npublic final class kickstart2022.c.AntsOnStickKt$main$$inlined$sortedBy$1<T> implements java.util.Comparator {\n public kickstart2022.c.AntsOnStickKt$ma... |
vubogovich__kickstart__fc694f8/src/kickstart2020/h/BoringNumbers.kt | package kickstart2020.h
import kotlin.math.max
private val power5 = Array(20) { 1L }
fun main() {
val inputFileName = "src/kickstart2020/h/BoringNumbers.in"
java.io.File(inputFileName).takeIf { it.exists() }?.also { System.setIn(it.inputStream()) }
for (i in 1 until power5.size) power5[i] = power5[i - 1] * 5
for (case in 1..readLine()!!.toInt()) {
val (l, r) = readLine()!!.split(' ').map { it.toLong() }
val res = boring(r) - boring(l - 1)
println("Case #$case: $res")
}
}
private fun boring(k: Long): Long {
val s = k.toString()
return calculate(s) + (1 until s.length).map { power5[it] }.sum()
}
private fun calculate(s: String): Long {
return when (s.length) {
1 -> (s.toLong() + 1) / 2
2 -> s.toLong() / 20 * 5 + if (s[0].toInt() % 2 > 0) (s.substring(1).toLong()) / 2 + 1 else 0
else -> max(0, s.take(2).toInt() - 1).toString().let { if (it.length == 2) calculate(it) * power5[s.length - 2] else 0 } +
if (s[0].toInt() % 2 > 0 && s[1].toInt() % 2 == 0) calculate(s.substring(2)) else 0
}
}
| [
{
"class_path": "vubogovich__kickstart__fc694f8/kickstart2020/h/BoringNumbersKt.class",
"javap": "Compiled from \"BoringNumbers.kt\"\npublic final class kickstart2020.h.BoringNumbersKt {\n private static final java.lang.Long[] power5;\n\n public static final void main();\n Code:\n 0: ldc ... |
vubogovich__kickstart__fc694f8/src/kickstart2020/c/Candies.kt | package kickstart2020.c
// TODO still slow
fun main() {
val inputFileName = "src/kickstart2020/c/Candies.in"
java.io.File(inputFileName).takeIf { it.exists() }?.also { System.setIn(it.inputStream()) }
for (case in 1..readLine()!!.toInt()) {
val (_, q) = readLine()!!.split(' ').map { it.toInt() }
val a = readLine()!!.split(' ').map { it.toInt() }.toIntArray()
val divider = Math.min(a.size, 330)
val calcSection: (Int) -> Pair<Long, Long> = { section ->
var sum1 = 0L
var sum2 = 0L
var mul = 1
for (i in 0 until divider) {
sum1 += mul * (i + 1) * a[section * divider + i]
sum2 += mul * a[section * divider + i]
mul = -mul
}
sum1 to sum2
}
val cache = (0 until a.size / divider).map(calcSection).toTypedArray()
var result = 0L
repeat(q) {
val operation = readLine()!!.split(' ')
when (operation[0]) {
"Q" -> {
val (l, r) = operation.slice(1..2).map { it.toInt() }
val startSection = (l + divider - 2) / divider
val endSection = r / divider
var mul = 1 // ok since divider is even
if (((l - 1) % divider > 0) || (startSection >= endSection)) {
val r0 = if (startSection >= endSection) r else startSection * divider
for (i in l..r0) {
result += mul * (i - l + 1) * a[i - 1]
mul = -mul
}
}
for (section in startSection until endSection) {
result += mul * cache[section].let { it.first + (section * divider - l + 1) * it.second }
}
if ((r % divider > 0) && (startSection < endSection)) {
val l0 = endSection * divider + 1
for (i in l0..r) {
result += mul * (i - l + 1) * a[i - 1]
mul = -mul
}
}
}
"U" -> {
val (x, v) = operation.slice(1..2).map { it.toInt() }
val section = (x - 1) / divider
a[x - 1] = v
cache[section] = calcSection(section)
}
}
}
println("Case #$case: $result")
}
}
| [
{
"class_path": "vubogovich__kickstart__fc694f8/kickstart2020/c/CandiesKt.class",
"javap": "Compiled from \"Candies.kt\"\npublic final class kickstart2020.c.CandiesKt {\n public static final void main();\n Code:\n 0: ldc #8 // String src/kickstart2020/c/Candies.in\n ... |
wrabot__competitive-tools__fd2da26/src/main/kotlin/tools/graph/FloydWarshall.kt | package tools.graph
class FloydWarshall(size: Int, weights: Map<Pair<Int, Int>, Double>) {
val indices = 0 until size
val dist = Array(size) { DoubleArray(size) { Double.POSITIVE_INFINITY } }
val prev = Array(size) { Array<Int?>(size) { null } }
override fun toString() = dist.toList().map { it.toList() }.toString()
init {
weights.forEach { (u, v), w ->
dist[u][v] = w
prev[u][v] = u
}
for (v in indices) {
dist[v][v] = 0.0
prev[v][v] = v
}
for (k in indices)
for (i in indices)
for (j in indices) {
val d = dist[i][k] + dist[k][j]
if (dist[i][j] > d) {
dist[i][j] = d
prev[i][j] = prev[k][j]
}
}
}
fun path(u: Int, v: Int) = path(u, v, emptyList())
private tailrec fun path(u: Int, v: Int?, path: List<Int>): List<Int> = when {
v == null -> emptyList()
u == v -> path
else -> path(u, prev[u][v], listOf(v) + path)
}
}
| [
{
"class_path": "wrabot__competitive-tools__fd2da26/tools/graph/FloydWarshall.class",
"javap": "Compiled from \"FloydWarshall.kt\"\npublic final class tools.graph.FloydWarshall {\n private final kotlin.ranges.IntRange indices;\n\n private final double[][] dist;\n\n private final java.lang.Integer[][] pre... |
wrabot__competitive-tools__fd2da26/src/main/kotlin/tools/graph/ShortPath.kt | package tools.graph
fun <Node : Any> shortPath(
start: Node,
end: Node,
cost: (origin: Node, destination: Node) -> Double = { _, _ -> 1.0 },
estimatedEndCost: (Node) -> Double = { 0.0 }, // A*
neighbors: (Node) -> List<Node>
) = shortPath(start, isEnd = { this == end }, cost, estimatedEndCost, neighbors)
fun <Node : Any> shortPath(
start: Node,
isEnd: Node.() -> Boolean,
cost: (origin: Node, destination: Node) -> Double = { _, _ -> 1.0 },
toEndMinimalCost: (Node) -> Double = { 0.0 }, // A*
neighbors: Node.() -> List<Node>
): List<Node> {
val spStart = ShortPathNode(start, 0.0, toEndMinimalCost(start), true)
val spNodes = mutableMapOf(start to spStart)
val todo = mutableListOf(spStart)
while (true) {
val currentSPNode = todo.removeFirstOrNull() ?: return emptyList()
currentSPNode.todo = false
if (currentSPNode.node.isEnd())
return generateSequence(currentSPNode) { it.predecessor }.map { it.node }.toList().reversed()
neighbors(currentSPNode.node).forEach { nextNode ->
val newFromStartCost = currentSPNode.fromStartCost + cost(currentSPNode.node, nextNode)
val nextSPNode = spNodes[nextNode]
when {
nextSPNode == null -> {
val spNode = ShortPathNode(
nextNode,
newFromStartCost,
newFromStartCost + toEndMinimalCost(nextNode),
true
)
spNode.predecessor = currentSPNode
spNodes[nextNode] = spNode
todo.add(-todo.binarySearch(spNode) - 1, spNode)
}
newFromStartCost < nextSPNode.fromStartCost -> {
var toIndex = todo.size
if (nextSPNode.todo) {
toIndex = todo.binarySearch(nextSPNode)
todo.removeAt(toIndex)
}
nextSPNode.predecessor = currentSPNode
nextSPNode.minimalCost -= nextSPNode.fromStartCost - newFromStartCost
nextSPNode.fromStartCost = newFromStartCost
nextSPNode.todo = true
todo.add(-todo.binarySearch(nextSPNode, toIndex = toIndex) - 1, nextSPNode)
}
}
}
}
}
private data class ShortPathNode<Node : Any>(
val node: Node,
var fromStartCost: Double,
var minimalCost: Double,
var todo: Boolean
) : Comparable<ShortPathNode<Node>> {
var predecessor: ShortPathNode<Node>? = null
override fun compareTo(other: ShortPathNode<Node>): Int {
val compare = minimalCost.compareTo(other.minimalCost)
return if (compare != 0) compare else id.compareTo(other.id)
}
private val id = nextId++
companion object {
private var nextId = Int.MIN_VALUE
}
}
| [
{
"class_path": "wrabot__competitive-tools__fd2da26/tools/graph/ShortPathKt.class",
"javap": "Compiled from \"ShortPath.kt\"\npublic final class tools.graph.ShortPathKt {\n public static final <Node> java.util.List<Node> shortPath(Node, Node, kotlin.jvm.functions.Function2<? super Node, ? super Node, java.... |
wrabot__competitive-tools__fd2da26/src/main/kotlin/tools/math/Modulo.kt | package tools.math
fun Long.times(multiplier: Long, modulo: Long): Long {
if (this < 0) error("negative multiplicand")
if (multiplier < 0) error("negative multiplier")
if (modulo < 0) error("negative modulo")
var res = 0L
var a = this % modulo
var b = multiplier % modulo
while (true) {
if (b and 1L > 0L) res = (res + a) % modulo
b = b shr 1
if (b == 0L) return res
a = a shl 1
if (a < 0) error("overflow")
a %= modulo
}
}
fun Long.inv(modulo: Long): Long = inverse(this, modulo, 1, 0).let { if (it < 0) it + modulo else it }
private tailrec fun inverse(v: Long, n: Long, s: Long, t: Long): Long =
if (v == 1L) s else inverse(n % v, v, t - n / v * s, s)
fun chineseRemainder(input: List<Pair<Long, Long>>): Long {
val np = input.fold(1L) { acc, i -> acc * i.second }
return input.fold(0L) { acc, (v, n) -> (np / n).let { (acc + v.times(it.inv(n), np).times(it, np)).mod(np) } }
}
| [
{
"class_path": "wrabot__competitive-tools__fd2da26/tools/math/ModuloKt.class",
"javap": "Compiled from \"Modulo.kt\"\npublic final class tools.math.ModuloKt {\n public static final long times(long, long, long);\n Code:\n 0: lload_0\n 1: lconst_0\n 2: lcmp\n 3: ifge 19\n... |
age-series__ElectricalAge2__86d843f/src/main/kotlin/org/eln2/mc/data/SegmentTree.kt | package org.eln2.mc.data
/**
* Represents the numeric range of a segment.
* @param min The lower boundary of this segment.
* @param max The upper boundary of this segment.
* [min] must be smaller than [max].
* */
data class ClosedInterval(val min: Double, val max: Double) {
val range get() = min..max
init {
if (min >= max) {
error("Invalid interval $min -> $max")
}
}
fun contains(point: Double) = point in range
}
data class SegmentTreeNode<T>(
val range: ClosedInterval,
val data: T?,
private val l: SegmentTreeNode<T>?,
private val r: SegmentTreeNode<T>?,
) {
constructor(range: ClosedInterval, segment: T?) : this(range, segment, null, null)
/**
* @return True if this segment's [range] contains the [point]. Otherwise, false.
* */
fun contains(point: Double): Boolean {
return range.contains(point)
}
/**
* Recursively queries until a leaf node containing [point] is found.
* @param point A point contained within a segment. If this segment does not contain the point, an error will be produced.
* @return The data value associated with the leaf node that contains [point]. An error will be produced if segment continuity is broken (parent contains point but the child nodes do not).
* */
fun query(point: Double): T? {
if (!contains(point)) {
return null
}
val left = l
val right = r
if (left != null && left.contains(point)) {
return left.query(point)
}
if (right != null && right.contains(point)) {
return right.query(point)
}
return data
}
}
class SegmentTree<T>(private val root: SegmentTreeNode<T>) {
fun queryOrNull(point: Double): T? {
if (!root.contains(point)) {
return null
}
return root.query(point)
}
/**
* Finds the segment with the specified range. Time complexity is O(log n)
* */
fun query(point: Double): T {
return root.query(point) ?: error("$point not found")
}
}
class SegmentTreeBuilder<TSegment> {
private data class PendingSegment<T>(val segment: T, val range: ClosedInterval)
private val pending = ArrayList<PendingSegment<TSegment>>()
/**
* Inserts a segment into the pending set. If its range is not sorted with the previously inserted segments,
* [sort] must be called before attempting to [build].
* */
fun insert(segment: TSegment, range: ClosedInterval) {
pending.add(PendingSegment(segment, range))
}
/**
* Sorts the segments by range.
* */
fun sort() {
pending.sortBy { it.range.min }
}
/**
* Builds a [SegmentTree] from the pending set.
* If segment continuity is broken, an error will be produced.
* */
fun build(): SegmentTree<TSegment> {
if (pending.isEmpty()) {
error("Tried to build empty segment tree")
}
/* if (pending.size > 1) {
for (i in 1 until pending.size) {
val previous = pending[i - 1]
val current = pending[i]
if (previous.range.max != current.range.min) {
error("Segment tree continuity error")
}
}
}*/
return SegmentTree(buildSegment(0, pending.size - 1))
}
private fun buildSegment(leftIndex: Int, rightIndex: Int): SegmentTreeNode<TSegment> {
if (leftIndex == rightIndex) {
val data = pending[leftIndex]
return SegmentTreeNode(data.range, data.segment)
}
val mid = leftIndex + (rightIndex - leftIndex) / 2
return SegmentTreeNode(
ClosedInterval(pending[leftIndex].range.min, pending[rightIndex].range.max),
data = null,
l = buildSegment(leftIndex, mid),
r = buildSegment(mid + 1, rightIndex)
)
}
}
| [
{
"class_path": "age-series__ElectricalAge2__86d843f/org/eln2/mc/data/SegmentTree.class",
"javap": "Compiled from \"SegmentTree.kt\"\npublic final class org.eln2.mc.data.SegmentTree<T> {\n private final org.eln2.mc.data.SegmentTreeNode<T> root;\n\n public org.eln2.mc.data.SegmentTree(org.eln2.mc.data.Segm... |
ldk123456__Introduction__8dc6bff/3/src/symbol/Symbol.kt | package symbol
fun main(args: Array<String>) {
val list = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
//总数操作符
println("=====总数操作符=====")
println("list.any{it > 10}: ${list.any { it > 10 }}")
println("list.all{it in 1..10}: ${list.all { it in 1..10 }}")
println("list.none { it > 10 }: ${list.none { it > 10 }}")
println("list.count { it in 1..10 }: ${list.count { it in 1..10 }}")
println("list.sumBy { it * it }: ${list.sumBy { it * it }}")
println("list.min(): ${list.min()}")
println("list.minBy { it * it }: ${list.minBy { it * it }}")
//过滤操作符
println("=====过滤操作符=====")
println("list.filter { it != 5 }:${list.filter { it != 5 }}")
println("list.filterNot { it == 5 }: ${list.filterNot { it == 5 }}")
println("list.filterNotNull(): ${list.filterNotNull()}")
println("list.take(4): ${list.take(4)}")
println("list.takeLast(4): ${list.takeLast(4)}")
println("list.takeLastWhile { it !!< 5 }: ${list.takeLastWhile { it !!< 5 }}")
println("list.drop(4):${list.drop(4)}")
println("list.dropLastWhile { it == 4 }: ${list.dropLastWhile { it == 4 }}")
println("list.dropWhile { it !!< 4 }: ${list.dropWhile { it !!< 4 }}")
println("list.slice(listOf(1, 2, 3)): ${list.slice(listOf(1, 2, 3))}")
//映射操作符
println("=====映射操作符=====")
val list1 = listOf(1, 2, 3, 4, 5)
val list2 = listOf(6, 7, 8, 9, 10)
println(list1.map { it + 1 })
println(list1.mapIndexed { index, i -> index * i })
println(list1.mapNotNull { it + 5 })
println(listOf(list1, list2).flatMap { it -> it })
println(listOf(list1.groupBy { if (it > 3) "big" else "small" }))
//顺序操作符
println("=====顺序操作符=====")
val list3 = listOf(1, 5, 9, 7, 26, 74, 32, 47, 41, 42, 6)
println("list.reversed(): ${list3.reversed()}")
println("list.sorted(): ${list3.sorted()}")
println("list.sortedBy { it % 2 }: ${list3.sortedBy { it % 2 }}")
println("list.sortedDescending(): ${list3.sortedDescending()}")
println("list.sortedByDescending { it % 2 }: ${list3.sortedByDescending { it % 2 }}")
//生产操作符
println("=====生产操作符=====")
println("list1.zip(list2): ${list1.zip(list2)}")
println("list1.zip(list2){it1, it2 -> it1 + it2}: ${list1.zip(list2){it1, it2 -> it1 + it2}}")
println("list1.partition { it > 3 }: ${list1.partition { it > 3 }}")
println("list1.plus(list2): ${list1.plus(list2)}")
println("listOf(Pair(1, 2), Pair(3, 4)).unzip(): ${listOf(Pair(1, 2), Pair(3, 4)).unzip()}")
//元素操作符
println("=====元素操作符=====")
println("list.contains(14): ${list.contains(14)}")
println("list.elementAt(4): ${list.elementAt(4)}")
println("list.elementAtOrElse(14, {it + 3}): ${list.elementAtOrElse(14, {it + 3})}")
println("list.elementAtOrNull(14): ${list.elementAtOrNull(14)}")
println("list.first(): ${list.first()}")
println("list.first { it % 3 == 0 }: ${list.first { it % 3 == 0 }}")
println("list.firstOrNull{ it > 14 }: ${list.firstOrNull{ it > 14 }}")
println("list.indexOf(5): ${list.indexOf(5)}")
println("list.indexOfFirst { it == 14 }: ${list.indexOfFirst { it == 14 }}")
println("list.lastOrNull { it == 8 }: ${list.lastOrNull { it == 8 }}")
println("list.single { it == 8 }: ${list.single { it == 8 }}")
println("list.singleOrNull { it == 8 }: ${list.singleOrNull { it == 8 }}")
} | [
{
"class_path": "ldk123456__Introduction__8dc6bff/symbol/SymbolKt.class",
"javap": "Compiled from \"Symbol.kt\"\npublic final class symbol.SymbolKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc #9 // String args\n 3: inv... |
DinaTuesta27__kotlin__ef8ce29/TallerRecursion/src/ean/estructuradedatos/taller/TallerRecursion.kt | package ean.estructuradedatos.taller
/**
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Universidad EAN (Bogotá - Colombia)
* Departamento de Sistemas
* Faculta de Ingeniería
*
* Taller Funciones Recursivas
* Fecha: 18 de abril de 2023
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
//Realizado por: <NAME> y <NAME>
import kotlin.math.pow
import kotlin.math.sqrt
/**
* Halla el factorial del número entero n
* n! = n * (n-1) * (n-2) * ... * 2 * 1
*/
fun factorial(n: Int): Int =
when(n){
1->1
else-> factorial(n-1)*n
}
/**
* Halla el n-ésimo término de la serie de fibonacci
*/ //Recursión binaria
fun fibonacci(n: Int): Int =
when(n){
1,2->1
else-> fibonacci(n-1) + fibonacci(n-2)
}
/**
* Permite determinar el término n,m del triángulo de Pascal
* n = fila, m = término
*/
fun pascal(n: Int, m: Int): Int {
if (m==1 || m==n+1) {
return 1
}
return pascal (n-1,m) + pascal(n-1,m-1)
}
/**
* Halla el valor de x^y =
* si y es cero entonces retorne 1
* sino retorne x multiplicado por elevar x a la y - 1
*/
fun elevar(x: Int, y: Int): Int =
when(y){
0->1
else->x* elevar(x,y-1)
}
/**
* Halla la suma de todos los números enteros entre 1 y n
*/
fun sumatoria(n: Int): Int =
when (n){
1->1
else-> sumatoria(n-1) + n
}
/**
* Halla la suma de los cuadrados de los números de 1 hasta n
*/
fun sumaCuadrados(n: Int): Int =
when(n) {
0->0
else-> sumaCuadrados(n-1) + (n*n)
}
/**
* Hallar el valor de la sumatoria de 1/(2i+1) desde 1 hasta n
*/
fun serie(n: Int): Double =
when(n) {
1->1.0/3.0
else-> serie(n-1) + 1.0/(2*n+1.0)
}
/**
* Hallar el valor de la sumatoria de 1 hasta n de i/(i^2+1)
*/
fun sumatoria2(n: Int): Double =
when (n){
1->1.0/2.0
else-> sumatoria2(n-1) + n/((n*n)+1.0)
}
/**
* Permite saber la cantidad de digitos que posee un número entero positivo n
*/
fun contarDigitos(n: Int): Int =
when(n) {
in 0 .. 9->1 //Tiene un dígito
else->{
val resto= n / 10 //le quito el último dígito
val c= contarDigitos(resto)
c+1 //le sumo uno para tenerelos completos
}
}
/**
* Permite saber el número de ceros que tiene un número.
* Por ejemplo: 2020 tiene dos ceros.
*/
fun numeroDeCeros(n: Int): Int =
if (n < 10) {
if (n == 0) {
1
} else {
0
}
} else {
val ult=n%10
val resto=n/10
val c= numeroDeCeros(resto)
if (ult == 0) {
c + 1
} else {
c
}
}
/**
* Permite hallar la suma de los dígitos de un número entero positivo n
*/
fun sumarDigitos(n: Int): Int =
when(n){
0->0
in 0 .. 9->n
else-> {
val ult = n % 10
val resto = n / 10
val c = sumarDigitos(resto)
c + ult
}
}
/**
* Un número entero positivo en múltiplo de 3 si:
* - tiene una cifra y es 0, 3, 6, o 9
* - tiene más de una cifra y la suma de sus dígitos es múltiplo de 3 (recursion)
* - en cualquier otro caso, el número no es múltiplo de 3
*
* - NO PUEDEN USAR LA OPERACIÓN MÓDULO (%) PARA SABER SI ES DIVISIBLE
*/
fun esMultiploDe3(n: Int): Boolean {
if (n == 0 || n == 3 || n == 6 || n == 9) {
return true
} else if (n > 10) {
val m = (sumarDigitos(n))
if (esMultiploDe3(m)==true) {
return true
}
}
return false
}
/**
* Cuenta el número de dígitos pares que tiene un número entero positivo >= 1
*/
fun cantidadDigitosPares(n: Int): Int =
if (n < 10) {
if (n == 0 || n==2 || n==4 || n == 6 || n==8 ) {
1
} else {
0
}
} else {
val ult=n%10
val resto=n/10
val c= cantidadDigitosPares(resto)
if (ult == 0 || ult==2 || ult==4 || ult == 6 || ult==8) {
c + 1
} else {
c
}
}
/**
* Determina si el número dado es binario o no.
* Los números binarios solo contienen los dígitos 1 y 0
* Por ejemplo: el numero 100011110 es binario, pero 231 no lo es
*/
fun esNumeroBinario(n: Int): Boolean {
if (n==0 ||n==1){
return true
}
if (n%10 > 1) {
return false
}
return esNumeroBinario(n/10)
}
/**
* Permite saber si el número dado posee el dígito indicado
*/
fun poseeDigito(n: Int, digito: Int): Boolean {
/*
si el numero n posee un solo digito, entonces
si n y el digito son iguales -> retorne true sino retorne false
sino si el número n tiene más de un dígito, entonces
si el ultimo dígito del número n es igual al dígito, entonces
listo, lo encontramos, retorne true
sino
halle el resto de n
mire si el resto de n posee el dígito indicado
*/
if (n in 0 .. 9) {
return n == digito
}else {
val ult = n % 10
if (ult == digito) {
return true
} else {
val sobra = n / 10
return poseeDigito(sobra, digito)
}
}
}
/**
* Retorna el dígito más grande que hace parte del número n
* Ejemplo: el dígito más grande del númer 381704 es el 8
* si el número tiene un solo dígito, el digito más grande es el numero
* sino
* halle el resto y el último
* halla el digito mas grande del resto
* retorne el mayor entre el último y el dígito más grande del resto
*/
fun digitoMasGrande(n: Int): Int {
if (contarDigitos(n) == 1) {
return n
} else {
val ult=n%10
val resto=n/10
var digitoMasGrande=digitoMasGrande(resto)
if (digitoMasGrande>ult) {
return digitoMasGrande
}
return ult
}
}
/**
* Halla el máximo común divisor entre m y n, utilizando el método de
* Euclides.
*/
fun mcd(m: Int, n: Int): Int =
when(n) {
0->m
else-> mcd(n,m%n)
}
/**
* Imprimir cada elemento de la lista, pero de manera recursiva
*/
fun <T> imprimirLista(lista: List<T>) {
if (lista.isEmpty()) { //si está vacía
println()
} else {
val prim = lista.first()
val resto=lista.subList(1,lista.size)//Desde la posición uno hasta la última
println(prim) //Imprimir
imprimirLista(resto)
}
}
/**
* Obtiene recursivamente la lista de los dígitos del número entero positivo n
* Ejemplo: digitos(351804) == [3, 5, 1, 8, 0, 4]
*/
fun digitos(n: Int): List<Int> {
if (n in 0 .. 9) {
return listOf(n)
}else{
val ult=n%10
val resto=n/10
var lst= digitos(resto)
lst += ult
return lst
}
}
/**
* Dado un número entero positivo >= 0, retorna una lista con la representación binaria
* del número dado.
* Ejemplo: convertirDecimalBinario(231) = List(1, 1, 0, 0, 1, 1, 1, 1, 1, 1)
*/
fun convertirDecimalBinario(n: Int): List<Int> {
if (n > 1) {
val ult = n % 2
val resto = n / 2
var deci = convertirDecimalBinario(resto)
deci += ult
return deci
}else if (n == 0) {
return listOf(0)
}
return listOf(1)
}
/**
* Determina cuantas palabras en la lista son verbos.
* Recursivamente.
*/
fun contarVerbos(palabras: List<String>): Int {
if (palabras.isEmpty()) { //si está vacía
return 0
} else {
var prim= palabras.first() //se toma el primer elemento
val resto= palabras.subList(1,palabras.size) //que "recora" la lista desde el 1 hasta el final
var sonVerbos= contarVerbos(resto) //que obtenga los verbos del resto
if (prim.endsWith("ar") || prim.endsWith("er") || prim.endsWith("ir")) {
sonVerbos += 1 // si el prim es un verbo que lo sume al resto
}
return sonVerbos
}
}
/**
* Recursion con listas: Hallar la suma de los números pares de la lista que se recibe
* como parámetro.
* Ejemplo: sumarParesLista([40, 21, 8, 31, 6]) == 54
*/
fun sumarParesLista(lista: List<Int>): Int {
if (lista.isEmpty()) { //si está vacía
return 0
} else {
val prim= lista.first()
val resto= lista.subList(1,lista.size)
var sum= sumarParesLista(resto)
if (prim%2==0){
sum+=prim
}
return sum
}
}
/**
* Recursión con listas: construir una función recursiva que retorne la posición del elemento en la lista
* Si la lista está vacía, retorne -1. No se puede usar indexOf o lastIndexOf
*/
fun buscarElementoEnUnaLista(lista: List<Int>, elem: Int): Int {
if (lista.isEmpty()) { //si está vacía
return -1
} else {
var prim= lista.first()
val resto= lista.subList(1,lista.size)
var busc= buscarElementoEnUnaLista(resto,elem)
if (prim == elem) {
return 0
}else if (busc == -1) {
return -1
} else {
return busc + 1
}
}
}
/**
* Traduce los diversos dígitos de la lista a un número entero
* Ejemplo: convertirListaDigitosNumero([3, 4, 1, 7, 9]) == 34179
*/
fun convertirListaDigitosNumero(digitos: List<Int>): Int {
if (digitos.isEmpty()) {
return 0
} else {
val ult = digitos.last()
val resto = digitos.subList(0, digitos.size - 1) //para llegar antes del último
return ult + 10 * convertirListaDigitosNumero(resto) // es para mover el valor en el que esta hasta el último
}
}
/**
* Función genérica y recursiva que permite saber si un elemento está dentro
* de la lista. No debe usarse la función indexOf o contains. Debe ser
* recursiva. Para buscar un elemento hay que tener en cuenta
* - si la lista está vacía, el elemento no está
* - si el primero de la lista es igual al elemento, retornamos true (el elemento está)
* - sino es igual al primero, entonces hay que ver si el elemento está en el resto de la lista
*/
fun <T> existeElemento(lista: List<T>, elem: T): Boolean {
if (lista.isEmpty()) { //si está vacía
return false
} else {
var prim= lista.first()
val resto= lista.subList(1,lista.size)
var exis= existeElemento(resto,elem)
if (prim == elem) {
return true
}else if (exis == true) {
return true
} else {
return false
}
}
}
/** Escribir una función recursiva que, sin usar pilas ni colas
* ni ninguna otra lista, obtenga la misma lista, pero invertida
*/
fun invertirLista(lista: List<Char>): List<Char> {
if (lista.isEmpty()) {
return lista
} else {
val ult = lista.last()
val resto = lista.subList(0, lista.size - 1) //toma del primero hasta el anterior al último
return listOf(ult) + invertirLista(resto)
}
}
/**
* Una palabra es palíndrome si se lee igual de izquierda a derecha y de derecha
* a izquierda. Esta función recibe la palabra (sin espacios) y de forma recursiva
* determina si la palabra es palíndrome.
*/
fun esPalindrome(palabra: String): Boolean =
if (palabra.length <= 1) {
true
} else {
val primera = palabra.first()
val ultima = palabra.last()
if (primera == ultima) {
esPalindrome(palabra.substring(1, palabra.length - 1))// substring invierte las letras desde la pos 1 hasta la anterior a la última
} else {
false
}
}
/**
* Recursividad con listas. Escriba una función recursiva
* Obtiene el número más grande de la lista. Si la lista está vacía retorne el número
* entero más pequeño.
*/
fun mayorDeUnaLista(lista: List<Int>): Int {
if (lista.isEmpty()) {
return Int.MIN_VALUE
} else {
val prim = lista.first()
val resto = lista.subList(1, lista.size)
val mayorResto = mayorDeUnaLista(resto)
if (prim > mayorResto) {
return prim
} else {
return mayorResto
}
}
}
/**
* Una clase auxiliar
*/
data class Punto(val x: Int, val y: Int) {
fun distanciaAlOrigen(): Double = sqrt(x.toDouble().pow(2) + y.toDouble().pow(2))
}
/**
* Recursivamente, obtener una lista con aquellos puntos que están en el origen o
* que hacen parte del primer cuadrante.
*/
fun puntosPrimerCuadrante(puntos: List<Punto>): List<Punto> {
if (puntos.isEmpty()) {
return listOf()
} else {
val prim=puntos.first()
val resto = puntos.subList(1, puntos.size)
var c= puntosPrimerCuadrante(resto)
if (prim.x >= 0 && prim.y >= 0) {
return listOf(prim) + c
} else {
return c
}
}
}
/**
* Recursivamente, obtiene el punto que está más lejano del origen.
* Si la lista esta vacía, retorne null
* Si la lista tiene un solo elemento, retorne ese elemento
* si la lista tiene más de un elemento, tome el primer elemento y
* compárelo con el punto más lejano del resto de la lista.
*/
fun puntoMasLejano(puntos: List<Punto>): Punto? {
if (puntos.isEmpty()) {
return null
} else if(puntos.size==1) {
return puntos[0]
}else{
val prim=puntos.first()
val resto = puntos.subList(1, puntos.size)
var m= puntoMasLejano(resto)
if (m==null) {
return null
} else {
if (prim.distanciaAlOrigen() > m.distanciaAlOrigen()) {
return prim
} else {
return m
}
}
}
}
| [
{
"class_path": "DinaTuesta27__kotlin__ef8ce29/ean/estructuradedatos/taller/TallerRecursionKt.class",
"javap": "Compiled from \"TallerRecursion.kt\"\npublic final class ean.estructuradedatos.taller.TallerRecursionKt {\n public static final int factorial(int);\n Code:\n 0: iload_0\n 1: iconst... |
fredyw__leetcode__a59d77c/src/main/kotlin/leetcode/Problem2013.kt | package leetcode
import kotlin.math.abs
/**
* https://leetcode.com/problems/detect-squares/
*/
class Problem2013 {
class DetectSquares() {
private val map = mutableMapOf<Int, MutableMap<Int, Int>>()
fun add(point: IntArray) {
val x = point[0]
val y = point[1]
val m = map[x] ?: mutableMapOf()
m[y] = (m[y] ?: 0) + 1
map[x] = m
}
fun count(point: IntArray): Int {
var count = 0
val x1 = point[0]
val y1 = point[1]
for ((y2, _) in map[x1] ?: mapOf<Int, Int>()) {
val length = abs(y1 - y2)
if (length == 0) {
continue
}
count += numSquares(x1 = x1, y1 = y1, x2 = x1 - length, y2 = y2)
count += numSquares(x1 = x1, y1 = y1, x2 = x1 + length, y2 = y2)
}
return count
}
private fun numSquares(x1: Int, y1: Int, x2: Int, y2: Int): Int {
val p1 = if (map[x1] != null) map[x1]!![y2] ?: 0 else 0
val p2 = if (map[x2] != null) map[x2]!![y1] ?: 0 else 0
val p3 = if (map[x2] != null) map[x2]!![y2] ?: 0 else 0
return p1 * p2 * p3
}
}
}
| [
{
"class_path": "fredyw__leetcode__a59d77c/leetcode/Problem2013.class",
"javap": "Compiled from \"Problem2013.kt\"\npublic final class leetcode.Problem2013 {\n public leetcode.Problem2013();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V... |
fredyw__leetcode__a59d77c/src/main/kotlin/leetcode/Problem1718.kt | package leetcode
/**
* https://leetcode.com/problems/construct-the-lexicographically-largest-valid-sequence/
*/
class Problem1718 {
fun constructDistancedSequence(n: Int): IntArray {
return constructDistancedSequence(n, 0, HashSet(), IntArray(n * 2 - 1)).array
}
private class Answer(val found: Boolean, val array: IntArray)
private fun constructDistancedSequence(n: Int, index: Int,
visited: MutableSet<Int>, array: IntArray): Answer {
if (visited.size == n) {
return Answer(true, array)
}
if (array[index] != 0) {
return constructDistancedSequence(n, index + 1, visited, array)
}
for (i in n downTo 1) {
if (i in visited) {
continue
}
if (i == 1) {
array[index] = i
} else {
if (index + i >= array.size || array[index + i] != 0) {
continue
}
array[index] = i
array[index + i] = i
}
visited += i
val answer = constructDistancedSequence(n, index + 1, visited, array)
if (answer.found) {
return answer
}
visited -= i
array[index] = 0
if (i != 1) {
array[index + i] = 0
}
}
return Answer(false, array)
}
}
| [
{
"class_path": "fredyw__leetcode__a59d77c/leetcode/Problem1718$Answer.class",
"javap": "Compiled from \"Problem1718.kt\"\nfinal class leetcode.Problem1718$Answer {\n private final boolean found;\n\n private final int[] array;\n\n public leetcode.Problem1718$Answer(boolean, int[]);\n Code:\n 0: ... |
fredyw__leetcode__a59d77c/src/main/kotlin/leetcode/Problem2192.kt | package leetcode
import java.util.*
/**
* https://leetcode.com/problems/all-ancestors-of-a-node-in-a-directed-acyclic-graph/
*/
class Problem2192 {
fun getAncestors(n: Int, edges: Array<IntArray>): List<List<Int>> {
val adjList = reverse(n, edges)
val answer = mutableListOf<List<Int>>()
for (i in 0 until n) {
val ancestors = mutableListOf<Int>()
val visited = BooleanArray(n)
getAncestors(i, adjList, ancestors, visited)
ancestors.sort()
answer += ancestors
}
return answer
}
private fun reverse(n: Int, edges: Array<IntArray>): Array<MutableList<Int>> {
val adjList = Array<MutableList<Int>>(n) { mutableListOf() }
for (edge in edges) {
val from = edge[0]
val to = edge[1]
adjList[to].add(from)
}
return adjList
}
private fun getAncestors(i: Int, adjList: Array<MutableList<Int>>,
ancestors: MutableList<Int>, visited: BooleanArray) {
visited[i] = true
for (adjacent in adjList[i]) {
if (!visited[adjacent]) {
ancestors += adjacent
getAncestors(adjacent, adjList, ancestors, visited)
}
}
}
}
| [
{
"class_path": "fredyw__leetcode__a59d77c/leetcode/Problem2192.class",
"javap": "Compiled from \"Problem2192.kt\"\npublic final class leetcode.Problem2192 {\n public leetcode.Problem2192();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V... |
fredyw__leetcode__a59d77c/src/main/kotlin/leetcode/Problem1514.kt | package leetcode
import java.util.PriorityQueue
/**
* https://leetcode.com/problems/path-with-maximum-probability/
*/
class Problem1514 {
fun maxProbability(n: Int, edges: Array<IntArray>, succProb: DoubleArray, start: Int,
end: Int): Double {
val adjList = buildAdjList(n, edges, succProb)
val dist = DoubleArray(n) { Double.NEGATIVE_INFINITY }
val queue = PriorityQueue<Node>()
queue += Node(start, dist[start])
while (queue.isNotEmpty()) {
val node = queue.remove()
for (edge in adjList[node.n]) {
val prob = if (dist[edge.from] == Double.NEGATIVE_INFINITY) edge.prob
else dist[edge.from] * edge.prob
if (prob > dist[edge.to]) {
dist[edge.to] = prob
queue += Node(edge.to, prob)
}
}
}
return if (dist[end] == Double.NEGATIVE_INFINITY) 0.0 else dist[end]
}
private fun buildAdjList(n: Int, edges: Array<IntArray>, succProb: DoubleArray): Array<MutableList<Edge>> {
val adjList = Array(n) { mutableListOf<Edge>() }
for ((i, e) in edges.withIndex()) {
val (from, to) = e
adjList[from].add(Edge(from, to, succProb[i]))
adjList[to].add(Edge(to, from, succProb[i]))
}
return adjList
}
private data class Node(val n: Int, val prob: Double) : Comparable<Node> {
override fun compareTo(other: Node): Int {
return other.prob.compareTo(prob)
}
}
private data class Edge(val from: Int, val to: Int, val prob: Double)
}
| [
{
"class_path": "fredyw__leetcode__a59d77c/leetcode/Problem1514$Node.class",
"javap": "Compiled from \"Problem1514.kt\"\nfinal class leetcode.Problem1514$Node implements java.lang.Comparable<leetcode.Problem1514$Node> {\n private final int n;\n\n private final double prob;\n\n public leetcode.Problem1514... |
fredyw__leetcode__a59d77c/src/main/kotlin/leetcode/Problem2115.kt | package leetcode
/**
* https://leetcode.com/problems/find-all-possible-recipes-from-given-supplies/
*/
class Problem2115 {
fun findAllRecipes(recipes: Array<String>, ingredients: List<List<String>>, supplies: Array<String>): List<String> {
val recipeToIngredients = mutableMapOf<String, List<String>>()
for ((index, recipe) in recipes.withIndex()) {
recipeToIngredients[recipe] = ingredients[index]
}
val answer = mutableListOf<String>()
val memo = mutableMapOf<String, Boolean>()
val visited = mutableSetOf<String>()
val supplySet = supplies.toSet()
for (recipe in recipes) {
if (findAllRecipes(recipeToIngredients, supplySet, recipe, visited, memo)) {
answer += recipe
}
}
return answer
}
private fun findAllRecipes(recipeToIngredients: MutableMap<String, List<String>>,
supplies: Set<String>,
recipe: String,
visited: MutableSet<String>,
memo: MutableMap<String, Boolean>): Boolean {
if (memo[recipe] != null) {
return memo[recipe]!!
}
if (recipe in visited) {
return false
}
visited += recipe
var found = true
for (ingredient in recipeToIngredients[recipe] ?: listOf()) {
found = if (ingredient in recipeToIngredients) {
found && findAllRecipes(recipeToIngredients, supplies, ingredient, visited, memo)
} else {
found && ingredient in supplies
}
}
memo[recipe] = found
return found
}
}
| [
{
"class_path": "fredyw__leetcode__a59d77c/leetcode/Problem2115.class",
"javap": "Compiled from \"Problem2115.kt\"\npublic final class leetcode.Problem2115 {\n public leetcode.Problem2115();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V... |
fredyw__leetcode__a59d77c/src/main/kotlin/leetcode/Problem1801.kt | package leetcode
import java.util.*
/**
* https://leetcode.com/problems/number-of-orders-in-the-backlog/
*/
class Problem1801 {
fun getNumberOfBacklogOrders(orders: Array<IntArray>): Int {
val buyMap = TreeMap<Int, Long> { a, b -> b.compareTo(a) }
val sellMap = TreeMap<Int, Long> { a, b -> a.compareTo(b) }
for ((price, amount, type) in orders) {
if (type == 0) { // buy
var remainingAmount = amount.toLong()
while (sellMap.isNotEmpty() && sellMap.firstKey() <= price) {
val count = sellMap[sellMap.firstKey()] ?: 0
if (count - remainingAmount <= 0) {
remainingAmount -= count
sellMap.pollFirstEntry()
} else {
sellMap[sellMap.firstKey()] = count - remainingAmount
remainingAmount = 0
break
}
}
if (remainingAmount > 0) {
buyMap[price] = (buyMap[price] ?: 0) + remainingAmount
}
} else { // sell
var remainingAmount = amount.toLong()
while (buyMap.isNotEmpty() && buyMap.firstKey() >= price) {
val count = buyMap[buyMap.firstKey()] ?: 0
if (count - remainingAmount <= 0) {
remainingAmount -= count
buyMap.pollFirstEntry()
} else {
buyMap[buyMap.firstKey()] = count - remainingAmount
remainingAmount = 0
break
}
}
if (remainingAmount > 0) {
sellMap[price] = (sellMap[price] ?: 0) + remainingAmount
}
}
}
var answer = 0L
for ((_, count) in buyMap) {
answer = (answer + count) % 1_000_000_007
}
for ((_, count) in sellMap) {
answer = (answer + count) % 1_000_000_007
}
return answer.toInt()
}
}
| [
{
"class_path": "fredyw__leetcode__a59d77c/leetcode/Problem1801.class",
"javap": "Compiled from \"Problem1801.kt\"\npublic final class leetcode.Problem1801 {\n public leetcode.Problem1801();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V... |
fredyw__leetcode__a59d77c/src/main/kotlin/leetcode/Problem2049.kt | package leetcode
/**
* https://leetcode.com/problems/count-nodes-with-the-highest-score/
*/
class Problem2049 {
fun countHighestScoreNodes(parents: IntArray): Int {
val root = buildTree(parents)
val scores = mutableMapOf<Long, Int>()
countHighestScore(parents.size, root, scores)
var answer = 0
var maxScore = 0L
for ((score, count) in scores) {
if (score > maxScore) {
maxScore = score
answer = count
}
}
return answer
}
data class Node(val value: Int, var left: Node? = null, var right: Node? = null)
private fun buildTree(parents: IntArray): Node? {
val nodes = Array(parents.size) { i -> Node(i) }
var root: Node? = null
for ((index, parentIndex) in parents.withIndex()) {
if (parentIndex == -1) {
root = nodes[0]
} else {
val parent = nodes[parentIndex]
val child = nodes[index]
if (parent.left == null) {
parent.left = child
} else {
parent.right = child
}
}
}
return root
}
private fun countHighestScore(n: Int, root: Node?, scores: MutableMap<Long, Int>): Long {
if (root == null) {
return -1
}
val left = countHighestScore(n, root.left, scores) + 1
val right = countHighestScore(n, root.right, scores) + 1
val score = (if (left == 0L) 1 else left) *
(if (right == 0L) 1 else right) *
(if (n - (left + right + 1) == 0L) 1 else n - (left + right + 1))
scores[score] = (scores[score] ?: 0) + 1
return left + right
}
}
| [
{
"class_path": "fredyw__leetcode__a59d77c/leetcode/Problem2049.class",
"javap": "Compiled from \"Problem2049.kt\"\npublic final class leetcode.Problem2049 {\n public leetcode.Problem2049();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V... |
fredyw__leetcode__a59d77c/src/main/kotlin/leetcode/Problem2212.kt | package leetcode
/**
* https://leetcode.com/problems/maximum-points-in-an-archery-competition/
*/
class Problem2212 {
fun maximumBobPoints(numArrows: Int, aliceArrows: IntArray): IntArray {
val answer = Answer()
maximumBobPoints(numArrows, aliceArrows, IntArray(12), 0, 0, answer)
return answer.bobArrows
}
private data class Answer(var max: Int = 0, var bobArrows: IntArray = IntArray(12))
private fun maximumBobPoints(numArrows: Int, aliceArrows: IntArray,
bobArrows: IntArray, index: Int, sum: Int, answer: Answer) {
if (index == aliceArrows.size) {
if (sum > answer.max) {
answer.max = sum
answer.bobArrows = bobArrows.copyOf()
answer.bobArrows[0] = numArrows
}
return
}
maximumBobPoints(numArrows, aliceArrows, bobArrows, index + 1, sum, answer)
if (numArrows - (aliceArrows[index] + 1) >= 0) {
bobArrows[index] = aliceArrows[index] + 1
maximumBobPoints(numArrows - (aliceArrows[index] + 1),
aliceArrows, bobArrows, index + 1, sum + index, answer)
bobArrows[index] = 0
}
}
}
| [
{
"class_path": "fredyw__leetcode__a59d77c/leetcode/Problem2212.class",
"javap": "Compiled from \"Problem2212.kt\"\npublic final class leetcode.Problem2212 {\n public leetcode.Problem2212();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V... |
fredyw__leetcode__a59d77c/src/main/kotlin/leetcode/Problem2257.kt | package leetcode
/**
* https://leetcode.com/problems/count-unguarded-cells-in-the-grid/
*/
class Problem2257 {
fun countUnguarded(m: Int, n: Int, guards: Array<IntArray>, walls: Array<IntArray>): Int {
val grid = Array(m) { IntArray(n) { UNGUARDED } }
for ((r, c) in guards) {
grid[r][c] = GUARD
}
for ((r, c) in walls) {
grid[r][c] = WALL
}
for ((r, c) in guards) {
// Up
var i = r - 1
while (i >= 0 && (grid[i][c] != WALL && grid[i][c] != GUARD)) {
grid[i][c] = GUARDED
i--
}
// Right
i = c + 1
while (i < n && (grid[r][i] != WALL && grid[r][i] != GUARD)) {
grid[r][i] = GUARDED
i++
}
// Down
i = r + 1
while (i < m && (grid[i][c] != WALL && grid[i][c] != GUARD)) {
grid[i][c] = GUARDED
i++
}
// Left
i = c - 1
while (i >= 0 && (grid[r][i] != WALL && grid[r][i] != GUARD)) {
grid[r][i] = GUARDED
i--
}
}
var answer = 0
for (i in 0 until m) {
for (j in 0 until n) {
if (grid[i][j] == UNGUARDED) {
answer++
}
}
}
return answer
}
companion object {
private const val GUARD = 1
private const val WALL = 2
private const val GUARDED = 3
private const val UNGUARDED = 4
}
}
| [
{
"class_path": "fredyw__leetcode__a59d77c/leetcode/Problem2257.class",
"javap": "Compiled from \"Problem2257.kt\"\npublic final class leetcode.Problem2257 {\n public static final leetcode.Problem2257$Companion Companion;\n\n private static final int GUARD;\n\n private static final int WALL;\n\n private... |
fredyw__leetcode__a59d77c/src/main/kotlin/leetcode/Problem1878.kt | package leetcode
import java.util.TreeSet
/**
* https://leetcode.com/problems/get-biggest-three-rhombus-sums-in-a-grid/
*/
class Problem1878 {
fun getBiggestThree(grid: Array<IntArray>): IntArray {
val rightDiagonalSums = mutableMapOf<RowCol, Int>()
val maxRow = grid.size
val maxCol = if (maxRow > 0) grid[0].size else 0
for (row in 0 until maxRow) {
rightDiagonalSums(grid, rightDiagonalSums, row, 0)
}
for (col in 0 until maxCol) {
rightDiagonalSums(grid, rightDiagonalSums, 0, col)
}
val leftDiagonalSums = mutableMapOf<RowCol, Int>()
for (row in 0 until maxRow) {
leftDiagonalSums(grid, leftDiagonalSums, row, maxCol - 1)
}
for (col in maxCol - 1 downTo 0) {
leftDiagonalSums(grid, leftDiagonalSums, 0, col)
}
val set = TreeSet<Int>()
for (row in 0 until maxRow) {
for (col in 0 until maxCol) {
set += rhombusSum(grid, leftDiagonalSums, rightDiagonalSums, row, col)
}
}
var list = mutableListOf<Int>()
var i = 0
while (set.isNotEmpty() && i < 3) {
list.add(set.pollLast())
i++
}
return list.toIntArray()
}
private data class RowCol(val row: Int, val col: Int)
private fun rightDiagonalSums(grid: Array<IntArray>,
rightDiagonalSums: MutableMap<RowCol, Int>,
row: Int, col: Int) {
val maxRow = grid.size
val maxCol = if (maxRow > 0) grid[0].size else 0
var r = row
var c = col
while (r < maxRow && c < maxCol) {
rightDiagonalSums[RowCol(r, c)] = if (rightDiagonalSums[RowCol(r - 1, c - 1)] == null) {
grid[r][c]
} else {
rightDiagonalSums[RowCol(r - 1, c - 1)]!! + grid[r][c]
}
r++
c++
}
}
private fun leftDiagonalSums(grid: Array<IntArray>,
leftDiagonalSums: MutableMap<RowCol, Int>,
row: Int, col: Int) {
val maxRow = grid.size
var r = row
var c = col
while (r < maxRow && c >= 0) {
leftDiagonalSums[RowCol(r, c)] = if (leftDiagonalSums[RowCol(r - 1, c + 1)] == null) {
grid[r][c]
} else {
leftDiagonalSums[RowCol(r - 1, c + 1)]!! + grid[r][c]
}
r++
c--
}
}
private fun rhombusSum(grid: Array<IntArray>,
leftDiagonalSums: MutableMap<RowCol, Int>,
rightDiagonalSums: MutableMap<RowCol, Int>,
row: Int, col: Int): MutableSet<Int> {
val set = mutableSetOf(grid[row][col])
val maxRow = grid.size
val maxCol = if (maxRow > 0) grid[0].size else 0
var r = row
val c = col
var length = 1
while (r + (length * 2) < maxRow && c - length >= 0 && c + length < maxCol) {
val topLeft = leftDiagonalSums[RowCol(r + length, c - length)]!! -
leftDiagonalSums[RowCol(r, c)]!! + grid[r][c]
val topRight = rightDiagonalSums[RowCol(r + length, c + length)]!! -
rightDiagonalSums[RowCol(r, c)]!! + grid[r][c]
val bottomLeft = rightDiagonalSums[RowCol(r + length * 2, c)]!! -
rightDiagonalSums[RowCol(r + length, c - length)]!! +
grid[r + length][c - length]
val bottomRight = leftDiagonalSums[RowCol(r + length * 2, c)]!! -
leftDiagonalSums[RowCol(r + length, c + length)]!! +
grid[r + length][c + length]
val sum = topLeft + topRight + bottomLeft + bottomRight -
(grid[r][c] + grid[r + length][c - length] +
grid[r + length][c + length] + grid[r + length * 2][c])
set += sum
length++
}
return set
}
}
| [
{
"class_path": "fredyw__leetcode__a59d77c/leetcode/Problem1878$RowCol.class",
"javap": "Compiled from \"Problem1878.kt\"\nfinal class leetcode.Problem1878$RowCol {\n private final int row;\n\n private final int col;\n\n public leetcode.Problem1878$RowCol(int, int);\n Code:\n 0: aload_0\n ... |
fredyw__leetcode__a59d77c/src/main/kotlin/leetcode/Problem2231.kt | package leetcode
/**
* https://leetcode.com/problems/largest-number-after-digit-swaps-by-parity/
*/
class Problem2231 {
fun largestInteger(num: Int): Int {
val oddIndexes = mutableListOf<Int>()
val evenIndexes = mutableListOf<Int>()
val numString = num.toString()
for ((i, n) in numString.withIndex()) {
if (n.toInt() % 2 != 0) {
oddIndexes += i
} else {
evenIndexes += i
}
}
var answer = CharArray(numString.length)
val sortedOddIndexes = oddIndexes.sortedWith(Comparator {a, b -> numString[b].compareTo(numString[a])})
val sortedEvenIndexes = evenIndexes.sortedWith(Comparator {a, b -> numString[b].compareTo(numString[a])})
if (numString[0].toInt() % 2 != 0) {
for ((i, j) in oddIndexes.withIndex()) {
answer[j] = numString[sortedOddIndexes[i]]
}
for ((i, j) in evenIndexes.withIndex()) {
answer[j] = numString[sortedEvenIndexes[i]]
}
} else {
for ((i, j) in evenIndexes.withIndex()) {
answer[j] = numString[sortedEvenIndexes[i]]
}
for ((i, j) in oddIndexes.withIndex()) {
answer[j] = numString[sortedOddIndexes[i]]
}
}
return String(answer).toInt()
}
}
| [
{
"class_path": "fredyw__leetcode__a59d77c/leetcode/Problem2231.class",
"javap": "Compiled from \"Problem2231.kt\"\npublic final class leetcode.Problem2231 {\n public leetcode.Problem2231();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V... |
fredyw__leetcode__a59d77c/src/main/kotlin/leetcode/Problem2055.kt | package leetcode
/**
* https://leetcode.com/problems/plates-between-candles/
*/
class Problem2055 {
fun platesBetweenCandles(s: String, queries: Array<IntArray>): IntArray {
val answer = IntArray(queries.size)
var startIndex = 0
while (startIndex < s.length && s[startIndex] != '|') {
startIndex++
}
var endIndex = s.length - 1
while (endIndex >= 0 && s[endIndex] != '|') {
endIndex--
}
if (endIndex <= startIndex) {
return answer
}
val prefixSums = IntArray(s.length)
val candles = mutableListOf<Int>()
// Keep track of the previous and next candle index positions for each plate index.
for ((index, value) in s.withIndex()) {
if (value == '*') {
prefixSums[index] = if (index - 1 < 0) 1 else prefixSums[index - 1] + 1
} else {
candles += index
prefixSums[index] = if (index - 1 < 0) 0 else prefixSums[index - 1]
}
}
data class PreviousNextCandle(val previous: Int, val next: Int)
val previousNextCandles = Array(s.length) { PreviousNextCandle(-1, -1) }
var candleIndex = 0
var index = startIndex
while (index <= endIndex) {
if (index != startIndex && s[index] == '|') {
candleIndex++
} else if (s[index] == '*') {
previousNextCandles[index] =
PreviousNextCandle(candles[candleIndex], candles[candleIndex + 1])
}
index++
}
for ((index, query) in queries.withIndex()) {
var start = query[0]
if (s[start] == '*') {
start = if (start < startIndex) {
startIndex
} else if (start > endIndex) {
endIndex
} else {
previousNextCandles[start].next
}
}
var end = query[1]
if (s[end] == '*') {
end = if (end < startIndex) {
startIndex
} else if (end > endIndex) {
endIndex
} else {
previousNextCandles[end].previous
}
}
answer[index] = if (start > end) 0 else prefixSums[end] - prefixSums[start]
}
return answer
}
}
| [
{
"class_path": "fredyw__leetcode__a59d77c/leetcode/Problem2055.class",
"javap": "Compiled from \"Problem2055.kt\"\npublic final class leetcode.Problem2055 {\n public leetcode.Problem2055();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V... |
fredyw__leetcode__a59d77c/src/main/kotlin/leetcode/Problem1824.kt | package leetcode
import kotlin.math.min
/**
* https://leetcode.com/problems/minimum-sideway-jumps/
*/
class Problem1824 {
fun minSideJumps(obstacles: IntArray): Int {
return minSideJumps(obstacles, lane = 2, index = 0,
memo = Array(obstacles.size) { IntArray(4) { -1 } })
}
private fun minSideJumps(obstacles: IntArray, lane: Int, index: Int, memo: Array<IntArray>): Int {
if (obstacles.size == index) {
return 0
}
if (obstacles[index] == lane) {
return Int.MAX_VALUE
}
if (memo[index][lane] != -1) {
return memo[index][lane]
}
val noSideJump = minSideJumps(obstacles, lane, index + 1, memo)
var hasSideJump = Int.MAX_VALUE
for (l in 1..3) {
if (l == lane || obstacles[index] == l) {
continue
}
var sideJump = minSideJumps(obstacles, l, index + 1, memo)
if (sideJump != Int.MAX_VALUE) {
sideJump++
}
hasSideJump = min(hasSideJump, sideJump)
}
val min = min(noSideJump, hasSideJump)
memo[index][lane] = min
return min
}
}
| [
{
"class_path": "fredyw__leetcode__a59d77c/leetcode/Problem1824.class",
"javap": "Compiled from \"Problem1824.kt\"\npublic final class leetcode.Problem1824 {\n public leetcode.Problem1824();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V... |
fredyw__leetcode__a59d77c/src/main/kotlin/leetcode/Problem2012.kt | package leetcode
import kotlin.math.max
import kotlin.math.min
/**
* https://leetcode.com/problems/sum-of-beauty-in-the-array/
*/
class Problem2012 {
fun sumOfBeauties(nums: IntArray): Int {
val left = IntArray(nums.size)
for ((i, n) in nums.withIndex()) {
left[i] = if (i == 0) n else max(left[i - 1], n)
}
val right = IntArray(nums.size)
for (i in nums.size - 1 downTo 0) {
right[i] = if (i == nums.size - 1) nums[i] else min(right[i + 1], nums[i])
}
var answer = 0
for (i in 1..nums.size - 2) {
if (left[i - 1] < nums[i] && nums[i] < right[i + 1]) {
answer += 2
} else if (nums[i - 1] < nums[i] && nums[i] < nums[i + 1]) {
answer++
}
}
return answer
}
}
| [
{
"class_path": "fredyw__leetcode__a59d77c/leetcode/Problem2012.class",
"javap": "Compiled from \"Problem2012.kt\"\npublic final class leetcode.Problem2012 {\n public leetcode.Problem2012();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V... |
fredyw__leetcode__a59d77c/src/main/kotlin/leetcode/Problem2048.kt | package leetcode
import kotlin.math.min
/**
* https://leetcode.com/problems/next-greater-numerically-balanced-number/
*/
class Problem2048 {
fun nextBeautifulNumber(n: Int): Int {
var answer = Answer()
val s = n.toString()
val numbers = arrayOf("1", "22", "122", "333", "1333", "4444", "14444", "22333",
"55555", "122333", "155555", "224444", "666666")
for (num in numbers) {
if (s.length > num.length) {
continue
}
permutations(num.toCharArray(), n = n, answer = answer)
}
return answer.value
}
private data class Answer(var value: Int = 1224444 /* maximum possible */)
private fun permutations(chars: CharArray, index: Int = 0, n: Int, answer: Answer) {
if (index == chars.size) {
val next = String(chars).toInt()
if (next > n) {
answer.value = min(answer.value, next)
}
}
for (i in index until chars.size) {
val tmp1 = chars[i]
val tmp2 = chars[index]
chars[i] = tmp2
chars[index] = tmp1
permutations(chars, index + 1, n, answer)
chars[i] = tmp1
chars[index] = tmp2
}
}
}
| [
{
"class_path": "fredyw__leetcode__a59d77c/leetcode/Problem2048$Answer.class",
"javap": "Compiled from \"Problem2048.kt\"\nfinal class leetcode.Problem2048$Answer {\n private int value;\n\n public leetcode.Problem2048$Answer(int);\n Code:\n 0: aload_0\n 1: invokespecial #9 ... |
fredyw__leetcode__a59d77c/src/main/kotlin/leetcode/Problem2182.kt | package leetcode
import java.util.PriorityQueue
/**
* https://leetcode.com/problems/construct-string-with-repeat-limit/
*/
class Problem2182 {
fun repeatLimitedString(s: String, repeatLimit: Int): String {
data class CharCount(val char: Char, val count: Int)
val array = IntArray(26)
for (char in s) {
array[char - 'a']++
}
val queue = PriorityQueue<CharCount> {a, b -> b.char.compareTo(a.char)}
for (i in array.indices) {
if (array[i] == 0) {
continue
}
queue += CharCount((i + 'a'.toInt()).toChar(), array[i])
}
val answer = StringBuilder()
var lastChar: Char? = null
var lastCount = 0
while (queue.isNotEmpty()) {
var e1: CharCount? = null
if (queue.isNotEmpty()) {
e1 = queue.remove()
if (lastChar == e1.char && lastCount == repeatLimit && queue.isEmpty()) {
break
}
var n = if (lastChar == e1.char) lastCount else 0
var count = 0
if (e1.count > repeatLimit - n) {
answer.append(e1.char.toString().repeat(repeatLimit - n))
count = repeatLimit - n
e1 = CharCount(e1.char, e1.count - (repeatLimit - n))
} else { // if (e1.count <= repeatLimit - n) {
answer.append(e1.char.toString().repeat(e1.count))
count = e1.count
e1 = null
}
if (lastChar == e1?.char) {
lastCount += count
} else {
lastChar = e1?.char
lastCount = count
}
}
var e2: CharCount? = null
if (queue.isNotEmpty()) {
e2 = queue.remove()
answer.append(e2?.char)
if (e2.count - 1 > 0) {
e2 = CharCount(e2.char, e2.count - 1)
} else if (e2.count - 1 == 0) {
e2 = null
}
lastChar = e2?.char
lastCount = 1
}
if (e1 != null) {
queue += e1
}
if (e2 != null) {
queue += e2
}
}
return answer.toString()
}
}
| [
{
"class_path": "fredyw__leetcode__a59d77c/leetcode/Problem2182$repeatLimitedString$CharCount.class",
"javap": "Compiled from \"Problem2182.kt\"\npublic final class leetcode.Problem2182$repeatLimitedString$CharCount {\n private final char char;\n\n private final int count;\n\n public leetcode.Problem2182... |
fredyw__leetcode__a59d77c/src/main/kotlin/leetcode/Problem2044.kt | package leetcode
/**
* https://leetcode.com/problems/count-number-of-maximum-bitwise-or-subsets/
*/
class Problem2044 {
fun countMaxOrSubsets(nums: IntArray): Int {
var max = 0
for (num in nums) {
max = max or num
}
var answer = 0
for (i in nums.indices) {
answer += countMaxOrSubsets(nums, max, i + 1, false, nums[i])
}
return answer
}
private fun countMaxOrSubsets(nums: IntArray, max: Int, index: Int, skipped: Boolean, accu: Int): Int {
if (index == nums.size) {
return if (!skipped && accu == max) 1 else 0
}
val count = if (!skipped && accu == max) 1 else 0
val a = countMaxOrSubsets(nums, max, index + 1, false, accu or nums[index])
val b = countMaxOrSubsets(nums, max, index + 1, true, accu)
return a + b + count
}
}
| [
{
"class_path": "fredyw__leetcode__a59d77c/leetcode/Problem2044.class",
"javap": "Compiled from \"Problem2044.kt\"\npublic final class leetcode.Problem2044 {\n public leetcode.Problem2044();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V... |
fredyw__leetcode__a59d77c/src/main/kotlin/leetcode/Problem2222.kt | package leetcode
/**
* https://leetcode.com/problems/number-of-ways-to-select-buildings/
*/
class Problem2222 {
fun numberOfWays(s: String): Long {
data class Binary(val zero: Int = 0, val one: Int = 0)
val left = Array(s.length) { Binary() }
for (i in s.indices) {
val zero = if (s[i] == '0') 1 else 0
val one = if (s[i] == '1') 1 else 0
left[i] = if (i == 0) {
Binary(zero, one)
} else {
Binary(zero + left[i - 1].zero, one + left[i - 1].one)
}
}
val right = Array(s.length) { Binary() }
for (i in s.length - 1 downTo 0) {
val zero = if (s[i] == '0') 1 else 0
val one = if (s[i] == '1') 1 else 0
right[i] = if (i == s.length - 1) {
Binary(zero, one)
} else {
Binary(zero + right[i + 1].zero, one + right[i + 1].one)
}
}
var answer = 0L
for (i in 1..s.length - 2) {
if (s[i] == '0') { // look for 101
answer += left[i - 1].one * right[i + 1].one
} else { // look for 010
answer += left[i - 1].zero * right[i + 1].zero
}
}
return answer
}
}
| [
{
"class_path": "fredyw__leetcode__a59d77c/leetcode/Problem2222.class",
"javap": "Compiled from \"Problem2222.kt\"\npublic final class leetcode.Problem2222 {\n public leetcode.Problem2222();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V... |
fredyw__leetcode__a59d77c/src/main/kotlin/leetcode/Problem1402.kt | package leetcode
import kotlin.math.max
/**
* https://leetcode.com/problems/reducing-dishes/
*/
class Problem1402 {
fun maxSatisfaction(satisfaction: IntArray): Int {
satisfaction.sort()
return maxSatisfaction(satisfaction, 0, 1, Array(satisfaction.size) {
IntArray(
satisfaction.size + 1
) { -1 }
})
}
private fun maxSatisfaction(satisfaction: IntArray, index: Int, time: Int, memo: Array<IntArray>): Int {
if (satisfaction.size == index) {
return 0
}
if (memo[index][time] != -1) {
return memo[index][time]
}
val m = max(
maxSatisfaction(satisfaction, index + 1, time, memo),
maxSatisfaction(satisfaction, index + 1, time + 1, memo) + satisfaction[index] * time)
memo[index][time] = m
return m
}
}
| [
{
"class_path": "fredyw__leetcode__a59d77c/leetcode/Problem1402.class",
"javap": "Compiled from \"Problem1402.kt\"\npublic final class leetcode.Problem1402 {\n public leetcode.Problem1402();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V... |
fredyw__leetcode__a59d77c/src/main/kotlin/leetcode/Problem2064.kt | package leetcode
import kotlin.math.max
/**
* https://leetcode.com/problems/minimized-maximum-of-products-distributed-to-any-store/
*/
class Problem2064 {
fun minimizedMaximum(n: Int, quantities: IntArray): Int {
var min = 1
var max = quantities[0]
for (i in 1 until quantities.size) {
max = max(max, quantities[i])
}
var answer = 0
while (min <= max) {
val mid = (min + max) / 2
if (canDistribute(n, quantities, mid)) {
max = mid - 1
answer = mid
} else {
min = mid + 1
}
}
return answer
}
private fun canDistribute(stores: Int, quantities: IntArray, x: Int): Boolean {
var n = stores
for (quantity in quantities) {
n -= if (quantity % x == 0) quantity / x else (quantity / x) + 1
if (n < 0) {
return false
}
}
return true
}
}
| [
{
"class_path": "fredyw__leetcode__a59d77c/leetcode/Problem2064.class",
"javap": "Compiled from \"Problem2064.kt\"\npublic final class leetcode.Problem2064 {\n public leetcode.Problem2064();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V... |
fredyw__leetcode__a59d77c/src/main/kotlin/leetcode/Problem1438.kt | package leetcode
import java.util.*
import kotlin.math.max
/**
* https://leetcode.com/problems/longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/
*/
class Problem1438 {
fun longestSubarray(nums: IntArray, limit: Int): Int {
var answer = 1
val minDeque = LinkedList<Int>()
val maxDeque = LinkedList<Int>()
var left = 0
for (right in nums.indices) {
while (minDeque.isNotEmpty() && nums[right] < minDeque.peekLast()) {
minDeque.pollLast()
}
minDeque.addLast(nums[right])
while (maxDeque.isNotEmpty() && nums[right] > maxDeque.peekLast()) {
maxDeque.pollLast()
}
maxDeque.addLast(nums[right])
while (maxDeque.peekFirst() - minDeque.peekFirst() > limit) {
if (minDeque.peekFirst() == nums[left]) {
minDeque.pollFirst()
}
if (maxDeque.peekFirst() == nums[left]) {
maxDeque.pollFirst()
}
left++
}
answer = max(answer, right - left + 1)
}
return answer
}
}
| [
{
"class_path": "fredyw__leetcode__a59d77c/leetcode/Problem1438.class",
"javap": "Compiled from \"Problem1438.kt\"\npublic final class leetcode.Problem1438 {\n public leetcode.Problem1438();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V... |
fredyw__leetcode__a59d77c/src/main/kotlin/leetcode/Problem2002.kt | package leetcode
import kotlin.math.max
/**
* https://leetcode.com/problems/maximum-product-of-the-length-of-two-palindromic-subsequences/
*/
class Problem2002 {
fun maxProduct(s: String): Int {
return maxProduct(s, 0, "", "")
}
private fun maxProduct(s: String, i: Int, word1: String, word2: String): Int {
if (s.length == i) {
if (isPalindrome(word1) && isPalindrome(word2)) {
return word1.length * word2.length
}
return 1
}
val a = maxProduct(s, i + 1, word1 + s[i], word2)
val b = maxProduct(s, i + 1, word1, word2 + s[i])
val c = maxProduct(s, i + 1, word1, word2)
return max(a, max(b, c))
}
private fun isPalindrome(s: String): Boolean {
var i = 0
var j = s.length - 1
while (i < j) {
if (s[i] != s[j]) {
return false
}
i++
j--
}
return true
}
}
| [
{
"class_path": "fredyw__leetcode__a59d77c/leetcode/Problem2002.class",
"javap": "Compiled from \"Problem2002.kt\"\npublic final class leetcode.Problem2002 {\n public leetcode.Problem2002();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V... |
fredyw__leetcode__a59d77c/src/main/kotlin/leetcode/Problem2266.kt | package leetcode
/**
* https://leetcode.com/problems/count-number-of-texts/
*/
class Problem2266 {
fun countTexts(pressedKeys: String): Int {
if (pressedKeys.length == 1) {
return 1
}
var answer = 1L
var i = 0
var length = 1
val memo3 = IntArray(pressedKeys.length + 1) { -1 }
val memo4 = IntArray(pressedKeys.length + 1) { -1 }
while (i < pressedKeys.length - 1) {
if (pressedKeys[i] != pressedKeys[i + 1]) {
val numDigits = numDigits(pressedKeys[i])
answer = (answer * countTexts(
numDigits,
length,
if (numDigits == 3) memo3 else memo4
)) % 1_000_000_007
length = 1
} else {
length++
}
i++
}
val numDigits = numDigits(pressedKeys[i])
answer = (answer * countTexts(
numDigits,
length,
if (numDigits == 3) memo3 else memo4
)) % 1_000_000_007
return answer.toInt()
}
private fun numDigits(key: Char): Int {
return if (key == '7' || key == '9') 4 else 3
}
private fun countTexts(numDigits: Int, length: Int, memo: IntArray): Int {
if (length < 0) {
return 0
}
if (length == 0) {
return 1
}
if (memo[length] != -1) {
return memo[length]
}
var count = 0
for (digit in 1..numDigits) {
count = (count + countTexts(numDigits, length - digit, memo)) % 1_000_000_007
}
memo[length] = count
return count
}
}
| [
{
"class_path": "fredyw__leetcode__a59d77c/leetcode/Problem2266.class",
"javap": "Compiled from \"Problem2266.kt\"\npublic final class leetcode.Problem2266 {\n public leetcode.Problem2266();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V... |
fredyw__leetcode__a59d77c/src/main/kotlin/leetcode/Problem1914.kt | package leetcode
/**
* https://leetcode.com/problems/cyclically-rotating-a-grid/
*/
class Problem1914 {
fun rotateGrid(grid: Array<IntArray>, k: Int): Array<IntArray> {
val maxRows: Int = grid.size
val maxCols: Int = if (grid.isNotEmpty()) grid[0].size else 0
var row = 0
var col = 0
var length = 0
var height = maxRows
var width = maxCols
while (height >= 2 && width >= 2) {
val perimeter = 2 * (height + width)
rotateGrid(grid, maxRows, maxCols, length++, row++, col++, k % (perimeter - 4))
height -= 2
width -= 2
}
return grid
}
private fun rotateGrid(grid: Array<IntArray>, maxRows: Int, maxCols: Int, length: Int,
row: Int, col: Int, k: Int) {
var elements = mutableListOf<Int>()
iterate(maxRows, maxCols, length, row, col) { r, c ->
elements.add(grid[r][c])
}
var index = 0
var start = false
var n = 0
for (i in 0 until elements.size + k) {
iterate(maxRows, maxCols, length, row, col) { r, c ->
if (n++ == k) {
start = true
}
if (start && index < elements.size) {
grid[r][c] = elements[index++]
}
}
}
}
private fun iterate(maxRows: Int, maxCols: Int, length: Int, row: Int, col: Int,
f: (Int, Int) -> Unit) {
// Go down.
var r = row
var c = col
while (r < maxRows - length) {
f(r, c)
r++
}
// Go left.
r--
c++
while (c < maxCols - length) {
f(r, c)
c++
}
// Go up.
r--
c--
while (r >= length) {
f(r, c)
r--
}
// Go right.
c--
r++
while (c >= length + 1) {
f(r, c)
c--
}
}
}
| [
{
"class_path": "fredyw__leetcode__a59d77c/leetcode/Problem1914.class",
"javap": "Compiled from \"Problem1914.kt\"\npublic final class leetcode.Problem1914 {\n public leetcode.Problem1914();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V... |
fredyw__leetcode__a59d77c/src/main/kotlin/leetcode/Problem1482.kt | package leetcode
import kotlin.math.max
import kotlin.math.min
/**
* https://leetcode.com/problems/minimum-number-of-days-to-make-m-bouquets/
*/
class Problem1482 {
fun minDays(bloomDay: IntArray, m: Int, k: Int): Int {
if (bloomDay.size < m * k) {
return -1
}
var min = Int.MAX_VALUE
var max = Int.MIN_VALUE
for (day in bloomDay) {
min = min(min, day)
max = max(max, day)
}
while (min <= max) {
val mid = min + ((max - min) / 2)
if (isValid(bloomDay, m, k, mid)) {
max = mid - 1
} else {
min = mid + 1
}
}
return min
}
private fun isValid(bloomDay: IntArray, m: Int, k: Int, day: Int): Boolean {
var bouquets = 0
var flowers = 0
for (d in bloomDay) {
if (d > day) {
flowers = 0
} else {
flowers++
}
if (flowers == k) {
flowers = 0
bouquets++
}
if (bouquets == m) {
return true
}
}
return false
}
}
| [
{
"class_path": "fredyw__leetcode__a59d77c/leetcode/Problem1482.class",
"javap": "Compiled from \"Problem1482.kt\"\npublic final class leetcode.Problem1482 {\n public leetcode.Problem1482();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V... |
fredyw__leetcode__a59d77c/src/main/kotlin/leetcode/Problem1895.kt | package leetcode
import kotlin.math.max
/**
* https://leetcode.com/problems/largest-magic-square/
*/
class Problem1895 {
fun largestMagicSquare(grid: Array<IntArray>): Int {
val maxRow = grid.size
val maxCol = if (maxRow > 0) grid[0].size else 0
val rowSums = Array(maxRow) { IntArray(maxCol) }
val colSums = Array(maxRow) { IntArray(maxCol) }
val rightDiagonalSums = Array(maxRow) { IntArray(maxCol) }
val leftDiagonalSums = Array(maxRow) { IntArray(maxCol) }
for (row in 0 until maxRow) {
for (col in 0 until maxCol) {
// Direction: --
rowSums[row][col] = if (col == 0) {
grid[row][col]
} else {
rowSums[row][col - 1] + grid[row][col]
}
// Direction: |
colSums[row][col] = if (row == 0) {
grid[row][col]
} else {
colSums[row - 1][col] + grid[row][col]
}
// Direction: \
rightDiagonalSums[row][col] = if (row == 0 || col == 0) {
grid[row][col]
} else {
rightDiagonalSums[row - 1][col - 1] + grid[row][col]
}
// Direction: /
leftDiagonalSums[row][col] = if (row == 0 || col == maxCol - 1) {
grid[row][col]
} else {
leftDiagonalSums[row - 1][col + 1] + grid[row][col]
}
}
}
var answer = 1
for (row in 0 until maxRow) {
for (col in 0 until maxCol) {
var k = 1
while (row + k <= maxRow && col + k <= maxCol) {
if (isMagicSquare(rowSums, colSums, leftDiagonalSums, rightDiagonalSums,
row, col, k)) {
answer = max(answer, k)
}
k++
}
}
}
return answer
}
private fun isMagicSquare(rowSums: Array<IntArray>,
colSums: Array<IntArray>,
leftDiagonalSums: Array<IntArray>,
rightDiagonalSums: Array<IntArray>,
row: Int, col: Int, size: Int): Boolean {
val maxRow = rowSums.size
val maxCol = if (maxRow > 0) rowSums[0].size else 0
var sum = 0
for (r in row until row + size) {
val rowSum = rowSums[r][col + size - 1] - (if (col - 1 >= 0) rowSums[r][col - 1] else 0)
if (sum == 0) {
sum = rowSum
} else {
if (sum != rowSum) {
return false
}
}
}
for (c in col until col + size) {
val colSum = colSums[row + size - 1][c] - (if (row - 1 >= 0) colSums[row - 1][c] else 0)
if (sum != colSum) {
return false
}
}
val rightDiagonalSum = rightDiagonalSums[row + size - 1][col + size - 1] -
(if (row - 1 >= 0 && col - 1 >= 0) rightDiagonalSums[row - 1][col - 1] else 0)
if (sum != rightDiagonalSum) {
return false
}
val leftDiagonalSum = leftDiagonalSums[row + size - 1][col] -
(if (row - 1 >= 0 && col + size < maxCol) leftDiagonalSums[row - 1][col + size] else 0)
if (sum != leftDiagonalSum) {
return false
}
return true
}
}
| [
{
"class_path": "fredyw__leetcode__a59d77c/leetcode/Problem1895.class",
"javap": "Compiled from \"Problem1895.kt\"\npublic final class leetcode.Problem1895 {\n public leetcode.Problem1895();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V... |
fredyw__leetcode__a59d77c/src/main/kotlin/leetcode/Problem2039.kt | package leetcode
import java.lang.Integer.max
import java.util.*
/**
* https://leetcode.com/problems/the-time-when-the-network-becomes-idle/
*/
class Problem2039 {
fun networkBecomesIdle(edges: Array<IntArray>, patience: IntArray): Int {
val adjList = buildAdjList(edges)
val queue = LinkedList<Int>()
val visited = mutableSetOf<Int>()
val edgeTo = mutableMapOf<Int, Int>()
val counts = mutableMapOf<Int, Int>()
queue.add(0)
while (!queue.isEmpty()) {
val current = queue.remove()
if (current in visited) {
continue
}
visited.add(current)
val neighbors = adjList[current]
if (neighbors != null) {
for (neighbor in neighbors) {
if (neighbor in visited) {
continue
}
if (neighbor !in edgeTo) {
edgeTo[neighbor] = current
counts[neighbor] = (counts[current] ?: 0) + 1
}
queue.add(neighbor)
}
}
}
var answer = 0
for (i in 1 until adjList.size) {
val time = counts[i]!! * 2
answer = max(answer, (time + (((time - 1) / patience[i]) * patience[i])) + 1)
}
return answer
}
private fun buildAdjList(edges: Array<IntArray>): Map<Int, List<Int>> {
val map = mutableMapOf<Int, MutableList<Int>>()
for (edge in edges) {
val list1 = map[edge[0]] ?: mutableListOf()
list1 += edge[1]
map[edge[0]] = list1
val list2 = map[edge[1]] ?: mutableListOf()
list2 += edge[0]
map[edge[1]] = list2
}
return map
}
}
| [
{
"class_path": "fredyw__leetcode__a59d77c/leetcode/Problem2039.class",
"javap": "Compiled from \"Problem2039.kt\"\npublic final class leetcode.Problem2039 {\n public leetcode.Problem2039();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V... |
fredyw__leetcode__a59d77c/src/main/kotlin/leetcode/Problem1462.kt | package leetcode
/**
* https://leetcode.com/problems/course-schedule-iv/
*/
class Problem1462 {
fun checkIfPrerequisite(numCourses: Int, prerequisites: Array<IntArray>,
queries: Array<IntArray>): List<Boolean> {
val adjList = buildAdjList(prerequisites)
val dependencyMap = mutableMapOf<Int, MutableSet<Int>>()
for (course in 0 until numCourses) {
val dependencies = mutableSetOf<Int>()
dfs(adjList, BooleanArray(numCourses), dependencies, course)
dependencyMap[course] = dependencies
}
val answer = mutableListOf<Boolean>()
for (query in queries) {
answer += query[1] in dependencyMap[query[0]]!!
}
return answer
}
private fun buildAdjList(prerequisites: Array<IntArray>): Map<Int, List<Int>> {
val adjList = mutableMapOf<Int, MutableList<Int>>()
for (prerequisite in prerequisites) {
val from = prerequisite[0]
val to = prerequisite[1]
val list = adjList[from] ?: mutableListOf()
list += to
adjList[from] = list
}
return adjList
}
private fun dfs(adjList: Map<Int, List<Int>>, visited: BooleanArray,
dependencies: MutableSet<Int>, course: Int) {
visited[course] = true
for (adj in (adjList[course] ?: listOf())) {
if (!visited[adj]) {
dfs(adjList, visited, dependencies, adj)
}
}
dependencies += course
}
}
| [
{
"class_path": "fredyw__leetcode__a59d77c/leetcode/Problem1462.class",
"javap": "Compiled from \"Problem1462.kt\"\npublic final class leetcode.Problem1462 {\n public leetcode.Problem1462();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V... |
fredyw__leetcode__a59d77c/src/main/kotlin/leetcode/Problem1604.kt | package leetcode
/**
* https://leetcode.com/problems/alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/
*/
class Problem1604 {
fun alertNames(keyName: Array<String>, keyTime: Array<String>): List<String> {
val map = mutableMapOf<String, MutableList<String>>()
for (i in keyName.indices) {
val times = map[keyName[i]] ?: mutableListOf()
times += keyTime[i]
map[keyName[i]] = times
}
val answer = mutableListOf<String>()
for ((key, value) in map) {
var i = 0
value.sort()
while (i < value.size - 2) {
val t = difference(value[i], value[i + 1]) + difference(value[i + 1], value[i + 2])
if (t <= 60) {
answer += key
break
}
i++
}
}
answer.sort()
return answer
}
private fun difference(from: String, to: String): Int {
val (fromHour, fromMinute) = from.split(":")
val (toHour, toMinute) = to.split(":")
val minute = toMinute.toInt() - fromMinute.toInt()
val hour = (toHour.toInt() - fromHour.toInt()) * 60
return minute + hour
}
}
| [
{
"class_path": "fredyw__leetcode__a59d77c/leetcode/Problem1604.class",
"javap": "Compiled from \"Problem1604.kt\"\npublic final class leetcode.Problem1604 {\n public leetcode.Problem1604();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V... |
fredyw__leetcode__a59d77c/src/main/kotlin/leetcode/Problem1559.kt | package leetcode
/**
* https://leetcode.com/problems/detect-cycles-in-2d-grid/
*/
class Problem1559 {
fun containsCycle(grid: Array<CharArray>): Boolean {
val maxRow = grid.size
val maxCol = if (maxRow == 0) 0 else grid[0].size
val visited = Array(grid.size) { BooleanArray(maxCol) }
var row = 0
while (row < maxRow) {
var col = 0
while (col < maxCol) {
if (visited[row][col]) {
col++
continue
}
if (containsCycle(grid, maxRow, maxCol, grid[row][col], visited, -1, -1, row, col)) {
return true
}
col++
}
row++
}
return false
}
private fun containsCycle(grid: Array<CharArray>, maxRow: Int, maxCol: Int, char: Char,
visited: Array<BooleanArray>, previousRow: Int, previousCol: Int,
currentRow: Int, currentCol: Int): Boolean {
if (visited[currentRow][currentCol]) {
return false
}
visited[currentRow][currentCol] = true
for ((r, c) in arrayOf(intArrayOf(1, 0), intArrayOf(-1, 0), intArrayOf(0, 1), intArrayOf(0, -1))) {
val newRow = currentRow + r
val newCol = currentCol + c
if (newRow < 0 || newRow == maxRow || newCol < 0 || newCol == maxCol) {
continue
}
if (grid[newRow][newCol] != char) {
continue
}
if (!(previousRow == newRow && previousCol == newCol)) {
if (visited[newRow][newCol]) {
return true
}
if (containsCycle(
grid, maxRow, maxCol, char, visited, currentRow, currentCol,
newRow, newCol
)
) {
return true
}
}
}
return false
}
}
| [
{
"class_path": "fredyw__leetcode__a59d77c/leetcode/Problem1559.class",
"javap": "Compiled from \"Problem1559.kt\"\npublic final class leetcode.Problem1559 {\n public leetcode.Problem1559();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V... |
EugenIvanushkin__kotlin-koans__321e41c/src/iii_conventions/MyDate.kt | package iii_conventions
import java.time.Month
data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int) : Comparable<MyDate> {
override fun compareTo(date: MyDate): Int {
if (this.year.compareTo(date.year) == 0) {
if (this.month.compareTo(date.month) == 0) {
if (this.dayOfMonth.compareTo(date.dayOfMonth) == 0) {
return 0
}else{
return this.dayOfMonth.compareTo(date.dayOfMonth)
}
} else {
return this.month.compareTo(date.month)
}
}
return this.year.compareTo(date.year)
}
}
operator fun MyDate.plus(b: MyDate) = MyDate(this.year + b.year, this.month + b.month, this.dayOfMonth + b.dayOfMonth)
operator fun MyDate.plus(b: TimeInterval) = when (b) {
TimeInterval.DAY -> MyDate(this.year, this.month, this.dayOfMonth + 1)
TimeInterval.WEEK -> MyDate(this.year + 1, this.month, this.dayOfMonth)
TimeInterval.YEAR -> MyDate(this.year + 1, this.month, this.dayOfMonth)
else -> MyDate(this.year, this.month, this.dayOfMonth)
}
operator fun MyDate.rangeTo(other: MyDate): DateRange = DateRange(this, other)
enum class TimeInterval {
DAY,
WEEK,
YEAR
}
class DateRange(val start: MyDate, val endInclusive: MyDate) : Iterable<MyDate> {
override fun iterator(): Iterator {
return Iterator
}
companion object Iterator : kotlin.collections.Iterator<MyDate> {
override fun next(): MyDate {
if (this.hasNext()) {
}
return MyDate(1, 1, 1)
}
override fun hasNext(): Boolean {
return false;
}
}
}
operator fun DateRange.contains(other: MyDate): Boolean {
return other.compareTo(start) in 0..1 && other.compareTo(endInclusive) in -1..0
}
| [
{
"class_path": "EugenIvanushkin__kotlin-koans__321e41c/iii_conventions/MyDate.class",
"javap": "Compiled from \"MyDate.kt\"\npublic final class iii_conventions.MyDate implements java.lang.Comparable<iii_conventions.MyDate> {\n private final int year;\n\n private final int month;\n\n private final int da... |
quincy__euler-kotlin__01d96f6/src/main/kotlin/com/quakbo/euler/Euler9.kt | package com.quakbo.euler
/*
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a^2 + b^2 = c^2
For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
According to Wikipedia, every Pythagorean triplet is expressed by
a = m^2 - n^2, b = 2mn, c = m^2 + n^2
where m > n > 0
and m and n are coprime
and m and n are both not odd
So an intelligent brute force approach is to increment m and n one at a time and find a, b, and c.
*/
fun main(args: Array<String>) {
val sum = 1000L
for (m in 2L..99L) {
for (n in 1L until m) {
val (a, b, c) = createPythagoreanTriplet(m, n) ?: continue
if ((a + b + c) == sum) {
println("Found ($a, $b, $c) with sum=${a + b + c} and product = ${a * b * c})")
return
}
}
}
println("No pythagorean triplets found which sum to 1000.")
}
internal fun createPythagoreanTriplet(m: Long, n: Long): Triple<Long, Long, Long>? {
if (m <= n || m < 1) {
return null
}
if (isOdd(m) && isOdd(n)) {
return null
}
if (coprime(m, n)) {
return null
}
val a: Long = (m * m) - (n * n)
val b: Long = 2 * m * n
val c: Long = (m * m) + (n * n)
return Triple(a, b, c)
}
private fun isOdd(i: Long): Boolean {
return i % 2L != 0L
}
/** Return true if the greatest common divisor of m and n is 1. */
private fun coprime(m: Long, n: Long): Boolean {
var gcd = 1
var i = 1
while (i <= m && i <= n) {
if (m % i == 0L && n % i == 0L) {
gcd = i
}
i++
}
return gcd == 1
}
| [
{
"class_path": "quincy__euler-kotlin__01d96f6/com/quakbo/euler/Euler9Kt.class",
"javap": "Compiled from \"Euler9.kt\"\npublic final class com.quakbo.euler.Euler9Kt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc #9 // String ar... |
quincy__euler-kotlin__01d96f6/src/main/kotlin/com/quakbo/euler/Euler6.kt | package com.quakbo.euler
/*
The sum of the squares of the first ten natural numbers is,
1^2 + 2^2 + ... + 10^2 = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)^2 = 55^2 = 3025
Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640.
Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
*/
private fun sumOfSquares(sequence: Sequence<Int>): Int {
return sequence
.map { it * it }
.sum()
}
private fun squareOfSums(sequence: Sequence<Int>): Int {
val sum = sequence.sum()
return sum * sum
}
fun main(args: Array<String>) {
val firstHundred = generateSequence(1, {i -> i + 1} ).take(100)
println(squareOfSums(firstHundred) - sumOfSquares(firstHundred))
}
/*
Sequences are a lot like Streams, but you can consume them as many times as you like. *hold for applause*
*/
| [
{
"class_path": "quincy__euler-kotlin__01d96f6/com/quakbo/euler/Euler6Kt.class",
"javap": "Compiled from \"Euler6.kt\"\npublic final class com.quakbo.euler.Euler6Kt {\n private static final int sumOfSquares(kotlin.sequences.Sequence<java.lang.Integer>);\n Code:\n 0: aload_0\n 1: invokedynami... |
quincy__euler-kotlin__01d96f6/src/main/kotlin/com/quakbo/euler/Euler4.kt | package com.quakbo.euler
/*
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
*/
internal fun isPalindrome(n: Int): Boolean {
val s = n.toString()
return s.reversed() == s
}
fun main(args: Array<String>) {
done@ for (i in 999 downTo 900) {
for (j in 999 downTo 900) {
val product = i * j
if (isPalindrome(product)) {
println(product)
break@done
}
}
}
}
/*
Earlier was saw the range operator which creates a Sequence.
1..999
We can also create a sequence of decreasing values with the downTo operator.
In Kotlin we write a foreach loop as
for (v in someRangeOfValues)
The in operator can be used in the following ways
- specifies the object being iterated in a for loop
- is used as an infix operator to check that a value belongs to a range, a collection or another entity that defines the 'contains' method
- is used in when expressions for the same purpose
done@ is a label to help with flow control. When we say break@done, we're saying break out of the loop labeled with done@.
Without the label we would have broken out of the loop at line 16 and begun another iteration of the outer for loop.
There are implicit labels for loop constructs. So you can do things like this...
while (foo < 100) {
for (i in 1..foo) {
if (foo == 2) { continue@while }
}
}
If blocks are known as conditional expressions because they return a value. So you are allowed to assign from them.
fun maxOf(a: Int, b: Int) = if (a > b) a else b
*/
| [
{
"class_path": "quincy__euler-kotlin__01d96f6/com/quakbo/euler/Euler4Kt.class",
"javap": "Compiled from \"Euler4.kt\"\npublic final class com.quakbo.euler.Euler4Kt {\n public static final boolean isPalindrome(int);\n Code:\n 0: iload_0\n 1: invokestatic #12 // Method java/l... |
HLQ-Struggle__LeetCodePro__76922f4/src/com/hlq/leetcode/array/Question26.kt | package com.hlq.leetcode.array
/**
* @author HLQ_Struggle
* @date 2020/11/30
* @desc LeetCode 26. 删除排序数组中的重复项 https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array/
*/
fun main() {
val nums = intArrayOf(0,0,1,1,1,2,2,3,3,4)
println("----> ${removeDuplicates(nums)}")
}
/**
* 双指针解法
*/
fun removeDuplicates(nums: IntArray): Int {
if(nums.isEmpty()){
return 0
}
var resultCount = 0
for(i in nums.indices){
if(nums[i] != nums[resultCount]){
nums[++resultCount] = nums[i]
}
}
return ++resultCount
}
/**
* LeetCode 执行用时范例
*/
fun removeDuplicates1(nums: IntArray): Int {
if (nums.isEmpty()) return 0
var i = 0
for (j in 1 until nums.size) {
if (nums[j] != nums[i]) {
i++
nums[i] = nums[j]
}
}
return i + 1
}
/**
* LeetCode 执行消耗内存范例
*/
fun removeDuplicates2(nums: IntArray): Int {
if(nums == null){
return 0
}
if(nums.size == 1){
return 1
}
var i = 0
for(j in 1 until nums.size){
if(nums[i] != nums[j]){
i++
nums[i] = nums[j]
}
}
return i+1
}
| [
{
"class_path": "HLQ-Struggle__LeetCodePro__76922f4/com/hlq/leetcode/array/Question26Kt.class",
"javap": "Compiled from \"Question26.kt\"\npublic final class com.hlq.leetcode.array.Question26Kt {\n public static final void main();\n Code:\n 0: bipush 10\n 2: newarray int\n ... |
HLQ-Struggle__LeetCodePro__76922f4/src/com/hlq/leetcode/array/Question349.kt | package com.hlq.leetcode.array
/**
* @author HLQ_Struggle
* @date 2020/11/08
* @desc LeetCode 349. 两个数组的交集 https://leetcode-cn.com/problems/intersection-of-two-arrays/
*/
fun main() {
val nums1 = IntArray(4)
nums1[0] = 1
nums1[1] = 2
nums1[2] = 2
nums1[3] = 1
val nums2 = IntArray(2)
nums2[0] = 7
nums2[1] = 9
// Set + contains
intersection(nums1, nums2)
// Kotlin intersect
intersection1(nums1, nums2)
intersection2(nums1, nums2)
// 排序 + 双指针
intersection3(nums1, nums2)
}
/**
* 排序 + 双指针
*/
fun intersection3(nums1: IntArray, nums2: IntArray): IntArray {
if (nums1.isEmpty() || nums2.isEmpty()) {
return IntArray(0)
}
var i = 0
var j = 0
var index = 0
var resultSet = hashSetOf<Int>()
nums1.sort()
nums2.sort()
while (i < nums1.size && j < nums2.size) {
if (nums1[i] == nums2[j]) {
resultSet.add(nums1[i])
i++
j++
} else if (nums1[i] < nums2[j]) {
i++
} else if (nums1[i] > nums2[j]) {
j++
}
}
var resultArray = IntArray(resultSet.size)
for (resultNum in resultSet) {
resultArray[index++] = resultNum
}
println(resultArray.asList())
return resultArray
}
/**
* Kotlin intersect
*/
fun intersection2(nums1: IntArray, nums2: IntArray): IntArray {
if (nums1.isEmpty() || nums2.isEmpty()) {
return IntArray(0)
}
return nums1.intersect(nums2.asList()).toIntArray()
}
/**
* Kotlin intersect
*/
fun intersection1(nums1: IntArray, nums2: IntArray): IntArray {
if (nums1.isEmpty() || nums2.isEmpty()) {
return IntArray(0)
}
val tempSet = nums1.asList().intersect(nums2.asList())
var resultArray = IntArray(tempSet.size)
var index = 0
for (result in tempSet) {
resultArray[index++] = result
}
println(resultArray.asList())
return resultArray
}
/**
* Set + contains
*/
fun intersection(nums1: IntArray, nums2: IntArray): IntArray {
if (nums1.isEmpty() || nums2.isEmpty()) {
return IntArray(0)
}
var tempSet = hashSetOf<Int>()
var resultSet = hashSetOf<Int>()
for (num1 in nums1) {
tempSet.add(num1)
}
for (num2 in nums2) {
if (tempSet.contains(num2)) {
resultSet.add(num2)
}
}
var resultIntArray = IntArray(resultSet.size)
var index = 0
for (resultNum in resultSet) {
resultIntArray[index++] = resultNum
}
println(resultIntArray.asList())
return resultIntArray
}
| [
{
"class_path": "HLQ-Struggle__LeetCodePro__76922f4/com/hlq/leetcode/array/Question349Kt.class",
"javap": "Compiled from \"Question349.kt\"\npublic final class com.hlq.leetcode.array.Question349Kt {\n public static final void main();\n Code:\n 0: iconst_4\n 1: newarray int\n 3: a... |
HLQ-Struggle__LeetCodePro__76922f4/src/com/hlq/leetcode/array/Question1.kt | package com.hlq.leetcode.array
/**
* @author HLQ_Struggle
* @date 2020/11/09
* @desc LeetCode 1. 两数之和 https://leetcode-cn.com/problems/two-sum/
*/
fun main() {
val nums = intArrayOf(3, 2, 4)
val target = 6
// 暴力解法 一
twoSum(nums, target)
// 优化
twoSum2(nums, target)
twoSum3(nums, target)
// 学习 LeetCode 执行用时范例
twoSum4(nums, target)
// 学习 LeetCode 执行消耗内存范例
twoSum5(nums, target)
}
/**
* 双指针解法
*/
fun twoSum(nums: IntArray, target: Int): IntArray {
// 基本校验
if (nums.isEmpty()) {
return IntArray(0)
}
var resultArray = IntArray(2)
var isl = false
var i = 0
var j = 1
while (i < nums.size - 1) {
while (j < nums.size) {
if (nums[i] + nums[j] == target) {
resultArray[0] = i
resultArray[1] = j
isl = true
break
}
j++
}
if (isl) {
break
}
i++
j = i + 1
}
return resultArray
}
/**
* 优化 一
*/
fun twoSum2(nums: IntArray, target: Int): IntArray {
// 基本校验
if (nums.isEmpty()) {
return IntArray(0)
}
var i = 0
var j = 1
while (i < nums.size - 1) {
while (j < nums.size) {
if (nums[i] + nums[j] == target) {
return intArrayOf(i, j)
}
j++
}
i++
j = i + 1
}
return intArrayOf(0, 0)
}
/**
* 继续优化
*/
fun twoSum3(nums: IntArray, target: Int): IntArray {
if (nums.isEmpty()) {
return intArrayOf(0, 0)
}
var i = 0
var j = 1
while (i < nums.size - 1) {
while (j < nums.size) {
if (nums[i] + nums[j] == target) {
return intArrayOf(i, j)
}
j++
}
i++
j = i + 1
}
return intArrayOf(0, 0)
}
/**
* 学习 LeetCode 执行用时最短事例
*/
fun twoSum4(nums: IntArray, target: Int): IntArray {
if (nums.isEmpty()) {
return intArrayOf(0, 0)
}
for (i in nums.indices) {
for (j in 0..i) {
if (i == j) {
continue
}
val a = nums[i];
val b = nums[j];
if (a + b == target) {
return intArrayOf(j, i)
}
}
}
return intArrayOf(0, 0)
}
/**
* 学习 LeetCode 执行消耗内存范例
*/
fun twoSum5(nums: IntArray, target: Int): IntArray {
if (nums.isEmpty()) {
return intArrayOf(0, 0)
}
val map: MutableMap<Int, Int> = HashMap()
for (i in nums.indices) {
val complement = target - nums[i]
if (map.containsKey(complement)) {
return intArrayOf(map[complement]!!, i)
}
map[nums[i]] = i
}
throw Exception()
} | [
{
"class_path": "HLQ-Struggle__LeetCodePro__76922f4/com/hlq/leetcode/array/Question1Kt.class",
"javap": "Compiled from \"Question1.kt\"\npublic final class com.hlq.leetcode.array.Question1Kt {\n public static final void main();\n Code:\n 0: iconst_3\n 1: newarray int\n 3: astore_... |
HLQ-Struggle__LeetCodePro__76922f4/src/com/hlq/leetcode/array/Question14.kt | package com.hlq.leetcode.array
import java.util.*
/**
* @author HLQ_Struggle
* @date 2020/11/09
* @desc LeetCode 14. 最长公共前缀 https://leetcode-cn.com/problems/longest-common-prefix/
*/
fun main() {
val strs = arrayOf("flower", "flow", "flight")
val strs1 = arrayOf("flower", "flower", "flower", "flower")
val strsNull = arrayOf("dog", "racecar", "car")
// 暴力解法 1
println("----> ${longestCommonPrefix(strs)}")
println("----> ${longestCommonPrefix(strs1)}")
println("----> ${longestCommonPrefix(strsNull)}")
// 暴力解法 2 - 3
println("----> ${longestCommonPrefix2(strs)}")
// 排序法
println("----> ${longestCommonPrefix3(strs)}")
// 获取最后一次相同位置
println("----> ${longestCommonPrefix4(strs)}")
}
fun longestCommonPrefix4(strs: Array<String>): String {
if (strs.isEmpty()) {
return ""
}
if (strs.size == 1) {
return if(strs[0].isEmpty()) "" else strs[0]
}
// 获取输入数组中最短长度
var min = Int.MAX_VALUE
for(str in strs){
if(min > str.length){
min = str.length
}
}
// 获取最后一次相同的位置
var isl = true
var index = 0
while (index < min){
for(i in strs.indices){
if(strs[0][index] != strs[i][index]){
isl = false
break
}
}
if(!isl){
break
}
index++
}
return strs[0].substring(0,index)
}
/**
* 排序法
*/
fun longestCommonPrefix3(strs: Array<String>): String {
var resultStr = ""
if (strs.isEmpty()) {
return resultStr
}
if (strs.size == 1) {
return strs[0]
}
var len = strs.size
Arrays.sort(strs)
for (i in strs[0].indices) {
if (strs[len - 1][i] == strs[0][i]) {
resultStr += strs[0][i]
} else {
break
}
}
return resultStr
}
/**
* 暴力解法 2
*/
fun longestCommonPrefix2(strs: Array<String>): String {
var resultStr = ""
if (strs.isEmpty()) {
return resultStr
}
if (strs.size == 1) {
return strs[0]
}
resultStr = strs[0]
for (i in 1 until strs.size) {
var j = 0
while (j < resultStr.length && j < strs[i].length) {
if (strs[i][j] != resultStr[j]) {
break
}
j++
}
resultStr = resultStr.substring(0, j)
if (resultStr.isEmpty()) {
break
}
}
return resultStr
}
/**
* 暴力解法 1
*/
fun longestCommonPrefix(strs: Array<String>): String {
var resultStr = ""
if (strs.isEmpty()) {
return resultStr
}
if (strs.size == 1) {
return strs[0]
}
resultStr = strs[0]
for (str in strs) {
var j = 0
while (j < resultStr.length && j < str.length) {
if (str.toCharArray()[j] != resultStr.toCharArray()[j]) {
break
}
j++
}
resultStr = resultStr.substring(0, j)
if (resultStr.isEmpty()) {
break
}
}
return resultStr
} | [
{
"class_path": "HLQ-Struggle__LeetCodePro__76922f4/com/hlq/leetcode/array/Question14Kt.class",
"javap": "Compiled from \"Question14.kt\"\npublic final class com.hlq.leetcode.array.Question14Kt {\n public static final void main();\n Code:\n 0: iconst_3\n 1: anewarray #8 ... |
elenavuceljic__advent-of-code-2022__c5093b1/src/day04/Day04.kt | package day04
import java.io.File
fun main() {
fun String.asIntRange() =
substringBefore('-').toInt()..substringAfter('-').toInt()
infix fun IntRange.contains(other: IntRange) = first <= other.first && last >= other.last
infix fun IntRange.overlaps(other: IntRange) = first <= other.last && last >= other.first
fun part1(input: String): Int {
val pairs = input.lines().map {
it.substringBefore(",").asIntRange() to it.substringAfter(",").asIntRange()
}
return pairs.count {
it.first contains it.second || it.second contains it.first
}
}
fun part2(input: String): Int {
val pairs = input.lines().map {
it.substringBefore(",").asIntRange() to it.substringAfter(",").asIntRange()
}
return pairs.count {
it.first overlaps it.second || it.second overlaps it.first
}
}
val testInput = File("src/day04/Day04_test.txt").readText().trim()
val part1Solution = part1(testInput)
val part2Solution = part2(testInput)
println(part1Solution)
check(part1Solution == 2)
check(part2Solution == 4)
val input = File("src/day04/Day04.txt").readText().trim()
println(part1(input))
println(part2(input))
}
| [
{
"class_path": "elenavuceljic__advent-of-code-2022__c5093b1/day04/Day04Kt.class",
"javap": "Compiled from \"Day04.kt\"\npublic final class day04.Day04Kt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc ... |
elenavuceljic__advent-of-code-2022__c5093b1/src/day03/Day03.kt | package day03
import java.io.File
fun main() {
fun prioritiseItem(it: Char) = if (it.isUpperCase())
(it - 'A' + 27)
else
(it - 'a' + 1)
fun part1(input: String): Int {
val rucksacks = input.lines()
val duplicateItems = rucksacks.flatMap {
val (first, second) = it.chunked(it.length / 2) { it.toSet() }
val intersect = first intersect second
intersect
}
return duplicateItems.sumOf { prioritiseItem(it) }
}
fun part2(input: String): Int {
val rucksacks = input.lines().map { it.toSet() }
val compartments = rucksacks.chunked(3).flatMap {
it.reduce(Set<Char>::intersect)
}
return compartments.sumOf { prioritiseItem(it) }
}
val testInput = File("src/day03/Day03_test.txt").readText().trim()
val part1Solution = part1(testInput)
val part2Solution = part2(testInput)
println(part1Solution)
check(part1Solution == 157)
check(part2Solution == 70)
val input = File("src/day03/Day03.txt").readText().trim()
println(part1(input))
println(part2(input))
}
| [
{
"class_path": "elenavuceljic__advent-of-code-2022__c5093b1/day03/Day03Kt.class",
"javap": "Compiled from \"Day03.kt\"\npublic final class day03.Day03Kt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc ... |
elenavuceljic__advent-of-code-2022__c5093b1/src/day02/Day02.kt | package day02
import java.io.File
enum class MyHand(val hand: Char, val scoreWorth: Int) {
X('R', 1), Y('P', 2), Z('S', 3);
}
enum class OpponentHand(val hand: Char) {
A('R'), B('P'), C('S');
}
fun scoreGame(theirs: OpponentHand, mine: MyHand): Int = when {
mine.hand == theirs.hand -> 3
(mine == MyHand.X && theirs == OpponentHand.C) || (mine == MyHand.Y && theirs == OpponentHand.A) || (mine == MyHand.Z && theirs == OpponentHand.B) -> 6
else -> 0
} + mine.scoreWorth
fun calculateHand(round: String): Int = when (round) {
"A X", "B Z", "C Y" -> 3
"B Y", "C X", "A Z" -> 2
"A Y", "B X", "C Z" -> 1
else -> 0
} + (round[2] - 'X') * 3
fun main() {
fun part1(input: String): Int {
val games = input.split("\n").map { it.split(" ") }
println(games)
val score = games.fold(0) { acc, hands ->
acc + scoreGame(OpponentHand.valueOf(hands[0]), MyHand.valueOf(hands[1]))
}
return score
}
fun part2(input: String): Int {
val games = input.split("\n")
println(games)
val score = games.fold(0) { acc, game ->
acc + calculateHand(game)
}
return score
}
val testInput = File("src/day02/Day02_test.txt").readText().trim()
val part1Solution = part1(testInput)
val part2Solution = part2(testInput)
println(part1Solution)
check(part1Solution == 15)
check(part2Solution == 12)
val input = File("src/day02/Day02.txt").readText().trim()
println(part1(input))
println(part2(input))
}
| [
{
"class_path": "elenavuceljic__advent-of-code-2022__c5093b1/day02/Day02Kt.class",
"javap": "Compiled from \"Day02.kt\"\npublic final class day02.Day02Kt {\n public static final int scoreGame(day02.OpponentHand, day02.MyHand);\n Code:\n 0: aload_0\n 1: ldc #9 // St... |
nicolegeorgieva__kotlin-practice__c96a023/kotlin-practice/src/main/kotlin/function/CalculateHoursOfStudying.kt | package function
fun main() {
var calculatedTime: Double = 2.08
val currentStudyMins = try {
calculateCurrentTimeOfStudyingInMin("18:43", "")
} catch (e: Exception) {
0
}
val currentStudy = try {
calculateCurrentTimeOfStudying(currentStudyMins)
} catch (e: Exception) {
0.0
}
calculatedTime = calculateTotalTimeOfStudying(calculatedTime, currentStudy)
println(calculatedTime.toString().split(".").let { parts ->
val mins = (parts[1] + "0").take(2)
"${parts[0]}h ${mins}m"
})
}
/**
* This fun receives the already calculated time of studying (e.g. 1.2) and current time of studying (e.g. 2.2) and
* returns a Double representing the sum of both values (3.2 in this example, which means 3h 20m).
*/
fun calculateTotalTimeOfStudying(calculatedTime: Double, currentTime: Double): Double {
return calculatedTime + currentTime
}
/**
* This fun receives currentMins and cutMins* and returns a Double value representing the currentTimeOfStudying
* (e.g. 1.2) in which "1" means 1 hour and "2" means 20 minutes. Or total - 1h 20m.
*/
fun calculateCurrentTimeOfStudying(mins: Int, cutMins: Int = 0): Double {
val reducedMins = mins - cutMins
val hour = (reducedMins / 60).toString()
val min = (reducedMins - (hour.toInt() * 60)).toString()
val res = if (min.toInt() < 10) {
"$hour.0$min".toDouble()
} else {
"$hour.$min".toDouble()
}
return res
}
// 15:20 - 16:40 (80m)
/**
* This fun receives startTime (e.g. 15:20) and endTime (e.g. 16:40) and calculates current time of studying in mins
* (80 for this example).
*/
fun calculateCurrentTimeOfStudyingInMin(startTime: String, endTime: String): Int {
val minutesPerHour = 60
val startHourInMins = startTime.removeRange(2, 5).toInt() * minutesPerHour
val totalStartTimeInMins = startHourInMins + startTime.removeRange(0, 3).toInt()
val endHourInMins = endTime.removeRange(2, 5).toInt() * minutesPerHour
val totalEndTimeInMins = endHourInMins + endTime.removeRange(0, 3).toInt()
return totalEndTimeInMins - totalStartTimeInMins
} | [
{
"class_path": "nicolegeorgieva__kotlin-practice__c96a023/function/CalculateHoursOfStudyingKt.class",
"javap": "Compiled from \"CalculateHoursOfStudying.kt\"\npublic final class function.CalculateHoursOfStudyingKt {\n public static final void main();\n Code:\n 0: ldc2_w #9 ... |
nicolegeorgieva__kotlin-practice__c96a023/kotlin-practice/src/main/kotlin/practice/Reservation.kt | package practice
//reserve a table
//input 1: peopleCount
//input 2: each person first name
//input 3: each person spending
//min consumation: 10 BGN/person (one can pay for the other). 10bgn is okay for 1 person
//reservation failed/successful (? advance need to pay && ? total)
//program says ? expense(all), advance money = 20% spending/person
fun main() {
val reservation = tableReserve()
println(reservation)
if (validateReservation(reservation)) {
println("Valid reservation.")
println("Your table's total bill is ${calculateTotalBill(reservation)}.")
println("Your table's money in advance is ${calculateAdvanceMoney(reservation)}.")
} else {
println("Invalid reservation.")
}
}
data class Reservation(val peopleCount: Int, val firstNames: List<String>, val individualBill: List<Double>)
private fun tableReserve(): Reservation {
val peopleCount = readInput("people count").toInt()
val firstNames = mutableListOf<String>()
val individualBill = mutableListOf<Double>()
for (i in 1..peopleCount) {
println("Enter person $i")
firstNames.add(readInput("first name"))
individualBill.add(readInput("individual spending").toDouble())
}
return Reservation(peopleCount, firstNames, individualBill)
}
private fun readInput(message: String): String {
println("Enter $message")
return readln()
}
fun validateReservation(reservation: Reservation): Boolean {
val tableMin = reservation.peopleCount * 10
val totalIndividualBillPlans = reservation.individualBill.sum()
return reservation.peopleCount > 0 && totalIndividualBillPlans >= tableMin
}
fun calculateAdvanceMoney(reservation: Reservation): Double {
return reservation.individualBill.sum() * 0.2
}
fun calculateTotalBill(reservation: Reservation): Double {
return reservation.individualBill.sum()
} | [
{
"class_path": "nicolegeorgieva__kotlin-practice__c96a023/practice/ReservationKt.class",
"javap": "Compiled from \"Reservation.kt\"\npublic final class practice.ReservationKt {\n public static final void main();\n Code:\n 0: invokestatic #10 // Method tableReserve:()Lpractice/Res... |
nicolegeorgieva__kotlin-practice__c96a023/kotlin-practice/src/main/kotlin/algorithms/old/WordsCount.kt | package algorithms.old
fun main() {
val text = "Hi, I'm Nicole. I've been diving deep into Software Development for about 2 years, particularly into " +
"Android Development with Kotlin and Jetpack Compose. I'm proficient in mobile UI/UX and have worked on " +
"projects related to productivity, fintech, and health. I'm genuinely passionate about tech and believe " +
"that IT has a huge role to play in our future. I’m ready to bring my expertise to exciting new challenges" +
" in Android development!"
println(text.wordsCount { it !in listOf("a", "to", "the") })
println(text.wordsCountWithDensity())
}
// Nice exercise. The exercise is under number 5. Nice.
private fun String.wordsCount(additionalWordFilter: ((String) -> Boolean)? = null): Map<String, Int> {
val wordsCountMap = mutableMapOf<String, Int>()
// Nice, exercise, The, exercise
val words = this.filter {
it != '.' && it != ',' && it != '!'
}.lowercase().split(" ")
val latest = if (additionalWordFilter != null) {
words.filter {
additionalWordFilter(it)
}
} else {
words
}
for (word in latest) {
val wordCount = wordsCountMap[word] ?: 0
wordsCountMap[word] = wordCount + 1
}
return wordsCountMap.toList().sortedByDescending { it.second }.toMap()
}
data class SeoInfo(
val wordCount: Int,
val densityPercent: Double
)
// 10 words, 3 count -> 30%
private fun String.wordsCountWithDensity(): Map<String, SeoInfo> {
val wordsCountMap = this.wordsCount()
val totalWords = wordsCountMap.size
val resMap = wordsCountMap.map {
Pair(
it.key, SeoInfo(
wordCount = it.value,
densityPercent = (it.value / totalWords.toDouble()) * 100
)
)
}.toMap()
return resMap
} | [
{
"class_path": "nicolegeorgieva__kotlin-practice__c96a023/algorithms/old/WordsCountKt.class",
"javap": "Compiled from \"WordsCount.kt\"\npublic final class algorithms.old.WordsCountKt {\n public static final void main();\n Code:\n 0: ldc #8 // String Hi, I\\'m Nicole. I... |
nicolegeorgieva__kotlin-practice__c96a023/kotlin-practice/src/main/kotlin/algorithms/new/SumOfCalibrationValues.kt | package algorithms.new
import java.io.File
fun main() {
val input = File("day1.txt").readText()
val input2 = File("new.txt").readText()
println(finalSum("www3two"))
println(finalSum(input))
println(finalSum(input2))
}
val numbers = mapOf(
Pair("one", 1),
Pair("two", 2),
Pair("three", 3),
Pair("four", 4),
Pair("five", 5),
Pair("six", 6),
Pair("seven", 7),
Pair("eight", 8),
Pair("nine", 9)
)
val finalNums = numbers + numbers.map {
val newKey = it.key.reversed()
Pair(newKey, it.value)
}
private fun finalSum(input: String): Int {
val words = getWords(input)
val res = words.map {
wordToTwoDigitNumber(it)
}.sum()
return res
}
private fun wordToTwoDigitNumber(word: String): Int {
val first = extractFirstDigit(word) ?: throw Exception("Error!")
val second = extractFirstDigit(word.reversed()) ?: first
return "$first$second".toInt()
}
private fun getWords(input: String): List<String> {
return input.split("\n")
}
private fun extractFirstDigit(word: String): Int? {
var accumulated = ""
var digit: Int? = null
for (char in word) {
if (char.isDigit()) {
digit = char.digitToInt()
break
}
accumulated += char
val number = containsTextDigit(accumulated)
if (number != null) {
digit = number
break
}
}
return digit
}
// "wwwone" -> "one"
// "www" -> null
private fun containsTextDigit(accumulated: String): Int? {
for (key in finalNums.keys) {
if (key in accumulated) {
return finalNums[key]
}
}
return null
} | [
{
"class_path": "nicolegeorgieva__kotlin-practice__c96a023/algorithms/new/SumOfCalibrationValuesKt.class",
"javap": "Compiled from \"SumOfCalibrationValues.kt\"\npublic final class algorithms.new.SumOfCalibrationValuesKt {\n private static final java.util.Map<java.lang.String, java.lang.Integer> numbers;\n... |
nicolegeorgieva__kotlin-practice__c96a023/kotlin-practice/src/main/kotlin/algorithms/new/CubeConundrum.kt | package algorithms.new
import java.io.File
fun main() {
val input = File("cubes.txt").readText()
val sets =
parseSets("Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green")
println(sumOfGamePowers(input))
}
val bag = Set(
redCubesCount = 12,
greenCubesCount = 13,
blueCubesCount = 14
)
data class Game(
val id: Int,
val sets: List<Set>
)
data class Set(
val redCubesCount: Int,
val greenCubesCount: Int,
val blueCubesCount: Int
)
private fun validGamesSum(input: String): Int {
return input.lines()
.map(::parseAsGame)
.filter(::validateGame)
.sumOf { it.id }
}
private fun sumOfGamePowers(input: String): Int {
val gamesList = input.lines()
.map(::parseAsGame)
var sum = 0
for (game in gamesList) {
val set = getFewestValidGameCubes(game.sets)
sum += powerOfFewestValidGameCubes(set)
}
return sum
}
private fun powerOfFewestValidGameCubes(set: Set): Int {
return set.redCubesCount * set.blueCubesCount * set.greenCubesCount
}
// Set(blue=2, red=3, red=1), Set(green=2, blue=3; green=4)
private fun getFewestValidGameCubes(gameSets: List<Set>): Set {
val redCount = gameSets.maxOf { it.redCubesCount }
val blueCount = gameSets.maxOf { it.blueCubesCount }
val greenCount = gameSets.maxOf { it.greenCubesCount }
return Set(redCubesCount = redCount, greenCubesCount = greenCount, blueCubesCount = blueCount)
}
// "Game 1: 4 blue, 16 green, 2 red; 5 red, 11 blue, 16 green; 9 green, 11 blue; 10 blue, 6 green, 4 red"
private fun parseAsGame(line: String): Game {
val gameId = parseGameId(line)
val gameSets = parseSets(line)
return Game(id = gameId, sets = gameSets)
}
// Game 15
private fun parseGameId(line: String): Int {
val gameTitleList = line
.split(":")
.first()
.split(" ")
return gameTitleList[1].toInt()
}
// "Game 1: 4 blue, 16 green, 2 red; 5 red, 11 blue, 16 green; 9 green, 11 blue; 10 blue, 6 green, 4 red"
private fun parseSets(line: String): List<Set> {
val lineWithoutTitle = line.split(":").last()
val sets = lineWithoutTitle.split(";")
return sets.map {
parseStringToSet(it)
}
}
// 4 blue, 16 green, 2 red
private fun parseStringToSet(input: String): Set {
var red = 0
var green = 0
var blue = 0
val inputList = input.split(",")
// 4 blue
for (i in inputList.indices) {
val current = inputList[i].filter {
it != ','
}.trim().split(" ")
when (current[1]) {
"red" -> red += current[0].toInt()
"green" -> green += current[0].toInt()
"blue" -> blue += current[0].toInt()
}
}
return Set(
redCubesCount = red,
greenCubesCount = green,
blueCubesCount = blue
)
}
private fun validateGame(game: Game): Boolean {
return game.sets.all {
validateSet(it)
}
}
// Set(redCubesCount=2, greenCubesCount=16, blueCubesCount=4)
private fun validateSet(set: Set): Boolean {
return set.redCubesCount <= bag.redCubesCount &&
set.greenCubesCount <= bag.greenCubesCount &&
set.blueCubesCount <= bag.blueCubesCount
} | [
{
"class_path": "nicolegeorgieva__kotlin-practice__c96a023/algorithms/new/CubeConundrumKt.class",
"javap": "Compiled from \"CubeConundrum.kt\"\npublic final class algorithms.new.CubeConundrumKt {\n private static final algorithms.new.Set bag;\n\n public static final void main();\n Code:\n 0: new ... |
nicolegeorgieva__kotlin-practice__c96a023/kotlin-practice/src/main/kotlin/exercise/collection/CollectionOperators3.kt | package exercise.collection
fun main() {
val employees = listOf(
Employee(
employeeId = 124,
name = "Kayla",
department = "HR",
salary = 2000.00
),
Employee(
employeeId = 125,
name = "Lulu",
department = "IT",
salary = 5600.00
),
Employee(
employeeId = 126,
name = "Amy",
department = "Customer support",
salary = 1500.00
)
)
println(filterByLetter(employees, 'U'))
}
data class Employee(
val employeeId: Int,
val name: String,
val department: String,
val salary: Double
)
fun findEmployeeById(employees: List<Employee>, id: Int): Employee? {
return employees.find { it.employeeId == id }
}
// sorts the list of employees alphabetically by their names
fun sortEmployeesByName(employees: List<Employee>): List<Employee> {
return employees.sortedBy { it.name }
}
fun filterEmployeesByDepartment(employees: List<Employee>): Map<String, List<Employee>> {
return employees.groupBy { it.department }
}
fun filterEmployeesByGivenDepartment(employees: List<Employee>, department: String): List<Employee> {
return employees.filter { it.department == department }
}
sealed interface TopNSalariesResult {
data class Error(val message: String) : TopNSalariesResult
data class Success(val list: List<Employee>) : TopNSalariesResult
}
fun findTopNSalaries(employees: List<Employee>, topN: Int): TopNSalariesResult {
if (topN <= 0 || topN > employees.size) return TopNSalariesResult.Error("Invalid criteria")
val res = employees.sortedByDescending { it.salary }.take(topN)
return TopNSalariesResult.Success(res)
}
// Pair(IT, 5600), Pair(HR, 2000)
fun calculateAverageSalaryByDepartment(employees: List<Employee>): Map<String, Double> {
val filtered = filterEmployeesByDepartment(employees)
return filtered.mapValues { (_, filtered) ->
filtered.map { it.salary }.average()
}
}
// Filter employees by a specific letter in their name
fun filterByLetter(employees: List<Employee>, letter: Char): List<Employee> {
return employees.filter { !it.name.uppercase().contains(letter.uppercase()) }
}
| [
{
"class_path": "nicolegeorgieva__kotlin-practice__c96a023/exercise/collection/CollectionOperators3Kt$findTopNSalaries$$inlined$sortedByDescending$1.class",
"javap": "Compiled from \"Comparisons.kt\"\npublic final class exercise.collection.CollectionOperators3Kt$findTopNSalaries$$inlined$sortedByDescending$... |
nicolegeorgieva__kotlin-practice__c96a023/kotlin-practice/src/main/kotlin/exercise/collection/CollectionOperators.kt | package exercise.collection
fun main() {
val students = listOf<Student>(
Student("John", 20, 3.5),
Student("Jane", 21, 3.8),
Student("Jack", 22, 3.2),
Student("J", 20, 6.0),
Student("JC", 20, 4.5)
)
println(studentsInfo(students))
}
data class Student(
val name: String,
val age: Int,
val grade: Double
)
fun sortStudentsByName(students: List<Student>): List<Student> {
return students.sortedBy { it.name }
}
fun sortStudentsByGradeDescending(students: List<Student>): List<Student> {
return students.sortedByDescending { it.grade }
}
fun filterStudentsByAgeRange(students: List<Student>, minAge: Int, maxAge: Int): List<Student> {
return students.filter { it.age in minAge..maxAge }
}
fun findTopStudents(students: List<Student>, topN: Int): List<Student> {
return students.sortedByDescending { it.grade }.take(topN)
}
fun groupByGradeRange(students: List<Student>): Map<GradeLetter, List<Student>> {
return students.groupBy { gradeDoubleToLetter(it.grade) }
}
enum class GradeLetter {
A,
B,
C,
D,
F
}
fun gradeDoubleToLetter(grade: Double): GradeLetter {
return when (grade) {
in 2.0..2.49 -> GradeLetter.F
in 2.5..3.49 -> GradeLetter.D
in 3.5..4.49 -> GradeLetter.C
in 4.5..5.49 -> GradeLetter.B
else -> {
GradeLetter.A
}
}
}
fun calculateAverageGrade(students: List<Student>): Double {
return students.map { it.grade }.average()
}
// students with grade >= 2.5 , sortedBy grade, uppercase name
fun passedStudents(students: List<Student>): List<Student> {
return students.filter { it.grade >= 2.5 }.map { it ->
Student(it.name.uppercase(), it.age, it.grade)
}
}
/*
new data class StudentInfo (1 student, belowAvg: Boolean (true if grade < avg), gradeLetter: Char)
fun studentsInfo(students: List<Student>) : List<StudentInfo>
Use fun calculateAverageGrade
Use fun gradeDoubleToLetter
*/
data class StudentInfo(
val student: Student,
val belowAverage: Boolean,
val gradeLetter: GradeLetter
)
fun studentsInfo(students: List<Student>): List<StudentInfo> {
val averageGrade = calculateAverageGrade(students)
return students.map { student ->
StudentInfo(
student = student,
belowAverage = student.grade < averageGrade,
gradeLetter = gradeDoubleToLetter(student.grade)
)
}
}
| [
{
"class_path": "nicolegeorgieva__kotlin-practice__c96a023/exercise/collection/CollectionOperatorsKt$findTopStudents$$inlined$sortedByDescending$1.class",
"javap": "Compiled from \"Comparisons.kt\"\npublic final class exercise.collection.CollectionOperatorsKt$findTopStudents$$inlined$sortedByDescending$1<T>... |
nicolegeorgieva__kotlin-practice__c96a023/kotlin-practice/src/main/kotlin/exercise/collection/CollectionOperators2.kt | package exercise.collection
fun main() {
val salesData = listOf<Sale>(
Sale("Meat", 7.0, 10),
Sale("Fish", 5.0, 5),
Sale("Snack", 3.0, 2),
Sale("Bread", 1.0, 5),
Sale("Nuts", 2.0, 9),
Sale("Chocolate", 3.0, 5)
)
println(calculateTotalProfit(salesData, 1.0))
}
/*
You are given a list of sales data represented as objects with the following
properties: productName (String), price (Double), and quantitySold (Int).
Your task is to create a Kotlin program that performs various operations on the list using collection operators.
*/
data class Sale(
val productName: String,
val price: Double,
val quantitySold: Int
)
fun calculateTotalRevenue(salesData: List<Sale>): Double {
return salesData.sumOf { it.price * it.quantitySold }
}
fun findMostSoldProduct(salesData: List<Sale>): String {
return try {
salesData.maxBy { it.quantitySold }.productName
} catch (e: Exception) {
"Invalid data"
}
}
fun filterSalesByPriceRange(salesData: List<Sale>, minPrice: Double, maxPrice: Double): List<String> {
return salesData.filter { it.price in minPrice..maxPrice }
.sortedByDescending { it.price }
.map { "${it.productName}: ${it.price}" }
}
fun findTopNSellingProducts(salesData: List<Sale>, topN: Int): List<String> {
return salesData.sortedByDescending { it.quantitySold }
.take(topN)
.map { "${it.productName}: ${it.quantitySold} sold" }
}
enum class PriceCategory {
Low,
Medium,
High
}
data class SaleWithProfit(
val saleData: Sale,
val profit: Double
)
fun calculatePriceCategory(price: Double): PriceCategory {
return when (price) {
in 0.0..2.0 -> PriceCategory.Low
in 2.01..3.0 -> PriceCategory.Medium
else -> PriceCategory.High
}
}
fun groupByPriceCategory(salesData: List<Sale>): Map<PriceCategory, List<Sale>> {
return salesData.groupBy { calculatePriceCategory(it.price) }
}
fun calculateTotalProfit(salesData: List<Sale>, fixedCostPerProduct: Double): List<String> {
return salesData.map {
SaleWithProfit(saleData = it, profit = (it.price * it.quantitySold) - (fixedCostPerProduct * it.quantitySold))
}
.map {
"${it.saleData.productName} - ${it.profit} profit"
}
} | [
{
"class_path": "nicolegeorgieva__kotlin-practice__c96a023/exercise/collection/CollectionOperators2Kt.class",
"javap": "Compiled from \"CollectionOperators2.kt\"\npublic final class exercise.collection.CollectionOperators2Kt {\n public static final void main();\n Code:\n 0: bipush 6\n ... |
ModestosV__Simple-Calculator-DreamTeam__3b7b7eb/app/src/main/kotlin/com/simplemobiletools/calculator/helpers/StatFunctions.kt | package com.simplemobiletools.calculator.helpers
fun updateStats(results: ArrayList<String>){
getMean(results)
getMedian(results)
getMode(results)
getRange(results)
}
fun getMean(results: ArrayList<String>): String{
var avg = 0.0
for(r in results) {
if(r.isEmpty())
return ""
avg += r.replace(",","").toDouble()
}
avg /= results.size
return String.format(java.util.Locale.US,"%.2f", avg)
}
fun getMedian(results: ArrayList<String>): String{
for(r in results) {
if (r.isEmpty())
return ""
}
val listOfSortedResults = sortListOfStringsOfDoubles(results)
return if(listOfSortedResults.size % 2 == 0) {
((listOfSortedResults[listOfSortedResults.size / 2] + listOfSortedResults[listOfSortedResults.size / 2 - 1]) / 2).toString()
} else {
(listOfSortedResults[listOfSortedResults.size / 2]).toString()
}
}
fun getMode(results: ArrayList<String>): String{
for(r in results) {
if (r.isEmpty())
return ""
}
val storeValues = hashMapOf<String, Int>()
val listOfModes = arrayListOf<String>()
var highestCount = 0
//Get count of each occurrence
for(r in results){
if(storeValues[r] == null)
storeValues[r] = 1
else{
val count = storeValues[r]
storeValues[r] = count!! + 1
}
}
//Store highest count
for(s in storeValues){
if(highestCount < s.value)
highestCount = s.value
}
//Every number with an equal highest count is added to return list
for(s in storeValues){
if(s.value == highestCount)
listOfModes.add(s.key)
}
val listOfSortedModes = sortListOfStringsOfDoubles(listOfModes)
return listOfSortedModes.toString()
}
fun getRange(results: ArrayList<String>): String {
for(r in results) {
if (r.isEmpty())
return ""
}
val listOfSortedModes = sortListOfStringsOfDoubles(results)
return (listOfSortedModes.last() - listOfSortedModes.first()).toString()
}
private fun sortListOfStringsOfDoubles(listOfStringOfDoubles: ArrayList<String>): ArrayList<Double> {
val listOfDoubles = ArrayList<Double>()
for(l in listOfStringOfDoubles){
listOfDoubles.add(l.replace(",","").toDouble())
}
listOfDoubles.sort()
return listOfDoubles
}
| [
{
"class_path": "ModestosV__Simple-Calculator-DreamTeam__3b7b7eb/com/simplemobiletools/calculator/helpers/StatFunctionsKt.class",
"javap": "Compiled from \"StatFunctions.kt\"\npublic final class com.simplemobiletools.calculator.helpers.StatFunctionsKt {\n public static final void updateStats(java.util.Arra... |
dzirbel__robopower__6c6f0a1/lib/src/main/kotlin/com/dzirbel/robopower/util/MapExtensions.kt | package com.dzirbel.robopower.util
/**
* Returns the key(s) whose associated values are the largest according to [comparator].
*/
internal fun <K, V> Map<K, V>.maxKeysBy(comparator: Comparator<V>): Set<K> {
val iterator = iterator()
if (!iterator.hasNext()) throw NoSuchElementException()
val first = iterator.next()
var maxValue = first.value
val maxKeys = mutableSetOf(first.key)
while (iterator.hasNext()) {
val (key, value) = iterator.next()
val comparison = comparator.compare(value, maxValue)
if (maxValue == null || comparison > 0) {
maxValue = value
maxKeys.clear()
maxKeys.add(key)
} else if (comparison == 0) {
maxKeys.add(key)
}
}
return maxKeys
}
/**
* Returns the first key (or an arbitrary key for unordered maps) whose value yields the maximum non-null result for
* [selector].
*/
fun <K, V, R : Comparable<R>> Map<K, V>.maxKeyByOrNull(selector: (V) -> R?): K? {
return this
.mapNotNull { (key, value) -> selector(value)?.let { key to it } }
.maxByOrNull { (_, value) -> value }
?.first
}
| [
{
"class_path": "dzirbel__robopower__6c6f0a1/com/dzirbel/robopower/util/MapExtensionsKt.class",
"javap": "Compiled from \"MapExtensions.kt\"\npublic final class com.dzirbel.robopower.util.MapExtensionsKt {\n public static final <K, V> java.util.Set<K> maxKeysBy(java.util.Map<K, ? extends V>, java.util.Comp... |
igorakkerman__maxtableprod-challenge__c8d705f/src/main/kotlin/de/igorakkerman/challenge/maxtableprod/MaxTableProd.kt | package de.igorakkerman.challenge.maxtableprod
import java.lang.Integer.max
class MaxTableProd(val prodSize: Int, numbersTable: String) {
val numbers: List<List<Int>>
val width: Int
val height: Int
init {
numbers = numbersTable
.lines()
.map { it.trim() }
.filter { it.isNotEmpty() }
.map { it.split(' ') }
.map { it.map { it.toInt() } }
if (prodSize < 1)
throw IllegalArgumentException("prodSize=${prodSize}<1")
height = numbers.size
if (height < prodSize)
throw IllegalArgumentException("height=${height}<${prodSize}=prodSize")
width = numbers[0].size
if (width < prodSize)
throw IllegalArgumentException("row 0 width=${width}<${prodSize}=prodSize")
numbers.forEachIndexed { rowIndex, row ->
if (row.size != width)
throw IllegalArgumentException("row ${rowIndex} width=${row.size}!=${width}")
}
}
internal fun maxHorizontalProd(): Int {
var maxProd = 0
for (i in (0 until height)) {
for (j in (0 .. width - prodSize)) {
maxProd = max(maxProd, (0 until prodSize).map { numbers[i][j + it] }.reduce { x, y -> x * y })
}
}
return maxProd
}
internal fun maxVerticalProd(): Int {
var maxProd = 0
for (j in (0 until width)) {
for (i in (0 .. height - prodSize)) {
maxProd = max(maxProd, (0 until prodSize).map { numbers[i + it][j] }.reduce { x, y -> x * y })
}
}
return maxProd
}
internal fun maxDiagonalLeftProd(): Int {
var maxProd = 0
for (i in (prodSize - 1 until height)) {
for (j in (prodSize - 1 until width)) {
maxProd = max(maxProd, (0 until prodSize).map { numbers[i - it][j - it] }.reduce { x, y -> x * y })
}
}
return maxProd
}
internal fun maxDiagonalRightProd(): Int {
var maxProd = 0
for (i in (prodSize - 1 until height)) {
for (j in (0 .. width - prodSize)) {
val fn = { k: Int -> numbers[i - k][j + k] }
maxProd = max(maxProd, (0 until prodSize).map(fn).reduce { x, y -> x * y })
}
}
return maxProd
}
}
| [
{
"class_path": "igorakkerman__maxtableprod-challenge__c8d705f/de/igorakkerman/challenge/maxtableprod/MaxTableProd.class",
"javap": "Compiled from \"MaxTableProd.kt\"\npublic final class de.igorakkerman.challenge.maxtableprod.MaxTableProd {\n private final int prodSize;\n\n private final java.util.List<ja... |
aesean__TwentyFour__666ae03/app/src/main/java/com/aesean/twentyfour/CalculateImpl.kt | package com.aesean.twentyfour
import java.math.BigDecimal
import java.util.*
interface CalculateRule {
fun size(): Int
fun calculate(a: String, index: Int, b: String): String
fun symbol(index: Int): String
fun deviation(): String
}
fun main(args: Array<String>) {
test("8,8,3,3")
test("5,5,5,1")
}
private fun String.format(): String {
return String.format("%2.1f", this.toFloat())
}
private fun test(s: String) {
val numbers = s.split(",")
val nodes = MutableList(numbers.size) {
Node(numbers[it])
}
val tree = Tree(nodes, CalculateRuleByBigDecimal())
tree.find {
if (Math.abs(it.number.toDouble() - 24) < 0.0000000001) {
println("${it.desc} = ${it.number.format()}")
}
}
println("**********")
tree.find {
if (Math.abs(it.number.toDouble()) <= 10) {
println("${it.desc} = ${it.number.format()}")
}
}
}
class CalculateRuleNormal : CalculateRule {
companion object {
val SYMBOLS = arrayOf("+", "-", "×", "÷")
const val DEVIATION = "0.00001"
}
override fun symbol(index: Int): String {
return SYMBOLS[index]
}
override fun calculate(a: String, index: Int, b: String): String {
val numA = a.toDouble()
val numB = b.toDouble()
when (index) {
0 -> {
return (numA + numB).toString()
}
1 -> {
return (numA - numB).toString()
}
2 -> {
return (numA * numB).toString()
}
3 -> {
if (numB == 0.0) {
throw RuntimeException("Can't multiply 0")
}
return (numA / numB).toString()
}
else -> {
throw RuntimeException("Unknown index")
}
}
}
override fun size(): Int {
return SYMBOLS.size
}
override fun deviation(): String {
return DEVIATION
}
override fun toString(): String {
return "CalculateRuleNormal{SYMBOLS = ${Arrays.toString(SYMBOLS)}, deviation = ${deviation()}}"
}
}
class CalculateRuleByBigDecimal : CalculateRule {
companion object {
val SYMBOLS = arrayOf("+", "-", "×", "÷")
const val DEVIATION = "0.00000000001"
}
override fun symbol(index: Int): String {
return SYMBOLS[index]
}
override fun calculate(a: String, index: Int, b: String): String {
val numA = BigDecimal(a)
val numB = BigDecimal(b)
when (index) {
0 -> {
return numA.add(numB).toString()
}
1 -> {
return numA.subtract(numB).toString()
}
2 -> {
return numA.multiply(numB).toString()
}
3 -> {
return numA.divide(numB, 16, BigDecimal.ROUND_HALF_UP).toString()
}
else -> {
throw RuntimeException("Unknown index")
}
}
}
override fun size(): Int {
return SYMBOLS.size
}
override fun deviation(): String {
return DEVIATION
}
override fun toString(): String {
return "CalculateRuleByBigDecimal{SYMBOLS = ${Arrays.toString(SYMBOLS)}, deviation = ${deviation()}}"
}
}
class Tree(private val nodes: MutableList<Node>, private val calculateRule: CalculateRule) {
private val nodeArrangement = Arrangement(nodes.size)
fun find(filter: (result: Node) -> Unit) {
nodeArrangement.traversal { left: Int, right: Int ->
val leftNode = nodes[left]
val rightNode = nodes[right]
for (symbolIndex in 0 until calculateRule.size()) {
val nextNodes: MutableList<Node> = ArrayList(nodes.size - 2)
nodes.forEachIndexed { index, value ->
if ((index != left) and (index != right)) {
nextNodes.add(value)
}
}
val number: String
try {
number = calculateRule.calculate(leftNode.number, symbolIndex, rightNode.number)
} catch (e: Exception) {
continue
}
val node = Node(number)
node.desc = "(${leftNode.desc}${calculateRule.symbol(symbolIndex)}${rightNode.desc})"
nextNodes.add(node)
if (nextNodes.size > 1) {
Tree(nextNodes, calculateRule).find(filter)
} else {
val n = nextNodes[0]
filter.invoke(n)
}
}
}
}
fun size(): Int {
return nodes.size
}
}
class Node(var number: String) {
var desc: String = number
override fun toString(): String {
return desc
}
}
class Arrangement(val size: Int) {
private var mainIndex: Int = -1
private var childIndex: Int = -1
init {
if (size < 2) {
throw RuntimeException("size should be >= 2. ")
}
}
private fun next(): Boolean {
if ((mainIndex == -1) and (childIndex == -1)) {
mainIndex = 0
childIndex = 1
return true
}
childIndex++
var check = false
if (childIndex < size) {
check = true
} else {
childIndex = 0
mainIndex++
if (mainIndex < size) {
check = true
}
}
if (check) {
return if (mainIndex == childIndex) {
next()
} else {
true
}
}
return false
}
fun traversal(result: (left: Int, right: Int) -> Unit) {
mainIndex = -1
childIndex = -1
while (next()) {
result.invoke(mainIndex, childIndex)
}
}
} | [
{
"class_path": "aesean__TwentyFour__666ae03/com/aesean/twentyfour/CalculateImplKt.class",
"javap": "Compiled from \"CalculateImpl.kt\"\npublic final class com.aesean.twentyfour.CalculateImplKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc #9 ... |
danielkr__adventofcode2017__366bacf/src/main/kotlin/dk/aoc/day13.kt | package dk.aoc.day13
import java.io.File
import java.util.*
val LAYER_PATTERN = Regex("""(\d+): (\d+)""")
fun main(args: Array<String>) {
val inputFile = File("src/main/resources/inputs/day13.txt")
val lines = inputFile.readLines()
val layers = parseLayers(lines)
val severity = calculateSeverity(layers)
println(severity)
}
fun parseLayers(lines: List<String>): SortedMap<Int, Int> {
val res = TreeMap<Int, Int>()
lines.forEach {
val result = LAYER_PATTERN.find(it)
if (result != null) {
res.put(result.groupValues[1].toInt(), result.groupValues[2].toInt())
}
}
return res
}
fun calculateSeverity(layers : SortedMap<Int, Int>) =
layers.entries.sumBy {
layerSeverity(it.key, it.value)
}
fun layerSeverity(depth : Int, range : Int) =
if (isCaught(depth, range))
depth * range
else
0
fun isCaught(depth: Int, range: Int) : Boolean {
val periodocity = (range - 1) * 2;
return range == 1 || depth % periodocity == 0
}
| [
{
"class_path": "danielkr__adventofcode2017__366bacf/dk/aoc/day13/Day13Kt.class",
"javap": "Compiled from \"day13.kt\"\npublic final class dk.aoc.day13.Day13Kt {\n private static final kotlin.text.Regex LAYER_PATTERN;\n\n public static final kotlin.text.Regex getLAYER_PATTERN();\n Code:\n 0: gets... |
grine4ka__samokatas__c967e89/codeforces/round573/TokitsukazeMadjong.kt | package codeforces.round573
// https://codeforces.com/contest/1191/problem/B
fun main(args: Array<String>) {
val listM = arrayOf(0, 0, 0, 0, 0, 0, 0, 0, 0)
val listP = arrayOf(0, 0, 0, 0, 0, 0, 0, 0, 0)
val listS = arrayOf(0, 0, 0, 0, 0, 0, 0, 0, 0)
val input = readLine()!!.split(" ").map {
Card(it[0].toString().toInt(), it[1].toString())
}
input.forEach {
when(it.type) {
"m" -> listM[it.number-1]++
"p" -> listP[it.number-1]++
"s" -> listS[it.number-1]++
}
}
val koutsuM = listM.max()!!
val shuntsuM = shuntsu(listM)
if (koutsuM >= 3 || shuntsuM >= 3) {
println("0")
return
}
val koutsuP = listP.max()!!
val shuntsuP = shuntsu(listP)
if (koutsuP >= 3 || shuntsuP >= 3) {
println("0")
return
}
val koutsuS = listS.max()!!
val shuntsuS = shuntsu(listS)
if (koutsuS >= 3 || shuntsuS >= 3) {
println("0")
return
}
if (koutsuM >= 2 || shuntsuM >= 2 ||
koutsuS >= 2 || shuntsuS >= 2 ||
koutsuP >= 2 || shuntsuP >= 2) {
println("1")
return
}
println("2")
}
// return the number of subsequence > 0
fun shuntsu(list: Array<Int>): Int {
val seq = ArrayList<Triple<Int, Int, Int>>()
for (i in 0 until 7) {
seq.add(Triple(list[i], list[i+1], list[i+2]))
}
var one = 0
var two = 0
for (triple in seq) {
if (triple.first > 0 && triple.second > 0 && triple.third > 0) {
return 3
} else if (triple.first > 0 && triple.second > 0) {
two++
} else if (triple.first > 0 && triple.third > 0) {
two++
} else if (triple.second > 0 && triple.third > 0) {
two++
} else if (triple.first > 0 || triple.second > 0 || triple.third > 0) {
one++
}
}
if (two > 0) return 2
if (one > 0) return 1
return 0
}
class Card(val number: Int, val type: String) | [
{
"class_path": "grine4ka__samokatas__c967e89/codeforces/round573/TokitsukazeMadjongKt.class",
"javap": "Compiled from \"TokitsukazeMadjong.kt\"\npublic final class codeforces.round573.TokitsukazeMadjongKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc ... |
grine4ka__samokatas__c967e89/codeforces/eduround68/YetAnotherCrossesProblem.kt | package codeforces.eduround68
import java.io.PrintWriter
import kotlin.math.min
// https://codeforces.com/contest/1194/problem/B
// this is mine
//fun eduround68.eduround68.eduround68.round567.round567.round573.codeforces.codeforces.codeforces.eduround69.kotlinheroes.kotlinheroes.main(args: Array<String>) {
// val q = eduround68.readInt()
// val matrices = mutableListOf<Matrix>()
// for (i in 0 until q) {
// val (n, m) = eduround68.readInts()
// val matrix = Matrix(n, m)
// for (j in 0 until n) {
// matrix.fillRow(j, readLine()!!)
// }
// matrices.add(matrix)
// }
// matrices.forEach {
// println("${it.findMinMinutesForCrosses()}")
// }
//}
//
//class Matrix(val n: Int, val m: Int) {
//
// private val body = Array(n) {
// IntArray(m)
// }
//
// private val tbody = Array(m) {
// IntArray(n)
// }
//
// fun fillRow(row: Int, symbols: String) {
// val r = body[row]
// symbols.forEachIndexed { index, c ->
// r[index] = if (c == '*') 1 else 0
// tbody[index][row] = if (c == '*') 1 else 0
// }
// }
//
// fun findMinMinutesForCrosses(): Int {
// var minSum = Int.MAX_VALUE
// for (i in 0 until n) {
// val rowSum = m - body[i].sum()
// for (j in 0 until m) {
// val colSum = n - tbody[j].sum()
// val sub = 1 - body[i][j]
// val sum = rowSum + colSum - sub
// if (sum < minSum) {
// minSum = sum
// }
// }
// }
// return minSum
// }
//}
// this is elizarov's
fun main() {
val q = readInt()
bufferOut {
repeat(q) { solveQuery() }
}
}
private fun PrintWriter.solveQuery() {
val (n, m) = readInts()
val a = Array(n) { readLine()!!.map { it == '*' }.toBooleanArray() }
val rowSums = IntArray(n)
val colSums = IntArray(m)
for (i in 0 until n) {
for(j in 0 until m) {
if (a[i][j]) {
rowSums[i]++
colSums[j]++
}
}
}
if (rowSums.any { it == m } && colSums.any { it == n }) {
println(0)
return
}
var ans = Int.MAX_VALUE
for (i in 0 until n) {
for(j in 0 until m) {
var d = n + m - rowSums[i] - colSums[j]
if (!a[i][j]) d--
ans = min(ans, d)
}
}
println(ans)
}
private fun readInt() = readLine()!!.toInt()
private fun readInts() = readLine()!!.split(" ").map(String::toInt)
// for the future
private fun bufferOut(block: PrintWriter.() -> Unit) = PrintWriter(System.out).use { block(it) } | [
{
"class_path": "grine4ka__samokatas__c967e89/codeforces/eduround68/YetAnotherCrossesProblemKt.class",
"javap": "Compiled from \"YetAnotherCrossesProblem.kt\"\npublic final class codeforces.eduround68.YetAnotherCrossesProblemKt {\n public static final void main();\n Code:\n 0: invokestatic #10 ... |
grine4ka__samokatas__c967e89/stepik/sportprogramming/UnlimitedAudienceApplicationsGreedyAlgorithm.kt | package stepik.sportprogramming
import java.io.File
fun main() {
val rooms = IntArray(33000) { 0 }
val applications = readFromFile()
println("Max of applications is ${count(rooms, applications)}")
}
private fun readFromFile(): MutableList<AudienceApplication> {
val applications = mutableListOf<AudienceApplication>()
File("stepik/sportprogramming/request2unlim.in").forEachLine {
applications.add(readApplication(it))
}
return applications
}
private fun readFromInput(): MutableList<AudienceApplication> {
val applications = mutableListOf<AudienceApplication>()
val n = readInt()
repeat(n) {
applications.add(readApplication(readLine()!!))
}
return applications
}
private fun count(rooms: IntArray, applications: List<AudienceApplication>): Int {
for (application in applications) {
for (i in application.left until application.right) {
rooms[i]++
}
}
return rooms.max()!!
}
private class AudienceApplication(val left: Int, val right: Int)
private fun readInt() = readLine()!!.trim().toInt()
private fun readApplication(string: String): AudienceApplication {
val ints = string.split(" ").map { it.trim().toInt() }.toIntArray()
return AudienceApplication(ints[0], ints[1])
}
private fun readInts() = readLine()!!.split(" ").map(String::toInt).toIntArray()
| [
{
"class_path": "grine4ka__samokatas__c967e89/stepik/sportprogramming/UnlimitedAudienceApplicationsGreedyAlgorithmKt.class",
"javap": "Compiled from \"UnlimitedAudienceApplicationsGreedyAlgorithm.kt\"\npublic final class stepik.sportprogramming.UnlimitedAudienceApplicationsGreedyAlgorithmKt {\n public stat... |
grine4ka__samokatas__c967e89/stepik/sportprogramming/ScheduleGreedyAlgorithm.kt | package stepik.sportprogramming
private const val MAX_DAYS = 5000
private val used: BooleanArray = BooleanArray(MAX_DAYS) { false }
private val orders = mutableListOf<Order>()
fun main() {
val n = readInt()
repeat(n) {
orders.add(readOrder())
}
val sortedByDeadlineOrders = orders.sortedDescending()
var sum: Long = 0
for (i in 0 until sortedByDeadlineOrders.size) {
val order = sortedByDeadlineOrders[i]
var k = order.deadline
while (k >= 1 && used[k]) {
k--
}
if (k == 0) {
continue
}
used[k] = true
sum += order.cost
}
println("Maximum sum of all orders will be $sum")
}
private class Order(val deadline: Int, val cost: Int) : Comparable<Order> {
override fun compareTo(other: Order): Int {
return cost - other.cost
}
}
private fun readInt() = readLine()!!.toInt()
private fun readOrder(): Order {
val pairOfInts = readLine()!!.split(" ").map(String::toInt).toIntArray()
return Order(pairOfInts[0], pairOfInts[1])
}
| [
{
"class_path": "grine4ka__samokatas__c967e89/stepik/sportprogramming/ScheduleGreedyAlgorithmKt.class",
"javap": "Compiled from \"ScheduleGreedyAlgorithm.kt\"\npublic final class stepik.sportprogramming.ScheduleGreedyAlgorithmKt {\n private static final int MAX_DAYS;\n\n private static final boolean[] use... |
grine4ka__samokatas__c967e89/stepik/sportprogramming/ContuneousBagProblemGreedyAlgorithm.kt | package stepik.sportprogramming
private val things = mutableListOf<Thing>()
fun main() {
val (n, maxWeight) = readPair()
repeat(n) {
things.add(readThing())
}
println("Maximum value of all things is ${solution(maxWeight)}")
}
private fun solution(maxWeight: Int): Int {
val sortedByValue = things.sortedDescending()
var sum = 0
var sumWeight: Int = maxWeight
for (i in 0 until sortedByValue.size) {
if (sumWeight <= 0) {
break
}
val thing = sortedByValue[i]
if (sumWeight >= thing.weight) {
sumWeight -= thing.weight
sum += thing.cost
} else {
sum += (sumWeight * thing.getValue())
sumWeight -= thing.weight
}
}
return sum
}
private class Thing(val weight: Int, val cost: Int) : Comparable<Thing> {
override fun compareTo(other: Thing): Int {
return getValue() - other.getValue()
}
fun getValue(): Int {
return cost / weight
}
}
private fun readPair(): Pair<Int, Int> {
val conditions = readLine()!!.split(" ").map(String::toInt).toIntArray()
return Pair(conditions[0], conditions[1])
}
private fun readThing(): Thing {
val thing = readLine()!!.split(" ").map(String::toInt).toIntArray()
return Thing(thing[0], thing[1])
}
| [
{
"class_path": "grine4ka__samokatas__c967e89/stepik/sportprogramming/ContuneousBagProblemGreedyAlgorithmKt.class",
"javap": "Compiled from \"ContuneousBagProblemGreedyAlgorithm.kt\"\npublic final class stepik.sportprogramming.ContuneousBagProblemGreedyAlgorithmKt {\n private static final java.util.List<st... |
grine4ka__samokatas__c967e89/stepik/sportprogramming/RecursiveComivoigerSolution.kt | package stepik.sportprogramming
private var a: Array<IntArray> = emptyArray()
private var ans: Int = Int.MAX_VALUE
private var ansPerm: String = ""
private var p: IntArray = intArrayOf()
private var used: BooleanArray = booleanArrayOf()
private var n: Int = 0
fun main() {
n = readInt()
a = Array(n) {
readInts()
}
p = IntArray(n) { 0 }
used = BooleanArray(n) { false }
p[0] = 0
recNew(1, 0)
println("The shortest path is $ansPerm with value $ans")
}
private fun recNew(idx: Int, len: Int) {
if (len >= ans) {
return
}
if (idx == n) {
val length = len + a[p[idx - 1]][0]
if (length < ans) {
ansPerm = p.joinToString(prefix = "{", postfix = "}")
ans = length
}
return
}
for (i in 1 until n) {
if (used[i]) continue
p[idx] = i
used[i] = true
recNew(idx + 1, len + a[p[idx - 1]][i])
used[i] = false
}
}
private fun readInt() = readLine()!!.toInt()
private fun readInts() = readLine()!!.split(" ").map(String::toInt).toIntArray()
| [
{
"class_path": "grine4ka__samokatas__c967e89/stepik/sportprogramming/RecursiveComivoigerSolutionKt.class",
"javap": "Compiled from \"RecursiveComivoigerSolution.kt\"\npublic final class stepik.sportprogramming.RecursiveComivoigerSolutionKt {\n private static int[][] a;\n\n private static int ans;\n\n pr... |
grine4ka__samokatas__c967e89/stepik/sportprogramming/LongestCommonSubsequenceDynamicProgramming.kt | package stepik.sportprogramming
import java.io.File
import java.io.PrintWriter
import java.util.*
import kotlin.math.max
fun main() {
output {
val n = readInt()
val a = readIntArray(n)
val m = readInt()
val b = readIntArray(m)
val d = Array(n + 1) {
IntArray(m + 1)
}
for (i in 0..n) {
d[i][0] = 0
}
for (j in 0..m) {
d[0][j] = 0
}
val path = Array(n + 1) { IntArray(m + 1) }
for (i in 1..n) {
for (j in 1..m) {
if (d[i - 1][j] > d[i][j - 1]) {
d[i][j] = d[i - 1][j]
path[i][j] = d[i-1][j]
} else {
d[i][j] = d[i][j - 1]
path[i][j] = d[i][j - 1]
}
if (a[i - 1] == b[j - 1] && (d[i - 1][j - 1] + 1 > d[i][j])) {
d[i][j] = d[i - 1][j - 1] + 1
path[i][j] = d[i - 1][j - 1] + 1
}
}
}
println("Longest common subsequence is ${d[n][m]}")
println("Path of longest subsequence is ")
recout(path, a, n, m)
}
}
private fun PrintWriter.recout(p: Array<IntArray>, a: IntArray, i: Int, j: Int) {
if (i <= 0 || j <= 0) {
return
}
when {
p[i][j] == p[i - 1][j] -> recout(p, a, i - 1, j)
p[i][j] == p[i][j - 1] -> recout(p, a, i, j - 1)
else -> {
recout(p, a, i - 1, j - 1)
print("${a[i - 1]} ")
}
}
}
/** IO code start */
//private val INPUT = System.`in`
private val INPUT = File("stepik/sportprogramming/seq2.in").inputStream()
private val OUTPUT = System.out
private val reader = INPUT.bufferedReader()
private var tokenizer: StringTokenizer = StringTokenizer("")
private fun read(): String {
if (tokenizer.hasMoreTokens().not()) {
tokenizer = StringTokenizer(reader.readLine() ?: return "", " ")
}
return tokenizer.nextToken()
}
private fun readLn() = reader.readLine()!!
private fun readInt() = read().toInt()
private fun readIntArray(n: Int) = IntArray(n) { read().toInt() }
private val writer = PrintWriter(OUTPUT, false)
private inline fun output(block: PrintWriter.() -> Unit) {
writer.apply(block).flush()
}
| [
{
"class_path": "grine4ka__samokatas__c967e89/stepik/sportprogramming/LongestCommonSubsequenceDynamicProgrammingKt.class",
"javap": "Compiled from \"LongestCommonSubsequenceDynamicProgramming.kt\"\npublic final class stepik.sportprogramming.LongestCommonSubsequenceDynamicProgrammingKt {\n private static fi... |
remisultan__multiarm-bandit-algorithm-kotlin__ead934d/core-bandit/src/main/kotlin/org/rsultan/bandit/algorithms/BanditAlgorithm.kt | package org.rsultan.bandit.algorithms
import java.security.SecureRandom
interface BanditAlgorithm {
fun selectArm(): Int
fun update(chosenArm: Int, reward: Float)
}
abstract class AbstractBanditAlgorithm(nbArms: Int) : BanditAlgorithm {
protected val random = SecureRandom()
protected val counts = (1..nbArms).map { 0 }.toTypedArray()
protected val values = (1..nbArms).map { 0.0f }.toTypedArray()
override fun update(chosenArm: Int, reward: Float) {
val armCount = ++counts[chosenArm]
val armValue = values[chosenArm]
values[chosenArm] = ((armCount - 1) / armCount.toFloat()) * armValue + (1 / armCount.toFloat()) * reward
}
}
abstract class AbstractSoftmaxAlgorithm(nbArms: Int) : AbstractBanditAlgorithm(nbArms) {
fun categoricalDraw(probabilities: List<Float>): Int {
val rand = random.nextFloat()
var cumulativeProbability = 0.0f
for (i in probabilities.indices) {
cumulativeProbability += probabilities[i]
if (cumulativeProbability > rand) {
return i
}
}
return probabilities.lastIndex
}
}
| [
{
"class_path": "remisultan__multiarm-bandit-algorithm-kotlin__ead934d/org/rsultan/bandit/algorithms/BanditAlgorithm.class",
"javap": "Compiled from \"BanditAlgorithm.kt\"\npublic interface org.rsultan.bandit.algorithms.BanditAlgorithm {\n public abstract int selectArm();\n\n public abstract void update(i... |
waploaj__Masomo__6a44d60/src/main/kotlin/complexity/Complexity.kt | package complexity
// ------------------------------ Time complexity ----------------------------------
//Big O notation for the different level of scalability in two dimension
//-- Execution time
//-- Memory Usage
//Time complexity - is the time it take for algorithm to run compare with data size.
//Constant Time - is the same running time regardless of an input size.
fun checkFirst(name: List<String>){
if(name.firstOrNull()!=null){
println(name.first())
}else
println("No name")
}
//Liner time complexity - As the input increase the time to execute also increase
fun printName(names:List<String>){
for (element in names){
println(element)
}
}
//Quadratic Time Complexity - refer to algorithm that takes time proportional to the square input size.
//Big O notation for quadratic time is = O(n^2)
fun multiplicationBoard(n:Int){
for (number in 1 ..n){
print("|")
for (otherNumber in 1..n){
println("$number * $otherNumber = ${number * otherNumber}|")
}
}
}
//Logarithmic Time Complexity -
fun linearContains(value:Int, numbers:List<Int>):Boolean {
for(element in numbers) {
return value == element
}
return false
}
//This is not efficient lets sort the values of number and divide in half
//As input increase the time takes to execute the algorithm increase at slowly rate.
//Big O notation for logarithm time complexity is Q(log n)
fun pseudoBinaryContains(value: Int, numbers: List<Int>):Boolean {
if (numbers.isEmpty()) return false
numbers.sorted()
val middleIndex = numbers.size/2
if (value <= numbers[middleIndex]){
for (element in 0 .. middleIndex){
return (numbers[element] == value)
}
}else{
for (elements in middleIndex until numbers.size){
return numbers[elements] == value
}
}
return false
}
//Quasilinear Time Complexity - perform worse than liner time but dramatically better than quadratic time.
//Other complexity time (polynomial , exponential and factorial time).
//NOTE: for small data sets, time complexity may not be an accurate measure of speed.
//Comparing Time complexity.
//suppose you find sums of numbers from 1 to n
fun sumFromOne(n:Int):Int{
var result = 0
for (i in 1..n){
result += i
}
return result
}
//This sum can be rewritten also with reduce function
//The time complexity of reduce function it also Q(n)
fun sumFromOnes(n:Int):Int{
return (1..n).reduce { element, sum -> sum + element }
}
//We can use the famous mathematician <NAME>
//That use the time complexity constant Q(1)
fun sumFrom1(n:Int):Int{
return n * (n + 1)/2
}
//--------------------------------------- Space complexity ---------------------------------
//space complexity - is measure of the resources for algorithm required to manipulate input data.
//Let's create the copy of sorted list and print it.
//The space complexity is Q(n)
fun printedSorted(number: List<Int>){
val sorted = number.sorted()
for (element in sorted){
println(element)
}
}
/*
NOTE: key Point
-Big O notation it used to represent the general form of space and time complexity.
-Time and space are high-level measures of scalability,
they don't measure the actual speed of algorithm itself
-For small dataset time complexity is usually irrelevant, a quasilinear algorithm can be slower than liner algo
* */ | [
{
"class_path": "waploaj__Masomo__6a44d60/complexity/ComplexityKt.class",
"javap": "Compiled from \"Complexity.kt\"\npublic final class complexity.ComplexityKt {\n public static final void checkFirst(java.util.List<java.lang.String>);\n Code:\n 0: aload_0\n 1: ldc #10 ... |
moosolutions__advent-of-code-2022__6ef815d/src/main/kotlin/aoc/day5/SupplyStacks.kt | package aoc.day5
class SupplyStacks(private val input: List<String>) {
val stacks = mutableListOf<Stack>()
init {
val rawStacks = input.slice(0..input.indexOf(""))
.filter { line -> line.isNotEmpty() }
.map {
it.split(",")
}
.flatten()
.map {
it.chunked(4).map {
s -> s.trim().removePrefix("[").removeSuffix("]")
}
}
val s = rawStacks.toMutableList()
s.removeLast()
for (i in 0 until rawStacks.last().count())
{
stacks.add(i, Stack())
s.forEach {
if (i in it.indices && it[i]!!.isNotEmpty()) {
stacks[i].addCrate(Crate(it[i]))
}
}
}
stacks.map { it.crates.reverse() }
}
fun rearrangeStacksBySingle(): String
{
val moves = input.slice(input.indexOf("") + 1 until input.count()).map {
val move = it.split(" ")
val quantity = move[1].toInt()
val from = move[3].toInt() - 1
val to = move[5].toInt() - 1
stacks[to].crates.addAll(stacks[from].crates.takeLast(quantity).reversed())
stacks[from].crates = stacks[from].crates.dropLast(quantity).toMutableList()
}
return stacks.map {
it.crates.last().toString()
}.joinToString("")
}
fun useCrateMover9001(): String
{
val moves = input.slice(input.indexOf("") + 1 until input.count()).map {
val move = it.split(" ")
val quantity = move[1].toInt()
val from = move[3].toInt() - 1
val to = move[5].toInt() - 1
stacks[to].crates.addAll(stacks[from].crates.takeLast(quantity))
stacks[from].crates = stacks[from].crates.dropLast(quantity).toMutableList()
stacks.forEach { println(it.crates.toString()) }
}
return stacks.map {
it.crates.last().toString()
}.joinToString("")
}
}
class Stack
{
public var crates = mutableListOf<Crate>()
fun addCrate(crate: Crate)
{
crates.add(crate)
}
}
class Crate(public val crateCode: String) {
override fun toString(): String {
return crateCode
}
}
| [
{
"class_path": "moosolutions__advent-of-code-2022__6ef815d/aoc/day5/SupplyStacks.class",
"javap": "Compiled from \"SupplyStacks.kt\"\npublic final class aoc.day5.SupplyStacks {\n private final java.util.List<java.lang.String> input;\n\n private final java.util.List<aoc.day5.Stack> stacks;\n\n public aoc... |
victorYghor__Kotlin-Problems__0d30e37/simpleCalculator/Main.kt | package calculator
val numbers = mutableListOf<Int>()
fun Char.isOperator(): Boolean {
return this == '+' || this == '-'
}
fun start() {
val input = readln().split(' ').joinToString("")
when (input) {
"" -> start()
"/exit" -> throw Exception()
"/help" -> println(
"""The program does the following operations:
sum(+) -> 1 + 3 = 4
subtract(-) -> 3 - 2 = 1
mix operations -> -3 -- 1 +++ 3 -15 = -14
""".trimIndent()
)
else -> fixLine(input)
}
start()
}
fun computePlusMinus(operator1: Char, operator2: Char): Char {
if (operator1 == operator2) {
return '+'
} else {
return '-'
}
}
fun fixLine(line: String) {
var awryLine = line
do {
var operator: Char? = null
do {
var first = awryLine[0]
val second: Char
if (1 <= awryLine.lastIndex && awryLine[1].isOperator() && first.isOperator()) {
second = awryLine[1]
awryLine = awryLine.drop(2)
awryLine = computePlusMinus(first, second) + awryLine
first = awryLine[0]
} else if (first.isOperator()) {
operator = first
awryLine = awryLine.removePrefix(first.toString())
first = awryLine[0]
}
} while (first.digitToIntOrNull() == null)
val numberPattern = Regex("((-?)|(\\+?))?\\d+")
val positionNumber = numberPattern.find(awryLine)
if (positionNumber != null) {
val number = awryLine.substring(positionNumber.range)
val numberAndOperator = if (operator == '-') '-' + number else number
numbers.add(numberAndOperator.toInt())
awryLine = awryLine.removePrefix(number)
}
} while (awryLine.length != 0)
compute()
}
fun compute() {
println(numbers.sum())
numbers.clear()
}
fun getNumbers(input: String): MutableList<Int> {
val numbers = mutableListOf<Int>()
input.split(' ').forEach { numbers.add(it.toInt()) }
return numbers
}
fun main() {
try {
start()
} catch (e: Exception) {
println("Bye!")
}
} | [
{
"class_path": "victorYghor__Kotlin-Problems__0d30e37/calculator/MainKt.class",
"javap": "Compiled from \"Main.kt\"\npublic final class calculator.MainKt {\n private static final java.util.List<java.lang.Integer> numbers;\n\n public static final java.util.List<java.lang.Integer> getNumbers();\n Code:\... |
Laomedeia__Java8InAction__0dcd843/src/main/java/leetcode/a350_intersectTwoArrays/Solution.kt | package leetcode.a350_intersectTwoArrays
import java.util.*
import kotlin.math.min
/**
* 给定两个数组,编写一个函数来计算它们的交集。
*
* 示例 1:
* 输入:nums1 = [1,2,2,1], nums2 = [2,2]
* 输出:[2,2]
*
* 示例 2:
* 输入:nums1 = [4,9,5], nums2 = [9,4,9,8,4]
* 输出:[4,9]
*
*
* 说明:
* 输出结果中每个元素出现的次数,应与元素在两个数组中出现次数的最小值一致。
* 我们可以不考虑输出结果的顺序。
* 进阶:
* 如果给定的数组已经排好序呢?你将如何优化你的算法?
* 如果 nums1 的大小比 nums2 小很多,哪种方法更优?
* 如果 nums2 的元素存储在磁盘上,磁盘内存是有限的,并且你不能一次加载所有的元素到内存中,你该怎么办?
*
* @author neptune
* @create 2020 07 13 10:39 下午
*/
class Solution {
fun intersect(nums1: IntArray, nums2: IntArray): IntArray {
// return nums2.intersect(nums1.asIterable()).toIntArray()
nums1.sort()
nums2.sort()
val length1 = nums1.size
val length2 = nums2.size
val intersection = IntArray(min(length1, length2))
var index1 = 0
var index2 = 0
var index = 0
while (index1 < length1 && index2 < length2) {
if (nums1[index1] < nums2[index2]) {
index1++
} else if (nums1[index1] > nums2[index2]) {
index2++
} else {
intersection[index] = nums1[index1]
index1++
index2++
index++
}
}
return Arrays.copyOfRange(intersection, 0, index)
}
}
fun main(args: Array<String>) {
val solution = Solution()
val nums1:IntArray = arrayOf(1,2,2,1).toIntArray()
val nums2:IntArray = arrayOf(2).toIntArray()
// val nums1:IntArray = arrayOf(1,2,2,1).toIntArray()
// val nums2:IntArray = arrayOf(2,2).toIntArray()
solution.intersect(nums1,nums2).iterator().forEach { el -> println(el) }
} | [
{
"class_path": "Laomedeia__Java8InAction__0dcd843/leetcode/a350_intersectTwoArrays/Solution.class",
"javap": "Compiled from \"Solution.kt\"\npublic final class leetcode.a350_intersectTwoArrays.Solution {\n public leetcode.a350_intersectTwoArrays.Solution();\n Code:\n 0: aload_0\n 1: invokes... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.