diff --git a/2025/01/cracking_code_interview_17_9_kth_multiple/README.md b/2025/01/cracking_code_interview_17_9_kth_multiple/README.md index 754c4e2..34a0076 100644 --- a/2025/01/cracking_code_interview_17_9_kth_multiple/README.md +++ b/2025/01/cracking_code_interview_17_9_kth_multiple/README.md @@ -1,5 +1,4 @@ # Solution for 17.9 -This solution uses Eratosthenes method which is simple but space O(n) which is -less than ideal. Maybe there are better solutions because it requires also to give -the max size of that array which is less than desirable. \ No newline at end of file +- Program.kt is not correct (didn't calculate what it was needed) +- Program2.kt is correct \ No newline at end of file diff --git a/2025/01/cracking_code_interview_17_9_kth_multiple/src/main/kotlin/pl/polgrabia/demos/crackingcodeinterview/t17x9/Program2.kt b/2025/01/cracking_code_interview_17_9_kth_multiple/src/main/kotlin/pl/polgrabia/demos/crackingcodeinterview/t17x9/Program2.kt new file mode 100644 index 0000000..95ebc4f --- /dev/null +++ b/2025/01/cracking_code_interview_17_9_kth_multiple/src/main/kotlin/pl/polgrabia/demos/crackingcodeinterview/t17x9/Program2.kt @@ -0,0 +1,43 @@ +package pl.polgrabia.demos.crackingcodeinterview.t17x9 + +import java.util.PriorityQueue +import kotlin.system.exitProcess + + +fun main() { + print("Give k number (>= 1): ") + val kNumber = readln().toInt() + if (kNumber < 1) { + System.err.println("kNumber cannot be smaller than as it's first number of 3,5,7") + exitProcess(1) + } + + val q = PriorityQueue( + 100 + ) { o1, o2 -> + o1.multipleNr - o2.multipleNr + } + + q.add(PrimeMultiple(1)) + + var kGenerated = 0 + var lastProcessed : Int = -1 + while(kGenerated < kNumber) { + val el = q.remove() + if (el.multipleNr <= lastProcessed) { + continue + } + lastProcessed = el.multipleNr + println("${++kGenerated} multiple is ${el.multipleNr}") + q.add(PrimeMultiple(el.multipleNr*3)) + q.add(PrimeMultiple(el.multipleNr*5)) + q.add(PrimeMultiple(el.multipleNr*7)) + } + + // println("K$kNumber multiple for 3,5,7 is: $lastProcessed") + +} + +data class PrimeMultiple( + var multipleNr: Int +)