title: Shooting gallery Puzzle!

text:
# Question
Title: Shooting gallery Puzzle!
> Have you been shooting gallery? We are recently.

In our shooting gallery cans and aluminum cans from under various drinks hang and stand. More precisely, they hung and stood.

From our shots, banks dangled from side to side on a rope, were torn off, rang, crumpled. This is not for you to shoot from your fingers.

Each of the bullets either went right through one of the cans, after which the affected can fell to the floor and rolled away so that it was no longer possible to get into it; or didn’t hit any of the cans. In any case, each of the bullets was stuck in the wall behind our target cans.

But that day is past. There was only a wall with bullets stuck in it and a photograph. In an attempt to restore that day and enjoy it again, we collected data on the position of each bullet in the wall, the location of the cans and the order of the shots.

> Help determine about each bullet whether it hit one of the cans, and if it hit, then which one.

**Input format**

The first line contains two integers n and m (1 ≤ m, n ≤ 1000) - the number of cans that were our target on that day, and the number of shots fired that day.

The i-th of the next n lines describes the position of the i-th jar. The position is set by the coordinates of the can’s projection onto the vertical plane. The projection is a rectangle, the sides of which are parallel to the coordinate system applied to this plane. The Y axis of this system is directed vertically upward, and the X axis is horizontally. A rectangle is defined by a pair of points - its left bottom and top right vertices.

> It is guaranteed that not a single pair of these rectangles has a single common point.

The i-th of the next m lines describes the position of the i-th bullet in the wall. The bullets are set in the same order in which they left our muzzle. The wall itself is strictly vertical, so we can assume that the position is given by the coordinates of the projection of bullets on a vertical plane. Moreover, the trajectories of the bullets were strictly perpendicular to this plane. The points themselves are defined by a pair of coordinates in the coordinate system already described above.

> The distance between the banks and the wall compared to the distance to the shooters is so small that we neglect it.

**Output format**

In the first and only line print m numbers, the i-th of which says which of the cans the i-th bullet went through, if any. If i didn’t hit any banks, print -1, otherwise print the serial number in the input of the bank, which was struck by the ith bullet.

```
Sample Input:

4 10
0 0 1 1
2 3 3 8
15 15 20 20
10 12 12 13
2 2
0 -1
23 18
13 12
10 13
16 16
17 17
3 5
3 5
3 3

Sample Output:

-1 -1 -1 -1 4 3 -1 2 -1 -1

```

Here is a representation of the positions in the above sample - the original locations of the four cans `1` \- `4`, and the ten bullet locations `a` \- `j` \- note that `i` is actually in the same location as `h` (`(3,5)`) and that a row is shown for `y=-1` due to `b`:

```
. . . . . . . . . . . . . . . 3 3 3 3 3 3 . . .
. . . . . . . . . . . . . . . 3 3 3 3 3 3 . . .
. . . . . . . . . . . . . . . 3 3 3 3 3 3 . . c
. . . . . . . . . . . . . . . 3 3 g 3 3 3 . . .
. . . . . . . . . . . . . . . 3 f 3 3 3 3 . . .
. . . . . . . . . . . . . . . 3 3 3 3 3 3 . . .
. . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . e 4 4 . . . . . . . . . . .
. . . . . . . . . . 4 4 4 d . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . .
. . 2 2 . . . . . . . . . . . . . . . . . . . .
. . 2 2 . . . . . . . . . . . . . . . . . . . .
. . 2 2 . . . . . . . . . . . . . . . . . . . .
. . 2 h . . . . . . . . . . . . . . . . . . . .
. . 2 2 . . . . . . . . . . . . . . . . . . . .
. . 2 j . . . . . . . . . . . . . . . . . . . .
. . a . . . . . . . . . . . . . . . . . . . . .
1 1 . . . . . . . . . . . . . . . . . . . . . .
1 1 . . . . . . . . . . . . . . . . . . . . . .
b . . . . . . . . . . . . . . . . . . . . . . .

```

Hence `e` struck `4`, `f` struck `3`, and `h` struck `2` (while `g`, `i`, and `j` would have struck cans if those cans had not already fallen to the floor):

```
 a  b  c  d  e  f  g  h  i  j
-1 -1 -1 -1  4  3 -1  2 -1 -1

```

# Answer
> 2 votes
# Jelly, (19?) 39 bytes

The entire second line is dealing with the strict I/O spec currently in place, while the 19 byte first line is a dyadic Link performing the core of the challenge. Also if `0` were allowed where `-1` is currently required save the `o-` for -2 bytes.

```
r/p/ċɗ€ⱮT€Ḣ€ŒQa"$o-
ỴḲ€VḢḢ‘œṖƲŒH€€1¦ç/K

```

**Try it online!**

---
Tags: code-golf, math, array, programming-puzzle
---


title: ASCII Pumpkin Carving

text:
# Question
Title: ASCII Pumpkin Carving
Today is Halloween and it's time to carve some pumpkins!

```
   &
((^.^))

```

Given an input integer, string, list of integers, etc., output the corresponding pumpkin. The input will always be of the form `Stem, Eyes, Mouth, Width`. For example, `2331` would be a valid input.

The pumpkin takes the form:

```
   S
((EME))

```

where `S` is the stem, `E` are the eyes, `M` is the mouth, and the parens form the body.

### Definitions

Stem:
`0` for a curl `&`
`1` for a straight `|`
`2` for a slant left `\`
`3` for a slant right `/`

Eyes:
`0` for angled `^`
`1` for small dots `.`
`2` for medium dots `o`
`3` for large dots `O`

Mouth:
`0` for angled `v`
`1` for small dot `.`
`2` for medium dot `o`
`3` for large dot `O`

Width:
`0` for a skinny pumpkin (only one pair of parens)
`1` for a fat pumpkin (two pairs of parens)

### Examples

```
0011
   &
((^.^))

3100
   /
 (.v.)

2331
   \
((OOO))

1200
   |
 (ovo)

```

## Rules

* Input/output can be given by any convenient method.
* You can print it to STDOUT or return it as a function result.
* Either a full program or a function are acceptable.
* Any amount of extraneous whitespace is permitted, provided the characters line up appropriately.
* You must use the numbering and ordering of the pumpkin carvings as they are described above.
* Standard loopholes are forbidden.
* This is so all usual golfing rules apply, and the shortest code (in bytes) wins.

# Answer
# Add++, 56 bytes

```
L,"&|\/^.oOv.oO ((("4$Tz£:BF"("+@32C3*$+Bh$2D-1A:1+")"*J

```

Try it online!

Add++ is not the best at string manipulation challenges

## How it works

We create an lambda function that takes a single argument - a list of integers - and outputs the final pumpkin.

```
L,                    - Define our function. Takes in a four element list e.g. [0 0 1 1]
                                                       STACK = [[0 0 1 1]]
  "&|\/^.oOv.oO ((("  - Push this string               STACK = [[0 0 1 1] '&|\/^.oOv.oO (((']
  4$T                 - Split it into 4 pieces         STACK = [[0 0 1 1] ['&|\/' '^.oO' 'v.oO' ' (((']
  z                   - Zip the lists together         STACK = [[['&|\\/' 0] ['^.oO' 0] ['v.oO' 1] [' (((' 1]]]
  £:                  - Index into each string         STACK = [['&' '^' '.' '(']]
  BF                  - Flatten the stack              STACK = ['&' '^' '.' '(']
  "("+                - Append a "(" to last element   STACK = ['&' '^' '.' '((']
  @                   - Reverse stack                  STACK = ['((' '.' '^' '&']
  32C3*$+             - Prepend 3 spaces to stalk      STACK = ['((' '.' '^' '   &']
  Bh                  - Output stack with newline      STACK = ['((' '.' '^']
  $2D                 - Push from under                STACK = ['((' '^' '.' '^']
  -1A:1+              - Add one the the last argument  STACK = ['((' '^' '.' '^' 2]
  ")"*                - Repeat ")" that many times     STACK = ['((' '^' '.' '^' '))']
  J                   - Join together                  STACK = ['((^.^))']
                      - Implicitly output

```
> 5 votes

# Answer
# JavaScript (ES6), 78 bytes

```
(s,e,m,w)=>`   ${'&|\\/'[s]}
${' ('[w]}(${(e='^.oO'[e])+'v.oO'[m]+e})`+' )'[w]

```

Try it online!
> 4 votes

# Answer
# Python 3, ~~96~~ ~~87~~ ~~86~~ 84 bytes

```
lambda s,e,m,w,a="^.oO":" "*(2+w)+"&|\/"[s]+"\n"+"("*-~w+a[e]+"v.oO"[m]+a[e]+")"*-~w

```

Try it online!

Thanks to:
\- @79037662 for saving me 2 bytes
> 2 votes

# Answer
# Wren, ~~98~~ 90 bytes

A naive approach. I could have used a lookup table, it golfs out 8 bytes.

```
Fn.new{|a,b,c,d|" "*3+"&|\\/"[a]+"\n"+" ("[d]+"("+"^.oO"[b]+"v.oO"[c]+"^.oO"[b]+")"*(d+1)}

```

Try it online!

# Wren, ~~148~~ 144 bytes

An even worse solution, yet I'd like to share it. Does a bunch of replaces on the specified string

```
Fn.new{|a,b,c,d|"   S\nW(EME)w".replace("S","&|\\/"[a]).replace("W"," ("[d]).replace("w"," )"[d]).replace("E","^.oO"[b]).replace("M","v.oO"[c])}

```

Try it online!
> 1 votes

# Answer
# Charcoal, 28 bytes

```
↙§&|\/Ｎ§^.oOＮ←§v.oOＮ←←×(⊕Ｎ‖Ｂ

```

Try it online! Link is to verbose version of code. Taking the inputs in a better order would save 2 bytes. Explanation:

```
↙§&|\/Ｎ

```

Input the stem and output the appropriate character, then move to the left eye.

```
§^.oOＮ

```

Input the eyes and output the appropriate character.

```
←§v.oOＮ←

```

Input the nose and output the appropriate character, then move to the left of the left eye.

```
←×(⊕Ｎ

```

Input the width and output the appropriate number of `(`s.

```
‖Ｂ

```

Reflect to complete the pumpkin.
> 1 votes

# Answer
# PHP (7.4), 91 bytes

Generates the output string using a template string and `strtr` array replacement mode.

```
fn($s,$e,$m,$w)=>strtr('   0
3(121)4',['&|\/'[$s],'^.oO'[$e],'v.oO'[$m],' ('[$w],' )'[$w]])

```

Try it online!

---

# PHP (7.4), 93 bytes

Generates the output string as it goes on.

```
fn($s,$e,$m,$w)=>'   '.'&|\/'[$s].'
'.' ('[$w].'('.($y='^.oO'[$e]).'v.oO'[$m]."$y)".' )'[$w];

```

Try it online!
> 0 votes

# Answer
# Red, 135 bytes

```
func[s e m w][a:["&|\/""^^.oO""v.oO"" ("" )"]rejoin["   "a/1/(s + 1) lf a/4/(t: w + 1) "("a/2/(u: e + 1) a/3/(m + 1) a/2/:u ")"a/5/:t]]

```

Try it online!
> 0 votes

# Answer
# Icon, 121 bytes

```
procedure f(s,e,m,w)
return map("   s\nw(eme)u","semwu","&|\\/"[s+1]||"^.oO"[e+1]||"v.oO"[m+1]||" ("[w+1]||" )"[w+1])
end

```

Try it online!
> 0 votes

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


title: Slash the matrix

text:
# Question
Title: Slash the matrix
You are given a matrix of forward and back slashes, for instance:

```
//\\
\//\
//\/

```

A slash cuts along the diagonal of its cell corner-to-corner, splitting it in two pieces. Pieces from adjacent (horizontally or vertically) cells are glued together. Your task is to count the number of resulting pieces. For the same example, the pieces are easier to see in this illustration - 8 of them:

Write a function or a complete program. Input is a non-empty matrix in any convenient form. You may choose any pair of values (characters or numbers) to represent `/` and `\`; in the tests below we use 0=`/` and 1=`\`. Loopholes forbidden. Shortest wins.

```
in:
[[0,0,1,1],
 [1,0,0,1],
 [0,0,1,0]]
out:
8

in:
[[1]]
out:
2

in:
[[1,0],
 [1,1],
 [0,1],
 [0,0]]
out:
6

in:
[[1,0,1,1,0,1,0,0,0,1,1,1],
 [1,0,1,0,1,1,1,1,1,1,1,0],
 [1,1,1,0,1,1,0,1,1,1,1,0],
 [0,1,0,1,0,1,0,0,1,0,1,1],
 [1,1,1,1,0,0,1,1,1,0,0,1]]
out:
19

in:
[[1,0,1,1,0,1,0,0,0,1,1,1,1,0,1,0,1],
 [1,1,1,1,1,1,0,1,1,1,0,1,1,0,1,1,1],
 [1,0,0,1,0,1,0,1,0,0,1,0,1,1,1,1,1],
 [1,0,0,1,1,1,0,0,1,0,0,1,0,1,1,1,1],
 [0,1,0,0,0,0,1,0,1,0,0,1,0,1,1,1,1],
 [0,1,0,0,1,0,0,0,1,0,1,0,0,1,1,1,0],
 [0,1,1,1,1,1,0,0,1,0,1,0,0,1,1,1,0]]
out:
27

in:
[[0,1,1,1,1,1,1,1,0,0,1,0,1,0,0,0,0],
 [1,1,1,0,0,0,1,1,1,1,1,0,1,1,0,1,0],
 [1,0,0,1,1,1,0,0,0,1,0,1,0,0,1,1,1],
 [0,0,0,1,1,0,1,0,0,0,1,1,0,1,1,1,0],
 [1,1,0,1,0,0,1,0,0,1,0,1,0,0,0,1,0],
 [0,1,0,1,0,0,0,1,0,1,0,1,0,1,1,0,0],
 [0,1,1,1,0,0,1,0,1,0,0,0,0,1,1,1,1]]
out:
32

```

# Answer
# MATL, 21 bytes

```
3XytPJ*-X*Xj~4&1ZIunq

```

The input is a matrix with `1` for `\` and `j` (imaginary unit) for `/`.

Try it online! Or verify all test cases.

With some extra code, you can see the different pieces in random colours. Or increase the resolution for a better looking result.

## Explanation

Consider input `[1,j; 1,1; j,1; j,j]` as an example. This corresponds to

```
\/
\\
/\
//

```

`3Xy` creates a 3×3 identity matrix:

```
1 0 0
0 1 0
0 0 1

```

`tP` pushes a copy of this matrix and flips it vertically. `J*` multiplies each entry by the imaginary unit, to give

```
0 0 j
0 j 0
j 0 0

```

`-` subtracts the two matrices:

```
 1     0    -j
 0   1-j     0
 -j    0     1

```

`X*` takes the input matrix implicitly and computes the Kronecker product. This replaces each entry in the input matrix by its product with the above 3×3 matrix:

```
 1    0   -j    j    0    1
 0  1-j    0    0  1+j    0
-j    0    1    1    0    j
 1    0   -j    1    0   -j
 0  1-j    0    0  1-j    0
-j    0    1   -j    0    1
 j    0    1    1    0   -j
 0  1+j    0    0  1-j    0
 1    0    j   -j    0    1
 j    0    1    j    0    1
 0  1+j    0    0  1+j    0
 1    0    j    1    0    j

```

`Xj` takes the real part:

```
1 0 0 0 0 1
0 1 0 0 1 0
0 0 1 1 0 0
1 0 0 1 0 0
0 1 0 0 1 0
0 0 1 0 0 1
0 0 1 1 0 0
0 1 0 0 1 0
1 0 0 0 0 1
0 0 1 0 0 1
0 1 0 0 1 0
1 0 0 1 0 0

```

Note how the above matrix is a "pixelated" version of

```
\/
\\
/\
//

```

`~` applies logical negation, that is, swaps `0` and `1`:

```
0 1 1 1 1 0
1 0 1 1 0 1
1 1 0 0 1 1
0 1 1 0 1 1
1 0 1 1 0 1
1 1 0 1 1 0
1 1 0 0 1 1
1 0 1 1 0 1
0 1 1 1 1 0
1 1 0 1 1 0
1 0 1 1 0 1
0 1 1 0 1 1

```

`4&1ZI` specifies `4`-connectivity, and finds connected components considering `1` as foreground and `0` as background. The result is a matrix of labelled connected components, where each original `1` is replaced by an integer label:

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

```

`unq` computes the number of unique elements and subtracts `1`. This gives the number of components, which is implicitly displayed.
> 30 votes

# Answer
# MSX-BASIC, ~~226~~ 199 bytes

```
1SCREEN2:READC,L:W=256/C:H=192/L:FORJ=1TOL:FORI=1TOC:A=H:B=H:READD:IFDTHENA=0:B=-H
2LINE(I*W,J*H-A)-STEP(-W,B):NEXTI,J:FORY=0TO191:FORX=0TO255:IFPOINT(X,Y)=4THENR=R+1:PAINT(X,Y)
3NEXTX,Y:SCREEN0:?R

```

This script draw slashes on a whole screen and use PAINT operator to count closed areas.

To test:

* copy to clipboard the script with test cases data (see below)
* open online emulator https://webmsx.org/
* press `Alt-V` and `Ctrl+V` to past test script into MSX
* press `Enter` and `F5` to run test script
* wait a some time to see a result (press `Shift-Alt-T` to switch in `CPU Turbo 8X` mode to save your time)

```
1SCREEN2:READC,L:W=256/C:H=192/L:FORJ=1TOL:FORI=1TOC:A=H:B=H:READD:IFDTHENA=0:B=-H
2LINE(I*W,J*H-A)-STEP(-W,B):NEXTI,J:FORY=0TO191:FORX=0TO255:IFPOINT(X,Y)=4THENR=R+1:PAINT(X,Y)
3NEXTX,Y:SCREEN0:?R
10 ' this and below lines are not counted
20 ' the script runs first uncommented test case.
30 ' comment unnecessary test cases
100 '
110 'test case 1: expected output=8
120 'DATA 4,3
130 'DATA 0,0,1,1,1,0,0,1,0,0,1,0
200 '
210 'test case 2: expected output=2
220 'DATA 1,1
230 'DATA 1
300 '
310 'test case 3: expected output=6
320 'DATA 2,4
330 'DATA 1,0,1,1,0,1,0,0
400 '
410 'test case 4: expected output=19
420 'DATA 12,5
430 'DATA 1,0,1,1,0,1,0,0,0,1,1,1
440 'DATA 1,0,1,0,1,1,1,1,1,1,1,0
450 'DATA 1,1,1,0,1,1,0,1,1,1,1,0
460 'DATA 0,1,0,1,0,1,0,0,1,0,1,1
470 'DATA 1,1,1,1,0,0,1,1,1,0,0,1
500 '
510 'test case 5: expected output=27
520 DATA 17,7
530 DATA 1,0,1,1,0,1,0,0,0,1,1,1,1,0,1,0,1
540 DATA 1,1,1,1,1,1,0,1,1,1,0,1,1,0,1,1,1
550 DATA 1,0,0,1,0,1,0,1,0,0,1,0,1,1,1,1,1
560 DATA 1,0,0,1,1,1,0,0,1,0,0,1,0,1,1,1,1
570 DATA 0,1,0,0,0,0,1,0,1,0,0,1,0,1,1,1,1
580 DATA 0,1,0,0,1,0,0,0,1,0,1,0,0,1,1,1,0
590 DATA 0,1,1,1,1,1,0,0,1,0,1,0,0,1,1,1,0
600 '
610 'test case 5: expected output=32
620 DATA 17, 7
630 DATA 0,1,1,1,1,1,1,1,0,0,1,0,1,0,0,0,0
640 DATA 1,1,1,0,0,0,1,1,1,1,1,0,1,1,0,1,0
650 DATA 1,0,0,1,1,1,0,0,0,1,0,1,0,0,1,1,1
660 DATA 0,0,0,1,1,0,1,0,0,0,1,1,0,1,1,1,0
670 DATA 1,1,0,1,0,0,1,0,0,1,0,1,0,0,0,1,0
680 DATA 0,1,0,1,0,0,0,1,0,1,0,1,0,1,1,0,0
690 DATA 0,1,1,1,0,0,1,0,1,0,0,0,0,1,1,1,1

```
> 4 votes

# Answer
# JavaScript (ES6),  ~~175~~  174 bytes

This is probably overcomplicated.

```
a=>a.map((r,y)=>r.map((v,x)=>[2,4].map(s=>v&s||(n++,g=(x,y,s,i,v=(r=a[y])&&r[x])=>!(v&(s^=i%2==v%2&&6))/v&&g(x+1-(r[x]|=s,s&2),y++,s^6)|g(x,y-=v%2*2^s&2,s,v))(x,y,s))),n=0)|n

```

Try it online!
> 3 votes

# Answer
# Charcoal, 70 bytes

```
≔×³Ｌθη≔×³Ｌ§θ⁰ζＢζηψＦＬθ«Ｊ¹⊕×³ιＦ§θι«¿κＰ\²Ｐ/²Ｍ³→»»Ｆη«Ｊ⁰ιＦζ«⊞υ¬℅ＫＫ¤#→»»⎚ＩΣυ

```

Try it online! Link is to verbose version of code. Uses the same format as the examples (except Charcoal requires the list of inputs as an outer array). Explanation:

```
≔×³Ｌθη≔×³Ｌ§θ⁰ζ

```

Like @LuisMendo, we're going to be drawing the matrix at 3x scale, so calculate that in advance.

```
Ｂζηψ

```

Draw an empty rectangle of that size so that we can fill the edge pieces.

```
ＦＬθ«Ｊ¹⊕×³ιＦ§θι«

```

Loop over the rows and columns.

```
¿κＰ\²Ｐ/²Ｍ³→»»

```

Draw each slash at triple size and move to the next one.

```
Ｆη«Ｊ⁰ιＦζ«

```

Loop over all of the squares.

```
⊞υ¬℅ＫＫ

```

Record whether this square was empty.

```
¤#→»»

```

But try filling it anyway before moving on to the next square. (`Fill` does nothing if the current square is not empty.)

```
⎚ＩΣυ

```

Clear the canvas and output the total number of empty squares found, which equals the number of pieces (because each piece would have been immediately filled in as soon as we counted it).
> 2 votes

# Answer
# C# (Visual C# Interactive Compiler), 292 bytes

```
n=>{var x=n.SelectMany(l=>"\0".Select(g=>l.SelectMany(r=>r.Skip(g).Concat(r.Take(g))).ToList())).ToList();int i=0,j=0,t=0;for(;i<x.Count;i++)for(j=0;j<x[0].Count;k(i,j++))t+=x[i][j]%2;void k(int a,int b){try{if(x[a][b]<50){x[a][b]='2';k(a+1,b);k(a-1,b);k(a,b-1);k(a,b+1);}}catch{}}return t;}

```

The `\0` should be a literal null byte.

`112` for `/`, `211` for `\`

Try it online!
> 2 votes

# Answer
# Jelly, ~~50~~ 46 bytes

```
®_ż+¥"SƝż€"Jż‘$$ḞṖ
ZJḤ©Żż‘$;€þJ;ÇẎfƇ@Ẏ¥€`Q$ÐLL

```

Try it online!

A full program taking a matrix as its input with `-0.5` as `/` and `0.5` as `\`. Returns an integer with the number of pieces.

Full explanation to follow, but works by generating a list of all the pairs of connected cells, and then merging overlapping sets until there’s no change. The final number of sets is the desired answer.
> 2 votes

---
Tags: code-golf, matrix, counting, binary-matrix, connected-figure
---


# Question
Title: Translate a simple sentence from Toki Pona
Toki Pona is a linguist's code golf: A minimalist language with a vocabulary of around 120 words. Because of this, it has very few grammatical irregularities found in other languages, making it ideal for a code golf challenge.

Your task is to take the most simple form of a Toki Pona sentence and translate it into English, using the (even more) limited dictionary provided in this question.

## The dictionary

While 120 words isn't a lot for a language, it's a lot of bytes. So, for that reason, I'm limiting the input to only contain these 20 words (English translation in brackets, Toki Pona in **bold**):

* Pronouns: **mi** (I/me), **sina** (you) and **ona** (he/she/it/him/her)
* Grammatical constructs: **li** and **e**
* Verbs: **jo** (to have), **moku** (to eat), **pona** (to fix), **oko** (to see) and **wile** (to want)
* Adjectives: **pona** (good/simple), **ike** (bad), **wan** (one/unique) and **mute** (many)
* Nouns: **kili** (fruit), **oko** (eye), **jan** (person/man/woman), **moku** (food), **ilo** (tool) and **ijo** (thing)

In addition, sentences involving the verb *to be* are included (expanded on later).

As you can see, simple sentences such as **I want food** can be made from this list: **mi wile e moku**. We'll address the exact grammatical construction in the next section. However, note that a single word may be used for multiple different English words (e.g. **moku**), which is how such a limited vocabulary is possible.

## Grammar

All of the sentences you'll be required to handle will have one of the following forms:

* **pronoun/noun "li" verb**
    + e.g. **ona li oko** (he sees)
* **pronoun/noun "li" pronoun/noun**
    + e.g. **ona li jan** (she is a person)
* **pronoun/noun "li" noun adjective**
    + e.g. **ona li ijo ike** (it is a bad thing)
* **pronoun/noun "li" verb "e" pronoun/noun**
    + e.g. **jan li jo e kili** (the person has fruit)
* **pronoun/noun "li" verb "e" noun adjective**
    + e.g. **jan li jo e kili pona** (the person has good fruit)

We'll call the first **pronoun/noun** the *subject* of the sentence and the second the *object*. Notice that the adjective comes after the noun, not before, and that pronouns cannot be paired with adjectives.

For example, **ona li moku e moku** (He eats food) is of the fourth form. However, the one exception is that if the subject is **mi** (I/me) or **sina** (you), then **li** is omitted. So **mi moku e moku** would translate as I eat food.

You'll notice that forms 2 and 3 don't have a verb, but our translated examples do. This is because Toki Pona has no word for *to be*. While we would say "I am good", Toki Pona speakers would say **mi pona** instead (omitting the verb). If the subject is not **mi** or **sina**, then **li** is used as it would be usually: **kili li moku**.

The two constructs **li** and **e** are used in the following ways:

* If the pronoun preceding is not **mi** or **sina**, the verb in the sentence is preceded by **li**. For example, **moku li moku** or **ona li oko**
* The object in the sentence is always preceded by **e**. For example, **moku li moku e moku** or **mi pona e ilo mute**.

Notice that Toki Pona doesn't conjugate verbs, nor does it change the word when plural. Due to this, you should assume that all input is in the singular (**ijo** is translated as **thing**, not **things**)

## English translation

In comparison, all outputted sentences should be in the forms

* **pronoun/noun verb**
* **pronoun/noun verb pronoun/noun**
* **pronoun/noun verb adjective pronoun/noun**

As each word has multiple translations (**ona** is he, she or it), we'll use these translations:

```
mi   (subject)   -> I
mi   (object)    -> me
sina             -> you
ona  (subject)   -> he
ona  (object)    -> him
jo               -> to have
moku (verb)      -> to eat
moku (noun)      -> food
pona (verb)      -> to fix
pona (adjective) -> good
oko  (verb)      -> to see
oko  (noun)      -> eye
wile             -> to want
ike              -> bad
wan              -> one
mute             -> many
kili             -> fruit
jan              -> person
ilo              -> tool
ijo              -> thing

```

However, because English has plenty of grammatical irregularities, and we have such a small vocabulary list, the English output should be as accurate as possible. Therefore:

* Verbs in English are to be conjugated. This means that for all verbs except *to be*:
    + The **I** and **you** forms are the same as the infinitive (to fix -\> I fix, you fix etc.)
    + The *he* form (which includes nouns) modifies the infinitive to end with an `s`. Specfically, the 5 verbs become **has**, **eats**, **fixes**, **sees** and **wants** respectively.
* For *to be*, **I** becomes **am**, **you** becomes **are** and **he** (including nouns) become **is**
* Nouns are prefixed with a `the`  (notice the space), unless the adjective after it is **wan** (one) or **mute** (many).
* Nouns before **mute** (many) should have a trailing `s` (yes even **fruit** and **food**). So **ilo mute** becomes **many tools**

## Your task

You are to take in a single sentence of Toki Pona consisting of only words from those 20, and always in one of the forms listed above (including the *to be* exceptions), and output the English translation. As is standard in Toki Pona, input will always be lowercase.

You may take input where the separator is any consistent non-alphabetic character or sequence of characters, including spaces (i.e. `mi@@@e@@@jan` is perfectly acceptable), or you may take input as a list of words, if you wish. The input does not have to make sense (e.g. **ijo li jo e jan mute**), but will always follow the grammatical rules.

Output rules are equally lax - you may output as a list of words, or as a single string with any consistent, non-alphabetical separator. Case is irrelevant.

This is so the shortest code in bytes wins!

## Test cases

```
mi wile e moku - I want the food
mi moku e moku - I eat the food
mi pona - I fix<sup>+</sup>
mi jan - I am the person
ona li oko - He sees/He is the eye<sup>*</sup>
ona li jan - He is the person
ona li ijo ike - He is the bad thing
jan li jo e kili - The person has the fruit
jan li oko e kili pona - The person sees the good fruit
kili li moku - The fruit is the food/The fruit eats<sup>*</sup>
moku li moku - The food is the food/The food eats<sup>*</sup>
moku li moku e moku - The food eats the food
ijo li jo e jan mute - The thing has many persons
ilo li pona e ijo - The tool fixes the thing
sina moku e kili mute - You eat many fruits
sina moku e kili ike - You eat the bad fruit
oko li oko e mi - The eye sees me
mi wile e sina - I want you
jan li moku e ona - The person eats him
mi jo e ijo wan - I have one thing
mi jo e ijo mute - I have many things
sina kili - you are the fruit

<sup>*</sup>: Either translation is acceptable for output, as both are valid translations
<sup>+</sup>: **I am good** would be the natural translation, but using **pona** as an adjective doesn't fix as one of our five forms, so is not a valid translation in this case

```

# Answer
> 7 votes
# JavaScript (ES6),  ~~498 ... 447~~  445 bytes

Outputs in lowercase, except for `'I'`.

```
s=>(s.replace(/\w+/g,w=>(x='2want||2eat/5food||5you|2see/5eye|5thing|1I/4me|5person|8many|8bad|5fruit|1he/4him|5tool||2fix/8good||2have||8one'.split`|`[n=parseInt(w,35)%781%21])&&(x=(g=_=>x.split`/`.find(x=>x[0]>>t&1,t++)||g())(),o[t]=x.slice(1),O[t]=n),o=[t=-1],O=[]))&&([s,v,o,a]=o,[S,V,O,A]=O,g=n=>4241>>n&1?'':'the ')(S)+s+` ${y=144>>S&1,1/V?V^17|y?v:'ha':S^4?S^7?'i':'am':'are'}${y?'':V^15?'s':'es'} `+g(A%10^9&&O)+[a&&a+' ']+[o]+['s'[A^9]]

```

Try it online!

### How?

We first split the input string \\$s\\$ into words and interpret each of them as an integer in base \\$35\\$, modulo \\$781\\$ and modulo \\$21\\$, which gives a unique ID \\$n\\$ in \\$\[0..19\]\\$. We associate a data string to each ID as follows:

```
 word   | base 35 to decimal | mod 781 | mod 21 | data
--------+--------------------+---------+--------+--------------
 'mi'   |                788 |       7 |      7 | '1I/4me'
 'sina' |            1223365 |     319 |      4 | '5you'
 'ona'  |              30215 |     537 |     12 | '1he/4him'
 'jo'   |                689 |     689 |     17 | '2have'
 'moku' |             973380 |     254 |      2 | '2eat/5food'
 'pona' |            1102090 |      99 |     15 | '2fix/8good'
 'oko'  |              30124 |     446 |      5 | '2see/5eye'
 'wile' |            1394799 |     714 |      0 | '2want'
 'ike'  |              22764 |     115 |     10 | '8bad'
 'wan'  |              39573 |     523 |     19 | '8one'
 'mute' |             981029 |      93 |      9 | '8many'
 'kili' |             880303 |     116 |     11 | '5fruit'
 'jan'  |              23648 |     218 |      8 | '5person'
 'ilo'  |              22809 |     160 |     13 | '5tool'
 'ijo'  |              22739 |      90 |      6 | '5thing'
 'li'   |                753 |     753 |     18 | ''
 'e'    |                 14 |      14 |     14 | ''

```

We keep track of the expected type of the next word in the variable \\$t\\$:

* \\$t=0\\$: subject
* \\$t=1\\$: verb
* \\$t=2\\$: object
* \\$t=3\\$: adjective

The leading digit in front of each translated word is a bitmask describing the types that the word can be associated with. For instance, `"5fruit"` means that `"fruit"` may be either the *subject* (\\$2^0=1\\$) or the *object* (\\$2^2=4\\$) of the sentence.

We use this information to assign the relevant type to each input word. At the end of this process, the array `[s,v,o,a]` holds the categorized words (subject, verb, object and adjective, respectively) while the array `[S,V,O,A]` holds the corresponding indices, as described in the penultimate column of the above table.

Using these variables, we can finally apply English rules to translate the sentence.

# Answer
> 2 votes
# Python 3, 1902 bytes

```

import re
p='mi|sina|ona'
v='jo|moku|pona|oko|wile'
a='pona|ike|wan|mute'
n='kili|oko|jan|moku|ilo|ijo'
pn=p+'|'+n
d={'p':p,'v':v,'a':a,'n':n,'pn':pn,'li':'li','e':'e',
   'f':'(?:(?:'+pn+') li|(?:mi|sina))'}
g=['f '+i for i in 'v,pn,n a,v e pn,v e n a'.split(',')]
ma=[re.compile('^%s$'%re.subn(r'\w+',lambda m:'({%s})'%m.group(0),i)[0].format(**d))
    for i in g]
tr0=lambda ph:[m.match(ph) and m.match(ph).groups() for m in ma]
d_={'s':{'mi':'I','sina':'you','ona':'he'},'o':{'mi':'me','sina':'you','ona':'him'},'v':{'jo':'have','moku':'eat','pona':'fix','oko':'see','wile':'want'},'n':{'moku':'food','oko':'eye','kili':'fruit','jan':'person','ilo':'tool','ijo':'thing'},'a':{'pona':'good','ike':'bad','wan':'one','mute':'many'}}
md=lambda x:dict((k,v) for i in x for k,v in d_[i].items())
d_['pn']=md('on')
d_['f']=md('sn')
d_['e']={'e':'_'}
mc=lambda x:lambda t:(lambda d:d[t] if t in d else d['_'])(x)
be=mc({'I':'am','you':'are','_':'is'})
vs=lambda p:list(d_[p].values())
os=vs('o')+vs('s')
tr=lambda x:[(n_,[d_[p][w if n else w.split(' ')[0]] \
              for n,(w,p) in enumerate(zip(i,pt.split(' ')))]) \
             for n_,(i,pt) in enumerate(zip(x,g)) if i]
noun=lambda t:lambda n:n if n in os else t+n
the=noun('the ')
the2=lambda n:'' if n in os else 'the '
v_=mc({'I':'','you':'','_':'s'})
m_=lambda o,a:('s' if (a == 'many') and (o not in os) else '')
tr_={0:lambda n,v:[the(n),
                   v+v_(n)],
     3:lambda s,v,e,o:[the(s),v+v_(s),the(o)],
     1:lambda s,o:[the(s),be(s),the(o)],
     2:lambda s,o,a:[the(s),be(s),the2(o)+a,o+m_(o,a)],
     4:lambda s,v,e,o,a:[the(s),v+v_(s),the2(o)+a,o+m_(o,a)],
     }
from functools import reduce
f_={'haves':'has','fixs':'fixes','the one':'one','the many':'many'}
fx=lambda s:reduce(lambda x,y:x.replace(y[0],y[1]),f_.items(),s)
c=lambda s:s[0].upper()+s[1:]
r=lambda s:[(n,c(fx(' '.join(tr_[n](*a))))) for n,a in tr(tr0(s))]

```

Try it online!

The function `r` does the thing.
The testing:

```

s=r'''mi wile e moku - I want the food
mi moku e moku - I eat the food
mi pona - I am good/I fix*
mi jan - I am the person
ona li oko - He sees/He is the eye*
ona li jan - He is the person
ona li ijo ike - He is the bad thing
jan li jo e kili - The person has the fruit
jan li oko e kili pona - The person sees the good fruit
kili li moku - The fruit is the food/The fruit eats*
moku li moku - The food is the food/The food eats*
moku li moku e moku - The food eats the food
ijo li jo e jan mute - The thing has many persons
ilo li pona e ijo - The tool fixes the thing
sina moku e kili mute - you eat many fruits
sina moku e kili ike - you eat the bad fruit
oko li oko e mi - The eye sees me
mi wile e sina - I want you
jan li moku e ona - The person eats him
mi jo e ijo wan - I have one thing
mi jo e ijo mute - I have many things'''.split('\n')
print('\n'.join(str((r(j.split(' - ')[0]),
                     j.split(' - ')[1].rstrip('*').split('/'))) \
                for j in s))

```

The test output:

```

([(3, 'I want the food')], ['I want the food'])
([(3, 'I eat the food')], ['I eat the food'])
([(0, 'I fix')], ['I am good', 'I fix'])
([(1, 'I am the person')], ['I am the person'])
([(0, 'He sees'), (1, 'He is the eye')], ['He sees', 'He is the eye'])
([(1, 'He is the person')], ['He is the person'])
([(2, 'He is the bad thing')], ['He is the bad thing'])
([(3, 'The person has the fruit')], ['The person has the fruit'])
([(4, 'The person sees the good fruit')], ['The person sees the good fruit'])
([(0, 'The fruit eats'), (1, 'The fruit is the food')], ['The fruit is the food', 'The fruit eats'])
([(0, 'The food eats'), (1, 'The food is the food')], ['The food is the food', 'The food eats'])
([(3, 'The food eats the food')], ['The food eats the food'])
([(4, 'The thing has many persons')], ['The thing has many persons'])
([(3, 'The tool fixes the thing')], ['The tool fixes the thing'])
([(4, 'You eat many fruits')], ['you eat many fruits'])
([(4, 'You eat the bad fruit')], ['you eat the bad fruit'])
([(3, 'The eye sees me')], ['The eye sees me'])
([(3, 'I want you')], ['I want you'])
([(3, 'The person eats him')], ['The person eats him'])
([(4, 'I have one thing')], ['I have one thing'])
([(4, 'I have many things')], ['I have many things'])

```

The raw thing:

```

import re
p='mi|sina|ona'
v='jo|moku|pona|oko|wile'
a='pona|ike|wan|mute'
n='kili|oko|jan|moku|ilo|ijo'
pn=p+'|'+n
d={'p':p,'v':v,'a':a,'n':n,'pn':pn,'li':'li','e':'e',
   'f':'(?:(?:'+pn+') li|(?:mi|sina))'}
g=['f '+i for i in 'v,pn,n a,v e pn,v e n a'.split(',')]
ma=[re.compile('^%s$'%re.subn(r'\w+',lambda m:'({%s})'%m.group(0),i)[0].format(**d))
    for i in g]
s=r'''mi wile e moku - I want the food
mi moku e moku - I eat the food
mi pona - I am good/I fix*
mi jan - I am the person
ona li oko - He sees/He is the eye*
ona li jan - He is the person
ona li ijo ike - He is the bad thing
jan li jo e kili - The person has the fruit
jan li oko e kili pona - The person sees the good fruit
kili li moku - The fruit is the food/The fruit eats*
moku li moku - The food is the food/The food eats*
moku li moku e moku - The food eats the food
ijo li jo e jan mute - The thing has many persons
ilo li pona e ijo - The tool fixes the thing
sina moku e kili mute - you eat many fruits
sina moku e kili ike - you eat the bad fruit
oko li oko e mi - The eye sees me
mi wile e sina - I want you
jan li moku e ona - The person eats him
mi jo e ijo wan - I have one thing
mi jo e ijo mute - I have many things'''.split('\n')
x=[(lambda ph:[m.match(ph) and m.match(ph).groups() for m in ma])\
   (i.split(' - ')[0]) for i in s]
y=r'''mi   (subject)   -> I
mi   (object)    -> me
sina (subject)            -> you
sina (object)            -> you
ona  (subject)   -> he
ona  (object)    -> him
jo   (verb)            -> to have
moku (verb)      -> to eat
moku (noun)      -> food
pona (verb)      -> to fix
pona (adjective) -> good
oko  (verb)      -> to see
oko  (noun)      -> eye
wile (verb)            -> to want
ike  (adjective)            -> bad
wan  (adjective)            -> one
mute (adjective)            -> many
kili (noun)            -> fruit
jan  (noun)            -> person
ilo  (noun)            -> tool
ijo  (noun)            -> thing'''
from collections import defaultdict
d_=defaultdict(dict)
for w,p,t in re.findall(r'(\w+)\s*\((\w+)\)\s*\-\>\s*(?:to )?(\w+)',y):
    d_[p[0]][w]=t
md=lambda x:dict((k,v) for i in x for k,v in d_[i].items())
d_['pn']=md('on')
d_['f']=md('sn')
d_['e']={'e':'_'}
#print(d_)
mc=lambda x:lambda t:(lambda d:d[t] if t in d else d['_'])(x)
be=mc({'I':'am','you':'are','_':'is'})
hv=mc({'I':'have','you':'have','_':'has'})
vs=lambda p:list(d_[p].values())
tr=lambda x:[(n_,[d_[p][w if n else w.split(' ')[0]] \
              for n,(w,p) in enumerate(zip(i,pt.split(' ')))]) \
             for n_,(i,pt) in enumerate(zip(x,g)) if i]
#print('\n'.join(str((tr(i),j.split(' - ')[1].rstrip('*').split('/'))) \
#                for i,j in zip(x,s)))
noun=lambda t:lambda n:n if n in vs('o')+vs('s') else t+n
the=noun('the ')
the2=lambda n:'' if n in vs('o')+vs('s') else 'the '
v_=mc({'I':'','you':'','_':'s'})
a_=lambda s:('the ' if s not in vs('p') else '')
m_=lambda o,a:('s' if (a == 'many') and (o not in vs('o')+vs('s')) else '')
tr_={0:lambda n,v:[the(n),
                   v+v_(n)],
     3:lambda s,v,e,o:[the(s),v+v_(s),the(o)],
     1:lambda s,o:[the(s),be(s),the(o)],
     2:lambda s,o,a:[the(s),be(s),the2(o)+a,o+m_(o,a)],
     4:lambda s,v,e,o,a:[the(s),v+v_(s),the2(o)+a,o+m_(o,a)],
     }
from functools import reduce
f_={'haves':'has','fixs':'fixes','the one':'one','the many':'many'}
fx=lambda s:reduce(lambda x,y:x.replace(y[0],y[1]),f_.items(),s)
c=lambda s:s[0].upper()+s[1:]
print('\n'.join(str(([(n,c(fx(' '.join(tr_[n](*a))))) for n,a in tr(i)],
                     j.split(' - ')[1].rstrip('*').split('/'))) \
                for i,j in zip(x,s)))
#print('\n'.join(map(str,x)))

```

You can run it to see it passes all the cases)

# Answer
> 1 votes
# Jelly, ~~257~~ 249 bytes

```
OP€%59µ“:¤¥“ ı“¦1"ø“/“2¿“#“,3‘œiⱮ¹Ƈ’S,@ɗ>5Ḣ$¡"J1,3yƊ$ḢW;1,6y$1¦€ƲḢ,2,3;Ʋ2,1œị=3Ʋ¡+2¦=2Ḣ$¡€58,3iⱮ×7ḢƲḣ;Ṛḣ¥ɗL=4Ɗ¡2+2¦e€3,4Ḣ$¡€1,3¦7œị“¢ṇḃ#ṅ³©½øỴ£⁺Ṭḥ*4=LƤ`:[?SœGʠṂ4£¤ɦ5Ẉḃ⁵ƓOqȤ2MœṁṾġqÐU¤¶ṀẆ¶`ƝUḋ#ḳ#Ạ4Ẏ[`-ckṫ©4%ṙẎọkɲẠ¶{t}6ọ6Ṇ»ỴḲ€“the ”;Ɱ;@Ɗ€3,4¦¤K;11e”sxƲ

```

Try it online!

A monadic link taking a list of words and returning a string. I’m sure this can be better golfed, but I was just pleased to have something that worked despite the various complexities of the English language!

## Explanation

### Stage 1

Convert to initial pairs of integers

Note the first of each pair is initially 1 for pronouns, 2 for verbs, 3 for nouns, 4 for adjectives, 5 for quantifiers, 6 for verb/adjective and 7 for verb/noun

```
O                   | Convert to Unicode codepoints
 P€                 | Product of each word
   %59              | Mod 59
      µ             | Start a new monadic chain
       “:...3‘œiⱮ   | Multidimensional index of this in [[58, 3, 4], [32, 25], [5, 49, 34, 29], 47, [50, 11], 35, [44, 51]]
                 ¹Ƈ | Filter ones that weren’t found (li and e)

```

### Stage 2

Determine meaning for words with two possible meanings; works because nouns can only appear in positions 1 and 3, verbs only in position 2 and adjectives in position 4

```
                 $ | Following as a monad:
          "     Ɗ  | - Map a link using the following as a monad as the right argument zipped with each element of the input to stage 2 as the left
           J       |   - Index along list
            1,3y   |   - Substitute 1s for 3s (words in the first position
        $¡         | - If:
     >5            |   - Greater than 5
       Ḣ           |   - Head (i.e. if first number is >5)
                   | - Then:
’                  |   - Increment both items in the pair by 1
 S                 |   - Sum
  ,@               |   - Pair the right argument with this

```

### Stage 3

Change pronouns appearing after position 1 to have 6 as their first integer (so that object versions can be used)

```
            Ʋ | Following as a monad:
Ḣ             | - Head
 W            | - Wrap in a list
  ;           | - Concatenate to:
   1,6y$1¦€   |   - The other list members at input to stage 3, with 1 replaced by 6

```

### Stage 4

Insert ‘to be’ if there is no verb

```
              Ɗ¡ | If:
       2,1œị     | - the word type of the second word
            =3   | - is equal to 3 (noun)
      Ʋ          | Then following as a monad:
Ḣ                | - Head
 ,2,3            | - Pair with [2,3] (verb to be)
     ;           | - Concatenate to rest of list

```

### Stage 5

If first word is ‘I’ or ‘you’, add 7 or 14 respectively to the verb number

```
      $¡€           | For each word, if:
   =2               | - Equals 2
     Ḣ              | - Head (i.e. if word is a noun)
+2¦               Ʋ | Add to the second item (word number) the following as a monad:
         58,3iⱮ     | - Index of mod 59 words (from stage 1) within 58 (I), 3 (you)
               ×7   | - Multiply by 7
                 Ḣ  | - Head (i.e. 7 if first word is ‘I’ and 14 if first word is ‘you’.

```

### Stage 6

Swap noun and adjective or quantifier around if present

```
         Ɗ¡  | If (as a monad):
      L      | - Length
       =4    | - Equals 4
     ɗ     2 | Then (as a dyad), using 2 as the right argument:
ḣ            | - First 2 words
 ;  ¥        | - Concatenated to following as a dyad:
  Ṛ          |   - Reverse
   ḣ         |   - First two words (i.e. last 2 words in reverse order)

```

### Stage 7

Use version of nouns and adjectives with preceding ‘the’ if they appear in the third or first position

```
           €1,3¦  | For each of first and third words
         $¡       | - If (as a monad):
   e€3,4          |   - Is one of 3 or 4
        Ḣ         |   - Head (i.e. if word type is noun or adjective)
                  | - Then:
+2¦             7 |   - Add 7 to the second item (i.e. word number)

```

### Stage 8

Index into word list

```
œị                          ¤ | Multidimensional index into following as a nilad
  “¢...Ṇ»                     | - “I you he/wants has is  fixes eats sees want have am  fix eat see want have are  fix eat see/fruit person tool thing  food eye/good bad/one many/me you him” where / indicates newline
         Ỵ                    | - Split at newlines
          Ḳ€                  | - Split each at spaces
                      Ɗ€3,4¦  | - For each of the third and fourth lists of words, do the following as a monad:
            “the ”;Ɱ          |   - Concatenate “the “ to each
                    ;@        |   - Concatenate to end of list

```

### Stage 9

Add “s” to end if many is used

```
K         | Join with spaces
 ;      Ʋ | Concatenate to the following as a monad (applied to the mod 59 words from stage 1)
  11e     | - Contains 11 (many)
     ”sx  | - that many “s”

```

---
Tags: code-golf, string, natural-language
---


title: Count to 100 in Danish

text:
# Question
Title: Count to 100 in Danish
Print all the numbers from 0-100 in the right order using the Danish way of counting

# How they count

* Like English, they have dedicated words for 0-20, 30, 40 and 100
* Instead of saying `twenty-one` and `twenty-two`, they say `one and twenty` and `two and twenty`
* Starting with fifty they say multiples of 10 as n\*20

```
50 = half third times twenty = half way to the 3rd multiple of 20
60 = three times twenty
70 = half fourth times twenty
80 = four times twenty
90 = half fifth times twenty

```

So for instance, 55 would be `five and half third times twenty`.

# Expected output

```
zero
one
two
three
four
five
six
seven
eight
nine
ten
eleven
twelve
thirteen
fourteen
fifteen
sixteen
seventeen
eighteen
nineteen
twenty
one and twenty
two and twenty
three and twenty
four and twenty
five and twenty
six and twenty
seven and twenty
eight and twenty
nine and twenty
thirty
one and thirty
two and thirty
three and thirty
four and thirty
five and thirty
six and thirty
seven and thirty
eight and thirty
nine and thirty
forty
one and forty
two and forty
three and forty
four and forty
five and forty
six and forty
seven and forty
eight and forty
nine and forty
half third times twenty
one and half third times twenty
two and half third times twenty
three and half third times twenty
four and half third times twenty
five and half third times twenty
six and half third times twenty
seven and half third times twenty
eight and half third times twenty
nine and half third times twenty
three times twenty
one and three times twenty
two and three times twenty
three and three times twenty
four and three times twenty
five and three times twenty
six and three times twenty
seven and three times twenty
eight and three times twenty
nine and three times twenty
half fourth times twenty
one and half fourth times twenty
two and half fourth times twenty
three and half fourth times twenty
four and half fourth times twenty
five and half fourth times twenty
six and half fourth times twenty
seven and half fourth times twenty
eight and half fourth times twenty
nine and half fourth times twenty
four times twenty
one and four times twenty
two and four times twenty
three and four times twenty
four and four times twenty
five and four times twenty
six and four times twenty
seven and four times twenty
eight and four times twenty
nine and four times twenty
half fifth times twenty
one and half fifth times twenty
two and half fifth times twenty
three and half fifth times twenty
four and half fifth times twenty
five and half fifth times twenty
six and half fifth times twenty
seven and half fifth times twenty
eight and half fifth times twenty
nine and half fifth times twenty
one hundred

```

# Rules

* You may use any separator to separate the numbers
* Due to a typo in the original specification, you may use `forth` instead of `fourth`.
* You may write a function or write to std-out
* Standard loopholes apply
* This is codegolf; shortest code in bytes win!

# Answer
# JavaScript (ES6), ~~347~~ ~~336~~ ~~326~~ ~~325~~ 308 bytes

```
for(a=btoa`...`.split(i=0);i<101;i++)alert(i<13?a[i]:i<20?(a[i]||a[i-10])+"teen":i>99?"one hundred":(i%10?a[i%10]+" and ":"")+(i<30?"twenty":i<40?"thirty":i<50?"forty":(i%20>9?"half "+["third","forth","fifth"][i/20-2|0]:a[i/20|0])+" times twenty"))

```

Before running, replace the `...` with the result of running this code:

```
atob("zero0one0two0three0four0five0six0seven0eight0nine0ten0eleven0twelve0thir00fif000eigh")

```

Or you could just use the uncompressed version:

```
for(a="zero0one0two0three0four0five0six0seven0eight0nine0ten0eleven0twelve0thir00fif000eigh".split(i=0);i<101;i++)alert(i<13?a[i]:i<20?(a[i]||a[i-10])+"teen":i>99?"one hundred":(i%10?a[i%10]+" and ":"")+(i<30?"twenty":i<40?"thirty":i<50?"forty":(i%20>9?"half "+["third","forth","fifth"][i/20-2|0]:a[i/20|0])+" times twenty"))

```

Still probably not optimal. 11 bytes saved in part by @Titus.
> 15 votes

# Answer
# Fourier, 7028 bytes

*The bounty will go to **Paul Schmitz's answer***

This was golfed programmatically using issacg's golfing program

```
[encoded data, 7028 characters]

```

**Try it online!**
> 14 votes

# Answer
# JavaScript (ES6), non-competing

I decided to do what the title actually asked, and counted to 100 på dansk. This is based on ETHproductions' answer. It is 292 bytes (286 if you use alert instead)

```
for(a="nul0en0to0tre0fire0fem0seks0syv0otte0ni0ti0elleve0tolv0tret0fjor0fem0seks0syt0at0nit".split(i=0);i<101;i++)console.log(i<13?a[i]:i<20?(a[i])+"ten":i>99?"hundrede":(i%10?a[i%10]+"og":"")+(["tyve","tredive","fyrre","halvtreds","tres","halvfjerds","firs","halvfems"][Math.floor(i/10)-2]))
```
> 10 votes

# Answer
# PHP, ~~397~~ ~~375~~ ~~372~~ ~~381~~ ~~386~~ 365 bytes

This was too funny to be ignored. It can possibly be golfed further.

```
zero_<?=join(_,$a=[one,two,three,four,five,six,seven,eight,nine,ten,eleven,twelve,thirteen,fourteen,fifteen,sixteen,seventeen,eighteen,nineteen])._;foreach([twenty,thirty,forty]as$t)for($i=-2;$i++<8;)echo($i<0?'':$c[]="$a[$i] and ").$t._;foreach([third,three,fourth,four,fifth]as$k=>$t)for($i=-2;$i++<8;)echo$c[$i],($k&1?'':'half '),"$t times twenty_";?>one hundred

```
* It uses underscore as the separator
* 10 to 19 are still hardcoded; any way to compute them doesn´t give as much as the join.
> 8 votes

# Answer
# ///, 434 bytes

```
/(/\/\///D/\/7(7/ and (2/twenty(4/ times (_/half ([/42
(&/three(;/thir()/four(!/fort($/_fifth[(#/seven(^/eight(@D;ty
(%D_!h[(*D_;d[(-/nine(`D!y
(F/five(T/teen
(O/one(X/six(GD&[(HD)[(ID2
(Y/two(AD$/zero
O
Y
&
)
F
X
#
^
-
ten
eleven
twelve
;T)TfifTXT#T^een
-T2
OIYI&I)IFIXI#I^I-I;ty
O@Y@&@)@F@X@#@^@-@!y
O`Y`&`)`F`X`#`^`-`_;d42
O*Y*&*)*F*X*#*^*-*&[OGYG&G)GFGXG#G^G-G_!h[O%Y%&%)%F%X%#%^%-%)[OHYH&H)HFHXH#H^H-H$OAYA&A)AFAXA#A^A-AO hundred

```

Try it online!
> 8 votes

# Answer
# Mathematica ~~251 238~~ 230 bytes

This now presents the output in the format of a list, to save 8 more bytes.

```
c@s_:=s<>" times twenty";f@n_:=Which[n<21∨{30,40,100}~MemberQ~n,IntegerName@n,n==50,c@"half third",n==60,c@"three",n==70,c@"half forth",n==80,c@"four",n==90,c@"half fifth",3>2,NumberExpand@n/.{t_,u_}:>f@u<>" plus "<>f@t];f/@0~Range~100

```
> 7 votes

# Answer
# Haskell, ~~308~~ ~~291~~ 285 bytes

```
w=words;q x=map(++x);m=w"thir four fif six seven eigh nine";t=w"zero one two three four five six seven eight nine ten eleven twelve"++q"teen"m++q"ty"(do b<-"twen":take 2m++q" times twen"["half third",t!!3,"half fourth",t!!4,"half fifth"];b:q b(q" and ".take 9$tail t))++["one hundred"]

```

**Readable version:**

```
w   = words
m   = w "thir four fif six seven eigh nine"
q x = map (++x)

t = w "zero one two three four five six seven eight nine ten eleven twelve"
 ++ q "teen" m
 ++ q "ty" (do b <- "twen" : take 2 m
                     ++ q " times twen"
                          ["half third",t!!3,"half fourth",t!!4,"half fifth"]
               b:q b(q" and ".take 9$tail t)
           )
 ++ ["one hundred"]

```

Also 285

```
w=words;m=w"thir four fif six seven eigh nine";x!l=map(++x)l
t  = w"zero one two three four five six seven eight nine ten eleven twelve"
  ++ "teen"!m
  ++ "ty"!(
  do x<-"twen":take 2m++" times twen"!
         ["half third",t!!3,"half fourth",t!!4,"half fifth"]
     x:x!(" and "!take 9(tail t)))
  ++ ["one hundred"]

```

It might not look much different, but it represents hours of factorization that eventually brought me full circle. I think I have done this before..
> 6 votes

# Answer
# C (gcc), ~~445~~ ~~426~~ ~~452~~ ~~449~~ ~~444~~ 439 bytes

```
*t[]={0,0,"twenty","thirty","fourty",[10]="one hundred","third","fourth","fifth"},*o[101]={"zero","one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"};i,p;main(j){for(;i<'e';i++)p=i%10,o[i]?puts(o[i]):printf("%s%s%s%s%s%s\n",p?o[p]:t,p?" and ":t,!t[j]&j%2?"half ":t,t[j]?t:j%2?t[j/2+9]:o[j/2],t[j]?t:" times ",t[j=i/10]?:t[2]);}

```

Try it online!

~~19~~ ~~22~~ 27 bytes shaved off thanks to @ceilingcat, but 26 bytes were added again, 3 to prevent a segfault (o\[\] really has to have 101 entries), and upon checking the rules again I noticed we had to print out all numbers from 0 to 100, not just provide a function that printed one number.

Ungolfed:

char *t[] = {0, 0, "twenty", "thirty", "fourty", 0, 0, 0, 0, 0, "one hundred", "third", "fourth", "fifth"};
char *o[101] = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten",
                "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"};
int i = 0;
int j = 0;
int p = 0;

main()
{
  for(; i < 101; i++) {
    p = i % 10;
    if(o[i])
        puts(o[i]);
    else
        printf("%s%s%s%s%s%s\n",
               p ? o[p] : "",
               p ? " and " : "",
               !t[j] & j % 2 ? "half " : "",
               t[j] ? "" : j % 2 ? t[j / 2 + 9] : o[j / 2],
               t[j] ? "" : " times ",
               t[j = i / 10] ? : t[2]
        );
  }
}
```
</code></pre>
> 6 votes

# Answer
# PHP, ~~333~~ ~~328~~ 321 bytes

@ETHproductions´s expression ported to PHP and golfed down. I am surprised that PHP can beat JavaScript *without any builtins*.

I guess the mightiest builtins are the implicit typecasts:

* I need no quotes for most of the strings, that alone is worth 12 bytes;
* and it allows me to use an array directly instead of splitting a string.
* the array indexing is implicitly typecasting any floats to integer, saving 6 bytes.

**BUT:** I need `$`s (21 of them) to tell PHP that it´s a variable.

So it´s still unclear where the 15 bytes actually come from. I didn´t golf away that much. Or did I? ETH caught up.

```
<?$a=[zero,one,two,three,four,five,six,seven,eight,nine,ten,eleven,twelve,thirteen,'',fifteen,'','',eighteen];for($n=-1;$n++<99;)echo$n>19?($n%10?$a[$n%10].' and ':'').($n>49?($n%20>9?"half ".[third,forth,fifth][$n/20-2.5]:$a[$n/20]).' times twenty':[twen,thir,'for'][$n/10-2].ty):($a[$n]?:$a[$n%10].teen),_;?>one hundred

```
> 5 votes

# Answer
# Fourier, 7020 bytes

```
122a101~za114a-3a10a111ava-9a10a116a+3a-8a10a116a104a114a101aa10a102a+9a+6a-3a10a102a+3a118a101a10a115a105a120a10a115a101a118a101a+9a10a101a+4a-2a^a116a10a110a-5a+5a-9a10a116a101a+9a10a101a+7a-7a118aza+9a10a116a+3a101a+7a118a101a10a116a104a^a+9a+2a101aa+9a10a102a+9a+6a-3a+2a101aa+9a10a102a+3a-3a116a101aa+9a10a115a105a120a-4a101aa+9a10a115a101a118aza+9a+6a101aa+9a10aza+4a-2a^a116a101aa+9a10a110a-5a+5a-9a116a101aa+9a10a116a+3a101a+9a+6a+5a10a111ava-9a32a97a110a100a32a116a+3a101a+9a+6a+5a10a116a+3a-8a32a97a110a100a32a116a+3a101a+9a+6a+5a10a116a104a114azaa32a97a110a100a32a116a+3a101a+9a+6a+5a10a102a+9a+6a-3a32a97a110a100a32a116a+3a101a+9a+6a+5a10a102a+3a118aza32a97a110a100a32a116a+3a101a+9a+6a+5a10a115a105a120a32a97a110a100a32a116a+3a101a+9a+6a+5a10a115a101a118a101a+9a32a97a110a100a32a116a+3a101a+9a+6a+5a10a101a+4a-2a^a116a32a97a110a100a32a116a+3a101a+9a+6a+5a10a110a-5a+5a-9a32a97a110a100a32a116a+3a101a+9a+6a+5a10a116a104a^a+9a+2a+5a10a111ava-9a32a97a110a100a32a116a104a^a+9a+2a+5a10a116a+3a-8a32a97a110a100a32a116a104a^a+9a+2a+5a10a116a104a114a101aa32a97a110a100a32a116a104a^a+9a+2a+5a10a102a+9a+6a-3a32a97a110a100a32a116a104a^a+9a+2a+5a10a102a+3a118a101a32a97a110a100a32a116a104a^a+9a+2a+5a10a115a105a120a32a97a110a100a32a116a104a^a+9a+2a+5a10a115a101a118a101a+9a32a97a110a100a32a116a104a^a+9a+2a+5a10a101a+4a-2a^a116a32a97a110a100a32a116a104a^a+9a+2a+5a10a110a-5a+5a-9a32a97a110a100a32a116a104a^a+9a+2a+5a10a102a+9a+3a+2a+5a10a111ava-9a32a97a110a100a32a102a+9a+3a+2a+5a10a116a+3a-8a32a97a110a100a32a102a+9a+3a+2a+5a10a116a104a114a101aa32a97a110a100a32a102a+9a+3a+2a+5a10a102a+9a+6a-3a32a97a110a100a32a102a+9a+3a+2a+5a10a102a+3a118a101a32a97a110a100a32a102a+9a+3a+2a+5a10a115a105a120a32a97a110a100a32a102a+9a+3a+2a+5a10a115a101a118a101a+9a32a97a110a100a32a102a+9a+3a+2a+5a10a101a+4a-2a^a116a32a97a110a100a32a102a+9a+3a+2a+5a10a110a-5a+5a-9a32a97a110a100a32a102a+9a+3a+2a+5a10a104a97a108a-6a32a116a104a^a+9a100a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a111ava-9a32a97a110a100a32a104a97a108a-6a32a116a104a^a+9a100a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a116a+3a-8a32a97a110a100a32a104a97a108a-6a32a116a104a^a+9a100a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a116a104a114a101aa32a97a110a100a32a104a97a108a-6a32a116a104a^a+9a100a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a102a+9a+6a-3a32a97a110a100a32a104a97a108a-6a32a116a104a^a+9a100a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a102a+3a118a101a32a97a110a100a32a104a97a108a-6a32a116a104a^a+9a100a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a115a105a120a32a97a110a100a32a104a97a108a-6a32a116a104a^a+9a100a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a115a101a118a101a+9a32a97a110a100a32a104a97a108a-6a32a116a104a^a+9a100a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a101a+4a-2a^a116a32a97a110a100a32a104a97a108a-6a32a116a104a^a+9a100a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a110a-5a+5a-9a32a97a110a100a32a104a97a108a-6a32a116a104a^a+9a100a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a116a104a114a101aa32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a111ava-9a32a97a110a100a32a116a104a114a101aa32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a116a+3a-8a32a97a110a100a32a116a104a114a101aa32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a116a104a114a101aa32a97a110a100a32a116a104a114a101aa32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a102a+9a+6a-3a32a97a110a100a32a116a104a114a101aa32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a102a+3a118a101a32a97a110a100a32a116a104a114a101aa32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a115a105a120a32a97a110a100a32a116a104a114a101aa32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a115a101a118a101a+9a32a97a110a100a32a116a104a114a101aa32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a101a+4a-2a^a116a32a97a110a100a32a116a104a114a101aa32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a110a-5a+5a-9a32a97a110a100a32a116a104a114a101aa32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a104a97a108a-6a32a102a+9a+6a-3a+2a104a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a111ava-9a32a97a110a100a32a104a97a108a-6a32a102a+9a+6a-3a+2a104a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a116a+3a-8a32a97a110a100a32a104a97a108a-6a32a102a+9a+6a-3a+2a104a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a116a104a114a101aa32a97a110a100a32a104a97a108a-6a32a102a+9a+6a-3a+2a104a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a102a+9a+6a-3a32a97a110a100a32a104a97a108a-6a32a102a+9a+6a-3a+2a104a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a102a+3a118a101a32a97a110a100a32a104a97a108a-6a32a102a+9a+6a-3a+2a104a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a115a105a120a32a97a110a100a32a104a97a108a-6a32a102a+9a+6a-3a+2a104a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a115a101a118a101a+9a32a97a110a100a32a104a97a108a-6a32a102a+9a+6a-3a+2a104a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a101a+4a-2a^a116a32a97a110a100a32a104a97a108a-6a32a102a+9a+6a-3a+2a104a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a110a-5a+5a-9a32a97a110a100a32a104a97a108a-6a32a102a+9a+6a-3a+2a104a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a102a+9a+6a-3a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a111ava-9a32a97a110a100a32a102a+9a+6a-3a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a116a+3a-8a32a97a110a100a32a102a+9a+6a-3a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a116a104a114a101aa32a97a110a100a32a102a+9a+6a-3a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a102a+9a+6a-3a32a97a110a100a32a102a+9a+6a-3a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a102a+3a118a101a32a97a110a100a32a102a+9a+6a-3a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a115a105a120a32a97a110a100a32a102a+9a+6a-3a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a115a101a118a101a+9a32a97a110a100a32a102a+9a+6a-3a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a101a+4a-2a^a116a32a97a110a100a32a102a+9a+6a-3a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a110a-5a+5a-9a32a97a110a100a32a102a+9a+6a-3a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a104a97a108a-6a32a102a+3a-3a116a104a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a111ava-9a32a97a110a100a32a104a97a108a-6a32a102a+3a-3a116a104a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a116a+3a-8a32a97a110a100a32a104a97a108a-6a32a102a+3a-3a116a104a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a116a104a114a101aa32a97a110a100a32a104a97a108a-6a32a102a+3a-3a116a104a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a102a+9a+6a-3a32a97a110a100a32a104a97a108a-6a32a102a+3a-3a116a104a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a102a+3a118a101a32a97a110a100a32a104a97a108a-6a32a102a+3a-3a116a104a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a115a105a120a32a97a110a100a32a104a97a108a-6a32a102a+3a-3a116a104a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a115a101a118a101a+9a32a97a110a100a32a104a97a108a-6a32a102a+3a-3a116a104a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a101a+4a-2a^a116a32a97a110a100a32a104a97a108a-6a32a102a+3a-3a116a104a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a110a-5a+5a-9a32a97a110a100a32a104a97a108a-6a32a102a+3a-3a116a104a32a116a105a+4a-8a115a32a116a+3a101a+9a+6a+5a10a111ava-9a32a104a117a-7a100a114a101ava

```

This is an improved version of Beta Decays program.
> 4 votes

# Answer
# 05AB1E, ~~127~~ ~~123~~ ~~120~~ 115 bytes

```
“¡×€µ‚•„í†ìˆÈŒšï¿Ÿ¯¥Š—¿áÓÁÏ‰ª†ìdßàŒšdï¿dŸ¯een¥Šd“¤'…§:#©`…«¹¿œÖƒ#“‰ª„í¦ƒ†ì³ä“#ε…ÿ„Æ«¹NÈi„Š£ ì]«vyTG®Nè'€ƒ‚yª]„€µ°¡»

```

Try it online!

```
“¡× (...) Šd“         # dictionary string "zero one two ... sixd sevend eighteen nined"
¤                     # get the last letter ("d") without popping
 '…§                  # dictionary string "teen"
    :                 # replace (changes all "d" to "teen" in the initial string)
     #                # split on spaces
      ©               # save this list to the register
       `              # dump all items on the stack
…«¹¿œÖƒ               # dictionary string "twenty thirty fourty"
       #              # split on spaces
“‰ª„í¦ƒ†ì³ä“          # dictionary string "third three fourth four fifth"
            #         # split on spaces
ε              ]      # for each:
 …ÿ„Æ«¹               #  append " times twenty"
       NÈi     ]      #  if the iteration count is even:
          „Š£ ì       #   prepend "half "
                «     # merge those two lists ([20, 30, 40] and [50, 60, 70, 80, 90])
v            ]        # for y in this list of names:
 y                    #  put y on the stack
  TG         ]        #  for N from 1 to 9:
    ®Nè               #   get the Nth element in the register
       '€ƒ‚           #   append "and"
           yª         #   append y
„€µ°¡                 # dictionary string "one hundred"
     »                # join the stack with newlines

```
> 4 votes

# Answer
# JavaScript (ES6), 346 bytes

Only a small idea to ETHproductions' solution: Replace `f(..)` with `a[..]` to be able to call `f` recursively to concat the output.

```
f=x=>(a="1one1two1three1four1five1six1seven1eight1nine1ten1eleven1twelve1thir11fif111eigh".split(1),x<1?"zero":f(x-1)+(x<13?a[x]:x<20?(a[x]||a[x-10])+"teen":x>99?"one hundred":(x%10?a[x%10]+" and ":"")+(x<50?"twen1thir1for".split(1)[x/10-2|0]+"ty":(x%20>9?"half "+"third1forth1fifth".split(1)[x/20-2.5|0]:a[x/20|0])+" times twenty")))+"\n"
f(100)

```

Still far away from optimal...
> 3 votes

# Answer
# Java ~~8~~ 7, ~~512~~ 490 + 19(import) bytes

Needs an import `import java.util.*;`

```
<T>void y(List<T>l,T...a){for(T t:a)l.add(t);}List x(){String b="teen",c="twenty",d="half ",e=" times "+c;String[]a={"zero","one","two","three","four","five","six","seven","eight","nine"},f={c,"thirty","fourty",d+"third"+e,a[3]+e,d+"fourth"+e,a[4]+e,d+"fifth"+e};List<String>g=new ArrayList<>(Arrays.asList(a));y(g,"ten","eleven","twelve","thir"+b,a[4]+b,"fif"+b,a[6]+b,a[7]+b,"eigh"+b,a[9]+b);for(String h:f){y(g,h);for(int i=1;i<=9;i++)y(g,(a[i]+" and "+h));}y(g,"one hundred");return g;}

```

**Ungolfed:**

```
<T> void y(List<T> l, T... a) {
    for (T t : a) {
        l.add(t);
    }
}

List x() {
    String b = "teen", c = "twenty", d = "half ", e = " times " + c;
    String[] a = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"},
        f = {c, "thirty", "fourty", d + "third" + e, a[3] + e, d + "fourth" + e, a[4] + e, d + "fifth" + e};
    List<String> g = new ArrayList<>(Arrays.asList(a));
    y(g, "ten", "eleven", "twelve", "thir" + b, a[4] + b, "fif" + b, a[6] + b, a[7] + b, "eigh" + b, a[9] + b);

    for (String h : f) {
        y(g, h);
        for (int i = 1; i <= 9; i++) {
            y(g, (a[i] + " and " + h));
        }
    }

    y(g, "one hundred");
    return g;
}

```

To run this, simply call `<instance>.x();`. This now returns the list containing all numbers.

Try it here!
> 3 votes

# Answer
# Python 2, ~~359~~ ~~349~~ 345 Bytes

```
a='one two three four five six seven eight nine'.split()
c=['ten','eleven','twelve']+[i+'teen'for i in['thir',a[3],'fif',a[5],a[6],'eigh',a[8]]]
p=' times twenty'
h='half '
x=[p[7:],'thirty','forty',h+'third'+p,a[2]+p,h+'forth'+p,a[3]+p,h+'fifth'+p]
f=['zero']+a+c
for i in x:f+=[i];f+=[b+' and '+i for b in a]
for i in f+['one hundred']:print i

```

## Explanation:

Create a list of the first 9 numbers.
Create a list of the next 10 numbers.
Create a list of the endings - `twenty`, `thirty`, `forty`, `half third times twenty` etc
Join the first two lists with `zero`
Append to the list each of the numbers from 50 onwards.
Print out list

Ungolfed code:

```
firstNumbers=['one','two','three','four','five','six','seven','eight','nine']
teenNumbers=['ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen']
endings=['twenty','thirty','forty','half third times twenty','three times twenty','half forth times twenty','four times twenty','half fifth times twenty']
joined=['zero']+firstNumbers+teenNumbers
for ending in endings:
    joined.append(ending)
    for number in firstNumbers:
        joined.append(number + 'and' + ending)
joined.append('one hundred')
for line in joined:
    print line

```
> 3 votes

# Answer
# Python 2, with num2words, 206 bytes

Even with num2words it takes quite a few bytes!

This is a full program.

```
from num2words import num2words as w
for i in range(1,101):d=i/10;e=w(i).split('-');print' and '.join(e[1:]+[10>d>4 and((d%2 and'half '+{5:'third',7:'forth',9:'fifth'}[d]or w(d/2))+' times twenty')or e[0]])

```

Here is a mocked version on **ideone**
(By mocked I mean that since the online interpreter does not have `num2words` I replaced `w` with a `lambda` which looks up `num2word`'s output in a list)

ungolfed and with 'fourth' rather than the allowed 'forth' (which saves a byte):

```
from num2words import num2words
for i in range(1,101):
    d = i / 10 # i div 10
    e = num2words(i).split('-') # i in English words with a "-" separator, split into parts
    if d > 4 and d < 10:
        if d % 2:
            p = 'half '+ {5:'third', 7:'fourth', 9:'fifth'}[d] + ' times twenty'
        else:
            p = num2words(d / 2) + ' times twenty'
    else:
        p = e[0]
    print' and '.join(e[1:]+[p])

```

Note that the separator used by `num2words(100)` is a space, whereas for the other numbers it is a "-", so we don't need to do anything fancy for that case other than stop it from being "five times twenty".

---

**Aside**

If the challenge were to actually produce the numbers in Danish one could take the lang\_DK.py from the github page and use:

```
from num2words import*
[num2words(i,lang='dk')for i in range(1,101)]

```

for 68 bytes, yielding:

```
['et', 'to', 'tre', 'fire', 'fem', 'seks', 'syv', 'otte', 'ni', 'ti', 'elleve', 'tolv', 'tretten', 'fjorten', 'femten', 'seksten', 'sytten', 'atten', 'nitten', 'tyve', 'enogtyve', 'toogtyve', 'treogtyve', 'fireogtyve', 'femogtyve', 'seksogtyve', 'syvogtyve', 'otteogtyve', 'niogtyve', 'tredive', 'enogtredive', 'toogtredive', 'treogtredive', 'fireogtredive', 'femogtredive', 'seksogtredive', 'syvogtredive', 'otteogtredive', 'niogtredive', 'fyrre', 'enogfyrre', 'toogfyrre', 'treogfyrre', 'fireogfyrre', 'femogfyrre', 'seksogfyrre', 'syvogfyrre', 'otteogfyrre', 'niogfyrre', 'halvtreds', 'enoghalvtreds', 'tooghalvtreds', 'treoghalvtreds', 'fireoghalvtreds', 'femoghalvtreds', 'seksoghalvtreds', 'syvoghalvtreds', 'otteoghalvtreds', 'nioghalvtreds', 'treds', 'enogtreds', 'toogtreds', 'treogtreds', 'fireogtreds', 'femogtreds', 'seksogtreds', 'syvogtreds', 'otteogtreds', 'niogtreds', 'halvfjerds', 'enoghalvfjerds', 'tooghalvfjerds', 'treoghalvfjerds', 'fireoghalvfjerds', 'femoghalvfjerds', 'seksoghalvfjerds', 'syvoghalvfjerds', 'otteoghalvfjerds', 'nioghalvfjerds', 'firs', 'enogfirs', 'toogfirs', 'treogfirs', 'fireogfirs', 'femogfirs', 'seksogfirs', 'syvogfirs', 'otteogfirs', 'niogfirs', 'halvfems', 'enoghalvfems', 'tooghalvfems', 'treoghalvfems', 'fireoghalvfems', 'femoghalvfems', 'seksoghalvfems', 'syvoghalvfems', 'otteoghalvfems', 'nioghalvfems', 'ethundrede']

```
> 3 votes

# Answer
# Bash (using `rev` and `sed`), ~~299~~ 276 bytes

I'm using bash's curly braces-expansion. However the braces are expanded in the wrong order, so I print all the words in reverted order and then fix the order of the letters using `rev`. After that, I still need some adjustments using `sed`:

```
printf '%s\n' orez {,{neet,yt{newt,riht,rof},ytnewt\ semit\ {drihtX,eerht,htruofX,ruof,htfifX}}Y}{,eno,owt,eerht,ruof,evif,xis,neves,thgie,enin} derdnuh\ eno |rev |sed -r 's,^Yte,t,;s,^Y,,;12s,.*,eleven,;13s,o.*,elve,;1,20{s,reeY,ir,;s,veY,f,;s,(t|)Y,,};s,Y, and ,;s,X,half ,'

```

A bit less unreadable:

```
printf '%s\n' orez {,{neet,yt{newt,riht,rof},\
ytnewt\ semit\ {drihtX,eerht,htruofX,ruof,htfifX}}Y}\
{,eno,owt,eerht,ruof,evif,xis,neves,thgie,enin} \
    derdnuh\ eno \
    |rev \
    |sed -r 's,^Yte,t,;
            s,^Y,,;
            12s,.*,eleven,;
            13s,o.*,elve,;
            1,20{s,reeY,ir,;s,veY,f,;s,(t|)Y,,};
            s,Y, and ,;
            s,X,half ,'

```
> 3 votes

# Answer
# PHP , 318 Bytes

```
for($i=~0;$i++<100;)echo([0=>zero,10=>ten,eleven,twelve,thirteen,15=>fifteen,18=>eighteen,100=>"one hundred"][$i]??["",one,two,three,four,five,six,seven,eight,nine][$i%10].($i>20&&$i%10?" and ":"").["",teen,twenty,thirty,forty,"half third",three,"half fourth",four,"half fifth"][$i/10].($i>49?" times twenty":"")).",";

```

first pick with the Null coalescing operator ?? the exceptions.

this version with 314 Bytes is without the , at the end

```
zero<?php for($i=0;$i++<100;)echo",".([10=>ten,eleven,twelve,thirteen,15=>fifteen,18=>eighteen][$i]??["",one,two,three,four,five,six,seven,eight,nine][$i%10].($i>20&&$i%10?" and ":"").["",teen,twenty,thirty,forty,"half third",three,"half fourth",four,"half fifth"][$i/10].($i>49?" times twenty":""));?>,one hundred

```
> 3 votes

# Answer
# ink, ~~286~~ 273 bytes

```
zero
-(c){
-c>9 and c<20:
{ten|eleven|twelve|{thir|four|fif|six|seven|eigh|nine}teen}
-c%10:
{&one|two|three|four|five|six|seven|eight|nine}{c>9: and {t}}
-1:
~temp t="{twenty|thirty|forty|{&half {third|fourth|fifth}|{three|four}} times twenty}"
{t}
}
{c<99:->c}one hundred

```

Try it online!

* -13 bytes by removing a useless "five times twenty" case, special-casing zero to be able to simplify the mod check, and simplifying the teens (which now also include ten)

Ink has sequences - they look like `{a|b|c}` and evaluate to a different value each time, until there's no next value at which point they stick with the last one. By combining and nesting these, we can get pretty advanced with very little in the way of actual conditionals.

A sequence that begins with `{&` instead of just `{` is a cycle - those loop and that's how we count units and how we alternate between "half nth times twenty" and "n times twenty" for the tens.

We keep track of the name for the tens in a variable `t` which we only update every tenth pass through the loop. On the passes where we update the variable, we print only the variable, on other passes we use cycles to print the unit followed by `and {t}`.
With a handful exceptions - below ten we skip printing the tens (no `three and zero`) and the teens are irregular enough that they get a sequence all to themselves.

`c` is a labelled gather. Gathers by themselves don't do anything, but they can be diverted to as a form of control flow, and they keep track of how many times they've been visited - we use this readcount to special-case the teens, to know when we need to update the tens variable, and to know when to stop looping, wrap everything up and print one hundred.

I know I could save a byte by using "forth" instead of "fourth", but I'm choosing not to.

## Ungolfed

```
zero // Print "zero"
- (c)
{
- c > 9 and c < 20:
    // The teens get a sequence of their own because they don't fit into the other numbers' pattern.
    {ten|eleven|twelve|{thir|four|fif|six|seven|eigh|nine}teen}
- c % 10: // Otherwise, unless we're meant to print a multiple of ten
    // Print the unit - this is a cycle, so it loops when it's been run through nine times.
    {&one|two|three|four|five|six|seven|eight|nine}
    {c > 9:<> and {t}} // If we're past nine (and, since we didn't enter the "teens" section earlier, past nineteen), also print " and " and the contents of the variable t.
- else:
    // Set the variable t to the multiple of ten we want. Note the cycle to alternate between "half nth" and "n"
  ~ temp t="{zero|ten|twenty|thirty|forty|{&half {third|fourth|fifth}|{three|four}} times twenty}"

    {t} // Print the contents of t
}
{c < 99: -> c} // If we've done all this fewer than a hundred times, we go back to the top.
one hundred // Print "one hundred"
// Out of content, end of program

```
> 3 votes

---
Tags: code-golf, string, kolmogorov-complexity, counting, natural-language
---


# Question
Title: How can I golf this JavaScript code, if at all?
I have some JavaScript code in a `<script>` HTML tag I'd like to golf, while still remaining in the tag. How can I golf that code, if at all? Here's the code:

```
<script>document.write`<font color=#40e0d0 face=arial>YOU ARE IN THE BEDROOM.<br>YOU SEE CRAB NICHOLSON.<br>HE HAS NO MITTENS.<br>HIS CLAWS ARE MENACING.<br>OBVIOUS EXITS ARE:<br>BATHROOM, KITCHEN, LIVING ROOM<br>AND CRAB NICHOLSON'S<br>ULTIMATE LAIR OF AWESOMENESS</font>`;document.body.style.background="#000"</script>
```

# Answer
> 10 votes
Save 3 bytes by assigning `document` to a variable:

```
(d=document).write`<font color=#40e0d0 face=arial>YOU ARE IN THE BEDROOM.<br>YOU SEE CRAB NICHOLSON.<br>HE HAS NO MITTENS.<br>HIS CLAWS ARE MENACING.<br>OBVIOUS EXITS ARE:<br>BATHROOM, KITCHEN, LIVING ROOM<br>AND CRAB NICHOLSON'S<br>ULTIMATE LAIR OF AWESOMENESS</font>`;d.body.style.background="#000"

```

Save 2 bytes by reusing ' CRAB NICHOLSON':

```
(d=document).write(`<font color=#40e0d0 face=arial>YOU ARE IN THE BEDROOM.<br>YOU SEE${c=' CRAB NICHOLSON'}.<br>HE HAS NO MITTENS.<br>HIS CLAWS ARE MENACING.<br>OBVIOUS EXITS ARE:<br>BATHROOM, KITCHEN, LIVING ROOM<br>AND${c}'S<br>ULTIMATE LAIR OF AWESOMENESS</font>`);d.body.style.background="#000"

```

Save 1 byte by using `.join`<br>``:

```
(d=document).write(`<font color=#40e0d0 face=arial>YOU ARE IN THE BEDROOM._YOU SEE${c=' CRAB NICHOLSON'}._HE HAS NO MITTENS._HIS CLAWS ARE MENACING._OBVIOUS EXITS ARE:_BATHROOM, KITCHEN, LIVING ROOM_AND${c}'S_ULTIMATE LAIR OF AWESOMENESS</font>`.split`_`.join`<br>`);d.body.style.background="#000"

```

Further golfs suggested by @Night2:

Save 14 bytes by using `.bgColor=0`:

```
(d=document).write(`<font color=#40e0d0 face=arial>YOU ARE IN THE BEDROOM._YOU SEE${c=' CRAB NICHOLSON'}._HE HAS NO MITTENS._HIS CLAWS ARE MENACING._OBVIOUS EXITS ARE:_BATHROOM, KITCHEN, LIVING ROOM_AND${c}'S_ULTIMATE LAIR OF AWESOMENESS</font>`.split`_`.join`<br>`);d.body.bgColor=0

```

Save 7 bytes by 'forgetting' to close the `<font>` tag (YMMV):

```
(d=document).write(`<font color=#40e0d0 face=arial>YOU ARE IN THE BEDROOM._YOU SEE${c=' CRAB NICHOLSON'}._HE HAS NO MITTENS._HIS CLAWS ARE MENACING._OBVIOUS EXITS ARE:_BATHROOM, KITCHEN, LIVING ROOM_AND${c}'S_ULTIMATE LAIR OF AWESOMENESS`.split`_`.join`<br>`);d.body.bgColor=0

```

---
Tags: tips, javascript
---


# Question
Title: Removing points from a triangular array without losing triangles
I have a combinatorics problem that I'd like to put on the OEIS—the problem is that I don't have enough terms. This code challenge is to help me compute more terms, and the winner will be the user with the submission containing the greatest number of terms.

---

# The Problem

Suppose I give you a triangular array of light bulbs with side length \\$n\\$:

```
     o
    o o
   o o o
  o o o o
 o o o o o
o o o o o o
1 2  ...  n

```

I'm going to turn on three lightbulbs that form an "upright" equilateral triangle as in the following example:

```
     o
    o x
   o o o
  o o o o
 o x o o x
o o o o o o

```

Before I turn on the lights, your job is to remove as many lightbulbs as possible from the array—without losing the ability to deduce the triangle of bulbs that has been turned on. To be clear, if a lightbulb has been removed, it is not lit up when its position is turned on.

For example, if you removed the following bulbs (marked by `.`) you would only see the following two lights turn on (marked by `x`), which is enough uniquely deduce the third (unlit) position:

```
     .              .
    . o            . x
   . . o          . . o
  o o o .   =>   o o o .
 o o o o .      o x o o . <- the third unlit position
o . . . o o    o . . . o o

```

Let `a(n)` be the maximum number of bulbs that can be removed without introducing any ambiguities.

---

# Example

With a naive algorithm, I have checked values up to a triangle with side length 7, as seen below:

```
                                                                      .
                                                      .              . o
                                        .            . o            o . o
                           .           . .          . . o          . o o .
              .           . .         . o o        o o o .        o o . o .
 .           . .         . o o       o o . o      o o o o .      o . o . o o
. .         . o o       . o o o     o . . o o    o . . . o o    o . o . o o o

a(2) = 3    a(3) = 4    a(4) = 5    a(5) = 7     a(6) = 9       a(7) = 11

```

---

# Scoring

The submission that computes the sequence `[a(2), a(3), ..., a(n)]` for the largest n wins. If two submissions have identical sequences, then the one that was posted earlier wins.

Although not necessary for the submission, it would be instructive to me if you post a construction of the resulting triangluar arrays, as in the example above.

# Answer
> 10 votes
# Python 3, `n=8`

```
import itertools
from ortools.sat.python import cp_model

def solve(n):
    model = cp_model.CpModel()
    solver = cp_model.CpSolver()
    cells = {
        (y, x): model.NewBoolVar(str((y, x)))
        for y in range(n) for x in range(y + 1)}
    triangles = [
            {cells[v] for v in ((y1, x1), (y2, x1), (y2, x1 + y2 - y1))}
            for (y1, x1) in cells.keys() for y2 in range(y1 + 1, n)]
    for t1, t2 in itertools.combinations(triangles, 2):
        model.AddBoolOr(t1.symmetric_difference(t2))
    model.Minimize(sum(cells.values()))
    solver.Solve(model)
    return len(cells) - round(solver.ObjectiveValue())

for n in itertools.count(2):
    print('a(%d) = %d' % (n, solve(n)))

```

Uses Google OR-Tools' CP-SAT solver.

After running for ~30 seconds, it outputs the following:

```
a(2) = 3
a(3) = 4
a(4) = 5
a(5) = 7
a(6) = 9
a(7) = 11
a(8) = 13

```

~~I didn't event try to wait for `n=9` as it would probably take hours (the number of constraints grows like \\$n^6\\$)~~. After less than 30 minutes of computation I found out that `a(9)=15`. I'm leaving my score as `n=8` because at the moment the time constraints are unclear, but half an hour is probably too long.

## How it works

Take two distinct equilateral triangles \\$T\_1\\$ and \\$T\_2\\$. To avoid ambiguity, there should be at least one bulb on a vertex belonging to *exactly* one of \\$T\_1\\$ and \\$T\_2\\$.

Thus the question may be rephrased as a SAT problem, with one constraint for every pair of triangles.

**PS:** I would very much like to include an example for `n=8`, but I'm having issues with the SAT solver which apparently wants to keep the solutions all for itself.

# Answer
> 2 votes
### Getting the solutions from @Delfad0r's program

I extended @Delfad0r's program to output solutions. It also gives intermediate results, so you get output like this:

```
Solving n = 8:
a(8) >= 9
a(8) >= 10
a(8) >= 11
a(8) >= 12
a(8) >= 13
       o
      . o
     . o o
    . o o .
   o o . o o
  o o o o . .
 o . . o o o .
o . . o . o o o
a(8) = 13

Solving n = 9:
a(9) >= 10
a(9) >= 13
a(9) >= 14
a(9) >= 15
        o
       o o
      o . .
     o . o o
    . o . o o
   . o o o o o
  o o o . o . .
 o o o . . . o o
. o o o o o o . .
a(9) = 15

```

This computation took several hours.

If you get impatient and press `Ctrl-C` after some possibly non-optimal solution was found, the program will show that solution. So it doesn't take long to get this:

```
                   .
                  o o
                 . o o
                . o o o
               o o . o o
              o . o o o .
             o . o . o o o
            . o o o o o . o
           o . . o o o o o o
          o o o o o o o o o .
         o o . o o o o . o o o
        o o o o o o . o . o o o
       o . o o . o o o o o o o o
      o o o . o o o o o . o o o o
     o o o . o o o o o o o o . . o
    o o o o o o o o o o o . o . . o
   o o o o . o o o o . o o o o o . o
  o o o o o o o o . o o . . o o o o .
 o o o o . o o . o . o o o o o o . o o
o o . o o . o o o o . o o o . o o o o o
a(20) >= 42

```

Here is the extended program:

```
import itertools
from ortools.sat.python import cp_model

class ReportPrinter(cp_model.CpSolverSolutionCallback):

    def __init__(self, n, total):
        cp_model.CpSolverSolutionCallback.__init__(self)
        self.__n = n
        self.__total = total

    def on_solution_callback(self):
        print('a(%d) >= %d' %
              (self.__n, self.__total-self.ObjectiveValue()) )

def solve(n):
    model = cp_model.CpModel()
    solver = cp_model.CpSolver()
    cells = {
        (y, x): model.NewBoolVar(str((y, x)))
        for y in range(n) for x in range(y + 1)}
    triangles = [
            {cells[v] for v in ((y1, x1), (y2, x1), (y2, x1 + y2 - y1))}
            for (y1, x1) in cells.keys() for y2 in range(y1 + 1, n)]
    for t1, t2 in itertools.combinations(triangles, 2):
        model.AddBoolOr(t1.symmetric_difference(t2))
    model.Minimize(sum(cells.values()))
    print('Solving n = %d:' % n)
    status = solver.SolveWithSolutionCallback(model, ReportPrinter(n,len(cells)))
    if status == cp_model.OPTIMAL:
        rel = '='
    elif status == cp_model.FEASIBLE:
        rel = '>='
    else:
        print('No result for a(%d)\n' % n)
        return
    for y in range(n):
        print(' '*(n-y-1), end='')
        for x in range(y+1):
            print('.o'[solver.Value(cells[(y,x)])],end=' ')
        print()
    print('a(%d) %s %d' % (n, rel, len(cells) - solver.ObjectiveValue()))
    print()

for n in itertools.count(2):
    solve(n)

```

# Answer
> 1 votes
# Python 3

Based strongly on Delfad0r's answer, mostly follows the same logic progression by checking triangle pairs and validating the configuration if it contains no triangle pairs that fail this validation. Since I didn't use any libraries besides itertools and copy, I have full control over saving the examples encountered throughout the program.

```
examples = dict() # stores examples by key pair of n to a tuple with the triangle and number of lights turned off

for n in range(3, 8):
    tri = [] # model of the triangle, to be filled with booleans representing lights
    tri_points = [] # list of tuples representing points of the triangle
    for i in range(n):
        tri.append([True]*(i + 1))
        for j in range(i+1):
            tri_points.append((i, j))

    t_set = [] # list of all possible triangles from tri, represented by lists of points
    for i in range(n):
        for j in range(len(tri[i])):
            for k in range(1, n - i):
                t_set.append([(i, j), (i + k, j), (i + k, j + k)])

    from itertools import combinations
    import copy

    # validates whether or not a triangle of n lights can have i lights turned off, and saves an example to examples if validated
    def tri_validate(x):
        candidate_list = list(combinations(tri_points, x))
        tri_pairs = list(combinations(t_set, 2))
        for candidate in candidate_list:
            temp_tri = copy.deepcopy(tri)
            valid = False
            for point in candidate:
                (row, col) = point
                temp_tri[row][col] = False
            for pair in tri_pairs:
                valid = False
                (tri1, tri2) = pair
                for point in tri1:
                    if not valid:
                        if point not in tri2:
                            (row, col) = point
                            if temp_tri[row][col]:
                                valid = True
                for point in tri2:
                    if not valid:
                        if point not in tri1:
                            (row, col) = point
                            if temp_tri[row][col]:
                                valid = True
                if not valid:
                    break
            if valid:
                examples[n] = (temp_tri, x)
                return True
        return False

    # iterates up to the point that validation fails, then moves on to the next n
    for i in range(len(tri_points)):
        if tri_validate(i + 1):
            continue
        break

```

Problem is, it's not very efficient. It runs really fast up to `n=5`, but starts to slow down significantly past that point. At `n=6`, it takes around a minute to run, and it's much slower at `n=7`. I imagine there are a lot of efficiency fixes that can be made with this program, but it's a quickly made rough draft of a good solution with a lot more flexibility to check out the inner workings of this method. I'll be incrementally working on this over time.

---
Tags: code-challenge, sequence, combinatorics
---


# Question
Title: Solve Subset-Sum in polynomial time (...if P = NP)
Shocking news: Dr. Mad J Scientist has released a proof of P = NP to the world. But the proof is nonconstructive, and she's keeping the algorithm to herself.

Worry not. Without even looking at her proof, we can still (almost) write a computer program that solves NP-complete problems in polynomial time.

# The Problem

Input a list of integers, such as `[-10, -4, 1, 1, 2, 6, 8]`. Output a nonempty sublist that sums to 0, such as `[-10, 1, 1, 2, 6]`. The output list can be in any order. Ignore any integer overflow issues in your language.

**If P = NP, your program must provably run in polynomial time on solvable inputs.** Your program may act arbitrarily on inputs with no solution. This is ; shortest code wins.

**Yes, this challenge is possible.** One approach is as follows:

> Enumerate all possible computer programs \\$P\_0, P\_1, P\_2, \dots\\$
> Repeat as \\$i\\$ goes from 0 to \\$\infty\\$:
> ----- Run the first \\$i\\$ programs on the input list, for \\$i\\$ steps each.
> ----- For each output you get, check whether it's a valid subset sum solution. If so, return it.

This works because, if P = NP, then some program \\$P\_m\\$ solves subset-sum in some polynomial time \\$O(n^k)\\$. Therefore, the above algorithm will output a solution on the \\$\max(m, O(n^k))\\$th iteration of the loop, if not before. Therefore, the above algorithm runs in polynomial time on solvable inputs.

Note: A proof that P ≠ NP would allow a 0-byte solution to this problem. Good luck with that :)

**Notes**

Before you start `eval`ing all strings in a language like Python, let me point out that some of those strings will reformat your hard drive.

This challenge does not run afoul of the no famous open questions rule, because although it is related to P vs NP, this challenge is solvable.

# Answer
# Python 3.8 (on Unix), 429 bytes

Since nobody else has posted an answer yet, I thought I'd have a go, though I not 100% certain I haven't missed something important (and I *am* 100% certain the code could be shrunk down significantly).

As noted in the question, evaluating arbitrary Python strings is dangerous. Fortunately, it's easy to come up with a safe subset of strings whose evaluation is still Turing complete, by embedding the Turing complete While Programming Language, summarised below:

This can be embedded into Python using only strings that match the following regex:

```
^([0-9 \n():_=+-]|while)+$

```

To reduce the number of necessary characters, we use a few embedding hacks:

* variable names are built only of underscores
* `if B then C1 else C2` is emulated using while loops (and temporary variables x and y, which hang around afterwards but that's ok):

```
x=B;y=not x
while x:C1;x=False
while y:C2;y=False

```
* skip is emulated using any constant expression, e.g. `0`
* true is emulated using e.g. `0==0`
* false is emulated using e.g. `0==1`
* `B & C` is emulated using a pre-evaluated if-then-else (and another temporary variable x):

```
if B then x=C else x=False

```
* `¬ B` is emulated using `1-B`

To make our life easier, we also allow `[` and `]`, as this permits direct operations on lists (including slicing and concatenation) which avoids having to translate the problem from one on lists into one on integers.

*Update*: as noted by @ØrjanJohansen, it's also necessary to include `<` to ensure basic arithmetic remains polynomial.

**I claim that any program with just those characters will either execute, or (far more likely) fail to execute, or raise an exception, but will *not* crash the interpreter or change any global state. Please correct me if I'm wrong.**

The rest of the solution is now similar to the prototype presented in the question. We generate all strings of increasing lengths *n* and execute them, prepopulating the input in variable `_` and checking and validating any output from the same variable. We catch any raised exceptions and continue.

The main tricky bit is ensuring polynomial complexity (and termination). We do this by breaking out of each execution after `n` seconds, using Unix signals and a handler that raises an exception (which the string executions themselves have no way of catching). Since every program will appear repeatedly (eg with trailing whitespace), we don't need to worry about breaking out too soon from a correct program. One tricky bit here is to make sure that the program doesn't crash if the signal is received *after* the execution completed (successfully or not) but *before* the signal has been reset; this explains the nested try-catch.

```
from itertools import*
from re import*
from signal import*
I=eval(input())
signal(SIGALRM,0)
for n in count():
 for p in product(*[set(map(chr,range(128)))]*n):
  if match("([0-9 \n()[\]:_=<+-]|while)+$",(s:="".join(p))):
   try:
    try:
     g={'_':I[::]};alarm(n);exec(s,g);h=g['_']
     if h and all(h.count(x)<=I.count(x)for x in h)and sum(h)==0:
      print(h);n=-1;break
    except:0
    alarm(0)
   except:0
 if n<0:break

```

Try it online! (though don't expect an actual result; it may be P but it's obscenely slow)
> 6 votes

---
Tags: code-golf, restricted-complexity
---


title: Quine in Bytes, not Characters

text:
# Question
Title: Quine in Bytes, not Characters
# Introduction

A quine is a program that takes no input and produces a copy of its own source code as output. Writing a quine is a standard test of a programming language. Most quines operate using strings of characters: that is what the source code is made of, after all! However, this quine is slightly different.

# Challenge

Your challenge is to write a program that takes no input and produces the number of bytes in the program as output.

* By "takes no input", I mean does not change based on input. Your program can still take command line arguments, or even arguments from stdin, but it cannot do anything with them. It must either discard or ignore them. Basically, your program should produce the same output no matter what input is given.
* Your program must output the number of bytes in it. If it is a function, it can output through its return value. If, and only if your language has no stdout, you may store output in a variable. The input can be printed as a string or an integer; the user cannot tell the difference between the output of `print('5')` or `print(5)`! Note that I said byte count, not character count. If your program uses Unicode characters that take up more than 1 byte (like some Jelly or APL programs), the output must reflect that.

# Rules

This is so shortest answer in bytes wins! Edit: Actually, since there is a 1 byte answer, let's do top 3 shortest.

Edit: this question is not the same as Output your Score. For one, this one does not disallow cheating quines. Also, I do not require a trailing " bytes" in output.

# Answer
# Most languages, 0 bytes

Try it online!

Outputs via exit code, which is `0` for almost any language where an empty program is valid.
> 12 votes

# Answer
# Poetic, ~~87~~ 86 bytes

*-1 byte due to a slightly better representation of the character "8".*

```
hey-o
i guess i got a number i can write
an apple a day keeps doctors away, we suppose

```

Try it online!

Poetic is an esolang I made in 2018 for a class project. It's basically brainfuck with word-lengths instead of symbols.

I couldn't resist making the word-lengths spell out a popular phrase, hehe. ⚕
> 5 votes

# Answer
# Jelly, 1 byte

```
1

```

Try it online!

This probably works in a lot of other languages as well. Note that the output does *not* have a trailing newline
> 4 votes

# Answer
# Python 2, 7 bytes

```
print 7

```

Try it online!
> 4 votes

# Answer
# Keg, 2 bytes

```
2#

```

Try it online!

Not a duplicate, and this should hopefully clinch me 3rd place :)
> 4 votes

# Answer
# Perl 5 `-p`, 4 bytes

```
$_=4

```

Try it online!
> 3 votes

# Answer
# Ruby, 3 bytes

Probably one of the only times Ruby can beat Perl in bytes.

```
p 3

```

Try it online!
> 3 votes

# Answer
# JavaScript, 4 bytes

Boring!

```
_=>4

```

Try it Online!
> 3 votes

# Answer
# brainfuck, 20 bytes

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

```

Try it online!
> 2 votes

# Answer
# MathGolf, 1 byte

Try it online!

## Explanation

```
╧  On the empty stack, pop a,b, push a.contains(b)
   0 definitely contains 0, pushing a 1.

Implicit output

```

# MathGolf, 1 byte

```
)

```

Try it online!

## Explanation

```
) Increment this 0 value on the stack, returning a 1.

```

# MathGolf, 1 byte

```
=

```

Try it online!

## Explanation

```
= Check equality of 0 and 0, returns 1.

```
> 2 votes

# Answer
# Retina 0.8.2, 1 byte

```
^

```

Try it online! In Retina, the empty program outputs 1 more than the length of its input, which is bad here, since we don't want the output to depend on the input. Fortunately, either `^` or `$` help here, as they force the output to be `1`, which is conveniently also their length.
> 2 votes

# Answer
# HQ9+, 1 byte

```
+

```

This language does not allow you to write a program that prints only one number. Therefore, I save the number of bytes in a special counter.

HQ9+ online interpreter
> 2 votes

# Answer
# Metatape, 22 bytes

```
@a{ooxooeooxoeo} !a !a

```

The space characters are not syntactically necessary, but they take up less space than it would to output `21` or `20`.

`@a{...}` defines a subroutine named `a`, and `!a` executes that subroutine.

Output is bitwise (highest bit first). While the actual language is more complicated, for the sake of this program:

* `x` makes subsequent `o`s output `1`.
* `e` makes subsequent `o`s output `0`.
> 2 votes

# Answer
# Haskell, 5 bytes

```
f a=5

```

Try it online!
> 1 votes

# Answer
# , 6 bytes

```
cat(6)

```

Try it online!

(Note that Jo King's 0 byte answer is also valid in R.)
> 1 votes

# Answer
# Bash, 6 bytes

```
echo 6

```

Try it online!
> 1 votes

# Answer
# Japt `-F0`, 0 bytes

Try it

This can be my first 0 bytes answer!

Using -F"0" flag =\> outputs 0 if the programme returns a falsey value
> 1 votes

# Answer
# Rust, 3 bytes

```
||3

```

Try it online!
> 1 votes

# Answer
# PMD 85 BASIC, 0 bytes

Without any lines of code, `RUN` will respond with

> OK

i.e. zero kilobytes.

(yes, it's cheating)
> 1 votes

# Answer
# Turing Machine Code, 9 bytes

```
0 _ 9 * 1

```

Try it online!
> 0 votes

---
Tags: code-golf, integer, quine
---


title: Minimum number of changes required

text:
# Question
Title: Minimum number of changes required
Given an array where each number represent a color. After iterating each item in the array (for each item in the iteration the pointer can also point to the second-item-to-the-right), and the two colors in the iteration is the same, do the following checking:

If there is a different color between the pointed colors, the colors will "dissolve" (which is not allowed).

eg.: `[1,2,1]` is not allowed but `[1,1,2,2]` is allowed. Here is an explanation for the above test cases:

```
[1, 2, 1]
 ^     ^

```

We find that the two pointed items have the same color. We then realize that the color between the pointed items are different than the two same colors; this ensures a "dissolving".

The following is an explanation of the second example:

```
[1, 1, 2, 2]
 ^     ^

```

In this step, the atoms are different, so we don't perform the check.

```
[1, 1, 2, 2]
    ^     ^

```

In this step the atoms are still different. All colors do not "dissolve", ensuring a valid array.

---

We can change one color to another but the condition is if we change one color, then we have to change all of its occurrences in the array. The cost of changing color is the number of appearances of the color in the array.

eg.: if the array is `[1,2,1,2,1,3,2]` and we have decided to change 2 to 1, then our array will become `[1,1,1,1,1,3,1]` and the cost will be 3 (for changing three 2's to 1's)

We have to minimize the cost and make sure no color dissolves.

## Test cases

```
[1,1,3,3,2,2] -> 0 (no changes are required to prevent dissolving)
[1,3,1,3,1] -> 2 (change all 3's to 1's costs 2)
[1,1,2,3,2,3]-> 2 (change color of all 2's to 3's OR change color of all 3's to 2's)
[1,2,2,2] -> 0 (This is valid; in the second iteration, the color between the pointed colors are equal to the pointed colors.)
[1,2,1,2,1,3,2] -> 3 (the 1's must be changed to make the array valid, and there's 3 of them)

```

# Answer
> 0 votes
# Perl 5, 92 bytes

```
sub f{min map{$o=$_;map{$s="@_";$c=!/$o/*$s=~s,$o,$_,g;$s=~/(.) (.) \1/&&$1-$2?9e9:$c}@_}@_}

```

Try it online!

```
sub f{                        #ungolfed:
  min                         #minimum of the yielded list of numbers (from core module List::Util)
  map{                        #map: outer loop of f()'s input args
    $o=$_;                    #keep $o (outer) loop element
    map{                      #map: inner loop of f()'s input args
      $s="@_";                #$s string are input args (input chars) concatenated with no separation
      $c=!/$o/*$s=~s,$o,$_,g; #$c becomes 0 if inner and outer loop elements are equal
                              #otherwise $c becomes the number of changes on the input
                              #$s string when swapping $o with $_ (outer and inner loop variable)
      $s=~/(.) (.) \1/&&$1-$2 #check if $s after the swapping is valid: no three consecutive chars
                              #...should exists in $s where 1st and 3rd are equal but 2nd is not
        ? 9e9                 #yield big number 9e9 if $s is invalid to make sure it wont be the minimum
        : $c                  #yield the number of swaps if $s is valid
    }
    @_                       #input arg's
  }
  @_                         #input arg's, outer loop
}

```

---
Tags: code-golf, array
---