Dataset Viewer
Auto-converted to Parquet Duplicate
kt_path
stringlengths
35
167
kt_source
stringlengths
626
28.9k
classes
listlengths
1
17
akshaybhongale__Largest-Sum-Contiguous-Subarray-Kotlin__e2de2c9/MaximumSubArray.kt
/** * Array Data Structure Problem * Largest Sum Contiguous Sub-array * Kotlin solution : * 1- Simple approach = time complexity O(n*n) where n is size of array * 2- kadane approach = time complexity O(n) where n is size of array */ class MaximumSubArray { companion object { @JvmStatic fun main(args: Array<String>) { val array = arrayOf(1, 3, 8, -2, 6, -8, 5) val simpleApproach = simpleApproach(array) val kadaneSolution = kadaneSolution(array) print("Maximum Sub array : simpleSolution $simpleApproach kadaneSolution $kadaneSolution") } private fun simpleApproach(array: Array<Int>): Int { var maximumSubArray = Int.MIN_VALUE for (i in array.indices) { var curSum = 0 for (j in i until array.size) { curSum += array[j] if (curSum > maximumSubArray) { maximumSubArray = curSum } }// end of j }// end of i return maximumSubArray } private fun kadaneSolution(array: Array<Int>): Int { var maximumSubArray = Int.MIN_VALUE var currentSum = 0 for (i in array.indices) { currentSum += array[i] if (currentSum > maximumSubArray) { maximumSubArray = currentSum } if (currentSum < 0) { currentSum = 0 } } return maximumSubArray } } }
[ { "class_path": "akshaybhongale__Largest-Sum-Contiguous-Subarray-Kotlin__e2de2c9/MaximumSubArray.class", "javap": "Compiled from \"MaximumSubArray.kt\"\npublic final class MaximumSubArray {\n public static final MaximumSubArray$Companion Companion;\n\n public MaximumSubArray();\n Code:\n 0: aload...
strouilhet__KeepCalmAndCode3__f779bf1/séance 1 et 2 _ classe et objet/correction/Complexe.kt
import kotlin.math.PI import kotlin.math.atan import kotlin.math.round import kotlin.math.sqrt class Complexe(val reel: Double = 0.0, val im: Double = 0.0) { constructor(c: Complexe) : this(c.reel, c.im) fun module(): Double = sqrt(reel * reel + im * im) fun argument(): Double = if (reel == 0.0) if (im >= 0) PI / 2 else -PI / 2 else atan(im / reel) fun add(z:Complexe): Complexe =Complexe(reel+z.reel, im+ z.im) fun mul(z:Complexe): Complexe = Complexe(reel*z.reel - im*z.im,reel*z.im + im*z.reel) /** * puissance * précondition n >=1 * @param n, puissance * @return puissance (Complexe) */ fun puissance(n:Int):Complexe { var r:Complexe=this for (i in 2..n) r=mul(r) return Complexe(round(r.reel), round(r.im)) } fun puissanceBis(n: Int): Complexe { var r = Complexe(1.0, 0.0) for (i in 0 until n) // n-1 compris r = r.mul(this) return r } /** * inverse du nombre complexe * précondition : this est non nul * @return inverse (Complexe) */ fun inverse(): Complexe =Complexe(reel / (reel * reel + im * im), -im / (reel * reel + im * im)) /** * division du nombre complexe par z * précondition : z non nul * @param z, diviseur * @return quotiont (Complexe) */ fun div(z: Complexe): Complexe = this.mul(z.inverse()) override fun toString(): String = "$reel + i $im" companion object { val I = Complexe(0.0, 1.0) val J = Complexe(-1 / 2.0, Math.sqrt(3.0) / 2) } } // question 1 --> avant l'ajout des getters /* class Complexe constructor(_reel:Double = 0.0, _im:Double= 0.0) { private val reel:Double=_reel private val im: Double=_im constructor(c:Complexe): this(c.reel, c.im) { } }*/
[ { "class_path": "strouilhet__KeepCalmAndCode3__f779bf1/Complexe.class", "javap": "Compiled from \"Complexe.kt\"\npublic final class Complexe {\n public static final Complexe$Companion Companion;\n\n private final double reel;\n\n private final double im;\n\n private static final Complexe I;\n\n private...
benjaminjkraft__aoc2017__e3ac356/day10.kt
fun doHash(lengths: List<Int>, n: Int, rounds: Int): Array<Int> { var pos = 0 var skip = 0 val list = Array(n, { it }) for (round in 0 until rounds) { for (i in lengths.indices) { val listAgain = list.copyOf() for (j in 0 until lengths[i]) { list[(pos + j) % n] = listAgain[(pos + lengths[i] - 1 - j) % n] } pos += lengths[i] + skip skip++; } } return list } fun firstProd(list: Array<Int>): Int { return list[0] * list[1] } fun denseHash(list: Array<Int>, n: Int): String { var output = "" val blockSize = list.size / n for (i in 0 until n) { val byte = list.slice(i * blockSize until (i + 1) * blockSize).reduce( { j, k -> j xor k }) output += byte.toString(16).padStart(2, '0') } return output } fun main(args: Array<String>) { val line = readLine()!! val extra = arrayOf(17, 31, 73, 47, 23) println(firstProd(doHash(line.split(",").map({ it.toInt() }), 256, 1))) println(denseHash(doHash(line.map({ it.toInt() }) + extra, 256, 64), 16)) }
[ { "class_path": "benjaminjkraft__aoc2017__e3ac356/Day10Kt.class", "javap": "Compiled from \"day10.kt\"\npublic final class Day10Kt {\n public static final java.lang.Integer[] doHash(java.util.List<java.lang.Integer>, int, int);\n Code:\n 0: aload_0\n 1: ldc #10 // S...
thuva4__Algorithms__7da835f/algorithms/Kotlin/QuickSort/QuickSort.kt
fun printArray(x: IntArray) { for (i in x.indices) print(x[i].toString() + " ") } fun IntArray.sort(low: Int = 0, high: Int = this.size - 1) { if (low >= high) return val middle = partition(low, high) sort(low, middle - 1) sort(middle + 1, high) } fun IntArray.partition(low: Int, high: Int): Int { val middle = low + (high - low) / 2 val a = this swap(a, middle, high) var storeIndex = low for (i in low until high) { if (a[i] < a[high]) { swap(a, storeIndex, i) storeIndex++ } } swap(a, high, storeIndex) return storeIndex } fun swap(a: IntArray, i: Int, j: Int) { val temp = a[i] a[i] = a[j] a[j] = temp } fun main(args: Array<String>) { println("Enter the number of elements :") val n = readLine()!!.toInt() val arr = IntArray(n) println("Enter the elements.") for (i in 0 until n) { arr[i] = readLine()!!.toInt() } println("Given array") printArray(arr) arr.sort() println("\nSorted array") printArray(arr) }
[ { "class_path": "thuva4__Algorithms__7da835f/QuickSortKt.class", "javap": "Compiled from \"QuickSort.kt\"\npublic final class QuickSortKt {\n public static final void printArray(int[]);\n Code:\n 0: aload_0\n 1: ldc #9 // String x\n 3: invokestatic #15 ...
dlfelps__aoc-2022__3ebcc49/src/Day01.kt
import java.io.File fun main() { fun parseInput(input: String) : List<Int> { fun getNext(rest: List<Int?>): Pair<Int,List<Int?>> { val next = rest.takeWhile {it != null} as List<Int> val temp = rest.dropWhile {it != null} val rest = if (temp.isEmpty()) { temp } else { temp.drop(1) //drop null } return Pair(next.sum(), rest) } var rest = input.lines().map {it.toIntOrNull()} val sums = mutableListOf<Int>() while (rest.isNotEmpty()) { val (sum, temp) = getNext(rest) rest = temp sums.add(sum) } return sums } fun part1(input: String): Int { val data = parseInput(input) return data.max() } fun part2(input:String): Int { val data = parseInput(input) return data .sortedDescending() .take(3) .sum() } val input = File("src/Day01.txt").readText() println(part1(input)) println(part2(input)) }
[ { "class_path": "dlfelps__aoc-2022__3ebcc49/Day01Kt.class", "javap": "Compiled from \"Day01.kt\"\npublic final class Day01Kt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc #10 // Stri...
MisterTeatime__AoC2022__d684bd2/src/Utils.kt
import java.io.File import java.math.BigInteger import java.security.MessageDigest import kotlin.math.absoluteValue /** * Reads lines from the given input txt file. */ fun readInput(name: String) = File("src", "$name.txt").readLines() /** * Converts string to md5 hash. */ fun String.md5(): String = BigInteger(1, MessageDigest.getInstance("MD5").digest(toByteArray())).toString(16).padStart(32, '0') typealias Graph = Map<String, List<String>> typealias Path = List<String> typealias Fold = Pair<Char, Int> data class Point2D (var x: Int, var y: Int) { operator fun plus(inc: Point2D) = Point2D(x + inc.x, y + inc.y) operator fun minus(inc: Point2D) = Point2D(x - inc.x, y - inc.y) fun neighbors4(): List<Point2D> { val neighborPoints = listOf(Point2D(1,0), Point2D(0,1), Point2D(-1, 0), Point2D(0,-1)) return neighborPoints.map { this + it }.sortedWith(Point2DComparator()) } fun neighbors8(): List<Point2D> { val neighborPoints = listOf( Point2D(1,0), Point2D(1,1), Point2D(0,1), Point2D(-1,1), Point2D(-1,0), Point2D(-1,-1), Point2D(0,-1), Point2D(1,-1) ) return neighborPoints.map { this + it }.sortedWith(Point2DComparator()) } fun neighbors4AndSelf(): List<Point2D> { val neighborPoints = neighbors4().toMutableList() neighborPoints.add(this) return neighborPoints.sortedWith(Point2DComparator()) } fun neighbors8AndSelf(): List<Point2D> { val neighborPoints = neighbors8().toMutableList() neighborPoints.add(this) return neighborPoints.sortedWith(Point2DComparator()) } fun distanceTo(other: Point2D) = (this.x - other.x).absoluteValue + (this.y - other.y).absoluteValue class Point2DComparator: Comparator<Point2D> { override fun compare(p0: Point2D?, p1: Point2D?): Int { return if (p0 == null || p1 == null) 0 else { when { (p0.y > p1.y) -> 1 (p0.y < p1.y) -> -1 else -> { when { (p0.x > p1.x) -> 1 (p0.x < p1.x) -> -1 else -> 0 } } } } } } } class Line(coords: List<String>) { val start: Point2D val end: Point2D init { val startPoint = coords[0].split(",") val endPoint = coords[1].split(",") this.start = Point2D(startPoint[0].toInt(), startPoint[1].toInt()) this.end = Point2D(endPoint[0].toInt(), endPoint[1].toInt()) } fun isHorizontal() = start.y == end.y fun isVertical() = start.x == end.x fun contains(point: Point2D) = point.y == getYAt(point.x) fun getYAt(x: Int) = ((end.y - start.y)/(end.x - start.x)) * (x - start.x) + start.y fun getAllIntegerPoints(): List<Point2D> { return when { isHorizontal() -> { when { (start.x < end.x) -> IntRange(start.x, end.x).map{ p -> Point2D(p, start.y) } else -> IntRange(end.x, start.x).map{ p -> Point2D(p, start.y) } } } isVertical() -> { when { (start.y < end.y) -> IntRange(start.y, end.y).map{ p -> Point2D(start.x, p) } else -> IntRange(end.y, start.y).map { p -> Point2D(start.x, p) } } } else -> { when { (start.x < end.x) -> IntRange(start.x, end.x).map{ p -> Point2D(p, getYAt(p)) } else -> IntRange(end.x, start.x).map{ p -> Point2D(p, getYAt(p)) } } } } } override fun toString(): String { return "(${start.x}, ${start.y}) -> (${end.x}, ${end.y})" } } class MyStack<E>(vararg items: E): Collection<E> { private val elements = items.toMutableList() fun push(element: E) = elements.add(element) fun peek(): E = elements.last() fun pop(): E = elements.removeAt(elements.size-1) override fun isEmpty() = elements.isEmpty() override fun contains(element: E) = elements.contains(element) override fun containsAll(elements: Collection<E>) = elements.containsAll(elements) override fun toString() = "Stack(${elements.joinToString()})" override fun iterator() = elements.iterator() override val size: Int get() = elements.size } data class Area<T>(var points: List<MutableList<T>>) { fun at(p: Point2D): T? { return points.getOrElse(p.y) { listOf() }.getOrNull(p.x) } fun setValue(p: Point2D, v: T) { if (at(p) != null) points[p.y][p.x] = v } companion object Factory { fun toIntArea(input: List<String>): Area<Int> { return Area(input.map { it.map { ch -> ch.toString().toInt() }.toMutableList() }) } fun toBinaryArea(input: List<String>, one: Char, zero: Char): Area<Int> { return Area(input.map { it.map { c -> when (c) { one -> 1 zero -> 0 else -> 0 } }.toMutableList() }) } } } data class Point3D(val x: Int, val y: Int, val z: Int) { operator fun plus(inc: Point3D) = Point3D(x + inc.x, y + inc.y, z + inc.z) operator fun minus(inc: Point3D) = Point3D(x - inc.x, y - inc.y, z - inc.z) } fun <T> List<T>.partitionGroups(divider: T): List<List<T>> { var startIndex = 0 val result = mutableListOf<List<T>>() this.forEachIndexed { index, t -> if (t == divider) { result.add(this.subList(startIndex, index)) startIndex = index + 1 } } if (startIndex < this.size) result.add(this.subList(startIndex, this.size)) return result }
[ { "class_path": "MisterTeatime__AoC2022__d684bd2/UtilsKt.class", "javap": "Compiled from \"Utils.kt\"\npublic final class UtilsKt {\n public static final java.util.List<java.lang.String> readInput(java.lang.String);\n Code:\n 0: aload_0\n 1: ldc #10 // String name\n...
UlrichBerntien__Codewars-Katas__034d7f2/6_kyu/Playing_with_digits.kt
/** Power function for integers */ fun Int.pow(exp: Int): Long { return this.toBigInteger().pow(exp).toLong() } /** * Sum decimal digits with power. * * @param x Calculate the digit powerd sum of this int. * @param p The exponent of the most significant digit. * @return sum of all decimal digits with power p,p+1,.. */ fun digitSum(x: Int, p: Int): Long { var digits = IntArray(32) assert( 10.pow(digits.size) > Int.MAX_VALUE.toLong() ) var nDigits = 0 var rest = x while (rest > 0) { digits[nDigits] = rest % 10 rest /= 10 nDigits++ } var sum: Long = 0 for (i in 0..nDigits - 1) { sum += digits[i].pow(p + nDigits - i - 1) } return sum } /** * Calculates funny integer. * * @param n Integer to analyse. * @param p exponent of the most significant digit in the sum. * @return k with k*n = powered decimal digit sum of n. */ fun digPow(n: Int, p: Int): Int { val s = digitSum(n, p) return if (s % n == 0L) (s / n).toInt() else -1 }
[ { "class_path": "UlrichBerntien__Codewars-Katas__034d7f2/Playing_with_digitsKt.class", "javap": "Compiled from \"Playing_with_digits.kt\"\npublic final class Playing_with_digitsKt {\n public static final long pow(int, int);\n Code:\n 0: iload_0\n 1: i2l\n 2: invokestatic #12 ...
UlrichBerntien__Codewars-Katas__034d7f2/4_kyu/The_observed_PIN.kt
/** * Generates all possible PINs based on the observed PIN. The true PIN is around the observed PIN. * Each key could be also the key around the observed key. * * @param The observed PIN. * @return All possible PINs. */ fun getPINs(observed: String): List<String> = when (observed.length) { 0 -> emptyList() 1 -> keyNeighbours[observed[0]]!!.map { it.toString() } else -> { var accu = emptyList<String>() val lhs = keyNeighbours[observed[0]]!! getPINs(observed.substring(1)).forEach { rhs -> lhs.forEach { it -> accu += it + rhs } } accu } } /** * Map from observed key to all possible input kyes. Maps to an empty array if the key is not on the * keypad. */ private val keyNeighbours: Map<Char, CharArray> = generateKeyNeighbours("123,456,789, 0 ") /** * Generates the map from observed key to possible keys. * * @param layout The layout of the keypad. Rows of the key pad are separated by comma. * @return Map observerd key -> possible keys. */ private fun generateKeyNeighbours(layout: String): Map<Char, CharArray> { var accu = HashMap<Char, CharArray>().withDefault { CharArray(0) } val keys: Array<String> = layout.split(',').toTypedArray() fun getKey(x: Int, y: Int): Char? = if (y in keys.indices && x in keys[y].indices && keys[y][x] != ' ') keys[y][x] else null for (row in keys.indices) for (col in keys[row].indices) getKey(col, row)?.let { k -> var options = emptyList<Char>() listOf(Pair(0, +1), Pair(0, -1), Pair(+1, 0), Pair(-1, 0), Pair(0, 0)).forEach { (x, y) -> getKey(col + x, row + y)?.let { options += it } } accu[k] = options.toCharArray() } return accu }
[ { "class_path": "UlrichBerntien__Codewars-Katas__034d7f2/The_observed_PINKt.class", "javap": "Compiled from \"The_observed_PIN.kt\"\npublic final class The_observed_PINKt {\n private static final java.util.Map<java.lang.Character, char[]> keyNeighbours;\n\n public static final java.util.List<java.lang.Str...
ILIYANGERMANOV__algorithms__4abe4b5/Algorithms/src/main/kotlin/LargestPalindromicNumber.kt
/** * # Largest Palindromic Number * Problem: * https://leetcode.com/problems/largest-palindromic-number/ */ class LargestPalindromicNumber { fun largestPalindromic(num: String): String { val digits = intArrayOf(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) for (c in num) { val digit = c.digitToInt() digits[digit] += 1 } val available = digits.mapIndexed { digit, count -> digit to count }.filter { (_, count) -> count > 0 }.sortedWith { (digit1, count1), (digit2, count2) -> /** * Returns zero if the arguments are equal, * a negative number if the first argument is less than the second, * or a positive number if the first argument is greater than the second. */ val oneRank = (if (count1 > 1) 100 else 0) + digit1 val twoRank = (if (count2 > 1) 100 else 0) + digit2 twoRank - oneRank// sort descending } val mirror = mirror(available) val palindrome = palindrome(mirror) // Filter leading 0's return if (palindrome.first() == '0') { palindrome.replace("0", "").takeIf { it.isNotEmpty() } ?: "0" } else palindrome } private fun palindrome(mirror: Pair<String, String?>): String { val (str, left) = mirror return if (left != null) str + left + str.reversed() else str + str.reversed() } private fun mirror(available: List<Pair<Int, Int>>): Pair<String, String?> { fun biggestLeftover(currentDigit: Int, secondLeft: String?): Int { val secondLeftSafe = secondLeft?.toInt() ?: 0 val next = available.getOrNull(1)?.first ?: return maxOf(currentDigit, secondLeftSafe) return if (next > currentDigit) { maxOf(next, secondLeftSafe) } else maxOf(currentDigit, secondLeftSafe) } if (available.isEmpty()) return "" to null val (digit, count) = available.first() return if (count.isEven()) { val first = digit.toString().repeat(count / 2) val (secondStr, secondLeft) = mirror(available.drop(1)) first + secondStr to secondLeft } else { if (count > 1) { // not even; count >= 3 val first = digit.toString().repeat((count - 1) / 2) val (secondStr, secondLeft) = mirror(available.drop(1)) first + secondStr to biggestLeftover( currentDigit = digit, secondLeft = secondLeft ).toString() } else { // count = 1 "" to digit.toString() } } } private fun Int.isEven(): Boolean = this % 2 == 0 }
[ { "class_path": "ILIYANGERMANOV__algorithms__4abe4b5/LargestPalindromicNumber.class", "javap": "Compiled from \"LargestPalindromicNumber.kt\"\npublic final class LargestPalindromicNumber {\n public LargestPalindromicNumber();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Met...
ILIYANGERMANOV__algorithms__4abe4b5/Algorithms/src/main/kotlin/NextClosestTime.kt
fun main() { val sut = NextClosestTime() for (h in 0..23) { val hour = if (h < 10) "0$h" else h.toString() for (m in 0..59) { val minute = if (m < 10) "0$m" else m.toString() val time = "$hour:$minute" println("\"$time\" -> \"${sut.nextClosestTime(time)}\"") } } } class NextClosestTime { fun nextClosestTime(time: String): String { val digits = mutableSetOf<Int>() digits.add(time[0].digitToInt()) digits.add(time[1].digitToInt()) digits.add(time[3].digitToInt()) digits.add(time[4].digitToInt()) val sortedDigits = digits.sorted() val hour = String(charArrayOf(time[0], time[1])) val minute = String(charArrayOf(time[3], time[4])) val minuteInt = minute.toInt() val hasZero: Boolean = sortedDigits.first() == 0 return tryNextMinute( sortedDigits = sortedDigits, hour = hour, minute = minute, minuteInt = minuteInt, hasZero = hasZero ) ?: tryNextHorWithMinimizedMin( sortedDigits = sortedDigits, hour = hour, hasZero = hasZero ) ?: minimizeTime(sortedDigits) } private fun tryNextMinute( sortedDigits: List<Int>, hour: String, minute: String, minuteInt: Int, hasZero: Boolean ): String? { if (minute == "59") return null for (i in sortedDigits.indices) { val digit1 = sortedDigits[i] if (hasZero) { // try single digit if (digit1 > minuteInt) return "$hour:0$digit1" } for (j in sortedDigits.indices) { val digit2 = sortedDigits[j] val newMinute = validMinute(digit1, digit2) if (newMinute != null && newMinute > minuteInt) return "$hour:${format(newMinute)}" } } return null } private fun tryNextHorWithMinimizedMin( sortedDigits: List<Int>, hour: String, hasZero: Boolean ): String? { fun minimizedMin(): String = sortedDigits.first().run { if (hasZero) "0$this" else "$this$this" } if (hour == "23") return null val hourInt = hour.toInt() for (i in sortedDigits.indices) { val digit1 = sortedDigits[i] if (hasZero) { // try single digit if (digit1 > hourInt) return "0$digit1:${minimizedMin()}" } for (j in sortedDigits.indices) { val digit2 = sortedDigits[j] val newHour = validHour(digit1, digit2) if (newHour != null && newHour > hourInt) return "${format(newHour)}:${minimizedMin()}" } } return null } private fun minimizeTime( sortedDigits: List<Int> ): String { val first = sortedDigits.first() return "$first$first:$first$first" } private fun format(newNumber: Int): String = if (newNumber < 10) "0$newNumber" else newNumber.toString() private fun validHour(digit1: Int, digit2: Int): Int? { val newHour = digit1 * 10 + digit2 return newHour.takeIf { it in 0..23 } } private fun validMinute(digit1: Int, digit2: Int): Int? { val newMinute = digit1 * 10 + digit2 return newMinute.takeIf { it in 0..59 } } /** * LeetCode compatibility */ private fun Char.digitToInt(): Int = this.toInt() - '0'.toInt() }
[ { "class_path": "ILIYANGERMANOV__algorithms__4abe4b5/NextClosestTimeKt.class", "javap": "Compiled from \"NextClosestTime.kt\"\npublic final class NextClosestTimeKt {\n public static final void main();\n Code:\n 0: new #8 // class NextClosestTime\n 3: dup\n 4:...
ILIYANGERMANOV__algorithms__4abe4b5/Algorithms/src/main/kotlin/MinimumAreaRectangle.kt
import kotlin.math.pow import kotlin.math.sqrt typealias Point = IntArray /** * # Minimum Area Rectangle * * _Note: Time Limit Exceeded (not optimal)_ * * Problem: * https://leetcode.com/problems/minimum-area-rectangle/ */ class MinimumAreaRectangle { fun minAreaRect(points: Array<Point>): Int { var minArea: Int? = null chooseFourUnique(points) { a, b, c, d -> if (parallel(a, b, c, d) && rectangle(a, b, c, d)) { println("rect: ${a.toList()}, ${b.toList()}, ${c.toList()}, ${d.toList()}") val area = area(a, b, c, d) minArea = minArea?.let { minOf(it, area) } ?: area } } return minArea ?: 0 } private inline fun chooseFourUnique( points: Array<Point>, block: (Point, Point, Point, Point) -> Unit ) { for (a in points) { for (b in points) { if (a sameAs b) continue for (c in points) { if (a sameAs c || b sameAs c) continue for (d in points) { if (a sameAs d || b sameAs d || c sameAs d) continue block(a, b, c, d) } } } } } private infix fun Point.sameAs(other: Point): Boolean = x() == other.x() && y() == other.y() private fun area( a: Point, b: Point, c: Point, d: Point ): Int { val minX = minOf(a.x(), b.x(), c.x(), d.x()) val maxX = maxOf(a.x(), b.x(), c.x(), d.x()) val minY = minOf(a.y(), b.y(), c.y(), d.y()) val maxY = maxOf(a.y(), b.y(), c.y(), d.y()) return (maxX - minX) * (maxY - minY) } private fun parallel( a: Point, b: Point, c: Point, d: Point, ): Boolean { val points = arrayOf(a, b, c, d) if (points.map { it.x() }.toSet().size > 2) return false if (points.map { it.y() }.toSet().size > 2) return false return true } /** * Conditions for rectangle: * - distance(a,b) == distance(c,d) * - distance(a,c) == distance(b,d) * - distance(a,d) == distance(b,c) * * @return whether four points form an rectangle, note: it might be rotated */ private fun rectangle( a: Point, b: Point, c: Point, d: Point ): Boolean = distance(a, b) == distance(c, d) && distance(a, c) == distance(b, d) && distance(a, d) == distance(b, c) /** * Formula: * d=√((x2 – x1)² + (y2 – y1)²) */ private fun distance(p1: Point, p2: Point): Double = sqrt( (p1.x().toDouble() - p2.x()).pow(2.0) + (p1.y().toDouble() - p2.y()).pow(2.0) ) private fun IntArray.x() = this[0] private fun IntArray.y() = this[1] }
[ { "class_path": "ILIYANGERMANOV__algorithms__4abe4b5/MinimumAreaRectangleKt.class", "javap": "Compiled from \"MinimumAreaRectangle.kt\"\npublic final class MinimumAreaRectangleKt {\n}\n", "javap_err": "" }, { "class_path": "ILIYANGERMANOV__algorithms__4abe4b5/MinimumAreaRectangle.class", "ja...
ILIYANGERMANOV__algorithms__4abe4b5/Algorithms/src/main/kotlin/AllWaysToMakeChange.kt
fun numberOfWaysToMakeChange(n: Int, denoms: List<Int>): Int { // Write your code here. println("----------- CASE: n = $n, denoms = $denoms ----------------") val allWays = ways( n = n, ds = denoms, ) println("All ways: $allWays") val uniqueWays = allWays.map { it.sorted() }.toSet() println("Unique ways: $uniqueWays") println("------------- END CASE ---------------") return uniqueWays.size } /* n = 3, denoms = [1,2] ways(3) = ways(1) + ways(2) */ fun ways( n: Int, ds: List<Int>, ways: List<Int> = emptyList() ): List<List<Int>> { if (n < 0) return emptyList() if (n == 0) return listOf(ways) val validDs = ds.filter { it <= n } return validDs.foldRight(initial = emptyList()) { d, allWays -> ways(n = n - d, ways = ways + d, ds = validDs) + allWays } }
[ { "class_path": "ILIYANGERMANOV__algorithms__4abe4b5/AllWaysToMakeChangeKt.class", "javap": "Compiled from \"AllWaysToMakeChange.kt\"\npublic final class AllWaysToMakeChangeKt {\n public static final int numberOfWaysToMakeChange(int, java.util.List<java.lang.Integer>);\n Code:\n 0: aload_1\n ...
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
16