0
\$\begingroup\$

Given a positive input \$n\$, output all permutations of either \$\{0,1,\ldots,n-1\}\$ or \$\{1,2,\ldots,n\}\$.

Examples

Outputting permutations of \$\{1,2,\ldots,n\}\$.

Input Output
1 [(1)]
2 [(1, 2), (2, 1)]
4 [(1, 2, 3, 4), (1, 2, 4, 3), (1, 3, 2, 4), (1, 3, 4, 2), (1, 4, 2, 3), (1, 4, 3, 2), (2, 1, 3, 4), (2, 1, 4, 3), (2, 3, 1, 4), (2, 3, 4, 1), (2, 4, 1, 3), (2, 4, 3, 1), (3, 1, 2, 4), (3, 1, 4, 2), (3, 2, 1, 4), (3, 2, 4, 1), (3, 4, 1, 2), (3, 4, 2, 1), (4, 1, 2, 3), (4, 1, 3, 2), (4, 2, 1, 3), (4, 2, 3, 1), (4, 3, 1, 2), (4, 3, 2, 1)]

Standard loopholes are forbidden. The shortest code wins.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Wouldn't it make more sense for the output to be the permutations of either \$\{0, 1, ..., n-1\}\$ or \$\{1, 2, ..., n\}\$? \$\endgroup\$ Aug 17 at 19:05
  • 1
    \$\begingroup\$ Duplicate? \$\endgroup\$ Aug 17 at 19:25

3 Answers 3

2
\$\begingroup\$

Print out -- Python 3, 58 bytes (@dingledooper)

def f(n,*r):[f(n,*r,x)for x in{*range(n)}-{*r}]or print(r)

Try it online!

Return list -- Python, 62 bytes

f=lambda n,*p:sum((f(n,*p,i)for i in{*range(n)}-{*p}),[])or[p]

Attempt This Online!

Ignoring the standard lib's itertools.permutations.

\$\endgroup\$
2
  • \$\begingroup\$ @solid.py but they conveniently take a set as input which saves them the range and the conversion to set. \$\endgroup\$
    – loopy walt
    Aug 17 at 19:47
  • 1
    \$\begingroup\$ 58 bytes by printing the results \$\endgroup\$ Aug 17 at 21:26
1
\$\begingroup\$

Python, 54 bytes

Outputs all permutations of \$\{0,1,\ldots,n-1\}\$.

lambda n:permutations(range(n))
from itertools import*

Attempt This Online!

\$\endgroup\$
0
\$\begingroup\$

Jelly, 2 bytes

Œ!

Try it online!

Boring builtin answer


Jelly, 4 bytes

!Rœ?

Try it online!

Slightly less boring mostly-builtin answer

How it works

!Rœ? - Main link. Takes n on the left
!    - Yield n!
 R   - Range; [1, 2, ..., n!]
  œ? - For each 1 ≤ i ≤ n!, get the ith permutation of [1, 2, ..., n]
\$\endgroup\$
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.