The objective is to produce output of n squares (nxn) of random integers (0-9) with a moving * that rotates clockwise around the corners, starting from the top left. The squares should be side by side and separated by a single space.

If n = 0, the output should be empty.

Output for n=1:


Output for n=2:

*3 4*
14 07

Output for n=3:

*34 82* 291
453 224 924
145 158 57*

Output for n=4:

*153 135* 0154 0235
2352 5604 3602 2065
2245 6895 3561 7105
7225 5785 479* *662

Notice how the * rotates (around the corners of the square), from left to right, like this: top left, top right, bottom right, bottom left, top left, etc. (clockwise)

enter image description here

The shortest answer (measured in bytes) wins.

  • 6
    \$\begingroup\$ Please halp me understand this \$\endgroup\$ Sep 14, 2016 at 21:11
  • 1
    \$\begingroup\$ Voting to reopen. This is completely clear to me. Have made some minor edits. ("perfect square" sounded too much like the algebra term to me) \$\endgroup\$ Sep 14, 2016 at 21:46
  • 2
    \$\begingroup\$ How "random" do the random numbers need to be? It's probably also worth being explicit in your question about the fact that the numbers need to be exactly N digits long, counting the asterisks as digits. \$\endgroup\$ Sep 14, 2016 at 22:16
  • 2
    \$\begingroup\$ <Shrug> Perhaps I'm being slow, but its still unclear to me. Can you explain the placing of the *s in the n=4 example? Perhaps give some more examples? \$\endgroup\$ Sep 14, 2016 at 23:22
  • 2
    \$\begingroup\$ @DigitalTrauma I couldn't figure it out either until I realized that you're not printing one "clock," you're printing n clocks side-by-side (which was not at all clear from the question). So in the n = 4 example, you see four "clocks"—the first with the top row *153, the second with the top row *135, and so on. \$\endgroup\$
    – Jordan
    Sep 15, 2016 at 1:06

7 Answers 7


05AB1E, 50 49 bytes



Examples for input = 4.

First we create a string of input^3 random numbers between 0 and 9.




Then we split that into pieces each the size of the input.
That is further split into input pieces.


This gives us a matrix of numbers.

[['6799', '7625', '4942', '5893'], 
 ['3413', '1798', '4133', '9990'], 
 ['7524', '5812', '3054', '1201'], 
 ['0122', '8842', '6290', '3656']]

We then loop over the rows of the matrix, inserting asterisks in the right places.

v                          } # for each row in matrix 
 y`                          # flatten list to stack
   ¦'*ì                      # replace the first digit of the last number with "*"
       N4%©>ir}              # if row-nr % 4 == 0, move the number with "*" to the front
               ®iRr}         # if row-nr % 4 == 1, move the number with "*" to the front
                             # and reverse the number, moving "*" to the numbers right side
                    ®<iR}    # if row-nr % 4 == 2, reverse the number, moving "*" 
                             # to the numbers right side
                         )ˆ  # wrap row in a list and add to global array

Now we have the matrix with a "*" on each row, but we want an asterisk per column.

[['*893', '4942', '7625', '6799'], 
 ['099*', '4133', '1798', '3413'], 
 ['7524', '5812', '3054', '102*'], 
 ['0122', '8842', '6290', '*656']]

So we zip this list turning rows into columns and vice versa.

[['*893', '099*', '7524', '0122'], 
 ['4942', '4133', '5812', '8842'], 
 ['7625', '1798', '3054', '6290'], 
 ['6799', '3413', '102*', '*656']]

All that's left now is to format the output.


Joining the rows on spaces and the columns on newlines gives us the final result.

*893 099* 7524 0122
4942 4133 5812 8842
7625 1798 3054 6290
6799 3413 102* *656

Try it online!

Old 50 byte solution


APL (Dyalog Unicode), 47 bytes


Try it online!

Anonymous prefix lambda.

{} "dfn"; n is called

⎕D[] index the list of digits with the indices:

  3⍴⍵ cyclically reshape n into a list of length 3

  10⍴⍨ cyclically reshape the number 10 into an array of those dimensions (3×n×n)

  ? random index (1…10) for each

 yield that as argument to the upcoming function (separates indices from data)

'*'@() place asterisks at the following locations:

  1(⍵1)⍵(1⍵) the list [1,[n,1],n,[1,n]]

  2⍴¨ cyclically reshape each into a list of length 2: [[1,1],[n,1],[n,n],[1,n]]

  ⍵⍴ cyclically reshape that list into length n

  (),¨ prepend an element to each, taking elements from this list:

   ⍳⍵ indices 1…n

⎕FMT ForMaT as character matrix (joins layers with a line of spaces)



Java 10, 370 ... 243 242 bytes

n->{int j=n*n,k,m=1;var a=new String[j];var r="";for(m*=Math.pow(10,n-1);j-->0;a[j]=(k*=Math.random())+m+r)k=9*m;for(;++j<n;m=k<2?0:n*n-n,a[m+j]=a[m+j].replaceAll(k%3<1?"^.":".$","*"))k=j%4;for(j=0;j<n*n;r+=j%n<1?"\n":" ")r+=a[j++];return r;}

Returns the result-String with trailing newline.

-51 bytes thanks to @ceilingcat.

Try it online.


n->{                             // Method with integer parameter & String return-type
  int j=n*n,k,                   //  Index-integers
      m=1;                       //  Temp-integer
  var a=new String[j];           //  Create a String-matrix of size n by n
  var r="";                      //  Result-String, starting empty
  for(m*=Math.pow(10,n-1);       //  Start the temp-integer `m` at 10 to the power the
                                 //  input minus 1
      j-->0                      //  Loop `j` in the range [0,n²):
      ;                          //    After every iteration:
       a[j]=                     //     Set the j'th cell to:
         (k*=Math.random())      //      A random integer in the range [0,k)
         +m                      //      Add `m`
         +r;                     //      And then convert it to a String
    k=9*m;                       //   Set `k` to 9 multiplied by `m`, so the random
                                 //   integer will be in the range [0,9*m)
  for(;++j<n;                    //  Loop `j` in the range (-1,n):
      ;                          //    After every iteration:
       m=k<2?                    //     If `k` is 0 or 1:
             0                   //      Set `m` to 0 (first row)
            :                    //     Else:
             n*n-n,              //      Set `m` to n²-n instead (last row)
       a[m+j]=a[m+j].replaceAll( //     Then replace a digit in the (m*j)'th cell:
               k%3<1?            //      If `k` is 0 or 3 (first column):
                "^."             //       Replace its first digit
               :                 //      Else (last column instead):
                ".$",            //       Replace its last digit
               "*"))             //      And replace this digit with a "*"
    k=j%4;                       //   Set `k` to `j` modulo-4
  for(j=0;j<n*n;                 //  Loop `j` in the range [0,n²) again:
      ;                          //    After every iteration:
       r+=j%n<1?                 //     If `j` is divisible by `n`:
           "\n"                  //      Append a newline to the result
          :                      //     Else:
           " ";                  //      Append a space to the result instead
    r+=a[j++];                   //   Append the j'th value to the result
  return r;}                     //  Return the result-String

PHP ,181 Bytes

for($i=-1;++$i<$c=($n=$argv[1])**3;){echo!($i%$q=$n*$n)?"\n":((!$m=$i%$n)?" ":"");echo(!$m&!($b=$i%$q/$n&3)|$m==$n-1&$b==1)&$i<$q|($m==$n-1&$b==2|!$m&$b==3)&$i>$c-$q?"*":rand(0,9);}
  • \$\begingroup\$ Can you make a "Try it online!"-version of this? \$\endgroup\$
    – Forwarding
    Sep 16, 2016 at 3:50
  • \$\begingroup\$ @forwarding Test it \$\endgroup\$ Sep 16, 2016 at 8:49

Japt -R, 20 19 bytes

I could save a byte by either filling each square with the same random digit but

ƲÆAöìh* òU zXÃÕm¸

Try it

18 bytes

By using the same random digit to fill each square. Dunno if that'd fit the definition of "pseudo-random" for this challenge, though.

ƲçAö)h* òU zXÃÕm¸

Try it

ƲÆAöìh* òU zXÃÕm¸     :Implicit input of integer U
Æ                       :Map each X in the range [0,U)
 ²                      :  U squared
  Æ                     :  Map the range [0,U²)
   A                    :    10
    ö                   :    Random number in the range [0,A)
     Ã                  :  End map
      ¬                 :  Join
       h*               :  Replace 1st char with "*" (Handles the edge case of U=1 by instead inserting the "*" into the empty string)
          òU            :  Partitions of length U
             zX         :  Rotate 90 degrees clockwise X times
               Ã        :End map
                Õ       :Transpose
                 m      :Map
                  ¸     :  Join with spaces
                        :Implicit output, joined with newlines
ƲçAö)h* òU zXÃÕm¸     :Implicit input of integer U
Ʋ                     :As above
  ç                    :  Repeat to length U²
   Aö                  :   As above
     )                 :  End repeat
      h* òU zXÃÕm¸     :As above
                       :Implicit output, joined with newlines

05AB1E, 27 bytes


Try it online or verify multiple dimensions.


Step 1: Create a matrix of the input by input amount of 1s, with the top-left value replaced with a "*":

и          # Repeat the (implicit) input the (implicit) input amount of times as list
           # (e.g. 5 → [5,5,5,5,5])
 L         # Convert each inner integer to a list in the range [1,input]
  d        # Convert each inner integer to a 1 (with a >=0 check)
   ć       # Extract head; pop and push remainder-list and first item separated
    '*0ǝ  '# Replace the first item in this list with a "*"
        š  # Prepend this list back to the matrix

Try just step 1 online.

Step 2: Rotate it the input-1 amount of times clockwise and keep each intermediate matrix in a list:

IG         # Loop the input-1 amount of times:
  D        #  Duplicate the current matrix
   øí      #  Rotate it once clockwise:
   ø       #   Zip/transpose; swapping rows/columns
    í      #   Reverse each inner row
 })        # After the loop: wrap all matrices on the stack into a list

Try just the first 2 steps online.

Step 3: Format these lists of loose matrices to the output-format by putting them next to each other with space delimiter:

ø          # Zip/transpose; swapping rows/columns
 J         # Join each inner-most list together to a string
  »        # Join each inner lists by spaces, and then these lines by newlines

Try just the first 3 steps online.

Step 4: Replace every 1 with a random digit, and output the final result:

ε          # Map over each character in the multi-line string:
 D         #  Duplicate the current character
  i        #  Pop, and if it's a 1:
   žh      #   Push constant "0123456789"
     Ω     #   Pop and push a random digit from this
]          # Close both the if-statement and map
 J         # Join this list of characters back to a string again

Husk, 19 17 bytes*

(* caveat: validity (or not) depends on the interpretation of 'pseudo-random integers'...)


Try it online!

Digits within each square are pseudo-random (there is a hidden pattern), although the same pseudo-random digits are re-used for each square.

               İπ       # the digits of pi
                        # (a source of pseudo-random digits)
             ṁs         # mapped to a character string   
          :'*           # and prepended with '*'
         C              # then cut into strings of input size
       ↑¹               # and taking just the input number of strings;
   ¡o                   # now, generate an infinite list 
                        # by repeatedly applying:
     T↔                 # reverse-and-transpose
                        # (this rotates the matrix);
 ↑¹                     # finally, take the first input matrices
T                       # and transpose to display in the correct format.

Husk, 24 bytes*


Try it online!

Doesn't re-use the same pseudo-random digits for each square (but there's still the same hidden pattern...).

  • \$\begingroup\$ Nice answer, but the definition of random is 'without pattern/unpredictable', which the digit of pi aren't. I'm not sure what the rules are for pseudo-random, but I seriously doubt the first \$x\$ digits of pi are considered pseudo-random. If you'd take a random section within pi's digits it's a completely different story, but right now all your squares use the same 314... digits. With an input of \$\geq5\$ your first and fifth squares are exactly the same. \$\endgroup\$ Sep 14 at 15:08
  • \$\begingroup\$ @KevinCruijssen - I agree that the digits of pi are not 'unpredictable', although I think that they are 'without pattern'. They do at least satisfy some statistical properties expected of a random stream of digits, which I've previously used to justify using them as a 'pseudo-random' sequence (see: codegolf.stackexchange.com/a/223136/95126, for instance). Unfortunately, Husk has no randomizing capability, so this is the only work-around that I can think of here... \$\endgroup\$ Sep 14 at 15:32
  • \$\begingroup\$ @KevinCruijssen - Re: the 1st & 5th squares being exactly the same - yes, I know, this is why I indicated that the digits are 'pseudo-random' per-square, but re-used for each square. It isn't clear to me from the question wording ("n squares ... of random integers") that this is disallowed. \$\endgroup\$ Sep 14 at 15:35
  • \$\begingroup\$ I'd agree with @KevinCruijssen on this one, I'm afraid. Even taking the loosest possible definition of "pseudo-random" shouldn't result in the output being constant, something should (be able to change) on each run of the programme. \$\endgroup\$
    – Shaggy
    Sep 15 at 9:16
  • \$\begingroup\$ @Shaggy - I suppose this is why there's usually such a strong encouragement to define 'random' in challenges... I'm interpreting 'pseudo-random integers (0-9)' here as 'a series of successive digits that do not follow any pattern', rather than 'digits that can change on each run of the program'. I'd argue that this is similar to the situation of a PRNG that always starts with the same seed on each program run. However, as this seems to be somewhat contentious, I'll mark my answer with a caveat... \$\endgroup\$ Sep 15 at 9:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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