title: Path of exile map combinations

text:
# Question
Title: Path of exile map combinations
This question will feature a mechanic from the game "Path Of Exile" in this game there are things called **MAPS** they are items that you can use to open high level areas, you can also combine 3 of them to get a upgraded one which will be the task of this challenge. The upgrade combinations are as follow:

```
A Crypt Map 68 -> Sewer Map
E Dungeon Map 68 -> Channel Map
I Grotto Map 68 -> Thicket Map
O Dunes Map 68 -> Mountain Ledge Map
U Pit Map 68 -> Cemetery Map
T Tropical Island Map 68 -> Arcade Map
N Desert Map 68 -> Wharf Map
S Sewer Map 69 -> Ghetto Map
H Channel Map 69 -> Spider Lair Map
R Thicket Map 69 -> Vaal Pyramid Map
D Mountain Ledge Map 69 -> Reef Map
L Cemetery Map 69 -> Quarry Map
C Arcade Map 69 -> Mud Geyser Map
M Wharf Map 69 -> Museum Map
W Ghetto Map 70 -> Arena Map
F Spider Lair Map 70 -> Overgrown Shrine Map
G Vaal Pyramid Map 70 -> Tunnel Map
Y Reef Map 70 -> Shore Map
P Quarry Map 70 -> Spider Forest Map
B Mud Geyser Map 70 -> Promenade Map
V Museum Map 70 -> Arena Map
K Arena Map 71 -> Underground Sea Map
J Overgrown Shrine Map 71 -> Pier Map
X Tunnel Map 71 -> Bog Map
Q Shore Map 71 -> Graveyard Map
Z Spider Forest Map 71 -> Coves Map
Ó Promenade Map 71 -> Villa Map
É Underground Sea Map 72 -> Temple Map
Á Pier Map 72 -> Arachnid Nest Map
Í Bog Map 72 -> Strand Map
Ú Graveyard Map 72 -> Dry Woods Map
Ü Coves Map 72 -> Colonnade Map
Ö Villa Map 72 -> Catacomb Map
Ä Temple Map 73 -> Torture Chamber Map
Ë Arachnid Nest Map 73 -> Waste Pool Map
Ï Strand Map 73 -> Mine Map
Æ Dry Woods Map 73 -> Jungle Valley Map
Œ Colonnade Map 73 -> Labyrinth Map
Ñ Catacomb Map 73 -> Torture Chamber Map
Ÿ Torture Chamber Map 74 -> Cells Map
1 Waste Pool Map 74 -> Canyon Map
2 Mine Map 74 -> Dark Forest
3 Jungle Valley Map 74 -> Dry Peninsula Map
4 Labyrinth Map 74 -> Orchard Map
5 Cells Map 75 -> Underground River Map
6 Canyon Map 75 -> Arid Lake Map
7 Dark Forest Map 75 -> Gorge Map
8 Dry Peninsula Map 75 -> Residence Map
9 Orchard Map 75 -> Underground River Map
0 Underground River Map 76 -> Necropolis Map
? Arid Lake Map 76 -> Plateau Map
! Gorge Map 76 -> Bazaar Map
( Residence Map 76 -> Volcano Map
) Necropolis Map 77 -> Crematorium Map
- Plateau Map 77 -> Precinct Map
/ Bazaar Map 77 -> Academy Map
\ Volcano Map 77 -> Springs Map
| Crematorium Map 78 -> Shipyard Map
= Precinct Map 78 -> Overgrown Ruin Map
* Academy Map 78 -> Village Ruin Map
† Springs Map 78 -> Arsenal Map
‡ Shipyard Map 79 -> Wasteland Map
§ Overgrown Ruin Map 79 -> Courtyard Map
[ Village Ruin Map 79 -> Excavation Map
] Arsenal Map 79 -> Waterways Map
_ Wasteland Map 80 -> Palace Map
~ Courtyard Map 80 -> Shrine Map
{ Excavation Map 80 -> Maze Map
} Waterways Map 80 -> Palace Map
© Palace Map 81 -> Abyss Map
€ Shrine Map 81 -> Abyss Map
< Maze Map 81 -> Colosseum Map
> Vaal Temple Map 81 -> Colosseum Map
µ Abyss Map 82
» Colosseum Map 82

```

These lines follow this sheme:

```
Symbol of the map | Name of the map | Level of the map | Map received from combining

```

Note that the abyss and colosseum map dont combine into higher level ones since they are the highest level.

**INPUT:**
Your input will be a a string of Symbols which correspond to the map symbols, example AAAEE which would mean 3 x crypt map and 2 x dungeon map.

**OUTPUT:**
The output will be again a string of symbols which would represent the highest possible combination of the input maps. Any combination of output is allowed as long as it features every map.

**EXAMPLES:**

```
INPUT: A
OUTPUT: A

INPUT: AAA
OUTPUT: S

INPUT: AAAEEEIII
OUTPUT: SHR or HRS or RHS or SRH

INPUT: AAAAAAAAAE
OUTPUT: WE or EW

INPUT: »»»»»
OUTPUT: »»»»»

```

**SCORING:**
Your score will be calculated through this formula, which is also actualy used in the game to calculate damage reduction:

```
POINTS = 1000 - (ByteCount / (ByteCount + 1000) * 1000);

```

**BONUS POINTS:**

1. If you add runlenght encoding to both the input and output then multiply your points by 1.2, example 3A input instead of AAA. You can omit the standard input if your answer will support this.
2. If your program will allow the actual map names as input/output then multiply your points by 1.5, you can ommit the "map" part of the map name so as a example input "**crypt crypt crypt**" and output "**sewer**" is ok. Your script also doesnt need to understand the standard input anymore if you use this method. This method also requires a space between names in both the input and output.
3. If your output string goes from lowest level map to highest then multiply your points by 1.08, maps with the same level dont need to be sorted in any particular way.

You can combine all 3 bonus points.

**ANSWER WITH THE MOST POINTS WINS!**

# Answer
> 5 votes
# ~~Haskell, 306 bytes, points = 766 * 1.2 * 1.08 = 992.343~~

```
import Control.Arrow;main=print=<<(\x->unwords.map(\(x,y)->show x++[y]).filter((>0).fst).g=<<(read***head)<$>(lex=<<words x))<$>getLine;g z@(x,y)|x<3=[z]|1<2=maybe[z](\w->(x`mod`3,y):g(x`div`3,w)).lookup y$words"ASWKÉÄŸ50)|‡_©µ EHFJÁË16?-=§~€µ IRGXÍÏ27!/*[{<» ULPZÜŒ490 TCBÓÖÑŸ NMVK >»">>= \x->zip x$tail x

```

I could squeeze out a few more bytes should anyone beat me, but for now I'm going to leave it as is.

# ~~Haskell, 284 bytes, points = 779 * 1.2 * 1.08 = 1009.346~~

```
import Control.Arrow;main=interact$show.(\x->unwords[show a++[b]|(a,b)<-g=<<second head<$>(reads=<<words x),a>0]);g z@(x,y)|x<3=[z]|1<2=maybe[z](\w->(x`mod`3,y):g(x`div`3,w)).lookup y$words"ASWKÉÄŸ50)|‡_©µ EHFJÁË16?-=§~€µ IRGXÍÏ27!/*[{<» ULPZÜŒ490 TCBÓÖÑŸ NMVK >»">>=(flip zip=<<tail)

```

I did squeeze out a few more bytes regardless.

# Haskell, 248 bytes, points = 801 * 1.2 * 1.08 = 1038.462

```
main=interact$ \x->unwords[show a++b|(a,b)<-(reads=<<words x)>>=g,a>0];g z@(x,y)|x<3=[z]|1<2=maybe[z](\w->(x`mod`3,y):g(x`div`3,w))$pure<$>lookup(head y)(zip<*>tail=<<words"ASWKÉÄŸ50)|‡_©µ EHFJÁË16?-=§~€µ IRGXÍÏ27!/*[{<» ULPZÜŒ490 TCBÓÖÑŸ NMVK >»")

```

I am also going to leave a few tables I made for others to use:

```
68   AS EH IR OD UL TC NM
69   SW HF RG DY LP CB MV
70   WK FJ GX YQ PZ BÓ VK
71   KÉ JÁ XÍ QÚ ZÜ ÓÖ
72   ÉÄ ÁË ÍÏ ÚÆ ÜŒ ÖÑ
73   ÄŸ Ë1 Ï2 Æ3 Œ4 ÑŸ
74   Ÿ5 16 27 38 49
75   50 6? 7! 8( 90
76   0) ?- !/ (\
77   )| -= /* \†
78   |‡ =§ *[ †]
79   ‡_ §~ [{ ]}
80   _© ~€ {< }©
81   ©µ €µ <»
82   µ  µ  »

     >»

```

You read it from top to bottom, two letters at a time (or ignore odd columns). Three A's make a S, Three S-es makes a W and so on. Chains that end simply wrap around to the first column on the next line. No three maps makes a \>.

Here are the chains of maps you can make with no repeats:

```
ASWKÉÄŸ50)|‡_©µ
EHFJÁË16?-=§~€µ
IRGXÍÏ27!/*[{<»
ULPZÜŒ490
TCBÓÖÑŸ
NMVK
>»

```

# Answer
> 4 votes
## **C#, ~~364~~ 361 bytes, points = 734.754 x 1.08 = 793.534**

Might as well get the ball rolling with a big one...

```
string F(string s){var m=@"AEIOUTNSHRDLCMWFGYPBVKJXQZÓÉÁÍÚÜÖÄËÏÆŒÑŸ1234567890?!()-/\|=*†‡§[]_~{}©€<>µ»";var g=new int[75];foreach(int a in s.Select(c=>m.IndexOf(c)))g[a]++;int i=0;for(;i<73;){g[m.IndexOf(@"SHRDLCMWFGYPBVKJXQZÓKÉÁÍÚÜÖÄËÏÆŒÑŸ1234Ÿ567890?!(0)-/\|=*†‡§[]_~{}©€<©µµ»»"[i])]+=g[i]/3;g[i++]%=3;}return string.Join("",g.Zip(m,(x,l)=>"".PadLeft(x,l)));}

```

I've yet to think of a clever way of mapping the seemingly random encoded characters to their relative worth, so I've used a brute force method for now.

This implements bonus feature 3 by virtue of the method of grouping, which nets me a cool 58ish points.

*Edit: Rewrote output loop into join/zip*

# Answer
> 2 votes
# SWI-Prolog, 354 bytes, points = 738.552 * 1.08 = 797.64

```
a(A,Z):-msort(A,S),b(S,[],B),(msort(B,S),string_codes(Z,S);a(B,Z)).
b(X,R,Z):-(X=[A,A,A|T],nth0(I,`AEIOUTNSHRDLCMWFGYPBVKJXQZÓÉÁÍÚÜÖÄËÏÆŒÑŸ1234567890?!()-/\\|=*†‡§[]_~{}©€<>`,A),nth0(I,`SHRDLCMWFGYPBVKJXQZÓKÉÁÍÚÜÖÄËÏÆŒÑŸ1234Ÿ567890?!(0)-/\\|=*†‡§[]_~{}©€<©µµ»»`,B),b(T,[B|R],Z);X=[A|T],b(T,[A|R],Z);Z=R).

```

Expects inputs as codes strings, for example `a(`AAAEEEIII`,Z).` will output `Z = "SRH"`.

I'll see what I can do about the other two bonuses...

# Answer
> 2 votes
# ~~Javascript, 432 bytes, points = 698.32 * 1.08 * 1.2 = 905.02~~

```
function g(r){for(var n="AEIOUTNSHRDLCMWFGYPBVKJXQZÓÉÁÍÚÜÖÄËÏÆŒÑŸ1234567890?!()-/|=*†‡§[]_~{}©€<>",t="SHRDLCMWFGYPBVKJXQZÓKÉÁÍÚÜÖÄËÏÆŒÑŸ1234Ÿ567890?!(0)-/|=*†‡§[]_~{}©€<©µµ»»",a=/([^»µ])\1{2}/,c=/\d+/,e=/\d+(.)/,f=0;0!==(f=r.match(c)-0);)r=r.replace(c,Array(f).join(r.match(e)[1]));for(;null!==(f=r.match(a));)r=r.replace(a,t.charAt(n.search(f[1])));return r.split("").sort(function(r,t){return n.indexOf(r)-n.indexOf(t)}).join("")}

```

# ECMAScript 6, 417 bytes, points = 705.72 * 1.08 * 1.2 = 914.61

## No online minifier version: (last version was passed through a minifier)

```
let F=s=>{for(var m="AEIOUTNSHRDLCMWFGYPBVKJXQZÓÉÁÍÚÜÖÄËÏÆŒÑŸ1234567890?!()-/\|=*†‡§[]_~{}©€<>",r="SHRDLCMWFGYPBVKJXQZÓKÉÁÍÚÜÖÄËÏÆŒÑŸ1234Ÿ567890?!(0)-/\|=*†‡§[]_~{}©€<©µµ»»",x=/([^»µ])\1{2}/,y=/\d+/,z=/\d+(.)/,p=0;(p=s.match(y)-0)!==0;)s=s.replace(y,Array(p).join(s.match(z)[1]));for(;(p=s.match(x))!==null;)s=s.replace(x,r.charAt(m.search(p[1])));return s.split('').sort((a,b)=>m.indexOf(a)-m.indexOf(b)).join('');};

```

Run with Babel

---

Tested with the following inputs:

1. `AAA`
2. `AAAEEEIII`
3. `3A3E3I`
4. `»»»»»`
5.

## General solution

Basically using regex whenever possible

```
var m = "AEIOUTNSHRDLCMWFGYPBVKJXQZÓÉÁÍÚÜÖÄËÏÆŒÑŸ1234567890?!()-/\|=*†‡§[]_~{}©€<>";
var r = "SHRDLCMWFGYPBVKJXQZÓKÉÁÍÚÜÖÄËÏÆŒÑŸ1234Ÿ567890?!(0)-/\|=*†‡§[]_~{}©€<©µµ»»";
var x = /([^»µ])\1{2}/;

while((p=s.match(x))!==null){
    s=s.replace(x,r.charAt(m.search(p[1])));
}

```

Nothing fancy here, just replacing a match for the respective output.

### For the 1.2 Bonus

Regexing the numbers and the following letter, readable code goes like this:

```
// variable 's' is the input string

var y = /\d+/;
var z = /\d+(.)/;

var p = 0;

while((p=s.match(y)-0) !== 0) {
    s=s.replace(y,Array(p).join(s.match(z)[1]));
}

```

As you can see, `s.match(y) - 0`, the matched string is subtracted by 0, that's to force a parse int without actually calling `parseInt()`.

Also `Array(p).join(s.match(z)[1])` basically joins an array of `p` **empty** elements, with the character found in the match, that's an easy way to print a letter (let's say `E`) `p` amount of times.

### For the 1.08 Bonus

Sorting algorithm:

```
s.split('').sort(function(a,b) {
    return m.indexOf(a) - m.indexOf(b);
}).join('');

```

# Answer
> 2 votes
# Javascript (ES6), 389 bytes, points = 719.942 * 1.08 * 1.2 = 933.045

In the lead, at least for now...

```
a=>{a=a.replace(/(\d)(.)/g,(m,A,B)=>B.repeat(A)),x='AEIOUTNSHRDLCMWFGYPBVKJXQZÓÉÁÍÚÜÖÄËÏÆŒÑŸ1234567890?!()-/\\|=*†‡§[]_~{}©€<>',y='SHRDLCMWFGYPBVKJXQZÓKÉÁÍÚÜÖÄËÏÆŒÑŸ1234Ÿ567890?!(0)-/\\|=*†‡§[]_~{}©€<©µµ»»',s=_=>(a=[...a].sort((a,b)=>x[I='indexOf'](a)-x[I](b)).join``);s();for(i=0;i<x.length;i++){a=a.replace(new RegExp(`[${('\\|'[I](h=x[i])<0?'':'\\')+h}]{3}`,'g'),y[i]);s()}return a}

```

Try it here:

```
F=a=>{a=a.replace(/(\d)(.)/g,(m,A,B)=>B.repeat(A)),x='AEIOUTNSHRDLCMWFGYPBVKJXQZÓÉÁÍÚÜÖÄËÏÆŒÑŸ1234567890?!()-/\\|=*†‡§[]_~{}©€<>',y='SHRDLCMWFGYPBVKJXQZÓKÉÁÍÚÜÖÄËÏÆŒÑŸ1234Ÿ567890?!(0)-/\\|=*†‡§[]_~{}©€<©µµ»»',s=_=>(a=[...a].sort((a,b)=>x[I='indexOf'](a)-x[I](b)).join``);s();for(i=0;i<x.length;i++){a=a.replace(new RegExp(`[${('\\|'[I](h=x[i])<0?'':'\\')+h}]{3}`,'g'),y[i]);s()}return a};

input=document.getElementById("input");
p=document.getElementById("a");
input.addEventListener("keydown", function(){
  setTimeout(function(){p.innerHTML = F(input.value);},10);
})
```

```
<form>Type your text here: <input type="text" id="input" value="3A"/></form>

<h3>Output:</h3>
<p id="a">S</p>
```

The 1.2 bonus is somewhat tricky in its formatting. If you want to input a regular number, place a `1` before it.

Basically, this scans through every character that has an upgrade (all except `µ` and `»`), then finds all sets of three of this character and replaces them with the upgraded char. Sorting after each `.replace` was the best way to make sure this always works properly, so that was an automatic bonus. The 1.2 bonus was a little harder, but I got it sorted out in 45 bytes. The 1.5 bonus is just not worth it at all, as it requires a ton more encoding and would at least double the length.

As always, suggestions are very welcome!

---
Tags: code-challenge
---


title: Switch program flow from external pulse

text:
# Question
Title: Switch program flow from external pulse
You work for the military as a coder and are responsible for writing software to control missiles. Your task is to write a program or function that will output a code sequence (any length ASCII string) to launch a missile. The program should be based on a loop taking the code sequence from memory and output it in a particular order. Then the code is sent to the missile controller, which launches the missile.

However, you work as one of our spies. We believe that writing the sequence in reverse order will cause the missile to explode in the silo as a form of sabotage! We are able to change by some way (the method is top secret and it is not important how we can do it) one byte of code in the missile controller software. You need to write such a program that changing one byte during the loop will change the loop so that the text will be typed in reverse order.

### The task

Write a program or function in any language of your choice that will use a loop to return ASCII sequence. The sequence can be stored in the memory or given from `stdin` or equivalent, function arguments, being a string or array of any length (\>0, \<=255 characters).

Changing one character or byte in the loop, in any iteration, should reverse the loop direction, making characters that have already been returned show again, from last to first.

For example, if the input text (the missile code sequence) would be `abcdefgh` and the loop switch begins in the 5th iteration, the result should be `abcdedcba`. We believe this would be enough to destroy the missiles.

However, we know that they are aware of our new weapon. We are not able to switch from or to any of the following characters, in your code:

* `+` (plus sign, addition)
* `-` (minus sign, subtraction, or unary negative operator)
* `>` and `<` (greater than, less than), we also expect this won't work for `<<` and `>>` operators (bit shift left/right), however you can change commands doing bit shift, if there are any in your language (eg. change `shr` to `shl`).

You may not change a whitespace character to a non-whitespace character (eg. you cannot change `[space]or` to `xor`).

You may not assign any constants or variables to values or codes so you will bypass the said characters (e.g. you cannot say `p = 1; n = -1;` and change `p` to `n` in such a line `i = i + p`).

If necessary, after the character switch, you are allowed to leave the loop and output the rest of the string in any way you like.

You are free to choose if one and only one character/byte will be switched or all of the same value. For example, you may switch all occurrences of `*` to `/`.

Any `GOTO`, `DJNZ` and equivalents also do count as loops.

The program must return no errors, so the enemy will never realize what has happened. The program should return the whole string if no switch would be made.

This is a codegolf, so shortest answer in bytes wins.

To make program simpler, you may insert in your code a conditional statement to switch program flow in particular iteration. This must simulate the line to be changed. If so, you do not have to count the bytes of the conditional in your code. However, you cannot modify anything in this part of code and use it for any other purposes.

### Example

The example below was written in PHP. Note, **it is invalid**, because it changes `+` sign to `-` sign, which is not allowed, however I hope it would be clear to understand what I mean.

```
function f($s){
   $result = ''; // initialize result
   $array = str_split($s); // convert string to array
   $char = 0; // loop start
   $increase = 1; // loop direction
   while($char>=0 && $char < strlen($s)){ // start loop
     $result = $result . $array[$char]; // add next character for the output

     // The conditional statements below simulate character switch
     // The number 5 means it will happen in the 5th iteration
     // The lines in if... and else... statements must have exactly the same length
     if(strlen($result) < 5){ // for iteration 5 and lower...
       $char = $char + $increase;  // count only this line in the block
     }
     else{
       $char = $char - $increase;
     }
     // end of the block

   } // end while loop
   return $result; // end of program
}

```

The usage of the function is to call it `echo f("abcdefghijkl");` which returns `abcdedcba`. Golfed a bit (removed some whitespaces and the conditional block):

```
function f($s){$result='';$array=str_split($s);$char=0;$increase=1;while($char>=0 && $char<strlen($s)){
$result=$result.$array[$char];
$char=$char+$increase; // this line instead of the block
}
return$result;}

```

(175 bytes)

Note, that the golfed version, without the conditional block (or `5` is replaced with `13` or more), returns `abcdefghijkl`.

*This is my very first task here. Let me know if I did something wrong.*

# Answer
## Python ~~76~~ 63 Bytes

This anon-function basically prints it's input as is.

```
lambda x:`[x[(~~e,e)[e<len(x)/2]]for e in range(len(x))]`[2::5]

```

Outputs - `z("123456") -> 123456`

But by changing the `~` to whitespace , it prints the second part of the string in reverse.

```
lambda x:`[x[( ~e,e)[e<len(x)/2]]for e in range(len(x))]`[2::5]
              ^

```

Outputs - `z("123456") -> 123321`
> 2 votes

---
Tags: code-golf
---


# Question
Title: Fill empty spaces by filling empty blanks
Write a function (such as `placeAt`) that takes an array of non-negative integers and an index that is a non-negative integer. It should place a 1 at the given index, possibly shifting other entries by one spot to vacate that spot, with 0's standing for empty spots.

* If the entry at the desired index is 0, fill it with a 1.
* Otherwise, look for the nearest 0 to the left of the index. Shift entries one spot left into that 0 to make room, then fill the index with a 1.
* If there's no 0 to the left, do the same going right.
* If neither is possible (i.e. if there is no 0), return the array unchanged.

The items are 0-indexed. Function name can be anything you want.

Examples:

(Letters stand for any positive integer values.)

```
[a, b, 0, c, d, 0] placeAt 2    // output [a, b, 1, c, d, 0]    place 2 is 0, just fill
[a, b, 0, c, d, 0] placeAt 3    // output [a, b, c, 1, d, 0]    place 3 is filled, shift items left
[a, b, 0, c, d, 0] placeAt 0    // output [1, a, b, c, d, 0]    place 0 is filled, can't shift left, shift items right
[a, b, 0, c, d, 0] placeAt 1    // output [a, 1, b, c, d, 0]    place 1 is filled, can't shift left, shift items right
[0, a, b, 0, c, d, 0] placeAt 2 // output [a, b, 1, 0, c, d, 0] place 2 is filled, shift items left
[0, a, b, 0, c, d, 0] placeAt 4 // output [0, a, b, c, 1, d, 0] place 4 is filled, shift items left (notice you keep shifting up until a 0)
[0, 2, 0, 2] placeAt 3          // output [0, 2, 2, 1]          place 3 is filled, shift items left

```

This is a code golf challenge. The shortest entry at the end of 9 days wins.

# Answer
> 4 votes
# JavaScript (ES6), 85

Test running the snippet on any EcmaScript 6 compliant browser (notably not Chrome not MSIE. I tested on Firefox, Safari 9 could go)

(I found this without looking at any of the other answers, now I see it's very similar to rink's. Yet quite shorter. Probably I won't get many upvotes for this one)

```
F=(a,p,q=~a.lastIndexOf(0,p)||~a.indexOf(0))=>(q&&(a.splice(~q,1),a.splice(p,0,1)),a)

// Ungolfed
U=(a,p)=>{
  q = a.lastIndexOf(0, p)
  if (q < 0) q = a.indexOf(0)
  if (q >= 0) {
    a.splice(q, 1)
    a.splice(p, 0, 1)
  }
  return a
}

// TEST
out=x=>O.innerHTML+=x+'\n';

[ [['a', 'b', 0, 'c', 'd', 0], 2, ['a', 'b', 1, 'c', 'd', 0]] // place 2 is 0, just fill
, [['a', 'b', 0, 'c', 'd', 0], 3, ['a', 'b', 'c', 1, 'd', 0]] // place 3 is filled, shift items left
, [['a', 'b', 0, 'c', 'd', 0], 0, [1, 'a', 'b', 'c', 'd', 0]] // place 0 is filled, can't shift left, shift items right
, [['a', 'b', 0, 'c', 'd', 0], 1, ['a', 1, 'b', 'c', 'd', 0]] // place 1 is filled, can't shift left, shift items right
, [[0, 'a', 'b', 0, 'c', 'd', 0], 2, ['a', 'b', 1, 0, 'c', 'd', 0]] // place 2 is filled, shift items left
, [[0, 'a', 'b', 0, 'c', 'd', 0], 4, [0, 'a', 'b', 'c', 1, 'd', 0]] // place 4 is filled, shift items left (notice you keep shifting up until a 0)
, [['a', 'b', 'c', 'd'], 2, ['a', 'b', 'c', 'd']] // impossible
, [[0, 2, 0, 2], 3, [0, 2, 2, 1]]] // place 3 is filled, shift items left
.forEach(t=>{
  i=t[0]+''
  r=F(t[0],t[1])+''
  k=t[2]+''
  out('Test ' + (r==k?'OK':'Fail') +'\nInput: '+i+' '+t[1]+'\nResult:'+r+'\nCheck: '+k+'\n')
})
```

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

# Answer
> 3 votes
# Julia, 122 bytes

Just a naïve implementation of the spec to get things started.

```
f(x,i)=(i+=1;x[i]==0?(x[i]=1):i>2&&x[i-1]==0?(x[i-1]=x[i];x[i]=1):i<length(x)-1&&x[i+1]==0?(x[i+1]=x[i];x[i]=1):error();x)

```

Ungolfed:

```
function placeAt(x::Array, i::Int)
    # Make i 1-indexed
    i += 1

    # Shift and modify the array as necessary
    if x[i] == 0
        x[i] = 1
    elseif i > 2 && x[i-1] == 0
        x[i-1], x[i] = x[i], 1
    elseif i < length(x)-1 && x[i+1] == 0
        x[i+1], x[i] = x[i], 1
    else
        error()
    end

    # Return the modified array
    x
end

```

# Answer
> 1 votes
## JavaScript (ES6), 98 bytes

Pretty much the same approach as my CoffeeScript answer but I'm short-circuiting to the extreme in order to save a `return` statement:

```
f=(a,x)=>(~($=a.lastIndexOf(0,x))||~(_=a.indexOf(0,x)))&&a.splice(~$?$:_,1)&&a.splice(x,0,1)&&a||a

```

### Explanation

To easier explain, I have rearranged my code a bit:

```
// Declare function f with two arguments: array and position
f = (a, x) => {
    // Take the part of the array from beginning to x and find the last 0
    $ = a.lastIndexOf(0, x)

    // Find the first 0 after position x
    _ = a.indexOf(0, x);

    // indexOf returns -1 if they aren't found
    // ~1 == 0 so I am checking if either $ or _ is truthy (zeros were found)
    if (~$ || ~_)
       // If zeros were found in the left, use that.
       // Otherwise use the found zero in the right.
       // Delete it from the array
       // Array.prototype.splice will return an array which evaluates to truthy
       // and continues execution with the &&
       // Insert value 1 at position x, deleting 0 elements
       // The last value is returned
       return a.splice(~$ ? $ : _, 1) && a.splice(x, 0, 1) && a
    else
       // No zeros were found so just return the original
       // In the golfed code the if would have evaluated to false to cut into the || part
       return a
}

```

Here's some information on JS short-circuit evaluation.

### Demo

At the moment this demo only works in Firefox and Edge due to use of ES6:

```
f=(a,x)=>(~($=a.lastIndexOf(0,x))||~(_=a.indexOf(0,x)))&&a.splice(~$?$:_,1)&&a.splice(x,0,1)&&a||a

// Snippet stuff
console.log = x => O.innerHTML += x + '\n';

console.log(f(['a', 'b', 0, 'c', 'd', 0], 2))
console.log(f(['a', 'b', 0, 'c', 'd', 0], 3))
console.log(f(['a', 'b', 0, 'c', 'd', 0], 0))
console.log(f([0, 'a', 'b', 0, 'c', 'd', 0], 2))
console.log(f([0, 'a', 'b', 0, 'c', 'd', 0], 4))
console.log(f(['a', 'b', 0, 'c', 'd', 0], 2))
console.log(f(['a', 'b', 0, 'c', 'd', 0], 1))
```

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

# Answer
> 1 votes
# Ruby, 208 bytes

```
def f(a,i)
  x=a.take(i).rindex(0);y=a[i+1..-1].index(0)
  if a[i]==0
    a[i]=1
  elsif !x.nil?
    a.delete_at(x);a.insert(i,1)
  elsif !y.nil?
    a.delete_at(y+i+1);a.insert(i,1)
  end
  a
end

```

# Answer
> 1 votes
# Haskell, 119 bytes

```
e=elem 0
r=reverse
f=(g.).splitAt
g(a,y@(x:b))|e(x:a)=r(h(x:r a)1)++b|e y=a++h y 1|1<2=a++y
h(0:r)n=n:r
h(a:r)n=n:h r a

```

Usage example:

```
*Main> mapM_ (print.uncurry f) [
                (2,[2,3,0,4,5,0]),
                (3,[2,3,0,4,5,0]),
                (0,[2,3,0,4,5,0]),
                (1,[2,3,0,4,5,0]),
                (2,[0,2,3,0,4,5,0]),
                (4,[0,2,3,0,4,5,0]),
                (3,[0,2,0,2]),
                (2,[2,3,4,5])  ]
[2,3,1,4,5,0]
[2,3,4,1,5,0]
[1,2,3,4,5,0]
[2,1,3,4,5,0]
[2,3,1,0,4,5,0]
[0,2,3,4,1,5,0]
[0,2,2,1]
[2,3,4,5]

```

How it works: Split the input list at the given position into left part `a`, the element at the position itself `x` and right part `b`. If there's a `0` in `a++x`, make room up to first `0` in the reverse of `a++x`. If there's a `0` in `x++b`, make room there. If there's no `0` at all, combine all parts unchanged to get the original list again.

# Answer
> 0 votes
## CoffeeScript, 96 bytes

```
f=(a,_)->a.splice((if~($=a.lastIndexOf 0,_)then $ else a.indexOf 0),1);a.splice(_,0,1)if 0in a;a

```

# Answer
> 0 votes
# C#, 265 bytes

**Golfed (265 Characters)**

```
static void placeAt(String[]Q,int P){int I;if(Q[P]=="0"){Q[P]="1";}else{I=Array.IndexOf(Q,"0");if(I>=0){if(I<P){for(int i=I;i<=P;i++){Q[i]=(i==P)?"1":Q[i+1];}}else if(I>P){for(int i=I;i>=P;i--){Q[i]=(i==P)?"1":Q[i-1];}}}}foreach(String s in Q)Console.Write(s+" ");}

```

**With white spaces and indentations**

```
static void placeAt(String[] Q, int P)
    {
        int I;

        if(Q[P] == "0")
        {
            Q[P] = "1";
        }
        else
        {
            I = Array.IndexOf(Q, "0");
            if (I >= 0)
            {
                if (I < P)
                {
                    for (int i = I; i <= P; i++)
                    {
                        Q[i] = (i == P) ? "1" : Q[i + 1];
                    }
                }
                else if (I > P)
                {
                    for (int i = I; i >= P; i--)
                    {
                        Q[i] = (i == P) ? "1" : Q[i - 1];
                    }
                }
            }
        }

        foreach (String s in Q)
            Console.Write(s + " ");
    }

```

**Whole Program**

```
using System;

class FillZero
{
    static void placeAt(String[] Q, int P)
    {
        int I;

        if(Q[P] == "0")
        {
            Q[P] = "1";
        }
        else
        {
            I = Array.IndexOf(Q, "0");
            if (I >= 0)
            {
                if (I < P)
                {
                    for (int i = I; i <= P; i++)
                    {
                        Q[i] = (i == P) ? "1" : Q[i + 1];
                    }
                }
                else if (I > P)
                {
                    for (int i = I; i >= P; i--)
                    {
                        Q[i] = (i == P) ? "1" : Q[i - 1];
                    }
                }
            }
        }

        foreach (String s in Q)
            Console.Write(s + " ");
    }

    static void Main()
    {
        String[] X = {"a", "b", "0", "c", "d", "0"};
        placeAt(X , 1);

    }

}

```

**Test Cases**

# Answer
> 0 votes
# Python 2, 102 bytes

```
def f(a,i):
 x=(a[i-1::-1]+a[i:]+[0]).index(0)
 if x<len(a):del a[(x,i-x-1)[x<i]];a[i:i]=[1]
 return a

```

Calculates the index of the zero to be removed by concatenating the list reversed up to the insertion index with the part after the index in normal order, then finding the index of the first zero. A zero is added to the end to avoid `ValueError` exceptions when no zero is found. Then just delete, insert and return.

# Answer
> 0 votes
# R, 87 bytes

```
f=function(a,i)if(0%in%a)append(a[-abs(min((b=which(a==0))*(1-(b<=i+1)*2)))],1,i)else a

```

Explanation

```
function(a,i)
if(0%in%a)                      # as long as a 0 exists
    append(                     # append 1 after i
        a[
          -abs(                 # remove absolute of min index
            min(                # minimum of adjusted index
              (b=which(a==0))*  # index of all 0's
              (1-(b<=i+1)*2)    # multiple -1 if <= i
              )
            )
        ]
        ,1
        ,i
    )
else                            # otherwise return untouched
    a

```

Tests

```
> f(c(2, 3, 0, 4, 5, 0) , 2)
[1] 2 3 1 4 5 0
> f(c(2, 3, 0, 4, 5, 0) , 3)
[1] 2 3 4 1 5 0
> f(c(2, 3, 0, 4, 5, 0) , 0)
[1] 1 2 3 4 5 0
> f(c(2, 3, 0, 4, 5, 0) , 1)
[1] 2 1 3 4 5 0
> f(c(0, 2, 3, 0, 4, 5, 0) , 2)
[1] 2 3 1 0 4 5 0
> f(c(0, 2, 3, 0, 4, 5, 0) , 4)
[1] 0 2 3 4 1 5 0
> f(c(0, 2, 0, 2) , 3)
[1] 0 2 2 1
>

```

# Answer
> 0 votes
# C, 154 bytes

```
p(a,l,i,c)int*a;{for(c=i;c+1;c--){if(!a[c]){for(;c<i;c++)a[c]=a[c+1];return a[i]=1;}}for(c=i;c<l;c++){if(!a[c]){for(;c>i;c--)a[c]=a[c-1];return a[i]=1;}}}

```

Passes the given test cases, **a** is the pointer to the array, **l** is the length of the array (I hope this doesn't break the brief), **i** is the index for the insert and **c** is used internally. Could possibly be improved by combining the left and right search for loops.

## Example

```
int main(int argc, char * argv[]) {
    int a[] = {0, 2, 0, 2};
    p(a, 4, 3);
}

```

## Ungolfed

Straight forward, and not really any tricks beyond K&R style declaration.

```
p(a,l,i,c) int *a; {
    /* Search left from i (also handles a[i] == 0) */
    for (c=i;c+1;c--) {
            if (!a[c]) {
                    /* Shift items left until i */
                    for (;c<i;c++) a[c]=a[c+1];
                    return a[i]=1;
            }
    }
    /* Search right from i */
    for (c=i;c<l;c++) {
            if(!a[c]) {
                    /* Shift items right until i */
                    for(;c>i;c--) a[c]=a[c-1];
                    return a[i]=1;
            }
    }
}

```

---
Tags: code-golf
---


title: Giving Directions

text:
# Question
Title: Giving Directions
## Challenge

You've given a map to a friend that looks a bit like this:

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

```

A simple map that starts at the top and ends at the bottom. Sadly, your friend doesn't get it. Can you decode the map so that he can read it?

## Input

The input is a string of characters consisting of `|`, `/`, `\`, `D`, `^`, `Y`,  *(space)*, and newlines.

* `|` tells to stay in the same column.
* `\` tells to move to the column to the right and down 1.
* `/` tells to move to the column to the left and down 1.
* `D` marks the destination.
    + `^` (if present) tells of a split in the path.
    + `Y` (if present) tells of a rejoining of paths. Treat it like a `|`.

The input will be arranged so that it makes a kind of path:

```
   |
   |
   \
    |
    ^
   / \
  /   |
 D    |

```

There will always be a space between two paths, and all paths will either rejoin or reach the last line of the input. There will only be one split per map. There is no limit to the length of the input map. There will never be more than two paths.

## Output

The output should be a string of directions.

* "**L**" should tell your friend to move **L**eft and take 1 step forward.
* "**R**" should tell your friend to move **R**ight and take 1 step forward.
* "**F**" should tell your friend to move 1 step forward.

For the input example map, the output would be as follows:

```
F F L F R R R

```

Note that your friend is starting at the top of the map and facing down the map. Give the directions from his perspective. For an instance of "^", your program must be able to choose the path that leads to the destination (D). If the two paths recombine, your program must choose the straightest path (the one with the most `|`s) to follow. Directions must be separated by spaces, and must end *on* **D**.

## Examples

**Input**

```
      |
      |
      \
       \
        ^
       / |
      |  |
      \  |
       \ \
        \ \
         \ /
          Y
          D

```

**Output**

```
F F L L L F F F L L R F

```

Since the leftmost path contains only 1 `|`, we use the rightmost path that has 3.

---

**Input**

```
\
 |
 /
|
\
 |
 /
D

```

**Output**

```
L F R F L F R

```

---

**Input**

```
    /
   \
    /
   \
    ^
   \ \
    D \

```

**Output**

```
R L R L R L

```

## Other details

* This is code golf, so the person with the shortest code by next Wednesday, the 19th of August, wins.
* Constructive feedback welcome and greatly appreciated.
* Partially inspired by A Map to Hidden Treasure
* Feel free to change the title to something more creative.
* If you find mistakes that I made, correct them.
* And of course, have fun.

## Thank you!

A bit late, maybe, but UndefinedFunction is the winner coding in JavaScript! Thanks to all who entered. No other entries will be accepted.

# Answer
> 5 votes
# Javascript (ES6), ~~261~~ ~~248~~ ~~252~~ ~~248~~ 212 bytes

Since only one split has to be supported:

```
s=>(s=s.replace(/ /g,o="",d=0).split(`
`)).map((v,j)=>{if(v=="^")for(v="/\\";(w=s[++j])&&(x=w[1]);d=x=="D"?1:w[0]=="D"?0:x>"{"?d+1:w[0]>"{"?d-1:d);o+=(p=v[d>0?1:0]||v[0])<"0"?"R ":p<"E"?"":p=="\\"?"L ":"F "})?o:o

```

However, ***240 bytes*** and we can deal with multiple splits:

```
s=>(s=s.replace(/ /g,o="").split(`
`)).map((v,j)=>{if(!v[1])t=d=0
else if(!t){for(t=1;(w=s[++j])&&(x=w[1]);d=x=="D"?1:w[0]=="D"?0:x>"{"?d+1:w[0]>"{"?d-1:d);o+=d>0?"L ":"R "}o+=(p=v[d>0?1:0])<"0"?"R ":p<"E"||p=="^"?"":p=="\\"?"L ":"F "})?o:o

```

Both programs define anonymous functions.

To use, give the function(s) a name by adding `f=` before the code.

Afterwards, they can be called with

```
alert(f(
`   |
   |
   \\
    |
    ^
   / \\
  /   |
 D    |`
))

```

### Explanation

(outdated, but still the same concept. For the multiple split solution)

```
s=>
    //Remove all spaces from the input
    (s=s.replace(/ /g,o="",
                 //Define function c, to convert symbols to directions
                 c=p=>p<"0"?"R ":p<"E"||p=="^"?"":p=="\\"?"L ":"F "
    //Split input into an array by newlines
    ).split(`
`))
    //for each string v in the input array, at index j:
    .map((v,j)=>{
        //if v is only one character long:
        if(!v[1]){
            t=1     //assign t to 1 (true) - we need to test if multiple paths
            d=0     //assign d to 0 - reset the counter for determining shortest path
        }
        //if v is two characters long, and we have not tested which path is shorter yet:
        else if(t){
            for(    t=0;    //assign t to 0 - we will have tested which path is longer

                    //for each string left in the input, while the input still has two characters:
                    (w=s[++j]) && w[1];
                    //assign d to determine which direction to go. This will be conveyed by if d>0
                    d=
                        w[1]=="D"?1:    //if the dest. is only on one side, choose that side.
                        w[0]=="D"?0:
                        w[1]=="|"?d+1:  //otherwise add/subtract from d (like a tug of war) to determine which side has more "|"
                        w[0]=="|"?d-1:
                        d
               );
            o+=d>0?"L ":"R "    //append to the output which direction was taken
        }

        o+=c(v[d>0?1:0])    //append to the output the characters from the correct path in any case, determined by d calculated above
                            //(or defaulting to 0, if path is not split, in which case the only character is appended)

    }) ? o : o  //coerce the result, which will evaluate to an array of the input, to the output (o) and implicitly return

```

### Notes

* All backslashes (`\`) in the input are escaped as `\\`, so that javascript can recognize them.
* Both outputs contain a trailing space.

# Answer
> 9 votes
# PHP, 634 631 607 396 382 381 347 338 330 337 324 bytes

My first ever golf so be gentle. Any tips are greatly appreciated.

```
<?php
foreach(str_split(strtr(fgets(STDIN),[' '=>'']))as $i){if($i!=D){$z=$i=='^';$x=$i==Y;$s=!$z&&!$x?($i=='/'?R:($i=='|'?F:($i=='\\'?L:$s))):$s;$a.=$z?R:($x?F:(($c==1||!$c)?$s:''));$b.=$z?L:($x?F:(($c==2||!$c)?$s:''));$c=$z?1:($x?0:($c==1?2:($c==2?1:$c)));}else{echo(substr_count($a,F)<substr_count($b,F)&&$c==0||$c==2)?$b:$a;}}

```

**Short Explanation:**
I have a count which is 0 if the Input has only one path. When the path splits the count is 1 for the left path and 2 for the right path. After defining both paths (or only one) I check which path has more "F's".
**Ungolfed Version:**

```
<?php
$input = fgets(STDIN);
$inputArray = str_split($input);
foreach ($inputArray as $currentChar) {
    if ($currentChar != 'D') {
        if ($i == '^') {
            $firstPath .= 'R';
            $secondPath .= 'L';
            $count = 1;
        } elseif ($i == 'Y') {
            $secondPath .= 'F';
            $firstPath .= 'F';
            $count = 0;
        } else {
            if ($i == ' ') {
                continue;
            }
            if ($i == '/') {
                $direction = 'R';
            } else {
                if ($i == '|') {
                    $direction = 'F';
                } else {
                    if ($i == '\\') {
                        $direction = 'L';
                    } else {
                        $direction = '';
                    }
                }
            }
            if ($count == 1) {
                $firstPath .= $direction;
                $count = 2;
            } elseif ($count == 2) {
                $secondPath .= $direction;
                $count = 1;
            }
            if (!$count) {
                $firstPath .= $direction;
                $secondPath .= $direction;
            }
        }
    } else {
        echo (substr_count($firstPath, 'F') < substr_count($secondPath, 'F')) || $count == 2 ? $secondPath : $firstPath;
    }
};

```

**Log:**
Saved 36 Bytes thanks to Kamehameha.
Saved many many bytes by changing the logic a bit.
Saved 42 Bytes thanks to axiac.
Replaced every if statment with ternary operators.

# Answer
> 3 votes
# PHP, 281 bytes

```
$b=0;$p=['|'=>'$a[$b].="F ";$f[$b]++;','/'=>'$a[$b].="R ";','\\'=>'$a[$b].="L ";','^'=>'$d.=$a[0];$n=2;$a=["R ","L "];$f=[];$b=1;','Y'=>'$d.=$a[$f[0]<$f[$n=1]]."F ";$a=[];','D'=>'$d.=$a[$b];exit(rtrim($d));'];foreach(str_split($argv[$n=1])as$c){if($x=$p[$c]){eval($x);$b=++$b%$n;}}

```

It is the result of two golfing iterations. The ungolfed version is:

```
$a=$f=[];       // these assignments are not required (they were suppresed in v2)
$n=1;           // this assignment can be squeezed into $argv[$n=1]
$b=0;           // if this assignment is suppressed $b becomes '' and breaks the logic
$code = [
    '|' => '$a[$b].="F ";$f[$b]++;',
    '/' => '$a[$b].="R ";',
    '\\'=> '$a[$b].="L ";',
    '^' => '$d.=$a[0];$n=2;$a=["R ","L "];$f=[];$b=1;',
    'Y' => '$d.=$a[$f[0]<$f[$n=1]]."F ";$a=[];',
    'D' => '$d.=$a[$b];echo(rtrim($d));',
];
foreach (str_split($argv[1]) as $char) {
    // ignore input characters not in the keys of $code
    if ($x = $code[$char]) {
        eval($x);
        $b = ++ $b % $n;   // cycles between 0 and 1 ($n == 2) or stays 0 ($n == 1)
    }
}

```

It is pretty golfed itself and it emerged as an improvement of the following golfed program (312 bytes):

```
$b=0;foreach(str_split($argv[$n=1])as$c){if($c=='|'){$a[$b].='F ';$f[$b]++;}elseif($c=='/'){$a[$b].='R ';}elseif($c=='\\'){$a[$b].='L ';}elseif($c=='^'){$d.=$a[0];$n=2;$a=['R ','L '];$f=[];$b=1;}elseif($c==Y){$d.=$a[$f[0]<$f[$n=1]].'F ';$a=[];}elseif($c==D){$d.=$a[$b];exit(rtrim($d));}else continue;$b=++$b%$n;}

```

It is the golfed version of the original:

```
$map = $argv[1];

$dir = '';              // the already computed directions
$nb = 1;                // the number of branches
$branches = [ '' ];     // the branches (2 while between '^' and 'Y', 1 otherwise)
$nbF = [ 0, 0 ];        // the number of 'F's on the branches (used to select the branch)
$curr = 0;              // the current branch
foreach (str_split($map) as $char) {
    if ($char == '|') {             // go 'F'orward
        $branches[$curr] .= 'F ';       // put it to the current branch
        $nbF[$curr] ++;                 // count it for the current branch
    } elseif ($char == '/') {       // go 'R'ight
        $branches[$curr] .= 'R ';
    } elseif ($char == '\\') {      // go 'L'eft
        $branches[$curr] .= 'L ';
    } elseif ($char == '^') {       // fork; choose the path ('L' or 'R') that contains the most 'F'orward segments
        $dir .= $branches[0];           // flush the current path (it was stored as the first branch)
        $nb = 2;                        // start two branches
        $branches = [ 'R ', 'L ' ];     // put the correct directions on each branch
        $nbF = [ 0, 0 ];                // no 'F's on any branch yet
        $curr = 1;                      // need this to let it be 0 on the next loop
    } elseif ($char == 'Y') {       // join
        $dir .= $branches[$nbF[0] < $nbF[1]];   // flush; choose the branch having the most 'F's
        $dir .= 'F ';                           // treat it like a "|"
        $branches = [ '' ];                     // back to a single, empty branch
        $nb = 1;
    } elseif ($char == 'D') {       // finish
        $dir .= $branches[$curr];       // flush
        break;                          // and exit; could use 'return' but it's one byte longer; use exit() in the final program and save 5 bytes
    } else {
        continue;
    }
    $curr = ++ $curr % $nb;
}
echo rtrim($dir);

```

Example execution:

```
$ php -d error_reporting=0 directions.php '
      |
      |
      \
       \
        ^
       / |
      |  |
      \  |
       \ \
        \ \
         \ /
          Y
          D
'; echo
F F L L L F F F L L R F
$

```

It also handles multiple forks correctly (need to join before the next fork in order to have at most two branches any time). I asked about multiple forks in a comment but the code was already done when the answer ("not needed") came.

The complete code with test suite and more comments can be found on github.

---
Tags: code-golf
---


# Question
Title: Lossless English language text compression challenge
## Challenge:

Your challenge (should you choose to accept it) is to compress and decompress the 5MB "*Complete Works of William Shakespeare*" as found here: http://www.gutenberg.org/cache/epub/100/pg100.txt

(MD5: `a810f89e9f8e213aebd06b9f8c5157d8`)

## Rules:

* You **must** take input via `STDIN` and output via `STDOUT`...
* ...and you **must** provide an identical decompressed result to the input.
    + (This is to say you **must** be able to `cat inpt.txt | ./cmprss | ./dcmpress | md5` and get the *same* MD5 as above.)
    + (Anything via `STDERR` is to be discarded.)
* You **must** use less than 2048 characters for your total source code.
    + *(This is **not** code-golf. You are **not** being scored based on length of source-code. This is was just a rule to keep things finite.)*
    + (Take the concatenated length of all source code if you have split it out.)
* You **must** be able to (theoretically) process similar plain-text inputs too.
    + (e.g. hard coding a mechanism which is *only* capable of outputting the provided *Shakespeare* input is unacceptable.)
    + (The compressed size of other documents is irrelevant - provided the decompressed result is identical to the alternative input.)
* You **may** use any choice of language(s).
    + (e.g. feel free to compress using `awk` and decompress using `java`)
* You **may** write two separate programs or combine them with some form of "switch" as you please.
    + (There must be clear demonstrations of how to invoke both the compression and decompression modes)
* You may **not** use any external commands (e.g. through `exec()`).
    + (If you are using a shell language - sorry. You'll have to make do with built-ins. You're welcome to post an "unacceptable" answer for the sake of sharing and enjoyment - but it won't be judged!)
* You may **not** use any built-in or library provided functions who's stated purpose is to compress data (like `gz`, etc)
    + (Altering the encoding is not considered compression in this context. Some discretion may be applied here. Feel free to argue the acceptableness of your solution in the submission.)
* Please try to have fun if choose to participate!

All good competitions have an objective definition of winning; ergo:

* Provided all rules are adhered to, the smallest **compressed** output (in `STDOUT` bytes) wins.
    + (Report your output please via `./cmprss | wc -c`)
* In the event of a draw (identical output sizes), the most community up-voted wins.
* In the event of a second draw (identical community up-votes), I'll pick a winner based on completely subjective examination of elegance and pure genius. `;-)`

## How to submit:

Please format your entry using this template:

```
<language>, <compressed_size>
-----------------------------

<description>  (Detail is encouraged!)

    <CODE...
    ...>

<run instructions>

```

I would encourage readers and submitters to converse through comments - I believe there's real opportunity for people to learn and become better programmers through codegolf.stack.

## Winning:

I'm away on vacation soon: I may (or may not) be monitoring submissions over the next few weeks and will draw the challenge to a close on the 19th September. I hope this offers a good opportunity for people to think and submit - and for a positive sharing of techniques and ideas.

If you've learned something new from participating (as a reader or submitter) please leave a comment of encouragement.

# Answer
> 5 votes
## Perl 5, 3651284

Just a simple word-based dictionary scheme. Analyzes the word frequency of the corpus, and uses that to determine whether to use one or two bytes of overhead per word. Uses two special symbols for the bytes \0 and \1 since they do not appear in the corpus. There are plenty of other symbols that could be used. This was not done. Does not do any huffman encoding or any of that jazz.

Compression script shakespeare.pl:

```
use strict;
use warnings;
use bytes;

my $text = join "", <>;
my @words = split/([^a-zA-Z0-9]+)/, $text;

my %charfreq;
for( my $i = 0; $i<length($text); ++$i ) {
    $charfreq{ substr($text, $i, 1) }++
}
for my $i ( 0..255 ) {
    my $c = chr($i);
    my $cnt = $charfreq{$c} // 0;
}

my %word_freq;
foreach my $word ( @words ) {
    $word_freq{ $word }++;
}

my $cnt = 0;
my ( @dict, %rdict );
foreach my $word ( sort { $word_freq{$b} <=> $word_freq{$a} || $b cmp $a } keys %word_freq ) {
    last if $word_freq{ $word } == 1;

    my $repl_length = $cnt < 127 ? 2 : 3;
    if( length( $word ) > $repl_length ) {
        push @dict, $word;
        $rdict{ $word } = $cnt;
        $cnt++;
    }
}

foreach my $index ( 0..$
    print "$dict[$index]\0";
}
print "\1";

foreach my $word ( @words ) {
    my $index = $rdict{ $word };
    if ( defined $index && $index <= 127 ) {
        print "\0" . chr( $index );
    } elsif ( defined $index ) {
        my $byte1 = $index & 127;
        my $byte2 = $index >> 7;
        print "\1" . chr( $byte2 ) . chr( $byte1 );
    } else {
        print $word;
    }
}

```

Decompression script deshakespeare.pl:

```
use strict;
use warnings;
use bytes;

local $/;
my $compressed = <>;
my $text = $compressed;
$text =~ s/^.+?\x{1}//ms;
my $dictionary = $compressed;
$dictionary =~ s/\x{1}.*$//ms;

my $cnt = 0;
my @dict;
foreach my $word ( split "\0", $dictionary ) {

    push @dict, $word;
}

my @words = split /(\x{0}.|\x{1}..)/ms, $text;
foreach my $word ( @words ) {
    if( $word =~ /^\x{0}(.)/ms ) {
        print $dict[ ord( $1 ) ];
    } elsif( $word =~ /^\x{1}(.)(.)/ms ) {
        my $byte1 = ord( $1 );
        my $byte2 = ord( $2 );
        my $index = ( $byte1 << 7 ) + $byte2;
        print $dict[ $index ];
    } else {
        print $word;
    }
}

```

Run using:

```
perl shakespeare.pl < pg100.txt >pg100.txt.compressed
perl deshakespeare.pl <pg100.txt.compressed >pg100.txt.restored
diff pg100.txt pg100.txt.restored

```

---
Tags: code-challenge, compression
---


title: Tournament Format Synonyms

text:
# Question
Title: Tournament Format Synonyms
I spent all of today at a Super Smash Bros. tournament, and I started thinking about some of the terminology we use when describing sets. These are the three kinds of sets that I see played at tournaments:

* Best of 3 (Bo3)
    + Three games are played. The winner of the set is the player who won the majority of the games.
    + If a single player wins two games of the set, they are immediately declared the winner, because it would be impossible for the opponent to catch up.
* Best of 5 (Bo5)
    + Five games are played. The winner of the set is the player who won the majority of the games.
    + If a single player wins three games of the set, they are immediately declared the winner, because it would be impossible for the opponent to catch up.
* First to 5 (Ft5)
    + Okay, I cheated a bit with my wording earlier. This kind of set isn't *part* of a tournament, but you'll often see them happening in the venue. This is traditionally the kind of set you'll play if you've challenged another player and money is on the line.
    + It's as simple as it sounds: The players repeatedly play games until one of them has won five, and that player is declared the winner.

Obviously, Bo3 and Bo5 are very similar, differing only in the number of games played. But Ft5 is clearly different... right? Not really! No matter how a Bo3 set goes down, the winner will have won exactly two games. The winner of a Bo5 set will have won exactly 3 games. Why not call them Ft2, or Ft3? The same logic, applied in reverse, will show that Ft5 is exactly the same as Bo9.

The objective of this challenge is to determine the synonym of a set format.

# Specification

Your program or function will take a single string from input. The first two characters will be `Bo` or `Ft`, and they will be followed by a number. The program/function will output a string with the opposite prefix and a number such that the input and output strings mean the same thing.

Any string beginning with `Bo` will end in an odd number.

You may assume that the number in the input string will never be greater than 200. You may also assume that you will never receive input for which the correct output would include a number greater than 200. Likewise, the input and correct output numbers will always be greater than 0.

# Examples

```
Bo3 -> Ft2
Ft2 -> Bo3

Bo5 -> Ft3
Ft3 -> Bo5

Bo9 -> Ft5
Ft5 -> Bo9

Bo51 -> Ft26
Ft26 -> Bo51

Bo199 -> Ft100
Ft100 -> Bo199

```

# Answer
# Pyth, 23 bytes

```
@,/hKsttz2tyKCp-"BoFt"z

```

Test suite.

How it works:

First, to find the `Bo` or `Ft`, the program filters out the characters in the input from `BoFt`, with `-"BoFt"z`.

This is immediately printed with `p`. `p` also returns its input. That string is converted to a number interpreting the bytes as base 256. The result is 17007 if the string was `Bo`, and is 18036 if the string was `Ft`.

Next, it calculates both possible results, `num * 2 - 1` and `(num + 1)/2` and puts this in a 2 entry list. Then, the program indexes into that list with the above number, 17007 or 18036. Due to Pyth's modular indexing, this selects the proper number. The result is then printed automatically.

Since `p` prints with no trailing newline, but the implicit printing does have the trailing newline, the two successive prints come out in exactly the right format.
> 11 votes

# Answer
# Python 2, 59

```
lambda s:'FBto'[s>'C'::2]+`eval(s[2:]+'/*22+-11'[s>'C'::2])`

```

In short challenges where functions are allowed, the brevity of `lambda` usually wins out even when the code must repeat itself due to the inability to assign variables.

We check which case we're in with string comparison `s>'C'`. Then, get the right prefix with the list slicing trick `'FBto'[s>'C'::2]`.

To get the number, we must evaluate the characters beyond the second and do either `*2+1` or `/2-1` to it. We do this by tacking on either of those two expressions as strings, again chosen by list slicing, evaluating the result, and turning that number into a string.

**Edit:** Saved one char (59):

```
lambda s:eval("''FBto''++``%%ss/*22+-11``"[s>'C'::2]%s[2:])

```

Don't even ask...
> 13 votes

# Answer
# C++11 Template Metaprogramming, 305 bytes

Edit: Got another 100 bytes off

Do I get any kind of handicap for my choice of language? :p

```
#define C wchar_t
#define T };template<C p
#define L C...l>struct
#define X l...>
C a{T,L I{T,C c,L I<p,c,X:I<10*p+c-'0',X{T>struct I<p>{enum E{v=p};T,L S{T,C c,C d,L G:G<p/10,c,d,p%10+'0',X{T,L G<0,p,X{typedef S<p,X t;T,L F{T,L F<p,'o',X:G<(I<0,X::v+1)/2,'F','t'>{T,L F<p,'t',X:G<I<0,X::v*2-1,'B','o'>{};

```

Examples:

```
#include <type_traits>
static_assert(I<0,'5'>::v == 5, "fail");
static_assert(I<0,'1','0','5'>::v == 105, "fail");
static_assert(I<0,'5','1'>::v == 51, "fail");
static_assert(std::is_same<typename G<5,'B','o'>::t, S<'B','o','5'>>::value, "fail");
static_assert(std::is_same<typename G<51,'F','t'>::t, S<'F','t','5','1'>>::value, "fail");
static_assert(std::is_same<typename F<'B','o','3'>::t, S<'F','t','2'>>::value, "fail");
static_assert(std::is_same<typename F<'F','t','2'>::t, S<'B','o','3'>>::value, "fail");
static_assert(std::is_same<typename F<'B','o','5'>::t, S<'F','t','3'>>::value, "fail");
static_assert(std::is_same<typename F<'F','t','3'>::t, S<'B','o','5'>>::value, "fail");
static_assert(std::is_same<typename F<'B','o','7'>::t, S<'F','t','4'>>::value, "fail");
static_assert(std::is_same<typename F<'F','t','4'>::t, S<'B','o','7'>>::value, "fail");
static_assert(std::is_same<typename F<'B','o','1','1'>::t, S<'F','t','6'>>::value, "fail");
static_assert(std::is_same<typename F<'F','t','6'>::t, S<'B','o','1','1'>>::value, "fail");
static_assert(std::is_same<typename F<'B','o','1','0','5'>::t, S<'F','t','5','3'>>::value, "fail");
static_assert(std::is_same<typename F<'F','t','5','3'>::t, S<'B','o','1','0','5'>>::value, "fail");
static_assert(std::is_same<typename F<'B','o','1','9','5'>::t, S<'F','t','9','8'>>::value, "fail");
static_assert(std::is_same<typename F<'F','t','9','8'>::t, S<'B','o','1','9','5'>>::value, "fail");
int main() {}

```
> 8 votes

# Answer
# CJam, 29 bytes

```
l('B=\1>i"Ft"1$)2/+"Bo"@2*(+?

```

Try it online

Nothing very elaborate here. Calculating the two possible results, and picking one of the two based on the first letter in the input. Will update if I come up with something better.

Explanation:

```
l     Get input.
(     Pop off first character.
'B=   Compare with 'B.
\1>   Get rest of input to top of stack, and slice off first character.
i     Convert to integer.
"Ft"  String part of first possible output.
1$    Copy input value to top.
)2/   Increment, and divide by 2.
+     Concatenate with string part.
"Bo"  String part of second possible output.
@     Move input value to top.
2*(   Multiply by 2, and decrement.
+     Concatenate with string part.
?     Ternary to pick one of the two constructed outputs, based on comparison
      of first input character with 'B.

```
> 6 votes

# Answer
# CJam, 27 bytes

```
4 27]r.^(_o'B=\(oi_2*(\)2/?

```

This makes use of the fact that `'B' ^ 'F' == 4` and `'o' ^ 't' == 27`.

Try it online in the CJam interpreter.
> 6 votes

# Answer
# Javascript (ES6), ~~50~~ 47 chars

Very simple solution: (Thanks to undergroundmonorail for removing one byte!)

```
x=>(y=x.slice(2),x<'C'?'Ft'+-~y/2:'Bo'+(y*2-1))

```

Ungolfed:

```
function(x){
  y = x.slice(2); // everything after the 'Ft' or 'Bo'
  return x<'C' ? 'Ft'+Math.ceil(y/2) : 'Bo'+(y*2-1)
}

```

For once my answer was only ~2x the length of the best Pyth answer!
> 5 votes

# Answer
# Haskell, 69 bytes

```
f('B':_:x)="Ft"++show(div(read x)2+1)
f(_:_:x)="Bo"++show(2*read x-1)

```

Reasonably straight-forward.
> 4 votes

# Answer
# Pyth - 31 bytes

Pretty simple, uses zip and modular indexing to get the switch. The actual calculation is really easy.

```
s@C,Jc"FtBo"2,h/Ksttz2tyKhxJ<z2

```

Test suite.
> 3 votes

# Answer
# Matlab, 95 bytes

```
function f(s)
t='Bo';a=2;b=-1;if s(1)<70
t='Ft';a=.5;b=a;end
[t num2str(str2num(s(3:end))*a+b)]

```

Examples:

```
>> f('Ft5')
ans =
Bo9
>> f('Bo51')
ans =
Ft26

```
> 3 votes

# Answer
# Julia, 63 bytes

```
x->(y=int(x[3:end]);join([x<"C"?"Ft":"Bo",x<"C"?(y+1)÷2:2y-1]))

```

Ungolfed:

```
function f(x::String)
    # Extract the number at the end
    y = int(x[3:end])

    # If x is lexographically less than "C", we have
    # "best of," so we need "first to." Otherwise we
    # need "best of."
    if x < "C"
        join(["Ft", (y+1)÷2])
    else
        join(["Bo", 2y-1])
    end
end

```
> 3 votes

# Answer
# FSharp - 153 143 bytes

```
let t(s:string)=
 let c=s.[2..]|>Seq.map string|>Seq.reduce(+)|>float
 if s.[0]='B'then sprintf"Ft%.0f"(ceil(c/2.)) else sprintf"Bo%.0f"(c*2.-1.)

```

## Updates

1. Knocked a few bytes off by switching from pattern matching to a simple `if ... then ...`
> 3 votes

# Answer
# Perl 5, 38 bytes (37 + 1 for `-p`)

```
$_=/Bo/?Ft.(.5+$'/2):Bo.(2*s/Ft//r-1)

```

**Usage**: save as 54768.pl and run as:

```
perl -p 54768.pl <<< 'Bo3'
# Ft2

```

or interactively:

```
perl -p 54768.pl
Bo199
# Ft100

```
> 3 votes

# Answer
# Powershell, 111

The wordiness of PowerShell and required parentheses are its downfall again. Even golfing the `.Substring(0,2)` to `[0..1]-join''` only saves 2 bytes each, and another couple bytes saved with an implied `Else` thanks to the `exit` command. Oh well. Good refresher on separating strings.

### Code:

```
$b=($a=$args[0])[0..1]-join'';$c=+($a[2..($a.Length-1)]-join'');if($b-eq"Bo"){"Ft"+($c+1)/2;exit};"Bo"+(2*$c-1)

```

### Usage:

```
PS C:\Scripts\Golfing> .\ssb_tourney.ps1 Bo199
Ft100

```

### Explanation

```
$b=($a=$args[0])[0..1]-join''      # Take in the command-line argument as $a, recast as
                                   # array, suck out the first two characters, save as $b
$c=+($a[2..($a.Length-1)]-join'')  # Do a similar trick with the right-hand side of $a,
                                   # re-cast it as an integer with the +
if($b-eq"Bo"){                     # If the first letters are "Bo"
    "Ft"+($c+1)/2                  # Implied write of the answer
    exit
}
"Bo"+(2*$c-1)                      # Implied write of the other answer, only reached if
                                   # the input is "Ft", else we would have hit the exit

```
> 3 votes

# Answer
Not ridiculously short like the others, but that's my first post:

# JS, 143 bytes

```
f=prompt("","");n=parseInt(f.match(/\d{1,}/));s=0;r=0;if(f.match(/B/)){r=(n+1)/2;s="Ft"+r;}if(f.match(/F/)){r=n*2-1;s="Bo"+r;}alert(f+" : "+s);

```

# Ungolfed Version:

```
var f = prompt("", "");
var n = parseInt(f.match(/\d{1,}/));
var s = 0;
var r = 0;

if (f.match(/B/)) {
  r = (n + 1)/ 2;
  s = "Ft"+r;
 }
if (f.match(/F/)) {
  r = n * 2 - 1;
  s = "Bo"+r;
 }
alert(f+" : "+s);

```
> 3 votes

# Answer
# PHP, 85 79 75 Bytes

```
<?php
$f=$argv[1];$s=substr($f,2);echo strpos($f,Bo)===0?Ft.($s+1)/2:Bo.($s*2-1);

```

**Usage:**
Call the script with an argument: `php -d error_reporting=0 script.php Bo5`
> 3 votes

# Answer
# Ruby, 82 Bytes

```
x=$*[0]
y=x.match(/..(\d*)/)[1].to_i
x=~/Bo/?(puts"Ft#{y/2+1}"):(puts"Bo#{y*2-1}")

```

Called with an argument to knock off a few bytes.
First post, suggestions welcome. :)

**EDIT:** Got rid of 12 bytes by changing up my math. Since the Bo numbers are odd they will always have a decimal after dividing by 2, meaning I can just truncate and add 1 instead of using `ceil` to round up.
> 3 votes

# Answer
# R, 144 bytes

New to code-golfing, R, and this site. So here goes:

```
a=function(){n=readline();z="Bo";p=(as.numeric(gsub("[^0-9]","",n)));if(grepl(z,n)==TRUE){x="Ft";b=(p+1)/2}else{x="Bo";b=p*2-1};cat(x);cat(b)}

```
> 2 votes

# Answer
# C#, 110 bytes

```
string f(string s){var b=s[0]=='B';var o=s.Remove(0,2);int i=int.Parse(o)/2;return b?"Ft"+(i+1):"Bo"+(4*i-1);}

```
> 1 votes

---
Tags: code-golf
---


# Question
Title: Convert a Point of the Compass to Degrees
I came up with this challenge independently, but it turns out to be the inverse to this challenge by Doorknob. As I really like his spec, I decided to steal large parts of it instead of cooking up my own explanations.

## The Challenge

Given the abbreviation of one of the 32 points on the compass, print the corresponding degrees. Feel free to skip ahead to the table below if you're not interested in an explanation of the 32 points.

Here is the full compass:

By Denelson83 (Own work) \[GFDL or CC-BY-SA-3.0\], via Wikimedia Commons

Each direction is 11.25 (360 / 32) degrees farther than the previous. For example, N (north) is 0 degrees, NbE (north by east) is 11.25 degrees, NNE (north-northeast) is 22.5 degrees, etc.

In detail, the names are assigned as follows:

* 0 degrees is N, 90 degrees is E, 180 degrees is S, and 270 degrees is W. These are called cardinal directions.
* The halfway points between the cardinal directions are simply the cardinal directions they're between concatenated. N or S always go first, and W or E always are second. These are called ordinal directions. The ordinal and cardinal directions together form the principal winds.
* The halfway points between the principal winds are the directions they're between concatenated. Cardinal directions go first, ordinal second. These are called half winds.
* The halfway points between principal and half winds are the adjacent principal wind "by" the closest cardinal direction away from the principal wind. This is denoted with a `b`. These are called quarter winds.

This results in the following chart:

```
#   Degrees  Abbrv.  Name
1   0        N       North
2   11.25    NbE     North by east
3   22.5     NNE     North-northeast
4   33.75    NEbN    Northeast by north
5   45       NE      Northeast
6   56.25    NEbE    Northeast by east
7   67.5     ENE     East-northeast
8   78.75    EbN     East by north
9   90       E       East
10  101.25   EbS     East by south
11  112.5    ESE     East-southeast
12  123.75   SEbE    Southeast by east
13  135      SE      Southeast
14  146.25   SEbS    Southeast by south
15  157.5    SSE     South-southeast
16  168.75   SbE     South by east
17  180      S       South
18  191.25   SbW     South by west
19  202.5    SSW     South-southwest
20  213.75   SWbS    Southwest by south
21  225      SW      Southwest
22  236.25   SWbW    Southwest by west
23  247.5    WSW     West-southwest
24  258.75   WbS     West by south
25  270      W       West
26  281.25   WbN     West by north
27  292.5    WNW     West-northwest
28  303.75   NWbW    Northwest by west
29  315      NW      Northwest
30  326.25   NWbN    Northwest by north
31  337.5    NNW     North-northwest
32  348.75   NbW     North by west

```

Here is a more detailed chart and possibly better explanation of the points of the compass.

Your task is to take as input one of the 32 abbreviations from the third column and output the corresponding degrees in the second column.

You may assume that input will always be exactly one of those 32 strings (and you may optionally but consistently expect a single trailing newline). Output should also be given exactly as listed above, although trailing zeroes are allowed. You may optionally output a single trailing newline.

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.

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

# Answer
> 2 votes
# Pyth, 47 bytes

```
c*45x"NuMD¢¼Ew
XSj.{§/gWbZ¹°"C%CzC\½4

```

Hexdump, due to unprintable characters:

```
0000000: 632a 3435 7822 4e86 754d 0344 a2bc 4504  c*45x"N.uM.D..E.
0000010: 770a 9518 1c58 536a 2e7b a77f 2f67 5762  w....XSj.{../gWb
0000020: 5ab9 15b0 8798 2243 2543 7a43 5cbd 34    Z....."C%CzC\.4

```

Test harness

Due to a bug in the official command line compiler, this code only works via the online compiler, linked above, or the `-c` flag of the offline compiler. (The bug was fixed after the question was asked.)

This solution is very similar to @Dennis's CJam answer, using the process of hashing the input, looking up the result in a 32 byte lookup string, and then multiplying by 11.25.

The hash function I use is converting the input to a string as if it was a base 256 integer with `C`, taking the result modulo `C` of `½`, which is 189, but saves a byte due to superior parsing, and converting that back to a string with `C` again.

Multiplying by 11.25 is accomplished by multiplying by 45, then dividing by 4, which saves a byte.

# Answer
> 9 votes
# Ruby, ~~118~~ 106

Thanks to Martin Büttner for 12 bytes saved.

This is currently the same length regardless of whether it's a function or a program.

lambda function

```
->s{n=4
d=0,0
s.chars{|e|c="SWNE".index e
c ?d[c%2]+=c/2*2*n-n :n=1}
(Complex(*d).arg*5.1).round%32*11.25}

```

program

```
n=4
d=0,0
gets.chars{|e|c="SWNE".index e
c ?d[c%2]+=c/2*2*n-n :n=1}
p (Complex(*d).arg*5.1).round%32*11.25

```

This is a cartesian walk through the points. The characters `NSEW` add or subtract 4 from the x and y coordinates stored in `d[]`. After a `b` (or any symbol other than `NSEW`) is encountered, this is reduced to 1.

The x and y data is then treated as a complex number to extract the angular argument. This is multiplied by 16/PI=`5.1` . Although there are some geometrical errors in the approach, rounding this angle is sufficient to give the correct number `-15..+16`. Modulo is used to correct this to `0..31` (in Ruby `%` always returns positive.) Finally the result is multiplied by 11.25.

# Answer
> 6 votes
# Javascript (ES6), 153 bytes

Just wanted to get the ball rolling with a simple one.

```
x=>'N NbE NNE NEbN NE NEbE ENE EbN E EbS ESE SEbE SE SEbS SSE SbE S SbW SSW SWbS SW SWbW WSW WbS W WbN WNW NWbW NW NWbN NNW NbW'.split` `.indexOf(x)*45/4

```

Not particularly innovative, but it works, and perhaps there's some tips that could be derived from it. Don't worry, I'll think of another (hopefully better) technique.

# Answer
> 2 votes
# CJam, 49 bytes

```
0000000: 72 34 62 32 35 33 25 63 22 4e bf 6f f1 80 e8 dc 38  r4b253%c"N.o....8
0000011: 45 3d f0 2e 94 3c d3 12 53 24 e5 5f a6 63 28 60 57  E=...<..S$._.c(`W
0000022: 5b 14 20 92 17 81 d1 22 23 31 31 2e 32 35 2a        [. ...."#11.25*

```

The above is a hexdump, which can be reversed with `xxd -r -c 17 -g 1`.

Try it online in the CJam interpreter.

### How it works

```
r      e# Read a token from STDIN.
4b     e# Convert the string (array of code points) from base 4 to integer.
253%   e# Take the result modulo 253.
c      e# Cast to character.
"…"    e# Push a 32 byte lookup table.
#      e# Find the index of the character.
11.25* e# Multiply the index by 11.25.

```

# Answer
> 1 votes
## Java, 653 (characters)

I know Java can't win but I like to make the effort anyway.

```
class C{float c=1/8f;int n=0;float a;public C(String s){if(s.contains("W"))n=4;switch(s.length()){case 1:p(d(s));case 2:p(e(s));case 3:if(s.contains("b"))f(s,1);g(s);}f(s,2);}int v(char x){switch(x){case 'N':return n;case 'E':return 1;case 'S':return 2;}return 3;}int d(String s){return v(s.charAt(0));}float e(String s){return (v(s.charAt(0))+v(s.charAt(1)))/2f;}void f(String s,int i){if(i<2)a=v(s.charAt(0));else a=e(s.substring(0,i));if(v(s.charAt(1+i))<a)c=-c;p(a+c);}void g(String s){p((d(s.substring(0,1))+e(s.substring(1)))/2f);}void p(float x){System.out.printf("%.2f",x*90);System.exit(0);}public static void main(String[]r){C c=new C(r[0]);}}

```

It takes input from the commandline and outputs to the console. Ungolfed version:

```
class Compass
{
    float c = 1/8f;
    int n = 0;
    float a;

    public Compass( String s )
    {
        if( s.contains( "W" ) )
        {
            n = 4;
        }
        switch( s.length() )
        {
            case 1:
                print( parse1( s ) );
            case 2:
                print( parse2( s ) );
            case 3:
                if( s.contains( "b" ) )
                {
                    parse3b4( s , 1 );
                }
                parse3( s );
        }
        parse3b4( s , 2 );
    }

    int getValue( char x )
    {
        switch( x )
        {
            case 'N':
                return n;
            case 'E':
                return 1;
            case 'S':
                return 2;
        }
        return 3;
    }

    int parse1( String s )
    {
        return getValue( s.charAt( 0 ) );
    }

    float parse2( String s )
    {
        return ( getValue( s.charAt( 0 ) ) + getValue( s.charAt( 1 ) ) ) / 2f;
    }

    void parse3b4( String s , int i )
    {
        if( i < 2 ) a = getValue( s.charAt( 0 ) );
        else a = parse2( s.substring( 0 , i ) );
        if( getValue( s.charAt( 1 + i ) ) < a )
        {
            c = -c;
        }
        print( a + c );
    }

    void parse3( String s )
    {
        print( ( parse1( s.substring( 0 , 1 ) ) + parse2( s.substring( 1 ) ) ) / 2f );
    }

    void print( float x )
    {
        System.out.printf( "%.2f" , x * 90 );
        System.exit( 0 );
    }

    public static void main( String[] args )
    {
        Compass compass = new Compass( args[ 0 ] );
    }
}

```

It works by assigning 0-3 to N-W (or 4 for N if W is involved). It recognizes 4 different situations:

* parse1 is for single letter points, it just returns the value.
* parse2 is for double letter points, it averages the values of the 2 points.
* parse3 is for triple letter points, it takes the average of the average of the double and the single points.
* parse3b4 is for all the ones with a 'b' in them, it calculates the value of the point before the 'b' and adds or subtracts 1/8 based on the 'direction' of the point after the 'b'.

In print() the value is multiplied by 90 to get the actual angle.

# Answer
> 1 votes
# Python 3, 149 bytes

I tried a recursive algorithmic approach. The quarter winds were harder to handle than I thought at first, so this solution grew relatively long.

```
def f(s):
 if'W'in s:s=s.replace(*'Nn')
 a=(len(s)-2)/8;return'b'in s and(1-a)*f(s[:-2])+a*f(s[-1])or a>=0and(f(s[0])+f(s[1:]))/2or'NESWn'.find(s)*90

```

Ungolfed:

```
def f(s):
    if 'W'in s:
        s = s.replace('N','n')
    a=(len(s)-2)/8
    if 'b' in s:
        a = 1/8 if len(s)==3 else 1/4
        return (1-a)*f(s[:-2])+a*f(s[-1])
    else:
        if len(s)==1:
            return 'NESWn'.find(s)*90
        else:
            return (f(s[0])+f(s[1:]))/2

```

# Answer
> 1 votes
# Haskell, 206 bytes

```
c l=11.25*(fromIntegral$b$l)
b l|(p y l)<0=a l+16|0<1=mod(a l)32
a l=round$(16/pi*)$atan$d$l
d l=p x l/p y l
p z[]=0.0
p z('b':[r])=z r/4
p z(a:r)=z a+p z r
x 'E'=4
x 'W'=(-4)
x c=0
y 'N'=4
y 'S'=(-4)
y c=0

```

Convenient test:

```
*Main> map c ["N","NbE","NNE","NEbN","NE","NEbE","ENE","EbN","E","EbS","ESE","SEbE","SE","SEbS","SSE","SbE","S","SbW","SSW","SWbS","SW","SWbW","WSW","WbS","W","WbN","WNW","NWbW","NW","NWbN","NNW","NbW"]
[0.0,11.25,22.5,33.75,45.0,56.25,67.5,78.75,90.0,101.25,112.5,123.75,135.0,146.25,157.5,168.75,180.0,191.25,202.5,213.75,225.0,236.25,247.5,258.75,270.0,281.25,292.5,303.75,315.0,326.25,337.5,348.75]

```

# Answer
> 0 votes
### PowerShell - 350

```
Add-Type -AssemblyName *sys*forms*
$f=new-object windows.forms.form
$c=new-object windows.forms.combobox
$c.DataSource=(-split"N NbE NNE NEbN NE NEbE ENE EbN E EbS ESE SEbE SE SEbS SSE SbE S SbW SSW SWbS SW SWbW WSW WbS W WbN WNW NWbW NW NWbN NNW NbW")
$c.Parent=$f
$c.Add_SelectedValueChanged({$f.text=$c.SelectedIndex*11.25})
$f.ShowDialog()

```

# Answer
> 0 votes
# Julia, 151 147 142 bytes

```
t=strchr
p=s->if ""==s 0;else i=t(s,'b')
(32/2^i)^sign(i)*p(i>0?s[1:i-1]:s[2:])+im^t("ESWN",s[i+1])end
f=s->90int(16mod(angle(p(s)),2pi)/pi)/8

```

A bit ungolfed:

```
# return approx. direction in term of complex number of absolute value 1,
# whose argument is the direction:
# N -> 0, E -> 0+1j, S -> -1, W -> 0-1j
function p(s)
    if ""==s 0;
    else
        i=strchr(s,'b');
        if i!=0
            # if 'b' is 2nd in the word, following direction weight is 1/8,
            # if 'b' is 3rd in the word, following direction weight is 1/4.
            weight=2^(5-i)
            # the first term to count avg is all before 'b'
            first_term=s[1:i-1]
        else
            # weights are equal for the counted and the new (eg. 'NNW <= avg(N, NW)')
            weight=1
            # the first term to count avg is all after the first character
            first_term=s[2:]
        end
        # the return value - average of two vectors
        # s[i+1] evaluates to FIRST character if 'b' didn't occur
        # or to the LAST CHARACTER (after 'b') if it did.
        e^(im*angle(weight*p(first_term)+im^t("ESWN",s[i+1])));
    end
end

# ... And the proper function for returning angle
# there are errors (sic!) in the counted direction, but dividing by 11.25,
# rounding and remultiplying by 11.25 filters them out
f=s->int32(mod(angle(p(s)),2pi)/pi*16)*11.25

```

In the ungolfed code, I count the average of two vectors as  in order to have the vector still normalized. However, the errors due to elongation of the first vector are not yet accumulating with so little additions in our recursion, so while golfing the normalization step was removed and the computation goes simply. Errors less than 1/64 of full circle are filtered out by rounding.

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


title: Hard Puzzle Game Solver

text:
# Question
Title: Hard Puzzle Game Solver
There is an app called Hard Puzzle which is a game where there is a red circle, and you have to fill all of the surface area with five smaller white circles

it may seen easy, but it's harder than it looks (it just takes a while to figure out). The circle dimensions change from device to device in the image above the red circles area is `41990 pixels` although on my device it is `40496 pixels` this is not important though.

So the challenge is to create the fastest algorithm (in any language) that solves this puzzle, by outputting the coordinates of where each white circle should be. Puzzle info: Red circle area = `40496 pixels`. each white circle's area = `15656 pixels (38.661% of red circle)`

Your time starts now there is 3 days for completion of the task

**GO!!**

# Answer
> 3 votes
## Python 2.7, runs almost instantly (0.02 seconds on my laptop)

```
import math, cProfile

def optimize():
    _WHITE_SURFACE = 15656
    white_radius = math.sqrt(_WHITE_SURFACE/math.pi)
    print "Assuming the red circle has its centre at (0,0), place the white circles at (x,y):"
    for i in range(5):
        print "   * Circle {0}: ({1:.5f}, {2:.5f})".format(i+1, white_radius*math.cos(i*math.pi/2.5), white_radius*math.sin(i*math.pi/2.5))

cProfile.run("optimize()")

```

---
Tags: puzzle-solver, fastest-algorithm
---


title: Barcodegolf: Generate a number's UPC

text:
# Question
Title: Barcodegolf: Generate a number's UPC
Just about every store nowadays uses Universal Product Code (UPC) barcodes to simplify the checking out process. If the name doesn't mean anything to you, you will surely recognize what they look like:

## Format

The most common system is UPC-A, which uses 12 digits to represent each specific product. Each digit is encoded into a series of black and white stripes to allow machines to read the code, a length of seven bits. There are a total of 11 bits worth of patterns that indicate the beginning, middle, and end of the barcode. This comes to a total barcode length of 12 × 7 + 11 = 95 bits. (From now on, when binary is used to refer to the color of each bit, `0` is white and `1` is black.)

The beginning and end both have a pattern of `101`. The digits are then divided into 2 groups of 6 and encoded as shown below, with a pattern `01010` between the left and right groups. This table lists the pattern for each number. Note that the pattern is different depending on if the digit is on the right or left side (This allows the barcode to be scanned upside down). However, the pattern for the right is the opposite (swap black for white and vice versa) of that of the left.

If you can't see the image above, this is each number's binary equivalent.

```
#   Left    Right
0   0001101 1110010
1   0011001 1100110
2   0010011 1101100
3   0111101 1000010
4   0100011 1011100
5   0110001 1001110
6   0101111 1010000
7   0111011 1000100
8   0110111 1001000
9   0001011 1110100

```

## Example

Say you have the UPC `022000 125033`. (Those aren't random numbers. Leave a comment if you figure out their significance.) You start with this boilerplate that is the same in every barcode:

```
101xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx01010xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx101

```

For the digits, you replace each one with the corresponding encoding for the side (left or right) it's on. If you're still confused, see the image below.

Here is the output in binary with `|` pipes separating the parts.

```
101|0001101|0010011|0010011|0001101|0001101|0001101|01010|1100110|1101100|1001110|1110010|1000010|1000010|101

```

## Challenge

Write a program that outputs the UPC-A barcode for the user input. The image's dimensions should be 95 × 30 pixels, with each "bit" being one pixel wide and 30 pixels tall. Black stripes are in `rgb(0, 0, 0)` and white stripes are consistently transparent or `rgb(255, 255, 255)`.

### Notes

* Take input from stdin or the command line, or write a function that takes a string or integer (note that input can have leading zeroes, and most languages remove them or convert the number to octal).
* Output the image in one of the following ways:
    + Save it to a file with a name and format (PNG, PBM, etc.) of your choice.
    + Display it on the screen.
    + Output its file data to stdout.
* You may not use libraries or builtins that generate barcodes (I'm looking at you, Mathematica), although you may use image or graphics libraries.
* The last digit of a UPC is usually a check digit, but for these purposes you don't have to worry about it.

## Examples

Here are some more examples to test your code with. The binary output is also given for convenience.

Input: `012345678910`

Output:

```
10100011010011001001001101111010100011011000101010101000010001001001000111010011001101110010101

```

Input: `777777222222`

Output:

```
10101110110111011011101101110110111011011101101010110110011011001101100110110011011001101100101

```

## Scoring

This is code golf, so the shortest submission (in bytes wins). Tiebreaker goes to the earliest post.

# Answer
# CJam, ~~58~~ 57 bytes

```
'P1N95S30N[A1r:~"rflB\NPDHt":i2fbf=:R6<::!0AAR6>A1]s30*S*

```

Prints a Portable BitMap (ASCII) to STDOUT. Try it online.

### How it works

```
'P1N95S30N     e# Push 'P', 1, '\n', 95, ' ', 30 and '\n'.

[              e#
  A1           e#   Push 10 and 1.
  r            e#   Read a token from STDIN.
  :~           e#   Caluate each character ('0' -> 0).
  "rflB\NPDHt" e#   Push that string.
  :i           e#   Cast each character to integer.
               e#   This pushes [114 102 108 66 92 78 80 68 72 116].
  2fb          e#   Convert each integer to base 2.
               e#   This pushes the representations for the right side.
  f=           e#   Select the proper representation of each digit in the input.
  :R           e#   Save the result in R.
  6<           e#   Keep the representations of the first six digits.
  ::!          e#   Negate each binary digit to obtain the "left" representation.
  0AA          e#   Push 0, 10, 10.
  R6>          e#   Push the representations of the last six digits.
  A1           e#   Push 10, 1.
]s             e# Collect in an array and cast to string.

30*            e# Repeat the resulting string 30 times.
S*             e# Join it, using spaces as separators.

```
> 3 votes

# Answer
# Rev 1 BBC BASIC, 155 ascii chars, tokenised filesize 132 bytes

```
INPUTn$
FORi=91TO185p=i MOD2j=i MOD47IFj<42j+=i DIV141*42p=(j>41EORASC(MID$("XLd^bFznvh",VAL(MID$(n$,j/7+1,1))+1)))>>(j MOD7)AND1
IFp LINEi*2,60,i*2,0
NEXT

```

saved a few bytes by incorporating the offset of 43 into the `i` loop. In order to avoid breaking the `MOD2` an additional 47 had to be added for a total of 90.

This moves the barcode further from the origin, as shown, if that is acceptable:

# Rev 0 BBC BASIC, 157 ascii chars, tokenised filesize 137 bytes

```
INPUTn$
FORi=1TO95p=i MOD2j=(i+43)MOD47IFj<42j+=i DIV51*42p=(i>50EORASC(MID$("XLd^bFznvh",VAL(MID$(n$,j/7+1,1))+1)))>>(j MOD7)AND1
IFp LINEi*2,0,i*2,60
NEXT

```

Download interpreter at http://www.bbcbasic.co.uk/bbcwin/bbcwin.html

The default screen mode is black text on a white background. This differs from original BBC BASC.

**Ungolfed version with test printing**

Calculation of a data bar depends on `IF j<42` and must all be done on one line. In the ungolfed version it is done in three steps. In the golfed version the last two steps are combined into a single huge expression `p=...`

I had to reverse the order of the bitmaps, because I use `>>(j MOD 7)` to access the bits, which means I access the least significant bit first. Once this is done, all the left bitmaps are conveniently in the ASCII range.

```
  INPUTn$
  FOR i=1TO95                            :REM iterate through 95 bars
    p=i MOD2                             :REM calculate colour of format bar 1=black
    j=(i+43)MOD47                        :REM repetition is 42 data bars + 5 format bars. offset and modulo. if j<42 it is a data bar and we must change p.

    REM if i DIV 51=1 we are in the second half, so add 42 to j. Find the bitmap for left hand value, from character j/7 of the input.
    REM i>50 evaluates to false=0 true=-1. XOR this with p to invert bitmap for right hand side. Shift and AND with 1.
    IF j<42 j+=i DIV51*42:p=ASC(MID$("XLd^bFznvh",  VAL(MID$(n$,j/7+1,1))+1  )) :p=(i>50EORp)>>(j MOD7) AND 1

    IF j MOD 7 = 0 PRINT                  :REM format test output
    PRINT ;p;                             :REM print test output
    IF p LINEi*2-2,0,i*2-2,60             :REM if p=1 plot bar. there are 2 logical units for each pixel.
  NEXT

```

**Typical output, ungolfed version, with test output**
> 4 votes

# Answer
# JavaScript ES6, 225 bytes

```
s=>`P1
30 90
`+([...`101${(f=(z,j)=>[...j].map(i=>`000${z[+i].toString(2)}`.slice(-7)).join``)([13,25,19,61,35,49,47,59,55,11],s[0])}01010${f([114,102,108,66,92,78,80,68,72,116],s[1])}101`].join` `+`
`).repeat(30).slice(0,-1)

```

Could of been shorter with ES7 features but I'm not sure about their support so I'm sticking with ES6. I'm also assuming an input as an array. The output is a PBN file. There is also lots of golfing to do.

If I did anything wrong leave a comment and I'll be sure to fix it
> 2 votes

# Answer
# Perl, 153 bytes

```
substr($_=<>,6,0)=A;y/0-9A/=ICmSa_kg;0/;$s.=sprintf("%07b",-48+ord$1^($k++>6?127:0))while/(.)/g;$s=~s/0{7}/01010/;print"P1
95 30
".('101'.$s.'101'.$/)x30

```

Copy to a file barcode.perl and then run like this:

```
perl barcode.perl > output.pbm

```

then input the barcode number.

Explanation:

The bit patterns for the barcode digits are stored in a string and substituted for the input digits using the Perl `y///` transliteration operator. Each value in the substitution string has 48 (ASCII '0') added from it, to avoid unprintable characters. Digits in the second half of the barcode are inverses of those in the first half.

The central pattern is set to 0000000 (a pattern that can otherwise never appear, encoded as 'A' and then '0') and then substituted with 01010 rather than handling its different length as a special case when `sprint`ing.
> 2 votes

# Answer
# Octave, 115 bytes

```
function b(s)
n='rflB\MPDHt'-0;r=dec2bin(n(s-47)',7)'(:)-48;v=[a=[1 0 1] ~r(1:42)' 0 a r(43:84)' a];v(ones(30,1),:)

```

Multi-line version:

```
function b(s)
   n='rflB\MPDHt'-0;
   r=dec2bin(n(s-47)',7)'(:)-48;
   v=[a=[1 0 1] ~r(1:42)' 0 a r(43:84)' a];
   v(ones(30,1),:)

```

`n` is the ASCII equivalent of the right-side digit codes (they were easier to enter than the left side as they were all displayable characters). After that, a straight decimal-to-binary conversion with some annoying type changes from char to numeric. `v` builds the final binary string and then we repeat it 30 times and output to console.

Sample output with only 2 of the 30 rows shown for brevity:

```
s = '777777222222';
ans =

 Columns 1 through 30:

   1   0   1   0   1   1   1   0   1   1   0   1   1   1   0   1   1   0   1   1   1   0   1   1   0   1   1   1   0   1
   1   0   1   0   1   1   1   0   1   1   0   1   1   1   0   1   1   0   1   1   1   0   1   1   0   1   1   1   0   1
...

 Columns 31 through 60:

   1   0   1   1   1   0   1   1   0   1   1   1   0   1   1   0   1   0   1   1   1   0   1   1   0   0   1   1   0   1
   1   0   1   1   1   0   1   1   0   1   1   1   0   1   1   0   1   0   1   1   1   0   1   1   0   0   1   1   0   1
...

 Columns 61 through 90:

   1   0   0   1   1   0   1   1   0   0   1   1   0   1   1   0   0   1   1   0   1   1   0   0   1   1   0   1   1   0
   1   0   0   1   1   0   1   1   0   0   1   1   0   1   1   0   0   1   1   0   1   1   0   0   1   1   0   1   1   0
...

 Columns 91 through 94:

   0   1   0   1
   0   1   0   1
...

```

Compressed output:

```
1010111011011101101110110111011011101101110110101110110011011001101100110110011011001101100101

```

I had originally intended to display the image, but sending output to the console saved me 9 bytes. You can display the results using `imshow`, but it displays `1` as white and `0` as black, so you have to invert the data first.

```
imshow(~v(ones(30,1),:));

```
> 1 votes

# Answer
# Cobra - 218

```
do(s='')
    print'P1\n95 30'+('\n'+('101'+(for n in 12get Convert.toString(if((t=139+[2,14,8,50,24,38,36,48,44,0][s[n]to int-48])and n<6,t,~t),2)[-7:]+if(n-5,'','01010')).join('')+'101').toCharArray.join(' ')).repeat(30)

```
> 1 votes

# Answer
# Javascript ES6, 199 bytes

```
n=>`P1 95 30 `+(101+(g=(a,...s)=>(``+1e12+n).slice(...s,-6).split``.map(m=>(1e3+a[m].toString(2)).slice(-7)).join``)(a=[13,25,19,61,35,49,47,59,55,11],-12)+`01010`+g(a.map(i=>~i&127))+101).repeat(30)

```
> 1 votes

# Answer
# Python 2, 174 bytes

I know it can be golfed.

The string `s` is the binary table in the question with the left half of the table as the left half of the string. The values are ANDed by 63 first if in the right half (remove first 1), then shifted by 63 to be printable ASCII.

BUG: Currently trying to fix a bug. The output of the first example is off by one digit of the barcode. If you figure it out, let me know please.

```
I=raw_input()
s="LXR|bpnzvJcekA[MOCGs"
x="".join(format(ord(s[int(I[i])+10*(i>5)])-63|1+63*(i>5),'07b')for i in range(len(I)))
L=len(x)/2
print"101%s01010%s101"%(x[:L],x[L:])

```
> 0 votes

---
Tags: code-golf, graphical-output
---


title: Create rainbow text

text:
# Question
Title: Create rainbow text
Your challenge is to take input as a line of text and output it like this.

## Input / output

The input will be a string that contains only printable ASCII characters. The first or last characters will never be spaces, and there will never be two spaces in a row. It will always be at least two characters long.

Your output should be the same string, converted to rainbow colors as will be described below. The output may be in image form (saved to a file or somehow otherwise made available), or it may simply display the result on the screen (as the reference implementation below does).

## Conversion

To determine what color each letter in the string should become, use the following algorithm. Note that *each letter is its own individual color*. **This is not a gradient!**

* If this character is a space:

+ ... it doesn't matter, because spaces can't really... have a color anyway. Simply output a space.
* Otherwise:

+ Let `i` = the index of this character in the string (0-based, so for the very first letter, this is `0`), not counting spaces. For example, in the string `foo bar`, this value would be `4` for the `a`. In other words, this is how many non-spaces have been encountered so far.
    + Let `n` = the number of non-spaces in the string.
    + The color of this letter can now be expressed, in the HSL cylindrical-coordinate system, as \[hue=(`i`/`n`)\*360°, saturation=100%, lightness=50%\].

Note that these directions imply that the output for `foo` and `f oo` should be exactly the same, except for an added space after the `f`. That is, all the letters should retain the same colors.

Further rules for the conversion process are described below, in the **Rules** section.

## Reference implementation

This is written in JavaScript, and you can try it by pressing the "Run code snippet" button.

```
window.addEventListener('load', function() {
    addRainbow('Your challenge is to take input as a line of text and ' +
        'output it like this.');
});

// append this text rainbow-ified to the argument (document.body by default)
function addRainbow(text, el) {
    (el || document.body).appendChild(makeRainbow(text));
}

// returns a <div> that contains the text in a rainbow font
function makeRainbow(text) {
    var div = document.createElement('div');
    var letterCount = text.replace(/ /g, '').length, spaceCount = 0;
    text.split('').forEach(function(letter, idx) {
        if (letter == ' ') ++spaceCount;
        div.appendChild(makeLetter(letter, (idx - spaceCount) / letterCount));
    });
    return div;
}

// returns a <span> that contains the letter in the specified color
function makeLetter(letter, hue) {
    hue = Math.floor(hue * 360);
    var span = document.createElement('span');
    span.appendChild(document.createTextNode(letter));
    span.style.color = 'hsl(' + hue + ', 100%, 50%)';
    return span;
}
```

## Rules

* When computing the Hue value of a letter, you will almost certainly get a decimal (non-integer) number. You may round this to the nearest integer, floor it, take the ceiling, or simply not round at all.
* The font size must be readable. Here, this is defined as a 10pt size font or greater.
* You may use a fixed-width canvas or "drawing area" to output the text, but it *must* be able to fit the example given in the very first sentence of this post.
* Scoring is , so the shortest code in bytes will win.

# Answer
> 12 votes
# Perl 5.28.1 (webperl) \+ `-p`, 88 bytes

```
@c=unpack C35,"..........vR../012.3-'!..9]........";s|\S|.[38;5;$c[@c*$i++/y/!-~//]m$&|g
```

Try it online!

## Explanation

This script uses an approximation of the colours available to terminal (256 maximum) currently only including a few colour points selected from this list, so it is likely not to spec, but this was fun anyway! I filtered the list to only show colours with `S` and `L` values of `100%` and `50%` respectively, then sorted by hue, packed the numbers into a string and select the colours from that list.

This implementation includes non-printable characters! Stole @edc65's idea of only replacing `\S` instead of `.`, simple, but clever!

# Answer
> 10 votes
# Python 2: 240 using PIL and colorsys lib

```
import PIL,colorsys as c
s=input()
u,a=len(s),255
g=Image.new('RGB',(u*6,13),(a,)*3)
[ImageDraw.Draw(g).text((j*6,0),s[j],fill=tuple(int(h*a)for h in c.hls_to_rgb(1.*(j-s[:j].count(' '))/(u-s.count(' ')),.5,1)))for j in range(u)]
g.show()

```

Example output:

Thanks to @agtoever and @Trang Oul for some golfing tips, and for @Mauris for pointing out the spaces requirement.

To add a true type fonts, font size control, including horizontal offset and color change based on length.

```
import PIL as P,colorsys as c
s=input()
u=len(s)
a=255
fs=25
f=P.ImageFont.truetype("a.ttf",fs)
sza=f.getsize(s)
oa=f.getoffset(s)
g=P.Image.new('RGB',(sza[0]+fs,2*sza[1]+oa[1]),(a,)*3)
r=fs/4
P.ImageDraw.Draw(g).text((r,0),s,fill=(0,0,0),font=f)
for j in range(u):
 o=f.getoffset(s[j])
 sz=f.getsize(s[j])
 r+=o[0]
 P.ImageDraw.Draw(g).text((r,0+fs),s[j],fill=tuple([int(h*a)for h in c.hls_to_rgb(1.*r/sza[0],.5,1)]),font=f)
 r+=sz[0]
g.save('a.png')
g.show()

```

The font I used is available from here: The result is (the top is just printing the string, the one below is printing per letter):

# Answer
> 5 votes
# JavaScript (ES6), 114 ~~117 125~~

*Edit2* 3 bytes saved thx @Dom Hastings *Edit* Invalid HTML, but working anyway.

Usual note: test running the snippet on an EcmaScript 6 compliant browser (notably not Chrome not MSIE. I tested on Firefox)

```
F=s=>document.write(s.replace(/\S/g,c=>`<b style=color:hsl(${i++/s.replace(/ /g,'').length*360},100%,50%>`+c,i=0))
```

```
<input value='Your challenge is to take input as a line of text and output it like this.' id=I size=100>
<button onclick='F(I.value)'>-></button>
```

# Answer
> 5 votes
# Python 3, 131 bytes

Simular to Dom Hastings' answer but implemented in python.

The string `'|\x82\x88\x8ejF"#$%\x1f\x19\x137[\x7f~}'` was built form the list `[124,130,136,142,106,70,34,35,36,37,31,25,19,55,91,127,126,125]` is the terminal colour codes to display in order. They have been filtered so they only include colours with saturation 100% and value 50%. The list was then sorted so the correct hues were displayed first.

Takes input from stdin and returns it to stdout.

### Your terminal you are using MUST support ANSI escape codes to run this properly.

```
x=input();u=u'|\82\88\8ejF"#$%\1f\19\137[\7f~}';j=0
for i in x:print('\033[38;5;%dm%s'%(ord(u[j*18//len(x.replace(" ", ""))]),i),end="");j+=i!=" "

```

Or shortened version with literal byte characters (Didn't paste properly):

```
x=input();u='|<82><88><8E>jF"#$%^_^Y^S7[^?~}';j=0
for i in x:print('ESC[38;5;%dm%s'%(ord(u[(j*18)//len(x.replace(" ", ""))]),i),end="");j+=i!=" "

```

Literal hexdump:

```
783d696e70757428293b753d277c82888e6a46222324251f1913375b7f7e7d273b6a3d300a666f72206920696e20783a7072696e7428271b5b33383b353b25646d25732725286f726428755b286a2a3138292f2f6c656e28782e7265706c616365282220222c20222229295d292c69292c656e643d2222293b6a2b3d69213d2220220a

```

Thanks @swstephe for saving 9 bytes (and also making me notice my byte counting was ever so slightly very wrong)!

# Answer
> 2 votes
# PHP, 165 bytes

Run with input as the parameter "s"

The HTML is invalid but it should render in all major browsers (tested in Chrome and Firefox)

```
<?php $n=preg_match_all("/[^ ]/",$q=$_GET['s']);for($i=$j=0;$j<strlen($q);$j++){if(" "!=$s=$q[$j])$i+=360;echo"<a style='color:hsl(".floor($i/$n).",100%,50%)'>".$s;}

```

# Answer
> 1 votes
# PHP 4.1, ~~112~~ ~~103~~ 102 bytes

I've used @DankMemes' answer as a starting point. From there on, I've implemented a **ton** of changes, to the point that the code is different.

The implementation is similar, the code is totally different.

```
foreach(str_split($s)as$c)echo"<a style=color:hsl(",((" "^$c?$i+=360:$i)/strlen($s))|0,",100%,50%>$c";

```

To use it, simply set a value on a SESSION/GET/POST/COOKIE with the name `s`.

Result of running this function, on the test sentence:

```
<a style=color:hsl(4,100%,50%>Y<a style=color:hsl(9,100%,50%>o<a style=color:hsl(14,100%,50%>u<a style=color:hsl(19,100%,50%>r<a style=color:hsl(24,100%,50%> <a style=color:hsl(29,100%,50%>c<a style=color:hsl(34,100%,50%>h<a style=color:hsl(38,100%,50%>a<a style=color:hsl(43,100%,50%>l<a style=color:hsl(48,100%,50%>l<a style=color:hsl(53,100%,50%>e<a style=color:hsl(58,100%,50%>n<a style=color:hsl(63,100%,50%>g<a style=color:hsl(68,100%,50%>e<a style=color:hsl(72,100%,50%> <a style=color:hsl(77,100%,50%>i<a style=color:hsl(82,100%,50%>s<a style=color:hsl(87,100%,50%> <a style=color:hsl(92,100%,50%>t<a style=color:hsl(97,100%,50%>o<a style=color:hsl(102,100%,50%> <a style=color:hsl(107,100%,50%>t<a style=color:hsl(111,100%,50%>a<a style=color:hsl(116,100%,50%>k<a style=color:hsl(121,100%,50%>e<a style=color:hsl(126,100%,50%> <a style=color:hsl(131,100%,50%>i<a style=color:hsl(136,100%,50%>n<a style=color:hsl(141,100%,50%>p<a style=color:hsl(145,100%,50%>u<a style=color:hsl(150,100%,50%>t<a style=color:hsl(155,100%,50%> <a style=color:hsl(160,100%,50%>a<a style=color:hsl(165,100%,50%>s<a style=color:hsl(170,100%,50%> <a style=color:hsl(175,100%,50%>a<a style=color:hsl(180,100%,50%> <a style=color:hsl(184,100%,50%>l<a style=color:hsl(189,100%,50%>i<a style=color:hsl(194,100%,50%>n<a style=color:hsl(199,100%,50%>e<a style=color:hsl(204,100%,50%> <a style=color:hsl(209,100%,50%>o<a style=color:hsl(214,100%,50%>f<a style=color:hsl(218,100%,50%> <a style=color:hsl(223,100%,50%>t<a style=color:hsl(228,100%,50%>e<a style=color:hsl(233,100%,50%>x<a style=color:hsl(238,100%,50%>t<a style=color:hsl(243,100%,50%> <a style=color:hsl(248,100%,50%>a<a style=color:hsl(252,100%,50%>n<a style=color:hsl(257,100%,50%>d<a style=color:hsl(262,100%,50%> <a style=color:hsl(267,100%,50%>o<a style=color:hsl(272,100%,50%>u<a style=color:hsl(277,100%,50%>t<a style=color:hsl(282,100%,50%>p<a style=color:hsl(287,100%,50%>u<a style=color:hsl(291,100%,50%>t<a style=color:hsl(296,100%,50%> <a style=color:hsl(301,100%,50%>i<a style=color:hsl(306,100%,50%>t<a style=color:hsl(311,100%,50%> <a style=color:hsl(316,100%,50%>l<a style=color:hsl(321,100%,50%>i<a style=color:hsl(325,100%,50%>k<a style=color:hsl(330,100%,50%>e<a style=color:hsl(335,100%,50%> <a style=color:hsl(340,100%,50%>t<a style=color:hsl(345,100%,50%>h<a style=color:hsl(350,100%,50%>i<a style=color:hsl(355,100%,50%>s<a style=color:hsl(360,100%,50%>.
```

---
Tags: code-golf
---