Skip to content

Instantly share code, notes, and snippets.

@gdejohn
Last active September 26, 2015 01:35
Show Gist options
  • Save gdejohn/d6e7d2c3a31bf39881a1 to your computer and use it in GitHub Desktop.
Save gdejohn/d6e7d2c3a31bf39881a1 to your computer and use it in GitHub Desktop.
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;
}
}
);
}
{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