Skip to content

Instantly share code, notes, and snippets.

@jesty
Last active May 14, 2018 15:34
Show Gist options
  • Save jesty/184786638c44553a4a5a07fbac161758 to your computer and use it in GitHub Desktop.
Save jesty/184786638c44553a4a5a07fbac161758 to your computer and use it in GitHub Desktop.
Functional Fibonacci, from Java to Kotlin
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
class NextInSeries {
public final int current;
public final int next;
NextInSeries(int current, int next) {
this.current = current;
this.next = next;
}
public NextInSeries nextValue() {
return new NextInSeries(next, current + next);
}
}
class Fibonacci {
public static int numberAtPosition(int position) {
NextInSeries initial = new NextInSeries(0, 1);
return IntStream.range(0, position)
.mapToObj(ignore -> new NextInSeries(0, 0))
.reduce(initial, (result, ignore) -> result.nextValue())
.next;
}
public static List<Integer> seriesUntilPosition(int position) {
return IntStream.rangeClosed(0, position)
.mapToObj(index -> numberAtPosition(index))
.collect(Collectors.toList());
}
}
class FibonacciK {
companion object {
@JvmStatic
fun numberAtPosition(position: Int): Int {
return (0..position)
.map { Pair(0, 1) }
.reduce { (first, second), next -> Pair(second, first + second) }
.second
}
@JvmStatic
fun seriesUntilPosition(position: Int): List<Int> {
return (1..position)
.map { numberAtPosition(it) }
}
}
}
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class FibonacciTest {
@Test
void numberAtPosition() {
assertAll(
() -> assertEquals(1, FibonacciK.numberAtPosition(0))
, () -> assertEquals(1, FibonacciK.numberAtPosition(1))
, () -> assertEquals(2, FibonacciK.numberAtPosition(2))
, () -> assertEquals(3, FibonacciK.numberAtPosition(3))
, () -> assertEquals(5, FibonacciK.numberAtPosition(4))
, () -> assertEquals(8, FibonacciK.numberAtPosition(5))
, () -> assertEquals(89, FibonacciK.numberAtPosition(10))
);
}
@Test
void series() {
assertAll(
() -> assertEquals(Arrays.asList(1), FibonacciK.seriesUntilPosition(0))
, () -> assertEquals(Arrays.asList(1, 1), FibonacciK.seriesUntilPosition(1))
, () -> assertEquals(Arrays.asList(1, 1, 2), FibonacciK.seriesUntilPosition(2))
, () -> assertEquals(Arrays.asList(1, 1, 2, 3), FibonacciK.seriesUntilPosition(3))
, () -> assertEquals(Arrays.asList(1, 1, 2, 3, 5), FibonacciK.seriesUntilPosition(4))
, () -> assertEquals(Arrays.asList(1, 1, 2, 3, 5, 8), FibonacciK.seriesUntilPosition(5))
, () -> assertEquals(Arrays.asList(1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89), FibonacciK.seriesUntilPosition(10))
);
}
}
@ubaldop
Copy link

ubaldop commented May 14, 2018

Bello Kotlin!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment