title: It was just a bug

text:
# Question
Title: It was just a bug
Inspired by the bugged output in *@Carcigenicate*'s Clojure answer for the Print this diamond challenge.

## Print this exact text:

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

```

(From the middle outward in both directions, each digit is separated by one more space than the previous line.)

## Challenge rules:

* There will be no input (or an empty unused input).
* Trailing spaces are optional.
* A single trailing new-line is optional.
* Leading spaces or new-lines are not allowed.
* Returning a string-array isn't allowed. You should either output the text, or have a function which returns a single string with correct result.

## General rules:

* This is , so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* Default Loopholes are forbidden.
* If possible, please add a link with a test for your code.
* Also, please add an explanation if necessary.

# Answer
> 4 votes
# MathGolf, 11 bytes

```
8╤{± *♂r╫up

```

Try it online!

## Explanation

```
8             push 8
 ╤            range(-n, n+1)
  {           for each element in range:
   ±          absolute value
              space character
     *        multiply space character x number of times
      ♂r      push 10, create range
        ╫     left-rotate list (0 goes to the end)
         u    join with separator (joins using x spaces)
          p   print with newline

```

Has a trailing newline in the end from printing. @ovs found a mistake in the original code that could be fixed by switching the first `9` to an `8`.

# Answer
> 70 votes
# Python 2,  ~~59 57 56~~ 55 bytes

```
i=8;exec"print(' '*abs(i)).join('1234567890');i-=1;"*17

```

Try it online!

> *@Leaky Nun helped golfing this a lot, @Praind Suggested a method to save 1 byte, which I formerly thought of, but forgot to edit, @CotyJohnathanSaxman suggested changing the loop.*

---

# Explanation

* `i=8` \- Assigns the value `8` to a variable called `i`.
* `exec"..."*17` \- Execute that block of code (`...`) 17 times.
* `print(...)` \- Output the result.
* `' '*abs(i)` \- Create a String with a space repeated `|i|` times.
* `.join('1234567890')` \- Interleave the string created above with `1234567890`, such that `|i|` spaces are inserted between the digits.
* `i-=1` \- Decrement `i`, and by executing it 17 times, it reaches `-8`, which creates te repetitive pattern with the help of `abs()`.

# Answer
> 38 votes
# Vim, 35 bytes:

```
i1234567890<esc>qqYP:s/\d/& /g
YGp{q7@q

```

Explanation:

```
i1234567890<esc>    " insert '1234567890'
qq                  " Record the following into register 'q'
  Y                 "   Yank a line
   P                "   Paste it above us
    :s/\d/& /g      "   Put a space after each number
Y                   "   Yank this line
 G                  "   Move the end of the buffer
  p                 "   Paste the line
   {                "   Move the beginning of the buffer
    q               " Stop recording
     7@q            " Call macro 'q' 7 times

```

# Answer
> 24 votes
# 05AB1E,  ~~14~~  13 bytes

```
17F9ÝÀN8αð×ý,

```

Try it online!

**Explanation**

```
17F            # for N in [0 ... 16] do
   9Ý          # push [0 ... 9]
     À         # rotate left
      N8α      # compute the absolute difference between N and 8
         ð×    # push that many spaces
           ý   # merge the list of digits with the space string as separator
            ,  # print

```

# Answer
> 24 votes
# C64 ASM, 358 bytes (102 bytes compiled with basicstub)

This is the closest I could get due to obvious limitations:

```
jsr $E544
lda #9
sta $FD
nl1: jsr dl
jsr il
dec $FD
bne nl1
inc $FD
nl2: ldy $FD
cpy #9
bne nt1
bl: jmp bl
nt1: iny
sty $FD
jsr dl
jsr il
jmp nl2
dl: clc
ldx #$31
ldy #0
lp: txa
sm: sta $0400, y
inx
cpx #$31
bne c1
rts
c1: cpx #$3A
bne nt2
ldx #$30
clc
nt2: tya
adc $FD
cmp #40
bcc c2
rts
c2: tay
jmp lp
il: lda sm+1
adc #39
bcc nc
inc sm+2
nc: sta sm+1
rts

```

(Could probably be optimized quite a bit)

# Answer
> 17 votes
# TSQL, 220 148 bytes

Improvement posted by ZLK:

```
DECLARE @ VARCHAR(MAX)=''SELECT TOP 17@+=REPLACE('1@2@3@4@5@6@7@8@9@0','@',SPACE(ABS(9-RANK()OVER(ORDER BY object_id))))+'
'FROM sys.objects PRINT @

```

Output:

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

```

# Answer
> 14 votes
# APL (Dyalog), 22 bytes

```
↑∊¨(1+|¯9+⍳17)↑¨¨⊂1⌽⎕D

```

Try it online!

`⎕D`**D**igits from zero to nine

`1⌽` rotate one step right (puts zero at end)

enclose (to treat as unit)

`(``)↑¨¨` for *each* of these numbers, take that many characters from *each* of the letters:

`⍳17` one through seventeen

`¯9+` subtract nine

`|` find the absolute values

`1+` add one

`∊¨` enlist (flatten) each

change one layer of depth into a level of rank (matrify)

# Answer
> 14 votes
# Haskell, 58 55 bytes

```
unlines["1234567890">>=(:(' '<$[1..abs n]))|n<-[-8..8]]

```

Try it online!

This is basically @nimi 's solution :)

# Answer
> 12 votes
# Japt `-R`, ~~19~~ ~~18~~ ~~16~~ ~~14~~ 13 bytes

```
Aõ%A
£qYçÃÔÅê

```

Test it or try it online

---

## Explanation

```
A             :10
 õ           :Range [1,10]
  %A         :Modulo each by 10
\n           :Assign to variable U
£            :Map each element at 0-based index Y
 q           :  Join U with
  Yç         :   Space repeated Y times
    Ã        :End map
     Ô       :Reverse
      Å      :Slice off first element
       ê     :Mirror
             :Implicitly join with newlines and output

```

# Answer
> 12 votes
# Java 11 (JDK), 98 bytes

```
o->{for(int i=-9;++i<9;)System.out.println("".join(" ".repeat(i<0?-i:i),"1234567890".split("")));}

```

Try it online!

* -14 bytes by switching to JDK 11, which now has a native `String::repeat`.

# Previous answer (Java (OpenJDK 8)), ~~113~~ 112 bytes

```
o->{for(int i=-9;++i<9;)System.out.printf("".join("%1$"+(i<0?-i:i>0?i:"")+"s","1234567890".split(""))+"%n","");}

```

Try it online!

### Explanations

I'm basically constructing the following `String` 17 times (`N` is a variable, not an actual value):

```
"1%1$Ns2%1$Ns3%1$Ns4%1$Ns5%1$Ns6%1$Ns7%1$Ns8%1$Ns9%1$Ns0%n"

```

It's all the expected digits, joined by `%1$Ns` where `N` is the number of spaces between each digit.

`%1$Ns` basically means "take the first argument and pad it until length is at least `N`". Also, `%1$0s` is not supported so a special case `%1$s` is made for `0`.

Finally, I format-print that string using a single argument: `""`, so the formatter reuses always the same empty string, padding it with spaces as needed.

### Saves

* 1 byte thanks to Kevin Cruijssen

# Answer
> 9 votes
# Clojure, ~~126~~ 99 bytes

-27 by fixing a couple of dumb mistakes. The outer use of `a` wasn't necessary, so I was able to get rid of `a` altogether and just write `apply str` once. That also allowed me to use a function macro for the main function, which saved some bytes. I also inlined the call to `Math/abs` instead of rebinding `n-spaces`.

Basically a Clojure port of @Mr.Xcoder's Python idea. In retrospect, I should have used the `abs`/`range` method for the diamond challenge originally, but I then I may not have produced the bugged output!

Pretty simple. Joins the number string with a number of spaces that depends on the current row.

```
#(doseq[n(range -8 9)](println(clojure.string/join(apply str(repeat (Math/abs n)\ ))"1234567890")))

```

---

```
(defn bugged []
  (doseq [n-spaces (range -8 9)]
    (println
        (clojure.string/join
          ; "String multiplication"
          (apply str
                 (repeat (Math/abs n-spaces) \space))
          "1234567890"))))

```

# Answer
> 9 votes
# Python 3, ~~58~~ ~~57~~ 54 bytes

```
i=8
while i+9:print(*'1234567890',sep=' '*abs(i));i-=1

```

Try it online!

(thanks to @flornquake for the last three bytes; I completely forgot using `sep` to save vs. `.join`)

# Answer
> 9 votes
# SOGL V0.12, 12 bytes

```
9{SUē↕∑}¹№╬«

```

Try it Here! Explanation:

```
9{     }      9 times do
  SU            push "1234567890"
    ē           push e, predefined with the input, which defaults to 0, and then increase it
     ↕          get that many spaces
      ∑         join the string of digits with those spaces
        ¹     collect the results in an array
         №    reverse the array vertically
          ╬«  palindromize vertically with 1 overlap

```

# Answer
> 8 votes
## JavaScript(ES2017), 83 73 72 68 bytes

Thanks Shaggy for saving 10 bytes. Thanks Craig for saving 1 byte. Thanks arcs for saving 4 bytes.

```
for(i=-9,a="";i++<8;)a+=[...`1234567890
`].join("".padEnd(i<0?-i:i))

```

```
for(i=-9,a="";i++<8;)a+=[...`1234567890
`].join("".padEnd(i<0?-i:i))

console.log(a);
```

```
.as-console-wrapper { max-height: 100% !important; top: 0; }
.as-console-row:after { display: none !important; }
```

# Answer
> 7 votes
# Brachylog, ~~30~~ ~~29~~ 28 bytes

```
Ị↺{∧≜;Ṣj₍g;?↔zcc}ᶠ⁹↔;XcP↔Pẉᵐ

```

Try it online!

*Saved one byte thanks to Leaky Nun*.

### Explanation

```
Ị↺                               The string "1234567890"
  {               }ᶠ⁹            Find the first 9 outputs of:
   ∧≜                              Take an integer
       ;Ṣj₍                        Juxtapose " " that number of times
           g;?↔z                   Zip that string of spaces with "1234567890"
                cc                 Concatenate twice into one string
                    ↔            Reverse the resuling list
                     ;XcP↔P      Palindromize the list (concatenate X to it into the list P,
                                   P reversed is still P)
                           ẉᵐ    Map writeln

```

# Answer
> 7 votes
# Pyth, ~~14~~ 13 bytes

1 byte thanks to Mnemonic.

```
V17j*da8NeMST

```

Try it online!

# Answer
> 7 votes
# Charcoal, 18 bytes

```
Ｆ⁹⪫⁺…Ｉ¹:⟦0¶⟧× ι‖Ｂ↑

```

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

```
Ｆ⁹      Repeat 9 times (i = loop variable)
  ⪫       Join
   ⁺       Concatentate
    …Ｉ¹:    All the characters from str(1) below ":" (i.e. to "9") as a list
    ⟦0¶⟧    A list whose element is the string "0\n"
   × ι     With i spaces
‖Ｂ↑     Reflect everything upwards but without duplicating the top line

```

Note: `Cast(1)` takes the same number of bytes because `"1"` would need a separator before `":"` (which as it happens the deverbosifier fails to insert).

# Answer
> 7 votes
# , 108 bytes

```
for(i in abs(-8:8))cat(paste0(el(strsplit("1234567890","")),paste(rep(" ",i),collapse=""),collapse=""),"\n")

```

Just pasting and collapsing the strings.

Try it online!

Edit: thanks for Challenger5 for pointing out a problem. Fixed it now.

Edit 2: saved a byte thanks to bouncyball.

# Answer
> 6 votes
## Java 8, 235 234 206 163 bytes

```
interface A{static void main(String[]a){for(int i=-8;i<9;i++){String s="";for(int j=1,k;j<10;j++){s+=j;for(k=0;k<(i>0?i:-i);k++)s+=" ";}System.out.println(s+0);}}}

```

**Update** : -28 bytes thanks to Leaky Nun !
**Update 2** : -43 bytes thanks to Leaky Nun again !

Ungolfed :

```
interface A {
    static void main(String[] a) {
        for (int i = -8; i < 9; i++) {
            String s = "";
            for (int j = 1, k; j < 10; j++) {
                s += j;
                for (k = 0; k < (i > 0 ? i : -i); k++)
                    s += " ";
            }
            System.out.println(s + 0);
        }
    }
}

```

Try it online

**EDIT :** The code earlier was wrong ! Made a mistake while golfing the code, it should work as intended now !

# Answer
> 6 votes
## Husk, 21 bytes

```
mΣṪ`:§+↔tḣR8' ṁs`:0ḣ9

```

This is a full program that prints to STDOUT. Try it online! There are lots of trailing spaces.

## Explanation

Husk is still missing lots of essential stuff like a two-argument range function, so parts of this solution are a little hacky.

```
mΣṪ`:§+↔tḣR8' ṁs`:0ḣ9
              ṁs`:0ḣ9  This part evaluates to the string "1234567890".
                   ḣ9   Range from 1 to 9.
                `:0     Append 0.
              ṁs        Convert each number to string and concatenate.
     §+↔tḣR8'          This part evaluates to a list like ["  "," ",""," ","  "]
                       but with 17 elements instead of 5.
          R8'           A string of 8 spaces.
         ḣ              Take prefixes.
     §+                 Concatenate
       ↔                the reversal and
        t               tail of the prefix list, palindromizing it.
  Ṫ                    Take outer product of the two lists
   `:                  with respect to flipped prepeding.
                       This prepends each digit to each string of spaces.
mΣ                     Map concatenation over the results, computing the rows.
                       Implicitly join with newlines and print.

```

# Answer
> 6 votes
# T-SQL 145 152 bytes

```
DECLARE @ VARCHAR(MAX)=''SELECT TOP 17@+=REPLACE('1x2x3x4x5x6x7x8x9x0','x',SPACE(ABS(number-8)))+'
'FROM master..spt_values WHERE type='P'PRINT @

```

**Updated** to use:

* `master..spt_values` to generate numbers (`WHERE type = 'P'`, these are always consecutive, starting at 0)
* @ZLK's `TOP 17` idea
* PRINT (to obey the rules - no stringlists)
* @JanDrozen's great idea of including the carriage return in the string (I counted that as just one byte - Windows CRLF what?)
* Idea of @Bridge to use just @ for variable name - all these tricks!!

Results:

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

```

(Thanks @JanDrozen for the REPLACE idea)

# Answer
> 5 votes
# Mathematica, 92 bytes

```
Column@Join[Reverse@(s=Row/@Table[Riffle[Range@10~Mod~10,""<>Table[" ",i]],{i,0,8}]),Rest@s]

```

Try it online

copy/paste code with ctrl-v
press shift+enter to run

# Answer
> 5 votes
# Jelly, 15 bytes

```
8ŒRA⁶ẋØDṙ1¤jÐ€Y

```

Try it online!

# Answer
> 5 votes
# C, 97 bytes

```
i=-9;main(j){for(;++i<9;putchar(10))for(j=0;++j<11;printf("        "+8-abs(i)))putchar(48+j%10);}

```

Your compiler will probably complain a *lot* about this code; mine threw 7 warnings of 4 different types. Might improve the code later.

Try it online!

# Answer
> 5 votes
# SOGL V0.12, 14 bytes

```
ā9{SUčf@*∑Κ}╬Æ

```

Try it Here!

Explanation:

```
ā               push an empty array
 9{        }    9 times do
   SU             push "1234567890"
     č            chop into characters
      f@*         get current iteration (0-based) amount of spaces
         ∑        join with that
          Κ       prepend this to the array
            ╬Æ  palindromize vertically with 1 overlap

```

# Answer
> 4 votes
# Charcoal, 21 20 19 18 bytes

```
Ｆ⁹«Ｆ…¹χ⁺κ… ι0⸿»‖Ｂ↑

```

Try it online!

Link to the verbose version. Basically I create the lower part of the drawing and then reflect the text up.

# Answer
> 4 votes
## CJam, 21 bytes

```
A,(+aH*ee{:\8-zS**n}/

```

Try it online!

### Explanation

```
A,     e# Get [0 1 2 ... 9].
(+     e# Rotate the 0 to the end.
aH*    e# Wrap in an array and repeat 17 times.
ee     e# Enumerate. This pairs each copy of the array with its index in
       e# the list.
{      e# For each [index array] pair...
  :\   e#   Unwrap the pair and swap its order.
  8-z  e#   Get the absolute difference of the index from 8.
  S*   e#   Get a string of that many spaces.
  *    e#   Riffle the list of digits with the string of spaces.
  n    e#   Print it with a trailing linefeed.
}/

```

# Answer
> 4 votes
# PHP, 69 bytes

```
for(;$i<17;)echo join(str_pad("",abs($i++-8)),range(1,9)+[9=>0]),"
";

```

Try it online!

# Answer
> 4 votes
## Batch, 163 bytes

```
@set s=1 2 3 4 5 6 7 8 9 0
@set t=
@for %%l in (9 7)do @for /l %%i in (1,1,%%l)do @call:%%l
:7
@set t=  %t%
:9
@set t=%t:~1%
@call echo %%s: =%t%%%

```

Note: First line ends in 9 spaces. Explanation: Uses creative line numbering! The first loop needs to run 9 times and delete a space each time, while the second loop needs to run 8 times and add a space each time. The former is achieved by running it 7 times and falling through for the 8th time, while the latter is achieved by adding two spaces and falling through to delete one of them again.

# Answer
> 4 votes
# bash (and shell utils), 69 bytes

```
for i in `seq 9 -1 1;seq 2 9`;do seq -f%-$i.f 9|tr -d \\n;echo 0;done

```

# Answer
> 4 votes
# C (gcc), 76 bytes

```
f(x,y){for(y=-9;++y<9;puts(""))for(x=10;x++;printf("%-*d",abs(y)+1,x%=10));}

```

Try it online!

It outputs some trailing spaces, which is supposed to be OK.

It prints the numbers using left-justified fields of dynamic length - that's what the format string `%-*d` is for.

The inner loop has some funny initialization (starts from 10; any multiple of 10 would be fine) to "simplify" its termination condition.

# Answer
> 4 votes
# Perl 5, ~~31~~ 29 bytes

```
$,=$"x abs,say 1..9,0for-8..8

```

Try it online!

# Answer
> 4 votes
# PowerShell, 30 bytes

```
8..0+1..8|%{1..9+0-join' '*$_}

```

Try it online!

Constructs a range of `8,7,6...2,1,0,1,2...8` then loops through each number. Inside the loop we construct a range of `1..9` concatenated with `0` then `-join` the numbers in the range together with the appropriate number of spaces. Each string is left on the pipeline, and output is implicit at program completion.

# Answer
> 4 votes
# jq `-nr`, ~~50~~ ~~46~~ 45 bytes

```
[range(9)+1,0|@sh]|join(range(17)-8|" "*fabs)

```

Try it on jqplay!

`[range(9)+1,0|@sh]` generates the array `["1", "2", ..., "9", "0"]`. This list is then joined by each of the results from:

`range(17)-8`: -8, -7, ..., 7, 8
`" "*fabs` a string of absolute value spaces

# Answer
> 3 votes
# perl 5: 43, 39, 31 bytes

Needs `-E` flag (which is free per our consensus).

```
map{$,=$"x abs;say 1..9,0}-8..8

```

**Usage:**

```
perl -E 'map{$,=$"x abs;say 1..9,0}-8..8'

```

Thanks to Dada

# Answer
> 3 votes
## JavaScript, 67 Bytes

```
f=(i=8)=>i+9?[...`1234567890
`].join(''.padEnd(i<0?-i:i))+f(i-1):''

```

```
f=(i=8)=>i+9?[...`1234567890
`].join(''.padEnd(i<0?-i:i))+f(i-1):''

console.log(f())
```

# Answer
> 3 votes
## LOGO, ~~58~~ 57 bytes

```
for[j 8 -8][repeat 9[type # repeat abs :j[type "\ ]]pr 0]

```

This should be run on new versions of FMSLogo (link above), where `#` is `repcount` in `repeat` loops. That is a new feature in FMSLogo, which seems to be undocumented.

# Answer
> 3 votes
# QBIC, ~~36~~ 32 bytes

```
[-8,8|?[|?!b%z$';space$(abs(a));

```

## Explanation

```
[-8,8|     FOR a = -8; a <= 8; a++      Sets upthe number of lines
?          Kick off each line with a \n
[|         FOR b = 1; b <= 10; b++      Loop over each digit: default behaviour for a no-arg FOR declaration
?          PRINT
 !   $     a strng cast (suppresses QBasic's tendency to space out numbers)
  b%z      of b modulo 10 (z is 10 in QBIC)
 '         Then take the next bit of code as literal QBasic
 ;         Suppress newlines and tabs
 space$    Add x spaces to the output, where X is
 (abs(a))  The absolute line number
 ;         And suppress all newlines and tabs after this too
           A closing ` to this code literal is auto added by QBIC at EOF
           Two closing NEXT statements are also auto-added.

```

## Sample output

Just because I really like the pattern. Note that this took some fiddling in QBasic because the usual terminal output is limited to 80 chars and it wraps.

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

```

# Answer
> 3 votes
# Common Lisp, 85 bytes

```
(dotimes(i 17)(format t(format()"~~{~~,,~aa~~}
"(abs(- i 8)))'(1 2 3 4 5 6 7 8 9 0)))

```

Try it online!

`format` “magic” of Common Lisp:

```
(dotimes (i 17)                     ; for i from 0 to 16
  (format t                         ; print with a format string generated from the next call
          (format ()                ; with nil as parameter generates a string instead of printing
                  "~~{~~,,~aa~~}
"                                   ; generate the format string "~{~,,na~}~%" with n given
                  (abs(- i 8)))     ;     by the value of abs(i-8) (number of spaces)
          '(1 2 3 4 5 6 7 8 9 0)))  ; the data to be printed for each line

```

# Answer
> 3 votes
# MATL, 21 bytes

```
-9Zv"l4Y29YS10:q@*Q(c

```

Try it online!

Explanation:

```
-9Zv                  % Generates [9 ... 2, 1, 2, ... 9].
    "                 % Iterate over this vector.
                   (  % Assignment indexing. Places elements B at positions C in existing vector A.
     l                %   A: Dummy vector with numeric [1] in it. Is always overwritten by char '1'.
      4Y29YS          %   B:  '0':'9', circularly shifted 9 positions to get '1':'9','0'
            10:q@*Q   %   C: Equally spaced indexing vector, spacing based on loop variable @.
                    c % Convert to char, because A was numeric.

```

Golfing done:

```
-9Zv     -->  built-in, instead of -8:8|Q or even 8:PQ9:h|
10:q@*Q  -->  2 bytes shorter than l@@10*3$:
l ... c  -->  1 byte shorter than 'x' (char dummy vector A)

```

I have attempted to get rid of the `9YS` by doing the circular shift in the indexing, but this increased the byte count (`10t:qwX\q@*Q` instead of `9YS10:q@*Q`). However, some interesting patterns were obtained in the process: Try it online!, Try it online!.

# Answer
> 3 votes
# , ~~25~~ 22 bytes

```
(1 j.|i:8)#"{1|.Num_j_

```

Try it online!

# Answer
> 3 votes
## PHP, 76 Bytes

Update: Thanks to Soaku for the addition.

```
for($i=-9;$i++<8;)echo join(str_repeat(' ',abs($i)),range(1,9)+[9=>0])."
";

```

Try it online !

## PHP, ~~88, 86, 80~~

Thanks to Caird for suggesting the golfing tips.

```
for($i=-9;$i++<8;)echo join(str_repeat(' ',abs($i)),[1,2,3,4,5,6,7,8,9,0])."\r";

```

You can try it here!

# Answer
> 3 votes
## Perl 6, 43 37 35 bytes

Originally, I came to:

```
map({say join " "x abs($_-8),1..9,0},0..16)

```

The say function in perl 6 automatically adds a newline, and it's map works a bit different from perl 5, requiring less parens due to it's more list based approach. Try it online

Fortunately, Jo King showed how to whittle it down further to 35 bytes:

```
{say join " "x.abs,1..9,0}for ^17-8

```

Try it online

# Answer
> 3 votes
# , 51 bytes

```
for(i in abs(-8:8))cat(1:9,0,"
",sep=strrep(" ",i))

```

Try it online!

Managed to find some more bytes thanks to JayCe's suggestion in the comments.

# Answer
> 3 votes
# C, 135 128 characters

### -7 characters thanks to kevin cruijssen

```
#define p printf
i=1,j,h=9,k;main(){for(;++i<22;i<10?h--:h++,p("\n"))for(j=0;++j<11;)for(p(j==10?"0":"%d",j),k=1;k++<h;)p(" ");}

```

Try it online!

---

### Fun bonus:

On my first compile I got the logic backwards and ended up with the output in reverse

```
i=1,j,k,h=9;main(){for(;i++<20;){for(j=0;j++<10;){printf(j==10?"0":"%d",j);for(k=1;k++<10-h;){printf(" ");}}i<11?h--:h++;printf("\n");}}

```

Edit: removed missed whitespace

# Answer
> 3 votes
# Vyxal `j`, 15 bytes

```
8N8ṡȧƛð$ẋ9ʀ1Ǔ$j

```

Try it Online!

-1 byte thanks to Aaron Miller

```
8N                 -8
  8                 8
   ṡ                inclusive range; -8, -7, ..., 7, 8
    ȧ               abs; 8, 7, ..., 1, 0, 1, ..., 7, 8
     ƛ---------     for each
      ð$            push space and swap it underneath
        ẋ           repeat the space N times
         9ʀ         [0, 1, ..., 8, 9]
           1Ǔ       rotate left once
             $j     swap and join

j (flag)            join on newlines

```

# Answer
> 3 votes
# Dash\*, 69 bytes

```
seq -- -8 8|xargs -I: sh -c 'seq -s"`printf "%:s_"`" 10'|sed s/_1*//g

```

Hopefully this iteration is fairly self explanatory -- pretty much a straight swap of `for` to `xargs`.

Try it online!

# Dash\*, ~~87~~, ~~86~~, 73 bytes

```
for p in `seq -- -8 8`;do seq -s"`printf "%${p}s_"`" 10;done|sed s/_1*//g

```

Try it online!

### Explanation (`for` method)

```
for p in `seq -- -8 8`

```

Produce -8 to 8, used to create separator in next `seq`. *NB BusyBox’s\* `seq` barfs on the `-8` without the `--` but TIO’s Dash env does not.*

```
;do seq -s"`printf "%${p}s_"`" 10

```

Print 1-10, separated with `p` × spaces, with an extra `_` appended (because `seq` won't accept an empty separator).

```
;done|sed s/_1*//g

```

Remove the `_` as well as the `1` from trailing `10`.

*EDIT: removed a silly space (thanks Kevin Cruijssen)*

*EDIT: saved many bytes because negative padding printf doesn't matter*

*EDIT: scraped off another few bytes by ditching the `for` in favour of `xargs`.*

**<sub>\*Actually this is aimed at Busybox 1.31.1 `ash`, `sed`, `seq` and `printf`, but TIO didn't have that environment. NB available `seq` options are limited to `-w` and `-s`.</sub>**

# Answer
> 2 votes
# , 18 bytes

```
¬19á08ñÄÓä/&
YGpH

```

Try it online!

# Answer
> 2 votes
**Swift 3.1, ~~186~~ 182 bytes**

```
func f(_ n:Int=0,_ u:Bool=true){let p={if n<8{f(n+1,u)}};let q={print((1...9).map{String($0)+String(repeating:" ",count:n)}.joined()+"0")};if u{q();p()}else{p();q()}};f(1,false);f()

```

Explanation

```
func f(_ n:Int=0,_ u:Bool=true){          function (recursive) that does
                                          all the heavy-lifting =)
                                          n - number of spaces,
                                          u - go "up" or "down
let p={if n<8 {f(n+1,u)}}                 closure that runs f on higher step if can
let q={                                   closure which does the printing
print((1...9).map{                        print closed range of number mapped...
String($0)+String(repeating:" ",count:n)  ...making String from each number in range
                                          and appending n spaces to it
.joined()+"0")                            join all "1    "-like strings and append "0"
if u{q();p()}                             if go "up" - then call f before printing
else{p();q()}                             if go "down - the other way
f(1,false);f()                            run "up" then "down"

```

Removed some silly spaces. Thanx to Kevin Cruijssen

# Answer
> 2 votes
# q/kdb+, 37 bytes

**Solution:**

```
-1" "{raze(1_11#.Q.n),\:y#x}'8-(!)17;

```

**Example:**

```
q)-1" "{raze(1_11#.Q.n),\:y#x}'8-(!)17;
1        2        3        4        5        6        7        8        9        0
1       2       3       4       5       6       7       8       9       0
1      2      3      4      5      6      7      8      9      0
1     2     3     4     5     6     7     8     9     0
1    2    3    4    5    6    7    8    9    0
1   2   3   4   5   6   7   8   9   0
1  2  3  4  5  6  7  8  9  0
1 2 3 4 5 6 7 8 9 0
1234567890
1 2 3 4 5 6 7 8 9 0
1  2  3  4  5  6  7  8  9  0
1   2   3   4   5   6   7   8   9   0
1    2    3    4    5    6    7    8    9    0
1     2     3     4     5     6     7     8     9     0
1      2      3      4      5      6      7      8      9      0
1       2       3       4       5       6       7       8       9       0
1        2        3        4        5        6        7        8        9        0

```

**Explanation:**

q is evaluation right-to-left. Here we are taking the range of -8..0..8, and joining that many spaces with the list "1234567890". We then use `-1` to print out to stdout (rather than returning the list of strings).

```
-1 " "{raze (1_11#.Q.n),\:y#x}'8 - til 17; / ungolfed solution
                                   til 17  / range of 0..16
                               8 -         / take 8 from each value, gives -8..0..8
   " "{                      }'            / each left/right, passes in " " and then -8, -7, etc..
                          y#x              / take from list " ", note: negatives take from 'back' of list
                       ,\:                 / \: is 'each left', , means concatenate with, so take each left and concatenate with the right
            (1_11#.Q.n)                    / 'the left'. .Q.n is range 0-9 as a string, take 11 to get 0123..90, then drop the first
       raze                                / reduce down output list into a single string
-1                                       ; / print to stdout and swallow return value (-1)

```

**Notes:**

Doing `(1_11#.Q.n)` is 1 byte shorter than the much more straightforward `"1234567890"`... but as `.Q.n` returns `"0123456789"` some manipulation is required.

# Answer
> 2 votes
# Ruby 2.4, 40 bytes

```
-8.upto 8{|i|puts [*1..9,0]*(' '*i.abs)}

```

# Ruby (lower than 2.4), 41 bytes

```
-8.upto(8){|i|puts [*1..9,0]*(' '*i.abs)}

```

Try it online!

# Answer
> 2 votes
# PHP, 71 bytes

```
while($y<17)echo chunk_split(1234567890,1,str_pad("",abs($y++-8))),"
";

```

Run with `-nr` or test it online.

# Answer
> 2 votes
# Bubblegum, 140 bytes

:P

```
0000000: ad92 510e c230 0c43 ff39 0547 802c f3bc  ..Q..0.C.9.G.,..
0000010: fb5f 8c10 c5d1 5a09 10b0 7d59 b1fd b4b6  ._....Z...}Y....
0000020: b95f eb33 8945 c225 5609 486c 1294 d825  ._.3.E.%V.Hl...%
0000030: 6e17 216d 02fa 84c3 04a3 5033 c906 8e0f  n.!m......P3....
0000040: 140c 0c8a 3000 ec50 f743 1987 2abb d83d  ....0..P.C..*..=
0000050: eb96 7707 dda0 f215 b70a 7b45 5141 66ac  ..w.......{EQAf.
0000060: 5296 19cf 04d2 67ba 4fd3 c2f2 3010 63c6  R.....g.O...0.c.
0000070: 3066 b6f8 8a8d fb0b fb0d eff3 2f7d 77ce  0f........../}w.
0000080: 1faf f3df 773c 7fa5 cedf f707            ....w<......

```

Try it online!

Do I get brownie points for having `._.` two times in the dump?

# Answer
> 2 votes
# Cubically, 2622 bytes

```
U3D1R3L1F3B1U1D3+3111111@6-2111@66666666+21111@6-21111@66666666+211111@6-211111@66666666+0@6-0@66666666+01@6-01@66666666+011@6-011@66666666+0111@6-0111@66666666+4@6-4@66666666+41@6-41@66666666+211@6-511111@6+5111111@6-2111@6666666+21111@6-21111@6666666+211111@6-211111@6666666+0@6-0@6666666+01@6-01@6666666+011@6-011@6666666+0111@6-0111@6666666+4@6-4@6666666+41@6-41@6666666+211@6-511111@6+5111111@6-2111@666666+21111@6-21111@666666+211111@6-211111@666666+0@6-0@666666+01@6-01@666666+011@6-011@666666+0111@6-0111@666666+4@6-4@666666+41@6-41@666666+211@6-511111@6+5111111@6-2111@66666+21111@6-21111@66666+211111@6-211111@66666+0@6-0@66666+01@6-01@66666+011@6-011@66666+0111@6-0111@66666+4@6-4@66666+41@6-41@66666+211@6-511111@6+5111111@6-2111@6666+21111@6-21111@6666+211111@6-211111@6666+0@6-0@6666+01@6-01@6666+011@6-011@6666+0111@6-0111@6666+4@6-4@6666+41@6-41@6666+211@6-511111@6+5111111@6-2111@666+21111@6-21111@666+211111@6-211111@666+0@6-0@666+01@6-01@666+011@6-011@666+0111@6-0111@666+4@6-4@666+41@6-41@666+211@6-511111@6+5111111@6-2111@66+21111@6-21111@66+211111@6-211111@66+0@6-0@66+01@6-01@66+011@6-011@66+0111@6-0111@66+4@6-4@66+41@6-41@66+211@6-511111@6+5111111@6-2111@6+21111@6-21111@6+211111@6-211111@6+0@6-0@6+01@6-01@6+011@6-011@6+0111@6-0111@6+4@6-4@6+41@6-41@6+211@6-511111@6+5111111@6+1@6+1@6+1@6+1@6+1@6+1@6+1@6+1@6-111111111@6-511111@6+5111111@6-2111@6+21111@6-21111@6+211111@6-211111@6+0@6-0@6+01@6-01@6+011@6-011@6+0111@6-0111@6+4@6-4@6+41@6-41@6+211@6-511111@6+5111111@6-2111@66+21111@6-21111@66+211111@6-211111@66+0@6-0@66+01@6-01@66+011@6-011@66+0111@6-0111@66+4@6-4@66+41@6-41@66+211@6-511111@6+5111111@6-2111@666+21111@6-21111@666+211111@6-211111@666+0@6-0@666+01@6-01@666+011@6-011@666+0111@6-0111@666+4@6-4@666+41@6-41@666+211@6-511111@6+5111111@6-2111@6666+21111@6-21111@6666+211111@6-211111@6666+0@6-0@6666+01@6-01@6666+011@6-011@6666+0111@6-0111@6666+4@6-4@6666+41@6-41@6666+211@6-511111@6+5111111@6-2111@66666+21111@6-21111@66666+211111@6-211111@66666+0@6-0@66666+01@6-01@66666+011@6-011@66666+0111@6-0111@66666+4@6-4@66666+41@6-41@66666+211@6-511111@6+5111111@6-2111@666666+21111@6-21111@666666+211111@6-211111@666666+0@6-0@666666+01@6-01@666666+011@6-011@666666+0111@6-0111@666666+4@6-4@666666+41@6-41@666666+211@6-511111@6+5111111@6-2111@6666666+21111@6-21111@6666666+211111@6-211111@6666666+0@6-0@6666666+01@6-01@6666666+011@6-011@6666666+0111@6-0111@6666666+4@6-4@6666666+41@6-41@6666666+211@6-511111@6+5111111@6-2111@66666666+21111@6-21111@66666666+211111@6-211111@66666666+0@6-0@66666666+01@6-01@66666666+011@6-011@66666666+0111@6-0111@66666666+4@6-4@66666666+41@6-41@66666666+211@6

```

Pretty simple, turns the cube to get it into this:

```
   242
   202
   242
000131555313
010121535343
000131555313
   424
   454
   424

```

Now the LEFT face sums up to 1. So we use the other faces to get as close to the desired ASCII values as possible, then just increment/decrement by 1.

This also works:

# Cubically, 2938 bytes

```
:4/1+5@6/1+3@66666666+2@6-2@66666666:5+1/1+5@6/1+3@66666666:5+2/1+5@6/1+3@66666666:5+3/1+5@6/1+3@66666666:5+1@6:5/1+3@66666666:1/1+51@6:5/1+3@66666666:2/1+51@6:5/1+3@66666666/1+51@6:5/1+3@66666666/1+5@6:1/1+1@6:4/1+5@6/1+3@6666666+2@6-2@6666666:5+1/1+5@6/1+3@6666666:5+2/1+5@6/1+3@6666666:5+3/1+5@6/1+3@6666666:5+1@6:5/1+3@6666666:1/1+51@6:5/1+3@6666666:2/1+51@6:5/1+3@6666666/1+51@6:5/1+3@6666666/1+5@6:1/1+1@6:4/1+5@6/1+3@666666+2@6-2@666666:5+1/1+5@6/1+3@666666:5+2/1+5@6/1+3@666666:5+3/1+5@6/1+3@666666:5+1@6:5/1+3@666666:1/1+51@6:5/1+3@666666:2/1+51@6:5/1+3@666666/1+51@6:5/1+3@666666/1+5@6:1/1+1@6:4/1+5@6/1+3@66666+2@6-2@66666:5+1/1+5@6/1+3@66666:5+2/1+5@6/1+3@66666:5+3/1+5@6/1+3@66666:5+1@6:5/1+3@66666:1/1+51@6:5/1+3@66666:2/1+51@6:5/1+3@66666/1+51@6:5/1+3@66666/1+5@6:1/1+1@6:4/1+5@6/1+3@6666+2@6-2@6666:5+1/1+5@6/1+3@6666:5+2/1+5@6/1+3@6666:5+3/1+5@6/1+3@6666:5+1@6:5/1+3@6666:1/1+51@6:5/1+3@6666:2/1+51@6:5/1+3@6666/1+51@6:5/1+3@6666/1+5@6:1/1+1@6:4/1+5@6/1+3@666+2@6-2@666:5+1/1+5@6/1+3@666:5+2/1+5@6/1+3@666:5+3/1+5@6/1+3@666:5+1@6:5/1+3@666:1/1+51@6:5/1+3@666:2/1+51@6:5/1+3@666/1+51@6:5/1+3@666/1+5@6:1/1+1@6:4/1+5@6/1+3@66+2@6-2@66:5+1/1+5@6/1+3@66:5+2/1+5@6/1+3@66:5+3/1+5@6/1+3@66:5+1@6:5/1+3@66:1/1+51@6:5/1+3@66:2/1+51@6:5/1+3@66/1+51@6:5/1+3@66/1+5@6:1/1+1@6:4/1+5@6/1+3@6+2@6-2@6:5+1/1+5@6/1+3@6:5+2/1+5@6/1+3@6:5+3/1+5@6/1+3@6:5+1@6:5/1+3@6:1/1+51@6:5/1+3@6:2/1+51@6:5/1+3@6/1+51@6:5/1+3@6/1+5@6:1/1+1@6:4/1+5@6/1+5@6:5+1/1+5@6:5+2/1+5@6:5+3/1+5@6:5+1@6:1/1+51@6:2/1+51@6:3/1+51@6-1@6:1/1+1@6:4/1+5@6/1+3@6+2@6-2@6:5+1/1+5@6/1+3@6:5+2/1+5@6/1+3@6:5+3/1+5@6/1+3@6:5+1@6:5/1+3@6:1/1+51@6:5/1+3@6:2/1+51@6:5/1+3@6/1+51@6:5/1+3@6/1+5@6:1/1+1@6:4/1+5@6/1+3@66+2@6-2@66:5+1/1+5@6/1+3@66:5+2/1+5@6/1+3@66:5+3/1+5@6/1+3@66:5+1@6:5/1+3@66:1/1+51@6:5/1+3@66:2/1+51@6:5/1+3@66/1+51@6:5/1+3@66/1+5@6:1/1+1@6:4/1+5@6/1+3@666+2@6-2@666:5+1/1+5@6/1+3@666:5+2/1+5@6/1+3@666:5+3/1+5@6/1+3@666:5+1@6:5/1+3@666:1/1+51@6:5/1+3@666:2/1+51@6:5/1+3@666/1+51@6:5/1+3@666/1+5@6:1/1+1@6:4/1+5@6/1+3@6666+2@6-2@6666:5+1/1+5@6/1+3@6666:5+2/1+5@6/1+3@6666:5+3/1+5@6/1+3@6666:5+1@6:5/1+3@6666:1/1+51@6:5/1+3@6666:2/1+51@6:5/1+3@6666/1+51@6:5/1+3@6666/1+5@6:1/1+1@6:4/1+5@6/1+3@66666+2@6-2@66666:5+1/1+5@6/1+3@66666:5+2/1+5@6/1+3@66666:5+3/1+5@6/1+3@66666:5+1@6:5/1+3@66666:1/1+51@6:5/1+3@66666:2/1+51@6:5/1+3@66666/1+51@6:5/1+3@66666/1+5@6:1/1+1@6:4/1+5@6/1+3@666666+2@6-2@666666:5+1/1+5@6/1+3@666666:5+2/1+5@6/1+3@666666:5+3/1+5@6/1+3@666666:5+1@6:5/1+3@666666:1/1+51@6:5/1+3@666666:2/1+51@6:5/1+3@666666/1+51@6:5/1+3@666666/1+5@6:1/1+1@6:4/1+5@6/1+3@6666666+2@6-2@6666666:5+1/1+5@6/1+3@6666666:5+2/1+5@6/1+3@6666666:5+3/1+5@6/1+3@6666666:5+1@6:5/1+3@6666666:1/1+51@6:5/1+3@6666666:2/1+51@6:5/1+3@6666666/1+51@6:5/1+3@6666666/1+5@6:1/1+1@6:4/1+5@6/1+3@66666666+2@6-2@66666666:5+1/1+5@6/1+3@66666666:5+2/1+5@6/1+3@66666666:5+3/1+5@6/1+3@66666666:5+1@6:5/1+3@66666666:1/1+51@6:5/1+3@66666666:2/1+51@6:5/1+3@66666666/1+51@6:5/1+3@66666666/1+5@6

```

Uses the existing cube and division to get the required ASCII values.

Found using these answers.

# Answer
> 2 votes
# Zsh, 48 bytes

```
for 1 ({9..1} {2..9})printf %-$1s {1..9} 0&&echo

```

Try it Online! <sub>~~49b~~ ~~61b~~ ~~57b~~</sub>

Similar to Spaceship Maw!. -4, -8 bytes thanks to @pxeger.

# Answer
> 2 votes
# Deadfish~, 2959 bytes

```
{iiiii}dc{dd}iiicccccccc{ii}ddc{dd}iicccccccc{ii}dc{dd}icccccccc{ii}c{dd}cccccccc{ii}ic{dd}dcccccccc{ii}iic{dd}ddcccccccc{ii}iiic{dd}dddcccccccc{ii}iiiic{dd}ddddcccccccc{ii}iiiiic{dd}dddddcccccccc{i}iiiiiic{dddd}iic{iiii}dc{dd}iiiccccccc{ii}ddc{dd}iiccccccc{ii}dc{dd}iccccccc{ii}c{dd}ccccccc{ii}ic{dd}dccccccc{ii}iic{dd}ddccccccc{ii}iiic{dd}dddccccccc{ii}iiiic{dd}ddddccccccc{ii}iiiiic{dd}dddddccccccc{i}iiiiiic{dddd}iic{iiii}dc{dd}iiicccccc{ii}ddc{dd}iicccccc{ii}dc{dd}icccccc{ii}c{dd}cccccc{ii}ic{dd}dcccccc{ii}iic{dd}ddcccccc{ii}iiic{dd}dddcccccc{ii}iiiic{dd}ddddcccccc{ii}iiiiic{dd}dddddcccccc{i}iiiiiic{dddd}iic{iiii}dc{dd}iiiccccc{ii}ddc{dd}iiccccc{ii}dc{dd}iccccc{ii}c{dd}ccccc{ii}ic{dd}dccccc{ii}iic{dd}ddccccc{ii}iiic{dd}dddccccc{ii}iiiic{dd}ddddccccc{ii}iiiiic{dd}dddddccccc{i}iiiiiic{dddd}iic{iiii}dc{dd}iiicccc{ii}ddc{dd}iicccc{ii}dc{dd}icccc{ii}c{dd}cccc{ii}ic{dd}dcccc{ii}iic{dd}ddcccc{ii}iiic{dd}dddcccc{ii}iiiic{dd}ddddcccc{ii}iiiiic{dd}dddddcccc{i}iiiiiic{dddd}iic{iiii}dc{dd}iiiccc{ii}ddc{dd}iiccc{ii}dc{dd}iccc{ii}c{dd}ccc{ii}ic{dd}dccc{ii}iic{dd}ddccc{ii}iiic{dd}dddccc{ii}iiiic{dd}ddddccc{ii}iiiiic{dd}dddddccc{i}iiiiiic{dddd}iic{iiii}dc{dd}iiicc{ii}ddc{dd}iicc{ii}dc{dd}icc{ii}c{dd}cc{ii}ic{dd}dcc{ii}iic{dd}ddcc{ii}iiic{dd}dddcc{ii}iiiic{dd}ddddcc{ii}iiiiic{dd}dddddcc{i}iiiiiic{dddd}iic{iiii}dc{dd}iiic{ii}ddc{dd}iic{ii}dc{dd}ic{ii}c{dd}c{ii}ic{dd}dc{ii}iic{dd}ddc{ii}iiic{dd}dddc{ii}iiiic{dd}ddddc{ii}iiiiic{dd}dddddc{i}iiiiiic{dddd}iic{iiii}dcicicicicicicicic{d}ic{dddd}iic{iiii}dc{dd}iiic{ii}ddc{dd}iic{ii}dc{dd}ic{ii}c{dd}c{ii}ic{dd}dc{ii}iic{dd}ddc{ii}iiic{dd}dddc{ii}iiiic{dd}ddddc{ii}iiiiic{dd}dddddc{i}iiiiiic{dddd}iic{iiii}dc{dd}iiicc{ii}ddc{dd}iicc{ii}dc{dd}icc{ii}c{dd}cc{ii}ic{dd}dcc{ii}iic{dd}ddcc{ii}iiic{dd}dddcc{ii}iiiic{dd}ddddcc{ii}iiiiic{dd}dddddcc{i}iiiiiic{dddd}iic{iiii}dc{dd}iiiccc{ii}ddc{dd}iiccc{ii}dc{dd}iccc{ii}c{dd}ccc{ii}ic{dd}dccc{ii}iic{dd}ddccc{ii}iiic{dd}dddccc{ii}iiiic{dd}ddddccc{ii}iiiiic{dd}dddddccc{i}iiiiiic{dddd}iic{iiii}dc{dd}iiicccc{ii}ddc{dd}iicccc{ii}dc{dd}icccc{ii}c{dd}cccc{ii}ic{dd}dcccc{ii}iic{dd}ddcccc{ii}iiic{dd}dddcccc{ii}iiiic{dd}ddddcccc{ii}iiiiic{dd}dddddcccc{i}iiiiiic{dddd}iic{iiii}dc{dd}iiiccccc{ii}ddc{dd}iiccccc{ii}dc{dd}iccccc{ii}c{dd}ccccc{ii}ic{dd}dccccc{ii}iic{dd}ddccccc{ii}iiic{dd}dddccccc{ii}iiiic{dd}ddddccccc{ii}iiiiic{dd}dddddccccc{i}iiiiiic{dddd}iic{iiii}dc{dd}iiicccccc{ii}ddc{dd}iicccccc{ii}dc{dd}icccccc{ii}c{dd}cccccc{ii}ic{dd}dcccccc{ii}iic{dd}ddcccccc{ii}iiic{dd}dddcccccc{ii}iiiic{dd}ddddcccccc{ii}iiiiic{dd}dddddcccccc{i}iiiiiic{dddd}iic{iiii}dc{dd}iiiccccccc{ii}ddc{dd}iiccccccc{ii}dc{dd}iccccccc{ii}c{dd}ccccccc{ii}ic{dd}dccccccc{ii}iic{dd}ddccccccc{ii}iiic{dd}dddccccccc{ii}iiiic{dd}ddddccccccc{ii}iiiiic{dd}dddddccccccc{i}iiiiiic{dddd}iic{iiii}dc{dd}iiicccccccc{ii}ddc{dd}iicccccccc{ii}dc{dd}icccccccc{ii}c{dd}cccccccc{ii}ic{dd}dcccccccc{ii}iic{dd}ddcccccccc{ii}iiic{dd}dddcccccccc{ii}iiiic{dd}ddddcccccccc{ii}iiiiic{dd}dddddcccccccc{i}iiiiiic{dddd}iic

```

# Answer
> 2 votes
# Excel, 74 bytes

```
=LET(x,MOD(COLUMN(A:J),10),CONCAT(x&IF(x,REPT(" ",ABS(ROW(1:17)-9)),"
")))

```

Link to Spreadsheet

The version without LET that would have been valid when the question was asked is only 2 bytes longer.

## Without LET, 76 bytes

```
=CONCAT(RIGHT(COLUMN(A:J))&IF(COLUMN(A:J)>9,"
",REPT(" ",ABS(ROW(1:17)-9))))

```

# Answer
> 2 votes
# Vyxal `j`, 11 bytes

```
8ʀṘ∞ƛ9ʀǓ$Ij

```

Try it Online!

```
8ʀṘ∞ƛ9ʀǓ$Ij
8ʀ          # Range [0, 8]
  Ṙ         # Reverse
   ∞        # Palindromise, append reverse without first element.
            # Produces [8, 7, 6, ..., 1, 0, 1, 2, ..., 7, 8]
    ƛ       # For each:
     9ʀ     # Range [0, 9]
       Ǔ    # Rotate it left to make [1,2,3,4,5,6,7,8,9,0]
        $   # Swap so the current element is at the top
         I  # Push that many spaces
          j # Join the number list by these spaces
            # j flag joins on newlines

```

# Answer
> 2 votes
# Thunno 2 `N`, 11 bytes

```
9LrⱮıṣkDỤsj

```

Try it online!

#### Explanation

```
9LrⱮıṣkDỤsj  # Implicit input
9L           # Push [0..9)
  r          # Reverse it
   Ɱ         # And palindromise that
    ı        # Map over this list:
     ṣ       #  Push that many spaces
      kDỤ    #  Push "1234567890"
         sj  #  Join it by the spaces
             # Join on newlines
             # Implicit output

```

# Answer
> 2 votes
# Swift 5.9, 106 bytes

```
for i in(1..<9)+(1...9).reversed(){(1...10).map{print($0%10,terminator:{String.init}()(" ",9-i))};print()}

```

# Answer
> 1 votes
# Cheddar, 42 bytes

```
-8|>8=>n->print(1|>9+[0]).join(abs(n)*' ')

```

Try it online!

# Answer
> 1 votes
# Stacked, 33 bytes

```
9:>' '*[9~>\#`]"!:8~>#rev\,$out"!

```

Try it online!

## Explanation

```
9:>' '*[9~>\#`]"!:8~>#rev\,$out"!
9:>                                 range from 0 to 9 (right-exclusive)
   ' '*                             vectorized repetition of the space
       [      ]"!                   on each repetition:
        9~>                           generate a range from 1 to 9
           \#`                        and join it by that repetition
                 :8~>#              copy all but the first element
                      rev           reverse it
                         \,         swap then concatenate
                           $out"!   output each

```

# Answer
> 1 votes
# ///, 251 bytes

```
/B/' //A/!!//@/" //?/\/\///>/  ?=/0
1?</ 2 3 4 5 6 7 8 9 ?;/!2!3!4!5!6!7!8!9!?:/'2'3'4'5'6'7'8'9'?-/="2"3"4"5"6"7"8"9"=?,/@2@3@4@5@6@7@8@9@?'/!"?&/=>2>3>4>5>6>7>8>9>=?%/=A2A3A4A5A6A7A8A9A=?#/1B2B3B4B5B6B7B8B9B0?"/! ?!/> /#
1:%,-;&<=23456789=<&;-,%:0
#

```

Try it online! Or here, interactively!

Considerably long, but /// has no real way of modifying data elegantly.

# Answer
> 1 votes
# Delphi / Pascal 137 Bytes\*

```
program x;{$APPTYPE CONSOLE}var i,j: Integer;begin for i:=-8 to 8do begin write(#10,1); for j:=2 to 10do Write(j mod 10:Abs(i)+1);end;end.

```

\*The `{$APPTYPE CONSOLE}` is a compiler directive that can be removed for pure Pascal. or if compiled with the Delphi command line compiler using the -cc switch to give **119 bytes**. Without it you get a runtime error as it tries to print to a non existent console.

# Answer
> 1 votes
# \[Java 7\], ~~137~~ 132 bytes

Saved 3 bytes thanx to Kevin Cruijssen and 2 more thanx to TheLethalCoder

```
void a(){int i,j,k;for(i=-8;i<9;i++){String a="";for(j=1;j<11;j++){a+=j%10;for(k=0;k<(i<0?-i:i);k++)a+=" ";}System.out.println(a);}}

```
~~```
 void a(){for(int i=-8;i<9;i++){String a="";for(int j=1;j<11;j++){a+=j%10;for(int k=0;k<Math.abs(i);k++){a+=" ";}}System.out.println(a);}}

```~~

Ungolfed:

```
  void a(){
    int i,j,k;
    for(i=-8;i<9;i++){
        String a="";
        for(j=1;j<11;j++){
            a+=j%10;
            for(k=0;k<(i<0?-i:i);k++)a+=" ";
        }
        System.out.println(a);
    }
}

```

# Answer
> 1 votes
# C#, 131 bytes

My first participation

```
for(int i=8;i>-9;i--){for(int n=1;n<=10;n++){Console.Write((n==10?"0":n.ToString())+new String(' ',Math.Abs(i))+(n==10?"\n":""));}}

```

More easy reading version

```
for (int i = 8; i > -9; i--)
{
    for (int n = 1; n <= 10; n++)
    {
        Console.Write((n==10 ? "0" : n.ToString()) + new String(' ', Math.Abs(i)) + (n == 10 ? "\n" : ""));
    }
}

```

# Answer
> 1 votes
# tcl, 112

Very naïve:

```
proc x n\ s {time {puts [join {1 2 3 4 5 6 7 8 9 0} [format %[incr n $s]s \ ]]} 9}
x 10 -1
puts 1234567890
x 0 1

```

# demo

# Answer
> 1 votes
# /// (Slashes), ~~377~~ 374 bytes

```
/a/1_//b/2_//c/3_//d/4_//e/5_//f/6_//g/7_//h/8_//i/9_//z/0
//./  //-/. //_/../a_b_c_d_e_f_g_h_i_za-b-c-d-e-f-g-h-i-za.b.c.d.e.f.g.h.i.za b c d e f g h i zabcdefghiz1-2-3-4-5-6-7-8-9-z1.2.3.4.5.6.7.8.9.z1 2 3 4 5 6 7 8 9 z123456789z1 2 3 4 5 6 7 8 9 z1.2.3.4.5.6.7.h.9.z1-2-3-4-5-6-7-8-9-zabcdefghiza b c d e f g h i za.b.c.d.e.f.g.h.i.za-b-c-d-e-f-g-h-i-za_b_c_d_e_f_g_h_i_0

```

**Try it online!**

## Explanation

The original output was initially compressed by doing the following replacements:

* *(4 spaces)*`_`
* *(3 spaces)*`-`
* *(2 spaces)*`.`

In a second step, `1_` was replaced by `a`, `2_` by `b` and so on. Finally, those mappings were inverted and prepended to the code.

Additional step (thx to CalculatorFeline):

`/./  //-/   //_/    /``/_/..//-/. //./  /`

# Answer
> 1 votes
# Sink, ~~102~~ 100 bytes

```
var v=range 0,17
var p=list.push(range 0,10),0
for var s:v
say list.join p,str.pad"",num.abs s-8
end

```

Try it online! (sort of, it's just a repl so you'll need to type it in)

-2 bytes thanks to @Kevin Cruijssen

# Answer
> 1 votes
# Lua, 106 85 bytes

-21 bytes thanks to user202729

```
n="1L2L3L4L5L6L7L8L9L0"for i=-8,8,1 do print((n:gsub("L",(" "):rep(math.abs(i)))))end

```

Output has a trailing newline

Ungolfed

```
n="1L2L3L4L5L6L7L8L9L0"
for i=-8,8,1 do
    print((n:gsub("L",(" "):rep(math.abs(i)))))
end

```

Try It Online

# Answer
> 1 votes
# brainfuck, 209 bytes

```
++++++++[->+>+>+>++++>++++++>+>>+<<<<<<<<]>++>+>+>>>>>+<<<<<<-[->>>>>>[-<<<+.>[-<<.>>>+<]>[-<+>]>>+<]>[-<+<<<->>>>]<<<-<.<<<<.>]>[->>>>>[-<<<+.>>>>>[->+<<<<<<<.>>>>>>]>[-<+>]<<+<]>[-<+<<<->>>>]>+<<<<<.<<<<.>>]

```

Try it online!

I noticed there wasn’t a brainfuck submission yet, so I gave it my best shot. Definitely not the most golfed solution possible, but I’m not upset with the result.

# Answer
> 1 votes
## Canvas, ~~20~~ 15 bytes

```
９｛９∔ ×９Ｒ0∔∑；＊］─

```

Try it here!

Explanation:
```
９｛９∔ ×９Ｒ0∔∑；＊］─  | (Full code)
                        | Print (implicit)
    ９∔ ×               | 9-i spaces
         ９Ｒ0∔∑；＊    | Inserted between the characters of the string "1234567890"
９｛                    | For each i in [1-9]
                   ］   | Separated by newlines
                     ─  | Palindromized vertically with 1 line of overlap

```

# Answer
> 1 votes
# VBA, 58 bytes

An immediate window function that takes no input and outputs to the console.

```
For i=-8To 8:For j=1To 9:?j &""Spc(Abs(i));:Next:?"0":Next

```

### Ungolfed and Commented

```
For i=-8To 8        ''  Iterate `i` from `-8` to `8`
For j=1To 9         ''  Iterate `j` from `1` to `9`
?j &""Spc(Abs(i));  ''  Print `j` and `i` spaces
Next                ''  Loop `j`
?"0"                ''  Print `0`, with a newline
Next                ''  Loop `i`

```

# Answer
> 1 votes
# QBasic, 66 bytes

An undeclared subroutine that takes no input and outputs to STDOUT

```
FOR i=-8TO 8
FOR j=49TO 57
?CHR$(j)SPC(ABS(i));
NEXT
?"0
NEXT

```

# Answer
> 1 votes
# JavaScript, 71 bytes

```
f=(i=8,q=[..."1234567890"].join(" ".repeat(i)))=>i?q+`
`+f(i-1)+`
`+q:q

```

# Answer
> 1 votes
# Elixir, 126 bytes

```
Enum.each 8..-8,fn n->IO.puts Enum.map Enum.into(1..10,[],&(rem &1,10)),&(Integer.to_string(&1)<>String.duplicate" ",abs n)end

```

Try it online!

```
Enum.each 8..-8,
          fn n->
            IO.puts
              Enum.map
                Enum.into(1..10, [], &(rem &1,10)),
                &(Integer.to_string(&1) <> String.duplicate" ",abs n)
          end

```

For each number in the range 8 to -8, do this anonymous function with the number as `n`. The function (inner to outer) sets the range 1 to 10 into a list after applying the remainder mod 10 (so we have the list 1,2,3,4,5,6,7,8,9,0). Then maps that list of numbers into strings, and concatenates the absolute value of `n` spaces onto the end. After getting each string we print out the whole list of strings... and Elixir doesn't put any delimiter on that by default.

Output:

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

```

# Answer
> 1 votes
# Pip `-l`, ~~18~~ 16 bytes

```
(\,t)%tJsXPZRV,9

```

Try it online!

### Explanation

```
                  t is 10, s is " " (implicit)
              ,9  Range(9): [0 1 2 3 4 5 6 7 8]
            RV    Reverse: [8 7 6 5 4 3 2 1 0]
          PZ      Palindromize: [8 7 6 5 4 3 2 1 0 1 2 3 4 5 6 7 8]
        sX        For each element of the above list, a string of that many spaces
 \,t              Inclusive-range(10): [1 2 3 4 5 6 7 8 9 10]
(   )%t           Mod 10: [1 2 3 4 5 6 7 8 9 0]
       J          For each string of spaces, join the above list on that string
                  Output the list of results one per line (`-l` flag)

```

---

The `PZ` operator was added more than a year after this challenge was posted, so here's a 17-byte answer that would have worked at that time:

```
(\,t)%tJsXAB:-8,9

```

Try it online!

# Answer
> 1 votes
# Sisi, 239 bytes

```
0set s8
1set d0-1
2set o""
3set i1
4set o o+i
5jumpif i7
6jump17
7set x s
8jump11
9set o o+" "
10set x x-1
11jumpif x9
12set c9>i
13jumpif c15
14set i0-1
15set i1+i
16jump4
17print o
18set s s+d
19jumpif s21
20set d1
21set q9>s
22jumpif q2

```

Try it online!

The basic strategy is to run a loop from 8 down to 0 and back up to 8, constructing each line accordingly and printing it. I'm not going to write a detailed explanation, but if you're trying to follow the algorithm, the following key to the variable names may be helpful:

* `s`: number of spaces to print between digits
* `d`: direction of change in `s` (-1 or 1)
* `o`: the current line of output
* `i`: the current digit
* `x`: loop counter while printing spaces
* `c`: conditional that tests whether `i` is less than 9 (if not, we set it to -1 so it gets incremented to 0 instead of 10)
* `q`: conditional that tests whether `s` is less than 9 (if so, we continue looping)

# Answer
> 1 votes
# ///, 244 bytes

```
/*/\/\///X/0
1*j/\/X*x/  *S/x *s/SS*-/S *_/s *(/- *)/_ *A/)2)3)4)5)6)7)8)9)*Bj_2_3_4_5_6_7_8_9_*Cjs2s3s4s5s6s7s8s9s*Dj(2(3(4(5(6(7(8(9(*Ej-2-3-4-5-6-7-8-9-*FjS2S3S4S5S6S7S8S9S*Gjx2x3x4x5x6x7x8x9x*Hj 2 3 4 5 6 7 8 9 /1ABCDEFGHX23456789HGFEDCBXA0

```

Try it online!

# Answer
> 1 votes
# Pushy, 27 bytes

Not the most elegant solution, but it does the job.

```
N9X@wL:Ocv:32;ZT:hT%#^"v;T'

```

Try it online!

Explanation:

```
N                                \ Set printing delimiter to empty string
 9X                              \ Push range(9) to stack: [0, 1, 2, 3, 4, 5, 6, 7, 8]
   @                             \ Reverse: [8, 7, 6, 5, 4, 3, 2, 1, 0]
    w                            \ Mirror: [8, 7, 6... 1, 0, 1... 6, 7, 8]
     L:                          \ Length (17) times do:
       Oc                        \   Go to (cleared) auxiliary stack
         v:                      \   Pop top of main stack, and that many times:
           32;                           Push character 32 (space)
              Z                  \   Push 0
               T                 \   Ten times do:
                :hT%             \      counter = (counter + 1) mod 10
                    #            \      Print the counter
                     ^"v;        \      Print the rest of the stack (spaces)
                         T'      \   Print a newline

```

# Answer
> 1 votes
# Tcl, 99 bytes

```
time {incr i;time {puts -nonewline [incr j][string repe " " [expr abs(9-$i)]]} 9;puts 0;unset j} 17

```

Try it online!

# Answer
> 1 votes
# Rockstar, ~~127~~ ~~126~~ 124 bytes

-1 byte thanks to Kevin

```
F takes X
cut 1234567890 into L
join L with " "*X
say L

X's9
while X
let X be-1
F taking X

while X-8
let X be+1
F taking X

```

Try it here (Code will need to be pasted in)

# Answer
> 1 votes
# Stax, 12 bytes

```
ü¡↑├☼Rσ┬q▄└m

```

Run and debug it

can probably tie mathgolf. Port of Emigna's answer.

# Answer
> 1 votes
# BRASCA, 72 bytes

```
8[a09Ir,m[oA:a[Eo{]x]xloA{]x09Ir,m[o]lo8[9$-a09Ir,m[oA:a[Eo{]x]xloA}9$-]

```

Try it online!

# Answer
> 1 votes
# Deadfish~, 2606 bytes

```
ioi{iii}cccccccc{ddd}o{iii}ccccccccd{ii}ci{dd}cccccccc{ii}c{dd}cccccccci{ii}cd{dd}ccccccccii{ii}cdd{dd}ccccccccd{{{i}}}odsddddcccccccc{{{i}}}oddsddddcccccccci{ddd}soiii{ii}cccccccc{{d}}o{i}ci{d}oi{iii}ccccccc{ddd}o{iii}cccccccd{ii}ci{dd}ccccccc{ii}c{dd}ccccccci{ii}cd{dd}cccccccii{ii}cdd{dd}cccccccd{{{i}}}odsddddccccccc{{{i}}}oddsddddccccccci{ddd}soiii{ii}ccccccc{{d}}o{i}ci{d}oi{iii}cccccc{ddd}o{iii}ccccccd{ii}ci{dd}cccccc{ii}c{dd}cccccci{ii}cd{dd}ccccccii{ii}cdd{dd}ccccccd{{{i}}}odsddddcccccc{{{i}}}oddsddddcccccci{ddd}soiii{ii}cccccc{{d}}o{i}ci{d}oi{iii}ccccc{ddd}o{iii}cccccd{ii}ci{dd}ccccc{ii}c{dd}ccccci{ii}cd{dd}cccccii{ii}cdd{dd}cccccd{{{i}}}odsddddccccc{{{i}}}oddsddddccccci{ddd}soiii{ii}ccccc{{d}}o{i}ci{d}oi{iii}cccc{ddd}o{iii}ccccd{ii}ci{dd}cccc{ii}c{dd}cccci{ii}cd{dd}ccccii{ii}cdd{dd}ccccd{{{i}}}odsddddcccc{{{i}}}oddsddddcccci{ddd}soiii{ii}cccc{{d}}o{i}ci{d}oi{iii}ccc{ddd}o{iii}cccd{ii}ci{dd}ccc{ii}c{dd}ccci{ii}cd{dd}cccii{ii}cdd{dd}cccd{{{i}}}odsddddccc{{{i}}}oddsddddccci{ddd}soiii{ii}ccc{{d}}o{i}ci{d}oi{iii}cc{ddd}o{iii}ccd{ii}ci{dd}cc{ii}c{dd}cci{ii}cd{dd}ccii{ii}cdd{dd}ccd{{{i}}}odsddddcc{{{i}}}oddsddddcci{ddd}soiii{ii}cc{{d}}o{i}ci{d}oi{iii}c{ddd}o{iii}cd{ii}ci{dd}c{ii}c{dd}ci{ii}cd{dd}cii{ii}cdd{dd}cd{{{i}}}odsddddc{{{i}}}oddsddddci{ddd}soiii{ii}c{{d}}o{i}ciio{d}ioioioioioioioi{d}o{i}ci{d}oi{iii}c{ddd}o{iii}cd{ii}ci{dd}c{ii}c{dd}ci{ii}cd{dd}cii{ii}cdd{dd}cd{{{i}}}odsddddc{{{i}}}oddsddddci{ddd}soiii{ii}c{{d}}o{i}ci{d}oi{iii}cc{ddd}o{iii}ccd{ii}ci{dd}cc{ii}c{dd}cci{ii}cd{dd}ccii{ii}cdd{dd}ccd{{{i}}}odsddddcc{{{i}}}oddsddddcci{ddd}soiii{ii}cc{{d}}o{i}ci{d}oi{iii}ccc{ddd}o{iii}cccd{ii}ci{dd}ccc{ii}c{dd}ccci{ii}cd{dd}cccii{ii}cdd{dd}cccd{{{i}}}odsddddccc{{{i}}}oddsddddccci{ddd}soiii{ii}ccc{{d}}o{i}ci{d}oi{iii}cccc{ddd}o{iii}ccccd{ii}ci{dd}cccc{ii}c{dd}cccci{ii}cd{dd}ccccii{ii}cdd{dd}ccccd{{{i}}}odsddddcccc{{{i}}}oddsddddcccci{ddd}soiii{ii}cccc{{d}}o{i}ci{d}oi{iii}ccccc{ddd}o{iii}cccccd{ii}ci{dd}ccccc{ii}c{dd}ccccci{ii}cd{dd}cccccii{ii}cdd{dd}cccccd{{{i}}}odsddddccccc{{{i}}}oddsddddccccci{ddd}soiii{ii}ccccc{{d}}o{i}ci{d}oi{iii}cccccc{ddd}o{iii}ccccccd{ii}ci{dd}cccccc{ii}c{dd}cccccci{ii}cd{dd}ccccccii{ii}cdd{dd}ccccccd{{{i}}}odsddddcccccc{{{i}}}oddsddddcccccci{ddd}soiii{ii}cccccc{{d}}o{i}ci{d}oi{iii}ccccccc{ddd}o{iii}cccccccd{ii}ci{dd}ccccccc{ii}c{dd}ccccccci{ii}cd{dd}cccccccii{ii}cdd{dd}cccccccd{{{i}}}odsddddccccccc{{{i}}}oddsddddccccccci{ddd}soiii{ii}ccccccc{{d}}o{i}ci{d}oi{iii}cccccccc{ddd}o{iii}ccccccccd{ii}ci{dd}cccccccc{ii}c{dd}cccccccci{ii}cd{dd}ccccccccii{ii}cdd{dd}ccccccccd{{{i}}}odsddddcccccccc{{{i}}}oddsddddcccccccci{ddd}soiii{ii}cccccccc{{d}}o

```

Try it online!

Deadfish~ has two output commands, `o` to print the accumulator as an integer and `c` to print a character. All whitespace is printed with `c`, and 84 of the 190 digits are printed with `c`, determined by an exhaustive search. If you're interested, here is the semi-golfed and fully unreadable generator: Try it online!

# Answer
> 1 votes
# Java (JDK), ~~105~~ 103 bytes

```
a->{for(int j,i=-9;i++<8;){var s="";for(j=0;j++<9;)s+=j+" ".repeat(i<0?-i:i);System.out.println(s+0);}}

```

Try it online!

Thanks to ceilingcat for -2

# Answer
> 1 votes
# Scala, ~~77~~ 76 bytes

```
(for(i<- -8 to 8)yield"1234567890".mkString(" "*math.abs(i)))foreach println

```

Try it online

Thanks Kevin Cruijssen for 1 byte saved!

# Answer
> 1 votes
# Vyxal `Ṁjr`, 10 bytes

```
₀ƛIkdǓj;Ṙ∞

```

Try it Online!

port of my vyxal 3 answer

# Answer
> 0 votes
# Python 2, 72 bytes

```
for i in range(-8,9):print(('%-'+'%ds'%-~abs(i))*10)%tuple('1234567890')

```

Try it online!

# Answer
> 0 votes
# Vim, 53 bytes

```
i1234567890^[^qq8a ^[lq8@qqeYpPqqqlxbequ^qw9@q@eq7@wdj

```

Where `^[` is the `ESC` Key.

```
i1234567890^[^       puts 1-9+0 in the buffer and returns the cursor to the beginning
qq8a ^[lq8@q         puts 8 spaces between each of the numbers
qeYpPq               records @e to duplicate the line twice and stay on the middle one
qqlxbequ^            records @q to delete one space between numbers and undoes it
qw9@q@eq             records @w to do @q 9 times, then @e
7@wdj                does @w 7 more times, then deletes two lines

```

# Answer
> 0 votes
# Python, 84 bytes

```
for x in range(-8,9):
 z=""
 for y in range(1,11):z+=str(y%10)+" "*abs(x)
 print(z)

```

Try it online

# Answer
> 0 votes
# Vyxal 3 `j`, 12 bytes

```
₀ƛkdṘmð×j]Ṛṅ

```

Try it Online!

---
Tags: code-golf, ascii-art, number, kolmogorov-complexity
---


title: Implement the Riemann R function

text:
# Question
Title: Implement the Riemann R function
The Riemann R function is as follows:

$$R (x)=\sum \_{n=1}^{\infty } \frac{\mu (n) \text{li}\left(x^{1/n}\right)}{n}.$$

This uses the Möbius function as well as the logarithmic integral.

From Wikipedia, the Möbius function is defined so that for any positive integer \\$n\\$, \\$μ(n)\\$ is the sum of the primitive nth roots of unity. It has values in \\$\\{−1, 0, 1\\}\\$ depending on the factorization of \\$n\\$ into prime factors:

* \\$μ(n) = +1\\$ if \\$n\\$ is a square-free positive integer with an even number of prime factors.
* \\$μ(n) = −1\\$ if \\$n\\$ is a square-free positive integer with an odd number of prime factors.
* \\$μ(n) = 0\\$ if \\$n\\$ has a squared prime factor.

The logarithmic integral is defined as:

$$\operatorname{li}(x) = \int\_2^x \frac{dt}{\log t}.$$

An alternative way to compute the Riemann R function is via the Gram series. That is:

$$R(x) = 1 + \sum\_{k=1}^{\infty}\frac{(\ln x)^k}{k k!\zeta(k+1)}.$$

The function \\$\zeta()\\$ is the Riemann zeta function.

# Challenge

Write code that computes \\$R(x)\\$ for \\$x\\$ up to \\$10^{31}\\$. The output may have a margin of error of up to 1.

# Test cases

Here are the answers for \\$10^i\\$ for \\$i = \\{1, 2, \dots, 31\\}\\$.

```
1 4.56458314100509023986577469558
2 25.6616332669241825932267979404
3 168.359446281167348064913310987
4 1226.93121834343310855421625817
5 9587.43173884197341435161292391
6 78527.399429127704858870292141
7 664667.447564747767985346699887
8 5761551.86732016956230886495973
9 50847455.4277214275139488757726
10 455050683.306846924463153241582
11 4118052494.63140044176104610771
12 37607910542.2259102347456960174
13 346065531065.82602719789292573
14 3204941731601.68903475050075412
15 29844570495886.9273782222867278
16 279238341360977.187230253927299
17 2623557157055978.00387546001566
18 24739954284239494.4025216514448
19 234057667300228940.234656688561
20 2220819602556027015.40121759224
21 21127269485932299723.733864044
22 201467286689188773625.159011875
23 1925320391607837268776.08025287
24 18435599767347541878146.803359
25 176846309399141934626965.830969
26 1699246750872419991992147.22186
27 16352460426841662910939464.5782
28 157589269275973235652219770.569
29 1520698109714271830281953370.16
30 14692398897720432716641650390.6
31 142115097348080886394439772958.0

```

Your code doesn't need to be fast, but ideally it should complete in under a minute.

# Related challenges

---

# Precision

You will need 128 bit floats to represent the output. In C `__float128` from `quadmath.h` is the simplest way (`long double` will most likely be 80 bits). Other languages may have standard libraries to support 128 bit floats (e.g Decimal in Python). challenges are judged *per language* so there is no penalty in using whatever is needed for your favorite langauge.

# Answer
# Wolfram Language (Mathematica), 8 bytes

```
RiemannR

```

Try it online!
> 11 votes

# Answer
# PARI/GP, 40 bytes

```
x->1+suminf(k=1,log(x)^k/k/k!/zeta(k+1))

```

Attempt This Online!

Using the Gram series.
> 11 votes

# Answer
# C (gcc), ~~193 183 173 165 154 145~~ 144 bytes

```
typedef _Float128 X;X logq();i,k;r(X x,X*y){for(X a=*y=k=1,q;i=999,k<i;*y-=(ldexp(a*=logq(x)/k++,-k)-a)/q)for(q=0;--i;)q+=(i%2?k:-k)*pow(i,~k);}

```

Try it online!

This estimates the Riemann R function from the Gram series. Note that this uses a horribly obfuscated but faster converging implementation of the Riemann zeta function.

$$\zeta(s)=\frac{1}{1-2^{1-s}}\sum\_{n=1}^{\infty}\frac{(-1)^{n+1}}{n^s}$$

-1 thanks to @Simd. -8 thanks to @c--.

Slightly golfed less:

```
typedef _Float128 X;
X logq();
i,k;
r(X x,X*y){
  for(X a=*y=k=1,q;i=999,k<i;){
    /* estimate the Riemann zeta function */
    for(q=0;--i;)
      q+=(i%2?k:-k)*pow(i,~k);
    *y-=(ldexp(a*=logq(x)/k++,-k)-a)/q
  }
}

```
> 9 votes

# Answer
# Vyxal, 44 bytes

```
Þ∞KƛƛÞ∞K$›eĖṠ2l≬₈vḞ≈c*n¡*?∆Lne$/;∑;2l≬₈vḞ≈c›

```

Try it Online!

I think this is correct. Might be 38 if there's an exact limit convergance somehow.

Precision is met by having a) things evaluated to 256 decimal places when approximating and b) exact values used until an approximation is needed. Good luck getting this to return an actual answer in the time we have left in the universe. The algorithm should be correct though.

## Explained

The main idea to find the sums of things with an infinite upper bound is to check every overlapping pair of items in an infinite list of the sum applied from `1..1`, `1..2`, `1..3`, and so on until the pair has all the same items. This is basically checking for convergence manually.

```
Þ∞Kƛ...;2l≬₈vḞ≈c›
Þ∞Kƛ   ;          # Calculate the gram series for all possible upper bounds
        2l        # get all the overlapping pairs
          ≬₈vḞ≈c  #  and get the first where the items to 256 decimal places are the same
                › # increment

```

```
ƛÞ∞K$e›ĖṠ2l≬₈vḞ≈c*n¡*?∆Lne$/;∑  # Note that the context variable is set to whatever number in a prefix in the prefix is being gram seriesed is being zeta'd
 Þ∞K                            # To each prefix of an infinite list of positive integers
    $e›ĖṠ2l≬₈vḞ≈c                # Zeta function
                 *              # times k
                  n¡*           # times k!
                     ?∆Lne$/    # log(input) ** k divided by above
                            ;∑  # sum the result of apply to each k

```

```
$e›ĖṠ2l≬₈vḞ≈c # the top of the stack is the prefix list
$e›           # each number in each prefix to the power of k + 1
   Ė          # reciprocal of each number in each prefix
    Ṡ         # sum of each prefix
     2l       # overlapping pairs of sums
       ≬₈vḞ≈c # first item where pair is all the same to 256 decimal places.

```
> 4 votes

# Answer
# Python \+ SymPy, ~~103~~ 99 bytes

```
lambda x:1+Sum(ln(x)**k/k/gamma(k+1)/zeta(k+1),(k,1,oo)).evalf(50)
from sympy import*;k=Symbol('k')

```

Attempt This Online! Takes ~30s on ATO for all 31 test cases.
> 4 votes

# Answer
# Julia, ~~141 138 133 125~~ 81 bytes

```
h(x,a=big(1.))=1-sum(k->(a*=log(x)/k)/sum(n->(-1)^n/n/n^k,1:99)/k*(1-2^-k),a:200)

```

-44 thanks to @MarcMush

Try it online!

Slightly less golfed.

```
function h(x)
  B=BigFloat
  a=y=B(1);
  for K=1:200
    q=0;
    k=B(K);
    for n=1:99
      q-=(-1)^n/n/n^k
    end;
    a*=log(x)/k;
    y+=a/q/k*(1-2^-k)
  end;
  y
end

```

# Julia using zeta() builtin, ~~209~~ 205 bytes

```
using Base.MPFR
function h(x)B=BigFloat;a=y=B(1);for K=1:187 k=B(K);a*=log(x)/k;z=B();ccall((:mpfr_zeta,:libmpfr),Int8,(Ref{BigFloat},Ref{BigFloat},Int8),z,k+1,Base.MPFR.ROUNDING_MODE[]);y+=a/k/z end;y end

```

Try it online!

Slightly golfed less.

```
using Base.MPFR
function h(x)
  B=BigFloat;
  a=y=B(1);
  for K=1:187
    k=B(K);
    a*=log(x)/k;
    z=B();
    ccall((:mpfr_zeta,:libmpfr),Int8,(Ref{BigFloat},Ref{BigFloat},Int8),z,k+1,Base.MPFR.ROUNDING_MODE[]);
    y+=a/k/z
  end;
  y
end

```
> 4 votes

# Answer
# Python \+ mpmath, 28 bytes

```
from mpmath import*
riemannr

```

Attempt This Online!

## Not using the builtin, 84 bytes

```
from mpmath import*
f=lambda x:1+nsum(lambda k:log(x)**k/k/fac(k)/zeta(k+1),[1,inf])

```

Attempt This Online!
> 3 votes

# Answer
# APL(NARS), 330 chars

```
F←{0⌈(⌊1+10⍟⍵)-⍨⌊3.322÷⍨⎕fpc-1}

r←p z q;n;t;w;m;d;y;h;e
→2×⍳∼q=1⋄r←∞⋄→0
t←q×¯1v⋄r←q-q⋄e←÷10x*p⋄n←0v⋄w←1v
→7×⍳e>w×←0.5v
y←d←1v⋄h←n+1⋄m←0v
h-←1⋄y+←(t*⍨m+1)×d×←¯1×h÷m+←1⋄→5×⍳m<n
r+←w×y⋄n+←1⋄→3
r÷←1-2*1+t

r←R q;L;n;d;m;e;y
y←q×1v⋄r←1v⋄L←⍟y⋄n←0⋄d←1v⋄e←÷10x*2+F q
r+←m←(÷n×(⌊⎕fpc÷3.5)z n+1)×d×←L÷n+←1⋄→2×⍳e<∣m

⍪{{⍵⍕⍨1⌈¯8+F⍵}R⍵}¨10v*1..31

```

32+ 24+16+33+14+18+38+15+10 +18+39+45 +28=330

z should be the Riemann Zeta function that stop calc until p digits after the decimal point, with input one number that should be integer, float, big float,complex, big float clomplex and one output that has to be big float or big float complex (I'm not sure of this speech 100%). It seems if the number is not a complex the calculation in z function is done not use complex operations but only float or big float operations. I'm not sure is safe to use ∞ as result for zeta in case input 1.

R it seems to be the Riemann R function cut on the possible digits it can reach from the instruction (⌊⎕fpc÷4.1) for speed reason, seen what the question ask too.

It seems:

1. ⎕fpc it is the lenght in bit of the float point number of type "NumbeRv"
2. ⌊1+10⍟⍵ it should be the lenght in decimal digit of the integer part of number in ⍵
3. ⌊3.322÷⍨⎕fpc-1 it should be the lenght in decimal digit of each float type "NumbeRv"
4. F ⍵ it should be the max lenght in decimal digit of fractional part number in ⍵, so it is the right place where end the computation
5. It seems is asked one decimal ¯8 + teoretical possible 128 bit precision for the calculus and for show the number
6. In function (r←p z q), if it was used the instruction r←q-q the calculation in z not use big complex float, but only big float
7. It seems 2+F q is safe as precision for R q (not for all other numbers return z function in R)

```
   ⍪{{⍵⍕⍨1⌈¯8+F⍵}R⍵}¨10v*1..31

```

4.56458314100509023986577469558
25.6616332669241825932267979404
168.359446281167348064913310987
1226.93121834343310855421625817
9587.43173884197341435161292391
78527.3994291277048588702921410
664667.447564747767985346699888
5761551.86732016956230886495974
50847455.4277214275139488757726
455050683.306846924463153241582
4118052494.63140044176104610771
37607910542.2259102347456960174
346065531065.826027197892925730
3204941731601.68903475050075412
29844570495886.9273782222867278
279238341360977.187230253927299
2623557157055978.00387546001566
24739954284239494.4025216514448
234057667300228940.234656688561
2220819602556027015.40121759224
21127269485932299723.7338640440
201467286689188773625.159011875
1925320391607837268776.08025287
18435599767347541878146.8033590
176846309399141934626965.830969
1699246750872419991992147.22186
16352460426841662910939464.5782
157589269275973235652219770.569
1520698109714271830281953370.16
14692398897720432716641650390.6
142115097348080886394439772958.2

one calculation that takes 15' here... it is possible change the number of bit of big float for to have

```
   ⎕fpc←64
   ⍪{{⍵⍕⍨F⍵}R⍵}¨10v*⍳3
4.56458314100509191
25.6616332669242044
168.359446281167561

```

with the last 3 or 4 decimal digits wrong it seems for the instruction
(⌊⎕fpc÷4.1) that should be (⌊⎕fpc÷3.322) for to have what it seems to me the exact solution (with about 2x the time for calculus here some second only for this)

```
   ⍪{{⍵⍕⍨F⍵}R⍵}¨10v*⍳3
4.56458314100509024
25.6616332669241826
168.359446281167348

```
> 2 votes

# Answer
# C (gcc), 354 bytes

```
#include <quadmath.h>
#define D __float128
#define U unsigned
D Z(U p,D q){D t=-q,y,d,r,w,e,h;U n,m;for(r=n=0,w=1,e=w/powq(10,p);(w*=0.5q)>e;++n,r+=w*y)for(y=d=m=1,h=n;m<=n;--h,++m)y+=powq(m+1,t)*(d*=-h/m);return r/=1-powq(2,1+t);}D Rr(D q){D r,l,d,e,m,n;for(m=d=r=n=1,l=logq(q),e=r/powq(10,31);e<fabsq(m);++n,r+=m)m=(d*=l/n)*(1/(n*Z(31,n+1)));return r;}

```

Try it online!

This should be the port with some change of APL NARS answer... a little long. Here printf can not print the number so it was need PP() for print in the screen the number. I minimize the function Rr and Z, skipping all ceck for arguments, but it seems take more than 1 minute so no result showed from the link...

This below is the version ungolfed, more long (only for 128 bit floats too) that ceck arguments but faster than above, and use the function Zeta could be right even for complex not only for the real part. 10 second is the run, so it is showed the result.

# C (gcc), 616 bytes

```
#include <quadmath.h>
#define U  unsigned
#define LD  __float128
#define CP __complex128
#define FM  FLT128_MAX
#define R   return
#define F   for
CP zeta(U p,CP q)
{CP t=-q,y,r,s[130],u;
 LD w,e,d,h;
 U  n,m,k;
 if(q==1||p>38)R FM;
 p+=p==0;k=2+p*3.322; // 38*3.322+2=128
 F(m=1,s[0]=0;m<k;++m)s[m]=cpowq(m,t);
 F(r=n=0,w=1,e=w/powq(10,p);(w*=0.5q)>e;++n,r+=w*y)
         F(y=d=m=1,h=n;m<=n;--h,++m)y+=(m+1>=k?cpowq(m+1,t):s[m+1])*(d*=-h/m);
 R r/=1-cpowq(2,1+t);
}

 LD Rr(LD q)
{LD r,l,d,e,m,t,n;
 F(m=d=r=n=1,l=logq(q),e=r/powq(10,31);e<fabsq(m);++n,r+=m)
           m=(d*=l/n)*(1/(n*zeta(31,n+1)));
 R r;
}

```

Try it online!
> 1 votes

---
Tags: code-golf, math, number-theory
---


title: Compiler for LaTeX

text:
# Question
Title: Compiler for LaTeX
## Problem:

Given a string representing a mathematical expression with constants (pi, e, psi, i), basic arithmetic operations (+, -, \*, /), parentheses, fractions, and exponentiation, write a program or function to convert a string to its equivalent LaTeX code. The input string will only contain digits, arithmetic operators, parentheses, spaces, and constants.

##### Example:

* **`Input:`** `2 + (3 * π) / (4 - e)^2`
* **`Output:`** `$2 + \frac{3\cdot\pi}{(4 - e)^2}$`
* **`Input:`** `π * 22/7 - 9.81`
* **`Output:`** `$\pi\cdot\frac{22}{7} - 9.81$`
* **`Input:`** `2 - e^i + 3^(32)*(2*ψ)/(7*π)`
* **`Output:`** `$2 - e^i + 3^{32}\cdot\frac{2\cdot\psi}{7\cdot\pi}$`

### Constraints:

* 0 \< `Input string` \< 100 chars.
* You need to implement fractions using the `\frac{}{}` command in LaTeX.

### Scoring:

This is , so the shortest code wins.

### Latex commands:

* `\pi` for the constant "π".
* `\psi` for the constant "ψ".
* `e` for the constant "e".
* `i` for the constant "i".
* `\cdot` for multiplication.
* `\frac{}{}` for fractions.
* `^` operator for exponentiation. "{}" for exponents are optional.
* The output should be enclosed in "$" or "$$" to indicate a math expression in LaTeX.

# Answer
# Tamsin, <sup>~~375~~ ~~220~~</sup> 211 bytes

```
1=2->E&'$'+E+'$'.2=3->R&{"/"&3->E&R<-'\\frac{'+R+'}{'+E+'}'}&(("-"|"+"|"*"&'\\cdot')->O&2->E&''+O+E)/R.3=(s&"("&2->E&")"&s&'('+E+')'|("π"&'\\pi'|"ψ"&'\\psi'|" "|$:alnum)/'')->R&("^"&3->E&'^{'+E+'}')/R.s={" "}.

```

Try it online!

Ungolfed and heavily commented version:

```
# expr1 (entrypoint); match `expr2` (store in E); return '$' + E + '$'
expr1 = expr2 -> E & '$' + E + '$'.

# implements "/", "-", "+", "*" over expr3
expr2 = expr3 -> R                             # match `expr3`    (store in R)
      & {                                      # while possible:
          "/"                                  #   match "/"
        & expr3 -> E                           #   match `expr3`  (store in E)
        & R <- '\\frac{' + R + '}{' + E + '}'  #   R = '\frac{' + R + '}{' + E + '}'
      } & (                                    # scope (
        ("-" | "+" | "*" & '\\cdot') -> O      #   match operator (store in O)
        & expr2 -> E                           #   match `expr2`  (store in E)
        & '' + O + E                           #   '' + O + E     (implicit return)
      )/R.                                     # ) match scope zero or more times then concatenate R and matches (implicit return)

# implements "()", numbers and "^"
expr3 = (                    # scope (
            spaces           #     match `spaces`
          & "("              #     match "("
          & expr2 -> E       #     match `expr1`   (store in E)
          & ")"              #     match ")"
          & spaces           #     match `spaces`
          & '(' + E + ')'    #     '(' + E + ')'   (implicit return)
        |                    #   or
          (                  #     scope (
              "π" & '\\pi'   #          match "π"  (replace with \pi)
            | "ψ" & '\\psi'  #       or match "ψ"  (replace with \psi)
            | " "            #       or match " "
            | $:alnum        #       or match alphanumeric [0-9A-Za-z]
          )/''               #     ) match scope zero or more times then concatenate matches (implicit return)
      ) -> R                 # ) store return from scope in R
      & (                    # scope (
        "^"                  #   match "^"
        & expr3 -> E         #   match `expr3`     (store in E)
        & '^{' + E + '}'     #   '^{' + E + '}'    (implicit return)
      )/R.                   # ) match scope zero or more times then concatenate R and matches (implicit return)

spaces = {" "}.  # zero or more spaces

# command to golf and copy to clipboard:
# sed 's/paces\|expr\| \|#.*//g; s/""/" "/g' latex.tamsin | tr -d '\n' | wl-copy

```
> 8 votes

# Answer
# Python 3, 513 bytes

```
from re import*
R=str.replace
def F(r,c):
	while'/^*'[c]in r:
		i=r.index('/^*'[c])
		r=r[:i-1]+[['\\frac{%s}{%s}','%s^{%s}','%s \\cdot %s'][c]%((c>0)*sub('(%\d+)([}]*)$','(\\1)\\2',r[i-1])or r[i-1],r[i+1])]+r[i+2:]
	return r
P=lambda e:R(R(' '.join(F(F(F(findall('%*[.\d]+|i|e|π|ψ|\+|-|\*|/|\^',e),1),0),2)),'π','\\pi'),'ψ','\\psi')
def f(e,t=[]):
	while'('in e:
		e=sub('\(([^()]*)\)',lambda m:f'%{(len(t),t.append(P(m[1])))[0]}',e)
	z=lambda e:t and z(R(e,f'%{len(t)-1}',t.pop()))or e
	return'$%s$'%z(P(e))

```

Try it online!

This took quite a while to golf down and for me to feel all right about it, but at this point I think I've done about all that I can without additional help. If we're allowed to go wild with parenthesis, then I can reduce this some more, but I'm not sure if just producing mathematically-equivalent LaTeX-accepted output is a valid solution.

The short explanation is that I use regex to replace inner parenthetical expressions with a meta token, inserting the LaTeX-ed version of that minimal expression into a work list, and after all parenthetical statements are replaced with meta tokens I go back and replace each meta token with its processed form, resulting in the fully LaTeX formatted string.

Full explanation:

```
# Needed for re.sub and re.findall
import re

'''
Parameters:	array - An array of tokens, or expressions, representing the current expression
		index - 0 for division, 1 for exponentiation, 2 for multiplication
Formats the provided array in one of three ways
    - Start by finding the index of the requested character
    - While that character is still a lone element in the array
        - Get the index of the requested opertor
        - Get the values on either side of the operator
        - Set the replacement string as appropriate for the operator
	    - If the operation is exponentiation or multiplication, we need to wrap the lefthand operand in parenthesis if it was a meta token (denoted by a token of the form '%<d>')
	- Replace indices (i - 1, i, and i + 1) with the LaTeX string representing the operation, and format the string to insert the formatted left and righthand sides
'''
def Format(array, index):
	c = '/^*'[index]	# Get the character we're doing formatting for
	while c in array:	# Do this until all standalone c have been formatted
		i = array.index('/^*'[index])		# Get the index into the list of c
		replacement = ''			# Placeholder for the text replacement
		l, r = array[i - 1], array[i + 1]	# The left and righthand sides of the operator

		# If division, insert l and r as-is in the {}'s
		if c == '/':
			replacement = '\\frac{%s}{%s}'

		# If exponentiation, we need to wrap the lefthand side with
		#  parenthesis iff it's a meta token (of the form '%\d+')
		elif c == '^':
			replacement = '%s^{%s}'
			# Find all occurrences of '%\d+' in array[i - 1]
			l = re.sub('(%\d+)([}]*)$', '(\\1)\\2', array[i-1])

		# If multiplication, we need to wrap the lefthand side with
		#  parenthesis iff it's a meta token (of the form '%\d+')
		elif c == '*':
			replacement='%s \\cdot %s'
			l = re.sub('(%\d+)([}]*)$', '(\\1)\\2', array[i-1])

		# Replace indices (i - 1, i, i + 1) with the LaTeX string,
		#  inserting our formatted left and righthand sides
		array = array[:i-1] + [replacement % (l, r)] + array[i+2:]

	# Return array as-is
	return array

# Takes a string expression of tokens and operators, and returns the string
#  representation of its LaTeX formatting
def Process(e):
	array = re.findall('%*[.\d]+|i|e|π|ψ|\+|-|\*|/|\^',e)	# Split the string into all valid tokens
	array = Format(array, 1)		# Format the list for exponentiation
	array = Format(array, 0)		# Format the list for division
	array = Format(array, 2)		# Format the list for multiplication
	string = ' '.join(array)		# Join all of the tokens in the expression
	string = string.replace('π','\\pi')	# Replace π with LaTeX command
	string = string.replace('ψ','\\psi')	# Replace ψ with LaTeX command
	return string				# Return the processed string

# The main function that performs the conversion
# Takes an expression, and uses a provided list to do work
def f(e, t=[]):
	# Define an inner function to hand to re.sub
	def helper(m):
		l = len(t)		# Get the current length of t
		t.append(Process(m[1]))	# Append the processed form of our matched group
		return f'%{l}'		# Return a meta token referencing the index in t we just added

	# While there are parenthesis still to parse through
	while '(' in e:
		# Find all occurrences of parenthesis with no parenthesis inside them
		#  and pass them to helper. This will replace an expression of the form
		#     (2 / ψ)
		#  with a meta token of the form
		#     %D
		#  where t[D] holds the LaTeX formatted representation of the expression
		#     t[D] = '\\frac{2}{\\psi}'
		e = re.sub('\(([^()]+)\)', helper, e)

	# Since we only processed sub-expressions, process the remainder
	e = Process(e)

	# Go through and replace each meta token with its true value
	# Since we added them 0->len(t)-1, we replace in reverse order
	#  by popping the values off of t
	while t:
		# Replace '%i' with the i-th value of t in our expression
		e = e.replace(f'%{len(t) - 1}', t.pop())

	# Finally wrap the expression in $'s and return
	return f'${e}$'

```
> 1 votes

---
Tags: code-golf, string, parsing
---


title: Mowing the Grass

text:
# Question
Title: Mowing the Grass
## Context

After attempting to program in Grass for the entire morning, you decide to go outside and mow some *real* grass. The grass can be viewed as a string consisting exclusively of the following characters: `wWv`. `w` denotes tall grass which takes \\$ 1 \\$ unit of energy to mow. `W` denotes *extremely* tall grass which takes \\$ 2 \\$ units of energy to mow. Lastly `v` denotes short grass which does not need to be mowed.

## Task

You decide to mow the grass from left to right *(beginning to the end of the string)*. However, every time you encouter a `v` *(short grass)*, you stop to take a break to replenish your energy, before carrying on with the mowing. Your task is to calculate the maximum amount of energy expended while mowing. In other words, find the maximum total energy of mowing a patch of grass, that of which does not contain `v`.

### Example

In the example input below, the answer is \\$ 8 \\$. Although the patch `wwwwwww` is a longer patch of grass, it only costs \\$ 7 \\$ units of energy, whereas the optimal patch `WWWW` expends \\$ 2 \times 4 = 8 \\$ units of energy.

```
Input: WwwvWWWWvvwwwwwwwvWwWw
Output: 8

```

Here is an example Python program -\> Try It Online!.

## Test Cases

```
WwwvWWWWvvwwwwwwwvWwWw -> 8
w -> 1
W -> 2
vwww -> 3
vWWW -> 6
v -> 0
vvvvvvv -> 0
vwvWvwvWv -> 2
vWWWWWWWWWWvwwwwwwwwwwwwwwwwwwwwwv -> 21
vWWWWWWWWWWvwwwwwwwwwwwwwwwwwwwv -> 20
vvWvv -> 2

```

This is , so the shortest code in bytes wins!

# Answer
> 21 votes
# Python 2, 49 bytes

```
lambda s:len(max(s.replace("W","ww").split('v')))

```

Try it online!

Here's how it works:

1. Replace each `W` with `ww`
2. Split on `v`'s to produce chunks of consecutive `w`'s
3. Take the `max` to get the longest one
4. Get its length

# Answer
> 13 votes
# Python 3.8, ~~55 46~~ 44 bytes

*Thanks @xnor for saving 2 bytes!*
*Thanks @dingledooper for saving 2 bytes!*

```
lambda s,t=0:max((t:=c%2*t+c%5%3)for c in s)

```

Try it online!

A function that takes in a byte string, and returns the max energy.

---

Cool trick with `eval`.

## Python 2, 61 bytes

```
lambda s:max(eval("+".join(s+"v").replace("v","0,")))
w=1;W=2

```

Try it online!

Transforms the given string by adding `+` between characters, then replaces `v` with comma (e.g `wWvW -> w+W+0,W`).

# Answer
> 12 votes
# Jelly,  ~~9~~  8 bytes

```
O’%3ṣ0§Ṁ

```

**Try it online!**

### How?

```
O’%3ṣ0§Ṁ - Link: list of characters   e.g. "wwwvWvwWww"
O        - ordinals                        [119,119,119,118,87,118,119,87,119,119]
 ’       - decremented                     [118,118,118,117,86,117,118,86,118,118]
  %3     - modulo three                    [1,1,1,0,2,0,1,2,1,1]
    ṣ0   - split at zeros                  [[1,1,1],[2],[1,2,1,1]]
      §  - sums                            [3,2,5]
       Ṁ - maximum                         5

```

# Answer
> 7 votes
# JavaScript (Node.js), 50 bytes

```
s=>Math.max(...Buffer(s).map(c=>e+=c%5%3||-e,e=0))

```

Try it online!

Or **42 bytes** if we can take a Buffer (or an array of ASCII codes) as input:

```
s=>Math.max(...s.map(c=>e+=c%5%3||-e,e=0))

```

Try it online!

# Answer
> 7 votes
# K (oK), ~~19~~ ~~18~~ 13 bytes

**Solution:**

```
|/+/'3!5!"v"\

```

Try it online!

**Explanation:**

Might be further golfable...

```
|/+/'3!5!"v"\ / the solution
         "v"\ / split on "v"
       5!     / modulo 5 (turns "vwW" into 3 4 2)
     3!       / modulo 3 (turns 3 4 2 into 0 1 2)
  +/'         / sum (+/) each (')
|/            / take maximum

```

# Answer
> 5 votes
# Charcoal, 12 bytes

```
Ｉ⌈Ｅ⪪Ｓv⁺Ｌι№ιW

```

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

```
    Ｓ           Input string
   ⪪ v          Split on literal `v`
  Ｅ             Map over chunks
          ι     Current chunk
         № W    Count of literal `W`
      ⁺         Plus
       Ｌι       Length of current chunk
 ⌈              Maximum
Ｉ               Cast to string for implicit print

```

# Answer
> 4 votes
# Perl 5 \+ `-p0166lF -MList::Util+max`, 19 bytes

```
$\=max$\,@F+y/W//}{
```

Try it online!

### Explanation

`-p` reads `STDIN` into `$_` breaking on each `$/`, `-0166` sets `$/` to `v` and `-l` strips `$/` from the end of each `$_`, sets `$\` to `$/` and enables automatic printing of `$\` at the end via `print` (because `$_` will be empty outside of the loop and `print` outputs `$\` at the end of each set of arguments - which default to `$_` if none are passed). `-F` splits the input into an array of chars, stored in `@F`.

This stores the larger of `$\` (initialised to `v` which is `0` when compared numerically) or `@F` (which is the array of chars in the input, or the length of the array when used in a numerical context) added to the number of `W` in the string.

Since `$\` is globally scoped, storing it here lasts for each iteration of the script the `}{` breaks out of the `while (<STDIN>) {` loop that `-p` inserts and terminates it so that instead of the current value of `$_` being printed alongside `$\`, `$_` is empty and only `$\` is printed.

# Answer
> 4 votes
# Retina 0.8.2, ~~19~~ 17 bytes

-2 bytes thanks to @Neil!

```
W
ww
S_`v
O^`
\Gw

```

Try it online!

Replaces `W` with `ww`, splits at `v`, sorts by length, then counts the `w`'s in the largest chunk.

# Answer
> 4 votes
# PowerShell 6+ for Windows, 48 bytes

port of math junkie's answer for Retina.

```
$args-creplace'W','ww'-split'v'|% len*|sort -b 1

```

Try it online!

# Answer
> 4 votes
# , 26 21 bytes

```
[:>./0+/;.1@,3|2+3&u:

```

Try it online!

* `3&u:` Change input to unicode int values
* `3|2+` Add 2 and then mod 3: Now `v` becomes 0, `w` becomes 1, and `W` 2.
* `0...,` Prepend 0
* `+/;.1` Split by first element (0) and sum the elements of each split chunk
* `[:>./` Take the max

# Answer
> 4 votes
# APL (Dyalog Unicode), 21 bytes

```
(((⌈/+/¨)×⊆⊢)'vwW'∘⍳)

```

Try it online! Assumes IO is 0.

**How it works**:

* we convert `v`, `w` and `W` into `0, 1, 2` respectively;
* we split on 0s;
* we sum each run of non-zeroes;
* and find the max of those.

# Answer
> 4 votes
# Haskell, 51 45 bytes

-6 bytes thanks to Ad Hoc Garf Hunter! Unfortunately all the grass-like operators were already taken :(

```
g=maximum.scanl(#)0
x#'w'=x+1
x#'W'=x+2
x#_=0

```

Try it online!

**Explanation**

`scanl` is basically a "running total", where for each element of a list, it applies a function to the element and an accumulator, and saves the accumulator at each step. So `scanl (+) 0 [1,2,3]` gives `[0,1,3,6]`. We're giving it the function `(#)` which we've defined to add `1` to the accumulator if the element of the list is `'w'`, add `2` to the accumulator if it's `'W'` or set the accumulator to `0` if it's anything else (`'v'`). Then we just get the maximum number of the new list, which will be the largest sum we managed to accumulate.

Cool idea I couldn't get to work: `mapping = zip "vwW" [(*0),(+1),(+2)]`

# Answer
> 4 votes
# Vyxal, 8 bytes

```
\v/va›ṠG

```

Try it Online!

```
  /      # Split on
\v       # "v"
   v     # For each
    a    # Is each char uppercase?
     ›   # Increment
      Ṡ  # Sum each
       G # Maximum

```

# Answer
> 3 votes
# C (gcc), ~~69~~ \\$\cdots\\$ ~~62~~ 60 bytes

Saved 5 bytes thanks to Arnauld!!!
Saved ~~2~~ 4 btes thanks to dingledooper!!!

```
e;m;f(char*g){for(e=m=0;*g;m=m>e?m:e)e=*g%2*e+*g++%5%3;e=m;}

```

Try it online!

# Answer
> 3 votes
# 05AB1E, 8 bytes

Port of the Jelly answer.

```
Ç<3%0¡Oà

```

Try it online!

# Answer
> 3 votes
# Ruby `-naFv`, 35 bytes

`-naFv` enables input on STDIN with auto-split on `v` into the `$F` global array.

```
p$F.map{|w|w.gsub(?W){11}.size}.max

```

Try it online!

# Answer
> 2 votes
# Jelly, 9 bytes

```
ṣ”v<”w‘§Ṁ

```

Try it online!

# Explanation

```
ṣ”v<”w‘§Ṁ  Main Link
ṣ”v        Split on "v"
   <”w     Check if less than "w" ("w" = 0, "W" = 1)
      ‘    Add one to every element
       §   Sum every sublist
        Ṁ  Find the maximum

```

# Answer
> 2 votes
# AWK, ~~85~~ ~~82~~ 69 bytes

```
{FS="v";gsub("W","ww");for(;i<NF;){s=length($++i);m=m>s?m:s;}print m}

```

Try it online!

Thanks to @dingledooper for cutting off 13 bytes.

The code could be even less, **62 bytes** accounting for the field separator flag being a parameter and not part of the actual code.

pretty straightforward: change all `W` into `w`, get lenght of words, `v` counts as field separator. Retain max score with ternary operator.

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

```
s->{int m=0,n=0;for(var c:s)m=(n=c%2*n+c%5%3)>m?n:m;return m;}

```

Try it online!

After finishing it, it seems to be a port of Noodle9's C answer.

# Answer
> 1 votes
# C# (Visual C# Interactive Compiler), 69 bytes

```
Func<string,int>g=s=>s.Replace("W","ww").Split('v').Max(x=>x.Length);

```

Try it online!

Heavy inspiration from @xnor

# Answer
> 1 votes
# Bash, 28 bytes

```
sed 's,W,ww,g;y/v/\n/'|wc -L

```

Input from stdin, output to stdout

There might be a better way.

Try it online!

# Answer
> 1 votes
# Mathematica, 53 bytes

```
Max[#~(s=StringCount)~"W"+#~s~_&@StringSplit[#,"v"]]&

```

More readable, un-golfed code:

```
Max[StringCount[#,"W"]+StringCount[#,_]&[StringSplit[#,"v"]]]&

```

`StringSplit[#,"v"]` takes a string and turns it into a list of strings, seperated by 'v', then add together the length of the string, and the count of 'W's, and take the max value.

# Answer
> 1 votes
# Crystal, 57 bytes

```
def f(a);a.split('v').max_of {|s|s.count('W')+s.size};end

```

Try it online!

# Answer
> 1 votes
# Python 2, 70 bytes

Comprehensive approach.

```
lambda n:max([sum([2if i=="W"else 1for i in x])for x in n.split('v')])

```

Try it online!

# Answer
> 0 votes
# Rust, 67 bytes

Port of xnor's answer

```
|s:&str|s.replace("W","ww").split('v').map(str::len).max().unwrap()

```

Try it online!

# Answer
> 0 votes
# Stax, 14 bytes

```
π├♦.8Σ0└ó?∟X≈Æ

```

Try it online!

# Answer
> 0 votes
# Pip, 13 bytes

```
MX#*YaR'Wt^'v

```

Try it online!

### Explanation

```
     a         First command-line argument
      R'W      Replace all occurrences of W
         t     with 10 (arbitrary value--the important thing is, it's two characters)
          ^'v  Split on occurrences of v
    Y          Yank (to enforce precedence)
  #*           Replace each string in the list with its length
MX             Take the maximum

```

# Answer
> 0 votes
# Excel, 101 bytes

```
=MAX(LEN(SUBSTITUTE(FILTERXML("<a><b>x"&SUBSTITUTE(A1,"v","</b><b>x")&"</b></a>","//b"),"W","ww"))-1)

```

Link to Spreadsheet

* `"<a><b>x"&SUBSTITUTE(A1,"v","</b><b>x")&"</b></a>"` converts text to XML containing "x" + the "wW" strings. The additional "x" prevents errors.
* `FILTERXML(~,"//b")` converts XML to a vertical array.
* `SUBSTITUTE(~,"W","ww")` change "W" to "ww".
* `LEN(~)-1` counts the "w"; minus 1 for the leading "x".
* `MAX(~)` return the largest one.

# Answer
> 0 votes
# Uiua SBCS, 13 bytes

```
⬚0/↥⊜/+.◿3-@@

```

Try it!

```
⬚0/↥⊜/+.◿3-@@
          -@@  # subtract @ character
        ◿3     # modulo three
    ⊜/+.       # sum groups delimited by zero
⬚0/↥           # maximum using zero as default

```

# Answer
> 0 votes
# YASEPL, 86 bytes

```
=s=1'=l®1=i=h=c`1!¥i,1}7,"v",2=c`2!}7,"w",3!c+`3!}7,"W",4!c++`4!c}4,h,5!h$c`5!i+}2,l>h

```

and just for fun,

# ibe, 130 bytes

```
adddQmwwoadddWmwwpadddEmoiadadadadaddsRdfTmRakqdgUmRmYshUmQmwskIakwshUmWmeafImwakeshUmEmrafImeakrsgImOmtskOafOmIaktafYmwssYmTmqasO

```

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