g | x | w | all
Bytes Lang Time Link
017Juby250522T180225ZJordan
055AWK250522T144055Zxrs
021Uiua240621T074042ZJoonas
021Octave/MATLAB240311T123624Z138 Aspe
067Go230316T193219ZThe Thon
021Risky210614T190755ZAdam
028TIBasic210908T161242ZYouserna
020jq210908T094940ZMarcMush
004yuno abandoned210508T191105Zhyperneu
002yuno abandoned210512T060720Zhyperneu
004Vyxal r210508T181035Zhyperneu
5614MMIX210508T211343ZNoLonger
030Ruby210419T114206ZG B
005Pyth210418T195443Zhakr14
079Python 2210418T191547ZFaelif
064Befunge98 PyFunge210417T200611Zuser
023Wolfram Language Mathematica210415T210324ZZaMoC
056Java JDK210416T222602ZOlivier
012Charcoal210416T184906ZNeil
118Python 3210415T203617ZSegFault
036Excel210416T154336ZAxuary
034Perl 5 a210416T142026ZXcali
003MATL210416T030753ZGiuseppe
035Zsh210416T134604Zpxeger
4544Bash210416T044401ZJonah
033Arturo210416T130146ZAdam
019Julia 1.0210416T114809ZMarcMush
046JavaScript ES6210415T203715ZArnauld
033Ruby210416T062051ZiBug
007J210416T041437ZJonah
006APL Dyalog Unicode210416T041431ZBubbler
3830V vim210416T022006ZRazetime
021Octave210416T020034Ztsh
061PowerShell210416T015241Zwasif
046C clang210415T214523ZNoodle9
041Python 3210416T000231ZNoodle9
037Python 2210415T225604Zdingledo
022Retina210415T232619ZNeil
003Japt m210415T224233ZShaggy
032Haskell210415T214524Zxnor
035Haskell210415T212341Zuser
040Python 2210415T212947Zxnor
007Japt210415T212526ZAZTECCO
00405AB1E210415T211123ZMakonede
030R210415T205115ZKirill L
003Jelly210415T203132Zhyperneu
044Scala210415T203813Zuser
043Python 2210415T203732Zhyperneu
004APL dzaima/APL210415T203451Zrak1507

J-uby, 17 bytes

:*%[:+|:& &:|,:+]

Attempt This Online!

Explanation

:* % [:+ | :& & :|, :+]
:* % [            ,   ]  # Map each n in
                    :+   # range 1..input
      :+ |               #   with range 1..input
           :& & :|       #   rotated right by n

AWK, 55 bytes

{for(;i<$1^2;printf i%$1?FS:RS)printf int(i/$1+i++)%$1}

Attempt This Online!

Similar to other answers, could be shorter if we don't print pretty:

Pretty Print

Uiua, 21 bytes, 9 characters

◌⍥(⊸↻1)⟜⇡

Try it on Uiua Pad

Code explained

Uiua is a stack-based language that reads code from right to left.

⟜⇡       #  Duplicate the input on top of the stack and create an array of integers
(⊸↻1)    #  Rotate the array by one and keep the input on top of the stack
⍥        #  Repeat the previous operation [input] times
◌         #  Discard the top stack value

Becauses the array rotates around, eventually the code produces the original array on top of the stack which is why the top stack value must be discarded.

Octave/MATLAB, 21 bytes

with the help of the built-in function magic

M = magic(n) returns an n-by-n matrix constructed from the integers 1 through n^2 with equal row and column sums. The order n must be a scalar greater than or equal to 3 in order to create a valid magic square.


Try it online!

@(n)mod(magic(n),n)+1

Go, 67 bytes

import."fmt"
func f(n int){
for k:=0;k<n*n;k++{Println((k+k/n)%n)}}

Attempt This Online!

Outputs each element of the flattened square on a newline.

Risky, 21 bytes

00?+0*_?-1/_?-1+_0+02-0?+0+_]+]+_]+]+_]+]

Try it online!

TI-Basic, 28 bytes

Prompt N
For(I,1,N
Disp remainder(I+seq(J,J,1,N),N
End

Outputs each row as a list on a separate line. Note that remainder( only works for TI-84+/SE with the 2.53 MP OS. The below version uses 2 more bytes but is compatible with earlier OS's.

30 bytes

Prompt N
For(I,1,N
Disp NfPart((I+seq(J,J,1,N))/N
End

jq, 20 bytes

range(.*.)*(1+1/.)%.

Try it online!

output is flattened

(my first jq answer)

yuno (abandoned), 4 bytes

ップア@%

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).

yuno (abandoned), 2 bytes

メリョ

(Disclaimer - rotate was implemented after this challenge, and I'm not sure about map. However, neither of these nor the way empty-stack is treated were designed with this challenge in mind, it just turns out that the way I want my functions to work supports this challenge more nicely than Jelly)

(リョ is one byte)

By abusing the way I manage my stack, we can get this down to two bytes, which is pretty much the minimum possible unless you either have a latin square built-in for some reason, or a "rotate by each in range" built-in.

メ    For each element in the second-from-top-of-stack
 リョ  Rotate Left

If the stack's size is insufficient, popping will give the first command line argument instead. If that doesn't exist, it will input each time. Thus, you can make this rectangular by using STDIN. Otherwise, supply the number as a command line argument, and it'll use that value for the TOS and second-TOS.

Thus, for each x in 1, ..., N, it rotates N to the left by x, and rotating a number casts it to a range by default.

Vyxal r, 4 bytes

ƛ⁰ɾǔ

Try it Online!

ƛ      for each in [1, ..., N]
 ⁰     push N
  ɾ    pop N, push [1, ..., N]
   ǔ   rotate

-1 byte thanks to Aaron Miller

MMIX, 56 bytes (14 instrs)

Stores a flattened \$n\times n\$ Latin square into second argument. The pattern is:

5 4 3 2 1
1 5 4 3 2
2 1 5 4 3
3 2 1 5 4
4 3 2 1 5

Declaration:

void __mmixware latinsq(wyde n, wyde *storage);

(jxd -T)

00000000: c1020000 c1030000 c1040000 a7020100  Ḋ£¡¡Ḋ¤¡¡Ḋ¥¡¡ʂ£¢¡
00000010: e7010002 27030301 73ff0301 220202ff  ḃ¢¡£'¤¤¢s”¤¢"££”
00000020: 260404ff 27020201 62030300 62020200  &¥¥”'££¢b¤¤¡b££¡
00000030: 5b04fff7 f8000000                    [¥”ẋẏ¡¡¡
latinsq SET  $2,$0          // i = n
        SET  $3,$0          // j = n
        SET  $4,$0          // k = n
0H      STWU $2,$1,0
        INCL $1,2           // loop: *storage++ = i
        SUBU $3,$3,1
        ZSZ  $255,$3,1      // t = !--j
        ADDU $2,$2,$255     // i += t
        SUBU $4,$4,$255     // k -= t
        SUBU $2,$2,1        // i--
        CSZ  $3,$3,$0       // if(!j) j = n
        CSZ  $2,$2,$0       // if(!i) i = n
        PBNZ $4,0B          // iflikely(k) goto loop
        POP  0,0            // return

Ruby, 30 bytes

->n{w=*1..n;w.map{w=w.rotate}}

Try it online!

A little late, sorry.

Pyth, 5 bytes

.>LUQ

Test suite

Explanation:

.>LUQ  | Full program
.>LUQQ | with implicit variables
-------+----------------------------------
.>LUQ  | rotate range(input) right d times
  L  Q | for each d in range(input)

Python 3 translation:

Q = eval(input())

print(list(map(lambda d: list(range(Q)[-d:])+list(range(Q)[:-d]), range(Q))))

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!

Befunge-98 (PyFunge), 64 bytes

&::01-v_@
99+*77<^\-*86g99`+1\*:\-*86g99:::.%\+-*86g99/\-*86g99p

Try it online!

This is my first Befunge answer, so I'm sure it can golfed a lot more. I'm particularly frustrated about the repetition of 99g68*-, which is the best way I could store an extra counter, since I couldn't find an equivalent of Factor/Forth's 2dup or rot for Befunge, nor can I define a function.

Wolfram Language (Mathematica), 23 bytes

+##&~Array~{#,#}~Mod~#&       

or (as @Roman suggested)

Plus~Array~{#,#}~Mod~#&

Try it online!

-2 bytes thanks to @att

Java (JDK), 56 bytes

n->{for(int i=n*n;i-->0;)System.out.println((i/n+i)%n);}

Try it online!

Charcoal, 12 bytes

NθIEθ⁺…ιθ…⁰ι

Try it online! Link is to verbose version of code. Note that Charcoal's default output doesn't look much like an array. Other 12-byte variants are possible, e.g. modular arithmetic between range and row number or modular sum of row and column. Explanation: Simply concatenates the ranges from i to n and from 0 to i for every row.

Python 3 - 127 118 bytes

n=int(input())
m,o=[],[]
for i in range(n):
  m.append(i)
for i in range(n):
  o.append(m)
  m=m[-1:]+m[:-1]
print(o)

Try it online!

Simple answer - takes a contiguous subset of numbers, cycles it every row, and prints (aka, the usual formula).

Excel, 36 bytes

=MOD(SEQUENCE(A1)+SEQUENCE(1,A1),A1)

This seems to be similar to some of the solutions in other languages.

Perl 5 -a, 34 bytes

$,=$";say$_.."@F",1..$_-1for 1..$_

Try it online!

MATL, 3 bytes

5YL

Try it online!

          %implicit input n
5YL       % create circular matrix of size n

Equivalent to the following Octave/MATLAB code

Octave, 23 bytes

@(n)gallery('circul',n)

Try it online!

Alternately, this is equivalent to tsh's Octave answer.

MATL, 5 bytes

:&+G\

Try it online!

	% implicit input n
:	% range 1:n
&+	% add to itself transposed, with broadcast
G\	% push n and modulo n
	% implicit output

Zsh, 35 bytes

n=$1
repeat n\*n echo $[a++*~n/n%n]

Try it online!

Port of @dingledooper's golf to @Noodle9's C answer, but in reverse.

The \ is a work-around for a bug in zsh, and could be removed in a later version for -1.

Bash, 45 44 bytes

for((i=0;i<$1*$1;)){
echo $[(i/$1+i++)%$1]
}

Try it online!

-1 thanks to dingledooper

Prints flattened square, one element per line.

Arturo, 33 bytes

$[n][map 0..(n*n)-1'x[(x+x/n)%n]]

Try it on the Arturo Playground! Note: it seems that editing the code edits it for everyone, so don't do that.

Julia 1.0, 19 bytes

!n=((N=1:n).+N').%n

Try it online!

JavaScript (ES6), 46 bytes

n=>[...Array(n)].map((_,i,a)=>a.map(_=>i++%n))

Try it online!


JavaScript (ES6), 42 bytes

As pointed out by @tsh, returning a flatten array is shorter.

n=>[...Array(n*n)].map((_,i)=>(i/n+i)%n|0)

Try it online!

Ruby, 33 bytes

->n{(0..n*n-1).map{|x|(x+x/n)%n}}

Try it online!

A lambda proc returning a flat array of n*n elements.

J, 7 bytes

|i.+/i.

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 |.

APL (Dyalog Unicode), 6 bytes

⍳⌽,⍨⍴⍳

Try it online!

There's already a nice 4-byter in dzaima/APL 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

V (vim), 38 30 bytes

"aD@aO0<ESC>V{g<C-A>V}JqqYpdw$pq@a@qdk

Try it online!

Input as a single number.

Range creating script taken from Leo's Range, Reverse, Sum 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

Octave, 21 bytes

@(n,x=1:n)mod(x+x',n)

Try it online!

The same thing as many other answers...

-2 bytes by Giuseppe

PowerShell, 61 bytes

param($n)(0..($n*$n-1)|%{[math]::floor($_+$_/$n)%$n})-join" "

Try it online!

C (clang), 73 \$\cdots\$ 49 46 bytes

Saved 3 bytes thanks to dingledooper!!!

a;f(n){for(a=n*n;a;)printf("%d ",--a*~n/n%n);}

Try it online!

Inputs \$n\$ and prints the Latin Square as a flat array consisting of \$n^2\$ values.

Python 3, 43 41 bytes

Saved 2 byte thanks to caird coinheringaahing!!!

lambda n:[(a+a//n)%n for a in range(n*n)]

Try it online!

Port of my C answer (turns out to be the same as xnor's Python 2 answer).

Python 2, 37 bytes

Outputs a flattened \$ n \times n \$ latin square.

lambda n:((range(n)*-~n)[1:]*n)[::~n]

Try it online!

Retina, 22 bytes

.+
*
Y`\_`w
L$`.
$<'$`

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 $&$'.)

Japt -m, 3 bytes

Output as a 2D array.

WéU

Try it

Or without the -m flag:

Japt, 4 bytes

ÆZéX

Try it

Haskell, 32 bytes

f n=[[x..n]++[1..x-1]|x<-[1..n]]

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!

Outputs a flat list, zero-indexed, using the method from my Python answer. A slight adaptation is needing to make it work for [1..n*n] instead of [0..n*n-1].

Haskell, 37 35 bytes

Saved 2 bytes thanks to @Delfad0r Would have saved 5 bytes thanks to @AZTECCO (see xnor's answer)

f n=[mod(x+o)n|x<-[1..n],o<-[1..n]]

Try it online!

Python 2, 40 bytes

lambda n:[(k+k/n)%n for k in range(n*n)]

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.

Japt, 7 bytes

o £o éX

Try it

o   - [0..U)
£   - map by:
o éX    > rotate X times [0..U)

05AB1E, 4 bytes

LD._

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

R, 30 bytes

n=scan();outer(1:n,1:n,`+`)%%n

Try it online!

Jelly, 3 bytes

RṙⱮ

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.

Scala, 44 bytes

n=>1 to n flatMap(_=>1 to n)sliding n take n

Try it in Scastie!

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

Python 2, 43 bytes

lambda x,r=range:[r(i,x)+r(i)for i in r(x)]

Try it online!

APL (dzaima/APL), 4 bytes

⌽ᐵ⍨⍳
⌽ rotate
ᐵ each left, apply each left element to the entire right argument
⍨ apply to both arguments
⍳ range

Try it online!