Output a Sudoku board

25

2

Today's challenge is simple: Without taking any input, output any valid sudoku board.

In case you are unfamiliar with sudoku, Wikipedia describes what a valid board should look like:

The objective is to fill a 9×9 grid with digits so that each column, each row, and each of the nine 3×3 subgrids that compose the grid (also called "boxes", "blocks", or "regions") contains all of the digits from 1 to 9.

Now here's the thing... There are 6,670,903,752,021,072,936,960 different valid sudoku boards. Some of them may be very difficult to compress and output in fewer bytes. Others of them may be easier. Part of this challenge is to figure out which boards will be most compressible and could be outputted in the fewest bytes.

Your submission does not necessarily have to output the same board every time. But if multiple outputs are possible, you'll have to prove that every possible output is a valid board.

You can use this script (thanks to Magic Octopus Urn) or any of these answers to verify if a particular grid is a valid solution. It will output a [1] for a valid board, and anything else for an invalid board.

I'm not too picky about what format you output your answer in, as long as it's clearly 2-dimensional. For example, you could output a 9x9 matrix, nine 3x3 matrices, a string, an array of strings, an array of 9-digit integers, or nine 9-digit numbers with a separator. Outputting 81 digits in 1 dimension would not be permitted. If you would like to know about a particular output format, feel free to ask me in the comments.

As usual, this is , so write the shortest answer you can come up with in the language(s) of your choosing!

James

Posted 2018-09-19T18:58:17.323

Reputation: 54 537

Can we output three 3x9 matrices? Each row of each submatrix representing a row in the sudoku board. Like this

– dylnan – 2018-09-19T20:23:07.693

2Related but not a dup. Also, if you're allowing flexible output I'm not sure that [tag:kolmogorov-complexity] applies, since that is normally for fixed outputs like exact ascii art. – BradC – 2018-09-19T20:33:20.047

Answers

13

Pyth, 22 14 12 10 bytes

.<LS9%D3 9

Saved 2 bytes thanks to Mr. Xcoder.

Try it here

.<LS9%D3 9
     %D3 9     Order the range [0, ..., 8] mod 3.
  >            For each, ...
.< S9          ... Rotate the list [1, ..., 9] that many times.

user48543

Posted 2018-09-19T18:58:17.323

Reputation:

11: m.<S9d%D3 9. – Mr. Xcoder – 2018-09-19T19:35:03.207

Cross that out, 10: .<LS9%D3 9. – Mr. Xcoder – 2018-09-19T19:36:17.143

Might wanna update the link (tio)

– bryc – 2019-11-26T18:49:56.100

12

Python 2, 47 bytes

l=range(1,10)
for x in l:print(l*9)[x*8/3:][:9]

Try it online!

xnor

Posted 2018-09-19T18:58:17.323

Reputation: 115 687

8

T-SQL, 96 89 bytes

Found one shorter than the trivial output!

SELECT SUBSTRING('12345678912345678',0+value,9)FROM STRING_SPLIT('1,4,7,2,5,8,3,6,9',',')

Extracts 9-character strings starting at different points, as defined by the in-memory table created by STRING_SPLIT (which is supported on SQL 2016 and later). The 0+value was the shortest way I could do an implicit cast to integer.

Original trivial output (96 bytes):

PRINT'726493815
315728946
489651237
852147693
673985124
941362758
194836572
567214389
238579461'

BradC

Posted 2018-09-19T18:58:17.323

Reputation: 6 099

7

Jelly, 7 bytes

9Rṙ%3$Þ

Try it online!

And a little bit of this...
-1 thanks to Jonathan Allan('s thinking?)

Erik the Outgolfer

Posted 2018-09-19T18:58:17.323

Reputation: 38 134

6

Python 2, 53 bytes

r=range(9)
for i in r:print[1+(j*10/3+i)%9for j in r]

Try it online!


Alternatives:

Python 2, 53 bytes

i=0;exec"print[1+(i/3+j)%9for j in range(9)];i-=8;"*9

Try it online!

Python 2, 54 bytes

for i in range(81):print(i/9*10/3+i)%9+1,'\n'*(i%9>7),
i=0;exec"print[1+(i/3+j)%9for j in range(9)];i+=10;"*9
r=range(9);print[[1+(i*10/3+j)%9for j in r]for i in r]

TFeld

Posted 2018-09-19T18:58:17.323

Reputation: 19 246

5

Python 3, 58 55 bytes

l=*range(10),
for i in b"	":print(l[i:]+l[1:i])

Try it online!

  • -3 bytes thanks to Jo King,

The elements of the byte string end up giving the numbers [1, 4, 7, 2, 5, 8, 3, 6, 9] which are used to permute the rotations of [0..9]. The 0 is removed in l[1:i] and there is no need for a null byte which takes two characaters (\0) to represent in a bytes object.

55 bytes

_,*l=range(10)
for i in b"	":print(l[i:]+l[:i])

dylnan

Posted 2018-09-19T18:58:17.323

Reputation: 4 993

55 bytes – Jo King – 2018-09-19T23:38:59.923

@JoKing Clever, thanks – dylnan – 2018-09-19T23:41:50.083

4

Jelly, 9 8 bytes

9Rṙ`s3ZẎ

Try it online!

9Rṙ`s3ZẎ
9R         Range(9) -> [1,2,3,4,5,6,7,8,9]
   `       Use the same argument twice for the dyad:
  ṙ        Rotate [1..9] each of [1..9] times.
           This gives all cyclic rotations of the list [1..9]
    s3     Split into three lists.
      Z    Zip. This puts the first row of each list of three in it's own list, 
           as well as the the second and third.
       Ẏ   Dump into a single list of nine arrays.

dylnan

Posted 2018-09-19T18:58:17.323

Reputation: 4 993

4

Batch, 84 bytes

@set s=123456789
@for %%a in (0 3 6 1 4 7 2 5 8)do @call echo %%s:~%%a%%%%s:~,%%a%%

Uses @Mnemonic's output. call is used to interpolate the variable into the slicing operation (normally it only accepts numeric constants).

Neil

Posted 2018-09-19T18:58:17.323

Reputation: 95 035

4

Perl 6, 40 32 27 bytes

-5 bytes thanks to nwellnhof

{[^9+1].rotate($+=3.3)xx 9}

Try it online!

Anonymous code block that returns a 9x9 matrix. Maps each row to a different rotation of the range 1 to 9.

Jo King

Posted 2018-09-19T18:58:17.323

Reputation: 38 234

4

JavaScript (Node.js), 47 bytes

Output as an array of the rows.

_=>[...w="147258369"].map(x=>(w+w).substr(x,9))

Try it online!

Generates this:

472583691
583691472
691472583
725836914
836914725
914725836
258369147
369147258
147258369

Shieru Asakoto

Posted 2018-09-19T18:58:17.323

Reputation: 4 445

4

05AB1E, 14 12 bytes

8ÝΣ3%}ε9Ls._

-2 bytes by creating a port of @Mnemonic's Pyth answer.

Try it online. (Footer is added to pretty-print it. Actual result is a 9x9 matrix; feel free to remove the footer to see.)

Explanation:

8Ý              # List in the range [0, 8]
  Σ  }          # Sort the integers `i` by
   3%           #  `i` modulo-3
      ε         # Map each value to:
       9L       #  List in the range [1, 9]
         s._    #  Rotated towards the left the value amount of times

Original 14 bytes solution:

9Lε9LN3*N3÷+._

Try it online. (Footer is added to pretty-print it. Actual result is a 9x9 matrix; feel free to remove the footer to see.)

Explanation:

9L                # Create a list of size 9
  ε               # Change each value to:
   9L             #  Create a list in the range [1, 9]
     N3*N3÷+      #  Calculate N*3 + N//3 (where N is the 0-indexed index,
                  #                        and // is integer-division)
            ._    #  Rotate that many times towards the left

Both answers result in the Sudoku:

123456789
456789123
789123456
234567891
567891234
891234567
345678912
678912345
912345678

Kevin Cruijssen

Posted 2018-09-19T18:58:17.323

Reputation: 67 575

4

J, 18 bytes

>:(,&|:|."{,)i.3 3

Try it online!

Output

1 2 3 4 5 6 7 8 9
4 5 6 7 8 9 1 2 3
7 8 9 1 2 3 4 5 6
2 3 4 5 6 7 8 9 1
5 6 7 8 9 1 2 3 4
8 9 1 2 3 4 5 6 7
3 4 5 6 7 8 9 1 2
6 7 8 9 1 2 3 4 5
9 1 2 3 4 5 6 7 8

How it works

>:(,&|:|."{,)i.3 3
             i.3 3  The 2D array X = [0 1 2;3 4 5;6 7 8]
   ,&|:|."{,        3-verb train:
   ,&|:               Transpose and flatten X to get Y = [0 3 6 1 4 7 2 5 8]
           ,          Flatten X to get Z = [0 1 2 3 4 5 6 7 8]
       |."{           Get 2D array whose rows are Z rotated Y times
>:                  Increment

Fancy version, 23 bytes

|.&(>:i.3 3)&.>|:{;~i.3

Try it online!

Output:

┌─────┬─────┬─────┐
│1 2 3│4 5 6│7 8 9│
│4 5 6│7 8 9│1 2 3│
│7 8 9│1 2 3│4 5 6│
├─────┼─────┼─────┤
│2 3 1│5 6 4│8 9 7│
│5 6 4│8 9 7│2 3 1│
│8 9 7│2 3 1│5 6 4│
├─────┼─────┼─────┤
│3 1 2│6 4 5│9 7 8│
│6 4 5│9 7 8│3 1 2│
│9 7 8│3 1 2│6 4 5│
└─────┴─────┴─────┘

How it works

|.&(>:i.3 3)&.>|:{;~i.3
                    i.3  Array [0 1 2]
                 {;~     Get 2D array of boxed pairs (0 0) to (2 2)
               |:        Transpose
|.&(>:i.3 3)&.>          Change each pair to a Sudoku box:
            &.>            Unbox
    >:i.3 3                2D array X = [1 2 3;4 5 6;7 8 9]
|.&                        Rotate this 2D array over both axes
                             e.g. 1 2|.X gives [6 4 5;9 7 8;3 1 2]
            &.>            Box again so the result looks like the above

Bubbler

Posted 2018-09-19T18:58:17.323

Reputation: 16 616

4

Octave & Matlab,50 48 29 bytes

mod((1:9)+['furRaghAt']',9)+1

Try it online!

-2 thanks to Johnathon frech

-14 thanks to Sanchises Broadcast addition suggestion, who also pointed out the non-compatibility.

-5 by noticing that the vector can be written in matlab with a char string and transposition.

Was intuitive, now not so. Uses broadcast summing to spread 1:9 over 9 rows, spread by values determined by the char string.

Sudoku board produced:

 5 6 7 8 9 1 2 3 4
 2 3 4 5 6 7 8 9 1
 8 9 1 2 3 4 5 6 7
 3 4 5 6 7 8 9 1 2
 9 1 2 3 4 5 6 7 8
 6 7 8 9 1 2 3 4 5
 7 8 9 1 2 3 4 5 6
 4 5 6 7 8 9 1 2 3
 1 2 3 4 5 6 7 8 9

Poptimist

Posted 2018-09-19T18:58:17.323

Reputation: 41

Hello and welcome to PPCG; nice first post. – Jonathan Frech – 2018-09-24T14:19:13.423

48 bytes. – Jonathan Frech – 2018-09-24T14:20:06.473

Of course, s could be defined in the matrix itself. I must have miscounted the bytes as well. – Poptimist – 2018-09-24T14:43:39.800

This is now Octave, no longer compatible with MATLAB. If you like, you can use the little chain icon at the top of Jonathan's link to copy paste the default PPCG formatting. – Sanchises – 2018-09-25T06:36:09.067

If you like, you can get this down to 34 bytes with broadcast addition: Try it online!

– Sanchises – 2018-09-25T06:39:34.957

Thanks for pointing out the issue Sanchises, now fixed with your suggestion and improved on top. – Poptimist – 2018-09-26T15:14:45.737

Save one more: (1:9)+'furRaghAt'.'. – Stewie Griffin – 2018-10-01T16:17:45.060

3

Haskell, 41 bytes

[[x..9]++[1..x-1]|x<-[1,4,7,2,5,8,3,6,9]]

Try it online!

Curtis Bechtel

Posted 2018-09-19T18:58:17.323

Reputation: 601

This is not valid. Each square contains multiple of the same number. You could do something like this (43 bytes) instead

– Jo King – 2018-09-19T23:33:58.700

Thanks! I took your suggestion – Curtis Bechtel – 2018-09-19T23:51:09.697

@RushabhMehta I did. It was 43 bytes but I removed the s= since it isn't necessary – Curtis Bechtel – 2018-09-22T16:54:59.887

3

MathGolf, 16 11 bytes

9{9╒♂ï*3/Ä╫

Try it online!

Saved 5 bytes thanks to JoKing

maxb

Posted 2018-09-19T18:58:17.323

Reputation: 5 754

11 bytes – Jo King – 2018-09-26T15:32:38.367

3

Java 10, 82 75 bytes

v->{for(int i=81;i-->0;)System.out.print((i/9*10/3+i)%9+1+(i%9<1?" ":""));}

-7 bytes by creating a port of one of @TFeld's Python 2 answers.

Try it online.

Explanation:

v->{                    // Method with empty unused parameter and no return-type
  for(int i=81;i-->0;)  //  Loop `i` in the range (81, 0]
    System.out.print(   //   Print:
     (i/9               //    (`i` integer-divided by 9,
         *10            //     then multiplied by 10,
         /3             //     then integer-divided by 3,
           +i)          //     and then we add `i`)
             %9         //    Then take modulo-9 on the sum of that above
               +1       //    And finally add 1
    +(i%9<1?            //    Then if `i` modulo-9 is 0:
            " "         //     Append a space delimiter
           :            //    Else:
            ""));}      //     Append nothing more

Outputs the following sudoku (space delimited instead of newlines like below):

876543219
543219876
219876543
765432198
432198765
198765432
654321987
321987654
987654321

Kevin Cruijssen

Posted 2018-09-19T18:58:17.323

Reputation: 67 575

2

Python - 81 bytes

l=list(range(1,10))
for i in range(1,10):print(l);l=l[3+(i%3==0):]+l[:3+(i%3==0)]

Try it Online

I like having 81 bytes, but after some optimizing :(

Python 2 - 75 68 59 58 bytes

-7 bytes thanks to @DLosc

-9 bytes thanks to @Mnemonic

-1 byte thanks to @JoKing

l=range(1,10)
for i in l:print l;j=i%3<1;l=l[3+j:]+l[:3+j]

Try it Online

Don Thousand

Posted 2018-09-19T18:58:17.323

Reputation: 1 781

281 bytes Perfect score! :D – James – 2018-09-19T19:53:06.957

@DJMcMayhem I was considering making it shorter by doing r=range(1,10) but I couldn't ruin the beauty – Don Thousand – 2018-09-19T19:53:39.797

68 bytes ;) – DLosc – 2018-09-19T19:58:46.180

@DLosc Ooh clever reuse of l – Don Thousand – 2018-09-19T19:59:35.830

If you don't mind Python 2, you can take the parens out of the print and remove the list packing. – None – 2018-09-19T20:02:13.230

How exactly do you remove the list packing? – Don Thousand – 2018-09-19T20:04:00.563

range already returns a list in Python 2. 59 bytes – None – 2018-09-19T20:04:46.437

@Mnemonic Oh right, I forgot, xrange is the generator in Python 2 – Don Thousand – 2018-09-19T20:13:25.647

2

Ruby, 34 bytes

(a=*1..9).map{|x|p a.rotate x*3.3}

Try it online!

G B

Posted 2018-09-19T18:58:17.323

Reputation: 11 099

2

Huge Thanks to @Shaggy!

JavaScript (Node.js), 61 bytes

t=>[...s='123456789'].map(e=>s.slice(t=e*3.3%9)+s.slice(0,t))

Try it online!

user58120

Posted 2018-09-19T18:58:17.323

Reputation:

1

A quick bit of golfing gets this down to 63 bytes.

– Shaggy – 2018-09-21T10:41:25.843

2

Sorry, 61 bytes; missed a stupidly obvious golf!

– Shaggy – 2018-09-21T13:21:50.517

2

R, 54 bytes

x=1:9;for(y in(x*3)%%10)print(c(x[-(1:y)],x[(1:y)]))

Output:

[1] 4 5 6 7 8 9 1 2 3
[1] 7 8 9 1 2 3 4 5 6
[1] 1 2 3 4 5 6 7 8 9
[1] 3 4 5 6 7 8 9 1 2
[1] 6 7 8 9 1 2 3 4 5
[1] 9 1 2 3 4 5 6 7 8
[1] 2 3 4 5 6 7 8 9 1
[1] 5 6 7 8 9 1 2 3 4
[1] 8 9 1 2 3 4 5 6 7

Try it online!

DobromirM

Posted 2018-09-19T18:58:17.323

Reputation: 313

1

Canvas, 13 11 bytes

◂j3[«3[T3[«

Try it here!

dzaima

Posted 2018-09-19T18:58:17.323

Reputation: 19 048

1

Japt, 11 10 bytes

9õ ñu3
£éX

Try it or verify the output


Explanation

9õ         :Range [1,9]
   ñ       :Sort by
    u3     :  Mod 3 of each
\n         :Assign to variable U
£          :Map each X
 éX        :  U rotated right by X

Shaggy

Posted 2018-09-19T18:58:17.323

Reputation: 24 623

1

C (clang), 65 bytes

f(i){for(i=0;i<81;)printf("%d%c",(i/9*10/3+i)%9+1,i++%9>7?10:9);}

The function is now able to be reused

Try it online!

Logern

Posted 2018-09-19T18:58:17.323

Reputation: 845

Instead of printing a NUL byte to seperate your digits, you could use a tab character at the same byte count. – Jonathan Frech – 2018-09-24T14:29:03.720

"Your submission does not necessarily have to output the same board every time. But if multiple outputs are possible, you'll have to prove that every possible output is a valid board." It does not say that multiple outputs are needed. @ceilingcat – Logern – 2018-09-24T17:46:57.453

1

@Logern The rule in question is that function submissions have to be reusable. It’s fine if it f(); f() outputs the same board twice, but not if the second call doesn’t work at all.

– Anders Kaseorg – 2018-09-25T04:40:53.003

63 bytes – Jo King – 2018-09-25T11:53:27.963

61 bytes, incorporating suggestions from @JoKing f(i){for(i=81;i--;)printf("%d%c",(i/9*10/3+i)%9+1,i%9?9:10);} – ceilingcat – 2018-10-02T19:45:22.730

1

K (ngn/k), 16 bytes

1+9!(<9#!3)+\:!9

Try it online!

First answer in ngn/k, done with a big help from the man himself, @ngn.

How:

1+9!(<9#!3)+\:!9 // Anonymous fn
              !9 // Range [0..8]
    (     )+\:   // Sum (+) that range with each left (\:) argument
        !3       // Range [0..2]
      9#         // Reshaped (#) to 9 elements: (0 1 2 0 1 2 0 1 2)
     <           // Grade up
  9!             // Modulo 9
1+               // plus 1

J. Sallé

Posted 2018-09-19T18:58:17.323

Reputation: 3 233

0

Charcoal, 14 bytes

E⁹⭆⁹⊕﹪⁺÷×χι³λ⁹

Try it online! Link is to verbose version of code. Uses @Mnemonic's output. Explanation:

E⁹              Map over 9 rows
  ⭆⁹            Map over 9 columns and join
          ι     Current row
         χ      Predefined variable 10
        ×       Multiply
       ÷   ³    Integer divide by 3
            λ   Current column
      ⁺         Add
     ﹪       ⁹  Modulo 9
    ⊕           Increment
                Implicitly print each row on its own line

Neil

Posted 2018-09-19T18:58:17.323

Reputation: 95 035