permutations_iter.sf 489 B

123456789101112131415161718192021222324252627
  1. #!/usr/bin/ruby
  2. #
  3. ## https://rosettacode.org/wiki/Permutations
  4. #
  5. func permute (code, arr) {
  6. var idx = arr.keys;
  7. while (true) {
  8. code(arr.items(idx...));
  9. var p = idx.end;
  10. while (idx[p - 1] > idx[p]) { --p };
  11. p == 0 && return();
  12. idx += idx.splice(p).reverse;
  13. var d = p;
  14. while (idx[p - 1] > idx[d]) { ++d };
  15. idx[p-1, d] = idx[d, p-1];
  16. }
  17. }
  18. var name = %c"abc";
  19. permute(func (list) { list.join(' ').say }, name);