# Is there an elegant way to generate the permutations of all the members of a set?

**URL:** <https://discourse.processing.org/t/is-there-an-elegant-way-to-generate-the-permutations-of-all-the-members-of-a-set/31810>\
**Category:** Coding Questions\
**Created:** [August 20, 2021, 5:04pm UTC](https://discourse.processing.org/t/is-there-an-elegant-way-to-generate-the-permutations-of-all-the-members-of-a-set/31810 "2021-08-20T17:04:55Z")\
**Posts on this page:** 1\
**Showing post:** 5

<div class="post-metadata">

**Author:** ![jeremydouglass](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/jeremydouglass/32/20_2.png) [@jeremydouglass](https://discourse.processing.org/u/jeremydouglass)\
**Post date:** [August 20, 2021, 4:14pm UTC](https://discourse.processing.org/t/is-there-an-elegant-way-to-generate-the-permutations-of-all-the-members-of-a-set/31810/5 "2021-08-20T16:14:26Z")

</div>

I’m happy to move these to a new thread / topic – @paulstgeorge, go ahead and create one.

> [@10 print chr$(205.5+rnd(1)); : goto 10](https://discourse.processing.org/t/10-print-chr-205-5-rnd-1-goto-10/15483/61):
>
> an elegant way to generate the permutations of all the members of a set

One example I like is the Python documentation of itertools.permutations.

- [itertools — Functions creating iterators for efficient looping — Python 3.12.1 documentation](https://docs.python.org/3/library/itertools.html#itertools.permutations)
- [cpython/Modules/itertoolsmodule.c at main · python/cpython · GitHub](https://github.com/python/cpython/blob/main/Modules/itertoolsmodule.c)

It is very idiomatically Python – the use of a separate index lookup, of slicing, and of `reversed()` – so it doesn’t translate well to Java, but it is pretty interesting as an approach.

```python
def permutations(iterable, r=None):
    # permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC
    # permutations(range(3)) --> 012 021 102 120 201 210
    pool = tuple(iterable)
    n = len(pool)
    r = n if r is None else r
    if r > n:
        return
    indices = list(range(n))
    cycles = list(range(n, n-r, -1))
    yield tuple(pool[i] for i in indices[:r])
    while n:
        for i in reversed(range(r)):
            cycles[i] -= 1
            if cycles[i] == 0:
                indices[i:] = indices[i+1:] + indices[i:i+1]
                cycles[i] = n - i
            else:
                j = cycles[i]
                indices[i], indices[-j] = indices[-j], indices[i]
                yield tuple(pool[i] for i in indices[:r])
                break
        else:
            return

```

---

_[View the full topic](https://discourse.processing.org/t/is-there-an-elegant-way-to-generate-the-permutations-of-all-the-members-of-a-set/31810)._
