Last active
September 26, 2015 01:35
-
-
Save gdejohn/d6e7d2c3a31bf39881a1 to your computer and use it in GitHub Desktop.
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
import ceylon.math.float {random} | |
{Integer*}? sample(Integer k, Range<Integer> range) { | |
value lowerBound = smallest(range.first, range.last); | |
return 0 <= k <= range.size then unfold([0, 0], | |
([Integer, Integer] seed) { | |
value [chosen, visited] = seed; | |
for (i in visited..(range.size)) { | |
if (random() < (k - chosen).float / (range.size - i)) { | |
return [i + lowerBound, [chosen + 1, i + 1]]; | |
} | |
} | |
else { | |
return null; | |
} | |
} | |
); | |
} |
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
{Element*} unfold<Element, Seed>(Seed seed, [Element, Seed]?(Seed) f) | |
=> if (exists [element, next] = f(seed)) then {element, *unfold(next, f)} else []; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment