[Question]
  [
*~~Inspired by~~ Taken from [a question at Stack Overflow](https://stackoverflow.com/q/47693536/2586922)*.
# The challenge
Given an integer `n>1`, output all arrays that can be obtained by swapping exactly two entries in the array `[1, 2, ..., n]`.
The arrays can be produced in any order.
You can consistently use `[0, 1, ..., n-1]` (0-based) instead of `[1, 2, ..., n]` (1-based).
# Additional rules
* Input and output are [flexible as usual](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods).
* [Programs or functions](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) are allowed, in any [programming language](https://codegolf.meta.stackexchange.com/questions/2028/what-are-programming-languages/2073#2073). [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* Shortest code in bytes wins.
# Test cases
Input `2` gives output (assumed 1-based)
```
2 1
```
Input `3` gives output (note that the three arrays could be in any order)
```
1 3 2
2 1 3
3 2 1
```
Input `4` gives output
```
1 2 4 3
1 3 2 4
1 4 3 2
2 1 3 4
3 2 1 4
4 2 3 1
```
Input `7` gives output
```
1 2 3 4 5 7 6
1 2 3 4 6 5 7
1 2 3 4 7 6 5
1 2 3 5 4 6 7
1 2 3 6 5 4 7
1 2 3 7 5 6 4
1 2 4 3 5 6 7
1 2 5 4 3 6 7
1 2 6 4 5 3 7
1 2 7 4 5 6 3
1 3 2 4 5 6 7
1 4 3 2 5 6 7
1 5 3 4 2 6 7
1 6 3 4 5 2 7
1 7 3 4 5 6 2
2 1 3 4 5 6 7
3 2 1 4 5 6 7
4 2 3 1 5 6 7
5 2 3 4 1 6 7
6 2 3 4 5 1 7
7 2 3 4 5 6 1
```
  
[Answer]
# [R](https://www.r-project.org/), 54 bytes
```
function(n)combn(n,2,function(x){z=1:n
z[x]=rev(x)
z})
```
[Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/TyNPMzk/NwlI6xjpwAUrNKurbA2t8riqoitibYtSy4AiXFW1mv/TNEw0/wMA "R – Try It Online")
Returns a matrix where each column is a permutation.
[`combn(n,k)`](https://stat.ethz.ch/R-manual/R-devel/library/utils/html/combn.html) 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.
[Answer]
# [Python 2](https://docs.python.org/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!](https://tio.run/##K6gsycjPM/r/v8i2KDEvPVUjM6@gtERDU5OroCgzryQ6N7FAozrTKksnyyqzVi89tUSnSKdIMy2/SCFTITNPoUgBxMwCM6OtMmNj//83AQA "Python 2 – Try It Online")
Uses [this tip](https://codegolf.stackexchange.com/a/51621/20260).
[Answer]
# [Haskell](https://www.haskell.org/), 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!](https://tio.run/##y0gszk7Nyfn/P00hzzY62lBPr0LXMFZbu9IqukIbyKsE8yqsoitBvLzYmgob3WgwS6cSyKqAiMb@z03MzFOwVchNLPCNV9AoKC0JLinyyVPQUyjNK88vSikGsoByCsUZ@eWaCioKaQrm/wE "Haskell – Try It Online")
I just generate the permutation, given the `x` and `y` to swap, for each `x,y`
[Answer]
# [Python 2](https://docs.python.org/2/), 72 bytes
```
r=range(input())
for j in r:
 for i in r[:j]:t=r*1;t[i]=j;t[j]=i;print t
```
[Try it online!](https://tio.run/##HccrDoAwDABQzykqNxwEtaUnWSYQfFrRLU0RnL581Mvrt51NZndFXeXYAkm/LMQ47E2BgQQ0DfCF/pTENRnqOGUrVJFfuCLlriQG5r48 "Python 2 – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 43 bytes
```
r/.{#->#2,#2->#}&@@@Subsets[r=Range@#,{2}]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7v0hfr1pZ107ZSEfZCEjVqjk4OASXJhWnlhRHF9kGJealpzoo61Qb1caq/Q8oyswriU5zMI/9DwA "Wolfram Language (Mathematica) – Try It Online")
Explanation: `Subsets[Range@#,{2}]` generates all subsets of `{1,2,...,n}` of size 2, then for each subset, `/.` swaps those two things in the list `{1,2,...,n}`.
That approach is disappointingly similar to many of the other submissions, but here's one that's more unique to Mathematica, for 3 extra bytes:
```
r~Permute~Cycles@{#}&/@Subsets[r=Range@#,{2}]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7v6guILUot7Qktc65MjkntdihWrlWTd8huDSpOLWkOLrINigxLz3VQVmn2qg2Vu1/QFFmXkl0moN57H8A "Wolfram Language (Mathematica) – Try It Online")
[Answer]
## Haskell, 62 bytes
```
g n|b<-[1..n]=[[last$k:[j|k==i]++[i|k==j]|k<-b]|i<-b,j<-b,j<i]
```
[Try it online!](https://tio.run/##JcYxCoAwDADAr2RwUNSAgovYJ/iCEKQFqWlrEXXs36victymL7@GkLOFmMzUUocYWREFfd2FH8klr5RwXZN8c5z81BpO8tq4H@G8a4mgYNfHvEB5nBJvtBVQjzhwfgA "Haskell – Try It Online")
```
i<-b                -- loop 'i' through [1..n]
     j<-b           -- loop 'j' through [1..n]
          j<i       -- consider only cases where j<i 
 [            k<-b] -- make a list by looping 'k' through [1..n] 
  last              -- pick
          [i|k==j]  -- 'i' if k==j
       [j|k==i]     -- 'j' if k==i
     k              -- 'k' else   
```
[Answer]
# [Haskell](https://www.haskell.org/), 71 bytes
```
f 0=[]
f x=map(++[x])(f$x-1)++[[1..y-1]++x:[y+1..x-1]++[y]|y<-[1..x-1]]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P03BwDY6litNocI2N7FAQ1s7uiJWUyNNpULXUBPIiTbU06vUNYzV1q6wiq7UBvIqwLzoytiaShvdaKhA7P/cxMw824KizLwSlTQFk/8A "Haskell – Try It Online")
---
This adds the current number to the end of all the permutations of last and then computes all the swaps that include the new number.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 12 bytes
```
:2XN!"G:@tP(
```
[Try it online!](https://tio.run/##y00syfn/38oowk9Ryd3KoSRA4/9/cwA "MATL – Try It Online")
```
            %implicit input, say, 4
:           %range, stack is {[1,2,3,4]}
2           %push 2
XN          %nchoosek, compute all combinations of [1,2,3,4] taken 2 at a time
            %this results in a matrix where each row is a combination, i.e.,
            %[1, 2;
              1, 3;
              1, 4;
              2, 3;
              2, 4;
              3, 4]
!           %transpose, because "for" iterates over columns
"           %begin for loop
G:          %push input and range, stack is now [1,2,3,4]
@t          %push "for" index (the column), say, [1;2], twice
P           %flip array, so stack is now: {[1,2,3,4],[1;2],[2;1]}
(           %assignment index, sets [1,2,3,4]([1;2])=[2;1],
            %resulting in [2,1,3,4]
            %implicit end of loop, implicit end of program, print the stack implicitly.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ 8 bytes
```
ŒcżU$y€R
```
[Try it online!](https://tio.run/##y0rNyan8///opOSje0JVKh81rQn6b6RjrGOiY364HchzB@KsRw1zDm07tO0/AA "Jelly – Try It Online")
### How it works
```
ŒcżU$y€R  Main link. Argument: n
Œc        Take all 2-combinations of [1, ..., n].
  żU$     Zip the result with the reversed pairs.
       R  Range; yield [1, ..., n].
     y€   For each [[i, j], [j, i]] in the result to the left, yield the result to
          the right, with i replaced by j and vice versa. 
```
[Answer]
# C, 93 bytes
```
i,j,k;f(n){for(i=0;i++<n;)for(j=i;j++<n;puts(""))for(k=0;k++<n;)printf("%d ",k-i?k-j?k:i:j);}
```
[Try it online!](https://tio.run/##ZYzBCsIwEETv/YoQEHZpAqKC0LX0WyQS2V2Mpa2n0m@PsYqXzmnmzTDB30PImZ04pQgJ5/gcgNs9cV1fEuEnSsska@xf0wjW4oq1rPS76gdOUwS7uxnr1HOnXjptuBGkJZfOPK6cAKu5MkURDvj/oh86btFpi87FLfkN)
[Answer]
# Octave, 38 bytes
```
@(n)(p=perms(k=1:n))(sum(p~=k,2)==2,:)
```
[Try it online!](https://tio.run/##y08uSSxL/f/fQSNPU6PAtiC1KLdYI9vW0CpPU1OjuDRXo6DONlvHSNPW1kjHSvN/Yl6xhonmfwA "Octave – Try It Online")
Generates all permutations of 1:n and select from them those that have two elements different from 1:n.
[Answer]
# JavaScript (ES6), 81 bytes
Prints 0-indexed arrays.
```
n=>(a=[...Array(n).keys()]).map(i=>a.map(j=>i>j&&alert(a.map(k=>k-i?k-j?k:i:j))))
```
### Demo
`alert()` is replaced with `console.log()` in this snippet for user-friendliness.
```
let f =
n=>(a=[...Array(n).keys()]).map(i=>a.map(j=>i>j&&alert(a.map(k=>k-i?k-j?k:i:j))))
alert = s => console.log(JSON.stringify(s));
f(4)
```
[Answer]
# [Python 2](https://docs.python.org/2/), 75 bytes
```
lambda n:[r(i)+[j]+r(i+1,j)+[i]+r(j+1,n)for j in r(n)for i in r(j)]
r=range
```
[Try it online!](https://tio.run/##JccxDoAgDADA3Vd0hOCii4kJL0EGjKJttJDGxdcjhu0uv8@ZeCzRLuUK97oF4NmJQm0ceVNhhp5q8A/VsI5JgAAZRLVgC2nfiZXAx16yID8Q1aTLBw "Python 2 – Try It Online")
[Answer]
# [Clean](https://clean.cs.ru.nl), ~~90~~ 82 bytes
```
import StdEnv
$n#n=[1..n]
=tl(removeDup[[if(c<>b)if(c<>a)c b a\\c<-n]\\b<-n,a<-n])
```
It can be done in 80 bytes, but it turns into a direct translation of the Haskell answers.
[Try it online!](https://tio.run/##JcyxCoMwEIDh3acI1MFAFTp1MZ3sUOjmmDhczlgCyUU0Cn35Xi2dvn/6MTggjmncghMRPLGPc1qy6PN4p70o6URKX5qGhkLlUC0upt1126y1nypsb1b@BYnCCjAG25oGY@zBGX4tuc9wHJUor/zBKcBr5frx5O5NED2uXw "Clean – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~15~~ 9 bytes
```
LœʒD{αĀO<
```
[Try it online!](https://tio.run/##MzBNTDJM/f/f5@jkU5Ncqs9tPNLgb/P/vykA "05AB1E – Try It Online")
**Explanation**
```
L            # push range [1 ... input]
 œ           # get all permutations
  ʒ          # filter, keep only elements that are true when
     α       # absolute value is taken with
   D{        # a sorted copy
      Ā      # each non-zero value in the resulting array is converted to 1
       O     # the array is summed
        <    # and the sum is decremented
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 9 bytes
```
!2§kδ#≠Pḣ
```
[Try it online!](https://tio.run/##yygtzv7/X9Ho0PLsc1uUH3UuCHi4Y/H////NAA "Husk – Try It Online")
## Explanation
```
!2§kδ#≠Pḣ  Input is an integer n.
        ḣ  Range: r=[1,2,..,n]
       P   Permutations of r.
   k       Classify by
     #     number of elements
      ≠    that are different from
  § δ      the corresponding element of r.
!2         Take the second class.
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~55~~ 53 bytes
```
->n{n.times{|x|x.times{|y|(w=*0...n)[w[x]=y]=x;p w}}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6vOk@vJDM3tbi6pqKmAsasrNEot9Uy0NPTy9OMLo@uiLWtjLWtsC5QKK@trf2fFm0Uy5UWbQIizGP/AwA "Ruby – Try It Online")
0-based solution
The trick here is that the inner loop always "skips" an iteration: the first time it's not executed at all, then only once on the second pass, and so on.
I was happy with 55 bytes until I saw that **R** could be golfed down to 54, so I had to get it to 53.
[Answer]
# [Python 2](https://docs.python.org/2/), 90 bytes
```
f=lambda n,r=range:n*[n]and[a+[n]for a in f(n-1)]+[r(1,i)+[n]+r(i+1,n)+[i]for i in r(1,n)]
```
[Try it online!](https://tio.run/##PYpBCsIwEADvfcUeE7MeUgWh0JeEHFZqdMFswpKLr4@NFG8zzNRPexWZe0/rm/J9IxDUVUmej0VOQSLJFsjtkIoCAQskI2dvowtqPLIdzalh51F24d/IYxxdbOxJS4ZalaUB51q0HTb91xnhgnBFuC0THNUkw9b2Lw "Python 2 – Try It Online")
[Answer]
# Pyth, 9 bytes
```
t{.rLQ*=U
```
[Demonstration](https://pyth.herokuapp.com/?code=t%7B.rLQ%2a%3DU&input=4&debug=0)
The easiest way to swap two values is to use `.r`, which is Pyth's rotary translation function. `.r<list>[A, B]` will swap all occurrences of `A` and `B` in `list`.
Therefore, by applying the translation function to `UQ`, the list from `0` to `n-1` with each two element list of different numbers in the list, we will generate the desired output. `Q` is the input, `n`, and `U` is the range function.
The easy way to do this would be:
```
.rLUQ.cUQ2
```
`.cUQ2` generates all 2 element combinations of distinct elements in the range, and `.rLUQ` maps the `.r` function over them and the list `UQ`.
However, that would be 10 bytes.
Instead of making `.cUQ2`, the distinct ordered pairs, we can make all pairs with `*=U`. This is implicitly equivalent to `*=UQQ`. It starts by overwriting `Q` with `UQ`, then taking the Cartesian product of `UQ` and `UQ`. This gives all pairs of numbers in the range, not necessarily ordered or distinct.
`.rLQ` swaps using each list. Recall that `Q` is now equal to the list from `0` to `n-1`, not `n`.
Because the pairs were not ordered, there are duplicates. `{` removes duplicates. Because the pairs were not distinct, the unchanged list is present. This list will always be first after deduplication, because `{` preserves the order of the first appearance and the unchanged list is produced by rotating by `[0,0]`. `t` removes the first element, giving the desired list of swaps.
[Answer]
# Pyth, 11 bytes
```
fq2snVTUQ.p
```
[Try it online](http://pyth.herokuapp.com/?code=fq2snVTUQ.p&input=7&debug=0)  
Not as short as isaacg's approach, but different enough to post.
### Explanation
```
fq2snVTUQ.p
         .pQ  Take the permutations of the (implicit) range [0,...,input].
f     T       Filter to get the permutations...
   snV UQ     ... where the number of differences with [0,...,input]...
 q2           ... is 2.
```
[Answer]
# Java 8, ~~109~~ 105 bytes
```
n->{String r="";for(int i=0,j,k;i++<n;)for(j=i;j++<n;r+="\n")for(k=0;k++<n;)r+=k!=i?k!=j?k:i:j;return r;}
```
I'm rusty.. Haven't code-golfed in months.. Ended up porting [@Steadybox' C answer](https://codegolf.stackexchange.com/a/152285/52210).. Can probably be golfed some more.
[Try it here.](https://tio.run/##hZDBasMwDIbvewotp5i0oayDQTWvT7Bedlx78Fx3yE6V4DiFUfLsqZrkOgqWQf8nIf3y5mKWdePYH8NgK9O28GmIr08AxMnFk7EOdvcU4CtF4l@wuRBghSL2EvLaZBJZ2AGDhoGXH9e5Nuosw1MdxxbSq4VfBKSieGdUd9lrQj@msdDZnrNRDXqFYSoSOTxr2srnt2FDG4/RpS4yROwHnMY33U8l4@ctLjUd4Swm8mmJ74NRs4G/NrlzWXepbISkinMubf6iRi//8vUD/vqAv6n5Vv1wAw)
[Answer]
# [Ruby](https://www.ruby-lang.org/), 66 bytes
```
->n{a=*1..n
a.permutation.select{|b|b.zip(a).count{|c,d|c!=d}==2}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6vOtFWy1BPL48rUa8gtSi3tCSxJDM/T684NSc1uaS6JqkmSa8qs0AjUVMvOb80DyiSrJNSk6xom1Jra2tUW/tfw0hPz1xTLzUxOaO6pqKmQCEtuiK29j8A "Ruby – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 80 bytes
*-12 bytes thanks to Unihedron.*
```
->n{(r=1..n).map{|x|r.map{|y|r.map{|i|i==x ?y:i==y ?x:i}}}.flatten(1).uniq[1,n]}
```
[Try it online!](https://tio.run/##NcZBCoAgEADAr3hUqAWhk2A9RDwUJCzUYmKgqG@3IDrNhHvL3ek@zlR40BKABJyrLzXV8CX/wYpaJ7Zk9ZrZkhS21sAda4w7cSngJryMHMi27gNSZM5Mtj8 "Ruby – Try It Online")
I had an approach in mind that best translated to Ruby for some reason so... I don't even really know Ruby...
]