Last active
January 14, 2025 16:52
-
-
Save valorad/3b8e2a2cf87ba37bba4be6b8938830c0 to your computer and use it in GitHub Desktop.
Salesforce Apex Fibonacci Generator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]; | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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