title: Mutually fill in the blanks

text:
# Question
Title: Mutually fill in the blanks
Given an input of two strings with sequences of underscores representing corresponding words, output the sentences with the "blanks" filled in.

The best way to describe this challenge is by example. Here is an example input:

```
programming _____________ and code golf
programming puzzles ______ code ____

```

And here is the corresponding output:

```
programming ___puzzles___ and code golf
programming puzzles _and__ code golf

```

For the purposes of this challenge, a "word" is defined as a sequence of one or more lowercase letters, and a "blank" is defined as one or more underscores (the input will always contain only lowercase letters, spaces, and underscores). *Words* and *blanks* in the input strings are separated by single spaces, and the sum of the number of *words* and *blanks* in the sentences will always be equal.

The objective of the challenge is to fill all of the *blanks* with the correct *words*, which are the words that occupy the same index in the other string when split by spaces.

* The word must be centered in the blank, as shown with the word "puzzles" in the example above—an equal number of underscores remain on either side.
* If the word cannot be exactly centered, the extra underscore may go either on the left or the right (ex. the word "and" in the example above).
* There will always be enough underscores for the word to fit, but there may be exactly as many as the length of the word (ex. the word "golf" in the example above).
* There will never be a blank in the same position in both strings.

Input/output may be any of the following (input/output do not necessarily have to be via the same method):

* single string separated by any character that is not alphabetic, a space, or an underscore (ex. newline or comma separated string)
* an array/list/etc. of two strings
* two function/command line arguments (input only)

Since this is , the shortest code in bytes will win.

The example above can be used as a test case. Here is a larger test case (second string in output may vary slightly due to different centering behavior):

```
lorem _____ dolor _____ amet _______________ adipiscing elit mauris dapibus tincidunt _____________________________ accumsan fringilla proin vulputate viverra lorem fermentum dictum
lorem ipsum ______ sit _______ consectetur _______________ elit mauris dapibus tincidunt metus accumsan fringilla proin vulputate viverra lorem ____________________________ dictum

lorem ipsum dolor _sit_ amet __consectetur__ adipiscing elit mauris dapibus tincidunt ____________metus____________ accumsan fringilla proin vulputate viverra lorem fermentum dictum
lorem ipsum dolor_ sit _amet__ consectetur __adipiscing___ elit mauris dapibus tincidunt metus accumsan fringilla proin vulputate viverra lorem _________fermentum__________ dictum

```

# Answer
# Pyth, 30

```
jL;Cmm|*}J\_k.[lkhx#JdJkdCcR;Q

```

Takes input and outputs as a list of two strings. Uses a pretty basic split–zip–double map–centre–zip–join approach.

Try it here

### Expanded:

```
jL;Cmm|*}J\_k.[lkhx#JdJkdCcR;Q   ##
                          cR;Q   ##  split
                         C       ##  zip
    mm                           ##  double map
      |*}J\_k.[lkhx#JdJkd        ##  centre
   C                             ##  zip
jL;                              ##  join

```

I'll explain more once I'm really satisfied that I can't golf this any more, although it should be pretty clear, given the ubiquity of the split–zip–double map–centre–zip–join approach and all.
> 5 votes

# Answer
## Retina, ~~102~~ ~~100~~ ~~93~~ 88 bytes

Byte count assumes ISO 8859-1 encoding.

```
$
!¶$`
m`(?<=^(\w+ )*)(?=_.*¶(?<-1>\w+ )*(\w+))
$2
(([a-z])+)(?<-2>_)*(_*)\3|!\D+
$3$1$3

```

The strings will are separated by a linefeed. If there is an odd number of underscores left, the extraneous one will be after the word.

Try it online!

### Explanation

I guess this is the "duplicate-append-lookback-match-add-centre approach", or something close...

```
$
!¶$`

```

We start by duplicating the input (separated with a `!` and a linefeed). The purpose of this is that we can then process both lines by fetching words from the *next* line (instead of having to treat the second line separately).

```
m`(?<=^(\w+ )*)(?=_.*¶(?<-1>\w+ )*(\w+))
$2

```

This prepends the correct word to each gap. We start by counting the current word position with the lookbehind `(?<=^(\w+ )*)` (the position is stored as the depth of group `1`). Then the lookahead a) ensures that we're at the beginning of a gap by matching `_`, then skips to the next line with `.*¶`, matches the correct number of words with `(?<-1>\w+ )*` to get to the right position, and then matches the word found there with `(\w+)` into group `2`.

```
(([a-z])+)(?<-2>_)*(_*)\3|!\D+
$3$1$3

```

This stage does three things:

* It removes the underscores corresponding to each word length. This is done by counting the word length into group `2` with `([a-z])+` and then matching that many underscores (which are never written back).
* It shifts the word to the centre of the gap by capturing half of the remaining underscores with `(_*)\3` and writing `$3$1$3` back.
* It removes the duplicated input by matching `!\D+` and replacing it with nothing.
> 7 votes

# Answer
## Python 2, 109

```
def f(a,b):exec"print' '.join([x,y][x<'`'].center(len(x),'_')for x,y in zip(a.split(),b.split()));a,b=b,a;"*2

```

The function takes two strings as arguments and prints the output as in the examples. It uses a boring approach, with `str.center(width, fillchar)` doing most of the work.

Try it online.
> 4 votes

# Answer
# Ruby, ~~111~~ 109 characters

```
->l{l.map(&:split).transpose.map{|c|c[m=c[0]<c[1]?0:1]=c[1-m].center c[m].size,?_
c}.transpose.map{|s|s*' '}}

```

Input: array of 2 strings; output: array of 2 strings.

Sample run:

```
2.1.5 :001 > puts ->l{l.map(&:split).transpose.map{|c|c[m=c[0]<c[1]?0:1]=c[1-m].center c[m].size,?_;c}.transpose.map{|s|s*' '}}[[
2.1.5 :002 >       'programming _____________ and code golf',
2.1.5 :003 >       'programming puzzles ______ code ____',
2.1.5 :004 >       ]]
programming ___puzzles___ and code golf
programming puzzles _and__ code golf

```
> 2 votes

# Answer
# JavaScript, ~~194~~ 185 bytes

```
f=(m,n)=>(m=m.split` `,n=n.split` `,G=(x,i,a)=>x[0]!='_'?x:(b=(a?n:m)[i],s=x.length-b.length,(k='_'.repeat(s/2))+b+k+(s%2?'_':'')),H=(e,y)=>e.map((x,i)=>G(x,i,y)).join` `,[H(m,1),H(n)])

```

Takes two strings as parameters and outputs two strings as array/list

```
f=(m,n)=>(
    m=m.split` `,
    n=n.split` `,
    G=(x,i,a)=>
        x[0]!='_'?x:
        (
            b=(a?n:m)[i],
            s=x.length-b.length,
            (k='_'.repeat(s/2))+b+k+(s%2?'_':'')
        ),
    H=(e,y)=>e.map((x,i)=>G(x,i,y)).join` `,
    [H(m,1),H(n)]
)

document.body.innerHTML = '<pre>' +
    "f('lorem _____ dolor _____ amet _______________ adipiscing elit mauris dapibus tincidunt _____________________________ accumsan fringilla proin vulputate viverra lorem fermentum dictum', 'lorem ipsum ______ sit _______ consectetur _______________ elit mauris dapibus tincidunt metus accumsan fringilla proin vulputate viverra lorem ____________________________ dictum')<br>" +
    f('lorem _____ dolor _____ amet _______________ adipiscing elit mauris dapibus tincidunt _____________________________ accumsan fringilla proin vulputate viverra lorem fermentum dictum', 'lorem ipsum ______ sit _______ consectetur _______________ elit mauris dapibus tincidunt metus accumsan fringilla proin vulputate viverra lorem ____________________________ dictum') + "<br><br>" +
    "f('programming _____________ and code golf', 'programming puzzles ______ code ____')<br>" +
    f('programming _____________ and code golf', 'programming puzzles ______ code ____')
'</pre>'
```
> 1 votes

# Answer
# Mathematica 223

There must be a shorter way to do this.

```
k=StringLength;m=StringSplit;
g=Partition[Riffle[m@#,m@#2],2]/.{{a_,a_}:> a<>" ",{a_,b_/; StringTake[b,1]=="_"}:> a<>" ",
{a_,b_}:>Table["_",Ceiling[z=(k@a-k@b)/2]]<>b<>""<>Table["_",Floor@z]<>" "}&;
s_~h~t_:={""<>g[s,t],""<>g[t,s]}

```

---

**Sample run**

```
h["programming _____________ and code golf", "programming puzzles ______ code ____"]

```
> 1 votes

# Answer
# Gema, ~~208~~ 203 characters

```
\B=@set{i;0}
<I>=@push{${v;f};$0}@incr{i}
\n=@set{v;s}@set{i;0}
 =
\E=@repeat{$i;@cmps{$f;$s;@set{f;@fill-center{$f;$s}};;@set{s;@fill-center{$s;$f}}}@set{F;$f ${F;}}@set{S;$s ${S;}}@pop{f}@pop{s}}$F\n$S

```

Just because Gema has the perfect function for this task: `@fill-center{*background*;*value*}`.

Input: 2 newline separated lines (no final newline); output: 2 newline separated lines (with trailing spaces – not seem to be forbidden).

Sample run:

```
bash-4.3$ echo -ne 'programming _____________ and code golf\nprogramming puzzles ______ code ____' |
> gema '\B=@set{i;0};<I>=@push{${v;f};$0}@incr{i};\n=@set{v;s}@set{i;0}; =;\E=@repeat{$i;@cmps{$f;$s;@set{f;@fill-center{$f;$s}};;@set{s;@fill-center{$s;$f}}}@set{F;$f ${F;}}@set{S;$s ${S;}}@pop{f}@pop{s}}$F\n$S'
programming ___puzzles___ and code golf
programming puzzles _and__ code golf

```
> 0 votes

# Answer
# C, 197 bytes

```
#define c(w,y)l=strspn(w,"_"),r=strcspn(y," "),memcpy(w+(l-r)/2,y,r),w+=l,y+=r;
main(l,v,w,y,r)char**v,*w,*y;{for(w=v[1],y=v[2];*w;w++,y++)if(*w^*y)if(*w^95)c(y,w)else c(w,y)puts(v[1]);puts(v[2]);}

```

## Output

```
$ ./a.out "lorem _____ dolor _____ amet _______________ adipiscing elit mauris dapibus tincidunt _____________________________ accumsan fringilla proin vulputate viverra lorem fermentum dictum" "lorem ipsum ______ sit _______ consectetur _______________ elit mauris dapibus tincidunt metus accumsan fringilla proin vulputate viverra lorem ____________________________ dictum"
lorem ipsum dolor _sit_ amet __consectetur__ adipiscing elit mauris dapibus tincidunt ____________metus____________ accumsan fringilla proin vulputate viverra lorem fermentum dictum
lorem ipsum dolor_ sit _amet__ consectetur __adipiscing___ elit mauris dapibus tincidunt metus accumsan fringilla proin vulputate viverra lorem _________fermentum__________ dictum

```
> 0 votes

# Answer
## ES6, 122 bytes

```
a=>a.map(s=>s.split` `).map((s,n,a)=>s.map((w,i)=>w<'a'?(l=w.length,t=w+a[n^1][i]+w,t.substr(t.length-l>>1,l)):w).join` `)

```

Takes an array of two strings as a single parameter and returns another array of two strings.
> 0 votes

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


# Question
Title: Shortest code to post a string to WebServer
In , this code posts `String to post` to `http://www.example.com/target`:

```
curl -d "String to post" "http://www.example.com/target"

```

**NOTE:** You should use **`http://www.example.com/target`** as the URL to `POST` to, without any change.

I think all other languages that I have knowledge in need a lot more code than this. I'm not blaming other languages. Let's see the interesting answers that reduce the effort.

Your task is to write the shortest code possible to send a **`POST`** request to a sample server, **`http://www.example.com/target`**, and the request data should be the string **`String to post`**.

# Answer
# Bash: 90 characters

No external tools, just pure `bash`.

```
echo 'POST /target HTTP/1.0
Content-length:14

String to post'>/dev/tcp/www.example.com/80

```
> 16 votes

# Answer
# Rebol (51 chars)

```
write http://www.example.com/target"String to post"

```

Above works in Rebol 3. Below is a Rebol 2 version (63 chars):

```
read/custom http://www.example.com/target[post"String to post"]

```
> 9 votes

# Answer
# Javascript, 84

```
with(XMLHttpRequest())open('POST','//www.example.com/target'),send('String to post')

```

Try in the console of any page served over plain HTTP.
> 5 votes

# Answer
# Powershell v3 - 58

```
iwr http://www.example.com/target -b "String to post"-me 3

```
> 5 votes

# Answer
## Lua (texlua), 73 bytes

```
require("socket.http").request("www.example.com/target","String to post")

```
> 3 votes

# Answer
# Smalltalk (Smalltalk/X), 64 71

```
HTTPInterface post:'http://www.example.com/target'with:'String to post'

```
> 3 votes

# Answer
### newLISP - 58 characters

```
(post-url "http://www.example.com/target""String to post")

```
> 3 votes

# Answer
## PHP - 100 bytes

```
<?fwrite(fsockopen('www.example.com',80),'POST /target HTTP/1.0
Content-length:14

String to post');

```

I apologize for any similarities to manatwork's bash solution, but I believe that this is the shortest way to do it.
> 3 votes

# Answer
# Bash - 63 chars

```
wget --post-data="String to post" http://www.example.com/target

```
> 3 votes

# Answer
# Tcl - 85 chars

```
package require http
http::geturl "//www.example.com/target" -query "String to post"

```
> 3 votes

# Answer
# VBScript: 114 characters

```
dim x:set x=createobject("MSXML2.ServerXMLHTTP")
x.open"post","http://example.com/target"
x.send"String to post"

```
> 2 votes

# Answer
## Game Maker Language (GMStudio), 66

```
http_post_string("http://www.example.com/target","String to post")

```
> 2 votes

# Answer
# Python 2: 80 chars

Just using the standard library:

```
import urllib2 as u
u.urlopen("http://www.example.com/target","String to post")

```

For an extra char, you can make the import less unusual.

```
import urllib2
urllib2.urlopen("http://www.example.com/target","String to post")

```
> 2 votes

# Answer
# jQuery, 58

`$.post("http://www.example.com/target", "String to post");`
> 2 votes

# Answer
# , 47 chars / 51 bytes (noncompetitive)

```
ɟŏ`//www.example.com/target⍪String to post

```

`Try it here (Firefox only).`

Uses jQuery's `post` function.
> 2 votes

# Answer
# PHP, 198 bytes

This is shamefully large...:

```
<?fopen('http://www.example.com/target','rb',0,stream_context_create(array('http'=>array('method'=>'POST','header'=>'Content-Type: application/x-www-form-urlencoded','content'=>'String to post'))));

```

At least I answered!
> 1 votes

# Answer
# Bash, 69 bytes

```
lwp-request -m POST -b http://www.example.com/target "String to post"

```

You can read about the `lwp-request` command here: http://linux.about.com/library/cmd/blcmdl1\_POST.htm

I think that the answer given by @manatwork is a much more neat and compatible version.
> 1 votes

# Answer
## Actionscript 3, 201

```
var aRV:URLVariables = new URLVariables();
aRV.STRING = "my string";
var aR:URLRequest = new URLRequest("http://www.example.com/target");
aR.method = URLRequestMethod.POST;
aR.data = aRV;
var aL = new URLLoader();
aL.load(aR);

```

no error handling
> 1 votes

# Answer
# Batch/Powershell - 118 Chars

If you need to post from a Windows batch file or avoid changing ExecutionPolicy:

```
powershell -Command "(New-Object Net.WebClient).UploadString('http://www.example.com/target', 'p1=String%20to%20Post')"

```
> 1 votes

---
Tags: code-golf, internet
---


title: Clock (card game)

text:
# Question
Title: Clock (card game)
Clock is an interesting card game, as it requires no skill. It is a single player game, and the same card configuration always leads to a win or a loss. In this challenge, **you need to figure out whether a given card configuration wins or loses**. You can play the game here.

The game is played as follows:

1. Thirteen piles of cards are dealt face down. Each pile is numbered from 0 to 12.
2. We set the 0th pile to be the *current pile*
3. We flip the top card of the current pile face up.
4. We move the face up card at the bottom of its respective pile *(A 4 card goes under the 4th pile)*. The card remains face up. This pile becomes the current pile.
5. If the current pile is completely face up, then the game is over. Otherwise, go back to step 3.

*Tip: The game will always end on the 0th pile*

The game is won if all cards end up face up, and is lost if there are remaining face down cards.

# Input/Output

A 2D array containing each of the piles. Cards are represented with numbers from 0 to 12 (suit is irrelevant, and not given). The top card of each pile is the first element of each array.

You can assume that the input will be well formed: it will contain 52 cards from 0 to 12 (inclusive), and contain each number exactly 4 times.

You must return a truthy value if the game can be won, and falsy if it cannot.

# Test cases

Truthy:

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

```

Falsy:

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

```

# Answer
> 9 votes
## ES6, 57 bytes

```
a=>(g=n=>a.map((x,i)=>i&&x[3]==n&&++c&&g(i)),g(c=0),c>11)

```

This works because only the cards on the bottom of piles 1-12 are relevant, and they need to form a directed graph back to pile 0. So, I count the number of piles whose bottom card is 0, then the number of piles whose bottom card was one of the piles I counted earlier, etc. If I reach 12 piles then the configuration is a winning one.

Outline proof:

The game always ends when you turn over the last 0, since that pile effectively has one fewer card than the others.

If the bottom cards on piles 1-12 form a directed graph to pile 0, then in order to clear pile 0, we have to clear all the piles whose last entry is 0, and so on recursively to all the piles we have to clear so that we can clear the piles whose last entry is 0, and so forth. The configuration is therefore a winning one.

If the cards on the bottom of piles 1-12 do not form a directed graph to pile 0, there must exist at least one cycle. No pile in this cycle can be cleared, since it depends on the previous pile in the cycle. (In the case of a cycle of length 2, this is a chicken-and-egg situation.) The configuration is therefore a losing one.

# Answer
> 7 votes
## CJam, ~~23~~ 21 bytes

```
q~({(\a@+1$ff-m<(}h*!

```

Run all test cases.

If the assignment of truthy and falsy was the opposite I could save 3 bytes:

```
q~{((\a@+1$ff-m<}h

```

### Explanation

> Putting the cards face up under another pile is a red herring. We might as well remove them from the game and keep playing until the current pile is empty. So that's what I'm doing: the code simply plays the game until the current pile is empty and then checks if any cards are left.

```
q~    e# Read and evaluate input.
(     e# Pull off the first (current) pile.
{     e# While the current pile is non-empty...
  (\  e#   Pull off the top card and swap with the remaining pile.
  a   e#   Wrap the pile in an array.
  @+  e#   Prepend it to the list of piles
  1$  e#   Copy the drawn card.
  ff- e#   Subtract it from all all remaining cards.
  m<  e#   Rotate the stack to the left by the drawn card
  (   e#   Pull off the top pile as the new current pile.
}h
*     e# The top pile is empty. Joining the other piles with it, flattens them.
!     e# Logical not, turns an empty array into 1 and a non-empty array into 0.

```

# Answer
> 4 votes
# Haskell, 85 bytes

```
(a:b)?n|n<1=tail a:b|1>0=a:b?(n-1)
l%i|null(l!!i)=all null l|1>0=l?i%(l!!i!!0)
f=(%0)

```

# Answer
> 4 votes
## Pyth, 13 bytes

```
!su@LGGXeMQZZ

```

Relies on @Neil's proof. `!su&VG@LGGeMQ` also works.

```
                 implicit: Q=input
! s u            Sum of (apply lambda G,H on ... until fixed point) equals 0
      @L         Index G into itself.
         G
         G
                  Apply that to:
      X                                            set to
        eM Q      Last elts of input, with the
        Z                                      0th
        Z                                                 0

```

Try it here.

# Answer
> 1 votes
**Python, 55 bytes**

```
x=lambda l,i=0:x(l,l[i].pop(0))if l[i]else[]==sum(l,[])

```

If the sublist is not empty, continue poping items. When it's empty, Return either all the lists are empty (by grouping them into one big list) or not.

# Answer
> 0 votes
## Jelly, 11 bytes

```
‘ịa
Ṫ€ÇL¡S¬

```

Try it here.

---
Tags: code-golf, decision-problem, card-games
---


title: Writing code for three tasks

text:
# Question
Title: Writing code for three tasks
When you run your program first, it should print an integer sequence. The second run should print the 'Mary had a little lamb' song. The third run should produce an ASCII image file.

## Scoring

Your score will be the sum of your bytes of code and any file content at the start of each of the 3 runs. Lowest score wins.

For example, `myprog` is 1500 bytes and does not change its size, but writes a 4 bytes file each run so it knows what to do on the next run. The score would be 1500 + (1500+4) + (1500+4) = 4508.

## Output

The first output is this sequence of 133 integers, separated by single spaces:

```
0 89 98 179 188 197 269 278 287 296 359 368 377 386 395 449 458 467 476 485
494 539 548 557 566 575 584 593 629 638 647 656 665 674 683 692 719 728
737 746 755 764 773 782 791 809 818 827 836 845 854 863 872 881 890 908
917 926 935 944 953 962 971 980 1079 1088 1097 1169 1178 1187 1196 1259
1268 1277 1286 1295 1349 1358 1367 1376 1385 1394 1439 1448 1457 1466 1475
1484 1493 1529 1538 1547 1556 1565 1574 1583 1592 1619 1628 1637 1646 1655
1664 1673 1682 1691 1709 1718 1727 1736 1745 1754 1763 1772 1781 1790 1808
1817 1826 1835 1844 1853 1862 1871 1880 1907 1916 1925 1934 1943 1952 1961
1970

```

The second output is this text exactly (including capitals, punctuation, and white space - the inconsistent punctuation is intentional):

```
Mary had a little lamb,
Little lamb, little lamb,
Mary had a little lamb,
Its fleece was white as snow

And everywhere that Mary went,
Mary went, Mary went,
Everywhere that Mary went
The lamb was sure to go

It followed her to school one day
School one day, school one day
It followed her to school one day
Which was against the rules.

It made the children laugh and play,
Laugh and play, laugh and play,
It made the children laugh and play
To see a lamb at school

```

The third output is this image in PPM ASCII(P3) format left in a file called `blue.ppm`. This is the image in PNG format:

The PPM file should look something like this:

```
P3 50 50 255
255 255 255 255 255 255 255 255 255 255 255 255 ...
...
255 255 255

```

There is a copy of the full PPM file here.

## Example run (on Linux)

```
# ls
myprog
# interpreter myprog
0 89 98 179 188 197 269 278 287 296 359 ...
# interpreter myprog
Mary had a little lamb,
Little ...
# interpreter myprog
# ls
blue.ppm
myprog
# cat blue.ppm
P3 50 50 255
255 255 255 255 255 ...

```

## Rules

* Your code may modify itself.
* Running the program a fourth time is undefined behaviour.
* You may write to a file in the current directory, but the size of this file will add to your score at the start of each run. The final PPM file is excluded from this.
* The first two outputs are to stdout (or similar). The last output is written to a file, with nothing sent to stdout.
* The first two outputs may optionally have a trailing white space character (e.g. space or line feed).
* You may not use compression or image libraries. You may use your own compression or image functions but this code must be included in your program.
* The standard loopholes are prohibited.

# Answer
> 9 votes
# Python (897 + 814 + 386 = 2097)

Simple self-modifying answer. I'll have to refine the second run later.

```
def p(x):print x,
map(p,[0]+filter(lambda x:sum(map(int,`x`))==17,range(1971)))
#l="ittle lamb,";M="Mary ";w=M+"went";e="verywhere that "+w;s="chool one day";I="It followed her to s"+s+"\n";j="augh and play";i="It made the children l"+j;print M+"had a l"+l+"\nL"+l+" l"+l+"\n"+M+"had a l"+l+"\nIts fleece was white as snow\n\n"+"And e"+e+",\n"+w+", "+w+",\nE"+e+"\nThe lamb was sure to go\n\n"+I+"S"+s+", s"+s+"\n"+I+"Which was against the rules.\n\n"+i+",\nL"+j+", l"+j+",\n"+i+"\nTo see a lamb at school"
#print>>file("blue.ppm","w"),"P3 50 50 255"+' '.join(" %i"%(255-255*any(a<y<b and x==c or y==d and e<x<f for a,b,c,d,e,f in[(2,48,2,47,2,37),(9,48,36,9,27,37),(9,41,28,40,9,29),(0,41,10,1,9,49),(0,37,48,36,14,49),(2,37,15,3,2,16)]))*2+" 255"for x in range(50)for y in range(50))
import sys;x=file(sys.argv[0],"r+");y='#'.join(x.read().split('#')[1:]);x.seek(0);x.truncate();x.write(y)

```

Additionally, if run for the fourth time, it safely degrades to a NOP:

```
'.join(x.read().split('#')[1:]);x.seek(0);x.truncate();x.write(y)

```

# Answer
> 11 votes
# Ruby, ~~1356~~ 1268 * 3 = 3804 bytes

```
if File.file?(?b)
s='P3
50 50
255
'
d=e=0
[153,44,6,1,42,1,6,1,42,1,6,1,42,1,6,1,42,1,6,1,42,1,6,1,42,1,4,40,5,1,4,1,1,1,36,1,5,1,4,1,1,1,36,1,5,1,4,1,1,1,36,1,5,1,4,1,1,1,36,1,5,1,4,1,1,34,3,1,5,1,4,1,34,1,3,1,5,1,4,1,34,1,3,1,5,1,4,1,34,1,3,1,5,1,4,1,34,1,3,1,5,1,4,1,34,1,3,1,5,1,4,1,34,1,3,1,5,1,4,1,34,1,3,1,5,1,4,1,34,1,3,1,5,1,4,1,34,1,3,1,5,1,4,1,34,1,3,1,5,1,4,1,34,1,3,1,5,1,4,1,34,1,3,1,5,1,4,1,8,31,5,1,4,1,8,1,25,1,9,1,4,1,8,1,25,1,9,1,4,1,8,1,25,1,9,1,4,1,8,1,25,1,9,1,4,1,8,1,25,1,9,1,4,1,8,1,25,1,9,1,4,1,8,1,25,1,9,1,4,1,8,37,4,1,34,1,14,1,34,1,14,1,34,1,14,1,34,1,14,1,34,1,14,1,34,1,14,1,34,1,14,1,34,1,14,1,34,1,14,1,34,1,14,1,34,1,14,36,63].map{|n|n.times{s+=[" 255 255 255"," 0 0 255"][d];s+=$/if (e+=1)%50==0};d=1-d}
File.write 'blue.ppm',s
elsif File.file?(?a)
puts [["","Mary had a ","little lamb",?,,?,,"Its fleece was white as snow"],["And ","everywhere that ","Mary went",?,,'',"The lamb was sure to go"],["","It followed her to ","school one day",'','',"Which was against the rules."],["","It made the children ","laugh and play",?,,'',"To see a lamb at school"]].map{|a,b,c,d,e,f|[a+b+c+d,c.capitalize+', '+c+d,b.capitalize+c+e,f]*$/}*"

"
`touch b`
else
1971.times{|i|$><<"#{i} "if i.to_s.chars.map(&:to_i).reduce(:+)%17<1}
`touch a`
end

```

To keep track of the invocation, I'm creating an empty file `a` on the first run and an empty file `b` on the second run.

* The first program uses a certain property of the numbers.
* The second program uses a bunch of reusable parts of the verses, but that currently only saves 100 bytes over naively printing the entire thing.
* The third program currently uses just a simple run-length encoding. I'll look into actually encoding the path of the line later.

# Answer
> 2 votes
# C++, 1204 * 3 = 3612 bytes

Compiler used - **GCC 4.9.2** with `-std=c++14` flag

```
#include<bits/stdc++.h>
int i,j,c;
using namespace std;int main(){fstream f("F"),g("G");if(!f){while(i<=1970){j=i,c=0;while(j)c+=j%10,j/=10;if(c==17||i==0)cout<<i<<" ";i++;}ofstream f("F");}else if(f&&!g){cout<<R"(Mary had a little lamb,
Little lamb, little lamb,
Mary had a little lamb,
Its fleece was white as snow

And everywhere that Mary went,
Mary went, Mary went,
Everywhere that Mary went
The lamb was sure to go

It followed her to school one day
School one day, school one day
It followed her to school one day
Which was against the rules.

It made the children laugh and play,
Laugh and play, laugh and play,
It made the children laugh and play
To see a lamb at school)";ofstream g("G");}else{ofstream F("blue.ppm");F<<"P3 50 50 ";vector<int> L={1,2,4,10,13,16,19,25,28,43,76,103,109,127,190,460};vector<string> R={"1","?","43","10","6","161=","1","14","39","10","4","1514121<","1","151412","33","10","12","1315141;","1","13151417","30","10","1","1514171","7",":1814171","36","01","1","41","11",";191","35","01","1",">"},C={"255","0"};string r;i=j=0;while(i<R.size()){stringstream S(R[i]);S>>c;while(c--)r+=R[i+1];i+=2;}i=0;while(i<r.size()){c=L[r[i]-48];while(c--){F<<C[j]<<" ";}j=1-j;i++;}}}

```

***Explanation -:***

```
#include<bits/stdc++.h>
using namespace std;

int main()
{
    fstream f( "F" ), g( "G" ); // Creating empty files so that the program can decide when to run which task

    /**************************** TASK 1 ****************************/

    if ( !f ) // Print all the numbers within the range whose sum of digits is 17
    {
        for ( int i = 0; i <= 1970; i++ )
        {
            int j = i, c = 0;
            while ( j )
            {
                c += j % 10, j /= 10;
            }
            if ( c == 17 || i == 0 )
            {
                cout << i << " ";
            }
        }
        ofstream f( "F" );
    }

    /**************************** TASK 2 ****************************/

    else if ( f && !g )  // Print the second task as it is using raw literals
    {
        cout << R"(Mary had a little lamb,
Little lamb, little lamb,
Mary had a little lamb,
Its fleece was white as snow

And everywhere that Mary went,
Mary went, Mary went,
Everywhere that Mary went
The lamb was sure to go

It followed her to school one day
School one day, school one day
It followed her to school one day
Which was against the rules.

It made the children laugh and play,
Laugh and play, laugh and play,
It made the children laugh and play
To see a lamb at school)";

        ofstream g( "G" );
    }

    /**************************** TASK 3 ****************************/

    else // Third task using Run-Length encoding
    {
        ofstream F( "blue.ppm" );
        F << "P3 50 50 ";

        /*
        L = set of all the lengths found during run-length encoding.
        R = vector containing the run-length encoding of "255" and "0" alternatingly.
                {1,"?") means 1 times print '255'/'0' "x" number of times where x = L[ASCII(?)-48] = L[15] = 469
        C = vector containing the two strings to be printed alternatingly.
        */

        vector<int> L = {1, 2, 4, 10, 13, 16, 19, 25, 28, 43, 76, 103, 109, 127, 190, 460};
        vector<string> R = {"1", "?", "43", "10", "6", "161=", "1", "14", "39", "10", "4", "1514121<", "1", "151412", "33", "10", "12", "1315141;", "1", "13151417", "30", "10", "1", "1514171", "7", ":1814171", "36", "01", "1", "41", "11", ";191", "35", "01", "1", ">"};
        vector<string> C = {"255", "0"};
        string r; // Contains the normal/expanded version of R
        i = j = 0;

        while ( i < R.size() ) // Expanding "R" into normal form and putting it into "r"
        {
            stringstream S( R[i] );
            S >> c; // Convert R[i] to its integer representation and put it in "c" with the help of stringstream.
            while ( c-- )
            {
                r += R[i + 1];
            }
            i += 2;
        }

        i = 0;
        while ( i < r.size() )
        {
            c = L[r[i] - 48];  // "c" is the number of times the current character has to be printed consecutively.
            while ( c-- )
            {
                F << C[j] << " ";
            }
            j = 1 - j; // Alternate "255" and "0"
            i++;
        }
    }
}

```

# Answer
> 2 votes
# Python 3, 1027 + 1028 + 1029 = 3084

```
0 or print('0 '+' '.join(str(i)for i in range(1971)if sum(map(int,str(i)))==17))
1 or print("""+$,
L$, l$,
+$,
Its fleece was white as snow

And e(@,
@, @,
E(@
The!was sure to go

#&
S&, s&
#&
Which was against the rules.

%l/,
L/, l/,
%l/
To see a!at school""".translate({43:'Mary had a l',36:'ittle lamb',40:'verywhere that ',64:'Mary went',35:'It followed her to s',38:'chool one day',47:'augh and play',37:'It made the children ',33:' lamb '}))
q=[153,44]+[e-63for e in b'E@i@E@i@E@i@E@i@E@i@E@i@CgD@C@@@c@D@C@@@c@D@C@@@c@D@C@@@c@D@C@@aB@D@C@a@B@D@C@a@B@D@C@a@B@D@C@a@B@D@C@a@B@D@C@a@B@D@C@a@B@D@C@a@B@D@C@a@B@D@C@a@B@D@C@a@B@D@C@a@B@D@C@G^D@C@G@X@H@C@G@X@H@C@G@X@H@C@G@X@H@C@G@X@H@C@G@X@H@C@G@X@H@C@GdC@a@M@a@M@a@M@a@M@a@M@a@M@a@M@a@M@a@M@a@M@a@Mc~?']
1 or open("blue.ppm","w").write("P3\n50 50\n255\n"+' '.join(q[r*2]*'255 255 255 '+q[r*2+1]*'0 0 255 'for r in range(140)).strip())
f=open(__file__);l=f.read();f.close();open(__file__,"w").write(l.replace("0 or","0 and",1).replace("1 or","0 or",1))

```

Uses OEIS A166370 for the numbers, some hand-written compression for Mary's Lamb and ASCII bytes to store the amounts of numbers in the PPM.

(Ab)uses Python's feature to only evaluate the second value for logical operators if the result is not known yet (short-circuiting): `1 or code` and `0 and code` do not evaluate `code`. Then uses some replacements to change the `0 or` enabling code execution to a `0 and` and the next `1 or` to `0 or`.

The 3rd execution kills the second replace, as there are no more `1 or`'s. The 4th execution kills the first replace, after which the code does basically nothing.

# Answer
> 1 votes
# PHP (1552\*3)+2 = 4658

There is A LOT of golfing that can be made.

The code writes 1 byte into another file called `z`, to check the status.

Here is the code:

```
<?$Y=base64_decode;$Z=gzdecode;$r=file_put_contents;switch(include z){case 2:$M=Mary;$l=lamb;$L=ittle;$H="$M had a l$L $l,";echo"$H
L$L $l, l$L $l,
$H
Its fleece was white as snow
";$W="$M went";$H="verywhere that $W";echo"
And e$H,
$W, $W,
E$H
The $l was sure to go
";$S=chool;$O="$S one day";$I="
It followed her to s$O";echo"$I
S$O, s$O$I
Which was against the rules.";$L="augh and play";$I="
It made the children l$L";echo"$I,
L$L, l$L,$I
To see a $l at s$S";$r(z,3);break;case 3:$r($Z($Y("H4sIAAAAAAAAA+3ay63CMBSE4X2qSAkRKH3QfzXAmkf8mBOfiX9dRXcBfIJ47Ewwj/uyb+u+Lbd9fx+r4gACAgICApoO2l5/Jf+X0icCfT4gG7ka0DSQQMdPOopB9bv5BpqeG6D2F8tjQK6AImJAroAiYkCugCJiQK6AemKQ51bWF+oaxe6Rk2DhAQUKjIIEIU9Xg8gTkBIiT0BKKG+e8nXMcVBRDFr3oyQIq4ADVLW1JNnfbEYkafYcJR+oatZLtrebEfluPVAAVDNKkn3yZoQfazhAvXkaW4WNTvQkEIUcSAlRyIGUEIUcSApRyIGUEIUcSAlRyIGUEIUcSAlRyH+/w/H7qudDXUHMf+nhpq4NGlM28196KOFtx5iy6XPpyTdiyaEhZdPg3p0S3gaN+baOAnVViAKV6bz4QxSoTOflAhAF6v95yfdVTT7otOEPCSNQ+Sgl/1jc9RhAhrOfux8HyG/2Gy6xE0J+v+AyXGInhAxnv98SOyFkOPspWA6Q3+w3XGInhChYQBGQ4ez3W2InhAxnPwXLAfKb/RfYvQqH8o0aENBJ0BPXPoC/PXEAAA==")),'blue.ppm');$r(z,1);break;default:echo$Z($Y("H4sIAAAAAAAAAxXSuQHAMAwCwFUYIehF+y8WXCWWaDj7gw4ncA+Uv7eIOcQKIf/fIPuQI+QuUj5fo+pQLdQsagclz67QeegSuhc9g95Gy/NLTBwmhanF9GCmMVsYeXeB5WFD2FxsDbYbO4XdxMr7I/QdREGxUA5UDXVBk9AGJGfuw33CcXExuGxcFa4TN4FbuvIHfq/091p/rk26N+nipN7R1RnuznB5htsz9GbuzzQA0wJMEzBtwNRbWIFlBpYdWIZgWYJlCpbe1hhsa7DNwbYH2yBsi7BNwtaLGIVjFY5ZOHbhGIZjGY5pOLbh6OWswzUPl+8+DcS1ENdEXBtxjcS1kku+sJ0oQ1GWokxF2YoyFmUtylzG4HsbDt/n3NG5C+cunbty7tq5G7738/3WJLxlVAIAAA=="));$r(z,2);}

```

I know that this is a VERY horrible code and I can try to golf the list.

But hey, I can't find a pattern on those :/

# Answer
> 1 votes
# Ruby, 691+612+225 = 1528 bytes

Another self modifying answer, this time in ruby. I just bumped into this yesterday and the compressing of the poem caught my eye. I was only able to save 92 bytes off the raw text thought.

```
puts (0..1970).select{|i|eval(i.to_s.gsub /\B/,'+')%17<1}*' '
File.write $0,%@
m='lamb:little 0,:Mary :2had a 1:2went:laugh and play:It made the children 5:It followed her to 10: was : that :11 one day:school:everywhere:3
1 1
3
Its fleece8white as snow

And 1294,
4, 4,
1294
The 08sure to go

7
10, 10
7
Which8against the rules.

6,
5, 5,
6
To see a 0 at 11'
12.downto(0){|i|m.gsub! i.to_s,m.split(':')[i]}
puts m.split(':')[13].gsub /^./,&:upcase
File.write $0,%!a=[1]
s=[16,13]
File.write 'blue.ppm',(' P3
50 50 '+[460,a*43,[19,127]*6,13,a*39,[s,4,109]*4,s,4,a*33,10,s,[103,10,s]*12,25,a*30,s,25,[76,28,13,25]*7,a*36,13,[103,43]*11,a*35,190].flatten.map{|i|('255 '*i)+'0 0 '}*' ')[1..-6]!@

```

Each run of the program rewrites the program for the next run. I didn't figure out the special property of the numbers until looking over the other answers. And did take same inspiration Martin's answer but I didn't use the suggestion from blutorange because I couldn't figure out why it worked.

There is probably a few more bytes to scavenge from the poem but not much. It is basically just subbing in common sequences and is using the order of the sequence as the part to replace.

For the final part I length encoded all of the 255 bytes into an array and glued them together with the zeros. And then I encoded the repeating sequences in that array.

# Answer
> 0 votes
# JavaScript + HTML, 3909 bytes

This is a HTML/JavaScript application that uses page reload to rerun files. I goofed on parsing the PPM. If you know how to read PPM files, please let me know. Stack Exchange doesn't allow local-storage. So you will have to run the JSFiddle.

Again, I know I bombed the ppm file.

But in the end:

**JavaScript**: 1,232 bytes * 3 = 3696

**HTML**: 71 bytes * 3 = 213

**Total**: 3909

JSFiddle

```
var mary = '</br>\
Mary had a little lamb,</br>\
Little lamb, little lamb,</br>\
Mary had a little lamb,</br>\
Its fleece was white as snow</br>\
</br>\
And everywhere that Mary went,</br>\
Mary went, Mary went,</br>\
Everywhere that Mary went</br>\
The lamb was sure to go</br>\
</br>\
It followed her to school one day</br>\
School one day, school one day</br>\
It followed her to school one day</br>\
Which was against the rules.</br>\
</br></br>\
It made the children laugh and play,</br>\
Laugh and play, laugh and play,</br>\
It made the children laugh and play</br>\
To see a lamb at school\
';
var img = '<img src="https://i.stack.imgur.com/sHCba.png"/>'

function run() {
  var step = localStorage.getItem("step");
  step++;
  localStorage.setItem("step", step);
  $('#step').text(step);
  var r = $('#results')
  switch (step) {
    case 1:
      for (var i = 0; i < 133; i++) {
        r.append(i + 1 + ' ');
      }
      break;
    case 2:
      r.html(mary);
      break;
    case 3:
      r.html(img);
      localStorage.setItem("step", 0);
      break;
    default:
      localStorage.setItem("step", 0);
      break;
  }
}
run();
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Step: <span id='step'></span>
</label>
<div id='results'></div>
```

---
Tags: code-golf, graphical-output, kolmogorov-complexity, sequence, compression
---


# Question
Title: "I know that language - that's Java. No? It's Perl?"
## Introduction

A known fact is that Jon Skeet can code Perl and make it look like Java. In this challenge you will try to do something similar.

## Challenge

Write a piece of code of any length that can be executed **without any errors/exceptions** in two different languages. Your program can take inputs, give outputs, whatever it wants.

The code has to be executed with interpreters/compilers of your choice one after another (with *basic* settings, means you are not allowed to adjust the compiler/interpreter settings).

*Note that the source code and any used sources (files, libs and so on) are **not** allowed to change during the execution of the script with the compilers/interpreters.*

## But which languages are "different"?

Two languages are different from each other if they are not the same language without looking at the version. **Example:** *Python 3.5* is not different to *Python 2.7*.

## Scoring

The final score consists out of several aspects:

* **charScore**: Take your code and then (max charScore is 95)...

1. Look at every function and delete all arguments (in *echo "Hello"* "Hello" counts as an argument). So now only keywords and functions count. **Example:** *System.out.println(1+1);* becomes *System.out.println();*
    2. Make all strings to empty strings *and all regex and literals* empty. **Example:** *"khffshiufahk"* becomes *""* and all regex (without string) gets deleted.
    3. Delete all comments. **Example:** *//Jon Skeet would also do this* becomes *\[nothing\]* \_Definition of "comment": _ Anything that doesn't change the execution of the program (So you could simply leave them out and nothing would change).
    4. Delete all characters that are not unicode 32-126. **Example:** *print(2²)* becomes *print(2)*
    5. Count only the *occurrences* of the letters. **Example:** *hiiiiiii-thhheeeree* has the same score as *hi-there* (means score of 8)

Here is a StackSnippet to do step 3 and 4 for you (report me if there is a bug):

```
function calcScore() {
 var onlyValidChars = "";
 var code = document.getElementById("code").value;
 for (i = 0; i < code.length; i++) {
  if (code[i].charCodeAt(0)>=32 && code[i].charCodeAt(0)<=126) { //step 3
     if (onlyValidChars.indexOf(code[i]) === -1) { //step 4
       onlyValidChars += code[i];
         }
       }
 }
  return onlyValidChars.length;
}
function showCalcScore() {
 alert("Your charScore: "+calcScore());
}
```

```
<body>
    <textarea placeholder="Insert your code here." id="code"></textarea>
    <br>
    <button type="button" onclick="showCalcScore();">calculate score</button>
  </body>
```
* **+20** if your code is still executable in both languages now (after the *charScore-changes*)
* **+50** if running the code with the different interpreters does different things (eg order change, prints other things etc)
* **+15** if your languages are Perl and Java

The answer with the highest score wins.

**EDIT:** I don't think that this is a duplicate (but very releated) because it has no "different language" limits and no score. On the other hand, I didn't know about so-called "polyglot"-code so maybe I am wrong.

# Answer
## PHP + Lenguage, 165

Scoring calculation: 95 + 20 + 50.

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

```

In PHP, this outputs the string verbatim (since there is no `<?` to signal for the preprocessor functionality).

In Lenguage, this is an infinite loop.

The charScore changes do not affect the program, as it consists of all 95 printable ASCII characters once, so it is eligible for the +20 bonus.
> 1 votes

---
Tags: code-challenge, polyglot
---


# Question
Title: What code compiles in the most number of languages?
Excluding trivial programs, what code compiles in the most number of languages?

(By "trivial" I mean to exclude answers such as the empty program or text that will be echoed directly.)

The following code apparently compiles in all of the following programming languages (and prints something different in each one): C, C++, Perl, TeX, LaTeX, PostScript, sh, bash, zsh and Prolog.

```
%:/*:if 0;"true" +s ||true<</;#|+q|*/include<stdio.h>/*\_/
{\if(%)}newpath/Times-Roman findfont 20 scalefont setfont(
%%)pop 72 72 moveto(Just another PostScript hacker,)show((
t)}. t:-write('Just another Prolog hacker,'),nl,halt. :-t.
:-initialization(t). end_of_file. %)pop pop showpage(-: */
int main(){return 0&printf("Just another C%s hacker,\n",1%
sizeof'2'*2+"++");}/*\fi}\csname @gobble\endcsname{\egroup
\let\LaTeX\TeX\ifx}\if00\documentclass{article}\begin{doc%
ument}\fi Just another \LaTeX\ hacker,\end{document}|if 0;
/(J.*)\$sh(.*)"/,print"$1Perl$2$/"if$_.=q # hack the lang!
/
sh=sh;test $BASH_VERSION &&sh=bash;test $POSIXLY_CORRECT&&
sh=sh;test  $ZSH_VERSION && sh=zsh;awk 'BEGIN{x="%c[A%c[K"
printf(x,27,27)}';echo "Just another $sh hacker," #)pop%*/

```

That's 10 different languages. I found it via pts oldalai (who also has a magnificent Christmas poem written in C, C++, Perl and TeX). Can anyone do better?

# Answer
> 9 votes
# 3 Languages - C, C++, and Python

```
#ifdef _cplusplus
    #include <iostream>
    #define print() int main(){cout << "Hello world! -- from C++" << endl;}
#elif (defined __STDC__) || (defined __STDC_VERSION__)
    #include <stdio.h>
    #define print() int main(){printf("Hello world! -- from C\n");}
#else
import builtins
print = lambda : builtins.print("Hello world! -- from Python")
#endif

print()

```

Something different is printed in each language. In C & C++, lines starting with '#' are preprocessing directives, but those same lines are comments in Python.

# Answer
> 4 votes
# 5 languages- Thue, Brainf\***, Boolf\***, Treehugger, and Javascript

```
/*::=
alert::=~This is Thue!
::=
-><[[--->+<]>-.[---->+++++<]>-.+.++++++++++.+[---->+<]>+++.-[--->++<]>-.++++++++++.+[---->+<]>+++.+[->++<]>.---[----->+<]>-.+++[->+++<]>++.++++++++.+++++.--------.---[->+++<]>+...---------.[-]]
^^[[--->+^]>-.[---->+++++^]>-.+.++++++++++.+[---->+^]>+++.-[--->++^]>-.++++++++++.+[---->+^]>+++.>-[--->+^]>-.-[--->+^]>+.-------------..+++.[--->+^]>---.++[->+++^]>++..--.+++++++++++++.[--->+^]>-----.[-]]
-+[+;;+;+;+;+;+;+;;;;+;+;+;;+;+;+;;+;+;+;;+;+;;+;;+;;;+;;;;;;+;+;;+;+;;+;+;+;;+;+;;+;;+;;;+;;;;;;+;+;;;+;+;;;;+;+;+;;;;+;+;;+;+;;;;+;+;;+;;;+;;+;+;;+;;+;;+;;+;;+;;+;+;+;+;+;+;;;+;+;+;+;+;+;;;+;+;+;+;+;+;;+;+;;;;+;+;;]
*/alert("This is Javascript!")

```

Note that the Treehugger portion times out in the web-based implementation, unfortunately, so you should use a different Treehugger interpreter.

---
Tags: code-challenge, polyglot
---


title: Eight Queens Obsfucation

text:
# Question
Title: Eight Queens Obsfucation
You've probably heard of the classic Eight Queens Puzzle. For those of you who haven't it goes something like this:

> Position 8 queens on an 8×8 chessboard so that no two queens threaten each other (no two queens appear on the same row, column or diagonal as each other).

Here is one answer that is very close:

```
X - - - - - - -
- - - - X - - -
- X - - - - - -
- - - - - X - -
- - X - - - - -
- - - - - - X -
- - - X - - - -
- - - - - - - X

```

As you can see, two queens appear on the long diagonal between the top left corner and the bottom right corner.
Your task is to solve the Eight Queens Puzzle (using any programming language) in a unique or obfuscated manner. The first answer to 15 up-votes wins (the number may be subject to change depending on the popularity of this question).
Your output must be like the example above (empty squares represented by `-`, queens represented by `X` and a space between each `X` or `-`). Good luck!!

# Answer
> 6 votes
# Mathematica

The following implementation challenges the player to find one or more solutions to the eight queens problem. (It was too easy to simply have the program output the answers.)

Clicking on any of the squares in the chessboard toggles between "queen" and . When `show attacks` is checked, any attacks between queens are highlighted.

The following picture `queenImg`.

In the board below, no queen attacks another:

Placing a fourth queen on a conflicting square results in two reciprocal attacks.

The following is one of the solutions.

```
DynamicModule[{qns = ConstantArray[0, {8, 8}]},
Manipulate[
ClickPane[
Dynamic[ArrayPlot[
 Array[Boole[(Mod[#1, 2] == 0 \[And]
       Mod[#2, 2] == 0) \[Or] (Mod[#1, 2] == 1 \[And]
       Mod[#2, 2] == 1)] &, {w, w}],
 ColorRules -> {1 -> White, 0 -> LightBrown}, Mesh -> True,
 Epilog -> {Red, Thickness[.005],
   If[attacks,
    Line[Cases[
       Tally@Flatten[z[##] & /@ (Reverse /@ Position[qns, 1]),
         1], {a_, n_} /; n > 1][[All, 1]]], {}],
   Table[Inset[queenImg, p, Automatic, 10/w], {p,
     Position[qns, 1] - .5}]}]], (qns = flip[qns, Ceiling@#]) &],
{{attacks, True, "show attacks"}, {True, False}},
Initialization -> (w = 8;
z[{r_, c_}] := {row[r], col[c], diag1[r, c], diag2[r, c]};
row[r_] := {{0, r - .5}, {8, r - .5}};
col[c_] := {{c - .5, 0}, {c - .5, 8}};
diag1[r_, c_] := {{0, r - c}, {8 - (r - c), 8}};
diag2[r_, c_] := {{0, c + r - 1}, {c + r - 1, 0}};
flip[a_, pos_] := MapAt[(# - 1)^2 &, a, pos])]]

```

# Answer
> 4 votes
# dc

```
[sSdlS*]sw[d252-lwx26482+lwx1504824-lwx50051569+lwx982283196-lwx10821394332+lwx58071763728-lwx99637122816+]sa10 0:d0[laxd*453%;d1100.8*11552+P1+d8%;dPd64>s]dssx

```

Also at 160 characters it's decently short.

# Answer
> 3 votes
# **Ruby \>=1.9**

```
queens = %w[Anne-Marie Mary Elizabeth Victoria Maleficent Gertrude Alexandra Latifa]
SQUARES_ON_A_CHESSBOARD = 64

queens.permutation.find do |succession|
  i = SQUARES_ON_A_CHESSBOARD
  [-1,1].map{ |m| succession.map{ |queen| queens.index(queen) + m*i+=1}}.map(&:uniq).map(&:size).inject(&:*) == SQUARES_ON_A_CHESSBOARD
end.each do |queen|
  r=queens.map{queens[SQUARES_ON_A_CHESSBOARD & 1][SQUARES_ON_A_CHESSBOARD % 10]}
  r[queens.index(queen)]=(queens*SQUARES_ON_A_CHESSBOARD.to_s)[SQUARES_ON_A_CHESSBOARD]
  puts r.join(" ").upcase
end

```

Outputs one solution in the required format.

# Answer
> 2 votes
### Ruby

```
Q=8;$><<[*0...Q].permutation.select{|u|u.each_with_index.map{|a,b|[a-b,a+b]}.transpose.map{|z|z.uniq.size}==[Q,Q]}.map{|s|s.map{|f|(["-"]*(Q-1)+["X"]).rotate(f)*"\040"}*$/}*($/*2)

```

A not so much obfuscated but unique code - it contains function uniq ;-) but not a single whitespace! Prints all solutions to console. Maybe I'll start to obfuscate it somehow.

# Answer
> 2 votes
## Haskell

```
import Data.List
import Control.Monad
import Control.Applicative

q8 = (sequence_ . (<$> (head.(foldM.flip.const)
       (\_' -> join<$>sequence [(:[])<$>(((\_''-> [_''|
                 foldr (\(_''',_')->( (((==)<*>(\\[0,_''',-_''']))[_''-_']) &&))
                   (((/=)<*>((\\)>>=id)) [_']) $ zip [1..] _'])<$>[1..8])>>=id),
                   [_'] ]) [] $ [1..8])))
       (\_' -> putStrLn$concat$replicate(_'-1)" -"++[" X"]++replicate(8-_')" -")

```

Output:

```
 - - - X - - - -
 - X - - - - - -
 - - - - - - X -
 - - X - - - - -
 - - - - - X - -
 - - - - - - - X
 - - - - X - - -
 X - - - - - - -

```

# Answer
> 2 votes
Here is my solution in Python. This outputs every possible solution to the problem.

```
from itertools import permutations

def board(vector):
print ("\n".join('- ' * i + 'X ' + '- ' * (8-i-1) for i in vector) + "\n\n= = = = = = = =\n")

cols = range(8)
for vector in permutations(cols):
    if 8 == len(set(vector[i]+i for i in cols)) \
         == len(set(vector[i]-i for i in cols)):
        board (vector)

```

Here is a short sample of the output.

```
X - - - - - - -
- - - - X - - -
- - - - - - - X
- - - - - X - -
- - X - - - - -
- - - - - - X -
- X - - - - - -
- - - X - - - -

= = = = = = = =

X - - - - - - -
- - - - - X - -
- - - - - - - X
- - X - - - - -
- - - - - - X -
- - - X - - - -
- X - - - - - -
- - - - X - - -

= = = = = = = =

X - - - - - - -
- - - - - - X -
- - - X - - - -
- - - - - X - -
- - - - - - - X
- X - - - - - -
- - - - X - - -
- - X - - - - -

```

# Answer
> 1 votes
# k

Relatively trivial solutions, For 32 characters:

```
-1'"-X"@0b\:'0x1002200140088004;

```

Slightly better (more painful to read than obfuscated):

```
((-).*:'(c;i))'@'[(*i)#,:(*i)#10h$45i;2/:'i#(*/(i:8 4))_0b\:*/c:7 129790099;:;10h$88i];

```

# Answer
> 1 votes
**Python, Obfuscation through Complexity**

Though you would see magic numbers in my code, they are not the hard-coded solution. On running the code, you would get the list of all possible positions of the queens

```
from itertools import*
from math import*
def foo():
    def bar(x):
        k1,k2,k4 = 6148914691236517205L,3689348814741910323L,1085102592571150095L
        x = ((x >> 1) & k1) | ((x & k1) << 1)
        x = ((x >> 2) & k2) | ((x & k2) << 2)
        x = ((x >> 4) & k4) | ((x & k4) << 4)
        return x
    op = [(9259542123273814144L,4,1,0),(9241421688590303745L,7,1,8),(9241421688590303745L,7,-1,-8)]
    for o in op:
        d=o[0]
        m=18446744073709551615L
        for n in range(o[1]):
            yield d
            yield bar(d)&18446744073709551615L
            m=(m<<o[3] if o[3]>0 else m>>-o[3])&18446744073709551615L
            d=(d>>o[2] if o[2]>0 else d<<-o[2])&(m)
for e in (int(''.join("{0:08b}".format(n) for n in p),2) for p in permutations((2**n for n in range(8)),8)):
    if all((round(log(m & e)/log(2),8)).is_integer() for m in foo() if m&e):
        print '\n'.join(''.join(e) for e in  zip(*[iter("{0:064b}".format(e))]*8))
        print '-'*8

```

# Answer
> 1 votes
## Q

Obfuscation through hideousness

```
nq:{
    f:{[]
        b:.[;;:;"X"]/[-1_'16 cut 128#"- ";flip (til 8;2*neg[8]?8)];
        v:{"X" in (x[;first where y="X"] each (til 8) except z)}[b]'[b;til 8];
        d:{"X" in x ./:{$[null r:1+last where raze (1#'x)=7;enlist -1 -1;x til r]}raze 1_{x,/:y}'[rotate[z;til 8];flip@[;(first where y="X")]@/:((+;neg@-)@\:2*til 8)]}[b]'[b;til 8];
        e:{"X" in x ./:{$[null r:1+last where raze (1#'x)=0;enlist -1 -1;x til r]}raze 1_{x,/:y}'[reverse rotate[z+1;til 8];flip@[;(first where y="X")]@/:((+;neg@-)@\:2*til 8)]}[b]'[b;til 8];
        (not any v,d,e;b)};
    while[not first q:f[];];
    -1 last q;
    }

```

.

```
q)nq[]
- - - X - - - -
- - - - - - - X
- - - - X - - -
- - X - - - - -
X - - - - - - -
- - - - - - X -
- X - - - - - -
- - - - - X - -

```

# Answer
> 1 votes
# ⍴Script (rhoScript)

You wanted obfuscated, well...

```
��ˠo����}���e���

```

Hexdump, for obvious reasons:

```
00000000: a991 cba0 6f87 c1fb e97d 82c1 cd65 e2f8  ....o....}...e..
00000010: 90

```

In less-obfuscated form:

```
8 range permutations
    (with-index
        (sum) map uniq arg-a with-index
                (*exploding subtract) map uniq concatenate length)
keep-maxes-by

```

Yeah, I don't really know what it does either.

---
Tags: code-challenge, chess, obfuscation, popularity-contest
---


title: Compute the winding number

text:
# Question
Title: Compute the winding number
The winding number is the integer number of net counterclockwise revolutions an observer must have made to follow a given closed path. Note that any clockwise revolutions count negative towards the winding number. The path is allowed to self intersect.

Some examples (shamelessly taken from Wikipedia) are given below:

Your goal is to compute the winding number for a given path.

# Input

The observer is assumed be at the origin `(0,0)`.

The input is a finite sequence of points (pair-like of integer numbers) from any desired input source which describes the piece-wise linear path. You may flatten this into a 1D sequence of integer numbers if desired, and may also swizzle the input to take all x coordinates before all y coordinates/vise-versa. You may also take the input as a complex number `a+b i`. The path may self intersect and may contain zero-length segments. The first point is the start of the path and is assumed to lie somewhere on the positive x axis.

No part of the path will intersect the origin. The path will always be closed (i.e. the first and lost point are the same). Your code may either imply the last point or require it to be included.

For example, depending on your preference both inputs specify the same square:

**implied end point**

```
1,0
1,1
-1,1
-1,-1
1,-1

```

**explicit end point**

```
1,0
1,1
-1,1
-1,-1
1,-1
1,0

```

# Output

The output is a single integer for the winding number. This may be to any source (return value, stdout, file, etc.).

# Examples

All examples have the end point explicitly defined and are given as x,y pairs. Incidentally, you should be able to also directly feed these examples into any codes assuming implicitly defined end points and the outputs should be the same.

**1. Basic test**

```
1,0
1,1
-1,1
-1,-1
1,-1
1,0

```

**Output**

```
1

```

**2. Repeated point test**

```
1,0
1,0
1,1
1,1
-1,1
-1,1
-1,-1
-1,-1
1,-1
1,-1
1,0

```

**Output**

```
1

```

**3. Clockwise test**

```
1,0
1,-1
-1,-1
-1,1
1,1
1,0

```

**Output**

```
-1

```

**4. Outside test**

```
1,0
1,1
2,1
1,0

```

**Output**

```
0

```

**5. Mixed winding**

```
1,0
1,1
-1,1
-1,-1
1,-1
1,0
1,-1
-1,-1
-1,1
1,1
1,0
1,1
-1,1
-1,-1
1,-1
1,0
1,1
-1,1
-1,-1
1,-1
1,0

```

**Output**

```
2

```

# Scoring

This is code golf; shortest code wins. Standard loopholes apply. You may use any builtin functions so long as they were not specifically designed to compute the winding number.

# Answer
## ES6, 83 bytes

```
a=>a.map(([x,y])=>r+=Math.atan2(y*b-x*c,y*c+x*b,b=x,c=y),b=c=r=0)&&r/Math.PI/2

```

Takes as input an array of pairs of points which are interpreted as complex numbers. Rather than converting each point into an angle, the points are divided by the previous point, which Math.atan2 then converts into an angle between -π and π, thus automatically determining which way the path is winding. The sum of the angles is then 2π times the winding number.

Since Math.atan2 doesn't care about the scale of its arguments I don't actually perform the full division `z / w = (z * w*) / (w * w*)` instead I just multiply each point by the complex conjugate of the previous point.

Edit: Saved 4 bytes thanks to @edc65.
> 10 votes

# Answer
# MATL, 11 bytes

```
X/Z/0)2/YP/

```

Input is a sequence of complex numbers including the end point.

**Try it online!**

### Explanation

Most of the work is done by the `Z/` function (`unwrap`), which unwraps angles in radians by changing absolute jumps greater than or equal to pi to their 2\*pi complement.

```
X/       % compute angle of each complex number
Z/       % unwrap angles
0)       % pick last value. Total change of angle will be a multiple of 2*pi because
         % the path is closed. Total change of angle coincides with last unwrapped
         % angle because the first angle is always 0
2/       % divide by 2
YP/      % divide by pi

```
> 3 votes

# Answer
## Jelly, 11 bytes

```
æAI÷ØPæ%1SH

```

This takes input as a list of y-coordinates and a list of x-coordinates.

Try it here.
> 2 votes

# Answer
# Python, 111

Longest answer so far. My motivations are 1) learn python and 2) possibly port this to pyth.

```
from cmath import *
q=input()
print reduce(lambda x,y:x+y,map(lambda (x,y):phase(x/y)/pi/2,zip(q[1:]+q[:1],q)))

```

Input is given as a list of complex numbers.

Ideone.

I think the approach is similar to the ES6 answer.

When 2 complex numbers are multiplied, the argument or phase of the product is the sum of the argument or phase of the two numbers. Thus when a complex number is divided by another, then the phase of the quotient is the difference between the phases of the numerator and denominator. Thus we can calculate the angle traversed through for each point and the next point. Sum these angles and divide by 2π gives the required winding number.
> 2 votes

---
Tags: code-golf, geometry
---


title: Help me Shut the Box

text:
# Question
Title: Help me Shut the Box
The inspiration for this challenge should be ridiculously obvious at the time of posting.

## The Task

You must create a Shut the Box style program (not function, program). The basics of shut the box are:

Players attempt to shut the box by turning a set of levers labelled 1-9. They must do so by flipping levers. The sequence of events of each turn are as follows:

1. The current position of the levers are shown.
    * On a new game, the position of the levers should be displayed as `123456789`.
    * On a game with shut levers, all shut levers are displayed as `-`. For example, on a game that has 1, 5, and 9 shut, the output would be `-234-678-`.
2. The di(c)e (is|are) rolled.
    * If levers 7, 8, and 9 are all off, only one six-faced die is thrown. Otherwise, 2 six-faced dice are thrown.
3. The player is prompted to choose how many levers they wish to flip.
    * If the player chooses a number \>9 or \<0, the game ends.
    * If the player chooses an already shut lever, the game ends.
4. The player selects that many levers.
    * If the sum of the levers does not equal the value of the di(c)e thrown, the game ends.
5. If all the levers are shut, congratulations, you win. Otherwise, go back to step 1.

## Rules for the Program

* On each turn, you should output the current positions of levers.
* You must output the value of the roll with the phrase `You rolled:` (note the space).
* You must prompt (and wait) for the number of levers to switch with the phrase `How many levers to flip:` (note the space).
* You must prompt (and wait) for as many levers as the player specified with the phrase `Which lever to flip:` (note the space).
* You must flip the specified levers.
* If at any point the game ends, you must output `Game Over`.
* If the player finishes a turn with no levers open, you must output `You win!`

## Example Games

```
123456789
You rolled: 5
How many levers to flip: 5
Which lever to flip: 1
Which lever to flip: 2
Which lever to flip: 3
Which lever to flip: 4
Which lever to flip: 5
Game Over
```

```
123456789
You rolled: 5
How many levers to flip: 3
Which lever to flip: 2
Which lever to flip: 2
Which lever to flip: 1
Game Over
```

```
123456789
You rolled: 12
How many levers to flip: 2
Which lever to flip: 3
Which lever to flip: 9
12-45678-
You rolled: 6
How many levers to flip: 2
Which lever to flip: 2
Which lever to flip: 4
1---5678-
You rolled: 11
How many levers to flip: 2
Which lever to flip: 5
Which lever to flip: 6
1-----78-
You rolled: 8
How many levers to flip: 1
Which lever to flip: 8
1-----7--
You rolled: 8
How many levers to flip: 2
Which lever to flip: 1
Which lever to flip: 7
---------
You win!
```

# Answer
> 3 votes
# Python 3, 348

Saved 5 bytes thanks to Mathias Ettinger.
Saved 7 bytes thanks to DSM.

Ooof, this is a long one. I also hate that there's not a good way to do test cases.

```
from random import*
*l,='123456789'
q=['-']*9
r=randint
p=print
f=' to flip: '
while l!=q:
 p(*l,sep='');t=r(1,6)+r(1,6)*(l[6:]!=q[6:]);p('You rolled: %s'%t);d={int(input('Which lever'+f))for _ in' '*int(input('How many levers'+f))}
 if len(set(d))-len(d)+1-all(str(x)in l for x in d)+t-sum(d):exit('Game Over')
 for x in d:l[x-1]='-'
p('You win!')

```

# Answer
> 2 votes
# C, ~~405~~ ~~403~~ ~~398~~ ~~392~~ ~~390~~ 387 bytes

```
#define R 1+rand()/(2147483647/6+1)
#define G return puts("Game Over");
#define I(s,w)printf(s);scanf("%d",&w);
w,s;main(r,l){char b[]="123456789";for(srand(time(0));w^9;w=strspn(b,"-")){puts(b);printf("You rolled: %d\n",r=R+(strspn(b+6,"-")<3?R:0));I("How many levers to flip: ",l)for(;l--;s+=w,b[w-1]=45){I("Which lever to flip: ",w);if(w>9|w<0|b[w-1]<48)G}if(s^=r)G}puts("You win!");}

```

## Ungolfed

```
/* Macro to get random integer in range [1,6] */
#define R 1+rand()/(2147483647/6+1)

i; /* Index variable */
main(r,l,w,s)
{
    /* Running game board */
    char b[]="123456789";

    /* Run while still levers not pulled */
    for(srand(time(0));i^9;i=strspn(b,"-"))
    {
        puts(b); /* Print game board */
        r=R+(b[6]^45||b[7]^45||b[8]^45?R:0); /* Get dice roll */
        printf("You rolled: %d\n",r); /* Print dice roll */
        printf("How many levers to flip: ");
        scanf("%d",&l); /* Get # of levers */
        for(i=s=0;i++<l;s+=w)
        {
            printf("Which lever to flip: ");
            scanf("%d",&w); /* Get lever # */
            if(w>9||w<0||b[w-1]==45) /* If invalid lever or lever already pulled, game over man */
                return puts("Game Over");
            b[w-1]=45; /* flip the lever */
        }
        if(s^r) /* If sum does not equal roll, game over */
            return puts("Game Over");
    }
    puts("You win!");
}

```

Edit: D'oh! Left an unused variable in my golfed answer. I had removed it but pasted the wrong version.

# Answer
> 2 votes
## PowerShell v2+, ~~330~~ 322 bytes

```
$a=1..9;$r={1+(Random 6)};for($g="Game Over"){($o=-join$a-replace0,'-');if($o-eq'-'*9){"You win!";exit}"You rolled: "+($b=(&$r)+(&$r)*(($a|sort)[8]-ge7));$l=Read-Host "How many levers to flip";if(9-lt$l-or1-gt$l){$g;exit}while($l){$b-=($i=Read-Host "Which lever to flip");$a[$i-1]-=$I;$l-=1}if($b-or($a|sort)[0]){$g;exit}}

```

### Newlines for clarity:

```
$a=1..9
$r={1+(Random 6)}
for($g="Game Over"){
  ($o=-join$a-replace0,'-')
  if($o-eq'-'*9){"You win!";exit}
  "You rolled: "+($b=(&$r)+(&$r)*(($a|sort)[8]-ge7))
  $l=Read-Host "How many levers to flip"
  if(9-lt$l-or1-gt$l){$g;exit}
  while($l){
    $b-=($i=Read-Host "Which lever to flip")
    $a[$i-1]-=$i
    $l-=1
  }
  if($b-or($a|sort)[0]){$g;exit}
}

```

<sub>(Rrequires version 2 or later since `Get-Random` didn't exist in PowerShell v1...)</sub>

### Explanation:

Start with setting the `$a`rray of levers by taking the range `1..9`, and also set `$r` equal to a script block that we execute later (described below with `$b`). The `Game Over` wording gets set to `$g` at the start of an infinite loop `for(){...}`. Each iteration, we set our output `$o` and immediately output it (thanks to the `(...)` encapsulation) by `-join`ing together the array and replace each `0` with a `-`. (The `0` is explained below). If the output is equal to 9 hyphens, output `You win!` and `exit`.

Next, we set our dice rolls to `$b` by calling the stored `$r` (via `&`) with some additional parameters. The `Get-Random` command with a `-Maximum` of `6` (the `-Maximum` is implied) will produce an integer from 0 to 5, inclusive. We add `1` on to that to get a six-sided die, and add that to another random die roll multiplied by `(($a|sort)[8]-ge7)` which checks whether the highest value left on the levers is one of `7,8,9` by first sorting `$a` and then taking the last element and checking whether it's greater-than-or-equal-to `7`. We use implicit typecasting to turn the Boolean value into either 0 (False) or 1 (True) for the multiplication, so the additional "die" is either `die*0` or `die*1`. We then output the result of the die roll.

Next is the `Read-Host` into `$l` for how many levers. Note that PowerShell automatically adds the colon-space `:` after a `Read-Host` prompt, so we get that for free at least. We then check that the number of levers the user wishes to flip is between 1 to 9, else `exit`.

Now we enter a `while` loop. Each iteration of this loop, we `Read-Host` which lever, store that into `$i`, and subtract that value from `$b`. We then also subtract the corresponding lever in the array, and subtract how many additional times to query the user.

The last line (excepting the closing brace) tests two Boolean constructions. The first, just `$b`, will only be `$True` if the user didn't properly subtract all numbers from the die roll (in PowerShell, any non-zero number is Truthy). The other condition sorts `$a` and takes the minimal value. If we subtracted the same lever twice, then the minimal value will be negative (or Truthy), otherwise the minimal value will be `0` (or Falsey).

### Example Run:

```
PS C:\Tools\Scripts\golfing> .\shut-the-box.ps1
123456789
You rolled: 6
How many levers to flip: 1
Which lever to flip: 6
12345-789
You rolled: 6
How many levers to flip: 2
Which lever to flip: 2
Which lever to flip: 4
1-3-5-789
You rolled: 6
How many levers to flip: 2
Which lever to flip: 1
Which lever to flip: 5
--3---789
You rolled: 10
How many levers to flip: 2
Which lever to flip: 3
Which lever to flip: 7
-------89
You rolled: 9
How many levers to flip: 1
Which lever to flip: 9
-------8-
You rolled: 8
How many levers to flip: 1
Which lever to flip: 8
---------
You win!

```

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


title: Test if a point is in an Icosahedron

text:
# Question
Title: Test if a point is in an Icosahedron
Take as input 3 floating point numbers, which represent the x, y, z coordinates of a point. Return a truthy or falsey value indicating whether the point is inside the regular icosahedron centred at the origin, with top and bottom vertices at (0, 0, 1) and (0, 0, -1), and with one of the upper ring of middle vertices in the +X+Z quarterplane. Input/output formats can be anything reasonable. To allow for rounding error, Your code does not have to give correct answers for points within 10^-6 units of the boundary

Example inputs / outputs:

```
0, 0, 0 => true
1, 1, 1 => false
0.7, 0.5, -0.4 => true
-0.152053, -0.46797, 0.644105 => false
-0.14609, -0.449618, 0.618846 => true

```

To be absolutely clear on the orientation of the icosahedron, the coordinates of the vertices are approximately

```
{{0., 0., -1.},
{0., 0., 1.},
{-0.894427190999916, 0., -0.447213595499958},
{0.894427190999916, 0., 0.447213595499958},
{0.723606797749979, -0.5257311121191336, -0.447213595499958},
{0.723606797749979, 0.5257311121191336, -0.447213595499958},
{-0.723606797749979, -0.5257311121191336, 0.447213595499958},
{-0.723606797749979,  0.5257311121191336, 0.447213595499958},
{-0.27639320225002106, -0.85065080835204, -0.447213595499958},
{-0.27639320225002106,  0.85065080835204, -0.447213595499958},
{0.27639320225002106, -0.85065080835204, 0.447213595499958},
{0.27639320225002106,  0.85065080835204, 0.447213595499958}}

```

Scoring is standard ; the fewest bytes wins.

# Answer
> 5 votes
# Ruby,87

```
->c,z{a=g=3-5**0.5
10.times{x=(c*="i".to_c**0.4).real
z=-z
a&&=z<1+x*g&&x*4>g-4+g*z}
a}

```

An anonymous function taking the x and y coordinates as a complex number and the z coordinate as a real. (The question says "any reasonable" format which is a bit vague. If the format is not acceptable I can change it.)

**Explanation**

Below you can see a view looking down the z axis at the icosahedron's vertices. (for simplicity I have just drawn 2 pentagons that are perpendicular to the z axis.)

I have labelled all the points with positive z with their approximate coordinates. I have given the exact coordinates `sqrt 0.8, 0, sqrt 0.2` for the point with positive z that lies in the xz plane (y=0), and I have also labelled the opposing point.

It can be seen that there is an edge parallel to the y axis whose equation is approximately `z=0.4472, x=-0.7236`. This edge is common to two faces of the icosahedron. I will describe these as a polar face and an equatorial face.

The equation of the polar face is `z=1+x*g` where `g=3-sqrt(5)` (this value was arrived at by studying Wikipedia and Wolfram Alpha, plus a bit of my own maths.) So z must be less than `1+x*g` if the point is inside the icosahedron.

The equation of the equatorial face is `x*4=g-4+g*z` so x\*4 must be greater than
`g-4+g*z` if the point is inside the icosahedron.

We could rotate these faces through 72 degrees to test if the point is inside the icosahedron, but it is easier to rotate the point about the origin. In order to cover both the top and bottom of the icosahedron, the symmetry operation applied to the point is a rotation of 36 degrees combined with a reflection in the xy plane (flip the z axis.) This operation is applied 10 times to cover all possibilities.

**Ungolfed in test program**

```
f=->c,z{
  a=g=3-5**0.5                    #g is slope of polar face. It is truthy, so can also be used to initialize a
  10.times{                       #generate 10 images of the point
    x=(c*="i".to_c**0.4).real     #rotate the point 36 degrees, assign the real value to x
    z=-z                          #flip the z axis
    a &&= z<1+x*g && x*4>g-4+g*z  #check the point is inside the two test planes and update a if necessary
  }
a}                                #return a true or false

p f["0+0i".to_c,0]                     #true
p f["1+i".to_c,1]                      #false
p f["-0.152053-0.46797i".to_c,0.644105]#false
p f["-0.14609-0.449618i".to_c,0.618846]#true

p f["-0.8944+0i".to_c,-0.4472]         #true, just inside vertex
p f["-0.8944+0i".to_c,0.4472]          #false, outside midpoint of an edge
p f["-0.8945+0i".to_c,-0.4473]         #false, just outside vertex

```

---
Tags: code-golf, geometry
---


title: Label dead ends

text:
# Question
Title: Label dead ends
Given an input of an ASCII art "road," output the road with all dead ends labelled.

This is a road:

```
########.....######..#..###
#......#######....#..#..#.#
#.##......#...#####..#..###
#..#####..#....#..#######.#
#......#...#####.....##...#
#..###.#...#...###...#..###
##########.#..#..##..#.##.#
..#......#.######.#..#.#.#.
..#......#.#..#.#.#..#.#.#.
..######.###..##..#########

```

This is the road with *dead ends* labelled with the letter `X`:

```
########.....######..X..###
#......#######....#..X..#.#
#.XX......X...X####..X..###
#..XXXXX..X....#..#######.#
#......X...#####.....##...#
#..###.X...#...###...#..###
##########.#..X..##..#.##.X
..X......#.#XXXXX.#..#.#.X.
..X......#.#..X.X.#..#.#.X.
..XXXXXX.###..XX..######XXX

```

A *dead end* is defined as any road tile that borders *n* other road tiles, at least *n-1* of which are considered *dead ends* already by this rule. "Bordering" is in the four cardinal directions, so tiles bordering diagonally don't count.

This rule is applied repeatedly, as newly created *dead ends* can, themselves, create more *dead ends*. Also note that any road tile that borders only one other road tile is considered a *dead end* the first time the rule is applied.

Input and output may be either a single string (with lines separated by any character that is not `#` or `.`) or an array/list/etc. If your language supports it, you may also take input with each line being a function argument.

You may assume the following about the input:

* There will always be at least one "loop"—that is, a group of `#` characters that can be followed infinitely. (Otherwise every single tile would become a dead end.)
* This implies that the input will always be 2×2 or larger, since the smallest loop is:

```
##
##

```

(Which, incidentally, should be output with no change.)
* All `#` characters will be connected. That is, if you were to perform a flood fill on any `#`, all of them would be affected.

Since this is , the shortest code in bytes will win.

The example above and the tiny 2×2 grid can be used as test cases (there aren't a lot of edge cases to cover in this challenge).

# Answer
> 7 votes
# CJam, 61 bytes

```
q_N/{{0f+zW%}4*3ew:z3few::z{e__4=_@1>2%'#e=*"#"='X@?}f%}@,*N*

```

Try it here.

### Explanation

```
Outline:

    q_N/               Read input lines
        {   }@,*       Perform some operation as many times as there are bytes
                N*     Join lines

Operation:

    {0f+zW%}4*         Box the maze with zeroes
    3ew:z3few::z       Mystical 4D array neighborhood magic.
                       (Think: a 2D array of little 3x3 neighborhood arrays.)

    {                        }f%    For each neighborhood, make a new char:
     e_                                 Flatten the neighborhood
       _4=_                             Get the center tile, C
           @1>2%                        Get the surrounding tiles
                '#e=                    Count surrounding roads, n
                    *                   Repeat char C n times
                     "#"=               Is it "#"? (i.e., C = '# and n = 1)
                         'X@?           Then this becomes an 'X, else keep C.

```

(Martin saved two bytes, thanks!)

# Answer
> 5 votes
# JavaScript (ES6), ~~110~~ 109 bytes

```
r=>[...r].map(_=>r=r.replace(g=/#/g,(_,i)=>(r[i+1]+r[i-1]+r[i+l]+r[i-l]).match(g)[1]||"X"),l=~r.search`
`)&&r

```

*1 byte saved thanks to @edc65!*

## Explanation

Very simple approach to the problem. Searches for each `#`, and if there are less than 2 `#`s around it, replaces it with an `X`. Repeats this process many times until it's guaranteed all the dead-ends have been replaced with `X`s.

```
var solution =

r=>
  [...r].map(_=>                    // repeat r.length times to guarantee completeness
    r=r.replace(g=/#/g,(_,i)=>      // search for each # at index i, update r once done
      (r[i+1]+r[i-1]+r[i+l]+r[i-l]) // create a string of each character adjacent to i
      .match(g)                     // get an array of all # matches in the string
        [1]                         // if element 1 is set, return # (the match is a #)
        ||"X"                       // else if element 1 is undefined, return X
    ),
    l=~r.search`
`                                   // l = line length
  )
  &&r                               // return the updated r
```

```
<textarea id="input" rows="10" cols="40">########.....######..#..###
#......#######....#..#..#.#
#.##......#...#####..#..###
#..#####..#....#..#######.#
#......#...#####.....##...#
#..###.#...#...###...#..###
##########.#..#..##..#.##.#
..#......#.######.#..#.#.#.
..#......#.#..#.#.#..#.#.#.
..######.###..##..#########</textarea><br>
<button onclick="result.textContent=solution(input.value)">Go</button>
<pre id="result"></pre>
```

# Answer
> 0 votes
## Python (3.5) ~~362~~ ~~331~~ ~~329~~ 314 bytes

thanks to @Alissa. she helps me to win ~33 bytes

```
d='.'
r=range
def f(s):
 t=[list(d+i+d)for i in s.split()]
 c=len(t[0])
 u=[[d]*c]
 t=u+t+u
 l=len(t)
 g=lambda h,x:t[h][x]=='#'
 for k in r(l*c):
  for h in r(1,l):
   for x in r(1,c):
    if g(h,x) and g(h+1,x)+g(h-1,x)+g(h,x+1)+g(h,x-1)<2:
     t[h][x]='X'
 print('\n'.join([''.join(i[1:-1])for i in t][1:-1]))

```

## Explanations

```
d='.'
r=range

```

Function definition

```
def f(s):

```

Add a border of '.' on right and left of the board

```
 t=[list(d+i+d)for i in s.split()]
 c=len(t[0])
 u=[[d]*c]

```

Add a border of '.' on top and bottom

```
 t=u+t+u
 l=len(t)

```

Lambda function to test '#'

```
 g=lambda h,x:t[h][x]=='#'

```

Loop on the input length to be sure we don't forget dead ends

```
 for k in r(l*c):

```

Loop on columns and lines

```
  for h in r(1,l):
   for x in r(1,c):

```

Test if we have '#' around and on the position

```
    if g(h,x) and g(h+1,x)+g(h-1,x)+g(h,x+1)+g(h,x-1)<2:

```

Replace '#' by 'X'

```
     t[h][x]='X'

```

Crop the border filled with '.' and join in string

```
 print('\n'.join([''.join(i[1:-1])for i in t][1:-1]))

```

## Usage

```
f("########.....######..#..###\n#......#######....#..#..#.#\n#.##......#...#####..#..###\n#..#####..#....#..#######.#\n#......#...#####.....##...#\n#..###.#...#...###...#..###\n##########.#..#..##..#.##.#\n..#......#.######.#..#.#.#.\n..#......#.#..#.#.#..#.#.#.\n..######.###..##..#########")

########.....######..X..###
#......#######....#..X..#.#
#.XX......X...X####..X..###
#..XXXXX..X....#..#######.#
#......X...#####.....##...#
#..###.X...#...###...#..###
##########.#..X..##..#.##.X
..X......#.#XXXXX.#..#.#.X.
..X......#.#..X.X.#..#.#.X.
..XXXXXX.###..XX..######XXX

```

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


title: Symbolic Integration of Polynomials

text:
# Question
Title: Symbolic Integration of Polynomials
Apply an indefinite integral to a given string. The only rules you will be using are defined as such:

```
∫cx^(n)dx = (c/(n+1))x^(n+1) + C, n ≠ -1
c, C, and n are all constants.

```

# Specifications:

* You must be able to integrate polynomials with any of the possible features:
    + A coefficient, possibly a fraction in the format `(numerator/denominator)`.
    + Recognition that e and π are constants, and in their use, be able to form fractions or expressions containing them (can be held in a fraction like `(e/denominator)` or `(numerator/e)`, or, if in exponents, `x^(e+1)`)
        - Aside of these two special constants, all coefficients will be rational, real numbers.
    + An exponent, possibly a fraction, in the format `x^(exponent)`
        - Expressions with `e` or `π` in them, aside of themselves, will not be in exponents. (you will not have to integrate stuff like `x^(e+1)`, but you might integrate `x^(e)`)
    + Can use non-x 1-char variables (i.e. `f`)
        - This is only for ASCII ranges 65-90 and 97-122.
    + You do not have to use chain rule or integrate `x^(-1)`.
* Output must have padding (separation between terms, i.e. `x^2 + x + C`.
* If it is unknown how to integrate with the above features, the program should print out `"Cannot integrate "+input`.
* It must be a full program.

# Bonuses:

* -10% if you print out the "pretty" exponents formatted for markdown (instead of `x^2`, `x<sup>2</sup>`).
* -10% if you print out the equation (i.e. `∫xdx = (1/2)x^2 + C`)

# Examples:

Input:

```
x
```

Output:

```
(1/2)x^(2) + C
```

---

Input:

```
-f^(-2)
```

Output:

```
f^(-1) + C
```

---

Input:

```
(1/7)x^(1/7) + 5
```

Output:

```
(1/56)x^(8/7) + 5x + C
```

---

Input:

```
πx^e
```

Output:

```
(π/(e+1))x^(e+1) + C
```

---

Input:

```
(f+1)^(-1)
```

Output:

```
Cannot integrate (f+1)^(-1)
```

# Answer
## Mathematica 478 * 0.9 = 430.2

```
φ=(α=ToExpression;Π=StringReplace;σ="Cannot integrate "<>#1;Λ=DeleteDuplicates@StringCases[#1,RegularExpression["[a-df-zA-Z]+"]];μ=Length@Λ;If[μ>1,σ,If[μ<1,Λ="x",Λ=Λ[[1]]];Ψ=α@Π[#1,{"e"->" E ","π"->" π "}];Φ=α@Λ;Θ=α@Π[#1,{"e"->" 2 ","π"->" 2 "}];λ=Exponent[Θ,Φ,List];Θ=Simplify[Θ*Φ^Max@@Abs@λ];Θ=PowerExpand[Θ/.Φ->Φ^LCM@@Denominator@λ];If[Coefficient[Ψ,Φ,-1]==0&&PolynomialQ[Θ,Φ],"∫("<>#1<>")d"<>Λ<>" = "<>Π[ToString[Integrate[Ψ,Φ],InputForm],{"E"->"e","Pi"->"π"}]<>" + C",σ]])&

```

This creates a true function φ that takes one String as Input. (Does that count as complete program for Mathematica?)

The ungolfed version would be:

```
φ=(
    σ="Cannot integrate "<>#1;
    Λ=DeleteDuplicates@StringCases[#1,RegularExpression["[a-df-zA-Z]+"]];
    If[Length@Λ>1,σ,
        If[Length@Λ<1,Λ="x",Λ=Λ[[1]]];
        Ψ=ToExpression@StringReplace[#1,{"e"->" E ","π"->" π "}];
        Φ=ToExpression@Λ;
        Θ=ToExpression@StringReplace[#1,{"e"->" 2 ","π"->" 2 "}];
        λ=Exponent[Θ,Φ,List];
        Θ=Simplify[Θ*Φ^Max@@Abs@λ];
        Θ=PowerExpand[Θ/.Φ->Φ^LCM@@Denominator@λ];
        If[Coefficient[Ψ,Φ,-1]==0&&PolynomialQ[Θ,Φ],
            "∫("<>#1<>")d"<>Λ<>" = "<>StringReplace[ToString[Integrate[Ψ,Φ],InputForm],{"E"->"e","Pi"->"π"}]<>" + C",
            σ
        ]
    ]
)&

```

Note that the Greek letters are necessary to be able to use all the other letters in the input.
> 2 votes

# Answer
# MATLAB, 646 x 0.9 = 581.4 bytes

```
t=input('','s');p=char(960);s=regexprep(t,{p,'pi([a-zA-Z])','([a-zA-Z])pi','([\)e\d])([a-zA-Z])','([a-zA-Z])(([\(\d]|pi))','e^(\(.+?\))','e'},{'pi','pi*$1','$1*pi','$1*$2','$1*$2','exp($1)','exp(1)'});r=[s(regexp(s,'\<[a-zA-Z]\>')),'x'];r=r(1);e=0;try
I=int(sym(strsplit(s,' + ')),r);S=[];for i=I
S=[S char(i) ' + '];end
b=0;o=[];for i=1:nnz(S)
c=S(i);b=b+(c==40)-(c==41);if(c==42&&S(i+1)==r)||(b&&c==32)
c='';end
o=[o c];end
o=regexprep(char([8747 40 t ')d' r ' = ' o 67]),{'pi','exp\(1\)','exp','\^([^\(])',['1/' r]},{p,'e','e^','^($1)',[r '^(-1)']});catch
e=1;end
if e||~isempty(strfind(o,'log'))
disp(['Cannot integrate ' t]);else
disp(o);end

```

This is currently a work-in-progress using MATLABs built in symbolic integration capabilities. Currently the requirements have been updated so the format now matches the requirements. It also does qualify for the second -10% bonus.

If anyone wants to pitch in and suggest ways of correcting the output, or use this code as a basis for another answer, feel free :). If I can find the time, I'll keep playing with it and see if I can think how to reformat the output.

**Update:** Ok, so after a bit more work, here is how the code currently stands. It is still a work in progress, but now getting closer to matching the required output.

```
t=input('','s'); %Get input as a string
p=char(960); %Pi character
s=regexprep(t,{p,'pi([a-zA-Z])','([a-zA-Z])pi','([\)e\d])([a-zA-Z])','([a-zA-Z])(([\(\d]|pi))','e^(\(.+?\))','e'},{'pi','pi*$1','$1*pi','$1*$2','$1*$2','exp($1)','exp(1)'}); %Reformat input to work with built in symbolic integration
r=[s(regexp(s,'\<[a-zA-Z]\>')),'x'];r=r(1); %determine the variable we are integrating
e=0; %Assume success
try
    I=int(sym(strsplit(s,' + ')),r); %Integrate each term seperately to avoid unwanted simplificaiton
    S=[];
    for i=I
        S=[S char(i) ' + ']; %Recombine integrated terms
    end
    %Now postprocess the output to try and match the requirements
    b=0;o=[];
    for i=1:nnz(S)
        %Work through the integrated string character by character
        c=S(i);
        b=b+(c=='(')-(c==')'); %Keep track of how many layers deep of brackets we are in
        if(c=='*'&&S(i+1)==r)||(b&&c==' ') %If a '*' sign preceeds a variable. Also deblank string.
            c=''; %Delete this character
        end
        o=[o c]; %merge into new output string.
    end
    o=regexprep([char(8747) '(' t ')d' r ' = ' o 'C'],{'pi','exp\(1\)','exp','\^([^\(])',['1/' r]},{p,'e','e^','^($1)',[r '^(-1)']});
catch
    e=1; %failed to integrate
end
if e||~isempty(strfind(o,'log'))
    disp(['Cannot integrate ' t])  %bit of a hack - matlab can integrate 1/x, so if we get a log, we pretend it didn't work.
else
    disp(o)% Display it.
end

```

Here are some examples of what it currently produces. As you can see, it's not quite right, but getting closer.

Inputs:

```
x
-f^(-2)
(1/7)x^(1/7) + 5
πx^e
(f+1)^(-1)

```

Outputs:

```
∫(x)dx = x^(2)/2 + C
∫(-f^(-2))df = f^(-1) + C
∫((1/7)x^(1/7) + 5)dx = x^(8/7)/8 + 5x + C
∫(πx^(e))dx = (πx^(e+1))/(e+1) + C
Cannot integrate (f+1)^(-1)

```
> 7 votes

---
Tags: code-golf, math, parsing, polynomials, calculus
---