Single swaps of an array
R, 54 bytes
function(n)combn(n,2,function(x){z=1:n
z[x]=rev(x)
z})
Try it online!
Returns a matrix where each column is a permutation.
combn(n,k)
generates all combinations of size k
from the list n
, or from 1:n
if n
is a single integer. It also optionally takes a function FUN
to be applied to the resultant combinations. So we write a function that performs the swap and returns the swapped list. The results are then all accumulated into an array
, which is in this case 2-dimensional and hence a matrix.
Python 2, 71 bytes
r=range(input())
print[map({i:j,j:i}.get,r,r)for i in r for j in r[:i]]
Try it online!
Uses this tip.
Haskell, 62 bytes
f n=[[1..x-1]++y:[x+1..y-1]++x:[y+1..n]|x<-[1..n],y<-[x+1..n]]
Try it online!
I just generate the permutation, given the x
and y
to swap, for each x,y