Skip to content

Instantly share code, notes, and snippets.

@valorad
Last active January 14, 2025 16:52
Show Gist options
  • Save valorad/3b8e2a2cf87ba37bba4be6b8938830c0 to your computer and use it in GitHub Desktop.
Save valorad/3b8e2a2cf87ba37bba4be6b8938830c0 to your computer and use it in GitHub Desktop.
Salesforce Apex Fibonacci Generator
public with sharing class FibonacciGenerator implements Iterable<Long> {
private Integer howMany = 0;
public FibonacciGenerator(Integer howMany) {
this.howMany = howMany;
}
public Iterator<Long> iterator() {
return new FibonacciIterator(howMany);
}
public class FibonacciIterator implements Iterator<Long> {
private Integer generationGoal = 0;
private Integer generationCount = 0;
private List<Long> state = new List<Long>{ 0, 1 };
public FibonacciIterator(Integer generationGoal) {
this.generationGoal = generationGoal;
}
public Boolean hasNext() {
return generationCount < generationGoal;
}
public Long next() {
generationCount++;
if (generationCount == 1) {
return state[1];
}
Long tmp = state[1];
state[1] = state[1] + state[0];
state[0] = tmp;
return state[1];
}
}
}
@IsTest
public with sharing class FibonacciGeneratorTest {
@IsTest
static void shouldGenerateFibonacci() {
Integer howManyToGenerate = 33;
for (Long num : new FibonacciGenerator(howManyToGenerate)) {
system.debug(num);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment