From 1811ab3c70e45b60e9a19074b54812f982629de4 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Tue, 16 Aug 2022 18:45:12 +0200 Subject: [PATCH] =?UTF-8?q?5kyu:=20add=20=E2=80=9EProduct=20of=20consecuti?= =?UTF-8?q?ve=20Fib=20numbers=E2=80=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- .../solution.kt | 61 +++++++++++++++++++ README.md | 1 + 2 files changed, 62 insertions(+) create mode 100644 5kyu/product_of_consecutive_fib_numbers/solution.kt diff --git a/5kyu/product_of_consecutive_fib_numbers/solution.kt b/5kyu/product_of_consecutive_fib_numbers/solution.kt new file mode 100644 index 0000000..943cf09 --- /dev/null +++ b/5kyu/product_of_consecutive_fib_numbers/solution.kt @@ -0,0 +1,61 @@ +package prodfib + +class FibonacciPairs : Iterable> { + private class FibonacciPairsIterator : Iterator> { + private var a: Long = 0 + private var b: Long = 1 + + /** + * Returns `true` if the iteration has more elements. + */ + override fun hasNext(): Boolean = true + + /** + * Returns the next element in the iteration. + */ + override fun next(): Pair { + val current = a to b + + a = current.second + b = current.first + current.second + + return current + } + } + + /** + * Returns an iterator over the elements of this object. + */ + override fun iterator(): Iterator> = FibonacciPairsIterator() +} + +fun productFib(prod: Long): LongArray = + FibonacciPairs() + .asSequence() + .dropWhile { (a, b) -> a * b < prod } + .first() + .let { (a, b) -> + longArrayOf( + a, b, if (a * b == prod) { + 1 + } else { + 0 + } + ) + } + +fun main() { + (0 until 10).zip(FibonacciPairs()).forEach { (i, pair) -> + println("$i → $pair") + } + + val tests = mapOf( + 4895L to longArrayOf(55, 89, 1), + 5895L to longArrayOf(89, 144, 0), + 714L to longArrayOf(21, 34, 1), + 800L to longArrayOf(34, 55, 0), + ) + tests.forEach { (prod, expected) -> + check(productFib(prod).contentEquals(expected)) + } +} diff --git a/README.md b/README.md index 4637ab9..f6cdadb 100644 --- a/README.md +++ b/README.md @@ -66,6 +66,7 @@ - [Buddy Pairs](https://www.codewars.com/kata/59ccf051dcc4050f7800008f) - [solution](5kyu/buddy_pairs) - [Simple assembler interpreter](https://www.codewars.com/kata/58e24788e24ddee28e000053) - [solution](5kyu/simple_assembler_interpreter) - [Maximum subarray sum](https://www.codewars.com/kata/54521e9ec8e60bc4de000d6c) - [solution](5kyu/maximum_subarray_sum) +- [Product of consecutive Fib numbers](https://www.codewars.com/kata/5541f58a944b85ce6d00006a) - [solution](5kyu/product_of_consecutive_fib_numbers) ### C#