title: Cardinals and ordinals, 1 to 100

text:
# Question
Title: Cardinals and ordinals, 1 to 100
Here's a simple one to stretch your compression muscles. Your code (a complete program) must output the spelled-out English representation of all the cardinal numbers from 1 to 100, and then all the ordinal numbers from 1 to 100. The numerals in each list should be delimited by commas and spaces and properly hyphenated. Each list should begin with a single capital letter and conclude with a period. The two lists should be separated by a newline.

For clarity's sake, you must produce this exact byte stream:

```
One, two, three, four, five, six, seven, eight, nine, ten, eleven, twelve, thirteen, fourteen, fifteen, sixteen, seventeen, eighteen, nineteen, twenty, twenty-one, twenty-two, twenty-three, twenty-four, twenty-five, twenty-six, twenty-seven, twenty-eight, twenty-nine, thirty, thirty-one, thirty-two, thirty-three, thirty-four, thirty-five, thirty-six, thirty-seven, thirty-eight, thirty-nine, forty, forty-one, forty-two, forty-three, forty-four, forty-five, forty-six, forty-seven, forty-eight, forty-nine, fifty, fifty-one, fifty-two, fifty-three, fifty-four, fifty-five, fifty-six, fifty-seven, fifty-eight, fifty-nine, sixty, sixty-one, sixty-two, sixty-three, sixty-four, sixty-five, sixty-six, sixty-seven, sixty-eight, sixty-nine, seventy, seventy-one, seventy-two, seventy-three, seventy-four, seventy-five, seventy-six, seventy-seven, seventy-eight, seventy-nine, eighty, eighty-one, eighty-two, eighty-three, eighty-four, eighty-five, eighty-six, eighty-seven, eighty-eight, eighty-nine, ninety, ninety-one, ninety-two, ninety-three, ninety-four, ninety-five, ninety-six, ninety-seven, ninety-eight, ninety-nine, one hundred.
First, second, third, fourth, fifth, sixth, seventh, eighth, ninth, tenth, eleventh, twelfth, thirteenth, fourteenth, fifteenth, sixteenth, seventeenth, eighteenth, nineteenth, twentieth, twenty-first, twenty-second, twenty-third, twenty-fourth, twenty-fifth, twenty-sixth, twenty-seventh, twenty-eighth, twenty-ninth, thirtieth, thirty-first, thirty-second, thirty-third, thirty-fourth, thirty-fifth, thirty-sixth, thirty-seventh, thirty-eighth, thirty-ninth, fortieth, forty-first, forty-second, forty-third, forty-fourth, forty-fifth, forty-sixth, forty-seventh, forty-eighth, forty-ninth, fiftieth, fifty-first, fifty-second, fifty-third, fifty-fourth, fifty-fifth, fifty-sixth, fifty-seventh, fifty-eighth, fifty-ninth, sixtieth, sixty-first, sixty-second, sixty-third, sixty-fourth, sixty-fifth, sixty-sixth, sixty-seventh, sixty-eighth, sixty-ninth, seventieth, seventy-first, seventy-second, seventy-third, seventy-fourth, seventy-fifth, seventy-sixth, seventy-seventh, seventy-eighth, seventy-ninth, eightieth, eighty-first, eighty-second, eighty-third, eighty-fourth, eighty-fifth, eighty-sixth, eighty-seventh, eighty-eighth, eighty-ninth, ninetieth, ninety-first, ninety-second, ninety-third, ninety-fourth, ninety-fifth, ninety-sixth, ninety-seventh, ninety-eighth, ninety-ninth, one hundredth.

```

This is code golf, shortest answer in bytes wins.

# Answer
# Common Lisp, ~~88~~ ~~82~~ 80 bytes

```
(format t"~@(~{~R~^, ~}~).
~:*~@(~{~:R~^, ~}~)."(loop as i to 99 collect(1+ i)))

```

(It is part of the language, I hope you don't mind)

### Output

```
One, two, three, four, five, six, seven, eight, nine, ten, eleven, twelve, thirteen, fourteen, fifteen, sixteen, seventeen, eighteen, nineteen, twenty, twenty-one, twenty-two, twenty-three, twenty-four, twenty-five, twenty-six, twenty-seven, twenty-eight, twenty-nine, thirty, thirty-one, thirty-two, thirty-three, thirty-four, thirty-five, thirty-six, thirty-seven, thirty-eight, thirty-nine, forty, forty-one, forty-two, forty-three, forty-four, forty-five, forty-six, forty-seven, forty-eight, forty-nine, fifty, fifty-one, fifty-two, fifty-three, fifty-four, fifty-five, fifty-six, fifty-seven, fifty-eight, fifty-nine, sixty, sixty-one, sixty-two, sixty-three, sixty-four, sixty-five, sixty-six, sixty-seven, sixty-eight, sixty-nine, seventy, seventy-one, seventy-two, seventy-three, seventy-four, seventy-five, seventy-six, seventy-seven, seventy-eight, seventy-nine, eighty, eighty-one, eighty-two, eighty-three, eighty-four, eighty-five, eighty-six, eighty-seven, eighty-eight, eighty-nine, ninety, ninety-one, ninety-two, ninety-three, ninety-four, ninety-five, ninety-six, ninety-seven, ninety-eight, ninety-nine, one hundred.
First, second, third, fourth, fifth, sixth, seventh, eighth, ninth, tenth, eleventh, twelfth, thirteenth, fourteenth, fifteenth, sixteenth, seventeenth, eighteenth, nineteenth, twentieth, twenty-first, twenty-second, twenty-third, twenty-fourth, twenty-fifth, twenty-sixth, twenty-seventh, twenty-eighth, twenty-ninth, thirtieth, thirty-first, thirty-second, thirty-third, thirty-fourth, thirty-fifth, thirty-sixth, thirty-seventh, thirty-eighth, thirty-ninth, fortieth, forty-first, forty-second, forty-third, forty-fourth, forty-fifth, forty-sixth, forty-seventh, forty-eighth, forty-ninth, fiftieth, fifty-first, fifty-second, fifty-third, fifty-fourth, fifty-fifth, fifty-sixth, fifty-seventh, fifty-eighth, fifty-ninth, sixtieth, sixty-first, sixty-second, sixty-third, sixty-fourth, sixty-fifth, sixty-sixth, sixty-seventh, sixty-eighth, sixty-ninth, seventieth, seventy-first, seventy-second, seventy-third, seventy-fourth, seventy-fifth, seventy-sixth, seventy-seventh, seventy-eighth, seventy-ninth, eightieth, eighty-first, eighty-second, eighty-third, eighty-fourth, eighty-fifth, eighty-sixth, eighty-seventh, eighty-eighth, eighty-ninth, ninetieth, ninety-first, ninety-second, ninety-third, ninety-fourth, ninety-fifth, ninety-sixth, ninety-seventh, ninety-eighth, ninety-ninth, one hundredth.

```

### Explanations

See Formatted Output to Character Streams.

* `(format t "<control string>" <arguments>)` formats the control string according to the (variadic) arguments and prints to standard output (because `t`)
* `(loop ...)` builds the list of integers from 1 to 100
* `~@( ... ~)` capitalizes the string returned by the inner control string
* `~{ ... ~}` iterates over the current argument and applies the inner formatting to each element
* Inside the iteration, everything that follows `~^` is *not* printed on the last iteration: this is used to add the comma-space separator *between* elements.
* `~R` outputs current argument as a cardinal
* `~:R` outputs current argument as an ordinal
* `~%` outputs a new line
* `~:*` reset the *current* argument to be processed as the previous one, which is used here to reuse the list of integers a second time.

Saved 2 bytes thanks to PrzemysławP.
> 28 votes

# Answer
# Pyth, ~~366~~ ~~342~~ 340 bytes

```
Lcbdj=Y", "++rhJy"one two three four five six seven eight nine"3+tJ+y"ten eleven twelve"+=Nm+d"teen"=by"thir four fif six seven eigh nine"sm+dm++d\-kJKy"twenty thirty forty fifty sixty seventy eighty ninety"+=H"one hundred"\.jY+rh=J++y"first second third"m+d=T"th"tPby"ninth"3+++tJy"tenth eleventh twelfth"+m+dTNsm++Pd"ieth"m++d\-kJK+H"th."

```

Live demo.

## 342-byte version:

```
Lcbdj", "++rhJy"one two three four five six seven eight nine"3+tJ+y"ten eleven twelve"+=Nm+d"teen"=by"thir four fif six seven eigh nine"sm+dm++d\-kJKy"twenty thirty forty fifty sixty seventy eighty ninety"+=H"one hundred"\.j", "+rh=J++y"first second third"m+d"th"tPby"ninth"3+++tJy"tenth eleventh twelfth"+m+d"th"Nsm++Pd"ieth"m++d\-kJK+H"th."

```

## 366-byte version:

```
Lcbd
j", "++"One"+tJy"one two three four five six seven eight nine"+y"ten eleven twelve"+=Nm+d"teen"y"thir four fif six seven eigh nine"sm+dm++d\-kJKy"twenty thirty forty fifty sixty seventy eighty ninety"+=H"one hundred"\.
j", "+"First"+++t=Jy"first second third fourth fifth sixth seventh eighth ninth"y"tenth eleventh twelfth"+m+d"th"Nsm++Pd"ieth"m++d\-kJK+H"th."

```
> 9 votes

# Answer
# PHP - 491 bytes

Small cheat here for the cardinals (I'm using the NumberFormatter class that comes default with PHP):

```
echo'One, ';$x=new NumberFormatter(0,5);for($i=1;$i++<100;)echo$x->format($i).($i>99?
'.':', ');echo"
";$y=[First,second,third,fourth,fifth,sixth,seventh,eighth,ninth,tenth,
eleventh,twelfth,thirteenth,fourteenth,fifteenth,sixteenth,seventeenth,eighteenth,nineteenth,
twentieth];for($z=[thirtieth,fortieth,fiftieth,sixtieth,seventieth,eightieth,ninetieth];
$j++<99;$q=floor($j/10),$w=$z[$q-2])echo$j<21?$y[$j-1]:($j%10?$x->format($q*10).'-'.
strtolower($y[$j%10-1]):$w),', ';echo'one hundredth.';

```

(added a few new lines for readability)
> 6 votes

# Answer
## PHP 5.3+, 195 bytes

That includes the newline character.

It's part of the `NumberFormatter` class, just like razvan's answer. Except I spell out both the cardinals and ordinals according to the ICU.

```
$f=numfmt_create(en,5);$g=clone$f;$g->setTextAttribute(6,'%spellout-ordinal');for($x=$y='',$i=1;$i++<100;){$x.=$f->format($i).($z=$i<=99?', ':'');$y.=$g->format($i).$z;}echo"One, $x.
First, $y.";

```

Related: https://stackoverflow.com/a/19411974/404623
> 6 votes

# Answer
# Oracle SQL 231 bytes

**SqlFiddleLiveDemo**

```
 SELECT 'O'||SUBSTR(LISTAGG(TO_CHAR(TO_DATE(level,'j'),'jsp'),', ')WITHIN GROUP(ORDER BY level),2)||'.','F'||SUBSTR(LISTAGG(TO_CHAR(TO_DATE(level,'j'),'jTHSP'),', ')WITHIN GROUP(ORDER BY level),2)||'.' FROM DUAL CONNECT BY level<101

```
> 4 votes

# Answer
# JavaScript ES6, ~~562~~ 464 bytes

Not even done golfing yet!

```
n=>(f=(a,b)=>Array(89).fill(a=btoa(a+`·§·,í*íË7èº»rÍø·,ìrÎÇ¯z{rÍè Ü³)Þ·,ó`).split`z`).map((l,i)=>i<1?b:i<20?a[i]:a[18+(i-i%10)/10]+'-'+a[i%10]).join`, `+', one hundred')(`¢w³·
3¶Þ{7èº¼ß÷³²,s±ëÞ7¢s)ÞÎ×§Íé^½éó·¥½ìí*íyéó~«µç§Íøµç§ÎÈ±µç§ÎÇ¯z{^z|Þmyéó)Þµç§ÎÜÜ³¶«·,ß¢êíË7â~Ü³²,mË;½éíË7¢rÎx§µì³`,'One')+`
`+f(`~*ì·;rÝÎØbÜß¢êí7â~Øs²,m;½éí7¢Øs)Þ¶íz{aÍé^½éí;pz[Þ¶í*íyéí7èº»^z{aÍøµç§¶ì^z{aÎÇ¯z{^z{aÍè ×Øs)Þµç§¶ó`,'First')+'th'

```

**If this doesn't work I might need to add a hexdump because of all the special characters** Please let me know if this is the case and I'll get to you by tomorrow.

If they are any typos also let me know.

Code in pastebin (Tested on Safari Nightly)

# Explanation

This may look like a bunch of garbled characters but it's actually pretty simple.

We start by generating the cardinals. This array is compressed using the `btoa` function.

```
['one', ..., 'eighteen', 'nineteen', 'twenty', 'thirty', ...,'ninety']

```

To loop through a "range" we use the following:

Now we generate an Array of length 89 using. The `...` is what uncompresses the array

```
Array(89).fill(...)

```

Then map through it, i is the index:

```
.map((l,i)=>

```

Now for the condition, `i < 1` or if it is the first item, we will use a capitalized version of one / first

```
i<1?b

```

Otherwise... if it is less than 20, we output eleven...nineteen

```
i<20?a[i]:

```

Otherwise... using `(i-i%10)/10` we get the last digit of the number. We add 18 to it to compensate for 1..19. We add a `-` and then add the last digit, or i%10

Finally, we add 'one hundred' to the very end because we don't.

We repeat this for both types of numbers and separate with a newline
> 3 votes

# Answer
# C++ ~~704~~ ~~642~~ ~~620~~ 602

No library usage other than `ostream` `operator<<()` for `char*`s.

```
#include<iostream>
char*q,a[]="|one|two|three|four|five|six|seven|eight|ni&u$Il%*twel&bthirte$Q(P#tif#j)/#k'L#|)y#r*4#s'9rst&>cond*5d)zh)gh)U#V)Ch)2h(}#V09$m0M$I0]'g0k)B0|*I#}1A+4$01f+y1u$$|+/nty+(y*`#X*3y)p#V)Ly))y(dyC5~hundred)Oie1o#|1c#}*E#s*a#t*}$&+9#|+T#|+uth",b[448],*s=a,*t=b;int i,j,k;auto p(int k){for(s=b;k--;)while(*s++);return s;}int main(){for(;k=*s++;)if(k>98)*t++=k<'|'?k:" "[k<'~'];else for(i=(k-35)*95+*s++-32,q=t-i/9,k=3+i%9;k--;)*t++=*q++;for(j=0;j<2;++j)for(i=1;b[1+126*j]^=32*(i<3),k=i<20?i:i%10,i<101;++i)std::cout<<p(40+!k*j*11+i/10)<<"-"[!k|i<20]<<p(j*20+k)<<", \0.\n"+i/100*3;}

```

Live version.

With some whitespace and some comments:

```
#include <iostream>

// Encoded as literal characters or offset/length pairs for previous runs of characters, LZ like
char *q, a[] =
             "|one|two|three|four|five|six|seven|eight|ni&u$Il%*twel&bthirte$Q(P#tif#j)/"
             "#k'L#|)y#r*4#s'9rst&>cond*5d)zh)gh)U#V)Ch)2h(}#V09$m0M$I0]'g0k)B0|*I#}1A+4$01f+y1u$$|"
             "+/nty+(y*`#X*3y)p#V)Ly))y(dyC5~hundred)Oie1o#|1c#}*E#s*a#t*}$&+9#|+T#|+uth",
         b[448], *s = a, *t = b;

int i, j, k;

// Find the kth null separated string in array b
auto p(int k) {
    for (s = b; k--;)
        while (*s++)
            ;
    return s;
}

int main() {
    // Decode the compressed 'primitives' we use to build up the output.
    for (; k = *s++;)
        if (k > 98)
            *t++ = k < '|' ? k : " "[k < '~'];
        else
            for (i = (k - 35) * 95 + *s++ - 32, q = t - i / 9, k = 3 + i % 9; k--;) *t++ = *q++;

    // Loop twice over numbers 1-100, building up output from the 'primitives' in our array
    for (j = 0; j < 2; ++j)
        for (i = 1; b[1 + 126 * j] ^= 32 * (i < 3), k = i < 20 ? i : i % 10, i < 101; ++i)
            std::cout << p(40 + !k * j * 11 + i / 10) << "-"[!k | i < 20] << p(j * 20 + k)
                      << ", \0.\n" + i / 100 * 3;
}

```

The compressed string is decoded from `a` into `b`:

```
|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|thirteen|fourteen|fifteen|
sixteen|seventeen|eighteen|nineteen||first|second|third|fourth|fifth|sixth|seventh|eighth|
ninth|tenth|eleventh|twelfth|thirteenth|fourteenth|fifteenth|sixteenth|seventeenth|
eighteenth|nineteenth|||twenty|thirty|forty|fifty|sixty|seventy|eighty|ninety|one~
hundred|||twentieth|thirtieth|fourtieth|fiftieth|sixtieth|seventieth|eightieth|
ninetieth|one~hundredth;

```

Without the newlines. During decompression the `|`s are replaced with `'\0'` and the `~`s are replaced with `' '` (quirk of the way the characters are encoded into printable ASCII). These 'primitive' strings are then looked up by index in the `b` array using the `p` function and used to assemble the output.

Compression is a simple LZ like scheme where characters are either encoded as literals or as a negative offset into the buffer and a run length (encoded into two characters) if a match of length \>=3 is found. The string could be compressed further using non-printable characters but I like my code to be copy and paste safe :)
> 3 votes

# Answer
# Vyxal `Hoj`, 98 bitsv2, 12.25 bytes

```
ɾ₍∆ċ∆oƛ‛, j¡\.+

```

Try it Online!

```
ɾ₍∆ċ∆oƛ‛, j¡\.+
ɾ                # H flag sets the stack to 100, so this makes a range [1,100]
 ₍               # Parallel apply the next two elements in a list
  ∆ċ∆o           # Nth Cardinal and Nth Ordinal (gotta love builtins)
      ƛ          # Map over the list of all cardinals and ordinals
       ‛, j      # Join by the two character string ", " where the second character is a space
           ¡\.+  # Convert to sentence case and add a period.
# Implicit output, the j flag prints the top of the stack joined by newlines, which formats the list of two strings into the desired output.

```

Created with the help of Luminespire.

Obviously non-competing.
> 2 votes

# Answer
# Javascript (ES6), 713

Similar to my second PHP submission on this question. (2444 - 713) / 2444 = 70.8% compression.

```
a=`Onez]cu^dP~Ntenz\`zHlvezmwgwjwkw{wqwpwHnQxZx]xcxux^xdxPx~xNmQXZX]XcXuX^XdXPX~XNforQbZb]bcbub^bdbPb~bNjQWZW]WcWuW^WdWPW~WNkQVZV]VcVuV^VdVPV~VN{QUZU]UcUuU^UdUPU~UNqQTZT]TcTuT^TdTPT~TNpQSZS]ScSuS^SdSPS~SNy.
FirstzaRMLKJI[ten}\`}Hlf}mGgGjGkG{GqGpGHnYx_xaxRxMxLxKxJxIx[mYX_XaXRXMXLXKXJXIX[forYb_babRbMbLbKbJbIb[jYW_WaWRWMWLWKWJWIW[kYV_VaVRVMVLVKVJVIV[{YU_UaURUMULUKUJUIU[qYT_TaTRTMTLTKTJTIT[pYS_SaSRSMSLSKSJSIS[yth.`,'eleven|`}|`z|twe|q}|{}|k}|j}|g}|pz|{z|kz|gz|one hundred|tyz|mdz|qtz|p~|q~|{~|k~|j~|m~|tie}|onez|nin}|twoz|fivez|firstz|teen|threez|secondz|for~|four|fif|twen~|six|thir|nine|eigh|, |seven|th, |ty-'.split('|').map((e,i)=>a=a.split('`GwHIJKLMNPduyQR~STUVWXYZ[]^_`cabgjxkmpqz{}~'[i]).join(e)),alert(a)

```

Fiddle
> 1 votes

# Answer
# Mathematica ~~415 391~~ 407

The cardinals are given by `IntegerName[n]`. The ordinals are derived from the cardinals.

```
s = StringRiffle; y = IntegerName; t = StringReplace;
k@n_ := If[(z = (TextWords["first second third a fifth a a a ninth,a, a twelfth a a a a a eighteenth a, twentieth"])[[n]]) == "a", y@n <> "th", z]
g@n_ := Module[{i = IntegerDigits[n], z}, z := y[Quotient[n, 10]*10];Which[n == 100, "one hundredth", n < 20, k[n], i[[-1]] == 0, t[z, "y" -> "ieth"], 3 > 2, z <> "-" <> k[i[[-1]]]]]
t[(s[y@Range@100 /. "one" -> "One", ", "] <> ".") <> s[g /@ Range@100 /. "first" -> "\nFirst", ", "] <> ".", "tt" -> "t"]

```

Output:

```
One, two, three, four, five, six, seven, eight, nine, ten, eleven, twelve, thirteen, fourteen, fifteen, sixteen, seventeen, eighteen, nineteen, twenty, twenty-one, twenty-two, twenty-three, twenty-four, twenty-five, twenty-six, twenty-seven, twenty-eight, twenty-nine, thirty, thirty-one, thirty-two, thirty-three, thirty-four, thirty-five, thirty-six, thirty-seven, thirty-eight, thirty-nine, forty, forty-one, forty-two, forty-three, forty-four, forty-five, forty-six, forty-seven, forty-eight, forty-nine, fifty, fifty-one, fifty-two, fifty-three, fifty-four, fifty-five, fifty-six, fifty-seven, fifty-eight, fifty-nine, sixty, sixty-one, sixty-two, sixty-three, sixty-four, sixty-five, sixty-six, sixty-seven, sixty-eight, sixty-nine, seventy, seventy-one, seventy-two, seventy-three, seventy-four, seventy-five, seventy-six, seventy-seven, seventy-eight, seventy-nine, eighty, eighty-one, eighty-two, eighty-three, eighty-four, eighty-five, eighty-six, eighty-seven, eighty-eight, eighty-nine, ninety, ninety-one, ninety-two, ninety-three, ninety-four, ninety-five, ninety-six, ninety-seven, ninety-eight, ninety-nine, one hundred.
First, second, third, fourth, fifth, sixth, seventh, eighth, ninth, tenth, eleventh, twelfth, thirteenth, fourteenth, fifteenth, sixteenth, seventeenth, eighteenth, nineteenth, twentieth, twenty-first, twenty-second, twenty-third, twenty-fourth, twenty-fifth, twenty-sixth, twenty-seventh, twenty-eighth, twenty-ninth, thirtieth, thirty-first, thirty-second, thirty-third, thirty-fourth, thirty-fifth, thirty-sixth, thirty-seventh, thirty-eighth, thirty-ninth, fortieth, forty-first, forty-second, forty-third, forty-fourth, forty-fifth, forty-sixth, forty-seventh, forty-eighth, forty-ninth, fiftieth, fifty-first, fifty-second, fifty-third, fifty-fourth, fifty-fifth, fifty-sixth, fifty-seventh, fifty-eighth, fifty-ninth, sixtieth, sixty-first, sixty-second, sixty-third, sixty-fourth, sixty-fifth, sixty-sixth, sixty-seventh, sixty-eighth, sixty-ninth, seventieth, seventy-first, seventy-second, seventy-third, seventy-fourth, seventy-fifth, seventy-sixth, seventy-seventh, seventy-eighth, seventy-ninth, eightieth, eighty-first, eighty-second, eighty-third, eighty-fourth, eighty-fifth, eighty-sixth, eighty-seventh, eighty-eighth, eighty-ninth, ninetieth, ninety-first, ninety-second, ninety-third, ninety-fourth, ninety-fifth, ninety-sixth, ninety-seventh, ninety-eighth, ninety-ninth, one hundredth.

```
> 1 votes

# Answer
# JavaScript (ES6), 480

```
/*TEST: redirect console output to snippet body */ console.log=x=>O.innerHTML=x

// Not a function, as a complete program is requested
b=x=>btoa(x).split`/`;
Z=i=>z[i]||z[i-8]||z[i-18];
y=b("ýø«²ßìyÊ'wûa·ýøÿÿÞ)ÿÿûpzWÿÿÿÿÿÿÿ");
z=b("þÞþÜ(þØkyïß¢êÿ~+ÞþÈ±þÇ¯zÞmþx§{û^÷¥z÷§þÜ÷¿¶«ÿ÷âÿÿz(!ÿûpzÿ~ÿÿÿÿ");
o=(z.map((v,i)=>i<20?i<13?v:(v||z[i-10])+'teen':z[S='slice'](0,10).map(d=>Z(i)+(d?'ty-'+d:'ty')))+`,${h='one hundred'}.\nF`).split`,`;
q=y.map((v,i)=>i<4?v:`${v||o[i]}th`);
q=z.map((v,i)=>i<20?' '+q[i]:q[S](0,10).map(d=>' '+Z(i)+(d?'ty-'+d:'tieth')));
console.log('O'+o.join`, `[S](3)+`${q}, ${h}th.`[S](4))

// INFO: z uncompressed is [,one,two,three,four,five,six,seven,eight,nine,ten,eleven,twelve,thir,,fif,,,eigh,,twen,,for,,,,,]
// INCO: y uncompressed is [,first,second,third,,fif,,,eigh,nin,,,twelf,,,,,,,,,]
```

```
#O { white-space: pre-wrap }
```

```
<pre id=O></pre>
```
> 1 votes

# Answer
# PHP - 842 bytes

Omitting regular PHP starting and ending tags, compression is 1 - 842/2445 = 65.6%

Basically getting the output of `base64_encode(gzdeflate($input, 9));` and reversing the operations. Obviously, if I chose to output in pure 8-bit vs. base-64, it would be 25% smaller, but at the risk of running into escape or non-printable characters.

```
echo gzinflate(base64_decode('VZRdcuIwEITfcwoOQHKMfd1DBGnlKspUEYfEt1+rf2bGL6gbkLplS9/ftV0v28/j+BjPduj++H4en8vr0F/L7/HRXm29Xtryb2zXy7pgAr6585ftp93nv7exPLc2v5lrSC2d4lhKYk6ixJJQc1WqY7F12z2+P1gPmi2lWVaOnW1QXQY7sI6602k/ctrW3MHuUeHUekTUCqdTuMzyyl8YLq1wOofTMbw/kI2B0ZRIlvQrylxpxFIjVZKhNMqkUeTxdnYNioRkJKUiYXw2ekZCM5JSkTCOhGHkPAe7BkZSIlKSkTSMlPahdKQkI2kUSaNInLg9hGJlGGyjaFmF2zFeLu9GqSDrErKsgS93jywhjQ7WrCDHBjYoIIN863JFI12O4bhgu0eGSyPcmuFyDLdBuAzCrRkuVzAR4UfaZXyvt2e7fbz9WZ5feDafj/XGK3ATMQaPyuDrG36AQ3sZWHYOm769+/eJIEw0g7CWKOR1JUWiXL+VDGnzSGuv29JCzkeBLQRWtBOTCRsqZDrN7MVplxVPxXvPSajYoNoYOWxjzuRzLW0SVaeZvTi3KbwqPtoEsviIXcYcQhfTh1XMLr3oWsSzehrVKABL6xLBML9adRCY2EE4UgfBjB0CZnVWT+MOSbS00cFQ85liB5OKh1x8YgfTDR2SbnVWT+MrkIhL6w5BuTzMahHI0mV7nY5q4o5dCu7Os3u1p0tZO1XqjRP24l6xVnAMrQJeLBX8Q6fCv9PMXpwKVQgW7zrJwbjZbBNgQ5ugGdsEENGmAPE0sxenNpWKxReCtWxTyLiNj7f/'));

```
> 0 votes

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


title: Output the longest list

text:
# Question
Title: Output the longest list
In this challenge you will take a non-empty (finite) list of (possibly infinite) lists of positive integers, and your task is to output the longest one. An infinite list is longer than a finite list of any length, and any two infinite lists are equally long.

You're guaranteed that there won't be any ties for longest between two distinct lists. That is, if two lists are tied for longest, whether they are finite or infinite, they will be equal so it won't matter which one you output.

Standard rules apply for outputting an infinite list.

This is . The goal is to minimize the size of your source code as measured in bytes.

A useful note from xnor:

> I think it's important for solvers to realize that you have to be outputting list entries as you go in some situations. There's no hope to find which list is longest then fully output it.

## Test cases

```
[1,1,1,1,1,1,1,1]
[2,2,2]
[]
=>
[1,1,1,1,1,1,1,1]

```

```
[1,1,1,1,1,1,1,1]
[2,2,2,9,9,9,9,9,9]
[]
=>
[2,2,2,9,9,9,9,9,9]

```

```
[1,2,3]
[1,2,3]
[2,4]
=>
[1,2,3]

```

```
[1,2,3,4,5,6,7,8,9,10,11,12,...]
[1,2,3,4,5,6,7,8,12]
[9,2]
=>
[1,2,3,4,5,6,7,8,9,10,11,12,...]

```

```
[2,6,4,5,6,7,8,9,10,11,12,13,...]
[2,6,4,5,6,7,8,9,10,11,12,13,...]
=>
[2,6,4,5,6,7,8,9,10,11,12,13,...]

```

```
[2,6,4,5,6,7,8,9,10,11,12,13,...]
[2,6,4,5]
[9,8,12,3]
=>
[2,6,4,5,6,7,8,9,10,11,12,13,...]

```

```
[1,2,3,4,5,6,7,8,9,10,11,12,...]
[1,2,3,4,5,6,7,8,9,10,11,12,...]
[1,2,3,4,5,6,7,8,12]
[9,2]
=>
[1,2,3,4,5,6,7,8,9,10,11,12,...]

```

---

The following cases are examples of undefined behavior, you may do whatever you wish including looping forever.

```
[1,2,3]
[1,2,3]
[2,6,7]

```

```
[2,4,6,8,10,12,14,16,...]
[1,3,5,7,9,11,13,15,...]

```

# Answer
> 8 votes
# Python, ~~74~~ 74 bytes

```
f=lambda i,n,m=0:1<len(r:={x(n)for x in i if x(m)})and f(i,n,m+1)or sum(r)

```

Attempt This Online!

Previous version had a bug

Potentially infinite lists are represented as functions that take an index and return the value at that index. If the index is out of bounds the function returns a zero.

# Answer
> 6 votes
# Haskell, ~~67~~ 58 bytes

```
foldl1(#)
(a:b)#(x:y)|a==x=a:b#y
c#z|(1<$c)>(1<$z)=c|0<1=z

```

Attempt This Online!

*-9 thanks to AnttiP mixing pattern failure and guard failure*

Test harness truncates to run all the cases in one go, but it can be run infinitely.

Since the algorithm may be non-obvious and not everyone can read Haskell:

## Explanation

```
foldl1 (#)

```

The function submission operating on a list of lists just reduces the list by a function of two lists, the infix operator `#`. (Since the input is guaranteed non-empty, `foldl1` won't error.)

```
(a:b) # (x:y)
  | a == x = a : (b # y)

```

The critical part for handling duplicate infinite lists: if the first element of both lists is the same, then put that element in the output list and recur on the remainders of both.

```
c # z
  | (1 <$ c) > (1 <$ z) = c
  | otherwise = z

```

And here's the part that actually takes the longest list, if the previous clause failed. Since one of the lists can still be infinite, an actual length comparison is out of the question, but replacing every element of both lists with 1, a lexicographic comparison will terminate as soon as it reaches the point where one list ends and not the other.

# Answer
> 5 votes
# Ruby, ~~124~~ 123 bytes

Input is an array of `Enumerator`s. Zips answers together until enough of them reach the ends of their sequences that the ones that remain are all equivalent, prints that, and keeps going.

```
->a{g=->{a.map{_1.next rescue p}};t=a;(t=g[]
t=t.zip(g[]).map{_2&&[*_1,_2]}while(t&t-[p])[1]
r,=t-[p];p *r)while(t-[p])[0]}

```

Attempt This Online!

##### Explanation

```
->a{                              # Lambda definition
    g=->{a.map{_1.next rescue p}} # Lambda to take the next element of each Enumerator
                                  #  If it throws StopIteration, output nil instead
    t=a                           # Set t to a as dummy value for while loop
    (                             # Start of instructions to loop over
      t=g[]                       #  Overwrite t with the next elements
                                  #  Start of a one-line while loop
      t=                          #   Set t to
        t.zip(g[])                #    t zipped with the next elements
                                  #    (will look like this: [[1,2,3],4])
         .map{                    #    Map over the zipped result
              _2                  #     If next element is nil, return just that
                &&                #     Otherwise,
                  [*_1,_2]        #     Combine the elements together
         }
       while(t&t-[p])[1]          #  Loop while at least 2 unique non-nil elements of t
                                  #  Now we know which elements can be safely printed
      r,=t-[p]                    #  Set r to first non-nil element of t
      p *r                        #  Print all such elements one at a time
    )while(t-[p])[0]              # Loop while at least one element of t is not nil
}

```

### Ruby, 20 bytes, technically against the spirit of the challenge

Input is an array of specific kinds of `Enumerator::Lazy` objects constructed from `Array`s or `Range`s, but not created manually with `Enumerator.new`. Returns an `Enumerator::Lazy` that can be iterated through later to print results.

Finite arrays can be written simply as `[...].lazy`. (The function also accepts the arrays directly, but for the sake of the exercise everything is passed in uniformly so no class-checking is done.)

Infinite arrays take the form of `(0..).lazy.map{...}`. For example, even numbers can be represented as `(0..).lazy.map{|i|i*2}`, the infinite array `[2,6,4,5,6,7,8,9,10,11,12,13,...]` in the examples can be written as `(0..).lazy.map{|i|i==1?6:i+2}`, and something more complicated like the Fibonacci sequence can use some custom function, e.g. `(0..).lazy.map{|i|SomeFunction(i)}`

With this method, infinite arrays will have a `size` of infinity, and finite arrays will have a `size` equal to their length. (This is why I'm not allowing enumerators constructed with `Enumerator.new`, because they have a `size` of `nil`.)

```
->a{a.max_by &:size}

```

Attempt This Online!

# Answer
> 2 votes
# Python, 146 bytes

*Uses generators for IO, sadly much longer than the other Python solution*

```
def f(L):
 while(Q:=[[[],l]for l in L]):
  while(Q:=[(k+[q],l)for k,l in Q if(q:=next(l,0))])*(len({str(k)for k,l in Q})>1):0
  yield from Q[0][0]

```

Attempt This Online!

# Answer
> 1 votes
# , 92 bytes

```
f=\(L,n,m=1,g=\(i)sapply(L,\(f)f(i)))`if`(sum(table(x<-g(n)[!!g(m)])|1)>1,f(L,n,m+1),max(x))

```

Attempt This Online!

Based on AnttiP's answer.

Takes input as list of functions and index (1-based) of the output sequence. Functions take index and return sequence value or 0 if it's out of bounds.

# Answer
> 1 votes
# , ~~88~~ 76 bytes

*Edit: -10 bytes by stealing some ideas from pajonk's R answer.*

```
\(l,g=\(n)sapply(c(l,l),\(f)f(n)))\(i){while(sd(x<-g(i)[g(T)>0]))T=T+1;x[1]}

```

Attempt This Online!

Input as a list of functions that each return the `i`-th element of a (possibly finite, possibly infinite) list. Output is the function corresponding to the longest list.

This could be 2 bytes shorter if it's re-arranged to take an additional argument, `i`, and directly output the `i`-th element of the longest list indexed by the input functions (the I/O-format used by pajonk's R answer).

---

Original, **86-byte** approach is here.

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

```
k=>f=(x,i=0)=>new Set(y=x.flatMap(c=>1/c(i)?c(k):[])).size>1?f(x,i+1):y[0]

```

Try it online!

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


title: Print 100 digits of π

text:
# Question
Title: Print 100 digits of π
Your challenge is to print any 100 consecutive digits of π. You must give the index at which that subsequence appears. The 3 is not included.

For example, you could print any of the following:

* `1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679` (index 0)
* `8214808651328230664709384460955058223172535940812848111745028410270193852110555964462294895493038196` (index 100)
* `4428810975665933446128475648233786783165271201909145648566923460348610454326648213393607260249141273` (index 200)

Output may be as a string / digit list / etc.

To ensure answers actually produce known digits of pi, all answers must be verifiable through the Pi API (note: This API counts the 3, your answer should not).

This is , shortest wins!

# Answer
> 10 votes
# JavaScript (ES11), 53 bytes

Starts at index 0. Returns a BigInt.

```
f=(x=375n*10n**97n,k=3n)=>x?x/k+f(x*k++/k++/4n,k):82n

```

Try it online!

The underlying formula is:

$$\pi-3=\sum\_{n=1}^{\infty}\frac{3}{4^n}\left(\prod\_{k=1}^{n}\frac{2k-1}{2k}\right)\times\frac{1}{2n+1}$$

(also used in my answer to this other challenge)

# Answer
> 9 votes
# Trivial answers

This is mostly for answers that use a built-in arbitrary-precision pi constant, or a built-in that generates digits of pi.

# Python 3, 49 bytes

```
from mpmath import*
mp.dps=102
print(str(pi)[3:])

```

Try it online!

# 05AB1E, 5 bytes

```
žs¦т£

```

Try it online!

# Vyxal `H`, 18 bitsv2, 2.25 bytes

```
ɾ∆i

```

Try it Online!

### Explained

```
ɾ∆i  # The H flag presets the stack to 100
ɾ    # For each number in the range [1, 100]:
 ∆i  # Push the nth digit of pi, 0 indexed, hence avoiding the `3`

```

Created with the help of Luminespire.

# , 12 bytes

```
ØP%1µ×1ȷ100Ḟ

```

Try it online!

# Wolfram Language (Mathematica), 31 bytes

```
Print@@@RealDigits[Pi-3,10,100]

```

Try it online!

# Charcoal, 13 bytes

```
Ｐ-×φψ¤≕PiＴ¹⁰⁰

```

Try it online! Link is to verbose version of code. Starts at the `997`th digit of `π`. Explanation:

```
Ｐ-×φψ

```

Make space for `1999` characters in the canvas.

```
¤≕Pi

```

Fill those characters with the digits of `π`, including the leading `3.`, so `1997` decimals.

```
Ｔ¹⁰⁰

```

Take only the `100` digits starting at the `997`th.

# Ruby, 53 bytes

`BigMath.PI` guarantees accuracy for a number of digits up to its argument, but it outputs more digits than that (requiring truncation), and it just so happens that `BigMath.PI(99)` is still accurate enough for the problem, saving a byte over `BigMath.PI(101)`.

```
require'bigdecimal/math'
p BigMath.PI(99).to_s[3,100]

```

Attempt This Online!

# Answer
> 7 votes
# Charcoal, 32 bytes

```
≔⊗Ｘχ¹⁰⁰θ≔θηＦφ≔⁺θ÷×η⁻φι⊕⊗⁻φιη✂Ｉη¹

```

Try it online! Link is to verbose version of code. Explanation: Calculates the first `1001` terms of `2 + 1/3*(2 + 2/5*(2 + 3/7*(2 + 4/9*(2 + ...))))`.

```
≔⊗Ｘχ¹⁰⁰θ

```

Calculate `2e100` as an integer.

```
≔θη

```

Start with that as an approximation to `1e100π`.

```
Ｆφ

```

Repeat `1000` times.

```
≔⁺θ÷×η⁻φι⊕⊗⁻φιη

```

Calculate the next approximation to `π`.

```
✂Ｉη¹

```

Output without the leading `3`.

# Answer
> 5 votes
## Python2, 91 bytes

```
print 0x296e417278c91bbebb472cab663a71405eef415a7751d7b251874642e34fa5406ba944ce62eb559eff7

```

Prints the first 100 digits starting at index 0.

# Answer
> 4 votes
# Octave, 24 bytes

Prints 100 digits of pi, starting at index 2

```
char(vpa(pi,102))(4:end)

```

Try it online!

# MATLAB, 30 28 bytes

```
t=char(vpa(pi,102));t(4:end)

```

---

For both versions, this first uses variable precision calculation to work out Pi exactly to 102 *digits* (not decimals, it includes the `3`).

Then it converts the result to a character vector and removes the string prefix `'3.1'` to leave exactly 100 characters. For the Octave version we can index directly into the returned value from the `char()` function, while MATLAB we have to save to a variable then truncate.

```
ans =
    4159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798

```

Notes:

* We have to use 102 instead of 101 (3 + 100 decimals), because the `vpa` function rounds the final digit. If we used 101 the final digit would be incorrect due to rounding.
* Based on this meta post, when output is allowed to return a string, the `ans=` is acceptable.

# Answer
> 3 votes
# Kamilalisp, 21 bytes

```
↓ 2\⍫← \○⊢*(fr 101)\π

```

Attempt This Online!

# Answer
> 3 votes
# Java 10, ~~176~~ 171 bytes

```
v->{var t=java.math.BigInteger.TEN.pow(100).shiftLeft(1);var p=t;for(int i=330;i>0;)p=t.add(p.multiply(t.valueOf(i)).divide(t.valueOf(i-~i--)));return(p+"").substring(1);}

```

Based on my answer for the related challenge of outputting the first 500 digits of pi.
-5 bytes thanks to *@Neil* by reverting the algorithm

Try it online.

# Answer
> 3 votes
## Python 3, 165 bytes

(index 0)

```
s=''
a=10000
e=0
f=[a//5]*365
for c in range(364,0,-14):
 d=0
 for b in range(c,0,-1):
  d=d*b+f[b]*a;g=2*b-1;f[b]=d%g;d//=g
 s+=f"{e+d//a:04}";e=d%a
print(s[1:101])

```

Try it in SageMathCell (with verification).

This algorithm only uses integer arithmetic. It was derived from obfuscated C code by Dik T. Winter, but I've modified it a bit over the years. Dik's version was a bit more compact, and can generate hundreds of digits, but it eventually produces erroneous output due to integer overflow, which isn't an issue in Python. OTOH, this algorithm gets a bit sluggish for large numbers of digits, due to the O(n^2) inner loop.

Of course, for serious pi digit generation, there are various lovely AGM based algorithms that converge quadratically. The Borwein brothers found several, but I like the Gauss / Brent / Salamin https://stackoverflow.com/a/26478803/4014959

# Answer
> 3 votes
# 05AB1E, ~~45~~ 44 bytes

```
8₂;×•13CÒ₃Sˆ`£û‰ñêˆǝd‰Ž¿Ð†₆{©«62—lÚÌ”ß°dZγ•J

```

Try it online! Starts at index \\$2{,}164{,}164{,}669{,}331\\$.

# Answer
> 2 votes
# Vyxal, 70 bitsv2, 8.75 bytes

```
u∆C₁⇧ḞḢḢṪ

```

Try it Online!

Calculates pi through \\$cos^{-1}(-1)\\$ and then formats to 100 decimal places.

## Explained

```
u∆C₁⇧ḞḢḢṪ
u∆C        # arccos(-1)
   ₁⇧Ḟ     # Formatted to 102 decimal places
      ḢḢ   # Remove the `3.`
        Ṫ  # and the last digit. The last digit is needed for rounding purposes.

```

Created with the help of Luminespire.

# Answer
> 1 votes
## Python 3, 256 bytes

This version computes pi using an accelerated version of Archimedes' algorithm for `pi = 4*arctan(1)`.

```
m=338
M=1<<m
def s(y,x=M):
 y<<=m;u=x
 while u<0 or u>1:u=(x//2+y)//x-x;x+=u>>1
 return x
a=b=x=M
g=s(2*M)
d=[a]
for i in range(16):
 a=(a+g)>>1;p,d=d,[a];q=0
 for u in p:q+=2;d+=[d[-1]-(u>>q)]
 b-=b>>q;g=s(a*g>>m,g)
print(str(b*x//d[-1]*4*10**100>>m)[1:])

```

Try it in SageMathCell

This code implements binary fixed point arithmetic using Python integers. The core arctan algorithm was devised by Bille Carlson, see Carlson, B. C. An Algorithm for Computing Logarithms and Arctangents, Mathematics of Computation, Apr 1972.

This algorithm rapidly calculates any of the standard inverse circular and hyperbolic functions. It even handles complex arguments (assuming the sqrt function does). Here's a non-golfed demo that computes `pi = 10*arcsin((sqrt(5)-1)/4)`.

This algorithm is very similar to the AGM (arithmetic-geometric mean), but it updates the two core terms `a` and `g` sequentially instead of in parallel. So it's sometimes referred to as the fake AGM. It's also known as Borchardt's modified AGM algorithm. The Borwein brothers pointed out that it is, in fact, the same algorithm Archimedes used to iteratively subdivide a polygon.

Carlson's innovation is to apply Richardson series acceleration, which speeds up the convergence considerably. It's not as fast as a true AGM, however it's quite efficient for high precision calculation because it only uses one non-trivial division. (The square root can be also be implemented to avoid non-trivial divisions, using the Quake-style 1/sqrt algorithm).

For further details on algorithms related to pi and the AGM, please see The Borwein brothers, Pi and the AGM by Richard P. Brent.

FWIW, Carlson also developed and analysed a suite of true AGM algorithms for computing elliptic integrals and functions, and those algorithms can (of course) handle circular & hyperbolic functions. See Numerical computation of real or complex elliptic integrals

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


title: List all words following a pattern

text:
# Question
Title: List all words following a pattern
This challenge is to list out all possible words which are built from a pattern of syllables. Words are composed by joining syllables together. Syllables are composed of a number of vowels with some number of consonants optionally to the left and/or right. Your code should take in:

* a list of consonants
* a list of vowels (the vowels and consonants may be assumed to be mutually exclusive)
* a syllable structure in some format you define; the format must contain information describing:
    + the minimum and maximum number of left consonants ( \>= 0)
    + the minimum and maximum number of vowels ( \>= 1)
    + the minimum and maximum number of right consonants. ( \>= 0)
* A minimum and maximum number of syllables ( \>= 1)

Examples:

```
Consonants: tk
Vowels: au
Structure: (c)cv(c) (means: 1 to 2 left consonants, 1 vowel, 0 to 1 right consonants)
Syllables: 1
Output: ta tat tak tu tut tuk ka kat kak ku kut kuk tta ttat ttak ttu ttut ttuk tka tkat tkak tku tkut tkuk kta ktat ktak ktu ktut ktuk kka kkat kkak kku kkut kkuk

Consonants: 'b', 'c', 'd'
Vowels: 'e'
Structure: 1, 1, 1, 2, 0, 0 (means: 1 left consonant, 1 to 2 vowels, 0 right consonants)
Syllables: 1, 2
Output: be bee ce cee de dee bebe bebee bece becee bede bedee beebe beebee beece beecee beede beedee cebe cebee cece cecee cede cedee ceebe ceebee ceece ceecee ceede ceedee debe debee dece decee dede dedee deebe deebee deece deecee deede deedee

Example of using a single string as input("4|P|T|C|K|2|A|I||vvV||ss")
Consonants: "4|P|T|C|K|"
Vowels: "2|A|I|"
Structure: "|vvV||" (means: 0 left consonants, 2 to 3 vowels, 0 right consonants)
Syllables: "ss" (means: 2)
Output: AAAA;AAAI;AAIA;AAII;AAAAA;AAAAI;AAAIA;AAAII;AAIAA;AAIAI;AAIIA;AAIII;AIAA;AIAI;AIIA;AIII;AIAAA;AIAAI;AIAIA;AIAII;AIIAA;AIIAI;AIIIA;AIIII;IAAA;IAAI;IAIA;IAII;IAAAA;IAAAI;IAAIA;IAAII;IAIAA;IAIAI;IAIIA;IAIII;IIAA;IIAI;IIIA;IIII;IIAAA;IIAAI;IIAIA;IIAII;IIIAA;IIIAI;IIIIA;IIIII;AAAAAA;AAAAAI;AAAAIA;AAAAII;AAAIAA;AAAIAI;AAAIIA;AAAIII;AAIAAA;AAIAAI;AAIAIA;AAIAII;AAIIAA;AAIIAI;AAIIIA;AAIIII;AIAAAA;AIAAAI;AIAAIA;AIAAII;AIAIAA;AIAIAI;AIAIIA;AIAIII;AIIAAA;AIIAAI;AIIAIA;AIIAII;AIIIAA;AIIIAI;AIIIIA;AIIIII;IAAAAA;IAAAAI;IAAAIA;IAAAII;IAAIAA;IAAIAI;IAAIIA;IAAIII;IAIAAA;IAIAAI;IAIAIA;IAIAII;IAIIAA;IAIIAI;IAIIIA;IAIIII;IIAAAA;IIAAAI;IIAAIA;IIAAII;IIAIAA;IIAIAI;IIAIIA;IIAIII;IIIAAA;IIIAAI;IIIAIA;IIIAII;IIIIAA;IIIIAI;IIIIIA;IIIIII

duplication test case:
Consonants: k
Vowels: a
Structure: cVc (means: 0 to 1 left consonants, 1 vowel, 0 to 1 right consonants)
Syllables: 2
Output:
kakkak
kakka
kakak
kaka
kaak
kaa
akkak
akka
akak
aka
aak
aa
(note that there is only one of each aka, kaka, akak, and kakak; you get two if you treat ak a and a ka separately)

```

Duplicate words should be removed. The order and format of the words does not matter, as long as they can be told apart (ie, don't output one long unbroken string of letters). The max and min of the left and right consonants is any non-negative integer; the max and min of the vowel and the number of syllables is any positive integer. The set of consonants will never have tokens from the set of vowels and vice versa. There will always be at least one consonant and one vowel provided in the input. You may define the format and order of the inputs. The words of the output must be built from the same characters as those entered in the input.

, so shortest code wins. To be considered valid, solutions must at least accept English vowels and consonants as valid vowels and consonants (having only upper or lower case is still valid), and must come up with a complete and correct word list for any valid input.

# Answer
> 2 votes
# JavaScript (V8), 139 bytes

Input format: `([[consonants], [vowels]], min_syllables, max_syllables, [[min, max], [min, max], [min, max]])`

Prints all valid words.

```
(a,p,q,m)=>(g=(s,k=0,i=0,j=0)=>i<3?j<m[i][j<m[i][0]||g(s,k,i+1),1]&&a[i&1].map(c=>g(s+c,k,i,j+1)):g[++k<q&&g(s,k),s]||k<p||print(g[s]=s))``

```

Try it online!

# Answer
> 2 votes
# Vyxal, 24 bytes

```
∞¨Z$÷ṡv↔f;Π£÷ṡƛ¥ÞẊvṅǍ;fU

```

Try it Online!

Takes input as

```
[consonants, vowels]
[min, max]: left-consonants, vowels, right-consonants
[min-syllables, max-syllables]

```

Explanation:

```
∞¨Z$÷ṡv↔f;Π£÷ṡƛ¥ÞẊvṅǍ;fU
∞                         # Palindromise [constants, vowels] (1. input) -> [constants, vowels, constants]
 ¨Z      ;                # Zip that with [min, max] (2. input) and map for each item:
   $÷ṡ                    # - Create a range from min to max
      v↔f                 # - For each number n in range, push all combinations of constants/vowels with length n
          Π               # Cartesian product over [left-constant, vowel, right-constant]-combinations
            ÷ṡ            # Create range from syllables-min to syllables-max (3. input)
           £  ƛ¥ÞẊv  ;    # For each number n in range, push cartesian product of combinations-list with itself n times
                  vṅǍ     # Merge each sublist
                      fU  # Flatten and remove duplicates

```

Created with the help of Luminespire.

# Answer
> 2 votes
# Charcoal, 58 bytes

```
Ｆ…·ＮＮ⊞υ×ιζＦυ¿ΣιＦ⌊ι«≔⪪⎇‹κ3εδ¹ζＦ№24κ⊞ζωＦ⁻Ｅζ⭆ι⎇⁼ξ⌕ικλνυ⊞υλ»⟦ι

```

Try it online! Link is to verbose version of code. See below for input format. Explanation:

```
Ｆ…·ＮＮ

```

Input the minimum and maximum number of syllables and loop from one to the other (inclusive).

```
⊞υ×ιζ

```

Repeat the syllable structure by the number of syllables and push the result to the predefined empty list. (In Charcoal, `Divide` splits a string, so `Multiply` joins a list with a string, rather than vectorised repeating the string.)

```
Ｆυ

```

Loop over the structures and words that will be generated below.

```
¿Σι

```

If this is a structure or partial word, then:

```
Ｆ⌊ι«

```

Get a digit from the structure.

```
≔⪪⎇‹κ3εδ¹ζ

```

Choose consonants or vowels depending on whether the digit is less than `3`.

```
Ｆ№24κ⊞ζω

```

If the digit is even then add an empty string to make the letter optional.

```
Ｆ⁻Ｅζ⭆ι⎇⁼ξ⌕ικλνυ⊞υλ

```

Replace the digit with each character in the list and push any new results to the predefined empty list for further processing.

```
»⟦ι

```

Otherwise, output the word.

The program takes five inputs:

1. The minimum number of syllables
2. The maximum number of syllables
3. A string describing the syllable format
4. A string of consonants
5. A string of vowels.

The syllable format is a string of digits from `1` to `4`, where they have the following meanings:

1. A consonant
2. An optional consonant
3. A vowel
4. An optional vowel

# Answer
> 1 votes
# Zsh, ~~67~~ 65 bytes

*saved **2 bytes** by moving everything into `eval`*, so no `$=shwordsplit` is needed.

```
eval "c=($1)
C=('' $1)
v=($2)
V=('' $2)
s=($3)
S=('' $3)
echo $4"

```

Attempt This Online! ~~Attempt This Online!~~

~~Ab~~uses flexible structure format to take input of the form `$^c$^C$^v$^V$^c`/`$^s$^S`, which when `eval`'d does cross product concatenations of the list elements.

`echo` is needed because `<<<` does not permit expansions which result in lists.

The ATO link enables tracing in the function for your convenience.

# Answer
> 1 votes
# Ruby, ~~114 ...~~ 82 bytes

```
->c,v,*s{[*?a..?z*s[7]*s.sum].grep /^(#{[k=?[+c+?],?[+v+?],k,?),?$]*"{%d,%d}"%s}/}

```

Try it online!

Works only in theory, takes forever to complete.

TIO link contains a hardcoded speedup version.

# Answer
> 1 votes
# Excel, ~~324~~ 312 bytes

`z` defined within Name Manager as:

```
    =LAMBDA(a,b,c,d,e,
        IF(
            OR(d,e),
            IF(
                c=e,
                IF(d,a,VSTACK(a,"")),
                LET(
                    f,VSTACK(
                        a,
                        z(TOCOL(a&"|"&TOROW(b)),b,c+1,d,e)
                    ),
                    FILTER(f,1+LEN(f)-LEN(SUBSTITUTE(f,"|",""))>=d)
                )
            ),
            ""
        )
    )

```

`(162 bytes)`

Within the worksheet:

```
=LET(
    g,A1#,
    h,"|",
    i,SUBSTITUTE(
        TOCOL(
            TOROW(
                z(g,g,1,C1,C2)&h&TOROW(z(B1#,B1#,1,E1,E2))
            )&h&z(g,g,1,D1,D2)
        ),
        h,
        ""
    ),
    UNIQUE(SUBSTITUTE(z(i,i,1,F1,F2),h,""))
)

```

`(150 bytes)`

* Consonant and vowel lists are spilled, vertical ranges `A1#` and `B1#` respectively.
* Left consonant min and max in `C1` and `C2` respectively.
* Right consonant min and max in `D1` and `D2` respectively.
* Vowel min and max in `E1` and `E2` respectively.
* Syllable min and max in `F1` and `F2` respectively.

# Answer
> 1 votes
# PHP, 401 bytes

(surely I can do better than that!?!)

a recursive generator
parameters:

* consonants (array)
* vowels (array)
* structure (array): V for vowels, C for consonants; lower case for optional and upper case for mandatory
* minimum number of syllables (int)
* maximum number of syllables (int)

usage: `foreach(f($c,$v,$s,$min,$max)as$w)echo "$w ";`

```
function c($a){if($a){if($u=array_pop($a))foreach(c($a)as$p)foreach($u as$v)yield$p+[count($p)=>$v];}else yield[];}function f($c,$v,$s,$y,$x,$r=NULL){static$z;is_null($r)&&$z=[];$x--;$y&&$y--;foreach(c(array_map(function($h)use($c,$v){return${strtolower($h)}+($h>'Z'?[-1=>'']:[]);},$s))as$b){$w=$r.implode($b);$y||!$w||in_array($w,$z)||yield$w;$z[]=$w;if($x)foreach(f($c,$v,$s,$y,$x,$w)as$w)yield$w;}}

```

Try it online

## breakdown:

(my cartesian generator is explained at https://stackoverflow.com/a/39174062/6442316)

```
// function to build cartesian product
function c($a){if($a){if($u=array_pop($a))foreach(c($a)as$p)
foreach($u as$v)yield$p+[count($p)=>$v];}else yield[];}

// function f builds one syllable, then recurses
function f($c,$v,$s,$y,$x,$r=NULL)
/*
    $c: array consonants
    $v: array  vowels
    $s: array syllable structure
    $y: int syllables min
    $x: int syllables max
    for recursions:
    $r:string word so far
the first three parameters should be string, but with arrays I can spare two str_split calls
*/
{
    static$z;
    is_null($r)&&$z=[]; // if new call, empty yielded words
    $x--;$y&&$y--; // decrease (remaining) syllable counts
    // loop through cartesian product of possible syllables:
    foreach(c( // create cartesian product over ...
        array_map(function($h)use($c,$v){ // map structure array -> possible letters
            return${strtolower($h)} # $$c or $$v
            +($h>'Z'?[-1=>'']:[]); # if $h is lower case, add empty char
        },$s))
    as$b)
    {
    {
        $w=$r.implode($b); // add syllable
        $y // if minimum syllables are reached
        || !$w // and the word is not empty
        || in_array($w,$z) // and it has not been yielded
        || yield$w; // yield word
        $z[]=$w; // add word to "already yielded"
        if($x) // if maximum syllables are not reached ...
            foreach(f($c,$v,$s,$y,$x,$w)as$w)yield$w; // ... recurse
    }
}

```

---
Tags: code-golf, combinatorics
---


# Question
Title: Convert a non-negative integer to Barbrack
# Barbrack

Your task is to write a program or function that takes a non-negative integer (in decimal or any other convenient base for your language), and output a number in the numbering system **Barbrack**.

## What's that?

Barbrack is a numbering system I made up that can represent non-negative integers. Zero is represented with an empty string or an underscore, one is represented with \[\], and all other positive integers can be represented with a **brack**.

A **brack** is delimited with brackets \[\] and works as follows (with an example of 84):

1. Take your number a and find its prime factorization. In this case, the prime factorization of 84 is 22\*31(\*50)\*71.
2. Find the indices of these primes, where the index of 2 is 1. In this case, the index of 3 is 2, since it's the prime right after 2; and the index of 7 is 4, since it's the fourth prime.
3. Take the exponents of each prime, and put them in brackets in increasing order of the size of the prime, with consecutive exponents being separated by bars (|). So the general format is \[exponent of 2|exponent of 3|exponent of 5…\]—in this case, \[2|1|0|1\]. **Minimize the number of cells!**
4. Recursively calculate the exponents in Barbrack, remembering that 0 is the empty string and 1 is \[\]. So \[2|1|0|1\] =\> \[\[1\]|\[\]||\[\]\] =\> \[\[\[\]\]|\[\]||\[\]\].
5. Output the final result.

## Test inputs

```
0     -> (nothing)
1     -> []
2     -> [[]]
5     -> [||[]]
27    -> [|[|[]]]
45    -> [|[[]]|[]]
54    -> [[]|[|[]]]
84    -> [[[]]|[]||[]]
65535 -> [|[]|[]||||[](48 bars)[]]
65536 -> [[[[[]]]]]

```

(sidenote: (48 bars) means 48 consecutive bars in the actual output)

## Rules

* Standard loopholes apply.
* No input in Barbrack! This isn't a cat challenge!
* You may replace \[\] with any other paired delimeter, like () or {}. However, the vertical bars need to be actual vertical bars.
* Whitespace is not allowed within the number, but is allowed outside of it (for example, a trailing newline).
* The program should be able to fully parse any number given infinite time and memory.

## Scoring

Scores are counted by minimum bytes on a per-language basis.

# Answer
# Jelly, 12 bytes

```
ÆEß€j”|Ø[jxẸ

```

Try it online!

A monadic link that takes an integer as its argument and returns a string.

## Explanation

```
ÆEß€j”|Ø[jxẸ
ÆE            # Prime exponents
  ß€          # Current (main) link for each member of the list of exponents
    j”|       # Join with the bar character
       Ø[j    # Wrap in square brackets
          xẸ  # Repeat once if original argument was non-zero else repeat zero times (effectively preserves current value if argument was non-zero else returns empty list)

```

Created with the help of Luminespire.

## Conversion back from barbrack

## Jelly, 13 bytes

```
ṖḊṣ”|ß€ÆẸµ0¹?

```

Try it online!

A monadic link that takes a string and returns an integer. The TIO link converts to barbrack and then back.
> 5 votes

# Answer
# Vyxal, 13 bytes

```
λ[∆Ǐvx\|jøB|¤

```

Try it Online!

```
λ             # Define a recursive lambda
 [            # If the input is nonzero
     x        # Recurse on
    v         # Each of
  ∆Ǐ          # The prime exponents of n
      \|j     # Join by |
         øB   # And wrap in []
 [         |¤ # Else, if it's zero, return the empty string.

```
> 4 votes

# Answer
# Python, 113 bytes

```
def f(n):
 P=i=2;r=''
 while w:=n>1:
  while n%i<1:n//=i;w+=1
  r+=P%i*'|'+f(w-1);P*=i*i*2;i+=1
 return'[%s]'%r*n

```

Attempt This Online!
> 4 votes

# Answer
# JavaScript (ES6), 96 bytes

```
f=(n,q=1)=>n?q>n?"]":["|["[(g=d=>q%d--?g(d):q<3|-d)(q++)]]+f((g=_=>n%q?0:1+g(n/=q))())+f(n,q):""

```

Try it online!
> 3 votes

# Answer
# Haskell, 196 bytes

```
n#f|n`mod`f==0=1+(n`div`f)#f|0<1=0
p 1=[]
p n=(:)<*>p.div n$until((<1).mod n)(+1)2
f 0=""
f 1="[]"
f n='[':concat(init$filter(\n->mod(product[1..n-1]^2)n>0)[2..maximum.p$n]>>=(:["|"]).f.(n#))++"]"

```

Try it online!
> 3 votes

# Answer
# Python3, 227 bytes

```
R=range
def f(n):
 if n<2:return'[]'*n
 d,K={},{}
 while n>1:
  for i in R(2,n+1):
   if(i==2 or all(i%j for j in R(2,i))):
    K[i]=1
    if 0==n%i:n//=i;d[i]=d.get(i,0)+1;break
 return'['+'|'.join(f(d.get(i,0))for i in K)+']'

```

Try it online!
> 2 votes

# Answer
# Charcoal, ~~99~~ ~~87~~ 80 bytes

```
⊞υＮＷυ«≔∨⊟υωι¿⁼ι⁺ωιι«≔⟦⟧θ≔²ηＷ⊖ι«⊞θ⌕Ｘ⁰⮌↨ιη⁰≧÷Ｘη§θ±¹ι⊞θ|≦⊕ηＷ¬⌊﹪η…²η≦⊕η»⊞υ]ＦΦ⮌θλ⊞υκ[

```

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

```
⊞υＮ

```

Start by processing the input integer.

```
Ｗυ«

```

Repeat until there are no more values to be processed.

```
≔∨⊟υωι

```

Get the next value, or the empty string if it is zero.

```
¿⁼ι⁺ωιι«

```

If the next value is a string then print it, otherwise:

```
≔⟦⟧θ

```

Start collecting prime powers.

```
≔²η

```

Start at the first prime.

```
Ｗ⊖ι«

```

Repeat until the integer is reduced to `1`.

```
⊞θ⌕Ｘ⁰⮌↨ιη⁰

```

Add the multiplicity of this prime factor to the list of prime powers.

```
≧÷Ｘη§θ±¹ι

```

Divide the integer by the power of the prime to the multiplicity.

```
⊞θ|

```

Add a separator to the list of prime powers.

```
≦⊕ηＷ¬⌊﹪η…²η≦⊕η

```

Find the next prime by brute force.

```
»⊞υ]

```

Push a `]` for later output.

```
ＦΦ⮌θλ⊞υκ

```

Push each prime power in reverse order, but without the leading separator.

```
[

```

Print `[`. Subsequent passes through the loop will then process the prime powers, separators and `]`.
> 1 votes

# Answer
# , 34 bytes

```
*#1|.'][',1}.&;'|'(,$:)&.>_&q: ::$

```

Attempt This Online!

`_&q: ::$` Get the prime exponents. If that errors (0), get an empty array instead.
`'|'(,$:)&.>` For each exponent, call the entire function recursively and prepend a bar to the result.
`1}.&;` Join into a single string and remove the first bar.
`1|.'][',` Wrap in brackets by prepending both, then rotating one to the back.
`*#` Replicate by sign of input. This makes sure 0 returns an empty string.
> 1 votes

# Answer
# Scala, 335 bytes

Port of @Ajax1234's Python answer in Scala.

\\$ \color{red}{\text{But the scala code fails on same cases. Any help would be appreciated.}} \\$

---

335 bytes, it can be golfed much more.

Golfed version. Try it online!

```
import scala.util.control.Breaks._
def f(n:Int):String={if(n<2)return"[]"*n;var d=Map[Int,Int]();var K=List[Int]();var num=n
while(num>1){breakable{for(i<-2 to num){if(i==2||(2 until i).forall(i%_!=0)){K=i::K;if(num%i==0){num/=i;d=d.updated(i,d.getOrElse(i,0)+1);break}}}}}
"["+K.distinct.map(i=>f(d.getOrElse(i,0))).mkString("|")+"]"}

```

Ungolfed version. Try it online!

```
import scala.util.control.Breaks._

object Main {
  def main(args: Array[String]): Unit = {
    println(f(0))
    println(f(1))
    println(f(2))
    println(f(65536))
  }

  def f(n: Int): String = {
    if (n < 2) return "[]" * n

    var d = Map[Int, Int]()
    var K = List[Int]()
    var num = n

    while (num > 1) {
      breakable({
      for (i <- 2 to num) {
        if (i == 2 || (2 until i).forall(i % _ != 0)) {
          K = i :: K
          if (num % i == 0) {
            num /= i
            d = d.updated(i, d.getOrElse(i, 0) + 1)
            break
          }
        }
      }
      })
    }

    "[" + K.distinct.map(i => f(d.getOrElse(i, 0))).mkString("|") + "]"
  }
}

```
> 1 votes

# Answer
# 05AB1E, 27 bytes

```
"D!i„[]×ëÓ®δ.V'|ý'[ì']«"©.V

```

As usual, 05AB1E isn't the best when it comes to recursive challenges. And since there isn't a way to interpret or convert a list `[]` to a string `"[]"`, it becomes even longer..

Try it online or verify all test cases.

Here an alternative that's 1 byte longer:

```
Δ.γd}εÐdi!i„[]×ëÓ'|ý…[ÿ]}}}J

```

Try it online or verify all test cases.

**Explanation:**

```
"..."             # Define the recursive string below
     ©            # Store this string in variable `®` (without popping)
      .V          # Pop and execute it as 05AB1E code
                  # (after which the result is output implicitly)

D                 # Duplicate the current integer
 !i               # Pop the copy, and if it's 0 or 1:
   „[]×           #  Repeat "[]" 0 or 1 times as string
  ë               # Else (it's >=2):
   Ó              #  Get a list of exponents of its prime factorization
     δ            #  Map over each integer:
    ® .V          #   Do a recursive call
   '|ý           '#  Join the list with "|"-delimiter
      '[ì']«      #  Prepend "[" and append "]"

```

```
Δ                 # Loop until the result no longer changes,
                  # using the implicit input in the first iteration:
 .γ }             #  Adjacent group-by the string by:
   d              #   Check whether it's a digit
 ε                #  Map over each group:
  Ð               #   Triplicate the current string
   di             #   If it's a number:
     !i„[]×ëÓ'|ý '#    Similar as above
     …[ÿ]         #    Prepend "[" and append "]"
     }            #    Close the inner if-else statements
    }             #   Close the outer if-statement
 }                #  Close the map
  J               #  Join this mapped list of groups back together to a single string
                  # (after which the result is output implicitly)

```
> 1 votes

# Answer
# Ruby, 109 bytes

```
require"prime"
f=->n{n<1?"":"[#{n<2?"":Prime.each((q=n.prime_division)[-1][0]).map{|x|f[q.to_h[x]||0]}*?|}]"}

```

Try it online!

```
f=->n{        _f_ takes an integer _n_ and
n<1?""        returns "" if _n_ == 0
:"[#{...}]"   else returns a string enclosed in brackets composed of:
n<2?""          empty string if _n_ == 1
:Prime.each(    else we take all primes up to
(q=n.prime_division)[-1][0])
                maximum factor( saving factorization in _q_ )
.map{|x|        and map them by:
f[...]            calling _f_ recursively with
q.to_h[x]         hash made from factorization( gives us powers )
||0               for primes not in factorization _q_ default _nil_ is converted to 0
}*?|            finally join with `|`

```
> 1 votes

---
Tags: code-golf, number
---


title: Multiplicity Test

text:
# Question
Title: Multiplicity Test
Use any programming language to display numbers between 1 and 99 (including both) in such a way, so that:

* the numbers are separated by single space,
* if a number is divisible by 3, it should be in parentheses,
* if a number is divisible by 4, it should be in square brackets,
* if a number is divisible by both 3 and 4, it should be in both parentheses and square brackets (with square brackets closer to the number).

Your program should display exactly:

```
1 2 (3) [4] 5 (6) 7 [8] (9) 10 11 ([12]) 13 14 (15) [16] 17 (18) 19 [20] (21) 22 23 ([24]) 25 26 (27) [28] 29 (30) 31 [32] (33) 34 35 ([36]) 37 38 (39) [40] 41 (42) 43 [44] (45) 46 47 ([48]) 49 50 (51) [52] 53 (54) 55 [56] (57) 58 59 ([60]) 61 62 (63) [64] 65 (66) 67 [68] (69) 70 71 ([72]) 73 74 (75) [76] 77 (78) 79 [80] (81) 82 83 ([84]) 85 86 (87) [88] 89 (90) 91 [92] (93) 94 95 ([96]) 97 98 (99)

```

# Answer
# 05AB1E, 23 bytes

-1 byte thanks to Kevin Cruijssen

```
тGND4Öi…[ÿ]}N3Öi…(ÿ)]ðý

```

Try it online!
> 7 votes

# Answer
# Python 2, ~~68~~ ~~65~~ 60 bytes

```
i=0
exec"i+=1;print'('[i%3:]+`[i][i%4:]or i`+')'[i%3:],;"*99

```

Try it online!
> 6 votes

# Answer
# , 61 bytes

```
"+"=c
r=""+""
cat(paste0(r+"(",r+""+"[",1:99,r+""+"]",r+")"))

```

Try it online!
> 5 votes

# Answer
# Jelly, ~~21~~ 20 bytes

```
³Ṗµ3,4ṚƬḍ×“([“])”j)K

```

Try it online!

### How it works

```
³Ṗµ3,4ṚƬḍ×“([“])”j)K  Main link. No arguments.

³                     Set the return value to 100.
 Ṗ                    Pop; yield [1, ..., 99].
  µ               )   Map the chain in between over [1, ..., 9]; for each integer k:
   3,4                    Set the return value to [3, 4].
      ṚƬ                  Reverse until a loop is reached. Yields [[3, 4], [4, 3]].
        ḍ                 Test k for divisibility by [[3, 4], [4, 3]], yielding a
                          matrix of Booleans.
         ×“([“])”         Repeat the characters of [['(', '['], [']', ')']] as many
                          times as the Booleans indicate.
                 j        Join the resulting pair of strings, separated by k.
                   K  Join the resulting array of strings, separated by spaces.

```
> 4 votes

# Answer
## C, C++, ~~136~~ ~~133~~ ~~131~~ ~~129~~ ~~128~~ 124 bytes

-5 bytes thanks to Zacharý and inspired by write() function in D language ( see Zacharý answer )

-2 bytes thanks to mriklojn

-12 bytes for the C version thanks to mriklojn

-4 bytes thanks to ceilingcat

```
#include<cstdio>
void f(){for(int i=0;i++<99;)printf("(%s%d%s%s%s"+!!(i%3),i%4?"":"[",i,i%4?"":"]",i%3?"":")",i%99?" ":"");}

```

### C Specific Optimization : 115 bytes

```
#include<stdio.h>
i;f(){for(;i++<99;)printf("(%s%d%s%s%s"+!!(i%3),i%4?"":"[",i,i%4?"":"]",i%3?"":")",i%99?" ":"");}

```
> 3 votes

# Answer
# , 110 bytes

```
import std.stdio;void f(){for(int i;i<99;)write(++i%3?"":"(",i%4?"":"[",i,i%4?"":"]",i%3?"":")",i%99?" ":"");}

```

Try it online!

Ported from @HatsuPointerKun's C++ answer.
> 3 votes

# Answer
# Charcoal, 30 bytes

```
⪫ＥＥＥ⁹⁹Ｉ⊕ι⎇﹪⊕κ⁴ι⪫[]ι⎇﹪⊕κ³ι⪫()ι

```

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

```
    ⁹⁹                          Literal 99
   Ｅ                            Map over implicit range
        ι                       Current value
       ⊕                        Incrementd
      Ｉ                         Cast to string
  Ｅ                             Map over list of strings
            κ                   Current index
           ⊕                    Incremented
             ⁴                  Literal 4
          ﹪                     Modulo
              ι                 Current value
                []              Literal string `[]`
                  ι             Current value
               ⪫                Join i.e wrap value in `[]`
         ⎇                      Ternary
 Ｅ                              Map over list of strings
                      κ         Current index
                     ⊕          Incremented
                       ³        Literal 3
                    ﹪           Modulo
                        ι       Current value
                          ()    Literal string `()`
                            ι   Current value
                         ⪫      Join i.e wrap value in `()`
                   ⎇            Ternary
                                Literal space
⪫                               Join list
                                Implicitly print

```
> 3 votes

# Answer
# , ~~54~~ 53 bytes

*1 byte less thanks to @Jonah*

```
(*stdout(3|.0=4 3 1 3 4&|,1=":)#3|.']) ([',":)@>i.100

```

Try it online!
> 3 votes

# Answer
# MathGolf, ~~41~~ ~~40~~ ~~34~~ 29 bytes

```
♀({îû)(î+╫îa_'(\')ßyΓî34α÷ä§

```

NOTE: It has a trailing space

Only my second MathGolf answer..
-5 bytes thanks to *@JoKing*.

Try it online.

**Explanation:**

```
♀(             # Push 99 (100 decreased by 1)
  {            # Start a loop, which implicitly loops down to (and excluding) 0
   û)(         #  Push string ")("
      î+       #  Append the 1-indexed index
        ╫      #  Rotate the string once towards the right
   îa          #  Push the 1-indexed index of the loop, wrap in a list
   _           #  Duplicate it
    '(        '#  Push string "("
      \        #  Swap the top two items of the stack
       ')     '#  Push string ")"
         ßy    #  Wrap all three into a list, and join them
   Γ           #  Wrap all four into a list
               #  (We now have a list [N, "(N)", "[N]", "([N])"], where N is the index)
   î           #  Push the 1-indexed index of the loop
    34         #  Push 3 and 4 to the stack
      α        #  Wrap all three into a list
       ÷       #  Check for each if the index is divisible by it
               #  (resulting in either [0,0], [0,1], [1,0], or [1,1]
        ä      #  Convert from binary to integer
               #  (resulting in either 0, 1, 2, or 3
         §     #  Push the string at that index from the array
               #  Push a space
               # (After the loop, output the entire stack joined together implicitly)

```
> 3 votes

# Answer
# Powershell, 60 bytes

```
"$(1..99|%{($_,"($_)","[$_]","([$_])")[!($_%3)+2*!($_%4)]})"

```

Explanation:

* the array with 4 elements: `$_, "($_)", "[$_]", "([$_])"`
* and the index: `[!($_%3)+2*!($_%4)]`
* repeat for each number
* convert the result to a string

Less golfed Test script:

```
$f = {

$r = 1..99|%{
    ($_, "($_)", "[$_]", "([$_])") [!($_%3)+2*!($_%4)]
}
"$($r)"

}

$expected = '1 2 (3) [4] 5 (6) 7 [8] (9) 10 11 ([12]) 13 14 (15) [16] 17 (18) 19 [20] (21) 22 23 ([24]) 25 26 (27) [28] 29 (30) 31 [32] (33) 34 35 ([36]) 37 38 (39) [40] 41 (42) 43 [44] (45) 46 47 ([48]) 49 50 (51) [52] 53 (54) 55 [56] (57) 58 59 ([60]) 61 62 (63) [64] 65 (66) 67 [68] (69) 70 71 ([72]) 73 74 (75) [76] 77 (78) 79 [80] (81) 82 83 ([84]) 85 86 (87) [88] 89 (90) 91 [92] (93) 94 95 ([96]) 97 98 (99)'
$result = &$f
$result-eq$expected
$result

```

Output:

```
True
1 2 (3) [4] 5 (6) 7 [8] (9) 10 11 ([12]) 13 14 (15) [16] 17 (18) 19 [20] (21) 22 23 ([24]) 25 26 (27) [28] 29 (30) 31 [32] (33) 34 35 ([36]) 37 38 (39) [40] 41 (42) 43 [44] (45) 46 47 ([48]) 49 50 (51) [52] 53 (54) 55 [56] (57) 58 59 ([60]) 61 62 (63) [64] 65 (66) 67 [68] (69) 70 71 ([72]) 73 74 (75) [76] 77 (78) 79 [80] (81) 82 83 ([84]) 85 86 (87) [88] 89 (90) 91 [92] (93) 94 95 ([96]) 97 98 (99)

```
> 3 votes

# Answer
# Haskell, 77 bytes

```
unwords[f"()"3$f"[]"4$show n|n<-[1..99],let f(x:r)m s|mod n m<1=x:s++r|1<3=s]

```

Try it online!

I wonder if `show[n]` can be used to shorten things up, so far to no avail.
> 2 votes

# Answer
# Python 2, ~~105~~ ~~97~~ ~~88~~ ~~86~~ ~~85~~ 84 bytes

```
x=1
while x<100:print((('%s','(%s)')[x%3<1],'[%s]')[x%4<1],'([%s])')[x%12<1]%x,;x+=1

```

Try it online!
> 2 votes

# Answer
# Red, 99 97 bytes

```
repeat n 99[a: b: c: d:""if n% 3 = 0[a:"("c:")"]if n% 4 = 0[b:"["d:"]"]prin rejoin[a b n d c" "]]

```

Try it online!
> 2 votes

# Answer
## C#, ~~124~~ ~~117~~ 123 bytes

-5 bytes thanks to Kevin Cruijssen

```
x=>{for(int i=0;i++<99;)System.Console.Write((i%3<1?"(":"")+(i%4<1?"[":"")+i+(i%4<1?"]":"")+(i%3<1?")":"")+(i>98?"":" "));}

```

Test with :

```
Action<int> t = x=>{for(int i=0;i++<99;)System.Console.Write((i%3<1?"(":"")+(i%4<1?"[":"")+i+(i%4<1?"]":"")+(i%3<1?")":"")+(i>98?"":" "));}
t.Invoke(0);
Console.ReadKey();

```
> 2 votes

# Answer
## Lua, ~~161~~ 123 bytes

```
b=""for i=1,99 do;c,d=i%3==0,i%4==0;b=b..(c and"("or"")..(d and"["or"")..i..(d and"]"or"")..(c and")"or"").." "end;print(b)

```

Try it online!

Ungolfed:

```
b = ""
for i = 1, 99 do
    c = 1 % 3 == 0
    d = 1 % 4 == 0
    a = ""
    if c then
        a = a .. "("
    end
    if d then
        a = a .. "["
    end
    a = a .. i
    if d then
        a = a .. "]"
    end
    if c then
        a = a .. ")"
    end
    b = b .. a .. " "
end
print(b)

```
> 2 votes

# Answer
# C (gcc), 84 bytes

```
main(i){while(99/i++)printf("%s%s%d%s%s ","("+i%3,"["+i%4,i-1,"]"+i%4,")"+i%3);}

```

There's a null byte at the beginning of each "bracket string".

Try it online!
> 2 votes

# Answer
# PowerShell, 98 82 74 ~~67~~ ~~63~~ 62 bytes

A whopping -31 bytes thanks to @Veskah -5 bytes thanks to @ASCII-only

```
(1..99|%{(($a=($_,"[$_]")[!($_%4)]),"($a)")[!($_%3)]})-join' '

```

Try it online!

I'm still not quite sure what I've done here.
> 2 votes

# Answer
# PowerShell, ~~67~~ 62 bytes

```
"$(1..99|%{'('*!($x=$_%3)+'['*!($y=$_%4)+$_+']'*!$y+')'*!$x})"

```

Try it online!

Basically a FizzBuzz using string multiplication times Boolean variables (implicitly cast to 1 or 0). Those strings are left on the pipeline and gathered within a script block inside quotes. Since the default `$OutputFieldSeparator` for an array is spaces, this implicitly gives us space-delimited array elements.
> 2 votes

# Answer
# Ruby, ~~72~~ 66 bytes

```
p [*1..99].map{|x|a=x
a="[#{x}]"if x%4<1
a="(#{a})"if x%3<1
a}*' '

```

Thanks to @jonathan-frech and @conor-obrien for additional trimming.
> 2 votes

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

```
f=(n=99)=>n&&f(n-1)+(s=n%4?n:`[${n}]`,n%3?s:`(${s})`)+' '

```

Try it online!

Changed to community cuz the optimize rely too much on it
> 1 votes

# Answer
# perl -E, 60 bytes

```
$,=$";say map$_%12?$_%3?$_%4?$_:"[$_]":"($_)":"([$_])",1..99

```

Some bytes can be saved if we can use newlines between the numbers: in that case, we can remove the `$,=$";`, change the `map` into a `for` loop, while moving the `say` into the loop.
> 1 votes

# Answer
# Perl 6, ~~51~~ 48 bytes

```
put {$_%3??$^a!!"($a)"}(++$_%4??$_!!"[$_]")xx 99

```

Try it online!
> 1 votes

# Answer
## Batch, 145 bytes

```
@set s=
@for /l %%i in (1,1,99)do @set/an=%%i,b=n%%4,p=n%%3&call:c
@echo%s%
:c
@if %b%==0 set n=[%n%]
@if %p%==0 set n=(%n%)
@set s=%s% %n%

```

The code falls through into the subroutine but the string has already been printed by this point so the code executes harmlessly.
> 1 votes

# Answer
# PHP 103

`for(;$i<1e2;$i++)$a.=$i%12==0?"([$i]) ":($i%3==0?"($i) ":($i%4==0?"[$i] ":"$i "));echo substr($a,5,-1);`

https://www.ideone.com/SBAuWp
> 1 votes

# Answer
# Clean, 100 bytes

```
import StdEnv,Text

```

#

```
join" "[if(n/3*3<n)m("("+m+")")\\n<-[1..99],m<-[if(n/4*4<n)(""<+n)("["<+n<+"]")]]

```

Try it online!
> 1 votes

# Answer
# sfk, 225 bytes

```
for n from 1 to 99 +calc -var #(n)/3+1/3 -dig=0 +calc -var #text*3-#(n) +setvar t +calc -var #(n)/4 -dig=0 +calc -var #text*4-#(n) +xed -var _0_#(t)\[#(n)\]_ _*_#(t)#(n)_ +xed _0*_([part2])_ _?*_[part2]_ +xed "_\n_ _" +endfor

```

Try it online!
> 1 votes

# Answer
# Java 8, ~~92~~ 91 bytes

*-1 byte thanks to @Dana*

`i->{for(;i++<99;)out.printf((i>1?" ":"")+(i%12<1?"([%d])":i%3<1?"(%d)":i%4<1?"[%d]":i),i);}`

Try it online!

Alternative solution, 82 bytes (with trailing space in the output - not sure if that's allowed):

`i->{for(;i++<99;)out.printf((i%12<1?"([%d])":i%3<1?"(%d)":i%4<1?"[%d]":i)+" ",i);}`

Explanation:

`for(;i++<99;)` \- a for loop that goes from the value of `i` (reused as input, taken to be 0 in this case) to 99

`out.printf(<part1>+<part2>,i);` \- formats the string before immediately printing it to stdout with the value of `i`

where `<part1>` is `(i>1?" ":"")` \- prints the space *before* printing the number *unless* that number is 1, in which case it omits the space

and `<part2>` is `(i%12<1?"([%d])":i%3<1?"(%d)":i%4<1?"[%d]":i)` \- if `i` is divisible by both 3 and 4, `i` has both square and round brackets around it; else if `i` is divisible by 3, `i` has round brackets; else if `i` is divisible by 4, `i` has square brackets; else, `i` has no brackets.
> 1 votes

# Answer
# Bash, 61 bytes

*-14 bytes, thanks to Dennis*

```
seq 99|awk '{ORS=" ";x=$1%4?$1:"["$1"]";print$1%3?x:"("x")"}'

```

# explanation

Pretty straightforward:

* `seq` produces 1..99
* we pipe that into `awk` with the output record separator (`ORS`) set to space so the output is a single line.
* the main awk body just adds "\[\]" when the number is divisible by 4, and then adds, on top of that, "()" when divisible by 3.

Try it online!
> 1 votes

# Answer
# PHP, 65 bytes

```
while($i++<99)echo$i%4?$i%3?$i:"($i)":($i%3?"[$i]":"([$i])")," ";

```

or

```
while($i++<99)echo"("[$i%3],"["[$i%4],$i,"]"[$i%4],")"[$i%3]," ";

```

(requires PHP 5.5 or later)

Run with `-nr` or try them online.
> 1 votes

# Answer
# Python 2, 78 bytes

```
i=0
exec"i+=1;u=i%3/-2*(i%4/-3-1);print'([%0d])'[u:7-u:1+(i%3<1<=i%4)]%i,;"*99

```

Try it online!

I envisioned this cool approach slicing `'([%0d])'` but I can't get the expressions any shorter.
> 1 votes

# Answer
# APL(NARS), 46 chars, 92 bytes

```
{{0=3∣w:1⌽')(',⍵⋄⍵}{0=4∣w:1⌽'][',⍵⋄⍵}⍕w←⍵}¨⍳99

```

litte test:

```
  {{0=3∣w:1⌽')(',⍵⋄⍵}{0=4∣w:1⌽'][',⍵⋄⍵}⍕w←⍵}¨⍳14
1 2 (3) [4] 5 (6) 7 [8] (9) 10 11 ([12]) 13 14

```
> 1 votes

# Answer
# Python 2, 68 bytes

```
i=0
exec"i+=1;t,f=i%3<1,i%4<1;print'('*t+'['*f+`i`+']'*f+')'*t,;"*99

```

Try it online!
> 1 votes

# Answer
# Pyth, 25 bytes

```
jdmj]W!%d4dc2*"()"!%d3S99

```

Try it online here.

```
jdmj]W!%d4dc2*"()"!%d3S99
  m                   S99   Map [1-99], as d, using:
                   %d3        d mod 3
                  !           Logical not, effectively maps 0 to 1, all else to 0
             *"()"            Repeat "()" the above number of times
           c2                 Chop into two equal parts - maps "()" to ["(",")"] , and "" to ["",""]
                                The above is result {1}
       %d4                    d mod 4
      !                       Logical not the above
    ]W    d                   If the above is truthy, [d], else d
                                The above is result {2}
   j                          Join {1} on string representation of {2}
jd                          Join the result of the map on spaces, implicit print

```
> 1 votes

# Answer
# Python 3, 95 bytes

```
print(*[(i if i%4else f"[{i}]")if i%3else(f"({i})"if i%4else f"([{i}])")for i in range(1,100)])

```

Try it online!
> 1 votes

# Answer
# Python 2, 68 bytes

```
for i in range(1,100):print("(%s)","%s")[i%3>0]%("[%s]"%i,i)[i%4>0],

```

Try it online!

Ends with a trailing space.
> 1 votes

# Answer
# Stax, ~~19~~ 17 bytes

```
ä┐r►U^îⁿ_╤▌,│☻£╡▬

```

Run and debug it
> 1 votes

# Answer
# C (gcc), 76 bytes

Surprisingly, this straight-forward solution was shorter than the "clever" ones I could come up with.

```
f(i){for(i=0;i++<99;)printf(i%3?i%4?"%d ":"[%d] ":i%4?"(%d) ":"([%d]) ",i);}

```

Try it online!
> 1 votes

# Answer
# Perl 5, 51 bytes

```
say map{$o=$_%4?$_:"[$_]";($_%3?$o:"($o)").$"}1..99

```

Try it online!
> 1 votes

# Answer
# Clojure, 104 bytes

```
(apply print(map #(do(def s(if(=(rem % 4)0)(str"["%"]")%))(if(=(rem % 3)0)(str"("s")")s))(range 1 100)))

```

Try it online!
> 1 votes

# Answer
# CJam, 70 bytes

```
99,:){X4%0={'[Xs']++}{X}?}fX]{Xs'[/_,(=']/0=i3%0={'(Xs')++}{X}?}fX]S*

```

Try it out online! (Permalink)

---

### Explanation

```
99                                                                    Push 99 to stack
  ,                                                                   Make a 0..98 array
   :)                                                                 Increment every value in array
     {                   }fX                                          For X in array at top of stack
                        ?                                             If...
      X4%0=                                                           Condition: X mod 4 = 0
           {        }                                                 Is true, then:
            '[                                                        Push "["
              Xs                                                      Push X as a string
                ']                                                    Push "]"
                  ++                                                  Concatenate to "[X]"
                     { }                                              Is false, then:
                      X                                               Push X
                            ]                                         Capture all in an array
                             {                                 }fX    For X in array at top of stack
                                                              ?       If...
                              Xs                                      X as a string
                                '[/                                   Split by "["
                                   _,(=                               Take last element after split
                                       ']/                            Split by "]"
                                          0=                          Take first element after split
                                            i                         Top element as an integer
                              Xs'[/_,(=']/0=i                         The number X minus any brackets
                                             3%0=                     Condition: X mod 3 = 0
                                                 {        }           Is true, then:
                                                  '(                  Push "("
                                                    Xs                Push the original X as a string
                                                      ')              Push ")"
                                                        ++            Concatenate to "(X)"
                                                           { }        If false, then:
                                                            X         Push X
                                                                  ]   Capture all in an array
                                                                   S* Separate by a space

```

This does not output a trailing space.
> 1 votes

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

```
int i;for(;i<99;)Write("{0:;;(}{1:;;[}{2}{1:;;]}{0:;;)} ",++i%3,i%4,i);

```

Try it online!

-9 bytes thanks to @ASCIIOnly!

Leveraging the semicolon (The ";" section separator) to create a custom format string.
> 1 votes

# Answer
# Japt, 30 bytes

```
Lo1@=X%4?X:"[{X}]"X%3?U:"({U})

```

Try it online!
> 1 votes

# Answer
# PHP, 59 bytes

```
for(;$i<100;$s=++$i%4?$i:"[$i]")echo$i%3|!$s?$s:"($s)"," ";

```

Try it online!
> 1 votes

# Answer
## Javascript, ~~114~~ 96 bytes

```
[...Array(99)].map(_=>['[4]','(3)'].reduce((a,r)=>n%r[1]<1?r.replace(r[1],a):a,++n),n=0).join` `

```

Try it Online!

Thanks to Conor O'Brien for helping me improve it :-)
> 1 votes

# Answer
# Attache, 56 bytes

```
Echo@@({~Join^^S@_'Mask[4'3|_,["["'"]","("'")"]]}=>1:99)

```

Try it online!

## Explanation

```
Echo@@({~Join^^S@_'Mask[4'3|_,["["'"]","("'")"]]}=>1:99)
       {                                        }=>1:99  over each number _, 1 to 99:
                        4'3|_                                check if 4 or 3 divide _
                   Mask[     ,["["'"]","("'")"]]             keep the respective brackets
             ^^S@_'                                          fold over this list (seed = S[_]):
        ~Join                                                joining elements by the iterator
Echo@@(                                                ) print strings separated by spaces

```

## Alternatives

**58 bytes:** `Echo@@({~Join^^S@_'Mask[[4,3]|_,["["'"]","("'")"]]}=>1:99)`

**59 bytes:** `Print@@({~Join^^S@_'Mask[[4,3]|_,["["'"]","("'")"]]}=>1:99)`

**76 bytes:** `Print@@(&/S@{Mask[1'3'4'12|_,Split@$"${_} (${_}) [${_}] ([${_}])"] }=>1:99)`
> 1 votes

# Answer
# ink, 61 bytes

```
VAR j=0
-(i)~j="{i%4:{i}|[{i}]}"
{i%3:{j}|({j})} <>{i<99:->i}

```

Try it online!

### Explanation

```
VAR j=0                       // Declare a variable called j.
-(i)~j="{i%4:{i}|[{i}]}"      // The i label keeps track of how many times it's been visited. Set j to that value, or that value surrounded by brackets, depending o nwhat it is.
{i%3:{j}|({j})} <>{i<99:->i}  // Print j or (j), depending on i. Use glue (<>) to not print a newline. Go back to the i label if it's been visited fewer than 99 times.

```
> 1 votes

# Answer
# Vyxal `HS`, 103 bits<sup>v2</sup>, 12.875 bytes

```
ɽƛ4ḊßøB;ƛ⌊₃ßøb

```

Try it Online!
> 1 votes

# Answer
# Go, 173 bytes

```
import(."strings";."fmt")
func f(){S,F:=[]string{},Sprintf
for i:=1;i<100;i++{s:=F("%d",i)
if i%4<1{s=F("[%s]",s)}
if i%3<1{s=F("(%s)",s)}
S=append(S,s)}
Print(Join(S," "))}

```

Attempt This Online!

Prints the output to STDOUT.
> 1 votes

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