Created
December 2, 2018 18:11
-
-
Save xpmatteo/97e1af0d9052b463d0b3cdebffae8db1 to your computer and use it in GitHub Desktop.
An imperative, object-oriented way to solve the "give me the first N primes" problem
This file contains 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 class SetOfPrimes { | |
private List<Integer> primes = new ArrayList<>(); | |
public static SetOfPrimes ofSize(int desiredSize) { | |
SetOfPrimes setOfPrimes = new SetOfPrimes(); | |
int candidate = 2; | |
while (setOfPrimes.size() < desiredSize) { | |
setOfPrimes.considerForInclusion(candidate++); | |
} | |
return setOfPrimes; | |
} | |
private void considerForInclusion(Integer candidate) { | |
if (notDivisibleByAnyPrime(candidate)) | |
primes.add(candidate); | |
} | |
private boolean notDivisibleByAnyPrime(Integer candidate) { | |
return primes.stream().allMatch( prime -> candidate % prime != 0); | |
} | |
private int size() { | |
return primes.size(); | |
} | |
public Set<Integer> toSet() { | |
return new LinkedHashSet<>(primes); | |
} | |
} |
This file contains 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 class SetOfPrimesTest { | |
@Test | |
public void setOfPrimesTest() throws Exception { | |
assertThat(SetOfPrimes.ofSize(0).toSet(), is(emptySet())); | |
assertThat(SetOfPrimes.ofSize(1).toSet(), is(singleton(2))); | |
assertThat(SetOfPrimes.ofSize(2).toSet(), is(setOf(2, 3))); | |
assertThat(SetOfPrimes.ofSize(3).toSet(), is(setOf(2, 3, 5))); | |
assertThat(SetOfPrimes.ofSize(4).toSet(), is(setOf(2, 3, 5, 7))); | |
assertThat(SetOfPrimes.ofSize(10).toSet(), is(setOf(2, 3, 5, 7, 11, 13, 17, 19, 23, 29))); | |
} | |
private Set<Integer> setOf(Integer ... numbers) { | |
return new HashSet<>(asList(numbers)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment