[Question]
  [
An \$n\times n\$ [Latin Square](https://en.wikipedia.org/wiki/Latin_square) is a grid containing exactly \$n\$ distinct values where the values in each row and column are distinct. For example,
$$\begin{matrix}
A & B & C \\
C & A & B \\
B & C & A \\
\end{matrix}$$
is a Latin square as no row or column contains a repeated value.
You are to take a positive integer \$n\$ as input and output an \$n\times n\$ Latin Square. The values can be any \$n\$ distinct values, and do not have to be consistent for different \$n\$. Your program should be consistent and deterministic, so running it with the same input should always produce the same output.
You may output in any reasonable manner, including a flat array consisting of \$n^2\$ values, or as a list of \$n\$ lists, each containing \$n\$ values. You may input and output in any [convenient method](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods)
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins.
## Test cases
These are just some possible outputs, your program may differ so long as the output is correct
```
1 [[1]]
2 [[1, 2], [2, 1]]
3 [[1, 2, 3], [2, 3, 1], [3, 1, 2]]
4 [[1, 2, 3, 4], [2, 1, 4, 3], [3, 4, 1, 2], [4, 3, 2, 1]]
5 [[1, 2, 3, 4, 5], [2, 3, 5, 1, 4], [3, 5, 4, 2, 1], [4, 1, 2, 5, 3], [5, 4, 1, 3, 2]]
```
  
[Answer]
# [Python 2](https://docs.python.org/2/), 37 bytes
Outputs a flattened \$ n \times n \$ latin square.
```
lambda n:((range(n)*-~n)[1:]*n)[::~n]
```
[Try it online!](https://tio.run/##RcuxCsIwGATgPU9xYxIrWAeHH/okNUOkjf6g1xK6uPTVY0IHlzs4vlu/22vhtaThXt7x85giKNbmyOds6fx5pxt7Cb6WyM5Q0pJBKHGYvsPNiUHMGQNS/Rg0on9y6UDPGs1hzcqt8VFFTwzmWMoP "Python 2 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes
```
RṙⱮ
```
[Try it online!](https://tio.run/##y0rNyan8/z/o4c6Zjzau@3@43f3/f2MA "Jelly – Try It Online")
## Explanation
```
RṙⱮ  Monadic link, takes an argument z
R    [1, 2, ..., z-1, z]
  Ɱ  For each on right argument (z, defaults to loop over range)
 ṙ   Rotate the left list by the right amount
```
Alternative solution: `+þ%`. Generates the \$n\times n\$ addition table and then applies modulo to bring the elements into range.
[Answer]
# [R](https://www.r-project.org/), 30 bytes
```
n=scan();outer(1:n,1:n,`+`)%%n
```
[Try it online!](https://tio.run/##K/r/P8@2ODkxT0PTOr@0JLVIw9AqTweEE7QTNFVV8/6b/gcA "R – Try It Online")
[Answer]
# [APL (dzaima/APL)](https://github.com/dzaima/APL), 4 bytes
```
⌽ᐵ⍨⍳
```
```
⌽ rotate
ᐵ each left, apply each left element to the entire right argument
⍨ apply to both arguments
⍳ range
```
[Try it online!](https://tio.run/##SyzI0U2pSszMTfz/P@1R24RHPXsfTtj6qHfFo97NXI/6pgKF0hRM4SyT//8B "APL (dzaima/APL) – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 6 [bytes](https://github.com/abrudz/SBCS)
```
⍳⌽,⍨⍴⍳
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT////1Hv5kc9e3Ue9a541LsFyPmf9qhtwqPevkddzYfWGz9qm/iob2pwkDOQDPHwDP6fpmACAA "APL (Dyalog Unicode) – Try It Online")
There's already a nice [4-byter in dzaima/APL](https://codegolf.stackexchange.com/a/223592/78410) by rak1507, but I wanted to share a non-trivial short one in vanilla Dyalog. It is shorter than a modulo addition table `⊢|⍳∘.+⍳` and ties with the trivial port of rak's `⍳⌽¨∘⊂⍳`.
Takes n and creates a flat matrix of numbers.
```
⍳⌽,⍨⍴⍳   ⍝ Input: n
  ,⍨     ⍝ [n, n]
    ⍴⍳   ⍝ Reshape [1..n] into an n×n matrix
         ⍝ For n = 4, this looks like this:
         ⍝ 1 2 3 4
         ⍝ 1 2 3 4
         ⍝ 1 2 3 4
         ⍝ 1 2 3 4
⍳⌽       ⍝ Rotate first row once, second row twice, ..., n-th row n times
         ⍝ 2 3 4 1
         ⍝ 3 4 1 2
         ⍝ 4 1 2 3
         ⍝ 1 2 3 4
```
[Answer]
# [Haskell](https://www.haskell.org/), 32 bytes
```
f n=[[x..n]++[1..x-1]|x<-[1..n]]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P00hzzY6ukJPLy9WWzvaUE@vQtcwtqbCRhfEzouN/Z@bmJmnYKuQm1jgq6ABJguKMvNKFPQU0jQVQIpMY/8DAA "Haskell – Try It Online")
A kind-of boring approach, just concatenates the ranges.
**34 bytes**
```
f n=[mod(k+div(-k)n)n|k<-[1..n*n]]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P00hzzY6Nz9FI1s7JbNMQzdbM08zrybbRjfaUE8vTysvNvZ/bmJmnoKtQm5iga9CQVFmXomCCoijkKYAUmMa@x8A "Haskell – Try It Online")
Outputs a flat list, zero-indexed, using the method from [my Python answer](https://codegolf.stackexchange.com/a/223604/20260). A slight adaptation is needing to make it work for `[1..n*n]` instead of `[0..n*n-1]`.
[Answer]
# [J](http://jsoftware.com/), 7 bytes
```
|i.+/i.
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/azL1tPUz9f5rcqUmZ@QrpCkYQhjqurrqMCHT/wA "J – Try It Online")
Creates an "addition table" of the range 0..n with itself `i.+/i.` and then takes the mod of each element by n `|`.
[Answer]
# [Julia 1.0](http://julialang.org/), 19 bytes
```
!n=((N=1:n).+N').%n
```
[Try it online!](https://tio.run/##yyrNyUw0rPj/XzHPVkPDz9bQKk9TT9tPXVNPNe9/SmZxQU5ipYaioaZ1QVFmXklOnoYmF1zUCKuoKVZRQwMk4f8A "Julia 1.0 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 40 bytes
```
lambda n:[(k+k/n)%n for k in range(n*n)]
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPKlojWztbP09TNU8hLb9IIVshM0@hKDEvPVUjTytPM/Y/SDAPIWioY6ZpVVCUmVeikKaRp/kfAA "Python 2 – Try It Online")
Since the challenge allows a flat list of `n*n` outputs, we make do mapping `k=0, 1, ... n*n-1` to the corresponding entry with `(k+k/n)%n`. We can get this by adding the row index `k/n` and column `k%n` and reducing modulo `n`, and removing the redundant inner `%n`. We could also do `k*-~n/n%n`.
[Answer]
# [Haskell](https://www.haskell.org/), ~~37~~ 35 bytes
Saved 2 bytes thanks to @Delfad0r
Would have saved 5 bytes thanks to @AZTECCO (see [xnor's answer](https://codegolf.stackexchange.com/a/223609/95792))
```
f n=[mod(x+o)n|x<-[1..n],o<-[1..n]]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P00hzzY6Nz9Fo0I7XzOvpsJGN9pQTy8vVicfxor9n5uYmadgZaXg6a@gockF5tkqFBRl5pUoqCjkJhYopCmAlJrG/gcA "Haskell – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 22 bytes
```
.+
*
Y`\_`w
L$`.
$<'$`
```
[Try it online!](https://tio.run/##K0otycxLNPz/X0@bS4srMiEmPqGcy0clQY9LxUZdJeH/fxMA "Retina – Try It Online") Explanation:
```
.+
*
```
Convert the input to unary.
```
Y`\_`w
```
Take the first `n` word characters (or use `p` for printable ASCII etc.)
```
L$`.
$<'$`
```
Create cycled rows. (`$<'` is the same as `$&$'`.)
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 21 bytes
```
@(n,x=1:n)mod(x+x',n)
```
[Try it online!](https://tio.run/##y08uSSxL/f/fQSNPp8LW0CpPMzc/RaNCu0JdJ0/zf2JesYal5n8A "Octave – Try It Online")
The same thing as many other answers...
-2 bytes by [Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe)
[Answer]
# [Arturo](https://arturo-lang.io/), 33 bytes
```
$[n][map 0..(n*n)-1'x[(x+x/n)%n]]
```
[Try it on the Arturo Playground!](http://arturo-lang.io/playground?HMWlRd) **Note: it seems that editing the code edits it for everyone, so don't do that.**
[Answer]
# [Perl 5](https://www.perl.org/) `-a`, 34 bytes
```
$,=$";say$_.."@F",1..$_-1for 1..$_
```
[Try it online!](https://tio.run/##K0gtyjH9/19Fx1ZFybo4sVIlXk9PycFNScdQT08lXtcwLb9IAcz8/9/kX35BSWZ@XvF/XV9TPQNDg/@6iQA "Perl 5 – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 23 bytes
```
+##&~Array~{#,#}~Mod~#&       
```
or (as @Roman suggested)
```
Plus~Array~{#,#}~Mod~#&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n277X1tZWa3OsagosbKuWllHubbONz@lTlntf0BRZl6Jgr5DerRp7P//AA "Wolfram Language (Mathematica) – Try It Online")
-2 bytes thanks to @att
[Answer]
# [jq](https://stedolan.github.io/jq/), 20 bytes
```
range(.*.)*(1+1/.)%.
```
[Try it online!](https://tio.run/##yyr8/78oMS89VUNPS09TS8NQ21BfT1NV7/9/EwA "jq – Try It Online")
output is flattened
(my first jq answer)
[Answer]
# [Python 2](https://docs.python.org/2/), 43 bytes
```
lambda x,r=range:[r(i,x)+r(i)for i in r(x)]
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaFCp8i2KDEvPdUqukgjU6dCUxtIaablFylkKmTmKRRpVGjG/i8oyswrUUjTMNTkgjGNEExjBNMEwTTV/A8A "Python 2 – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-m`](https://codegolf.meta.stackexchange.com/a/14339/), 3 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Output as a 2D array.
```
WéU
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LW0&code=V%2blV&input=NAotUQ)
Or without the `-m` flag:
## [Japt](https://github.com/ETHproductions/japt), 4 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
ÆZéX
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=xlrpWA&input=NAotUQ)
[Answer]
# [C (clang)](http://clang.llvm.org/), ~~73~~ \$\cdots\$ ~~49~~ 46 bytes
Saved 3 bytes thanks to [dingledooper](https://codegolf.stackexchange.com/users/88546/dingledooper)!!!
```
a;f(n){for(a=n*n;a;)printf("%d ",--a*~n/n%n);}
```
[Try it online!](https://tio.run/##PY3BCoMwEETv@YolIGy0ofTSy9aPWVIigp2KWnqQ9NObBpXOZdiZt0zwYVB0OatEhlvjc2JtUUNU3Dj1WCLb6k725L3WH5xRwUnKD@3BzqyGisoTcUEJ1NJFit3oKtQ0cFu/UxtZNuR/ja9lZmuPJJlk8jfEQbs5@/cP "C (clang) – Try It Online")
Inputs \$n\$ and prints the Latin Square as a flat array consisting of \$n^2\$ values.
[Answer]
# JavaScript (ES6), 46 bytes
```
n=>[...Array(n)].map((_,i,a)=>a.map(_=>i++%n))
```
[Try it online!](https://tio.run/##LclBCoNADEDRq8ymmKDN1lUGeo4qEqzKiE0kiuDpp0Xcvc@f5ZCt97TuT7XPkEfOyvFNRC93OUGxpa@sAF2VKkGOcmXHMZXlQxFzb7rZMtBiE4xQ4/U9cAxOsyWFIhSINxv9O/8A "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES6), 42 bytes
As pointed out by [@tsh](https://codegolf.stackexchange.com/users/44718/tsh), returning a flatten array is shorter.
```
n=>[...Array(n*n)].map((_,i)=>(i/n+i)%n|0)
```
[Try it online!](https://tio.run/##DcvbCoJAEADQX/FFnEmbTQp8WsHvCJFlvTSiM7JKENW3b533M7un233g7TiL9kMcbRRb34moCcG9QE6CLa1uA@gKRlsDG8kZU/lcMHqVXZeBFp1ghAppVhbIkgz/5fAPMPQur0V5@5oJMf4A "JavaScript (Node.js) – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), 3 bytes
```
5YL
```
[Try it online!](https://tio.run/##y00syfn/3zTS5/9/CwA "MATL – Try It Online")
```
          %implicit input n
5YL       % create circular matrix of size n
```
Equivalent to the following Octave/MATLAB code
# [Octave](https://www.gnu.org/software/octave/), 23 bytes
```
@(n)gallery('circul',n)
```
[Try it online!](https://tio.run/##y08uSSxL/Z@mYKugp6f330EjTzM9MScntahSQz05syi5NEddJ0/zf5qGpeZ/AA "Octave – Try It Online")
Alternately, this is equivalent to [tsh's Octave answer](https://codegolf.stackexchange.com/a/223622/67312).
# [MATL](https://github.com/lmendo/MATL), 5 bytes
```
:&+G\
```
[Try it online!](https://tio.run/##y00syfn/30pN2z3m/39TAA "MATL – Try It Online")
```
	% implicit input n
:	% range 1:n
&+	% add to itself transposed, with broadcast
G\	% push n and modulo n
	% implicit output
```
[Answer]
# [yuno (abandoned)](https://github.com/hyper-neutrino/yuno-abandoned/), 4 [bytes](https://github.com/hyper-neutrino/yuno-abandoned/wiki/Byte-count)
```
ップア＠％
```
## Explanation
```
ップ　　　　outer product table; for each (first) and for each (second)
　　ア　　　add
　　　＠　　swap top two
　　　　％　modulo
```
Can be written as `ppua@%`. Code is grouped as `[ップ][ア][＠][％]`. To prove this is actually 4 bytes, the bytecode is `'~\x00ðó'` (use the `b` flag to interpret code from bytecode).
[Answer]
# Scala, 44 bytes
```
n=>1 to n flatMap(_=>1 to n)sliding n take n
```
[Try it in Scastie!](https://scastie.scala-lang.org/EZzhiRjVQgOTdOfyHL2c5Q)
This is so simple it hardly needs an explanation, but here's one anyway:
```
n =>                     //The input
1 to n                   //Make a range of n numbers
  flatMap(_ => 1 to n)   //Map each to the range [1, n] and flatten
                         //This creates a list of n*n numbers
  sliding n              //Take n-sized chunks and move ahead by one each time
  take n                 //Keep the first n chunks
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes
```
LD._
```
[Try it online!](https://tio.run/##yy9OTMpM/f/fx0Uv/v9/UwA "05AB1E – Try It Online")
```
LD._  # full program
  ._  # push...
L     # [1, 2, 3, ...,
      # ..., implicit input...
L     # ]...
  ._  # rotated to the left...
      # (implicit) each element in...
LD    # [1, 2, 3, ...,
      # ..., implicit input...
LD    # ]
      # implicit output
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 7 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
o £o éX
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=byCjbyDpWA&input=NC1S)
```
o   - [0..U)
£   - map by:
o éX    > rotate X times [0..U)
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 61 bytes
```
param($n)(0..($n*$n-1)|%{[math]::floor($_+$_/$n)%$n})-join" "
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/vyCxKDFXQyVPU8NATw9Ia6nk6Rpq1qhWR@cmlmTEWlml5eTnF2moxGurxOsDlamq5NVq6mblZ@YpKSj9///fCAA "PowerShell – Try It Online")
[Answer]
# [V (vim)](https://github.com/DJMcMayhem/V), ~~38~~ 30 bytes
```
"aD@aO0<ESC>V{g<C-A>V}JqqYpdw$pq@a@qdk
```
[Try it online!](https://tio.run/##K/v/XynRxSHR38DGNdjZLqw63cZZ19EurNarsDCyIKVcpaDQIdGhMCX7/39jg/@6ZQA "V (vim) – Try It Online")
Input as a single number.
Range creating script taken from Leo's [Range, Reverse, Sum](https://codegolf.stackexchange.com/a/223249/80214) answer.
-8 bytes from Leo using `J`.
Fixed the problem with multidigit numbers.
## Explanation
```
"aD@aO0<ESC>V{g<C-A>V}J
"aD                          delete first line and store in register a
   @aO0<ESC>                 print 0 on a newline a times
            V{g<C-A>         convert the zeroes to a range
                    V}J      select all, join with spaces
$xqqYp2x$pq@a@qdk
$x                           remove the last space
  qq                         start macro q:
    Yp                        duplicate current line
      dw                      remove first word (number + space)
        $p                    paste at the end
          q                  end macro
           @a@q              replay macro a times
               dk            delete last two extra iterations
```
[Answer]
# Ruby, 33 bytes
```
->n{(0..n*n-1).map{|x|(x+x/n)%n}}
```
[Try it online!](https://tio.run/##KypNqvyfqGCr8F/XLq9aw0BPL08rT9dQUy83saC6pqJGo0K7Qj9PUzWvtvZ/gUKiXnJiTo6CMRecafofAA)
A lambda proc returning a flat array of n\*n elements.
[Answer]
# [Java (JDK)](http://jdk.java.net/), 56 bytes
```
n->{for(int i=n*n;i-->0;)System.out.println((i/n+i)%n);}
```
[Try it online!](https://tio.run/##jU09T8MwEN3zK54qIcWNYrqwYNKFiYGpI2IwblJdSM6Rfa6Eqvz24JaPhQ4Mp6d7n7092rrfvy80Tj4I@vzrJDTotSn@cF1iJ@T5LLrBxohnS4xTAUzpbSCHKFYyHD3tMWat3EkgPry8woZDVBcr8MTy6DmmsQ3omoXr7anzoSQWUMNrNlTX241Ru48o7ah9Ej3lGhm4LOmWK1I3rMy8mEtbjuIriwYbk@GhwV3GqvoZBK5UUbW6Xynzbei0da6dpKRf6krmH9pcnG9ePgE "Java (JDK) – Try It Online")
[Answer]
# Python 2, 79 bytes
```
n=input()
f=lambda b:f(b+b[-1:]+b[-n:-1])if len(b)<n*n else b
print f(range(n))
```
[Try it online!](https://tio.run/##FcWxDkAwEAbg3VPceEcMJJaGJxFDL1qa1K@hBk9f8S1fevN@oi8FU0B6Mkvlp2gPXS2p8ayNzm1nlj@YtlskeIoOrDKiBrl4O9IqXQGZPF8Wm2OIlDJ8)
]