Skip to content

Instantly share code, notes, and snippets.

@gavinking
Last active August 29, 2015 14:27
Show Gist options
  • Select an option

  • Save gavinking/7baadeee8b59010c48ff to your computer and use it in GitHub Desktop.

Select an option

Save gavinking/7baadeee8b59010c48ff to your computer and use it in GitHub Desktop.
permutations of a list, adapted from http://stackoverflow.com/a/28241384/2889760
shared void run() {
for (perm in permutations("ABCD").indexed) {
print(perm);
}
}
shared {Element[]*} permutations<Element>
(List<Element> list)
=> object satisfies {Element[]*} {
iterator()
=> object satisfies Iterator<Element[]> {
value length = list.size;
value permutation = Array(0:length);
value indexes = Array(0:length);
value swaps = Array(0:length);
value directions = Array.ofSize(length, -1);
variable value counter = length;
shared actual Element[]|Finished next() {
while (counter > 0) {
if (counter == length) {
counter--;
return permutation.collect((i) {
assert (exists elem = list[i]);
return elem;
});
}
else {
assert (exists swap = swaps[counter],
exists dir = directions[counter]);
if (swap > 0) {
assert (exists index = indexes[counter]);
value otherIndex = index + dir;
assert (exists swapIndex = permutation[otherIndex]);
permutation.set(index, swapIndex);
permutation.set(otherIndex, counter);
indexes.set(swapIndex, index);
indexes.set(counter, otherIndex);
swaps.set(counter, swap-1);
counter = length;
}
else {
swaps.set(counter, counter);
directions.set(counter, -dir);
counter--;
}
}
}
return finished;
}
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment