title: Calculate the Kronecker symbol

text:
# Question
Title: Calculate the Kronecker symbol
Relevant links here and here, but here is the short version:

You have an input of two integers \\$a\\$ and \\$b\\$ between negative infinity and infinity (though if necessary, I can restrict the range, but the function must still accept negative inputs).

**Definition of the Kronecker symbol**

You must return the Kronecker symbol \\$(a|b)\\$ for inputs \\$a\\$ and \\$b\\$ where

$$(a|b) = (a|p\_1)^{e\_1} \cdot (a|p\_2)^{e\_2} \cdots (a|p\_n)^{e\_n}$$

where \\$b = p\_1^{e\_1} \cdot p\_2^{e\_2} \cdots p\_n^{e\_n}\\$, and \\$p\_i\\$ and \\$e\_i\\$ are the primes and exponents in the prime factorization of \\$b\\$.

* For an odd prime \\$p\\$, \\$(a|p)=a^{\frac{p-1}2} \mod p\\$ as defined here.
* For \\$b = 2\\$,

$$ (n|2) = \begin{cases} 0 & \text{if } n \equiv 0 \mod 2 \\ 1 & \text{if } n \equiv \pm 1 \mod 8 \\ -1 & \text{if } n \equiv \mp 3 \mod 8 \end{cases} $$

* For \\$b = -1\\$,

$$ (n|-1) = \begin{cases} -1 & \text{if } n \< 0 \\ 1 & \text{if } n \ge 0 \end{cases} $$

* If \\$a \ge b\\$, \\$(a|b) = (z|b)\\$ where \\$z = a\mod b\\$. By this property, and as explained here and here, \\$a\\$ is a quadratic residue of \\$b\\$ if \\$z\\$ is, even though \\$a \ge b\\$.
* \\$(-1|b) = 1\\$ if \\$b \equiv 0,1,2 \mod 4\\$ and \\$-1\\$ if \\$b = 3 \mod 4\\$.
* \\$(0|b)\\$ is \\$0\\$ except for \\$(0|1)\\$ which is \\$1\\$, because \\$(a|1)\\$ is always \\$1\\$ and for negative \\$a\\$, \\$(-a|b) = (-1|b) \times (a|b)\\$.

The output of the Kronecker symbol is always \\$-1, 0 \text{ or } 1\\$, where the output is \\$0\\$ if \\$a\\$ and \\$b\\$ have any common factors. If \\$b\\$ is an odd prime, \\$(a|b) = 1\\$ if \\$a\\$ is a quadratic residue \\$\mod b\\$, and \\$-1\\$ if is it is not a quadratic residue.

**Rules**

* Your code must be a program or a function.
* The inputs must be in the order `a b`.
* The output must be either \\$-1, 0 \text{ or } 1\\$.
* This is code golf, so your code does not have to be efficient, just short.
* No built-ins that directly calculate the Kronecker or the related Jacobi and Legendre symbols. Other built-ins (for prime factorization, for example) are fair game.

**Examples**

```
>>> kronecker(1, 5)
1
>>> kronecker(3, 8)
-1
>>> kronecker(15, 22)
1
>>> kronecker(21, 7)
0
>>> kronecker(5, 31)
1
>>> kronecker(31, 5)
1
>>> kronecker(7, 19)
1
>>> kronecker(19, 7)
-1
>>> kronecker(323, 455625)
1
>>> kronecker(0, 12)
0
>>> kronecker(0, 1)
1
>>> kronecker(12, 0)
0
>>> kronecker(1, 0)
1
>>> kronecker(-1, 5)
1
>>> kronecker(1, -5)
1
>>> kronecker(-1, -5)
-1
>>> kronecker(6, 7)
-1
>>> kronecker(-1, -7)
1
>>> kronecker(-6, -7)
-1

```

This is a complicated function, so please let me know if anything is unclear.

# Answer
> 3 votes
## CJam (70 bytes)

```
{_g\zmf+f{:P2+"W>2*(
z1=
;1
7&4-z[0W0X0]=
P%P+P(2/#P%_1>P*-"N/<W=~}:*}

```

Online demo (test cases generated with Mathematica).

### Dissection

```
{               e# Anonymous function. Stack: a b
  _g\zmf+       e# Factorise b, with special treatment for negatives
                e# CJam also gives special treatment to 0 and 1
                e# Stack: e.g. a [-1 2 2 5]; or a [-1 1]; or a [0 0]; or a [1 2 2 5]
  f{            e# For each "prime" factor P, find (a|P)
    :P2+        e# Extract code for P from an array formed by splitting a string
    "W>2*(      e#   a -> (a|-1)
z1=             e#   a -> (a|0)
;1              e#   a -> (a|1)
7&4-z[0W0X0]=   e#   a -> (a|2)
P%P+P(2/#P%_1>P*-" e# a -> (a|P) for odd prime P
    N/<W=~      e# Split string and select appropriate element
  }
  :*            e# Multiply the components together
}

```

I found several ways of evaluating `(a|2)` for the same character count, and have chosen to use the one with the clearest presentation.

`integer array <W=` is IMO a quite elegant way of doing fallbacks: if the integer is greater than the length of the array, we select the last element.

### Other comments

It's disappointing that for odd prime `p` the direct Fermat-style `(a|p)` is so short, because there's a very golfy way of finding `(a|n)` for positive odd `n` which I wanted to use. The basis is Zolotarev's lemma:

> If `p` is an odd prime and `a` is an integer coprime to `p` then the Legendre symbol `(a|p)` is the sign of the permutation `x -> ax (mod p)`

This was strengthened by Frobenius to

> If `a` and `b` are coprime positive odd integers then the Jacobi symbol `(a|b)` is the sign of the permutation `x -> ax (mod b)`

and by Lerch to

> If `b` is a positive odd integer and `a` is an integer coprime to `b` then the Jacobi symbol `(a|b)` is the sign of the permutation `x -> ax (mod b)`

See Brunyate and Clark, *Extending the Zolotarev-Frobenius approach to quadratic reciprocity*, The Ramanujan Journal 37.1 (2014): 25-50 for references.

And it can easily be strengthened one step further (although I haven't seen this in the literature) to

> If `b` is a positive odd integer and `a` is an integer then the Jacobi symbol `(a|b)` is the Levi-Civita symbol of the map `x -> ax (mod b)`.

Proof: if `a` is coprime to `b` then we use Zolotarev-Frobenius-Lerch; otherwise the map is not a permutation, and the Levi-Civita symbol is `0` as desired.

This gives the Jacobi symbol calculation

```
{_2m*{~>},@ff*\ff%::-:*g}

```

But the special treatment required for `(a|-1)` and `(a|2)` mean that I haven't found a way of calculating the Kronecker symbol which is shorter with this approach: it's shorter to factorise and treat the primes individually.

# Answer
> 4 votes
# Python 3, ~~747~~ ~~369~~ 335 bytes

As an example answer, only slightly golfed, and to give you an idea of what an answer will look like.

And yes, the prime factorization and run-length-encoding bits are cribbed from Pyth with apologies to isaacg.

```
from itertools import*
def k(d,r):
 if d<0:a=-d;m=1
 else:a=d;m=0
 if r==1:return 1
 p=1;w=r;n=2;f=[]
 while n*n<=w:
  while w%n<1:w//=n;f+=n,
  n+=1
 if w>1:f+=w,
 z=[[k,len(list(g))]for k,g in groupby(f)]
 for i,j in z:
  if i==2:p*=pow(-1,(a*a-1)//8)
  x=pow(a,(i-1)//2,i)
  if x>1:x-=i
  p*=x**j
 if m:p*=pow(-1,(r-1)//2)
 return p

```

# Answer
> 2 votes
# LabVIEW, 44 Bytes LabVIEW Primitives

~~Since its symetrical i swapped the inputs if a was bigger than b.~~

Represents the real formula now

counting like always according to

for true case

# Answer
> 2 votes
# Mathematica, ~~169~~ ~~175~~ 165 bytes

```
(1|-1)~k~0=_~k~1=1
_~k~0=0
a_~k~-1=If[a<0,-1,1]
a_~k~2=DirichletCharacter[8,2,a]
a_~k~p_/;PrimeQ@p=Mod[a^((p-1)/2),p,-1]
a_~k~b_:=1##&@@(a~k~#^#2&@@@FactorInteger@b)

```

# Answer
> 1 votes
# Julia, 195 bytes

```
k(a,b)=b==0?a∈[1,-1]?1:0:b==1?1:b==2?iseven(a)?0:a%8∈[1,-1]?1:-1:b==-1?a<1?-1:1:isprime(b)&&b>2?a%b==0?0:a∈[i^2%b for i=0:b-1]?1:-1:k(a,sign(b))*prod(i->k(a,i)^factor(b)[i],keys(factor(b)))

```

This is a recursive function `k` that accepts two integers and returns an integer.

Ungolfed:

```
function k(a::Integer, b::Integer)
    if b == 0
        return a ∈ [1, -1] ? 1 : 0
    elseif b == 1
        return 1
    elseif b == 2
        return iseven(a) ? 0 : a % 8 ∈ [1, -1] ? 1 : -1
    elseif b == -1
        return a < 1 ? -1 : 1
    elseif isprime(b) && b > 2
        return a % b == 0 ? 0 : a ∈ [i^2 % b for i = 1:b-1] ? 1 : -1
    else
        p = factor(b)
        return k(a, sign(b)) * prod(i -> k(a, i)^p[i], keys(p))
    end
end

```

# Answer
> 1 votes
# Haskell, 286 bytes

```
a#0|abs a==1=1|1<2=0
a#1=1
a#2|even a=0|mod a 8`elem`[1,7]=1|1<2=(-1)
a#b|b<0=a`div`abs a*a#(-b)|all((/=0).mod b)[2..b-1]=if elem n[0,1] then n else(-1)|1<2=product$map(a#)$f b where n=a^(div(b-1)2)`mod`b
f 1=[]
f n|n<0=(-1):f(-n)|1<2=let p=head$filter((==0).mod n)[2..n]in p:f(div n p)

```

Probably not completely optimized, but a valiant effort. The Kronecker symbol is defined as the infix function a#b, i.e.

```
*Main>323#455265
1

```

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


title: Write an interpreter for 2B

text:
# Question
Title: Write an interpreter for 2B
# Write an interpreter for 2B

I like David Catt's esoteric language 2B, having memory stored in a tape where each cell is a seperate tape of bytes (the 'subtape'). Write an interpreter for it!

## Language Specification

Official specification can be found here. In this specification, `"` means a number in the range `0-9` (`0` is interpreted as `10`), and `_` means a string of any length. Each cell stores a value in the range `0-255`, and overflow/underflow wraps around as it would a BF. (Thanks @MartinBüttner). To convert text to numbers `0-255`, use ASCII codes. Because I can find no detail on this, I'm going to say that the tape length should be `255` minimum, but if you know otherwise please edit.

```
+-------------+----------------------------------------------------------------------------------------------------------------------------------------+
| Instruction |                                                              Description                                                               |
+-------------+----------------------------------------------------------------------------------------------------------------------------------------+
| 0           | Zeroes the current cell and clears the overflow/underflow flag.                                                                        |
| {           | If the current cell is zero, jump to the matching }.                                                                                |
| }           | A placeholder for the { instruction.                                                                                |
| (           | Read a byte from the input stream and place it in the current cell.                                                                    |
| )           | Write the value of the current cell to the console.                                                                                |
| x           | Store the value of the current cell in a temporary register.                                                                           |
| o           | Write the value of the temporary register to the console.                                                                              |
| !           | If the last addition overflowed, add one to the current cell. If the last subtraction underflowed, subtract one from the current cell. |
| ?           | Performs a binary NOT on the current cell.                                                                                |
| +"          | Adds an amount to the current cell.                                                                                |
| -"          | Subtracts an amount from the current cell.                                                                                |
| ^"          | Moves the subtape up a number of times.                                                                                |
| V"          | Moves the subtape down a number of times.                                                                                |
| <"          | Moves the tape left a number of times.                                                                                |
| >"          | Moves the tape right a number of times.                                                                                |
| :_:         | Defines a label of name _.                                                                                |
| *_*         | Jumps to a label of name _.                                                                                |
| ~_~         | Defines a function of name _.                                                                                |
| @_@         | Calls a function of name _.                                                                                |
| %           | Ends a function definition.                                                                                |
| #_#         | Is a comment.                                                                                |
| [SPACE]     | Is an NOP.                                                                                |
| [NEWLINE]   | Is treated as whitespace and removed.                                                                                |
| [TAB]       | Is treated as whitespace and removed.                                                                                |
+-------------+----------------------------------------------------------------------------------------------------------------------------------------+

```

## Tests

```
+0+0+0+0+0+0+0+2)+0+0+9)+7))+3)-0-0-0-0-0-0-0-9)+0+0+0+0+0+0+0+0+7)-8)+3)-6)-8)-7-0-0-0-0-0-0)

```

Should output `Hello world!`

---

`+1:i:{()*i*}`

Sort of a `cat` program, just without a newline.

---

`+1:loop:{@ReadChar@*loop*}@PrintHello@@WriteAll@(~ReadChar~(x-0-3<2o^1>1+1>1%~PrintHello~+0+0+0+0+0+0+0+2)-1+0+0+0)+7))+3)+1-0-0-0-0-0-0-0-0)%~WriteAll~<1x:reverse:{<1v1>1-1*reverse*}o-1:print:{-1<1)^1>1*print*}%`

Should first accept a name, then, on press of `Return`, should output `Hello name` (where *name* is what was inputted).

Credit for that program goes to David Catt.

---

I'm working on a full test program.

## Rules

* Standard loopholes are forbidden
* Your interpreter must meet all the specifications, except for comments, which are not required.

## Scoring

* This is , so fewest bytes wins!
* -10 bytes if your interpreter handles comments.

## Leaderboard

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```
# Language Name, N bytes

```

where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:

```
# Ruby, <s>104</s> <s>101</s> 96 bytes

```

```
var QUESTION_ID=67123;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),e.has_more?getAnswers():process()}})}function shouldHaveHeading(e){var a=!1,r=e.body_markdown.split("\n");try{a|=/^#/.test(e.body_markdown),a|=["-","="].indexOf(r[1][0])>-1,a&=LANGUAGE_REG.test(e.body_markdown)}catch(n){}return a}function shouldHaveScore(e){var a=!1;try{a|=SIZE_REG.test(e.body_markdown.split("\n")[0])}catch(r){}return a}function getAuthorName(e){return e.owner.display_name}function process(){answers=answers.filter(shouldHaveScore).filter(shouldHaveHeading),answers.sort(function(e,a){var r=+(e.body_markdown.split("\n")[0].match(SIZE_REG)||[1/0])[0],n=+(a.body_markdown.split("\n")[0].match(SIZE_REG)||[1/0])[0];return r-n});var e={},a=1,r=null,n=1;answers.forEach(function(s){var t=s.body_markdown.split("\n")[0],o=jQuery("#answer-template").html(),l=(t.match(NUMBER_REG)[0],(t.match(SIZE_REG)||[0])[0]),c=t.match(LANGUAGE_REG)[1],i=getAuthorName(s);l!=r&&(n=a),r=l,++a,o=o.replace("{{PLACE}}",n+".").replace("{{NAME}}",i).replace("{{LANGUAGE}}",c).replace("{{SIZE}}",l).replace("{{LINK}}",s.share_link),o=jQuery(o),jQuery("#answers").append(o),e[c]=e[c]||{lang:c,user:i,size:l,link:s.share_link}});var s=[];for(var t in e)e.hasOwnProperty(t)&&s.push(e[t]);s.sort(function(e,a){return e.lang>a.lang?1:e.lang<a.lang?-1:0});for(var o=0;o<s.length;++o){var l=jQuery("#language-template").html(),t=s[o];l=l.replace("{{LANGUAGE}}",t.lang).replace("{{NAME}}",t.user).replace("{{SIZE}}",t.size).replace("{{LINK}}",t.link),l=jQuery(l),jQuery("#languages").append(l)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",answers=[],page=1;getAnswers();var SIZE_REG=/\d+(?=[^\d&]*(?:<(?:s>[^&]*<\/s>|[^&]+>)[^\d&]*)*$)/,NUMBER_REG=/\d+/,LANGUAGE_REG=/^#*\s*([^,]+)/;
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"><div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table></div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table></div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody></table><table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody></table>
```

# Answer
# Python2, ~~748~~ ~~736~~ ~~731~~ ~~709~~ ~~704~~ 691 bytes

This was a fun little challenge, I am sure I can make this code even shorter (maybe I'll do that at some point later).

```
from sys import*
w=stdout.write
p=open(argv[1],'r').read()
c,r,s,x,y,t,o=0,0,256,0,0,0,0
g=[[0]*s]*s
e=lambda d:p.find(d,c+1)
def h(i,j=0,k=0):global c,x,y;c+=1;n=1+(int(p[c])-1)%10;l=g[x][y]+n*i;g[x][y]=l%s;o=l/s;x=(x+n*j)%s;y=(y+n*k)%s
a="g[x][y]"
b="[p[c+1:i]]"
l={}
f={}
d={'0':a+"=0",'{':"if "+a+"<1:c=e('}')",'(':"i=stdin.read(1);"+a+"=ord(i)if i else 0",')':"w(chr("+a+"))",'x':"t="+a,'o':"w(chr(t))",'!':a+"+=o",'?':a+"=0if "+a+"else 1",'+':"h(1)",'-':"h(-1)",'^':"h(0,1)",'V':"h(0,-1)",'<':"h(0,0,-1)",'>':"h(0,0,1)",':':"i=e(':');l"+b+"=i;c=i",'*':"i=e('*');c=l"+b,'~':"i=e('~');f"+b+"=i;c=e('%')",'@':"i=e('@');r=i;c=f"+b,'%':"c=r"}
while c<len(p):
    if p[c]in d:exec d[p[c]]
    c+=1

```

This implementation requires for labels and functions to be declared (implemented) before being called. It works perfectly with the two tests given but it unfortunately doesn't work with the "SayHi.2b" program written by the author of the language (even after changing the order of declaration of the functions). I think this problem might have to do with the way I understood the tape and subtape system. When moving along the main tape, is the position on the corresponding subtape reset to 0? At the moment I am keeping the position on the subtape even when moving on the main tape.

Here is the more readable version:

```
#!/usr/bin/python

import sys
w=sys.stdout.write
p=open(sys.argv[1],'r').read()
c,r,s,x,y,t,o=0,0,256,0,0,0,0
# c is the current index in the program string
# r is the return index (for functions)
# s is the size of the tape, subtapes and modulo for ints (max int will be 255)
# x and y are the coordinates in the grid
# t is the temporary register
# o is overflow
g=[[0]*s]*s # initialise a grid 256x256 with 0

e=lambda d:p.find(d,c+1)
def n():global c;c+=1;i=int(p[c]);return i if i>0 else 10 # get the number specified
def h(i):j=g[x][y]+i;g[x][y]=j%s;o=j/s # handle addition and substraction
def m(i,j):global x,y;x=(x+i)%s;y=(y+j)%s # move current cell

a="g[x][y]" # string of current cell
b="[p[c+1:i]]" # key for label or function
l={} # dictionary of labels
f={} # dictionary of functions
d={'0':a+"=0",
   '{':"if "+a+"<1:c=e('}')",
   '(':"i=sys.stdin.read(1);"+a+"=ord(i)if i else 0",
   ')':"w(chr("+a+"))",
   'x':"t="+a,
   'o':"w(chr(t))",
   '!':a+"+=o",
   '?':a+"=0if "+a+"else 1",
   '+':"h(n())",
   '-':"h(-n())",
   '^':"m(n(),0)",
   'V':"m(-n(),0)",
   '<':"m(0,-n())",
   '>':"m(0,n())",
   ':':"i=e(':');l"+b+"=i;c=i",
   '*':"i=e('*');c=l"+b,
   '~':"i=e('~');f"+b+"=i;c=e('%')",
   '@':"i=e('@');r=i;c=f"+b,
   '%':"c=r",
   '#':"c=e('#')"
   }

while c<len(p): # loop while c is not EOF
    # print c, p[c]
    if p[c]in d:exec d[p[c]] # execute code kept as a string
    c+=1 # increment index

```

Edit: Take into account the comments handling (-10 bytes), fixing an off by one error. This implementation doesn't support nested function calls (I could implement it if it is a required feature)

Edit2: Changed the handler function to do addition, substraction and cell movement. More lambdas! :D (The "more readable version" may be out of sync now)

Edit3: I just realized that handling comments costs me 5 bytes (taking into account the -10). So I just removed it, it's shame it now feels incomplete.

Edit4: moved definition of n from lambda to var inside the handler h()
> 4 votes

---
Tags: code-golf, interpreter
---


title: Create a Winter Bash 2015 hat reminder

text:
# Question
Title: Create a Winter Bash 2015 hat reminder
**Input**

Two dates, each comprising of a month (Dec or Jan) and a day (01-31). These will be given as 4 integers (`12 01 01 01`, for example), in any reasonable format you choose (leading zeroes, no leading zeroes, list, individual inputs, list of lists, etc.). The first date is supposed to represent today's date.

**Output**

* If the second input date is Dec 14, output `Sufganiyot`
* If it is Dec 18, output `A new hope`
* For Dec 23, `The airing of grievances`
* For Dec 25, `O Tannenbaum`
* For Dec 31 or Jan 1, `Auld Lang Syne`
* Otherwise output `Try some other day!` (in which case you will not compare the dates, see below)

This is followed by

* `, Go and get it!` if the first and second input dates are same.
* `, Wait for it!` if the first date comes before the second date.
* `, But you missed it!` if the first date comes after the second date.

**Sample runs**

`Dec 23 Dec 23` -\> `The airing of grievances, Go and get it!`

`Dec 28 Jan 1` -\> `Auld Lang Syne, Wait for it!`

`Dec 18 Dec 17` -\> `Try some other day!`

`Jan 25 Dec 25` -\> `O Tannenbaum, But you missed it!`

**Score**

This is code golf, so shortest code in bytes wins.

# Answer
> 1 votes
# Java, ~~400~~ ~~340~~ 333 - 139 = ~~261~~ ~~201~~ 194 bytes

I considered these characters "convenient":

```
, Go and get it!, Wait for it!, But you missed it!Try some other day!Auld Lang SyneO TannenbaumThe airing of grievancesA new hopeSufganiyot
```

Here is the code (called with `s(first month number, first month date, second month number, second month date)`):

```
String s(int a,int b,int c,int d){String x="";int e=(a*b!=1)?a*b:372;if(e==372)x="Auld Lang Syne";if(e==216)x="A new hope";if(e==276)x="The airing of grievances";if(e==300)x="O Tannenbaum";if(x=="")return"Try some other day!";int f=(c==1)?372*d:c*d;return x+", "+((e>f)?"Wait for it...":(e<f)?"But you missed it!":"Go and get it!");}
```

Ungolfed:

```
static String v(int a,int b,int c,int d){
    String x="";
    int e=(a*b!=1)?a*b:372;
    if(e==372)x="Auld Lang Syne";
    if(e==216)x="A new hope";
    if(e==276)x="The airing of grievances";
    if(e==300)x="O Tannenbaum";
    if(x=="")return"Try some other day!";
    int f=(c==1)?372*d:c*d;
    return x+", "+((e>f)?"Wait for it...":(e<f)?"But you missed it!":"Go and get it!");
}
```

# Answer
> 0 votes
# Mouse-2002, 664 - 171 = 493 bytes

I consider the following strings "convenient":

```
"Sufganiyot""A new hope""The airing of grievances""O Tannenbaum""Auld Lang Syne""Auld Lang Syne"", go and get it!"", wait for it!"", but you missed it""Try some other day"

```

And the code:

```
?a:?b:?c:?d:c.12=[d.14=["Sufganiyot"a.12=[b.14=[#R,1;|b.14<[#R,2;|b.14>[#R,3;]]]|a.1=[#R,3;]]|d.18=["A new hope"|a.12=[b.18=[#R,1;|b.18<[#R,2;|b.18>[#R,3;]]]|a.1=[#R,3;]]|d.23=["The airing of grievances"|a.12=[b.23=[#R,1;|b.23<[#R,2;|b.23>[#R,3;]]]|a.1=[#R,3;]]|d.25=["O Tannenbaum"|a.12=[b.23=[#R,1;|b.23<[#R,2;|b.23>[#R,3;]]]|a.1=[#R,3;]]|d.31=["Auld Lang Syne"|a.12=[b.31=[#R,1;|b.31<[#R,2;|b.31>[#R,3;]]]|a.1=[b.1=[#R,1;|b.1<[#R,2;|b.1>[#R,3;]]]]]]]]]]|c.1=[d.1=["Auld Lang Syne"|a.1=[b.1=[#R,1;|b.1<[#R,2;|b.1>[#R,3;]]]]]|#R,4;]]$R1%a:a.1=[", Go and get it"#E;|a.2=[", Wait for it"#E;|a.3=[", But you missed it"#E;|a.4=["Try some other day"#E;]]]]@$E33!'"!"@$

```

Ungolfed:

```
~ Create a Winter Bash 2015 hat reminder

? a: ? b: ? c: ? d:

c. 12 =
[
  d. 14 =
  [
    "Sufganiyot"
    a. 12 =
    [
      b. 14 =
      [
        #R,1;
      | b. 14 <
        [
          #R,2;
        | b. 14 >
          [
            #R,3;
          ]
        ]
      ]
    | a. 1 =
      [
        #R,3;
      ]
    ]
  | d. 18 =
    [
      "A new hope"
    | a. 12 =
      [
        b. 18 =
        [
          #R,1;
        | b. 18 <
          [
            #R,2;
          | b. 18 >
            [
              #R,3;
            ]
          ]
        ]
      | a. 1 =
        [
          #R,3;
        ]
      ]
    | d. 23 =
      [
        "The airing of grievances"
      | a. 12 =
        [
          b. 23 =
          [
            #R,1;
          | b. 23 <
            [
              #R,2;
            | b. 23 >
              [
                #R,3;
              ]
            ]
          ]
        | a. 1 =
          [
            #R,3;
          ]
        ]
      | d. 25 =
        [
          "O Tannenbaum"
        | a. 12 =
          [
            b. 23 =
              [
                #R,1;
              | b. 23 <
                [
                  #R,2;
                | b. 23 >
                  [
                    #R,3;
                  ]
                ]
              ]
          | a. 1 =
            [
              #R,3;
            ]
          ]
        | d. 31 =
          [
            "Auld Lang Syne"
          | a. 12 =
            [
              b. 31 =
                [
                  #R,1;
                | b. 31 <
                  [
                    #R,2;
                  | b. 31 >
                    [
                      #R,3;
                    ]
                  ]
                ]
            | a. 1 =
              [
                b. 1 =
                  [
                    #R,1;
                  | b. 1 <
                    [
                      #R,2;
                    | b. 1 >
                      [
                        #R,3;
                      ]
                    ]
                  ]
              ]
            ]
          ]
        ]
      ]
    ]
  ]
| c. 1 =
  [
    d. 1 =
      [
        "Auld Lang Syne"
      | a. 1 =
        [
          b. 1 =
            [
              #R,1;
            | b. 1 <
              [
                #R,2;
              | b. 1 >
                [
                  #R,3;
                ]
              ]
            ]
        ]
      ]
  | #R,4;
  ]
]

$R
  1% a:
  a. 1 =
  [
    ", Go and get it" #E;
  |
    a. 2 =
    [
      ", Wait for it" #E;
    |
      a. 3 =
      [
        ", But you missed it" #E;
      |
        a. 4 =
        [
          "Try some other day" #E;
        ]
      ]
    ]
  ]
@
$E33!'"!"@
$

```

I am never, ever, ever going anywhere near this thing ever, ever again.

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


title: Santa's Decision

text:
# Question
Title: Santa's Decision
# Santa's Decision:

In this challenge, you will help Santa Claus decide whether somebody on their list has been naughty or nice, and subsequently get `coal` or `toys`.

But unfortunately, Santa is unorganised, in some of his entries, the `naughty`, `nice` and `name` fields are in the wrong order.

## Input

Input will come in the following, interchangeable format:

* the person's name (cannot contain a colon, only `a-zA-Z0-9`)
* the word `naughty` followed directly by a colon and an non-negative integer representing the amount of times Santa caught you being naughty
* the word `nice` followed directly by a colon and an non-negative integer representing the amount of times Santa caught you being nice

All separated with a single whitespace (ASCII 32) between each of them.

Additionally, the name will have no whitespace between the parts of the name `Santa Claus` -\> `SantaClaus`.

## Bonus:

* **(25%)**: He is Santa Claus, so he needs to check the list *twice*, and make sure there are no duplicates. (In which case, it just gets the first scores that user has)

## Example:

```
Quill naughty:4 nice:0
naughty:0 Doorknob nice:3
naughty:2 Quill nice:6
nice:3 balpha naughty:3
pops nice:4 naughty:2

```

## Output:

The output should consist of:

The name of the person followed by:

* If there's more points in `naughty`, then `coal`:
* If there's more points in `nice`, then `toys`.
* But if `naughty` and `nice` are equal, then `needs more data`

### Example output:
* With organisation bonus and duplicate removal bonus:

```
Quill coal
Doorknob toys
balpha needs more data
pops toys

```
* Without bonus:

```
Quill coal
Doorknob toys
Quill toys
balpha needs more data
pops toys

```

# Lowest byte count wins!

# Answer
# Pyth, 68 bytes - 25% = 51

```
V.zI-hA.g}\:kcNdY=+YGjd+G@c"needs more data
coal
toys"b._-Fmsecd\:SH

```

Try it online: Demonstration
> 4 votes

# Answer
# Julia, ~~176~~ 169 bytes

```
s->for l=split(s,"\n") M(r)=parse(matchall(r,l)[1]);g=M(r"e:\K\d+");b=M(r"y:\K\d+");println(replace(l,r" *\w+:\d+ *","")," ",g>b?"toys":b>g?"coal":"needs more data")end

```

This is an anonymous function that accepts a string and prints the result to STDOUT. To call it, give it a name, e.g. `f=s->...`.

Ungolfed:

```
function santa(s::AbstractString)
    # Split the input on newlines and process each line separately
    for l in split(s, "\n")
        # Define a function to get the number from the result of a
        # regular expression match
        M(r) = parse(matchall(r, l)[1])

        # Goodness
        g = M(r"e:\K\d+")

        # Badness
        b = M(r"y:\K\d+")

        # Get the name by replacing the naughty and nice specifications
        # with empty strings and print the line to STDOUT
        println(replace(l, r" *\w+:\d+ *", ""), " ",
                g > b ? "toys" : b > g ? "coal" : "needs more data")
    end
end

```
> 5 votes

# Answer
# Pyth - 64 bytes

Will try to use packed strings.

```
jmj\ +hK.g@k\:cd\ @c"needs more data
coal
toys"b._-Fmseck\:SeK.z

```

Try it online here.
> 4 votes

# Answer
## Perl, ~~138~~ ~~113~~ ~~105~~ ~~103~~ ~~102~~ 96 - 25% = 72

*includes +1 for `-p`*

```
s/ *\w*(.):(\d+) */$$1=$2,()/eg;$$_++?$_='':s/\n/$".('needs more data',toys,coal)[$e<=>$y].$&/e

```

# Less golfed:

```
s/ *\w*(.):(\d+) */$$1=$2,()/eg;    # strip naughty/nice, set $a to naughty, $i to nice
                                    # $_ is now the input name followed by \n
$$_++ ? $_='' :                     # only output once per name
s/\n/                               # replace newlines with:
  $".                               # a space,
  ('needs more data',toys,coal)     # one of these strings,
  [$e<=>$y]                         # indexed by -1, 0 or 1
  .$&                               # and the matched newline.
/ex                                 # (/x only for legibility)

```

---

* *update 113*
    + save 25 bytes by using 1 letter from `nice` or `naughty` as variable name;
    + loose 5 bytes by fixing bug when name is last
* *update 105* save 8 bytes by using `<=>` to index a list of output strings.
* *update 103* save 2 bytes by using regex to append output string
* *update 102* save 1 byte by using last letter of `nice` or `naughty` instead of 2nd.
* *update 96* save 6 bytes by changing `$$_ ? ... : ($$_++, ...)` into `$$_++ ? ... : ...`
*(why didn't I see that before).*
> 3 votes

# Answer
# Ruby, ~~144~~ ~~123~~ 155 * .75 = 116.25 bytes

```
->s{d={}
s.split("
").map{|l|
a=l.split
b=a.grep /:/
i,j,v=(b.sort*'').scan(/\d+/)+a-b
d[v]||(d[v]=0
puts v+' '+['needs more data','coal','toys'][i<=>j])}}

```

Thanks to histocrat for suggesting `grep` method.

**164 * .75 = 123 bytes**

```
->s{d={}
s.split("
").map{|l|
a=l.split
b=a.select{|t|t[?:]}
i,j,v=(b.sort*'').scan(/\d+/)+a-b
d[v]||(d[v]=0
puts v+' '+['needs more data','coal','toys'][i<=>j])}}

```

**144 bytes**

```
->s{puts s.split("
").map{|l|b=(a=l.split).select{|t|t[?:]};i,j=(b.sort*'').scan(/\d+/);(a-b)[0]+' '+['needs more data','coal','toys'][i<=>j]}}

```

**Ungolfed**

```
->s{
  d={}
  s.split("
  ").map{ |l|
    a = l.split
    b = a.grep /:/
    i, j, v = (b.sort * '').scan(/\d+/) + a-b
    d[v] ||
      (d[v]=0
       puts v + ' ' + ['needs more data','coal','toys'][i<=>j]
      )
  }
}

```

**Usage:**

```
# Assign the anonymous function to a variable
f = ->s{d={}
s.split("
").map{|l|
a=l.split
b=a.grep /:/
i,j,v=(b.sort*'').scan(/\d+/)+a-b
d[v]||(d[v]=0
puts v+' '+['needs more data','coal','toys'][i<=>j])}}

f["Quill naughty:4 nice:0
naughty:0 Doorknob nice:3
naughty:2 Quill nice:6
nice:3 balpha naughty:3
pops nice:4 naughty:2"]

Quill coal
Doorknob toys
balpha needs more data
pops toys

```
> 3 votes

# Answer
# JavaScript (ES6), 174 bytes - 25% bonus = 130.5 score

```
s=>s.split`
`.map(l=>l.split` `.map(p=>(m=p.match(/\w:\d+/))?(n=+m[0].slice(2),m>"f")?b=n:c=n:a=p)&&d[a]?"":d[a]=a+" "+(b>c?`coal
`:b<c?`toys
`:`needs more data
`),d={}).join``

```

## Explanation

```
s=>
  s.split`
`.map(l=>                   // for each line l of Santa's list
    l.split` `.map(p=>      // for each word p in l
      (m=p.match(/\w:\d+/)) // m = "y:x" for naughty, "e:x" for nice or null for name
        ?(n=+m[0].slice(2), // n = number at end of match
          m>"f")?b=n:c=n    // if naughty matched b = n, if nice matched c = n
        :a=p                // if no match, a = name
    )
    &&d[a]?"":              // if the name has been used before, add nothing to output
    d[a]=                   // else set d[name] to true

      // Add the appropriate text to the output
      a+" "+(b>c?`coal
`:b<c?`toys
`:`needs more data
`),

    // NOTE: This line is executed BEFORE the code above it in the map function...
    d={}                    // d = list of names that have been output
  )
  .join``                   // return the list of outputs as a string

```

## Test

```
var solution = s=>s.split`
`.map(l=>l.split` `.map(p=>(m=p.match(/\w:\d+/))?(n=+m[0].slice(2),m>"f")?b=n:c=n:a=p)&&d[a]?"":d[a]=a+" "+(b>c?`coal
`:b<c?`toys
`:`needs more data
`),d={}).join``
```

```
<textarea rows="5" cols="40" id="input">Quill naughty:4 nice:0
naughty:0 Doorknob nice:3
naughty:2 Quill nice:6
nice:3 balpha naughty:3
pops nice:4 naughty:2</textarea><br />
<button onclick="result.textContent=solution(input.value)">Go</button>
<pre id="result"></pre>
```
> 2 votes

# Answer
# CJam, 64 bytes

```
qN/{S/':f/_{,1=},_@^$1f=:~:-g"needs more data
coal
toys"N/=S\N}/

```

Try it online!
> 2 votes

# Answer
# Lua, 329 Bytes - 25% bonus = 246.75

```
a={...}p={}u=" "k=ipairs for i=1,#a/3 do p[i]={}end for i,v in k(a)do p[math.floor((i+2)/3)][(v:find("y:")and 3)or(v:find("e:")and 2)or 1]=v:gsub("%a+%:","")end for i,v in k(p)do d=tonumber b,g,n=d(v[3]),d(v[2]),v[1]if(not u:find(" "..n.." "))then u=u..n.." "print(n..(g<b and" coal"or g>b and" toys"or" needs more data"))end end

```

Will edit in ungolfed version and explanations later, a bit tired at the moment. All input is taken in through command line, space separated.
> 2 votes

# Answer
# Python 2, 206 bytes - 25% = 154.5

```
s=[]
x=[0,0]
for p in zip(*(iter(input().split()),)*3):
 for w in p:
  j=w.find(':')+1
  if j:x[j<6]=int(w[j:])
  else:N=w
 b,g=x
 if N not in s:print N,['needs more data','coal','toys'][(b>g)-(g>b)];s+=[N]

```
> 2 votes

# Answer
# JavaScript (ES6) 120 (160-25%)

Anonymous function using template strings, there are 4 newlines that are significant and included in the byte count

```
l=>l.split`
`.map(r=>k[r=r.replace(/\S+:(\d+)/g,(a,c)=>(t-=a[1]<'i'?c:-c,''),t=0).trim()]?'':k[r]=r+(t>0?` toys
`:t<0?` coal
`:` needs more data
`),k={}).join``

```
> 2 votes

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


title: Run-Length Racers

text:
# Question
Title: Run-Length Racers
You will be given two pieces of input: a string in run-length encoded format defining the running track, and a capital letter representing the lane to start from. For example, the string "3a4A6b5B" expands to "aaaAAAAbbbbbbBBBBB". You then use the expanded string to create a track, as such:

```
 A) aaaAAAA
 B) bbbbbbBBBBB

```

This is a track with two lanes. Lowercase letters represent air. You can not run on air! Uppercase letters represent road you can run on. Your goal for this challenge is, given a capital letter, output how far a racer starting on that lane could run. Racers are allowed to switch lanes if there is a piece of road directly above or below them. **They are also allowed to run backwards!** On this particular track the output is **0** for any letter input, because neither of the tracks has runnable road at position 1.

## Examples:

**Input:** "4A5B4c3C", "A"

This code expands to a track that looks like this:

```
A) AAAA
B) BBBBB
C) ccccCCC

```

The output for this example is **7**, because a runner starting on lane A could move down to lane B, and then lane C, and end up at the 7th position.

**Input:** "4A2B3D", "D"

**Track:**

```
A) AAAA
B) BB
C)
D) DDD

```

The output is **3**, because a runner starting on lane D has no way to get to lane B or A

**Input:** "4A4a4A3b6B5C", "A"

**Track:**

```
A) AAAAaaaaAAAA
B) bbbBBBBBB
C) CCCCC

```

The output is **12**, because the runner on A can switch over to B, and then come back to A at the end. The max distance for "C" is also 12. For "B" it is 0.

**Input:** "12M4n10N11O", "M"

**Track:**

```
M) MMMMMMMMMMMM
N) nnnnNNNNNNNNNN
O) OOOOOOOOOOO

```

Simple example with multi-digit run-lengths. Output is **14**.

**Input:** "4A5B1b2B4c3C", "A"

**Track:**

```
A) AAAA
B) BBBBBbBB
C) ccccCCC

```

The output is **8**, because the runner at A can go down to B, then down to C, then come back to B. (Thank you to FryAmTheEggman for this example.)

**Input:** "1a2A2a2B1c1C1d3D", "B"

**Track:**

```
A)aAAaa
B)BB
C)cC
D)dDDD

```

Output is **4**. Runner has to check both paths two see which goes further. (Thanks to user81655 for this example.)

**Input:** "2A1b1B2C1D3E","A"

**Track:**

```
A) AA
B) bB
C) CC
D) D
E) EEE

```

Output is **3**. You have to run backwards to reach the furthest destination. (Once again, thanks to user81655 for this example.)

## Notes:

* If a track does not have a letter at a certain position, that counts as air too. As such, if the input is "Q" and no road has been placed on lane "Q" the output should be **0**.
* There are two pieces of input. The first is a run-length encoded string. The second is a capital letter (you can use string or char datatype for this.) For readability, there should be some reasonable separator between these inputs (space, new line, tab, comma, semi-colon).
* The run-length encoded string will always list elements in alphabetical order
* The very longest the entire length of a lane can be is 1000. Therefore, the greatest possible output is 1000.

## Track Generator:

In honor of our first answer, here is a track generator. Try to come up with something to stump the current answers! (Note: Just because the generator doesn't show an error message doesn't mean your track code is necessarily valid. See above examples for proper form.)

```
function reset() {
    var t = document.getElementById("track");
    t.innerHTML = "";
    for(var i = 0;i<26;i++) {
      var c = String.fromCharCode(i+65);
      t.innerHTML += "<div><span>"+c+") </span><span id='"+c+"'></span></div>";

    }
  }

function rand() {
  var track = "";
  for(var i = 0;i<26;i++) {
  var blocks = Math.floor(Math.random()*4);
  var start = Math.floor(Math.random()*2);
  for(var j = 0;j<blocks;j++) {
    var letter = String.fromCharCode(65+i+32*((start+j)%2));
    var length = Math.floor(Math.random()*4)+1;
    track += length+letter;
  }
  }
  document.getElementById("code").value = track;
}

  function gen() {
  var s = document.getElementById("code").value;
    var check = s.match(/(\d+[A-Za-z])+/);
    if(check == null || check[0]!=s) {
      alert("Invalid Track");
      return false;
    }
    reset();
  var n = s.match(/\d+/g);
    var o = s.match(/[A-Za-z]/g);
    for(var i = 0;i<n.length;i++) {
      var c = o[i].toUpperCase();
      document.getElementById(c).textContent += o[i].repeat(n[i]);
    }
    return true;
    }
```

```
<body onload="reset()">
Track: <input type="text" id="code" size="75%" /><input type="submit" onclick="gen()" /><input type="button" value="Random Track" onclick="rand()" /><code id="track"/>
  </body>
```

# Answer
## Perl, ~~231~~ ~~219~~ ~~203~~ ~~192~~ 189 bytes

*includes +1 for `-p`*

```
sub f{my($l,$p,$m)=@_;map{$m=$_>$m?$_:$m}f($l,$p+1)+1,f($l-1,$p),f($l+1,$p),f($l,$p-1)-1if$L[$l][$p]&&!$V{$l}{$p}++;$m}s/(\d+)(.)\s*/push@{$L[ord$2&~32]},(0|$2lt'a')x$1;()/ge;$_=0|f(ord,0)

```

## Less golfed:

```
sub f{                          # this is a recursive function, so we need locals.
    my($l,$p,$m)=@_;            # in: lane, position; local: max path length

    map{
      $m = $_ > $m ? $_ : $m    # update max
    }
    f( $l,   $p+1 )+1,          # same lane, forward
    f( $l-1, $p   ),            # left lane, same pos
    f( $l+1, $p   ),            # right lane, same pos
    f( $l,   $p-1 )-1           # same lane, backtrack
    if
        $L[$l][$p]              # check if there's road here
    && !$V{$l}{$p}++            # and we've not visited this point before.
    ;

    $m                          # return the max
}

s/(\d+)(.)\s*/                  # Parse RLE pattern, strip starting lane separator
  push@{ $L[ord$2&~32] }        # index @L using uppercase ascii-code, access as arrayref
  ,(0|$2lt'a')x$1               # unpack RLE as bitstring
  ;()                           # return empty list for replacement
/gex;                           # (x for ungolfing)
                                # $_ now contains trailing data: the start lane.

$_ =                            # assign output for -p
   0|                           # make sure we print 0 instead of undef/nothing
   f(ord,0)                     # begin calculation at start of current lane

```

## Running

Store the *code above* in a file (say `231.pl`). Input in the form of `(\d+\w)+ *\w`. Example: inputting track `4A5B4c3C` and lane `A`:

```
echo 4A5B4c3C A | perl -p 231.pl

```

## TestSuite

(not golfed)

```
printf "==== Testing %s\n", $file = shift // '231.pl';

sub t{
    my($input,$expect) = @_;
#   $input =~ s/\s//g;
    printf "TEST %-20s -> %-3s: ", $input, $expect;

    $output = `echo $input | perl -p $file`;

    printf "%-3s  %s\n", $output,
    $output == $expect
    ? " PASS"
    : " FAIL: $output != $expect";

}

t("4A5B4c3C A", 7);
t("4A5B4c3C C", 0);
t("4A2B3D D", 3);
t("4A4a4A3b6B5C A", 12);
t("4A4a4A3b6B5C B",  0);
t("4A4a4A3b6B5C C", 12);
t("12M4n10N11O M", 14 );
t("4A5B1b2B4c3C A", 8);
t("1a2A2a2B1c1C1d3D B", 4 );
t("2A1b1B2C1D3E A", 3 );
t("10A9b1B8c2C9D1E11F A", 11);

```
* *update 219* save 12 bytes by reworking array indices.
* *update 203* Save 16 bytes by refactoring recursion.
* *update 192* save 11 bytes by eliminating the `@L=map{[/./g]}@L` postprocessing.
* *update 189* save 3 bytes by postfixing `if` using `map` instead of `for`.
> 3 votes

# Answer
# JavaScript (ES6), ~~298~~ 334 bytes

```
(t,s)=>[a=[],t.match(/\d+(.)(\d+\1)*/gi).map(l=>a[c=l.match`[A-Z]`+"",n=c.charCodeAt(),c==s?i=n:n]=l[r="replace"](/\d+./g,p=>(p.slice(-1)<"a"?"1":"0").repeat(parseInt(p))),i=o=-1),...a.join``,a[i]?a[i]=a[i][r](/^1/,2):0].map(_=>a.map((l,y)=>a[y]=l[r](/1/g,(c,x)=>((a[y-1]||s)[x]|(a[y+1]||s)[x]|l[x-1]|l[x+1])>1?(x>o?o=x:0,2):c)))&&o+1

```

## Explanation

Basically this solution treats the track as a maze. It finds where all the tiles that are possible for the runner to reach are and returns the greatest value of the X index it found.

The first thing it does is decode the input string into an array of lines. Instead of using letters though, it turns a capital letter into a `1` and a lowercase letter into a `0`. The resulting map will look something like this:

```
11100011
0011100
100111

```

After this it makes the first tile of the starting track a `2` (only if it is already `1`) and loops through every tile checking adjacent tiles for a `2`. If a `1` has an adjacent `2` it becomes a `2`. The above map will become this if the runner started on the first line:

```
22200011
0022200
100222

```

The highest X index for a `2` becomes the result.

I made a very minor oversight when I did the initial version of this and it cost me 36 bytes to hack at it until it worked, so there's probably a lot of improvements that could be made to this. *\*sigh\**

### Ungolfed

```
(t,s)=>
  [

    // Decode run-length encoded string into an array of track lanes
    a=[],                           // a = array of track line strings, 0 = air, 1 = tiles
    t.match(/\d+(.)(\d+\1)*/gi)     // regex magic that separates pairs by their letter
    .map(l=>                        // for each line of pairs
      a[                            // add the tiles to the array
        c=l.match`[A-Z]`+"",        // c = pair character
        n=c.charCodeAt(),           // n = index of line
        c==s?i=n:n                  // if this line is the starting line, set i
      ]=l[r="replace"](/\d+./g,p=>  // match each pair, p = pair
        (p.slice(-1)<"a"
          ?"1":"0").repeat(         // repeat 0 for air or 1 for ground
            parseInt(p)             // cast of match would return NaN because of the
          )                         //     letter at the end but parseInt works fine
      ),
        i=                          // i = index of starting line, initialise as invalid
          o=-1                      // o = output (max value of x)
    ),

  // Find all positions that are possible for the runner to get to
    ...a.join``,                   // add every letter of the track lines to an array
    a[i]?a[i]=a[i][r](/^1/,2):0    // set the starting tile to 2 if it is already 1
  ].map(_=>                        // loop for the amount of tiles, this is usually way
                                   //     more than necessary but allows for hard to reach
                                   //     tiles to be parsed
    a.map((l,y)=>                  // for each line l at index y
      a[y]=l[r](/1/g,(c,x)=>       // for each character c at index x

        // Replace a 1 with 2 if there is a 2 to above, below, left or right of it
        ((a[y-1]||s)[x]|(a[y+1]||s)[x]|l[x-1]|l[x+1])>1?
          (x>o?o=x:0,2):c          // set o to max value of x for a 2 tile
      )
    )
  )
  &&o+1                            // return o + 1

```

## Test

Bonus: Output includes the parsed map!

```
var solution = (t,s)=>[a=[],t.match(/\d+(.)(\d+\1)*/gi).map(l=>a[c=l.match`[A-Z]`+"",n=c.charCodeAt(),c==s?i=n:n]=l[r="replace"](/\d+./g,p=>(p.slice(-1)<"a"?"1":"0").repeat(parseInt(p))),i=o=-1),...a.join``,a[i]?a[i]=a[i][r](/^1/,2):0].map(_=>a.map((l,y)=>a[y]=l[r](/1/g,(c,x)=>((a[y-1]||s)[x]|(a[y+1]||s)[x]|l[x-1]|l[x+1])>1?(x>o?o=x:0,2):c)))&&o+1
function generateMap() { var start = 0; a.some((l, i) => l ? start = i : 0); var end = 0; a.map((l, i) => l && i <= 90 ? end = i : 0); for(var output = "", i = start; i < end + 1; i++) output += String.fromCharCode(i) + ") " + (a[i] || "") + "\n"; return output; }
```

```
Track = <input type="text" id="track" value="2A1b1B2C1D3E" /><br />
Starting Letter = <input type="text" id="start" value="A" /><br />
<button onclick="result.textContent=solution(track.value,start.value)+'\n\n'+generateMap()">Go</button>
<pre id="result"></pre>
```
> 6 votes

---
Tags: code-golf, string, path-finding
---


title: How much water is left?

text:
# Question
Title: How much water is left?
Here in California, we're in a drought so we need to know how much water we have left so we can conserve as much water as possible.

Because water is limited supply, your code will need to be as short as possible.

## Examples

```
|   |
|   |
|~~~|
|___|

Output: 0.5

```

```
|~~~~~|
|     |
|     |
|_____|

Output: 1

```

```
|  |
|__|

Output: 0 (or bonus)

```

## Specification

The input will consist solely of all of: `|_ ~` and newlines. All above the `~`'s are considered air; `_`, spaces below `~`, and `~` itself are considered water. The percent of water left is computer by `water / (air + water)`. Your output needs to be accurate to 4 decimal places (unless you go for the percent bonus). The input will always be rectangular. The `~` will only be on one line, if on any. The input may optionally also have a trailing line feed if you'd like.

## Bonus

If you go for both bonuses the -15% bonus is applied before the -35 bonus

**-35 byte Bonus:** If your code prints "This drought *goat* out of hand", instead of 0 when the Output is 0

**-15% Bonus:** If you output a percent.

To do this, you would shift the decimal place two places to the left, trim leading zeros, and add a `%` to the end. Trailing zeros (max 2) are allows as long as they don't affect the value. `0.5` -\> any of: `50.00% 50% 50.0%`

# Answer
> 16 votes
# Pyth - ~~17~~ ~~46~~ ~~45~~ 52 * .85 - 35 = 9.2 bytes

Filters the input (With the new `#` filter meta-op!) for a line with `~` in it, then indexes that to the input, and then divides that by the length of the input. If there are none with `~`, it errors, and triggers the except clause of `.x` and prints the string.

```
.x+*100-1cxK.zh@#\~KlK\%." u(C$éáPãbÉãç*îÂe[W

```

Try it online here.

# Answer
> 10 votes
## Python 3, 37 bytes

```
lambda x:1-(x+'|~').find('|~')/len(x)

```

No bonuses. Takes an input string with newlines, including a trailing newline.

Let's look at why the formula works. The fraction of water is the complement of the fraction of air, which we'll derive.

```
frac_water = 1 - frac_air

```

Numbering the rows `0, 1, 2, ...`, we have

```
frac_air = water_row_index / num_rows

```

The same is true if both are multiplied by the width of each row, counting newlines, which simplify to expressions in the number of characters.

```
frac_air = (width * water_row_index) / (width * num_rows)
         = water_row_start_char_index / num_chars

```

The water row start is found by searching the input string `x` for `|~`, and the number of chars is just the length.

```
frac_air = x.find('|~') / len(x)

```

Finally, in order to make no-water inputs work, we append a fictional water row start `|~` to the end before searching, which makes it look like the water level is 0.

The bonuses seemed not worth it. The best I got on the string one is 73-35=38:

```
lambda x:['This drought goat out of hand',1-x.find('|~')/len(x)]['~'in x]

```

# Answer
> 7 votes
# CJam, ~~19~~ ~~17~~ ~~16~~ 58 * 0.85 - 35 = 14.3 bytes

```
q'|-_'~#_)\@,d/1\m100*s'%+"This drought goat out of hand"?

```

Try it online

This version gets both bonuses. The input *must* have a trailing newline for this solution to work.

Thanks to @Martin Büttner for saving 2 bytes.

Explanation:

```
q       Get input.
'|-     Remove left/right wall, so that position of first ~ in remaining string
        corresponds to the water level.
_       Make a copy.
'~#     Find ~ character.
_)      Make copy of find result, and increment it. This is 0 if the ~
        was not found, and will be used for the bonus condition.
\       Swap original find result to top.
@,      Rotate copy of remaining input to top, and get its length.
d       Convert to double to get float division.
/       Divide the two values. Since the position of the ~ was indexed from
        the top, this is 1 minus the desired result.
1\m     Subtract value from 1, to get the actual result.
100*    Multiply by 100 to get percent.
s       Convert to string.
'%+     Append % sign.
"This drought goat out of hand"
        Push bonus zero string.
?       Ternary operator to pick calculated result or zero string.

```

# Answer
> 5 votes
# JavaScript (ES6), 45 (94 -15% -35)

As an anonymous function. Using template strings, there is a newline that is significant and included in the byte count

**Edit** 1 byte saved thx @user81655

```
p=>p.split`
`.map((r,i)=>r>'|~'?p=i:q=~i)&&q-p?(1+p/q)*100+'%':'This drought goat out of hand'

```

**Less golfed**

```
p=>(
  p.split('\n') // split in rows
  .map((r,i)=> // execute for each row
    r>'|~'   // look for the water top
      ? p=i  // position of water top in p
      : q=~i // if not water top, set current position (-i-1) in q
  ),
  // at the end,if water top not found, p still contains the input string
  q-p // subtracting the input string I get NaN (that is a falsy value)
  ? (1+p/q)*100+'%' // calc % taking into account the negative sign of q
  : 'This drought goat out of hand'
)

```

**Test snippet**

```
F=p=>p.split`\n`.map((r,i)=>r>'|~'?p=i:q=~i)&&q-p?(1+p/q)*100+'%':'This drought goat out of hand'

function Update() {
  var w=+W.value, h=+H.value, t=+T.value,
      b=Array(h).fill().map((r,i)=>'|'+(i==h-1?'_':i==t?'~':' ').repeat(w)+'|').join`\n`
  O.textContent = b+'\n\n'+F(b)

}

Update()
```

```
<table>
  <tr><td>Width</td><td><input id=W type=number value=4 oninput='Update()'></td></tr>
  <tr><td>Height</td><td><input id=H type=number value=4 oninput='Update()'></td></tr>
  <tr><td>~~~ at row</td><td><input id=T type=number value=2 oninput='Update()'></td></tr>
</table>
<pre id=O></pre>
```

# Answer
> 4 votes
# Par, 57 * 85% - 35 = 13.45 bytes

```
`This drought goat out of hand`r√″T┐↑⌐'~˦↑↔~÷Zx²*'%↔╡\z_g

```

## Explanation

```
`This dr...d`  ## 'This drought goat out of hand'
r              ## Read entire input
√              ## Split by newlines
″              ## Duplicate
T              ## Transpose
┐↑             ## Second element of each line
⌐              ## Reverse
'~˦            ## First index of '~'
↑              ## Plus one
↔              ## Swap
~÷             ## Divide by size
Z              ## Assign to z
x²*            ## Multiply by 100
'%↔╡           ## Append '%'
\              ## Array of string and number
z_g            ## If z=0, then string; else, number

```

# Answer
> 3 votes
## Perl, *70 - 15% - 35* = 24.5 bytes

*includes +1 for `-p`*

```
 $S[$w|=/~/]++}{$_=$w?100*$S[1]/$..'%':'This drought goat out of hand'

```

With comments:

```
$S[ $w |= /~/ ]++                   # $w=0 for air, 1 for having seen water; count element
}{                                  # -n/-p: end the `while(<>){` and begin END block
$_ = $w                             # assign output for -p
  ? 100 * $S[1] / $. . '%'          # $. is $INPUT_LINE_NUMBER
  :'This drought goat out of hand'  # costs 35 aswell, but is effectively more after -15%

```

---

* 26+1 byte version, no bonus: **27**

```
$S[$w|=/~/]++}{$_=$S[1]/$.

```
* 34+1 byte version, with 15% bonus: **29.75**

```
$S[$w|=/~/]++}{$_=100*$S[1]/$..'%'

```
* 61+1 byte version, with -35 bonus: **27**

```
$S[$w|=/~/]++}{$_=$w?$S[1]/$.:'This drought goat out of hand'

```
* 69+1 byte version, both bonuses: **24.50**

```
$S[$w|=/~/]++}{$_=$w?100*$S[1]/$..'%':'This drought goat out of hand'

```

# Answer
> 2 votes
# Javascript, 59.3

I hope extra decimal places are OK. Assumes no trailing newline.

```
drought=
// code
a=>(b=-1,e=a.split`
`.map((c,d)=>b=c[1]=='~'?d:b).length,++b?(e-b+1)*100/e+"%":"This drought goat out of hand")

// I/O
var i = document.getElementById("i");
var o = document.getElementById("o");
i.onchange = i.onkeyup = function(){
  o.textContent = drought(i.value);
};

// explanation
inputStr=>(
  tildePosition = -1, // default: not found
  containerDepth =    // if the current line has a tilde, set tildePosition, otherwise
                      // keep current tildePosition
      inputStr.split`\n`.map((line, pos)=> tildePosition = line[1]=='~' ? pos : tildePosition)
    .length,          // assign number of lines (container depth) to containerDepth
  ++tildePosition     // if it's still -1, print the message, otherwise print percent
    ?(containerDepth-tildePosition+1)*100/containerDepth+"%"
    :"This drought goat out of hand")
```

```
<textarea id="i"></textarea>
<p id="o"></p>
```

# Answer
> 1 votes
## Haskell, 56 bytes

```
l=sum.(>>[1])
f i|s<-lines i=l(snd$break(elem '~')s)/l s

```

Usage example: `f "| |\n|~~|\n| |\n|__|"` -\> `0.75`.

`l` is a custom length function, which is necessary, because the build in `length` returns integer values, but we need floating point values for the division (there's `genericLength` which also provides this feature, but it's longer, let alone the required `import Data.List`). `f` splits the input `i` into lines (-\> `s`) and then into a pair where the first element is a list with all the lines up to (and excluding) the first one with a `~` in it. The second element is a list with the rest of the lines. The result is the length of the second element divided by the length of `s`.

The bonuses don't pay off.

# Answer
> 1 votes
Python is verbose!

# Python: 98.45 bytes

*(157 * 0.85) - 35 = 98.45 bytes*

This version reads from stdin, and collects both bonuses:

```
import sys
r=[x[1]for x in sys.stdin.read().split('\n|')]
o="This drought goat out of hand"if'~'not in r else"%g%%"%(100-100.0*r.index('~')/len(r))
print(o)

```

# Answer
> 1 votes
# Awk, 72 characters - 15% - 35 = 26.2

```
/~/{w=NR}END{print w?(NR-w+1)/NR*100"%":"This drought goat out of hand"}

```

Sample run:

(Initial `1;` only used in these sample runs to display the “human readable” tank.)

```
bash-4.3$ awk '1;/~/{w=NR}END{print w?(NR-w+1)/NR*100"%":"This drought goat out of hand"}' <<< $'| |\n| |\n| |\n|_|'
| |
| |
| |
|_|
This drought goat out of hand

bash-4.3$ awk '1;/~/{w=NR}END{print w?(NR-w+1)/NR*100"%":"This drought goat out of hand"}' <<< $'| |\n| |\n|~|\n|_|'
| |
| |
|~|
|_|
50%

```

# Answer
> 1 votes
# PHP, 92 characters - 15% - 35 = 43.2

(88 characters in two blocks of code + 4 characters command line options.)

```
$argn[1]>z&&$w=+$argi;

```

```
echo$w?100*($argi-$w+1)/$argi."%":"This drought goat out of hand";

```

Assumes `error_reporting` is set to default.

(Not a big deal, just wished to use the `-R` and `-E` once. Now only `-B` left.)

Sample run:

(Initial `echo"$argn\n";` only used in these sample runs to display the “human readable” tank.)

```
bash-4.3$ php -R 'echo"$argn\n";$argn[1]>z&&$w=+$argi;' -E 'echo$w?100*($argi-$w+1)/$argi."%":"This drought goat out of hand";' <<< $'| |\n| |\n| |\n|_|'
| |
| |
| |
|_|
This drought goat out of hand

bash-4.3$ php -R 'echo"$argn\n";$argn[1]>z&&$w=+$argi;' -E 'echo$w?100*($argi-$w+1)/$argi."%":"This drought goat out of hand";' <<< $'| |\n| |\n|~|\n|_|'
| |
| |
|~|
|_|
50%

```

# Answer
> 0 votes
**QBIC \- 116 - 15% = 98.6 bytes**

```
{input S$:S$=MID$(S$,2,1):I=I+1:IF y<1 then x=I
y=y+instr(S$,"~"):IF instr(S$,"_")>0 THEN ?(1-(x-y)/I)*100;"%":END}

```

I've created QBIC to make QBasic more competitive, but it still needs several improvements. As of now, there are no shortcuts for error trapping, `THEN` (which is a pretty big oversight on my part) and `input$`. They will be added shortly.

I couldn't hit the 0 bonus, too costly... I did manage to print percentages.

Sample in/output:

```
? |  |
? |  |
? |~~|
? |__|
 50 %

```

The program reads the input interactively. When it detects the bottom of the lake (`_`) it prints the percentage and quits. Tested for full containers and empty ones as well.

Edit: To show how QBIC has been expanded during the last year, here's the same program written for the current interpreter:

```
{_?A=$MID$|(A,2,1)#~|#_| i=i+1~j<1|k=i]j=j+instr(A,B)~instr(A,C)|?(1-(k-j)/i)*100,@%|_X

```

87 bytes, printing percentages, is a score of 74.

---
Tags: code-golf
---


title: Map a random number to pi

text:
# Question
Title: Map a random number to pi
A double precision representation of a decimal can only guarantee an accuracy of 15 decimal places, thus pi is approximated as:

```
3.141592653589793

```

You can see that the digit `3` is in positions `1, 10, 16`, the digit `1` is in positions `2, 4` etc.

**Challenge**

Your task is to create a program or function that creates a random double number between 0 and 1, and maps the values of that number onto the value of pi. You do this by placing the different digits in the random numbers in the position that digit has in pi. If the digit is not found in pi, you'll skip it, and every digit in pi that's not in the random number will be represented by an `x`. Each value can only be used once, starting from the left.

A few examples will probably make this more clear. In the following examples, the first number is pi, the second is the random number, and the last is the desired output.

```
3.141592653589793
0.111111111111111
x.1x1xxxxxxxxxxxx

3.141592653589793
0.531000000000000
3.1xx5xxxxxxxxxxx

3.141592653589793
0.123456789123456
3.141592653x8x7xx

3.141592653589793
0.967552381459391
3.14159265358979x

```

Rules:

* The function should not take any input (a possible exception is explained in bullet point 3)
* The output shall consist of only the output string, with an optional newline (a single trailing space is also accepted)
* If your program doesn't have a built-in Pi-value, and/or a RNG then you can hardcode Pi, and take the random number as input. You cannot hardcode the random number or take Pi as input.
* Both the hardcoded value for Pi, and the 15 random digits (you can skip `0.` since you know it will be between 0 and 1), will be included in the byte count.
* If your language doesn't have the required precision, you can use less precision under the following restrictions
    + The digits of Pi must be accurate up to the precision you have
    + You can't output more values than you're guaranteed to have correct, i.e. you can't output 15 digits if the precision only allows 8 accurate decimals.
    + The hardcoded value of Pi will count as 16 bytes (you don't need the decimal point), even if your program only supports 8 digits.
    + The input value for the random number will count as 15 bytes (you don't need `0.`. This is because languages with low precision should not have an unfair advantage.
    + The program must support 5 decimals precision (at least).
    + **Edit: To validate the answer: The random number should be printed somehow, but this operation doesn't have to be included in the byte count. So for instance, if it's possible to insert a `print r` in the end of the script, that part will not increase the score.**
    + You cannot subtract the bytes if it's part of another necessary operation. I.e. if the code is `print pi, r`, then you can only subtract `, r`.
    + If you have to insert parts several places in the code, please include both versions (the one that prints the random number and the one that doesn't with a comment such as: `_p` and `_oNo` are needed to print the random number. `_p` does xxx and `_oNo` does yyy. `_p` and `_oNo` will not be included in the byte count.

Shortest code in bytes win.

---

## Leaderboard

The Stack Snippet at the bottom of this post generates the catalog from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```
## Language Name, N bytes

```

where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:

```
## Ruby, <s>104</s> <s>101</s> 96 bytes

```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:

```
## Perl, 43 + 2 (-p flag) = 45 bytes

```

You can also make the language name a link which will then show up in the snippet:

```
## [><>](http://esolangs.org/wiki/Fish), 121 bytes

```

```
var QUESTION_ID=67223,OVERRIDE_USER=44713;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```

# Answer
# Pyth, 25 bytes

```
 u&p?}HGH\x.-GH`.n0<`O017

```

Try it online: Demonstration or Test showing the random number

### Explanation:

```
 u&p?}HGH\x.-GH`.n0<`O017
                .n0         the constant pi
               `            convert it into a string
                     O0     random number in the range [0.0, 1.0)
                    `       convert to string
                   <   17   only use the first 17 chars (zero, point and 15 digits)
 u                          for each char H in the pi-string:
    ?}HGH\x                    if H in G (the random number string) then H else "x"
   p                           print this char without newline
  &                            and
           .-GH                remove the digit H once from G
<space>                     suppress the output (u returns the unused digits in G)

```
> 5 votes

# Answer
# LabVIEW, 53 LabVIEW Primitives

I match Strings and put the number into an "empty" x.xxx string and remove the number from pi so it doesn´t show up again.

the random number and the single chars here are kinda visible, is that all right or do i have to redo the recording?
> 14 votes

# Answer
# Mathematica, 105 or 147 characters

If random number "*between* 0 and 1" means `0 <= random <= 1`, i.e. includes 0 & 1.

```
StringReplace[ToString@InputForm@N@Pi,
Thread[ToString/@Complement[Range@9,RandomInteger[{0,9},15]]->"x"]]

```

(105 characters)

Otherwise, taking random number "*between* 0 and 1" to mean `0 < random < 1`.

Loop to get 15 random integers, not all zero. Select complement from 0 to 9 range, i.e. those numbers from 0 to 9 not in the random list. Convert those integers to strings and replace the matching characters in a pi string.

(147 characters)

```
While[True,r=RandomInteger[{0,9},15];
If[Union@r!={0},Break[]]];
StringReplace[ToString@InputForm@N@Pi,
Thread[ToString/@Complement[Range@9,r]->"x"]]

3.1x15x265358x7x3

```

Random digits:-

```
FromDigits[r]

820307536180783

```
> 6 votes

# Answer
# JavaScript (ES6), ~~89~~ 87 bytes

```
_=>(r=[...Math.random()+""],Math.PI+"").replace(/./g,d=>(r[i=r.indexOf(d)]=_,~i?d:"x"))

```

## Explanation

**Edit:** Random string is now not truncated as clarified by the poster.

Loops through each digit of pi and removes the digit from the random number if it was found, else replaces the digit in pi with `x`.

```
_=>(
    r=[...Math.random()+""],      // r = array of 15 digit random number chars
    Math.PI+"").replace(/./g,d=>( // for each digit d of pi, includes "." which is always
                                  //     in the random number
      r[i=r.indexOf(d)]=_,        // i = position of d within r, remove digit from r
                                  // "_" is the unused function argument (equals undefined)
      ~i?d:"x"                    // if found, leave the digit, else replace with x
    ))

```

## Test

Test outputs the random number also.

```
var solution = _=>(r=[...n=Math.random()+""],Math.PI+"").replace(/./g,d=>(r[i=r.indexOf(d)]=_,~i?d:"x"))
```

```
<button onclick="result.textContent='Result: '+solution()+'\nNumber: '+n">Go</button>
<pre id="result"></pre>
```
> 5 votes

# Answer
## CJam, ~~48~~ ~~46~~ ~~42~~ ~~38~~ 36 bytes

```
P`'xf+1dmr`{1$f#:!1a/0=:)W+H<.%}/1f=

```

Test it here.

And here is the version which prints both π and the random number:

```
P_p`'xf+1dmr`_oNo{1$f#:!1a/0=:)W+H<.%}/1f=

```

Test it here.

I do not truncate the random number to 15 decimal places, as clarified by the OP in a comment.

### Explanation

The idea is to turn each character in the string representation of π into a pair of that character and `x`. For each character in the random number, we swap the first pair which starts with that character. At the end we output the second character of each pair.

```
P`      e# Get string representation of π.
'xf+    e# Append "x" to each character.
1dmr`   e# Get string representation of random number in [0,1).
{       e# For each character in that string...
  1$    e#   Copy the list of pairs.
  f#    e#   For each pair, find the index of the current character. If the character is
        e#   not in the pair, we get -1 (truthy). If it is the first character of the pair,
        e#   we get 0 (falsy). If it is the second character, we get 1 (truthy).
  :!    e#   Logical NOT for each of the results. We get a 1 for every pair we could
        e#   potentially swap.
  1a/   e#   Split around those 1s.
  0=    e#   Keep only the first chunk.
  :)    e#   Turn all the 0s into that chunk into 1s.
  W+    e#   Append a -1.
  H<    e#   Truncate to 17 elements (the number of pairs).
  .%    e#   Apply % pairwise. This reverses the element at the position of the -1.
}/
1f=     e# Select the second character from each pair.

```
> 3 votes

# Answer
# Lua, ~~231~~ 230 bytes

```
m,s=math,""p,r=m.pi..s,s..m.random()p=p:sub(1,#p-1)p:gsub(".",function(c)s=s..(47>c:byte()and c or"x")end)r:gsub("[^%.]",function(c)l=p:find(c)if l then p,s=p:sub(1,l-1).."x"..p:sub(l+1),s:sub(1,l-1)..c..s:sub(l+1)end end)print(s)

```

### Explanations

```
function f()
  m,s=math,""
  p,r=m.pi..s,s..m.random()
  p=p:sub(1,#p-1)                       -- remove the last digit of math.pi

  p:gsub(".",function(c)
    s=s..(47>c:byte()and c or"x")      -- Construct a string full of "x" with a single dot
  end)

  r:gsub("[^%.]",function(c)            -- Iterate over each character but the dot in the random number
    l=p:find(c)                         -- if c isn't in pi, l=nil
    if l                                -- which is one of the two falsy value in lua
    then
      p,s=p:sub(1,l-1).."x"..p:sub(l+1),-- If c is in pi, we replace it in p by an x
          s:sub(1,l-1)..c..s:sub(l+1)   -- and in s by its value
    end
  end)
  return s
end

```

Sadly, lua doesn't help me at all here. math.pi round the last digit of pi it return :

```
print(math.pi)
>> 3.1415926535898

```

I have to truncate this number :

```
stringPI=""..math.pi
print(stringPI:sub(1,#stringPI-1))
>> 3.141592653589

```

The second big default to do this challenge was lua lack of string.replace(). As I'm doing this action twice using `s:sub(1,l-1)..c..s:sub(l+1)`, I wanted to do an anonymous function, thinking it would be shorter. It isn't, so I kept it written twice.

The reason I have to be careful about the dot, is how lua return its position. In regexes, a dot mean "any character", so when i'm evaluating the character `.` in my loop it matches the first character :

```
c="."  -- The value of the dot in the loop
found = stringPI:find(c)
print(stringPI)
print("location of \".\": "..found)
print("char at "..found..": "..stringPI:sub(found,found))

>> 3.141592653589
>> location of ".": 1   --Keep in mind that lua arrays are 1-based :)
>> char at 1: 3

```

You can test lua online. As I am not seeding the PRNG, here's a code allowing you to run several test while still watching values.

```
function f()m,s=math,""p,r=m.pi..s,s..m.random()print("Random number: "..r)p=p:sub(1,#p-1)p:gsub(".",function(c)s=s..(c:byte()<47 and c or"x")end)r:gsub("[^%.]",function(c)l=p:find(c)if l then p,s=p:sub(1,l-1).."x"..p:sub(l+1),s:sub(1,l-1)..c..s:sub(l+1)end end)return s end

for i=1,10
do
    print(f())
end

```
> 2 votes

# Answer
## Python 2.7, ~~117~~ 110 bytes

```
import math,random
n=list(`random.random()`)
print''.join(n.pop(n.index(d))if d in n else'x'for d in`math.pi`)

```

Tested on the latest QPython Android app, but should work anywhere.

Edit 1: changed `str(pi)` to backticks.

For testing:

```
import math,random
n=list(`random.random()`)
print `math.pi`
print ''.join(n)
print''.join(n.pop(n.index(d))if d in n else'x'for d in`math.pi`)

```
> 2 votes

# Answer
# Python, 147 bytes

```
import math as m,random as r
L=lambda t:[_ for _ in str(t)]
p=L(m.pi)
R=L(r.random())
A=""
print R #subtracted from byte count
for n in p:
    try:R.remove(n);A+=n
    except:A+='x'
print A

```

Fairly self-explanatory: lambda function converts float to list; we then loop through the pi-list attempting to remove each digit from the random-list. If we can, good, append it to the answer; if not, append an 'x' instead.
> 1 votes

# Answer
# Perl, 70 bytes

```
$_=4*atan2(1,1);s/\d/x$&/g;for$i(rand=~/\d/g){s/x$i/$i/}s/x./x/g;print

```

With comments:

```
$_=4*atan2(1,1);        # Perl doesn't have a Pi constant
s/\d/x$&/g;             # prepend a x to all digits in Pi
for $i (rand=~/\d/g)    # iterate the digits in the random number
{ s/x$i/$i/ }           # replace first occurrence of x-nr pair
s/x./x/g;               # strip all remaining numbers
print                   # print!

```

---

This version will print pi, the random number, and the result:

```
$_=$p=4*atan2(1,1);
s/\d/x$&/g;
$r=rand;
for $i ($r=~/\d/g)
{ s/x$i/$i/ }
s/x./x/g;
print "$p\n$r\n$_\n"

```

Example output:

```
3.14159265358979
0.877757977767946
x.x4x59x6xxx897x

```

I hope this is okay:

* pi contains 15 digits total, including the 3, so it doesn't exceed accuracy.
* the last digit (`9`) is accurate.
> 1 votes

---
Tags: code-golf, string, random, pi
---


title: Parrot User’s Delay

text:
# Question
Title: Parrot User’s Delay
A simple code golf challenge similar to an already existing, but more complex one:

1. Wait for user to press enter.
2. Wait for user to press enter again.
3. Print the elapsed time between the 1. and 2.
4. Wait an equal amount of time
5. Print the actual elapsed time of 4.

Order of 3. and 4. is not important. Notice that the second printout entails actual timekeeping during the machine's delay; just outputting the desired delay is not enough.

The time outputs should be in seconds, with at least 10 ms resolution.

# Answer
> 2 votes
# MATL, 14 bytes

This answer uses the current version of the language (3.1.0), which is earlier than the challenge.

```
jY`jZ`tDY`Y.Z`

```

### Example

I tried to wait for about 1 second:

```
>> matl jY`jZ`tDY`Y.Z`
>
>
1.011063770698121
1.013172086910349

```

### Explanation

```
j       % input string (will be empty)
Y`      % start a stopwatch timer
j       % input string (will be empty)
Z`      % read the stopwatch timer and push the value onto the stack
tD      % duplicate, convert to string and display
Y`      % start a stopwatch timer (this doesn't produce any output)
Y.      % pause the specified amount of time (which is at the top of the stack)
Z`      % read the stopwatch timer (will be implicitly displayed)

```

# Answer
> 1 votes
# R, 87 bytes

### code

```
f=readline;s=Sys.time;f();q=s();f();e=(m=s())+(z=(m-q));while(s()<e)1;cat(z,"\n",s()-m)

```

### example

```
> f=readline;s=Sys.time;f();q=s();f();e=(m=s())+(z=(m-q));while(s()<e)1;cat(z,"\n",s()-m)
> 1.343448     # 1 second wait plus 0.3s mental lag
> 1.358646

```

# Answer
> 1 votes
## Matlab: 44 bytes ##

```
input('');tic;input('');t=toc
pause(t);toc-t

```

Output

```
t =
    1.8318
ans =
    1.8338

```

Explanation: `input('')` wait for enter, `tic` starts timer, `t=toc` display

# Answer
> 0 votes
## Mathematica, 71 bytes

```
(b=InputString)[];a=(c=Print@*First)@(d=AbsoluteTiming)@b[];c@d@Pause@a

```

Needs to be run in v10.3 or higher. Good thing that symbols are first-class objects...

# Answer
> 0 votes
# Bash + GNU utilities, 63

```
d=0
f(){ read;d=`date +%s.%N-$d|bc -l`;}
f
f
bc<<<$d/1
sleep $d

```

---
Tags: code-golf, date, keyboard
---


title: cat file reader with line numbering

text:
# Question
Title: cat file reader with line numbering
You must do a program that reads a file given in first argument and print it's content to STDOUT and number the lines on the file, the numbers should be followed by a space.
For instance, assuming that your program is named cat, we could write `./cat "myfile.txt"` (or execute it with its interpreter)

With myfile.txt:

```
Hello, world, this
is a file with
multiple characters..0

```

And the program should output to STDOUT :

```
1  Hello, world, this
2  is a file with
3  multiple characters..0

```

The shortest program in bytes win.

For example :

Perl

```
$r++&print"$r ".$_ while<>

```

# Answer
> 0 votes
# LabVIEW, 32 LabVIEW Primitives

Reads line by line and concatenates numbers space and newlines, then deletes a trailing number, space and newline.

---
Tags: code-golf
---


title: The Complement Cat

text:
# Question
Title: The Complement Cat
**Objective** Write a full program that outputs (to STDOUT or closest alternative) an arbitrary string of text, no more than 64 characters long. Simple enough, right? Well, here's the catch: You may not use any characters that were present in the previous answer's output. That's right, *none* of them.

Thus, you are trying to be the last answer for a total of three days. That is, you want no one to answer the question in the 72 hours following the posting of your question.

## Some rules

* Your answer (and output) may only contain printable ASCII characters, newlines (carriage returns included), and tabs.
* Your answer's output may not be the same as another answer's output. Two output's are the same if and only if they use the exact same characters.
* You may use any language that was not specifically made for this challenge, even if it was made after the challenge. (This language, of course, must be testable.)
* You may not use any language that was previously used.
* Your entry may not include comments. You may, of course, provide an extra commented program.
* You *may not* answer twice in a row.
* Your program must be at least 1 byte.

## Entry format

Your answer should look generally like the following:

```
# {Language}
Uses: `characters present in the output`

Does not use: `characters used in the previous output` from [previous submission, language](link-to-previous-submission]

    {program}

Outputs:

    {output}

```

An explanation with your answer is appreciated.

# Answer
> 2 votes
# Ruby

```
$><<'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" '

```

Does not use `abcdefghijklmnopqrstuvwxyz{}\~_^[]|`` from the previous answer.

Prints, and hence uses, `ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"`, a space, and a newline.

# Answer
> 5 votes
# Brainfuck

Uses: `-.`

Does not use: `!"%&')+,0123456789<=>ABCDEFGHIJKLNOPRSTWXYZ]`acefghjlnoprstux{|` from CJam. Thanks to SuperJedi

```
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------.--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.-------------------------------------------------------------------------------------------.-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.

```

Outputs:

```
; (){}[]"'

```

# Answer
> 5 votes
# Pyth

Uses: `()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefg`.

Doesn't use: `!"#$%&'()*+,-./0123456789:;<=>?@[\]^_`abcdefghijklnsm{|}~` from previous submission in Octave.

Code:

```
pMCMryyTyyytytttT

```

Output:

```
()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefg

```

# Answer
> 3 votes
# CJam

Uses: `0123456789:;_bc`

Does not use:  `!GSaefgimnoprstuw`, from previous submission, MATLAB

```
183185535513294435547695067785526290427932963043839368372854060721693597139131275368051870173845056551161192991350318233082749156998652_;128b:c

```

Outputs:

```
 !"%&')+,0123456789<=>ABCDEFGHIJKLNOPRSTWXYZ]`acefghjlnoprstux{|

```

# Answer
> 3 votes
# Octave

Uses:  `!"#$%&'()*+,-./0123456789:;<=>?@[\]^_``abcdefghijklnsm{|}~` and a newline in the output.

Doesn't use: `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"` from previous submission in Microscript.

Code:

```
[' ':'@','[':'`','{':'~',('@'+' '):('>'+'/')]

```

Output:

```
ans =
 !"#$%&'()*+,-./0123456789:;<=>?@[\]^_`{|}~`abcdefghijklm

```

Explanation:

This is a collection of consecutive ASCII-characters. The code is equivalent to:

```
[char(32:64) char(91:96) char(123:126) char(96:109)]

```

Where `char(32:64)` are the ASCII characters from 32 to 64 (space to @). In order to get the alphabet-part in the end of the output, I had to add characters, as I couldn't use `a` and `m`. `@+`  equals 96 (\`\`) and `>+/` equals 109 (m)

# Answer
> 3 votes
# Perl

Uses:  `0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz}` (with space)

Does not use: `"#$%'()*+,-./123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`{|~` from previous submission in Unreadable

```
eval q!print uc q&} abcdefghijklmnopqrstuvwxyz&!and eval q}print q&0abcdefghijklmnopqrstuvwxyz&}and eval q&print length for qw!a bc def ghij klmno pqrstu vwxyzab cdefghij klmnopqrs!&

```

Outputs:

```
} ABCDEFGHIJKLMNOPQRSTUVWXYZ0abcdefghijklmnopqrstuvwxyz123456789

```

---

…the old joke about monkeys writing code comes to mind…

You can run the program online.

This program abuses the weird features of Perl to write code in just about any subset of ASCII:

* Functions can be called without parentheses in some cases (unsure about exact rules)
* `q#text#` where `#` can be almost any character is the same as `"text"`
* `qw#word1 word2 word3#` like the above is the same as `["word1", "word2", "word3"]`
* `for` loops and other things can be appended to lines, eliminating any punctuation

# Answer
> 3 votes
# Javascript ES6

Previous answer: https://codegolf.stackexchange.com/a/67406/39022

Source does not contain `!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ`, space, or newline.

```
alert`abcdefghijklmnopqrstuvwxyz{}\\~_^[]|\``

```

Output:

```
abcdefghijklmnopqrstuvwxyz{}\~_^[]|`

```

(Lowercase alphabet, curly brackets, backslash, tilde, underscore, carat, square brackets, pipe, and backtick)

# Answer
> 2 votes
# Python 3

Uses: `!CGaceilmnoprstw z`.

```
print("Germanic Capitalization is awesome!")

```

Simply prints `Germanic Capitalization is awesome!` with no restrictions. Good luck!

# Answer
> 2 votes
# MATLAB

Uses:  `!GSaefgimnoprstuw` and newline.

Does not use: `!CGaceilmnoprstw z` from previous submission, Python 3.

```
[83,116,101,119,105,101,32,71,114,105,102,102,105,110,32,105,115,32,97,32,112,114,111,109,105,110,101,110,116,32,103,101,110,105,111,117,115,33,'']

```

Prints:

```
ans =

Stewie Griffin is a prominent genious!

```

# Answer
> 2 votes
# Microscript II

Previous answer: here. Program does not use semicolon, space, parentheses, curly brackets, square brackets, single straight quotes, or double straight quotes. This program would be a lot shorter if it didn't have to avoid quotes.

Output includes: `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"`, and a newline.

Program:

```
97Kp98Kp99Kp100Kp101Kp102Kp103Kp104Kp105Kp106Kp107Kp108Kp109Kp110Kp111Kp112Kp113Kp114Kp115Kp116Kp117Kp118Kp119Kp120Kp121Kp122Kp""P65Kp66Kp67Kp68Kp69Kp70Kp71Kp72Kp73Kp74Kp75Kp76Kp77Kp78Kp79Kp80Kp81Kp82Kp83Kp84Kp85Kp86Kp87Kp88Kp89Kp90Kp123456789qh

```

Exact output:

```
abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ"123456789"

```

# Answer
> 2 votes
# Unreadable

Uses: `"#$%'()*+,-./123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`{|~`

Does not use: `()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefg` from previous submission in Pyth

> '"'""'""'"'""'"'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'"'""'""'"'""'"'""'"'""'"'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'"""

Outputs:

```
"#$%'()*+,-./123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`{|~

```

---

In case you are wondering, yes, programming by hand in this language is painful, so I made this script (in JavaScript) to generate the code:

```
var program = `"`,
    output = "\"#$%'()*+,-./123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`{|~";
for(var i = 1, c = 0; c < output.length; i++) {
  program = `'""` + program;
  if(i == output.charCodeAt(c)) {
    program = `'"` + program;
    c++;
  }
}
program;

```

I used the Python interpreter for Unreadable here to run the code.

# Answer
> 1 votes
# GolfScript

Uses: space, newline, `!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ`.

Doesn't use `0-9A-Za-z{` or space from previous submission in Perl.

The code:

```
'!'.!=('['.!=,>''+

```

The output:

```
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ

```

And a trailing newline.

Try it here.

---
Tags: string, restricted-source, printable-ascii, answer-chaining
---