27
\$\begingroup\$

An \$n\times n\$ 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

This is , 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]]
\$\endgroup\$
3
  • \$\begingroup\$ Related. Related. Brownie points for beating or matching my 12 byte Jelly answer \$\endgroup\$ Apr 15, 2021 at 20:27
  • \$\begingroup\$ It there an upper limit on n the code can assume? \$\endgroup\$
    – cnamejj
    Apr 16, 2021 at 1:01
  • 3
    \$\begingroup\$ @cnamejj Yeah, you'll never have to handle an integer greater than the square root of the maximum integer in your languages (basically, don't worry about big n so long as your algorithm is sound) \$\endgroup\$ Apr 16, 2021 at 1:10

46 Answers 46

1
2
3
+100
\$\begingroup\$

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

\$\endgroup\$
4
  • \$\begingroup\$ You can rotate ranges now \$\endgroup\$
    – lyxal
    May 9, 2021 at 11:25
  • \$\begingroup\$ @lyxal poggers. \$\endgroup\$
    – hyper-neutrino
    May 9, 2021 at 14:08
  • \$\begingroup\$ 4 bytes \$\endgroup\$ May 12, 2021 at 5:28
  • \$\begingroup\$ @AaronMiller oh, nice, i thought i tried that, lol \$\endgroup\$
    – hyper-neutrino
    May 12, 2021 at 5:34
3
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
1
2
\$\begingroup\$

Excel, 36 bytes

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

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

\$\endgroup\$
2
\$\begingroup\$

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

\$\endgroup\$
12
  • 1
    \$\begingroup\$ You can easily golf ~30 bytes off just by removing all the spaces around the =, + and += commands \$\endgroup\$ Apr 15, 2021 at 20:37
  • \$\begingroup\$ Fails for inputs >223. \$\endgroup\$
    – Makonede
    Apr 15, 2021 at 21:10
  • \$\begingroup\$ This is 115 bytes, but you can make it 104 bytes \$\endgroup\$ Apr 15, 2021 at 21:36
  • \$\begingroup\$ @Makonede Let me see what I can do about that. \$\endgroup\$ Apr 16, 2021 at 8:29
  • \$\begingroup\$ @Makonede Fixed now. \$\endgroup\$ Apr 16, 2021 at 8:31
2
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

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))))
\$\endgroup\$
2
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

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

\$\endgroup\$
2
  • \$\begingroup\$ You can remove the f=, and this is a duplicate answer in Python 2 \$\endgroup\$ Apr 16, 2021 at 0:06
  • \$\begingroup\$ @cairdcoinheringaahing Duh, so used to writing recursively forgot! T_T Not a duplicate since I didn't copy it and the variable names are different! :P \$\endgroup\$
    – Noodle9
    Apr 16, 2021 at 0:11
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

Ruby, 30 bytes

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

Try it online!

A little late, sorry.

\$\endgroup\$
1
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

Risky, 21 bytes

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

Try it online!

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

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.

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

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
\$\endgroup\$
1
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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