Skip to content

Instantly share code, notes, and snippets.

@alexandreaquiles
Last active December 12, 2015 09:59
Show Gist options
  • Select an option

  • Save alexandreaquiles/4755961 to your computer and use it in GitHub Desktop.

Select an option

Save alexandreaquiles/4755961 to your computer and use it in GitHub Desktop.
import java.util.Iterator;
public class FibonacciSequence implements Iterator<Long> {
private long n = 0;
private long a = 0;
private long b = 1;
public boolean hasNext() { return a + b > 0; }
public Long next() {
long fib;
if(n == 0 || n == 1) {
fib = n;
}
else {
fib = a + b;
a = b;
b = fib;
}
n++;
return fib;
}
public void remove() {}
public static void main(String[] args) {
FibonacciSequence fs = new FibonacciSequence();
for(int i = 0; i < 10 && fs.hasNext(); i++){
System.out.println(fs.next());
}
}
}
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Taker<T> {
public List<T> take(int n, Iterator<T> xs) {
List<T> taken = new ArrayList<T>();
for (int i = 0; xs.hasNext() && i < n; i++) {
taken.add(xs.next());
}
return taken;
}
public static void main(String[] args) {
List<Long> fibonacciUpto25 = new Taker<Long>().take(25, new FibonacciSequence());
System.out.println(fibonacciUpto25);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment