title: Typesetting multidimensional labels

text:
# Question
Title: Typesetting multidimensional labels
In a steam-punk multidimensional world, our boss wants to affix printed index labels to each drawer in our conglomerate's multidimensional file cabinet.

The boss wants to typeset the entire label sheet as a single form, using a font bought only for this purpose, so we have to order the sorts (metal symbol pieces). Since sorts are very expensive, our order must be for the exact count of each digit-symbol.

For a given (by any means) set of lengths of dimensions ≥ 0, return (by any means) our order, which is the frequency table of digits required to typeset all the Cartesian coordinates. It must be arranged by keyboard order of appearance (i.e. 0 after 9), and may not include orders of 0 sorts, so if no sorts are to be ordered at all (because a dimension has length 0); print nothing.

* Bonus of -3 sorts if your code can handle (i.e. print nothing) 0 dimensions too.
* Final newline chars are acceptable.
* Prohibition on standard loopholes apply.
* As mentioned, sorts are expensive, this is therefore .

A kind soul may edit this challenge to include automated scoring, so include a header like:
`# LanguageName, 123 sorts`

### Test cases

Given `11`, print:

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

```

because the needed labels are `1`, `2`, `3`, `4`, `5`, `6`, `7`, `8`, `9`, `10`, and `11`.

---

Given `2 3`, print:

```
1 5
2 5
3 2

```

because the needed labels are `1 1`, `1 2`, `1 3`, `2 1`, `2 2`, and `2 3`.

---

Given `2 0`, print an empty line:

or nothing.

---

Given `1 2 3`, print:

```
1 11
2  5
3  2

```

because the needed labels are `1 1 1`, `1 1 2`, `1 1 3`, `1 2 1`, `1 2 2`, and `1 2 3`

---

Given `5 5 5 5`, print:

```
1 500
2 500
3 500
4 500
5 500

```

And no, I'm not going to list all 625 labels.

# Answer
# Dyalog APL, ~~10~~ 7

The code is 10 bytes long and qualifies for the bonus.

Thanks to user46915 for 3 bytes!

```
,∘≢⌸∊⍕¨∊⍳⎕

```

Note that  (input) doesn't work on TryAPL; you can try the function form here.

```
            ⎕      Get input
           ⍳       Index vector
       ∊⍕¨∊        Flatten, stringify, flatten again
      ⌸            From the key, display the
{⍺,  }             elements concatenated with the
   ≢⍵              number of times they occur

```

I don't completely understand the  operator, but `{⍺}⌸` lists the unique values taken on, and `{⍵}⌸` lists their places in the argument.

This has the correct ordering because it is the order in which digits appear in the multidimensional array of labels.
> 6 votes

# Answer
# Mathematica, 48 bytes - 3 = 45

```
Grid@Tally@Flatten@IntegerDigits@Tuples@Range@#&

```
> 10 votes

# Answer
## R, 110 bytes

*Saved 4 thanks to Alex A. (thanks!)*

```
U=unlist
X=table(U(strsplit(as.character(U(expand.grid(Map(seq_len,scan())))),"")))
z=Map(cat,names(X),X,"\n")

```
> 2 votes

# Answer
# Mathematica, ~~111~~ 85 bytes

```
Grid[Thread@{Range@10~Mod~10,DigitCount@Tuples@Range@#~Total~2}~DeleteCases~{_,0}]&

```

Most of the work here is done by `DigitCount`.
> 2 votes

# Answer
# Ruby, 92 bytes

```
f,*r=$*.map{|n|[*1..n.to_i]}
a=f.product(*r)*''
puts a.chars.uniq.map{|c|[c,a.count(c)]*" "}

```

Takes the lengths as command line arguments:

```
$ ruby foo.rb 1 2 3
1 11
2 5
3 2

```
> 1 votes

# Answer
# CJam, 31 bytes

```
Laq~{,m*}/e_:)s{_'0=A*+}$e`{(S\N}%

```

Try it online

Code is 34 bytes, and takes 3 byte bonus for working with empty input list. The input is a list in CJam format, e.g.:

```
[1 2 3]

```

Explanation:

```
La    Push list containing empty list to seed Cartesian products.
q~    Get and interpret input.
{     Loop over values in input list.
  ,     Built range from 0 to value-1.
  m*    Form Cartesian product with the list we already have.
}/    End loop over values in input list.
e_    Resulting list has extra nesting. Flatten it.
:)    Increment all values in list, since it is 0-based, and we need 1-based.
s     Convert it to string, so we can operate on digits.
{     Block to calculate source key, needed to get 0 to the end.
  _     Copy the digit.
  '0=   Compare with '0.
  A*    Multiply comparison result by 10...
  +     ... and add it to digit.
}$    End of sort key block.
e`    RLE.
{     Start of loop over RLE entries, for generating output in specified format.
  (     Pop off the first value, which is the count.
  S     Push a space...
  \     ... and swap it with the count.
  N     Push a newline.
}%    End of loop over RLE entries.

```
> 0 votes

# Answer
# Pyth, 15 bytes

```
rjko%N_Ts*FSMQ8

```
> 0 votes

# Answer
# Haskell, 125 bytes

```
import Data.List
l=mapM_(putStrLn.(\(h:r)->h:' ':show(length r+1))).group.sort.concatMap show.concat.sequence.map(\n->[1..n])

```
> 0 votes

---
Tags: code-golf, sorting, counting, permutations, 3d
---


title: What am I even saying?

text:
# Question
Title: What am I even saying?
You're playing TF2, and you want to make a bot that will just put voice commands into the chat box. Typically, to "call" a voice command, one would press a key (`Z`, `X`, or `C`) and a number (`1-8`) to create an audio dialogue. Here are the text equivalents of the audios displayed when pressing these keys:

```
Voice Menu 1
Default key: Z
==============
1. MEDIC!
2. Thanks!
3. Go Go Go!
4. Move Up!
5. Go Left
6. Go Right
7. Yes
8. No

Voice Menu 2
Default key: X
==============
1. Incoming
2. Spy!
3. Sentry Ahead!
4. Teleporter Here
5. Dispenser Here
6. Sentry Here
7. Activate ÜberCharge!
8. MEDIC: ÜberCharge Ready   ; ignore the MEDIC: bit

Voice Menu 3
Default key: C
==============
1. Help!
2. Battle Cry    ; see bonus
3. Cheers
4. Jeers
5. Positive
6. Negative
7. Nice Shot
8. Good Job

```

---

**Objective** Given an input string (or input character + character, character + number, etc.; whatever is most relevant/convenient to your language), take the respective message from the chart above and output it. If the input is invalid, do not output anything. This is a , so the shortest program in bytes wins.

## Example IOs

```
> Z3
Go Go Go!

> Z1
MEDIC!

> Z5
Go Left

> X8
ÜberCharge Ready

> X7
Activate ÜberCharge!

> C1
Help!

> C8
Good Job

```

## Bonuses/penalties

These bonuses are applied in the order of appearance in this list.

* -1 byte for every byte used in the physical text of `C2` (i.e., `Battle Cry`); I will not add points for errors on `C2`, so be creative if you wish! (By physical text, I mean every byte used for constructing (not outputting) the string. For example, for `STDOUT "AHHHHHHHH!"`, `"AHHHHHHHH!"` is free, but nothing else is. In `console.log(`${v="Tha"}t's too you, you idiot!`)`, the free characters are ``"Tha" t's too you, you idiot!``. These characters are the only ones that make up part of the string and their respective quotes.)
* -15% if your program takes input and outputs the respective entry until an invalid input is given, at which point your program should terminate.
* +5 bytes for every capitalization, punctuation, or spacing error
* +10 bytes for every wrong/missing letter
* -20 bytes if you can take a string like "X5C3Z6..." and output each respective message, separated by newlines.
* -30 bytes if you take a class input (either `Scout`, `Soldier`, `Pyro`, `Demoman`, `Heavy`, `Engineer`, `Sniper`, `Medic`, or `Spy`) and verify if the class can say the given expression. The only expression that applies is `X8`, i.e., `MEDIC: ÜberCharge Ready`; only the Medic can say this. If any other class *besides* the medic attempts to say this, do not output anything. (The names are case insensitive.)

## Leaderboard

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

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

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

# Answer
> 1 votes
# Perl, 280 - 15% - 20 = 218 bytes

```
#!perl -l
@Z=<0 {MEDIC,Thanks,Go_Go_Go,Move_Up}! Go_{Left,Right} Yes No>;
@X=<0 Incoming Spy! Sentry_Ahead! {Teleporter,Dispenser,Sentry}_Here Activate_ÜberCharge! ÜberCharge_Ready>;
@C=<0 Help! You_Fight_Like_A_Dairy_Farmer! {Ch,J}eers {Posi,Nega}tive Nice_Shot Good_Job>;
y/_/ /,print while$_=${getc=~s/
//r||getc}[getc]

```

Counting the shebang as one, input is taken from stdin. The newlines after semicolons are not necessary, and have been left for readability.

---

**Sample Usage**

```
$ echo Z3 | perl tf2.pl
Go Go Go!

$ echo X7 | perl tf2.pl
Activate ÜberCharge!

$ echo C2 | perl tf2.pl
You Fight Like A Dairy Farmer!

$ echo X5C3Z6 | perl tf2.pl
Dispenser Here
Cheers
Go Right

```

---

**Interactive Mode**

The code may also be run in interactive mode, in which case it will continue accepting input until an invalid input is given.

```
$ perl tf2.pl
Z2
Thanks!
X3
Sentry Ahead!
C4
Positive
V5

```

---

# Perl, 331 - 354 (C2) - 20 - 30 = -73 bytes

```
#!/usr/bin/env perl -l
@Z=<0 {MEDIC,Thanks,Go_Go_Go,Move_Up}! Go_{Left,Right} Yes No>;
@X=(<0 Incoming Spy! Sentry_Ahead! {Teleporter,Dispenser,Sentry}_Here Activate_ÜberCharge!>,{Medic.$/,'ÜberCharge Ready'});
@C=(0,'Help!',(join!open(0),<0>),<{Ch,J}eers>,<{Posi,Nega}tive>,Nice_Shot,Good_Job);
print%{$_=@{$`}[<>=~/.\K(.)/]}?$_->{$c}:y/_/ /rwhile$c=<>

```

Supports multiple entries, and filtering by class. The battle cry I've chosen is the entire source code. It can be seen that every byte of the source is necessary for the *construction* of this particular battle cry - were any byte missing, the battle cry would be different. This includes the entire shebang, which by convention is counted as one.

---

**Sample Usage**

```
$ more in.dat
Medic
X8
Spy
X8
Heavy
C8
Pyro
Z2

$ perl tf2.pl < in.dat
ÜberCharge Ready

Good Job
Thanks!

```

# Answer
> 5 votes
# CJam, -48 bytes

```
"\"MEDIC!
Thanks!
Go Go Go!
Move Up!
Go Left
Go Right
Yes
No
Incoming
Spy!
Sentry Ahead!
Teleporter Here
Dispenser Here
Sentry Here
Activate ÜberCharge!

Help!

Cheers
Jeers
Positive
Negative
Nice Shot
Good Job
\"N/Fleu\"MEDIC\"=\"ÜberCharge Ready\"*tq2/\"ZXC\"9,1>sm*f{\a#-2$=_S=W$@?N}\?"_~

```

The source code is **292 bytes** long, can handle multiple inputs (**-20 bytes**) and checks for the class name (**-30 bytes**). Furthermore, I have chosen

```
"MEDIC!
Thanks!
Go Go Go!
Move Up!
Go Left
Go Right
Yes
No
Incoming
Spy!
Sentry Ahead!
Teleporter Here
Dispenser Here
Sentry Here
Activate ÜberCharge!

Help!

Cheers
Jeers
Positive
Negative
Nice Shot
Good Job
"N/Fleu"MEDIC"="ÜberCharge Ready"*tq2/"ZXC"9,1>sm*f{\a#-2$=_S=W$@?N}\?

```

as battle cry, so the first **290 bytes** that are used to push this string are free.

Try it online in the CJam interpreter.

# Answer
> 4 votes
# D, 692 bytes

731 - 39(for `"B"~"a"~"t"~"t"~"l"~"e"~" "~"C"~"r"~"y"`)

```
import std.stdio;import std.conv;import std.utf;void main(char[][] a){char t=a[1][0];int n=to!int(a[1][1])-48;string G="Go ";char z='Z';char x='X';char c='C';string H=" Here";string U=to!string('\u00DC');string[int][char]o;o[z][1]="MEDIC!";o[z][2]="Thanks!";o[z][3]=G~G~"Go!";o[z][4]="Move Up!";o[z][5]=G~"Left";o[z][6]=G~"Right";o[z][7]="Yes";o[z][8]="No";o[x][1]="Incoming";o[x][2]="Spy!";o[x][3]="Sentry Ahead!";o[x][4]="Teleporter"~H;o[x][5]="Dispenser"~H;o[x][6]="Sentry"~H;o[x][7]="Activate "~U~"berCharge!";o[x][8]=U~"berCharge Ready";o[c][1]="Help!";o[c][2]="B"~"a"~"t"~"t"~"l"~"e"~" "~"C"~"r"~"y";o[c][3]="Cheers";o[c][4]="Jeers";o[c][5]="Positive";o[c][6]="Negative";o[c][7]="Nice Job";o[c][8]="Good Job";write(o[t][n]);}

```

*I like D a lot.*

## D, 724 bytes w/ Classes

793 - 39(same as above) - 30(for class option)

```
import std.stdio;import std.conv;import std.utf;void main(char[][] a){char t=a[1][0];int n=to!int(a[1][1])-48;string G="Go ";char z='Z';char x='X';char c='C';string H=" Here";string U=to!string('\u00DC');string[int][char]o;o[z][1]="MEDIC!";o[z][2]="Thanks!";o[z][3]=G~G~"Go!";o[z][4]="Move Up!";o[z][5]=G~"Left";o[z][6]=G~"Right";o[z][7]="Yes";o[z][8]="No";o[x][1]="Incoming";o[x][2]="Spy!";o[x][3]="Sentry Ahead!";o[x][4]="Teleporter"~H;o[x][5]="Dispenser"~H;o[x][6]="Sentry"~H;o[x][7]="Activate "~U~"berCharge!";o[x][8]=U~"berCharge Ready";o[c][1]="Help!";o[c][2]="B"~"a"~"t"~"t"~"l"~"e"~" "~"C"~"r"~"y";o[c][3]="Cheers";o[c][4]="Jeers";o[c][5]="Positive";o[c][6]="Negative";o[c][7]="Nice Job";o[c][8]="Good Job";if(a.length>2){if(!(a[2]!="Medic"&&t==x&&n==8))goto P;}else P:write(o[t][n]);}

```

This version lets you input a class for `X8`. Use it like `tf2 X8 Medic`. It will print the correct message if you use the correct class. *Yes, this does use a **goto**. Kill it now.*

# Answer
> 4 votes
# Prolog, ~~371~~ 362 - 11 = 351 bytes

My first attempt at code golf.
I chose a language which seem to be underrepresented here.
I'm far from an expert at prolog, so this can most likely be improved a lot.
I did not go for any optional bonuses. I tried for the 15% one but it cost me more than I gained.

```
    a(z,['MEDIC!','Thanks!','Go Go Go!','Move Up!','Go Left','Go Right','Yes','No']).
    a(x,['Incoming','Spy!','Sentry Ahead!','Teleporter Here','Dispenser Here','Sentry Here','Activate ÜberCharge!','ÜberCharge Ready']).
    a(c,['Help!','For Pony!','Cheers','Jeers','Positive','Negative','Nice Shot','Good Job']).
    r:-read(X),read(Y),a(X,Z),nth1(Y,Z,A),write(A),1=2.

```

## Try it out

You can try it out online here.

1. Create new program
2. Paste code
3. As query, just use 'r' without quotes.

Input is first a letter then a number.

**Example:**
Input: z
Press Send
Input 3
Press Send
Outputs: Go Go Go!
**Edit:**
Saved 9 bytes with input from @Fatalize

# Answer
> 1 votes
# TeaScript, 225 - 6 = 219 bytes

```
b=xS(1)-1
x0¦'Z'?æMEDIC!,Tnks!,Go Go Go!,Move Up!,Go Left,Go Right,Y,No`.s`,`[b]:x0¦'X'?æîa,Spy!,SÀ^y AÊ%!,Tà({Zr He,DáÀ He,SÀ^y He,Acve Ã¼rCrge!`.s`,`[b]:x0¦'C'?æHelp!,PÇës!,CÊ8s,JÁÄ,PoÐÓve,Negive,Ni St,Good Job`.s`,`[b]:''

```

As short as I can get it. None of the bonuses save any bytes.

Try it online. If the outputs show up weird for you, tell me and I'll add a hex dump too deal with all the special characters.

# Answer
> 1 votes
# Mathematica, 368 - 24 = 344 bytes

```
Check[StringExtract["MEDIC!,Thanks!,Go Go Go!,Move Up!,Go Left,Go Right,Yes,No;Incoming,Spy!,Sentry Ahead!,Teleporter Here,Dispenser Here,Sentry Here,Activate ÜberCharge!,ÜberCharge Ready;Help!,Why am I saying this...,Cheers,Jeers,Positive,Negative,Nice Shot,Good Job",";"-><|"Z"->1,"X"->2,"C"->3|>[#~StringTake~1],","->FromDigits[#~StringDrop~1]]/._Missing->"",""]&

```

# Answer
> 1 votes
# Haskell, 397 -15% - 20 = 317.45 bytes

```
v=[('Z',["MEDIC!","Thanks!","Go Go Go!","Move Up!","Go Left","Go Right","Yes","No"]),('X',["Incoming","Spy!","Sentry Ahead!","Teleporter Here","Dispenser Here","Sentry Here","Activate ÜberCharge!","ÜberCharge Ready"]),('C',["Help!","Battle Cry","Cheers","Jeers","Positive","Negative","Nice Shot"])]
h(Just k)=k
m(x:y:s)=((h$lookup x v)!!((fromEnum y)-49))++('\n':m s)
m""=""
main=interact$concat.map m.lines

```

The input is taken from the standard input and it will output messages until there is no more input or an invalid input is given.

*P.S. :* Changing the order in which to apply the bonuses, according to a comment from the OP.

# Answer
> 1 votes
# AppleScript, (595-18)\*.85 = 490.45 Bytes

I beat *somebody*.

```
set a to{"MEDIC!","Thanks!","Go Go Go!","Move Up!","Go Left","Go Right","Yes","No","Incoming","Spy!","Sentry Ahead!","Teleporter Here","Dispenser Here","Sentry Here","Activate ÜberCharge!","ÜberCharge Ready","Help!","FOR APPLESCRIPT!","Cheers","Jeers","Positive","Negative","Nice Shot","Good Job"}
set c to true
considering case
repeat while c
set b to(display dialog""default answer"")'s text returned's characters
set n to 0
set k to item 1 of b
if k="C" then
set n to 0
else if k="X" then
set n to 8
else if k="Z" then
set n to 16
else
exit
end
display dialog(item(n+item 2 of b)of a)
end
end
```

Basically, I push all the items into an array. I get input through a text window (see gif below) and then an output window displays the referenced text.

The bonuses that apply are for the Battle Cry and the looping until invalid.

# Answer
> 1 votes
# Vitsy, 343 - 15 - 20 = 308 Bytes

I only qualify for the Battle Cry bonus and separating the segments by newline. My language can't do that other stuff. ;(

```
<OaZm+-1;)D]++2f[)-V'Z']+9[)-V'X']+1[)-V'C'Vi0;)/8^/21^2D-*68i
'!CIDEM'
'!sknahT'
'!oG oG oG'
'!pU evoM'
'tfeL oG'
'thgiR oG'
'seY'
'oN'
'gnimocnI'
'!ypS'
'!daehA yrtneS'
'ereH retropeleT'
'ereH resnepsiD'
'ereH yrtneS'
'!egrahCrebÜ etavitcA'
'ydaeR egrahCrebÜ'
'!pleH'
'syawlA ystiV'
'sreehC'
'sreeJ'
'evitisoP'
'evitageN'
'tohS eciN'
'boJ dooG'
```

This uses method structuring to push items to the stack according to a specific reference. Since it's easier to understand the way I originally wrote it, I have put the original code down below. The only difference is that the one above uses the `<` character to loop around the line backwards, one of the special ways that Vitsy loops around the line. The explanation for the top layer of code (in executed order) is below:

```
i86*-D1-D8M-);0iV'C'V-)[1+]'X'V-)[9+]'Z'V-)[f2++]D(;1-+mZ
i86*-                                                     Get the number value of the ASCII input.
     D1-D8M-);                                            If the number is within the range 0-8, continue the program. Otherwise, end execution.
              0                                           Placeholder of zero.
               iV                                         Get the character component and save it as a global variable.
                 'C'V-)[1+]                               If it's 'C', add 1
                           'X'V-)[9+]'Z'V-)[f2++]         Do the same things with 'X' and 'Z', adding 1 and a multiple of 8.
                                                 D(;      If after all this, the number is still zero, end execution.
                                                    1-+   Subtract one and add the components.
                                                       m  Execute that line number.
                                                        Z Print everything in the stack to STDOUT and quit.
```

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


title: Self-debugging code

text:
# Question
Title: Self-debugging code
**Your Task**

Write a program using ASCII characters. Five alphanumeric (0-9, A-Z, a-z) characters will be inserted at random into your program's source code. Your task is to detect and output these characters inserted into your program.

**Conditions**

* Your code cannot use any form of backup file.
* Your code may produce any unnecessary error messages, provided these are distinguishable from the actual output.
* The output may be on the screen or into a file.
* The output may also contain unnecessary characters, but no extra alphanumeric characters (excluding error messages).

**Winning**

The post with the largest vote count wins.

# Answer
# PHP, 0 bytes

PHP will simply echo the source until it sees an opening code tag `<?`.
> 15 votes

---
Tags: popularity-contest, error-correction
---


title: Print a Pentomino Rectangle

text:
# Question
Title: Print a Pentomino Rectangle
Write a program or function that takes no input but prints or returns a constant textual depiction of a rectangle made of the 12 distinct pentominoes:

The rectangle may have any dimensions and be in any orientation, but all 12 pentominoes must be used exactly once, so it will have area 60. Each different pentomino must be composed of a different printable ASCII character (you don't need to use the letters from above).

For example, if you chose to output this 20×3 pentomino rectangle solution:

Your program's output might look something like this:

```
00.@@@ccccF111//=---
0...@@c))FFF1//8===-
00.ttttt)))F1/8888=-

```

Alternatively, you might find it easier to golf this 6×10 solution:

```
000111
203331
203431
22 444
2   46
57 666
57769!
58779!
58899!
5889!!

```

Any rectangle solution will do, your program only needs to print one. (A trailing newline in the output is fine.)

This great website has loads of solutions for various rectangle dimensions and it's probably worth browsing them to make sure your solution is as short as possible. This is code-golf, the shortest answer in bytes wins.

# Answer
# Pyth, 37 bytes

```
jc4.HC"&f3ªªwril3:[·)ÌDU[r)ÌDA»

```

Demonstration

Uses a very straightforward approach: Use hex bytes as numbers. Convert to a hex number, base 256 encode that. That gives the magic string above. To decode, use Pyth's base 256 decoder function, convert to hex, split into 4 chunks, and join on newlines.
> 1 votes

# Answer
# Bash + common Linux utils, 50

```
xxd -s20 -p -c2 $0
#<30 bytes of binary data>

```

To recreate this from encoded base64:

```
base64 -d <<< eHhkIC1zMjAgLXAgLWMyICQwCiMiImaSaZlmkDAAMwSjRKNEqoGogYhRVVF7UXu7d3s= > pent.sh

```

Since there are 12 pentominoes, their colours are easily encoded in hex nybbles.

### Output:

```
$ ./pent.sh
2222
6692
6999
6690
3000
3304
a344
a344
aa81
a881
8851
5551
7b51
7bbb
777b
$

```
> 5 votes

# Answer
## CJam (44 bytes)

Given in xxd format because it contains control characters (including a raw tab, which plays *really* badly with MarkDown):

```
0000000: 2202 7e0d 8ef3 570d e085 e168 cf27 092c
0000010: a235 0c22 3235 3662 3562 332f 5f2c 2c2e
0000020: 7b32 2f27 412b 662b 7d7a 4e2a

```

which decodes to something along the lines of

```
"MAGIC STRING"256b5b3/_,,.{2/'A+f+}zN*

```

Slightly ungolfed online demo which doesn't contain control characters and so plays nicely with browser URI decoding library functions.

The basic principle is that since no piece spans more than 5 rows we can encode an offset from a linear function of the row number compactly (in base 5, in fact, although I haven't tried to determine whether this would always be the case).
> 5 votes

# Answer
# J, 49 bytes

```
u:64++/\|:3#.inv 1377859090 1567813024 1337683230

```

You can choose the letters in a way that the maximal increments between vertically adjacent letters are 2. We use this fact to encode vertical increments in base3. After that we create the running sums and add an offset to get the ASCII codes of the letters.

Definitely golfable. (I yet to find a way to input extended precision base36 numbers but simple base36 should save 3 bytes alone.)

Output:

```
AAA
ABA
BBB
DBC
DCC
DCC
DEE
DFE
FFE
FGE
FGG
GGH
HHH
IIH
JII
JJI
JKK
JKL
KKL
LLL

```

Try it online here.
> 4 votes

# Answer
# Microscript II, 66 bytes

Lets start with the simple answer.

```
"00.@@@ccccF111//=---\n0...@@c))FFF1//8===-\n00.ttttt)))F1/8888=-"

```

Hooray implicit printing.
> 2 votes

# Answer
# Ruby

# Rev 3, 55bytes

```
i=1
'S, OJ1*$HCH(#%0'.bytes{|e|puts "%x"%i+=e*130&9011}

```

As a further development on Randomra's idea, consider the output and difference table below. The difference table can be compressed as before, and expanded by multiplying by 65=binary 1000001 and applying a mask 11001100110011. However, Ruby does not work predictably with 8 bit characters (it tends to interpret them as Unicode.)

Surprisingly, the last column is entirely even. Because of this, in compression we can perform a rightshift on the data. This ensures all codes are 7 bit ASCII. In expansion we simply multiply by 65\*2=130 instead of 65.

The first column is also entirely even. Therefore we can add 1 to each element (32 to each byte) where necessary, to avoid any control characters. The unwanted 1 is removed by using the mask 10001100110011=9011 instead 11001100110011.

```
Solution 59 of document linked in question

Start0001

Out  Diff
2223 2222
2433 0210
2433 0000
4445 2012
6555 2110
6577 0022
6687 0110
6887 0200
8897 2010
aa99 2202
caa9 2010
cab9 0010
cbbb 0102
cdbd 0202
cddd 0020

```

Although I use 15 bytes for the table, I only really use 6 bits of each byte, which is a total of 90 bits. There are in fact only 36 possible values for each byte, which is 2.21E23 possibities in total. That would fit in 77 bits of entropy.

# Rev 2, 58 bytes, using Randomra's incremental approach

```
i=0
'UPEIP@bPHPBETTEPRADT'.bytes{|e|puts "%x"%i+=e*65&819}

```

Finally, something shorter than the naive solution. Randomra's incremental approach, with the bytepacking method of Rev 1.

# Rev 1, 72 bytes, golfed version of rev 0

Some changes were made to the baseline to accomodate a reordering of the code for golfing reasons, but still came in longer than the naive solution.

```
i=0
'UPUIYD&!)$&V*).);c+*'.bytes{|e|i+=1;puts "%x"%(i/2*273+(e*65&819))}

```

The offsets are encoded into each character of the magic string in base 4 in format `BAC`, ie with the 1's representing the righthand symbol, the 16's representing the middle symbol, and the lefthand symbol shoehorned into the 4's position. In order to extract them, the ascii code is multiplied by 65 (binary 1000001) to give `BACBAC`, then it is anded with 819 (binary 1100110011) to give `.A.B.C`.

Some of the ascii codes have the 7th bit set, i.e. they are 64 higher than the required value, to avoid control characters. Because this bit is removed by the mask 819, this is inconsequential, except when the value of `C` is 3, which causes a carryover. This has to be corrected in one place only (instead of `g` we have to use `c`.)

# Rev 0, ungolfed version

```
a= %w{000 010 000 201 100 100 011 021 110 120 011 112 111 221 211 221 122 123 112 222}
i=2
a.each{|e|puts "%x"%(i/2*273+e.to_i(16));i+=1}

```

**Output**

```
111
121
222
423
433
433
455
465
665
675
677
778
888
998
a99
aa9
abb
abc
bbc
ccc

```

**Explanation**

From the following solution, I subtract the baseline, giving the offset which I store as data. The baseline is regenerated as a hexadecimal number in the code by `i/2*273` (273 decimal = 111 hex.)

```
solution   baseline   offset
AAA        AAA        000
ABA        AAA        010
BBB        BBB        000
DBC        BBB        201
DCC        CCC        100
DCC        CCC        100
DEE        DDD        011
DFE        DDD        021
FFE        EEE        110
FGE        EEE        120
FGG        FFF        011
GGH        FFF        112
HHH        GGG        111
IIH        GGG        221
JII        HHH        211
JJI        HHH        221
JKK        III        122
JKL        III        123
KKL        JJJ        112
LLL        JJJ        222

```
> 1 votes

# Answer
# Foo, 66 Bytes

```
"00.@@@ccccF111//=---\n0...@@c))FFF1//8===-\n00.ttttt)))F1/8888=-"

```
> 0 votes

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


# Question
Title: Evaluating the score based from a chess FEN string
# Challenge

Forsyth–Edwards Notation (FEN) is a standard notation for describing a particular board position of a chess game. Your challenge is to evaluate the score using the FEN string. This is an example of a FEN string:

```
5k2/ppp5/4P3/3R3p/6P1/1K2Nr2/PP3P2/8

```

Using this string, you can calculate the material score for each color with the following score table:

> * p / P = Pawn = 1 point
> * n / N = Knight = 3 points
> * b / B = Bishop = 3 points
> * r / R = Rook = 5 points
> * q / Q = Queen = 9 points
> * k / K = King, these don't have any points because every legal position contains a king for each side

White pieces are designated using upper-case letters ("PNBRQK") while black pieces use lowercase ("pnbrqk"). Empty squares are noted using digits 1 through 8 (the number of empty squares), and "/" separates ranks.

From the example FEN string, we can calculate the material scores for each side:

For black:

> 5**k**2/**ppp**5/4P3/3R3**p**/6P1/1K2N**r**2/PP3P2/8
>
> All the black pieces left: p + p + p + p + r, this is a total of 9

For white:

> 5k2/ppp5/4**P**3/3**R**3p/6**P**1/1**K**2**N**r2/**PP**3**P**2/8
>
> All the white pieces left: P + R + P + N + P + P + P, this is a total of 13

The final score is determined with the following formula: **White score** \- **Black score** = **Final score**, so for the example the final score would be: 13 - 9 = 4

**Example** :

*Input:*

```
5k2/ppp5/4P3/3R3p/6P1/1K2Nr2/PP3P2/8

```

*Output:*

```
4

```

---

All rules apply here, the solution with the least amount of bytes wins.

---

# How to post

```
# Language Name, N bytes

 [code]

 [explaination, etc.]

```

# Answer
> 3 votes
# CJam, ~~28~~ ~~27~~ 26 bytes

```
0l{i32mdD%[5ZZX9]=\3%(*+}/

```

Try it online in the CJam interpreter.

### How it works

```
0l         e# Push a 0 (accumulator) and a line from STDIN.
{          e# For each character of that line:
  i32md    e#   Divide its code point by 32; push quotient and residue.
           e#   This serves two purposes:
           e#     1. The quotient will let us distinguish between uppercase
           e#        letters, lowercase letters and non-letters.
           e#     2. The residue will be the same for uppercase and lowercase
           e#        variants of the same letter.
  D%       e#   Take the residue modulo 13.
           e#   This maps R,N,B,P,Q -> 5,1,2,3,4
  [5ZZX9]= e#   Select the element at that index (5 ≡ 0) from [5 3 3 1 9].
  \        e#   Swap the quotient on top of the stack.
           e#   1 is digit or slash, 1 is uppercase, 2 is lowercase.
  3%(      e#   Take the quotient modulo 3 and subtract 1 from the result.
           e#   This maps 1,2,3 -> 0,1,-1.
  *+       e#   Multiply the generated integers.
  +        e#   Add the product to the accumulator.
}/         e#

```

# Answer
> 5 votes
# \>\<\>, ~~64~~ ~~57~~ ~~56~~ 53 bytes

```
"QRBNP"013359v
$0p4}:{:v?=1l<p4+' '{-
g4v?(0:i<+
n~<;

```

*(-7 bytes with some inspiration from @El'endiaStarman's answer, -3 bytes thanks to @randomra)*

### Explanation

The program uses the codebox as a lookup table. Out-of-range puts/gets don't work with the online interpreter, so this only works with the official Python interpreter.

The first line pushes the pieces, followed by the piece values. It also pushes an initial 0 to kick off the total for the third line.

The second line then puts the appropriate positive or negative value at the corresponding piece cell, e.g. `-1` is placed at `('p', 4)` and `1` is placed `('P', 4)`. The length of the stack is checked to make sure the loop runs 5 times.

After the loop is over, the stack consists of our single zero from the first line. For each char we perform a lookup at the corresponding cell in the table and add it to our total. By default, uninitialised cell values are 0, which is perfect for our purposes.

The last line merely prints the result.

# Answer
> 4 votes
## Ruby, 88 chars

```
->s{s.chars.map{|c|({P:1,N:3,B:3,R:5,Q:9}[:"#{c.upcase}"]||0)*(c.ord<90?1:-1)}.inject:+}

```

This is awkward and ugly, and there's probably a better way, but oh well.

Ruby's `{foo: 'bar'}` syntax is actually just sugar for `{:foo => 'bar'}`—this is annoying for golf because it means I have to convert the key to a symbol before using it to access a hash element (`:"#{x}"` is one char shorter than `x.to_sym`).

# Answer
> 4 votes
# Pip, 39 bytes

I'll take my brief turn in the lead before the CJam and Pyth answers come along...

```
$+Y(95<=>A_)*013359@{"KPNBRQ"@?UCa|0}Ma

```

Takes the FEN string as a command-line argument. Here's an explanation for a slightly ungolfed version:

```
$+({(95<=>Aa)*013359@("KPNBRQ"@?UCa|0)}Ma)

   {                                  }Ma   Map this function to each character in input:
                                UCa          Uppercase version of character
                      "KPNBRQ"@?             Its index in this string, nil if not present
                                   |0        Logical or with 0 (to turn nil into 0)
              013359@(               )       Index into this number to get piece's score
          Aa                                 ASCII value of character
     95<=>                                   1 if less than 95, -1 if greater than 95
    (       )*                               Multiply by the score
$+(                                      )  Sum all scores and autoprint result

```

# Answer
> 4 votes
# Perl, 44 bytes

```
#!perl -p
$\+=lc=~y/pnbrq/13359/r*(a cmp$_)for/\D/g}{

```

Counting the shebang as one, input is taken from stdin.

---

**Sample Usage**

```
$ echo 5k2/ppp5/4P3/3R3p/6P1/1K2Nr2/PP3P2/8 | perl fen-score.pl
4

```

---

**Explanation**

Pieces are transliterated with their respective values. If the piece is capitalized (i.e. less than `a`), its value is added to the sum, if not it is subtracted.

# Answer
> 3 votes
# JavaScript ES7, 79 bytes ~~124~~ ~~131~~

```
s=>(i=0,[for(q of s)i+={P:1,N:3,B:3,R:5,Q:9,p:-1,n:-3,b:-3,r:-5,q:-9}[q]||0],i)

```

As short as I can get. Uses fancy array comprehensions, to loop through the string.

# Explanation

```
s=>(     // Define function with an argument

    i=0, // this var will store the score

    [for(q of s)   // Loops through input
      i+=          // Adds to score by...

         {P:1,...,   // Defines value of each letter
          p:-1,...}  // Negative value instead, which will subtract
         || 0        // Otherwise add 0

    ], i           // Return score

```

# Answer
> 3 votes
## Minkolang 0.9, ~~72~~ ~~65~~ ~~64~~ ~~60~~ ~~44~~ ~~42~~ 41 bytes

```
13359"QRBNP"m5[d3~c~$r48*+0p0p]$I[o0q+]N.

```

Try it here.

Much thanks to Sp3000 for pointing out a much more efficient way to do this!

### Explanation

`13359"QRBNP"m` pushes the scores and their corresponding characters, then *interleaves* them, so the stack looks like this: `[1,80,3,78,3,66,5,82,9,81]`. Then `5[d3~c~$r48*+0p0p]` puts the score of each character, both lowercase and uppercase, at its location in the code space. Finally, `$I[o0q+]N.` loops through the input until it's empty, adding up the scores as it goes along.

# Answer
> 2 votes
# Perl 5, ~~71~~ 63 bytes

```
%a=(P,1,N,3,B,3,R,5,Q,9);$\+=$a{$_}||-$a{uc$_}for<>=~/./g;print

```

This modifies `$\` (the line separator for `print`, which starts false) for every alphanumeric in the string that's a key of the hash `%a` defined at the beginning. It increments `$\` by the value of the hash if the letter is a key as is; otherwise, it increments by *negative* the value of the hash if the uppercased letter is a key; otherwise it adds nothing.

Many thanks to primo for saving me eight bytes (in a comment on this answer).

---

I can save another byte with another suggestion from primo (thanks!): change `$a{$_}||-$a{uc$_}` to `$a{$_}-$a{$"^$_}`. But that's a rather different answer than mine, I think, so I'll not take the "credit" (of −1 byte) for it.

# Answer
> 2 votes
# CJam, 33 bytes

```
q{"PNBRQ"_el+#13359Ab_Wf*+0+=}%:+

```

Here's the super-naïve string-find way. Try it online.

# Answer
> 2 votes
# Ouroboros, 82

Ouroboros is an esolang I designed this week. Time to take it for a spin!

```
i.1+!57*(\m1(M\1).96>.@32*-.80=\.78=3*\.66=3*\.82=5*\81=9*++++\2*1\-*+
)L!4*(4Sn1(

```

Each line of single-char commands1 represents an ouroboros snake, wherein execution proceeds from head (start) to tail (end) and loops back to the head. The `(` and `)` commands let you eat part of the tail or regurgitate it, thus changing what commands get executed. If the instruction pointer is ever swallowed, the snake dies (stops executing). An Ouroboros program consists of one or more snakes executing in parallel. Each snake has a stack of its own, and there is also a shared stack.

1One exception, which distinguishes Ouroboros from many 2D languages: multi-digit numbers can be written straightforwardly, without having to do math or push a 0 first.

### Snake 1

The first snake reads a character (`i`) and checks whether it's -1 / EOF (`.1+!`). If so, it eats most of its tail, up to and including the `M` (`57*(`).

The snake then swaps the character code with the tally that is above it on the stack (`\`), moves the tally to the shared stack (`m`), and swallows another character (`1(`). If it had already swallowed a bunch, this means it swallows the `(` that the IP is currently on and dies. Otherwise, execution proceeds by moving the tally back to snake 1's stack, swapping it with the char code, and regurgitating the character that was previously swallowed (`M\1)`).

We then use math and stack operations to generate the appropriate score for the character. `.96>` tests whether it's lowercase or not; the subsequent `32*-` converts to uppercase. Then the long stretch from `.80=` to `81=9*++++` maps `P` -\> `1`, `N` -\> `3`, etc. Finally, `\2*1\-*` negates the score if the letter was lowercase, and `+` adds it to the running tally. The snake then loops and reads another character.

### Snake 2

The second snake starts with a regurgitate operation (`)`), which does nothing the first time through (since nothing's been swallowed yet, and also since popping an empty stack gives `0`). Next, it pushes the length of the shared stack to its own stack and logically negates (`L!`). This gives `1` if the stack is empty, `0` otherwise. The snake multiplies by 4 and eats that many characters (`4*(`).

If the shared stack was empty, this means the snake now ends before the `S`. It pushes `4` and loops back to the `)`, where it regurgitates the characters it just swallowed and starts over again.

If there was a value on the shared stack, however, no characters are swallowed and execution continues. The snake switches to the shared stack and outputs the number there (`Sn`); then it swallows its last character and dies (`1(`).

### Synchronization

The two snakes must be carefully synchronized so that there is never a value on the shared stack when snake 2 does its check, until the end of input is reached. Snake 1 puts a value on the shared stack briefly on each pass through its loop. Thus, snake 2's `L` command must never be executed between the `m` and `M` commands in snake 1. Fortunately, the snakes line up very well. Crucially, the length of snake 1's loop (70 instructions) is a multiple of snake 2's loop (7 instructions), so the two will never get out of sync:

```
i.1+!57*(\m1(M\1).96>.@32*-.80=\.78=3*\.66=3*\.82=5*\81=9*++++\2*1\-*+
)L!5*(5)L!5*(5)L!5*(5)L!5*(5)L!5*(5)L!5*(5)L!5*(5)L!5*(5)L!5*(5)L!5*(5
          |__|
       Danger zone

```

If the numbers hadn't worked out so perfectly, I would have padded one or both snakes with spaces to make them align as needed.

### All of this is very well, but I want to see it in action!

Here is the above program via Stack Snippet. Even on 1000 operations per second, it takes about 10 seconds to spit out the answer for the sample input--but it does get there!

```
// Define Stack class
function Stack() {
  this.stack = [];
  this.length = 0;
}
Stack.prototype.push = function(item) {
  this.stack.push(item);
  this.length++;
}
Stack.prototype.pop = function() {
  var result = 0;
  if (this.length > 0) {
    result = this.stack.pop();
    this.length--;
  }
  return result;
}
Stack.prototype.top = function() {
  var result = 0;
  if (this.length > 0) {
    result = this.stack[this.length - 1];
  }
  return result;
}
Stack.prototype.toString = function() {
    return "" + this.stack;
  }

// Define Snake class
function Snake(code) {
  this.code = code;
  this.length = this.code.length;
  this.ip = 0;
  this.ownStack = new Stack();
  this.currStack = this.ownStack;
  this.alive = true;
  this.wait = 0;
  this.partialString = this.partialNumber = null;
}
Snake.prototype.step = function() {
    if (!this.alive) {
      return null;
    }
    if (this.wait > 0) {
      this.wait--;
      return null;
    }
    var instruction = this.code.charAt(this.ip);
    var output = null;
    if (this.partialString !== null) {
      // We're in the middle of a double-quoted string
      if (instruction == '"') {
        // Close the string and push its character codes in reverse order
        for (var i = this.partialString.length - 1; i >= 0; i--) {
          this.currStack.push(this.partialString.charCodeAt(i));
        }
        this.partialString = null;
      } else {
        this.partialString += instruction;
      }
    } else if (instruction == '"') {
      this.partialString = "";
    } else if ("0" <= instruction && instruction <= "9") {
      if (this.partialNumber !== null) {
        this.partialNumber = this.partialNumber + instruction; // NB: concatenation!
      } else {
        this.partialNumber = instruction;
      }
      next = this.code.charAt((this.ip + 1) % this.length);
      if (next < "0" || "9" < next) {
        // Next instruction is non-numeric, so end number and push it
        this.currStack.push(+this.partialNumber);
        this.partialNumber = null;
      }
    } else if ("a" <= instruction && instruction <= "f") {
      // a-f push numbers 10 through 15
      var value = instruction.charCodeAt(0) - 87;
      this.currStack.push(value);
    } else if (instruction == "$") {
      // Toggle the current stack
      if (this.currStack === this.ownStack) {
        this.currStack = this.program.sharedStack;
      } else {
        this.currStack = this.ownStack;
      }
    } else if (instruction == "s") {
      this.currStack = this.ownStack;
    } else if (instruction == "S") {
      this.currStack = this.program.sharedStack;
    } else if (instruction == "l") {
      this.currStack.push(this.ownStack.length);
    } else if (instruction == "L") {
      this.currStack.push(this.program.sharedStack.length);
    } else if (instruction == ".") {
      var item = this.currStack.pop();
      this.currStack.push(item);
      this.currStack.push(item);
    } else if (instruction == "m") {
      var item = this.ownStack.pop();
      this.program.sharedStack.push(item);
    } else if (instruction == "M") {
      var item = this.program.sharedStack.pop();
      this.ownStack.push(item);
    } else if (instruction == "y") {
      var item = this.ownStack.top();
      this.program.sharedStack.push(item);
    } else if (instruction == "Y") {
      var item = this.program.sharedStack.top();
      this.ownStack.push(item);
    } else if (instruction == "\\") {
      var top = this.currStack.pop();
      var next = this.currStack.pop()
      this.currStack.push(top);
      this.currStack.push(next);
    } else if (instruction == "@") {
      var c = this.currStack.pop();
      var b = this.currStack.pop();
      var a = this.currStack.pop();
      this.currStack.push(c);
      this.currStack.push(a);
      this.currStack.push(b);
    } else if (instruction == ";") {
      this.currStack.pop();
    } else if (instruction == "+") {
      var b = this.currStack.pop();
      var a = this.currStack.pop();
      this.currStack.push(a + b);
    } else if (instruction == "-") {
      var b = this.currStack.pop();
      var a = this.currStack.pop();
      this.currStack.push(a - b);
    } else if (instruction == "*") {
      var b = this.currStack.pop();
      var a = this.currStack.pop();
      this.currStack.push(a * b);
    } else if (instruction == "/") {
      var b = this.currStack.pop();
      var a = this.currStack.pop();
      this.currStack.push(a / b);
    } else if (instruction == "%") {
      var b = this.currStack.pop();
      var a = this.currStack.pop();
      this.currStack.push(a % b);
    } else if (instruction == "_") {
      this.currStack.push(-this.currStack.pop());
    } else if (instruction == "I") {
      var value = this.currStack.pop();
      if (value < 0) {
        this.currStack.push(Math.ceil(value));
      } else {
        this.currStack.push(Math.floor(value));
      }
    } else if (instruction == ">") {
      var b = this.currStack.pop();
      var a = this.currStack.pop();
      this.currStack.push(+(a > b));
    } else if (instruction == "<") {
      var b = this.currStack.pop();
      var a = this.currStack.pop();
      this.currStack.push(+(a < b));
    } else if (instruction == "=") {
      var b = this.currStack.pop();
      var a = this.currStack.pop();
      this.currStack.push(+(a == b));
    } else if (instruction == "!") {
      this.currStack.push(+!this.currStack.pop());
    } else if (instruction == "?") {
      this.currStack.push(Math.random());
    } else if (instruction == "n") {
      output = "" + this.currStack.pop();
    } else if (instruction == "o") {
      output = String.fromCharCode(this.currStack.pop());
    } else if (instruction == "r") {
      var input = this.program.io.getNumber();
      this.currStack.push(input);
    } else if (instruction == "i") {
      var input = this.program.io.getChar();
      this.currStack.push(input);
    } else if (instruction == "(") {
      this.length -= Math.floor(this.currStack.pop());
      this.length = Math.max(this.length, 0);
    } else if (instruction == ")") {
      this.length += Math.floor(this.currStack.pop());
      this.length = Math.min(this.length, this.code.length);
    } else if (instruction == "w") {
      this.wait = this.currStack.pop();
    }
    // Any instruction not covered by the above cases is ignored
    if (this.ip >= this.length) {
      // We've swallowed the IP, so this snake dies
      this.alive = false;
      this.program.snakesLiving--;
    } else {
      // Increment IP and loop if appropriate
      this.ip = (this.ip + 1) % this.length;
    }
    return output;
  }

// Define Program class
function Program(source, speed, io) {
  this.sharedStack = new Stack();
  this.snakes = source.split(/\r?\n/).map(function(snakeCode) {
    var snake = new Snake(snakeCode);
    snake.program = this;
    snake.sharedStack = this.sharedStack;
    return snake;
  }.bind(this));
  this.snakesLiving = this.snakes.length;
  this.io = io;
  this.speed = speed || 10;
  this.halting = false;
}
Program.prototype.run = function() {
  if (this.snakesLiving) {
    this.step();
    this.timeout = window.setTimeout(this.run.bind(this), 1000 / this.speed);
  }
}
Program.prototype.step = function() {
  for (var s = 0; s < this.snakes.length; s++) {
    var output = this.snakes[s].step();
    if (output) {
      this.io.print(output);
    }
  }
}
Program.prototype.halt = function() {
  window.clearTimeout(this.timeout);
}
var ioFunctions = {
  print: function(item) {
    var stdout = document.getElementById('stdout');
    stdout.value += "" + item;
  },
  getChar: function() {
    if (inputData) {
      var inputChar = inputData[0];
      inputData = inputData.slice(1);
      return inputChar.charCodeAt(0);
    } else {
      return -1;
    }
  },
  getNumber: function() {
    while (inputData && (inputData[0] < "0" || "9" < inputData[0])) {
      inputData = inputData.slice(1);
    }
    if (inputData) {
      var inputNumber = inputData.match(/\d+/)[0];
      inputData = inputData.slice(inputNumber.length);
      return +inputNumber;
    } else {
      return -1;
    }
  }
};
var program = null;
var inputData = null;

function resetProgram() {
  var stdout = document.getElementById('stdout');
  stdout.value = null;
  if (program !== null) {
    program.halt();
  }
  program = null;
  inputData = null;
}

function initProgram() {
  var source = document.getElementById('source'),
    stepsPerSecond = document.getElementById('steps-per-second'),
    stdin = document.getElementById('stdin');
  program = new Program(source.value, +stepsPerSecond.innerHTML, ioFunctions);
  inputData = stdin.value;
}

function runBtnClick() {
  if (program === null || program.snakesLiving == 0) {
    resetProgram();
    initProgram();
  } else {
    program.halt();
    var stepsPerSecond = document.getElementById('steps-per-second');
    program.speed = +stepsPerSecond.innerHTML;
  }
  program.run();
}

function stepBtnClick() {
  if (program === null) {
    initProgram();
  } else {
    program.halt();
  }
  program.step();
}
```

```
.container {
  width: 100%;
}
.so-box {
  font-family: 'Helvetica Neue', Arial, sans-serif;
  font-weight: bold;
  color: #fff;
  text-align: center;
  padding: .3em .7em;
  font-size: 1em;
  line-height: 1.1;
  border: 1px solid #c47b07;
  -webkit-box-shadow: 0 2px 2px rgba(0, 0, 0, 0.3), 0 2px 0 rgba(255, 255, 255, 0.15) inset;
  text-shadow: 0 0 2px rgba(0, 0, 0, 0.5);
  background: #f88912;
  box-shadow: 0 2px 2px rgba(0, 0, 0, 0.3), 0 2px 0 rgba(255, 255, 255, 0.15) inset;
}
.control {
  display: inline-block;
  border-radius: 6px;
  float: left;
  margin-right: 25px;
  cursor: pointer;
}
.option {
  padding: 10px 20px;
  margin-right: 25px;
  float: left;
}
h1 {
  text-align: center;
  font-family: Georgia, 'Times New Roman', serif;
}
a {
  text-decoration: none;
}
input,
textarea {
  box-sizing: border-box;
}
textarea {
  display: block;
  white-space: pre;
  overflow: auto;
  height: 40px;
  width: 100%;
  max-width: 100%;
  min-height: 25px;
}
span[contenteditable] {
  padding: 2px 6px;
  background: #cc7801;
  color: #fff;
}
#stdout-container,
#stdin-container {
  height: auto;
  padding: 6px 0;
}
#reset {
  float: right;
}
#source-display-wrapper {
  display: none;
  width: 100%;
  height: 100%;
  overflow: auto;
  border: 1px solid black;
  box-sizing: border-box;
}
#source-display {
  font-family: monospace;
  white-space: pre;
  padding: 2px;
}
.activeToken {
  background: #f88912;
}
.clearfix:after {
  content: ".";
  display: block;
  height: 0;
  clear: both;
  visibility: hidden;
}
.clearfix {
  display: inline-block;
}
* html .clearfix {
  height: 1%;
}
.clearfix {
  display: block;
}
```

```
<!--
Designed and written 2015 by D. Loscutoff
Much of the HTML and CSS was taken from this Befunge interpreter by Ingo Bürk: http://codegolf.stackexchange.com/a/40331/16766
-->
<div class="container">
  <textarea id="source" placeholder="Enter your program here" wrap="off">i.1+!57*(\m1(M\1).96>.@32*-.80=\.78=3*\.66=3*\.82=5*\81=9*++++\2*1\-*+
)L!4*(4Sn1(</textarea>
  <div id="source-display-wrapper">
    <div id="source-display"></div>
  </div>
</div>
<div id="stdin-container" class="container">
  <textarea id="stdin" placeholder="Input" wrap="off">5k2/ppp5/4P3/3R3p/6P1/1K2Nr2/PP3P2/8</textarea>
</div>
<div id="controls-container" class="container clearfix">
  <input type="button" id="run" class="control so-box" value="Run" onclick="runBtnClick()" />
  <input type="button" id="pause" class="control so-box" value="Pause" onclick="program.halt()" />
  <input type="button" id="step" class="control so-box" value="Step" onclick="stepBtnClick()" />
  <input type="button" id="reset" class="control so-box" value="Reset" onclick="resetProgram()" />
</div>
<div id="stdout-container" class="container">
  <textarea id="stdout" placeholder="Output" wrap="off" readonly></textarea>
</div>
<div id="options-container" class="container">
  <div class="option so-box">Steps per Second: <span id="steps-per-second" contenteditable>1000</span>
  </div>
</div>
```

# Answer
> 2 votes
# JavaScript ES6, 71

As an anonymous function

```
n=>[...n].map(x=>t+=~(y='q   rnb p PBN R   Q'.search(x))?y-9|1:0,t=0)|t

```

# Answer
> 1 votes
# Python 3, 93

```
v=dict(zip('pbnrqPBNRQ',[1,3,3,5,9]*2))
print(sum(v.get(c,0)*(-1)**(c>'Z')for c in input()))

```

# Answer
> 1 votes
# Clojure/ClojureScript, 63 chars

```
#(apply +(map{"P"1"N"3"B"3"R"5"Q"9"p"-1"n"-3"b"-3"r"-5"q"-9}%))

```

Written using a ClojureScript REPL, should also be valid Clojure. Try it here. Enter it, then call it using `(*1 "FEN_string_here")`

Pretty straightforward. `{"P"1..."q"-9}` is a data structure literal for a map of "P" to 1, "N" to 3, etc. `map` takes the function as the first argument and the data structure to process as the second--in this case, it's using the feature that a data structure (the map literal) can act as its own accessor function. The string parameter (`%` from the function macro) can be treated as a list of individual character strings. Any character not in the map will end up as `nil` in the resulting list, which `+` happily ignores.

# Answer
> 1 votes
# Pyth, 25 bytes

```
-Fmsmhy/4@S5%Ck12@Gd_rBz2

```

Demonstration

This uses the following mapping formula for letters in `pbnrq`, if `k` is the letter:

```
(4 / (((chr(k) % 12) % 5) + 1) * 2 + 1

```

This is represented in Pyth as:

```
hy/4@S5%Ck12

```

First, the program creates the case-swapped version of the input, then on both strings filters for lowercase letters, then applies the above formula, then sums and subtracts the black values from the white values.

---
Tags: code-golf, chess
---


title: Dimensional Analysis

text:
# Question
Title: Dimensional Analysis
Calculate a product or ratio of SI units.

For example, `kg m / s s` (kilogram-meter per second squared) should return `N` (newton).

The input will always be either:

* A list of symbols for SI units, space-separated (representing a product) or
* The above, `/`, and the above (representing a ratio).

The input will never contain any other characters (such as numeric literals or other punctuation).

You may assume that this will always equal a single SI unit.

Use the following symbols:

```
Base quantities:
s               # second
m               # meter
kg              # kilogram
A               # ampere

Derived quantities:
N  = kg m / s s # newton
J  = N m        # joule
W  = J / s      # watt
Hz = W / J      # hertz
Pa = N / m m    # pascal
C  = s A        # coulomb
V  = J / C      # volt
F  = C / V      # farad
Ω  = V / A      # ohm      (you may use the O symbol instead, for a penalty of +3 bytes)
S  = A / V      # siemens
Wb = J / A      # weber
T  = Wb / m m   # tesla
H  = Wb / A     # henry

```

Examples:

```
m            => m
N m          => J
J / W        => s
A J / W      => C
T m m        => Wb
N / A m      => T
V s / A      => H
J S / F A    => V
s / s s      => Hz
Hz kg m Hz   => N
Hz s / Ω     => S
Wb / H       => A
V Pa S s / C => Pa
N s / m Hz   => kg
V A          => W
s / Ω        => F
J / A s A    => Ω

```

Shortest code (in bytes) wins.

# Answer
# CJam, ~~184~~ ~~105~~ ~~98~~ 96 bytes

```
00000000: 22 73 20 6d 20 6b 67 41 20 4e 20 4a 20 57 20 48  "s m kgA N J W H
00000010: 7a 50 61 43 20 56 20 46 20 ce a9 53 20 57 62 54  zPaC V F ..S WbT
00000020: 20 48 22 32 2f 53 66 2d 22 d6 9c 64 c6 a1 24 a4   H"2/Sf-"..d..$.
00000030: 4b f9 1c 4a 57 f4 61 79 31 ed 82 34 22 33 31 38  K..JW.ay1..4"318
00000040: 62 35 62 32 66 6d 34 2f 6c 53 25 32 24 32 24 65  b5b2fm4/lS%2$2$e
00000050: 72 22 2f 22 61 2f 3a 3a 2e 2b 3a 2e 2d 61 23 3d  r"/"a/::.+:.-a#=

```

The above is a hexdump; it can be reversed with `xxd -r`.

Verify all test cases at once in the CJam interpreter. 1

### Test run

```
$ LANG=en_US
$ cjam si.cjam <<< 'Hz s / Ω'; echo
S
$ cjam si.cjam <<< 'J / A s A'; echo
Ω

```

### Idea

We can encode each unit **u = sa mb kgc Ad** as the vector **tu = (a + c - d, b, c, d)**. 2

This way, for the input **u1 … un / v1 … vm**, we only have to calculate **(tu1 \+ … + tun) - (tv1 \+ … + tvm)** and check which unit it corresponds to.

### Code

```
"s m kgA N J W HzPaC V F Î©S WbT H"

2/     e# Split the string into chunks of length 2.
Sf-    e# Remove all spaces (if any) from each chunk.

"ÖdÆ¡$¤KùJWôay1í4"

318b   e# Convert from base 318 to integer.
5b     e# Convert from integer to base 5.
2fm    e# Subtract 2 from each base-5 digit.
4/     e# Split into chunks of length 4.
lS%    e# Read one line of input sand split it at spaces.
2$2$   e# Copy the unit names and the vector table.
er     e# Perform transliteration.
"/"a/  e# Split at "/".
::.+   e# Add the vectors of numerator and denominator (if any).
:.-    e# Subtract the resulting sums (or leave a single sum untouched).
a#     e# Find the index of the resulting vector in the vector table.
=      e# Retrieve the corresponding unit.

```

---

1 Note that, due to limitations of the online interpreter, I cannot use a different encoding for source code and I/O. Therefore, the symbol Ω shows up as its UTF-8 encoding (Î©). The official Java interpreter does not share this limitation.
2 This saves a few bytes over the straightforward mapping to **(a, b, c, d)**, since it shortens the range of the first coordinate.
> 7 votes

# Answer
# GNU sed, 1118

Way too long but gets the job done.

Score includes +1 for `-r` option to sed. As if it matters here. Score excludes comments.

```
### convert 2-letter units to 1-letter substitutes
s/kg/k/g
s/Hz/z/g
s/Pa/P/g
s/Wb/b/g
### remove spaces
s/ //g
### start label for main loop to render all in terms of base units
:
### convert N in denominator to s s / kg m
s|/(.*)N|ss/\1km|;t
### convert N in numerator to kg m / ss
s|N(.*)/|\1km/ss|;t
### convert N in non-rational to kg m / ss
s|N(.*)|\1km/ss|;t
### ... etc for all other derived units
s|/(.*)J|ss/\1kmm|;t
s|J(.*)/|\1kmm/ss|;t
s|J(.*)|\1kmm/ss|;t
s|/(.*)W|sss/\1kmm|;t
s|W(.*)/|\1kmm/sss|;t
s|W(.*)|\1kmm/sss|;t
s|/(.*)z|s/\1|;t
s|z(.*)/|\1/s|;t
s|z(.*)|\1/s|;t
s|/(.*)P|mss/\1k|;t
s|P(.*)/|\1k/mss|;t
s|P(.*)|\1k/mss|;t
s|C|sA|;t
s|/(.*)V|sssA/\1kmm|;t
s|V(.*)/|\1kmm/sssA|;t
s|V(.*)|\1kmm/sssA|;t
s|/(.*)F|kmm/\1ssssAA|;t
s|F(.*)/|\1ssssAA/kmm|;t
s|F(.*)|\1ssssAA/kmm|;t
s|/(.*)Ω|sssAA/\1kmm|;t
s|Ω(.*)/|\1kmm/sssAA|;t
s|Ω(.*)|\1kmm/sssAA|;t
s|/(.*)S|kmm/\1sssAA|;t
s|S(.*)/|\1sssAA/kmm|;t
s|S(.*)|\1sssAA/kmm|;t
s|/(.*)b|ssA/\1kmm|;t
s|b(.*)/|\1kmm/ssA|;t
s|b(.*)|\1kmm/ssA|;t
s|/(.*)T|ssA/\1k|;t
s|T(.*)/|\1k/ssA|;t
s|T(.*)|\1k/ssA|;t
s|/(.*)H|ssAA/\1kmm|;t
s|H(.*)/|\1kmm/ssAA|;t
s|H(.*)|\1kmm/ssAA|;t
### cancel out any units appearing in both numerator and denominator
s|(.)(.*/.*)\1|\2|;t
### remove trailing slash when rational cancels down to non-rational
s|/$||
### sort numerator and denominator kg > m > s > A
:A;s|([^/A])A|A\1|;tA
:s;s|([^/s])s|s\1|;ts
:m;s|([^/m])m|m\1|;tm
:k;s|([^/k])k|k\1|;tk
### Final replacements back to derived units
s|kmm/sssAA|Ω|
s|kmm/sssA|V|
s|kmm/sss|W|
s|kmm/ssAA|H|
s|kmm/ssA|Wb|
s|kmm/ss|J|
s|km/ss|N|
s|k/mss|Pa|
s|k/ssA|T|
s|/s|Hz|
s|ssssAA/kmm|F|
s|sssAA/kmm|S|
s|sA|C|
s/k/kg/

```
> 5 votes

# Answer
# Javascript ES6, 479 bytes

```
f=(s,b="s, m, gk, A, gkm,ss gkmm,ss gkmm,sss gkmm,AAss gk,mss As, gkmm,Asss AAssss,gkmm gkmm,AAsss AAsss,gkmm gkmm,Ass gk,Ass ,s".split` `,d="s m kgA N J W H PaC V F Ω S WbT Hz",p=s.split` / `.map(i=>i.split` `.map(i=>b[d.indexOf(i)/2].split`,`).reduce((p,c)=>(p[0]+=c[0],p[1]+=c[1],p),[[],[]])))=>(p[1]&&(p[0][0]+=p[1][1],p[0][1]+=p[1][0]),[x,y]=p[0].map(i=>[...i].sort().join``),d.match(/../g)[b.indexOf([...x].reduce((p,c)=>(y==(n=y.replace(c,""))&&(p+=c),y=n,p),"")+","+y)])

```

Ungolfed:

```
f=(s,                                              // define function, accept string to calculate
                                                   // vvv derived quantities reduced to base quantities in the form of <numerator>,<denominator>
   b="s, m, gk, A, gkm,ss gkmm,ss gkmm,sss gkmm,AAss gk,mss As, gkmm,Asss AAssss,gkmm gkmm,AAsss AAsss,gkmm gkmm,Ass gk,Ass ,s".split` `,
   d="s m kgA N J W H PaC V F Ω S WbT Hz",         // symbols list
   p=s.split` / `                                  // split input into [numerator,denominator]
      .map(i=>i.split` `                           // split numerator and denominator strings into list of symbols
               .map(i=>b[d.indexOf(i)/2].split`,`) // convert symbols to their base quantities
               .reduce((p,c)=>(p[0]+=c[0],p[1]+=c[1],p),[[],[]])) // consolidate base quantities
  )=>(
    p[1]&&(p[0][0]+=p[1][1],p[0][1]+=p[1][0]),     // if input was in form of numerator / denominator, reduce to numerator / 1
    [x,y]=p[0].map(i=>[...i].sort().join``),       // sort base quantities in numerator and denominator strings
    d.match(/../g)[b.indexOf(                      // derive symbol from base quantities
        [...x].reduce((p,c)=>(y==(n=y.replace(c,""))&&(p+=c),y=n,p),"")+","+y // remove duplicate symbols from numerator and denominator
  )])

```

Test Runs:

```
>> ["m","N m","J / W","A J / W","T m m","N / A m","V s / A",
    "J S / F A","s / s s","Hz kg m Hz","Hz s / Ω","Wb / H",
    "V Pa S s / C","N s / m Hz","V A","s / Ω","J / A s A"]
     .forEach(i=>console.log((i+" ".repeat(12)).slice(0,12)+"  ->  "+f(i)))

<< m             ->  m
   N m           ->  J
   J / W         ->  s
   A J / W       ->  C
   T m m         ->  Wb
   N / A m       ->  T
   V s / A       ->  H
   J S / F A     ->  V
   s / s s       ->  Hz
   Hz kg m Hz    ->  N
   Hz s / Ω      ->  S
   Wb / H        ->  A
   V Pa S s / C  ->  Pa
   N s / m Hz    ->  kg
   V A           ->  W
   s / Ω         ->  F
   J / A s A     ->  Ω

```
> 3 votes

---
Tags: code-golf, math, physics
---


title: Enumerating N-Dimensional Vectors

text:
# Question
Title: Enumerating N-Dimensional Vectors
Given a positive integer `k > 1` and a non-negative integer `i`, generate a `k`-tuple (or `k`-dimensional vector) of non-negative integers. For every `k`, the map from ℕ to ℕk, **must be bijective**. That is, every input `i` should produce a different tuple, and every possible tuple must be produced by some input `i`.

You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument and outputting the result via STDOUT (or closest alternative), function return value or function (out) parameter.

You may use any convenient, unambiguous, flat list format for the output.

Your solution should impose no artificial limits on `k` and `i` but you may assume that they fit into your language's native integer size. At the very least, you must support values up to `255`, though, even your native integer size is smaller than that.

For any `1 < k < 32`, `i < 2<sup>31</sup>`, your code should produce a result in a matter of seconds (of course, if your answer doesn't support `i` that large due to the previous rule, the limit is adjusted accordingly). This should be no issue: it's possible to solve this challenge such that it works up to 2128 in a few seconds, but the limit is there to avoid answers which actually iterate from `0` to `i` to find the result.

Please include in your answer a description of your chosen mapping and a justification for why it's bijective (this doesn't need to be a formal proof).

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

### Related Challenges

# Answer
# Pyth, ~~15~~ 12 bytes

```
ms+0_%Q>_zdQ

```

Test suite

My transformation is similar to one of xnor's, but in base 10. It works by unzipping the input into k separate numbers:

```
n = 21003034
k = 3

21003034
 1  3  4    134
2  0  3     203
  0  0        0

```

The numbers are ordered in decreasing position of the rightmost digit, so that all orderings of any group of numbers are possible.

The way the code works is we reverse the input, then slice off the last `0, 1, ... k-1` digits, then take every `k`th digit, reverse again, stick a `0` at the begining, and convert to int.
> 5 votes

# Answer
# CJam, 20 bytes

```
q~({4b2fmd2/z2fb~p}*

```

The mapping is bijective since it applies the mapping from this answer **k - 1** times.

The program reads the input as `i k`. Try it online in the CJam interpreter.

### Idea

We can construct a bijective mapping **f : N → N2** by defining **f(i)** as follows:

* Convert **i** into the array of its binary digits.
* Prepend a **0** to this array if there is an odd number of digits.
* Deinterleave the resulting array, forming to new ones in the process.
* Convert those arrays from base 2 to integer. Define **f1(i)** and **f2(i)** as the results.

To obtain a bijective mapping **g : N → N3**, we can define **g(n) := (f1(i), f1(f2(i)), f2(f2(i)))**.

To obtain a bijective mapping **h : N → N4**, we can define **h(i) := (g1(i), g2(i), f1(g3(i)), f2(g3(i)))**.

Continuing the above process, we eventually arrive at a bijective map **N → Nk**.

### Code

```
q~      e# Read and evaluate all input. This pushes i and k.
({      e# Do k-1 times:
  4b    e#   Convert the integer on the stack (initially i) to base 4.
  2fmd  e#   Replace each base-4 digit d by d/2 and d%2.
  2/    e#   Split into the chunks [d/2 d%2].
  z     e#   Transpose. This collects all quotients in one array and all
        e#   residues in another one.
  2fb   e#   Convert each array from base 2 to integer.
  ~     e#   Dump both integers on the stack.
  p     e#   Print the topmost one.
}*      e#

```
> 4 votes

# Answer
# J, ~~38~~ ~~28~~ 27 bytes

```
(({.,g^:_1@}.)g=:_ q:>:)~<:

```

This is a tacit, dyadic verb that takes **i** and **k** as left and right arguments. Try it online with J.js.

### Idea

We define a map **f : N → Nk** by **f(i) := (α1, … αk-1, p1αk…p2αk+1… - 1)**, where **⟨pn** is the sequence of prime numbers and **i + 1 = p1α1p2α2**.

By the Fundamental Arithmetic Theorem, the map **g : N → Nω** defined by **g(i) := (α1, α2, …)** (exponents of the prime factorization of **i + 1**) is bijective.

Since **f(i) = (g1(i), … gk-1(i), g-1(gk(i), gk+1(i), …))**, the map **f** is bijective as well.

### Code

```
                            Left argument: i -- Right argument: k
                         <: Decerement k.
(                      )~   Reverse the order of the arguments and apply the
                            dyadic verb inside the parentheses to k-1 and i.
              g=:            Define a monadic helper verb g:
                     >:       Increment its right argument.
                 _ q:         Calculate the exponents of the prime factorization.
                             (implicit) Apply g to i.
(            )               Apply the dyadic verb inside the parentheses to k-1
                             and (g i).
           }.                 Drop the first k-1 elements of (g i)...
          @                   and...
     g^:_1                    apply the inverse of g to the result.
  {.                          Take the first k-1 elements of (g i).
    ,                         Append the rightmost result to the leftmost one.

```
> 3 votes

# Answer
# CJam, 18 bytes

```
q~({)2bW%_1#p))b}*

```

It uses a more stupid formula.

Try it here.

### Explanation

```
q~          e# Read input.
({          e# Repeat k-1 times:
    )       e# Increment the current integer (initially i), to make it positive.
    2b      e# Convert to binary.
    W%      e# Reverse the binary.
            e# The result can be any non-empty binary string without trailing 0s.
    _1#     e# Find the position of the first 1, or the number of initial 0s.
    p       e# Print.
    )       e# Extract the final bit, which is always 1.
            e# An array that can be any binary string is left in the stack.
    )       e# Increment the 1 to make it 2.
    b       e# Convert the binary string to a number using base 2.
            e# Only the number of initial 0s doesn't affect the result,
            e# which is exactly what is printed before.
}*          e# The final integer is printed automatically when the program ends.

```

In summary, it maps a positive integer to:

1. The number of trailing zeros.
2. The original integer with trailing zeros removed, reversed, and the trailing (originally initial) 1 removed.
> 3 votes

# Answer
## Python 2, 62

```
lambda z,k:[int('0'+bin(z)[~i:1:-k][::-1],2)for i in range(k)]

```

This code is ugly and golfable, but the idea is very simple.

Pack `k` binary expansions into one by reading every `k`th digit with different offsets. For example, with `k=3`, the input `357` maps to `(3,0,7)`:

```
101100101 <- 357
  1  0  1 -> 5
 0  0  0  -> 0
1  1  1   -> 7

```

Zipping the numbers back together reverses it, so it's a bijection. In doing so, think of the binary expansions as having an infinite number of leading zeroes.
> 3 votes

# Answer
## Python 2, 72

```
q=lambda z:z and z%2+2*q(z/4)
g=lambda z,k:1/k*[z]or[q(z)]+g(q(z/2),k-1)

```

The function `q` acts on binary numbers by taking every second bit starting from the end. As a result `q(z), q(z>>1)` gives two numbers whose binary digits intersperse to give `z`. For example, 594 splits into 12 and 17.

```
1001010010   <- 594
 0 1 1 0 0   ->  12
1 0 0 0 1    ->  17

```

This is a bijection because we can zip the numbers back together to recover the original number.

The function `g` applies this bijection `k-1` times, expanding from a single element to a pair to a triple ... to a `k`-tuple. Each time, the last element is expanded to two elements. This is done recursively by mapping the input to a pair via the bijection, taking the first element of the pair for the first entry of the output, and applying the function recursively with `k-1` to the second element to produce the remaining entries.
> 1 votes

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


title: Three mutual quines

text:
# Question
Title: Three mutual quines
## The task

In this challenge, your task is to write three programs that form a kind of mutual quine-like system. Let's call the programs `A`, `B` and `C`. If one of the programs is given the source of another program as input, it shall output the source of the third program. For example, if `A` is given `B` as input, it outputs `C`. If the programs are given their own source as input, they shall output the three strings `"three"`, `"mutual"`, and `"quines"` (without quotes). In all cases, they may output one additional trailing newline. For any other inputs, the programs may do anything, including crash.

## Example

For example, suppose that the source codes of `A`, `B` and `C` are `aSdf`, `ghJk` and `zxcV`. Then the programs should behave as follows.

```
Source Input  Output
--------------------
aSdf   aSdf   three
aSdf   ghJk   zxcV
aSdf   zxcV   ghJk
ghJk   aSdf   zxcV
ghJk   ghJk   mutual
ghJk   zxcV   aSdf
zxcV   aSdf   ghJk
zxcV   ghJk   aSdf
zxcV   zxcV   quines

```

## Rules and scoring

The solutions `A`, `B` and `C` can be either functions or full programs, but they must be completely independent: **no** shared code is allowed. Standard loopholes and quine rules apply, so the programs can't access their own source codes in any way.

Your score is the combined byte count of `A`, `B` and `C`, lower score being better.

# Answer
> 17 votes
# CJam, ~~165~~ ~~147~~ ~~114~~ ~~108~~ 99 bytes

```
2 _ri^_q+@"quinesmutualthree"6/=?

```

```
1 _ri^_q+@"quinesmutualthree"6/=?

```

```
3 _ri^_q+@"quinesmutualthree"6/=?

```

*Thanks to @MartinBüttner for a suggestion that helped save 48 bytes!*

Try it online in the CJam interpreter.

### Verification

```
$ cat A
2 _ri^_q+@"quinesmutualthree"6/=?
$ cat B
1 _ri^_q+@"quinesmutualthree"6/=?
$ cat C
3 _ri^_q+@"quinesmutualthree"6/=?
$

$ cjam A < A
three
$ cjam A < B
3 _ri^_q+@"quinesmutualthree"6/=?
$ cjam A < C
1 _ri^_q+@"quinesmutualthree"6/=?
$

$ cjam B < A
3 _ri^_q+@"quinesmutualthree"6/=?
$ cjam B < B
mutual
$ cjam B < C
2 _ri^_q+@"quinesmutualthree"6/=?
$

$ cjam C < A
1 _ri^_q+@"quinesmutualthree"6/=?
$ cjam C < B
2 _ri^_q+@"quinesmutualthree"6/=?
$ cjam C < C
quines

```

### Idea

The set **{0, 1, 2, 3}** is a group under the operation **^** (binary exclusive OR), where each element is its own inverse.

If all three programs are identical except for the the first character (an element of **{0, 1, 2, 3}**), we can distinguish and print them easily:

* We start by XORing the digit at the beginning of the source code and the input.
* If the result is in **0**, source and input match.

Thus, we print one of the three words, selected by this common digit.
* If the result is not **0**, it is the element of **{1, 2, 3}** that is neither in the source nor in the input.

Thus, we prints it, followed by the rest of the input.

### How it works

```
2                                  e# Push the number N on the stack.
  _                                e# Push a copy.
    r                              e# Read a token from STDIN, i.e., the input up
                                   e# to and excluding the next whitespace char.
     i                             e# Cast to integer.
      ^                            e# XOR it with the copy of N. Result: X
       _                           e# Push a copy of the result.
        q+                         e# Append the rest of the input.
          @                        e# Rotate N on top of the stack.
           "quinesmutualthree"6/   e# Push ["quines" "mutual" "three"].
                                =  e# Select the word at index N.
                                 ? e# If X is non-zero, select the modified input;
                                   e# otherwise, select the word.

```

---
Tags: code-golf, quine
---


# Question
Title: A most excellent proof, too small to fi—!
You sit at home, rubbing your hands in a most evil fashion. *This time, I'll be able to set the community A-SPIN! I'll merely claim that I have proven this problem (which is of no doubt improvable) inside this book here…* You open to the first relevant page. You scrawl those words…

You are, of course, the evil Fermat! Haha, just kidding. You know it didn't happen like this; this is merely the narrative of his evil twin, Format. Format here is too lazy to condense his “proof” into the margin. He has therefore called upon you to do it for him.

**Objective** Given a proof (string), and a page (text block), "write" into the margin the proof.

## Valid page rules

A text block contains a page if and only if it meets the following requirements:

* The top and bottom borders are of the form `-{10,}\+$` (Regular expression for `-` at least ten times until a `+`, then the end of the line).
* Every non-top and non-bottom line must end with a `|`. There will be at least one such line.
* There will be at least five spaces from the last `|` in each line.
* All lines are the same width.

So the following is a valid page (the `.`s are for showing where the maximal margin border is):

```
-----------------+
Lorem Ipsum.     |
and other  .     |
latin crud .     |
           .     |
        EOF.     |
-----------------+

```

Here is another page with a wider margin:

```
------------------------+
Hello world!   .        |
How are you, to.        |
day? --Mme. B  .        |
               .        |
------------------------+

```

You are to write the given string in the margin, maintaining words that you can, as far as you can. For example, if `hello` fits on the next line, do not break it on the current line.

## I/Os

Filler text

```
Proof: This is a most excellent proof, too small for anyone!
Text:                       ; not a leading newline
------------------------+
Hello world!            |
How are you, to         |
day? --Mme. B           |
                        |
------------------------+
Output:
------------------------+
Hello world!    This a  |
How are you, to most    |
day? --Mme. B   excellen|
                t proof,|
------------------------+

Proof: Execute the member as an example to the others!
Text:
------------------------------------------------+
Contrary to popular belief, Lorem               |
Ipsum is not simply random text.                |
It has roots in a piece of classical            |
Latin literature from 45 BC, making             |
it over 2000 years old. Richard                 |
McClintock, a Latin professor at                |
Hampden-Sydney College in Virginia,             |
looked up one of the more obscure               |
Latin words, consectetur, from a                |
Lorem Ipsum passage, and going through          |
the cites of the word in classical              |
literature, discovered the undoubtable          |
source. Lorem Ipsum comes from...               |
------------------------------------------------+
Output:
------------------------------------------------+
Contrary to popular belief, Lorem      Execute  |
Ipsum is not simply random text.       the      |
It has roots in a piece of classical   member as|
Latin literature from 45 BC, making    an       |
it over 2000 years old. Richard        example  |
McClintock, a Latin professor at       to the   |
Hampden-Sydney College in Virginia,    others!  |
looked up one of the more obscure               |
Latin words, consectetur, from a                |
Lorem Ipsum passage, and going through          |
the cites of the word in classical              |
literature, discovered the undoubtable          |
source. Lorem Ipsum comes from...               |
------------------------------------------------+

Proof: Consider supercalifragilisticexpialidocious. Therefore, x.
Output:
-----------------------------------------+
sections 1.10.32 and                     |
1.10.33 of "de Finibus                   |
Bonorum et Malorum"                      |
(The Extremes of Good                    |
and Evil) by Cicero,                     |
written in 45 BC. This                   |
book is a treatise on                    |
the theory of ethics,                    |
very popular during the                  |
Renaissance. The first                   |
line of Lorem Ipsum,                     |
"Lorem ipsum dolor sit                   |
amet..", comes from a                    |
line in section 1.10.32.                 |
-----------------------------------------+
Output: Consider supercalifragilisticexpialidocious. Therefore, x.
-----------------------------------------+
sections 1.10.32 and     Consider        |
1.10.33 of "de Finibus   supercalifragili|
Bonorum et Malorum"      sticexpialidocio|
(The Extremes of Good    us. Therefore, x|
and Evil) by Cicero,     .               |
written in 45 BC. This                   |
book is a treatise on                    |
the theory of ethics,                    |
very popular during the                  |
Renaissance. The first                   |
line of Lorem Ipsum,                     |
"Lorem ipsum dolor sit                   |
amet..", comes from a                    |
line in section 1.10.32.                 |
-----------------------------------------+

Proof: Alex is a bird. All birds can fly. All things that fly are wrong. Ergo, Alex is wrong.
Text:
----------+
Sorry     |    ; 5 spaces.
----------+
Output:
----------+
Sorry Alex|
----------+

```

---

This is a , so the shortest program in bytes wins!

---

## Leaderboard

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

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

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

# Answer
> 4 votes
# Python 2, 334

```
p=open("f.txt",'r').readlines()
r,S,p=p[0][7:],p[2].strip(),p[3:-1]
import textwrap as t,itertools as i
m,l=max([len(s[:-5].strip()) for s in p]),len(S)-2
P = i.izip_longest(["{} {{:{}}}|".format(s[:m],l-m) for s in p],t.wrap(r,l-m),fillvalue="")
print S
for q in P:
 if not q[0]:break
 print q[0].format(q[1])
print S

```

**Sample IO** with contents of `f.txt` followed by code output

Case 1

```
Proof: This is a most excellent proof, too small for anyone!
Text:
------------------------+
Hello world!            |
How are you, to         |
day? --Mme. B           |
                        |
------------------------+

------------------------+
Hello world!    Proof:  |
How are you, to This is |
day? --Mme. B   a most e|
                xcellent|
------------------------+

```

Case 2

```
Proof: Consider supercalifragilisticexpialidocious. Therefore, x.
Output:
-----------------------------------------+
sections 1.10.32 and                     |
1.10.33 of "de Finibus                   |
Bonorum et Malorum"                      |
(The Extremes of Good                    |
and Evil) by Cicero,                     |
written in 45 BC. This                   |
book is a treatise on                    |
the theory of ethics,                    |
very popular during the                  |
Renaissance. The first                   |
line of Lorem Ipsum,                     |
"Lorem ipsum dolor sit                   |
amet..", comes from a                    |
line in section 1.10.32.                 |
-----------------------------------------+

-----------------------------------------+
sections 1.10.32 and     Consider superca|
1.10.33 of "de Finibus   lifragilisticexp|
Bonorum et Malorum"      ialidocious.    |
(The Extremes of Good    Therefore, x.   |
and Evil) by Cicero,                     |
written in 45 BC. This                   |
book is a treatise on                    |
the theory of ethics,                    |
very popular during the                  |
Renaissance. The first                   |
line of Lorem Ipsum,                     |
"Lorem ipsum dolor sit                   |
amet..", comes from a                    |
line in section 1.10.32.                 |
-----------------------------------------+

```

Case 3

```
Proof: Alex is a bird. All birds can fly. All things that fly are wrong. Ergo, Alex is wrong.
Text:
----------+
Sorry     |
----------+

----------+
Sorry Alex|
----------+

```

---
Tags: code-golf, typography
---


title: Get The Getters

text:
# Question
Title: Get The Getters
## The Task

I guess everybody loves automatic code generation and saving some time during work. You have to create a lot of classes and members during the day and you don't want to create all those `getters` manually.

The task is to write a program or function, that generates `getters` for all class members automatically for you.

---

## The Input

In our language objects are very simple. Names of classes and members must start with an chararacter from `[a-zA-Z]` and can only contain the characters `[a-zA-Z0-9]`. Here's an example:

```
class Stack {
    public overflow;
    protected trace;
    private errorReport;
}

```

---

## The Output

This is a valid output based on the given example:

```
class Stack {
    public overflow;
    protected trace;
    private errorReport;

    public function getOverflow() {
        return this->overflow;
    }

    public function getTrace() {
        return this->trace;
    }

    public function getErrorReport() {
        return this->errorReport;
    }
}

```

---

## The Getter

The requirements for a `getter` method are:

* The function name must start with `get` followed by the member name with an uppercase initial.
* The function has no parameters.
* To return a variable use `return this->memberName;`.
* `getters` and `setters` (*see **The Bonuses***) must be grouped and must come after all variable declarations.

**Example:**

```
private value1;
private value2;

public function getValue1() { return this->value; }
public function setValue1(value) { this->value = value; }

public function getValue2() { return this->value; }
public function setValue2(value) { this->value = value; }

```

---

## The Requirements

* Create a program or a function.
* Input can come from STDIN, command line arguments, function arguments, a file etc.
* Any output format is acceptable from a simple `return`-value to a file or writing to STDOUT.
* In- and output don't need to be formatted with whitespaces, newlines, tabs etc. This is a valid input: `class A{protected a;}`.
* You can assume that the input is valid and your program can handle unexpected input unexpected as well.

---

## The Bonuses

You can get down to 10% of your original byte count by withdrawing 30% for each feature:

**A:** Your program can address newly added variables and adds missing `getters` only (`public function getB() { return this->b; }` in this case):

```
class A {
    public a;
    public b;

    public function getA() { return this->a; }
}

```

**B:** Your program also generates `setters`:

```
class A {
    public a;
    public getA() { return this->a; }
    public setA(a) { this->a = a; }
}

```

**C:** Your program can handle static members:

```
class A {
    public static c;
    public static function getC() { return this->c; }
}

```

---

This is code golf – so shortest answer in bytes wins. Standard loopholes are disallowed.

# Answer
# Perl, 161 - 90% = 16.1 bytes

```
$/=0;$_=<>;for$g(/\bp\S*( +static)? +(\S*);/g){++$i%2?$c="public$g function":/get\u$g/||s/}$/$c get\u$g(){return this->$g;}\n$c set\u$g(x){this->$g=x;}\n}/}print

```
> 13 votes

# Answer
# Pyth, ~~198 bytes - 90% = 19.8 bytes~~ ~~187 - 90% = 18.7 bytes~~ 183 bytes - 90% = 18.3 bytes

```
pJ<rs.z6_1sm?}+=b"get"K+rh=Zed1tZJks[Y=N|@d1kGbK"(){return "=H+"this->"Z";}"YNG"set"K"(x){"H"=x;}"):Js["(?:(?:"=Y"public""|private|protected)(?!"=G" function "")( static)?) (\w+)")4\}

```

*Must...beat...Perl...*

## 187-byte/18.7-byte version

```
J<rs.z6_1s_+\},sm?}+=b"get"K+rh=Zed1tZJks[Y=N|@d1kGbK"(){return "=H+"this->"Z";}"YNG"set"K"(x){"H"=x;}"):Js["(?:(?:"=Y"public""|private|protected)(?!"=G" function "")( static)?) (\w+)")4J

```

## 198-byte/19.8-byte version

```
J<rs.z6_1s_,sm?}K+rhed1tedJks["public"=N|@d1k=G" function ""get"K"(){return this->"ed";}public"NG"set"K"("ed"){this->"ed"="ed";}"):J"(?:(?:public|private|protected)(?! function )( static)?) (\w+)"4J

```

**TODO:** More golfing!
> 10 votes

# Answer
# JavaScript ES6 (at the moment), ~~305~~ ~~289~~ 223 - 60% = 89.2 bytes

Was `256 - 30% = 179.2 bytes`

Qualifies for static and setter bonuses; now with extra ES6!

```
s=>s.replace(/\}$/,s.match(/(public|private)( static)* \w+/g).map(e=>{o=(r=e.split` `).pop();return(n=r.join` `)+` get${U=o[0].toUpperCase()+o.slice(1)}(){return this->${o};}${n} set${U}(${o}){this->${o}=${o};}`}).join``+"}")

```

## ES5 function, 115.6 bytes

```
function g(s){return s.replace(/\}$/,s.match(/(p(?:ublic|rivate))( static)* (\w+?);/gm).map(function(e){o=(r=e.split(" ")).pop().replace(/;/,"");return(n=r.join(" "))+" get"+(U=o[0].toUpperCase()+o.slice(1))+"(){return this->"+o+";}"+n+" set"+U+"("+o+"){this->"+o+"="+o+";}"}).join("")+"}")}

```
> 5 votes

# Answer
# CJam, 71 bytes

```
q';/W<_{S%W=:O(eu"public function get"\@"{return this->"O";}"}%\';f+\'}

```

Try it online in the CJam interpreter.
> 3 votes

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


# Question
Title: Unholy Grail Layout (Reverse Holy Grail Layout)
The Holy Grail Layout in CSS, is a full height, 3 column layout which consists of a fluid central column, and two side columns with fixed widths.

## Your Task is Simple!

Reverse it, make a fixed width central column, and two fluid width columns to the sides. The point is for them to take **All available space *both vertically and horizontally***. So if one adds elements above, or elements below (assume 100% width), your solution should shrink to accommodate. Same goes with elements on the sides. Your layout should fill 100% of its container's space.

## Restrictions

* HTML and CSS only (no JavaScript)
* IE8+ support mandatory
* Must work in all major browsers (it is, after all, a layout!)
* HTML and CSS must both be **valid**.
* No tables, it's supposed to be a layout, not an abomination.

## Winner

* Code with fewest characters wins, **excess spaces and newlines do not count, don't be afraid to be readable!** (I'm running the solution through a minifier)

---

Good luck!

# Answer
Simple

```
<div style=float:left;>L</div><div style=float:right;>R</div><div style="width: 100px;margin:0px auto;">C</div>

```
* Who said that it needs to be valid html?
* Who said that I need a doctype?
> 2 votes

# Answer
display:table-cell is compatible ie8+ (as seen in caniuse)

```
<!DOCTYPE html>
<head>
  <title>a</title>
  <style>
    html { height: 100%}
    body { margin: 0; display: table; height: 100%; width: 100%}
    .c { display: table-cell }
    .c2 { width: 6em }
  </style>
</head>

<a class="c c1">a</a>
<a class="c c2">z</a>
<a class="c c3">e</a>

```

This is html/css valid, tried here : https://validator.w3.org/nu/#textarea

That's why there is head/title stuff. But you can ommit html/body, according to the specs.

The issue I see is when you want to put something above/below, you have to make them `display: table-row`, and probably specify a `height`.
> 1 votes

# Answer
Guaranteed to work in all browsers - old and new:

```
<table>
<tr>
    <td>a</td>
    <td class="f">b</td>
    <td>c</td>
</tr>
</table>

```

CSS:

```
table, tr{
    width: 100%;
}
.f{
    width:100px;
}

```

Here's a fiddle: http://jsfiddle.net/8QWBX/1/

Note: if you want to make it shorter (but fail HTML standards) you may remove the `tr` tag and its styling. This will save 12 characters the way I see it.
> 0 votes

---
Tags: code-golf, css
---