title: Print a word clock

text:
# Question
Title: Print a word clock
Since I saw the first one a few years ago, I always was subjugated by this kind of word clock where the time is actually spelled out by words being lit up or not into a meaningful sentence.

The text displayed on that clock is the following.

```
IT IS HALF TEN
QUARTER TWENTY
FIVE MINUTES TO
PAST TWO THREE
ONE FOUR FIVE
SIX SEVEN EIGHT
NINE TEN ELEVEN
TWELVE O'CLOCK

```

Your task is to write such a working clock. Words are lit up if and only if they're relevant to printing the current time. Otherwise, they're lit down. Words are "lit up" by being printed and are "lit down" by being replaced by a number of spaces being the length of the word.

Example: if the current time is 17:23, the printed text must be exactly the following:

```
IT IS
        TWENTY
FIVE MINUTES
PAST
         FIVE

```

## Rules

1. The time printed is the 12h variant, but without AM/PM.
2. The rounding is done on the base of minutes only (seconds are totally irrelevant). The rounding is done to the closest multiple of 5. So, for example, even though 17:52:38 really is closest to 17:55, but since the seconds are irrelevant, 17:52 is actually rounded down to 17:50, and the text printed is "IT IS TEN MINUTES TO SIX" (with relevant spacing). So if `XX` is a multiple of five, `XX` will be used from HH:(XX-2):00 until HH:(XX+2):59. The word `MINUTES` must appear if `FIVE`, `TEN` or `TWENTY` are lit up in the minutes section (before "TO" or "PAST").
3. All irrelevant words are replaced by as many spaces as needed to keep the text where it is located in the template above. Trailing spaces may be trimmed. Spaces relevant to keeping the text at the expected position must be kept.
4. Trailing lines may be trimmed as well. Relevant empty lines are still required to appear. Example:

```
IT IS      TEN

     MINUTES
PAST TWO

```
5. Do not light up `TEN` on the first line or `FIVE` on the third line when these values refer to the hours.
6. You may accept an input. If you accept an input, the input will be the time to print in any valid format you want (string, list of integers, native time type your language support, ...), but no parameters are allowed if they're not related to the time to print. If you support no input, then you must use the current time. If you support both, that's better but there's no bonus ;)
7. Your code may be a program, a function, a lambda but not snippet.
8. If your language supports printing in any way, **it must print** the result (in a file, on the standard output, I don't mind). If your language doesn't support printing in any way, it is allowed to simply "return" the expected text. The result may be either all uppercase or all lowercase, not a mix of both.
9. Standard loopholes apply.
10. This is code-golf so the shortest code wins!
11. In the measure of possible, please provide a link to an online interpreter of your language.

## Test cases

```
Input:  <no input> (the current local time is 19:20)
Output:
IT IS
        TWENTY
     MINUTES
PAST

    SEVEN

```

---

```
Input: 13:15
Output: (empty line is being printed)
IT IS
QUARTER

PAST
ONE

```

---

```
Input: 13:58
Output: (rounding)
IT IS

     TWO

       O'CLOCK

```

---

```
Input: 14:30
Output: (half is always a edge-case)
IT IS HALF

PAST TWO

```

---

```
Input: 15:35
Output: (light up "TO")
IT IS
        TWENTY
FIVE MINUTES TO

    FOUR

```

---

```
Input: 10:00
Output: (do not use the TEN or FIVE on the first line when referring to the hours)
IT IS

    TEN
      O'CLOCK

```

---

```
Input: 12:00
Output: (O'CLOCK and a lot of empty lines)
IT IS

TWELVE O'CLOCK

```

# Answer
# PHP, ~~387~~ ~~384~~ ~~353~~ ~~352~~ ~~342~~ ~~323~~ ~~310~~ ~~306~~ ~~298~~ ~~293~~ 291 bytes

**Thanks @Christoph** for golfing along with his **excellent** findings!
At least 45 bytes are on his account; 16 or more inspired by him.

A Marvel Team Up!

```
IT IS <?foreach([HALF,TEN,QUARTER,TWENTY,FIVE,MINUTES,TO,PAST,TWO,THREE,ONE,FOUR,FIVE,SIX,SEVEN,EIGHT,NINE,TEN,ELEVEN,TWELVE,"O'CLOCK"]as$w)echo strstr([w,ghj,dhj,ej,fhj,fghj,cj,fghi,fhi,ei,dhi,ghi][$m=date(i)/5+.5].mklnopqrstuvm[date(h)-($m<7)],99+$i)?$w:$w^$w^"       ","
  "[$i++%3^$i<3];

```

loops through the data and checks if the current index is in a generated string that contains the indexes of the words to light up (mapped to letters); appends linebreak or space depending on the index.

May yield notices if you dont´t use the default value for `error_reporting` (22519).

Test it online.

**breakdown**

```
IT IS <?
foreach([HALF,TEN,QUARTER,TWENTY,FIVE,MINUTES,TO,PAST,  // loop through words
TWO,THREE,ONE,FOUR,FIVE,SIX,SEVEN,EIGHT,NINE,TEN,ELEVEN,TWELVE,"O'CLOCK"]as$w)
    echo strstr(                    // search word index in ...
        [w,ghj,dhj,ej,fhj,fghj,cj,fghi,fhi,ei,dhi,ghi][$m=date(i)/5+.5] // minutes & co
        .mklnopqrstuvm[date(h)-($m<7)]                          // hours (-1 if minutes<33)
    ,99+$i                          // (map 0..20 to c..w)
    )?$w:$w^$w^"       ",           // if found, print string, else print spaces
    "\n  "[$i++%3^$i<3];            // if $i in [3,5,8,...], print newline, else space

```

**Golfs**:

* `$x/5+.5|0` is two bytes shorter than `round($x/5)`.
* Two calls of `date(h)` are one byte shorter than assigning the `date` result to a variable.
* Using a single assigment golfed away the variable that the light-up indexes were stored in.
* A string for the light-up indexes instead of an array saved **around 30 bytes**.
* `$w<A` is three bytes shorter than `$w=="\n"` \- make sure that no space is after a delimiter!
* `abs` saved 8 bytes on the minutes word.
* Thanks @Christoph: Moving from numbers to letters for the map rendered the separators obsolete and allowed one more string instead of array; saved **23+8 bytes**.
Using underscore as the first index allowed to include it into the "it is" alternatives; and it rendered the quotation for the hours obsolete.
* Duplicating the `1` value in the hours map rendered the modulo obsolete and that with additional golfing saved 10 bytes. Inspired by @Christoph.
* Calculating the linebreaks and spaces instead of hardcoding them shaved off **19 bytes**.
* Bit logic on strings saves 7 bytes: `str_pad("",strlen($w))` -\> `$w^$w^" "`. (Christoph)
* If `strtr`´s second parameter is no string, it will be interpreted as an ascii code. saves 5 bytes.
> 15 votes

# Answer
# TI-Basic, 335 334 bytes

Pretty much perfect, since the TI-84 calcs have 8x16 letter displays, and this is 8x15. Date is taken as input in order to support calcs earlier than TI-84, which do not have internal clocks. With no arguments, `Input` gets input by default into `X` and `Y`, similar to `Prompt X,Y`. So make `X` be hours (anything `>=0` will work correctly) and have `Y` be minutes.

```
Input
ClrHome
int(Y/5-5.6
Output(1,1,"IT IS
If Ans=~6
Output(8,8,"O'CLOCK
If 2=abs(3-abs(Ans
Output(3,1,"FIVE
If 4=abs(Ans
Output(1,12,"TEN
If 3=abs(Ans
Output(2,1,"QUARTER
If 2=abs(Ans
Output(2,8,"TWENTY
If sum(abs(Ans)={1,2,4,5
Output(3,5,"MINUTES
If not(Ans
Output(1,7,"HALF
If Ans<1 and Ans+6
Output(4,1,"PAST
If Ans>0
Output(3,14,"TO
12fPart(12(^~1)(X+(Y>32->A
If not(Ans
12->A
{21,6,10,25,30,41,45,51,61,66,70,81
.05Ans(A
Output(int(4+Ans),20fPart(Ans),sub("ONE   TWO   THREE FOUR  FIVE  SIX   SEVEN EIGHT NINE  TEN   ELEVENTWELVE",6A-5,6

```

Note 1: For TI-84+ you can replace `Input` with something like `getTime:Ans(1->X:getTime:Ans(2->Y`. Also, `int(Y/5-5.6` is equivalent to `round(Y/5,0)-6`. And no, in this case `int(` could not be interchanged with `iPart(`.

Note 2: This prints the input just fine, but for asethetic reasons you probably want `Pause` at the end of the program to avoid the `Done` message upon program termination.

Edit: Byte count lowered because tokenized (see note on previous revision), also a bug is fixed thanks to @Neil. Third, fixed a bug I found myself which would have costed 2 bytes but the optimization actually saved 1 byte overall, and I also realized that I am getting input so I don't need to call `getTime` (duh?). Last, for anyone who wants to confirm this byte count, the only two byte token is `sub(`.
> 19 votes

# Answer
## JavaScript (ES6), ~~291~~ ~~303~~ 295 bytes

Takes input as two integers with currying syntax `(h)(m)`

```
h=>m=>console.log(`IT IS HALF TEN
QUARTER TWENTY
FIVE MINUTES TO
PAST TWO THREE
ONE FOUR FIVE
SIX SEVEN EIGHT
NINE TEN ELEVEN
TWELVE O'CLOCK`.replace(/\S+/g,w=>(k/=2)&1?w:w.replace(/./g,' '),k=[x=1<<19,88,81,66,84,92,64.5,60,52,34,49,56,x,h=(m<33?h+11:h)%12][m/5+.4|0]*16|6|2048<<(h?h-(h<3):2)))

```

### How it works

The whole clock can be seen as 23 LEDs that are either ON or OFF. So, the clock state is a 23-bit integer.

```
Bit | Word        Bit | Word
----+--------     ----+--------
00  | IT          12  | ONE
01  | IS          13  | FOUR
02  | HALF        14  | FIVE
03  | TEN         15  | SIX
04  | QUARTER     16  | SEVEN
05  | TWENTY      17  | EIGHT
06  | FIVE        18  | NINE
07  | MINUTES     19  | TEN
08  | TO          20  | ELEVEN
09  | PAST        21  | TWELVE
10  | TWO         22  | O'CLOCK
11  | THREE

```

The *minutes* logic that we need to implement to enable the right words is not as simple as one might think at first glance. A magic-golfing formula may exist but I went the easy way and decided to just hardcode each possible configuration:

```
Minutes | Words                    | Enabled bits | Value   | Value / 8
--------+--------------------------+--------------+---------+----------
  00    | O'CLOCK                  | 22           | 4194304 | 524288
  05    | FIVE MINUTES PAST        | 6, 7, 9      | 704     | 88
  10    | TEN MINUTES PAST         | 3, 7, 9      | 648     | 81
  15    | QUARTER PAST             | 4, 9         | 528     | 66
  20    | TWENTY MINUTES PAST      | 5, 7, 9      | 672     | 84
  25    | TWENTY FIVE MINUTES PAST | 5, 6, 7, 9   | 736     | 92
  30    | HALF PAST                | 2, 9         | 516     | 64.5
  35    | TWENTY FIVE MINUTES TO   | 5, 6, 7, 8   | 480     | 60
  40    | TWENTY MINUTES TO        | 5, 7, 8      | 416     | 52
  45    | QUARTER TO               | 4, 8         | 272     | 34
  50    | TEN MINUTES TO           | 3, 7, 8      | 392     | 49
  55    | FIVE MINUTES TO          | 6, 7, 8      | 448     | 56

```

### Test cases

```
let f =

h=>m=>console.log(`IT IS HALF TEN
QUARTER TWENTY
FIVE MINUTES TO
PAST TWO THREE
ONE FOUR FIVE
SIX SEVEN EIGHT
NINE TEN ELEVEN
TWELVE O'CLOCK`.replace(/\S+/g,w=>(k/=2)&1?w:w.replace(/./g,' '),k=[x=1<<19,88,81,66,84,92,64.5,60,52,34,49,56,x,h=(m<33?h+11:h)%12][m/5+.4|0]*16|6|2048<<(h?h-(h<3):2)))
;

[[13,15],[13,58],[14,30],[15,35],[10,0],[12,0]].map(([h, m]) => {
  console.log('h = ' + h, 'm = ' + m);
  f(h)(m);
});
```
> 13 votes

# Answer
## Batch, 789 bytes

```
@echo off
if not "%1"=="" setlocal&set time=%1
set/a"h=%time:~0,2%,m=6%time:~3,2%%%60+2,h+=m/35,h%%=12,m=6-m/5%%12,n=m%%3,o=m%%2
set p=
set s=
call:c %m:-=% "IT IS HALF" 0 "IT IS      TEN" 4 "IT IS"
call:c %m:-=% QUARTER 3 "        TWENTY" 2 "        TWENTY" 1
if %m% lss 0 set s= TO
call:c 0 "            " %n% "     MINUTES" %o% "FIVE MINUTES"
set s=
set p=PAST
if %m%==6 set p=
if %m% lss 0 set p=
call:c %h% TWO 2 "    THREE" 3
set p=
call:c %h% ONE 1 "    FOUR" 4 "          FIVE" 5
call:c %h% SIX 6 "    SEVEN" 7 "          EIGHT" 8
call:c %h% NINE 9 "     TEN" 10 "         ELEVEN" 11
if %m%==6 set s= O'CLOCK
call:c %h% TWELVE 0 "      "
exit/b
:c
set t=%1
:l
if %t%==%3 echo(%p%%~2%s%&exit/b
shift
shift
if not "%3"=="" goto l
echo(%p%%~2%s%

```

Note: Trailing space after `PAST` and 5 trailing spaces on each of the following two lines.
> 6 votes

# Answer
## JavaScript, ~~567 564 551 542 529 527~~ 519 bytes

```
f=(h,m)=>{c={m6:"HALF ",m2:"TEN\n",m3:"QUARTER ",m4:"TWENTY\n",m1:"FIVE ",m:"MINUTES ",t:"TO\n",p:"PAST ",h2:"TWO ",h3:"THREE\n",h1:"ONE ",h4:"FOUR ",h5:"FIVE\n",h6:"SIX ",h7:"SEVEN ",h8:"EIGHT\n",h9:"NINE ",h10:"TEN ",h11:"ELEVEN\n",h0:"TWELVE ",m0:"O'CLOCK"};l=[];p="push";m=Math.round(m/5);if(m>11){m=0;h++}if(m>6){l[p]("t");m=12-m;h++}else if(m)l[p]("p");if(m%3)l[p]("m");if(m==5)l[p]("m4","m1");else l[p]("m"+m);l[p]("h"+h%12);s="IT IS ";for(k in c)s+=(l.indexOf(k)>=0)?c[k]:c[k].replace(/\S/g," ");console.log(s)}

f(19, 20);
f(13, 15);
f(13, 58);
f(14, 30);
f(15, 35);
f(10, 0);
f(12, 0);
```

I don't know if it's OK to take hours and minutes as arguments. You said "list of integers". Does it still count?

It's my first time golfing, by the way. What do you think?

---

**Edit:** Saved a few bytes by dividing minutes. Thanks, Olivier!
> 4 votes

# Answer
## Python 2, ~~466~~,~~460~~,~~449~~,~~452~~,~~459~~ 449 bytes

As it's allowed to be a function accepting h and m as integers we can save a few bytes. Try it online.

```
def t(h,m):

m=(2+m)//5
 h=h%12
 n=0
 if m>6:n,m=1,12-m;h+=1
 a="""IT IS _HALF _TEN_
 _QUARTER _TWENTY_
 _FIVE _MINUTES _TO_
 _PAST _TWO _THREE_
 _ONE _FOUR _FIVE_
 _SIX _SEVEN _EIGHT_
 _NINE _TEN _ELEVEN_
 _TWELVE _O'CLOCK""".split("_")
 b=[1,m==6,m==2,1,m==3,3<m<6,1,m in[1,5],m in[1,2,4],n*m,1,(1-n)*m,h==2,h==3,1,h==1,h==4,h==5,1,h==6,h==7,h==8,1,h==9,h==10,h==11,1,h==0,m==0]
 for i,c in enumerate(a):
  if b[i]:print c,
  else:print' '*len(c),

```

I had a couple of bugs (now fixed) with the logic for `TO`/`PAST` vs `O'CLOCK`. Also saved a few bytes for `enumerate`, changing the `import`, and `19<m<26` instead of `m in [20,25]`. Saved another 8 for working in 5-minute chunks rater than minutes. Rod pointed out some more bugs costing me quite a bit, but I recovered a little with more efficient assignments and a bugfix that worked in my favour.
> 4 votes

# Answer
# JavaScript (ES6) 360

A function with input parameters hour (0..23) and minute (0..59).
Using `alert` for output, as it's the standard output function in javascript even if it's inconvenient. (And it's short)

```
(k,n,m=(n+2)/5|0,h=(k+(m>6))%12,i=0)=>alert(`IT IS HALF TEN
QUARTER TWENTY
FIVE MINUTES TO
PAST TWO THREE
ONE FOUR FIVE
SIX SEVEN EIGHT
NINE TEN ELEVEN
TWELVE O'CLOCK`.replace(/\S+/g,w=>[,,m-6,m-2&&m-10,m-3&&m-9,m-4&&m-8&&m-5&&m-7,m-1&&m-11&&m-5&&m-7,!(m%3),m<7|m==12,!m|m>6,h-2,h-3,h-1,h-4,h-5,h-6,h-7,h-8,h-9,h-10,h-11,h%12,m%12][i++]?w.replace(/./g,' '):w))

```

**Test** Note: for your peace of mind, in the test snippet the alert output is redirected to the page text

```
F=
(k,n,m=(n+2)/5|0,h=(k+(m>6))%12,i=0)=>alert(`IT IS HALF TEN
QUARTER TWENTY
FIVE MINUTES TO
PAST TWO THREE
ONE FOUR FIVE
SIX SEVEN EIGHT
NINE TEN ELEVEN
TWELVE O'CLOCK`.replace(/\S+/g,w=>[,,m-6,m-2&&m-10,m-3&&m-9,m-4&&m-8&&m-5&&m-7,m-1&&m-11&&m-5&&m-7,!(m%3),m<7|m==12,!m|m>6,h-2,h-3,h-1,h-4,h-5,h-6,h-7,h-8,h-9,h-10,h-11,h%12,m%12][i++]?w.replace(/./g,' '):w))

function alert(x) { O.textContent=x }
function update() { F(+H.value,+M.value) }

update()
```

```
input { width:3em }
```

```
Hours<input id=H type=number min=0 max=23 value=17 oninput='update()'>
Minutes<input id=M type=number min=0 max=59 value=37 oninput='update()'>
<pre id=O></pre>
```
> 4 votes

# Answer
# Perl 6, ~~308~~ ~~296~~ 293 bytes

```
->\h,\m{my \n=round(m/5)%12;say "IT IS HALF TEN
QUARTER TWENTY
FIVE MINUTES TO
PAST TWO THREE
ONE FOUR FIVE
SIX SEVEN EIGHT
NINE TEN ELEVEN
TWELVE O'CLOCK".subst: /\S+/,{++$==1|2|(0,7,4,5,6,(6|7),3)[min n,12-n]|8*?(n%3)|(23,10,9)[(n+5)/6]|(13,11,12,|(14..*))[(h+m/33-1)%12]??$_!!" "x.comb},:g}

```

Try it online!

### Explanation

The basic structure is as follows:

```
-> \h, \m {                             # A lambda taking two args (hour and minute).
    my \n = round(m / 5) % 12;          # Index from 0 to 11, representing the minutes.
    say "...".subst: /\S+/, {           # Print the template with each word replaced:
        ++$ == ...|...|...|...          # If counter equals one of expected indices,
            ?? $_                       # then replace the word with itself,
            !! " " x .comb              # else replace it with spaces.
    }, :g                               # (Use global matching.)
}

```

The expression elided as `...|...|...|...` above, is a Junction of integers representing 1-based word indices, and is made up as follows:

```
  1|2                                   # IT IS
| (0,7,4,5,6,(6|7),3)[min n,12-n]       # FIVE / TEN / QUARTER / TWENTY / TWENTY FIVE / HALF
| 8*?(n%3)                              # MINUTES
| (23,10,9)[(n+5)/6]                    # O'CLOCK / PAST / TO
| (13,11,12,|(14..*))[(h+m/33-1)%12]    # ONE / TWO / THREE / FOUR / FIVE / SIX / SEVEN / ...

```
> 3 votes

# Answer
## **Python3 , (569 bytes)**

This answer requires time in format *hh mm* (space separated integers) .I managed to have '\n' printed, which is inspired by *Chris's* method.Thanks, Chris! Any help reducing code is appreciated.

```
H,M=input().split()
w="""HALF _TEN_
_QUARTER _TWENTY_
_FIVE _MINUTES _TO_
_PAST _TWO _THREE_
_ONE _FOUR _FIVE_
_SIX _SEVEN _EIGHT_
_NINE _TEN _ELEVEN_
_TWELVE _O'CLOCK""".split("_")
h,m=int(H),int(M)
if h>12:h-=12
m=(m//5+1)*5 if m%5>2.5 else m//5*5
if m>30:
    m=60-m
    h=(h+1)%12
X=[m==30,m==10,1,m==15,m in[20,25],1,m in[5,25],m not in[0,15,30],int(M)>30 and m!=0,1,m!=0 and int(M)<31,h==2,h==3,1,h==1,h==4,h==5,1,h==6,h==7,h==8,1,h==9,h==10,h==11,1,h in[0,12],m==0]
t="IT IS "
for i in range(0,28):
    if(X[i]):t+=w[i]
    else:t+=" "*len(w[i])
print(t.strip())

```

Try It Online
> 2 votes

# Answer
# SimpleTemplate, ~~737~~ 708 bytes

Yeah, verbosity and lack of "real" math hurt the bytecount badly.

```
{@seth argv.0}{@php$DATA[m]=ceil($DATA[argv][1]/5)*5%60|0}{@ifm}{@ifm is30}{@setA"HALF"}{@/}{@if"@[15]0$@"is matchesm}{@setB"TEN"}{@/}{@if"@[14]5$@"is matchesm}{@setC"QUARTER"}{@/}{@if"@[24]0$@"is matchesm}{@setD"TWENTY"}{@/}{@if"@^[25]?5$@"is matchesm}{@setE"FIVE"}{@/}{@if"@^([235]?5|[1245]0)$@" is matchesm}{@setF"MINUTES"}{@/}{@ifm is greater30}{@setG"TO"}{@else}{@setH"PAST"}{@/}{@else}{@setU"O\'CLOCK"}{@/}{@setZ"","ONE","TWO","THREE","FOUR","FIVE","SIX","SEVEN","EIGHT","NINE","TEN","ELEVEN","TWELVE"}{@setY"J"}{@incbyh Y}{@php$DATA[$DATA[Y]]=$DATA[Z][$DATA[h]]}{@print"IT IS%-6s%s\n%8s%s\n%-5s%-7s %s\n%4s %3s %s\n%3s %4s %s\n%3s %5s %s\n%4s %3s %s\n%6s %s",A,B,C,D,E,F,G,H,J,K,I,L,M,N,O,P,Q,R,S,T,U}

```

This expects the hour and minutes as the 1st and 2nd parameter on the class.

---

**Ungolfed:**

```
{@set hour argv.0}

{@//The bitwise is required for the `@if minutes is 30`}
{@//Otherwise, I would be forced to write `@if minutes is equal to 30`}
{@php $DATA['minutes'] = ((ceil($DATA['argv'][1] / 5) * 5) % 60) | 0}

{@if minutes}
    {@if minutes is 30}
        {@set A "HALF"}
    {@/}
    {@if "@[15]0$@" is matches minutes}
        {@set B "TEN"}
    {@/}
    {@if "@[14]5$@" is matches minutes}
        {@set C "QUARTER"}
    {@/}
    {@if "@[24]0$@" is matches minutes}
        {@set D "TWENTY"}
    {@/}
    {@if "@^[25]?5$@" is matches minutes}
        {@set E "FIVE"}
    {@/}
    {@if "@^([235]?5|[1245]0)$@" is matches minutes}
        {@set F "MINUTES"}
    {@/}
    {@if m is greater than 30}
        {@set G "TO"}
    {@else}
        {@set H "PAST"}
    {@/}
{@else}
    {@set U "O\'CLOCK"}
{@/}

{@set numbers "", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE", "TEN", "ELEVEN", "TWELVE"}
{@set key "J"}
{@inc by hour key}
{@php $DATA[$DATA['key']] = $DATA['numbers'][$DATA['hour']]}

{@print "IT IS%-6s%s\n%8s%s\n%-5s%-7s %s\n%4s %3s %s\n%3s %4s %s\n%3s %5s %s\n%4s %3s %s\n%6s %s", A, B, C, D, E, F, G, H, J, K, I, L, M, N, O, P, Q, R, S, T, U}

```

---

**How to run:**

1. Get the code from https://github.com/ismael-miguel/SimpleTemplate
2. Run the following code:

```
<?php
    include 'SimpleTemplate.php';

    $template = new SimpleTemplate('<code>');

    $template->render($hour, $minutes);

    //system-time: $template->render(date('g'), date('i'));

```
3. Done!
> 1 votes

# Answer
# Python 2, ~~443~~ 440 bytes

```
R=range
w="HALF TEN QUARTER TWENTY FIVE MINUTES TO PAST TWO THREE ONE FOUR FIVE SIX SEVEN EIGHT NINE TEN ELEVEN TWELVE O'CLOCK".split(' ')
h=[10,8,9]+R(11,20)
c=['IT','IS']+[' '*len(x)for x in w]
i,j=input()
i=(i,i+1)[j>30]%13-1
j=int(round(j/5.0)*5.0)%60
for z in[[20],[4,5,7],[1,5,7],[2,7],[3,5,7],[3,4,5,7],[0,7],R(3,7),[3,5,6],[2,6],[1,5,6],R(4,7)][j/5]:c[z]=w[z]
c[h[i]]=w[h[i]]
x=0
for y in[4]+R(6,22,3)+[23]:print' '.join(c[x:y]);x=y

```

Try it online!

It could probably still benefit from some more golfing. Input is a list of integers e.g. 7,23 = 7:23
> 1 votes

# Answer
# Java (OpenJDK 9), 437 bytes

```
(h,m)->{h=(h+m/35+11)%12+1;Object[]s="HALF TEN QUARTER TWENTY FIVE MINUTES TO PAST TWO THREE ONE FOUR FIVE SIX SEVEN EIGHT NINE TEN ELEVEN TWELVE O'CLOCK".split(" ");for(int i=s.length,M[]={1<<20,176,162,132,168,184,129,120,104,68,98,112};i-->0;)s[i]=(7<i&i<20?h==i-(h>3?7:h>1?6:9):(M[(m+2)/5%12]&(1<<i))>0)?s[i]:"";System.out.printf("IT IS %4s %3s%n%7s %6s%n%4s %7s %2s%n%4s %3s %5s%n%3s %4s %4s%n%3s %5s %5s%n%4s %3s %6s%n%6s %7s",s);}

```

Try it online!

I thought I'd finally give a shot at my challenge ;)
> 1 votes

# Answer
# Perl 5, ~~487~~ 449 bytes

```
($a,$_,$h)=localtime;s/[3-7]$/5/;s/[12]$/0/;$m=s/(.?)[89]$/($1+1)*10/er;$_="IT IS half ten
quarter tw
five minutes to
past 2two 3three
1one 4four 5five
6six 7seven 8eight
9nine 10ten 11eleven
12twelve oc";if($m>30){s/to/TO/;$h++;$m=60-$m}elsif($m){s/past/PAST/}$h=$h%12||12;$m!=30?$m%15?s/m\w+/uc$&/e:$m?s/q\w+/uc$&/e:s/oc/O'CLOCK/:s/half/HALF/;$m%10&&!/Q/&&s/five/FIVE/;$m>15&&$m<30?s/tw/TWENTY/:$m==10&&s/ten/TEN/;s/\b$h\w+/uc$&/es;y/a-z0-9/ /;say

```

Try it online!
> 1 votes

# Answer
# C, 447 bytes

A function `c()` which takes hours and minutes as arguments, and prints the result to standard output stream:

```
char*z="";c(h,m){h+=(m+=2,m/=5)>6;h%=12;m=1<<m;printf("IT IS%5s %s\n%7s %s\n%4s%8s %s\n%4s%4s %s\n%3s%5s %s\n%3s%6s %s\n%4s%4s %s\n%6s %s",m&64?"HALF":z,m&1028?"TEN":z,m&520?"QUARTER":z,m&432?"TWENTY":z,m&2210?"FIVE":z,m&3510?"MINUTES":z,m&3968?"TO":z,m&126?"PAST":z,h-2?z:"TWO",h-3?z:"THREE",h-1?z:"ONE",h-4?z:"FOUR",h-5?z:"FIVE",h-6?z:"SIX",h-7?z:"SEVEN",h-8?z:"EIGHT",h-9?z:"NINE",h-10?z:"TEN",h-11?z:"ELEVEN",h?z:"TWELVE",m&4097?"O'CLOCK":z);}

```

## Explanation

The selection of the hour number should be obvious; for the other words, we make a 13-bit mask (0-12) of the minute hand's position, and use this to select which texts light up.

```
void clock(int hour, int min)
{
    min = (min + 2) / 5;
    if (m > 6) ++hour;
    hour = hour % 12;
    min = 1 << min;
    printf("IT IS%5s %s\n"
           "%7s %s\n"
           "%4s%8s %s\n"
           "%4s%4s %s\n"
           "%3s%5s %s\n"
           "%3s%6s %s\n"
           "%4s%4s %s\n"
           "%6s %s",
    min & (1 << 6) ? "HALF" : "",
    min & ((1 << 2) | (1 << 10)) ? "TEN" : "",
    min & ((1 << 3) | (1 << 9)) ? "QUARTER" : "",
    min & ((1 << 4) | (1 << 5) | (1 << 7)  | (1 << 8)) ? "TWENTY" : "",
    min & ((1 << 1) | (1 << 5) | (1 << 7) | (1 << 11)) ? "FIVE" : "",
    min & ((1 << 1) | (1 << 2) | (1 << 4) | (1 << 5) | (1 << 7) | (1 << 8) | (1 << 10) | (1 << 11)) ? "MINUTES" : "",
    min & ((1 << 7) | (1 << 8) | (1 << 9) | (1 << 10) | (1 << 11)) ? "TO" : "",
    min & ((1 << 1) | (1 << 2) | (1 << 3) | (1 << 4) | (1 << 5) | (1 << 6)) ? "PAST" : "",
    hour == 2 ? "TWO" : "",
    hour == 3 ? "THREE" : "",
    hour == 1 ? "ONE" : "",
    hour == 4 ? "FOUR" : "",
    hour == 5 ? "FIVE" : "",
    hour == 6 ? "SIX" : "",
    hour == 7 ? "SEVEN" : "",
    hour == 8 ? "EIGHT" : "",
    hour == 9 ? "NINE" : "",
    hour == 10 ? "TEN" : "",
    hour == 11 ? "ELEVEN" : "",
    hour == 0 ? "TWELVE" : "",
    min & ((1 << 0) | (1 << 12)) ? "O'CLOCK" : "");
}

```

## Demo

This is also available on Try It Online.

```
#include <stdio.h>
int clock(int hour, int min)
{
    c(hour, min);
    printf("(%2d:%02d)\n---\n", hour, min);
}

int main(void)
{
    /* examples from the question */
    clock(19, 20);
    clock(13, 15);
    clock(13, 58);
    clock(14, 30);
    clock(15, 35);
    clock(10, 00);
    clock(12, 00);

    /* Test all the lights */
    int hour = 11;
    for (int min = 0;  min <= 60;  min += 5) {
        clock(++hour, min);
    }
}

```
> 1 votes

---
Tags: code-golf, string, date
---


title: It's a dog! (Or is it?)

text:
# Question
Title: It's a dog! (Or is it?)
The city defines a dog as any living entity with four legs and a tail. So raccoons, bears, mountain lions, mice, these are all just different sizes of dog.

Given an ASCII-art image of an animal, determine if that animal is a dog.

## Rules

An animal is a dog if it has four legs and a tail.

The foot of a leg starts with one of `\` (backslash), `|` (pipe), or `/` (slash), has one or more `_` in between, and another `\`, `|`, or `/`. Each foot will hit the last line of the string. The feet may not share a common border.

```
\ \  |   /   /    |  |     /  |   |  / /     <-- These are all just
|_|  |___|  |_____|  |_____|  |___|  |_|         different sizes of leg.

```

A tail is a line coming out of the left side of the figure and touching the leftmost part of the multiline string. The tail is made up of either `-` or `=` characters. The tail must be at least one character long, and can optionally end with a `o` or `*`.

```
o---  *--  *==  --  ==  -  =  o===  *-      <-- These are all just
                                                different sizes of tail.

```

You can take input as a multiline string, or array of lines. Output a truthy or falsy value to determine if the figure is a dog, or any two distinct values.

Truthy test cases:

```
      ______/\__/\
    _/    (  U U  )
*--/____. ,\_ w _/
    \  /| |\ |\ \
    /_/ \_/|_| \_\

```

```
    _________/\
o==/         ''>
   |_||_||_||_|

```

```
        /\__/\
       (  o O)
       /   m/
      |    |      don't ask
o-----|    \__
      |   ___ \_______
      //\ \  \___ ___ \
     /_/ \_\    /_|  \_|

```

Falsy test cases:

```
        __________          _
 ______/ ________ \________/o)<
(_______/        \__________/

```

```
     ____/)(\
    /   \o >o
   (     \_./
o--\ \_.  /
    \____/
    ||  ||
    \/  \/

```

```
   /\/\/\/\/\
o-/       o.o
   /_/_/_/_/

```

# Answer
> 3 votes
# 05AB1E, ~~43~~ 41 bytes

```
ε„*oõš„-=âJÅ?}àIθ„__¬:.œε…\|/Sã'_ý¢O}à4Q*

```

Input as a list of lines.

Try it online or verify all test cases. (NOTE: I've added a remove spaces `ðK` before the partition builtin, to speed it up significantly. So should you test a 'dog' which has a space in one of its feet (e.g. `|_ |`, the `ðK` should be removed to test it properly.)

**Explanation:**

Step 1: Validate the tail:

```
ε              # Map over each line of the (implicit) input-list:
 „*o           #  Push string "*o"
    õš         #  Convert it to a list of characters and append an empty string:
               #   ["*","o",""]
      „-=      #  Push string "-="
         â     #  Get all combinations of the two with the cartesian product:
               #   [["","-"],["","="],["*","-"],["*","="],["o","-"],["o","="]]
          J    #  Join each inner pair together to a string:
               #   ["-","=","*-","*=","o-","o="]
           Å?  #  Check for each whether the current line starts with it
}à             # After the map: pop and push the maximum to check if any was truthy

```

Step 2: Validate the feet:

```
I              # Push the input-list again
 θ             # Leave just its last line
  „__          # Push string "__"
     ¬         # Push its first character (without popping): "_"
      :        # Keep replacing all "__" with "_" until there are no "__" left
.œ             # Get all partitions of this string
  ε            # Map over each partition:
   …\|/S       #  Push triplet-list ["\","|","/"]
        ã      #  Get all pairs with the cartesian power of 2:
               #   [["\","\"],["\","|"],["\","/"],["|","\"],["|","|"],["|","/"],["/","\"],["/","|"],["/","/"]]
         '_ý  '#  Join each inner pair with "_" delimiter:
               #   ["\_\","\_|","\_/","|_\","|_|","|_/","/_\","/_|","/_/"]
            ¢  #  Count how many times each foot occurs in the parts
             O #  Sum the counts of each type of foot together
  }à           # After the map: pop and leave the maximum sum of counts
    4Q         # Check if this is equal to 4

```

Step 3: Combine the checks and output:

```
*              # Multiply the two checks together
               # (after which the result is output implicitly)

```

# Answer
> 6 votes
# Python, 102 bytes

```
lambda x:any(re.match("[\*o]?[\-=]+",r)for r in x)*len(re.split(r"[\\|/]_+[\\|/]",x[-1]))==5
import re

```

Attempt This Online!

Takes in a list of lines.

# Answer
> 4 votes
# Retina 0.8.2, 59 bytes

```
^((.*¶)*[*o][-=])?(.*¶)*(.*?[\\|/]_+[\\|/])*.*$
$#4$#1
^41$

```

Try it online! Link is to test suite that splits on blank lines for convenience. Explanation:

```
^((.*¶)*[*o][-=])?(.*¶)*(.*?[\\|/]_+[\\|/])*.*$

```

Optionally match a tail, then match any number of legs.

```
$#4$#1

```

Replace with the count of legs and whether a tail was matched.

```
^41$

```

Check for exactly four legs and a tail.

# Answer
> 3 votes
# Factor, ~~62~~ 101 bytes

```
[ dup R/ ^[*o]?[-=]+/m re-contains? swap
"\n" split last R/ [\\|\/]_+[\\|\/]/ count-matches 4 = and ]

```

+39 bytes to disallow dogs with more than four legs. Ouch. :\

# Answer
> 3 votes
# Bash, 77 bytes

Though it's using core tools, so should work on other shells.

Edit: 7 bytes saved because I was being brain dead about how to test in TIO. Thanks for the nudge, @Neil.

Edit: just added more test cases

```
grep -Eqo ^[o*]?[=-] $1&&[ `tail -1 $1|grep -Eo "[/\\|]_+[/\\|]"|wc -l` = 4 ]

```

Try it online!

# Answer
> 3 votes
# JavaScript (Node.js), 65 bytes

```
x=>x.match(/[\\|\/]_+[\\|\/](?=.*$)|$/g)[4]</^[*o]?[-=]/m.test(x)

```

Try it online!

```
'' < true
'' ≮ false
undefined ≮ true
'|_|' ≮ true

```

# Answer
> 1 votes
# awk, 57 bytes

```
/^[o*]?[=-]/{t=1}END{exit t&&gsub(/[/\\|]_+[/\\|]/,0)==4}

```

Try it online!

---
Tags: code-golf, ascii-art, decision-problem
---


title: Make me a shape

text:
# Question
Title: Make me a shape
The game shapez.io has a huge variety of shapes you can produce, such as:

Each shape has a unique *short code*, for example the above is `CrWbScRu`.

This means, going clockwise from top right, red circle (`Cr`), blue wedge (`Wb`), cyan star (`Sc`), uncolored rectangle (`Ru`).

There are four different shapes:

* Rectangle - `R`
* Wedge - `W`
* Star - `S`
* Circle - `C`

And eight different colours:

* uncolored - `u`
* red - `r`
* green - `g`
* blue - `b`
* yellow - `y`
* purple - `p`
* cyan - `c`
* white - `w`

A quadrant is made out of one of each of these - (shape)(color). A quadrant can also be *empty* with `--`. This means there are 33 possible quadrants.

Four quadrants concatenated together make a *layer*, of which there are \\$33^4 - 1 = 1185920\\$ possibilities. You can't have an empty layer (`--------`). These layers can be stacked on top of one another by joining with `:` \- the code `CyCyCyCy:SrSrSrSr` looks like:

Shapes can be stacked up to 4. This means there are \\$\left(33^{4}-1\right)+\left(33^{4}-1\right)^{2}+\left(33^{4}-1\right)^{3}+\left(33^{4}-1\right)^{4} = \\$ 1.97 septillion possible shapes total.

Your challenge is to randomly generate one of these.

Your generation does not have to be uniformly random, as long as every possible shape has a nonzero chance of being chosen.

## Specs

* Each *quadrant* is one of `SWCR` followed by one of `ugbrycpw`, or `--`.
* A *layer* is four *quadrants* concatenated together.
* A *shape* is 1-4 *layers* joined by `:`
* You should generate a not-necessarily-uniformly-random *shape*.

You can view shapes at https://viewer.shapez.io/.

# Scoring

This is , shortest wins!

# Answer
# 05AB1E, ~~35~~ ~~40~~ ~~38~~ 36 bytes

+5 to prevent empty output which would've occured with probability \\$33^{-16}\\$
-2 bytes thanks to Kevin Cruijssen!

Quite slow, generates \\$33^4\\$ possible layers 4 times and chooses a random one each time. Layers of all `-` are removed.

```
[₄ε‘¥„W‘’»Õpcw’â„--ª4ãΩJ}'-8×K':ýDĀ#

```

Try it online!

At the cost of two bytes this can actually run fast: Try it online!

Because every quadrant in each layer has a \\$1\\$ in \\$33\\$ chance of being empty the resulting shapes are quite noisy:

---

```
[    ...    Dg#              # until the the output is not empty, do the following:

₄                            # push constant 1000
  ε                     }    # for each digit in this number:
   ‘¥„W‘                     #   dictionary compressed string "SRCW"
        ’»Õpcw’              #   dictionary compressed string "rugbypcw"
               â             #   cartesian product of the two strings
                „--ª         #   append "--" to this list
                    4ã       #   4th cartesian power, all 4-element combinations from the length-2 strings
                      Ω      #   choose a random one
                       J     #   join into a single string

'-8×                         # string of 8 -'s
    K                        # remove all occurences from the list
     ':ý                     # join the list by ":"

```
> 7 votes

# Answer
# Jelly, ~~38~~ ~~35~~ 34 bytes

```
“SWCR”p“¬,ĖṆḷ⁸»Żṗ4XʋⱮ4ẸƇƊṆ¿o⁾--j”:

```

Try it online!

This *just* about finishes on TIO most of the time (it has a \\$1\\$ in \\$33^{16}\\$ chance of taking longer), taking around 55 seconds. Full program, as we require Jelly's smash-printing to get the correct output

-4 bytes thanks to Jonathan Allan!

The first sample output I got was:

External link

# How it works

```
“SWCR”p“¬,ĖṆḷ⁸»Żṗ4XʋⱮ4ẸƇƊṆ¿o⁾--j”: - Main link. No arguments. Left argument = 0
                        Ɗ          - Group the previous 3 links into a monad f(_): (ignores the argument)
“SWCR”                             -   Set the return value to “SWCR”
                   ʋ               -   Group the previous 4 links into a dyad g(“SWCR”, i): (ignores i)
       “¬,ĖṆḷ⁸»                    -     Compressed string: “rugbypcw”
      p                            -     Cartesian product with “SWCR”
               Ż                   -     Prepend a zero (represents “--”)
                ṗ4                 -     4th Cartesian power
                  X                -     Choose a random list
                    Ɱ4             -   Yield [g(“SWCR”,1), g(“SWCR”,2), g(“SWCR”,3), g(“SWCR”,4)]
                      ẸƇ           -   Remove any that are just zeros
                          ¿        - While:
                         Ṇ         -   The left argument is falsey ([] or 0)
                        Ɗ          -   Set the left argument to f(_)
                           o⁾--    - Replace all zeros with “--”
                               j”: - Join by ”: and smash-print

```
> 6 votes

# Answer
# Python 3, 129 bytes

```
from random import*
print(':'.join(''.join(sample(q,4))for q in[[i+j for i in'RWSC'for j in'urgbypcw']*4+['--']*3]*randint(1,4)))

```

Try it online!

For each layer, 4 items are picked from a distribution containing 3 empty quadrants and the other shape-colour combinations 4 times.
> 5 votes

# Answer
# Japt, ~~40~~ ~~39~~ 38 bytes

This version has a *very* high probability of having all 4 layers, using a similar approach as Level's Ruby solution of generating all 4 layers, removing the ones consisting entirely of empty quadrants and making a recursive call if there are none left.

```
4Æ"RWCS"ï`Õ½wbgp` p-² ö4 qÃfÈr-Ãq': ªß

```

Test it

## Original, 39 bytes

```
Ò4ö)ÆÈr-}a@"RWCS"ï`Õ½wbgp` p-² ö4 q
q':

```

Test it

```
Ò4ö)ÆÈr-}a@"RWCS"ï`Õ½wbgp` p-² ö4 q\nq':
Ò                                            :Negate the bitwise not of (i.e., increment)
 4ö                                          :  Random int in the range [0,4)
   )                                         :End bitwise op
    Æ                                        :Map the range [0,Ò4ö)
     È                                       :  Left function taking a string as argument
      r-                                     :    Remove all "-"s
        }                                    :  End function
         a                                   :  Return the first result of the right function that returns truthy (non-empty string) when passed through the left
          @                                  :  Right function
           "RWCS"ï                           :    Cartesian product of "RWCS" and
                  `Õ½wbgp`                   :      Compressed string "ucrywbgp"
                           p                 :    Push
                            -²               :      "-" duplicated
                               ö4            :    Choose 4 random elements
                                  q          :    Join
                                     q':     :Join with ":"

```
> 4 votes

# Answer
# C#\[9.0\] \- ~~191, 235, 228, 204,~~ 203 Bytes (Condensed)

```
static Random r=new();static string g(){var z="";for(int j,i,l=r.Next(1,4);l-->0;z+=":")for(i=j=0;i++<4;)z+=r.Next()%8<1&&j++<3?"--":$"{"CRWS"[r.Next(0,3)]}{"rgbypcuw"[r.Next(0,7)]}";return z.Trim(':');}

```
* `+44` bytes due to a missed requirement.
* `-5` bytes by reducing `GetShape` to `g` per @emanresu A's recommendation.
* `-24` bytes by using `var`, consolidating declarations and using constant strings per @Johan du Toit.
* `-1` byte by swapping `==0` for `<1` per @ceilingcat.

#### How it Works

```
// Create a new random number generator using C# 9.0's `new` invocation.
static Random r = new();
static string g() {

    // Create a variable to store the possible shapes.
    string s = "CRWS",

            // Create a variable to store the possible colors.
            c = "rgbypcuw",

            // Create a variable to store the result.
            z = "";

    // Create an iteration variable to iteratively create between 1 and 4 layers randomly.
    // Evaluate for stop then decrement.
    // Append `:` to the result.
    for (int l = r.Next(1, 4); l-- > 0; z+=":")

        // Create an iteration variable to iteratively create the four quadrants.
        // Create a variable for tracking the number of empty quadrants.
        for (int i = 0, j = 0; i++ < 4;)

            // If we haven't reached the maximum number of allowed empty quadrants, a new one can still be added.
            // Use a random number to determine if we should create an empty quadrant.
            // Since && short circuits, the increment of J doesn't occur unless we're adding an empty quadrant.
            if (r.Next() % 8 == 0 && j++ < 3)

                // Add an empty quadrant.
                z += "--";

            // Otherwise, add a shape and color from the variables above,
            //      using a random index within the bounds of the variables lengths.
            else
                z += $"{s[r.Next(0, 3)]}{c[r.Next(0, 7)]}";

    // Return the result and remove any trailing `:`.
    return z.Trim(':');
}

```

#### Sample Output

I called the method in a `for` loop over 10 iterations to sample the output for this post:

```
--CyCpCb:RpCu--Rc
RpCyWbWc:RcWuWyWc
CyWy--Cr:RrWpWuWg
Wp--WuRc
RpCcCgWp
CbWuWgCu:--RcRbWg:CcCuCpCc
RgRpCyCu:CbWyWuCu
CgCuRpCu
CyRc--Ru:WuRuRbRu:--CgRbWr
WpCgCpRu

```

#### Resulting Image Sample

I ran the shape code `CbWuWgCu:--RcRbWg:CcCuCpCc` through and got this result:
> 4 votes

# Answer
# Charcoal, 51 bytes

```
⪫ＥＥ⊕‽⁴⊕‽⊖Ｘ³³¦⁴⭆Ｅ⁴÷ιＸ³³λ⎇﹪λ³³⁺§RWSCλ§urgbypcw÷λ⁴--¦:

```

Try it online! Link is to verbose version of code. Explanation:

```
    ‽⁴                                              Random integer 0-3
   ⊕                                                Incremented
  Ｅ                                                 Map over implicit range
         Ｘ³³¦⁴                                      33⁴
        ⊖                                           Decremented
       ‽                                            Random integer
      ⊕                                             Incremented
 Ｅ                                                  Map over random integers
               Ｅ⁴                                   Map over quadrants
                 ÷ι                                 Current random integer
                 ÷                                  Integer divide by
                    ³³                              Literal integer `33`
                   Ｘ                                Raised to power
                      λ                             Current quadrant
              ⭆                                     Map over values and join
                         λ                          Current value
                        ﹪ ³³                        Modulo literal `33`
                       ⎇                            If nonzero then
                             §RWSCλ                 Cyclically indexed colour
                            ⁺                       Concatenated with
                                   §urgbypcw        Shape cyclically indexed by
                                             λ      Current value
                                            ÷       Integer divide by
                                              ⁴     Literal integer `4`
                                               --   Else literal string `--`
⪫                                                 : Join with literal `:`
                                                    Implicitly print

```
> 2 votes

# Answer
## Perl 5, ~~95~~ 138 bytes

```
{@q=(qw(: --),map{$s=$_;map$s.$_,ugbrycpw=~/./g}C,R,W,S);@i=map$_%5?$==1+rand
33:0,1..rand 19;@i%5==4&&" @i "!~/ (1 ){4}/||redo;say@q[@i]}

```

Try it online!
> 2 votes

# Answer
# C (gcc), 137 bytes

```
#define r rand()
m;b;q(){m=r;m&30||q();}f(){for(q(b=5+r%4*5);--b;)printf(b%5?m&1<<b%5?"%c%c":"--":":"+!q(),"WRSC"[r%4],"rugbywcp"[r%8]);}

```

Try it online!

-5 bytes thanks ceilingcat!
> 2 votes

# Answer
# Vyxal `rR`, 37 bytes

```
\:4℅ƛ«3⟩∑ḣ`«`SWRC`Ẋ‛--J33²²‹℅τ∑₅8ε-;j

```

Try it Online!

This uses a quite neat custom-base-decompression-based approach to ensure there'll never be an empty layer. It basically generates a random number between 1 and \\$33^4 - 1\\$, decompresses it with the key as all possible quadrants (with `--` first, so 0 can never occur, so empty layers won't either).

```
  4℅ƛ                              ;  # array of length (random 1-4) filled with...
                       33²²‹℅         # Random integer between 1 and 33^4-1 inclusive
                             τ        # Decompressed by...
                  Ẋ                   # Cartesian product of...
     «3⟩∑ḣ`«                          # Compressed string `bcgpruwy`
            `SWRC`                    # String literal `SWRC`
                   ‛--J               # Prepend a `--`
                              ∑       # Concatenate all this
                               ₅8ε-   # Pad with `-` from the start
                                    j # Join the whole thing by...
\:                                    # Semicolons.

```
> 2 votes

# Answer
# Ruby, ~~117~~ 114 bytes

```
->{s=((0..19).map{|i|i%5<1??::"-SWCR"[(r=rand 40)/8]+"rgbpucyw-"[r<8?8:r%8]}*'').gsub ?:+?-*8,''
s>''?s[1,99]:f[]}

```

Try it online!

A function returning a string.

**Commented code (original version)**

```
->{s=
 ((0..19).map{|i|i%5<1?     #Iterate 20 times to make an array. if i%5==0
 ?::                        #put a colon, else...
  "-SWCR"[(r=rand 40)/8]+   #Select a shape
  (r<8??-:"rgbpucyw"[r%8])  #If selected shape is - then put another -, else put a colour
  }*'').                    #Convert the 20-element array into a string
  gsub(?:+?-*8,'')          #Delete all instances of :--------
  s<?!?f[]:s[1,99]}         #If s is empty, recursively call f[] to try again. Else output s (minus the initial colon)

```
> 2 votes

# Answer
# Java (JDK), ~~263~~ 253 bytes

-10 thanks to ceilingcat! Forgot that `|` exists and that ternary `if`s can be written without parentheses. D'oh!

```
String f(int i){var r=new Random();var q=""+"SWCR-".charAt(r.nextInt(5));q+=q.equals("-")?'-':"ugbrycpw".charAt(r.nextInt(8));return i<1?(f(2)+f(2)+f(2)+f(3)).substring(1):i<9?i>2|r.nextInt(2)<1?(":"+f(9)+f(9)+f(9)+f(9)).replace(":--------",f(1)):"":q;}

```

Try it online!

Took forever to find something promising, ow my head... This won't win any prices, but I liked the approach so here it is anyways. It uses the same function recursively with a different parameter to build different parts of the string.
I hope I find the template for Java lambdas again, I keep forgetting how the boilerplate needs to look for them to work :(

## EDIT:

Function lamdas aren't shorter in this case, since you don't call but `apply()` them, which is WAY longer. Still, thanks for the template `Johan du Troit`!

### Explained:

```
// function is called with 0 to start
String f(int i) {
    // use var because it's shorter
    var r=new Random();

    // build a quadrant
    // decide on a type...
    var q=""+"SWCR-".charAt(r.nextInt(5));
    // ...and append the color. If the type is "-" then append a "-" instead
    q+=q.equals("-")?'-':"ugbrycpw".charAt(r.nextInt(8));

    // decide what to return
    return
    // shape case: build full shape
    i<1?
      // a shape consists of four layers
      // each layer starts with a :, cut the first one off
      (f(2)+f(2)+f(2)+f(3)).substring(1)

    // not the starting case, check for layer case
    :i<9?
      // build one layer. It either doesn't exist or contains four shapes
      // note: 3 overrides the random decision and always returns a layer
      i>2|r.nextInt(2)<1?
        // replace an empty layer with a newly generated one...
        (":"+f(9)+f(9)+f(9)+f(9)).replace(":--------",f(1))
        // ...or return a nonexistant layer
        :""
    // not the shape case nor the layer case, return the quadrant calculated above
    :q;
}

```
> 2 votes

# Answer
# APL(Dyalog Unicode), 64 bytes SBCS

A full program that prints the shape.

```
⊃{∊⍺':'⍵}/{∊((⊂'--'),,'RWCS'∘.,'urgbypcw')[?4⍴33]}⍣{∨/'-'≠⍺}¨⍳?4

```

Try it on APLgolf!

`?4` random integer between 1 and 4
`... ¨⍳` call the function on the left this many times and collect the results in a list:

`{ ... }⍣{∨/'-'≠⍺}` until any char in the result is not `-`:
`'RWCS'∘.,'urgbypcw'` Cartesian product of the two strings
`,` flatten into a list of 2-char strings
`(⊂'--'),` prepend the empty quadrant
`( ... )[?4⍴33]` get elements at 4 random indices between 1 and 33.
flatten into a string

`{∊⍺':'⍵}/` join with `:`
get the first element from the nested output
> 1 votes

# Answer
# JavaScript, ~~125~~ ~~120~~ ~~119~~ ~~115~~ ~~112~~ 118 bytes

To avoid the possibility of an empty layer, we force the 4th quadrant to be non-empty *if* all previous quadrants are already empty (+6 bytes 'cause I realised I'd screwed that up).

Need to figure out a way to shorten the selection of the characters.

```
(r=x=>Math.random(g=s=>s[7]?l--?s+`:`+g``:s:g(s+`RWSC-`[c=r(5^s==`------`)]+`urgbypcw-`[c-4?r(8):8]))*x|0,l=r(4))=>g``

```

Try it online!
> 1 votes

# Answer
# JavaScript (ES6), 117 bytes

*-2 thanks to @l4m2*

Although this is not required, this solution has a uniform distribution.

```
f=(k=(R=Math.random)()*4|0,q=R(n=4)*1185920)=>n--?f(k,q/33)+'SWCR-'[((q%=33)&35)%7]+'ugbrycpw-'[q>>2]:k?f(k-1)+':':''

```

Try it online!
> 1 votes

# Answer
# CSASM v2.5.1, 514 bytes

```
func a:
lda 0
sta $1
lda ""
sta $2
push 1
push 5
extern Random.Next(i32,i32)
pop $a
.lbl a
push $a
brfalse b
dec $a
push 0
pop $1
push ""
pop $3
.lbl c
push $1
push 4
sub
brfalse d
inc $1
push "RWSC-"
push 5
extern Random.Next(i32)
dup
push 1
add
substr
dup
push "-"
sub
len
brtrue f
dup
add
br e
.lbl f
push "urgbypcw"
push 8
extern Random.Next(i32)
dup
push 1
add
substr
add
.lbl e
push $3
swap
add
dup
pop $3
push "--------"
sub
len
brtrue c
push 0
pop $1
push ""
pop $3
br c
.lbl d
push $2
push $3
add
pop $2
push $a
brfalse a
push $2
push ":"
add
pop $2
br a
.lbl b
push $2
print
ret
end

```

Whew, this was one mammoth of a program to write.

This submission defines a function `a` which generates then prints the random shape string as is specified by the challenge.

---

**Explained:**

```
func a:
    ; $a = random value in [1, 4]
    ; $1 = loop counter for quadrants
    ; $2 = final string
    ; $3 = build string
    lda 0
    sta $1

    ; Initialize $2 to an empty string
    lda ""
    sta $2

    ; Initialize $a to the random value specified above
    push 1
    push 5
    extern Random.Next(i32,i32)
    pop $a

    .lbl a
        ; Stop looping if $a == 0
        push $a
        brfalse b
        dec $a

        ; Reset $1 and $3
        push 0
        pop $1
        push ""
        pop $3

        .lbl c
            ; Stop looping if $1 == 4
            push $1
            push 4
            sub
            brfalse d
            inc $1

            ; Get a random letter in "RWSC-"
            push "RWSC-"
            push 5
            extern Random.Next(i32)
            dup
            push 1
            add
            substr

            ; Check if the letter was "-"
            dup
            push "-"
            sub
            len
            brtrue f
            ; Letter was "-"; just add the other one
            dup
            add
            br e
        .lbl f
            ; Letter was not "-"; Get the color
            push "urgbypcw"
            push 8
            extern Random.Next(i32)
            dup
            push 1
            add
            substr

            ; Add the two parts together
            add
        .lbl e
            ; Add the new piece to $3
            push $3
            swap
            add
            dup
            pop $3

            ; Check $3.  If it's "--------", generate another layer
            push "--------"
            sub
            len
            brtrue c

            ; Reset the quadrants counter and build string
            push 0
            pop $1
            push ""
            pop $3

            br c
        .lbl d
            ; Append the layer to the result
            push $2
            push $3
            add
            pop $2

            ; If $a == 0, don't add the ":"
            push $a
            brfalse a
            push $2
            push ":"
            add
            pop $2
            br a
.lbl b
    ; Print the result
    push $2
    print
    ret
end

```

---

The first run of this code produce the following shape:
`--Cp----:--RgSg--:CgRwWbRr:WyWpWwWw`

More examples of shapes generated by the code:

```
--ScWyRp
WuWuCbRg:--RbSwRc:CwRuWrCb
CgSgRpCb:Cu--SrRb
Wc--CcCg:----CrRu
SyCbWc--
SrCbSc--:----WrWb
Ry--CgSr:--Cp--Sw
--CwWpCc:CbCpRcSy:CpWw--Cy:--Ru----

```
> 1 votes

# Answer
# MathGolf, 49 bytes

```
{╘4{4{"CRSW"w"bcgpruwy"w+v¶╛æ;û--}Γy}Γ'-8*a-}↔':u

```

Try it online.

The first output was: `CwRuRrRw:RpSwSbRp:RcWpRpCu:CpWwWgWc`:

**Explanation:**

```
{ ... }↔          # Do while false without popping:
 ╘                #  Empty the stack (in case we've encountered a fully empty result)
  4{              #  Loop 4 times:
    4{            #   Inner loop 4 times:
      "CRSW"w     #    Push a random character from "CRSW"
      "bcgpruwy"w #    Push a random character from "bcgpruwy"
       +          #    Concat these two characters together
        v         #    Push a random integer in the range [-2147483648,2147483647]
         ¶╛       #    If this integer is a prime number,
           æ      #    use the following four character as inner code-block:
            ;     #     Discard the earlier character pair
             û--  #     Push "--"
     }            #   After the inner loop:
      Γ           #   Wrap the top four items into a list
       y          #   And join this list together to a single string
   }              #  After the outer loop:
    Γ             #  Wrap the top (up to) four items into a list
     '-8*a-      '#  Remove any strings consisting of 8 "-"
}↔                # After the do-while false:
  ':u            '# Join the list with ":" delimiter
                  # (after which the entire stack is output implicitly as result)

```

Compressed strings are pretty mediocre in MathGolf, so unfortunately it won't save any bytes here. `"CRSW"w` can be `╖╖`'w+wδ` which is 1 byte longer, and `"bcgpruwy"` can be `╕█≈║☺ 'ußy` which is the same byte-count.
> 1 votes

# Answer
# FMSLogo, 106 bytes

```
show bl map[word pick bf invoke[(crossmap "word ? ? ? ?)]se[--]crossmap "word[RWCS urgbycpw]":]random 1500

```

Don't try it online. The calormen.com logo interpreter does not support "templates" (which is what logo calls anonymous functions) on map, only procedure names; it's error messages also leave something to be desired. The program works in FMSLogo 8.3.2 and propably MSWLogo and UCBLogo as well, as FMSLogo is based on them.

Explaination:

* Logo is based on lisp but allows omitting parentheses around procedures that use their default arity.
* `crossmap` generates all possible combinations of the members of its inputs, which can be given in a list. The first input is a function, or "template", which is passed each combination to combine them.
* I don't know a better way to remove the empty layer yet, so the first `crossmap` generates a 1185921 element list of every possible layer and then `bf` removes the first one. That's why this program takes approximately 27 seconds to run on my laptop.
* Numbers can be coerced to strings in logo, so `map` maps the big instruction list in the middle over the characters of a random number, which has some length between one and four. `repeat 1+random 4[...]` would not output the concatenation of the results, and using `map[...]iseq random 4 4` is 4 characters longer.
* I would not be able to tell, of course, but maybe some correlation in the random number generator makes some shapes actually impossible. I am not going to investigate.

Anonymous functions can not be called the normal way, unlike in javascript for example. They must be called by `apply`, `map`, or similar, which is why I consider

```
[bl map[word pick bf invoke[(crossmap "word ? ? ? ?)]se[--]crossmap "word[RWCS urgbycpw]":]random 1500]

```

to be an invalid submission.

Alternative much faster 5 characters longer solution, which, unlike the submission, can propably produce empty output:

## FMSLogo, 111 bytes

```
show bl map[invoke[if ?="--------: ["][?]]word map[pick se[--]crossmap "word[RWCS urgbcypw]]1234 ":]random 1500

```

Sample shape: `CpCuRpSc:SwSuCcWr:Sb--RwSb` (everyone seems to do this)
> 1 votes

# Answer
# Bash, 158 bytes

```
p='eval printf %s, '
s=$($p {S,W,C,R}{u,g,b,r,y,c,p,w})--
l=`$p{$s}{$s}{$s}{$s}`
$p{$l}:{$l}:{$l}:{$l}|tr , \\n|sed -E "s/-{4}(:|$)//g;/(^|:)(:|$)/d"|shuf -n1

```

Attempt This Online!
> 1 votes

# Answer
# Wolfram Language (Mathematica), 155 bytes

```
r=RandomInteger
c=RandomChoice
t=Table
StringRiffle[StringJoin/@(Nest[#/.c@#->"--"&,#,r@2]&/@t[t[#<>#2&@@c@*Characters/@{"RWSC","urgbypcw"},4],r@3+1]),":"]

```

The distribution of the non-empty quadrants is uniform, but the distribution of shapes is not, as empty quadrants are generated after the fact.

*TIO* requires two extra bytes for symbol assignment so that the output can be printed.

Try it online!
> 1 votes

# Answer
# JavaScript (V8), ~~117 116~~ 114 bytes

```
f=(k=n=5*~R(4))=>++n?n%5?R(~k%5)?'--'+f(k+1):'SWCR'[R(4)]+'ugbrycpw'[R(8)]+f(k):':'+f(n):''
R=n=>Math.random()*n|0

```

Try it online!

If already \\$k\\$ empty in this layer, then there's \\$\frac 1{4-k}\\$ probably be not empty, aka 1 when already 3 empty
> 0 votes

---
Tags: code-golf, kolmogorov-complexity, random
---


# Question
Title: Find the submatrix with the smallest mean
You're given a **n-by-m** matrix of integers, where **n,m \> 3**. Your task is to find the **3-by-3** sub-matrix that has the lowest mean, and output this value.

**Rules and clarifications:**

* The integers will be non-negative
* Optional input and output format
* The output must be accurate up to at least 2 decimal poins (if it's non-integer)
* The submatrices must be made up of consecutive rows and columns

**Test cases:**

```
35    1    6   26   19   24
 3   32    7   21   23   25
31    9    2   22   27   20
 8   28   33   17   10   15
30    5   34   12   14   16
 4   36   29   13   18   11

Minimum mean: 14

```

---

```
100    65     2    93
  3    11    31    89
 93    15    95    65
 77    96    72    34

Minimum mean: 46.111

```

---

```
1   1   1   1   1   1   1   1
1   1   1   1   1   1   1   1
1   1   1   1   1   1   1   1
1   1   1   1   1   1   1   1

Minimum mean: 1

```

---

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

Minimum mean: 2.2222

```

This is so the shortest code in each language wins. I encourage people to post answers in languages that are already used, even if it's not shorter than the first one.

# Answer
# Jelly, ~~11~~ 9 bytes

```
+3\⁺€F÷9Ṃ

```

Saved 2 bytes thanks to @Dennis.

Try it online!

## Explanation

```
+3\⁺€F÷9Ṃ  Main link. Input: 2d matrix
+3\        Reduce overlapping sublists of size 3 by addition
   ⁺€      Repeat previous except over each row
     F     Flatten
      ÷9   Divide by 9
        Ṃ  Minimum

```
> 12 votes

# Answer
# Octave, 30 bytes

```
@(A)min(mean(im2col(A,[3,3])))

```

Try it online!
> 12 votes

# Answer
# Octave, 38 bytes

```
@(M)min(conv2(M,ones(3)/9,'valid')(:))

```
> 8 votes

# Answer
# MATL, ~~13~~ 9 bytes

```
3thYCYmX<

```

Port of @rahnema1's answer.

Try it online!

### How it works

Consider input

```
[100 65  2 93;
   3 11 31 89;
  93 15 95 65;
  77 96 72 34]

```

as an example.

```
3th   % Push [3 3]
      % STACK: [3 3]
YC    % Input matrix implicitly. Convert 3x3 sliding blocks into columns
      % STACK: [100   3  65  11;
                  3  93  11  15;
                 93  77  15  96;
                 65  11   2  31;
                 11  15  31  95;
                 15  96  95  72;
                  2  31  93  89;
                 31  95  89  65;
                 95  72  65  34]
Ym    % Mean of each column
      % STACK: [46.1111 54.7778 51.7778 56.4444]
X<    % Minimum of vector. Display implicitly
      % STACK: [46.1111]

```
> 8 votes

# Answer
# Mathematica, ~~37~~ 35 bytes

Thanks @MartinEnder for 2 bytes!

```
Min@BlockMap[Mean@*Mean,#,{3,3},1]&

```

**Explanation**

```
Min@BlockMap[Mean@*Mean,#,{3,3},1]&
    BlockMap[                    ]&  (* BlockMap function *)
                        #            (* Divide the input *)
                          {3,3}      (* Into 3x3 matrices *)
                                1    (* With offset 1 *)
             Mean@*Mean              (* And apply the Mean function twice to
                                        each submatrix *)
Min                                  (* Find the minimum value *)

```
> 7 votes

# Answer
# Python 2, ~~93~~ ~~81~~ ~~80~~ 79 bytes

```
f=lambda M:M[2:]and min(sum(sum(zip(*M[:3])[:3],()))/9,f(M[1:]),f(zip(*M)[1:]))

```

Try it online!

### How it works

**f** is a recursive function that takes a list of tuples (or any other indexable 2D iterable that represents a matrix **M**) and recursively computes the minimum of the mean of the **3×3** submatrix in the upper left corner and **f** applied recursively to **M** without its first row and **M** without its first column.

`f(M)` does the following.

* If **M** has less than three rows, `M[2:]` is an empty list, which **f** returns.

Note that, since **n \> 3** in the first run, the initial cannot cannot return an empty list.
* If **M** has three rows or more, `M[2:]` is non-empty and thus truthy, so the code to the right of `and` gets executed, returning the minimum of the three following values.

```
min(sum(sum(zip(*M[:3])[:3],()))/9

```

`M[:3]` yields the first three rows of **M**, `zip(*...)` transposes rows and columns (yielding a list of tuples), `sum(...,())` concatenates all tuples (this works because `+` is concatenation), and `sum(...)/9` computes the mean of the resulting list of nine integers.

```
f(M[1:])

```

recursively applies **f** to **M** with its first row removed.

```
f(zip(*M)[1:])

```

transposes rows and columns, removes the first row of the result (so the first column of **M**, and recursively applies **f** to the result.

Note that the previously removed layer in a recursive call will always be a row, so testing if **M** has enough rows will always be sufficient..

Finally, one may expect that some recursive calls returning `[]` would be a problem. However, in Python *2*, whenever **n** is a number and **A** is an iterable, the comparison `n < A` returns *True*, so computing the minimum of one or more numbers and one or more iterables will always return the lowest number.
> 5 votes

# Answer
# , 21 bytes

```
[:<./@,9%~3+/\3+/\"1]

```

Try it online!

The proper way to operate on subarrays in J is to use the third (`_3`) form of cut `;.` where `x (u;._3) y` means to apply verb `u` on each full subarray of size `x` of array `y`. A solution using that requires only 1 more byte but will be much more efficient on larger arrays.

```
[:<./@,9%~3 3+/@,;._3]

```

Try it online!

## Explanation

```
[:<./@,9%~3+/\3+/\"1]  Input: 2d array M
                    ]  Identity. Get M
                  "1   For each row
              3  \       For each overlapping sublist of size 3
               +/          Reduce by addition
          3  \         For each overlapping 2d array of height 3
           +/            Reduce by addition
       9%~             Divide by 9
[:    ,                Flatten it
  <./@                 Reduce by minimum

```
> 5 votes

# Answer
# Jelly, 18 bytes

*Missed the trick, as used by miles in their answer, of using an n-wise cumulative reduce of addition - the whole first line can be replaced with `+3\` for 11.*

```
ẆµL=3µÐfS€
ÇÇ€FṂ÷9

```

Try it online!

Traverses all contiguous sublists, filters to keep only those of length 3 and sums (which vectorises) then repeats for each resulting list, to get the sums of all 3 by 3 sub-matrices and finally flattens those into one list, takes the minimum and divides by 9 (the number of elements making this minimal sum).
> 2 votes

# Answer
# Pyth, 19 bytes

```
chSsMsMs.:R3C.:R3Q9

```

A program that takes input of a list of lists and prints the result.

Test suite

**How it works**

*\[Explanation coming later\]*
> 2 votes

# Answer
# Haskell, 87 bytes

```
import Data.List
t(a:b:c:d)=a+b+c:t(b:c:d);t _=[]
s=(/9).minimum.(t=<<).transpose.map t

```

Try it online!
> 2 votes

# Answer
# Uiua, 14 bytes

```
÷9/↧♭⍥(/+⍉◫3)2

```

Try it!

```
÷9/↧♭⍥(/+⍉◫3)2    input: a matrix of shape RxC
      ⍥(      )2    repeat twice:
             ◫3      windows of 3; shape (R-2)x3xC
           ⍉        transpose (rotate axes once); shape 3xCx(R-2)
         /+          sum over the length-3 axis; shape Cx(R-2)
             ◫3      windows of 3; shape (C-2)x3x(R-2)
           ⍉        transpose (rotate axes once); shape 3x(R-2)x(C-2)
         /+          sum over the length-3 axis; shape (R-2)x(C-2)
÷9/↧♭               minimum of all elements divided by 9

```

# Uiua, 14 bytes

```
÷9/↧♭/+/+◫-2△.

```

Try it!

```
÷9/↧♭/+/+◫-2△.    input: a matrix of shape RxC
           -2△     subtract 2 from the shape; [R-2, C-2]
          ◫   .    2D windows of that size; gives 3x3x(R-2)x(C-2) array
      /+/+          sum over the first two axes
÷9/↧♭              minimum of all elements divided by 9

```
> 2 votes

# Answer
## JavaScript (ES6), ~~107~~ ~~98~~ 96 bytes

A function that computes the sums of triplets over the rows and then calls itself to do the same thing over the columns, keeping track of the minimum value `M`.

```
f=m=>m.map((r,y)=>r.map((v,x)=>M=(z[x<<9|y]=v+=r[x+1]+r[x+2])<M?v:M),z=[M=1/0])&&m[1]?f([z]):M/9

```

JS is a bit verbose for that kind of stuff and lacks a native `zip()` method. It took me quite a lot of time to save just a dozen bytes over a more naive approach. (Yet, a shorter method probably exists.)

### Non-recursive version, 103 bytes

*Saved 2 bytes with the help of Neil*

```
m=>m.map((r,y)=>y>1?r.map((v,x)=>[..."12345678"].map(i=>v+=m[y-i%3][x+i/3|0])&&(M=v<M?v:M)):M=1/0)&&M/9

```

### Test cases

```
f=m=>m.map((r,y)=>r.map((v,x)=>M=(z[x<<9|y]=v+=r[x+1]+r[x+2])<M?v:M),z=[M=1/0])&&m[1]?f([z]):M/9

console.log(f([
  [ 35,  1,  6, 26, 19, 24 ],
  [  3, 32,  7, 21, 23, 25 ],
  [ 31,  9,  2, 22, 27, 20 ],
  [  8, 28, 33, 17, 10, 15 ],
  [ 30,  5, 34, 12, 14, 16 ],
  [  4, 36, 29, 13, 18, 11 ]
]));

console.log(f([
  [ 100, 65,  2, 93 ],
  [   3, 11, 31, 89 ],
  [  93, 15, 95, 65 ],
  [  77, 96, 72, 34 ]
]));

console.log(f([
  [ 1, 1, 1, 1, 1, 1, 1, 1 ],
  [ 1, 1, 1, 1, 1, 1, 1, 1 ],
  [ 1, 1, 1, 1, 1, 1, 1, 1 ],
  [ 1, 1, 1, 1, 1, 1, 1, 1 ]
]));

console.log(f([
  [ 4, 0, 0, 5, 4 ],
  [ 4, 5, 8, 4, 1 ],
  [ 1, 4, 9, 3, 1 ],
  [ 0, 0, 1, 3, 9 ],
  [ 0, 3, 2, 4, 8 ],
  [ 4, 9, 5, 9, 6 ],
  [ 1, 8, 7, 2, 7 ],
  [ 2, 1, 3, 7, 9 ]
]));
```
> 1 votes

# Answer
# Python 3, ~~111~~ 103 bytes

```
lambda m,r=range:min(sum(sum(m[y+i][x:x+3])for i in r(3))/9for x in r(len(m[0])-3)for y in r(len(m)-3))

```

Try it online!
> 1 votes

# Answer
# Python 2, 96 bytes

```
h=lambda a:[map(sum,zip(*s))for s in zip(a,a[1:],a[2:])]
lambda a:min(map(min,h(zip(*h(a)))))/9.

```

Test cases at **Repl.it**

An unnamed function taking a list of lists, `a` \- the rows of the matrix.

The helper function `h` zips through three adjacent slices, and maps the sum function across the transpose, `zip(*s)`, of each. This results in summing all height three slices of single columns.

The unnamed function calls the helper function, transposes and calls the helper function again on the result, then finds the minimum of each and the minimum of the result, which it then divides by `9.` to yield the average.
> 1 votes

# Answer
# 05AB1E, ~~21~~ 16 bytes

```
2FvyŒ3ùO})ø}˜9/W

```

Try it online!

**Explanation**

```
2F         }       # 2 times do:
  v     }          # for each row in the matrix
   yŒ3ù            # get all sublists of size 3
       O           # reduce by addition
         )ø        # transpose matrix
            ˜      # flatten the matrix to a list
             9/    # divide each by 9
               W   # get the minimum

```
> 1 votes

# Answer
# Uiua, ~~17~~ 16 bytes

```
÷9/↧♭≡≡(/+♭)◫3_3

```

Try it!

-1 thanks to alephalpha

```
÷9/↧♭≡≡(/+♭)◫3_3
            ◫3_3  # 3x3 windows
     ≡≡(   )      # map function to each matrix in 4D array
          ♭       # deshape
        /+        # sum
    ♭             # deshape
  /↧              # minimum
÷9                # divide by 9

```
> 1 votes

# Answer
# Nekomata, 10 bytes

```
2ᵑ{q3Lµ}aṁ

```

Attempt This Online!

```
2ᵑ{q3Lµ}aṁ
2ᵑ{    }        Apply the following function twice
   q                Choose a contiguous subsequence
    3L              of length 3
      µ             Take its mean
        aṁ      Minimum of all possible results

```
> 1 votes

# Answer
# K (ngn/k), ~~21~~ ~~20~~ 17 bytes

Port of @miles' J solution

-3 thanks to @Bubbler

```
1%9%&//2(+3+/':)/

```

Try it online!
> 1 votes

# Answer
# , 78 bytes

```
\(m,l=nrow(m))min(mapply(\(x,y)mean(m[x-0:2,y-0:2]),3:l,y=rep(3:ncol(m),l-2)))

```

Try it online!
> 1 votes

# Answer
# Vyxal, 10 bytes

```
2(3lvṁ∩)fg

```

Try it Online!

```
2(     )   # Twice
  3l       # Take sliding windows of length 3
    vṁ     # Take the mean of each window
      ∩    # Transpose
        fg # Flatten and take the minimum

```
> 1 votes

# Answer
# Scala, 142 bytes

Golfed version. Try it online!

```
M=>if(M.size<3||M(0).size<3)Double.MaxValue else List((0 to 2).flatMap(i=>(0 to 2).map(j=>M(i)(j))).sum/9.0,f(M.tail),f(M.transpose.tail)).min

```

Ungolfed version. Try it online!

```
object Main {

  def f(M: List[List[Int]]): Double = {
    if (M.length < 3 || M.head.length < 3) Double.MaxValue
    else {
      val minSubMatrix = (0 until 3).flatMap(i => (0 until 3).map(j => M(i)(j))).sum / 9.0
      List(minSubMatrix, f(M.tail), f(M.transpose.tail)).min
    }
  }

  def main(args: Array[String]): Unit = {
    val M = List(List(100, 65, 2, 93), List(3, 11, 31, 89), List(93, 15, 95, 65), List(77, 96, 72, 34))
    println(f(M))
  }
}

```
> 0 votes

---
Tags: code-golf, math, matrix
---


title: Generate this number table

text:
# Question
Title: Generate this number table
Given an integer \\$1 \< n \< 10 \\$ generate a table like below.

For \\$n = 5\\$,

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

```

For \\$n = 8\\$,

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

```

Shortest code wins! Trailing whitespace allowed

Output format isn't strict, you can output a 2D list/matrix in any reasonable format.

# Answer
> 15 votes
# Jelly, 2 bytes

```
»þ

```

Try it online!

Outputs an `n x n` matrix. If the output format is required, 4 bytes

This is simply a table of maximums. For each cell \\$A\_{i,j}\\$ in the output, the result is equal to \\$\max(i,j)\\$. The 4 byte answer has ``` to reuse the argument, and `G` to format the output as a grid.

# Answer
> 8 votes
# APL (Dyalog Unicode), 5 bytes (SBCS)

Anonymous tacit prefix function.

```
∘.⌈⍨⍳

```

Try it online!

`∘.⌈⍨` maximum-table for

**i**ntegers 1 through the argument

# Answer
> 7 votes
# Factor, 35 bytes

```
[ [1,b] dup [ max ] cartesian-map ]

```

Try it online!

`cartesian-map` Takes two sequences (in this case, both are \[1, n\]) and applies a quotation to each pair of elements, resulting in a matrix. In effect, we are mapping `max` over a coordinate matrix.

# Answer
> 7 votes
# Wolfram Language (Mathematica), 16 bytes

```
Max~Array~{#,#}&

```

Try it online!

# Answer
> 6 votes
## \<\>^v, ~~93~~ 89 bytes

```
i,tTv
v`j1<
>I)iIT‹!0jv
 v        <
 >J)jJI≥v_~ v
        >~  v
 ^  v≤TJ<\23<
    `
^   <

```

##### Explanation

`i` pops the top of the stack (by default 0) and stores it into the variable `i`. `,` reads an integer from stdin, then `t` pops it and stores it into variable `t`. `T` pushes to the stack the value of the variable `t` and `v` redirects the intruction pointer towards the end of the next line. `<` tells the instruction pointer to go left. `1` pushes 1 onto the stack and `j` stores it into the variable `j`, and ``` prints a newline. Then `v` and `>` sends the instruction towards the right on the next line. `I` pushes the variable `i`'s value onto the stack, `)` increments it, `i` takes it and puts it into `i`, `I` pushes the value of `i` onto the stack and `T` brings onto the stack the number that was previously read to stdin.  compares them and terminates the program if the grid has finished printing. Then it initializes `j` to 0 and sends the instruction pointer into a loop that increments `j`, then prints a space (`\23` (pointer is currently going left, that's why it is reversed) pushes 32 (ASCII id of " ") and prints it) (`32\` is used instead of `" "~` because it is one character shorter), prints `j` if `j` is lower than `i`, or else prints `i`. When `j` is greater or equal to `t`, it exits the loop, prints a new line and goes back into the outer loop.

In the code, the `t` variable contains the number read from stdin, `i` is the current line number, and `j` is the current character number.

run online

# Answer
> 5 votes
# , 9 bytes

```
1+>./~@i.

```

Try it online!

## Explanation

```
1+>./~@i.    input: n
       i.    range from 0 to n-1 inclusive
    /~       table:
  >.            max(n, n)
1+           add 1 to each

```

# Answer
> 5 votes
# Octave, 19 bytes

```
@(n)max([1:n]',1:n)

```

Try it online!

# Answer
> 4 votes
# , 30 bytes

```
function(n)outer(1:n,1:n,pmax)

```

Try it online!

# Answer
> 4 votes
# Stax, 3 bytes

```
╗ìΦ

```

Run and debug it

# Answer
> 4 votes
# PowerShell Core, 40 bytes

```
param($a)1..$a|%{"$(,$_*($_-1)+$_..$a)"}

```

Try it online!

# Answer
> 4 votes
# Python 3, 49 bytes

```
f=lambda x:x*[x]and[a+[x]for a in f(x-1)]+[[x]*x]

```

Try it online!

# Answer
> 4 votes
# Vyxal, 6 bytes

```
ƛ£⁰ƛ¥∴

```

Try it Online! Returns an array of arrays

```
ƛ      # (1...input) Map...
 £     # Push to register
  ⁰ƛ   # (1...input) Map...
    ¥  # Register
     ∴ # Maximum of the two

```

Or, for grid output, 10 bytes:

```
ƛ£⁰ƛ¥∴;Ṅ;⁋

```

Try it Online!

```
ƛ       ;  # (1...input) Map...
 £         # Push to register
  ⁰ƛ  ;    # (1...input) Map...
    ¥      # Push register
     ∴     # Max
       Ṅ   # Joined by spaces
         ⁋ # Joined by newlines.

```

# Answer
> 4 votes
# Python 2, 48 bytes

```
r=range(1,input()+1)
for x in r:print[x]*x+r[x:]

```

Try it online!

Prints a list for each row.

# Answer
> 3 votes
# Julia, 19 bytes

```
!n=max.((1:n)',1:n)

```

Try it online!

# Answer
> 3 votes
# K (ngn/k), 10 bytes

```
{x|\x}1+!:

```

Try it online!

Somewhat surprisingly, using a seeded scan `x|\x` returns the same results as an each-right (`x|/:x`) or each-left (`x|\:x`).

* `1+!:` generate `1..n` from the (implicit) input
* `{x|\x}` set up a scan, seeded with the input, run over the input

# Answer
> 3 votes
# C# (Visual C# Interactive Compiler), 70 bytes

```
a => new int[a][].Select((x,p)=>new int[a].Select((y,q)=>p>q?p+1:q+1))

```

I'm sure there is a shorter way to do this, but I can't find it.

Try it online!

# Answer
> 3 votes
# TI-Basic, ~~38~~ 41 bytes

```
Input N
identity(N→[A]
For(I,1,N
For(J,1,N
max(I,J→[A](I,J
End
End
[A]

```

Output is stored as a matrix in `Ans` and is displayed.

# Answer
> 3 votes
# Rust, 84 bytes

```
|n|(1..=n).fold("".into(),|a,i|(1..=n).fold(a,|b,j|format!("{}{} ",b,i.max(j)))+"
")

```

Try it online!

The output will be a `String`. The newline is given literally inside quotes, which saves one byte.

# Answer
> 2 votes
# Japt, 5 bytes

Outputs a 2D-array.

```
õ@õwX

```

Try it

```
õ@õwX     :Implicit input of integer U
õ         :Range [1,U]
 @        :Map each X
  õ       :  Range [1,U]
   wX     :  Max of each with X

```

Or, if outputting a 1D-array is allowed:

# Japt, 4 bytes

```
õ ïw

```

Try it

```
õ ïw     :Implicit input of integer U
õ        :Range [1,U]
  ï      :Cartesian product with itself
   w     :Reduce each pair by Max

```

# Answer
> 2 votes
# JavaScript (Node.js), 56 bytes

```
n=>[...Array(n)].map((_,x,a)=>a.map((_,y)=>x>y++?-~x:y))

```

Try it online!

Outputs an array of arrays.

Thanks to Shaggy for -5 bytes

Thanks to Arnauld for further -2 bytes

# JavaScript (Node.js), 71 bytes

```
n=>[...Array(n)].map((_,x,a)=>a.map((_,y)=>x>y++?-~x:y).join``).join`
`

```

Try it online!

Outputs string

## History

```
n=>[...Array(n)].map((_,x,a)=>a.map((_,y)=>-~x>++y?-~x:y)) // 58

n=>[...m=Array(n)].map((_,a)=>[...m].map((_,b)=>-~a>++b?-~a:b)) // 63

n=>[...(m=Array(n))].map((_,a)=>[...m].map((_,b)=>-~a>++b?-~a:b)) // 65

n=>[...(m=Array(n)).keys()].map(a=>[...m.keys()].map(b=>-~a>++b?-~a:b)) // 71

```

# Answer
> 2 votes
# C (gcc), 65 bytes

```
i,j;f(n){for(i=1;n/i;)printf(j/n?j=!++i,"%d\n":"%d ",i>++j?i:j);}

```

Try it online!

# Answer
> 2 votes
# Ruby, 35 bytes

```
->x{(1..x).map{|y|[y]*y+[*y+1..x]}}

```

Try it online!

# Answer
> 2 votes
# 05AB1E, 6 bytes

```
Lã€àsä

```

Try it online! Outputs as a 2D list. Link includes a footer to format the output.

```
Lã€àsä  # full program
  €     # list of...
   à    # maximum...
  €     # s...
   à    # of...
  €     # each element of...
 ã      # list of distinct combinations of two elements in...
L       # [1, 2, 3, ...,
        # ..., implicit input...
L       # ]...
 ã      # repeated twice...
     ä  # split into pieces of length...
    s   # implicit input
        # implicit output

```

# Answer
> 2 votes
# Haskell, 28 bytes

```
f n=(<$>[1..n]).max<$>[1..n]

```

Try it online!

Generates each row by taking the max of each element of `[1..n]` and a fixed value equal to the row number.

```
map(max 3)[1,2,3,4,5] = [3,3,3,4,5]

```

We use `<$>` as an infix synonym for `map`.

It would be nice to reuse the `<$>[1..n]`, but it runs into type-checking issues

**26 bytes, doesn't work**

```
f n|q<-(<$>[1..n])=q$q.max

```

Try it online!

If a 1D output is allowed, we can do:

**25 bytes**

```
f n=max<$>[1..n]<*>[1..n]

```

Try it online!

# Answer
> 2 votes
# Python 3, 67 bytes

```
lambda n:[print(*(max(y,x)+1 for y in range(n))) for x in range(n)]

```

Try it online!

# Answer
> 2 votes
# Python 3, ~~51~~ 49 bytes

```
lambda n:mgrid[:n,:n].max(0)+1
from numpy import*

```

Try it online!

# Answer
> 2 votes
# T-SQL (277 bytes)

Not sure how inputs are handled in SQL but my first declared parameter is the input. I also can't get an online T-SQL compiler that runs this. But this will run in your SSMS just fine.

```
DECLARE @a int = 7DECLARE @ int=1DECLARE @c int=1DECLARE @b nvarchar(max)='SELECT'WHILE @<=@a BEGIN
SET @c=1WHILE @c<=@a BEGIN
SET @b+=IIF(@c=1,'',',')+STR(IIF(@c<@,@,@c))+'AS['+STR(@c)+']'SET @c+=1
END
SET @b+=IIF(@<@a,'UNION ALL SELECT','')SET @+=1
END
EXEC sp_executesql @b;

```

It's a naive approach with nothing special, except that it dynamically builds up a query.

The query it generates is:

```
SELECT         1AS[         1],         2AS[         2],         3AS[         3]UNION ALL SELECT         2AS[         1],         2AS[         2],         3AS[         3]UNION ALL SELECT         3AS[         1],         3AS[         2],         3AS[         3]

```

# Answer
> 2 votes
# Regenerate, 80 bytes

```
((${$2+1}|1)( $2){$2-1}( ${$4+1}{1-$4/$~1}| ${$2+1}{1-$2/$~1}){$~1-$2+1}\n){$~1}

```

Takes the argument from the command-line. Try it here!

### Explanation

(Spaces are replaced with underscores to improve visibility.)

Each line is generated in three parts. Top-level structure:

```
(                           )       Group 1: a line of output
 (...)                               Group 2: the first digit
      (...){...}                     Group 3: repetitions of the first digit
                (...){...}           Group 4: count up to N
                          \n         Add a newline
                             {$~1}  Repeat, generating N lines

```

Group 2, the first digit on each line:

```
(         )
 ${$2+1}     Add 1 to the previous value of group 2
        |    Or, if group 2 has not been previously matched...
         1   Use 1

```

Group 3, the rest of the digits on the line that are identical to the first number:

```
(_$2)        The most recent value of group 2 (with a space in front of it)
     {$2-1}  repeated (group 2) - 1 times

```

Group 4, the remaining numbers on the line, starting with (group 2) + 1 and counting up to N:

```
( ${$4+1}{1-$4/$~1}| ${$2+1}{1-$2/$~1}){$~1-$2+1}
(                                     )
 _                                                 Space
  ${$4+1}                                          Previous value of group 4, plus 1
         {        }                                Repeat the value this many times:
            $4/$~1                                  1 if group 4 == N, 0 otherwise
          1-                                        Subtract from 1: 1 -> 0 and 0 -> 1
                                                   So if the new value would have been N+1,
                                                   it instead becomes empty string
                   |                               If the previous value of group 4 was not
                                                   a number, the arithmetic fails, and we
                                                   instead use...
                    _                              Space
                     ${$2+1}                       Last value of group 2, plus 1
                            {1-$2/$~1}             Repeat 0 times if group 2 == N
                                       {        }  Repeat the above
                                        $~1-$2+1   N - (group 2) + 1 times

```

### Worked example

Suppose the input is 3.

**Line 1:**

* Group 2: not previously matched, so `1`
* Group 3:  `1` repeated `1-1` = 0 times, so empty string
* Group 4 is repeated `3-1+1` = 3 times:
    1. Group 4 not previously matched, so  followed by `2` repeated `1-1/3` = 1 time (the division is integer division)
    2. Previous value of group 4 is  `2`, so  followed by `3` repeated `1-2/3` = 1 time
    3. Previous value of group 4 is  `3`, so  followed by `4` repeated `1-3/3` = 0 times

Result: `1 2 3`

**Line 2:**

* Group 2: previous value is `1`, so `2`
* Group 3:  `2` repeated `2-1` = 1 time
* Group 4 is repeated `3-2+1` = 2 times:
    1. Previous value of group 4 is , which is not a number, so  followed by `3` repeated `1-2/3` = 1 time
    2. Previous value of group 4 is  `3`, so  followed by `4` repeated `1-3/3` = 0 times

Result: `2 2 3`

**Line 3:**

* Group 2: previous value is `2`, so `3`
* Group 3:  `3` repeated `3-1` = 2 times
* Group 4 is repeated `3-3+1` = 1 time:
    1. Previous value of group 4 is , which is not a number, so  followed by `4` repeated `1-3/3` = 0 times

Result: `3 3 3`

# Answer
> 2 votes
# Nim, ~~138~~ 122 bytes

```
proc x(i:int)=
  for x in 1..i:
    for j in 1..x:stdout.write($x&" ")
    for j in x+1..i:stdout.write($j&" ")
    echo()

```

# Answer
> 2 votes
# ayr, 5 bytes

```
^:\`~

```

# Explained

```
    ~  One-range to N
   `   Commute (copy arg to make next symbol dyadic)
  \    Table
^:      Of maxes

```

# Answer
> 2 votes
# Excel VBA, ~~45~~ 44 bytes

Saved 1 bytes thanks to Taylor Raine because of course. At least now it's my favorite number of bytes.

```
[A1].Resize([A1],[A1])="=Max(Row(),Column())"

```

Input is in the cell `A1` of the active sheet. Program is run from the immediate window. It works by writing a formula into a range of cells. This will also overwrite the input cell with a formula.

# Answer
> 2 votes
# JavaScript (Node.js), 75 bytes

Not the best JS solution for a string output, but really close!
I tried to gain bytes by parsing only a single one-dimensional array, but lost some bytes in calculations, and i don't find how to shorten it further.

```
n=>[...Array(n*n)].map((_,i)=>Math.max(i%n,i/n|0)+1+(++i%n?' ':`
`)).join``

```

Try it online!

# Answer
> 2 votes
# Perl 5, 39 bytes

```
//,say map{$",$_<$'?$':$_}@;for@;=1..<>

```

Try it online!

# Answer
> 1 votes
# APL (Dyalog Unicode), 11 bytes

```
{(⍳⍵)∘.⌈⍳⍵}

```

Anonymous prefix function

-2 bytes thanks to @Adam in chat

# Answer
> 1 votes
# Vyxal, 15 bytes

```
ɾƛnS:I*fvI⁰ɾnȯJ

```

Try it Online!

Wish if we had maximum table....

# Answer
> 1 votes
# Posix SH + sed, ~~99~~ ~~97~~ 96 bytes

```
seq -s\  $1|sed -nE ':t
p
s/((.)( \2)*) (.)/\1=\4/
/(.)=\1/q
:r
s/ ?(.)=(.)/=\2 \2/
tr
s/=//
tt'

```

or, 99 bytes with looping (ugh):

```
seq -s\  $1|sed -nE ':t
p
s/(.) /\1=/
:l
s/(.)=\1 ?/\1 \1=/
tl
:r
s/ ?(.)=(.)/=\2 \2/
tr
s/^=//
tt'

```

With an earlier gnu sed version, `:t` and `tt` can be replaced with `:` and `t`, respectively, saving two bytes for each solution (I think).

Takes input in `$1`. Outputs exactly as in the question (but with a trailing newline I think).

## Explanation

```
seq -s\  $1       \  # Collect the numbers 1..$1 with space as
                  \  # the -separator.
  |sed -nE '...'     # Replace it. The -E is for -Extended Regular
                     # Expressions, which allow less escaping.
                     # The -n is for -no printing by default.

```

```
:t                          # Label for "t"op.
p                           # "p"rint the line.
s/((.)( \2)*) (.)/\1=\4/    # Mark the end of the first run of
                            # equal elements followed by a number.
                            #    4 4 4 4 5 6 7 8 9
                            # => 4 4 4 4=5 6 7 8 9
                            #    9 9 9 9 9 9 9 9 9
                            # => 9 9 9 9 9 9 9 9=9
/(.)=\1/q                   # If the marked element and its successor
                            # are the same (like in the example above
                            # with all nines), "q"uit, don't process
                            # any more lines.
:r                          # Start "r"eplacement loop.
s/ ?(.)=(.)/=\2 \2/         # For any characters a, b, replace a=b
                            # with =b b. examples:
                            #    4 4 4 4=5 6 7 8 9
                            # => 4 4 4=5 5 6 7 8 9
                            # => 4 4=5 5 5 6 7 8 9
tr                          # "t"est if there was a replacement made.
                            # if there was, do another replacement
                            # loop iteration.
s/=//                       # At this point, the cursor must have
                            # reached the beginning of the line
                            # so no replacement could be made.
                            # Remove the =
tt                          # Go to the top again, where this row
                            # will be printed, and a new one will be
                            # started.

```

# Answer
> 1 votes
# C (clang), ~~75~~ 77 bytes

Added 2 bytes for a bug fix kindly provided by dingledooper.

```
i;j;k;f(n){for(i=0;n/++i;puts(""))for(j=i,k=0;n/++k;j+=k>=i)printf("%d ",j);}

```

Try it online!

# Answer
> 1 votes
# Charcoal, 11 bytes

```
ＮθＥθ⭆θ⊕⌈⟦ιλ

```

Try it online! Link is to verbose version of code. Explanation:

```
Ｎθ          First input as an integer
   θ        Input
  Ｅ         Map over implicit range (0-indexed)
     θ      Input
    ⭆       Map over implicit range and join
         ι  Outer index
          λ Inner index
       ⌈⟦   Maximum of all of the above
      ⊕     Incremented
            Implicitly print

```

Would be 14 bytes if spacing was desired (13 bytes if a leading space was acceptable).

# Answer
> 1 votes
# Java (JDK), 84 bytes

```
n->{for(int i=0;i<n*n;)System.out.printf("%d%c",i%n>i/n?i%n+1:i/n+1,++i%n<1?13:32);}

```

Try it online!

## Alternative, 84 bytes too

```
n->{for(int i=1,j=0;i<=n;)System.out.printf("%d%c",i>++j?i:j,(j%=n)<1?13+i-i++:32);}

```

Try it online!

# Answer
> 1 votes
# Husk, 4 bytes

```
´ṪYḣ

```

Try it online!

Outputs as a 2d matrix.

```
´       # argdup: apply a funciton to two copies of the same argument
 Ṫ      # Ṫable: make a 'multiplication table' ...
  Y     # ... using function Y = maximum of two values
   ḣ    # with (duplicated) argument ḣ = range from 1 to input number

```

7 bytes \- `¶mw´ṪYḣ` \- to ouput in the exact same format as the examples in the question.

# Answer
> 1 votes
# PHP -F, ~~80~~ 69 bytes

```
for(;++$i<=$argn;)echo str_pad('',$i-1,$i).join(range($i,$argn))."
";

```

Try it online!

Quite naive solution, but I think it can be golfed more..

**EDIT:** saved 11 bytes by having a shorter `str_pad` so that the `join(range(` is no longer conditional

# Answer
> 1 votes
# Python, 52 bytes

```
lambda a="123456789":[a[n]*n+a[n:]for n in range(9)]

```

Try it online!

# Answer
> 1 votes
# Pari/GP, 26 bytes

```
n->matrix(n,,i,j,max(i,j))

```

Try it online!

# Answer
> 1 votes
# Vyxal 2.6.0 `r`, 4 bytes

```
ẊvGẇ

```

Try it Online!

Feels good to have Cartesian product use ranges for numbers now. Posting as a separate answer to emanresuA because it uses features not available in the version they used (haha rewrite go brrr).

## Explained

```
ẊvGẇ
Ẋ    # The Cartesian Product of the ranges [1, input] and [1, input]
 vG  # the maximum of each pair
   ẇ # wrapped to chunks of length input

```

# Answer
> 1 votes
# Pyth, 12 bytes

```
VSQm?>dNdNSQ

```

Try it online!

# Answer
> 1 votes
# Excel (Office 365 Insider Preview), 38 bytes

An anonymous worksheet function that takes input \\$n\\$ from cell `A1` and outputs an \\$n\times n\\$ dynamic array to the calling cell.

This solution makes use of the `=MAKEARRAY()` and `=LAMBDA()` functions, which are currently only available via the Office Insiders program.

```
=MakeArray(A1,A1,Lambda(r,c,Max(r,c)))

```

### Annotated

```
=MakeArray(A1,A1,                    ) ' Make an nxn array holding row & col index
                 Lambda(r,c,        )  ' Pass the indices into a function
                            Max(r,c)   ' Take the larger of two at each position
                                       ' Output as nxn dynamic array

```

# Answer
> 1 votes
# Thunno 2, 4 bytes

```
RDȷ§

```

Try it online!

#### Explanation

```
RDȷ§  # Implicit input
R     # Push [1..input]
 D    # Duplicate
  ȷ   # Outer product over:
   §  #  Dyadic maximum
      # Implicit output

```

# Answer
> 1 votes
# Uiua, 6 bytes

```
⊞↥.+1⇡

```

Try it!

```
⊞↥.+1⇡
     ⇡  # range
   +1   # increment
  .     # duplicate
⊞↥      # table by maximum

```

# Answer
> 1 votes
# Vyxal, 2 bytes

```
ǒ∴

```

Try it Online!

> Wish if we had maximum table....

Wish no more!

Quite literally table by maximum

# Answer
> 1 votes
# RProgN 2, 16 bytes

```
x=x«y=x²yMS•.p»;

```

## Explaination

```
x=x«y=x²yMS•.p»;
x=               # Set x to the input
  x«          »; # For 1 - x
    y=           # Assign y to the iterator
      x²  S      # Generate a stack from a pair-function
        yM       # The max of y and the current index
           •.p  # Join via spaces, and print

```

Try it online!

# Answer
> 1 votes
# JavaScript (Node.js), 52 bytes

```
n=>(g=(i,j)=>i?[...g(i-1,j),j?i<j?j:i:g(n,i)]:[])(n)

```

Try it online!

---

# JavaScript (Node.js), 55 bytes

```
n=>[...Array(n)].map((_,x,a)=>a.map((_,y)=>1+(x+=y>x)))

```

Try it online!

From user100752(deleted)'s answer

Alternate

# Answer
> 0 votes
# Python 2, 50 bytes

```
lambda x:[[i+1]*i+range(i+1,x+1)for i in range(x)]

```

Try it online!

-2 bytes thanks to dingledooper

# Answer
> 0 votes
# JavaScript (Node.js), 85 bytes

```
n=>[...(A=Array)(n)].map((_,i)=>[...A(i++).fill(i),...[...A(n-i+1)].map((u,j)=>i+j)])

```

Try it online!

In the form of an array. Since JS doesn't have the convenient `list.__mul__` and `list.__add__` operations, this takes up quite some space.

---

# JavaScript (Node.js), 90 bytes

```
f=(n,i=0)=>n-i?`${i+1} `.repeat(i)+[...Array(n-i++)].map((_,j)=>i+j).join` `+`
`+f(n,i):''

```

Try it online!

As a string.

---

# Answer
> 0 votes
# Arturo, 36 bytes

```
$[n][map 1..n'x[++repeat x x-1x..n]]

```

Try it

```
$[n][               ; a function taking an argument n
  map 1..n'x[       ; map over the range 1..n; assign current value to x
    ++              ; append
    repeat x x-1    ; a block containing x x-1 times
    x..n            ; the range x..n
  ]                 ; end map
]                   ; end function

```

# Answer
> 0 votes
# Perl 5 \+ `-M5.10.0 -na`, 37 bytes

```
$,=$";say+($_)x$_,$_+1.."@F"for 1..$_
```

Try it online!

---
Tags: code-golf, integer, matrix
---


title: Golf Transmission

text:
# Question
Title: Golf Transmission
As in, the 5 speed transmission from the original VW Golf GTI.

Print the transmission pattern in as few bytes as possible.

Yes I know this isn't what it actually looks like but the GTI 5 speed shift knob pattern is a lot worse.

```
1  3  5
|  |  |
|--|--|
|  |  |
2  4  R

```

# Answer
> 9 votes
# Japt, 25 bytes

```
7Ç%3?-:°U+'|³+°UÃ·û Õr6'R

```

Test it

~~Japt beatsties with Jelly!~~ The Jelly submission has improved a lot, but unfortunately I don’t think this solution can.

I'll explain this part by part as it's a bit hard to visualize without seeing the in-between results.

```
7Ç%3?-:°U+'|³+°UÃ·
7Ç                  # For each number from 0 to 6:
  %3                #   Take it modulo 3.
    ?-              #   If it's truthy (nonzero), return a dash "-".
      :             #   Otherwise:
       °U           #     Increment variable U (starts at zero).
         +'|³       #     Append "|" three times.
             +°U    #     Append U incremented again.
                Ã   # End map over range.
                 ·  # Join this list on newlines.

```

Created with the help of Luminespire.

This gives:

```
1|||2
-
-
3|||4
-
-
5|||6

```

Next, `û` centers each line:

```
1|||2
  -
  -
3|||4
  -
  -
5|||6

```

And `Õ` transposes the rows and columns:

```
1  3  5
|  |  |
|--|--|
|  |  |
2  4  6

```

Finally, `r6'R` replaces the final 6 with "R" to get the proper image:

```
1  3  5
|  |  |
|--|--|
|  |  |
2  4  R

```

# Answer
> 6 votes
# Jelly,  ~~26 25~~  24 bytes

-1 thanks to Unrelated String!

```
6s2j€”|$⁺Zj"⁾ -KŒBḤ¤YṖ”R

```

A full program that prints.

**Try it online!**

### How?

```
6s2j€”|$⁺Zj"⁾ -KŒBḤ¤YṖ”R - Main Link: no arguments
6                        - six
 s2                      - split into twos     -> [[1,2],[3,4],[5,6]]
   j€”|$                 - join each with '|'  -> [[1,'|',2],[3,'|',4],[5,'|',6]]
        ⁺                - repeat that         -> [[1,'|','|','|',2],[3,'|','|','|',4],[5,'|','|','|',6]]
         Z               - transpose           -> [[1,3,5],['|','|','|'],['|','|','|'],['|','|','|'],[2,4,6]]
                   ¤     - nilad followed by link(s) as a nilad:
            ⁾ -          -   [' ', '-']          -> [' ','-']
               K         -   join with spaces    -> [' ',' ','-']
                ŒB       -   bounce              -> [' ',' ','-',' ',' ']
                  Ḥ      -   double (vectorises) -> ["  ","  ","--","  ","  "]
                            - (multiplying each character by 2 in Python)
           "             - zip with:
          j              -   join              -> [[1,"  ",3,"  ",5],['|',"  ",'|',"  ",'|'],['|',"--",'|',"--",'|'],['|',"  ",'|',"  ",'|'],[2,"  ",4,"  ",6]]
                    Y    - join with newlines  -> [1,"  ",3,"  ",5,'\n','|',"  ",'|',"  ",'|','\n','|',"--",'|',"--",'|','\n','|',"  ",'|',"  ",'|','\n',2,"  ",4,"  ",6]
                     Ṗ   - pop (remove the 6)
                         - implicit, smashing print
                      ”R - 'R'
                         - implicit print

```

# Answer
> 5 votes
# Charcoal, 20 bytes

```
⁶⸿⸿↑Ｅ⪪2143R5²⟦⟦⪫ι|||

```

Try it online! Link is to verbose version of code. Explanation:

Output `6` `-`s to the canvas.

```
⸿⸿

```

Move to the start of the line below next.

```
↑Ｅ⪪2143R5²⟦⟦⪫ι|||

```

Loop over `21`, `43`, `R5`, inserting `|||` between each pair, and output vertically and triple-spaced.

# Answer
> 4 votes
# APL+WIN, 47 bytes

```
5 7⍴(,⍉(7⍴2)⊤⎕av⍳'II⌷II')\'135||||--|--||||24R'

```

Try it online!Thanks to Dyalog Classic

Explanation:

```
⎕av⍳'II⌷II' Convert characters to integers 73 73 127 73 73

,⍉(7⍴2)⊤ Convert to boolean matrix, transpose and flatten to a vector

 1 1 1 1 1
 0 0 1 0 0
 0 0 1 0 0
 1 1 1 1 1
 0 0 1 0 0
 0 0 1 0 0
 1 1 1 1 1

 1 0 0 1 0 0 1
 1 0 0 1 0 0 1
 1 1 1 1 1 1 1
 1 0 0 1 0 0 1
 1 0 0 1 0 0 1

 1 0 0 1 0 0 1 1 0 0 1 0 0 1 1 1 1 1 1 1 1 1 0 0 1 0 0 1 1 0 0 1 0 0 1

 This vector has as many 1s as the characters to be displayed.

 \'135||||--|--||||24R'  Inserts spaces into the character vector  corresponding to the 0s

1  3  5|  |  ||--|--||  |  |2  4  R

5 7⍴ Reshapes output as a matrix

```

Trivial answer for 41 bytes

```
5 7⍴'1  3  5|  |  ||--|--||  |  |2  4  R'

```

# Answer
> 4 votes
# Vyxal, 154 bitsv2, 19.25 bytes

```
\|3*5ɾ\RJ2ẇvj\-dd½½YføĊ§

```

(24 bytes SBCS)

Try it Online! | | -6 bits with `L`

Optimizing this was a fun process, especially with Vyncode!

Bitstring:

```
0110101010001111001101000011000011101011101011110001101000001010010011110100010010101010100111111110100100011011101101100010011011010001010111110000101110

```

```
\|3*5ɾ\RJ2ẇvj\-dd½½YføĊ§
\|3*                      # Push `|||`
    5ɾ\RJ                 # Append "R" to range [1,5]
         2ẇvj             # Split into chunks of length 2, join by "|||"
             \-dd½½       # Double "-" twice, halve twice (Push [["-","-"],["-","-"]])
                   Yf     # Interleave and flatten
                     øĊ§  # Centre, transpose and join by newlines

```

# Answer
> 2 votes
# ///, 36 bytes

```
/a/  //b/
|a|a|
/1a3a5b|--|--|b2a4aR

```

Try it online!

# Answer
> 2 votes
# Python 3, ~~52~~ 51 bytes

Boring, straightforward answer. Prints to STDERR.

```
exit("1  3  5\n|  |  |\n|--|--|\n|  |  |\n2  4  R")

```

In a REPL, or Notepad & PHP (39 bytes), or paper (0 bytes), we can shorten that to this:

```
'''1  3  5
|  |  |
|--|--|
|  |  |
2  4  R'''

```

# Answer
> 2 votes
# Haskell, 53 bytes

```
"1  3  5"++a++"|--|--|"++a++"2  4  R"
a="\n|  |  |\n"

```

Attempt This Online!

The boring 45 byte answer:

```
"1  3  5\n|  |  |\n|--|--|\n|  |  |\n2  4  R"

```

Attempt This Online!

# Answer
> 2 votes
# Retina, 35 bytes

```

1x3x5y|--|--|y2x4xR
y
¶|x|x|¶
x

```

Attempt This Online!

The last line contains two spaces. Replaces the input the fixed string `1x3x5y|--|--|y2x4xR`, then replaces `y` with `¶|x|x|¶`, where the pilcrows are newlines, and finally replaces `x` with two spaces.

## Old Answer, ~~45~~ 39 bytes bytes

```

135$&7*|24R
.
$&
3`\|
|--|--|
L`.{9}

```

Attempt This Online!

-6 bytes thanks to Neil

### How it works

1. Ignored the input and replaces it by `135`, 7 `|`s (we actually need 9, but these are inserted in step 4) and `24R`
2. Replaces every character by itself, followed by two spaces
3. Replaces the third pipe (0-indexed) by `|--|--|`
4. Formats into lines of 9 characters each

# Answer
> 2 votes
# 05AB1E, ~~28~~ ~~25~~ 24 bytes

```
0'|…|--)û.B7δ∍»¾5L'Rªι.;

```

Try it online.

**Explanation:**

```
0          # Push "0"
 '|       '# Push "|"
   …|--    # Push "|--"
       )   # Wrap all three values into a list
        û  # Palindromize it: ["0","|","|--","|","0"]
.B         # Box it: add trailing spaces to make all strings the same length:
           #  ["0  ","|  ","|--","|  ","0  "]
   δ       # Map over each string:
  7 ∍      #  Extend it to length 7:
           #   ["0  0  0","|  |  |","|--|--|","|  |  |","0  0  0"]
     »     # Join by newlines:
           #  "0  0  0\n
           #   |  |  |\n
           #   |--|--|\n
           #   |  |  |\n
           #   0  0  0"
¾          # Push 0
 5L        # Push list [1,2,3,4,5]
   'Rª    '# Append "R"
      ι    # Uninterleave it into two parts: [[1,3,5],[2,4,"R"]]
       .;  # Replace every first 0 one by one with the flattened values of this list
           # (after which the result is output implicitly)

```

# Answer
> 1 votes
# JavaScript, 55 bytes

Another one of those boring answers:

```
console.log(`1  3  5
|  |  |
|--|--|
|  |  |
2  4  R`)
```

I am aware the shaving off the pair of those pesky parentheses saves 2 bytes, but sadly the result is not as requested.

Trying to do some *actual* cool golfing performs worse (**~~59~~ 56 bytes in this case from noodle man**):

```
console.log(`1  3  5${v=`
|  |  |
`}|--|--|${v}2  4  R`)
```

(No Try It Online button because you can run the snippets right here!)

# Answer
> 1 votes
# PowerShell, 41 bytes

Unfortunately, the shortest I could create was simple a string of the required output... quite boring I know!

```
"1  3  5
|  |  |
|--|--|
|  |  |
2  4  R"

```

Try it online!

# Answer
> 1 votes
# C# .NET 6, 152 146 bytes

```
int a=124,b=45,c=10;foreach(var x in new[]{49,0,51,0,53,c,a,0,a,0,a,c,a,b,b,a,b,b,a,c,a,0,a,0,a,c,50,0,52,0,82})Console.Write((x>0?(char)x:"  "));

```

Edit: Stored 124 '|', 45 '-', and 10 '\n' into vars to eliminate a char each call

---
Tags: code-golf, kolmogorov-complexity
---