Advertisement
Guest User

Untitled

a guest
Dec 3rd, 2016
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.55 KB | None | 0 0
  1. const swap = (x, y, a) => {
  2. const arr = a.slice()
  3. arr[y] = a[x];
  4. arr[x] = a[y];
  5. return arr
  6. }
  7.  
  8. function* heapPermutations(arr) {
  9. const length = arr.length
  10. const c = Array.apply([], { length }).map(() => 0)
  11. let i = 0;
  12. yield arr
  13. while (i < length) {
  14. if (c[i] < i) {
  15. arr = swap(i%2===0 ? 0 : c[i], i, arr)
  16. yield arr
  17. c[i] += 1
  18. i = 0
  19. } else {
  20. c[i] = 0
  21. i += 1
  22. }
  23. }
  24. }
  25.  
  26. const stringPermutations = string => [...heapPermutations(string.split(''))].map(a => a.join(''))
  27. console.log(stringPermutations('zamagni'))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement