title: Notes to Tablature

text:
# Question
Title: Notes to Tablature
## Challenge

Given a list a notes, you must return the corresponding tablature.

## Notes

The notes must be in the range of A to G inclusive and the octave range being 2 to 6 inclusive. The format is note-octave with `#` representing a sharp and `b` representing a flat. E.g: `A7` or `F#3`.

## Tabs

Tablature is a method of writing music, by diagrammatically representing the instrument. It is usually represented as five lines with numbers on them.

The numbers that are written on the lines represent the fret used to obtain the desired pitch. For example, the number 3 written on the top line of the staff indicates that the player should press down at the third fret on the high E (first string). Number 0 denotes the nut — that is, an open string.

Fret numbers may not be greater than 22 and the guitar is six string.

The tablature must be in the standard ASCII format. You must not include any technique indicators (hammer on, slide etc.). Separate each note by five dashes. In the case of double digits, reduce the number of dashes to four.

The beginning of the tab should look like this:

```
e |-----
B |-----
G |-----
D |-----
A |-----
E |-----

```

And the end should look like:

```
-----|

```

for all lines.

<sub>(source: justinguitar.com)</sub>

## Example

```
Input: C3 C3 D3 E3 F3

Output:

e |-----------------------------------|
B |-----------------------------------|
G |-----------------------------------|
D |-----------------0-----2-----3-----|
A |-----3-----3-----------------------|
E |-----------------------------------|

```

## Winning

The shortest code wins

# Answer
# Python 3 – ~~329~~ ~~328~~ ~~319~~ 300

This is my first post on codegolf.se, and probably not nearly optimal; I have read a lot of posts here but did my first code golf ever maybe 50 hours ago. Wanted to try, though!

**EDIT:** Removed 1 byte, didn't need to output an extra dash there

**EDIT 2:** Removed 9 bytes, removed some spaces from the note string

**EDIT 3:** Removed 19 bytes by converting `filter()` to a generator

```
a,b='C B#oC#DboD oD#EboE FboF E#oF#GboG oG#AboA oA#BboB Cb',input().split()
for f in range(6):print('eBGDAE'[f]+' |-----'+''.join([((str(d[-1])if f==6-len(d)else'')+'-'*6)[:6]for d in[[c-d+9for d in b"%*/48="if c+9>=d]for c in[12*int(g[-1])+a[:a.index((g[:-1]+' ')[:2])].count('o')for g in b]]])+'|')

```

A bit ungolfed:

```
a='C B#oC#DboD oD#EboE FboF E#oF#GboG oG#AboA oA#BboB Cb' # string of notes
b=input().split()                                         # read user input
for f in range(6):                    # loop through the strings

  print('eBGDAE'[f] + ' |-----' +     # string identifier and start of string
  ''.join([                           # join notes of tablature
  ((str(d[-1])                        # highest string the note can be played on
  if f == 6 - len(d)                  # if this is the correct string print the fret
  else '')                            # if not then only dashes
  + '-' * 6)                          # print the dashes after the fret
  [:6]                                # but only until 6 chars per note

  for d in [                          # loop through strings
  [c - d                              # calculate fret number
  + 9                                 # add back the 9 (explained below)
  for d in b"%*/48="                  # string values increased by 9 as ASCII bytes
  if c + 9 >= d]                      # filter to remove too high-pitched strings

  for c in [                          # loop through note values
  12 * int(g[-1]) +                   # octave value
  a[:a.index(                         # part of note string before this note
  (g[:-1] + ' ')[:2])]                # unique note identifier
  .count('o')                         # o's (frets) between C and this note
  for g in b]]])                      # loop through notes

  + '|')                              # end tablature

```
> 8 votes

---
Tags: code-golf, music
---


# Question
Title: Approximated (unsorted) square from a set of values
So a colleaque came with this problem lately and I want to challange you to solve the problem in the code-golf style, shortest solution in any language wins.

**The Problem:**

Given is a random set of values, where the values themselfs are not the concern, but the amount (which is random as well)of values.

To keep the posts readable, let's limit the amount of values to 200, but the program must be able to handly any amount of values, which the language supports.

**Input:** No Input needet, due the programm should set an random amount of values (limited to 200).

**Output:** Can be text or graphic(px) I recommend to use single digits as values if you use text based output, to keep the output clear.

**Example:**

```
{1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7}   -- Amount : 16

```

Now you should sort these values in a approcimated square matrix like:

```
1 2 3 4
5 6 7 8
9 1 2 3
4 5 6 7
(4 x 4)

```

Pretty simple so far, if not boring.

**But now the challange:**

The number of fields in the matrix must be equivalent to the amount of values given. No empty fields or ignored values are allowed.

As an example, with 12 values, an square matrix is not possible, so you have to find the next aproximitation to it, which is 3x4 or 4x3 but NOT 4x4.

For any prime, the matrix would be **1 x prime**

**Examples:**

For 12 Values:

```
1 2 3 4
5 6 7 8
9 1 2 3
X X X X   <- NOT ALLOWED, it makes the matrix square, but inserts non existing values.

```

or

```
1 2 3
4 5 6
7 8 9
1 2 3

```

For 35 Values:

```
1 2 3 4 5 6 7
8 9 1 2 3 4 5
6 7 8 9 1 2 3
4 5 6 7 8 9 1
2 3 4 5 6 7 8

```

# Answer
## Mathematica, 91 bytes

```
n=RandomInteger@199+1
TableForm@Partition[Range@9~RandomChoice~n,Divisors@n~Nearest~Sqrt@n]

```

I hope I got this right:

* Generate a random length between `1` and `200` (inclusive).
* Generate a list of that length with numbers from `1` to `9` (inclusive).
* Find one of the two divisors closest to the square root, with `Divisors@n~Nearest~Sqrt@n`.
* Break the list into rows of that length.
* Display the grid with `TableForm`.

Example run:
> 1 votes

# Answer
## Javasript, ~~156 or 119~~ 152 or 115

Output numbers 1 to 9: **152**

```
for(q=~~Math.sqrt(n=new Date%200);~~(w=n/q)!=w;--q);i=q=0;alert("".replace.call(Array(n+1),/./g,function(){return(++q>9?q=1:q)+(++i==w?i=0||"\n":" ")}))

```

Output zeroes: **115**

```
for(q=~~Math.sqrt(n=new Date%200);~~(w=n/q)!=w;--q);alert(Array(q+1).join("".replace.call(Array(w+1),/./g,0)+"\n"))

```
> 0 votes

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


# Question
Title: JavaScript: Tricks to shorten onkeydown, setInterval etc
Are there any tricks to shorten defined function names like setInterval, onkeydown, onkeyup, createLinearGradient or even return?

When using it more than once it's nice to put it as a string into a variable and reuse it afterwards but most functions I only need once.

I know that ES6 has arrowed functions - maybe there is an apporach?

# Answer
> 7 votes
There is a rather clever trick for shortening method names for a particular object that I first learned about during the first JS1k competition. See Martijn Haverbeke's page about it, under "Mechanized Abbreviation".

The idea is that you iterate over the keys of the object and apply a hash function *h(k)* to each of the keys in order to compute an alias for the key. With some trickery you can make sure to only apply the aliasing to keys referring to function values (i.e. only if `typeof o[k] == 'function'`), but of course this costs some extra characters. If only one of the keys being aliased hash to the same value, then you can use the abbreviated name unambiguously. If there are collisions you have to fall back to the full name (since the order of iteration is undefined).

When using this trick, remember that it's a trade-off between length of hash function (expression) and number of collisions. Of course, this approach is only helpful when you use a lot of long-name methods on one particular object (e.g. canvas code). For a paricular snippet that you want to golf, it could be useful to find the number of occurrences of each identifier and put together something like this page, to simplify the search for a good hash function.

This trick could be used with global functions since the global object is `this` at the global scope (or even shorter, `windows` = `window.top` = `top` in a web environment). Also, another thing to keep in mind with frequent use of methods on one object is the `with` statement.

# Answer
> 5 votes
There are a lot of different cases here. I'll try to address as many as I can think of, but others might spot a few additional ones.

For starts, `return` is not a function. It's a keyword. So you're out of luck there. (Unless you can write your function in a single statement, in which case ES6 arrow functions make the return implicit, like `f=s=>s.length` instead of `f=s=>{return s.length;}`.)

For static-like functions such as `setInterval` or `Math.sin` you can just give them a new name:

```
t=setInterval
s=Math.sin

```

If you want to call a function on an object repeatedly, you'll have to work a bit harder though. For instance if you want to use `s.charCodeAt` multiple times on a string `s`, then you *cannot* do:

```
c=s.charCodeAt
c(1)
c(2)
...

```

Because if invoked like this, `c` will not know it's `this`-context. The simplest option here is to store `c` as a property of `s`:

```
s.c=s.charCodeAt
s.c(1)
s.c(2)

```

If you're using this *very* often though, you don't want to write the `s.` every time. To get rid of that, you'll need to write your own function. Using ES6 notation:

```
c=i=>s.charCodeAt(i)
c(1)
c(2)

```

Note however that this requires that you always want to call it on the *same* `s`. However, if you want to use a shortened member function on several objects, you can make those parameters:

```
c=(o,i)=>o.charCodeAt(i)
c(s,1)
c(t,2)
...

```

Then there's also the option to modify the prototype to patch the function into *every* instance of a class, but I'd have to look up the details.

# Answer
> 2 votes
ES6 can be the answer regarding function definition, with arrow functions, array comprehension and closure expressions

ECMAScript 5:

```
function z(a) {
  statement; statement; ...
  return value;
}

```

ECMAScript 6

```
z=a=> {
   statement; statement; ...
   return value;
}

// or

z=a=> expression

```

*Example* Factorial

```
function f(n) { for(r=1;n;n--;) r*=n; return r } // Iterative

function f(n) { return n>1 ? n*f(n-1) : 1 } // recursive

f=n=> n>1 ? n*f(n-1):1// ES6 recursive

```

---
Tags: code-golf, tips, javascript
---


# Question
Title: Print Hamlet's monologue using as few characters as possible
The task here is to print the text below, using **as few characters as possible** in your code. You can't use any external resource. (file, stdin, network)

```
To be, or not to be: that is the question:
Whether 'tis nobler in the mind to suffer
The slings and arrows of outrageous fortune,
Or to take arms against a sea of troubles,
And by opposing end them? To die: to sleep;
No more; and by a sleep to say we end
The heart-ache and the thousand natural shocks
That flesh is heir to, 'tis a consummation
Devoutly to be wish'd. To die, to sleep;
To sleep: perchance to dream: ay, there's the rub;
For in that sleep of death what dreams may come
When we have shuffled off this mortal coil,
Must give us pause: there's the respect
That makes calamity of so long life;
For who would bear the whips and scorns of time,
The oppressor's wrong, the proud man's contumely,
The pangs of dispriz'd love, the law's delay,
The insolence of office and the spurns
That patient merit of the unworthy takes,
When he himself might his quietus make
With a bare bodkin? Who would these fardels bear,
To grunt and sweat under a weary life,
But that the dread of something after death,
The undiscover'd country from whose bourn
No traveller returns, puzzles the will
And makes us rather bear those ills we have
Than fly to others that we know not of?
Thus conscience does make cowards of us all;
And thus the native hue of resolution
Is sicklied o'er with the pale cast of thought,
And enterprises of great pith and moment
With this regard their currents turn away,
And lose the name of action.--Soft you now!
The fair Ophelia! Nymph, in thy orisons
Be all my sins remember'd.

```

# Answer
> 2 votes
## CJam, ~~713~~ 683 characters

We're counting by characters so here's the usual Unicode encoding approach. I'm sure this can be beaten, but at least it's less than half as many characters as the output.

```
"=迗拢쌜僨糌ࢬꭖ杋鏊ꦓ廃啒⼬ᏸꛒ멉尬䳉藋底淡蟖ꣃ⪖恉囻ꮠⶠ榯൨鞺㹑悩眷ဋ㟯ㅕ葡Ż㼡惽Т託⹡嫰뵴䕞凿绸䷛䴽繋㐚挻ᙶ᪻뼶䌼냞ോ貿ꐯ欲鄁卒梷몧臡ꙉꐰ臸惽ệ昣䙍樬ᓜ녖谴鈦⃇炣膊Ე戭⟣䌮ꆰ躍➥կ语鄂셸ⷽⁿ덝곋䚴䚗Ḹ硅㺁餌쀎柁ᛔ礳괰蚴變㿢䅋砤鈴綸䨜᾽㓔䘅䊶䭚⦑럜䧑䔠⳾뇾䴓ꣽ鎋੩呝䓔ᇽἰ䗚笨簛䀣䲮攌꘦↢ኲㄉ⥈䎺韧᭩滥叒㰥ꬔ懭彼垥丼됑艨ᒝ荶뵴枀膛㛏닱関㵃踫⹦瀗媂㴫꺼柝➍ꜙ纫弡ꔕ㦂蹘ꬃ粅ᛧ熄寝㎍衰飔㩏鈅廀裝굗猪맊␰例㘇ꓶ᫋⟗㟔獇⍨ꉔ뵯瓗ℎ岻摔撎偱紁꽓澤䔷刪㒰墄㰑쀨ꦞ沣뤣葇欕鎨빵ဟ赊剡篠壃ఌ忎꺉鴩绘腀뉂每倢觌びው錵ꏅ儅몧瑳갎媢㗿陣欿᫉ꋿ週䰧鉝깊屌軌먝궔꘹ҙ伔肢⨘緍㰑㐩삭善เⴹ뫑勂㣗曝㛊瘐蠚椂ỿꖴ⎫ᶬ鐸它蒗ؑ謅໐뮦ꩇℇ虇ヽ襟餰塹媬蕥偃⒭躧ꩆ꣢麡翲ⷜ緤飆㛉鴳㾂偾ᖈ欍㩻䦛ꄆꏝ꣭䠦᭳㭱囃㣝䥀鿆䴹෽蝩荲輳蓆娠啃帶ᮾᨍ쀶ѱⴣ㻝順᫰掽紈걉壬虾撆Ⅴ軚䀥ᚑF㠡㞮ᨣ溹뷝欬듺㡧玌딿섄ଷ럫㏵椉䴚ጪ⾗瞾䕼效㠐翢Տ须䈲蘸อ괟㿬む攩糼烏뼊ⷫ庁诔뀗瀦䴇鳨匿ò韑祋夯稚骪愫蕁렒蒔룳πབྷℇଉ簿ّ뺦謃刨㫳ᔥ槦ᑃ璽皩宩傜䷗᥁ꊙ庉놨ꠑᯋ撿ᰃ⧹ⷅ瓴눥᮶â䏶뒾ञ代뫵ਫ㙺Ἑధॆ偟끎녘ৈ黗돃Ὄ檮㢈괿哟繹ꈥ垌喞ᘜ齈㒹뭹ᴴ轳浬曥瑾級꫼ᡊᴮ留㝸螱Ḵ嗳汏ᔔ藁嫜≵୛掣Ẁ恪⍩슅手彶䤇萴櫹ວჲ⽢а琨늪ㇲᭈ쇰ӳ㧠㥡놀Ꙭ碐ゼ⎴릊⍢蠐贈㧑请骰곮쀕렳ಊ祟㽖葬汓䢢兘뢺韴泧馆净벏ᵢ䕋僛♃⩖䎹ᑟ㓆虑鈃ڳ눼絇移ꝴ匯䇸㓀♔⳶㓧෴較õ乛ᔫ欚嗶᥄ꈢャ✉Ꝼ拂橳˯㶲ʤ댯ᡃ볿籚䊋釗␶傍궔樥泤趡鮚㺅卫㲴汒穿ⵑ衙ꞅ修쉚皨ƽ┐꣚漛༻ꔤ꾰䖓澐꣗輘醵醸乯ᦳ䕴䛯词麈鏡棧ᚒ᳜朝ꙧꬫ諒㜑瑕⨱㴥뎋面ᬀ滯憮௦庰民눿隆磁꼓詮䡎䵩费㤋腔杦薎㱿ᇆ韗騏⧢盚븎"5e4b128b:c

```

For some reason I end up with a leading `a` after decoding, which I need to remove first.

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


title: Catch some drug dealers

text:
# Question
Title: Catch some drug dealers
**(spoilers on decade-old TV show below)**

In the HBO show "The Wire", the dealers use a system of encoding phone numbers where they "jump the 5" on the number pad.

```
+-----------+
| 1 | 2 | 3 |
+-----------+
| 4 | 5 | 6 |
+-----------+
| 7 | 8 | 9 |
+-----------+
| # | 0 | * |
+-----------+

```

A "1" becomes a "9", "4" becomes "6", etc ... and "5" and "0" swap places. So, the input number 2983794-07 becomes 8127316-53. # and * are undefined. Input in the show was numeric with a dash, your code does not need to preserve the dash but it does need to accept it. No real restrictions on how user interaction is handled, can be a function or console application as needed.

Scoring criteria:

This is a code golf, fewest characters wins. There is a 100 character penalty for solving it with a number/character swap or array lookup (I'm trying to broadly paint a brush stroke to avoid `"9876043215"[i]`-style lookups). 10 character bonus for not stripping dashes.

# Answer
# MATLAB, 25 bytes

Function accepting a string.

`-` is converted to `=`... so the dash is not just preserved, there is twice as much of it?

```
@(n)106-n-5*(n==48|n==53)

```
> 10 votes

# Answer
## tr, 107 (17 + 100 - 10)

```
tr 0-9 5987604321

```
> 9 votes

# Answer
## GolfScript 9 (= 19 - 10)

```
{16|106\-.5%3=5*-}%

```

or

```
{16|~107+.5%3=5*-}%

```

Online demo

### Explanation

As observed by a few people, this calls for subtraction of the digit from 10 in most cases. Since the digits in ASCII start at 48, that means subtracting the ASCII code from `48*2+10 = 106`. That leaves three special cases:

* `0` and `5`: these map to `10` and `5` respectively, and need to map to `5` and `0`. Solution: `.5%3=5*-` subtracts `5` if the result is equal to `3` modulo `5`.
* `-`: this is the fun one. ASCII code `45`, so equivalent to digit `-3`. After the reflection it's equivalent to digit `13`, so I need to subtract `16`. But I can equivalently do that by *adding* `16` before the reflection, and since `45` is the only relevant ASCII code not to have the bit corresponding to `16` set, I can accomplish that with a simple bitwise OR: `16|`.
> 8 votes

# Answer
## JavaScript, ES6, 27 bytes (37 - 10)

```
f=_=>_.replace(/\d/g,y=>y%5?10-y:5-y)

```

Try it in latest Firefox like

```
f("2983794-07")

```
> 6 votes

# Answer
## CJam, 13 (23 - 10) bytes

```
'-_l\/{{si_5%A5?\-}%}%*

```

Try it online here
> 1 votes

# Answer
# C (63 - 10 = 53)

```
main(_){while(_=getchar())putchar(_>47?(_-=48)%5?58-_:53-_:_);}

```
> 0 votes

---
Tags: code-golf
---


# Question
Title: Jumblers vs Rebuilders: Coding with Tetris Bricks - Area for Rebuilder Answers
This is the companion question to Jumblers vs Rebuilders: Coding with Tetris Bricks where Rebuilders can post their solutions.

As argued in Where should we put robbers? it allows more formatting freedom for robbers and lets them gain rep.

Only answer this question if you have cracked a yet uncracked answer to Jumblers vs Rebuilders: Coding with Tetris Bricks. **Please include a link to that answer in your answer *and* a comment in that answer linking to your answer.**

The accepted answer for this question will be the winning rebuilder.

The scoreboard will only appear in the other question.

COTO has generously made a JSFiddle for easily manipulating code-bricks. I've updated this fiddle so ES 6 is not required, and minimized it for this Stack Snippet:

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><script>function parseSpec(s){function first(){var e,t;t=S.findIndex(function(t){return(e=t.findIndex(function(e){return/\S/.test(e)}))!=-1});return t==-1?null:[e,t]}function at(e){var t=e[0],n=e[1];return n>=0&&n<S.length&&t>=0&&t<S[n].length?S[n][t]:" "}function wipe(e){var t=e[0],n=e[1];if(n>=0&&n<S.length&&t>=0&&t<S[n].length)S[n][t]=" "}var P,S=s.split("\n").map(function(e){return e.split("")});var oPats=$(".proto-tet [pat]").get().map(function(e){return{sPat:eval("["+$(e).attr("pat")+"]"),e:e,block:function(e){return[at(e)].concat(this.sPat.map(function(t){return at([e[0]+t[0],e[1]+t[1]])}))},wipe:function(e){this.sPat.forEach(function(e){return wipe([P[0]+e[0],P[1]+e[1]])})},match:function(e){return!/\s/.test(this.block(e).join(""))}}});window.oPats=oPats;while(P=first()){var oPat=oPats.find(function(e){return e.match(P)});if(!oPat){orphan(at(P));wipe(P);continue}createPiece(oPat.e,oPat.block(P));wipe(P);oPat.wipe(P)}}function createPiece(e,t){function r(e){var t=$(this).position();G.isIgnoreClick=false;G.eDrag=this;G.iOffsets=[e.clientX-t.left,e.clientY-t.top]}function i(){if(G.isIgnoreClick)return;var e=$(this);s($(".proto-tet ."+e.attr("rr")),function(e,t){return n[t-1]},e.css("left"),e.css("top"));e.remove()}function s(e,t,n,s){e.clone().html(e.html().replace(/@(\d)(\d)/g,t)).appendTo("body").on("mousedown",r).click(i).css({left:n,top:s})}var n=[];s($(e),function(e,r,i){return n[r-1]=t[i-1]},18+G.iSpawn%8*18*4+"px",18+~~(G.iSpawn/8)*18*4+"px");G.iSpawn++}function init(){$(document).on("mouseup",function(){return G.eDrag=null}).on("mousemove",function(e){if(G.eDrag){var t=$(G.eDrag),n=Math.round((e.clientX-G.iOffsets[0])/18)*18,r=Math.round((e.clientY-G.iOffsets[1])/18)*18,i=t.position();if(n!=i.left||r!=i.top)G.isIgnoreClick=true;t.css({left:n+"px",top:r+"px"})}})}function orphan(e){error("Spec character not a part of any block: '"+e+"'")}function error(e){$(".error").css("display","block").append("<div>"+e+"</div>")}function go(){$(init);$(function(){parseSpec($("#spec").val())});$("#spec").remove();$("#info").remove();$("#go").remove()}var G={eDrag:null,isIgnoreClick:true,iSpawn:0};Array.prototype.findIndex=function(e){for(var t=0;t<this.length;t++){if(e(this[t]))return t}return-1};Array.prototype.find=function(e){var t=this.findIndex(e);if(t==-1)return;else return this[t]}</script><style>.proto-tet, .spec{display: none;}.tet-I{color: darkgreen;}.tet-J{color: orangered;}.tet-L{color: navy;}.tet-T{color: darkred;}.tet-O{color: darkcyan;}.tet-S{color: darkviolet;}.tet-Z{color: darkorange;}body > .tet{position: absolute;cursor: move;-webkit-touch-callout: none;-webkit-user-select: none;-khtml-user-select: none;-moz-user-select: none;-ms-user-select: none;user-select: none;border-collapse: collapse;}.tet td{width: 18px;height: 18px;font: bold 14px "Courier New",monospace;text-align: center;vertical-align: middle;padding: 0;}.error{z-index: 1024;position: absolute;display: none;color: red;font-weight: bold;background-color: white;}textarea{font-family: "Courier New", Courier, monospace;}</style><div id='info'>Put code-bricks here and hit OK. Re-run the snippet to restart.<br>(You may need to replace spaces in code-bricks with some other character first.)</div><textarea id='spec' rows='16' cols='80'>ABCD  a
      b   Oo
      c   oo
      d

 E    h
 F  efg   hg   GFE
 GH        f   H
           e

 I           IJK
 J   l         L
LK   kji  kl
          j
          i
                   t
 OP   p     QR    rs
MN    on     ST   q
       m
 W             z
 XY    zxw    yx     Y
 Z      y      w    WXZ</textarea><br><button id='go' type='button' onclick='go()'>OK</button><div class="proto-tet"><table class="tet tet-I tet-I0" rr="tet-I1" pat="[1,0],[2,0],[3,0]"><tr><td>@11</td><td>@22</td><td>@33</td><td>@44</td></tr></table><table class="tet tet-I tet-I1" rr="tet-I2" pat="[0,1],[0,2],[0,3]"><tr><td>@11</td></tr><tr><td>@22</td></tr><tr><td>@33</td></tr><tr><td>@44</td></tr></table><table class="tet tet-I tet-I2" rr="tet-I3" ><tr><td>@40</td><td>@30</td><td>@20</td><td>@10</td></tr></table><table class="tet tet-I tet-I3" rr="tet-I0"><tr><td>@40</td></tr><tr><td>@30</td></tr><tr><td>@20</td></tr><tr><td>@10</td></tr></table><table class="tet tet-J tet-J0" rr="tet-J1" pat="[0,1],[-1,2],[0,2]"><tr><td></td><td>@11</td></tr><tr><td></td><td>@22</td></tr><tr><td>@33</td><td>@44</td></tr></table><table class="tet tet-J tet-J1" rr="tet-J2" pat="[0,1],[1,1],[2,1]"><tr><td>@31</td><td></td><td></td></tr><tr><td>@42</td><td>@23</td><td>@14</td></tr></table><table class="tet tet-J tet-J2" rr="tet-J3" pat="[1,0],[0,1],[0,2]"><tr><td>@41</td><td>@32</td></tr><tr><td>@23</td><td></td></tr><tr><td>@14</td><td></td></tr></table><table class="tet tet-J tet-J3" rr="tet-J0" pat="[1,0],[2,0],[2,1]"><tr><td>@11</td><td>@22</td><td>@43</td></tr><tr><td></td><td></td><td>@34</td></tr></table><table class="tet tet-O tet-O0" rr="tet-O1" pat="[1,0],[0,1],[1,1]"><tr><td>@11</td><td>@22</td></tr><tr><td>@33</td><td>@44</td></tr></table><table class="tet tet-O tet-O1" rr="tet-O2"><tr><td>@30</td><td>@10</td></tr><tr><td>@40</td><td>@20</td></tr></table><table class="tet tet-O tet-O2" rr="tet-O3"><tr><td>@40</td><td>@30</td></tr><tr><td>@20</td><td>@10</td></tr></table><table class="tet tet-O tet-O3" rr="tet-O0"><tr><td>@20</td><td>@40</td></tr><tr><td>@10</td><td>@30</td></tr></table><table class="tet tet-L tet-L0" rr="tet-L1" pat="[0,1],[0,2],[1,2]"><tr><td>@11</td><td></td></tr><tr><td>@22</td><td></td></tr><tr><td>@33</td><td>@44</td></tr></table><table class="tet tet-L tet-L1" rr="tet-L2" pat="[1,0],[2,0],[0,1]"><tr><td>@31</td><td>@22</td><td>@13</td></tr><tr><td>@44</td><td></td><td></td></tr></table><table class="tet tet-L tet-L2" rr="tet-L3" pat="[1,0],[1,1],[1,2]"><tr><td>@41</td><td>@32</td></tr><tr><td></td><td>@23</td></tr><tr><td></td><td>@14</td></tr></table><table class="tet tet-L tet-L3" rr="tet-L0" pat="[-2,1],[-1,1],[0,1]"><tr><td></td><td></td><td>@41</td></tr><tr><td>@12</td><td>@23</td><td>@34</td></tr></table><table class="tet tet-S tet-S0" rr="tet-S1" pat="[1,0],[-1,1],[0,1]"><tr><td></td><td>@21</td><td>@12</td></tr><tr><td>@43</td><td>@34</td><td></td></tr></table><table class="tet tet-S tet-S1" rr="tet-S2" pat="[0,1],[1,1],[1,2]"><tr><td>@41</td><td></td></tr><tr><td>@32</td><td>@23</td></tr><tr><td></td><td>@14</td></tr></table><table class="tet tet-S tet-S2" rr="tet-S3"><tr><td></td><td>@30</td><td>@40</td></tr><tr><td>@10</td><td>@20</td><td></td></tr></table><table class="tet tet-S tet-S3" rr="tet-S0"><tr><td>@10</td><td></td></tr><tr><td>@20</td><td>@30</td></tr><tr><td></td><td>@40</td></tr></table><table class="tet tet-Z tet-Z0" rr="tet-Z1" pat="[1,0],[1,1],[2,1]"><tr><td>@11</td><td>@22</td><td></td></tr><tr><td></td><td>@33</td><td>@44</td></tr></table><table class="tet tet-Z tet-Z1" rr="tet-Z2" pat="[-1,1],[0,1],[-1,2]"><tr><td></td><td>@11</td></tr><tr><td>@32</td><td>@23</td></tr><tr><td>@44</td><td></td></tr></table><table class="tet tet-Z tet-Z2" rr="tet-Z3"><tr><td>@40</td><td>@30</td><td></td></tr><tr><td></td><td>@20</td><td>@10</td></tr></table><table class="tet tet-Z tet-Z3" rr="tet-Z0"><tr><td></td><td>@40</td></tr><tr><td>@20</td><td>@30</td></tr><tr><td>@10</td><td></td></tr></table><table class="tet tet-T tet-T0" rr="tet-T1" pat="[1,0],[2,0],[1,1]"><tr><td>@11</td><td>@22</td><td>@33</td></tr><tr><td></td><td>@44</td><td></td></tr></table><table class="tet tet-T tet-T1" rr="tet-T2" pat="[-1,1],[0,1],[0,2]"><tr><td></td><td>@11</td></tr><tr><td>@42</td><td>@23</td></tr><tr><td></td><td>@34</td></tr></table><table class="tet tet-T tet-T2" rr="tet-T3" pat="[-1,1],[0,1],[1,1]"><tr><td></td><td>@41</td><td></td></tr><tr><td>@32</td><td>@23</td><td>@14</td></tr></table><table class="tet tet-T tet-T3" rr="tet-T0" pat="[0,1],[1,1],[0,2]"><tr><td>@31</td><td></td></tr><tr><td>@22</td><td>@43</td></tr><tr><td>@14</td><td></td></tr></table></div><div class="error"></div>
```

# Answer
> 9 votes
# Crack of xnor's 340-area answer

No cryptographic mumbo-jumbo for me.

**Code:**

```
10000001111111222
22388892357889356
69968999352143221
80867227952780811
a=23333333444444
b=71122368066667
c=47948316823798
d=79254432699451
496857235742
579159386011
606961806231
pow(a,b,c)-d
62656269644465648
67766884711672530
73487440752777431
print('Tetris'*(1
))
7873806482918808
8843930593249458
946095869869

```

**Mapping of blocks to line numbers**

```
    #Four spaces 9-12
    #Four spaces 9-12
    #Four spaces 9-12
    #Four spaces 9-12
    #Four spaces 17
    #Four spaces 17
    #Four spaces 17
    #Four spaces 17-20
    #Four spaces 5-8
))  #Two spaces 17
0290 1-4
0398 1-4
0866 1-4
0887 1-4
0892 1-4
0992 1-4
1108 13-16
1268 1-4
1297 1-4
1339 1-4
1555 1-4
1722 1-4
1817 1-4
1848 1-4
1930 1-4
2328 1-4
2521 1-4
2611 1-4
2747 5-8
3179 5-8
3192 5-8
3245 5-8
3284 5-8
3334 5-8
3613 5-8
3862 5-8
4086 5-8
4629 5-8
4639 5-8
4674 5-8
4695 5-8
4781 5-8
4968 9
5723 9
5742 9
5791 10
5938 10
6011 10
6069 11
6180 11
6231 11
6265 13
6269 13
6444 13
6564 13
6776 14
6884 14
7116 14
7253 14
7348 15
7440 15
7527 15
7743 15
7873 17
8064 17
8291 17
8808 17
8843 18
9305 18
9324 18
9458 18
9460 19
9586 19
9869 19
==== 5-8
a,b, 12
abcd 5-8
c)-d 12
etri 16
pow( 12
prin 16
s'*( 16
t('T 16
four spaces  9-12
four spaces  20

```

# Answer
> 6 votes
**Solution to xnor's 212 area puzzle**

```
print('Tetris'* (3580048039607960824098110131314133014381502228523172479258529553116373838184169435643604632480050165153525653945598563157585840631264256539704571638903974876749009825073297156762481649%38941394))

```

# Answer
> 6 votes
# Teromino Sandbox

While not a solution ipso facto, I wanted to share this online tool I put together with other potential rebuilders. It facilitates quick and error-free manipulation of the "code tetrominos".

The shapes are specified using a simple character grid in the `spec` element. Most answers should be a simple copy/paste off of PPCG. The default shape spec provides numerous examples. I've also included the shape specs for my C-72 answer.

Two caveats:

1. the specs are whitespace-sensitive
2. some HTML control characters may need to be escaped

The pieces are shown in different colours. Drag them to move them, and click them to rotate them. Easy peasy.

Anyone who wants to add improvements, add new specs, fix bugs, etc., is welcome to fork the fiddle and edit this answer to provide an updated link.

Happy rebuilding. :)

# Answer
> 5 votes
# Solution to es1024's 80 area answer

```
main(q){char c[]
={'/T','$"e','t'
,0162,'rIi>`:i',
'?#>s',q<q/**/};
return puts(c);}

```

# Answer
> 4 votes
## Solution to Gerli's 72 area submission

```
FromCharacterCode[
 {8*10+4, 10*10+1,
 100+16, 10*10+14,
 105, 115}]//Print

```

There's a mistake in the submission though. In the third `T` block, Gerli "rotated" the `[` and `{` when rotating the block.

All done by hand. The `Print` was quite easy to find. Then I wrote out the remaining letters, and found them to be an anagram of `FromCharacterCode`. That put a lot of restrictions on the maximum code height and most blocks. Since there was no `@` and only one pair of brackets, that gave away that `Print` was applied using suffix notation (which determined both its position and that it's preceded by the `//`. In the end there were only an `S` and two `T`s left. The `S` was forced by the layout and the first assignment of `T`s I tried worked.

---
Tags: cops-and-robbers
---


title: Book Stack Sort

text:
# Question
Title: Book Stack Sort
When stacking books you usually want to put the largest ones at the bottom and the smallest ones at the top. However, my latent OCD makes me feel very uneasy if I've got two books where one is shorter (in height) but wider than the other. No matter which order I place them in, the top book will extend beyond the bottom book on one side.

As an example, say one book has dimensions `(10,15)` and another has dimensions `(11,14)`. No matter which way around I put them, I get an overhang. But if I have books with dimensions `(4,3)` and `(5,6)`, I can avoid an overhanging by placing the latter below the former.

For the purposes of this challenge we will consider overhangs only in relation to the book *immediately below*. E.g. if I have a stack `(5,5)`, `(3,3)`, `(4,4)` (not that any sane person would do that), the top book counts as an overhang, although it does not extend beyond the bottom book. Similarly, the stack `(3,3)`, `(3,3)`, `(4,4)` also has only one overhang, despite the top book extending beyond the bottom one.

## The Challenge

Given a list of integer pairs for book dimensions, sort those pairs/books such that the number of overhangs is minimal. You must not rotate the books - I want all the spines facing the same direction. If there are multiple solutions with the same number of overhangs, you may choose any such order. Your sorting algorithm does not have to be stable. Your implementation may assume that book dimensions are less than 216 each.

**Time complexity:** To make this a bit more interesting, the asymptotic worst-case complexity of your algorithm must be polynomial in the size of the stack. So you can't just test every possible permutation. Please include a short proof of your algorithm's optimality and complexity and optionally a plot that shows the scaling for large random inputs. Of course, you can't use the maximum size of the input as argument that your code runs in O(1).

You may write a program or function, take input via STDIN, ARGV or function argument in any convenient (not preprocessed) list format and either print or return the result.

This is code golf, so the shortest answer (in bytes) wins.

I am confident that a polynomial-solution exists, but if you can prove me wrong, you may submit such a proof instead of a golfed submission. In this case, you may assume P ≠ NP. I will accept the first correct such proof and award a bounty to it.

## Examples

```
In:  [[1, 1], [10, 10], [4, 5], [7, 5], [7, 7], [10, 10], [9, 8], [7, 5], [7, 5], [3, 1]]
Out: [[10, 10], [10, 10], [9, 8], [7, 7], [7, 5], [7, 5], [7, 5], [4, 5], [3, 1], [1, 1]]

In:  [[4, 5], [5, 4], [5, 4], [5, 4], [5, 4], [4, 5], [4, 5], [4, 5], [5, 4], [4, 5]]
Out: [[4, 5], [4, 5], [4, 5], [4, 5], [4, 5], [5, 4], [5, 4], [5, 4], [5, 4], [5, 4]]
  or [[5, 4], [5, 4], [5, 4], [5, 4], [5, 4], [4, 5], [4, 5], [4, 5], [4, 5], [4, 5]]

In:  [[2, 3], [1, 1], [5, 5], [7, 1]]
Out: [[5, 5], [2, 3], [7, 1], [1, 1]]
 or  [[5, 5], [2, 3], [1, 1], [7, 1]]
 or  [[7, 1], [5, 5], [2, 3], [1, 1]]
 or  [[7, 1], [1, 1], [5, 5], [2, 3]]

```

I created these by hand, so let me know if you spot any mistakes.

# Answer
> 2 votes
# Pyth, 30

```
FN_SQFbYIgeeYeb~b]NB)E~Y]]N;sY

```

This is a direct golf of grc's awesome algorithm. Here is the precise equivalent of the above pyth program, in its compiled python code.

```
Q = eval(input())
Y = []
for N in sorted(Q)[::-1]:
     for b in Y:
         if Y[-1][-1] >= b[-1]:
             b += [N]
             break
     else:
         Y += [[N]]
print(Psum(Y))

```

In this context, the `Psum(Y)` function is equivalent to the python `sum(Y,[])`.

Actual compiled and run code (from `pyth -d`):

```
Y=[]
Q=copy(eval(input()))
for N in neg(Psorted(Q)):
 for b in Y:
  if gte(end(end(Y)),end(b)):
   b+=[N]
   break
 else:
  Y+=[[N]]
Pprint("\n",Psum(Y))

```

# Answer
> 21 votes
## Python, 113

```
P=[]
for n in sorted(input())[::-1]:
 for p in P:
  if p[-1][1]>=n[1]:p+=[n];break
 else:P+=[[n]]
print sum(P,[])

```

After sorting the list of books in descending order (by width first and then height), this partitions the books into piles without overlaps. To determine where to place each book, its height is compared with the height of the top book in each pile. It is placed on the first pile possible, or else a new pile is created.

I'm not very good with time complexity, but I believe it would have a worst case of *O*(*N2*). There are two loops, each with at most *N* iterations. I also use Python's builtin sort, which is *O*(*n* log *n*).

---

My first proof that this algorithm produces optimal solutions did turn out to be incorrect. A huge thanks goes to @xnor and @Sp3000 for a great discussion in the chat about proving this (which you can read starting here). After working out a correct proof, @xnor found that part of it had already been done (Dilworth's theorem).

Here's an overview of the proof anyway (credit to @xnor and @Sp3000).

First, we define the notion of an antipile, or antichain, (quoted from @xnor):

> An antipile is a sequence of books of decreasing height, but increasing width
> So, each successive book is strictly taller but strictly less wide
> Note that any book in an antipile overhangs over any other book in an antipile
> So, no two books within an antipile can be in the same pile
> As a consequence, if you can find an antipile of x books, then those books must be in different piles
> So, the size of the largest antipile is a lower bound on the number of piles

Then, we sort the books in descending order by their width (first) and their height (second)\*.

For each book *B*, we do as follows:

1. If *B* can fit on the first pile, we place it there and move on.
2. Otherwise, we find the earliest\* pile *x* which *B* can be placed on top of. This can be a new pile if necessary.
3. Next, we link *B* to *P*, where *P* is the top book on the previous pile *x - 1*.
4. We now know that:
    * *B* is strictly\* smaller in width than *P*, since the books are sorted in descending order by width
    * *B* is strictly greater in height than *P*, or we would have placed *B* on top of *P*

Now, we have constructed a link from every book (except those in the first pile), to a book in the previous pile that is greater in width and lower in height.

@Sp3000's excellent diagram illustrates this well:

By following any path from the last pile (on the right), to the first pile (on the left), we get an antipile. Importantly, this antipile's length is equal to the number of piles. Hence, the number of piles used is minimal.

Finally, since we have organised the books into the minimum number of piles without overlaps, we can stack them on top of each other to get one pile with the minimum number of overlaps.

* this helpful comment explains a few things

---
Tags: code-golf, array, sorting, restricted-complexity
---


title: Are you in the biggest room?

text:
# Question
Title: Are you in the biggest room?
## Introduction

You have recently accepted a job offer at a Pretty Good Software Company. You're pretty content with the size of your office, but do you have the **biggest** office? Its kinda hard to tell from just eyeballing your co-workers' offices when you stop by. The only way to figure this out is to examine the blueprints for the building...

## Your Task

Write a program, script, or function that takes a floor plan for your building and indicates whether your office is the largest. The floor plan is easy to read because the building is an *n* by *n* square.

The input will consist of *n+1* `\n`-delimited lines. The first line will have the number *n* on it. The next *n* lines will be the floorplan for the building. A simple example input:

```
6
......
.  . .
.X . .
.  . .
.  . .
......

```

The rules for the floorplan are as follows:

* `.` (ASCII 46) Will be used to represent walls.  (Space \[ASCII 32\]) will be used to represent open space.
* You are represented by an `X` (ASCII 88). You are in your office.
* The floorplan will be *n* lines, each with *n* characters.
* The building is totally surrounded by walls on all sides. This implies that the 2nd line of input (the first line of the floorplan) and the last line of input will be all `.`s. It also implies that the first and last characters of every floorplan line will be `.`s.
* An office size is defined as the sum of adjacent spaces (contiguous by moving in 4 directions, N, S, E, W, without going through a wall).
* For the purpose of office size, the X representing you counts as a  (open space)
* 4 \<= *n* \<= 80

You should output whether or not your office is strictly bigger than all the other offices. The output can be anything that unambiguously signifies True or False in your programming language of choice and adheres to standard conventions of zero, null, and empty signifying False. True implies your office is strictly the biggest.

Sample output for above input:

```
1

```

Because your office is 8 square feet, and the only other office is 4 square feet.

## I/O Guidelines

* The input may be read from stdin, and answer output to stdout.

Or

* The input may be a single string argument to a function, and answer be the return value of that function.

## FAQ

* The entire building consists of walls and offices.
* The building is only one floor
* There is guaranteed to be an X in the input, but there are not guaranteed to be any spaces. You could have a 1x1 office and the rest of the building is walls (You have the biggest office! hooray!).

### Other Example

```
10
..........
.   .  . .
.  .   . .
.  .   . .
. ..   . .
..       .
..........
.      X .
.        .
..........

```

Here there are 3 offices, your south office is rectangular, the northwest office is a triangle(ish) and the northeast office is strangely misshapen, yet bigger than yours. The output should be False.

This is a challenge to write the shortest code, happy ing!

# Answer
## Ruby 2.0, 133 characters

A collaboration with @Ventero. Always a good sign when it starts breaking the syntax highlighter!

This is a recursive flood-fill solution. Reads from STDIN and outputs to STDOUT:

```
f=->*a{a.product([~n=$_.to_i,-1,1,n+1]){|p,d|a|=[p]if$_[p+=d]<?.}!=a ?f[*a]:a.size}
gets(p).scan(/ /){$*<<f[$`.size]}
p$*.max<f[~/X/]

```

See it running on Ideone.
> 11 votes

# Answer
## GolfScript (85 bytes)

```
n/(~.*:N:^;{{5%[0.^(:^N]=}/]}%{{{.2$*!!{[\]$-1=.}*}*]}%zip}N*[]*0-:A{.N=A@-,2*+}$0=N=

```

Online demo

This has three sections:

1. An initial input transformation which produces a 2D array using `0` to represent a wall, `N` (the total number of cells) to represent my starting position, and a distinct number between those for each other open space.

```
n/(~.*:N:^;{{5%[0.^(:^N]=}/]}%

```
2. A flood-fill.

```
{{{.2$*!!{[\]$-1=.}*}*]}%zip}N*

```
3. The final counting. This uses a variant on the tip for most common element in an array, adding a tie-breaker which biases against `N`.

```
[]*0-:A{.N=A@-,2*+}$0=N=

```
> 7 votes

# Answer
# Javascript (E6) 155 ~~292~~

```
F=(a,n=parseInt(a)+1,x,y)=>[...a].map((t,p,b,e=0,f=p=>b[p]==' '|(b[p]=='X'&&(e=1))&&(b[p]=1,1+f(p+n)+f(p-n)+f(p+1)+f(p-1)))=>(t=f(p))&&e?y=t:t<x?0:x=t)|y>x

```

**Ungolfed base version**

```
F=a=>
{
  var k, max=0, my=0, k=1, t, n = parseInt(a)+1;
  [...a].forEach(
    (e,p,b) =>
    {
       x=0;
       F=p=>
       {
          var r = 1;
          if (b[p] == 'X') x = 1;
          else if (b[p] != ' ') return 0;
          b[p] = k;
          [n,1,-n,-1].forEach(q => r+=F(q+p));
          return r;
       }
       t = F(p);
       if (t) {
          if (x) my = t;
          if (t > max) max = t;
          k++;
          console.log(b.join(''));
       }
    }
  )
  return my >= max
}

```

**Test**

Javascript console in firefox

`F('6\n......\n. . .\n.X . .\n. . .\n. . .\n......')`

```
1

```

`F('10\n..........\n. . . .\n. . . .\n. . . .\n. .. . .\n.. .\n..........\n. X .\n. .\n..........\n')`

```
0

```
> 3 votes

# Answer
### C#, ~~444~~ 372/(342 thanks HackerCow)bytes

Rather poor score and late to the party, but seems to work. Outputs 1 when you have the single biggest office, 0 when you do not. I've not been very intricate with the golfing yet. Works by building up disjoint sets from the input (first loop), tallying the size of each set (second loop) and then looking to see if my set is the largest (third loop).

Two versions are provided, one is a compilable program tat accepts the input from the command line, the other is just a function that expects a string as input and returns an int as the result (and is just a reworked copy of the first) - it does not need any using clauses or the like, should be able to put it anywhere and it will work.

Program *372bytes*:

```
using System;class P{static void Main(){int s=int.Parse(Console.ReadLine()),e=0,d=s*s,a=d;int[]t=new int[d],r=new int[d];Func<int,int>T=null,k=v=>t[T(v)]=t[v]>0?a:0;T=v=>t[v]!=v?T(t[v]):v;for(;a>0;)foreach(var m in Console.ReadLine()){a--;if(m!=46){t[a]=a;e=m>46?a:e;k(a+s);k(a+1);}}for(a=d;a-->2;)r[T(a)]++;for(;d-->1;)a=d!=T(e)&&r[d]>=r[T(e)]?0:a;Console.WriteLine(a);}}

```

Function *342bytes*:

```
static int F(string g){var b=g.Split('\n');int s=int.Parse(b[0]),e=0,d=s*s,a=d;int[]t=new int[d],r=new int[d];System.Func<int,int>T=null,k=v=>t[T(v)]=t[v]>0?a:0;T=v=>t[v]!=v?T(t[v]):v;for(;a>0;)foreach(var m in b[a/s]){a--;if(m!=46){t[a]=a;e=m>46?a:e;k(a+s);k(a+1);}}for(a=d;a-->2;)r[T(a)]++;for(;d-->1;)a=d!=T(e)&&r[d]>=r[T(e)]?0:a;return a;

```

Less golfed:

```
using System;

class P
{
    static int F(string g)
    {
        var b=g.Split('\n');
        int s=int.Parse(b[0]),e=0,d=s*s,a=d;
        int[]t=new int[d],r=new int[d];
        System.Func<int,int>T=null,k=v=>t[T(v)]=t[v]>0?a:0;
        T=v=>t[v]!=v?T(t[v]):v;

        for(;a>0;)
            foreach(var m in b[a/s])
            {
                a--;
                if(m!=46)
                {
                    t[a]=a;
                    e=m>46?a:e;
                    k(a+s);
                    k(a+1);
                }
            }
        for(a=d;a-->2;)
            r[T(a)]++;
        for(;d-->1;)
            a=d!=T(e)&&r[d]>=r[T(e)]?0:a;
        return a;
    }

    static void Main()
    {
        /* F() test
        var s=Console.ReadLine();
        int i=int.Parse(s);
        for(;i-->0;)
        {
            s+="\n"+Console.ReadLine();
        }
        Console.WriteLine(F(s));*/

        int s=int.Parse(Console.ReadLine()),e=0,d=s*s,a=d;
        int[]t=new int[d],r=new int[d];
        Func<int,int>T=null,k=v=>t[T(v)]=t[v]>0?a:0;
        T=v=>t[v]!=v?T(t[v]):v;

        for(;a>0;)
            foreach(var m in Console.ReadLine())
            {
                a--;
                if(m!=46)
                {
                    t[a]=a;
                    e=m>46?a:e;
                    k(a+s);
                    k(a+1);
                }
            }
        for(a=d;a-->2;)
            r[T(a)]++;
        for(;d-->1;)
            a=d!=T(e)&&r[d]>=r[T(e)]?0:a;
        Console.WriteLine(a);
    }
}

```
> 3 votes

# Answer
## CJam, 106 bytes

A different approach to flood fill. Although, makes it longer ...

```
liqN-'Xs0aer\_:L*{_A=' ={[AAL-A(]1$f=$:D1=Sc<{D2<(aer}*D0=_' ={T):T}@?A\t}*}fAT),\f{\a/,}_$W%_2<~>@@0=#0=&

```

Try it here
> 2 votes

# Answer
# Python 2 - 258 bytes

```
r=range;h=input();m="".join(raw_input()for x in r(h))
w=len(m)/h;n=0;f=[x!='.'for x in m]
for i in r(w*h):
 if f[i]:
    a=[i];M=s=0
    while a:
     i=a.pop();s+=1;M|=m[i]=='X';f[i]=0
     for j in(i-1,i+1,i-w,i+w):a+=[[],[j]][f[j]]
    n=max(s,n)
    if M:A=s
print A==n

```

uses stdin for input

Note: first `if` is indented by a single space, other indented lines are either using a single tab char or a tab and a space.
> 2 votes

# Answer
## J : 150 121 bytes

```
(({~[:($<@#:I.@,)p=1:)=([:({.@#~(=>./))/@|:@}.({.,#)/.~@,))(>./**@{.)@(((,|."1)0,.0 _1 1)&|.)^:_[(*i.@:$)2>p=:' X'i.];._2

```

*Edit*: `id` and `comp` were ridiculously complicated and slow. Now it works shifting the map 4 times, instead of scanning it with a 3x3 window using `cut` (`;.`).

Takes as argument the blueprint as string. Explained below:

```
    s =: 0 :0
..........
.   .  . .
.  .   . .
.  .   . .
. ..   . .
..       .
..........
.      X .
.        .
..........
)
p=:' X' i. ];._2 s                NB. 0 where space, 1 where X, 2 where wall
id=:*i.@:$2>p                     NB. Give indices (>0) to each space
comp =: (>./ * *@{.)@shift^:_@id  NB. 4 connected neighbor using shift
  shift =: ((,|."1)0,.0 _1 1)&|.  NB. generate 4 shifts
size=:|:}.({.,#)/.~ , comp        NB. compute sizes of all components
NB. (consider that wall is always the first, so ditch the wall surface with }.)
NB. is the component where X is the one with the maximal size?
i=: $<@#:I.@,                     NB. find index where argument is 1
(comp {~ i p=1:) = {.((=>./)@{: # {.) size

NB. golfed:
(({~[:($<@#:I.@,)p=1:)=([:({.@#~(=>./))/@|:@}.({.,#)/.~@,))(>./**@{.)@(((,|."1)0,.0 _1 1)&|.)^:_[(*i.@:$)2>p=:' X'i.];._2 s
0

```
> 1 votes

# Answer
# Python 2 - 378 bytes

*Wow.* I'm out of practice.

```
def t(l,x,y,m,c=' '):
 if l[y][x]==c:l[y][x]=m;l=t(l,x-1,y,m);l=t(l,x+1,y,m);l=t(l,x,y-1,m);l=t(l,x,y+1,m)
 return l
def f(s):
 l=s.split('\n');r=range(int(l.pop(0)));l=map(list,l);n=1
 for y in r:
    for x in r:l=t(l,x,y,*'0X')
 for y in r:
  for x in r:
    if l[y][x]==' ':l=t(l,x,y,`n`);n+=1
 u=sum(l,[]).count;o=sorted(map(u,map(str,range(n))));return n<2or u('0')==o[-1]!=o[-2]

```

This is a function answer, but it pollutes the global namespace. If this is unacceptable, it can be fixed at the cost of 1 byte:

* Add a space to the beginning of line 1 (+1)
* Replace the space at the beginning of lines 2 and 3 with a tab character (+0)
* Move line 4 to the beginning (+0)

I had a whole long explanation written out, but apparently it didn't save properly and I'm not doing that again l m a o
> 0 votes

---
Tags: code-golf, graph-theory, grid
---


title: Circle packing in a rectangle

text:
# Question
Title: Circle packing in a rectangle
Your task is to write a program that finds the largest radius that *N* circles can have and still fit inside of a rectangle that is X by Y pixels large. (similar to this wikipedia article) Your program must find the largest possible radius and optimal position of these *N* circles so that

1. No two circles overlap
2. All of the circles fit inside of the rectangle.

Your program should then print this to the console:

```
Highest possible radius: <some_number>
Circle 1 Focus: (x, y)
Circle 2 Focus: (x, y)
...
Circle N-1 Focus: (x, y)
Circle N Focus: (x, y)

```

(Obviously, you must replace some\_number with the radius your program calculates, N with the number of circles you end up using, and x and y with the actual coordinates of the circle)

Lastly, it should create and save a picture with these circles drawn.

# Rules:

1. This program must run with any size of rectangle, and any number of circles and still get a valid answer. You can use command line arguments, user input, hard coded variables, or anything else you want.
2. If any circle overlaps or does not fit entirely inside of the box, your submission is invalid.
3. Each circle must have the same radius.
4. Just to make this reasonable and do-able, all numbers must be precise to the 2nd decimal place.

This is code golf, so shortest program (as of 10/28/2014) wins.

# Answer
# JavaScript 782 725 characters

*first post, be gentle!*

The program is now called via the wrapped function. Eg: `(function(e,f,g){...})(100,200,10)`.

```
function C(e,f,g,c,a,d){if(0>g-a||g+a>e||0>c-a||c+a>f)return d;for(var b in d)if(Math.sqrt(Math.pow(d[b].x-g,2)+Math.pow(d[b].y-c,2))<2*a)return d;d.push({x:g,y:c});for(b=0;b<Math.PI;)XX=Math.cos(b)*a*2+g,YY=Math.sin(b)*a*2+c,d=C(e,f,XX,YY,a,d),b+=.01;return d}
(function(e,f,g){var c=e+f,a,d;for(a=[];a.length<g;)a=d=c,a=C(e,f,a,d,c,[]),c-=.01;console.log("Highest possible radius: "+Math.round(100*c)/100);e='<svg width="'+e+'" height="'+f+'"><rect width="'+e+'" height="'+f+'" style="fill:red" />';for(var b in a)console.log("Circle "+b+" Focus: ("+Math.round(100*a[b].x)/100+", "+Math.round(100*a[b].y)/100+")"),e+='<circle cx="'+a[b].x+'" cy="'+a[b].y+'" r="'+c+'" fill="blue" />';console.log(e+"</svg>")})(400,300,13);

```

## Test 1

`(function(e,f,g){...})(200,200,4)`

```
Highest possible radius: 49.96
Circle 1 Focus: (49.97, 49.97)
Circle 2 Focus: (149.91, 49.97)
Circle 3 Focus: (149.99, 149.91)
Circle 4 Focus: (50.05, 149.91)
<svg width="200" height="200"><rect width="200" height="200" style="fill:blue;" /><circle cx="49.97000000021743" cy="49.97000000021743" r="49.960000000217434" fill="white" /><circle cx="149.9100000006523" cy="49.97000000021743" r="49.960000000217434" fill="white" /><circle cx="149.98958489212322" cy="149.90996831285986" r="49.960000000217434" fill="white" /><circle cx="50.04958489168835" cy="149.90996831285986" r="49.960000000217434" fill="white" /></svg>

```

Obviously we would expect the radius to be exactly 50, but for reasons discussed in the question's comments, I couldn't reasonably make it happen. The SVG looks like this...

## Test 2

`(function(e,f,g){...})(100,400,14)`

```
Highest possible radius: 26.55
Circle 1 Focus: (26.56, 26.56)
Circle 2 Focus: (79.68, 26.56)
Circle 3 Focus: (132.8, 26.56)
Circle 4 Focus: (185.92, 26.56)
Circle 5 Focus: (239.04, 26.56)
Circle 6 Focus: (292.16, 26.56)
Circle 7 Focus: (345.28, 26.56)
Circle 8 Focus: (372.63, 72.1)
Circle 9 Focus: (319.52, 73.25)
Circle 10 Focus: (265.47, 72.64)
Circle 11 Focus: (212.35, 73.25)
Circle 12 Focus: (159.23, 72.64)
Circle 13 Focus: (106.11, 73.25)
Circle 14 Focus: (52.99, 72.64)
<svg width="400" height="100"><rect width="400" height="100" style="fill:blue;" /><circle cx="26.560000000311106" cy="26.560000000311106" r="26.550000000311105" fill="white" /><circle cx="79.68000000093332" cy="26.560000000311106" r="26.550000000311105" fill="white" /><circle cx="132.80000000155553" cy="26.560000000311106" r="26.550000000311105" fill="white" /><circle cx="185.92000000217774" cy="26.560000000311106" r="26.550000000311105" fill="white" /><circle cx="239.04000000279996" cy="26.560000000311106" r="26.550000000311105" fill="white" /><circle cx="292.16000000342217" cy="26.560000000311106" r="26.550000000311105" fill="white" /><circle cx="345.2800000040444" cy="26.560000000311106" r="26.550000000311105" fill="white" /><circle cx="372.6271770491687" cy="72.09972230654316" r="26.550000000311105" fill="white" /><circle cx="319.5195599732359" cy="73.24663493712801" r="26.550000000311105" fill="white" /><circle cx="265.47097406711805" cy="72.63752174440503" r="26.550000000311105" fill="white" /><circle cx="212.35454341475625" cy="73.25330971030218" r="26.550000000311105" fill="white" /><circle cx="159.23097406587362" cy="72.63752174440503" r="26.550000000311105" fill="white" /><circle cx="106.11454341351183" cy="73.25330971030218" r="26.550000000311105" fill="white" /><circle cx="52.99097406462921" cy="72.63752174440503" r="26.550000000311105" fill="white" /></svg>

```

And the SVG looks like this...

## Test 3

`(function(e,f,g){...})(400,400,3)`

```
Highest possible radius: 101.68
Circle 1 Focus: (101.69, 101.69)
Circle 2 Focus: (298.23, 153.98)
Circle 3 Focus: (154.13, 298.19)
<svg width="400" height="400"><rect width="400" height="400" style="fill:blue;" /><circle cx="101.69000000059772" cy="101.69000000059772" r="101.68000000059772" fill="white" /><circle cx="298.2343937547503" cy="153.97504264473156" r="101.68000000059772" fill="white" /><circle cx="154.13153961740014" cy="298.19269546075066" r="101.68000000059772" fill="white" /></svg>

```

And the SVG looks like this...

They aren't all pretty.

## How it works

Ungolfed code below. This program has two assumptions:

1. One circle will always be in the corner. This seems like a pretty safe bet.
2. Every circle will always be touching another circle. I don't see why they wouldn't be.

The program starts by calculating a large radius based on the box dimensions. It then tries to fit one circle in the corner of the box. If that circle fits, it extends a diameter line from that circle and tries to create a circle at the end of the line. If the new circle fits, another line will be extended from the new circle. If it doesn't fit, the line will swing 360 degrees, checking for open spaces. If the box fills up before the desired number of circles are created, the radius is reduced and it all starts over again.

## Ungolfed Code (snippet)

```
// this functions attempts to build a circle
// at the given coords. If it works, it will
// spawn additional circles.
function C(x, y, X, Y, r, cc){

 // if this circle does not fit in the rectangle, BAIL
 if(X-r < 0 || X+r > x || Y-r < 0 || Y+r > y)
  return cc;

 // if this circle is too close to another circle, BAIL
 for(var c in cc){
  if( Math.sqrt(Math.pow(cc[c].x - X, 2) + Math.pow(cc[c].y - Y, 2)) < (r*2) )
   return cc;
 }

 // checks passed so lets call this circle valid and add it to stack
 cc.push({"x": X, "y": Y});

 // now rotate to try to find additional spots for circles
 var a = 0; // radian for rotation
 while(a < Math.PI){
  XX = Math.cos(a)*r*2 + X;
  YY = Math.sin(a)*r*2 + Y;
  cc = C(x, y, XX, YY, r, cc);
  a += .01; // CHANGE FOR MORE OR LESS PRECISION
 }

 return cc;
}

// this function slowly reduces the radius
// and checks for correct solutions
// also prints svg graphic code

(function B(x, y, n){

 var r = x + y; // pick a big radius
 var X, Y; // these are the coords of the current circle. golf by combining this with `var r..`?
 var cc = []; // array of coordinates of the circles

 // while we cant fit n circles, reduce the radius and try again
 while(cc.length < n){
  X = Y = r;
  cc = C(x, y, X, Y, r, []);
  r-=.01; // CHANGE FOR MORE OR LESS PRECISION
 }

 console.log('Highest possible radius: ' + Math.round(r*100)/100);
 var s = '<svg width="' + x + '" height="' + y + '"><rect width="' + x + '" height="' + y + '" style="fill:red" />';
 for(var c in cc){
  console.log('Circle '+c+' Focus: (' + Math.round(cc[c].x*100)/100 + ', ' + Math.round(cc[c].y*100)/100 + ')');
  s += '<circle cx="' + cc[c].x + '" cy="' + cc[c].y + '" r="' + r + '" fill="blue" />';
 }
 s += '</svg>';
 console.log(s);
 document.write(s);
})(150, 150, 5);
```
> 9 votes

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


title: Old MacDonald function

text:
# Question
Title: Old MacDonald function
Create a function in your chosen language that prints out the following:

```
Old MacDonald had a farm, E-I-E-I-O,
And on that farm he had a cow, E-I-E-I-O,
With a moo moo here and a moo moo there,
Here a moo, there a moo, everywhere a moo moo,
Old MacDonald had a farm, E-I-E-I-O!

```

Where `cow` and `moo` are strings in the function parameters, and as such, can be changed to `pig` and `oink` or `sheep` and `baa`, for example.

It should take into account capital letters, hyphens, punctuation, spaces and line breaks.

Aim to type the fewest amount of Unicode characters in your code.

# Answer
# Javascript ES6 - 204

> Aim to type the fewest amount of **Unicode** characters in your code.

Not the shorter but probably the most obfuscated.

```
f=(a,b)=>{for(c=[b,a].concat('!,-ADEHIMOWacdefhilmnortvwy \n'.split(o='')),i=62;i;o+=c[e>>10]+c[e/32&31]+c[e&31])e='ⱞᄤ⒇瓤抣瘭㾭癍㚏᫶⦮函࿋Π疽䌐獲樘ྰ㞠戝晐}疽䌐࿈䌐眲Π疽㛏戝癐Π疽伲࿌⒋ფᲉѽ疽䦯䨝抽瘭䦹容㾷碶ᅣᲉᄤྦྷ㜕㞱㗽㾲妴㣗畍⺏'.charCodeAt(--i);alert(o)}

```

If your browser do not support ES6 :

```
function f(a,b){for(c=[b,a].concat('!,-ADEHIMOWacdefhilmnortvwy \n'.split(o='')),i=62;i;o+=c[e>>10]+c[e/32&31]+c[e&31])e='ⱞᄤ⒇瓤抣瘭㾭癍㚏᫶⦮函࿋Π疽䌐獲樘ྰ㞠戝晐}疽䌐࿈䌐眲Π疽㛏戝癐Π疽伲࿌⒋ფᲉѽ疽䦯䨝抽瘭䦹容㾷碶ᅣᲉᄤྦྷ㜕㞱㗽㾲妴㣗畍⺏'.charCodeAt(--i);alert(o)}

```

Copy/Paste that code into your browser console and try `f('cow','moo')`, `f('pig','oink')`, `f('sheep','baa')`

## How it works ?

`c` is an array of 29 *letters* plus the animal and its sound (let call this our *alphabet*).
So, all the 31 *characters* fit in 5 bits (2^5 = 32).
A Unicode character is 16 bits long, so it can encode 3 characters of our *alphabet* with a padding bit.
The full text with the new lines is 186 characters of our *alphabet*, it can be encoded with 62 Unicode characters.

For example, `Old` is encoded like this :

```
alphabet value         O      l      d
alphabet index         11     20     15
unicode           0  01011  10100  01111  ===> \u2e8f (⺏)

```

If you have troubles to read some Unicode chars, install Code2000 font
> 16 votes

# Answer
# CJam - 142 / GolfScript - 144

```
{" had| a |farm|68, |68 8|here|Old MacDonald765|, E-I-E-I-O|10,
And on that 5 he7690,
With3 2 and3 t2,
Here4t24everyw23,
10!"'|/~A,{`/\*}/}:F;

```

Usage: `"cow""moo"F`
For GolfScript replace `'|` with `"|"` and `A` with `10`

**Explanation:**

The key part is `A,{`/\*}/`:
`A,{...}/` executes the block for each number from 0 to 9 (A=10)
``` converts the number to string
`/\*` does a string replace: if we have on the stack `"bar" "foo 1 baz" "1"` then `/` splits the string resulting in `["foo " " baz"]`, `\` swaps this array with the previous item ("bar") and `*` joins the array resulting in `"foo bar baz"`

So the code replaces each number in the main string with a string that's previously on the stack. We have the animal and the sound, then " had", " a ", etc and finally ", E-I-E-I-O" and the main string, "10,...!". To avoid using too many quotes, I put all the strings (except the parameters) in one string, then split it and dumped the resulting array (`'|/~`)

The main string goes through the following transformations:

```
10,
And on that 5 he7690,
With3 2 and3 t2,
Here4t24everyw23,
10!

```

replace `"0"` with `", E-I-E-I-O"`:

```
1, E-I-E-I-O,
And on that 5 he769, E-I-E-I-O,
With3 2 and3 t2,
Here4t24everyw23,
1, E-I-E-I-O!

```

replace `"1"` with `"Old MacDonald765"`:

```
Old MacDonald765, E-I-E-I-O,
And on that 5 he769, E-I-E-I-O,
With3 2 and3 t2,
Here4t24everyw23,
Old MacDonald765, E-I-E-I-O!

```

replace `"2"` with `"here"`, then `"3"` with `"68 8"` etc.

8 corresponds to the sound, and 9 to the animal.
> 6 votes

# Answer
# Bash + iconv, 128 Unicode characters

Takes the below pure-bash/ascii function body and reverse-encodes into unicode chars:

```
m()(c=`iconv -t unicode<<<㵳⁜屡␠ਲ㵨敨敲攊ⰽ⁜ⵅⵉⵅⵉ੏㵯伢摬䴠捡潄慮摬栠摡愠映牡⑭≥攊档␢Ɐ䄊摮漠桴瑡映牡敨栠摡愠␠␱ⱥ圊瑩⑨⁳㈤␠湡⑤⁳㈤琠栤ਬ效敲猤⑴⑨ⱳ攠敶祲⑷⑨⁳㈤ਬ漤™ਠ`
eval "${c:2}")

```

Defines a shell function `m`. Call as:

```
$ m pony neigh
Old MacDonald had a farm, E-I-E-I-O,
And on that farm he had a pony, E-I-E-I-O,
With a neigh neigh here and a neigh neigh there,
Here a neigh, there a neigh, everywhere a neigh neigh,
Old MacDonald had a farm, E-I-E-I-O!
$

```

---

# Pure bash, 171 bytes (ascii-only)

*I think its worth noting that the original verse (with "cow" and "moo") is only 203 chars.*

```
m()(s=\ a\ $2
h=here
e=,\ E-I-E-I-O
o="Old MacDonald had a farm$e"
echo "$o,
And on that farm he had a $1$e,
With$s $2 $h and$s $2 t$h,
Here$s, t$h$s, everyw$h$s $2,
$o"!)

```

Defines the shell function `m`. Call as:

```
$ m sheep baa
Old MacDonald had a farm, E-I-E-I-O,
And on that farm he had a sheep, E-I-E-I-O,
With a baa baa here and a baa baa there,
Here a baa, there a baa, everywhere a baa baa,
Old MacDonald had a farm, E-I-E-I-O!
$

```
> 6 votes

# Answer
# C++ (403)

Alright, this is a bit of a long shot, but who doesn't like over-defining?

```
#define O ", E-I-E-I-O"
#define E O<<","
#define I "Old MacDonald had a farm"
#define H(a) "And on that farm he had a "<<a<<E
#define D(s) s<<" "<<s
#define W(s) "With a "<<D(s)<<" here and a "<<D(s)<<" there,"
#define V(s) "Here a "<<s<<", there a "<<s<<", everywhere a "<<D(s)<<","
#define F I<<O<<"!"
#define N endl
void m(string a, string s){cout<<I<<E<<N<<H(a)<<N<<W(s)<<N<<V(s)<<N<<F<<N;}

```
> 5 votes

# Answer
# Python, 116 Unicode chars

```
def f(**a):print u'鱸쿳光䷰癌쿉ы㊲匒ሔ툕謒畲尔㵵䅵忘쮇⼱ⅅ伿⒡넣Ⰴ邩ઑ꩕醪徜妮ꊌ㰺⒳Ⰳ鮕꾟ౙ㎧譒ᕒ끒镈롴쀼怪㪢愐腤닔ꋔ狊兔Ⲹ㾗꽡Ȩ똀䝸å'.encode('u16')[2:].decode('zip')%a

```

StackOverflow is eating my special characters, though, so here's the file in base64:

```
77u/ZGVmIGYoKiphKTpwcmludCB1J+mxuOy/s+WFieS3sOeZjOy/idGL44qy5YyS4YiU7YiV6KyS55Wy5bCU47W15IW15b+Y7K6H4ryx4oWF5Ly/4pKh64Sj4rCE6YKp4KqR6qmV6Yaq5b6c5aau6oqM47C64pKz4rCD6a6V6r6f4LGZ446n6K2S4ZWS74yS64GS6ZWI7pKA66G07IC85oCq46qi5oSQ6IWk64uU6ouU54uK5YWU4rK4476X6r2hyKjrmIDknbjDpScuZW5jb2RlKCd1MTYnKVsyOl0uZGVjb2RlKCd6aXAnKSVh

```

The data is packed using zlib, which efficiently codes repeated strings (zlib is good at compressing text in general). To take advantage of the "Unicode characters" rule, the 121-byte zlib chunk is padded and halved to a 61-character Unicode string by interpreting the bytestring as UTF-16.

Call the function as

```
f(cow='pig', moo='oink')

```
> 3 votes

# Answer
# Python, 217

You can't really golf this much. I just took out the blatant front-end repetition and...

```
m,f="Old MacDonald had a farm, E-I-E-I-O",lambda x,y:m+",\nAnd on that farm he had a %s, E-I-E-I-O,\nWith a %shere and a %sthere,\nHere a %s, there a %s, everywhere a %s %s,\n%s!"%((x,)+((y+' ')*2,)*2+(y,)*4+(m,))

```

### Javascript, 241 - JSCrush cheat

Made this with JSCrush...not really a real answer, it'd just be interesting to see if anybody can beat this in a mainstream language. (**EDIT**: uh)

```
_='var f=function(c,a){var b=a "+a;return"Anon that he hadcWith  and tHere  t   everyw!"};OlMacDonalhaa a "+, O,\\nhere+"b farm a, d E-I-';for(Y in $=' ')with(_.split($[Y]))_=join(pop());eval(_)

```
> 2 votes

# Answer
## Java - ~~262~~ 258

```
void m(String...s){String b=s[1],c=b+" "+b,d="E-I-E-I-O",e="Old MacDonald had a farm, "+d;System.out.print(e+",\n"+"And on that farm he had a "+s[0]+", "+d+",\nWith a "+c+" here and a "+c+" there,\nHere a "+b+", there a "+b+", everywhere a "+c+",\n"+e+"!");}

```

Further optimization is definitely possible.
> 2 votes

# Answer
# Rebol, 206 202

```
f: func[a b][print reword{$o$e,
And on that farm he had a $a$e,
With a $b $b here and a $b $b there,
Here a $b, there a $b, everywhere a $b $b,
$o$e!}[e", E-I-E-I-O"o"Old MacDonald had a farm"a a b b]]

```

Usage: `f "cow" "moo"`
> 2 votes

# Answer
# Java, 246

```
void f(String[] a){String o="Old MacDonald had a farm",e=", E-I-E-I-O",x=" a "+a[1],s=x+" "+a[1];System.out.print(o+e+",\nAnd on that farm he had a "+a[0]+e+",\nWith"+s+" here and"+s+" there,\nHere"+x+", there"+x+", everywhere"+s+",\n"+o+e+"!");}

```

Usage: `f(new String[]{"cow","moo"});`
> 2 votes

# Answer
# JavaScript: 152 chars / ES6: 149 chars

Here's a JS function called "z" that does the job in 214 chars. (don't execute it!)

```
function z(a,b){c=' a '+b;d=c+' '+b;e=', E-I-E-I-O';f='Old MacDonald had a farm'+e;return(f+',\nAnd on that farm he had a '+a+e+',\nWith'+d+' here and'+d+' there,\nHere'+c+', there'+c+', everywhere'+d+',\n'+f+'!')}

```

I "packed" it in unicode chars using a technique created by @subzey and I for 140byt.es).

```
eval(unescape(escape('').replace(/uD./g,'')))

```

execute that last snippet, then call `z("cow","moo")`, and you'll get this string:

```
Old MacDonald had a farm, E-I-E-I-O,
And on that farm he had a cow, E-I-E-I-O
With a moo moo here and a moo moo there,
Here a moo, there a moo, everywhere a moo moo,
Old MacDonald had a farm, E-I-E-I-O!"

```

More info here: http://xem.github.io/golfing/en.html#compress

### ES6 version:

```
eval(unescape(escape('').replace(/uD./g,'')))

```
> 2 votes

# Answer
## Perl 5 (UTF-8) - 131 characters, 313 bytes

The script below needs to be saved as UTF-8 with no BOM.

```
use utf8;use Encode;eval encode ucs2,'獵戠晻③㴤∮灯瀻⑥㴢Ⱐ䔭䤭䔭䤭伢㬤漽≏汤⁍慣䑯湡汤慤慲洤攢㬤ⰽ≥牥∻獡礢⑯Ⰺ䅮搠潮⁴桡琠晡牭攠桡搠愠䁟⑥Ⰺ坩瑨③③␬湤③③⁴桥牥Ⰺ䠤Ⱔ戬⁴栤Ⱔ戬癥特睨␬③③Ⰺ⑯™紱';

```

Usage: `f("cow", "moo");`.

Perl needs to have been run with the `-M5.010` flag to enable Perl 5.10 features. (This is allowed.)

I quite like the symmetry of the character count (131) and byte count (313). It's very yin and yang.

## Perl 5 (ASCII) - 181 characters, 181 bytes

```
sub f{$b=$".pop;$e=", E-I-E-I-O";$o="Old MacDonald had a farm$e";$,="ere a";say"$o,
And on that farm he had a @_$e,
With a$b$b h$,nd a$b$b there,
H$,$b, th$,$b, everywh$,$b$b,
$o!"}

```

Usage: `f("cow", "moo");`.

Again, perl needs to have been run with the `-M5.010` flag to enable Perl 5.10 features.
> 2 votes

# Answer
# CJam (non-ASCII) - 77 chars

```
"啝裢樃濿䶹讄團챤鋚䖧雿ꆪꆵ䷶텸紎腕Խꍰ搓᩟童䚯⤭刧损⬛豳Ẍ퍾퓱郦퉰怈䡞௳閶蚇⡾쇛蕟猲禼࿆艹蹚㞿䛴麅鞑椢⧨餎쏡첦휽嬴힡ݷ녣㯂鐸㭕"56e3b127b:c~

```

Usage: `"cow""moo"F`

The string is my other CJam solution converted from base 127 to base 56000.
A UTF-8 locale might be required.

By the way, now you can try this online at http://cjam.aditsu.net/
> 2 votes

# Answer
# C# - 339 Bytes

```
void x(string c, string d){var a="Old MacDonald had a farm";var b=", E-I-E-I-O";var f=" a ";var g=" there";Debug.WriteLine(a+b+",");Debug.WriteLine("And on that farm he had"+f+c+b+",");Debug.WriteLine("With"+f+d+" "+d+" here and"+f+d+" "+d+g+",");Debug.WriteLine("Here"+f+d+","+g+f+d+", everywhere"+f+d+" "+d+",");Debug.WriteLine(a+b+"!");

```

Usage: `x("cow","moo");`
> 2 votes

# Answer
# Delphi XE3 (272 252)

```
procedure k(a,s:string);const o='Old MacDonald had a farm';e=', E-I-E-I-O';n=','#13#10;begin s:=' '+s;write(o+e+n+'And on that farm he had a '+a+e+n+'With a'+s+s+' here and a'+s+s+' there'+n+'Here a'+s+', there a'+s+' every where a'+s+s+n+o+e+'!');end;

```

### Ungolfed

```
procedure k(a,s:string);
const
  o='Old MacDonald had a farm';
  e=', E-I-E-I-O';
  n=','#13#10;
begin
  s:=' '+s;
  write(o+e+n+'And on that farm he had a '+a+e+n+'With a'+s+s+' here and a'+s+s+' there'+n+'Here a'+s+', there a'+s+' every where a'+s+s+n+o+e+'!');
end;

```
> 1 votes

# Answer
# Cobra - 203

```
def f(a,b)
    d=" a [b] "+b
    e=", E-I-E-I-O"
    m="Old MacDonald had a farm[e]"
    print "[m],\nAnd on that farm he had a [a][e],\nWith[d] here and[d] there,\nHere a [b], there a [b], everywhere[d],\n[m]!"

```

Even for a language with little-to-no multi-lining, and strict indentation rules, Cobra still does pretty well.
> 1 votes

# Answer
## Lua 237

```
function f(a,b)c=b.." "..b;d="Old MacDonald had a farm, E-I-E-I-O"print(d..",\nAnd on that farm he had a "..a..", E-I-E-I-O,\nWith a "..c.." here and a "..c.." there,\nHere a "..b..", there a "..b..", everywhere a "..c..",\n"..d.."!")end

```

By defining `c=b.." "..b`, I can save a dozen characters. By defining `d` as I do, I save 23 characters. I do not see how I can shorten this anymore. This is called via `f("<animal>","<sound>")`.
> 1 votes

# Answer
# JavaScript 220

```
function f(a,b){c=' a '+b;d=c+' '+b;e=', E-I-E-I-O';f='Old MacDonald had a farm'+e;console.log(f+',\nAnd on that farm he had a '+a+e+',\nWith'+d+' here and'+d+' there,\nHere'+c+', there'+c+', everywhere'+d+',\n'+f+'!');}

```

Called by

```
f('cow', 'moo');

```
> 1 votes

# Answer
# Java 8(411)

```
String m(String...m){LinkedHashMap<String,String>n=new LinkedHashMap<>();n.put("/","( * #, -");n.put("#","farm");n.put("-","E-I-E-I-O");n.put("+","here");n.put("*","had a");n.put("(","Old MacDonald");n.put("|"," a )");n.put(")","moo");n.put("moo",m[1]);n.put("cow",m[0]);m[0]="/,\nAnd on that # he * cow, -,\nWith|) + and|) t+,\nHere|, t+|, everyw+|),\n/!";n.forEach((k,v)->m[0]=m[0].replace(k,v));return m[0];}

```

Abusing of lambda, putted the replaces in a LinkedhashMap to keep em in a defined order then used a foreach lambda to replace key with value in main String. parameters are added as last 2 replacements in the map. that varargs argument is to shave off some bytes in the method header

Ungolfed version:

```
String m(String... m)
{
    LinkedHashMap<String, String> n = new LinkedHashMap<>();
    n.put("/", "( * #, -");
    n.put("#", "farm");
    n.put("-", "E-I-E-I-O");
    n.put("+", "here");
    n.put("*", "had a");
    n.put("(", "Old MacDonald");
    n.put("|", " a )");
    n.put(")", "moo");
    n.put("moo", m[1]);
    n.put("cow", m[0]);
    m[0] = "/,\nAnd on that # he * cow, -,\nWith|) + and|) t+,\nHere|, t+|, everyw+|),\n/!";
    n.forEach((k, v) -> m[0] = m[0].replace(k, v));
    return m[0];
}

```
> 1 votes

# Answer
## Pure C, 298 bytes, no unicode

In my function I take a single argument, which is actually a bunch of `char*`'s packed together. Each string is null terminated, and there's an extra null terminator at the end. This allows me to check `strlen(a)` at the end of each loop, rather than keeping a counter variable.

mcdonald.c:

```
m(char*a){while(strlen(a)){printf("Old MacDonald had a farm, E-I-E-I-O\nAnd on that farm he had a %s, E-I-E-I-O,\nWith a ",a);a+=strlen(a)+1;printf("%s %s here and a %s %s there,\nHere a %s, there a %s, everywhere a %s %s,\nOld MacDonald had a farm, E-I-E-I-O!\n",a,a,a,a,a,a,a,a);a+=strlen(a)+1;}}

```

main.c:

```
int m(char *v);
int main(int argc, char **argv) {
    m("cow\0moo\0programmer\0meh\0\0");
    return 0;
}

```

Output:

```
clang main.c mcdonald.c && ./a.out
Old MacDonald had a farm, E-I-E-I-O
And on that farm he had a cow, E-I-E-I-O,
With a moo moo here and a moo moo there,
Here a moo, there a moo, everywhere a moo moo,
Old MacDonald had a farm, E-I-E-I-O!
Old MacDonald had a farm, E-I-E-I-O
And on that farm he had a programmer, E-I-E-I-O,
With a meh meh here and a meh meh there,
Here a meh, there a meh, everywhere a meh meh,
Old MacDonald had a farm, E-I-E-I-O!

```
> 1 votes

# Answer
# C: 224 bytes

By using the printf precision specifier, we can use the same string as both the printf format string and as two of the parameters.

```
o(char*x,char*y){char*f="Old MacDonald had a farm, E-I-E-I-O,\nAnd on that farm he had a %s%.13sWith a %s %s here and a %s %s there,\nHere a %s, there a %s, everywhere a %s %s,\n%.35s!\n";printf(f,x,f+24,y,y,y,y,y,y,y,y,f);}

```

With white space and the string split into lines:

```
o(char* x, char* y)
{
    char* f=
        "Old MacDonald had a farm, E-I-E-I-O,\n"
        "And on that farm he had a %s%.13s"
        "With a %s %s here and a %s %s there,\n"
        "Here a %s, there a %s, everywhere a %s %s,\n"
        "%.35s!\n";

    printf(f,x,f+24,y,y,y,y,y,y,y,y,f);
}

```
> 1 votes

# Answer
# PHP - 272 characters, 272 bytes

```
function m($q,$w){for($e="@&And on that farm he had^<%&With *h# and*th#&H(th(everywh#^> >&@!",$r=1;;$e=$r){$r=str_replace(["@","#","^","%","<",">","&","*","("],["Old MacDonald had^farm%","ere"," a ",", E-I-E-I-O",$q,$w,",\n","^> > ","#^>, "],$e);if($e==$r)break;}echo $e;}

```

Usage: `m("cow", "moo");`, `m("fox", "Hatee-hatee-hatee-ho");`

Parameters with `@#%^<>&*(` crash the output.
> 1 votes

# Answer
# Haskell (282 and still somewhat readable :))

```
wc -c oldmacdonald.hs
     282 oldmacdonald.hs

```

The file:

```
main=mapM putStrLn[s"cow""moo",s"pig""oink",s"sheep""baa"]
s c m=o#",\nAnd on that farm he had"#b c#e#let n=m#" "#m in",\nWith"#b n#" here and"#b n#" there,\nHere"#b m#", there"#b m#", everywhere"#b n#",\n"#o#"!\n"
o="Old MacDonald had a farm"#e
e=", E-I-E-I-O"
b=(" a "#)
(#)=(++)

```
> 1 votes

# Answer
## ES6, 2 solutions of ~~179~~ 186 chars without any unicode

```
f=(a,b)=>alert("325And on that farm he had a025With a11 h4nd a11 th45H41, th41, everywh411532!".replace(/\d/g,x=>[" "+a," "+b,", E-I-E-I-O","Old MacDonald had a farm","ere a",",\n"][x]))

```

And the second:

```
f=(a,b)=>alert("3625And on7at6 he ha8025With a11 h4n811745H41,741, everywh4115362!".replace(/\d/g,x=>(` ${a}0 ${b}0, E-I-E-I-O0Old MacDonald had a0ere a0,\n0 farm0 th0d a`).split(0)[x]))

```

I've added alert call (+7 chars).
> 1 votes

# Answer
# JavaScript (E6) 140 chars

Char counter: https://mothereff.in/byte-counter, 140 chars, 425 bytes in UTF-8

```
eval(unescape(escape('').replace(/uD./g,'')))

```

Original ASCII code 188 bytes

```
f=(a,b)=>alert('0125And on 6at13e3ad7 925Wi6 a88347nd a88 645H478, 6478, everywh47885012!'.replace(/\d/g,c=>('Old MacDonald had a0 farm0, E-I-E-I-O0 h0ere0,\n0th0 a0 '+b+0+a).split(0)[c]))

```

Compressed with http://xem.github.io/obfuscatweet/

**Test** in FireFox/FireBug console

```
f('mosquito','zzz')

```

*Output*

```
Old MacDonald had a farm, E-I-E-I-O,
And on that farm he had a mosquito, E-I-E-I-O,
With a zzz zzz here and a zzz zzz there,
Here a zzz, there a zzz, everywhere a zzz zzz,
Old MacDonald had a farm, E-I-E-I-O!

```
> 1 votes

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


title: Python: I wish I was PHP

text:
# Question
Title: Python: I wish I was PHP
There's an old story about a stonecutter who was never satisfied with what he was. He wished he could become the sun, and so he was. Blocked by the clouds, he wished to be - and became - a cloud. When the wind blew, he wished himself into being the wind. Stopped by the mountain, he wished to be a mountain, and thus became one. Soon, however, he was being hacked at by a stonecutter, and wished to be a stonecutter.

Similarly, your task is to write a program which is never satisfied with the language it is in. Your program must output a set of regex replacements to turn it into a different language. And so on.

## Rules

1. Write a program in a language of your choice.
2. The program should output a series of at least two segments. A segment is a bunch of text, separated by semicolons. However, if a semicolon is contained within a regex, such that breaking it up there will result in invalid syntax, it does not separate segments. See the example.
3. The first segment is a regex pattern to find, and the second segment is the replacement pattern. The third is another "find" pattern, and the fourth is a "replace" pattern, and so on.
4. Apply the regex patterns to the program. Replace the pattern on the first segment with one on the second; replace the third pattern with the one on the fourth, and so on.
5. The result should be a program in a different language, which, itself, follows rules 2 to 4.
6. The languages used must form an infinite, repeating cycle.
    * For example, Python -\> PHP -\> C++ -\> Python -\> PHP -\> C++ -\> Python -\> ...
7. Your score is the period of the cycle. Ties are broken by shortest initial code length.
    * In the above example, the score is three.
8. In each iteration of the cycle, no language may be used more than once.
9. For rules 5 and 7, compatible languages (C and C++) and different versions of the same language (Python 2 and Python 3) are considered the same.
10. The programs themselves do not need to repeat.
    * In the above example, the first and fourth programs may be different.
11. Any version of regex is acceptable, but the same must be used for all the programs.
12. The total output for each program may not exceed 100 characters.
13. Each output must contain instructions to actually change the program. That is, no two consecutive programs in the cycle may be the same.

## Example

**Python -\> Ruby -\> Python -\> ...**

```
print "uts;Z;rint;uts;Z(?=;Z);rint"

```

Outputs:

```
uts;Z;rint;uts;Z(?=;Z);rint

```

The segments are:

```
FIND     ;    REPLACE
uts      ;    Z
rint     ;    uts
Z(?=;Z   ;    rint   (breaking the first segment in two would result in invalid syntax)

```

Applying the regex replacements, in order, gives us:

```
print "Z;Z;rint;Z;Z(?=;Z);rint"      # replace each "uts" with "Z"
puts "Z;Z;uts;Z;Z(?=;Z);uts"         # replace each "rint" with "uts"
puts "rint;Z;uts;rint;Z(?=;Z);uts"   # replace each "Z" followed by ";Z" with "rint"

```

Running the last line gives us the instructions to turn this back into Python code.

# Answer
## 2 Languages: Python, Ruby; ~~33~~ 29 bytes

Here is another way to do Python and Ruby, that's a bit shorter than the one in the challenge:

```
Python:   print'^;puts"^.*?\\42#\\73"#'
prints:   ^;puts"^.*?\42#\73"#

Ruby:     puts"^.*?\42#\73"#print'^;puts"^.*?\\42#\\73"#'
prints:   ^.*?"#;

```

It shouldn't be *too* difficult to add PHP into the mix.
> 6 votes

# Answer
# 2 languages: Python 2 and Befunge-93, 77 bytes

After *carefully reading the rules this time*, I came up with a real answer. It won't win any prizes, but Befunge is just too fun to program in.

```
u=u">>>>>:#,_@;Z;print;>>>>>:#,_@;Z(?=;Z);print;<v;Y;u;<v;Y(?=;Y);u"
print u

```

This Python program outputs:

```
>>>>>:#,_@;Z;print;>>>>>:#,_@;Z(?=;Z);print;<v;Y;u;<v;Y(?=;Y);u

```

Which yields these replacements:

```
FIND         REPLACE
>>>>>:#,_@   Z
print        >>>>>:#,_@
Z(?=;Z)      print
<v           Y
u            <v
Y(?=;Y)      u

```

Which turns the program into this Befunge program:

```
<v=<v"print;Z;>>>>>:#,_@;print;Z(?=;Z);>>>>>:#,_@;u;Y;<v;u;Y(?=;Y);<v"
>>>>>:#,_@ <v

```

Maybe I'll see if I can make it one line. Frankly, I'm a little surprised Befunge works for this sort of problem at all.

(Sorry for deleting and undeleting a bunch; I was panicking for a second because I thought the program might not have worked.)
> 1 votes

---
Tags: code-challenge, regular-expression, rosetta-stone
---