Skip to content

Instantly share code, notes, and snippets.

@EmmanuelOga
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EmmanuelOga/18873d5f34bc4a5e3d10 to your computer and use it in GitHub Desktop.
Save EmmanuelOga/18873d5f34bc4a5e3d10 to your computer and use it in GitHub Desktop.
Generate a list of permutations given a list of numbers.
// Port to ceylon of number permutations code found here:
// https://github.com/johnwhitington/more-ocaml-exercises/blob/master/exercises/Chapter10/exercises.ml#L3-L25
alias IntList => {Integer*};
"intersperce the elem in the list
example:
intersperce({ 1, 2 }, 3)
produces:
{ { 3, 1, 2 }, { 1, 3, 2 }, { 1, 2, 3 } }"
{IntList*} intersperce(Integer elem, IntList list) => {
for (i->_ in list.indexed)
expand { for (j->e in list.indexed) i == j then { e, elem } else { e } }
}.follow(list.follow(elem));
"return a list of lists that results of putting elem in every possible position of each of the lists.
combine(5, {{1,2}, {3,4}})
produces:
{ { 5, 1, 2 }, { 1, 5, 2 }, { 1, 2, 5 }, { 5, 3, 4 }, { 3, 5, 4 }, { 3, 4, 5 } }
"
{IntList*} combine(Integer elem, {IntList*} list) =>
expand { for (subl in list) intersperce(elem, subl) };
"return every permutation of the values of the list"
{IntList*} permutations(IntList list) =>
list.empty then { {} } else combine(list.first else -1, permutations(list.rest));
"should print { { 1, 2, 3 }, { 2, 1, 3 }, { 2, 3, 1 }, { 1, 3, 2 }, { 3, 1, 2 }, { 3, 2, 1 } }"
void main() {
print(permutations({ 1, 2, 3 }));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment