title: Number Named Regex Groups

text:
# Question
Title: Number Named Regex Groups
Using named matching groups is often easier to understand than numbering groups but takes up more bytes. Given a regular expression as specified below, your program or function must convert named groups to numbered groups.

## Task

These specifications are based on python 3's re module.

A named group takes the form of `(?P<name>...)` where `name` is replaced with the name of the group and `...` is a valid regex.

A reference to a named group takes the form of `(?P=name)` where `name` is replaced with the name of the group.

A numbered group takes the form of `(...)` where `...` is a valid regex.

A reference to a numbered group takes the form of `\number` where `number` is replaced with the number of the group as follows:

> groups are numbered from left to right, from 1 upward. Groups can be nested; to determine the number, just count the opening parenthesis characters, going from left to right. (Python howto)

The number of opening parentheses characters includes the group's opening parenthesis.

Thus your program or function must, given a *valid* regular expression, convert named groups to numbered groups and references to named groups to references to numbered groups with the right number.

## Example

The input is `s(tar)+t(?P<name1>subre)cd(?P=name1)`. The `(?P=name1)` bit refers to the capturing group `(?P<name1>subre)`. It is group `2` because the string `s(tar)+t(` contains two opening parentheses. Thus `(?P=name1)` is replaced with `\2` to get `s(tar)+t(?P<name1>subre)cd\2`

The `(?P<name1>subre)` group can be converted to a non-named group by simply removing the name and identification to get `(subre)`. Applying this into the string so far yields `s(tar)+t(subre)cd\2`. Since there are no named groups nor named references, the program is done and outputs `s(tar)+t(subre)cd\2`.

## Rules

* There are no non-capturing groups in the input regular expression (in other words, all groups are either numbered or named).
* You may assume that all input groups are named.
* Any further pedantics due to technical specifications of regular expressions should be ignored.
    + The input will always contain no digits directly after named backreferences.
    + Every reference to a named group in the input will have an actual named group to reference to.
    + All parentheses in the input delimit a group
    + The group names will contain no spaces.
* The output may optionally have a trailing newline.
* Brownie points for solving this challenge using a regular expression!

## Remember Defaults:

## Test Cases

```
Input
Output
-----
this has no* groups \bubbles
this has no* groups \bubbles
-----
this has (?P<name>named)+ groups (?P=name)
this has (named)+ groups \1
-----
this has no(?P<references> sadness*)?
this has no( sadness*)?
-----
I need (?P<reference> very+ much) here is one: (?P=reference)
I need ( very+ much) here is one: \1
-----
t(?P<one>o)n(?P<another>s) of (?P<groups>named) groups (?P=another) (?P=one) (?P=groups)
t(o)n(s) of (named) groups \2 \1 \3
-----
Of course, we need (?P<moregroups>misdirection) (?P<n>n(?P<e>e(?P<s>s(?P<t>t)i)n)g) (?P=n)n(?P=e)e(?P=s)s(?P=t)ing
Of course, we need (misdirection) (n(e(s(t)i)n)g) \2n\3e\4s\5ing
-----
(?P<Lorem>Lorem ipsum dolor sit amet), (?P<consectetur>consectetur adipiscing elit), (?P<sed>sed do eiusmod tempor incididunt ut labore et dolore magna aliqua). (?P<Ut>Ut enim ad minim veniam, (?P<quis>quis) nostrud exercitation ullamco laboris nisi ut (?P<aliquip>aliquip ex ea commodo consequat.)) Duis aute irure dolor in (?P<finale>reprehenderit in voluptate velit esse cillum dolore eu fugiat (?P<null>null)a pariatur. (?P<Except>Excepteur (?P<sin>sin)t occae(?P<cat>cat) )cupidatat non proident, sunt) in culpa qui officia deserunt mollit anim id est laborum. (?P=cat)(?P=sin)(?P=Except)(?P=null)(?P=finale)(?P=aliquip)(?P=quis)(?P=Ut)(?P=sed)(?P=consectetur)(?P=Lorem)
(Lorem ipsum dolor sit amet), (consectetur adipiscing elit), (sed do eiusmod tempor incididunt ut labore et dolore magna aliqua). (Ut enim ad minim veniam, (quis) nostrud exercitation ullamco laboris nisi ut (aliquip ex ea commodo consequat.)) Duis aute irure dolor in (reprehenderit in voluptate velit esse cillum dolore eu fugiat (null)a pariatur. (Excepteur (sin)t occae(cat) )cupidatat non proident, sunt) in culpa qui officia deserunt mollit anim id est laborum. \11\10\9\8\7\6\5\4\3\2\1

```

(Above, I was referring to numbered groups as being disjoint from named groups, when named groups are also numbered. Pretend that I meant non-named groups when I said numbered groups.)

# Answer
> 3 votes
## JavaScript (ES6), 91 bytes

```
f=
s=>s.replace(/\(\?P=(\w+)\)|\(\?P<(\w+)>|\(/g,(_,b,n)=>b?`\\`+r[b]:(r[n]=++c,`(`),c=0,r={})
```

```
<textarea cols=30 rows=5 oninput=o.textContent=f(this.value)></textarea><div id=o>
```

# Answer
> 1 votes
# PHP, 198 bytes

```
preg_match_all("#\(\?P<.+?>|\(\?P=.+?\)|\(#",$a=$argn,$t);foreach($t[0]as$x)$x[1]?$x[3]=="<"?$a=strtr($a,[$x=>"("]).!$n[substr($x,4,-1)]=++$k:$a=strtr($a,[$x=>"\\".$n[substr($x,4,-1)]]):++$k;echo$a;

```

Try it online!

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


title: Generate a Kolakoski sequence

text:
# Question
Title: Generate a Kolakoski sequence
## Definition1

> A Kolakoski sequence is a *self-describing* infinite sequence {kn} of alternating blocks of 1's and 2's, given by the following rules:
>
> * k0 = 1
> * kn = the length of the (n+1)'th block

## The Task

Given a positive integer `n`, generate the first `n` elements of the Kolakoski sequence.

## Details

Input will be provided as a single command line argument `n`. Please write a full program that will print the first `n` elements of the Kolakoski sequence (in order) to STDOUT, with each element separated by your favorite whitespace.

## Scoring

Lets count source code bytes this time with all whitespace included. Fewest number of bytes wins. In the event of a tie, the solution with the earliest submission time wins.

## The Sequence2

1, 2, 2, 1, 1, 2, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 2, 1, 2, 1, 1, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 2, 2, 1, 2, 1, 1, 2, 1, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 1, 2, 2, 1, 2, 1, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 2, 1, 2, 1, 1, 2, 1, 2, 2, ...

---

References 1. John Smith, Ariel Scolnicov, yark. "Kolakoski sequence" (version 3). PlanetMath.org. Freely available at http://planetmath.org/KolakoskiSequence.html.
2. The Online Encyclopedia of Integer Sequences http://oeis.org/A000002

Other resources

# Answer
# J - 23 char

A little late to the party, but I'd like to bust out a neat little J trick here.

```
1($1+2|I.)^:_~".>2{ARGV

```

Given input `N`, this verb operates by executing `N&($1+2|I.)` on a starting argument of 1 until it reaches a fixed point. If the item at index `i` in `y` is `n`, there will be `n` copies of `i` in `I.y`, so for instance `I. 0 1 1 0 0 3 1` is `1 2 5 5 5 6`. We mod the result of that by 2 and add one. Then, `x $ y` forces `y` into a list of length `x`, truncating it or extending it cyclically as necessary.

So here's what happens when the input is, say, 10.

```
   10 ($1+2|I.)^:a: 1
1 0 0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1 1 1
1 2 1 2 1 2 1 2 1 2
1 2 2 1 2 2 1 2 2 1
1 2 2 1 1 2 1 1 2 2
1 2 2 1 1 2 1 2 2 1

```

We start with a row of all 1s and then "settle down" into the Kolakoski sequence. First, it turns into `1 2 1 2 1 2...` as each contiguous block of ones or twos is described by length 1. Then we apply it again and it turns into `1 2 2 1 2 2 1 2 2...` since the ones are described by 1 and the twos are described by 2. The we continue again and again until we see there is no change, at which point we stop and give the result.

Other "self-describing" sequences can be similarly derived in J using `I.` and `^:_`.

---

## Edit

Over a year ago, @ardnew asked:

> what is the relationship between `n` and the number of those intermediate iterations required to generate the sequence of length `n`?

To make sure we're on the same page, I consider the calculation for `n` = 10 above to have taken 5 iterations.

If there are *s* terms settled at the *i*-th iteration for `n`, then at the (*i*+1)-th iteration, there will be (at least) *k*0 \+ *k*1 \+ ... + *k**s* \+ 1 terms settled. The '+ 1' appears because the next term will also be correct, since it must be and is different from the term before it.

So if K(*s*) is the sequence of partial sums of *k*n, then we can lower bound the number of iterations for `n` by the least *a* such that (1+K)*a*(1) ≥ `n`. I don't how to prove we don't accidentally do a bit better (by picking up more correct terms than we expected in some iteration), but according to the numbers, we don't:

```
   k =: ($ 1 + 2 | I.)^:_&1               NB. Kolakoski seq
   pk =: +/\ @: k                         NB. partial sums ("K")
   ((1 + pk 2000) {~ <:) ::_:^:(i.20) 1   NB. iterating 1+K, say, 20 times
1 2 4 7 11 18 28 43 65 99 150 226 340 511 768 1153 1728 2590 _ _
   NB. compare with observed number of settled terms up to 2000:
   +/"1 }. (k <./\ . ="1 ($1+2|I.)^:a:&1) 2000
1 2 4 7 11 18 28 43 65 99 150 226 340 511 768 1153 1728 2000

```

The underscores are index errors (`:: _:`), telling us 20 iterations is too much for the first 2000 terms of *k*n to handle.
> 9 votes

# Answer
## Ruby (73 characters)

```
s=[1,2,2];n=2;ARGV[0].to_i.times{puts s[n-2];s[n].times{s+=[1+n%2]};n+=1}

```
> 5 votes

# Answer
## GolfScript (48 chars)

You can't test this online because the online GS shell doesn't take command-line arguments, but:

```
;"#{ARGV[-1]}"~[1 2.]2{.2$=[1$2%)]*@\+\)}3$*;<n*

```

This takes input from stdin instead and works

```
~[1 2.]2{.2$=[1$2%)]*@\+\)}3$*;<n*

```
> 3 votes

# Answer
# Python 93

Adapted from my solution to Calculate the nth term of Golomb's self-describing sequence:

```
import sys;n=int(sys.argv[1]);a=[1,2,2];
for i in range(3,n):a+=[~i%2+1]*a[i-1]
print a[:n]

```

Still trying to figure out how to do this with list comprehension which I just learned about today, but I'm running into problems with self-reference.

EDIT: Instead of breaking if list was too long, just printed the appropriate slice.

EDIT: Now pulling arg from command line
> 3 votes

# Answer
# Python (87 chars)

My code turned out to be basically the same as scleaver's solution even though I wrote it independently. It saves a few characters by not shifting the index i by 1.

```
import sys
n=int(sys.argv[1])
l=[1,2,2]
for i in range(2,n):l+=[1+i%2]*l[i]
print l[:n]

```
> 3 votes

# Answer
# Perl, ~~41~~ 39 bytes

A trivial modification of the classic TPR(0,3) solution:

```
perl -E 'say$_=($.+=!--$.[$.])%2+1for@.=(0)x pop' 20

```
> 3 votes

# Answer
# Haskell 157 144

Haskell is kind of verbose so I expect this will be significantly longer than the shortest answer, but here it is.

```
import System
a=1:2:drop 2(concat.zipWith replicate a.cycle$[1,2])
main=do args<-getArgs;putStr$concatMap((' ':).show)$take(read$args!!0::Int)a

```

### Edit:

Implemented FUZxxl's suggestions and also a few other small fixes.
> 2 votes

# Answer
# Brain-Flak, 128 bytes

```
(({}<((())<>)>)<{({}[()]<{{({}[()])<>(({}))<>}{}<>(()()()[{}])<>}<>{({}<>)<>}(())<>>)}>){({}[()]<({}<>)<>>)}{}{{}}<>{({}<>)<>}<>

```

Try it online!
> 2 votes

# Answer
# Python (118 characters)

Takes n as a command line argument. Could trim four more characters if the printing of first n requirement is relaxed to first n or n + 1. I can't think of any more fat to trim...will be interested to see what a more experienced Python golfer could do

```
import sys
k,b=[1,2,2],1
n=int(sys.argv[1])
while len(k)<n:k.extend([2,1][b%2]for z in range(k[b+1]));b+=1
print k[:n]

```
> 1 votes

# Answer
## Perl, 59 chars

```
say"@{[map{push@a,(2-$_%2)x($b=$a[$_-1]||$_);$b}1..shift]}"

```

As usual, run with Perl 5.10+ and the `-M5.010` switch to enable the `say` feature.
> 1 votes

# Answer
### Javascript (414 Characters)

```
function range(n,e,t){if("undefined"==typeof e&&(e=n,n=0),"undefined"==typeof t&&(t=1),t>0&&n>=e||0>t&&e>=n)return[];for(var i=[],r=n;t>0?e>r:r>e;r+=t)i.push(r);return i}function kolakoskiGen(n){var e=[1,2,2],t=parseInt(n),r=range(2,t);for(i in r)if(-1!=r.indexOf(parseInt(i))){var f=[1+i%2];f.length=f.length*e[i],f[f.length-1]=f[0],2==f.length?(e[e.length]=f[0],e[e.length]=f[1]):e[e.length]=f[0]}console.log(e)}

```

Could probably be more Efficient
> 0 votes

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


title: Golfing Python string literals

text:
# Question
Title: Golfing Python string literals
## Background

Python 3 has many types of string literals. For example, the string `this 'is' an exa\\m/ple` can be represented as:

```
'this \'is\' an exa\\\\m/ple'
"this 'is' an exa\\\\m/ple"
r"this 'is' an exa\\m/ple"
'''this 'is' an exa\\\\m/ple'''
"""this 'is' an exa\\\\m/ple"""
r'''this 'is' an exa\\m/ple'''
r"""this 'is' an exa\\m/ple"""

```

As you can see, using different delimiters for strings can lengthen or shorten strings by changing the escaping needed for certain characters. Some delimiters can't be used for all strings: `r'` is missing above (see later for explanation). Knowing your strings is very useful in code golf.

One can also combine multiple string literals into one:

```
'this \'is\' an ''''exa\\\\m/ple'''
"this 'is' an "r'exa\\m/ple'

```

---

## Challenge

The challenge is, given a printable ASCII string, to output its *shortest* literal representation in Python.

### Details on string mechanics

Strings can be delimited using `'`, `"`, `'''` and `"""`. A string ends when the starting delimiter is hit again unescaped.

If a string literal starts with `'''` or `"""` it is consumed as the delimiter. Otherwise `'` or `"` is used.

Characters can be escaped by placing a `\` before them. This inserts the character in the string and eliminates any special meaning it may have. For example, in `'a \' b'` the middle `'` is escaped and thus doesn't end the literal, and the resulting string is `a ' b`.

Optionally, one of `r` or `R` may be inserted before the starting delimiter. If this is done, the escaping `\` will appear in the result. For example, `r'a \' b'` evaluates to `a \' b`. This is why `a ' b` cannot be delimited by `r'`.

To escape `'''` or `"""`, one only needs to escape one of the characters.

These literals can be concatenated together, which concatenates their contents.

### Rules

* The input is the string to golf. Printable ASCII only, so no newlines or other special characters.
* The output is the golfed string literal. If there are multiple solutions, output one.
* To simplify the challenge, in non-`r` strings any escapes except for `\\`, `\'` and `\"` are considered invalid. They must not be used in the output, even though `'\m'` is equal to `'\\m'` in Python. This removes the need to process special escape codes such as `\n`.
* Builtins for golfing Python strings are disallowed. Python's `repr` is allowed, since it's crappy anyway.
* Standard rules apply.

## Example inputs/outputs

I tried my best to verify these, but let me know if there are mistakes. If there are multiple valid outputs to the cases, they are all listed below the input.

```
test
 -> 'test'
 -> "test"
te\st
 -> 'te\\st'
 -> "te\\st"
 -> r'te\st'
 -> r"te\st"
te'st
 -> "te'st"
te"st
 -> 'te"st'
t"e"s't
 -> 't"e"s\'t'
te\'st
 -> "te\\'st"
 -> r'te\'st'
 -> r"te\'st"
te\'\"st
 -> r'te\'\"st'
 -> r"te\'\"st"
t"'e"'s"'t"'s"'t"'r"'i"'n"'g
 -> """t"'e"'s"'t"'s"'t"'r"'i"'n"'g"""
 -> '''t"'e"'s"'t"'s"'t"'r"'i"'n"'g'''
t"\e"\s"\t"\s'\t"\r"\i"\n"\g
 -> r"""t"\e"\s"\t"\s'\t"\r"\i"\n"\g"""
 -> r'''t"\e"\s"\t"\s'\t"\r"\i"\n"\g'''
t"""e"""s"""'''t'''s'''"""t"""r"""'''i'''n'''g
 -> 't"""e"""s"""'"'''t'''s'''"'"""t"""r"""'"'''i'''n'''g"
t\"""e\"""s\"""'''t'''s'''\"""t\"""r\"""'''i'''n'''g
 -> r"""t\"""e\"""s\"""'''t'''s'''\"""t\"""r\"""'''i'''n'''g"""
t"e"s"t"s"t"r"i"n"g"\'\'\'\'\'\'\'\
 -> r't"e"s"t"s"t"r"i"n"g"\'\'\'\'\'\'\'''\\'
 -> r't"e"s"t"s"t"r"i"n"g"\'\'\'\'\'\'\''"\\"
"""t"'e"'s"'t"'s"'t"'r"'i"'n"'g'''
 -> """\"""t"'e"'s"'t"'s"'t"'r"'i"'n"'g'''"""
 -> '''"""t"'e"'s"'t"'s"'t"'r"'i"'n"'g''\''''

```

Thanks to Anders Kaseorg for these additional cases:

```
\\'"\\'\
 -> "\\\\'\"\\\\'\\"
''"""''"""''
 -> '''''"""''"""'\''''

```

# Answer
# Python 3, ~~264~~ 262 bytes

```
f=lambda s,b='\\',r=str.replace:min(sum([['r'+d+s+d,d+r(r(s[:-1],b,b+b),d,d[1:]+b+d[0])+b*(s[-1:]in[b,d[0]])+s[-1:]+d][d in r(r(s+d[1:],b+b,'x'),b+d[0],b)or r(s,b+b,'')[-1:]==b:]for d in["'",'"',"'''",'"""']],[f(s[:k])+f(s[k:])for k in range(1,len(s))]),key=len)

```

Try it online!

This works but is very slow without memoization, which you can add with

```
import functools
f=functools.lru_cache(None)(f)

```

It found an improved solution for one of the test cases:

```
t"e"s"t"s"t"r"i"n"g"\'\'\'\'\'\'\'\
 -> 't"e"s"t"s"t"r"i"n"g"'r"\'\'\'\'\'\'\'"'\\'
 -> r't"e"s"t"s"t"r"i"n"g"\'\'\'\'\'\'\'''\\'

```

Previous versions of this answer returned incorrect results on the following, which could be added as test cases:

```
\\'"\\'\
 -> "\\\\'\"\\\\'\\"
''"""''"""''
 -> '''''"""''"""'\''''

```
> 7 votes

---
Tags: code-golf, string, python, optimized-output
---


title: Output Pi without math

text:
# Question
Title: Output Pi without math
In as few bytes as possible, your job is to write a program that outputs:

```
3.14

```

In celebration of a late Pi day of course! :)

## Rules

You can do it anyway you like, but there are some restrictions.

* You may **not** use arithmetic operations anywhere in your program. This includes `+`, `-`, `*`, `/`, `%`, `^` (exponentiation), etc... This also includes incrementing (usually `++`), decrementing (`--`), **bitwise operations**, and any built in functions that can be used as a replacement such as `sum()`, `prod()`, `mod()`, `double()`, `pow()`, `sqrt()`, `inc()`, `dec()`, etc... (Author's discretion)
* The digits `3`, `1`, and `4` may **not** appear anywhere in your code.
* You may **not** use any predefined variables/constants that your language may have as a replacement for `3`, `1`, and `4`. (Author's discretion)
* You may also **not** use any trigonometric functions such as `sin()`, `cos()`, `tan()`, `arcsin()`, `arccos()`, `arctan()`, `sinh()`, `cosh()`, `tanh()`, etc... (Author's discretion)
* You may **not** use built-in or predefined values of Pi (or `3.14`). *No web requests*.
* Your program **cannot** require input of any kind (besides running it).
* `3.14` is the **only** thing that you may output, it cannot be part of some longer/larger output..

## Winner

The answer with the least amount of bytes on **April 18th** wins. Good luck!

Looking forward to clever answers from clever minds! Malbolge anyone? :P

# Answer
> 25 votes
# CJam - ~~8~~ 6

```
S`,'.E

```

CJam is a new language I am developing, similar to GolfScript - http://sf.net/p/cjam.
Here is the explanation:

`S` is a variable preinitialized to space (" ")
``` generates the string representation of the last value - which is exactly `" "` (3 characters)
`,` calculates the string length (3)
`'.` is the dot character
`E` is a variable preinitialized to 14; 3, 1 and 4 are not allowed but it doesn't say anything about 14 :)

Credits to Doorknob for the backtick idea

# Answer
> 113 votes
## PHP - 22 bytes

```
<?=date('n.j',8899e5);

```

Pi Day in year 1998 was really cool!

# Answer
> 92 votes
## C, 39

*Assumes the machine is little-endian and uses IEEE floating-point standard.*

```
main(){printf("%.2f",*(float*)"P@I@");}

```

The fun fact is that `"P@I@"` is actually not related to `PI` but is equivalent to `0x40494050` which is the representation of `3.144550323486328`

http://ideone.com/uXVEtl

# Answer
> 50 votes
# dc, 11 9 bytes

```
zE[.]znPp

```
* `z` Push current stack depth (0) onto the stack
* `E` Push E<sub>16</sub> (==14<sub>10</sub>)
* `[.]` Push the string "."
* `z` Push current stack depth (3) onto the stack
* `n` Pop 3 and print as number
* `P` Pop "." and print as char
* `p` Pop 14 and print as number with newline

Output:

```
$ dc <<< zE[.]znPp
3.14
$

```

# Answer
> 42 votes
# JavaScript (*ES5*) 20 bytes

A variation of m.buettner's JS solution.

```
(x='.'+0xE).length+x

```

---

# Edit: JavaScript (*ES5*) 18 bytes

A variation of ComFreek's idea of using the base64 decode function.

```
atob('Mw')+'.'+0xE

```

---

# Edit: Javascript (*ES5*) 16 bytes

If the unary `+` operator is allowed to cast a string to a number, it can be reduced to:

```
+atob('MDMuMTQ')

```

# Answer
> 39 votes
# Haskell, 41 bytes

When is pi day in Australia?

```
p=(\(a:n:y:t:i:m:e:_)->[m,a,t,e])['.'..]

```

Edited to add: like the other Haskell answer, that outputs a string, so has quotes. You can score 33, and be strictly within the rules, but it's less fun:

```
p=putStr$map([','..]!!)[7,2,5,8]

```

# Answer
> 32 votes
**Morse Code, 33 Bytes**

```
morse -d ...-- .-.-.- .---- ....-

```

Technically speaking, the information only takes 21 bytes.

# Answer
> 27 votes
# J - ~~15~~ ~~11~~ 10 char

Made it shorter, using the fantastic `i:`.

```
6{i:6.28j8

```

Explained:

* `6.28j8` \- The complex number 6.28 + 8i.
* `i:` \- This is where the magic happens. `i:` on a complex number A+Bi, B≠0 takes B+1 equally spaced points from the interval \[-A,A\].
* `6{` \- Take element at index 6, which just so happens to be 3.14.

Previously, we had the following nonsense:

```
|.'.'2}":22b8d5

```

Explained by explosion:

```
         22b8d5  NB. 8d5 in base 22 = 4163
       ":        NB. convert to string
  '.'2}          NB. change character at index 2 to '.'
|.               NB. reverse to make '3.14'

```

# Answer
> 20 votes
# Linux command line, 35 bytes

This one is nowhere near winning, but here it is for the fun of it:

```
ping -w2 67502862|grep -oP '.\..\d'

```

Output (after 2 seconds):

```
$ ping -w2 67502862|grep -oP '.\..\d'
3.14
$

```

# Answer
> 16 votes
# GolfScript, ~~18~~ ~~13~~ 12

```
'.'.`,\.,n`,

```

Old version:

```
'...','.'.,'....',

```

It's very artistic, only 3 unique characters! ;)

How it works:

```
# cmd   # stack
'...',  # 3
'.'.    # 3 '.' '.'
,       # 3 '.' 1
'....', # 3 '.' 1 4

```

Here's an explanation of the 12-char version (much more interesting, IMO):

```
'.' # '.'
.`, # '.' 3
\.  # 3 '.' '.'
,   # 3 '.' 1
n`, # 3 '.' 1 4

```

It works because `n`,` is `4`, since `n`` is `'"\n"'`. Same logic for `'.'`,`. It also swaps instead of creating a new string to save a char (thanks @algorithmshark).

Alternate version:

```
'pi ','.'.,'day!',

```

or

```
'Hi ','.'.,'PPCG',

```

Or anything in those strings, really. :P

# Answer
> 14 votes
OP's answer.

# Mathematica, 21 20 18

This feels cheap...

```
Range[2,5,.06][[20]]

```

or

```
Range[2,5,.02][[58]]

```

Figured out how to make it 18:

```
Range[-.86,5][[5]]

```

# Haskell, 49 48 12

(48 includes the new line character)

```
p=[-6..]
r=concat$show(p!!9):".":(show$p!!20):[]

```

Run it by calling the `r` function.

Using the method as with Mathematica above, you can type this into GHCi:

```
[-2.86..]!!6

```

# Java, 87 86

```
class P{public static void main(String[]a){System.out.print("tri".length()+"."+0xe);}}

```

# Scala, 27

Translated from Java as suggested by **Score\_Under**. (I don't really know Scala)

```
print("tri".length+"."+0xe)

```

# Answer
> 12 votes
# Bash, 50

Help/error messages aren't external resources, they're a command's output!

If anything is rule abuse, this is it. It uses the coincidence that the help message given to `STDERR` by the exact command

```
ping6

```

is 314 characters long (at least on Ubuntu 13.10 with `iputils-121221`). EDIT: I appreciate that this is much less portable than I expected...

```
m=`ping6|&wc -c`
false
o=$?
echo ${m:0:o}.${m:o:2}

```

The first line takes the character length of the help message and stores it in a variable.

As in my other answers, the next few lines obtain the number 1 by taking the exit status of `false` (not very portable but this is after all!), then use that value to insert a decimal point in the last line

Output: `3.14`

# Answer
> 11 votes
# Bash+TeX 28 bytes

If you have TeX installed:

```
tex -v|head -c8|cut -d\  -f2

```

The version number of TeX asymptotically approaches pi as the software improves. So, as time goes on, you can use this (nonconforming) implementation to print more and more digits!

```
tex -v|cut -d\  -f2 | head -n1

```

This printed 3.1415926 back in 2011; as of January 2014, it will print 3.14159265.

# Answer
> 10 votes
## JavaScript, 20 bytes

```
'...'.length+'.'+0xe

```

Use it in a console, so that the result is directly printed. Otherwise, `alert(...)` will add another 7 characters.

Same as my other answer, I just noticed it's a lot shorter in JS.

The idea of using `0xe` for 14 is taken from the OP's submission with the OP's kind permission.

# Answer
> 10 votes
# GNU date, 17 bytes

```
date -d2/5 +%u.%y

```

This one only guaranteed to work this year, but I don't see any limitation in the rules about this ;-)

The `+` is simply indicates the start of the format specifier for `date` and is not an arithmetic addition. Same with the `-`, indicating input date.

Output:

```
$ date -d2/5 +%u.%y
3.14
$

```

# Answer
> 10 votes
# Bash, 17 bytes

```
tr 0 .<<<$[62#MC]

```

---

# Dash, 41 bytes

```
perl -pechomp,s/./$./<<$

..

.

```

# Answer
> 7 votes
## Bash 23 22

```
seq 2 .02 5|sed -n 58p

```

---

## Shell (without history expansion) 20

```
seq 2 .02 5|sed 58!d

```

# Answer
> 6 votes
## Python, 39 or 28 ~~47 or 34~~

(Thank you Score\_Under for golfing it down so much)

```
print"%s.%s%c"%(len('aaa'),len('a'),52)

```

`+` here is the string concatenation operator, not addition.

Copying the `0xe` trick from the OP, here's 28 chars with help from @psal

```
print('%X.%s'%(675,0xE))[2:]

```

Old versions:

```
print str(len('aaa'))+'.'+str(len('a'))+chr(52)

print str(len('aaa'))+'.'+str(0xe)

print"%s.%s"%(len('aaa'),0xe)

```

# Answer
> 5 votes
# GolfScript, 8 bytes

```
'??.'(\(

```

This program contains non-printable ASCII characters, so it cannot be directly pasted here. Instead, the question marks in the code above should be replaced with the bytes `03` and `0E` in hexadecimal.

For convenience, here's a hex dump of the actual program. Unix / Linux users can run this hex dump through `xxd -r` to reconstruct the program:

```
0000000: 2703 0e2e 2728 5c28                      '...'(\(

```

Explanation:

* The first five bytes of the program form a single-quoted string literal encoding the three characters with the ASCII codes 3, 14 and 46 (= ASCII period).
* `(` chops the first character off the string and pushes its ASCII code (3) on the stack. `\` swaps the top two items on the stack, pulling the string back to the top, and the second `(` chops another character off the string, again pushing its ASCII code (14) on the stack.

At the end of the program, the stack (excluding the empty input string) therefore looks like this:

```
3 "." 14

```

At the end of the program, the default behavior of the GolfScript interpreter is to stringify and print everything on the stack, yielding the desired output.

# Answer
> 5 votes
# bash -- 39

We all know that the first few digits of Pi can be computed from the following statement:

> May I have a large container of coffee

We need only 2 decimal places, right?

```
m=May
i=I
h=have
echo ${#m}.${#i}${#h}

```

# Answer
> 4 votes
## Perl, 15 20 bytes

```
print 05706=~s/0/./r
print 0xbc6=~s/0/./r

```

# Answer
> 4 votes
## Mathematica - 78

```
DateList["March"<>ToString@FromDigits@"E"]~DateString~{"MonthShort",".","Day"}

```

# Answer
> 4 votes
# tr \+ Bash, 17 bytes

```
tr a-j 0-9<<<d.be

```

The `-` chars here are not arithmetic subtraction operators. They indicate range.

Output:

```
$ tr a-j 0-9<<<d.be
3.14
$

```

# Answer
> 4 votes
## BASH, 57

This is longer than most answers, but there is nothing bad in trying.

```
f=`echo aaaaaaaaaaaaa|wc -c`;e=`echo aa|wc -c`;echo $e.$f

```

gives

```
3.14

```

# Answer
> 4 votes
## C, 36

```
main(){printf("%d\b.%o\b",' ','`');}

```

# Answer
> 3 votes
## JavaScript - 23 bytes

```
atob('Mw')+atob('LjE0')

```

Thanks to nderscore (see his comments)!

# Answer
> 3 votes
# GolfScript, ~~13~~ 10

```
{xy}.*'.'\

```

Thanks to **Ilmari Karonen** for the improved version!

`x` and `y` are non-printable characters (see http://www.asciitable.com/ for more info), respectively `ETX` and `SO`, which decode to 3 and 14.

What this code does should be pretty clear.

**Note:** The following rule

`You may not use any predefined variables/constants that your language may have as a replacement for 3, 1, and 4. (Author's discretion)`

is not broken, since ASCII characters are neither variables, nor constants.

# Answer
> 3 votes
**C#**

```
 ((int)'ĺ').ToString("#\\.##");

```

ĺ is character 314, not a pre-defined variable or constant. the .ToString formats the output into a digit, a period, and then 2 more digits.

# Answer
> 3 votes
New to the site and can't write comments yet, so I'll post it here. Just wondering about this Javascript solution:

```
'...'.length+'.'+0xe

```

and this rule:

*3.14 is the only thing that you may output, it cannot be part of some longer/larger output..*

If I run this code in my browser console, I get:

```
"3.14"

```

or using Node at the command line:

```
'3.14'

```

but if I run this code:

```
parseFloat('...'.length+'.'+0xe)

```

I get:

```
3.14

```

Using Node.js to run a .js file, I can write:

```
console.log('...'.length+'.'+0xe)

```

and get:

```
3.14

```

# Answer
> 2 votes
## Mathematica, 56 bytes

```
(l=ToString@StringLength@#&)@"..."<>"."<>l@"."<>l@"...."

```

Not much to say. I'm generating the digits as string lengths and concatenate them.

# Answer
> 2 votes
## Python, 49

```
a=str(range(298,500,2)[8]);print a[0]+'.'+a[5<6:]

```

Explanation

* `range(298,500,2)[8]`-Clever way to get `314`
* `a=str(314)` \- `'314'`
* `a[0]`-`3`
* `5<6`-Shorter than `True` which means `1`
* `a[5<6:]` \- `a[1:]` \- `'14'`
* `print a[0]+'.'+a[5<6:]` \- Putting the `.` and printing. The `+`s are string-concatenators.

---

## Python <sub>(abusing the rules unless OP abuses their discretion)</sub>52 43

```
from cmath import*
print round(phase(-2),2)

```

# Answer
> 2 votes
# Pure bash, 22 bytes

```
a=.$[0xE];echo ${#a}$a

```

Output:

```
$ a=.$[0xE];echo ${#a}$a
3.14
$

```

`$[0xE]` is just a base conversion with no actual arithmetic explicitly performed, so I assume this is legal.

# Answer
> 2 votes
# Perl, 22 bytes

```
print pack N,858665268

```

# Answer
> 2 votes
# **BF,45 chars(without \n)**

How About BF

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

```

thanks for pointing out that it only needs 3.14

# Answer
> 2 votes
# Bash, 53 (using `seq`)

Does `seq` count as arithmetic?

Reuses bits of my other answer. Based on string length - it generates a string which is 314 characters long.

```
m=`seq -8 99|wc -c`
false
o=$?
echo ${m:0:o}.${m:o:2}

```

Line 1 generates a sequence of integers between -8 and 99 using `seq` and sends the result to `wc -c` which counts the number of bytes in its input. The result is stored in `m`.

After this point, it's the same as my other answer:

`m` should now be 314. Now I want to insert a decimal point after the first character... *but I'd need the digit 1 to do that!*

Lines 3 and 4 circumvent that by taking the exit status of `false` and storing it in a variable. The exit status of `false` isn't 1 on some systems, so this isn't very portable, but this is after all!

Line 5 concatenates the first character of `m`, a decimal point and the next two characters of `m`, and prints the result to standard output.

Output: `3.14`.

# Answer
> 2 votes
## PowerShell - 47 24 20

Update: after seeing @grax's answer, use a single `[char]`, and use format string.

```
'{0:#\.##}'-f+"ĺ"[0]

```

# Answer
> 2 votes
# JavaScript, 22

Just a modification of ComFreek's idea

```
atob(atob('TXk0eE5B'))

```

# JavaScript, 150

A different way just for fun

```
while(!m||a[0]>=(0+a)[a.length]){a=(Math.random()+"").replace(/(.)(.)(.*)(.)(..)/,"$2.$5");
m=a.match(/([^0-25-9]).[^02-9][^0-25-9]/)}m[0]

```

The idea was to get a random numbers until it is the desired one. Challenge was not to use the forbidden digits :) The two regexes should be possible to combine into one but I'm too tired now :)

# Answer
> 2 votes
## **Matlab - 39 characters with a bit of magic**

39 characters:

```
x=magic(6);fprintf('%d.%d\n',x([2,29]))

```

output:

```
3.14

```

magic(6) produces a magic square of size 6x6. It happens to provide the same square every time, which allows us to cherry-pick numbers. Matlab R2011b is used here.

# Answer
> 1 votes
# Bash, 72

I would use `base64`... *if the digit 4 didn't appear in it!!*

I might have used `tr` but that's already been done...

So instead I'm going to misuse `chmod`, which is by no means the shortest solution. What this script does is set its own permissions to the octal mode `314`, then insert a decimal point.

```
chmod u=wx,o=r,g=x $0
m=`stat -c%a $0`
false
o=$?
echo ${m:0:o}.${m:o:2}

```

The first line sets the script file's permissions to the equivalent of octal mode `314` (`--wx--xr--`).

The second line uses `stat` and its `--format` option (shortened to `-c`) to get the file's octal mode only, represented by `%a`. The result is saved to a variable `m`.

After the second line, `m` should be 314. Now I want to insert a decimal point after the first character... *but I'd need the digit 1 to do that!*

Lines 3 and 4 circumvent that by taking the exit status of `false` and storing it in a variable. The exit status of `false` isn't 1 on some systems, so this isn't very portable, but this is after all!

Line 5 concatenates the first character of `m`, a decimal point and the next two characters of `m`, and prints the result to standard output.

Output: `3.14`.

# Answer
> 1 votes
# Ruby - 78

Long one, but it can be easily extended to print more digits.

```
a="How I wish".split(' ')
print "#{a.shift.length}."
a.each{|w|print w.length}

```

And the output: `3.14`

Longer(194) version for more digits:

```
a="How I wish I could enumerate pi easily since all these bullshit mnemonics prevent recalling any of the sequence more simply".split(' ')
print "#{a.shift.length}."
a.each{|w|print w.length}

```

and output: `3.14159265358979323846`.

# Answer
> 1 votes
## PHP (30 bytes)

Longer than most here, but uses only very dirty tricks:

```
<?=ceil(2.5).'.'.(!0).chr(52);

```

Another version (29 bytes), if error reporting is disabled, otherwise outputs a notice:

```
<?=ceil(2.5).'.'.hexdec(E);?>

```

# Answer
> 1 votes
## C, 58

```
main(){printf("%d.%d%c",(int)ceil(2.9),(int)ceil(.8),52);}

```

## C, 43

With a little cheating. Constants for `14` were not forbidden.

```
main(){printf("%d.%d",(int)ceil(2.9),0xe);}

```

# Answer
> 1 votes
**VB.NET - 0**

After failing to write anything under 16 bytes, I decided to just make a joke answer. A PictureBox holds a saved screenshot of the "3.14" from the original post, instead of actual digits, so if you're looking for output in text format, I have failed.

But hey, I didn't have to write any code at all! And technically it shows *exactly* what the original post says to output...

# Answer
> 1 votes
## Oracle SQL,56

```
select to_char(to_date('70907','YMMDD'),'Q.WD')from dual

```

Output:

```
3.14

```

# Answer
> 1 votes
# BASH

Not the shortest of the bunch, but it doesn't contain any numbers so I thought it was kind of cool:

## 29 bytes

```
wc<<<'a

'|sed 's/ /./;s/ //'

```

Output:

```
3.14

```

# Answer
> 1 votes
## Java, 65

```
System.out.println("abc".length()+"."+"abcdefghijklmn".length());

```

# Answer
> 0 votes
# C++, ~~214~~ 202

Only works for little-endian processors... Big-endian version would be shorter.

```
#include<algorithm>
#include<iostream>
#include<iterator>
union u{int i;char c[];};struct s{u a,b;};int main(){s x;x.a.i=858665268;std::reverse_copy(x.a.c,x.b.c,std::ostream_iterator<char>(std::cout));}

```

# Answer
> 0 votes
# JavaScript - ~~46~~ 43

Not very original, but who cares :)

```
(a="a+b").length+(b=".")+b.length+(a+b).length

```

And after some help from nderscore:

```
(a="a+b")[L="length"]+(b=".")+b[L]+(a+b)[L]

```

(Note: all occurrences of `+` are string concatenations).

# Answer
> 0 votes
## Java, 106 95

```
class A{public static void main(String[]a){System.out.print((""+(int)'ཊ').replace('9','.'));}}

```

# Answer
> 0 votes
# PHP, 22

`<?=ceil(M_E),'.',0xE?>`

3,1,4 does not appear in the code and M\_E is none of them

# Perl, 29

`printf "%d.%d",(-2..5)[5],0xE`

# Perl, 25

`print((-2..5)[5],".",0xE)`

# Awk 54

`END{split(systime(),a,"");printf a[2]"."a[7-6]"%c",52}`

# Awk (Bonus)

`END{O=""=="";X=O""O;X+=O+=O+O;print O"."X;}`

I know it uses arithmetics but at least there are no numbers at all! XOXOXOX

# Answer
> 0 votes
## APL (with lambdas), 21 character (byte count depend on encoding)

APL capable font needed to see this.

```
{⍴⍵,⍎⍵}'⍞←⌽".",⍕⍴⍕⍳2'

```

Here explained

```
{⍴⍵,⍎⍵}'⍞←⌽".",⍕⍴⍕⍳2'
⍴'⍞←⌽".",⍕⍴⍕⍳2',⍎'⍞←⌽".",⍕⍴⍕⍳2' # lambda applied
⍴'⍞←⌽".",⍕⍴⍕⍳2',⍞←⌽".",⍕⍴⍕⍳2    # string is being evaluated as expression
⍴'⍞←⌽".",⍕⍴⍕⍳2',⍞←⌽".",⍕⍴⍕1 2   # ⍳2 expanded to 1 2
⍴'⍞←⌽".",⍕⍴⍕⍳2',⍞←⌽".",⍕⍴'1 2'  # 1 2 stringized
⍴'⍞←⌽".",⍕⍴⍕⍳2',⍞←⌽".",⍕3       # got dimension of '1 2'
⍴'⍞←⌽".",⍕⍴⍕⍳2',⍞←⌽".",'3'      # 3 stringized
⍴'⍞←⌽".",⍕⍴⍕⍳2',⍞←⌽'.3'         # '.' and '3' concatenated
⍴'⍞←⌽".",⍕⍴⍕⍳2',⍞←'3.'          # '.3' reversed
⍴'⍞←⌽".",⍕⍴⍕⍳2','3.'            # '3.' printed
⍴'⍞←⌽".",⍕⍴⍕⍳23.'               # '⍞←⌽".",⍕⍴⍕⍳2' and '3.' concatenated
14                              # got dimension of '⍞←⌽".",⍕⍴⍕⍳23.'
                                # finally, '14' printed

```

# Answer
> 0 votes
# PowerShell, 19 bytes

```
+''[0],0xe-join'.'

```

The third character is the non-printable control char ETX, ascii code 3. Hex dump:

```
Offset(h) 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F
00000000  2B 27 03 27 5B 30 5D 2C 30 78 65 2D 6A 6F 69 6E  +'.'[0],0xe-join
00000010  27 2E 27                                         '.'

```

This feels like cheating. I did have to use a '3' after all in the hex editor. Personally, I don't think an answer requiring the use of a hex editor should be allowed. If your language supports escaping non-printable chars, fine, but if it can't be copy/pasted from here, I don't think it should be allowed, JMO.

---

PowerShell, 20 bytes

```
+'ಎ'[0]-replace2,'.'

```

---

PowerShell, 21 bytes

```
(5..2)[2],0xe-join'.'

```

---

PowerShell, 22 bytes

```
(-6..20)[9,20]-join'.'

```
* Array from -6 to 20
* Indexes 9 and 20 grab 3 and 14
* Join on dot (.)

---

PowerShell, 24 bytes

```
[int]'ಎ'[0]-replace2,'.'

```
* 'ಎ' is a string with the unicode char 3214
* 'ಎ'\[0\] gets the char
* \[int\]'ಎ'\[0\] casts to an int with value 3214
* -replace converts 3214 to a string and swaps the 2 for a dot (.)

# Answer
> 0 votes
**C 71**

```
int main(){printf("%d.%d%d",strlen("***"),strlen("*"),strlen("****"));}

```

# Answer
> 0 votes
## Java 41 / 83 characters

```
System.out.println((int)''+"."+(int)'');

```

Unfortunately copy pasting directly into the IDE from here might not work. The characters inside the `''` don't show correctly here, but they are essentially variations on the space ASCII character with the decimal values 3 and 14. Below a full compilable version;

```
class C{public static void main(String[]a){System.out.println((int)''+"."+(int)'');}}

```

# Answer
> 0 votes
### ksh 19

```
echo ${#0}.$((0xe))
3.14

```

# Answer
> 0 votes
# Brainfuck - 39

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

```

Note that `+` and `-` are not arithmetic operators.

# Answer
> 0 votes
**Python 3, 45 bytes**

```
a=str(ord("ĺ"))
print("%s.%s"%(a[0],a[True:]))

```

(Had to use `True` to get around the restriction on the digit 1...)

# Answer
> 0 votes
# Python 2, 40

Doesn't bend the rules at all.

```
print('%i\b.%i'%(ord(' '),ord('î'))[:-1]

```

Extended ASCII ftw. Shame I couldn't put `\b` at the end of my string and remove the `()[:-1]`...

# ~-~!, also 40

```
'=~~,~~~~~,~~~~~:@'+~:@'-~~~~:@'-~:@'+~~

```

# Answer
> 0 votes
# Object disoriented \- 72 characters

```
dmain.ozozososozozososozozosozosososozozozososozozozosozozososozosozozzz

```

Boring answer, but the most compact I've achieved.

# Answer
> 0 votes
## T-SQL, 36

This entry assumes CHECKSUM() is allowed.

```
PRINT STUFF(CHECKSUM('2~2'),2,2,'.')

```

Try the SELECT version in SQL Server 2012 here.

# Answer
> 0 votes
## TinyMUSH, 16

This entry assumes decrypt() is allowed.

```
\decrypt(A<?B,.)

```

# Answer
> 0 votes
# Tcl, 28

```
puts [scan ^C %c].[scan ^N %c]

```

^C and ^N are one byte. Each one is obtained by pressing Alt+03 and Alt+014. They correspond to ASCII control chars ♥ and ♫

# Answer
> 0 votes
# JavaScript, 32 bytes

```
'３.１４'.normalize('NFKD')

```

Not sure if it is valid, and it also not the shortest. But post this just for fun since did not find a similar one.

---
Tags: code-golf, pi
---


# Question
Title: Find the coefficients of a rational generating function
If we write a sequence of numbers as the coefficients of a power series, then that power series is called the (ordinary) **generating function** (or G.f.) of that sequence. That is, if for some function `F(x)` and series of integers `a(n)` we have:

```
a(0) + a(1)x + a(2)x^2 + a(3)x^3 + a(4)x^4 + ... = F(x)

```

Then `F(x)` is the generating function of `a`. For example, the geometric series tells us that:

```
1 + x + x^2 + x^3 + x^4 + ... = 1/(1-x)

```

So the generating function of `1, 1, 1, ...` is `1/(1-x)`. If we differentiate both sides of the equation above and multiply by `x` we get the following equality:

```
x + 2x^2 + 3x^3 + 4x^4 + ... = x/(1-x)^2

```

So the generating function of `1, 2, 3, ...` is `x/(1-x)^2`. Generating functions are a very powerful tool, and you can do many useful things with them. A short introduction can be found here, but for a really thorough explanation there is the amazing book generatingfunctionology.

---

In this challenge you will take a rational function (the quotient of two polynomials with integer coefficients) as input as two arrays of integer coefficients, first the numerator then the denominator. For example the function `f(x) = x / (1 - x - x^2)` will be encoded as `[0, 1], [1, -1, -1]` in the input.

Given this input your program must infinitely print the coefficients of the power series that equals the generating function, one per line, starting at the coefficient of `x`, then `x^2`, etc.

---

Examples:

```
[1], [1, -1] -> 1, 1, 1, 1, 1, 1, 1, ...
[1], [2, -2] -> 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, ...
[0, 1], [1, -2, 1] -> 1, 2, 3, 4, 5, 6, 7, 8, ...
[0, 1], [1, -1, -1] -> 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
[1], [1, -2] -> 1, 2, 4, 8, 16, 32, 64, 128, ...
[0, 1, 1], [1, -3, 3, -1] -> 1, 4, 9, 16, 25, 36, ...

```

# Answer
> 7 votes
# Haskell, 63 bytes

```
z=0:z
(a:b)%y@(c:d)=a/c:zipWith(-)(b++z)(map(a/c*)d++z)%y
_%_=z

```

Try it online!

Defines an operator `%` returning an infinite lazy list of coefficients. The list is zero-indexed, so the constant coefficient is included.

# Answer
> 3 votes
# Mathematica, 64 ~~83~~ ~~90~~ bytes

```
Do[Echo@Limit[D[#/#2/i!&@@Fold[x#+#2&]/@#,{x,i}],x->0],{i,∞}]&

```

Thanks to @ngenisis and @Jenny\_mathy !

Take input as two lists.

Need `Alt+.` to terminate the execution to see the result. Frontend may crash due to rapid output.

83 bytes version (@Jenny\_mathy):

```
i=1;v=Tr[#*x^Range@Length@#]&;While[1<2,Echo@Limit[D[v@#/v@#2/i!,{x,i}],x->0];i++]&

```

# Answer
> 1 votes
## CJam (22 bytes)

```
{\{(W$(@\/_pW*f*.+1}g}

```

Online demo. Note that as many of the existing answers, this includes the 0th coefficient in the output.

### Dissection

```
{           e# Define a block which takes numerator N and denominator D as arguments
  \         e# Flip to put D at the bottom, since that won't change
  {         e# Infinite loop:
    (       e#   Pop the first element of (the modified) N
    W$(     e#   Copy D and pop its first element
            e#   Stack: D N[1:] N[0] D[1:] D[0]
    @\/     e#   Bring N[0] to top, flip, divide
            e#   Stack: D N[1:] D[1:] N[0]/D[0]
    _p      e#   Print a copy
    W*f*.+  e#   Multiply by -1, multiply all, pointwise add
            e#   Stack: D N[1:]-(N[0]/D[0])*D[1:]
  1}g
}

```

# Answer
> 0 votes
# Mathematica, ~~86~~ 79 bytes

```
f=x^Range@Length@#.#&;For[n=1,8>3,Print@SeriesCoefficient[f@#/f@#2,{x,0,n++}]]&

```

Takes input as two separate lists (numerator coefficients, denominator coefficients). If the input can be taken directly as a fraction of polynomials rather than as lists of coefficients, this can be shortened significantly.

It seems that `Do` can work with infinite bounds in v11. I can't test this locally, but, if this is the case, then this solution can be shortened to **75 bytes**:

```
f=x^Range@Length@#.#&;Do[Print@SeriesCoefficient[f@#/f@#2,{x,0,n}],{n,∞}]&

```

# Answer
> 0 votes
# Pyth, 23 bytes

```
JE#
KchQhJ=t-M.t,Q*LKJ0

```

Try it online!

### How it works

```
                       Q = eval(input())
JE                     J = eval(input())
  #                    infinite loop:
 chQhJ                   Q[0]/J[0]
K                        assign that to K (and print it, because of the preceding newline)
              *LKJ       K times every element of J
            ,Q           [Q, that]
          .t      0      transpose, padding with 0s
        -M               subtract each pair
       t                 remove the first element
      =                  assign that back to Q

```

# Answer
> 0 votes
# Pari/GP, 66 bytes

```
p->q->for(i=0,oo,print(Pol(Polrev(p)/(Polrev(q)+O(x*x^i)))\x^i%x))

```

Try it online!

---
Tags: code-golf, math, integer, polynomials
---


title: Let's play Rummikub!

text:
# Question
Title: Let's play Rummikub!
*Note: This is related to a variation of the game Rummikub*

---

# Background & Rules

*Rummikub* is a tile-based game. There are four colors: red, orange, blue and black. For each color there are 13 tiles (labeled from 1 to 13), and there are also 2 Jokers which are color-independent, hence there are 54 pieces in total. In this variation of Rummikub, each player receives 14 tiles and must get one more tile and drop another one each round, such that the tile count is constant. The players don't see each other's tiles. The goal is to group the tiles, such that all pieces belong to at least one group (see below). When a player has all the pieces grouped, they drop their tile board and reveal their pieces. The others then check if all the combinations are valid, and if they are, the player wins the round.

# How can the tiles be grouped?

There are only two types of groups:

* **Multi-color** groups:

+ They consist of 3 or 4 tiles.
    + They only contain tiles with the same number on them.
    + All the tiles are of different colors.
    + Example: `RED 9, BLUE 9, BLACK 9`.
* **Mono-color** groups:

+ They consist of at least 3 tiles.
    + They cannot contain more than 13 tiles.
    + They only contain tiles with different, consecutive numbers on them, in ascending order.
    + All the tiles have the same color.
    + Tiles labeled with `1` **may not** be places after tiles labeled `13`.
    + Example: `RED 5, RED 6, RED 7`.

### Wait, what do the Jokers do?

Jokers can substitue any piece in the game. For example, our first example can become `JOKER, BLUE 9, BLACK 9`, `RED 9, JOKER, BLACK 9` or `RED 9, BLUE 9, JOKER`. The same applies to our other example. However, one may *not* place two Jokers in the same group, so things like `JOKER, ORANGE 8, JOKER` are forbidden.

---

# Task

Given a Rummikub tile group, determine whether it is valid. You are guaranteed that no duplicate tiles will appear, except for the 2 jokers and that the tiles you receive as input are valid (eg. things like `60` will not appear).

# Input / Output

You may take input and provide the output by any standard method.

Some valid input formats: list of strings, list of tuples, nested lists, strings, or anything else you find suitable. The colors can be taken as Strings (e.g: `"Blue","Red", etc.`), as String abbreviations (please make Blue and Black tiles distinguishable), or as integers coresponding to a color. When it comes to Jokers, you should mention the way your program receives them as input. If you choose Strings, you may have something like `RED 9, JOKER, ...`, if you choose tuples you can have `(9,"RED"), ("JOKER")` or something equivalent. If it helps, you may receive a color for that Joker (which should not affect the output of your program). For example, you may have `("JOKER","RED")` or `("JOKER","BLUE")`, but that should not influence the output in any way.

Regarding the output, standard rules for a apply.

# Worked examples

Let's take an example, that would hopefully make it easier to understand. Given a group as follows, where each tuple represents a tile:

```
[(9, "RED"), (9, "ORANGE"), ("JOKER"), (9, "BLACK")]

```

This should return a truthy value, because the input is valid. In this case, the Joker substitutes `(9, "BLUE")`, and they form a multi-color group.

If you would be given the following group:

```
[(9, "BLUE"), (9, "ORANGE"), (9, "RED"), (9, "BLACK"), ("JOKER")]

```

It would be invalid, and thus you program should return a falsy value, because there is nothing left for the joker to substitute, because the maximum number of cards in a multi-color group is 4.

# Additional Test Cases

These are for an extended test suite that cover nearly all possible situations:

```
Input -> Output

[(1,"BLUE"),(2,"BLUE"),(3,"BLUE"),(4,"BLUE"),(5,"BLUE"), (6,"BLUE")] -> truthy

[(6,"BLUE"),(6,"RED"),(6,"BLACK)] -> truthy

[(5,"BLACK"),(6,"BLACK"),(7,"BLACK"),(8,"BLACK"),(9,"BLACK"),(10,"BLACK"),("JOKER"),(12,"BLACK")] -> truthy

[("JOKER"),(3,"BLUE"),(3,"RED")] -> truthy

[(8,"BLACK"),(2,"RED"),(13,"BLUE")] -> falsy

[(4,"RED"), (3,"RED"), (5,"RED")] -> falsy

[(5,"BLACK"), (6, "BLACK)] -> falsy

[("JOKER"),(5,"RED"),("JOKER")] -> falsy

[(4,"RED"),(5,"RED"),(6, BLUE")] -> falsy

[(4,"RED"),("JOKER"),(5,"RED")] -> falsy

[(12,"BLACK"),(13,"BLACK),(1,"BLACK")] -> falsy

```

This is , so the shortest code in bytes in every language wins!

# Answer
# APL (Dyalog), 58 bytes

Takes list of colors (1-4) as right argument and list of numbers as left argument. A Joker's number is denoted `(⍳4)` which is equivalent to `(1 2 3 4)` to indicate that it could be any of those. Likewise, its color is denoted `(⍳13)` to indicate that it could be any of the numbers from 1 through 13.

```
{(3≤≢⍺)∧((s⍵)∧⍺≡∪⍺)∨((s←{1∊≢∘∪¨⊃,¨/⍵})⍺)∧∨/∊(⊃,¨/⍵)⍷¨⊂⍳13}

```

Try it online!

### Algorithm

**There are three conditions, of which the last two have two conditions each:**

1. The run must have length greater than or equal to 3

**AND EITHER**

2. 1. a single number AND
    2. unique colors

**OR**

3. 1. a single color AND
    2. sequential numbers

**in order for the run to be valid.**

### Reading order

`3≤` 3 is less than or equal to the `≢⍺` number of tiles

and

`s⍵` all numbers are the same

and

`⍺≡∪⍺` the colors are unique

or

`1∊` 1 is among `≢∘∪¨` the number of unique `⊃,¨/` expanded  colors

and

`∨/` there exists at least one  among all `⊃,¨/⍵` expanded number runs `⍷¨⊂` one which is found in `⍳13` 1 through 13

### Full code explanation

`{``}` anonymous function where  is left argument and  is right argument

**3.2.**

`⍳13` the numbers 1 through 13

`(``)⍷¨` find the starting positions of each of the following runs:

`,¨/⍵` join each element of the numbers (creates a run for each Joker value)

disclose (because `/` reduces rank)

**ϵ**nlist (flatten)

`∨/` OR reduction (i.e. are any true?)

`(``)∧` AND:

**3.1**

`(``)⍺` the result of applying the following function on the list of colors:

`s←{``}`*s* (for **s**ame) which is the following anonymous function ( is *its* argument):

`,¨/⍵` join each element across (creates a run for each Joker value)

disclose (because `/` reduces rank)

`≢∘∪¨` the the number of unique elements in each list

`1∊` is one a member? (i.e. are there any all-same lists?)

`(``)∨`**OR:**

**2.2.**

`∪⍺` the unique colors

`⍺≡` are identical to the colors (i.e. they are unique)

`(``)∧` AND:

**2.1.**

`s⍵` the numbers are all the same

`(``)∧`**AND**

**1.**

`≢⍺` the number of colors (i.e. the number of tiles)

`3≤` three is less than or equal to that
> 6 votes

# Answer
# Python 2, ~~371 370 362 341 329~~ 325 bytes

* @Mr.Xcoder saved 1 byte: `str.split()` instead of `list literal`
* 8 bytes saved: shorthand for `len(x)-1`
* 19 bytes saved: `J O BK B R` for `Joker, Orange, Black, Blue, Red` literals
* @Mr.Xcoder saved yet another 12 bytes, Thanks!!
* Another 4 bytes thanks to @Mr.Xcoder

```
def f(x):
 j=sum("J"in i for i in x);z=len(x)-1
 if j>1or z<2:return False
 if j<1:return(all(i[0]==x[0][0]for i in x)and sum(i[1]==x[0][1]for i in x)<2)or(all(i[1]==x[0][1]for i in x)and sum(int(x[m+1][0])==int(x[m][0])+1for m in range(z))==z)
 return any(f([[k,(i+1,j)]["J"in k]for k in x])for j in'RBbO'for i in range(13))

```

Try it online!
> 3 votes

# Answer
# Jelly, ~~41~~ ~~40~~ ~~38~~ 36 bytes

```
EȧI=1ȦȯE
0,W€yµZç/ɓQ⁼⁸ȧ
L>2ȧ4p13ðç€Ṁ

```

Try it online! (comes with a test-suite footer)

Takes input as an array of `(color, value)` for regular tiles and `0` for jokers. Colors are represented as integers (although I'm not sure if that even matters for the current code).

Outputs `1` (truthy) or `0` (falsy).

### Explanation

```
L>2ȧ4p13ðç€Ṁ    Main link, checks if a sequence is valid. Args: sequence
L                 Get the length of the sequence.
 >2               Check if it's at least 3 tiles.
   ȧ4             And: yield 4 if it is, 0 otherwise.
     p13          Cartesian product: yield all possible tiles if
                  result was 4, empty array otherwise.
        ð         Begin a new dyadic chain with args (tiles, sequence).
         ç€       Call the first helper link for each tile with args (tile, sequence).

0,W€yµZç/ɓQ⁼⁸ȧ    First helper link, checks if a sequence is valid if jokers
                  are substituted for the given tile. Args: tile, sequence
0,                  Make a pair [0, tile].
  W€                Turn that into [[0], [tile]].
    y               Map all 0's (jokers) into tile in the sequence.
     µ              Begin a new monadic chain with args (sequence).
      Z             Transpose to get list [colors, values].
       ç/           Call the second helper link with args (colors, values).
         ɓ          Begin a new dyadic chain with args (sequence, valid).
          Q         Remove duplicate tiles from the sequence.
           ⁼⁸       Check if the sequence is unchanged (i.e. there were no duplicates).
             ȧ      And with the output of the second helper.

EȧI=1ȦȯE    Second helper link, checks if a sequence is valid assuming no duplicates.
            Args: colors, values
E             Check if all the colors are the same.
 ȧ            Logical and with the values array.
              Yields the values if they were, 0 if not.
  I           Find the differences between each value.
              Yields [] if the colors differed.
   =1         See if each difference is equal to 1.
              Yields [] if the colors differed.
     Ȧ        Check if the list was nonempty and all values were truthy.
              Yields 1 for valid mono-colors, 0 otherwise.
      ȯ       Logical or with the values array.
              Yields 1 for valid mono-colors, the values otherwise.
       E      Check if all the values are the same. For valid mono-colors
              this tests if all items of [1] are equal (obviously true).
              Yields 1 for valid sequences, 0 otherwise.

```
> 3 votes

# Answer
# Scala, ~~491~~ 477 chars, ~~491~~ 477 bytes

This challenge was fun; thanks.

```
var c=Seq("O","B","b","R")
t match{case _ if t.length<3=>false
case _ if t.exists(x=>x._1==0)=>{var b=false
if(t.filter(q=>q._1!=0).exists(q=>q._1==0))b else{for(y<-1 to 13)for(u<-c)b=b|f(t.takeWhile(q=>q._1!=0)++:(y,u)+:t.reverse.takeWhile(q=>q._1!=0).reverse)
b}}
case _::(x,_)::_ if t.forall(_._1==x)=>true
case _ if t.forall(_._2==c(0))|t.forall(_._2==c(1))|t.forall(_._2==c(2))|t.forall(_._2==c(3))=>(t(0)._1 to t(0)._1+t.length-1).toList equals t.map(_._1)
case _=>false}

```

So `f` at line 4 is a recursive call where I try replacing "JOKER" by every other tile. See tio for a clearer view of the code. I chose taking as input a sequence of 2-tuples (Int,String) - called `t` in my code, see tio \- so "JOKER" is represented by a 2-tuple (0,"JOKER").

EDIT : 14 bytes saved thanks to comments, I take O B b R for ORANGE BLACK BLUE RED.

Try It Online!

EDIT : -2 bytes, deleted useless `(` around conditions of the `case _ if`s
> 1 votes

# Answer
# Javascript (ES6), 286 bytes

```
var testcases = [[{n:1,c:"BLUE"},{n:2,c:"BLUE"},{n:3,c:"BLUE"},{n:4,c:"BLUE"},{n:5,c:"BLUE"}, {n:6,c:"BLUE"}],[{n:6,c:"BLUE"},{n:6,c:"RED"},{n:6,c:"BLACK"}],[{n:5,c:"BLACK"},{n:6,c:"BLACK"},{n:7,c:"BLACK"},{n:8,c:"BLACK"},{n:9,c:"BLACK"},{n:10,c:"BLACK"},{n:0,c:"JOKER"},{n:12,c:"BLACK"}],[{n:0,c:"JOKER"},{n:3,c:"BLUE"},{n:3,c:"RED"}],[{n:8,c:"BLACK"},{n:2,c:"RED"},{n:13,c:"BLUE"}],[{n:4,c:"RED"}, {n:3,c:"RED"}, {n:5,c:"RED"}],[{n:5,c:"BLACK"}, {n:6,c:"BLACK"}],[{n:0,c:"JOKER"},{n:5,c:"RED"},{n:0,c:"JOKER"}],[{n:4,c:"RED"},{n:5,c:"RED"},{n:6,c:"BLUE"}],[{n:4,c:"RED"},{n:0,c:"JOKER"},{n:5,c:"RED"}],[{n:12,c:"BLACK"},{n:13,c:"BLACK"},{n:1,c:"BLACK"}],[{n:11,c:"BLACK"},{n:12,c:"BLACK"},{n:0,c:"JOKER"}],[{n:1,c:"BLACK"},{n:2,c:"BLACK"},{n:3,c:"BLACK"},{n:1,c:"BLUE"},{n:2,c:"BLUE"},{n:3,c:"BLUE"}]];

g=a=>a.length
j=a=>a.n==0
l=(x,y)=>x.c==y.c||j(x)||j(y)
a=s=>g(s)>2&&([q=[0],x=s[0],s.map(y=>q[0]+=x==y||((l(x,y)||x.n==y.n)&&!(j(x)&&j(y)))&&(([n=s.indexOf(y),n<1||([x=s[n-1],!l(x,y)||y.n>0&&x.n<y.n])[1]||(n<g(s)-1&&x.n+1<s[n+1].n)||(n==g(s)-1&&y.n==0&&x.n<13)])[1])?1:0)])[0][0]==g(s)

testcases.forEach(H=>console.log(a(H)));
```

(Note that the test cases above contain 2 additional test cases that are not in the Question: they are true and false respectively: see the ungolfed version for readability).

Rough process:

```
 Using first tile x:
   For each tile y:
     count for x: can group with y
 return: x matches n tiles, where n is the number of tiles

```

Jokers are indicated by having a `0` as their numerical value (a negative number would work too); this keeps the input struct consistent (has both a Color and Value) and doesn't rely on having to check if `c=="JOKER"`, saving 7 bytes.

Its possible that some parentheses could be removed, it might be possible to not box `q` as an array (I tried it and the value just either stayed 0 or caused nasal demons).

Ungolfed:

```
var testcases = [
[{n:1,c:"BLUE"},{n:2,c:"BLUE"},{n:3,c:"BLUE"},{n:4,c:"BLUE"},{n:5,c:"BLUE"}, {n:6,c:"BLUE"}],//true
[{n:6,c:"BLUE"},{n:6,c:"RED"},{n:6,c:"BLACK"}],//true
[{n:5,c:"BLACK"},{n:6,c:"BLACK"},{n:7,c:"BLACK"},{n:8,c:"BLACK"},{n:9,c:"BLACK"},{n:10,c:"BLACK"},{n:0,c:"JOKER"},{n:12,c:"BLACK"}],//true
[{n:0,c:"JOKER"},{n:3,c:"BLUE"},{n:3,c:"RED"}],//true
[{n:8,c:"BLACK"},{n:2,c:"RED"},{n:13,c:"BLUE"}],//false
[{n:4,c:"RED"}, {n:3,c:"RED"}, {n:5,c:"RED"}],//false
[{n:5,c:"BLACK"}, {n:6,c:"BLACK"}],//false
[{n:0,c:"JOKER"},{n:5,c:"RED"},{n:0,c:"JOKER"}],//false
[{n:4,c:"RED"},{n:5,c:"RED"},{n:6,c:"BLUE"}],//false
[{n:4,c:"RED"},{n:0,c:"JOKER"},{n:5,c:"RED"}],//false
[{n:12,c:"BLACK"},{n:13,c:"BLACK"},{n:1,c:"BLACK"}],//false
[{n:11,c:"BLACK"},{n:12,c:"BLACK"},{n:0,c:"JOKER"}],//true
[{n:1,c:"BLACK"},{n:2,c:"BLACK"},{n:3,c:"BLACK"},{n:1,c:"BLUE"},{n:2,c:"BLUE"},{n:3,c:"BLUE"}]
];

g=a=>a.length
i=(a,v)=>a.indexOf(v)
j=x=>x.n==0
m=(x,y)=>
       (l(x,y)||x.n==y.n)
    &&!(j(x)&&j(y))
l=(x,y)=>x.c==y.c||j(x)||j(y)
c=(a,v)=>([n=i(a,v),
      n<1
    ||([x=a[n-1],!l(x,v)||v.n>0&&x.n<v.n])[1]
    ||(n<g(a)-1&&x.n+1<a[n+1].n)
    ||(n==g(a)-1&&v.n==0&&x.n<13)])[1]
a=s=>g(s)>2&&([q=[0],x=s[0],s.map(y=>q[0]+=x==y||m(x,y)&&c(s,y)?1:0)])[0][0]==g(s)

testcases.forEach(H=>console.log(a(H)));
```

Version I worked on to get the logic correct. Single-use lambdas got in-lined; here's their corresponding function:

```
g() -> string.length
i() -> indexof
j() -> isJoker
m() -> do tiles match
l() -> do colors match
c() -> same-color isConsecutiveOrder
a() -> main lambda

```
> 1 votes

# Answer
# C# (.NET Core), 198 bytes

```
using System.Linq;(C,N)=>{int l=C.Length,j=C.Count(x=>x<1),c=C.Distinct().Count(),n=N.Distinct().Count(),u=N.Min();foreach(var x in N)u*=0<(u&x)?2:0;return l>2&((u>0&n==l&c<2+j)|(n<2+j&c==l&l<5));};

```

Takes in the colors of tiles and numbers on them as separate lists of integers. The specifics of that mapping don't matter as long as each color has a different integer and Jokers are represented as 0.

The format for inputting numbers is pretty special though. The number that needs to be input for a number `n` is instead 2^n, while the number used to represent a joker should be (2^14)-1. This enables the bitwise and `u&x` to evaluate to u if the tile x has value equal to u or is a joker.

# C# (.NET Core), 200 bytes

```
using System.Linq;(C,N)=>{int l=C.Length,j=N.Count(x=>x<1),c=C.Distinct().Count(),n=N.Distinct().Count(),u=N.Min();foreach(var x in N)u=u==x|x<1?u+1:0;return l>2&((u>0&n==l&c<2+j)|(n<2+j&c==l&l<5));};

```

A 2 byte longer solution which isn't eclectic about input. Turns out just using a special case for jokers in the one place they were hard to deal with wasn't much longer than the clever bitwise operation I was so proud of. Here Jokers are (0,0), other numbers are as expected, and colors are represented any 4 values which are distinct from each other by C#'s default comparison (specifically, the Linq `Distinct()` operation must consider values for the same color as 'not distinct' and values for different colors as 'distinct').

Something which might be of use to other languages, `u*=!u++^x*x` would be equivalent to `u=u==x|x<1?u+1:0` in some languages; u^x is 0 iff u==x, and 0 times any int is 0, so u^x\*x would be 0 for either u==x or x==0 if C# didn't make bitwise operations lower precedence than mathematical ones. C# also can't interpret ints as bools without explicit casting. A language that tries harder to make types work might convert the values `0` and `not 0` to `false` and `true` before applying `!` to them though, and then when going back to an int interpret `!false` as 1 and `!true` as 0. All that said, I can't guarantee another language would actually benefit from the rest of the algorithm so it might not even come up.
> 1 votes

---
Tags: code-golf, decision-problem, board-game
---


title: Fill the histogram with water

text:
# Question
Title: Fill the histogram with water
**Imagine a histogram.** Pour an infinite amount of water on to it. Then stop. How much water does the histogram hold?

Let's say we have a histogram with columns of these heights:

1 3 2 1 4 1 3

That would look like this:

```
    #
 #  # #
 ## # #
#######
1321413

```

If we pour an infinite amount of water on this histogram, some of those holes will fill up, and we'll end up with this:

```
    #
 #..#.#
 ##.#.#
#######
1321413

```

Apparently, this histogram can hold 5 slots of water.

**Your task**, should you choose to accept it, is to calculate the number of slots of water that a given histogram can hold. You may accept the input as a list, string, array, matrix, bitmap or whatever format you like. The output should be nothing but a single integer, in any format you like.

The input will only contain column heights between 1 and 1000, and the input size is between 1 and 1000 columns.

**Test cases:**

```
1 -> 0
2 1 2 -> 1
1 3 2 1 4 1 3 -> 5
1 3 5 7 6 4 2 1 -> 0
7 1 1 1 1 1 1 1 1 1 7 -> 54
2 6 3 5 2 8 1 4 2 2 5 3 5 7 4 1 -> 35

```

If you're looking for possible ways to solve this problem, here's four.

This is code golf, so the least bytes of source code wins.

# Answer
# Retina, 16 bytes

```
(?<=# *) (?= *#)

```

Try it online! Link includes test case. Works by counting the spaces which are surrounded by `#`s.
> 1 votes

# Answer
# Python 2, 68 bytes

```
lambda l:sum(min(max(l[:i+1]),max(l[i:]))-v for i,v in enumerate(l))

```

Try it online!
> 0 votes

---
Tags: code-golf
---


# Question
Title: Are there any languages especially good at ASCII art?
I was wondering if there are any esoteric or golfing languages which specifically target text output and ASCII art?

For example, 05AB1E at least started by targeting base conversions. Are there any golfing languages targeting text output and text output art?

If so, do they have tip pages here, and are they in common use?

Note: I'm not looking for languages that are **able** to output ASCII art, but rather ones **intentionally** designed to be able to complete challenges in a relatively short and concise way.

# Answer
Well, as a matter of fact, there is! One such language is one I have been working on for a while called .

Under the hood, V is just vim, but all of the keystrokes are run automatically, and the contents of the vim buffer are printed to STDOUT when the program is over. This just makes running it more convenient.

Some history on the language. When I started using the vim text editor for code-golf, I discovered that it's actually pretty good at it, but has some annoying features that make it more difficult to compete it. For example, you can set up a "while loop" of sorts by doing

```
qq<foobar>@qq@q

```

which will repeat `<foobar>` until an error happens. This has 7 bytes of boilerplate code. In V, this is shortened to `ò<foobar>ò`.

Some of the things that make V great for ASCII-art:

* It is 2d by nature. One feature is that is has a "cursor" position, where most of the commands do something based on where the cursor is in the text. The other commands move the location of the cursor. For example,  deletes a single character, but Wx moves forward a word and *then* deletes a character. Since most other languages are not intentionally 2 dimensional, this offers a nice edge when the challenge is about positioning text in 2D space
* It is *entirely* string based. You *can* use some mathy operations, but these are usually the longer way to achieve things.
* It uses regex compression to quickly change text.
* All of it's internal memory, which is just a 2d array of characters, is implicitly printed when the program ends. Additionally, all inputs is implicitly added into it's internal memory, which is nice when most of the challenge is about changing the input in a certain way.

So I really enjoy using this language, and if you are looking for a specifically language, I highly recommend it. *However*, I would also give a few disclaimers.

* It is very confusing to learn. It's also very powerful, but because it's based on a very popular text editor that is 30 years old, there are lot's of obscure features that could very easily confuse new users.
* Even though it is better at handling numbers than vim, it's number support is still not great. Personally, I think this makes it more fun to work in (kind of like using retina for tasks regex was never intended for). :D
* It is still a WIP. There are some bugs, and some things I haven't gotten around to adding yet.
* It doesn't have very many users. (Current number of users: 1).

If you are interested in learning more, here are some good resources:

* A chat room where I would be happy to answer any questions you have, and help explain how it works to you.
* A tips thread for golfing in vim, but most of the tips carry over.
* A meta post describing V in some more detail.
> 15 votes

# Answer
I recently made a new programming language, called Turtlèd, which operates on a grid of characters with a turtle, which moves around the grid, writes to the grid, and has control flow with the grid. The grid is implicitly printed at the end. By this fact that it does not have to write spaces, and that it can write the text spatially, rather than left to right, up to down, it probably makes it meet the definition given, being good at ascii art.

Currently, there are not any docs, so you probably will not be able to use it, unless you want to read my interpreter, which is probably not something you want to do. I think there may also be bugs in the interpreter, but the spec is not developed enough to say if it is a bug. Turtlèd will probably be finished soon, with docs and all, though
> 8 votes

# Answer
# Intro to ASCII-Golfing for 05AB1E (Base Conversion \[Simple\])

While 05AB1E isn't intended for ASCII-Art directly, I've won 2 challenges with it. The best thing about 05AB1E is that, even with the simple base conversion there's often tricks you can use to extend and even halve your byte-count. Often in ASCII challenges there are repitition tricks you can utilize to only draw half the pattern then flip and concatenate. If it's a four way pattern you can do things like zip and bifurcate to only draw a corner of the pattern. There's plenty of data-structure manipulation techniques to use in conjunction with this simple base compression idea.

---

**Here's a quick crash-course on a base conversion tactic:**

In 05AB1E I enumerate all of the characters used in the ASCII-art, for instance:

`--===___===--`

Would result in:

```
-
=
_

```

I then assign them numbers starting with 1 then 0 then 2:

```
- is 1.
= is 0.
_ is 2.

```

I replace the characters in the original string with the numbers:

```
1122200022211

```

I convert to decimal using the lowest possible base (3):

```
879412

```

(How to do this using 05AB1E)

I then convert it to base 214:

```
Jh]

```

(How to do this using 05AB1E)

I then wrap it in the following code:

# 05AB1E, 16 bytes

```
•Jh]•3B…102…-_=‡

```

Try it online!

Or try it with intermediate steps displayed.

**Final explained:**

```
•Jh]•            # Push the compressed ASCII integer.
     3B          # Convert it to base 3.
       …102      # Push the keys to the conversion.
           …-_=  # Push the values to the conversion.
               ‡ # Transliterate, replace 0, 1 and 2 with the symbols.

```

Now, with this specific challenge the string is so short it doesn't make sense to do. I'd probably just push half the string and Palindromize for 10 bytes `"--===__"û` or golf it like Adnan did in the comments using factorial, smart man `•Jh]•3B5!…-=_‡`. He's also *(one of?)* the creator *(s?)* of 05AB1E.

---

**More complex example:**

https://codegolf.stackexchange.com/a/106621/59376

---

~~Also, maybe try Dennis' kolmogorov-complexity language: Bubblegum; no idea how to use this.~~
> 3 votes

# Answer
# Paintbrush

Paintbrush is a recreational programming language created by myself, Hyper Neutrino, for the purposes of being good at ASCII-Art. It doesn't compete well with Charcoal in many cases, but it can take input and do a variety of other things. It operates on a 2D grid of characters and is able to manipulate the background character, manipulate what is considered a background character at the time, shift rows and columns, move rows and columns, copy rows, columns, or the entire grid, etc.

Some examples may be found in the GitHub repository.
> 2 votes

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


title: Calculate the MU-numbers

text:
# Question
Title: Calculate the MU-numbers
The first two MU-numbers are 2 and 3. Every other MU-number is the smallest number not yet appeared that can be expressed as the product of two earlier distinct MU-numbers in exactly one way.

Here are the first 10

```
2, 3, 6, 12, 18, 24, 48, 54, 96, 162

```

## Task

Given a positive number calculate and output the **n**th MU-number.

This is a competition so you should aim to make your source code as small as possible.

OEIS A007335

# Answer
# Pyth, ~~22~~ 21 bytes

```
@u+Gfq2l@GcLTGheGQhB2

```

Try it online. Test suite.

0-indexed.

### Explanation

```
@u+Gfq2l@GcLTGheGQhB2Q    Implicitly append Q and read+eval input to it.
                  hB2     Take the list [2, 2 + 1].
 u               Q        Put the list in G and apply this Q times:
               eG           Get last number in G.
              h             Add one.
    f                       Starting from that, find the first T such that:
          cLTG                Divide T by each of the numbers in G.
        @G                    Find the quotients that are also in G.
       l                      Get the number of such quotients.
     q2                       Check that it equals 2.
  +G                        Append that T to G.
@                    Q    Get the Q'th number in G.

```
> 5 votes

# Answer
## Haskell, ~~80~~ 77 bytes

```
l#(a:b)|[x]<-[a|i<-l,j<-l,i<j,i*j==a]=a:(a:l)#b|1<2=l#b
((2:3:[2,3]#[4..])!!)

```

Try it online!

How it works

```
2:3:             -- start the list with 2 and 3 and append a call to # with
    [2,3]        -- the list so far and
         #[4..]  -- list of candidate elements

l # (a:b)        -- l -> list so far, a -> next candidate element, b -> rest c.el.
  | [x]<-[...]   -- if the list [...] is a singleton list
    =a:(a:l#b) -- the result is a followed by a recursive call with l extended
                    by a and b
  | 1<2=l#b      -- if it's not a singleton list, drop a and retry with b

                 -- the [...] list is
 [ i<-l,j<-l,    -- loop i through l and j through l and whenever
       i<j,      -- i<j and
       i*j==a]   -- i*j==a
  a|             -- add a to the list

```
> 4 votes

# Answer
# , ~~127~~ ~~118~~ ~~111~~ ~~108~~ ~~105~~ ~~100~~ ~~98~~ 90 bytes

8 bytes thanks to Giuseppe.

```
r=3:2;for(i in 1:scan())r=c(min((g=(r%o%r)[i:-1<i])[colSums(g%o%g==g*g)+g%in%r<3]),r);r[3]

```

Try it online!
> 3 votes

# Answer
# Jelly, 22 bytes

```
ŒcP€ḟ⁸ṢŒgLÞḢḢṭ
2,3Ç¡ị@

```

A monadic link, 1-indexed.

**Try it online!**

### How?

```
ŒcP€ḟ⁸ṢŒgLÞḢḢṭ - Link 1, add the next number: list, a  e.g. [2,3,6,12,18,24]
Œc             - unordered pairs                            [[2,3],[2,6],[2,12],[2,18],[2,24],[3,6],[3,12],[3,18],[3,24],[6,12],[6,18],[6,24],[12,18],[12,24],[18,24]]
  P€           - product of €ach                            [6,12,24,36,48,18,36,54,72,72,108,144,216,288,432]
     ⁸         - chain's left argument, a                   [2,3,6,12,18,24]
    ḟ          - filter discard                             [36,48,36,54,72,72,108,144,216,288,432]
      Ṣ        - sort                                       [36,36,48,54,72,72,108,144,216,288,432]
       Œg      - group runs of equal elements               [[36,36],[48],[54],[72,72],[108],[144],[216],[288],[432]]
          Þ    - sort by:
         L     -   length                                   [[48],[54],[108],[144],[216],[288],[432],[36,36],[72,72]]
           Ḣ   - head                                       [48]
            Ḣ  - head                                       48
             ṭ - tack to a                                  [2,3,6,12,18,24,48]

2,3Ç¡ị@ - Link: number, i                              e.g. 7
2,3     - literal [2,3]                                     [2,3]
    ¡   - repeat i times:
   Ç    -   call last link (1) as a monad                   [2,3,6,12,18,24,48,54,96]
     ị@ - index into with swapped @rguments (with i)        48

```
> 3 votes

# Answer
## CJam (32 bytes)

```
4,{_2m*{~>},::*1$-$e`$0=|}qi*-2=

```

Online demo with 0-indexing.

I'm not sure there's much to be done beyond a trivial translation of the spec with one exception: by starting with a list of `[0 1 2 3]` (instead of `[2, 3]`) I save one byte immediately on initialisation and another two by being able to do `0=|` (adding just the new element because its frequency is `1` and is already in the list), but don't introduce any false elements because for every `x` in the list `0*x` and `1*x` are already in the list.
> 2 votes

# Answer
# Python 2, ~~127~~ 118 bytes

```
n=input()
l=[2,3]
exec't=sorted(x*y for i,x in enumerate(l)for y in l[i+1:]);l+=min(t,key=(l+t).count),;'*n
print l[n]

```

Try it online!
> 2 votes

# Answer
# Mathematica, 154 bytes

simple modification of the code found at oeis link

```
(s={2,3};Do[n=Select[Split@Sort@Flatten@Table[s[[j]]s[[k]],{j,Length@s},{k,j+1,Length@s}],#[[1]]>s[[-1]]&&Length@#==1&][[1,1]];AppendTo[s,n],{#}];s[[#]])&

```
> 1 votes

# Answer
# PHP, 130 bytes

0-indexed

```
for($r=[2,3];!$r[$argn];$r[]=$l=min($m)/2){$m=[];foreach($r as$x)foreach($r as$y)($p=$x*$y)<=$l|$y==$x?:$m[$p]+=$p;}echo$r[$argn];

```

Try it online!

Expanded

```
for($r=[2,3];!$r[$argn]; #set the first to items and loop till search item exists
$r[]=$l=min($m)/2){ # add the half of the minimum of found values to the result array
  $m=[]; # start with empty array
  foreach($r as$x) # loop through result array
    foreach($r as$y) # loop through result array
      ($p=$x*$y)<=$l|$y==$x? # if product is greater as last value and we do multiple two distinct values
        :$m[$p]+=$p; # add 2 times or more the product to array so we drop 36 cause it will be 144
}
echo$r[$argn]; # Output

```

# PHP, 159 bytes

0-indexed

```
for($r=[2,3];!$r[$argn];$r[]=$l=min(array_diff_key($m,$d))){$d=$m=[];foreach($r as$x)foreach($r as$y)$x<$y?${dm[$m[$p=$x*$y]<1&$p>$l]}[$p]=$p:0;}echo$r[$argn];

```

Try it online!

# PHP, 161 bytes

0-indexed

```
for($r=[2,3];!$r[$argn];$r[]=$l=min(array_diff($m,$d))){$d=$m=[];foreach($r as$x)foreach($r as$y)$x<$y?${dm[!in_array($p=$x*$y,$m)&$p>$l]}[]=$p:0;}echo$r[$argn];

```

Try it online!
> 1 votes

# Answer
# Mathematica, 140 bytes

```
(t=1;s={2,3};While[t<#,s=AppendTo[s,Sort[Select[First/@Select[Tally[Times@@@Permutations[s,{2}]],#[[2]]==2&],#>Last@s&]][[1]]];t++];s[[#]])&

```
> 1 votes

# Answer
# MATL, 25 bytes

```
3:i:"t&*9B#u2=)yX-X<h]2_)

```

Try it online!

### Explanation

```
3:     % Push [1 2 3]. Initial array of MU numbers, to be extended with more numbers
i:     % Input n. Push [1 2 ... n]
"      % Do this n times
  t    %   Duplicate array of MU numbers so far
  &*   %   Matrix of pair-wise products
  9B   %   Push 9 in binary, that is, [1 0 0 1]
  #    %   Specify that next function will produce its first and fourth ouputs
  u    %   Unique: pushes unique entries (first output) and their counts (fourth)
  2=   %   True for counts that equal 2
  )    %   Keep only unique entries with count 2
  y    %   Duplicate (from below) array of MU numbers so far
  X-   %   Set difference
  X<   %   Minimum. This is the new MU number
  h    %   Concatenate vertically horizontally to extend the array
]      % End
2_     % Push 2 negated, that is, -2
)      % Get entry at position -2, that is, third-last. Implicitly display

```
> 1 votes

# Answer
## JavaScript (ES6), ~~119~~ ~~118~~ 117 bytes

A recursive function that takes a 0-based index.

```
f=(n,a=[2,m=3])=>a[n]||a.map(c=>a.map(d=>c<d&(d*=c)>m?b[d]=b[d]/0||d:0),b=[])|f(n,a.push(m=b.sort((a,b)=>a-b)[0])&&a)

```

### How?

At each iteration of ***f()***, we use the last term ***m*** of the sequence and an initially empty array ***b*** to identify the next term. For each product ***d \> m*** of two earlier distinct MU-numbers, we do:

```
b[d] = b[d] / 0 || d

```

and then keep the minimum value of ***b***.

The above expression is evaluated as follows:

```
b[d]               | b[d] / 0  | b[d] / 0 || d
-------------------+-----------+--------------
undefined          | NaN       | d
already equal to d | +Infinity | +Infinity
+Infinity          | +Infinity | +Infinity

```

This guarantees that products which can be expressed in more than one way will never be selected.

### Formatted and commented

```
f = (n, a = [2, m = 3]) =>           // given: n = input, a[] = MU array, m = last term
  a[n] ||                            // if a[n] is defined, return it
  a.map(c =>                         // else for each value c in a[]:
    a.map(d =>                       //   and for each value d in a[]:
      c < d &                        //     if c is less than d and
      (d *= c) > m ?                 //     d = d * c is greater than m:
        b[d] = b[d] / 0 || d         //       b[d] = either d or +Infinity (see 'How?')
      :                              //     else:
        0                            //       do nothing
    ),                               //   end of inner map()
    b = []                           //   initialization of b[]
  ) |                                // end of outer map()
  f(                                 // do a recursive call:
    n,                               //   - with n
    a.push(                          //   - push in a[]:
      m = b.sort((a, b) => a - b)[0] //     m = minimum value of b[]
    ) && a                           //     and use a[] as the 2nd parameter
  )                                  // end of recursive call

```

### Demo

```
f=(n,a=[2,m=3])=>a[n]||a.map(c=>a.map(d=>c<d&(d*=c)>m?b[d]=b[d]/0||d:0),b=[])|f(n,a.push(m=b.sort((a,b)=>a-b)[0])&&a)

for(var n = 0; n < 10; n++) {
  console.log('MU[' + n + '] = ' + f(n));
}
```
> 1 votes

# Answer
# Perl 6, 96 bytes

```
{(2,3,{first *∉@_,@_.combinations(2).classify({[*]
$_}).grep(*.value==1)».key.sort}...*)[$_]}

```

Try it online!

* `2, 3, { ... } ... *` is an infinite sequence where each element starting with the third is computed by the brace-delimited code block. Since the code block takes its arguments via the slurpy `@_` array, it receives the entire current sequence in that array.
* `@_.combinations(2)` is a sequence of all 2-element combinations of `@_`.
* `.classify({ [*] $_ })` classifies each 2-tuple by its product, producing a hash where the products are the keys and the values are the list of 2-tuples that have that product.
* `.grep(*.value == 1)` selects those key-value pairs from the hash where the value (ie, the list of pairs having that key as a product) has a size of 1.
* `».key` selects only the keys of each pair. This is the list of products that arise from only one combination of factors of the current sequence.
* `.sort` sorts the products numerically.
* `first * ∉ @_, ...` finds the first of those products that has not already appeared in the sequence.
> 1 votes

# Answer
# Python ~~3~~ 2, ~~167~~ ~~139~~ ~~136~~ ~~133~~ ~~123~~ ~~121~~ ~~120~~ 118 bytes

```
a=[2,3];exec'p=[x*y for x in a for y in a if x-y];a+=min(q for q in p if p.count(q)+(q in a)<3),;'*input();print a[-2]

```

Try it online!

---

Thanks to @Mr.Xcoder and @LeakyNun for improvements!
> 0 votes

# Answer
# Haskell, ~~117~~ ~~115~~ 113 bytes

```
n x=[a*b|[a,b]<-mapM id[1:x,x]]
d x=minimum[a|a<-n x,2==sum[1|b<-n x,b==a]]:x
l x|x<3=x+1:[2]|1>0=d$l$x-1
(!!0).l

```

Try it online!
> 0 votes

---
Tags: code-golf, sequence
---


# Question
Title: Trigger the chutes and protect the jackpot
You are going to participate in a gameshow. One of the challenges works as follows:

* The first room contains a large number of identical balls.
* The second room contains a series of chutes, each of which has a sensor which counts how many balls have been placed in it. A ball which is placed in a chute cannot then be recovered.
* Each chute will trigger after a certain number of balls (its *trigger count*) have been placed into it. When it triggers it flashes lights, makes a noise, and leaves you in no doubt that it has triggered.
* You must trigger `N` chutes to continue to the next challenge.
* You know the trigger counts, but not the correspondence between count and chute.
* You have one opportunity to take balls from the first room into the second. Once you put a ball into a chute, you cannot go back for more balls.
* Each ball which you take deducts money from the jackpot.

Obviously you want to ensure that you will pass the challenge, but you want to minimise the jackpot money loss. Write a program, function, verb, etc. to tell you how many balls you need.

### Example

Suppose the trigger counts are 2, 4, and 10, and you need to trigger 2 chutes to pass. There is a strategy to pass with 10 balls: place up to 4 balls in the first chute, up to 4 balls in the second chute, and up to 4 balls in the third chute. Since one of the three chutes will trigger after only 2 balls, you only use a total of 10. There is no strategy which is guaranteed to work with fewer than 10, so that is the correct output.

### Input

The input consists of an array of integer trigger counts and a integer giving the number of chutes to trigger. You may take the two inputs in either order, and if needed you may take a third input with the length of the array.

You may assume that all of the inputs are greater than zero, and that the number of chutes which must be triggered does not exceed the number of chutes.

You may also assume that the counts are sorted (ascending or descending), as long as you state that clearly in your answer.

### Output

The output should be a single integer, giving the number of balls required by the optimum strategy.

### Test cases

Format: `N counts solution`

```
1 [2 4 10] 6
2 [2 4 10] 10
3 [2 4 10] 16
1 [3 5 5 5 5 5 5 5 5 5] 5
2 [1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 8 11] 8
2 [1 2 6 6 6 6 6 6 6 10] 16
2 [1 2 3 3 4 4 6 6 6 11] 17
3 [1 2 3 4 5 5 6] 16
3 [2 4 7 7 7 7 7 7 7] 21
5 [1 2 2 3 3 3 3 3 5 9 9 11] 27
2 [5 15 15] 25
1 [4 5 15] 10
3 [1 4 4 4] 10
2 [1 3 4] 6
2 [1 3 3 8] 8

```

# Answer
# Python, 222 198 bytes

```
def S(G,P,T=0):
 T=T or[0]*len(P);r=[0]*(sum(t>=p for t,p in zip(T,P))>=G)
 for i,t in enumerate(T):
    if t<max(P):a=next(p for p in P if p>t)-t;T[i]+=a;r+=[a+S(G,P,sorted(T))];T[i]-=a
 return min(r)

```

Usage is `S(2, (2, 4, 10))`.

In order to test this program at any decent speed, add memoization by putting this after the function definition:

```
old_s = S
mem = {}
def S(G, P, T=0):
    k = (G, tuple(P), T and tuple(T) or 0)
    if k in mem: return mem[k]
    r = old_s(G, P, T)
    mem[k] = r
    return r

```

---

We do dynamic programming on an array T that contains the number of balls we've thrown into each chute, initially all zeroes. Without providing a rigorous proof, I claim that we can keep T sorted at all times, that is, assume we always throw the most balls into the last chute, which in turn we will assume was the largest chute.

If then T, when matched element for element with P (which is our problem input), has at least G (which is our goal) elements bigger, we've found a solution, and we return 0, because we need to throw 0 more balls to find a solution. This means that if G is 1 our least thrown into chute must contain an equal or more amount of balls than the smallest chute requirement, and so on for bigger G.

Otherwise, for each position we throw in enough balls to upgrade to the next chute requirement (anything in between would never be observable) and recurse. We then return the minimum of these recursive calls.
> 4 votes

# Answer
# Haskell, ~~124~~ ~~117~~ ~~100~~ ~~98~~ ~~91~~ ~~80~~ 78 bytes

Saved 11 bytes thanks to @Peter Taylor

```
0#_=0
n#a=minimum$zipWith(\x y->x*y+(n-1)#(snd.splitAt y$a))a[1..length a-n+1]

```

Try it online!

(#) takes an integer and a list of integers in descending order as arguments

Usage is `1#[10,4,2]`

### Explaination:

For each value, x, in position i (1-idexed) in the list, the best tactic to remove that element (or some amount of elements less than or equal to x) is to pour x balls into i chutes.

For each element, x, in position i in the list, (n#) calculates x\*i + ((n-1)#) of the list beyond position i (until n is 0). Then it takes the minimum of all the possibilities checked.
> 4 votes

# Answer
# Haskell, 54 bytes

```
(%)0
(p%l)n|h:t<-l=p+min(p%t$n)(h%t$n-1)|n<1=p|1>0=1/0

```

Try it online!

Takes the list in ascending order.
> 3 votes

# Answer
# Python, 73 bytes

```
f=lambda n,c:n and min(c[i]*-~i+f(n-1,c[-~i:])for i in range(len(c)-n+1))

```

Port of H.PWiz's Haskell answer. Requires the input to be in descending order.
> 2 votes

# Answer
## CJam (35 bytes)

```
{:A,,e!f<{$__(;A,+.-\Af=.*1bz}%:e<}

```

Online demo

Takes input as `N counts` assuming that `counts` is sorted in ascending order.

### Dissection

Denote the counts in descending order as a 1-indexed array `C` (so the second element of `C` is the second largest count). Suppose that we end up winning by triggering chutes `C[a_0], C[a_1], ... C[a_{N-1}]`. Then in the worst case, for each `C[a_i]` we have put at least `C[a_i]` balls into each of chutes `1` to `a_i`. So we put `C[a_{N-1}]` balls into `a_{N-1}` chutes, an additional `C[a_{N-2}]` balls into `a_{N-2}` of them, ...

Over each subset of `N` counts, which gives us the smallest sum? Then we should aim to win with that subset of counts.

NB The code actually uses the counts in ascending order, but I think descending order is more intuitive.

```
{         e# Define a block
  :A      e#   Store the sorted counts as A
  ,,e!f<  e#   Get all N-element subsets of A's indices
  {       e#   Map over these subsets S:
    $__   e#     Sort the subset and get a couple of copies
    (;A,+ e#     Remove the first element from one copy and append len(A)
    .-    e#     Pointwise subtraction, giving [S[0]-S[1] S[1]-S[2] ...]
    \Af=  e#     Get the counts [A[S[0]] A[S[1]] ...]
    .*    e#     Pointwise multiplication
    1bz   e#     Sum and take absolute value, giving the worst case score
  }%
  :e<     e#   Select the minimum worst case score
}

```
> 1 votes

---
Tags: code-golf, optimization
---


title: Abbreviate list of names until they fit

text:
# Question
Title: Abbreviate list of names until they fit
Given a list (array) of names, your challenge is to join the items using some glue and abbreviate the longest items first until the joined string fits a maximum length. And output that string. Since the glue is part of the final string, the length of the glue is included too

Abbreviation is done using the character

**Examples**

For example when `|` is the glue and 20 is the maximum length

* `giraffe` would become `giraffe` (length = 7)
* `giraffe, Spiny lumpsucker` would become `giraffe|Spiny lumps…` (length = 20)
* `giraffe, Spiny lumpsucker, rhinoceros` would become `giraf…|Spiny…|rhino…` (length = 20)
* `giraffe, Spiny lumpsucker, rhinoceros, Hellbender` would become any of these:
    + `gira…|Spi…|rhi…|Hel…`
    + `gir…|Spin…|rhi…|Hel…`
    + `gir…|Spi…|rhin…|Hel…`
    + `gir…|Spi…|rhi…|Hell…` (all length = 20)

**Rules**

The list, glue and maximum length are input parameters of the program.

When abbreviation is needed, abbreviation must be done on any of the longest items first. When the longest items are equally long, it doesn't matter which you abbreviate.

The output length is smaller than the maximum length when no abbreviation was necessary. When abbreviation needs to occur, the length of the output is exactly equal to the maximum length.

The order of the (abbreviated) items must match the order of the items in the input

You can't assume that the abbreviation character  and the glue won't occur as characters in the items in the list.

**Update**

I'm afraid that I overlooked the fact that the length of the glue concatenated with many items by itself may result into a string that is longer than the allowed maximum length. Without considering this, your program may run into an infinite loop. I prefer your program to throw an error in this case. I hope that's not too much of an inconvenience for the ones who already wrote an answer or that are busy writing one. To throw an error is NOT a requirement to win, but I would appreciate if you add a variant that does.

**The winner**

This is code-golf, so the shortest valid answer – measured in bytes – wins.

# Answer
# Jelly, 25 bytes

```
ṖṖ;⁽÷ẓỌµ€µL€MḢµ¦µj⁴L>⁵ð¿j

```

Try it online!

This unfortunately does not contain the error-if-invalid feature.

### Explanation

This is what I call the *Jelly syndrome*: the easy part is explaining the algorithm, the hard part is explaining how you found the exact order to put the code in to make it execute correctly.

```
ṖṖ;⁽÷ẓỌµ€µL€MḢµ¦µj⁴L>⁵ð¿j
                       ¿     While
                 j           joining the input list
                  ⁴          with the glue produces a string
                   L         whose length
                    >        is larger than
                     ⁵       the maximum,
               ¦             in the input array at the
             Ḣ               first of the positions that
            M                have maximal
          L€                 length,
ṖṖ                           remove the last two characters,
  ;                          append
   ⁽÷ẓ                       the number 8230
      Ọ                      and cast it to a character.
                        j    Finally, join again with the glue.

```
> 5 votes

# Answer
# 05AB1E, 25 bytes

```
[Ð³ýDg²›≠#\Déθ©k®¨¨"…"«sǝ

```

Try it online!
> 3 votes

# Answer
# Python 3, 102 bytes

```
def f(l,n,g):
 while len(g.join(l))>n:i=l.index(max(l,key=len));l[i]=l[i][:-2]+'…'
 return g.join(l)

```

Try it online!

Alternatively if you want to see the result being shortened over time:

```
def f(l,n,g):
 while len(g.join(l))>n:i=l.index(max(l,key=len));l[i]=l[i][:-2]+'…';yield g.join(l)

```
> 3 votes

# Answer
# JavaScript (ES6), ~~153~~ 152 bytes

```
(a,g,n)=>eval(`while(a.join('')#>n-2*a#+1+a#==1){for(i=n;x=a.findIndex(w=>w#==i),i--&&!~x;);a[x]=a[x].slice(0,-2)+'…'}a.join(g)`.split`#`.join`.length`)

```

```
f=(a,g,n)=>eval(`while(a.join('')#>n-2*a#+1+a#==1){for(i=n;x=a.findIndex(w=>w#==i),i--&&!~x;);a[x]=a[x].slice(0,-2)+'…'}a.join(g)`.split`#`.join`.length`)
console.log(
  f(['giraffe'], '|', 7),
  f('giraffe, Spiny lumpsucker'.split`, `, '|', 20),
  f('giraffe, Spiny lumpsucker, rhinoceros'.split`, `, '|', 20),
  f('giraffe, Spiny lumpsucker, rhinoceros, Hellbender'.split`, `, '|', 20)
)
```
> 3 votes

# Answer
## JavaScript (ES6), 91 bytes

```
a=>n=>g=>f=(l=n,r=a.join(g))=>r[n]?f(l-!a.some((s,i)=>s[l]&&(a[i]=s.slice(0,-2)+'…'))):r

```

Uses currying i.e. `F(A)(N)(G)()`. Explanation: No string can have a length of more than `n` and still fit, so without loss of generality the overlong length `l` starts off at `n`. Each recursive call then checks whether the strings fit. If not, then the first overlong string found is trimmed, otherwise the overlong length is decremented when all strings have been trimmed to that length.
> 1 votes

---
Tags: code-golf, string, optimized-output
---


# Question
Title: C# First 1 (right to left) in binary number
I am trying to use C# to find the index of the first 1 (right to left) in the binary representation of a number. For example, since 100 in binary is:

```
0b1100100

```

The first 1 is in the third position from the right, so it should yield 3.

234 should yield 2, 0 should yield 0, etc.

Here is my current solution:

```
k < 1 ? 0 :(int)Math.Log(k & -k, 2) + 1;

```

Any ways I can make this shorter?

# Answer
If only C# supported machine-specific intrinsics… There is a single instruction that can do this in x86 assembly language, and on most other processor architectures as well. Then you'd have not only the shortest code, but very likely the fastest.

In fact, making this code *shorter* is an extremely boring problem compared to making this code *fast*. There are all sorts of really neat, efficient, bit-twiddling solutions, and you could also consider using a look-up table.

None of that matters for golfing, though. It looks to me like your current solution is the best you can do. Of course, you can remove the superfluous whitespace:

```
k<1?0:(int)Math.Log(k&-k,2)+1

```

I would personally write it as:

```
k>0?(int)Math.Log(k&-k,2)+1:0

```

because I think it's slightly clearer to have the direction of the conditional test that way, as well as to compare it against zero, but I guess it's six one way, half a dozen the other.

C# doesn't support implicit conversion from `int` to `bool` like C and C++ do, so you can't really shorten the conditional test any further.

You are also stuck with the explicit cast from `double` (as returned my `Math.Log`) to `int`, as C# won't allow this to happen implicitly. Of course, that's normally a good thing because it would point out that you have a *big* performance problem here: promoting an `int` to a `double`, computing the log of a `double`, and then converting the `double` result back to an `int` will be *massively* slow, so it's normally something that you'd want to avoid. But these are the kinds of perversions you have to put up with when playing code golf.

---

I had initially come up with

```
k > 0
      ? ((k & -k) >> 1) + 1
      : 0

```

(ungolfed for clarity, of course), which avoids taking the logarithm and is therefore an improvement in code size and speed. Unfortunately, this doesn't always get the right answer, and I assume that's an inflexible requirement. :-) Specifically, it fails if the input value (`k`) is a factor of 8. This is fixable, but not without making the code longer than the `Math.Log` version.
> 3 votes

---
Tags: code-golf, tips, binary, c#
---