1
0
Fork 0
mirror of https://gitlab.com/mfocko/CodeWars.git synced 2024-11-24 09:41:55 +01:00

5kyu: add „Product of consecutive Fib numbers“

Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
Matej Focko 2022-08-16 18:45:12 +02:00
parent fd3b272a35
commit 1811ab3c70
Signed by: mfocko
GPG key ID: 7C47D46246790496
2 changed files with 62 additions and 0 deletions

View file

@ -0,0 +1,61 @@
package prodfib
class FibonacciPairs : Iterable<Pair<Long, Long>> {
private class FibonacciPairsIterator : Iterator<Pair<Long, Long>> {
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<Long, Long> {
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<Pair<Long, Long>> = 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))
}
}

View file

@ -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#