title: Draw an Empty Scrabble Board

text:
# Question
Title: Draw an Empty Scrabble Board
A standard Scrabble board is a 15×15 grid of spaces to place letter tiles. Most of the spaces are blank but some are double word scores (pink), triple word scores (red), double letter scores (light blue), and triple letter scores (blue). There is usually a star in the very center (which counts as a double word score).

Write a program or function that outputs a standard, empty Scrabble board in ASCII form where:

* `.` represents an empty space
* `D` represents a double word score
* `T` represents a triple word score
* `d` represents a double letter score
* `t` represents a triple letter score
* `X` represents the center star

That is, your exact output must be

```
T..d...T...d..T
.D...t...t...D.
..D...d.d...D..
d..D...d...D..d
....D.....D....
.t...t...t...t.
..d...d.d...d..
T..d...X...d..T
..d...d.d...d..
.t...t...t...t.
....D.....D....
d..D...d...D..d
..D...d.d...D..
.D...t...t...D.
T..d...T...d..T

```

optionally followed by a trailing newline.

**The shortest code in bytes wins.**

# Answer
# MATL, ~~59~~ ~~54~~ 52 bytes

```
4t:g2I5vXdK8(3K23h32h(H14(t!XR+8: 7:Pht3$)'DtdTX.'w)

```

Try it online!

## Explanation

The code follows three main steps:

1. Generate the 8x8 matrix

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

```
2. Extend it to the 15x15 matrix

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

```
3. Index the string `'DtdTX.'` with that matrix to produce the desired result.

### Step 1

```
4        % Push 4
t:       % Duplicate, range: pushes [1 2 3 4]
g        % Logical: convert to [1 1 1 1]
2I5      % Push 2, then 3, then 5
v        % Concatenate all stack vertically into vector [4 1 1 1 1 2 3 5]
Xd       % Generate diagonal matrix from that vector

```

Now we need to fill the nonzero off-diagonal entries. We will only fill those below the diagonal, and then make use symmetry to fill the others.

To fill each value we use linear indexing (see this answer, length-12 snippet). That means accessing the matrix as if it had only one dimension. For an 8×8 matrix, each value of the linear index refers to an entry as follows:

```
1   9         57
2  10         58
3  11
4
5  ...       ...
6
7             63
8  16 ... ... 64

```

So, the following assigns the value 4 to the lower-left entry:

```
K        % Push 4
8        % Push 8
(        % Assign 4 to the entry with linear index 8

```

The code for the value 3 is similar. In this case the index is a vector, because we need to fill several entries:

```
3        % Push 3
K        % Push 4
23h      % Push 23 and concatenate horizontally: [4 23]
32h      % Push 32 and concatenate horizontally: [4 23 32]
(        % Assign 4 to the entries specified by that vector

```

And for 2:

```
H        % Push 2
14       % Push 14
(        % Assign 2 to that entry

```

We now have the matrix

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

```

To fill the upper half we exploit symmetry:

```
t!       % Duplicate and transpose
XR       % Keep the upper triangular part without the diagonal
+        % Add element-wise

```

### Step 2

The stack now contains the 8×8 matrix resulting from step 1. To extend this matrix we use indexing, this time in the two dimensions.

```
8:       % Push vector [1 2 ... 7 8]
7:P      % Push vector [7 6 ... 1]
h        % Concatenate horizontally: [1 2 ... 7 8 7 ... 2 1]. This will be the row index
t        % Duplicate. This will be the column index
3$       % Specify that the next function will take 3 inputs
)        % Index the 8×8 matrix with the two vectors. Gives a 15×15 matrix

```

### Step 3

The stack now contains the 15×15 matrix resulting from step 2.

```
'DtdTX.' % Push this string
w        % Swap the two elements in the stack. This brings the matrix to the top
)        % Index the string with the matrix

```
> 16 votes

# Answer
## JavaScript (ES6), 112 bytes

```
a=Math.abs,f=(n=239)=>n?f(n-1)+(i=a(n%16-8),j=a((n>>4)-7),d=i%7^j%7,n&15?d%4?".":"XdtDDDDTddtd"[(i|j)+d]:`
`):''

```

## JavaScript (ES5), 121 bytes

```
c="";for(a=-8;8>++a;)for(j=0>a?-a:a,b=-8;9>++b;)i=0>b?-b:b,d=i%7^j%7,c+=i-8?d%4?".":"XdtDDDDTddtd"[(i|j)+d]:"\n";alert(c)

```

The ES5 version trades a handwritten `Math.abs()`, two `for` loops and the output via `alert` for the unavailable recursive concise arrow function.

Both versions use the idea in the Ruby/C answer above, by Level River St. Using binary `|` instead of `+` shortens the defining string, `d` stays positive when diffing by `^` instead of `-`.
> 9 votes

# Answer
# Ruby, ~~103~~ 97 bytes

Thanks to Mitch Schwartz for a 6 byte improvement on the iterations.

```
a=(-7..7).map &:abs
a.map{|i|puts a.map{|j|(d=i%7-j%7)%4<1?'X d t DTDdDdDtT d'[i+j+d*d/3]:?.}*''}

```

A similar but significantly different approach to my original answer below. As before, we use the fact that a letter must be printed if `i%7-j%7` is equal to 0 or 4. But here we store that difference in `d` and use the formula `i+j+d*d/3` to give an integer which is unique (up to symmetry) to that particular coloured square. Then we just look it up in the magic string.

*Just for fun: **C version of this approach, 120 bytes***

```
z,i,j,d;f(){for(z=240;z--;)i=abs(z%16-8),j=abs(z/16-7),putchar(i-8?(d=i%7-j%7)%4?46:"X d t DTDdDdDtT d"[i+j+d*d/3]:10);}

```

# Ruby, ~~115~~ 113 bytes

2 bytes saved thanks to Value Ink.

```
(k=-7..7).map{|y|k.map{|x|i=x.abs;j=y.abs
$><<=(i%7-j%7)%4<1?"#{'XdTdT'[(i+j)/3]}dtDDDD"[[i%7,j%7].min]:?.}
puts}

```

**Explanation**

The origin is considered to be the centre of the board.

A letter must be printed if the x and y coordinates of the square have magnitudes that are identical or differ by 4. The only exceptions are on the outer edge of the board, but these follow the same pattern as the central row/column of the board, so we can use the same condition if we take the x and y coordinates modulo 7.

The choice of letter displayed is based on the coordinate of minimum magnitude. In this way the doubles and triples at (1,5) and (2,6) follow the same rule as at (1,1) and (2,2) and are obtained from the 7 character string `"#{formula}dtDDDD"` This does not cover all variations for the edge and centreline squares, so the first character of the string is calculated from the formula `'XdTdT'[(i+j)/3]`.

```
(k=-7..7).map{|y|
  k.map{|x|
    i=x.abs;j=y.abs
    print (i%7-j%7)%4<1?      #IF this expression is true print a letter
    "#{'XdTdT'[(i+j)/3]       #select 1st character of magic string where [i%7,j%7].min==0
     }dtDDDD"[[i%7,j%7].min]: #remaining 6 characters of magic string for diagonal
    ?.                        #ELSE print .
  }
  puts                        #at the end of the row print a newline
}

```
> 8 votes

# Answer
# brainfuck, ~~598~~ ~~596~~ 590 bytes

Golfing tips welcome.

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

```

**Explanation**

Initialize the tape to **\[10 116 68 46 100 84 92\]** i.e. **\[nl t D . d T \\\]**

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

Each line here then prints one line of the board.
The middle line also decreases `92 to 88 i.e. \ to X`

```
.<<..>.<...>>.<<...>.<..>>.<<<<<.
>>>.<.>...<<.>>...<<.>>...<.>.<<<.
>>>..<.>...>.<.>.<...<.>..<<<.
>>>>.<..<.>...>.<...<.>..>.<<<<.
>>>....<.>.....<.>....<<<.
>>>.<<.>>...<<.>>...<<.>>...<<.>>.<<<.
>>>..>.<...>.<.>.<...>.<..<<<.
>>>>>.<<..>.<...>>>----.<<<...>.<..>>.<<<<<.
>>>..>.<...>.<.>.<...>.<..<<<.
>>>.<<.>>...<<.>>...<<.>>...<<.>>.<<<.
>>>....<.>.....<.>....<<<.
>>>>.<..<.>...>.<...<.>..>.<<<<.
>>>..<.>...>.<.>.<...<.>..<<<.
>>>.<.>...<<.>>...<<.>>...<.>.<<<.
>>>>>.<<..>.<...>>.<<...>.<..>>.

```

Try it online!
> 7 votes

# Answer
## PowerShell v2+, ~~147~~ 143 bytes

```
($x='T..d...T...d..T')
($y='.D...t..','..D...d.','d..D...d','....D...','.t...t..','..d...d.'|%{$_+-join$_[6..0]})
'T..d...X...d..T'
$y[5..0]
$x

```

Try it online!

Takes advantage of how the default `Write-Output` at end of program execution handles arrays (i.e., it inserts a newline between elements). Might be a better way to generate the middle of the board -- I'm still working at it.

The first line outputs the top line of the board, also storing it in `$x` for use later.

The next line generates all the Double-Word lines by taking the left "half" of each, mirroring them (the `-join$_[6..0]` statement), and storing them as elements in array `$y`.

The next line is the middle row, with an `X` in the middle, thanks to `-replace`.

The next line outputs `$y` in reverse order, giving us the bottom Double-Word lines.

The final line is just `$x` again.

```
PS C:\Tools\Scripts\golfing> .\draw-empty-scrabble-board.ps1
T..d...T...d..T
.D...t...t...D.
..D...d.d...D..
d..D...d...D..d
....D.....D....
.t...t...t...t.
..d...d.d...d..
T..d...X...d..T
..d...d.d...d..
.t...t...t...t.
....D.....D....
d..D...d...D..d
..D...d.d...D..
.D...t...t...D.
T..d...T...d..T

```

*-4 bytes thanks to Veskah.*
> 6 votes

# Answer
# \>\<\> (Fish), 153 Bytes

```
\!o;!?l
\'T..d...T...d..T'a'.D...t...t...D.'a'..D...d.d...D..'a'd..D...d...D..d'a'....D.....D....'a'.t...t...t...t.'a'..d...d.d...d..'a'T..d...'
\'X/'02p

```

A horribly, awfully, inefficient way of doing things. Currently looking into a way of shortening it down by mirroring both horizontally and vertically properly.

Try it online! (If you don't want to be there all day make sure you either set execution speed to max or run without the animation.)
> 5 votes

# Answer
# 05AB1E, ~~57~~ 53 bytes

### Code

```
•jd]31‚ŽÔc¦Ïïì¹Ep.Üì8Ìa;“•6B4ÝJ".TdDt"‡5'.3×:Â'Xý15ô»

```

Uses the **CP-1252** encoding. Try it online!

---

### Explanation (outdated)

The `•4ç“–šã&$W§ñçvßÖŠ_æá_VFÛÞýi~7¾¬ÏXôc•5B` decompresses to this number:

```
1002000100020010400030003000400040002020004002004000200040020000400000400000300030003000300020002020002001002000

```

With `4ÝJ".TdtD"‡`, we transliterate the following in this big number:

```
0 -> .
1 -> T
2 -> d
3 -> t
4 -> D

```

We bifurcate the whole string, leaving the string and the string reversed on the stack and join them by `"X"` using `ý`. We split the entire string into pieces of 15 using th `15ô` code and join the whole array by newlines using `»`.
> 4 votes

# Answer
## C, ~~146~~ ~~145~~ ~~142~~ 138 bytes

```
i,r,c;main(){for(;i<240;)r=abs(i/16-7),c="T..12..0..12..0"[r+7-abs(i%16-7)],putchar(++i%16?c&4?c:"Xd.dd.tt.D..D.dD.dD.tTd."[c%4+r*3]:10);}

```

Try it online!

*~~1 byte~~5 bytes saved thanks to Level River St*

This exploits the diagonal pattern of the board for encoding. In particular, if we take the top left quadrant of the board and align the diagonal, we get:

```
       T..d...T
      .D...t..
     ..D...d.
    d..D...d
   ....D...
  .t...t..
 ..d...d.
T..d...X

```

...a lot of the columns now line up. If we encode columns in a line this way:

```
       0..12..0 y/012/Td./
      .0..12..  y/012/D.t/
     ..0..12.   y/012/D.d/
    2..0..12    y/012/D.d/
   12..0..1     y/012/D../
  .12..0..      y/012/tt./
 ..12..0.       y/012/dd./
T..12..0        y/012/Xd./

```

...then the board pattern can be collapsed into a 15 character string: `T..12..0..12..0`; and we simply need the right mappings for each row.

With that in mind, here's an expanded version with comments:

```
i,r,c;
main() {
   for(;i<240;)  // one char per output including new line
   r=abs(i/16-7) // row; goes from 7 to 0 and back to 7.
   , c="T..12..0..12..0"[r+7-abs(i%16-7)] // pattern char
   , putchar(++i%16 // if this is 0 we need a new line
   ? c&4 // hash to distinguish 'T' and '.' from '0', '1', '2'
     ? c // print 'T' and '.' literally
     : "Xd.dd.tt.D..D.dD.dD.tTd."[c%4+r*3] // otherwise look up replacement char
   : 10 // print the new line
   );
}

```
> 4 votes

# Answer
# 05AB1E, ~~49~~ 44 bytes

```
•1nÑ=}íge/Þ9,ÑT‰yo¬iNˆå•6B8ôû€û»5ÝJ".TtdDX"‡

```

Try it online!

# Explained:

Push: `1003000104000200004000303004000300004000020002000030003010030005`

Split into chunks of 8, palindromize each.

Palindromize again.

Replace numbers with characters.

---

# Other Idea (Someone Try this in MATL)

Seeing as EVERYTHING is garunteed to have a period inbetween it...

Count the number of zeros inbetween each piece:

```
1003000104000200004000303004000300004000020002000030003010030005
^  ^   ^ ^   ^    ^   ^ ^  ^   ^    ^    ^   ^    ^   ^ ^  ^   ^

```

`131424334342233135 => w\F6ß¿`

Taking the counts of zeros runs:

`23134312344343123 => ì:¼˜¾`

Then you would decrypt and transpose them together.

Using them in 05AB1E (results in a +5 byte increase):

# 05AB1E, 27 bytes

```
•w\F6ß¿•6BS•ì:¼˜¾•5BS0×‚øJJ

```

Try it...

---

Meta-golfed entry:

# 05AB1E, 104 bytes

```
•G¨J´JÏÍ?»"”Ö3úoÙƒ¢y”vf%¯‚6À°IÕNO’Å2Õ=ÙŠxn®žÑŸ¶¼t¨š,Ä]ÓŽÉéÈºÂ/ø‡ŸÖ|e³J—Ë'~!hj«igÄ‹Î‚wî’©•7BžLR"
.DTXdt"‡

```

Try it!

Meta-golfed using my meta-golfer for ASCII art: https://tio.run/nexus/05ab1e#JY9NSgNBEIWvUo4/qAQxyfi30yAioiAiuBM6M9U9DT3doao7ccBFrhI3ooss3QguJniRXCR2x01RfK9479Xqtf2@XHy2H78/tw/L6aydq8VXr5sPsuX0LeP1jCwbJD3r54v3dp5mFGbZzWp1wXBPyLpE6@GRQj0C1spiCQJ4gjjSVgG@YBG8HiM4KpHAWbgiXYqmA1wF79ONrxCGa5nBOyCUQSEyCFuCi2LEklwNjGO0YAQpNA3cBTa6hsIF60kjd9Y@jAWhF9SAk1C5Gk1yiTSQ9g1MBKcKAp4q7RGuXWCMFlYioS3iKowBhf@9Kh2DNbEHGSIexhSZeDRIUcq4oTDxDS09aAsjZ3TRHGycb25tP@/s7@51e/386Pjk9OzwDw
> 3 votes

# Answer
# Python 3, 138 bytes

```
d=lambda s:s+s[-2::-1]
print(*d(list(map(d,'T..d...T .D...t.. ..D...d. d..D...d ....D... .t...t.. ..d...d. T..d...X '.split()))),sep='\n')

```
> 2 votes

# Answer
# Charcoal, 33 bytes (noncompeting)

All credit for this answer goes to @DLosc.

```
T↑↑↘tdd↗→→↖XdtDDDD↓T..d‖Ｏ⟦↗→↓⟧ＵＢ.

```

Try it online!

## Verbose

```
Print("T")
Move(:Up)
Move(:Up)
Print(:DownRight, "tdd")
Move(:UpRight)
Move(:Right)
Move(:Right)
Print(:UpLeft, "XdtDDDD")
Print(:Down, "T..d")
ReflectOverlap([:UpRight, :Right, :Down])
SetBackground(".")

```

Try it online!
> 2 votes

# Answer
# Canvas, 30 bytes

```
TDDDDtdX＼tdd＼６２╋d４１╋T８１╋：⤢ｎ┼.ｒ

```

Try it here!

A different enough approach to the existing Canvas answer to justify its own post, I think.

Constructs the art as follows:

```
T
 D
  D
   D
    D
     t
      d
       X

```

```
T
 D   t
  D   d
   D   d
    D
     t
      d
       X

```

```
T  d
 D   t
  D   d
   D   d
    D
     t
      d
       X

```

```
T  d   T
 D   t
  D   d
   D   d
    D
     t
      d
       X

```

```
T  d   T
 D   t
  D   d
d  D   d
    D
 t   t
  d   d
T  d   X

```

```
T  d   T   d  T
 D   t   t   D
  D   d d   D
d  D   d   D  d
    D     D
 t   t   t   t
  d   d d   d
T  d   X   d  T
  d   d d   d
 t   t   t   t
    D     D
d  D   d   D  d
  D   d d   D
 D   t   t   D
T  d   T   d  T

```

```
T..d...T...d..T
.D...t...t...D.
..D...d.d...D..
d..D...d...D..d
....D.....D....
.t...t...t...t.
..d...d.d...d..
T..d...X...d..T
..d...d.d...d..
.t...t...t...t.
....D.....D....
d..D...d...D..d
..D...d.d...D..
.D...t...t...D.
T..d...T...d..T

```
> 2 votes

# Answer
## Javascript (ES6), 150 bytes

```
_=>(r='',"T2d3T3d2T.D3t3t3D3D3d.d3D2d2D3d3D2d4D5D5t3t3t3t3d3d.d3d2T2d3".replace(/./g,c=>(c=+c?'.'.repeat(c):c,r=c+r,c))+'X'+r).match(/.{15}/g).join`
`

```

### How it works

The string `"T2d3T3d2T.D3t3t3D3D3d.d3D2d2D3d3D2d4D5D5t3t3t3t3d3d.d3d2T2d3"` describes the board from its top left corner to the square just before the 'X', with consecutive empty squares encoded as digits. The `replace()` function both unpacks the empty squares and builds the mirror string `r` for the bottom of the board. Then both parts are put together and carriage returns are inserted every 15 characters.

### Demo

```
let f =
_=>(r='',"T2d3T3d2T.D3t3t3D3D3d.d3D2d2D3d3D2d4D5D5t3t3t3t3d3d.d3d2T2d3".replace(/./g,c=>(c=+c?'.'.repeat(c):c,r=c+r,c))+'X'+r).match(/.{15}/g).join`
`
console.log(f())
```
> 1 votes

# Answer
## C 234 Bytes

```
#define g(t) while(i++<8)putchar(*b++);b-=2;--i;while(--i>0)putchar(*b--);putchar('\n');b+=t;
char*r="T..d...T.D...t....D...d.d..D...d....D....t...t....d...d.T..d...X";i;f(){char*b=r;do{g(9);}while(*b);b-=16;do{g(-7);}while(b>=r);}

```

Here's the output:

```
T..d...T...d..T
.D...t...t...D.
..D...d.d...D..
d..D...d...D..d
....D.....D....
.t...t...t...t.
..d...d.d...d..
T..d...X...d..T
..d...d.d...d..
.t...t...t...t.
....D.....D....
d..D...d...D..d
..D...d.d...D..
.D...t...t...D.
T..d...T...d..T

```
> 1 votes

# Answer
## JavaScript (ES6), 221 bytes

```
f=
_=>(a=[...Array(15)].map(_=>Array(15).fill`.`),r=([c,i,j])=>[a[i][j]=a[k=14-i][j]=a[i][j=14-j]=a[k][j]=c,j,i],[..."TDDDDtdX"].map((c,i)=>r([c,i,i])),"d30t51d62d73T70".replace(/.../g,s=>r(r(s))),a.map(a=>a.join``).join`
`)
;o.textContent=f()
```

```
<pre id=o>
```

Since I went to the trouble of creating this I thought I'd post it anyway even though there's a clearly superior solution available.
> 1 votes

# Answer
# Canvas, 33 bytes

```
“e+╪>ｖ.２eC｝¼Ｐ↕V⁸╋ＵＳF∔uiＴ═Ｉk¼‟８ｎ┼┼

```

Try it here!

uses a huge compressed string and quad palidromizes it. Can probably be shortened by adding the main diagonal later.
> 1 votes

# Answer
## Haskell, 114 bytes

```
g=(++)<*>reverse.init
unlines$g$g<$>words"T..d...T .D...t.. ..D...d. d..D...d ....D... .t...t.. ..d...d. T..d...X"

```

`g` in a non-pointfree version is `g x = x ++ (reverse (init x))`. It is applied once per (half-)line and again on the result.
> 0 votes

# Answer
## GNU sed, ~~219~~ 205 bytes

```
s/$/T..d...T...d..T/p;h
s/.*/.D...t...t...D./p;G;h
s/.*/..D...d.d...D../p;G;h
s/.*/d..D...d...D..d/p;G;h
s/.*/....D.....D..../p;G;h
s/.*/.t...t...t...t./p;G;h
s/.*/..d...d.d...d../p;G;h
s/.*\n//;s/T/X/2p;g

```

Taking advantage of the mirror symmetry of the board, the second half is the first one that was stored in reverse order in the hold space.
> 0 votes

# Answer
## sh + coreutils, 119 bytes

This is a binary file. Shown as hexdump:

```
00000000  74 61 69 6c 20 2d 63 39  34 20 24 30 7c 67 75 6e  |tail -c94 $0|gun|
00000010  7a 69 70 0a 65 78 69 74  0a 1f 8b 08 00 2e ec ca  |zip.exit........|
00000020  57 00 03 65 4f c9 0d c0  30 08 fb 7b 18 4f 91 11  |W..eO...0..{.O..|
00000030  fc e8 00 1e a1 fb ab 08  68 a4 90 07 60 d9 98 43  |........h...`..C|
00000040  a4 49 8a 59 05 ae 40 6f  c7 22 98 84 b3 29 10 fc  |.I.Y..@o."...)..|
00000050  13 59 1d 7a 11 9d b1 bd  15 a8 56 77 26 54 c4 b3  |.Y.z......Vw&T..|
00000060  f7 0d fd f6 9f f3 ef fd  e7 7d f3 7e 8d ff 3e 05  |.........}.~..>.|
00000070  57 d9 a0 f0 00 00 00                              |W......|
00000077

```

Here's the base64 form so you can copy/paste it:

```
begin-base64 755 test.sh
dGFpbCAtYzk0ICQwfGd1bnppcApleGl0Ch+LCAAu7MpXAANlT8kNwDAI+3sY
T5ER/OgAHqH7qwhopJAHYNmYQ6RJilkFrkBvxyKYhLMpEPwTWR16EZ2xvRWo
VncmVMSz9w399p/z7/3nffN+jf8+BVfZoPAAAAA=
====

```
> 0 votes

# Answer
# C ~~230~~ 228 Bytes

```
char *s="T.D..Dd..D....D.t...t..d...dT..d...X";
int x,y,a,b;
#define X(N) {putchar(s[a]);N y<=x?1:y;}
#define P for(y=1;y<8;y++)X(a+=)for(y--;y+1;y--)X(a-=)puts("");
main(){for(;x<8;x++){a=b+=x;P}for(x=6;x+1;x--){a=b-=(x+1);P}}

```

try it on ideone

This is an attempt at improving the original C version posted that had quarter of board stored in a C array. Not as short as I was hoping for. This version only has one eighth of the board stored.

Ungolfed:

```
char *s="T.D..Dd..D....D.t...t..d...dT..d...X";
int x,y,a,b;
main(){
    for(x = 0; x < 8; x++){
        a=b+=x;
        for(y = 1; y < 8; y++){
            putchar(s[a]);
            a += y<=x ? 1 : y;
        }
        for(y--; y >= 0; y--){
            putchar(s[a]);
            a -= y<=x ? 1 : y;
        }
        puts("");
    }
    for(x=6; x >= 0; x--){
        a=b-=(x+1);
        for(y = 1; y < 8; y++){
            putchar(s[a]);
            a += y<=x ? 1 : y;
        }
        for(y--; y >= 0; y--){
            putchar(s[a]);
            a-= y<=x ? 1 : y;
        }
        puts("");
    }
}

```
> 0 votes

# Answer
# 05AB1E, 40 bytes

```
•7â∍û¯øÉ»₄XÍ«Ÿ=SPтŸƶR±•".TdDtX"Åв8äJ€ûû»

```

Try it online!

```
•...•".TdDtX"Åв8äJ€ûû»  # trimmed program
                     »  # join...
             Åв         # list of characters of...
     ".TdDtX"           # literal...
             Åв         # with indices in base-10 values of base length of...
     ".TdDtX"           # literal...
             Åв         # digits of...
•...•                   # 10654502656792583423375424705593131734076028132261...
                ä       # split into...
               8        # literal...
                ä       # equal length pieces...
                        # (implicit) with each element...
                 J      # joined...
                  €     # with each element...
                   û    # concatenated with itself reversed excluding the first character...
                    û   # concatenated with itself reversed excluding the first element...
                     »  # by newlines
                        # implicit output

```
> 0 votes

# Answer
# Excel, 115 bytes

```
=LET(j,8-ABS(8-ROW(1:15)),k,TRANSPOSE(j),n,IF(k>j,k,j),MID("T.D..Dd..D....D.t...t..d...dT..d...X",n*(n-3)/2+j+k,1))

```

Link to Spreadsheet
> 0 votes

# Answer
# Vyxal, 242 bytes

Try it online!

```
`T..d...T...d..T
.D...t...t...D.
..D...d.d...D..
d..D...d...D..d
....D.....D....
.t...t...t...t.
..d...d.d...d..
T..d...X...d..T
..d...d.d...d..
.t...t...t...t.
....D.....D....
d..D...d...D..d
..D...d.d...D..
.D...t...t...D.
T..d...T...d..T`,

```

For answer number 4, we have the empty Scrabble board in its natural habitat.
> -1 votes

---
Tags: code-golf, ascii-art, kolmogorov-complexity, board-game, scrabble
---


title: Print this Multiplication Table

text:
# Question
Title: Print this Multiplication Table
Write shortest code to print the following Multiplication Table:

```
1×1=1
1×2=2  2×2=4
1×3=3  2×3=6  3×3=9
1×4=4  2×4=8  3×4=12 4×4=16
1×5=5  2×5=10 3×5=15 4×5=20 5×5=25
1×6=6  2×6=12 3×6=18 4×6=24 5×6=30 6×6=36
1×7=7  2×7=14 3×7=21 4×7=28 5×7=35 6×7=42 7×7=49
1×8=8  2×8=16 3×8=24 4×8=32 5×8=40 6×8=48 7×8=56 8×8=64
1×9=9  2×9=18 3×9=27 4×9=36 5×9=45 6×9=54 7×9=63 8×9=72 9×9=81

```

# Answer
> 14 votes
## Excel, ~~92~~ 91 Bytes

From the VBA editor's immediate window, run the following command: `Range("A1:I9").Formula="=IF(ROW()<COLUMN(),"""",COLUMN()&""×""&ROW()&""=""&COLUMN()*ROW())"` The output is directly on the active worksheet.

I golfed an extra byte by swapping the order of an `if` to change `>=` to `<`. I didn't update the screenshot, but it only affects the formula at the top, not the output.

# Answer
> 8 votes
# Python (75)

```
r=range(1,10)
for i in r:print''.join('%sx%s=%-3s'%(j,i,i*j)for j in r[:i])

```

a little better golfed than the other two Python versions.

# Answer
> 6 votes
# C++, ~~106~~ 98 bytes

I used two loops and a few tricks.

```
#import <cstdio>
main(){for(int i,j;i++-9;j=0)while(j++-i)printf("%dx%d=%d%c",j,i,i*j,j<i?32:10);}

```

# Answer
> 5 votes
# J: 57 51 characters

```
([:;"2*\#"2(":@],'x',":@[,'=',":@*,' '"_)"0/~)>:i.9

```

No loops.

# Answer
> 4 votes
# Ruby: ~~60~~ 59 characters

```
1.upto(9){|i|puts (1..i).map{|j|"%dx%d=%-3d"%[j,i,i*j]}*""}

```

Sample run:

```
bash-4.2$ ruby -e '1.upto(9){|i|puts (1..i).map{|j|"%dx%d=%-3d"%[j,i,i*j]}*""}'
1x1=1
1x2=2  2x2=4
1x3=3  2x3=6  3x3=9
1x4=4  2x4=8  3x4=12 4x4=16
1x5=5  2x5=10 3x5=15 4x5=20 5x5=25
1x6=6  2x6=12 3x6=18 4x6=24 5x6=30 6x6=36
1x7=7  2x7=14 3x7=21 4x7=28 5x7=35 6x7=42 7x7=49
1x8=8  2x8=16 3x8=24 4x8=32 5x8=40 6x8=48 7x8=56 8x8=64
1x9=9  2x9=18 3x9=27 4x9=36 5x9=45 6x9=54 7x9=63 8x9=72 9x9=81

```

# Answer
> 4 votes
# D, 75 chars

```
foreach(i,1..10){foreach(j,1..i+1){writef("%dx%d=%d ",i,j,i*j);}writeln();}

```

you just said code not function or full program

# Answer
> 4 votes
## APL (37)

```
∆∘.{⊃(⍺≥⍵)/,/(⍕⍺)'×'(⍕⍵)'=',⍕⍺×⍵}∆←⍳9

```

And it's not even just two for-loops. In APL, the following construct:

```
x ∘.F y

```

where `x` and `y` are lists, and `F` is a function, applies `F` to each pair of items in `x` and `y` and gives you a matrix.

So: `∆∘.×∆←⍳9` gets you a multiplication table from 1 to 9. The above function generates the required string for each pair, i.e. `(⍕⍺)`, string representation of the first number, followed by `×`, followed by `(⍕⍵)`, string representation of the second number, followed by `=`, followed by `⍕⍺×⍵`, as long as `⍺≥⍵`.

# Answer
> 4 votes
# Perl, 54 Characters

```
printf"%dx$?=%-3d"x$?.$/,map{$_,$_*$?}1..$?while$?++<9

```

# Answer
> 4 votes
## APL (Dyalog), 28

```
↑{⍵{⍕⍵,'×',⍺,'=',⍺×⍵}¨⍳⍵}¨⍳9

```

Analogous to a double loop in other languages

`{⍵{...}¨⍳⍵}¨⍳9` sets up the double loop
`⍕⍵,'×',⍺,'=',⍺×⍵` creates the string for each pair
Convert array of array of strings to a matrix of stings

**Output**

```
1 × 1 = 1
1 × 2 = 2  2 × 2 = 4
1 × 3 = 3  2 × 3 = 6   3 × 3 = 9
1 × 4 = 4  2 × 4 = 8   3 × 4 = 12  4 × 4 = 16
1 × 5 = 5  2 × 5 = 10  3 × 5 = 15  4 × 5 = 20  5 × 5 = 25
1 × 6 = 6  2 × 6 = 12  3 × 6 = 18  4 × 6 = 24  5 × 6 = 30  6 × 6 = 36
1 × 7 = 7  2 × 7 = 14  3 × 7 = 21  4 × 7 = 28  5 × 7 = 35  6 × 7 = 42  7 × 7 = 49
1 × 8 = 8  2 × 8 = 16  3 × 8 = 24  4 × 8 = 32  5 × 8 = 40  6 × 8 = 48  7 × 8 = 56  8 × 8 = 64
1 × 9 = 9  2 × 9 = 18  3 × 9 = 27  4 × 9 = 36  5 × 9 = 45  6 × 9 = 54  7 × 9 = 63  8 × 9 = 72  9 × 9 = 81

```

# Answer
> 4 votes
## *Mathematica*, 45

Pretty boring, but I guess it serves as a syntax comparison:

```
Grid@Table[Row@{a, "x", b, "=", a b}, {a, 9}, {b, a}]

```

# Answer
> 3 votes
## VBScript (133); without loops.

```
g=""
sub m(x,y)
    g=x&"x"&y&"="&x*y&vbTab&g
    if x>1 then
        m x-1,y
    elseif y>1 then
        g=vbLf&g
        m y-1,y-1
    end if
end sub
m 9,9
wscript.echo g

```

On request of the challenger: no loops. This code uses recursive subroutine calls.

# Answer
> 3 votes
# Maple, 64

```
seq(printf(seq(printf("%ax%a=%a ",j,i,i*j),j=1..i),"\n"),i=1..9)

```

# Answer
> 3 votes
# x86\_64 machine code (linux), ~~175~~ ~~99~~ 76 bytes

```
0000000000400080 <_start>:
  400080:   66 bf 09 00             mov    $0x9,%di

0000000000400084 <_table.L2>:
  400084:   6a 0a                   pushq  $0xa
  400086:   89 fe                   mov    %edi,%esi

0000000000400088 <_table.L3>:
  400088:   89 f0                   mov    %esi,%eax
  40008a:   f7 e7                   mul    %edi

000000000040008c <_printInteger>:
  40008c:   6a 20                   pushq  $0x20
  40008e:   3c 0a                   cmp    $0xa,%al
  400090:   7d 02                   jge    400094 <_printInteger.L1>
  400092:   6a 20                   pushq  $0x20

0000000000400094 <_printInteger.L1>:
  400094:   66 31 d2                xor    %dx,%dx
  400097:   b3 0a                   mov    $0xa,%bl
  400099:   66 f7 f3                div    %bx
  40009c:   83 c2 30                add    $0x30,%edx
  40009f:   52                      push   %rdx
  4000a0:   66 85 c0                test   %ax,%ax
  4000a3:   75 ef                   jne    400094 <_printInteger.L1>
  4000a5:   6a 3d                   pushq  $0x3d
  4000a7:   66 57                   push   %di
  4000a9:   80 04 24 30             addb   $0x30,(%rsp)
  4000ad:   6a 78                   pushq  $0x78
  4000af:   66 56                   push   %si
  4000b1:   80 04 24 30             addb   $0x30,(%rsp)
  4000b5:   ff ce                   dec    %esi
  4000b7:   75 cf                   jne    400088 <_table.L3>
  4000b9:   ff cf                   dec    %edi
  4000bb:   75 c7                   jne    400084 <_table.L2>

00000000004000bd <_printChars>:
  4000bd:   66 ba 00 08             mov    $0x800,%dx
  4000c1:   b0 01                   mov    $0x1,%al
  4000c3:   66 bf 01 00             mov    $0x1,%di
  4000c7:   48 89 e6                mov    %rsp,%rsi
  4000ca:   0f 05                   syscall

```

~~This is a dump of the binary file, and all of this is 175 bytes. It basically does the same two loops that all the answers do, but printing to the console is a bit harder and basically requires pushing the characters to print onto the stack in reverse, and then making a (linux specific) syscall to actually put those chars into stdout.~~

I've now optimized this so that only 1 write operation is performed (faster!) and has magic numbers (wow!) and by pushing the entire result onto the stack backwards before making the syscall. I also took out the exit routine because who needs proper exit code?

Here's a link to my first and second attempts, in their original nasm syntax.

I welcome anyone who has any other suggestions on how it can be improved. I can also explain the logic in more detail if anyone is curious.

~~(Also, it doesn't print the extra spaces to make all the columns aligned, but if that's required I can put the logic in at the cost of a few more bytes).~~

EDIT: Now prints extra spaces and is golfed down even more! It's doing some pretty crazy stuff with the registers, and is probably unstable if this program were to be expanded.

# Answer
> 3 votes
## Javascript, 190 bytes

Late to the party, but I was piqued by @jdstankosky 's comment and decided to take a different approach. Here's a Javascript entry that mauls a template and evals itself along the way.

```
t="a*b=c ";u="";r=u;for(i=1;i<10;i++){a=0;u=u+t;r+=u.split(' ').map(x=>x.replace('a',++a).replace('b',i)).map(x=>x.replace('*','x').replace('c',eval(x.substr(0,3)))).join(' ')+'\n'}alert(r);

```

Un-golfed version (slightly older version in which a function returns the table instead of a script alerting it, but the same principles apply):

```
function f()
{
    t="a*b=c "; // template for our multiplication table
    u="";r="";  // tmp- and return values
    for(i=1;i<10;i++)
    {
        a=0;    // is auto-incremented in MAP
        u=u+t;// extend the template once per iteration
        v=u.split(' '); // Smash the template to pieces
        w=v.map(x=>x.replace('a', ++a).replace('b', i)) // MAP replaces the A and B's with the correct numbers
        w=w.map(x=>x.replace('*', 'x').replace('c', eval(x.substring(0,3)))).join(' '); // second map evals that and replaces c with the answer, makes the asteriks into an X
        r=r+w+'\n'  // results get concatenated
    }
    return r;
}

```

# Answer
> 3 votes
# Pascal (FPC), ~~128 125~~ 138 bytes

One recursive procedure takes care of everything. Call with `m(9,9)`.

```
procedure m(i,j:int8);begin if i<1then Exit;if i=j then begin m(i-1,j-1);writeln;end;m(i-1,j);write(i,'x',j,'=',i*j,' ':2-i*j div 10);end;

```

Ungolfed:

```
procedure m(i, j: int8);
begin
  if i<1 then
    Exit;
  if i=j then
  begin
    m(i-1, j-1);
    writeln;
  end;
  m(i-1, j);
  write(i,'x',j,'=',i*j,' ':2-i*j div 10);
end;

```

The reason for the byte count going up: the output was not aligned correctly. It is fixed now.

Try it online!

# Answer
> 3 votes
# Fourier, ~~756~~ 632 bytes

Thanks @BetaDecay for 124 bytes!

```
1o120~Ea1o61a1o10~Na1oEa2o61a2o32~Saa2oEa2o61a4oNa1oEa3o61a3oSaa2oEa3o61a6oSaa3oEa3o61a9o^a1oEa4o61a4oSaa2oEa4o61a8oSaa3oEa4o61a12oSa4oEa4o61a16oNa1oEa5o61a5oSaa2oEa5o61aNoSa3oEa5o61a15oSa4oEa5o61a20oSa5oEa5o61a25oNa1oEa6o61a6oSaa2oEa6o61a12oSa3oEa6o61a18oSa4oEa6o61a24oSa5oEa6o61a30oSa6oEa6o61a36oNa1oEa7o61a7oSaa2oEa7o61a14oSa3oEa7o61a21oSa4oEa7o61a28oSa5oEa7o61a35oSa6oEa7o61a42oSa7oEa7o61a49oNa1oEa8o61a8oSaa2oEa8o61a16oSa3oEa8o61a24oSa4oEa8o61aSoa5oEa8o61a40oSa6oEa8o61a48oSa7oEa8o61a56oSa8oEa8o61a64oNa1oEa9o61a9oSaa2oEa9o61a18oSa3oEa9o61a27oSa4oEa9o61a36oSa5oEa9o61a45oSa6oEa9o61a54oSa7oEa9o61a63oSa8oEa9o61a72oSa9oEa9o61a81o

```

# Answer
> 3 votes
# ConTeXt, ~~67~~ 60 bytes

```
\let~\dorecurse\starttext~9{~#1{##1x#1=\luaexpr{#1*##1} }

}

```

# Answer
> 2 votes
# Coreutils/Bash: 147 136 135

```
for i in {1..9}; do
  yes $'\n' | head -n $[i-1] > $i
  paste -dx= <(yes $i) <(seq $i 9) <(seq $[i*i] $i $[9*i]) |head -n$[10-i] >> $i
done
paste {1..9}

```

Golfed, using explicit newline and, using deprecated head option (thanks manatwork):

```
for i in {1..9};do yes '
'|head -$[i-1]>$i;paste -dx= <(yes $i) <(seq $i 9) <(seq $[i*i] $i $[9*i])| head -$[10-i]>>$i;done;paste {1..9}

```

Output:

```
1x1=1
1x2=2   2x2=4
1x3=3   2x3=6   3x3=9
1x4=4   2x4=8   3x4=12  4x4=16
1x5=5   2x5=10  3x5=15  4x5=20  5x5=25
1x6=6   2x6=12  3x6=18  4x6=24  5x6=30  6x6=36
1x7=7   2x7=14  3x7=21  4x7=28  5x7=35  6x7=42  7x7=49
1x8=8   2x8=16  3x8=24  4x8=32  5x8=40  6x8=48  7x8=56  8x8=64
1x9=9   2x9=18  3x9=27  4x9=36  5x9=45  6x9=54  7x9=63  8x9=72  9x9=81

```

# Answer
> 2 votes
## vba 55

(immediate window)

```
for f=1 to 9:for j=1 to f:?f;"x";j;"=";f*j,:next:?:next

```

note - GWBasic only needs 2 extra characters:

```
1 for f=1 to 9:for j=1 to f:?f;"x";j;"=";f*j,:next:?:next

```

# Answer
> 2 votes
## Tcl 98 chars

```
while {[incr a]<10} {set b 0;while {[incr b]<=$a} {puts -nonewline "$a×$b=[expr $a*$b] "};puts ""}

```

# Answer
> 2 votes
## Javascript, 75

```
for(s="",a=b=1;a<10;b=a==b?(a++,alert(s),s="",1):b+1)s+=b+"x"+a+"="+a*b+" "

```

I wonder if something better than two (combined?) for loops is possible...

# Answer
> 2 votes
# Python 2, 72

```
i=1;exec"j=1;exec'print\"%sx%s=%-2s\"%(j,i,j*i),;j+=1;'*i;print;i+=1;"*9

```

Output:

```
1x1=1
1x2=2  2x2=4
1x3=3  2x3=6  3x3=9
1x4=4  2x4=8  3x4=12 4x4=16
1x5=5  2x5=10 3x5=15 4x5=20 5x5=25
1x6=6  2x6=12 3x6=18 4x6=24 5x6=30 6x6=36
1x7=7  2x7=14 3x7=21 4x7=28 5x7=35 6x7=42 7x7=49
1x8=8  2x8=16 3x8=24 4x8=32 5x8=40 6x8=48 7x8=56 8x8=64
1x9=9  2x9=18 3x9=27 4x9=36 5x9=45 6x9=54 7x9=63 8x9=72 9x9=81

```

# Answer
> 2 votes
## LOLCODE, 202 bytes

```
IM IN YR o UPPIN YR b TIL BOTH SAEM b AN 10
c R ""
IM IN YR i UPPIN YR a TIL BOTH SAEM a AN SUM OF b AN 1
c R SMOOSH c SMOOSH a "x" b "=" PRODUKT OF a AN b " " MKAY
IM OUTTA YR i
VISIBLE c
IM OUTTA YR o

```

Ungolfed:

```
HAI 1.3 BTW Unnecessary in current implementations
IM IN YR outer UPPIN YR multiplicand TIL BOTH SAEM multiplicand AN 10
    I HAS A output ITZ ""
    IM IN YR inner UPPIN YR multiplier TIL BOTH SAEM multiplier AN SUM OF multiplicand AN 1
        output R SMOOSH output AN SMOOSH multiplier AN "x" AN multiplicand AN "=" AN PRODUCKT OF multiplicand AN multiplier AN " " MKAY MKAY BTW AN is optional to separate arguments, a linebreak is an implicit MKAY.
    IM OUTTA YR inner
    VISIBLE output
IM OUTTA YR outer
KTHXBYE BTW Unnecessary in current implementations

```

Pythonated for non-leetspeakers:

```
for multiplicand in range(1, 10):
    output = ""
    for multiplier in range(1, multiplicand + 1):
        output = output + (multiplier + "x" + multiplicand + "=" + str(multiplicand * multiplier) + " ")
    print(output)

```

# Answer
> 2 votes
# JAVA, ~~103 94 92~~ 90 bytes

Using JShell from Java 9 SDK allows me to save large amount of space

```
for(int i=0,j;i++<9;)for(j=1;j<=i;)System.out.print(i+"*"+j+"="+i*j+"\t"+(j++<i?"":"\n"))

```

Following Kevin's suggestion I reduced solution by 2 bytes.

Thanks to cliffroot, I was able to reduce it by another 1 byte

# Answer
> 2 votes
**c#, 142 bytes**

```
Enumerable.Range(1,9).ToList().ForEach(i =>Enumerable.Range(1,i).ToList().ForEach(j=>Console.Write("{0}x{1}={2}{3}",j,i,j*i,j==i?"\n":"\t")));

```

And not a for in sight...

# Answer
> 2 votes
## Pyke, ~~17~~ 16 bytes (noncompeting)

Pyke was created after this question was asked

```
TFjSF\xj\=ij*s(P

```

Try it here!

```
TFj           (  - for j in range(10):
   SF         (  -     for i in range(1,j+1):
     \xj\=ij*s   -         sum(i,"x",j,"=",i*j)
               P - pretty_print(^)

```

# Answer
> 2 votes
# \>\<\>, 50 bytes

```
1v
 1
?\::n"x"o{::n"="o}*n" "o1+:{:})
 \~1+:a=?;ao

```

You can try it on the online interpreter.

Note that there is trailing spaces on each lines, which might make it incorrect (OP hasn't stated on this point as of this answer).

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

```
/_/\/\///x/×_N/x9=_E/x8=_V/x7=_S/x6=_F/x5=_R/x4=_O/
1_t/  2_h/ 3/1x1=1Ox2=2tx2=4Ox3=3tx3=6 hx3=9OR4tR8 hR12 4R16OF5tF10hF15 4F20 5F25OS6tS12hS18 4S24 5S30 6S36OV7tV14hV21 4V28 5V35 6V42 7V49OE8tE16hE24 4E32 5E40 6E48 7E56 8E64ON9tN18hN27 4N36 5N45 6N54 7N63 8N72 9N81

```

# Answer
> 2 votes
# Excel, 57 bytes

Requires Excel 365 / 2019 version 2007 or newer

An excel worksheet function that defines the contextual arrays `c` and `r` then outputs an `9x9` array containg the output.

```
=Let(c,Column(A:I),r,Row(1:9),If(c>r,"",r&"x"&c&"="&r*c))

```

# Excel VBA Version, 64 Bytes

Anonymous VBE Immediate window function that takes no input and outputs to range `[A1:I9]` on the `ActiveSheet` object

```
[1:9]="=Let(c,Column(),r,Row(),If(c>r,"""",r&""x""&c&""=""&r*c))

```

### Output

# Answer
> 2 votes
# Japt, 23 bytes

```
9õÈõ_[X'×Z'=X*Z]¬ú6Ã¸Ã·

```

Try it

---

## Explanation

```
9õ                          :Range [1,9]
  È                  Ã      :Pass each integer X through a function
   õ                        :  Range [1,X]
    _              Ã        :  Pass each integer Z through a function
     [X'×Z'=X*Z]            :    Array [X,"×",Z,"=",X*Z]
                ¬           :    Join to a string
                 ú6         :    Pad end with spaces to length 6
                    ¸       :  Join with spaces
                      ·     :Join with newlines

```

# Answer
> 2 votes
# PowerShell, ~~54~~ 52 bytes

```
1..9|%{''+(1..($l=$_)|%{"$_`×$l={0,-2}"-f($_*$l)})}

```

Try it online!

# Answer
> 1 votes
**Perl:  65 , 62 characters**

```
map{map{printf"%dx%d=%2d ",$_,$i,$_*$i}1..($i=$_);print$/}1..9

```

# Answer
> 1 votes
## Javascript: 82 characters

```
o="";for(a=1;a<10;a++){for(b=1;b<=a;b++){o+=a+"x"+b+"="+(a*b)+" "}o+="\n"}alert(o)

```

# Answer
> 1 votes
## Python: 87

I'm eyeballing the solutions others have posted and most of them don't appear to get the spacing correct.

```
for i in range(1,10):print''.join(('%s×%s=%s'%(j,i,i*j)).ljust(7)for j in range(1,i+1))

```

# Answer
> 1 votes
## Python (79)

or (**77**) if I use `range(10)` except that produces an empty line at the start

```
for i in range(1,10):print' '.join('%dx%d=%-2d'%(j,i,j*i)for j in range(1,i+1))

```

---

```
1x1=1
1x2=2  2x2=4
1x3=3  2x3=6  3x3=9
1x4=4  2x4=8  3x4=12 4x4=16
1x5=5  2x5=10 3x5=15 4x5=20 5x5=25
1x6=6  2x6=12 3x6=18 4x6=24 5x6=30 6x6=36
1x7=7  2x7=14 3x7=21 4x7=28 5x7=35 6x7=42 7x7=49
1x8=8  2x8=16 3x8=24 4x8=32 5x8=40 6x8=48 7x8=56 8x8=64
1x9=9  2x9=18 3x9=27 4x9=36 5x9=45 6x9=54 7x9=63 8x9=72 9x9=81

```

# Answer
> 1 votes
# Ruby: ~~79~~ 77 characters (without loops)

```
m=->i,j{"%dx%d=%-3d"%[i,j,i*j]+(i<j ?m[i+1,j]:j<9?$/+m[1,j+1]:$/)};$><<m[1,1]

```

Sample run:

```
bash-4.2$ ruby -e 'm=->i,j{"%dx%d=%-3d"%[i,j,i*j]+(i<j ?m[i+1,j]:j<9?$/+m[1,j+1]:$/)};$><<m[1,1]'
1x1=1
1x2=2  2x2=4
1x3=3  2x3=6  3x3=9
1x4=4  2x4=8  3x4=12 4x4=16
1x5=5  2x5=10 3x5=15 4x5=20 5x5=25
1x6=6  2x6=12 3x6=18 4x6=24 5x6=30 6x6=36
1x7=7  2x7=14 3x7=21 4x7=28 5x7=35 6x7=42 7x7=49
1x8=8  2x8=16 3x8=24 4x8=32 5x8=40 6x8=48 7x8=56 8x8=64
1x9=9  2x9=18 3x9=27 4x9=36 5x9=45 6x9=54 7x9=63 8x9=72 9x9=81

```

# Answer
> 1 votes
**C++, 126 characters**

I took the expected approach.

```
#include <iostream>
int main(){for(int i=1,j;i<10;i++){for(j=1;j<=i;j++)std::cout<<i<<"x"<<j<<"="<<i*j<<" ";std::cout<<std::endl;}}

```

# Answer
> 1 votes
# C, ~~86~~ ~~85~~ 84 bytes

```
i;m(j){for(;i++^9;puts(""))for(j=0;j++^i;printf("%d×%d=%d %c",j,i,j*i,j*i>9?:32));}

```

# Answer
> 1 votes
# k (63 characters)

Prints the output to stdout.

```
-1@`/:" "/:'{7$x,"×",y,"=",z}.''$v,''(*).''v:(1+!:'t),''t:1+!9;

```

Example

```
k)-1@`/:" "/:'{7$x,"×",y,"=",z}.''$v,''(*).''v:(1+!:'t),''t:1+!9;
1×1=1
1×2=2  2×2=4
1×3=3  2×3=6  3×3=9
1×4=4  2×4=8  3×4=12 4×4=16
1×5=5  2×5=10 3×5=15 4×5=20 5×5=25
1×6=6  2×6=12 3×6=18 4×6=24 5×6=30 6×6=36
1×7=7  2×7=14 3×7=21 4×7=28 5×7=35 6×7=42 7×7=49
1×8=8  2×8=16 3×8=24 4×8=32 5×8=40 6×8=48 7×8=56 8×8=64
1×9=9  2×9=18 3×9=27 4×9=36 5×9=45 6×9=54 7×9=63 8×9=72 9×9=81

```

# Answer
> 1 votes
# VBA, 118 bytes

```
Sub M()
While B<9
B=1-B*(B<>A)
A=A-(B=1)
S=S &B &"x"&A &"="&A*B &IIf(A=B,vbLf,Space(2+(A*B>9)))
Wend
MsgBox S
End Sub

```

No for loops :-) and only one while loop.

And no If statements, so I could potentially one-line it and get the automatic "End Sub" for 8 fewer bytes if pushed; but I'm not that close to the leaderboard :-)

```
Sub M():While B<9:B=1-B*(B<>A):A=A-(B=1):S=S &B &"x"&A &"="&A*B &IIf(A=B,vbLf,Space(2+(A*B>9))):Wend:MsgBox S

```

# Answer
> 1 votes
# Python 2, 91 characters

```
for k in[" ".join(["%ix%i=%i"%(j,i,j*i)for j in range(1,i+1)])for i in range(1,10)]:print k

```

Or, if each line as string like '1x2=2 2x2=4' is acceptable, this is 85 characters:

```
for k in[" ".join(["%ix%i=%i"%(j,i,j*i)for j in range(1,i+1)])for i in range(1,10)]:k

```

This one is slightly varied, resulting 93 characters:

```
print("\n".join([" ".join(["%ix%i=%i"%(j,i,j*i)for j in range(1,i+1)])for i in range(1,10)]))

```

# Answer
> 1 votes
## Convex, 27 bytes

```
9´{_´f{æ*'×@@'=\_s,¿)S*}N}%

```

Try it online!

Use the following version if only a single space is required between each equation:

## Convex, 21 bytes

```
9´{_´f{æ*'×@@'=\S}N}%

```

Try it online!

# Answer
> 1 votes
## Javascript (using external library) (74 bytes)

```
n=>_.Range(1,9).WriteLine(v=>_.Range(1,v).Write(" ",x=>v+"x"+x+"="+(v*x)))

```

Link to lib: https://github.com/mvegh1/Enumerable

Code explanation: Create a range starting from 1, for 9 elements. For each integer in the range, write a line according to the predicate accepting the current value as the input param.

Each line in WriteLine will create a range from 1 to v, and write a space delimited string where each integer in the 1 to v sequence is mapped to the multiplication equation

# Answer
> 1 votes
# Kotlin, 73 bytes

```
(1..10).forEach{(1..it).forEach{x->print("${x}x$it=${x*it} ")};println()}

```

Kotlin is the latest JVM language and I mainly wanted to try my hand at it.

You can try it on their online interpreter.

# Answer
> 1 votes
# Groovy, ~~65~~ 60 characters

```
1.upto(9){x->1.upto(x){printf(x+"x$it=%-3d",x*it)}println()}

```

Sample run:

```
bash-4.3$ groovy -e '1.upto(9){x->1.upto(x){printf(x+"x$it=%-3d",x*it)}println()}'
1x1=1
2x1=2  2x2=4
3x1=3  3x2=6  3x3=9
4x1=4  4x2=8  4x3=12 4x4=16
5x1=5  5x2=10 5x3=15 5x4=20 5x5=25
6x1=6  6x2=12 6x3=18 6x4=24 6x5=30 6x6=36
7x1=7  7x2=14 7x3=21 7x4=28 7x5=35 7x6=42 7x7=49
8x1=8  8x2=16 8x3=24 8x4=32 8x5=40 8x6=48 8x7=56 8x8=64
9x1=9  9x2=18 9x3=27 9x4=36 9x5=45 9x6=54 9x7=63 9x8=72 9x9=81

```

# Answer
> 1 votes
# golflua, ~~54~~ 49 characters

```
~@i=1,9~@j=1,i I.w(S.q(i.."x%d=%-3d",j,i*j))$w()$

```

Sample run:

```
bash-4.3$ golflua -e '~@i=1,9~@j=1,i I.w(S.q(i.."x%d=%-3d",j,i*j))$w()$'
1x1=1
2x1=2  2x2=4
3x1=3  3x2=6  3x3=9
4x1=4  4x2=8  4x3=12 4x4=16
5x1=5  5x2=10 5x3=15 5x4=20 5x5=25
6x1=6  6x2=12 6x3=18 6x4=24 6x5=30 6x6=36
7x1=7  7x2=14 7x3=21 7x4=28 7x5=35 7x6=42 7x7=49
8x1=8  8x2=16 8x3=24 8x4=32 8x5=40 8x6=48 8x7=56 8x8=64
9x1=9  9x2=18 9x3=27 9x4=36 9x5=45 9x6=54 9x7=63 9x8=72 9x9=81

```

# Answer
> 1 votes
**C 79 bytes**

```
i=1,j=1;f(){printf("%dx%d=%d ",j,i,i*j);++i>j?++j,i=1,j<=9?puts(""),f():0:f();}

```

the main

```
main(){f();}

```

the table

```
1x1=1
2x1=2 2x2=4
3x1=3 3x2=6 3x3=9
4x1=4 4x2=8 4x3=12 4x4=16
5x1=5 5x2=10 5x3=15 5x4=20 5x5=25
6x1=6 6x2=12 6x3=18 6x4=24 6x5=30 6x6=36
7x1=7 7x2=14 7x3=21 7x4=28 7x5=35 7x6=42 7x7=49
8x1=8 8x2=16 8x3=24 8x4=32 8x5=40 8x6=48 8x7=56 8x8=64
9x1=9 9x2=18 9x3=27 9x4=36 9x5=45 9x6=54 9x7=63 9x8=72 9x9=81

```

# Answer
> 1 votes
# Julia (236 Bytes, potentially 63) - Could use help.

```
A=[1 2 3 4 5 6 7 8 9; 1 2 3 4 5 6 7 8 9; 1 2 3 4 5 6 7 8 9; 1 2 3 4 5 6 7 8 9; 1 2 3 4 5 6 7 8 9; 1 2 3 4 5 6 7 8 9; 1 2 3 4 5 6 7 8 9; 1 2 3 4 5 6 7 8 9;1 2 3 4 5 6 7 8 9]
map(x->x>0?print(x,"x",x,"=",x*x,"\t"):println(),triu!(A'))

```

Someone put in the comments "Who's going to do anything but use 2 loops?"

**This guy is!**

I don't know how to instantiate matrices easily in Julia, anyone who could help me do the instantiation of the matrix better I will be grateful. I can only get it to make a 2D array, and triu doesn't work on that.

How it works:

* `A = [...]` creates a 9x9 matrix with 1-9 in each vector (someone please teach me to do this right without accidentally creating a 2D array... I want to learn this language better, but I'm confused on the typing differences and a lot of the documentation is pretty terse for matrices.
* `triu!(A')` takes the inverse of the upper triangle of the matrix.
* `map(x->x?0...:...,A)` mapping function that differentiates on x=0, printing a newline when needed.

Output:

```
1×1=1
1×2=2  2×2=4
1×3=3  2×3=6  3×3=9
1×4=4  2×4=8  3×4=12 4×4=16
1×5=5  2×5=10 3×5=15 4×5=20 5×5=25
1×6=6  2×6=12 3×6=18 4×6=24 5×6=30 6×6=36
1×7=7  2×7=14 3×7=21 4×7=28 5×7=35 6×7=42 7×7=49
1×8=8  2×8=16 3×8=24 4×8=32 5×8=40 6×8=48 7×8=56 8×8=64
1×9=9  2×9=18 3×9=27 4×9=36 5×9=45 6×9=54 7×9=63 8×9=72 9×9=81

```

# Answer
> 1 votes
# PHP, 73 bytes

```
for(;$m++<9;print"
")for($n=0;$n++<$m;)printf("%d×%d=%-3d",$n,$m,$n*$m);

```

Try it online!

# Answer
> 1 votes
# Pyth, 25 bytes

Now fully conformant!

```
VS9jdm.[s[N\×d\=*Nd)\ 6SN

```

Try it online!

# Answer
> 1 votes
# 05AB1E, ~~22~~ 20 bytes

```
9LεLyâε'×ý'=yPðJ6∍]»

```

-2 bytes thanks to *@Grimmy*.

Try it online.

**Explanation:**

```
9L                 # Push a list in the range [1,9]
  ε                # Map over each value `y`:
   L               #  Push a list in the range [1,y]
    yâ             #  Pair each value in this list with `y`
                   #   i.e. [1,2,3] and 3 → [[1,3],[2,3],[3,3]]
      ε            #  Map over each pair:
       '×ý        '#   Join the pair with "×" delimiter
          '=      '#   Push a "="
            yP     #   Push the pair again, and pop and push it's product
              ð    #   Push a space " "
               J   #   Join all three values on the stack together
                6∍ #   And then shorten the string to size 6
  ]                # Close both the maps
   »               # Join each inner list by spaces, and then each string by newlines
                   # (after which the result is output implicitly)

```

# Answer
> 1 votes
# Burlesque, 45 bytes

```
9roJcp:SOm{Jpdjimup"x="**j_+}{-]j-]==}gb)wduN

```

Try it online!

I'm almost positive there're multiple cuts that can be made here, but I just can't get them...

```
9ro     # Range [1,9]
J       # Duplicate
cp      # Cartesian product
:SO     # Filter for sorted-reversed
m{      # Map
 J      # Duplicate
 pd     # Product
 jimup  # Convert the two numbers into a string ({1 1} => "11")
 "x="** # Riffle in x=                          ("11""x=" => "1x1=")
 j_+    # Append the result
 }
 {
  -]j-] # Heads of both
  ==    # Are equal
 }gb    # Group by first digit being the same
 )wd    # Separate each internal list by spaces
 uN     # Separate main list by newline and prettify

```

# Answer
> 1 votes
# Vyxal, ~~359~~ 20 bytes, `-j` flag

Try it online

```
9ƛɾMƛ\×j\=+nΠ+9↲7Ẏ;∑

```

Finally, I'm done, and to round up LoTM, more forward-slashes. (Edit 1: the \s are gone)

# Answer
> 0 votes
# C#, 131:

```
Action<string> n=x=>Console.Write(" "+x);Action f=()=>{for(int i=1,x=1;i<10;i++){for(;x<=i;x++){n(x+"x"+i+"="+i*x);}n("\n");x=1;}};

```

Isn't the EXACT shape, but nearly there.

# Answer
> 0 votes
## Erlang escript 99

```
$ cat multi

main(_)->[[[io:format("~bx~b=~-3b",[B,A,A*B])||B<-s(A)],io:nl()]||A<-s(9)].
s(X)->lists:seq(1,X).

```

and run

```
$ escript multi
1x1=1
1x2=2  2x2=4
1x3=3  2x3=6  3x3=9
1x4=4  2x4=8  3x4=12 4x4=16
1x5=5  2x5=10 3x5=15 4x5=20 5x5=25
1x6=6  2x6=12 3x6=18 4x6=24 5x6=30 6x6=36
1x7=7  2x7=14 3x7=21 4x7=28 5x7=35 6x7=42 7x7=49
1x8=8  2x8=16 3x8=24 4x8=32 5x8=40 6x8=48 7x8=56 8x8=64
1x9=9  2x9=18 3x9=27 4x9=36 5x9=45 6x9=54 7x9=63 8x9=72 9x9=81

```

# Answer
> 0 votes
# Javascript, ES6 65

```
for(i=0,r='';++i<10;r+='\n')for(e=0;e++<i;r+=i+'x'+e+'='+i*e+' ');

```

It was pretty fun to make!

# Answer
> 0 votes
**C 95 bytes**

```
i=1,j=1;f(){printf("%dx%d=%d %c",j,i,i*j,i!=2||j>4?:32);++i>j?++j,i=1,j<=9?puts(""),f():0:f();}

```

they want this table:

```
1x1=1
2x1=2 2x2=4
3x1=3 3x2=6  3x3=9
4x1=4 4x2=8  4x3=12 4x4=16
5x1=5 5x2=10 5x3=15 5x4=20 5x5=25
6x1=6 6x2=12 6x3=18 6x4=24 6x5=30 6x6=36
7x1=7 7x2=14 7x3=21 7x4=28 7x5=35 7x6=42 7x7=49
8x1=8 8x2=16 8x3=24 8x4=32 8x5=40 8x6=48 8x7=56 8x8=64
9x1=9 9x2=18 9x3=27 9x4=36 9x5=45 9x6=54 9x7=63 9x8=72 9x9=81

```

# Answer
> 0 votes
## Racket 94 bytes

```
(for((n(range 1 10)))(for((i(range 1(add1 n))))(printf "~ax~a=~a  "i  n(* i n)))(displayln""))

```

Ungolfed:

```
(define (f)
  (for ((n (range 1 10)))
    (for ((i (range 1 (add1 n))))
      (printf "~ax~a=~a  " i  n (* i n)))
    (displayln ""))
  )

```

Testing:

```
(f)

```

Output:

```
1x1=1
1x2=2  2x2=4
1x3=3  2x3=6  3x3=9
1x4=4  2x4=8  3x4=12  4x4=16
1x5=5  2x5=10  3x5=15  4x5=20  5x5=25
1x6=6  2x6=12  3x6=18  4x6=24  5x6=30  6x6=36
1x7=7  2x7=14  3x7=21  4x7=28  5x7=35  6x7=42  7x7=49
1x8=8  2x8=16  3x8=24  4x8=32  5x8=40  6x8=48  7x8=56  8x8=64
1x9=9  2x9=18  3x9=27  4x9=36  5x9=45  6x9=54  7x9=63  8x9=72  9x9=81

```

# Answer
> 0 votes
# tcl, 93

```
time {incr i;set j 0;while {[incr j]<=$i} {puts -nonewline $j\x$i=[expr $j*$i]\ };puts ""} 10

```

## demo

# Answer
> 0 votes
# Python 3.6, ~~70~~ 68 bytes

```
r=range(1,10)
for b in r:print(*[f"{a}x{b}={a*b:<2}"for a in r[:b]])

```

Try it online!

# Answer
> 0 votes
# ///, 262 bytes

```
/;/=4//:/x\/\///-/ 6:,/=2//'/ 5:&/=1//%/ 4:#/ 3:"/
1:!/  2x/1x1&"2,!2;"3=3!3=6 #3=9"4;!4=8 #4&2%4&6"5=5!5&0#5&5%5,0'5,5"6=6!6&2#6&8%6,4'6=30-6=36"7=7!7&4#7,1%7,8'7=35-7;2 7x7;9"8=8!8&6#8,4%8=32'8;0-8;8 7x8=56 8x8=64"9=9!9&8#9,7%9=36'9;5-9=54 7x9=63 8x9=72 9x9=81

```

Try it online!

# Answer
> 0 votes
# JavaScript, 70 characters

```
for(s=i='';i++<9;s+='\n')for(j=0;j++<i;s+=j+'×'+i+'='+j*i+' ');alert(s)
```

Respecting alignment, 83 characters:

```
for(s=i='';i++<9;s+='\n')for(j=0;j++<i;s+=j+'×'+i+'='+j*i+(j*i>9?' ':'  '));alert(s)
```

# Answer
> 0 votes
# Haskell, ~~84~~ 82 bytes

```
putStr$init$unlines[unwords[s i++'×':s j++'=':s(i*j)|i<-[1..j]]|j<-[1..9]]
s=show

```

-2 thanks to @Laikoni!

Try it online!

# Answer
> 0 votes
# Perl 5, 51 bytes

```
for$/(1..9){printf$_."x$/=%-3d",$_*$/for 1..$/;say}

```

Try it online!

# Answer
> 0 votes
# Excel VBA, 82 Bytes

Anonymous VBE immediate window function that takes no input and outputs to the VBE immediate window.

```
For y=1To 9:For x=1To 9:?IIf(x>y,"",Left(x &"x"&y &"=" &x*y &"  ",7));:Next:?:Next

```

# Answer
> 0 votes
# uBASIC, 87 bytes

Anonymous function that takes no input and outputs to the console.

```
0ForY=1To9:ForX=1To9:z=x*y:Ifx<=yThen?x;"x";y;"=";z;" ";:Ifz<10Then?" ";
2NextX:?:NextY

```

Try it online!

# Answer
> 0 votes
# Yabasic, 101 bytes

Anonymous function that takes no input and prints a multiplication table to the console.

```
For y=1To 9
For x=1To 9
If(x<=y)Then
?Left$(Str$(x)+"x"+Str$(y)+"="+Str$(x*y)+"  ",7);
Fi
Next
?
Next

```

-3 bytes for the use of `Fi` over `EndIf`

Try it online!

# Answer
> 0 votes
# MY-BASIC, 105 bytes

Anonymous function that takes no input and prints a multiplication table to the console.

`Str(...)` conversions are costly in this solution.

```
For Y=1 To 9
For X=1 To 9
If x<=y Then Print Left(Str(x)+"x"+Str(y)+"="+Str(x*y)+"  ",7)
Next
Print;
Next

```

Try it online!

# Answer
> 0 votes
# Stax, 18 bytes, (17 chars, UTF-8)

```
9mc{b"`n×` =`*"mJ

```

Run and debug it

can't be compressed due to the unicode requirement. a 16 may be possible if I can find a way to compress it. 14 if using `x` is allowed.

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


title: Build me a city

text:
# Question
Title: Build me a city
Coders are always trying to flatten arrays into boring 1-dimensional entities and it makes me sad.

Your task is to unflatten an arbitrary string of characters, outputting a lovely city skyscape.

Consider the string: `aaabbbbbccqrrssstttttttPPw`

It looks much better like this:

```
            tt
            tt
  bb        tt
  bb        tt
aabb      sstt
aabbcc  rrssttPP
aabbccqqrrssttPPww

```

(Ok, yes, the letters are duplicated to make it look more city-skyline-ery).

Take an input string, duplicate each subsection of matching characters (not necessarily alphabetic letters) and build me a city!

Shortest code bytes win.

I actually thought I had the requirements nailed, but to answer some questions:

* it must be on the ground
* you can have extra sky if you want (leading blank lines, surrounding blank space) - but not between the buildings
* letters can be reused inside the string (same architecture, different location)
* the letters are assumed to be ASCII, but more flair will be given to those supporting additional encodings (UTF8, etc)

# Answer
# 05AB1E, 6 bytes

```
γ€DζR»

```

Try it online!

In a version newer than the challenge, `ζ` has been added as a replacement fo `.Bø`

# 05AB1E, 8 bytes

```
γ€D.BøR»

```

Explanation:

```
γ            Convert into a list of consecutive equal elements
 €D          Duplicate each element
   .B        Squarify; pad each element with spaces so that they are the length of the longest element
     ø       Transpose
      R      Reverse (otherwise the city would be upside-down)
       »     Join by newlines

```

Try it online!
> 11 votes

# Answer
# Jelly, 9 bytes

```
Œgx'2z⁶ṚY

```

Try it online!

Explanation:

```
Œgx'2z⁶ṚY  Main Link
Œg         Group runs of equal elements
  x        Repeat
   '              the lists
    2                       twice without wrapping
     z⁶    Zip (transpose), filling in blanks with spaces
       Ṛ   Reverse the whole thing so it's upside-down
        Y  Join by newlines

```
> 6 votes

# Answer
# CJam, 23 bytes

```
qe`::*:__:,:e>f{Se[}zN*

```

Try it online!

Explanation:

```
qe`::*:__:,:e>f{Se[}zN* Accepts (multi-line?) input
q                       Take all input
 e`::*                  Split into groups of equal elements
      :_                Duplicate each
        _:,:e>          Push maximal length without popping
              f{Se[}    Left-pad each to that length with space strings (NOT space chars, although not a problem here)
                    z   Zip
                     N* Join with newlines

```
> 6 votes

# Answer
# Python 3, ~~155~~ ~~136~~ ~~134~~ 132 bytes

*-19 bytes thanks to @LeakyNun*
*-2 bytes thanks to @officialaimm*
*-1 byte thanks to @Wondercricket*

```
s=input()+'+'
k=' '*len(s)
a=[]
c=b=''
while s:
 while c in b:b+=c;c,*s=s
 a+=b+k,b+k;b=c
for r in[*zip(*a)][:0:-1]:print(*r,sep='')

```

Try it online!
> 6 votes

# Answer
# Japt `-R`, ~~19~~ ~~18~~ ~~15~~ ~~13~~ ~~12~~ 9 bytes

Includes trailing spaces on each line.

```
ò¦ Õ®m²ÃÔ

```

Try it

```
ò¦ Õ®m²ÃÔ     :Implicit input of string
ò             :Partition by
 ¦            :  Inequality
   Õ          :Transpose
    ®         :Map
     m        :  Map
      ²       :    Duplicate
       Ã      :End map
        Ô     :Reverse
              :Implicit output joined with newlines

```
> 5 votes

# Answer
# Python 2, 117 bytes

```
import re
s=input()
for l in zip(*[x+S*len(s)for x,_ in re.findall(r'((.)\2*)',s)for S in'  '])[::-1]:print''.join(l)

```

Try it online!
> 5 votes

# Answer
# Java 8, ~~412~~ ~~400~~ ~~330~~ ~~324~~ ~~312~~ 319 bytes

-6 bytes thanks to VisualMelon
-12 bytes thanks to Kevin Cruijssen
but +19 bytes because I forgot to include the imports in the byte count.

```
import java.util.*;x->{Map m=new HashMap(),n;int l=x.length(),i=l,v,y,h=0,d=1;char c,k;for(;i-->0;m.put(c,d=m.get(c)!=null?d+1:1),h=d>h?d:h)c=x.charAt(i);for(y=h;y>0;y--){n=new HashMap(m);for(i=0;i<l;i++)if(n.get(k=x.charAt(i))!=null){v=(int)m.get(k);System.out.print((y>v?"  ":k+""+k)+(i==l-1?"\n":""));n.remove(k);}}}

```

Try it online!
> 5 votes

# Answer
# Mathematica, 150 bytes

```
(z=Characters[v=#];f=CharacterCounts[v][#]&/@(d=Union@z);Row[Column/@Map[PadLeft[#,Max@f,""]&,Table[Table[d[[i]]<>d[[i]],f[[i]]],{i,Length@d}],{1}]])&

```
> 4 votes

# Answer
# , 135 bytes

```
e=rle(sub('(.)','\\1\\1',strsplit(scan(,''),'')[[1]]));write(sapply(sum(e$l|1):1,function(x)ifelse(e$l>=x,e$v,'  ')),'',sum(e$l|1),,'')

```

Try it online!

reads from stdin, writes to stdout (with a trailing newline).

### Explanation:

* `rle` finds the lengths of the streaks of characters, the heights of each tower.
* the `sub` expression replaces each character with its double (so I didn't have to muck about with setting adjacent indices together)
* `sapply` returns an array (in this case a matrix):
    + `sum(e$l|1)` is the number of distinct characters; we go from top to bottom
    + `ifelse( ... )` is a vectorized `if...else` allowing us to build a matrix of towers and double spaces
    + `write` writes to console, with a few options to format.
> 4 votes

# Answer
# Pyth, 13 bytes

```
j_.tsC*2]*Mr8

```

Try it online!
> 3 votes

# Answer
# PHP, 138 bytes

```
for(;~$s=&$argn;$s=substr($s,$r++%2*$i))for($i=0;$i<strspn($s,$c=$s[0]);$f[$i++][$r]=$c)a&$f[$i]?:$f[$i]=" ";krsort($f);echo join("
",$f);

```

Try it online!
> 3 votes

# Answer
# MATL, 15 bytes

```
'(.)\1*'XXtvc!P

```

**Try it online!**

### Explanation

```
'(.)\1*' % Push string to be used as regexp pattern
XX       % Implicit input. Regexp matching. Pushes row cell array of matching substrings
t        % Duplicate
v        % Concatenate vertically
c        % Convert to char. This reads cells in column-major order (down, then across)
         % and produces a 2D char array, right-padding with spaces
!        % Transpose
P        % Flip vertically. Implicitly display

```
> 2 votes

# Answer
# Charcoal, 40 bytes:

```
Ａ⟦⟦ω⟧⟧λＦθ¿⁼ι§§λ±¹¦⁰⊞§λ±¹ι⊞λ⟦ι⟧ＦλＦ²↑⁺⪫ιω¶

```

Try it online! Link is to verbose version of code. I originally tried a simple loop over the input string to print an oblong every time the letter changed, but I switched to this list-building method as it saved 5 bytes. Explanation: The variable `l` contains a nested list of the input letters. Characters that match the current last list elements get pushed onto the last list otherwise a new sublist is created for that character. It then remains to join the letters in each sublist so that they can be printed vertically twice.
> 2 votes

# Answer
# QuadS, 15 + 1 = 16 bytes

+1 byte for the `1` flag.

```
⊖⍵
(.)\1*
2/⍪⍵M

```

Try it online!

`⊖⍵` post-process by flipping upside down

`(.)\1*` runs of identical characters

`2/⍪⍵M` duplicate the columnified **M**atch

The `1` flag causes the results to be merged together.
> 2 votes

# Answer
# Ruby, 116 bytes

```
->s{a=s.scan(/(.)(\1*)/).map{|x,y|[x,y.size+1]}.to_h
m=a.values.max
m.times{|i|puts a.map{|k,v|v+i<m ?'  ':k*2}*''}}

```

Try it online!
> 2 votes

# Answer
# C, ~~259~~ 231 Bytes

## Golfed Code

```
#define v a[1][i
i,k,l,x,h,w;main(char*s,char**a){for(;v];w+=2*!x,s=v++],h=x>h?x:h)x=(s==v])*(x+1);h++;s=malloc((x=h++*++w+1)+w);memset(s,32,h*w);for(i=k;v];s[x+1]=s[x]=k=v++],x=k==v]?x-w:(h-1)*w+l++*2+3)s[i*w]=10;printf("%s",s);}

```

## Verbose Code

```
//Variable Explanations:
//i - increment through argument string, must beinitialized to 0
//k - increment through argument string, must be initialized to 0
//l - record x coordinate in return value, must be initialized to 0
//x - record the actual character position within the return string
//arrheight - the height of the return string
//arrwidth - the width of the return string
//arr - the return string
//argv - the string containing the arguments
#define v argv[1][i

i,k,l,x,arrheight,arrwidth;

main(char*arr,char**argv){
  for(;v];                                 //For Length of input
    arrwidth+=2*!x,                        //increment width by 2 if this char is not the same as the last
    arr=v++],                              //set arr to current char
    arrheight=x>arrheight?x:arrheight      //see if x is greater than the largest recorded height
  )x=(arr==v])*(x+1);                     //if this character is the same as the last, increment x (using arr to store previous char)
  arrheight++;                             //increment height by one since its 0 indexed
  arr=malloc((x=arrheight++*++arrwidth+1)+arrwidth); //create a flattened array widthxheight and set x to be the bottom left position
  memset(arr,32,arrheight*arrwidth);       //fill array with spaces
  for(i=k;v];                              //For Length of input
    arr[x+1]=arr[x]=k=v++],                //set x and x+1 positions to the current character, store current character in i
    x=k==v]?x-arrwidth:(arrheight-1)*arrwidth+l++*2+3 //if next char is same as current move vertically, else set x to bottom of next column
  )arr[i*arrwidth]=10;                     //Add new lines to string at end of width

  printf("%s",arr);                        //output string

}

```

Compiled with GCC, no special Flags

### Edit

Saved 28 bytes thanks to adelphus. His change allowed me to create a define. And I made the while loops into for loops to save 2 bytes each by rearranging the loop. I also fixed an issue where the code would break when the last character in input wasn't singleton. The code will fail if there is only one unique letter but should work in all other cases.
> 2 votes

# Answer
# Factor \+ `grouping.extras sequences.repeating`, 94 bytes

```
[ [ ] group-by values dup longest length '[ _ 32 pad-head ] map 2 repeat flip [ print ] each ]

```

Modern Factor doesn't require a conversion to string before printing a sequence of code points, so have a screenshot of running the quotation in the listener:

Here's a TIO link with the extra `>string`:

Try it online!

## Explanation:

It's a quotation (anonymous function) that takes a string as input and outputs to standard output. Assuming `"aaabbbbbccqrrssstttttttPPw"` is on the data stack when this quotation is called...

* `[ ] group-by values` Split into groups of equal elements.

**Stack:** `{ V{ 97 97 97 } V{ 98 98 98 98 98 } V{ 99 99 } V{ 113 } V{ 114 114 } V{ 115 115 115 } V{ 116 116 116 116 116 116 116 } V{ 80 80 } V{ 119 } }`
* `dup longest length` Keep the 'city' on the stack but also find the length of the longest 'building.'

**Stack:** `~city~ 7`
* `'[ _ 32 pad-head ] map` Pad the city with whitespace to be a rectangular matrix.

**Stack:** `{ V{ 32 32 32 32 97 97 97 } V{ 32 32 98 98 98 98 98 } V{ 32 32 32 32 32 99 99 } V{ 32 32 32 32 32 32 113 } V{ 32 32 32 32 32 114 114 } V{ 32 32 32 32 115 115 115 } V{ 116 116 116 116 116 116 116 } V{ 32 32 32 32 32 80 80 } V{ 32 32 32 32 32 32 119 } }`
* `2 repeat` Repeat each row twice.
* `flip` Transpose the matrix.
* `[ print ] each` Print each row to standard output.
> 2 votes

# Answer
# , 22 bytes

```
2|.@|:@#[[;.1~1,2~:/\]

```

Try it online!
> 2 votes

# Answer
# Pip, 22 bytes

21 bytes of code, +1 for `-l` flag.

```
Ya@`(.)\1*`RV:yWVyZDs

```

Try it online!

### Explanation

```
                       a is 1st cmdline arg; s is space (implicit)
 a@`(.)\1*`            Using regex, create list of runs of same character in a
Y                      Yank that into y variable
              yWVy     Weave (interleave) y with itself to duplicate each item
                  ZDs  Zip to transpose, with a default character of space filling gaps
           RV:         Reverse the resulting list (with the compute-and-assign
                        meta-operator : being abused to lower the precedence)
                       Auto-print, one sublist per line (implicit, -l flag)

```
> 1 votes

# Answer
# Haskell, 144 bytes

```
f s=let x=groupBy(==)s;l=length;m=maximum(map l x)in concatMap(++"\n")$reverse$transpose$concat[[z,z]|z<-(map(\y->y++(replicate(m-(l y))' '))x)]

```

I'm pretty confident I can do better than this, but this is the best I can come up with for the time being.
> 1 votes

# Answer
# Stacked, 42 bytes

```
[rle toarr[...*chars]map FIX 2*tr rev out]

```

Try it online!
> 1 votes

# Answer
# Ruby, 107 bytes

```
gets.gsub(/(.)(\1*)/,'\0
'*2).split('
').map{|x|x.ljust($_.size).chars}.transpose.reverse.map{|x|puts x*""}

```

Try it online!

a full program which assumes there will be no newlines in the string.
> 1 votes

# Answer
# JavaScript (V8), 98 bytes

```
x=>x.replace(/(.)\1*/g,y=>s=s.replace(/$/mg,_=>y[i]+y[i--]||'  ',i=n),s=`
`.repeat(n=x.length))&&s

```

Try it online!

# JavaScript (V8), 100 bytes

```
x=>x.replace(/(.)\1*/g,(y,c)=>s=s.replace(/$/mg,_=>y[i--]?c+c:'  ',i=n),s=`
`.repeat(n=x.length))&&s

```

Try it online!
> 1 votes

# Answer
# APL (Dyalog), 37 bytes

```
{⊃,/⍵↑⍨¨-⌈/≢¨⍵}'(.)\1*'⎕S{2/⍪⍵.Match}

```

Try it online!
> 0 votes

# Answer
# q/kdb+, 53 bytes

**Solution:**

```
{(|)(+)(,/)(max(#:)each c)$(+)2#(,)c:((&)differ x)_x}

```

**Example:**

```
 q){(|)(+)(,/)(max(#:)each c)$(+)2#(,)c:((&)differ x)_x}"BBPPPPxxGGGGKKKKKKKkkkkEEeeEEEeeEEEEEOOO8####xxXXX"
 "        KK                      "
 "        KK                      "
 "        KK          EE          "
 "  PP  GGKKkk        EE    ##    "
 "  PP  GGKKkk    EE  EEOO  ##  XX"
 "BBPPxxGGKKkkEEeeEEeeEEOO  ##xxXX"
 "BBPPxxGGKKkkEEeeEEeeEEOO88##xxXX"

```

**Explanation:**

```
{reverse flip raze (max count each c)$flip 2#enlist c:(where differ x)_x} / ungolfed function
{                                                                       } / lambda function
                                                      (where differ x)    / indices where x differs
                                                                      _   / cut at these points aabbbc -> "aa","bbb","c"
                                                    c:                    / save in variable c
                                             enlist                       / put this list in another list
                                           2#                             / take two from this list (duplicate)
                                      flip                                / rotate columns/rows
                   (max count each c)                                     / find the longest run of characters
                                     $                                    / whitespace pad lists to this length
              raze                                                        / reduce down lists
         flip                                                             / rotate columns/rows
 reverse                                                                  / invert so buildings are on the ground

```
> 0 votes

# Answer
# Perl 5, 92 + 1 (-p) = 93 bytes

```
while(s/(.)\1*//){$a[$_].=($"x($i-length$a[$_])).$1x2for 1..length$&;$i+=2}say while$_=pop@a

```

Try it online!
> 0 votes

---
Tags: code-golf, string, ascii-art
---


title: Which th second now in this year

text:
# Question
Title: Which th second now in this year
In this challenge you have to find out which nth second it is now in this year, current date and time now. Or in other words, how many seconds have passed since New Year.

An example current Date is (it's not given, you'll have to find the current Date):

```
March 5, 2021 1:42:44 AM

```

For which the answer is `5449364` (or optionally `5449365` if you count January 1, 2021 0:00:00 as the first second).

So you should return or output which 'th second it is now in this year. Standard loopholes apply, shortest code wins. You may keep fractional seconds in output optionally.

# Answer
# PHP, 27 bytes

```
<?=time()-strtotime('1/1');

```

---

```
time()           // current timestamp in seconds
strtotime('1/1') // timestamp of January 1st

```

Try it online!
> 6 votes

# Answer
# Python 2, 55 bytes

```
from time import*
k=86400
print~-gmtime()[7]*k+time()%k

```

Try it online!

*-4 bytes thanks to Wasif*

*-11 bytes thanks to dingledooper*
> 5 votes

# Answer
# PowerShell, 31 bytes

```
new-timespan 1/1 (date)|% t*ls*

```

Try it online!

Too late to post this one

---

# PowerShell, 71 bytes

```
$x=date;((($x|% d*r)-1)*86400)+($x.hour*3600)+($x.minute*60)+($x|% s*d)

```

Try it online!

Example output:

```
Friday, March 5, 2021 6:20:21 AM
5466021

```

You just multiply day of year by 86400 (24*60*60) and then minutes by 60, hours by 3600 (60\*60) and seconds, and sum up all
> 3 votes

# Answer
# , 73 bytes

```
`?`=as.double
-?as.POSIXct(paste0(substr(t<-Sys.time(),1,4),"-01-01"))-?t

```

Try it online!

Returns the index of the current second, in the year that the program is run (currently 2021 at time of posting).

The POSIXct class used by  to represent dates conveniently equals the number of seconds since the start of 1970.
So, to calculate the index of the current second *this year* (2021), we just need to subtract the number of seconds between 1 Jan 1970 and 1 Jan 2021, which is 1609455600. This requires only 32 bytes of code.

Unfortunately, all of the slickness of the approach above is somewhat lost by the clunkiness of extracting a string to represent 1 Jan of the *current year*...
> 3 votes

# Answer
# Red, 58 bytes

```
d: now prin d/11 - 1 * 86400 +(d/7 * 3600)+(d/8 * 60)+ d/9

```

Try it online!

Explanation: `d` is of `date!` datatype. I would normally acces its fields usng `path` notation like `d/yearday` to find which date of the year is today. Luckily Red has ordinal accessors for the fields as follows:

```
Index Name
1     date
2     year
3     month
4     day
5     zone
6     time
7     hour
8     minute
9     second
10    weekday
11    yearday
12    timezone
13    week
14    isoweek

```
> 2 votes

# Answer
# Japt, ~~19 12~~ 11 bytes

```
K-ÐKi T)zA³

```

Try it online!

does current time(in ms) - january 1 , divide by 1000 and floor.

-7 bytes from Shaggy and AZTECC0.

-1 byte from Shaggy.
> 2 votes

# Answer
# JavaScript (V8), 53 bytes

```
print(((n=new Date)-new Date(n.getFullYear(),0))/1e3)

```

Try it online!

Prints fractional number of seconds. Adding `|0` will make this an integer for 2 more bytes.
> 2 votes

# Answer
## Excel, 20 or 36 bytes

This works for just 2021

```
=(NOW()-44197)*86400

```

This works for all years.

```
=(NOW()-DATE(YEAR(NOW()),1,1))*86400

```
> 2 votes

# Answer
# JavaScript (V8), ~~46~~ 32 bytes

-14 bytes thanks to ophact!

```
_=>(Date.now()-16094592e5)/1e3|0

```

Try it online!

The function gets the timestamp of the current time, i.e. number of milliseconds from the 1st January 1970

```
new Date().getTime()

```

Then subtract the number of milliseconds passed from 1970 to 2021

```
1609459200000

```

And divides the result by `1000` to get the number of seconds.

Finally it returns the result after having converted it to unsigned integer through the bitwise OR `|` (because the division gives a floating point number)

The variable `_` is never used but passing no argument would cost one byte `()=>`.
> 2 votes

# Answer
# Python 2, 79 bytes

```
from datetime import*
print (datetime.now()-datetime(2021,1,1)).total_seconds()

```

Try it online!

---

# Python 2, 105 bytes

```
from datetime import*
n=datetime.now();print n.timetuple().tm_yday*86400+n.hour*3600+n.minute*60+n.second

```

Try it online!

**Equal-byte alternative:**

# Python 2, 105 bytes

```
from datetime import*
n=datetime.now();print int(n.strftime('%j'))*86400+n.hour*3600+n.minute*60+n.second

```

Try it online!

# Python 2, 84 bytes

```
from datetime import*
n=datetime.now();print(n-datetime(n.year,1,1)).total_seconds()

```

Try it online!

Thanks to @ovs for -21 bytes
> 1 votes

# Answer
# Javascript (Browser), 163 bytes

```
d=new Date();x=d.getFullYear();y=((Date.UTC(x,d.getMonth(),d.getDate())-Date.UTC(x,0,0))/864e5)-1;alert(y*86400+d.getHours()*3600+d.getMinutes()*60+d.getSeconds())

```

UTC based day of year calculation thanks to this answer in Stack Overflow, I then tried to golf and use the function

# JavaScript (V8), 163 bytes

```
d=new Date();x=d.getFullYear();y=((Date.UTC(x,d.getMonth(),d.getDate())-Date.UTC(x,0,0))/864e5)-1;print(y*86400+d.getHours()*3600+d.getMinutes()*60+d.getSeconds())

```

Try it online!
> 1 votes

# Answer
# T-SQL 55 Bytes,

`PRINT DATEDIFF(S,STR(YEAR(GETDATE()))+'0101',GETDATE())`

DATEDIFF takes difference between two DATETIME types, S makes the difference be in seconds.

GETDATE() gets the local datetime as a DATETIME.

YEAR takes a DATETIME/DATE argument, returns the year component of the argument.

STR converts the YEAR integer to a string. + is also string concatenation in T-SQL.

The string in format 'YYYYMMDD' is implicitly converted to a DATETIME with a zero time component in the DATEDIFF function.

Results in the number of seconds since the 1st of Jan this Year.
> 1 votes

# Answer
# AWK, 47 bytes

```
$0=strftime("%j",r=systime(),1)*(q=86400)+r%q-q

```

Try it online!

I wasn't sure if the seconds into the year should start from midnight Jan 1 in the local timezone or in UTC. This version works for UTC.

It figures out the julian date (the number of days into the year), converts that to seconds then adds in the fractional day's worth of seconds.

```
strftime("%j",r=systime(),1)

```

Gets the julian date, and stores the UNIX epoch in variable `r` in the process. It add a 3rd parameter on `strftime` to get the time in UTC.

```
*(q=86400)

```

Converts the days to seconds and saves the constant "seconds per day" in for use later.

```
+r%q

```

Adds in the seconds corresponding to the `HH:MM:SS` offset from midnight UTC using modulo math.

```
-q

```

And this is annoying 2 characters I couldn't figure out how to drop... Since julian days start with 1, the `%j` include the current day so we have to subtract a full day.

```
$0=

```

Finally, assigning the result to `$0` means the whole expression is actually a condition, which is always truthy except for at exactly midnight on Jan 1st, so the value is printed.

If an offset in seconds from local time is acceptable, this more straightforward, and slightly shorter code would work.

```
$0=systime()-mktime(strftime("%Y 1 1 0 0 0"))

```

That one just subtracts the UNIX epoch for Jan 1st at mightnight of the current year from the current epoch time.
> 1 votes

# Answer
# JavaScript, ~~83~~ 61 bytes

```
_=>(new Date()-new Date(new Date().getFullYear()+'-1-1'))/1e3

```

Yes, it was possible in the end. Could probably shave off a few more bytes. This code outputs the number of seconds since January 1 of the current year, 2021 at the time of writing. Returns a floating point number.

This code does not explicitly output, but running something like

```
console.log(f())

```

where `f` is the function I posted, will output the result
> 1 votes

# Answer
# Bash, 33

```
dc<<<`date -f- +%s<<<"now
1/1"`-p

```

Try it online!

### Explanation

```
                     "now\n1/1"     # newline separated now, Jan-1st dates
      date -f- +%s<<<"now\n1/1"     # with -f, date formats multiple lines as multiple seconds-since-1970/01/01
     `date -f- +%s<<<"now\n1/1"`-p  # expands to dc expression to push now-seconds, Jan-1st-seconds, then subtract, then print
dc<<<`date -f- +%s<<<"now\n1/1"`-p  # evaluate the dc expression

```
> 1 votes

# Answer
# Vyxal, 26 bytes

```
kτ‹86400*kḢ3600*+kṀ60*+kṠ+

```

Try it Online!

For some unknown reason, `s` flag dosen't work
> 1 votes

# Answer
# Julia 1.0, 54 bytes

```
using Dates
f(n=now())=(n-DateTime(year(n))).value/1e3

```

Try it online!
> 1 votes

# Answer
# R, ~~60~~ 31 bytes

```
-difftime(paste0(substr(t<-Sys.time(),1,4),"-01-01"),t,,'s')

```

using difftime with @Dominic van Essen's new years day replacement method

answer is in the following format:

> Time difference of 11203844 secs

TIO\_link

rdrr.io link

a much shorter version:

```
as.double(Sys.time())%%31536000

```

Try it online!
> 1 votes

# Answer
# IBM/Lotus Notes Formula, 33 bytes

```
@Now-@Date(@Year(@Now);1;1;0;0;0)

```

Date comparisons return seconds by default. Unfortunately `@Date` requires the seconds otherwise it constructs a date with the current time.

No TIO for formula so here are a couple of screenshots:
> 0 votes

# Answer
# Wolfram Language (Mathematica), 36 bytes

```
DateDifference[{2021},Now,"Second"]

```

Try it online!
> 0 votes

# Answer
# APL (Dyalog Unicode) 18.0, 16 bytes (SBCS)

Full program

```
-/20⎕DT↑∘⎕TS¨6 1

```

Try APL online!

`6 1` a 2-element list `[6,1]`

`↑∘⎕TS¨` for each number, take that many elements from the current YMDhmsf list

`20⎕DT` convert the two dates (the 1-element date is padded with the lowest valid values, i.e. `[1,1,0,0,0,0]` for the beginning of the 1st of January) to UNIX time (seconds since the beginning of 1970)

`-/` difference between them
> 0 votes

# Answer
# 05AB1E, 37 bytes

```
•ΘÏF•ºS₂+žf<£že<ªOŽª+·*žaŽEU*žb60*žcO

```

Try it online.

**Explanation:**

```
•ΘÏF•                   # Push compressed integer 5254545
     º                  # Mirror it to 52545455454525
      S                 # Convert it to a list of digits: [5,2,5,4,5,4,5,5,4,5,4,5,2,5]
       ₂+               # Add 26 to each: [31,28,31,30,31,30,31,31,30,31,30,31,28,31]
         žf             # Push the current month
           <            # Decrease it by 1
            £           # Leave that many leading integers from the list
             že         # Push the current day of the month
               <        # Decrease it by 1 as well
                ª       # Append it to the list
                 O      # Sum it together (total amount of days thus far)
                  Žª+   # Push compressed integer 43200
                     ·  # Double it to 86400
                      * # And multiply it to the amount of days
ža                      # Push the current hours
  ŽEU*                  # Multiply it by compressed 3600
žb                      # Push the current minutes
  60*                   # Multiply it by 60
žc                      # Push the current seconds
O                       # Sum all values on the stack together
                        # (after which the result is output implicitly)

```

See this 05AB1E tip of mine (section *How to compress large integers?*) to understand why `•ΘÏF•` is `5254545`; `Žª+` is `43200`; and `ŽEU` is `3600`.
> 0 votes

# Answer
# Factor, 38 bytes

```
now now start-of-year time- second>> .

```

TIO is too old to have `start-of-year`, so have a screenshot of running the code in the listener. Link to online documentation for the word: https://docs.factorcode.org/content/word-start-of-year,calendar.html

## How it works:

Generate two timestamps: one now, and the other at the beginning of the year. Subtract them and then extract the result
> 0 votes

# Answer
# Javascript 25 bytes

Reach 38 with the console.log().

```
console.log(Date.now()/1e3-1609459200)
```
> 0 votes

# Answer
# Nim, 59 bytes

```
import times
echo inSeconds now()-($now().year).parse"YYYY"

```

Try it on the Nim playground! (For some reason, it doesn't work correctly on TIO.)
> 0 votes

---
Tags: code-golf, math, date
---


title: Least notes money exchange

text:
# Question
Title: Least notes money exchange
Suppose A and B are two good friends. A has borrowed \\$n\\$ dollar from B. Now B wants the money back from A and A is also ready to give it. But the problem is A has only \\$x\\$ dollar notes and B has \\$y\\$ dollar notes. They both want to keep the number of notes in exchange as low as possible.

As an example if \\$n=37\\$, \\$x=5\\$ and \\$y=2\\$, then the least amount of notes in exchange will be nine $5 notes from A and four $2 notes from B, which totals to $37.

Your input will be \\$n, x, y\\$ and your output should be the least of amount of notes possible for \\$A\\$ and \\$B\\$ such that \\$B \> 0\\$. Input and output seperator can be anything, no leading zeros in input numbers, no negative numbers in input. Standard loopholes apply and shortest code wins.

**Test Cases**

```
37 5 2 -> 9 4
89 3 8 -> 35 2
100 12 7 -> 13 8
10 1 100 -> 110 1

```

Input will be always solvable.

# Answer
# Python 2, 51 bytes

```
n,x,y=input()
c=n+y
while c%x:c+=y
print(c-n)/y,c/x

```

Try it online!

-8 bytes thanks to Jonathan Allan
> 7 votes

# Answer
# , 40 bytes

```
1 :'1+[:($#:u i.~,)[:+//(,-)*/1+[:i.u+]'

```

Try it online!

A bit labored as J code, but the idea is simple.

We construct a table with all the possible linear combinations, and just find the coordinates of what we're looking for:

In the actual code we drop the first column (because of the B \> 0) constraint, and then have to add 1 to the returned coords, to adjust for 0-indexing.
> 7 votes

# Answer
# Brachylog, 14 12 bytes

```
b;.z₂×ᵐ-~h?∧

```

Try it online!

The albeit strange constraint that the outputs must be `≥1` helps, as Brachylog tries only positive numbers for multiplication.

```
b;.z₂×ᵐ+~h?∧  [37,5,2]
b             [5,2]
 ;.           [[5,2], output]
   z₂         [[5, A], [2, B]]
     ×ᵐ       [5 * A, 2 * B]
       -      5 * A - 2 * B
        ~h?   [5 * A - 2 * B, X, Y] = [37, 5, 2]
           ∧  return the output [A,B] and solve the constraints

```
> 7 votes

# Answer
# JavaScript (Node.js), 54 bytes

```
f=(n,x,y,i=0)=>(i-n)%y||n>i?f(n,x,y,i+x):[i/x,(i-n)/y]

```

Try it online!

Javascript beats Python!
> 4 votes

# Answer
# Jelly,  ~~14 13 12~~  11 bytes

-1 thanks to Nick Kennedy! (Dividing through and keeping those invariant under flooring is terser than testing divisibility and then integer dividing.)

```
‘r×ṀɗĖ÷ḞƑƇḢ

```

A dyadic Link accepting `amount owed` and a list of denominations `[y, x]` that yields a list of `[B gives, A gives]`.

**Try it online!**

### How?

```
‘r×ṀɗĖ÷ḞƑƇḢ - Link: integer, n; list of integers [y,x]
‘           - increment (n)
    ɗ       - last three links as a dyad - f(n+1,[y,x]):
   Ṁ        -   maximum ([y,x])
  ×         -   (n+1) multiplied by (that)
 r          -   inclusive range -> [n+1, n+2, ..., (n+1)×max([y,x])]
     Ė      -   enumerate -> [[1,n+1],[2,n+2],...]
                   (...note that this equals [[n+1-n,n+1],[n+2-n,n+2],...])
      ÷     -  divide by ([y,x])? (vectorises)
         Ƈ  - keep those which are:
        Ƒ   -   invariant under:
       Ḟ    -     floor
          Ḣ - head

```
> 4 votes

# Answer
# JavaScript (V8), 45 bytes

```
x=>y=>n=>(g=m=>m%x?g(m+y):[m/x,(m-n)/y])(n+y)

```

Try it online!
> 4 votes

# Answer
# JavaScript (V8), ~~41~~ 39 bytes

```
(n,x,y)=>g=(B=1)=>(n+=y)%x?g(B+1):[n/x,B]  // 41 bytes, original

(n,x,y)=>g=B=>(n+=y)%x?g(-~B):[n/x,-~B]    // 39 bytes, user l4m2’s improvement

```

## 41 bytes, original

Try it online

The formula to satisfy is `A * x = n + B * y`, or `A = (n + B * y) / x`. Since we are looking for an `A` that is an integer, we try `B = 1, 2, 3, …` until `n + B * y` is divisible by `x`.

For `B = 1, 2, 3, …`, we have `A * x = n + y, n + y + y, n + y + y + y, …`, so we can reuse `n` to store `A * x` and increment it by `y` at the beginning of each iteration.

The solution is similar to Redwolf Programs’, and is equally 41 bytes long, but IMHO its form is different enough to merit being a separate answer, and the function accepts the arguments in a more natural form `f(n,x,y)` rather than `f(n,x)(y)`.

## 39 bytes, user l4m2’s improvement

Try it online

`~B` gives the 2’s complement of `B`, which for non-negative integers is equivalent to `-(B + 1)`. So `-~B` is equivalent to `B+1`… with the difference that `~B` implicitly casts `undefined` to 0, so we no longer need to initialize `B=0`. What a trick!
> 4 votes

# Answer
# JavaScript (V8), ~~47~~ ~~42~~ 41 bytes

*-5 from @Arnauld*
*-1 from @tsh*

```
(n,x,b=0)=>g=y=>(++b,n+=y)%x?g(y):[n/x,b]

```

Try it online!

**Old:**

```
(n,x,b=0)=>g=y=>(a=++b*y+n)%x?g(y):[a/x,b]

```

Try it online!

**Old:**

```
(n,x,y)=>(g=b=>(a=b*y+n)/x%1?g(b+1):[a/x,b])(1)

```

Try it online!
> 3 votes

# Answer
# Python 3, 50 bytes

```
f=lambda x,y,n,s=1:s+n%x and 1j+f(x,y,n+y,0)or n/x

```

Try it online!

Output as the format `(9+4j)`
> 3 votes

# Answer
# Charcoal, 28 bytes

```
Ｎθ≔⁺×…·¹θＮＮη≔⌕﹪ηθ⁰ζＩ⟦÷§ηζθ⊕ζ

```

Try it online! Link is to verbose version of code. Takes input in the order `x y n`. Explanation:

```
Ｎθ

```

Input `x`.

```
≔⁺×…·¹θＮＮη

```

Form a range from `1` to `x`, multiply each element by `y`, and add `n`.

```
≔⌕﹪ηθ⁰ζ

```

Find the index of the first multiple of `x`, which is also `1` less than the number of notes for `B`.

```
Ｉ⟦÷§ηζθ⊕ζ

```

Calculate the number of notes for `A` and output the results on separate lines.
> 3 votes

# Answer
# APL (Dyalog Unicode), ~~21~~ 20 bytes

Similar idea as Jonah's J answer, but quite a bit shorter due to APL's 1-indexing.

```
{⊃⍸⍺=⊃∘.-/⍵×⊂⍳⍺+⌈/⍵}

```

Try it online!

A dfn which takes `n` as left input  and the array `x y` as right argument :

```
             ⍳⍺+⌈/⍵   ⍝ indices from 1 to n + max(x, y)
          ⍵×⊂         ⍝ multiply x and y with each index
     ⊃∘.-/            ⍝ create a table of all pairwise differences
   ⍺=                 ⍝ for each value: does it equal n?
 ⊃⍸                   ⍝ get the first index of a 1

```
> 3 votes

# Answer
# , ~~54~~ 50 bytes

```
function(n,x,y){while((m=n+T*y)%%x)T=T+1;c(m/x,T)}

```

Try it online!

Port of @hyper-neutrino's answer.

*-4 bytes thanks to @Dominic*

---

Port of @tsh's answer:

### , 53 bytes

```
f=function(n,x,y,s=1)"if"(s+n%%x,1i+f(n+y,x,y,0),n/x)

```

Try it online!

---

Other ports of @hyper-neutrino's answer:

### , 54 bytes

```
function(n,x,y,K=n+y){while(K%%x)K=K+y;c(K/x,(K-n)/y)}

```

Try it online!

### , 54 bytes

```
function(n,x,y,K=n){while((K=K+y)%%x)0;c(K/x,(K-n)/y)}

```

Try it online!
> 3 votes

# Answer
# Java, ~~79~~ 63 bytes

```
(n,x,y)->{int a=n/x,b;for(;(b=++a*x-n)%y>0;);return a+" "+b/y;}

```

*Saved 16 bytes thanks to Olivier Grégoire.*

Try it online!
> 2 votes

# Answer
# Haskell, 50 bytes

```
(x#y)n=[(div(n+i*y)x,i)|i<-[1..],mod(n+i*y)x<1]!!0

```

Try it online!

The relevant function is `(#)`, which takes as input integers `x`, `y`, `n` and returns a pair `(a,b)`, meaning that A should give `a` notes and B should give `b` back.
> 2 votes

# Answer
# C (clang), ~~60~~ 58 bytes

Saved 2 bytes thanks to G. Sliepen!!!

```
f(n,x,y,s){(n+=y)%x?f(n,x,y,s+1):printf("%d %d",n/x,s+1);}

```

Try it online!

Uses the formula from Jonathan Allan's comment to hyper-neutrino's Python answer.
> 2 votes

# Answer
# 05AB1E, 22 bytes

```
∞*.Δ²@²y-³Ö*}D²α³÷,¹÷,

```

Try it online!

A port of hyper-neutrino's python answer.
> 1 votes

# Answer
# Ruby, 38 bytes

```
->n,x,y{[1.step.find{(n+=y)%x<1},n/x]}

```

Try it online!

### How

The trick is in `1.step.find`: we add y to n at least once, and count iterations until n is divisible by x.

Outputs `[B,A]`
> 1 votes

# Answer
# Lua, 75 bytes

```
load('n,x,y='.. .....' c=n repeat c=c+y until c%x==0 print(c/x,(c-n)/y)')()

```

Try it online!
> 1 votes

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