title: A Sine of Greatness

text:
# Question
Title: A Sine of Greatness
# Introduction

Everyone's heard of sine (sin), cosine (cos), tangent (tan), cotangent (cot), secant (sec), and cosecant (csc). Nearly every angle has them.

Far less known, or remembered, are the exsecant (exsec), excosecant (excsc), versine (versin), and coversine (cvs). Nearly every angle has those as well. There are some that are *even less* known, but we'll just stick to these.

I've created a visualization of these for angle θ, which is 45°.

---

# The Challenge

Create a program that takes an input of an angle `n`, in degrees, and will output:

1. the sine of angle `n`
2. the cosine of angle `n`
3. the tangent of angle `n`
4. the secant of angle `n`
5. *at least* one of the following. Every additional item from this list will earn a bonus -5%, for a maximum of -25%.

* exsecant of angle `n`
    * cosecant of angle `n`
    * excosecant of angle `n`
    * versine of angle `n`
    * coversine of angle `n`
    * cotangent of angle `n`

If your score is a decimal after applying a bonus, round up to the nearest whole number.

---

# Input

You may accept your input through STDIN or through a function call. A single argument, `n`, will be passed.

`n` will always be a whole integer that is greater than 0, but less than or equal to 90.

---

# Output

Here is an example of the output for sine of 45°. All output items must be in this format. The order of the items does not matter.

```
sine: 0.70710678118

```

All items must have exactly 4 numbers after the decimal (precision to the ten-thousandths). Below are a few examples of rounding.

```
0 -> 0.0000
1 -> 1.0000
0.2588190451 -> 0.2588
5.67128181962 -> 5.6713
10 -> 10.0000
12.4661204396 -> 12.4661

```

Any nonexistent/undefined results should default to 0.

---

# Example

```
myprogram(60)

sine: 0.8660
cosine: 0.5000
tangent: 1.7321
secant: 2.0000
exsecant: 1.0000
cosecant: 1.1547
excosecant: 0.1547
versine: 0.5000
coversine: 0.1340
cotangent: 0.5774

```

---

# Scoreboard

For your score to appear on the board, it should be in this format:

```
# Language, Score

```

Or if you earned a bonus:

```
# Language, Score (Bytes - Bonus%)

```

Strikethroughs shouldn't cause a problem.

```
function getURL(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 getAnswers(){$.ajax({url:getURL(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){var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),useData(answers)}})}function getOwnerName(e){return e.owner.display_name}function useData(e){var s=[];e.forEach(function(e){var a=e.body.replace(/<s>.*<\/s>/,"").replace(/<strike>.*<\/strike>/,"");console.log(a),VALID_HEAD.test(a)&&s.push({user:getOwnerName(e),language:a.match(VALID_HEAD)[1],score:+a.match(VALID_HEAD)[2],link:e.share_link})}),s.sort(function(e,s){var a=e.score,r=s.score;return a-r}),s.forEach(function(e,s){var a=$("#score-template").html();a=a.replace("{{RANK}}",s+1+"").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SCORE}}",e.score),a=$(a),$("#scores").append(a)})}var QUESTION_ID=58283,ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",answers=[],answer_ids,answers_hash,answer_page=1;getAnswers();var VALID_HEAD=/<h\d>([^\n,]*)[, ]*(\d+).*<\/h\d>/;
```

```
body{text-align:left!important}table thead{font-weight:700}table td{padding:10px 0 0 30px}#scores-cont{padding:10px;width:600px}#scores tr td:first-of-type{padding-left:0}
```

```
<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="scores-cont"><h2>Scores</h2><table class="score-table"><thead> <tr><td></td><td>User</td><td>Language</td><td>Score</td></tr></thead> <tbody id="scores"></tbody></table></div><table style="display: none"> <tbody id="score-template"><tr><td>{{RANK}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SCORE}}</td></tr></tbody></table>
```

# Answer
# CJam, ~~94~~ ~~89~~ ~~85~~ ~~81~~ 80 bytes

```
"sine tangent secant"S/{"co"1$+}%rd90/_i33Yb@[P*2/__ms\mc@mt]_Wf#W%+?.{d": %.4f"e%N}

```

The code is 84 bytes long and qualifies for a 5% bonus (*cotangent* and *cosecant*).

Try it online in the CJam interpreter.

### How it works

```
"sine tangent secant" e# Push that string.
S/                    e# Split it at spaces.
{"co"1$+}%            e# For each chunk, append a copy to the string "co", pushing
                      e# ["sine" "cosine" "tangent" "cotangent" "secant" "cosecant"].
rd90/                 e# Read a Double from STDIN and divide it by 90.
_i                    e# Push a copy and cast it to integer.
33Yb                  e# Push 33 in base 2, i.e., [1 0 0 0 0 1].
@                     e# Rotate the Double on top of the stack.
[                     e#
  P*2/                e# Multiply by Pi and divide by 2.
  __                  e# Push two copies of the result.
  ms                  e# Compute the sine of the topmost copy.
  \mc                 e# Swap and compute the cosine of the next copy.
  @mt                 e# Rotate and compute the tangent of the original.
 ]                    e#
 _Wf#                 e# Copy the array and raise all Doubles to the power -1.
                      e# This computes cosecant, secant and cotangent.
 W%                   e# Reverse their order.
 +                    e# Append to the original array.
 ?                    e# Select 33Yb if the integer part of the input divided by 90 is
                      e# (i.e., if the input is 90), the constructed array otherwise.
 .{                   e# For each function name and result:
   d                  e# Cast to Double (needed for 33Yb).
   ": %.4f"           e# Push a format string containing ": " and a 4-decimal float.
   e%                 e# Apply the formatting to the Double on the stack.
   N                  e# Push a linefeed.
 }                    e#

```
> 8 votes

# Answer
# Julia, 162 - 10% = 144 bytes

```
n->for z=zip(split("sine cosine tangent secant exsecant cosecant cotangent"),[sind,cosd,tand,secd,i->secd(i)-1,cscd,cotd]) @printf("%s: %.4f\n",z[1],z[2](n))end

```

Ungolfed:

```
function f(n)
    # Construct a vector of names
    s = split("sine cosine tangent secant exsecant cosecant cotangent")

    # Construct a vector of functions
    o = [sind, cosd, tand, secd, i -> secd(i) - 1, cscd, cotd]

    # Print each in a loop
    for z = zip(s, o)
        @printf("%s: %.4f\n", z[1], z[2](n))
    end
end

```
> 6 votes

# Answer
## Mathematica (Invalid at the moment), ~~134~~ ~~121~~ 104

Just for fun, surely it can be golfed down a lot

```
f[n_]:=(a={Sin,Cos,Tan,Sec,Cot,Csc};TableForm[N[#@n,4]&/@a,TableHeadings->{ToString[#]<>":"&/@a,None}])

```

And it should have a 5% bonus (Cot and Csc), therefore amounting at 99 characters

Example output:
> 5 votes

# Answer
# Pyth, 66 - 10% = 59.4 bytes

```
j+V+Jc"sine secant tangent")+L"co"Jsmm%": %.4f"^.t.td7k^_1k3,Q-90Q

```

Calculates the sine, secant and tangent. Then, the co- functions are simply calculated via the formula `coF(x) = F(90 - x)`.
> 5 votes

# Answer
# JavaScript (ES6), 173 (182 - 5%)

**Edit** revised after clarification, now the bonus is 5%

**Edit** realized that the angle can not be 0

```
// TEST - redefine alert
alert=x=>O.innerHTML=x

r=(a=prompt(i=0))*(M=Math).PI/180,V=_=>[s=M.sin(r),c=M.cos(r),(f=a-90)&&s/c,c/s,f&&1/c,1/s][i++].toFixed(4);
alert(`sine
tangent
secant`.replace(/.+/g,h=>h+`: ${V()}
co${h}: ${V()}`))

/* More bonus, but too longer
r=(a=prompt(i=0))*(M=Math).PI/180,V=_=>[s=M.sin(r),c=M.cos(r),1-c,1-s,(f=a-90)&&s/c,c/s,f&&1/c,1/s][i++].toFixed(4);
alert(`sine
versine
tangent
secant`.replace(/.+/g,h=>h+`: ${V()}
co${h}: ${V()}`))
*/
```

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

# Answer
# Javascript ES6, ~~154~~ 148 (198 - 25%)

```
(n=0)=>[S='sine',(O='co')+S,T='tangent',C='secant',X=O+C,O+T,V='ver'+S,O+V,'ex'+C,'ex'+X].map((q,i)=>q+': '+[s=Math.sin(n),c=Math.cos(n),t=s/c,e=1/c,o=1/s,1/t,1-c,1-s,e-1,o-1][i].toFixed(4)).join`
`

```

Ungolfed:

```
(n=0)=>          // function declaration, accepts number, defaults to 0
  [              // create array of trig function names
    S='sine',    // sine
    (O='co')+S,  // cosine
    T='tangent', // tangent
    C='secant',  // secant
    X=O+C,       // cosecant
    O+T,         // cotangent
    V='ver'+S,   // versine
    O+V,         // coversine
    'ex'+C,      // exsecant
    'ex'+X       // excosecant
  ].map((q,i)=>  // map over names
                 // append ": <value rounded to 4 decimals>" to function name:
    q+': '+[s=Math.sin(n),c=Math.cos(n),t=s/c,e=1/c,o=1/s,1/t,1-c,1-s,e-1,o-1][i].toFixed(4)
  ).join`        // add newline between each function
`

```
> 4 votes

# Answer
# R, ~~122~~ ~~136~~ 134 bytes

```
n=scan()*pi/180;write(paste0(c("sine","cosine","tangent","secant","versine"),sprintf(": %.4f",c(sin(n),r<-cos(n),tan(n),1/r,1-r))),"")

```

---

**Example usage**

```
> n=scan()*pi/180;write(paste0(c("sine","cosine","tangent","secant","versine"),sprintf(": %.4f",c(sin(n),r<-cos(n),tan(n),1/r,1-r))),"")
1: 60
2:
Read 1 item
sine: 0.8660
cosine: 0.5000
tangent: 1.7321
secant: 2.0000
versine: 0.5000

```
> 3 votes

# Answer
# Python 3, 282 (375 - 25%)

Error handling turned out to be somewhat complicated by floating-point errors; namely, `cos(90)` came out to a very small number instead of zero.

It's never going to be the top answer, but I like to think it **might** be the shortest valid all-functions answer in a non-golfy language that doesn't have the trig functions in the default namespace. ;-)

```
import math as m
def p(q,r):print(q+':','%.4f'%r)
def a(n):
 n=n*m.pi/180
 C,S=round(m.cos(n),8),m.sin(n)
 A=S,1,0,C,1,S,C,0,C,S,1,C,0,1,S,1,C,-1,1,S,C,1,1,S,1
 def t():
  nonlocal A;u,v,w,x,y,*A=A;z=-1 if w>0 else 1
  try:return z*u/v+w,z*x/y+w
  except:return 0,0
 def q(y,x=''):J,K=t();p(x+y,J);p(x+'co'+y,K)
 q('sine');q('tangent');s='secant';q(s);q(s,'ex');q('versine')

```

Sample output:

```
>>> a(60)
sine: 0.8660
cosine: 0.5000
tangent: 1.7321
cotangent: 0.5774
secant: 2.0000
cosecant: 1.1547
exsecant: 1.0000
excosecant: 0.1547
versine: 0.5000
coversine: 0.1340

```
> 3 votes

# Answer
# Perl, ~~182~~ 177 (236 - 25%)

Run with `-n` (1 byte added to uncorrected score).

```
$b=$_==90;$_/=57.296;$c=cos;$s=sin;sub f{printf"%s: %.4f\n",@_}$T=tangent;f$T,$b?0:$s/$c;f co.$T,$c/$s;$S=sine;f $S,$s;f co.$S,$c;$C=secant;f$C,$b?0:1/$c;f co.$C,1/$s;f ex.$C,$b?0:1-1/$c;f exco.$C,1/$s-1;$V=ver.$S;f$V,1-$c;f co.$V,1-$s

```

Nothing fancy. It takes advantage of `-n` for implicit input, `$_` as a default argument to `sin` and `cos`, and barewords for strings. The “undefined = 0” rule is hardcoded in using the ternary operator `?:` (it applies only for 90°).

One thing I learend is that apparently, you cannot have (or cannot *call*) a subroutine named `s` (or `m`, `y`, `tr`): `sub s {print 1}; s` yields `Substitution pattern not terminated at -e line 1`.
> 3 votes

# Answer
# Perl, 165 (193 - 15%)

I am submit this a s a new answer because the idea is quite different from the other one. Please let me know if it is more appropriate to replace my first attempt.

```
$p=atan2 1,0;$b=$_-90;%h=qw(sine $s tangent $b?$s/$c:0 secant $b?1/$c:0 versine 1-$c);$_/=90/$p;sub e{$c=cos;$s=sin}e;sub f{eval"printf'$x$_: %.4f
',$h{$_}"for keys%h}f;$b=1;$_=$p-$_;e;$x=co;f

```

Run with `-n` (1 byte added).

Ungolfed:

```
# π/2
$p=atan2 1,0;

# trouble?
$b=$_-90;

# Construct a hash whose keys are the “base” function names,
# and whose values are the corresponding expressions in terms of sin and cos
%h=qw(sine $s tangent $b?$s/$c:0 secant $b?1/$c:0 versine 1-$c);

# Thanks to ‘-n’, input is in $_; convert to radians
$_/=90/$p;

# Compute sin and cos in a reusable way
sub e{$c=cos;$s=sin}
e;

sub f {
   eval "printf '$x$_: %.4f
', $h{$_}"
      for keys %h
}

f;

# Now the “co” functions
# No trouble here
$b=1;

# x ← π/2 - x
$_=$p-$_;

e;
$x=co;
f

```

Since it does the four “co”-functions, I think it qualifies for a 3\*5% = 15% bonus.
> 3 votes

# Answer
# Perl, ~~100~~ ~~95~~ 94 bytes

Whoa, lotta perl answers.

```
$_=<>;printf"sine: %.4f\ncosine: %.4f\ntangent: %.4f\nsecant: %.4f\n",sin,cos,(sin)/cos,1/cos

```
> 3 votes

# Answer
# Haskell, 159 = 186 - 15% bytes

```
s x=zipWith(\a b->a++": "++show b)(concatMap(\n->[n,"co"++n])$words"sine tangent versine secant")$map($(x*pi/180))[sin,cos,t,(1/).t,(1-).cos,(1-).sin,e.t,e.(1/).t]
e=sqrt.(+1).(^2)
t=tan

```

No ex-thingies to keep my clever naming scheme and since I didn't know how to shorten `(\x->x-1)`. `(-1)` is just a number.

Please complain if you want me to prettify (`mapM_ putStrLn`) the lines.
> 2 votes

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


title: Filling Arbitrary Ice Cube Trays

text:
# Question
Title: Filling Arbitrary Ice Cube Trays
Suppose this grid of spaces and `X`'s represents the cross section of some strangely shaped empty ice cube trays:

```
   X     X X
X  X X  XX X  XX   X
XXXXXX XXXXXXXXXXXXX

```

Columns without `X`'s represent holes or gaps in the trays that can't hold water, draining into an infinite capacity sink. Water falling off the leftmost or rightmost edge of the grid goes into this endless sink as well.

If we were to position a faucet above the trays and let them fill with water until the water level in all compartments remains stable, the exact compartments that become filled would depend on exactly where the water stream was positioned above the trays. (Assume a thin, steady stream of water with no splashing.)

---

For example, if our faucet `F` were above the very left grid column

```
F
   X     X X
X  X X  XX X  XX   X
XXXXXX XXXXXXXXXXXXX

```

the water would fall down to the topmost `X` in that column and spread left and right, the left half spilling into the sink below, and the right half filling up the 2×1 compartment. Once the compartment fills, the right half of the water stream has nowhere to flow but into the sink and the water level everywhere is essentially stable.

Turning the faucet off, the tray now looks like this: (with `~` as water)

```
   X     X X
X~~X X  XX X  XX   X
XXXXXX XXXXXXXXXXXXX

```

---

Similarly, if we position the faucet like this:

```
   F
   X     X X
X  X X  XX X  XX   X
XXXXXX XXXXXXXXXXXXX

```

It will fill up the two leftmost compartments but the rest of the water will drain away:

```
   X     X X
X~~X~X  XX X  XX   X
XXXXXX XXXXXXXXXXXXX

```

---

If we position the faucet like this:

```
         F
   X     X X
X  X X  XX X  XX   X
XXXXXX XXXXXXXXXXXXX

```

The left half of the stream will flow into the sink but the right half will eventually fill up the three rightmost compartments because there's no limit to how far water can travel horizontally on a flat surface:

```
   X     X~X
X  X X  XX~X~~XX~~~X
XXXXXX XXXXXXXXXXXXX

```

Positioned like this, however:

```
        F
   X     X X
X  X X  XX X  XX   X
XXXXXX XXXXXXXXXXXXX

```

All the water drains away and no compartments are filled:

```
   X     X X
X  X X  XX X  XX   X
XXXXXX XXXXXXXXXXXXX

```

---

# Challenge

Write a program or function that takes in a rectangular grid of spaces, `X`'s, and one `F`. The top row will always contain the `F` and otherwise only contain spaces. The `X`'s in each column (if there are any) will extend in a solid line up from the base of the grid, i.e. there will be no caves or overhangs.

Print or return the grid after the faucet `F` has filled what it can with water `~` as described above. Leave the top `F` row out of the output.

* The grid apart from the faucet row will be 1×1 at minimum so

```
F
X

```

is the smallest input you need to support.
* The input will come in as a complete text rectangle. Leading and trailing spaces do matter in the input and output. e.g. the input

```
    F
  X  X
  XXXX

```

should result in

```
  X~~X
  XXXX

```

(note the leading and trailing spaces)
* Having a single trailing newline in the input or output is fine.
* You can use any four distinct printable ASCII characters in place of space, `X`, `F`, `~`.

**The shortest code in bytes wins.**

---

**Big Example:**

Input:

```
                F
              X             X
              X             X X
X            XXX       X    X X           X    X
X   X     XXXXXXX      X    XXX     XXXXXXX X  X
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXX

```

Output:

```
              X~~~~~~~~~~~~~X
              X~~~~~~~~~~~~~X~X
X~~~~~~~~~~~~XXX~~~~~~~X~~~~X~X~~~~~~~~~~~X    X
X~~~X~~~~~XXXXXXX~~~~~~X~~~~XXX~~~~~XXXXXXX X  X
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXX

```

# Answer
> 1 votes
# perl -p0, 204+2 bytes

**IDEA**

* If both sides of the island below F are of equal height, replace all `X *X`es with `X~*X`es on that island.
* If one side is higher, replace all `X *X`es with `X~*X`es between the drain on the lower side and the point closest to F that's higher than the lower side's top.

The land directly below F counts as a part of both sides here.

**GOLF**

```
s/.*(F).*
//;$f=@-[1];($%,$r)=map{y///c}/(.{0,$f})\bX+?\b(.*)$/;($a,$b)=map{y///c}/[^~]*^(?(?=(.{$%,$f}X)).{$f} *|.{$f} *X(.*)).{$r}
/m;$a=$%if!$a||$b;$b+=$r;s/(?<=.{$a})\b *\b(?=.{$b})/"~"x length($&)/ge

```

**NOTES**

```
perl -p0e ' # slurp stdin, print the result

s/.*(F).*\n//; # remove the first line, record the index of F
$f=@-[1]; # get the index of F

($l,$r)=map{length}m/(.{0,$f})\bX+?\b(.*)$/;
# gets the distance from either side to the drains closest to F
($a,$b)=map{length}m/[^~]*^(?(?=(.{$l,$f}X)).{$f} *|.{$f} *X(.*)).{$r}\n/m;
# tries to find the lowest line that has at least one X on
# one side of the island, but none on the other
$a=$l if !$a||$b;
$b+=$r; # use the captured groups to calculate the left and right bounds
s/(?<=.{$a})\b *\b(?=.{$b})/"~" x length($&)/ge;
# replace all pools within those bounds
'

```

It might be hard to recognise the original algorithm in this implementation since Perl doesn't support lookbehinds of variable length.

# Answer
> 6 votes
# Lua 5.2, 581 Bytes

Again, slow start with so ineffective language for golfing and with ineffective algorithm. But I will improve :)

```
r=io.read w=io.write F=r()f=F:find("F")o={[1]=F}W=#F i=2
repeat s=r()if s==nil then break end o[i]={}for j=1,W do o[i][j]=s:sub(j,j)end i=i+1 until false
function e(i,j)
local k,l,b,c=j+1,j-1,false
if i>=#o or(o[i+1][j]==" "and e(i+1,j)==0)then return 0 end
while k<=W do
b=b or o[i][k]=="X"
if b or(o[i+1][k]==" "and e(i+1,k)==0)then break end
k=k+1 end
while l>0 do
c=c or o[i][l]=="X"
if c or(o[i+1][l]==" "and e(i+1,l)==0)then break end
l=l-1 end
if b and c then for m=l+1,k-1 do o[i][m]="~"end return 1 end
return 0 end
e(1,f)for i=2,#o do for j=1,W do w(o[i][j])end w"\n"end

```

Test cases (with water source):

```
---------
    F
  X~~X
  XXXX
--------------------
         F
   X     X~X
X  X X  XX~X~~XX~~~X
XXXXXX XXXXXXXXXXXXX
--------------------
   F
   X     X X
X~~X~X  XX X  XX   X
XXXXXX XXXXXXXXXXXXX
--------------------------------------------------
                F
              X~~~~~~~~~~~~~X
              X~~~~~~~~~~~~~X~X
X~~~~~~~~~~~~XXX~~~~~~~X~~~~X~X~~~~~~~~~~~X    X
X~~~X~~~~~XXXXXXX~~~~~~X~~~~XXX~~~~~XXXXXXX X  X
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXX

```

from bash it is possible to test this way, but it doesn't look so nice:

```
$ echo "    F
  X  X
  XXXX   " | lua f.lua

```

# Answer
> 1 votes
# Javascript, 460 Bytes

Online demo (in console, tested in current Chrome and Firefox).

```
function e(i,j){var k=j+1,l=j-1,b=0,c=0,I=i+1
if(i>(O-2)||(o[I][j]==" "&&e(I,j)==0))return 0
while(k<W){b=b||(o[i][k]=="X")
if(b||(o[I][k]==" "&&e(I,k)==0))break
k++}while(l>=0){c=c||(o[i][l]=="X")
if(c||(o[I][l]==" "&&e(I,l)==0))break
l--}if(b&&c){for(m=l+1;m<k;m++)o[i][m]="~"
return 1}return 0}function f(d){o=d.split("\n")
F=o[0];s=F.indexOf("F");W=F.length;O=o.length
for(i=0;i<O;i++)o[i]=o[i].split("")
e(0,s);for(i=1;i<O;i++)console.log(o[i].join(""))}

```

Challenging myself is not so fun, but still possible. Same algorithm as the Lua one, now in javascript.

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


# Question
Title: Isn't the point of math to just use numbers?
Write a program that converts a mathematical expression to words, evaluates the expression, and prints how the equation would be spoken aloud.

**Input**

* The input must only contain numbers and the symbols `+`, `-`, `*`, and `/`. There cannot be any whitespace in the input.
* The input does not say what the expression is equal to.

**Output**

* While order of operations must be followed in determining the numerical answer in the expression, it is not necessary to indicate this in the output (for this reason, the input cannot contain parentheses).
* Numbers must be printed in capital letters. Operations must be printed in lower case.
* Numbers must be printed in the order that they appear in the input. Then the word `equals` must be printed, then the answer.
* Numbers in the output can be negative. The word negative is written in capital letters.
* Operations and numbers must be separated by a space. There cannot be any space after the last letter is printed.
* `+` in the input gets converted to `plus` in the output. `-` in the input gets converted to `minus` in the output. `*` in the input gets converted to `times` in the output. `/` in the input gets converted to `divided by` in the output.
* Division by 0 is not allowed.
* When division results in a decimal, the number should be rounded to three decimal places and read `X POINT X X X` where the `X`s are replaced by numbers.
* Negative numbers should have \`NEGATIVE in front of them.
* For simplicity, all numbers must have absolute value less than 1000.
* `0` is `ZERO` (not `NOUGHT`, `OH`, etc).

**Samples**

Inputs

```
1+2
2-3
6*2-4/1
1+1-1*1/1
2/3
413-621

```

Outputs

```
ONE plus TWO equals THREE
TWO minus THREE equals NEGATIVE ONE
SIX times TWO minus FOUR divided by ONE equals EIGHT
ONE plus ONE minus ONE times ONE divided by ONE equals ONE
TWO divided by THREE equals ZERO POINT SIX SIX SEVEN
FOUR HUNDRED THIRTEEN minus SIX HUNDRED TWENTY-ONE equals NEGATIVE TWO HUNDRED EIGHT

```

---

This is code golf, fellas. Standard CG rules apply. Shortest code in bytes wins.

# Answer
# JavaScript ES6, ~~255~~ ~~247~~ ~~237~~ ~~225~~ 219 bytes

```
s=>(s+'='+ +eval(s).toFixed(3))[h=(a,b,l)=>' '+[a,...btoa(b).split`z`][l],t='replace'](/\D/g,l=>h('divided by',`¶)³:eºÌæ{¬Íê®j[3¦§·<`,'*+-/=.'.indexOf(l)))[t](/\d/g,l=>h('ZERO',`8Ñ3Mc³LtD1NQÅ!Q3HóHED71tó4D`,l))

```

I'll resume golfing tomorrow. Gotta sleep :/

Base encoding may cause issues. If it does, I'll add a pastebin and possibly a hex dump.

If you find any issues (or the spec changes) don't hesitate to tell me, I'll fix it as soon as possible.

## Explanation

```
s=>     // Function with argument "s"
 (s+'='                  // Add an equal sign to the input
   + +eval(s).toFixed(3)    // Add the value of the expression rounded to 3 places
 )[h=(a,b,l)=>           // Function h with args a,b, and l
                         // Return...
     ' '+                    // A space added to...
     [a,...btoa(b).split`z`] // Base decode the compressed words
     [l]                     // Grab the correct word
  ,t='replace'            // Alias replace command

 ](/\D/g,                // Replace non-digits with...
    l=>h(                                   // Function h
       'divided by',`¶)³:eºÌæ{¬Íê®j[3¦§·<`, // Base encoded words
       '*+-/=.'.indexOf(l)                  // Replace operator with correct word
    )

 )[t](                             // Replace again
    /\d/g,l=>                      // Replaces Digits with...
      h('ZERO',`8Ñ3Mc³LtD1NQÅ!Q3HóHED71tó4D` // Base encoded words
        ,l                                   // The associated number
      )
 )

```
> 4 votes

# Answer
# Pyth, ~~170~~ ~~143~~ 141 bytes

```
jdm@c"ZERO,ONE,TWO,THREE,FOUR,FIVE,SIX,SEVEN,EIGHT,NINE,plus,minus,times,divided by,POINT,equals"\,x+jkm`kUT"+-*/.="d++z\=?q>2J`.Rvz3".0"<2JJ

```

Evaluates the input and if it ends with ".0", strips it. Then loops through a list with the numbers, then looks with their word representation.
> 1 votes

# Answer
## Python 3, 268 224bytes

```
a=input()
o=eval(a)
print(*[{i:j for i,j in zip('*+-./=1234567890','times,plus,minus,POINT,divided by,equals,ONE,TWO,THREE,FOUR,FIVE,SIX,SEVEN,EIGHT,NINE,ZERO'.split(','))}[i] for i in a+'='+('%.'+str(3*(int(o)!=o))+'f')%o])

```

A dictionary lookup for each item assuming numbers are only evaluated between 0-9. Would appreciate some feedback on this.

Explanation:

The following formats the output string with the required decimals based on the fact that in python integers evaluate as equal to the equivalent float. e.g. 1.0 == 1 Which I use to identify integer numbers.

```
('%.'+str(3*(int(o)!=o))+'f')%o
('%.0f')%o if o is an integer
('%.3f')%o if o is a decimal

```

---

edit: Dictionary generators!
> 1 votes

# Answer
# Python 2, ~~281~~ ~~223~~ ~~221~~ 219 + 5 bytes

run with: "python -Qnew golf.py" to enable float divisions

```
a=raw_input()
print" ".join("ZERO%ONE%TWO%THREE%FOUR%FIVE%SIX%SEVEN%EIGHT%NINE%NEGATIVE%times%plus%equals%minus%POINT%divided by".split("%")[ord(i)-48]for i in a+','+("%.3f"%eval(a)).replace("-",")").replace(".000",""))

```

4 bytes off thanks to Zach Gates
> 1 votes

# Answer
# Python 2, 628 + 5 bytes

run with: "python -Qnew golf.py" to enable float divisions

this one should spell correctly the numbers

```
import re
a=raw_input()
d,x="ZERO%ONE%TWO%THREE%FOUR%FIVE%SIX%SEVEN%EIGHT%NINE%TEN%ELEVEN%TWELVE%THIR%FOUR%FIF%SIX%SEVEN%EIGH%NINE%TWENTY%THIRTY%FORTY%FIFTY%SIXTY%SEVENTY%EIGHTY%NINETY%NEGATIVE%times%plus%equals%minus%POINT%divided by".split("%"),[]
for i in re.split("([.),/*+-])",a+','+("%.3f"%eval(a)).replace("-",")").rstrip('0').rstrip('.')):
    r=""
    if len(i)>2:
        x+=[d[int(i)//100],"HUNDRED"];i=i[1:].lstrip("0")
    if len(i)>1:
        z=int(i)
        if z<20:r+=d[z]+["","TEEN"][z>12];i=""
        else:r+=d[z//10+18]+["-",""][i[1]<"1"];i=i[1].strip("0")
    if i:
        c=d[ord(i)-48]
        if i<"0":x+=[c]
        else:r+=c
    if r:x+=[r]
print" ".join(x)

```

# Test

```
1+2
ONE plus TWO equals THREE
2-3
TWO minus THREE equals NEGATIVE ONE
6*2-4/1
SIX times TWO minus FOUR divided by ONE equals EIGHT
1+1-1*1/1
ONE plus ONE minus ONE times ONE divided by ONE equals ONE
2/3
TWO divided by THREE equals ZERO POINT SIX HUNDRED SIXTY-SEVEN
413-621
FOUR HUNDRED THIRTEEN minus SIX HUNDRED TWENTY-ONE equals NEGATIVE TWO HUNDRED EIGHTEEN

```
> 0 votes

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


title: Break tabs in half

text:
# Question
Title: Break tabs in half
> Holy wars have been fought over spaces vs. tabs. (And of course spaces, being objectively superior, won.) —Alex A.

**S**ome peo**p**le still refuse to **a**ccept that whi**c**h is cl**e**arly **s**upreme. You've just received **a** file using the incor**re**ct, **b**ad, and inf**e**rior form of whi**t**espace, and now **t**he cont**e**nts of the file a**r**e tainted and ruined.

You decide you might as well show the person who sent the file to you just how wrong they are—violently.

## Description

As the title suggests, your challenge is to take a file that contains one or more tabs:

```
this is an evil tab    onoes

```

and ruthlessly shatter them into pieces:

```
this is an evil tab

                     o
                     n
                     o
                     e
                     s

```

Note that the Stack Exchange software turns literal tabs into four spaces (because it's right), so tabs within this post will be displayed as four spaces. The input to your program, however, will contain actual tabs.

## Challenge

The solution should take a single string as input, which may contain printable ASCII, newlines, and tabs. There will always be at least a single tab in the input.

The output should be the same string, with the following rules applied:

* Start the cursor at coordinates (0,0) and with a direction of right. The coordinates are (column,row), zero-indexed, and the direction is which way you should move the cursor after printing a character.
* For each character in the string:

+ If it's a newline, move to coordinates (0,n), where n is the number of newlines in the string so far (including this one), and reset the direction to right.
    + If it's a tab, output two spaces, *rotate the cursor direction 90 degrees clockwise*, and output two more spaces, effectively "breaking" the tab in half. Here's a visual example, where a tab is represented as `--->` and spaces as `·`:

    ```
    foo--->bar--->baz

    ```

    becomes

    ```
    foo···
         ·
         b
         a
         r
         ·
         ·
     zab··

    ```
    + Otherwise, simply output the character at the cursor and move the cursor one step in the current direction.

Since you are reading the string from start to end, it is possible that you will have to write "on top" of existing characters—this is okay. For example, the input

```
foo--->bar

spaces are superior

```

should result in an output of

```
foo

     b
spaces are superior
     r

```

You may choose whether "broken tabs" should overwrite other characters—the original intention was that they do not, but the spec was ambiguous, so this is your decision.

Furthermore, after applying these rules, you may also

* add or remove as many trailing spaces as you would like.
* add a maximum of a single trailing newline.

The input will *never* contain trailing spaces; it will also never contain leading or trailing newlines. You may also always assume that you will never need to write to a column or a row less than 0 (i.e. off the screen).

## Test case

Tabs in this test case are represented as `--->` because otherwise SE gobbles them up.

Input:

```
Test case. Here's a tab--->there's a tab--->everywhere a tab--->tab--->this is some more text
blah
blah
blah blah blah blah blah blah--->blaah--->blaah--->blah--->blaaaaah--->blah--->blah--->blah--->blah--->blah

```

Output:

```
Test case. Here's a tab
blah
blah                     t
blah blah blah blah blah blah
                        blaablah
                         r     b
                         e     l  b
                      h  'h    a  l
                      a  sa    a  a
                      l   l    h  h
       this is some mobe tbxt

                         haalhalb
     b                   a
     a                   b
     t

        bat a erehwyreve

```

Fancy animation:

## Rules

* This is , so the shortest code in bytes will win!

# Answer
# MATLAB, 144 bytes

The weapon of choice for dealing with strings is of course a language designed for manipulating numbers \[citation needed\]. Kidding aside, the great thing about Matlab is that it doesn't care if you assign to an array 'out of bounds': it will simply make a larger matrix. Furthermore, the default matrix element, `0`, is rendered as a space instead of a `null` character the ASCII spec prescribes.

Tabs are simply a jump in coordinates, so no spaces are outputted for a tab.

```
function o=q(t)
u=2;v=0;x=1;y=1;n=1;for s=t
if s==9 x=x+u-v;y=y+v+u;a=v;v=u;u=-a;elseif s<11
n=n+1;x=1;y=n;else
o(y,x)=s;x=x+u/2;y=y+v/2;end
end

```

I started out with 209 bytes, but some more careful golfing got rid of most of that; there's a lot of repetition in this code, so I did some trial-and-error which alternatives worked best. I don't think there's much space for more optimization with this code, but I'm always happy to be proven wrong. **Edit:** Tom Carpenter managed to prove me wrong; he managed to save 9 bytes which I optimized to save a whopping 29 bytes. Last byte saved by assuming there are no control characters (ASCII \< 9) in the input - MATLAB strings aren't `null`-terminated.
> 8 votes

# Answer
# Python 3, ~~272~~ ~~270~~ ~~266~~ ~~262~~ ~~255~~ ~~253~~ 244 bytes

```
I=[]
try:
 while 1:I+=[input()]
except:r=m=0
M=sum(map(len,I))
O=[M*[' ']for _ in[0]*M]
for l in I:
 x=b=0;y=r;a=1;r+=1
 for c in l:
  if'\t'==c:a,b=-b,a;x+=a+2*b;y+=b-2*a
  else:O[y][x]=c
  x+=a;y+=b;m=max(m,y)
for l in O[:m+1]:print(*l,sep='')

```

The `\t` should be an actual tab character.

The code works somewhat like Zach Gates' answer, first generating a `M` by `M` grid where `M` is the sum of the lengths of the lines. (That's a huge amount of excess, but makes the code shorter.) It then loops through the characters, placing them in the correct spots, keeping track of the bottommost visited row. Finally, it prints all the lines up to that row.

The output contains (usually a huge amount of) trailing spaces and 1 trailing newline.
> 5 votes

# Answer
# Javascript (ES6), ~~264~~ 245 bytes

Tried the "create a giant grid of spaces, fill and trim" approach, which ended up 19 bytes shorter than the other.

```
a=t=>(o=`${' '.repeat(l=t.length)}
`.repeat(l).split`
`.map(q=>q.split``),d=x=y=z=0,s=c=>o[d>2?y--:d==1?y++:y][d?d==2?x--:x:x++]=c,[...t].map(c=>c=='\t'?(s` `,s` `,++d,d%=4,s` `,s` `):c==`
`?(x=d=0,y=++z):s(c)),o.map(p=>p.join``).join`
`.trim())

```

By modifying the second-to-last line like so, you can remove the large amount of trailing spaces on every line:

```
...o.map(p=>p.join``.trimRight())...

```

Try it here:

```
a=t=>(o=`${' '.repeat(l=t.length)}
`.repeat(l).split`
`.map(q=>q.split``),d=x=y=z=0,s=c=>o[d>2?y--:d==1?y++:y][d?d==2?x--:x:x++]=c,[...t].map(c=>c=='\t'?(s` `,s` `,++d,d%=4,s` `,s` `):c==`
`?(x=d=0,y=++z):s(c)),o.map(p=>p.join``.trimRight()).join`
`.trim())

function submit(){ O.innerHTML = a(P.value.replace(/\\t|-+>/g,'\t')); }
```

```
<p>Input: (Use <code>\t</code> or <code>---></code> for a tab.)</p>
<textarea id=P rows="10" cols="40">this is an evil tab\tonoes</textarea>
<br><button onclick="submit()">Try it!</button>
<p>Output: (Looks best in full-page mode.)</p>
<pre id=O>
```

Explanation coming soon; suggestions welcome!
> 3 votes

# Answer
# JavaScript (ES6), 180 ~~183~~

Using template strings, there are some newlines that are significant and counted.

That's a function returning the requested output (padded with tons of trailing spaces)

There is little to explain: the rows are builded as neeeded. There is not a direction variable, just the 2 offset for x and y, as in clockwise rotation they are easily managed: `dx <= -dy, dy <= dx`

Test running the snippet below in Firefox

```
f=s=>[...s].map(c=>c<`
`?(x+=2*(d-e),y+=2*(e+d),[d,e]=[-e,d]):c<' '?(y=++r,e=x=0,d=1):(t=[...(o[y]||'')+' '.repeat(x)],t[x]=c,o[y]=t.join``,x+=d,y+=e),o=[r=x=y=e=0],d=1)&&o.join`
`

// TEST

// Avoid evil tabs even in this source
O.innerHTML = f(`Test case. Here's a tab--->there's a tab--->everywhere a tab--->tab--->this is some more text
blah
blah
blah blah blah blah blah blah--->blaah--->blaah--->blah--->blaaaaah--->blah--->blah--->blah--->blah--->blah`
 .replace(/--->/g,'\t'))
```

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

# Answer
# Python 2, ~~370~~ ~~369~~ 368 bytes

Thanks to @sanchises and @edc65 for saving me a byte each.

```
J=''.join
u=raw_input().replace('\t','  \t  ')
w=u[:]
G=range(len(u))
d,r=0,[[' 'for _ in G]for _ in G]
u=u.split('\n')
for t in G:
 x,y=0,0+t
 for c in u[t]:
  if c=='\t':d=(d+1)%4
  if c!='\t':
   if c.strip():r[y][x]=c
   if d<1:x+=1
   if d==1:y+=1
   if d==2:x-=1
   if d>2:y-=1
r=r[:max(i for i,n in enumerate(r)if J(n).strip())+1]
for i in r:print J(i).rstrip()

```

It generates the largest grid possible and then loops around, character by character, switching direction at each tab.
> 1 votes

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


title: The Stack Exchange Site List

text:
# Question
Title: The Stack Exchange Site List
Currently, the Stack Exchange network has nearly 150 sites. These sites are as follows:

```
Computer Graphics
Portuguese Language
elementary OS
Open Source
Law
Русский язык
Mythology
Health
Stack Overflow на русском
CiviCRM
Woodworking
Music Fans
Vi and Vim
Coffee
Engineering
Lifehacks
Economics
History of Science and Mathematics
Emacs
スタック・オーバーフロー
Worldbuilding
Startups
Community Building
Hinduism
Buddhism
Craft CMS
Puzzling
Data Science
Joomla
Earth Science
Mathematics Educators
Expatriates
Arduino
Software Recommendations
Beer
Ebooks
Aviation
Stack Overflow em Português
Italian Language
Amateur Radio
Pets
Tor
Astronomy
Space Exploration
Blender
Freelancing
Open Data
Network Engineering
Reverse Engineering
Tridion
Sustainable Living
English Language Learners
Magento
Anime & Manga
Politics
ExpressionEngine® Answers
Robotics
Genealogy & Family History
Ask Patents
Salesforce
Islam
Russian Language
Raspberry Pi
Chess
Chemistry
Windows Phone
The Workplace
Computer Science
Academia
Sports
Martial Arts
The Great Outdoors
Cognitive Sciences
Mathematica
Poker
Biology
Chinese Language
Movies & TV
Computational Science
Spanish Language
LEGO® Answers
History
Biblical Hermeneutics
Linguistics
Bitcoin
Christianity
French Language
Signal Processing
Cryptography
Personal Productivity
Travel
Gardening & Landscaping
Philosophy
Japanese Language
German Language
Mi Yodeya
Software Quality Assurance & Testing
Music: Practice & Theory
SharePoint
Parenting
Motor Vehicle Maintenance & Repair
Drupal Answers
Physical Fitness
Skeptics
Project Management
Quantitative Finance
Programming Puzzles & Code Golf
Code Review
Science Fiction & Fantasy
Graphic Design
Database Administrators
Video Production
Writers
Information Security
Sound Design
Homebrewing
Physics
Board & Card Games
Electrical Engineering
Android Enthusiasts
Programmers
Bicycles
Role-playing Games
Ask Different
Theoretical Computer Science
WordPress Development
Unix & Linux
User Experience
English Language & Usage
Personal Finance & Money
Ask Ubuntu
TeX - LaTeX
Geographic Information Systems
Home Improvement
Mathematics
Cross Validated
Photography
Game Development
Seasoned Advice
Webmasters
Arqade
Web Applications
Stack Apps
MathOverflow
Super User
Meta Stack Exchange
Server Fault
Stack Overflow

```

## Your Task:

* Write a program that prints out all of the sites in Stack Exchange, including those with non-ASCII characters (It doesn't need to be in any specific order).
* The program must accept no input, and must output each site on its own line (optional leading/trailing newlines).
* No standard loopholes.
* This is , so the shortest program, measured in bytes, wins.

# Answer
> 4 votes
# Bubblegum, ~~1227~~ 1197 bytes

```
0000000: 65 55 37 7a 2b 37 10 ee 71 0a 54 ee de 05 dc 29 4b fe  eU7z+7..q.T....)K.
0000012: 44 8b 56 b4 cb e1 62 48 8e 85 05 d6 00 96 d4 be e6 05  D.V...bH..........
0000024: 75 ce b1 77 eb ec ca 39 fb 02 d4 19 78 11 ff 00 c3 47  u..w...9....x....G
0000036: fa 29 10 3f 06 33 98 f4 63 38 7f fe f3 fc f9 9f f3 fb  .).?.3..c8........
0000048: fb f9 f3 ef e6 f7 bf ce 9f 7f 39 bf ff 6d 7e ff 61 f9  ..........9..m~.a.
000005a: fc 6c 7e ff 0d 80 da a9 c8 70 2d a4 76 6a 4a dc 06 7d  .l~......p-.vjJ..}
000006c: 4e 46 bc da 71 26 78 31 fa c0 a5 71 1b 85 62 8a 90 49  NF..q&x1...q..b..I
000007e: cd fa 25 dd 23 37 82 7e 30 ad 38 8f f5 2d dc a0 76 e2  ..%.#7.~0.8..-..v.
0000090: ad de 97 e1 90 03 bb 54 76 7d 4a 80 b1 e0 ab 41 eb 52  .......Tv}J....A.R
00000a2: 0b 98 82 77 be ee d4 ce 44 28 89 77 6a 97 39 a8 5d 19  ...w....D(.wj.9.].
00000b4: 58 a9 c8 ea 63 0e 35 3b 6e 93 54 11 d2 aa ab 2c 67 e0  X...c.5;n.T....,g.
00000c6: ad 1f 75 58 53 e5 05 36 96 9d c9 66 9e 82 41 40 7b 79  ..uXS..6...f..A@{y
00000d8: 39 a2 3a ab b6 c6 8c 25 d6 6a 6f 8c ac e0 ae cb 28 46  9.:....%.jo.....(F
00000ea: 7c 8a e3 c8 fa 14 c1 b7 34 62 08 02 ce 85 9c 24 e8 c8  |.......4b.....$..
00000fc: 44 f6 ce 7b 6a cf 1b d6 e7 3c 11 9e 02 23 1b c6 32 82  D..{j....<...#..2.
000010e: 8a 4c 58 5f 54 c2 ae e2 08 51 5d b7 d9 4e ef b6 62 8d  .LX_T....Q]..N..b.
0000120: b8 51 16 35 6d 2a 29 91 5d 69 2e a5 1c f4 51 a0 66 9c  .Q.5m*).]i....Q.f.
0000132: 73 5a 4b d6 2a 81 86 49 ef f5 2e 80 7c 8c fa 9a ac 18  sZK.*..I....|.....
0000144: 4a 6c b0 ef 9a e4 47 d9 b2 53 fb 94 68 40 88 7f c7 d4  Jl....G..S..h@....
0000156: e2 72 62 94 7c 88 45 be be 6b 3f b4 0d bc ef b8 38 65  .rb.|.E..k?.....8e
0000168: 9c cd 3e 7f b8 7f 78 f6 f0 6c f6 cb ec a7 d9 cf fa e1  ..>...x..l........
000017a: 83 d9 8f 0f ef cc 7e 51 07 14 d2 78 6d 74 30 f0 fe 36  ......~Q...xmt0..6
000018c: aa 83 2a 37 46 2a 20 cb 55 0a a5 1d 07 6e 84 aa 71 c8  ..*7F* .U....n..q.
000019e: 19 b2 65 b4 26 51 e8 f4 d9 85 3a a8 09 aa 9b e7 c0 56  ..e.&Q....:......V
00001b0: e2 78 5d 60 7d ca 14 1c e2 78 e1 04 1d bb 8a 58 d5 c1  .x]`}....x.....X..
00001c2: 5d 43 f0 84 6c 63 c6 01 7d 42 fd 16 97 fe f3 ed 3a 8f  ]C..lc..}B......:.
00001d4: c3 c0 6c c9 55 f0 92 b1 ab d6 57 b1 ca 5d d7 fb 3c 61  ..l.U.....W..]..<a
00001e6: eb 9b 1c 1e 04 c1 b0 83 2a bc 40 cb c4 8a 9a 6c 78 c4  ........*.@....lx.
00001f8: 8e 29 b3 08 f2 43 aa c5 76 fa 18 65 f4 a1 c3 d1 a2 ca  .)...C..v..e......
000020a: 52 e9 13 37 f4 a1 2e 6d d4 17 5d 4c 5c 47 1c 43 e2 36  R..7...m..]L\G.C.6
000021c: 5c 2e 74 e1 35 ca c8 a9 63 5c 9b c6 ea 58 9c 69 33 f1  \.t.5...c\...X.i3.
000022e: 96 b7 ae 56 ed 87 ab 52 6b 84 83 c7 93 c0 4c 2a 04 3f  ...V...Rk.....L*.?
0000240: f6 35 0f 02 4f 11 5f c1 fa a4 6e 82 9f 70 49 64 2b 14  .5..O._...n..pId+.
0000252: ae da 90 79 7a 12 2d d5 ea 24 91 95 cd 90 5e a1 86 36  ...yz.-..$....^..6
0000264: d9 0d 89 f7 b5 25 75 4a 53 75 7a 70 74 b6 51 cd 53 19  .....%uJSuzpt.Q.S.
0000276: f2 98 aa db 8c a0 2c b1 84 d2 83 91 4b 1e 6b 48 92 39  ......,.....K.kH.9
0000288: 14 12 84 eb 58 69 03 c7 4d ac 0f 4c 5b 15 2a 16 e9 d9  ....Xi..M..L[.*...
000029a: 84 c3 d0 fa a9 ea 71 e6 65 82 1f 7d 70 57 8d 11 16 ab  ......q.e..}pW....
00002ac: 9e e8 37 bc e1 0e 97 79 58 e8 6b 46 19 2d a3 24 e2 12  ..7....yX.kF.-.$..
00002be: 3b 74 38 53 e3 9c 1b 92 00 95 89 70 c4 fe f2 5a f5 da  ;t8S.......p...Z..
00002d0: 28 15 ba e6 e2 02 be ac fb 81 2a b8 e7 7c 3e e6 5c ee  (.........*..|>.\.
00002e2: 5e 97 c6 8b 29 f1 2a a7 a9 0f b7 5b e4 3d 6b d8 e9 fc  ^...).*....[.=k...
00002f4: 56 16 e8 c2 b7 01 d4 ef 53 1e 56 f9 bc cf 21 96 97 7b  V.......S.V...!..{
0000306: 28 ab 38 7a de 71 b7 3e 80 47 8f 4c 31 07 24 65 29 aa  (.8z.q.>.G.L1.$e).
0000318: d3 1f 8b f5 d1 e3 75 02 fa d5 4b 05 ee 10 62 b9 2a a1  ......u...K...b.*.
000032a: 27 71 29 c0 ea 6f 39 e0 d3 4a 5a 6c 43 6a 47 ed 56 d7  'q)..o9..JZlCjG.V.
000033c: e0 04 b7 d4 35 9c ae 71 a6 72 bf 7d fc d8 96 6a 94 01  ....5..q.r.}...j..
000034e: 75 e4 ed 30 9f bf c9 55 ca d3 18 a6 85 32 45 2d a7 f3  u..0...U.....2E-..
0000360: 5a 4b c8 2b 11 c2 e5 55 4a ea 9c 62 33 e0 00 4a f6 45  ZK.+...UJ..b3..J.E
0000372: 61 c6 c1 09 6f 15 e9 dc 0f 7c 0e 0d c0 f2 a3 c6 52 07  a...o....|......R.
0000384: 69 99 ab 10 b5 31 6e 51 ee 82 10 d0 d0 e7 32 2e e9 0d  i....1nQ......2...
0000396: 47 55 66 6b 79 60 2e 51 ec d4 05 13 aa c7 06 53 6b 22  GUfky`.Q.......Sk"
00003a8: 59 93 03 dc e2 b8 b5 49 5d 8c 29 70 df 8b 03 94 d1 b2  Y......I].)p......
00003ba: c6 15 2a 96 63 b9 b8 e5 a6 c4 72 e1 87 69 0a 45 8d 9c  ..*.c.....r..i.E..
00003cc: 6c 1e b9 3b 31 b6 61 d9 a3 4b 8e a5 7d 6b a5 73 ae 3c  l..;1.a..K..}k.s.<
00003de: ca e7 4c 79 37 d9 ba 75 66 f5 52 2f 1a 82 15 06 8d f5  ..Ly7..uf.R/......
00003f0: a1 9c 67 89 db 9c 4c 10 f8 4c fc 05 71 77 9a 66 05 d7  ..g...L..L..qw.f..
0000402: bc de de ea d9 ef b3 ef f5 c3 d3 f5 9c fd 63 f6 db ff  ..............c...
0000414: 55 b8 d6 cb 56 ff fb 65 b9 0e b8 01 68 1b 0e 98 83 1c  U...V..e....h.....
0000426: 00 63 22 34 69 60 41 05 99 e4 84 2e f9 75 fd 08 61 61  .c"4i`A......u..aa
0000438: 55 20 b8 3e 0a 4c 49 9f b5 c9 f8 fc d4 0a e7 39 15 9a  U .>.LI........9..
000044a: bd f0 8d 92 f5 6f f0 00 d0 c0 bc f3 41 5d 06 c2 80 c4  .....o......A]....
000045c: 22 26 67 7d e5 e4 2e 4f 47 71 ed 9d ca 11 e4 9a 70 58  "&g}...OGq......pX
000046e: 58 5f 4b 19 53 d7 52 03 1a f6 6b e2 c3 f0 86 07 b9 28  X_K.S.R...k......(
0000480: 56 aa 65 79 21 a8 29 c2 39 a0 38 e3 a7 51 e3 29 38 56  V.ey!.).9.8..Q.)8V
0000492: 37 de 9b fc 08 91 0b 70 30 fd 3c db b7 e6 34 a4 d6 0c  7......p0.<...4...
00004a4: 56 5f 9f 37 41 ca 2d ff 01                             V_.7A.-..

```

Prints a sorted list of SE sites.

Compression has been done with zopfli, which uses the DEFLATE format but obtains a much better ratio than (g)zip.

# Answer
> 1 votes
# Python3, ~~1754~~ ~~1728~~ 1662 bytes

~~Python3 includes the `lzma` module, which allowed me to obtain a really decent compression ratio.~~ (I have switched to `gzip`.) I was originally going to use base64 to encode the output but realized I could squeeze some more bytes out using base85 (ascii85).

I avoided the issue with escaping `'` by using a triple-quoted string and avoided the issue with escaping `\` characters by using the `r""` prefix.

```
import base64,gzip
print(gzip.decompress(base64.a85decode(r'''+,^C)B/BZj!rlh3]9_20&FK!&W8.1RdSX2MG($0f,4;Ut&gBgi+qS,^:g1Gf=(R8b8Y=`"jO#8sSE-4$#Gc:bO5pd"a]c<M-kMcVF75Ychj%1^aigAZ<M?`A-I0YX;,\St;Kbp<"UQq`P)[UCng5)1'j6s9g1M[#C+ZkYm5DT.]@Ye]gHW,bjmN$5n%8%sn&2_mKemVoLau@M(*\_f>KWEMq71K\\c$=@S(rF=3rJaG^$+dImSCm_V/uIdq5(M-0s6/SjJB.JghWm*0(3p3qJJJE&d,bmQH8[;Oe,L&'L<-_B3iX@>j2e?E4`YS1JKd&2SrS8Jk?c'bFhgZmN:?S+91#42Z(O%pR=DAO)O`]p\W2GmISBsk%D=,Q8eW@egBR-W!?R-!EdLM[Q6=PGPlW\D-lO)MI)k:"i']CRRc$QVd`Q=H=_?MKo5.$9>#5H1eJ/fZT'P.iKSu-c4l-:ieL,pY>qA@&s#0+M:Bf1>'Z90aoI35N`-FXotZS)ba\bga\'%C+%nnr4Que%Rinl/10W?AqBnNn[?jgWCF:GCK=H&1,U%Kr\IiPP5V-:\kIUj[!sD/Bl%tA))40(rLMIZt;e1%4\U%0U)S#3_mFLU9Kj0>2ZrJma=2H0VKPa26iWN/>89p+!i+rG#3g!NMP'dJ9m6\Y@7X&l;<1ZEAfIkXf^W=?J24pDMR;;O*ahk?f/rj;=;O^,sN.dplEWS9Q84]#>0R):Xf>4C`9PXbpB5X_92'WV6::04$aNMmBYn61H4Q=pX:'tW*g_M0oY@V:\-!RBbbbGi79]\74^bqA9.XfghaFsT_fqBc.j\6b:`uaKW"WXLCFGpdVbf"TSTh\C-%GEI#`-KCah+CU2osaZ#.'9SlGJjU*m5b2U1`5)>EI$WGVe62?NP$GG=&Rie4G&6"O7p8bA*1-%#gY#Y)i8uQZa8kp??#UpG8Z;D"8%"?7CV3ce\IA4\AJNX$0pXq[pH2XLnXB"=e%c@#agB@<?,FFB]F^)o.Lg#H,@?.E6jdhC\a7=WDO`um>Dm2Ju2=1W4h3<!knpd*/E*XJ>3+Aqbe!sOVTo;6+p,hn7K;g%U@,&_?>V2a07T5G)/,S8nfq2HsO#4#C7ad'3\QmFgPtcF@fJ*-Q)WIZH0HZDP#Sa5`pgJKH2[f)k$GO]Wu'Sg54>Eh+*HFkfd;=DeMa;CN1>bQTAUqZsA7[+>i(sDo`:n:oKpu1Beh`*.cf*h8HnV3Ot>5kie@>8$:n+U4:>:>V`.Wp8f2c(X2)1a=C??bgX.%N2q\E*$f+&r%h:ubWRX.g:*<::QWNWhWZ"qZ%+)L`,M`HoCm@XJ91.,6dO/,%J.u$jAs%B\7ShidHX6,c1";KU2fc2Ntn=Bj]p@,IV8<UHVW>l6/2Y1a7',4p;eT`m$YKom'MtC%nc?t_gpr?ceY\2Ynjh@V0n;upk;YY/q=:)fPEmM1:6u$la$)!e[aZ:md#3)bkLT]Xp`B<YWMLlPOPB<PSAXF%WPR=Ml'V`6CGj3ItR:0.l+(RDYWYjl0]E?FjoMuiF&=2#K`3d1%?RBmMe9!"kZ)LPK-FcX>]UD]BXk\/OT09#QOi''')).decode())

```

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


title: Watch 'em fall like dominoes

text:
# Question
Title: Watch 'em fall like dominoes
You live inside a terminal that is 80 characters wide. You are bored, so you decide to play dominoes. No, not the boring kind that look like Scrabble, the fun kind where you spend an hour setting them to watch them fall in a second.

In terminals, dominoes look like this:

```
|   upright domino
\   left-tilted domino
/   right-tilted domino
__  fallen domino

```

As we all know, if a tilted domino touches an upright one, the second domino gets tilted as well. The only exception to this is if *two* tilted dominoes touch it:

```
|\ --> \\        /| --> //        /|\ --> /|\

```

Adjust your terminal's gravitational constant so this transition takes 100 ms.

If a tilted domino is supported by another domino or the terminal's walls, its journey ends.

None of the tilted dominoes in

```
\||||____||||/__                /|\    /\    /|\                __\||||____||||/

```

(80 characters) will move, since the two outmost tilted dominoes are supported by the terminal's walls and all others are supported by other dominoes.

However, if the space in the tilting direction is empty, the domino falls down:

```
| \\ --> |__\        // | --> /__|

```

Terminal. Gravitational constant. You get the point…

Finally, there's a slight wind from the left, so right-tilted dominoes fall faster than left-tilted ones:

```
|/ \| --> |__\|

```

### Task

Write a program/function that shows an animation of playing dominoes in a terminal.

Your code should do the following:

1. Read a string from input, representing the initial state of the dominoes.

This string will contain no more than 80 characters and consist solely of the dominoes described above and empty spaces.
2. Print the state and wait for 100 ms.
3. Transform the state as explained above.
4. If the state changed, go back to 2.

### Additional rules

* The length of the input string does not affect the terminal's width; even if the string is shorter than 80 characters, the walls of the terminal are still 80 characters apart.
* Each time step 2 is executed, the state should get printed to the same location, overwriting the previous state.
* Since some languages are incapable of waiting *exactly* 100 ms, feel free to wait any amount between 50 and 1000 ms.
* Standard rules apply.

### Examples

* For the initial state

```
 ||\/||

```

print the following (one over the other):

```
 ||\/||
 |\\//|
 \\\///
__\\//__

```
* For the initial state

```
/||||\

```

print the following

```
/||||\
//||\\
///\\\

```
* For the initial state

```
/|||\

```

print the following

```
/|||\
//|\\

```
* For the initial state

```
|/ \|/ \|/ \|/ \|

```

print the following:

```
|__\|__\|__\|__\|

```
* For the initial state (80 characters)

```
\||||____||||/__                /|\    /\    /|\                __\||||____||||/

```

print the following

```
\||||____||||/__                /|\    /\    /|\                __\||||____||||/

```

# Answer
# Retina, ~~87~~ ~~86~~ 85 bytes

*Thanks to Dennis for saving 1 byte.*

```
^.{0,79}$
$0
:`^
<ESC>c
(`/ | \\
__
/\|(?!\\)
//a
(?<!/)\|\\
\\
$
aaaaa
a
aaaa
(a+)+b|a
<empty>

```

`<ESC>` should be replaced by the actual control character (0x1B). `<empty>` represents an empty trailing line. You can then run the above code from a single file with the `-s` flag.

The code requires a terminal which supports ANSI escape codes. I can't suppress the line feed in Retina's output so I need to clear the entire console with `<ESC>c` each time. I've tested the code in bash using Mono to run Retina.

## Explanation

```
^.{0,79}$
$0

```

We start by appending a space if the input contains fewer than 80 characters. This is so that a `/` at the right end does not have to be treated separately.

```
:`^
<ESC>c

```

Now we prepend `<ESC>c` to the string, which is the ANSI escape code for clearing the terminal. So every time the string is printed it will do so at the top of the terminal. The `:`` instructs Retina to print out the result of this substitution, i.e. the initial configuration.

```
(`/ | \\
__

```

`(`` begins a loop. Since there is no matching `)`, the loop is assumed to go until the last stage of the program. Each iteration will simulate one step of the dominoes falling and then "sleep" a bit. This first stage replaces `/` and `\` next to a space into `__`. This automatically handles the `/ \` case correctly, because matches cannot overlap and are searched for from left to right. So the `/<sp>` would be matched and turned into `__` such that the `\` can't be matched, and we get the correct `__\`.

```
/\|(?!\\)
//a

```

This turns `/|` into `//` provided there's no `\` next to it. We append an `a` such that this new `/` doesn't mess with the next stage (which shouldn't "know" about this change yet).

```
(?<!/)\|\\
\\

```

The opposite situation: turn `|\` into `\\` provided there's no `/` next to it. We don't need to put an `a` here, because we're done with this step of the simulation.

Now the sleeping part...

```
$
aaaaa

```

Appends 5 more `a`s to the end of the code.

```
a
aaaa

```

Turns each `a` into 4 `a`s, so we get 20 `a`s at the end.

```
(a+)+b|a
<empty>

```

Now the fun part... we sleep for a bit with the help of catastrophic backtracking. There is an exponential amount of ways to split up a match of `(a+)+` between repetitions of the group. Because the `b` causes the match to fail, the engine will backtrack and try every single one of those combinations before deciding that `(a+)+b` can't match. For the twenty `a`s at the end that takes something like half a second.

At the same time, we allow the regex to match a single `a`, but only *after* doing the backtracking. When that matches, we replace it with an empty string, removing all the `a`s we inserted for one reason or another from the string.

That leaves printing the string at the end of the loop iteration. Here it comes in handy that I haven't fixed the printing behaviour of loops in Retina yet. Currently, there is only one flag for each stage, which says "print" or "don't print". The default is "don't print" except for the last stage in the program, which defaults to "print". But the stage is looped, so that means it actually prints the current string on each iteration. Normally, that is really annoying, and you almost always need to include an additional empty stage at the end if you only want the final result, but here it lets me save four bytes.
> 13 votes

# Answer
# Javascript (ES6), ~~206~~ ~~148~~ ~~129~~ 158 bytes

I'd finally gotten it down to a nicely low point, but it wouldn't clear the console or append an extra space; these problems have been fixed now.

```
c=console;d=s=>{c.clear(s[79]||(s+=' ')),c.log(s),t=s[R='replace'](/\/ | \\/g,'__')[R](/\/\|/g,'//a')[R](/\|\\/g,'\\\\')[R](/a/g,'');t!=s&&setTimeout(d,99,t)}

```

Alternate 153 byte version which should work in Node.JS:

```
d=s=>{s[79]||(s+=' '),console.log("\033c"+s),t=s[R='replace'](/\/ | \\/g,'__')[R](/\/\|/g,'//a')[R](/\|\\/g,'\\\\')[R](/a/g,'');t!=s&&setTimeout(d,99,t)}

```

IMHO, it's quite fun to play with. Try an HTML version here:

```
output=document.getElementById("output"),console.log=a=>output.innerHTML=a;
d=s=>{s[79]||(s+=' ');console.log(s),t=s[R='replace'](/\/ | \\/g,'__')[R](/\/\|/g,'//a')[R](/\|\\/g,'\\\\')[R](/a/g,'');t!=s&&setTimeout(d,99,t)}
s=n=>{n=n||15,r='';for(i=0;i<n;i++)r+=(i%2?'|'.repeat(Math.random()*16|0):'\\ /'[Math.random()*3|0].repeat(Math.random()*3+1|0));return r} // randomizer
input=document.getElementById("input");
input.addEventListener("keydown",e=>e.keyCode==13?(e.preventDefault(),d(input.value)):0);
```

```
<p>Enter your dominoes here:</p>
<textarea id="input" rows="1" cols="80">|||\ |||\ /|\ /||||||||\ /|||| /|||</textarea>
<button id="random" onclick="input.value=s()">Randomize</button><button id="run" onclick="d(input.value)">Run</button>
<p>Result:</p>
<pre id="output"></pre>
```

There's probably a good bit more room for golfing. Suggestions welcome!
> 6 votes

# Answer
# C#, 335 bytes

Not a great choice of language.

I abused the delay being allowed between 50 and 1000 to select a two-digit number.

New lines and indentation added for clarity:

```
namespace System.Threading{
    class P{
        static void Main(string[]z){
            var c=@"/|\,/|\,/|,//,|\,\\,/ ,__, \,__".Split(',');
            for(string a=z[0].PadRight(80),b="";a!=b;){
                Console.Clear();
                Console.Write(b=a);
                Thread.Sleep(99);
                a="";
                for(int i,j;(i=a.Length)<80;)
                    a+=(j=Array.FindIndex(c,d=>b.Substring(i).StartsWith(d)))%2==0
                        ?c[j+1]
                        :b.Substring(i,1);
            }
        }
    }
}

```
> 3 votes

# Answer
# Perl 5, ~~154~~ 146

Had to use a temporary character to maintain the state between 2 regexes.
To deal with the risk that something like / | | | \ would end up as / / / \ \ instead of / / | \ \ .

```
$_=substr(pop.' ',0,80);$|++;while($}ne$_){print"$_\r";$}=$_;s@ \\|/ @__@g;s@/\|(?=[^\\])@/F@g;s@([^/])\|\\@$1\\\\@g;tr@F@/@;select($\,$\,$\,0.1)}

```

### Test

```
$ perl dominos.pl '|\ |\/|||\/|'
|\__\//|\\/__

```
> 2 votes

# Answer
# ES6, 220 218 195 bytes

Minified

```
f=d=>{var e,c=console;if(!d[79])d+=' ';c.clear();c.log(d);e=d;d=d[R='replace'](/\/\|\\/g,'a')[R](/\/ | \\/g,'__')[R](/\/\|/g,'//')[R](/\|\\/g,'\\\\')[R]('a','/|\\');if(e!=d)setTimeout(f,100,d);};

```

More Readable

```
f=d=> {
    var e,
    c=console;
    if(!d[79])
        d+=' ';
    c.clear();
    c.log(d);
    e=d;
    d = d[R='replace'](/\/\|\\/g, 'a')  //Substitute '/|\' with 'a' so it doesn't get replaced
        [R](/\/ |  \\/g, '__')     //Replace '/ ' and ' \' with '__'
        [R](/\/\|/g, '//')    //Replace '/|' with '//'
        [R](/\|\\/g, '\\\\')  //Replace '|\' with '\\'
        [R]('a', '/|\\');     //Put '/|\' back
    if(e!=d)
        setTimeout(f,100,d);
};

```
> 2 votes

# Answer
# PHP, 175 bytes

```
$i=sprintf("%-80s",$argv[1]);$p='preg_replace';do{echo($o=$i)."\r";$i=$p('(/\|\\\\(*SKIP)(?!)|(?|(/)\||\|(\\\\)))','$1$1',$p('(/ | \\\\)','__',$i));usleep(1e5);}while($i!=$o);

```

Un-minified:

```
$input = sprintf("%-80s",$argv[1]);
do {
  echo $input."\r";
  $old = $input;
  $input = preg_replace('(/ | \\\\)','__',$input);
  $input = preg_replace('(/\|\\\\(*SKIP)(?!)|(?|(/)\||\|(\\\\)))','$1$1',$input);
  usleep(100000);
}
while( $input != $old);

```

Basically regex golf. First flattens any falling dominoes that have space (and due to left-to-right matching order, the "wind" blows). Then comes the ugly part (curse you slashes!)

* Match `/|\`, then skip it.
* Match `(/)|` and replace with `//`
* Match `|(\)` and replace with `\\`

This makes the dominoes fall. Finally, just wait 100ms for the next step.

Using `()` as delimiters on the regex means the `/`s don't need escaping, which helps minimally!
> 1 votes

# Answer
# POSIX shell+sed, 144

```
sed 's/^.\{1,79\}$/& /;s/.*/printf '"'&\\r'"';sleep .1/;h;:;s,/|\\,/:\\,g;s,\(/ \| \\\),__,g;s,/|,//,g;s,|\\,\\\\,g;H;t;x;y/:/|/;s/\\/\\\\/g'|sh

```

This is in two parts. The main work of toppling the dominoes is standard `sed` pattern replacement, accumulating lines into hold space. We temporarily turn `/|\` into `/:\` to protect it, recovering at the end.

```
s/^.\{0,79\}$/& /
h

:
s,/|\\,/:\\,g
s,\(/ \| \\\),__,g
s,/|,//,g
s,|\\,\\\\,g
H
t

x
y/:/|/

```

Since `sed` hasn't got any way of inserting delays (I looked into terminfo/termcap, but couldn't find any standard way), I wrap each line in `printf "...\r"; sleep .1` to print a line every 100ms. I actually do this first, when we have just one line, as the characters in the command won't be touched by any of the substitutions of toppling.

All tested using `dash` and GNU `coreutils`, with `POSIXLY_CORRECT` set in the environment.
> 1 votes

---
Tags: code-golf, ascii-art, animation, dominoes
---


title: Person of Interest

text:
# Question
Title: Person of Interest
# Background

*Person of Interest* is a crime drama on CBS, and my favorite TV show, as of late.

The show is about a man named Harold Finch, a billionaire programmer, and his partner John Reese, a special forces veteran and ex-CIA operative. This programmer created a sentient AI called "The Machine" that predicts violent crimes before they happen. It tracks every person on Earth at all times by monitoring and analyzing all surveillance cameras and electronic communications across the globe.

Harold built The Machine for the United States government to detect terrorist activity before-the-fact. It divides the crimes that it predicts into lists based on whether or not they are relevant to national security. The relevant cases are handled by the government, while the "irrelevant" list is programmed to be deleted daily.

Harold made a small backdoor for himself in hopes to deal with the "irrelevant" list, himself. This backdoor causes The Machine to call the payphone nearest Harold (once every day or so) and read a Social Security number to him. This SSN belongs to someone whose life is in danger as part of a premeditated crime, or of someone who is planning such a crime.

---

# The Challenge

Write a program that takes no input, and outputs 30 random phone numbers & SSNs (see below).

---

# Output

There are two lines of text that will be printed every "day".

1. `Crime predicted: 555-55-5555`
2. `Calling: 1-555-555-5555` followed by a newline

This process should repeat for one "month" (30 "days").

---

# Phone Numbers

Every phone number must have the following elements:

* Must have the United States country code (the first digit).
* Must have a random area code (first set of three digits).
* The first three digits of the phone number itself should be `555`, followed then by 4 random digits.

Here is an annotated example:

```
1-814-555-3857
|  |   |   |
|  |   |   |
|  |   |   +---------->   random four digits
|  |   |
|  |   +-------------->   the set 555
|  |
|  +------------------>   area code
|
+--------------------->   country code

```

---

# Social Security Numbers

Every SSN must be 9 random digits in the following format.

```
342-98-1613

```

---

# Example

```
Crime predicted: 234-72-8311
Calling: 1-633-555-0188

Crime predicted: 135-77-0910
Calling: 1-202-555-4719

Crime predicted: 722-90-6653
Calling: 1-466-555-1069

...

```

Continuing for 27 more cycles.

---

# Scoreboard

For your score to appear on the board, it should be in this format:

```
# Language, Bytes

```

Strikethroughs shouldn't cause a problem.

```
function getURL(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 getAnswers(){$.ajax({url:getURL(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){var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),useData(answers)}})}function getOwnerName(e){return e.owner.display_name}function useData(e){var s=[];e.forEach(function(e){var a=e.body.replace(/<s>.*<\/s>/,"").replace(/<strike>.*<\/strike>/,"");console.log(a),VALID_HEAD.test(a)&&s.push({user:getOwnerName(e),language:a.match(VALID_HEAD)[1],score:+a.match(VALID_HEAD)[2],link:e.share_link})}),s.sort(function(e,s){var a=e.score,r=s.score;return a-r}),s.forEach(function(e,s){var a=$("#score-template").html();a=a.replace("{{RANK}}",s+1+"").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SCORE}}",e.score),a=$(a),$("#scores").append(a)})}var QUESTION_ID=58199,ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",answers=[],answer_ids,answers_hash,answer_page=1;getAnswers();var VALID_HEAD=/<h\d>([^\n,]*)[, ]*(\d+).*<\/h\d>/;
```

```
body{text-align:left!important}table thead{font-weight:700}table td{padding:10px 0 0 30px}#scores-cont{padding:10px;width:600px}#scores tr td:first-of-type{padding-left:0}
```

```
<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="scores-cont"><h2>Scores</h2><table class="score-table"><thead> <tr><td></td><td>User</td><td>Language</td><td>Score</td></tr></thead> <tbody id="scores"></tbody></table></div><table style="display: none"> <tbody id="score-template"><tr><td>{{RANK}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SCORE}}</td></tr></tbody></table>
```

# Answer
# CJam, ~~68~~ ~~66~~ 64 bytes

Thanks to Dennis for saving 2 bytes!

```
"Crime predicted: --
Calling: 1--555-

"30*{_5<{iAa*:mr}&}/

```

Copypasting won't work since there are a few unprintables (one in place of each random group), so here's an `xxd` dump:

```
00000000: 2243 7269 6d65 2070 7265 6469 6374 6564  "Crime predicted
00000010: 3a20 032d 022d 040a 4361 6c6c 696e 673a  : .-.-..Calling:
00000020: 2031 2d03 2d35 3535 2d04 0a0a 2233 302a   1-.-555-..."30*
00000030: 7b5f 353c 7b69 4161 2a3a 6d72 7d26 7d2f  {_5<{iAa*:mr}&}/

```

To reverse it, paste it into a file and launch `xxd -r in_file > out_file`. You can also try it online.

# Explanation

```
"..."30*     Push the string 30 times
{ ... }/     For each character in the string:
_5<{ ... }&    If the ASCII code is < 5:
iAa*             Push an array of as many 10s as the ASCII code
:mr              For each 10, choose a random 0-9 number

```
> 10 votes

# Answer
## Python 2, 129

```
from random import*
print''.join([c,`randint(0,9)`][c>'w']for c in'Crime predicted: xxx-xx-xxxx\nCalling: 1-xxx-555-xxxx\n\n'*30)

```

A naive method. Takes the message

```
Crime predicted: xxx-xx-xxxx
Calling: 1-xxx-555-xxxx

```

and copies it 30 times. Then, replaces each `x` with a random digit `randint(0,9)`, keeping all other characters the same.
> 8 votes

# Answer
# Python 2, 151 bytes

Thank the lord (and @Dennis) for `%0nd` :D

```
from random import randrange as r
for i in[1]*30:print"Crime predicted: %03d-%02d-%04d\nCalling: 1-%03d-555-%04d\n"%(r(1e3),r(100),r(1e4),r(1e3),r(1e4))

```
> 6 votes

# Answer
# Perl, 85 Bytes, thanks to Dennis and grc!

```
$_="Crime Predicted: NNN-NN-NNNN
Calling: 1-NNN-555-NNNN

"x30;s/N/0|rand 10/eg;print

```

# Original Perl, 91 92 Bytes

```
print"Crime Predicted: NNN-NN-NNNN
Calling: 1-NNN-555-NNNN

"=~s/N/int rand 10/egr for 1..30

```
> 6 votes

# Answer
# CJam, ~~73~~ ~~71~~ 70 bytes

```
30{"Crime predicted: x-x-x
Calling: 1-x-555-x
"'x/[ZY4Z4]Aaf*::mr.+N}*

```

Try it online in the CJam interpreter.

### How it works

```
30{     e# Repeat 30 times:

e# Push the following string:

"Crime predicted: x-x-x
Calling: 1-x-555-x
"

'x/     e# Split at x's.
[ZY4Z4] e# Push the array [3 2 4 3 4].
Aaf*    e# For each integer in that array, repeat [10] that many times.
        e# This pushes [[10 10 10][10 10][10 10 10 10][10 10 10][10 10 10 10]].
::mr    e# For each 10, select a random integer between 0 and 9 (inclusive).
.+      e# Vectorized concatenation.
        e# This places the digits at the spots of the x's.
N       e# Push a linefeed.
}*      e#

```
> 5 votes

# Answer
# ß, ~~121~~ ~~118~~ 112 bytes

```
°/N=1°(30°/M°=ß$-ß$$'Crime predicted: 000-00-0000\nCalling: 1-000-555-0000\n\n'),'',3)µ€(M='0')?ß!G0,9,1):M)°)°)

```

Basically replaces 0 with a random number each and calls itself 30 times.

Test it using the online terminal:

```
sharps:~$ "<ctrl+v the code here>"
Crime predicted: 214-59-4707
Calling: 1-850-555-8529

Crime predicted: 722-97-6832
Calling: 1-864-555-6965

<and so on...>

```

Edit (112B): Using `$$` (something like sprintf) & ternary operator.
> 5 votes

# Answer
# Pyth, 66

```
V30sX"Crime Predicted: v-w-x
Calling: 1-y-555-z
">5GmjkmOTdj32434T

```

Uses `X` to translate the last 5 letters of the alphabet (`>5G == 'vwxyz'`) onto the 5 random numbers. Uses the same RNG as Sok found.

Try it online here
> 4 votes

# Answer
# Pyth, 62

An implementation of Andrea's fantastic CJam answer.

```
sm?<Cd5jkmOTCdd*30"Crime Predicted: --
Calling: 1--555-

"

```

Note that there are several unprintable characters in the source, and there should not be a trailing `"`. That was added for SE so that it seems a bit more readable. I have not been able to get a hexdump yet, but the link below works and you should be able to copy-paste out of it.

Try it online here
> 4 votes

# Answer
# CJam, 74 bytes

```
30{[ZY4Z4]{Aa*:mrs}%"Crime predicted: %s-%s-%s
Calling: 1-%s-555-%s

"e%}*

```

Not a winner, but it's at least somewhat close to what Dennis has so far, and it's using a different approach. So I thought it was worth posting anyway.

This uses the CJam `e%` operator, which generates output with a printf style format string.

```
30      Repeat count for whole output.
{       Start loop.
  [ZY4Z4] Build list of random number lengths: [3 2 4 3 4].
  {       Start loop over all random number lengths.
    Aa*     Build list of [10 ... ] with the random number length.
            E.g. for length 3, this will be [10 10 10].
    :mr     Apply the random number operator to the list. This will generate
            a list of random numbers between 0 and 9, with the given length.
    s       Convert it to a string.
  }%      End of loop over random number lengths.
  "..."   Format string, with a %s for each random number.
  e%      Apply printf style formatting.
}*      End of main repeat loop.

```
> 3 votes

# Answer
# JavaScript (ES6), 142

**Side note** mixmat answer in **ß** shows a so better way to accomplish this task, and could easily implemented in JS giving a better score. I wish I had thought about it.

**Edit** Added the missing text (I misread the challenge)

Test running the snippet below in an EcmaScript 6 compliant browser

```
/* TEST redirect console.log */ console.log=x=>O.innerHTML+=x+'\n'

for(i=30;i--;)console.log(`Crime predicted: ${(R=d=>(1e-9+Math.random()+'').substr(2,d))(3)}-${R(2)}-${R(4)}
Calling: 1-${R(3)}-555-${R(4)}
`)
```

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

# Answer
## Matlab / Octave, 108 ~~172~~ bytes

```
disp(sprintf('Crime predicted: %i%i%i-%i%i-%i%i%i%i\nCalling: 1-%i%i%i-555-%i%i%i%i\n\n',randi(10,1,480)-1))

```

Try it online
> 3 votes

# Answer
# Fourier, ~~166~~ 142 bytes

```
45~d030(~i67a114a-9a+4a-8a32a112a^^a101ava+5a-6a116a101ava58a32a999roda99roda9999ro10a67a97a108aa-3a+5a-7a58a32a1oda999roda5oooda9999ro10aai^)

```

This has one of the highest byte counts, but I am a huge fan of Fourier and wanted to try my hand at a solution. Not very optimized.

Breaking it down:

```
45~d

```

Sets the variable d to 45, the ASCII code for a hyphen. This character is printed so much that it saves some bytes to declare it here.

```
030(...)

```

Sets the accumulator to zero and loops inside the parentheses until it reaches 30.

```
67a114a-9a+4a-8a32a112a^^a101ava+5a-6a116a101ava58a32a

```

Print "Crime predicted: ".

```
999roda99roda9999ro10a

```

Print a completely random SSN + newline.

```
67a97a108aa-3a+5a-7a58a32a

```

Print "Calling: ".

```
1oda999roda5oooda9999ro

```

Print a phone number that follows the guidelines: 1-xxx-555-xxxx

```
10aa

```

Print two newlines to start over.
> 3 votes

# Answer
# Pyth, 67 bytes

```
V30s.ic"Crime predicted: |-|-|
Calling: 1-|-555-|
"\|mjkmOTdj32434T

```

The newlines are important, and are included in byte count. Try it out here.

```
                                Implicit: T=10, k=''
       "..."                    The output string
      c     \|                  Split on '|' placeholders
                     j32434T    32434 to base ten -> [3,2,4,3,4]
              m                 Map for d in the above:
                 mOTd             Generate d random numbers from 0-9
               jk                 Concatenate into string (join on empty string)
    .i                          Interleave segments of output string with random strings
   s                            Concatenate and output
V30                             Perform the above 30 times

```
> 2 votes

# Answer
# Haskell, 150 bytes

```
import System.Random
p '#'=putChar=<<randomRIO('0','9')
p x=putChar x
main=mapM p$[1..30]>>"Crime predicted: ###-##-####\nCalling: 1-###-555-####\n\n"

```
> 2 votes

# Answer
# R, ~~151~~ 146 or 144 Bytes

### Code

```
for(l in 1:30)cat(sep="","Crime predicted: ",(i=floor(runif(16,,10)))[1:3],"-",i[4:5],"-",i[6:9],"\nCalling: 1-",i[10:12],"-555-",i[13:16],"\n\n")

```

Test it online.

### Ungolfed

```
for(l in 1:30) {
  i=floor(runif(16,,10))
  cat(sep="","Crime predicted: ",
      i[1:3],"-",i[4:5],"-",i[6:9],
      "\nCalling: 1-",i[10:12],"-555-",
      i[13:16],"\n\n")
  }

```

I think there is a lot of room to improve but I am no good messing with strings in R.

Edit 1: changed the `runif(16,max=10)` to `runif(16,,10)`.

I've done another code (~~147~~ 144 bytes) with `sprintf` but I don't think it is much a R-like code.

```
for(l in 1:30)cat(do.call(sprintf,as.list(c('Crime predicted: %s%s%s-%s%s-%s%s%s%s\nCalling: 1-%s%s%s-555-%s%s%s%s\n\n',floor(runif(16,,10))))))

```

Another approach (149 bytes):

```
for(p in 1:30)cat(sep="",replace(s<-strsplit("Crime predicted: '''-''-''''\nCalling: 1-'''-555-''''\n\n","")[[1]],which(s<"-"),floor(runif(16,,10))))

```
> 2 votes

# Answer
# Java, 246 bytes

```
import java.util.*;class C{static{Random r=new Random();for(int i=0;i++<30;)System.out.printf("Crime predicted: %s-%s-%s\nCalling: 1-%s-555-%s\n\n",r.nextInt(900)+100,r.nextInt(90)+10,r.nextInt(900)+100,r.nextInt(900)+100,r.nextInt(9000)+1000);}}

```

With line breaks:

```
import java.util.*;
class C{
    static{
       Random r = new Random();
       for(int i = 0; i++<30;)
           System.out.printf("Crime predicted: %s-%s-%s\nCalling: 1-%s-555-%s\n\n",r.nextInt(900)+100,r.nextInt(90)+10,r.nextInt(900)+100,r.nextInt(900)+100,r.nextInt(9000)+1000);
    }
}

```

It's a start. Instead of producing random digits I used random 3-digit or 4-digit numbers.
> 2 votes

# Answer
# JavaScript (ES6), ~~130~~ 123 bytes

Taking minxomat's ß solution a step further, I've replaced the `0`s with the number of `0`s that would have been there. The code uses those numbers to pull the correct number of digits off of `Math.random()`, saving a good bit of bytes in the process.

```
for(i=30;i--;)console.log(`Crime predicted: 3-2-4
Calling: 1-3-555-4
`.replace(/[2-4]/g,x=>`${Math.random()}`.substr(2,x)))

```

Try it out:

```
// redirecting console.log() for this demonstration
console.log=x=>O.innerHTML+=x+'\n';
O.innerHTML='';

for(i=30;i--;)console.log(`Crime predicted: 3-2-4
Calling: 1-3-555-4
`.replace(/[2-4]/g,x=>`${Math.random()}`.substr(2,x)))
```

```
<pre id=O>
```

As always, suggestions welcome!
> 2 votes

# Answer
# PHP, 144 143 Bytes

```
<?=preg_replace_callback('/x/',function($x){return chr(rand(48,57));},str_repeat("Crime predicted: xxx-xx-xxxx
Calling: 1-xxx-555-xxxx

",30));

```
> 2 votes

# Answer
# GolfScript, 91 bytes

```
{9rand}+:r;{"Crime Predicted: "{r}3*"-"{r}2*"-"{r}4*"
Calling: 1-"{r}3*"-555-"{r}4*"

"}30*

```

Try it online.
> 2 votes

# Answer
## C#, 280 263 246 bytes

Golfed:

```
using System;class C{static string G(){var r=new Random();var s="";n h=x=>r.Next(x).ToString("D"+x);for(int i=0;i++<30;){s+="Crime predicted: "+h(3)+"-"+h(2)+"-"+h(4)+"\nCalling: 1-"+h(3)+"-555-"+h(4)+"\n\n";}return s;}delegate string n(int x);}

```

Indented:

```
using System;
class C
{
    static string G()
    {
        Random r = new Random();
        string s = "";
        Func<int, string> f = x => r.Next((int)Math.Pow(10, x)).ToString("D" + x);

        for (int i = 0; i++ < 30;)
        {
            s += "Crime predicted: " + f(3) + "-" + f(2) + "-" + f(4) + "\nCalling: 1-" + f(3) + "-555-" + f(4) + "\n\n";
        }
        return s;
    }
}

```

New on Codegolf, tips are welcome!
> 2 votes

# Answer
# Hassium, 230 Bytes

```
func main(){foreach(x in range(1,31){println("Crime predicted: "+r(3)+"-"+r(2)+"-"+r(4));println("Calling: 1-"+r(3)+"-555-"+r(4)+"\n");}}
func r(l){z=new Random();a="";foreach(y in range(1,l))a+=z.next(0,10).toString();return a;}

```

Expanded:

```
func main () {
        foreach (x in range(1, 31) {
                println("Crime predicted: " + r(3) + "-" + r(2) + "-" + r(4));
                println("Calling: 1-" + r(3) + "-555-" + r(4) + "\n");
        }
}
func r (l) {
        z = new Random();
        a = "";
        foreach (y in range(1, l))
                a += z.next(0, 10).toString();
        return a;
}

```
> 1 votes

# Answer
# PowerShell, ~~120~~ ~~108~~ ~~103~~ 102 Bytes

```
0..29|%{("Crime predicted: XXX-XX-XXXX`nCalling: 1-XXX-555-XXX"-split"X"|%{$_+(Random 10)})-join'';""}

```

~~Shortened a few more bytes by setting the split-loop to instead be a code block that outputs to an array `@(..)` and is re-joined.~~

Eliminated the `@` by remembering that `(...)` designates a code block executed before the `-join''` anyway.

This eliminates needing to assign the `$a` variable. Also noticed that due to how the `-split` functionality works, the previous code was spitting out too many digits for the phone number, so got a free byte saving there by shrinking to `1-XXX-555-XXX`. That made up for the erroneous `Random 9` that actually picks random from `0-8`, so we instead need to specify `Random 10.`

*Sooo* dang close to double-digits, but I'm not sure where it's possible to golf off another ~~four~~ 3 bytes ...

---

### Previous, 108

```
0..29|%{$a="";"Crime predicted: XXX-XX-XXXX`nCalling: 1-XXX-555-XXXX"-split"x"|%{$a+="$_$(Random 9)"};$a;""}

```

Shortened the code a couple bytes by instead splitting a string on `X`'s, then re-looping through the resultant array of strings and concatenating each entry with a `Random` digit to build our final output string `$a`. Note that we couldn't do something like `"string".replace("x",$(Random 9))` because then the `Random` would only get called once, so you'd have `1-222-555-2222` for a phone number, for example.

---

### Previous-er, 120

```
0..29|%{"Crime predicted: "+(Random 1e9).ToString("000-00-0000");"Calling: "+(Random 1e7).ToString("1-000-555-0000");""}

```

Pretty dang competitive for a verbose language, thanks to generous output specifications (i.e., `000-00-0001` is treated as a valid SSN) and the really robust `.ToString()` formatting algorithm that PowerShell uses. PowerShell also outputs `\r\n` after every string output, so the requirement for a newline in between iterations is just a simple `""`.

Note that this uses an implied `Get-` in front of `Random`, so this may be *really slow* on some platforms/implementations.
> 1 votes

# Answer
# Ruby, 98 characters

```
30.times{puts"Crime Predicted: DEF-GH-IJKL
Calling: 1-MNO-555-QRST

".tr"D-OQ-T",rand.to_s[2..-1]}

```

Sample run:

```
bash-4.3$ ruby -e '30.times{puts"Crime Predicted: DEF-GH-IJKL\nCalling: 1-MNO-555-QRST\n\n".tr"D-OQ-T",rand.to_s[2..-1]}' | head
Crime Predicted: 867-29-2637
Calling: 1-278-555-5424

Crime Predicted: 913-31-6306
Calling: 1-744-555-8188

Crime Predicted: 868-36-4612
Calling: 1-926-555-3576

Crime Predicted: 988-06-1643

```
> 1 votes

# Answer
# JavaScript, ~~146~~ 141

```
console.log(Array(30).join("Crime predicted: 3-2-3\nCalling: 1-3-555-4\n\n").replace(/[2-4]/g,function(m){return(m+Math.random()).substr(3,m)}))

```
> 1 votes

# Answer
## pre-ES6 Javascript, 128

```
for(i=30;i--;)console.log('Crime predicted: x-x-x\nCalling: x-555-x\n'.replace(/x/g, function(){return 1e3*Math.random()|0}))

```

I feel like the dashes could be removed somehow, but not sure.
> 1 votes

# Answer
## Pyth, 73 bytes

```
V30FGPc"Crime predicted: xxx-xx-xxxx\nCalling: 1-xxx-555-xxxx"\xpGpOT)pb"

```

Demo
> 1 votes

# Answer
# Ruby, ~~90~~ 88 bytes

```
30.times{puts"Crime predicted: NNN-NN-NNNN
Calling: 1-NNN-555-NNNN

".gsub(?N){rand 10}}

```

Try it online.
> 1 votes

# Answer
# Julia, 120 bytes

```
R(n)=lpad(rand(0:10^n-1),n,0)
for i=1:30 println("Crime Predicted: "R(3)"-"R(2)"-"R(4)"\nCalling: 1-"R(3)"-555-"R(4))end

```

Ungolfed:

```
# Define a function for returning a random number with a
# specified number of digits
function R(n::Int)
    lpad(rand(0:10^n-1), n, 0)
end

# Print 30 times
for i = 1:30
    println("Crime Predicted: " R(3) "-" R(2) "-" R(4)
            "\nCalling: 1-" R(3) "-555-" R(4))
end

```
> 1 votes

# Answer
# Befunge-98, 170

I think this can still be golfed down a bit. But at least I beat C#. Tested at befungius.aurlien.net.

```
a3*>  82*v>":detciderp emirC">:#,_$...'-,..'-,....av
>1 -:!#;_v^;v,,,"-555-"...,,,,,,,,,,,"Calling: 1-",<
\  ^v< <2?1v,
+    ^;^3<;<,
^ <0?3vv....<
^;^6<;<>a,v
   v_@#:-1<

```
> 0 votes

# Answer
# Python 2, ~~151~~ 150 bytes

```
from random import*
p="Crime predicted: xxx-xx-xxxx\nCalling: 1-xxx-555-xxxx\n\n"*30
while'x'in p:p=p.replace('x',str(randint(0,9)),1)
print p.strip()

```

As golfed as I could get this method.
> 0 votes

---
Tags: code-golf, random
---


title: Generate a Monotonic Function

text:
# Question
Title: Generate a Monotonic Function
# Overview

In this challenge, your task is to randomly generate a monotonic mathematical function between two sets.

# Input

Your inputs are two positive integers `s` and `n`.

After getting these inputs, your program shall generate a random mathematical function `f` from the set `{0,1,...,s-1}<sup>n</sup>` to `{0,1,...,s-1}`. In other words, `f` is a "rule" that takes in an `n`-tuple of integers between `0` and `s-1`, and returns one such integer. Additionally, `f` should be *monotonic* in the following sense. If `A` and `B` are two `n`-tuples such that `A[i] ≥ B[i]` holds for every coordinate `i`, then `f(A) ≥ f(B)`.

The exact distribution of the monotonic functions `f` doesn't matter, as long as each such function has a positive probability of being generated (assuming a perfect RNG).

# Output

Your output shall be an enumeration of the inputs and outputs of `f`. It shall contain all `n`-tuples of integers between `0` and `s-1` in some order, each one being followed by the corresponding output of `f`. The exact output format is flexible (within reason).

# Examples

The inputs `s = 3` and `n = 2` might produce the output

```
(0, 0) 0
(0, 1) 1
(0, 2) 2
(1, 0) 0
(1, 1) 1
(1, 2) 2
(2, 0) 1
(2, 1) 1
(2, 2) 2

```

It contains all the pairs over the set `{0, 1, 2}` exactly once, and each one is followed by its `f`-value. The monotonicity condition is also satisfied. The tuples are given here in lexicographical order, but this is not necessary.

As another example, `s = 2` and `n = 4` might produce

```
(0, 0, 0, 0) 0
(0, 0, 0, 1) 0
(0, 0, 1, 0) 0
(0, 0, 1, 1) 0
(0, 1, 0, 0) 1
(0, 1, 0, 1) 1
(0, 1, 1, 0) 1
(0, 1, 1, 1) 1
(1, 0, 0, 0) 0
(1, 0, 0, 1) 1
(1, 0, 1, 0) 0
(1, 0, 1, 1) 1
(1, 1, 0, 0) 1
(1, 1, 0, 1) 1
(1, 1, 1, 0) 1
(1, 1, 1, 1) 1

```

The following are all possible outputs for `s = 2` and `n = 2` (up to reordering the tuples); your program should randomly output one of them:

```
(0,0) 0
(0,1) 0
(1,0) 0
(1,1) 0
-------
(0,0) 0
(0,1) 0
(1,0) 0
(1,1) 1
-------
(0,0) 0
(0,1) 0
(1,0) 1
(1,1) 1
-------
(0,0) 0
(0,1) 1
(1,0) 0
(1,1) 1
-------
(0,0) 0
(0,1) 1
(1,0) 1
(1,1) 1
-------
(0,0) 1
(0,1) 1
(1,0) 1
(1,1) 1

```

# Rules and Scoring

You can write a full program or a function. The lowest byte count wins, and standard loopholes are disallowed. Code with explanation is preferred.

There are no restrictions on time complexity, but I'll give a **bonus of -15 %** if your solution is always guaranteed to finish in a certain amount of time (depending on the inputs, and assuming a perfect RNG that runs in constant time).

# Answer
# Pyth, 35 bytes (38 - 15% = 31.45 farther down)

```
#I!sm><FhMds<MCeMd^JC,mOQK^UQvzK2JB

```

Demonstration

Input is in the format:

```
n
s

```

Output is in the format:

```
[[value, tuple], [value, tuple], ...]

```

Simply generates random possibilities and tests them.

---

Alternative 37 byte version which I believe qualifies for the bonus:

```
Of!sm><FhMds<MCeMd^T2mC,d^UQvz^UQ^Qvz

```

Demonstration

This starts by generating all possible monotonic functions, then outputs one at random. It is much slower, and tops out at `2,2`.
> 4 votes

# Answer
# CJam, 40 bytes - 15% = 34 bytes

```
q~1$\m*\1$,m*{W$\.+2m*{:.<2b}%1&!},mR]zp

```

This approach generates all valid functions and then selects on at random. Run time is at least **O(s2sn)**, but constant for a given input.

I doubt this is what the OP had in mind, but it is *guaranteed to finish in a certain amount of time (depending on the inputs\[...\])* and therefore qualifies for the bonus.

Try it online in the CJam interpreter.
> 1 votes

# Answer
# Julia, 64 bytes (-15% = 54.4)

```
g(s,n)=(K=rand(0:s-1,ntuple(n,i->s));for i=1:n K=sort(K,i)end;K)

```

Ungolfed:

```
function g(s,n)
  # Generates a random n-dimensional array with s per dimension
  # and all values being integers between 0 and s-1
  K=rand(0:s-1,ntuple(n,i->s))
  # Loop over the various dimensions
  for i=1:n
    # Sort in the current dimension
    K=sort(K,i)
  end
  return K
end

```

This will run quickly, with the only possible issue being with memory for large enough s and n (g(10,10) has to produce a 10^10 array, so obviously it's going to run out of memory - even if each number is one byte, that's 10 gigabytes of data).

Output is 1-based indexing, so to determine the result for a given input, you need to add one to each input value. For example, to find f(1,2,6,0,3), you need to examine `K[2,3,7,1,4]`.
> 1 votes

---
Tags: code-golf, random, generation
---