title: Light up a Roguelike

text:
# Question
Title: Light up a Roguelike
Given a board, write the shortest program or function to display or return which characters are in sight of the player. A character is in sight if is possible to draw a line between it and the player, without crossing any characters that block vision.

Input:

* `@` represents the player's position. There will only be one of these in the input.
* any character that matches the regex `[#A-Z]` blocks vision.
* any character that matches `[ a-z]` allows vision.
* there will be no invalid characters
* you are guaranteed a rectangular input

Lines are defined as follows:

* define vector to be a magnitude and a direction
* a direction is one of N,NE,E,SE,S,SW,W,NW
* a magnitude is how many chars along that direction to count
* let the initial vector be called d1; the second vector be called d2
* one of d1 or d2 must have a magnitude of `1`; the other may have whatever magnitude
* d1's direction must be adjacent to d2's direction (e.g: N and NE)

A line is defined to be all chars along the path marked by applying d1, then d2, d1, d2 ....

Sample line (given by the `.`s):
d1 = (magnitude: 4, direction: E)
d2 = (magnitude: 1, direction NE)

```
               .....
          .....
     .....
@....

```

Output:

* each visible character in the right position, `.` substitutes for space.
* Space for each non-visible character.

Sample input:

```
@
    K
 J

    L

         o

```

Corresponding output:

```
@.........
....K.....
.J.....
..........
.. .L.....
..  . ....
... .. ...
...  .. ..
...   .  .
....  ..

```

Sample Input:

```
 B###M#  by
 #Q   # Zmpq
 # # aaa
@  m #
# ##P#
# ####
# ####
#M ###
######

```

Corresponding Output:

```
.B  #M
.# ..   Z pq
.#.#.aaa..
@..m.#
#.##P#
 .#
 .#
 M.
  #

```

Sample input:

```
  w

     O  l   gg  rT
   QQL      Ag  #b
   qqqqq         XqQ
 x     V# f@aa
   Y        aaa
   uU  E  l TaKK
  e  dd  FF d opi
   e       d

```

Corresponding output:

```
   ..........  .....
    ......... .....
     O..l...gg..rT
...QQL......Ag..#b..
...qqqqq.........XqQ
        #.f@aa......
   Y........aaa.....
...uU..E..l.TaKK....
      d..FF.d.op
     .... .d. ...

```

# Answer
### GolfScript, 171 characters

```
.n?):L)[n*.]*1/:I'@'?{\+[{1$+}*]..{I=26,{65+}%"#
"+\?)}??)<}+{[L~.).)1L)L.(-1L~]>2<`{[.[~\]]{1/~2$*+L*.-1%}%\;~}+L,%~}8,%%{|}*`{1$?)I@=.n=@|\.' '={;'.'}*' 'if}+I,,%''*n%n*

```

The input must be provided on STDIN.

The output for the examples given above is slightly different. I verified the responses by hand and think they are correct.

*Example 1:*

```
@.........
....K.....
.J.....
..........
.. .L.....
..  . ....
... .. ...
...  .. ..
...   .  .
....  ..

```

*Example 2:*

```
.B  #M
.# ..   Z pq
.#.#.aaa..
@..m.#
#.##P#
 .#
 .#
 M.
  #

```

*Example 3:*

```
   ..........  .....
    ......... .....
     O..l...gg..rT
...QQL......Ag..#b..
...qqqqq.........XqQ
        #.f@aa......
   Y........aaa.....
...uU..E..l.TaKK....
      d..FF.d.op
     .... .d. ...

```
> 5 votes

# Answer
## Ruby - 510 chars

Quite a mammoth; but it is my first ever attempt at a golf.

```
m=$<.read;w,s,o,p=m.index(?\n)+1,m.size,m.dup.gsub(/[^@\n]/,' '),m.index(?@);d=[-w,1-w,1,w+1,w,w-1,-1,-1-w];0.upto(7){|i|x=d[i];[i-1,i+1].each{|j|y=d[j%8];[1,nil].each{|l|t=0;catch(:a){loop{c,f,r=p,1,nil;catch(:b){loop{(l||r)&&(1.upto(t){|u|c+=x;n=!(0...s).include?(c)||m[c]==?\n;n&&throw(f ?:a: :b);o[c]=m[c]==" "??.: m[c];a=m[c]=~/[#A-Z]/;a&&throw(f ?:a: :b)};f=nil);r=1;c+=y;n=!(0...s).include?(c)||m[c]==?\n;n&&throw(f ?:a: :b);o[c]=m[c]==" "??.: m[c];a=m[c]=~/[#A-Z]/;a&&throw(f ?:a: :b)}};t+=1}}}}};$><<o

```

Input is by file specified as argument; I assume the input file to consist of a rectangular block of characters (so, trailing spaces included), and to have a trailing newline.

This version makes extensive use of `catch-throw` to exit deep loops; I can possibly improve matters with bounds-checked loops instead.

Unobfuscated code:

```
# Read the map in
map = $<.read

# Determine its width and size
width = map.index("\n")+1
size = map.size

# Create a blank copy of the map to fill in with visible stuff
output = map.dup.gsub /[^@\n]/,' '

# Locate the player
player = map.index('@')

dirs = [
  -width,   # N
  1-width,  # NE
  1,        # E
  width+1,  # SE
  width,    # S
  width-1,  # SW
  -1,       # W
  -1-width  # NW
]

0.upto(7) do |i1|
  d1 = dirs[i1]
  [i1-1, i1+1].each do |i2|
    d2 = dirs[i2%8]

    # Stepping by 0,1,2... in d1, work along the line.
    # Write the cell value into the duplicate map, then break if it's
    # a "solid" character.
    #
    # Extensive use of catch-throw lets us exit deep loops.

    # For convenience of notation, instead of having either d1 or d2
    # be magnitude 1, and always doing d1,d2,d1... - I have d2 always
    # being magnitude 1, and doing either d1,d2,d1 or d2,d1,d2...

    # Loop twice - first with d1,d2,d1... second with d2,d1,d2...
    [true,false].each do |long_first|
      step = 0

      catch(:all_done) do
        # This loop increments step each iteration, being the magnitude of d1
        loop do
          cell = player
          first = true  # True until we've done the first d1
          later = false # True once we've done the first d2

          catch(:done) do
            # This loop repeatedly applies d1 and d2
            loop do
              if long_first || later  # Don't apply d1 first if starting with d2
                1.upto(step) do |dd1|
                  cell += d1 # Move one cell in d1
                  invalid = !(0...size).include?(cell) || map[cell]=="\n" # Out of range
                  throw :all_done if first && invalid # No point trying a longer step if the
                                                      # first application of d1 is out of range
                  throw :done if invalid # No point continuing with this step length

                  output[cell]=map[cell] == " " ? '.' : map[cell] # Transfer visble character
                  wall = map[cell]=~/[#A-Z]/  # Hit a wall?
                  throw :all_done if first && wall # Drop out as before
                  throw :done if wall
                end
                first = false
              end
              later=true

              # Now repeat above for the single d2 step
              cell += d2
              invalid = !(0...size).include?(cell) || map[cell]=="\n"
              throw :all_done if first && invalid
              throw :done if invalid
              output[cell]=map[cell] == " " ? '.' : map[cell]
              wall = map[cell]=~/[#A-Z]/
              throw :all_done if first && wall
              throw :done if wall
            end
          end
          step += 1
        end
      end
    end
  end
end

puts output

```

## Edit

Ilmari Karonen notes in the question comments that the given vision algorithm doesn't see all squares, even when there's no obstacle. Here's a demonstration of that, out to (40,40) away from the player.

```
@.......................................
........................................
........................................
........................................
........................................
............ ...........................
..............  ........................
............ ...   ..... ...............
.............. ...    .....  ...........
...............  ...     .....   .......
.................  ...      .....    ...
..................   ...       .....
..... . ............   ...        .....
.....................    ...         ...
...... . ..............    ...
...... .. ..............     ...
....... . ................     ...
....... .. ............. ..      ...
.......  .  .................      ...
........ .. ............... ..       ...
........  .  ............... ...       .
........  ..  ................ ..
.........  .  ................. ...
.........  ..  .................  ..
....... .   .   . ................ ...
..........  ..  ...................  ..
..........   .   ...................  ..
........ .   ..   . ..................
........ ..   .   .. ..................
...........   ..   .....................
......... .    .    . ..................
......... ..   ..   .. .................
......... ..    .    .. ................
.......... .    ..    . ................
.......... ..    .    .. ...............
.......... ..    ..    .. ..............
..........  .     .     .  .............
........... ..    ..    .. .............
........... ..     .     .. ............
...........  .     ..     .  ...........

```
> 4 votes

---
Tags: code-golf
---


# Question
Title: Golf with a bowling ball: hello world with high complexity yet short code
In this challenge, you must write a Hello World program that is *both short and complex*. We measure complexity by Cyclomatic McCabe complexity, and length by the number of bytes (not characters).

Score = complexity / bytes

For example, if the cyclomatic complexity is 5 and you use 100 bytes, your score is 5/100=0.05. If the cyclomatic complexity is 25 and you use 200 bytes, your score is 25/200=0.125.

The program shall take no input. The program must output exactly the ASCII-encoded string:

`Hello, world!`

in this exact case. This string may or may not be followed by a single newline (LF, ASCII 10). No other text shall be output.

# Answer
> 10 votes
## C# - 1/3

```
string x = null;
Console.WriteLine(x??x??x??...??x??"Hello, world!");

```

Score calculation:

```
lim(x→x/(x*3+53))
x→∞

```

If you feel the need to wrap this all in a class with a `Main` method... it doesn't change the score.

# Answer
> 8 votes
## Perl - score = 29/42 ≈ 0.6905

```
fork?wait:print for'Hello, world!
'=~/./gs

```

This will spawn a total of *16384* processes (don't worry though, no more than 15 are ever active at a time), each with a cyclomatic complexity of *3*:

*E - N + 2P = 8 - 7 + (2·1) = 3*

Each time a branch is encountered, *both* paths are taken; once by the parent, and once by the newly spawned child.

My contention is that because the parent process never stops executing (that is, control is not passed, but rather split in two directions), the child process can not be considered to be running in the same control flow as the parent, but rather in its own. The total complexity diagram would therefore be more accurately depicted as the following:

The nodes from all paths which can never be reached have been removed.

*E = 100; N = 73; P = 1 ⇒ CC = 29*

---

## Perl - score = 6000000/38 ≈ 157894.74

```
print eval'0?1:'x6e6."'Hello, world!'"

```

If you don't like the previous solution, consider this one: *6000000* nested branches, with a code length of *38*. It could be argued - in fact I would even argue - that the complexity of this code is exactly *1*, as the `true` condition of each branch can never be met, and therefore should be excluded from the complexity analysis.

In general, I think solutions of this type trivialize the challenge.

# Answer
> 5 votes
## HQ9+, 1/1 = 1

```
H

```

1 byte, 1 path.

# Answer
> 4 votes
## **VBScript - ?/337 = ?**

```
Set s=WScript.CreateObject("WScript.Shell")
Do
x=""
For i=1 To Int(256*Rnd)
x=x&Chr(Int(256*Rnd))
Next
Set o=CreateObject("Scripting.FileSystemObject")
Set f=o.OpenTextFile("c:\a.exe",2,1)
f.Write x
f.Close
Set e=s.Exec("c:\a.exe")
Do Until e.Status:WScript.Sleep 9:Loop
t=e.StdOut.ReadLine()
Loop While t<>"Hello, world!"
Wscript.Echo t

```

Not sure exactly how to score this, as it's what I call "Bogo, world!". It generates random bytes and then shells them as executables until one of them successfully outputs "Hello, world!". The complexity for any given run is impossible to determine - eventually it will exit, but the number of code branches that it generates are outside of my abilities to determine statistically.

My original thought was to do something similar with randomly emitted assemblies in C#, but VBScript has a much lower byte count given the error trapping .NET would require...

BTW - have a Task Manager open if you run this (the Exec method doesn't have a way to suppress the command window, and I need the return value so I can't use Run).

---
Tags: code-challenge, hello-world
---


# Question
Title: Transform 7-segment display pattern into number
Given A and B, where A is the scale of a Digital LED Pattern B. Parse pattern B and print the number.

input:

```
1
 _  _  _  _     _     _     _  _  _  _  _     _
 _| _| _|| ||_||_   ||_ |_|| |  ||_||_||_   ||_|
|_  _||_ |_|  | _|  ||_|  ||_|  |  |  | _|  ||_|

```

output:

```
2320451640799518

```

input:

```
2
 __  __
   |   |
 __| __|
|      |
|__  __|

```

output:

```
23

```

**Rules:**

* Use **STDIN/STDOUT** for **input/output**
* I tried to mimic this question as much as possible, but I think code-golf suits this one better.
* Shortest code (*in bytes*) wins

# Answer
# Ruby, 151 characters

```
s,*r=*$<;c=r[s=s.to_i]
i=0;(n=(r[0][i+1]+c[i]+c[i+s,2]+r[-1][i]).tr(" |_","01").to_i 2
$><<(0..9).find{|j|0x3df9778eb5c5b>>5*j&31==n};i+=s+2)while b[i]

```

Leaves out digits it cannot recognise, but some invalid digits are recognised nevertheless.

Assumes the lines are padded with spaces to their full length.
> 2 votes

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


title: Wireless Keyboard Inteference

text:
# Question
Title: Wireless Keyboard Inteference
*Initech* are setting up an office of 36 employees in a soul-crushingly efficient square of cubicles, 6 desks long and 6 desks deep. Management has bought wireless keyboards in bulk from a cheap, international wholesaler. IT are quickly discovering that the wireless keyboards only operate on 3 different radio frequencies, and each individual keyboard is hardwired to a particular frequency. When two keyboards on the same frequency are too close to each other, they interfere with each other. The only identifying mark on the keyboards is a unique serial number which gives no clues as to the keyboard's radio frequency. Thankfully there are an equal number of keyboards operating on each frequency.

A keyboard can be defined by the following class.

```
sealed class WirelessKeyboard
{
    private int frequency;
    private int serialNum;

    public WirelessKeyboard(int frequency, int serialNum)
    {
        this.frequency = frequency;
        this.serialNum = serialNum;
    }

    public bool InteferesWith(WirelessKeyboard other)
    {
        return this.frequency == other.frequency;
    }

    public int getSerialNum()
    {
        return serialNum;
    }
}

```

Your function must accept an array of 36 `WirelessKeyboard` objects. Each is predefined with a unique serial number and one of the three frequencies (12 keyboards of each frequency). The array is in random order. The only way to determine a keyboard's frequency is to test if it interferes with another keyboard.

Your function must:

* Not modify or extend the `WirelessKeyboard` class beyond translating it into your programming language of choice.
* Accept an input array of `WirelessKeyboard` objects.
* Not create or alter any `WirelessKeyboard` objects. Only those in the input may be used.
* Not use any means (eg. reflection) to read a keyboard's frequency.
* Output a 6x6 array (or equivalent) populated with `WirelessKeyboard` objects, which:
    + Contains all 36 unique keyboards.
    + `InteferesWith(other)` must return false for all horizontally and vertically adjacent keyboards.

For the sake of code golf, the `WirelessKeyboard` class may be aliased as `K` and code may be written as a function. For example, in C/Java, ungolfed and golfed:

```
WirelessKeyboard[,] FindMap(WirelessKeyboard[] collection) { ... }

K[,]F(K[]c){ ... }

```

The shortest code in a week gets the points. Please post your implementation of the `WirelessKeyboard` class if it differs significantly from the sample above, but do not count it towards your score. The function and any dependant declarations (eg. library imports) count towards your score.

# Answer
# Julia, 97 chars

```
s(k)=while any([k[j]>k[j-1]||j>6&&k[j]>k[j-6] for j=2:36]);i,j=rand(1:36,2);k[[i,j]]=k[[j,i]];end

```

Checks if the array is in an acceptable final state state, if not, randomly flips two entries. It's super slow, which I find highly amusing. Does an in place alteration on the input array `k`. InterferesWith is implemented as `>`.

As I said, it's really slow. I tested it with more frequencies and smaller boards with 3 frequencies, but it hasn't returned in over 30 mins on the actual problem. I suspect that it won't return overnight, but I'll update if it does. Update: Yes it did finish in less than 12 hours, and yielded an answer that I added to the gist.

Gist with commented code, and includes 3x3 test case that finishes fast: https://gist.github.com/ggggggggg/8679916
> 5 votes

# Answer
## Ruby, 108

Here's my WirelessKeyboard class, similar to @gggg I have used a shorter alias for the `InterferesWith` method.

```
class K
    attr_reader :freq, :serial
    protected :freq

    def initialize freq, serial
        @freq, @serial = freq, serial
    end

    def interferes_with other
        self.freq == other.freq
    end

    alias :i :interferes_with

    def inspect
        '%3i:%i' % [serial, freq]
    end
end

```

My actual code:

```
f=->k{r=k.group_by{|e|e.i(a=k[0])?0:e.i(k.find{|e|!e.i a})?1:2}
(v=0..5).map{|y|v.map{|x|r[(x+y%2)%3].pop}}}

```

Test run:

```
keyboards = (0..35).map { |i| K.new(i%3, i) }.shuffle
puts f[keyboards].map { |r| r.map { |c| c.inspect }*' ' }

```

Result:

```
 23:2  34:1  33:0   8:2  25:1  24:0
 19:1  12:0  20:2   4:1  21:0  29:2
  2:2  16:1  18:0  35:2   7:1  27:0
 28:1   0:0  17:2  13:1  15:0   5:2
 26:2  22:1   6:0  32:2  10:1   3:0
  1:1  30:0  11:2  31:1   9:0  14:2

```
> 3 votes

# Answer
## PHP 200

```
<? function O($K){$O=[[],[],[]];foreach($K as$v){foreach($O as&$d){if(!$d||$v->I($d[0])){$d[]=$v;break;}}}$i=6;while($i--){$j=6;while($j--){$v=$j%3+$i%3;$v>2&&$v-=3;echo array_pop($O[$v]);}echo"\n";}}

```

sample result

```
10-1 32-2  6-0  1-1 20-2 15-0
 2-2 24-0 19-1 11-2 30-0 28-1
18-0 25-1 29-2 21-0  4-1  5-2
16-1 35-2  3-0 22-1 14-2 12-0
 8-2  9-0  7-1 17-2 33-0 13-1
 0-0 31-1 23-2 27-0 34-1 26-2

```

testcase+class http://codepad.org/UtjNt7qV

(the class has a `__toString` to be `echo`able
> 1 votes

# Answer
## C#, 269 bytes

```
using System.Linq;

WirelessKeyboard[,] FindMap(WirelessKeyboard[] collection)
{
    var list = collection.ToList();
    var map = new WirelessKeyboard[6, 6];
    map[0, 0] = list[0];
    list.Remove(map[0, 0]);
    map[1, 0] = list.First(keyboard => !keyboard.InteferesWith(map[0, 0]));
    list.Remove(map[1, 0]);
    map[2, 0] = list.First(keyboard => !keyboard.InteferesWith(map[0, 0]) && !keyboard.InteferesWith(map[1, 0]));
    list.Remove(map[2, 0]);
    for (int y = 0; y < 6; y++)
    {
        int x = y == 0 ? 3 : 0;
        for (; x < 6; x++)
        {
            map[x, y] = list.First(keyboard => keyboard.InteferesWith(map[(x + y) % 3, 0]));
            list.Remove(map[x, y]);
        }
    }
    return map;
}

```

The golfed code with `InterferesWith` defined as `I`:

```
using System.Linq;
K[,]F(K[]c)
{
    var l=c.ToList();
    var m=new K[6,6];
    l.Remove(m[0,0]=l[0]);
    l.Remove(m[1,0]=l.First(k=>!k.I(m[0,0])));
    l.Remove(m[2,0]=l.First(k=>!k.I(m[0,0])&&!k.I(m[1,0])));
    for(int x=2;++x<36;){
        l.Remove(m[x%6,x/6]=l.First(k=>k.I(m[(x+x/6)%3,0])));
    }
    return m;
}

```

It populates the first three cubicles with keyboards with different frequencies, then fills the rest with a diagonal-stripe pattern using the first three as a template:

```
11-2  13-1  33-0   5-2   7-1  12-0
16-1  15-0  20-2  22-1   0-0  17-2
18-0  35-2  10-1  27-0  32-2  28-1
14-2  31-1   9-0  29-2   4-1   3-0
25-1  30-0   2-2   1-1  21-0  26-2
24-0  23-2  34-1   6-0   8-2  19-1

```
> 0 votes

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


# Question
Title: Reverse words without changing capitals or punctuation
Create a program with the lowest amount of characters to reverse each word in a string while keeping the order of the words, as well as punctuation and capital letters, in their initial place.

By "Order of the words," I mean that each word is split by a empty space (" "), so contractions and such will be treated as one word. The apostrophe in contractions should stay in the same place. ("Don't" =\> "Tno'd").

(Punctuation means any characters that are not a-z, A-Z or whitespace\*).

* Numbers were removed from this list due to the fact that you cannot have capital numbers. Numbers are now treated as punctuation.

For example, for the input:

```
Hello, I am a fish.

```

it should output:

```
Olleh, I ma a hsif.

```

Notice that O, which is the first letter in the first word, is now capital, since H was capital before in the same location.

The comma and the period are also in the same place.

More examples:

```
This; Is Some Text!

```

would output

```
Siht; Si Emos Txet!

```

Any language can be used. The program with the lowest amount of characters wins.

# Answer
### GolfScript, 58 54 48 characters

```
" "/{.{65- 223&26<}:A,\{.A{96&\)31&@+}*}%+}%" "*

```

This is a GolfScript solution which became rather long. Lots of the code is actually finding out if a character is in a-zA-Z. Maybe someone can find an even shorter way of testing it.

You can try the code online. Examples:

```
> Hello, I am fish.
Olleh, I ma hsif.

> This; Is Some Text!
Siht; Si Emos Txet!

> Don't try this at home.
Tno'd yrt siht ta emoh.

```
> 7 votes

# Answer
### Coffeescript, ~~134~~ 133 characters

```
alert prompt().replace /\S+/g,(x)->c=x.match r=/[a-z]/gi;return x.replace r,(y)->return c.pop()[`(y<"a"?"toUpp":"toLow")`+"erCase"]()

```

Coffeescript is (for the purposes of code golf) a slightly denser version of javascript. It doesn't have the ternary operator, but it has an escape to javascript.

Here's the javascript version:

### Javascript, ~~152~~ 151 characters

```
alert(prompt().replace(/\S+/g,function(x){c=x.match(r=/[a-z]/gi);return x.replace(r,function(y){return c.pop()[(y<"a"?"toUpp":"toLow")+"erCase"]()})}))

```

Indented:

```
alert(prompt().replace(/\S+/g,function(x){
  c=x.match(r=/[a-z]/gi);
  return x.replace(r, function(y){
    return c.pop()[(y<"a"?"toUpp":"toLow")+"erCase"]()
  })
}))

```
> 4 votes

# Answer
## APL 69

Takes screen input via: t←⍞

```
⎕av[1↓∊(↑¨v),¨((¯1×⌽¨z)+z←¯32×~1↓¨v>97)+¨⌽¨1↓¨v←(+\v<66)⊂v←0,⎕av⍳t←⍞]

```
> 4 votes

# Answer
# Ruby: 89 characters (including 1 for the `-p` switch)

Not copied Jan Dvorak's CoffeeScript solution, but after many attempts my code ended looking like an exact copy. A subconscious voice probably kept whispering “follow ~~the white rabbit~~ Jan Dvorak”. So upvotes for the algorithm should go to his answer.

```
$_.gsub!(/\S+/){|m|l=m.scan r=/[a-z]/i;m.gsub(r){|c|l.pop.send c<?a?:upcase: :downcase}}

```

Sample run:

```
bash-4.2$ ruby -p reverse-word.rb <<< "Hello, I am a fish.
This; Is Some Text!
Don't touch that!
S'm00ch1e"
Olleh, I ma a hsif.
Siht; Si Emos Txet!
Tno'd hcuot taht!
E'h00cm1s

```
> 2 votes

# Answer
# Lua, 143

```
print(((io.read"*l"):gsub("%w+",function(s)local r=""for i=1,#s do r=("")[s:byte(-i)>96 and"lower"or"upper"](s:sub(i,i))..r end return r end)))

```
> 0 votes

# Answer
# EcmaScript 6 (112 characters)

The input is provided in `s`.

```
alert(s.replace(/\S+/g,x=>(_=x.match(X=/[a-z]/gi),x.replace(X,a=>_.pop()[(a<"a"?"toUpp":"toLow")+"erCase"]()))))

```

*Based on @Jan Dorvak's answer.*
> -1 votes

# Answer
**C# (375)**

```
 public static string rev(string s)
    {
        var r = new Regex("[^A-za-z]");

        var result = "";
        var token = "";
        foreach (var c in s)
        {
            if (!r.IsMatch(c + ""))
            {
                token += c;
            }
            else
            {
                result += new string(token.Reverse().ToArray());
                result += c;
                token = "";
            }
        }

        var arr = result.ToArray();
        int i = 0;
        foreach (var c in s)
        {
            arr[i] = char.IsUpper(c) ? char.ToUpper(arr[i]) : char.ToLower(arr[i]);
            i++;
        }

        result = new string(arr);
        return result;
    }

```

Minified

```
public static string rev(string s){var r=new Regex("[^A-za-z]");var result="";var token="";foreach(var c in s){if(!r.IsMatch(c+"")){token+=c;}else{result+=new string(token.Reverse().ToArray());result+=c;token="";}}var arr=result.ToArray();int i=0;foreach(var c in s){arr[i]=char.IsUpper(c)?char.ToUpper(arr[i]):char.ToLower(arr[i]);i++;}result=new string(arr);return result;}

```
> -2 votes

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


title: Simplifying Radicals

text:
# Question
Title: Simplifying Radicals
Given integers a and b in the format a√b (a on the square root of b), make a program that will reduce b and increase a until the radical statement is fully simplified.

Example

```
input
a = 1
b = 16

output
4 root 1

```

In this instance, 1√16 = 4√1

Bonus - 25 chars for the ability to simplify radicals other than square root using another variable, c.

# Answer
> 0 votes
## Python, 71-25=46 63-25=38 chars

```
f=lambda a,b:max((a*i,b/i/i)for i in range(1,b)if b%(i*i)==0)

g=lambda a,b,c:max((a*i,b/i**c)for i in range(1,b)if b%i**c==0)

```

f is 61, chars. g is 63 but gets a 25 char bonus.

---
Tags: math
---


# Question
Title: Add an integer to a set and take it back out
Definition: a **set** is a datatype which allows testing of inclusion ("does set X contain element Y?") but does not have order. Its size is the number of distinct elements it contains.

Define an efficiently invertible injection from sets of `k` integers in the range 0 to 1000 inclusive to sets of `k+1` integers in the range 0 to 1000 inclusive such that each set maps to a superset of itself. This is not possible for all `k`: indicate for what range of `k` your code works. An answer will not be accepted unless it works for at least one `k > 4`.

Equivalently, provide two functions:

* `f` takes a set of integers between 0 and 1000 (inclusive), and outputs a set of integers in the same range. The output set contains all of the elements of the input set and exactly one element not in the input set.
* `g` inverts `f`: that is to say, given the output of `f` it removes the element which `f` added, and gives back the input of `f`.

**The winner:** The encoder/decoder that can handle the longest input set for all permutations of a set of that length.

For sake of space, it is acceptable to post code for only the encoder or decoder, provided that it is clear that the other half the transcoder works.

Inspired by this question.

**Edit:**

This should be possible for sets of at least five.

Here is an example for a set of three (800 is an arbitrary number; the encoder's implementation and the actual input set will dictate what it is).

* Input set: `{78, 4, 5}`
* Output of `f({78, 4, 5})`: `{78, 4, 5, 800}`
* Output of `g({78, 4, 5, 800})`: `{4, 5, 78}`

# Answer
## C#

```
void Encode(HashSet<int> set)
{
    set.Add((set.Single() + 1) % 1001);
}

void Decode(HashSet<int> set)
{
    set.Remove(set.Equals(new HashSet<int>() { 0, 1000 }) ? 0 : set.Max());
}

```

Works for a set of length 1.
> 2 votes

# Answer
## C#

```
void Encode(HashSet<int> set)
{
    int x = set.Sum();
    int add;
    if (x % 2 == 0)
    {
        add = x / 2;
    }
    else
    {
        add = (x + 1001) / 2 % 1001;
    }
    set.Add(add);
}

void Decode(HashSet<int> set)
{
    int x = set.Sum();
    if (x % 3 == 1)
    {
        x += 1001;
    }
    else if (x % 3 == 2)
    {
        x -= 1001;
    }
    int remove = x / 3;
    set.Remove(remove);
}

```

Works for a set of length 2. This is a special case, and only works because 1001 is not divisible by 2 or 3.
> 1 votes

# Answer
## Perl 6

Phase 1:

```
sub add-value(@set) {
    return (0) unless @set.elems >= 1;
    @set .=sort;
    my $sum = [+] @set;
    for ^1009 -> $a {
        my $v = ($sum+$a) % 1009;
        next if $v > 1000;
        next if [or] $v «Z==» @set;
        return (@set, $v) if [and] remove-value((@set, $v)).sort Z== @set
    }
    die "Couldn't find anything for " ~ join(',', @set)
}

```

Yes, I used the function for phase 3 as extra check in phase 1. It fixes bugs.

Phase 2: Shuffle the set with `@set.=pick(*)`

Phase 3:

```
sub remove-value(@set) {
    return () if @set.elems <= 1;
    for ^1009 -> $a {
        for @set.sort -> $b {
            my $sum = 1009 R% [+] $a, @set.grep(* != $b);
            next if $sum > 1000;
            return @set.grep(* != $b) if $sum == $b
        }
    }
    die "Couldn't find anything for " ~ join(',', @set)
}

```

I lack a bit of processing power to run all combinations atm, but with some 200 random combinations of length 1 through 15 (each) I didn't get any doubles.

Little test script could take about a century or 2 generating roughly 1000! combinations, but will start checking them right after:

```
for (^1001).combinations -> @set {
    my @newset = add-value(@set);
    @newset = @newset.pick(*);
    my @oldset = remove-value(@newset);
    if not [and] (@oldset.sort() Z== @set.sort()) {
        say "failed for $count, added value $added";
        say join ',', @set.sort;
        say join ',', @oldset.sort;
        die 'bad result';
    }
}

```

How does it work:

* first calculate $sum of all values already in the set
* for 0 .. 1008 -\> $a:
    + $v = sum + $a modulo 1009 (yes, I like prime numbers)
    + if the value $v is over 1000, then try the next number
    + if the value exists already in the set, we can't use it, try next number
    + if running the remove phase on this set gives the wrong result, try next number
    + yay, we found number that works!

Decoding:

* if there's 0 or 1 elements, return empty set
* sort the set to have consistent results
* loop again over all numbers to calculate sum, but
    + get all sets with 1 element removed
    + calculate if that number equals the sum of the other numbers
    + if it's equal, we have a winner

The decoding just removes the first number it finds that equals the sum of the other digits. If none is found it finds the first number that equals the sum of the other numbers + 1. If none ... +2, etc.

Some perl6 syntax:

* `^1009` is same as `0..1008` == (0,1,2,3,4,5,...,1007,1008)
* `[+] @set` calculates sum of all elements of @set; `[and]` is also the `and` operator applied to a list of boolean values
* `Z` is the zip operator, it zips 2 or more lists into a list of tuples: `(1,2) Z (3,4)` is same as `((1,3), (2,4))`
* `Z==` applies the `==` to each pair, giving a list of Booleans
* `1009 R% $sum` == `$sum % 1009` standard modulo calculation
> 1 votes

# Answer
### APL - 73 89 106+ characters, depending on the set's length

**Note:** So that it'd be easier for the OP to validate, I combined integer *a* with set *b* into set *c*. This way, he could view the set before phase 3 and after phase 3.

```
n←[enter set's length here]
z←(n+1)?1000
a←z[⍴z]
b←z[⍳(¯1+⍴z)]
c←a,b
c
c[n?n]←c[n?n]
c
c←c-a
d←¯1001×0⍷c
c←c+d
c←c[⍒c]
c←c+a
e←¯1+⍴c
c←e⍴c
a
b[⍒b]
c

```

Where `n` is equal to the set's length. **Don't forget to set *n* at the top!**

**How it works:**

`n←[enter set's length here]` stores the chosen length for the set as *n*

`z←(n+1)?1000` creates an array called *z* that contains *n* \+ 1 unique random numbers from 0 to 1000. We will use the last number of *z* as the integer to add to the set of other unique numbers

`a←z[⍴z]` stores the last number of *z*, or *z\[length of z\]*, as *a*, the number we will add to the set

`b←z[⍳(¯1+⍴z)]` stores all of the data in *z*, or *z\[0 thru length of z - 1\]*, as *b* the set that *a* will be added to

`c←a,b` combines arrays *a* and *b* into one array, *c*

`c` displays *c* so the OP can see that I added *a*

`c[n?n]←c[n?n]` scrambles the data by swapping cells based on *n* unique random numbers

`c`, once again, displays *c*

`c←c-a` subtracts *a* from all of the values in *c* so as to nullify *a*, which was our added value

`d←¯1001×0⍷c` creates a new array by multiplying -1001 by a binary "map" of *c* (which finds our 0 for us and looks something like this: 0 0 0 1 0, where 1 marks the location of the 0 in *c*)

`c←c+d` adds to *d* to *c* in order to turn the 0 that used to be *a* into ¯1001, which is one above the maximum number, 1000

`c←c[⍒c]` orders our data in *c* from greatest to least. This pushes our ¯1001 all the way to the right

`c←c+a` restores our original data from *b* by reversing the `c←c=a` we did earlier

`e←¯1+⍴c` creates a variable, *e*, that is equal to the length of *c* \- 1

`c←e⍴c` decreases the length of *c* by 1 and does so by creating a shape with a length equal to *e*, that contains the data from *c*, but does not have what used to be *a* because the length decreased and *a* was on the right end

`a` displays *a*

`b[⍒b]` displays *b* from greatest to least

`c` displays *c*
> 1 votes

# Answer
# **366 Characters** \- Python 2

```
i=lambda v,c,m,j:[h(s(v,m)+[j],x) for x in range(c+1)]
h=lambda v,c:hash(','.join(map(str,sorted(v)+[c])))%1001
a=lambda v,c=0:v+[h(v,c)] if t(h(v,c),v,c) else a(v,c+1)
s=lambda v,m:[n for n in v if n!=m ]
w=lambda v,c=0:s(v,o(v,c)[0]) if len(o(v,c))==1 else w(v,c+1)
o=lambda v,c:[m for m in v if h(s(v,m),c)==m]
t=lambda j,v,c:all([m not in i(v,c,m,j) for m in v])

```

Could probably be golfed more, I didn't spend too much time on it. Call `a` with a list of integers to add a number, and call `w` with a shuffled version of the new list to remove that number.

Works by appending a loop counter to the sequence, and choosing as the additional number the hash modulo 1001 the concatenated sequence. If the hash generated results in a sequence where there is only *one* number that can be removed to generate itself for every possible value of the loop counter up to the current one, then output the sequence. Otherwise increment the loop counter and try again. To decode, remove each item from the sequence and see if the hash value of the remaining sequence+loop counter is the removed value. If only one value matches these criteria, it is the solution, otherwise increment the loop counter and try again. This version will hang if faced with an unencodable sequence due to the entire space being taken up by hash collisions, but a check can trivially be added to the `a` function to simply output that the sequence is unencodable.

Confirmed to work for at least all sets of 2 or less, and works with decreasing probability for larger sets. Higher probabilities might be reachable with a better hash function but that would require more characters. I did some quick random sampling to see what the probability of being able to encode an input sequence of a given size was via this method (you'll notice the precision going down as I got less and less patient):

```
Size  Probability
  5     100.00%
 10     100.00%
 50     100.00%
100     100.00%
200     98.3%
400     73%
800     8%

```

Anyone who wants to play with it can use the following version which will output whether a sequence is or is not encodable:

```
i=lambda v,c,m,j:[h(s(v,m)+[j],x) for x in range(c+1)]
h=lambda v,c:hash(','.join(map(str,sorted(v)+[c])))%1001
a=lambda v,c=0:v+[h(v,c)] if t(h(v,c),v,c) else a(v,c+1) if len(set([n for m in v for n in i(v,c,m,h(v,c))]))<999 else None
s=lambda v,m:[n for n in v if n!=m ]
w=lambda v,c=0:s(v,o(v,c)[0]) if len(o(v,c))==1 else w(v,c+1)
o=lambda v,c:[m for m in v if h(s(v,m),c)==m]
t=lambda j,v,c:all([m not in i(v,c,m,j) for m in v])

if __name__ == "__main__":
    from random import shuffle,randrange,sample
    from operator import eq
    from itertools import combinations
    def random_combination(iterable, r):
        "Random selection from itertools.combinations(iterable, r)"
        pool = tuple(iterable)
        n = len(pool)
        indices = sorted(sample(xrange(n), r))
        return tuple(pool[i] for i in indices)
    valid=invalid=0
    for z in range(100): #change to test more cases
        r=list(sorted(random_combination(range(1001),randrange(1,100)))) #change to test longer sequences
        d=a(r)
        if d is None:
            invalid+=1
            continue
        shuffle(d)
        e=sorted(w(d))
        if not all(map(eq,r,e)):
            raise Exception("Incorrect",r)
        valid+=1
    print "%d Valid, %d Invalid"%(valid,invalid)

```
> 1 votes

---
Tags: code-challenge, open-ended-function
---


# Question
Title: Convert radicals to mixed & entire radicals and to real numbers
## Challenge

The goal of this challenge is to take a radical and convert it to a reduced and entire radical, and a real number. You do not have to convert it to all 3, however, you will get bonus points for converting it to 2 or 3 of them. You will also get bonus points if your code works not just with square roots. How the input works is your choice. You don't have to parse the input so you could just have it as a function. If your unable to output the root symbol (√) then you could output it as `sqrt(x)` or `cuberoot(x)`. You could also use a superscript (²√) for the index of the radical.

## Rules

* If you just output one of the 3 options, then you can't just output it without converting it (ie: if the input is `√125` then you can't just output `√125` back).
* The entire radical must have no co-efficient.
* The mixed radical must have a coefficient (if there is no coefficient, then it should be `1`).
* The real number (or result of the radical) should have as many decimals as possible.

## Example

Here's an example output for the square root of 125 (√125):

```
Entire radical: √125
Mixed radical: 5√5
Real number: 11.18033988749895

```

## Scoring

* 10% off your score for outputting 2 of either an entire radical, mixed radical, or real number.
* 30% off your score for outputting all 3 (entire radical, mixed radical, and real number).
* 30% off your score for working with a radical with any index

## Winner

The person with the shortest code length wins. Good luck!

# Answer
> 2 votes
# APL, 77 × .7² = 37.7

```
{(a b)←×⌿(∪p)*[1]c,⍪e-⍺×c←⌊⍺÷⍨e←∪⍦p←π⍵⋄q←⍺/⍨⍺≠2⋄∊¨⍕¨¨⍪(q'√'⍵)(a'×'q'√'b),⍺√⍵}

```

Nars2000. Could be golfed some more, for instance by printing worse output, but I'm being lazy.
Also, pretty output is pretty.

**Ungolfed**

```
{
  p←π⍵                       ⍝ prime factors of the radical argument ⍵
  u←∪p                       ⍝ unique prime factors
  e←∪⍦u                      ⍝ exponents of those factors (so that ⍵=u*e)
  r←⌊e÷⍺                     ⍝ u's exponents for the reduced radical factor
  f←×/u*r                    ⍝ reduced radical factor
  a←×/u*e-⍺×r                ⍝ reduced radical argument
  i←⍺/⍨⍺≠2                   ⍝ index, unless it's 2 (AH THE DECADENCE, I CAN WASTE SO MUCH)
  o←(i'√'⍵)(f'×'i'√'a),⍺√⍵   ⍝ the three expressions to output
  ∊¨⍕¨¨⍪o                    ⍝ return them as a table without spaces
}

```

**Examples**

```
     2 f 125
√125
5×√5
11.18033989
     2 f 1440
√1440
12×√10
37.94733192
     3 f 1440
3√1440
2×3√180
11.29243235
     2 f 987654321
√987654321
51×√379721
31426.96805

```

# Answer
> 2 votes
## C (314)

```
n,d;main(i){scanf("%d %d",&n,&d);int val[d];for(;pow(i,n)<=d;i++)val[i]=pow(i,n);printf("Entire radical: %drt(%d)\n",n,d);for(i--;i>0;i--)if(d%val[i]==0){printf("Mixed radical: %d*%drt(%d)\n",i,n,d/val[i]);break;}double v,x=1.5,a=d;do{v=(a/pow(x,n-1)-x)/n;x+=v;}while(abs(v)>=1E-9);printf("Real number: %lf\n",x);}

```

Here it is with whitespace.

```
n,d;
main(i){
    scanf("%d %d",&n,&d);
    int val[d];

    for(;pow(i,n)<=d;i++)
        val[i]=pow(i,n);

    printf("Entire Radical: %d*rt(%d)\n",n,d);

    for (i--;i>0;i--)
        if (d%val[i]==0){
            printf("Mixed Radical: %d*%drt(%d)\n", i, n, d/val[i]);
            break;}

    double v,x=1.5,a=d;
    do{
        v=(a/pow(x,n-1)-x)/n;
        x+=v;
    }while(abs(v)>=1E-9);

    printf("Real number: %lf\n", x);
}

```

Input:

```
2 125

```

Output:

```
Entire radical: 2rt(125)
Mixed radical: 5*2rt(5)
Real number: 11.180340

```

Input:

```
3 125

```

Output:

```
Entire radical: 3rt(125)
Mixed radical: 5*3rt(1)
Real number: 5.000000

```

This isn't perfect, the root calculation will not work for all input values, and the chosen guess value is not random. It takes the whole value of the radical as input (see above).

# Answer
> 1 votes
# C - 222 × 70% × 70% ≆ 108.78

```
p,c=1,i,n=2,t;main(){scanf("%d %d",&i,&p);printf("Entire radical: rt%d(%d)\nReal number: %.16
lf\n",i,p,pow(p,1.0l/i));for(;n++<p;t=0){for(;!(p%n);t++)p/=n;c*=pow(n,t/i);p*=pow(n,t%i);}pr
intf("Mixed root: %drt%d(%d)",c,i,p);}

```

Has some problems with rounding, but is otherwise fine.

# Answer
> 0 votes
# Ruby, 199 chars * 70% * 70% = 97.51

I'm not good at mathstuffs. :P

```
a,b=gets.split.map &:to_i
c=b
[*2..o=b].map{|x|x**a}.map{|x|o=c/=x if c%x==0}until o==b
puts"Entire radical: #{a}rt#{b}
Mixed radical: #{((b/c)**(1.0/a)).round}*#{a}rt#{c}
Real number: #{b**(1.0/a)}"

```

I particularly like line 3. It's supposed to keep dividing out squares until it can't divide anymore. How I did it is that `o` is set to `b` in the beginning (conveniently tucking it into the range expression), and if a square can be divided out, `o` is set to the result (also conveniently only adding 2 more characters). Then, I used `until o==b`, so that it keeps going until `o` didn't change (meaning no squares could be divided out).

More explanations coming soon....

---

Sample runs:

```
c:\a\ruby>radicalstuffs
2 100
Entire radical: 2rt100
Mixed radical: 10.0*2rt1
Real number: 10.0

c:\a\ruby>radicalstuffs
2 125
Entire radical: 2rt125
Mixed radical: 5*2rt5
Real number: 11.180339887498949

c:\a\ruby>radicalstuffs
2 100
Entire radical: 2rt100
Mixed radical: 10*2rt1
Real number: 10.0

c:\a\ruby>radicalstuffs
5 32
Entire radical: 5rt32
Mixed radical: 2*5rt1
Real number: 2.0

c:\a\ruby>radicalstuffs
3 27
Entire radical: 3rt27
Mixed radical: 3*3rt1
Real number: 3.0

c:\a\ruby>radicalstuffs
2 99
Entire radical: 2rt99
Mixed radical: 3*2rt11
Real number: 9.9498743710662

c:\a\ruby>radicalstuffs
2 98
Entire radical: 2rt98
Mixed radical: 7*2rt2
Real number: 9.899494936611665

```

# Answer
> 0 votes
# Julia, 19\*0.9 = 17.1

```
julia> f(n)="$(sqrt(n)) √$n"

julia> f(125)
"11.180339887498949 √125"

```

I feel like I must not have understood the challenge. As far as I could tell there is only a small bonus for bothering to reduce the radical.

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


title: Write a hash function for Morse Code

text:
# Question
Title: Write a hash function for Morse Code
Your goal is to write a hash function, that accepts morse code character and returns a hash code that you get to define.

### You can be sure, passed string will be:

* One of the Latin characters (A-Z) encoded into Morse Code using `.` and `-`, or
* One of the digits (0-9) encoded into Morse Code using `.` and `-`, or
* Empty

So, there could be any of 37 different strings passed to you.

### Requirements:

* The returned number should be unique for all 37 strings
* For empty string the function should return 0

### Score:

1. Initially, you have a 100 points.
2. You will lose
    * 1 point for every bitwise operator in your code
    * 2 points for every addition (subtraction) operator in your code (operators in loop clauses (e.g. inside `for(;;)` or `while()` don't count)
    * 4 points for every multiplication (division, modulo, etc) operator
    * 6 points for every if (else) statement
    * 8 points for every loop statement (including loops in the called functions. You can presume that any called function has no more than one loop)
    * 12 points for every conditional operator
    * 200 points for using a built-in hash function

### Bonuses:

* If all numbers, produced by your function are less than `N`, you will get additional `137 - N` points (of course, if the bonus is positive)

### Winners:

Score matters, but be creative!

---

### Example:

## Score: 100 - 5\*2 - 3\*4 - 8 + (137 - 134) = 73

I know, this could be improved by removing modulo operator and make a loop starts from 1, but this is just an example

```
#include <iostream>
#include <map>
#include <set>

std::size_t hash_morse(const std::string& s)
{
    std::size_t ans = 0;

    for(std::size_t i = 0; i < s.size(); ++i)
    {
        ans += (s.at(i) - '-' + 2) * (i + 1) * (i + 1);
    }

    return ans % 134;
}

int main()
{
    std::map<std::string, char> m
    {
        {"",     0},
        {".-",   'A'},
        {"-...", 'B'},
        {"-.-.", 'C'},
        {"-..",  'D'},
        {".",    'E'},
        {"..-.", 'F'},
        {"--.",  'G'},
        {"....", 'H'},
        {"..",   'I'},
        {".---", 'J'},
        {"-.-",  'K'},
        {".-..", 'L'},
        {"--",   'M'},
        {"-.",   'N'},
        {"---",  'O'},
        {".--.", 'P'},
        {"--.-", 'Q'},
        {".-.",  'R'},
        {"...",  'S'},
        {"-",    'T'},
        {"..-",  'U'},
        {"...-", 'V'},
        {".--",  'W'},
        {"-..-", 'X'},
        {"-.--", 'Y'},
        {"--..", 'Z'},

        {".----",    '1'},
        {"..---",    '2'},
        {"...--",    '3'},
        {"....-",    '4'},
        {".....",    '5'},
        {"-....",    '6'},
        {"--...",    '7'},
        {"---..",    '8'},
        {"----.",    '9'},
        {"-----",    '0'}
    };

    std::map<std::size_t, std::string> hashes;

    for(const auto& elem: m)
    {
        auto hash = hash_morse(elem.first);

        if(hashes.find(hash) != hashes.end())
        {
            std::cout << "Collision" << std::endl;
            std::cout << '"' << hashes[hash] << R"(" and ")" << elem.first << '"' << std::endl;
            std::cout << "Hash: " << hash << std::endl;
            std::cout << std::endl;
        }
        else
        {
            hashes[hash] = elem.first;
        }
    }

    std::cout << "Total amount of collisions: " << (m.size() - hashes.size()) << std::endl;

    return 0;
}

```

# Answer
> 9 votes
## Arguably perfect score

There are some possible loopholes in the scoring system. In particular,

> 8 points for every loop statement (including loops in the called functions. You can presume that any called function has no more than one loop)

According to PHP documentation,

> **array()** is a language construct used to represent literal arrays, and not a regular function.

So it's arguable that

```
$hash = array(
    '' => 0,
    '.-' => -1,
    ...
);
return $hash[$morse];

```

contains no called functions and should score a perfect 100 + (137 - 1) = 236 points.

# Answer
> 7 votes
# bash — 236 points

I understand there's some griping over using negative numbers, so have revised:

```
echo '' '[morse code]'|grep -o ' [\.-]*'|tr -t '.-' '19'|sed 's/ /0./g'|awk '{printf("%g\n",$0)}'

```

Will generate codes from 0.1 to 0.99999 for valid Morse Code and 0 for empty input.

e.g.

```
$ echo '' '. - .. -- .-.- -.-. ..... -----'|grep -o ' [\.-]*'|tr -t '.-' '19'|sed 's/ /0./g'|awk '{printf("%g\n",$0)}'
0.1
0.9
0.11
0.99
0.1919
0.9191
0.11111
0.99999

```

As per specs, empty input `''` returns 0:

```
$ echo '' ''|grep -o ' [\.-]*'|tr -t '.-' '19'|sed 's/ /0./g'|awk '{printf("%g\n",$0)}'
0

```

**Points Calculation**

Starting with 100, deduct:

* 1 point for every bitwise operator - none
* 2 points for every addition (subtraction) operator - none
* 4 points for every multiplication (division, modulo, etc) operator - none
* 6 points for every if (else) statement - none
* 8 points for every loop statement - none
* 12 points for every conditional operator - none
* 200 points for using a built-in hash function - none

So still have 100 points.

**Bonus Calculation**

All numbers are less than 1 (largest is 0.99999 for ----- a.k.a. Morse Code Zero), so the bonus is 137 - 1 or 136 points, again for a total of 236 points.

---

# bash — 236 points

```
echo '' '[morse code]'|grep -o ' [\.-]*'|tr -t '.-' '67'|sed 's/ /-0/g'|awk '{printf("%d\n",$0)}'

```

Will generate codes from -77777 to -6 for valid Morse Code and 0 for empty input.

e.g.

```
$ echo '' '. - ..--. -..- .--- .. -..-. .. -----'|grep -o ' [\.-]*'|tr -t '.-' '67'|sed 's/ /-0/g'|awk '{printf("%d\n",$0)}'
-6
-7
-66776
-7667
-6777
-66
-76676
-66
-77777

```

As per specs, empty input `''` returns 0:

```
$ echo '' ''|grep -o ' [\.-]*'|tr -t '.-' '67'|sed 's/ /-0/g'|awk '{printf("%d\n",$0)}'
0

```

**Points Calculation**

Starting with 100, deduct:

* 1 point for every bitwise operator - none
* 2 points for every addition (subtraction) operator - none
* 4 points for every multiplication (division, modulo, etc) operator - none
* 6 points for every if (else) statement - none
* 8 points for every loop statement - none
* 12 points for every conditional operator - none
* 200 points for using a built-in hash function - none

So still have 100 points.

**Bonus Calculation**

All numbers are less than 1 (largest is 0 for an empty input), so the bonus is 137 - 1 or 136 points for a total of 236 points.

# Answer
> 6 votes
# Ruby 100 - 6 (one if/else) - 2 (one subtraction) = 92 + 75 (largest value is 62) = 167 (159 if string find/replace counts as looping)

```
code = gets.chomp
if code.empty?
  p -1
else
  p ('1' + code.gsub(/./){|c| c.ord - 45 }).to_i(2)
end

```

Simply does a find/replace on the string, but replaces each character with its ASCII code - 45. This turns `-` into `0` and `.` into `1`. It then prepends a `1` (to handle leading zeroes) and parses this string as binary.

# Answer
> 5 votes
## GolfScript (143 164 192 points)

I was slightly wrong about the relationship with the other Morse question: this one is much much simpler.

```
2base

```

scores 100 - 8 points for an implicit loop = 92, with no bonus.

```
2base 87%

```

scores 100 - 4 points for a modulo - 8 points for an implicit loop + (137 - 82) bonus points for a total of 143 points.

That has two parameters which can potentially be optimised to improve the bonus. The best I've found so far is

```
46base 62%

```

for `N=61` and a total of 164 points.

But it's possible to do even better.

```
2base MAGIC_STRING=

```

scores 100 - 8 points for an implicit loop + (137 - 37) bonus points for a total of 192 points, where MAGIC\_STRING is a suitable 1427-character string literal:

```
"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x1E\x0F\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x17\x18\v\x13\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x19\x11\x15\x0E!\x1C\x1F\x1D\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\e$#\r\"\f\x14\x1A\x00\x16\x00\x10 \x12\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\n\x00\t\x00\x00\x00\b\x00\x00\x00\x00\x00\x00\x00\a\x02\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x04\x00\x05\x06"

```

# Answer
> 2 votes
## Perl - score = 165

```
print~-oct'0b1'.<>=~y/.-/10/r

```

Re-interpretting morse as binary, with a `1` prepended.

**Score break-down**

* **-1** \- bitwise inversion (`~`)
* **-8** \- loop statement (`y`)
* **+74** \- the largest value produced is *62*

# Answer
> 2 votes
# Scheme:

Initial 100 points and it has no reduction since there was no mention of `switch/case` there and the `/` is part of the number not an operator..

The output is a rational number between 0 and 1. Extra score would be 137-1=136.

Total score: 236

```
(define (hash-morse-code code)
  (case code
    (("") 0)
    ((".-") 1)
    (("-...") 1/2)
    (("-.-.") 1/3)
    (("-..") 1/4)
    ((".") 1/5)
    (("..-.") 1/6)
    (("--.") 1/7)
    (("....") 1/8)
    (("..") 1/9)
    ((".---") 1/10)
    (("-.-") 1/11)
    ((".-..") 1/12)
    (("--") 1/13)
    (("-.") 1/14)
    (("---") 1/15)
    ((".--.") 1/16)
    (("--.-") 1/17)
    ((".-.") 1/18)
    (("...") 1/19)
    (("-") 1/20)
    (("..-") 1/21)
    (("...-") 1/22)
    ((".--") 1/23)
    (("-..-") 1/24)
    (("-.--") 1/25)
    (("--..") 1/26)
    ((".----") 1/27)
    (("..---") 1/28)
    (("...--") 1/29)
    (("....-") 1/30)
    ((".....") 1/31)
    (("-....") 1/31)
    (("--...") 1/32)
    (("---..") 1/33)
    (("----.") 1/34)
    (("-----") 1/35)))

(hash-morse-code "...") => 1/19

```

# Answer
> 0 votes
# Java - 100 + 136 = 236

```
public static int hashMorse(String toHash) {
    switch (toHash){
        case ".-": //A
            return -36;
        case "-...": //B
            return -35;
        case "-.-.": //C
            return -34;
        case "-..": //D
            return -33;
        case ".": //E
            return -32;
        case "..-.": //F
            return -31;
        case "--.": //G
            return -30;
        case "....": //H
            return -29;
        case "..": //I
            return -28;
        case ".---": //J
            return -27;
        case "-.-": //K
            return -26;
        case ".-..": //L
            return -25;
        case "--": //M
            return -24;
        case "-.": //N
            return -23;
        case "---": //O
            return -22;
        case ".--.": //P
            return -21;
        case "--.-": //Q
            return -20;
        case ".-.": //R
            return -19;
        case "...": //S
            return -18;
        case "-": //T
            return -17;
        case "..-": //U
            return -16;
        case "...-": //V
            return -15;
        case ".--": //W
            return -14;
        case "-..-": //X
            return -13;
        case "-.--": //Y
            return -12;
        case "--..": //Z
            return -11;
        case ".----": //1
            return -10;
        case "..---": //2
            return -9;
        case "...--": //3
            return -8;
        case "....-": //4
            return -7;
        case ".....": //5
            return -6;
        case "-....": //6
            return -5;
        case "--...": //7
            return -4;
        case "---..": //8
            return -3;
        case "----.": //9
            return -2;
        case "-----": //0
            return -1;
        default:
            return 0;
    }
}

```

All those `-` signs don't count; they stand for the literal number. If you want to count them, then I'll just replace all those numbers with the binary literal (no minuses then).

Switches are free according to the question; neither an if nor an else. If you don't want switches, I'll just replace it with a `HashMap`

The largest possible number is `0`, for the empty string or invalid strings.

---

Don't like negative numbers? This works (score of 200):

```
public static int hashMorse(String toHash) {
    switch (toHash){
        case ".-": //A
            return 36;
        case "-...": //B
            return 35;
        case "-.-.": //C
            return 34;
        case "-..": //D
            return 33;
        case ".": //E
            return 32;
        case "..-.": //F
            return 31;
        case "--.": //G
            return 30;
        case "....": //H
            return 29;
        case "..": //I
            return 28;
        case ".---": //J
            return 27;
        case "-.-": //K
            return 26;
        case ".-..": //L
            return 25;
        case "--": //M
            return 24;
        case "-.": //N
            return 23;
        case "---": //O
            return 22;
        case ".--.": //P
            return 21;
        case "--.-": //Q
            return 20;
        case ".-.": //R
            return 19;
        case "...": //S
            return 18;
        case "-": //T
            return 17;
        case "..-": //U
            return 16;
        case "...-": //V
            return 15;
        case ".--": //W
            return 14;
        case "-..-": //X
            return 13;
        case "-.--": //Y
            return 12;
        case "--..": //Z
            return 11;
        case ".----": //1
            return 10;
        case "..---": //2
            return 9;
        case "...--": //3
            return 8;
        case "....-": //4
            return 7;
        case ".....": //5
            return 6;
        case "-....": //6
            return 5;
        case "--...": //7
            return 4;
        case "---..": //8
            return 3;
        case "----.": //9
            return 2;
        case "-----": //0
            return 1;
        default:
            return 0;
    }
}

```

# Answer
> 0 votes
# Java - 100 + 136 = 236

```
public static int hash(String morse){
    try{
        morse.charAt(0);
    }catch (IndexOutOfBoundsException e){
        return 0;
    }
    return Integer.parseInt("-1" + help(morse), 2);
}
private static String help(String morse) {
    int a = 0;
    try {
        a = (int) morse.charAt(0);
    } catch (IndexOutOfBoundsException e) {
        return "";
    }
    a = Integer.parseInt(String.valueOf(Integer.toString(a, 2).charAt(4)));
    return a + help(morse.substring(1));
}

```

call `hash(someString);` to use this function. I'm working on a loop-free alternative to `Integer.parseInt` and `Integer.toString`.

I avoided the penalties by:

* using recursion instead of loops
* using Strings and String concatenation instead of numbers

So I get 100 + 136 as the largest output is 0.

# Answer
> 0 votes
# JavaScript, 217pts

```
replace : Minus 8pts (loop)
replace : Minus 8pts (loop)
/ 100000: Minus 4pts (division)

```

100 - 20 = 80 + (137 - 0) = 217

```
function mc2(s) {
    return s.replace(/\./g,'1').replace(/-/g,'2') / 100000
}

```

# JavaScript 199pts

```
for     : Minus  8pts (loop)
r+=     : Minus  2pts (addition)
(c>'-') : Minus  6pts (if)
c>'-'   : Minus 12pts (conditional operator)
:2      : Minus  6pts (else)
r/      : Minus  4pts (division)

```

100-38pts = 62pts + (137-0) = 199pts

```
function mc2(s) {
    r=''
    for(i=0;(c=s[i]);i++)r+=(c>'-')?1:2
    return r/100000
}

```

# Answer
> -1 votes
## Python, 236

Now, Peter Taylor claims to have a perfect score. But really, he's only got 200. Negative numbers all being smaller than zero, my bonus is `137-1`, so this solution is 36 points better.

```
F = lambda s:-eval(''.join([
'12340'[s[0:].find('-')],'12340'[s[0:].find('.')],
'12340'[s[1:].find('-')],'12340'[s[1:].find('.')],
'12340'[s[2:].find('-')],'12340'[s[2:].find('.')],
'12340'[s[3:].find('-')],'12340'[s[3:].find('.')],
'12340'[s[4:].find('-')],'12340'[s[4:].find('.')]]))

```

---
Tags: atomic-code-golf, hashing, morse
---


title: Hide one message inside another

text:
# Question
Title: Hide one message inside another
Your task is to hide a small message or string inside a larger block of text. To do so, you must hide the message as capital letters inside the larger

For the quoted test:

> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut convallis porta varius. Donec lo**B**ortis adipiscing dolor ac **E**uismod. Ut **M**incidunt e**Y** cursus nunc pul**V**inar, eu m**A**ttis nibh tincidunt. Phase**L**lus s**E**d molestie sapie**N**. In**T**eger congue maur**I**s in **N**isi faucibus, at aliquam ligula cons**E**ctetur. Quisque laoreet turpis at est cursus, in consequat.

(Emboldened text only to highlight where the letters are)

The secret text reads:

**BE MY VALENTINE**

You choose how to spread the words out, and should error if you try to hide a string inside another that won't fit either from length or lack of required characters.

Assume the input is plain text, where the first letter of each sentence may be capitalised or not (those can be lower cased or ignored, but should not be part of the secret message, for clarity).

You'll get -10 points for writing a second program that recovers the hidden message from a block of text. In this eventuality your score is the average of the two, minus the 10 bonus points.

E.g. If the Message hiding code is 73 characters, and the recovery one is 80, your score is:

```
(73+80)/2-10=66.5

```

# Answer
## Ruby, (69+35)/2-10 = 42

```
a=gets
$><<gets.gsub(/./){a[0]!=$&?$&:a.slice!(0).upcase}
1/0if a>?\n

```

Takes input on STDIN, first line is the message to hide, second line is the text block. Assumes the secret message is lower-case. Example input:

```
codegolf
You'll get -10 points for writing a second program that recovers the hidden message from a block of text. In this eventuality your score is the average of the two, minus the 10 bonus points.

```

Example output:

```
You'll get -10 points for writing a seCOnD program that rEcovers the hidden messaGe frOm a bLock oF text. In this eventuality your score is the average of the two, minus the 10 bonus points.

```

Here's the program to obtain the secret back from the output (again, provided on STDIN):

```
$><<gets.scan(/(?<!^|\. )[A-Z]/)*''

```

One caveat here is that Ruby's lookbehind expressions have to be fixed width, so this code only works for text where the periods are followed by exactly one space. Suggestions welcome!
> 3 votes

# Answer
## Python 3, (136 + 74) / 2 - 10 = 95

Encoder (message must be lowercase):

```
t,m=input(),list(input().replace(' ', ''))
print([''.join(map(lambda c:m.pop(0).upper()if c.islower()and c in m[:1]else c,t))][bool(m)])

```

Decoder:

```
import re
print(filter(str.isupper, re.sub(r'(^|\. )[A-Z]', '', input())))

```
> 2 votes

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


# Question
Title: Convert from binary to unary in 7x7 Manufactoria
In the game manufactoria, take in a binary number and output that number of red pieces. The catch? The board-size is only 7x7:

Here's the manufactoria code for the problem:

http://pleasingfungus.com/Manufactoria/?ctm=Razors;Treat\_the\_input\_as\_a\_binary\_number\_and\_output\_that\_number\_of\_reds;b:r|brr:rrrr|brb:rrrrr|brbb:rrrrrrrrrrr|:|brrrr:rrrrrrrrrrrrrrrr|brbr:rrrrrrrrrr;7;3;0;

I have a solution, so it most definitely exists.

EDIT: Least "total parts" wins (as reported by manufactoria engine)

# Answer
# ~~21~~ ~~20~~ 19 parts! Ha!

http://pleasingfungus.com/Manufactoria/?lvl=32&code=q12:9f0;c12:8f3;g9:8f1;q9:9f4;b10:8f3;p10:9f0;r10:10f1;y11:9f0;g12:5f3;c12:6f3;r9:6f3;c9:7f2;r10:6f0;p10:7f2;q11:7f1;i12:7f7;p13:7f6;r13:6f0;c13:8f0;&ctm=Razors;Treat\_the\_input\_as\_a\_binary\_number\_and\_output\_that\_number\_of\_reds;b:r|brr:rrrr|brb:rrrrr|brbb:rrrrrrrrrrr|:|brrrr:rrrrrrrrrrrrrrrr|brbr:rrrrrrrrrr;7;3;0;

**Edit 2:** Back to the original design, but with two parts shaved off by creative reuse of conveyors. The 7 × 7 board really does start to feel confining — I've come up with several ways to shrink this further, if I only had one more row of vertical space...
> 5 votes

# Answer
# 30 26 24 22 Parts

Here is my entry, with 22 parts and a time of 4:16. This can be rearranged slightly to fit into a 5 wide by 7 tall space.

It works by dividing the tape into three sections: the instructions (blue and red), the data (green), and a data terminator symbol (yellow). Each cycle of operation, it reads and replaces the first instruction. It then cycles the rest on the instructions to the back of the tape until it reaches the data. For each data symbol read, it adds two of them to the back of the tape. Once the data terminator is read, the instructions are once again at the front of the tape. It deletes the first instruction (which was just executed). It then adds one more data symbol to the end of the tape if the current instruction (read earlier) is blue. The yellow symbol is then re-appended. Once there are no more instructions, then all of the green symbols are converted to red and are output.

```
Example: input is BBR (110 or 6)
These are the important steps in execution, in more detail than before
BBR
BBRY     #yellow is appended
YBBR     #the instructions are cycled through, execution is on the left half
YBBR     #all of the greens (none yet) are duplicated
BRG      #Y and B are removed and a G appended
BRGY     #yellow is appended
GYBR     #instructions are cycled, execution is on left half
YBRGG    #Gs are duplicated
RGGG     #Y,B removed; G added
RGGGY    #Y added
GGGYR    #instructions are cycled, execution is on RIGHT half
YRGGGGGG #Gs duplicated
GGGGGG   #YR removed, G NOT added
GGGGGGY  #Y added
YRRRRRR  #Greens are changed to red
RRRRRR   #output

```
> 4 votes

# Answer
I managed 27 parts, but it would fit on a 5x7 grid:

I'm using the double-and-add method. Start by putting a green to mark the start of the number and then a green or a yellow to determine whether the next digit pulled off is a zero or a one. Skip past the rest of the number and then double the number of reds currently in place. Finally add one more if the next piece is yellow. Repeat until the number goes to zero.
> 1 votes

# Answer
## 17 13 parts

I took some liberty with the specification. I'm going to define the input binary number to appear in little-endian order. You never say explicitly whether the input is little or big endian, but it appears you assume big endian because your tests assume that. I'm going to use these little-endian tests instead.

http://pleasingfungus.com/Manufactoria/?ctm=RazorsLE;Treat\_the\_input\_as\_a\_little\_endian\_binary\_number\_and\_output\_that\_num\_of\_red;b:r|rrb:rrrr|brb:rrrrr|bbrb:rrrrrrrrrrr|:|rrrrb:rrrrrrrrrrrrrrrr|rbrb:rrrrrrrrrr;7;3;0;

The code works by decrementing the binary number by 1 each loop and adding one yellow mark. At the end, it replaces the yellow with red and deletes the binary number (all blue at this point, representing -1).
> 0 votes

---
Tags: code-golf, binary, counting, manufactoria
---