# Question
Title: Convert English to a number without built-ins or libraries
This challenge is similar to this other, however I made a restriction (see bold text below) that I think would made it much diffent and (I hope) fun either.

# The Challenge

Write a program or a function in any programming language that takes as input the English name of a positive integer `n` not exceeding `100` and returns `n` as an integer.

Standard loopholes are forbidden and ***you cannot use any built-in function, external tool, or library that already does this job***.

Shortest source code in bytes wins.

# Test

Here all the `input->output` cases:

```
one              -> 1
two              -> 2
three            -> 3
four             -> 4
five             -> 5
six              -> 6
seven            -> 7
eight            -> 8
nine             -> 9
ten              -> 10
eleven           -> 11
twelve           -> 12
thirteen         -> 13
fourteen         -> 14
fifteen          -> 15
sixteen          -> 16
seventeen        -> 17
eighteen         -> 18
nineteen         -> 19
twenty           -> 20
twenty-one       -> 21
twenty-two       -> 22
twenty-three     -> 23
twenty-four      -> 24
twenty-five      -> 25
twenty-six       -> 26
twenty-seven     -> 27
twenty-eight     -> 28
twenty-nine      -> 29
thirty           -> 30
thirty-one       -> 31
thirty-two       -> 32
thirty-three     -> 33
thirty-four      -> 34
thirty-five      -> 35
thirty-six       -> 36
thirty-seven     -> 37
thirty-eight     -> 38
thirty-nine      -> 39
forty            -> 40
forty-one        -> 41
forty-two        -> 42
forty-three      -> 43
forty-four       -> 44
forty-five       -> 45
forty-six        -> 46
forty-seven      -> 47
forty-eight      -> 48
forty-nine       -> 49
fifty            -> 50
fifty-one        -> 51
fifty-two        -> 52
fifty-three      -> 53
fifty-four       -> 54
fifty-five       -> 55
fifty-six        -> 56
fifty-seven      -> 57
fifty-eight      -> 58
fifty-nine       -> 59
sixty            -> 60
sixty-one        -> 61
sixty-two        -> 62
sixty-three      -> 63
sixty-four       -> 64
sixty-five       -> 65
sixty-six        -> 66
sixty-seven      -> 67
sixty-eight      -> 68
sixty-nine       -> 69
seventy          -> 70
seventy-one      -> 71
seventy-two      -> 72
seventy-three    -> 73
seventy-four     -> 74
seventy-five     -> 75
seventy-six      -> 76
seventy-seven    -> 77
seventy-eight    -> 78
seventy-nine     -> 79
eighty           -> 80
eighty-one       -> 81
eighty-two       -> 82
eighty-three     -> 83
eighty-four      -> 84
eighty-five      -> 85
eighty-six       -> 86
eighty-seven     -> 87
eighty-eight     -> 88
eighty-nine      -> 89
ninety           -> 90
ninety-one       -> 91
ninety-two       -> 92
ninety-three     -> 93
ninety-four      -> 94
ninety-five      -> 95
ninety-six       -> 96
ninety-seven     -> 97
ninety-eight     -> 98
ninety-nine      -> 99
one hundred      -> 100

```

# Answer
# C, 160 bytes

```
g(char*s){char i=1,r=0,*p="k^[#>Pcx.yI<7CZpVgmH:o]sYK$2";for(;*s^'-'&&*s;r+=*s++|9);r=r%45+77;for(;*p!=r;p++,i++);return((*s^'-')?0:g(s+1))+(i<21?i:10*(i-18));}

```

# Test it

```
int main ()
{
    char* w[] = {"", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen", "twenty", "twenty-one", "twenty-two", "twenty-three", "twenty-four", "twenty-five", "twenty-six", "twenty-seven", "twenty-eight", "twenty-nine", "thirty", "thirty-one", "thirty-two", "thirty-three", "thirty-four", "thirty-five", "thirty-six", "thirty-seven", "thirty-eight", "thirty-nine", "forty", "forty-one", "forty-two", "forty-three", "forty-four", "forty-five", "forty-six", "forty-seven", "forty-eight", "forty-nine", "fifty", "fifty-one", "fifty-two", "fifty-three", "fifty-four", "fifty-five", "fifty-six", "fifty-seven", "fifty-eight", "fifty-nine", "sixty", "sixty-one", "sixty-two", "sixty-three", "sixty-four", "sixty-five", "sixty-six", "sixty-seven", "sixty-eight", "sixty-nine", "seventy", "seventy-one", "seventy-two", "seventy-three", "seventy-four", "seventy-five", "seventy-six", "seventy-seven", "seventy-eight", "seventy-nine", "eighty", "eighty-one", "eighty-two", "eighty-three", "eighty-four", "eighty-five", "eighty-six", "eighty-seven", "eighty-eight", "eighty-nine", "ninety", "ninety-one", "ninety-two", "ninety-three", "ninety-four", "ninety-five", "ninety-six", "ninety-seven", "ninety-eight", "ninety-nine", "one hundred"};

    int n;
    for (n = 1; n <= 100; n++)
    {
        printf ("%s -> %d\n", w[n], g(w[n]));
        if (n != g(w[n]))
        {
            printf ("Error at n = %d", n);
            return 1;
        }
    }
    return 0;
}

```

# How it works

After some attempts, I found a function that maps the "exceptional" numbers `one`, `two`, `three`, `four`, `five`, `six`, `seven`, `eight`, `nine`, `ten`, `eleven`, `twelve`, `thirteen`, `fourteen`, `fifteen`, `sixteen`, `seventeen`, `eighteen`, `nineteen`, `twenty`, `thirty`, `forty`, `fifty`, `sixty`, `seventy`, `eighty`, `ninety`, `one hundred`, to the printable ASCII characters `k`, `.`, `[`, `<`, `*`, , `c`, `K`, `w`, `y`, `e`, `(`, `S`, `_`, `-`, `C`, `)`, `7`, `=`, `4`, `&`, `o`, `]`, `s`, `Y`, `g`, `m`, `N`, respectively.

This function is:

```
char hash (char* s)
{
    char r = 0;

    while (*s)
    {
        r += *s|9;
        s++;
    }

    return r%45+77;
}

```

The golfed program computes the `hash` function of the input until it reaches the end of the string or the character `-`. Then it searches the hash in the string `k.[<* cKwye(S_-C)7=4&o]sYgmN` and determines the corresponding number. If the end of the input string was reached the number is returned, if instead a `-` was reached, then it is returned the number plus the result of the golfed program applied to the rest of the input string.
> 22 votes

# Answer
# JavaScript (ES6), ~~175~~ ~~166~~ ~~163~~ ~~156~~ ~~153~~ 147 bytes

*Saved 7 bytes thanks to @Neil*

```
a=>+a.replace(/.+te|.*el|y$/,x=>x[1]?'on-'+x:'-d').split(/ |-|dr/).map(x=>"un|d,on|le,w,th,fo,f,x,s,h,i,".split`,`.findIndex(y=>x.match(y))).join``

```

Verify it here:

```
f=a=>+a.replace(/.+te|.*el|y$/,x=>x[1]?'on-'+x:'-d').split(/ |-|dr/).map(x=>"un|d,on|le,w,th,fo,f,x,s,h,i,".split`,`.findIndex(y=>x.match(y))).join``;

document.body.innerHTML="<pre>"+["one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen","twenty","twenty-one","twenty-two","twenty-three","twenty-four","twenty-five","twenty-six","twenty-seven","twenty-eight","twenty-nine","thirty","thirty-one","thirty-two","thirty-three","thirty-four","thirty-five","thirty-six","thirty-seven","thirty-eight","thirty-nine","forty","forty-one","forty-two","forty-three","forty-four","forty-five","forty-six","forty-seven","forty-eight","forty-nine","fifty","fifty-one","fifty-two","fifty-three","fifty-four","fifty-five","fifty-six","fifty-seven","fifty-eight","fifty-nine","sixty","sixty-one","sixty-two","sixty-three","sixty-four","sixty-five","sixty-six","sixty-seven","sixty-eight","sixty-nine","seventy","seventy-one","seventy-two","seventy-three","seventy-four","seventy-five","seventy-six","seventy-seven","seventy-eight","seventy-nine","eighty","eighty-one","eighty-two","eighty-three","eighty-four","eighty-five","eighty-six","eighty-seven","eighty-eight","eighty-nine","ninety","ninety-one","ninety-two","ninety-three","ninety-four","ninety-five","ninety-six","ninety-seven","ninety-eight","ninety-nine","one hundred"].map((x,y)=>'f("'+x+'") === '+f(x)+"? "+(f(x)===y+1)).join("<br>")+"</pre>"
```

### How it works

The basic idea is to split each number into its digit-words, then map each word to the corresponding digit. *Almost* all of the words are set up to be matched properly with a simple regex, but there are a few anomalies:

* `eleven` through `nineteen`: if the word contains an `el`, or a `te` in the middle (to avoid `ten`), we add a `on-` to the beginning, changing these to `on-eleven` through `on-nineteen`.
* `twenty`, `thirty`, etc.: replacing a trailing `y` with `-d` changes these to `twent-d`, `thirt-d`, etc.

Now we split at hyphens, spaces, and `dr`s. This splits everything from 11 to 99 into its corresponding digit-words, and `"one hundred"` into `[one,hun,ed]`. Then we map each of these words through an array of regexes, and keep the index of the one that matches first.

```
0: /un|d/ - This matches the "hun" and "ed" in 100, as well as the "d" we placed on the end of 20, 30, etc.
1: /on|le/ - Matches "one" and the "on" we placed on the beginning of 11 through 19, along with "eleven".
2: /w/ - Matches "two", "twelve", and "twenty".
3: /th/ - Matches "three" and "thirty".
4: /fo/ - Matches "four" and "forty".
5: /f/ - "five" and "fifty" are the only words by now that contain an "f".
6: /x/ - "six" and "sixty" are the only words that contain an "x".
7: /s/ - "seven" and "seventy" are the only words by now that contain an "s".
8: /h/ - "eight" and "eighty" are the only words by now that contain an "h".
9: /i/ - "nine" and "ninety" are the only words by now that contain an "i".
10: /<empty>/ - "ten" is the only word left, but it still has to be matched.

```

By now, each and every input will be the array of the proper digits. All we have to do is join them with `join``` , convert to a number with unary `+`, and we're done.
> 11 votes

# Answer
# sh + coreutils, 112 bytes

Can be run on all testcases at once, one per line.

```
sed -r "`awk '$0="s/"$0"/+"NR"/g"'<<<"on
tw
th
fo
fi
si
se
ei
ni
te|lv
el"`
s/ /y0/
s/y/*10/
s/^\+|[a-z-]//g"|bc

```

## Explanation

The backticked `awk` evaluates to the `sed` script

```
s/on/+1/g       # one, one hundred
s/tw/+2/g       # two, twelve, twenty
s/th/+3/g       # three, thirteen, thirty
s/fo/+4/g       # ...
s/fi/+5/g
s/si/+6/g
s/se/+7/g
s/ei/+8/g
s/ni/+9/g
s/te|lv/+10/g   # ten, -teen, twelve
s/el/+11/g      # eleven

```

which transforms parts of numbers into their numeric representation.

```
fife            ->    +5ve
ten             ->    +10n
eleven          ->    +11even
twelve          ->    +2e+10e
sixteen         ->    +6x+10en
thirty-seven    ->    +3irty-+7ven
forty-four      ->    +4rty-+4ur
eighty          ->    +8ghty
one hundred     ->    +1e hundred

```

The additional lines of the sed script

```
s/ /y0/
s/y/*10/

```

take care of `-ty`s and `one hundred`.

```
+3irty-+7ven    ->    +3irt*10-+7ven
+4rty-+4ur      ->    +4rt*10-+4ur
+8ghty          ->    +8ght*10
+1e hundred     ->    +1ey0hundred      ->    +1e*100hundred

```

Finally, remove leading `+`s and everything that is not `+`, `*` or a digit.

```
s/^\+|[a-z-]//g"

```

Only math expressions remain

```
fife            ->    5
sixteen         ->    6+10
forty-four      ->    4*10+4
eighty          ->    8*10
one hundred     ->    1*100

```

and can be piped into `bc`.
> 6 votes

# Answer
## Pyth, 79 76 75 68 bytes

Thank @ETHproductions for 7 bytes.

```
?}"hu"z100sm*+hxc."ewEÐ¡Bu["2<d2?|}"een"d}"lv"dTZ?}"ty"dT1cz\-

```

Basically first checks the corner case of 100, then uses an array of the first two letters of the numbers 0 to 11 to determine the semantics of the input and modify the value according to suffix ("-ty" and "-teen"; "lv" in 12 is another corner case). First splits input into a list of words, then map each one to a value, and sum them up.

In pythonic pseudocode:

```
                           z = input()    # raw, unevaluated
                           Z = 0
                           T = 10
?}"hu"z                    if "hu" in z:  # checks if input is 100
  100                        print(100)
                           else:
sm                           sum(map( lambda d: # evaluates each word, then sum
  *                            multiply(
   +hxc."ewEÐ¡Bu["2<d2           plusOne(chop("ontwth...niteel",2).index(d[:2])) + \
                                 # chops string into ["on","tw",..."el"]
                                 # ."ewEÐ¡Bu[" is a packed string
     ?|}"een"d}"lv"dTZ               (T if "een" in d or "lv" in d else Z),
                                     # add 10 for numbers from 12 to 19
   ?}"ty"dT1                     T if "ty" in d else 1),  # times 10 if "-ty"
  cz\-                         z.split("-"))  # splits input into words

```

Test suite

---

## Python 3, 218 bytes

```
z=input()
if "hu" in z:print(100);exit()
print(sum(map(lambda d:([0,"on","tw","th","fo","fi","si","se","ei","ni","te","el"].index(d[:2])+(10 if "een" in d or "lv" in d else 0))*(10 if "ty" in d else 1),z.split("-"))))

```

Basically identical to the Pyth answer.

---

Off-topic:

I just discovered a meaningful version of the answer to life, the universe and everything: it's tea-thirsty twigs. Wow, twigs that yearn for tea! I'm not sure how many other answers do this, but for my answer if the input is "tea-thirsty-twigs" the output is 42.
> 4 votes

# Answer
## Haskell, ~~252~~ 231 bytes

```
let l=words;k=l"six seven eight nine";w=l"one two three four five"++k++l"ten eleven twelve"++((++"teen")<$>l"thir four fif"++k)++[n++"ty"++s|n<-l"twen thir for fif"++k,s<-"":['-':x|x<-take 9w]]in maybe 100id.flip lookup(zip w[1..])

```

This creates a list of all English number names from "one" to "ninety-nine" and then looks the index of the input up. If it doesn't exist, we're in the edge case "one hundred", so it returns `100`, otherwise it's going to return the index.

### Ungolfed

```
-- k in the golfed variant
common = words "six seven eight nine"

-- w in the golfed variant
numbers = words "one two three four five" ++ common
       ++ words "ten eleven twelve" ++ [p ++ "teen" | p <- words "thir four fif" ++ common]
       ++ [p ++ "ty" ++ s| p <- words "twen thir for fif" ++ common
                         , s <- "" : map ('-':) (take 9 numbers)]

-- part of the expression in the golfed variant
convert :: String -> Int
convert s = maybe 100 id $ lookup s $ zip numbers [1..]

```
> 2 votes

# Answer
# Python 3, ~~365~~ ~~361~~ ~~310~~ 303 characters

## Golfed

```
def f(a):
 y=0
 for i in a.split("-"):
  x="one,two,three,four,five,six,seven,eight,nine,ten,eleven,twelve,thir;four;fif;six;seven;eigh;nine;twenty,thirty,forty,fifty,sixty,seventy,eighty,ninety,one hundred".replace(";","teen,").split(",").index(i)
  y+=x+1 if x<20 else range(30,110,10)[x-20]
 return y

```

## Ungolfed

```
 def nameToNumber (numberName):
    names = ["one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve","thirteen",
             "fourteen","fifteen","sixteen","seventeen","eighteen","nineteen","twenty","thirty","forty","fifty",
             "sixty","seventy","eighty","ninety","one hundred"]
    numbers = range(30, 110, 10)
    number = 0
    for n in numberName.split("-"):
        x = names.index(n)
        number += x + 1 if x < 20 else numbers[x - 20]
    return number

```
> 2 votes

# Answer
# Python 2, 275 characters

```
def x(n):a='one two three four five six seven eight nine ten eleven twelve'.split();t='twen thir four fif six seven eigh nine'.split();b=[i+'teen'for i in t[1:]];c=[i+'ty'for i in t];return(a+b+[i+j for i in c for j in ['']+['-'+k for k in a[:9]]]+['one hundred']).index(n)+1

```

It simple builds a list of every number and finds the index.
> 2 votes

# Answer
# Japt, 82 bytes

```
+Ur`(.+)¿``¿-$1` r"y$""-d" q$/ |-|dr/$ £`un|Üaiwo|ØÏ¿ifoifix¿iÊ¿¿e¿iv`qi b_XfZ}Ãq

```

Each `¿` represents an unprintable char. Test it online!

Based on my JS answer. Subtract one byte if the output doesn't need to be an integer, since it would appear exactly the same as a string.

### How it works

```
+Ur`(.+)¿` `¿-$1`  r"y$""-d" q/ |-|dr/ £  `un|Üaiwo|ØÏ¿ifoifix¿iÊ¿¿e¿iv`          qi b_ XfZ}Ã q
+Ur"(.+)te""on-$1" r"y$""-d" q/ |-|dr/ mX{"un|dioniwo|wenithifoifixisihineiteiniv"qi bZ{XfZ}} q

Ur"(.+)te""on-$1" // Replace "thirteen", "fourteen", etc. with "on-thiren", "on-fouren", etc.
r"y$""-d"         // Replace "twenty", "thirty", etc. with "twent-d", "thirt-d", etc.
q/ |-|dr/         // Split at occurances of a space, hyphen, or "dr". By now,
                  // "one", "thirteen", "twenty", "sixty-six", "one hundred" will have become:
                  // "one", "on" "thiren", "twent" "d", "sixty" "six", "one" "hun" "ed"
mX         }      // Map each item X in the resulting array to:
"..."qi           //  Take this string, split at "i"s,
b_XfZ}            //  and find the first item Z where X.match(RegExp(Z)) is not null.
                  //  See my JS answer to learn exactly how this works.
                  // Our previous example is now
                  // "1", "1" "3", "2" "0", "6" "6", "1" "0" "0"
+              q  // Join and convert to integer.
                  // 1, 13, 20, 66, 100

```
> 1 votes

# Answer
# JavaScript, ~~214~~ 199 bytes

As always: turns out this is too long to compete, but now that I'm done it'd be a waste not to post this.

Perhaps there's an obvious way to golf this further that I've overlooked?

```
e=s=>s.slice(-1)=='d'?100:'  ontwthfofisiseeinite'.indexOf(s.slice(0,2))/2;f=s=>([t,u]=s.split('-'),~s.indexOf`le`?11:~s.indexOf`lv`?12:e(t)+(t.slice(-3)=='een')*10+''+(u?e(u):t.slice(-1)=='y'?0:''))

```

JSFiddle for test cases
> 1 votes

# Answer
## Perl, 158 bytes

```
@s=split/(\d+)/,'te1ten0l1le1on1tw2th3fo4fi5si6se7ei8ni9d00';foreach(split'-',$n=$ARGV[0]){for($i=0;$i<$#s;$i+=2){m/$s[$i]/&&print$s[$i+1]}}$n=~/ty$/&&print 0

```

Runs from the command line. `one hundred` must be entered as `"one hundred"` to stop it being interpreted as two inputs.
> 1 votes

---
Tags: code-golf, number, kolmogorov-complexity, natural-language, conversion
---


# Question
Title: Calculating Parabolic Curves in 3D Space
## Task

Write a program or function that will determine if a point in 3D space lies on a 2D parabolic curve.

---

## Input

3 points in 3D space

* vertex of a 2D parabolic curve
* arbitrary point on the curve
* arbitrary point in space

Input may be taken in any form (string, array, etc.) provided no other data is passed.

---

You may assume

* the axis of a parabola will be parallel to the z axis
* the vertex of a parabola has the maximal z value
* parabolae will never degenerate
* point values will be whole numbers that are `≥ -100` and `≤ 100`

---

## Output

A truthy/falsey value representing whether the third point given lies on the parabolic curve of the first two points.

---

## Examples

Input:

```
(2, 1, 3)
(1, 0, 1)
(4, 3, -5)

```

Output:

```
1

```

---

Input:

```
(16, 7, -4)
(-5, 1, -7)
(20, 6, -4)

```

Output:

```
0

```

---

## Walkthrough (Example #1)

1. Find a third point on the curve. To do this, mirror the arbitrary point (on the curve) over the vertex. Here is a visual (each blue line is √6 units):
2. Find the parabolic curve between the three. This is easiest on a 2D plane. Here is the 3D graph, translated to a 2D graph (each blue line is √6 units):
3. Graph the third given point and solve.

# Answer
## Jelly, ~~13~~ 11 bytes

```
_÷/µḢ²=A;$P

```

The input format is a bit strange; it takes ***P1*** as the second argument, and (***P3***,***P2***) as the first argument, where each point is expressed in the form `((x+yj),z)`.

We first normalize the points so that the vertex is on the origin, and then make sure that P1 and P2 are on the same line, and also that the ratio of their z distances is equal to the ratio of their x distances.

```
_÷/             Helper link. Inputs: (P3,P2) on left, P1 on right.
_                  Subtract right from left. (P3-P1,P2-P1).
 ÷/                Fold division. (P3-P1)/(P2-P1). P2-P1 is nonzero in both x+yi and z.
   µ               Push the chain onto the stack, and start a new monadic link.
    Ḣ²=A;$P     Hook; main link. Calculates whether w² = a and a is nonnegative.
                Input: The result of the helper link. Call it [w,a].
    Ḣ²              Pop w and square it. Now the list is [a].
       A,$          Concatenate a to its absolute value.
      =             Fork; is w equal to [a,abs(a)]? Returns 2 element list of 0 or 1
          P         Product; that is, true if w was equal to both a and abs(a).

```

Try it here.
> 3 votes

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


title: Math without math class

text:
# Question
Title: Math without math class
You receive an input with a number and a string with a space in the middle. The string tells you what you need to do with the number, it can be:

sqrt - square root of number

sqr - square of number

cube - cube of number

abs - absolute of number

round - rounded version of number

You need to output the final result of the calculation with whatever you have. If your language doesn't have an input, you can hard-code that in.

**Rules:**

You can't use a math library, even if it is built-in.

You don't get a number or a result bigger than the highest possible one in your language.

Because of the vulnerability of the above rule, you can't use languages, which only support a 1 bit number. (1 and 0)

If your language doesn't support non-integer numbers, you need to output a rounded result.

**Test cases**

16 sqrt = 4

25 sqr = 625

3 cube = 27

-10 abs = 10

18.38 round = 18

Because this is a code-golf, the shortest answer in bytes wins.

Good luck!

# Answer
> 1 votes
# Mathematica, ~~155~~ 153 bytes

```
{a=ToExpression@#,a a,a a a,c=a~Mod~1,a+Boole[c>=.5]-c,,,,If[Chop@a==0,0,a/Sign@a],If[a>0,(#+a/#)/2&~FixedPoint~1.,0]}[[Hash@#2~Mod~12]]&@@StringSplit@#&

```

Could probably be golfed further. Doesn't use "any sort of functionality, wich allows you to calculate the squareroot/square/cube/absolute/roubded version of a number."

# Answer
> 1 votes
# Bash - ~~141 137~~ 132

```
t(){ for((;x*x!=$1;x++));do :;done;}
r(){ ((x=$1*$1));}
e(){ ((x=$1**3));}
s(){ x=${1#-};}
d(){ x=${1%.*};}
${2:${#2}-1} $1
echo $x

```

Run as

```
bash math.sh 16 sqrt
bash math.sh 25 sqr
bash math.sh 3 cube
bash math.sh -10 abs
bash math.sh 18.38 round

```

It strips the operation done to the last character, which is unique for each, then calls the appropriate function with the number

# Answer
> 1 votes
# ES6 - 124 bytes

```
(a,b)=>eval('_=>'+'{for(c=1;c*c<a;c++);return c}_a*a_a*a*a_a<0?-a:a_a.toFixed()'.split`_`['tresd'.indexOf(b[b.length-1])])()

```

Square root only works for rounded numbers. Sqrt of 15 will result in 4, I hope this is allowed. Re-writing a fully functional square root function feels like overkill.

Explanation

```
(a,b)=> // anonymous function
    eval(
        '_=>' + // construct an anonymous function to eval
        '{for(c=1;c*c<a;c++);return c} // sqrt
        _ // seperator
        a*a // sqr
        _
        a*a*a // cube
        _
        a<0?-a:a // abs
        _
        a.toFixed()' // round
        .split`_` // create an array of functions
        [ // select the function to use
            'tresd'.indexOf(b[b.length-1]) // get index of input
        ]
    )() // end eval and call the returned function

```

Golfing tips are welcome

Test cases:

```
f=
(a,b)=>eval('_=>'+'{for(c=1;c*c<a;c++);return c}_a*a_a*a*a_a<0?-a:a_a.toFixed()'.split`_`['tresd'.indexOf(b[b.length-1])])()

F=(a,b)=>document.body.innerHTML+='<pre>'+a+', '+b+':\n'+f(a,b)+'\n</pre>';

F(16,'sqrt')
F(25,'sqr')
F(3,'cube')
F(-10,'abs')
F(18.38,'round')
```

# Answer
> 0 votes
# Python 2, 153 bytes

```
S=str.split;x,f=S(raw_input())
exec'print '+dict(zip('tresd',S('[a for a in range(x)if a*a==x][0]|x*x|x**3|abs(x)|round(x)','|')))[f[-1]].replace('x',x)

```

---
Tags: code-golf
---


# Question
Title: Bijective mapping from integers to a variable number of bits
A variable number of bits is an array of 0 or more bits. So `[0, 1]` is a variable number of bits, but so is `[]`.

Write a function or program that, given an nonnegative integer returns a variable number of bits such that every integer has a one-to-one (bijective) mapping with an array.

There are an infinite amount of such mappings, you are free to construct one as you please, but it **must** be one-to-one. Your mapping must *conceptually* be one-to-one for an arbitrarily sized integer, but it's OK if your *implementation* fails for large integers due to numerical limits of types in your preferred language (e.g. C's `int`).

As an example of what is **not** a one-to-one mapping, is simply listing the binary digits of the integer. In such a system 5 becomes `[1, 0, 1]` (or `0b101`), but it's not one-to-one, because `0b0101` or `[0, 1, 0, 1]` also means 5.

It should be fairly obvious that a mapping is not one-to-one if it skips an integer (e.g. it doesn't work for 5), but I'd like to make it clear that skipping a variable bit array is also not one-to-one. You must map to every possible variable bit array, including `[]`.

---

Shortest code in bytes wins.

# Answer
# Jelly, 3 bytes

```
‘BḊ

```

Same idea as xnor: maps `0 1 2 3 4 ...` to `[] [0] [1] [0 0] [0 1] ...`; the code is basically `increment → binary → remove first`.

Try it out online.
> 4 votes

# Answer
## Python, 20 bytes

```
lambda n:bin(~n)[4:]

```

Test:

```
>> [bin(~n)[4:] for n in range(16)]
['', '0', '1', '00', '01', '10', '11', '000', '001', '010', '011', '100', '101', '110', '111', '0000']

```

Doing `lambda n:bin(n+1)[3:]` increments the input, then takes the binary representation with the first symbol removed (`[3:]` because the prefix `0b` is two chars chars). Since any positive number starts with 1 in binary, this uniquely gives a binary representation.

A byte is saved by instead using the bit complement `~n` to get the negation `-(n+1)`, and removing the negative sign by chopping off one more symbol.
> 10 votes

# Answer
## Pyth, 5 bytes

```
t.BhQ

```

Simply a translation of xnor's answer into Pyth.

`Q` is eval()'d input(), `h` increments it, `.B` converts it to a binary string, and `t` takes the "tail" (which is everything except the first character).
> 2 votes

# Answer
## Haskell, ~~41~~ ~~38~~ ~~30~~ 29 bytes

```
l="":[b:x|x<-l,b<-"01"]
(l!!)

```

Usage example: `(l!!) 4` -\> `"10"`.

Starting with the empty list as the first element, walk lazily through the list and append the current element with `0` and with `1` in front of it.

Edit: @xnor saved ~~3~~ 11 bytes. Thanks!
> 2 votes

# Answer
## JavaScript (ES6), 29 bytes

```
x=>(~x).toString(2).slice(2)

```

Same idea as xnor.

```
f=x=>(~x).toString(2).slice(2);
[...Array(100)].map((v,x)=>A.textContent+=x + ': ' + f(x) + '\n')
```

```
<pre id=A></pre>
```
> 1 votes

# Answer
# Jolf, 4 bytes

Try it here!

```
wBhj
  hj  input + 1
 B    converted to binary
w     with first removed.

```

Very simple strategy, also happens to be the shortest.
> 1 votes

# Answer
## Haskell, 35 bytes

```
h 1=[]
h n=mod n 2:h(div n 2)
h.(+1)

```

Haskell doesn't have a binary built-in, so the (reversed) conversion is done manually. To remove the initial 1, the base case has `1` transform to the empty list.

Edit: Saved a byte by conjugating by the `+1` instead.

```
h 0=[]
h m=1-mod m 2:h(div(m+1)2-1)

```
> 1 votes

# Answer
# C, 40 bytes

```
f(n){if(++n/2)putchar(n%2+48),f(n/2-1);}

```

Converts the input to bijective base 2 (with symbols `0` and `1`), like the other answers.

ideone it!
> 1 votes

---
Tags: code-golf, integer, open-ended-function, bitwise
---


title: Efficient Scientific Notation

text:
# Question
Title: Efficient Scientific Notation
The other day my chemistry teacher was explaining to us about scientific notation (using a small number and multiplying it by powers of ten to express large numbers more easily), which brought me back a few years to when I first learnt it. After learning the basics, we had done a bunch of typical maths questions, some of which were like the following:

> Represent the following in scientific notation:
> a) 50000000
> b) 120000000000000
> c) 90000000000000000000000000000000000000
> d) pi^e^i^j^k^std::vector
> ...
> z) **200**
> ...

And I thought, "What? We were told that scientific notation was used to make writing large numbers more efficient, but some cases aren't more efficient at all!"

Consider the number

```
300

```

and its representation in scientific notation:

```
3x10^2

```

What, the scientifically notated version actually takes up more space? We can't have that now can we? (Screen space is precious.)
We could determine ourselves if it's more space efficient to write a number in scientific notation or not, or...

# Task

Your program or function should take as input a single positive number `n` of arbitrary size (up to what your language supports) and output the scientifically notated version of the number.
However, if the original number `n`, after removal of trailing zeroes and trailing decimal place, takes less or the same amount of characters to display than its scientifically notated version, you must output that original number `n` instead.

Your code needs to be as short as possible because the output also has to be as short as possible.

# Specifications

Efficient Scientific Notation is defined as follows:

```
bx10^e

```

`b` is the input number appropriately divided by powers of 10 such that `1 <= b < 10`. This number must have all trailing zeroes (and decimal point if required) removed, but must have the precision of the original number (up to the decimal point limit in your language, of course). Ie `90000` becomes `9`, `13.500` becomes `1.35`, `0.000675` becomes `6.75` etc. If this number ends up containing more decimal places than your language can handle, it should be rounded to that maximum number of decimal places.

`e` is the exponent to which ten is raised such that `n = b x 10^e` (remember that this number needs to be negative if `n` is smaller than 1). This number should not have any trailing zeros or a decimal place (mainly because if it's not an integer something is wrong...).

The characters `x10^` *must* remain as is in the string between `b` and `e`.

# Test cases

```
Input -> output
1 -> 1
20 -> 20
3000000 -> 3x10^6
400000 -> 400000
0.008093 -> 0.008093
0.007835000000000 -> 0.007835
0.000003000000 -> 3x10^-6
0.00000065 -> 6.5x10^-7
0 -> 0

```

# Scoring

This is , so shortest code in bytes wins.

# Other rules and clarification

* Trailing zeros (and/or trailing decimal place) are not counted towards the character count of the original input number `n`. Keep that in mind for cases such as test case 6
* You may assume that if the input number is less than 1, it will always start with a 0 in place for the ones digit (as in test cases 5-8).
* Input number will never be negative
* Built-ins that make this challenge trivial and standard loopholes are disallowed
* A trailing newline in the output is OK

**EDIT**
Thanks to user81655 for pointing out test cases 7 and 8 had incorrect powers of ten. I have now fixed those so make sure your code evaluates them correctly.

# Answer
> 4 votes
## ES6, ~~83~~ 81 bytes

```
x=>(e=s=>s.replace(/e\+?/,'x10^'),z=e(x.toExponential()),y=e(''+x))[z.length]?z:y

```

Probably fails for some edge cases where `toString` insists on exponential format.

Edit: Saved 2 bytes thanks to @user81655.

# Answer
> 2 votes
# Python 3, 346 342 319 302 bytes

```
L=len;N=str(float(input()))
if N.endswith('.0'):N=N[:-2]
if'e'in N:C,P=N.split('e');N=N.replace('e','x10^')
else:
 C=N.strip('.0').replace('.','');F=N.find('.')
 if L(C)>1:C=C[0]+'.'+C[1:]
 P=((L(N) if F==-1 else F)-1-N.lstrip('0').find(C[0]))
print(min([N,'{0}x10^{1}'.format(C,int(P))],key=L))

```

Probably horribly golfed, but hey, this is my first try at something like this. It's hard to read, so it must be good.

As far as I'm aware, it should work on every case, even with Python's tendency to automatically convert numbers past whatever threshold into scientific notation (except with that cool and fancy 'e'). I don't remember exactly how I made that be able to return standard form numbers, but it does that.

# Answer
> 2 votes
# Perl 6, ~~96~~ 90 bytes

I feel like this could be shorter, but this is my best for now

```
{my \s=($_,*×(1>$_??10!!.1)…10>*>=1);min(s[*-1]~"x10^"~(1>$_??1-s!!s-1),$_,by=>&chars)}

```

**usage**: Assign this to a variable

Here it is ungolfed a bit with some bad commentary:

```
my &f = -> $n {
    my $a = 1 > $n ?? 10 !! .1;             # If $n < 1, we will multiply by 10
                                            # in the sequence below, else by 0.1

    my @seq = ($n, * × $a ... 10 > * >= 1); # Sequence starting at $n,
                                            # multiply the previous value by $a
                                            # until we reach a number 1 <= x < 10

    # Join the last element in @seq, "x10^", and the length of @seq,
    # with an extra subtraction for numbers less than 1.
    # this gets us our scientific notation.
    my $science = @seq[*-1] ~ "x10^" ~ @seq - (1 > $n ?? @seq*2 !! 1);

    min($science, $n, by => &chars) # Uses the &chars function to
                                    # choose a min value and return it.
}

```

# Answer
> 2 votes
## TI BASIC (nspire): 112 bytes

```
Define f(x)=
Prgm
string(x)➝a
If x≥1 Then
format(x,"s")➝a
EndIf
instring(a,"ᴇ")➝b
left(a,b-1)&"x10^"&mid(a,b+1)➝a
If dim(a)<dim(string(n)) or x<1 Then
Disp a
Else
Disp x
Endif
EndPrgm

```

**Explanation**

```
If x≥1 Then
format(x,"s")➝a
EndIf

```

Converts the input to scientific notation with the format function if it already isn't in that format- as small decimals are automatically converted.

```
instring(a,"ᴇ")➝b
left(a,b-1)&"x10^"&mid(a,b+1)➝a

```

Finds the position of the fancy E that denotates exponents and replaces it with "x10^".

```
If dim(a)<dim(string(x)) or x<1 Then
Disp a
Else
Disp x
Endif

```

Checks which output is larger and returns the optimal one. Unless it is a small decimal, which are smaller by default.

# Answer
> 0 votes
## Python (3.5) 177 bytes

A solution using regular expression

```
import re
g=lambda s:re.sub(r"e\+?(-?)0?","x10^\\1",s)
def f(i):
 t=g(re.sub(r"\.[0]*e","e","%e"%i))
 u=g(re.sub(r"(\..*)[0]*$","\\1",str(i)))
 return t if len(u)>len(t) else u

```

## Explanation

Importation of regexp module

```
import re

```

Définition of the lambda function to replace `e` by `x10^`

```
g=lambda s:re.sub("e\+?(-?)0?","x10^\\1",s)
def f(i):

```

Convertion of the string in scientific notation

```
 t=g(re.sub(r"\.[0]*e","e","%e"%i))

```

Remove 0 padding in the orginal string

```
 u=g(re.sub(r"(\..*)[0]*$","\\1",str(i)))

```

compare length

```
 return t if len(u)>len(t) else u

```

## Results

```
>>> [f(i) for i in [1, 20, 3000000, 400000, 0.008093, 0.007835000000000, 0.000003000000, 0.00000065, 0]]
['1', '20', '3x10^6', '400000', '0.008093', '0.007835', '3x10^-6', '6.5x10^-7', '0']

```

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


title: To be or not to be

text:
# Question
Title: To be or not to be
In the fewest bytes possible, determine whether the two values given each match one of the following:

**First value**

```
2      string or integer - whichever you prefer
to     case insensitive
too    case insensitive
two    case insensitive
t0     case insensitive (t zero)

```

**Second value**

```
b      case insensitive
be     case insensitive
bee    case insensitive
b3     case insensitive

```

# Examples

```
2          'Bee'            true
'2'        'b'              true
'not to'   'be'             false
'that is'  'the question'   false

```

# Answer
# Shakespeare, 4778 Bytes

*Note: this answer is not meant to be a serious competitor*

```
To Be or Not To Be, This is the Answer.

Hamlet, the main player in our story.
Horatio, Hamlet's guide through his internal struggles.
The Ghost, a handsome honest bold fair gentle king.
Claudius, the worthless usurper of the throne.
Ophelia, who Hamlet always writes two.
Polonius, the unfortunate third man caught between Hamlet and Claudius.
Brabantio, the greater.
Banquo, the lesser.
Emilia, the greater.
Egeus, the lesser.
Othello, the greater.
Orsino, the lesser.
Tybalt, the greater.
Titania, the lesser.
Valentine, who doubled is greater.
Viola, who doubled is lesser.

Act I: A simple question in so many words.

Scene I: Hamlet passes judgment over the cast.

[Enter Hamlet and Horatio]
Hamlet:
    Thou art the sum of a good healthy sunny warrior and a lovely day.
[Exit Horatio]
[Enter Claudius]
Hamlet:
    Thou art the sum of The Ghost and warm cute brave trustworthy hero.
[Exit Claudius]
[Enter Ophelia]
Hamlet:
    Thou art the sum of Claudius and a smooth spaceman.
[Exit Ophelia]
[Enter Polonius]
Hamlet:
    Thou art the sum of Ophelia and a plum.
[Exit Polonius]
[Enter Brabantio]
Hamlet:
    Thou art the sum of The Ghost and the sum of The Ghost and a rich kingdom.
[Exit Brabantio]
[Enter Banquo]
Hamlet:
    Thou art the sum of Brabantio and The Ghost.
[Exit Banquo]
[Enter Emilia]
Hamlet:
    Thou art the sum of Brabantio and the sum of joy and a gentle girl.
[Exit Emilia]
[Enter Egeus]
Hamlet:
    Thou art the sum of Emilia and The Ghost.
[Exit Egeus]
[Enter Othello]
Hamlet:
    Thou art the sum of Emilia and the sum of a cunning lover and the sweetest golden embroidered rose.
[Exit Othello]
[Enter Orsino]
Hamlet:
    Thou art the sum of Othello and The Ghost.
[Exit Orsino]
[Enter Tybalt]
Hamlet:
    Thou art the sum of Othello and the sum of happiness and fair fine heaven.
[Exit Tybalt]
[Enter Titania]
Hamlet:
    Thou art the sum of Tybalt and The Ghost.
[Exit Titania]
[Enter Valentine]
Hamlet:
    Thou art the sum of Tybalt and the sum of a happy day and a pony.
[Exit Valentine]
[Enter Viola]
Hamlet:
    Thou art the sum of Valentine and The Ghost.
[Exeunt]

Scene II: The beginning of Horatio's interrogation.
[Enter Hamlet and Horatio]
Hamlet:
Horatio:
    Open your mind.
    Art thou as good as Tybalt?  If so, let us proceed to Scene IV.
    Art thou as good as Titania?  If so, let us proceed to Scene IV.
    Art thou as good as Ophelia?  If not, let us proceed to Scene XII.

Scene III: Are we to?
Horatio:
    Open your mind.
    Art thou as good as The Ghost?  If so, let us proceed to Scene VII.
    Let us proceed to Scene XII.

Scene IV: Can we go further than t?
Horatio:
    Open your mind.
    Art thou as good as Claudius?  If so, let us proceed to Scene III.
    Art thou as good as Valentine?  If so, let us proceed to Scene VI.
    Art thou as good as Viola?  If so, let us proceed to Scene VI.
    Art thou as good as Othello?  If so, let us proceed to Scene V.
    Art thou as good as Orsino?  If not, let us proceed to Scene XII.

Scene V: Oone oor twoo?
Horatio:
    Open your mind.
    Art thou as good as The Ghost?  If so, let us proceed to Scene VII.
    Art thou as good as Othello?  If so, let us proceed to Scene III.
    Art thou as good as Orsino?  If so, let us proceed to Scene III.
    Let us proceed to Scene XII.

Scene VI: Hamlet desperately searches for whOo?.
Horatio:
    Open your mind.
    Art thou as good as Othello?  If so, let us proceed to Scene III.
    Art thou as good as Orsino?  If so, let us proceed to Scene III.
    Let us proceed to Scene XII.

Scene VII: Knowing to, what to do?
Horatio:
    Open your mind.
    Art thou as good as Brabantio?  If so, let us proceed to Scene VIII.
    Art thou as good as Banquo?  If not, let us proceed to Scene XII.

Scene VIII: Learning what to Bleive.
Horatio:
    Open your mind.
    Art thou as good as me?  If so, let us proceed to Scene XI.
    Art thou as good as Emilia?  If so, let us proceed to Scene X.
    Art thou as good as Egeus?  If so, let us proceed to Scene X.
    Art thou as good as Polonius?  If not, let us proceed to Scene XII.

Scene IX: The Eend is nigh?
Horatio:
    Open your mind.
    Art thou as good as me?  If so, let us proceed to Scene XI.
    Let us proceed to Scene XII.

Scene X: Wee may havee succeeeedeed.
Horatio:
    Open your mind.
    Art thou as good as Emilia?  If so, let us proceed to Scene IX.
    Art thou as good as Egeus?  If so, let us proceed to Scene IX.
    Art thou as good as me?  If not, let us proceed to Scene XII.

Scene XI: Hamlet is at peace.
Horatio:
    Thou art a beacon of happiness.
    Let us proceed to Scene XIII

Scene XII: The demons have won.
Horatio:
    Thou art nothing.

Scene XIII: Hamlet opens up.
Horatio:
    Hamlet! Open your heart.
[Exeunt]

```

Outputs 0 if false, 1 if true.

This could easily be shorter (and if people really want me to, the word lengths could be cut down), but to do so would be a slap to the face of good ol' Will. I've always felt Horatio is the unsung hero of Hamlet, so I made sure that he was the one to deliver the intense monologue to Hamlet where Hamlet has to ultimately prove that he is as good as Horatio (who represents the newline).

The code itself is pretty simple. All of the characters sans Hamlet are ascii values (In order:`newline,space,0,2,3,B,b,E,e,O,o,T,t,V,v`) and then the code is a simple state machine (specifically, a DFA) that transitions to `Scene XI` as an accept state and `Scene XII` as a reject state.

.

After making this, I just plugged it into Shakespeare, using the fact that I could drop down to the next state when they were numerically adjacent. I only tested it with the version of Shakespeare I linked in the title, but I believe we define a language by an implementation iirc.
> 34 votes

# Answer
# Retina, 28

* 1 byte saved thanks to @MartinBüttner.

Quite possibly my quickest ever code-golf answer - 9 minutes after OP.

Input parameters are comma-separated. Output is 1 for truthy and 0 for falsey.

```
i`^(2|t[ow]?o|t0),b(e?e?|3)$

```

Try it online.
> 18 votes

# Answer
# Pyth, 34 bytes

```
.A}Lrw1c2c." Wô-WûÄæ§Òé
}

```

Try it online: Demonstration

### Explanation:

```
          ."...   packed string, gets decoded to: "2 TO TOO TWO T0 B BE BEE B3"
         c        split by spaces
       c2         split into 2 lists: [['2', 'TO', 'TOO', 'TWO', 'T0'],
                                       ['B', 'BE', 'BEE', 'B3']]
   L              for each list:
     w               read a line
    r 1              convert it to uppercase
  }                  and test if it is part of this list list
.A                test if both return true

```
> 7 votes

# Answer
# Pyth, 41 bytes

```
&xrw0c"2 to too two t0"dxrw0c"b be bee b3

```

Try it here!

Straightforward list lookup. Prints an empty list as falsy value and a non-empty list as truthy value.

Looking or a better way tho, I don't really like this one.
> 4 votes

# Answer
# Oracle SQL 11.2, 86 bytes

```
SELECT 1 FROM DUAL WHERE:1 IN('2','to','too','two','t0')AND:2 IN('b','be','bee','b3');

```

Returns one row for truthy and no row for falsey.
> 4 votes

# Answer
## ES6, ~~56~~ ~~48~~ 45 bytes

```
(...a)=>/^(2|t0|t[wo]?o),b(ee?|3)?$/i.test(a)

```

Saved 5 bytes thanks to @user81655. Saved 3 bytes from some further optimisation. Saved another 3 bytes thanks to @Patrick Roberts.

`t[wo]?o` is the shortest regex I could think of to match all three homophones.

If it's permitted to pass the two values as a single parameter array, then the rest parameter can become a normal parameter, saving another 5 bytes.
> 3 votes

# Answer
# 05AB1E, ~~39~~ 45 bytes

Code:

```
“2€„…«Œ† t0“' ¡)Ilrk\U“b€ïÍÝ b3“' ¡)Ilrk\>X>*

```

Try it online!

Uses CP-1252 encoding. Truthy is when a number is outputted and falsy is when nothing is outputted.

**Non-competing version (39 bytes)**, works with the newest version:

```
“2€„…«Œ† t0“ð¡)IlkU“b€ïÍÝ b3“ð¡)Ilk>X>*

```
> 3 votes

# Answer
## Python 2.7, 133 bytes

```
def e(a, b):
        c, d = """2,too,to,t0,two""","""be,b,bee,b3"""
        return a.lower() in c and b.lower() in d

print e('2', 'bee')

```

Not sure if we're supposed to post solutions if there's a smaller version in the comments but here's my version in Python.

Edit: Without the function it's only 73 bytes (and that's not even near the best answers. Forgive me I'm new

```
a, b = "to", "bee"
print a in "2 too to t0 two" and b in "be b bee b3"

```
> 3 votes

# Answer
# Perl 6, ~~45~~ 44 bytes

Thanks to the folks in IRC for helping me golf this down

```
{@_~~(~2|/:i^t[0|oo?|wo]$/,/:i^b[ee?|3]?$/)}

```

**usage**

```
> my &f = {@_~~(~2|/:i^t[0|oo?|wo]$/,/:i^b[ee?|3]?$/)}
-> *@_ { #`(Block|309960640) ... }
> f("2", "Bee")
True
> f("2", "b")
True
> f("not to", "be")
False
> f("that is", "the question")
False

```

**Non-competing alternative, 54 bytes**

This is a nice alternative to the above if you think regexes are gross, but it is a tad longer. It could be golfed down a couple more bytes but since it's non-competing I'll leave it as is.

```
{@_».lc~~(qw<to too two t0 2>.any,<b be bee b3>.any)}

```
> 3 votes

# Answer
## Ruby, 53 55 52 bytes

```
f=->(a,b){/^(2|t[wo]?o|t0)$/i=~a&&/^b(e?e?|3)$/i=~b}

```

I'll be honest, this is my first attempt at trying to golf a problem.

Function call in the form of `f.call(firstValue, secondValue)`

`0` is Truthy, `nil` is Falsy.

Test it Here
> 2 votes

# Answer
## Pyth, 39 bytes

*-3 bytes by @FryAmtheEggman*

```
.A.b}rN1cY\@Q,."0WÑ³5YYÅJB"."3EW´l¢ï

```

Try it here.
> 1 votes

# Answer
## PowerShell v3+, ~~74~~ 70 bytes

```
param($a,$b)+($a-in-split'2 to too two t0')*($b-in-split'b be bee b3')

```

Doesn't use regex. Takes two input, checks if the first one is `-in` the array that's been dynamically created by the `-split` operator, converts that Boolean to an int with `+`, then multiplies that `*` with checking whether the second is `-in` the second array (which will automatically cast the Boolean as an int). This works because `x*y == x&y` if `x` and `y` can only be `1` or `0`.

PowerShell by default is case-insensitive, so we get that for free. Will output `0` or `1` for falsey/truthy, respectively. Requires v3 or newer for the `-in` operator.

Edit -- Saved 4 bytes by using unary -split
> 1 votes

# Answer
# Japt, 36 bytes

```
!Uv r"2|t(0|wo|oo?)" «Vv r"b(e?e?|3)

```

Maybe I missed something, but this should work completely. Test it online!
> 1 votes

# Answer
# Python, ~~85~~ 83 bytes

@Manatwork saved me two bytes.

This is pretty brute force, I'll look into regex solutions next.

```
lambda a,b:a.lower()in'2 to too two t0'.split()and b.lower()in['b','be','bee','b3']

```
> 1 votes

# Answer
# Groovy, 52 bytes

```
f={x,y->"$x $y"==~"(?i)(2|t([wo]o?|0)) (b(ee?|3)?)"}

```

`==~` is a cool regex operator in groovy that checks for equality.

Tests:

Regex101 test.

```
assert f('2', 'Bee') == true
assert f('2', 'b') == true
assert f('not to', 'be') == false
assert f('that is', 'the question') == false

```
> 0 votes

# Answer
# MATL, 32 ~~41~~ ~~43~~ bytes

```
jk'^(2|t[ow]?o|t0),b(e?e?|3)$'XX

```

Same approach as @DigitalTrauma's Retina answer. Inputs are separated by a comma. Truthy output is a string with the two inputs lowercased; falsy is no output.

**Try it online!**

```
j                                % input as a string
k                                % convert to lowercase
'^(2|t[ow]?o|t0),b(e?e?|3)$'     % regular expression to match the two inputs
XX                               % match regular expression

```
> 0 votes

# Answer
# C# 6, 132 bytes

```
bool t(string x,string y)=>new[]{"2","to","too","two","t0"}.Contains(x.ToLower())&&new[]{"b","be","bee","b3"}.Contains(y.ToLower());

```

Ungolfed version (Only slightly more readable):

```
bool t(string x, string y) => new[] { "2", "to", "too", "two", "t0" }.Contains(x.ToLower()) && new[] { "b", "be", "bee", "b3" }.Contains(y.ToLower());

```
> 0 votes

# Answer
# Python 2, 67 bytes

Uses Digital Trauma's regex. Input is a single string separated by a comma. Not sure if that format is allowed for input...

```
import re
f=lambda x:bool(re.match('^(2|t[ow]?o|t0),b(e?e?|3)$',x))

```
> 0 votes

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


# Question
Title: A small language deserves a small interpreter
Here is a very simple language definition:

```
A Variable is any string that does not contain ^, <, >, !, or ?
The empty string is a valid variable identifier
The value of every variable starts at 0.
A Statement is one of (var is a Variable, P is a Program):
    var^   -> changes var to be equal to 1 more than itself
    var<P> -> while var > 0, changes var to be equal to 1 less than itself, then runs P
    var! -> output value of var
    var? -> ask for non-negative integer as input, increase var by that value
A Program is a concatenation of Statements, running a Program means running each Statement in order

```

Example programs (note that the empty string is a variable, but I will use it sparingly for the sake of clarity, and some variables are zeroed out in the program when they are usually 0 by default):

```
<>: sets the value of the empty string variable to 0
b<>b?b<a^>: asks for b, then adds the value stored in b to a, zeroing b in the process
b<>b?a<>b<a^>: asks for b, then sets a to the value of b, zeroing b in the process
a<>c<>b<a^c^>c<b^> : copies the value in b into a without zeroing it
b<>c<>a<c^c^c<b^>>b! : outputs a multiplied by 2
b^b<a<>a?a!b^> : outputs what you input, forever

```

Your goal is to write the smallest interpreter for this language.

1. The value of a variable can be arbitrarily large and should only be limited by the total memory your language has access to, in theory, but you are only required to handle values up to 2^256.
2. Your program should be able to handle arbitrarily long programs, in theory, but you will only be required to work on programs under 2^32 characters long. You are required to handle nested loops of depth up to 2^32 as well.
3. You can assume that the program is a valid program, and that you will only ever get non-negative integers when you ask for input. You can also assume that only ASCII printable characters are included in the input string.
4. The speed of the program you interpret doesn't matter, it will already be painfully slow for things as simple as 5-digit multiplication, without optimization.
5. If you want to use a language which cannot reasonably accept input or produce output in the way described by the language, use any interpretation you want to make it possible. This applies to any reason your language can't implement some required behavior. I want all languages to be able to compete.
6. Shortest program wins. Standard loopholes apply.

# Answer
> 5 votes
# Ruby, 182 bytes

```
$h=Hash.new 0
def r(c)c.scan(/(([^!?^<>]*)(<(\g<1>*)>|[!?^]))/){$4?($1=~/(.*?)<(.*)>/
($h[$1]-=1;r$2)while$h[$1]>0):$3<?"?p($h[$2]):$h[$2]+=$3<?@?STDIN.gets.to_i:
1}end
r IO.read *$*

```

Try it like this:

```
$ cat code
a?b<>c<>a<c^c^c<b^>>b!

$ ruby lynn.rb code
3                           <-- input
6                           <-- output

```

## How it works

The `r` function tokenizes an input string and executes each token:

```
def r(c)
    c.scan(/(([^!?^<>]*)(<(\g<1>*)>|[!?^]))/){
        ...
    }
end

```

We look for some variable name `$2` matching `[^!?^<>]*`, followed by either

* `<...>` where `...` matches zero or more programs (`\g` is recursion), in which case `$4` isn't `nil`
* A `!`, `?`, or `^` character, captured by `$3`, in which case `$4` is `nil`.

Then the logic for executing a token is quite simple when indenting it a bit:

```
$4 ? (                                    # If it's a loop:
    $1 =~ /(.*?)<(.*)>/                   #   Re-match token*
    ($h[$1]-=1; r $2) while $h[$1] > 0    #   Recurse to run loop
) :                                       # Else:
    $3 < ?"                               #   If it's an !:
      ? p($h[$2])                         #     Print the var
      : $h[$2] +=                         #   Else, increment it by:
          $3 < ?@                         #     If it's a ?:
              ? STDIN.gets.to_i           #       User input
              : 1                         #     Else: 1

* There's an oniguruma bug, I think, that keeps me from simply using $3 here.

```

# Answer
> 1 votes
# JavaScript (ES6) 184 ~~194 209~~

**Edit** Simplified (using function parameters for input and output seemed a nice idea, but it was not), 1 more byte saved thx @ӍѲꝆΛҐӍΛПҒЦꝆ

**Edit 2** Modified parsing. The logic for increment/input is borrowed from @Lynn's answer

```
F=(p,i=0,v={},n='')=>eval("for(;c='>?^!<'.indexOf(q=p[i++]||'');n=~c?'':n+q)if(c>3){for(;v[n]--;)F(p,i,v);i=F(p,i,v[n]=0)}else~c&&v?c>2?alert(v[n]|0):v[n]=~~v[n]+(--c||+prompt()):0;i")

```

**Less golfed**

```
F=(p,      // program
   i = 0,  // initial instruction pointer
   v = {}, // variables (default to empty) or if 0, flag of dummy execution
   n = ''    // name of current variable (has to be local for recursive calls)
{
  for(; c='>?^!<'.indexOf(q=p[i++]||''); )
  // q = current character
  // c = current command (int 0..4 or -1 id not recognized)
  //     note 0 end of subprogram or end of program
  {
    if(c>3) // 4='<' call subprogram - recursive
    {
      for(;v[n]--;)
        F(p,i,v); // conditional call, repeated - using real environment
      v[n] = 0; // Reset variable at loop end
      i=F(p,i,0) // one more unconditional dummy call, just to advance i
    }
    else
      ~c&&v? // if valid command (1..3) and not dummy
      c>2?
        alert(v[n]|0) // output, undefined becomes 0
        :v[n]=~~v[n]+(--c||+prompt()) // inc with 1 or user input
      :0     // not valid command or dummy, do nothing
    n=~c?'':n+q // reset or update current variable name
  }
  return i // return current istruction pointer (for recursive calls)
}

```

**TEST** The snippet start evaluating 2016 using the program posted by @Neil. Be patient...

```
F=(p,i=0,v={},n='')=>eval("for(;c='>?^!<'.indexOf(q=p[i++]||'');n=~c?'':n+q)if(c>3){for(;v[n]--;)F(p,i,v);i=F(p,i,v[n]=0)}else~c&&v?c>2?alert(v[n]|0):v[n]=~~v[n]+(--c||+prompt()):0;i")

// TEST
function definput(){  I.disabled = KI.checked; }
function defoutput(){  O.disabled = KO.checked; }

function run()
{
  var prog=P.value, irows = I.value.split('\n'), pi=0;
  var fout=x=>O.value+=x+'\n';
  var fin=x=>irows[pi++];
  var saveAlert=alert, savePrompt=prompt
  if (!KO.checked) alert=fout,O.value=''
  if (!KI.checked) prompt=fin

  F(prog);

  alert=saveAlert
  prompt=savePrompt
}

P.value="^^^^<a^a^>a<^^^^><a^b^>a<c<b^^>b<c^^>>!"

run()
```

```
Program <button onclick="run()">RUN</button><br>
<textarea id=P></textarea><br>
Input (or <input type=checkbox id=KI onclick="definput()"> interactive prompt)<br>
<textarea id=I>5</textarea><br>
Output (or <input type=checkbox id=KO onclick="defoutput()"> popup)<br>
<textarea id=O readonly></textarea><br>
```

# Answer
> 1 votes
# C++, 301

**Thanks to @ceilingcat for some very nice pieces of golfing - now even shorter**

```
#import<bits/stdc++.h>
std::map<std::string,long>V;int r(char*s){char*p;for(long c;*s;s=p){p=strpbrk(s,"^<?!");c=*p-60;*p++=0;!c?[s](auto&p){char*e=p,c=0;for(;*e-62|c;e++)c+=*e-62?*e==60:-1;for(*e++=0;V[s];r(strdup(p)))V[s]--;p=e;}(p),0:c+27?c-3?c-34||V[s]++:scanf("%llu",&V[s]):printf("%llu",V[s]);}}

```

Try it online!

# Answer
> 0 votes
# Perl, 251 bytes

```
@p=split/([<>!?^])/,<>;for$c(0..$#p){$_=$p[$c];/</&&push@j,$c;if(/>/){$a=pop@j;$p[$c]=">$a";$p[$a]="<$c";}}while($c<$#p){$_=$p[$c];/\^/&&$v{$l}++;/!/&&print$v{$l};/\?/&&($v{$l}=<>);/<(\d+)/&&($v{$l}?$v{$l}--:($c=$1));/>(\d+)/&&($c=$1-2);$l=$_;$c++;}

```

Easier to read version:

```
# treat the first line of input as a program

# split on punctuation keywords; @p will contain the program as a list
# of tokens (including whitespace between adjacent punctuation)
@p = split /([<>!?^])/, <>;

# rewrite jump addresses

# the interpreter could scan backwards to avoid this, but that idea
# makes me feel dirty
for $c (0..$#p) {
    $_ = $p[$c];
    # save loop-start address on stack
    /</ && push @j, $c;
    if (/>/) {
        # if we encounter a loop-end instruction, rewrite it and the
        # corresponding loop-start to include the address (of the
        # instruction---jumps have to offset from this)
        $a = pop @j;
        $p[$c] = ">$a";
        $p[$a] = "<$c";
    }
}

# execute the program

# our program is already in @p

# $c will contain our program counter

# $l will contain the name of the last-referenced variable

while ($c < $#p) {
    # move current instruction into $_ for shorter matching
    $_ = $p[$c];

    # increment instruction
    /\^/ && $v{$l}++;

    # output instruction
    /!/ && print $v{$l};

    # input instruction
    /\?/ && ($v{$l} = <>);

    # loop start, including address
    /<(\d+)/ && ($v{$l} ? $v{$l}-- : ($c = $1));

    # loop end, including address
    />(\d+)/ && ($c = $1-2);

    # copy current instruction into "last variable name"---this will
    # sometimes contain operators, but we have null-string
    # instructions between adjacent operators, so it'll be fine
    $l = $_;

    # advance the program counter
    $c++;
}

```

This wastes a bunch of bytes fixing up loops to be direct jumps, but scanning backwards for the loop start offended my sense of aesthetics.

---
Tags: code-golf, interpreter
---


title: Compress an image to a 4 KiB preview

text:
# Question
Title: Compress an image to a 4 KiB preview
In this challenge you will be creating an image preview compression algorithm. It's goal is to reduce an arbitrary image file to a 4 KiB preview image, that can be used to quickly identify images with very little bandwidth.

You must write two programs (or one combined program): a compressor and a decompressor. Both must take a file or stdin as input, and output to a file or stdout. The compressor must accept one image in a mainstream lossless image format of choice (e.g. PNG, BMP, PPM), and output a file **of at most 4096 bytes**. The decompressor must accept any file generated by the compressor, and output an image as close as possible to the input. Note that there is no source code size limit for the encoder/decoder, so you can be creative in your algorithm.

Restrictions:

* No 'cheating'. Your programs may not use hidden inputs, storing data on the internet, etc. You are also forbidden from including features / data pertaining only to the set of scoring images.
* For libraries / tools / built-ins you **are** allowed to use *generic* image processing operations (scaling, blurring, color space transformation, etc), but **not** image decoding / encoding / compression operations (except for compressor input and decompressor output). Generic compression / decompression is also **disallowed**. It is intended that you implement your own compression for this challenge.
* The dimensions of the image output by the decompressor must exactly match those of the original file given to the compressor. You may assume that the image dimensions do not exceed 216 in either direction.
* Your compressor must run on an average consumer PC in under 5 minutes, and the decompressor must run in under 10 seconds for any image in the set below.

## Scoring

To help quick verification and visual comparison, **please include a lossless image album of the test corpus after compression using your answer.**

Your compressor will be tested using the following corpus of images:

You can download all images in a zip file here.

Your score will be the average structural similarity index for your compressor on all the images. We will be using the open source `dssim` for this challenge. It is easily built from source, or if you're on Ubuntu it also has a PPA. It is preferred if you score your own answer, but if you do not know how to build C applications and you do not run Debian/Ubuntu, you can let someone else score for you. `dssim` expects input/output in PNG, so convert your output to PNG first if you output in a different format.

To make scoring painless, here's a quick helper Python script, usage `python score.py corpus_dir compressed_dir`:

```
import glob, sys, os, subprocess

scores = []
for img in sorted(os.listdir(sys.argv[1])):
    ref, preview = (os.path.join(sys.argv[i], img) for i in (1, 2))
    sys.stdout.write("Comparing {} to {}... ".format(ref, preview))
    out = subprocess.check_output(["dssim", ref, preview]).decode("utf-8").split()[0]
    print(out)
    scores.append(float(out))

print("Average score: {:.6f}".format(sum(scores) / len(scores)))

```

---

Lowest score wins.

# Answer
> 8 votes
## Python with PIL, score 0.094218

Compressor:

```
#!/usr/bin/env python
from __future__ import division
import sys, traceback, os
from PIL import Image
from fractions import Fraction
import time, io

def image_bytes(img, scale):
    w,h = [int(dim*scale) for dim in img.size]
    bio = io.BytesIO()
    img.resize((w,h), Image.LANCZOS).save(bio, format='PPM')
    return len(bio.getvalue())

def compress(img):
    w,h = img.size
    w1,w2 = w // 256, w % 256
    h1,h2 = h // 256, h % 256
    n = w*h
    total_size = 4*1024 - 8 #4 KiB minus 8 bytes for
                            # original and new sizes
    #beginning guess for the optimal scaling
    scale = Fraction(total_size, image_bytes(img, 1))
    #now we do a binary search for the optimal dimensions,
    # with the restriction that we maintain the scale factor
    low,high = Fraction(0),Fraction(1)
    best = None
    start_time = time.time()
    iter_count = 0
    while iter_count < 100: #scientifically chosen, not arbitrary at all
        #make sure we don't take longer than 5 minutes for the whole program
        #10 seconds is more than reasonable for the loading/saving
        if time.time() - start_time >= 5*60-10:
            break
        size = image_bytes(img, scale)
        if size > total_size:
            high = scale
        elif size < total_size:
            low = scale
            if best is None or total_size-size < best[1]:
                best = (scale, total_size-size)
        else:
            break
        scale = (low+high)/2
        iter_count += 1
    w_new, h_new = [int(dim*best[0]) for dim in (w,h)]
    wn1,wn2 = w_new // 256, w_new % 256
    hn1, hn2 = h_new // 256, h_new % 256
    i_new = img.resize((w_new, h_new), Image.LANCZOS)
    bio = io.BytesIO()
    i_new.save(bio, format='PPM')
    return ''.join(map(chr, (w1,w2,h1,h2,wn1,wn2,hn1,hn2))) + bio.getvalue()

if __name__ == '__main__':
    for f in sorted(os.listdir(sys.argv[1])):
        try:
            print("Compressing {}".format(f))
            with Image.open(os.path.join(sys.argv[1],f)) as img:
                with open(os.path.join(sys.argv[2], f), 'wb') as out:
                    out.write(compress(img.convert(mode='RGB')))
        except:
            print("Exception with {}".format(f))
            traceback.print_exc()
            continue

```

Decompressor:

```
#!/usr/bin/env python
from __future__ import division
import sys, traceback, os
from PIL import Image
from fractions import Fraction
import io

def process_rect(rect):
    return rect

def decompress(compressed):
    w1,w2,h1,h2,wn1,wn2,hn1,hn2 = map(ord, compressed[:8])
    w,h = (w1*256+w2, h1*256+h2)
    wc, hc = (wn1*256+wn2, hn1*256+hn2)
    img_bytes = compressed[8:]
    bio = io.BytesIO(img_bytes)
    img = Image.open(bio)
    return img.resize((w,h), Image.LANCZOS)

if __name__ == '__main__':
    for f in sorted(os.listdir(sys.argv[1])):
        try:
            print("Decompressing {}".format(f))
            with open(os.path.join(sys.argv[1],f), 'rb') as img:
                decompress(img.read()).save(os.path.join(sys.argv[2],f))
        except:
            print("Exception with {}".format(f))
            traceback.print_exc()
            continue

```

Both scripts take input via command line arguments, as two directories (input and output), and convert all images in the input directory.

The idea is to find a size that fits under 4 KiB and has the same aspect ratio as the original, and use a Lanczos filter to get as high of a quality out of the downsampled image as possible.

Imgur album of compressed images, after resizing to original dimensions

Scoring script output:

```
Comparing corpus/1 - starry.png to test/1 - starry.png... 0.159444
Comparing corpus/2 - source.png to test/2 - source.png... 0.103666
Comparing corpus/3 - room.png to test/3 - room.png... 0.065547
Comparing corpus/4 - rainbow.png to test/4 - rainbow.png... 0.001020
Comparing corpus/5 - margin.png to test/5 - margin.png... 0.282746
Comparing corpus/6 - llama.png to test/6 - llama.png... 0.057997
Comparing corpus/7 - kid.png to test/7 - kid.png... 0.061476
Comparing corpus/8 - julia.png to test/8 - julia.png... 0.021848
Average score: 0.094218

```

# Answer
> 7 votes
## Java (vanilla, should work with java 1.5+), score 0.672

It does not generate particularly good dssim scores but, to my eye it produces more human friendly images...

Album: https://i.stack.imgur.com/ZU3hc.jpg

Scoring script output:

```
Comparing corpus/1 - starry.png to test/1 - starry.png... 2.3521
Comparing corpus/2 - source.png to test/2 - source.png... 1.738
Comparing corpus/3 - room.png to test/3 - room.png... 0.1829
Comparing corpus/4 - rainbow.png to test/4 - rainbow.png... 0.0633
Comparing corpus/5 - margin.png to test/5 - margin.png... 0.4224
Comparing corpus/6 - llama.png to test/6 - llama.png... 0.204
Comparing corpus/7 - kid.png to test/7 - kid.png... 0.36335
Comparing corpus/8 - julia.png to test/8 - julia.png... 0.05
Average score: 0.672

```

The compression chain:

```
1. if filter data has already been generated goto step 6
2. create sample images from random shapes and colours
3. take sample patches from these sample images
4. perform k-clustering of patches based on similarity of luminosity and chomanosity.
5. generate similarity ordered lists for each patch as compared to the other patches.
6. read in image
7. reduce image size to current multiplier * blocksize
8. iterate over image comparing each blocksize block against the list of clustered luminosity patches and chromanosity patches, selecting the closest match
9. output the index of the closet match from the similarity ordered list (of the previous block) (repeat 8 for chromanosity)
10. perform entropy encoding using deflate.
11. if output size is < 4096 bytes then increment current multiplier and repeat step 7
12. write previous output to disk.

```

To decompress, inflate and then read the block indexes and output the corresponding patch to the output file, then resize to the original dimensions.

Unfortunately the code is too large for stackoverflow so can be found at https://gist.github.com/anonymous/989ab8a1bb6ec14f6ea9

To run:

```
Usage:
       For single image compression: java CompressAnImageToA4kibPreview -c <INPUT IMAGE> [<COMPRESSED IMAGE>]
       For multiple image compression: java CompressAnImageToA4kibPreview -c <INPUT IMAGES DIR> [<COMPRESSED IMAGE DIR>]
       For single image decompression: java CompressAnImageToA4kibPreview -d <COMPRESSED IMAGE> [<DECOMPRESSED IMAGE>
       For multiple image decompression: java CompressAnImageToA4kibPreview -d <COMPRESSED IMAGE DIR> [<DECOMPRESSED IMAGES DIR>]

If optional parameters are not set then defaults will be used:
       For single image compression, compressed image will be created in same directory are input image and have '.compressed' file extension.
       For multiple image compression, compressed images will be created in a new 'out' sub directory of <INPUT IMAGES DIR> and have '.compressed' file extensions.
       For single image decompression, decompressed image will be created in same directory are input image and have '.out.png' file extension.
       For multiple image decompression, decompressed images will be created a new 'out' sub directory of <COMPRESSED IMAGE DIR> and have '.png' file extensions.

```

The first time this application is run, required files will be generated and saved in a directory relative to execution working dir. This may take a few minutes. For subsequent executions, this step will not need to be performed.

---
Tags: code-challenge, image-processing, compression
---


title: Where does the spaceship go?

text:
# Question
Title: Where does the spaceship go?
*Based on an idea suggested by Zgarb.*

A spaceship is moving around a regular 3D grid. The cells of the grid are indexed with integers in a right-handed coordinate system, *xyz*. The spaceship starts at the origin, pointing along the positive *x* axis, with the positive *z* axis pointing upwards.

The spaceship will fly along a trajectory defined by a non-empty sequence of movements. Each movement is either `F`(orward) which makes the spaceship move one cell in the direction its facing, or one of the six rotations `UDLRlr`. These corresponds to pitch, yaw and roll as follows:

Thanks to Zgarb for creating the diagram.

* `U`p and `D`own change the pitch of the spaceship by 90 degrees (where the direction corresponds to the movement of the spaceship's nose).
* `L`eft and `R`ight change the yaw of the spaceship by 90 degrees. They are just regular left and right turns.
* `l`eft and `r`ight are 90 degree rolling movements, where the direction indicates which wing moves downwards.

Note that these should always be interpreted relative to the spaceship so the relevant axes rotate along with it.

In mathematical terms, the spaceship is initially at position `(0, 0, 0)`, pointing along the `(1, 0, 0)` vector, with `(0, 0, 1)` pointing upwards. The rotations correspond to the following matrices applied to the coordinate system:

```
U = ( 0  0 -1     D = ( 0  0  1
      0  1  0           0  1  0
      1  0  0 )        -1  0  0 )

L = ( 0 -1  0     R = ( 0  1  0
      1  0  0          -1  0  0
      0  0  1 )         0  0  1 )

l = ( 1  0  0     r = ( 1  0  0
      0  0  1           0  0 -1
      0 -1  0 )         0  1  0 )

```

You should output the final position of the spaceship as three integers *x*, *y*, *z*. Output may be three separate integers or a list or string containing them. They may be in any consistent order as long as you specify it.

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.

Standard rules apply.

## Test Cases

```
F                                                   => (1, 0, 0)
FDDF                                                => (0, 0, 0)
FDDDF                                               => (1, 0, 1)
LrDDlURRrr                                          => (0, 0, 0)
UFLrRFLRLR                                          => (1, 0, 1)
FFrlFULULF                                          => (3, 0, -1)
LLFRLFDFFD                                          => (-2, 0, -2)
FrrLFLFrDLRFrLLFrFrRRFFFLRlFFLFFRFFLFlFFFlUFDFDrFF  => (1, 5, 7)
FUrRLDDlUDDlFlFFFDFrDrLrlUUrFlFFllRLlLlFFLrUFlRlFF  => (8, 2, 2)
FFLrlFLRFFFRFrFFFRFFRrFFFDDLFFURlrRFFFlrRFFlDlFFFU  => (1, 2, -2)
FLULFLFDURDUFFFLUlFlUFLFRrlDRFFFLFUFrFllFULUFFDRFF  => (-3, -2, -3)

```

## Worked example

Here are the intermediate steps of the `UFLrRFLRLR` test case. Here, all intermediate coordinates and direction vectors are given in the initial, global coordinate system (as opposed to one local to the spaceship):

```
Cmd.  Position    Forward     Up
      ( 0, 0, 0)  ( 1, 0, 0)  ( 0, 0, 1)
U     ( 0, 0, 0)  ( 0, 0, 1)  (-1, 0, 0)
F     ( 0, 0, 1)  ( 0, 0, 1)  (-1, 0, 0)
L     ( 0, 0, 1)  ( 0, 1, 0)  (-1, 0, 0)
r     ( 0, 0, 1)  ( 0, 1, 0)  ( 0, 0, 1)
R     ( 0, 0, 1)  ( 1, 0, 0)  ( 0, 0, 1)
F     ( 1, 0, 1)  ( 1, 0, 0)  ( 0, 0, 1)
L     ( 1, 0, 1)  ( 0, 1, 0)  ( 0, 0, 1)
R     ( 1, 0, 1)  ( 1, 0, 0)  ( 0, 0, 1)
L     ( 1, 0, 1)  ( 0, 1, 0)  ( 0, 0, 1)
R     ( 1, 0, 1)  ( 1, 0, 0)  ( 0, 0, 1)

```

# Answer
# MATL, ~~76~~ 75 bytes

```
FFF!3Xyj"FFT_FTFv4BvtFT_YStTF_YS3:"3$y!]6$Xh@'ULlDRr'4#mt?X)Y*}xxt1Z)b+w]]x

```

This works in current version (12.1.1) of the language.

*Edit (April 4, 2016): The behaviour of function `v` has changed in release 15.0.0 of the language. To make the above code run, remove the first `v` and replace the second `3$v`. The following link includes this modification.*

**Try it online**!

### Explanation

The state of the ship can be described in terms of two variables:

* position: 3x1 vector
* orientation: 3x3 matrix with the *accumulated* rotation, where "accumulated" means repeated matrix product.

A third variable would be the direction in which the ship is facing, but that's not needed, because it can be obtained as the initial direction (column vector \[`1;0;0]`) times the current orientation; that is, the first column of the orientation.

These two state variables are kept on the stack, and are updated with each letter. Each of the letters `ULlDRr` multiplies the orientation matrix by one of the six rotation matrices to update the orientation. Letter `F` adds the current position plus the first column of the orientation matrix.

The six rotation matrices are created as follows: first is introduced directly; second and third are circular shifts of the previous one; and the remaining three are transposed versions of the others.

```
FFF!             % 3x1 vector [0;0;0]: initial position
3Xy              % 3x3 identity matrix: initial orientation
j                % input string
"                % for-each character in that string
  FFT_FTFv4Bv    %   rotation matrix for U: defined directly
  tFT_YS         %   rotation matrix for L: U circularly shifted to the left
  tTF_YS         %   rotation matrix for l: L circularly shifted down
  3:"            %   repeat three times
    3$y!         %     copy third matrix from top and transpose
  ]              %   end loop. This creates rotation matrices for D, R, r
  6$Xh           %   pack the 6 matrices in a cell array
  @              %   push current character from the input string
  'ULlDRr'4#m    %   this gives an index 0 for F, 1 for U, 2 for L, ..., 6 for r
  t?             %   if non-zero: update orientation
    X)           %     pick corresponding rotation matrix
    Y*           %     matrix product
  }              %   else: update position
    xx           %     delete twice (index and rotation matrix are not used here)
    t1Z)         %     duplicate orientation matrix and take its first column
    b+           %     move position vector to top and add
    w            %     swap the two top-most elements in stack
  ]              %   end if
]                % end for-each
x                % delete orientation matrix
                 % implicitly display position vector

```
> 3 votes

# Answer
# Octave, 175 bytes

```
function p=s(i)m.U=[0,0,-1;0,1,0;1,0,0];m.D=m.U';m.L=[0,-1,0;1,0,0;0,0,1];m.R=m.L';m.l=flip(flip(m.L),2);m.r=m.l';a=m.F=eye(3);p=[0;0;0];for c=i p+=(a*=m.(c))*[c=='F';0;0];end

```

Readable version:

```
function p=s(i)
  m.U=[0,0,-1;0,1,0;1,0,0];
  m.D=m.U';
  m.L=[0,-1,0;1,0,0;0,0,1];
  m.R=m.L';
  m.l=flip(flip(m.L),2);
  m.r=m.l';
  a=m.F=eye(3);
  p=[0;0;0];
  for c=i p+=(a*=m.(c))*[c=='F';0;0];
end

```
> 1 votes

# Answer
## ES6, ~~265~~ 259 bytes

```
s=>[...s.replace(/F/g,"f$`s")].reverse().map(e=>d={U:(x,y,z)=>[-z,y,x],D:(x,y,z)=>[z,y,-x],L:(x,y,z)=>[-y,x,z],R:(x,y,z)=>[y,-x,z],r:(x,y,z)=>[x,-z,y],l:(x,y,z)=>[x,z,-y],F:(...d)=>d,f:(x,y,z)=>[a+=x,b+=y,c+=z]),s:_=>[1,0,0]}[e](...d),d=[1,0,a=b=c=0])&&[a,b,c]

```

Explanation: Normally to calculate the direction of the spaceship you would compose all the rotations together, and then for each move you would compose the result to the unit vector `F = (1, 0, 0)` (or more simply extract the first column of the matrix). For instance, `FFrlFULULF => F + F + r⋅l⋅F + r⋅l⋅U⋅L⋅L⋅L⋅F`. Since matrix multiplication is associative, languages with built-in matrix multiplication can obviously compute the partial product `r⋅l⋅U⋅L⋅L⋅L` as they go along, multiplying by `F` as necessary to produce the terms that are then added together. Unfortunately I don't have that luxury, so the cheapest option is to compute each term in the above expression separately, starting with `F` and working back. For that, I need a list for each of the occurrences of `F` of all the rotations up to that point. I do this using `replace` with `$`` so I also need to mark the start and end of each term in the list so that I can ignore the rest of the string. Slightly ungolfed:

```
s=>[... // split the string into separate operations
    s.replace(/F/g,"f$`s")] // For each 'F', wrap the operations up to that point
  .reverse() // Play all the operations in reverse order
  .map(e=>d= // Update the direction for each operation
    { // set of operations
      U:(x,y,z)=>[-z,y,x], // Up
      D:(x,y,z)=>[z,y,-x], // Down
      L:(x,y,z)=>[-y,x,z], // Left turn
      R:(x,y,z)=>[y,-x,z], // Right turn
      r:(x,y,z)=>[x,-z,y], // right roll
      l:(x,y,z)=>[x,z,-y], // left roll
      F:(...d)=>d, // does nothing, `s` and `f` do the work now
      f:(x,y,z)=>[a+=x,b+=y,c+=z], // do the move
      s:_=>[1,0,0] // back to start
    }[e](...d), // apply the operation to the current direction
    d=[1,0,a=b=c=0] // initialise variables
  )&&[a,b,c] // return result

```
> 0 votes

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


title: Connect the Dots

text:
# Question
Title: Connect the Dots
Given a series of `o`s representing dots, connect them vertically or horizontally

## Examples

Input:

```
o   o

o

```

Output:

```
o---o
|
|
o

```

---

Input:

```
o   o    o

    o

```

Output:

```
o---o----o
    |
    o

```

## Spec

* If you want the input padded with spaces to form a rectangle, please specify this in your answer
* There will only be `o`, spaces, and newlines in the input
* There will always be a pair of dots to connect
* No two `o`s will be directly adjacent
* Dots should be connected with `|` and `-`, for vertical and horizontal connections respectively
* No dot connections will overlap

# Answer
> 2 votes
# Japt, ~~33~~ 29 bytes

```
Uy eV="o +o"_rS'|} y eV,_rS'-

```

Test it online!

### How it works

```
Uy         // Transpose rows with columns in the input.
eV="o +o"  // Set V to the regex-string "o +o", and recursively replace each match Z with:
_rS'|}     //  Z with spaces replaced with "|"s.
y          // Transpose again.
eV,        // Recursively replace matches Z of V with:
_rS'-      //  Z with spaces replaced with "-"s.

```

# Answer
> 2 votes
## Ruby, ~~137~~ 133 bytes

```
->s{eval"s.split($/).map(&:chars)#{".map{|x|x.join.gsub(/o +(?=o)/){|x|x.tr' ',?|}.chars}.transpose"*2}.map(&:join)*$/".sub'?|','?-'}

```

This is absolutely horrible. Still trying to golf.

Input as a padded rectangle, please.

Newline for "readability":

```
eval"s.split($/).map(&:chars)#{".map{|x|x.join.gsub(/o +(?=o)/){|x|x.tr' ',?|}
.chars}.transpose"*2}.map(&:join)*$/".sub'?|','?-'

```

# Answer
> 2 votes
## Retina, 80 bytes

```
T` `-`o.+o
Tm` `|`(?<=(?(1)!)^(?<-1>.)*o\D*¶(.)*) (?=(.)*¶\D*o(?<-2>.)*$(?(2)!))

```

Input needs to be padded.

Try it online!

### Explanation

The first stage is pretty simple, it just turns all spaces into hyphens which are found between two `o`s in the same line.

The second stage covers the `|`s. This is a bit trickier and requires balancing groups. The lookbehind

```
(?<=(?(1)!)^(?<-1>.)*o\D*¶(.)*)

```

checks that there's an `o` earlier in the same column. Remember that lookbehinds should be read from right to left. `(.)*` stores the horizontal position of match, `\D*¶` checks skips to any character in the preceding lines, `o` matches literally. Then `(?(1)!)^(?<-1>.)*` ensures that the horizontal position of that `o` is the same.

The lookahead

```
(?=(.)*¶\D*o(?<-2>.)*$(?(2)!))

```

Does exactly the same thing in the opposite direction.

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


title: A register calculator challenge

text:
# Question
Title: A register calculator challenge
# A simple register calculator

This challenge involve a simple register calculator that works in the following way:

* It has some registers named `A,B,C,...,Z`, each of them can contain an integer, they are all initialized to `0`.
* It executes instructions of 3 characters: The first character of any instruction is one of `+,-,*,/,=` (add, subtract, multiple, divide, copy), the second character is the name of a register, and the third character is the name of a register or one of `0,1`. The meaning of the instruction should be quite clear, here some examples:

+ `+AB` means "set the value of the register `A` to the result of `A + B`", and similarly for `-AB,*AB,/AB`. The division `A / B` is done as in C.
    + `+A1` means "increment the register `A` of `1`", and similarly `-A1` decrements `A` of `1`.
    + `=AB` means "copy the value of `B` into the register `A`, similarly `=A0`, `=A1` sets `A` to `0`, `1`, respectively.
* It takes as input a string of consecutive instructions and it returns the result of the last operation, some examples:
    + Given `=A1+A1*AA` it returns `4`.
    + Given `+A1+A1=BA+A1*AB` it returns `6`.
    + Given `+A1+A1+A1*AA=BA-B1*AB` it returns `72`.

It is easy to write such a calculator in your preferred programming language, here an example in Python:

```
def compute(cmd):

    opr = {"=": lambda x, y: y, "+": lambda x, y: x + y, "-": lambda x, y: x - y, "*": lambda x, y: x * y, "/": lambda x, y: x / y}
    reg = {"0": 0, "1": 1, "A": 0, "B": 0, "C": 0, "D": 0, "E": 0}
    ans = 0
    i = 0

    while i < len(cmd):
        op = cmd[i]
        r1 = cmd[i + 1]
        r2 = cmd[i + 2]
        reg[r1] = ans = opr[op](reg[r1], reg[r2])
        i += 3

    return ans

```

# The challenge

Write a program in any programming language that takes as input a positive integer `n` and returns a string of instructions that the calculator described above evaluates to `n`. For example, given `n = 13` a valid output for your program could be `+A1+A1+A1=BA+A1*AB+A1`. There are some restrictions:

* Standard loopholes are forbidden.
* The source code of your program should not exceed 1024 characters.

# How to compute your score

Run you program on each of the following 1000 random integers and sum the total number of operations in each output. For example, `+A1+A1+A1=BA+A1*AB+A1` consists of 6 operations, note that the copy instructions `=` are NOT operations and you should not count them.

```
3188162812
3079442899
158430004
2089722113
3944389294
2802537149
3129608769
4053661027
2693369839
420032325
2729183065
4214788755
680331489
3855285400
4233942695
4206707987
2357544216
457437107
2974352205
3469310180
3552518730
4140980518
2392819110
2329818200
662019831
2841907484
1321812679
2853902004
2272319460
133347800
1692505604
2767466592
3203294911
1179098253
2394040393
2013833391
3329723817
977510821
2383911994
1590560980
2045601180
1324377359
1586351765
1604998703
3016672003
3653230539
1466084071
2746018834
1056296425
3225491666
2113040185
918062749
3506683080
1809626346
3615092363
3944952222
4281084843
137951018
577820737
2304235902
4143433212
3183457224
294693306
1680134139
689588309
3657258008
2664563483
628899295
886528255
2539006585
2767153496
2742374091
2927873610
3725967307
2252643563
2716697503
1098010781
895335331
305272851
2605870648
3473538459
2739664556
2127000353
1774191919
3239195523
3120846790
3239808174
2588745068
3363081711
3105613110
3443977876
3233369379
949558184
2159450658
2930876206
1714955144
712790171
2472327763
3524210951
24655707
754856403
3220292764
708275816
2369186737
2485130017
404438291
1444836457
3936354990
3488645083
3881548856
1385884481
3750970390
1355492018
4246667593
791749996
1768738344
4014670055
3594141439
3111942631
2763557857
250495911
1635747286
1397550167
35044748
826650975
1249876417
2756572453
2014910140
1934230545
3893965263
1921703452
3479225211
232639352
1205471850
3147410912
4161504178
3896565097
336993337
898565456
1377983619
627866260
2972370545
2867339047
1517056183
3113779980
3650970589
105184832
3785364530
1892053898
2844419064
3581584776
773357885
1635965442
579795505
1082737975
4177210361
33726403
500010881
3770114942
1949554222
1808394144
2552929558
1679344177
4127951276
3703470385
2167661112
2012330972
3330988942
1625024662
4028645080
2268576559
1122753547
2801157103
2297468355
1248325165
3040195088
1505917132
1975920989
1331044994
1060195583
4053434779
1711909914
4165818150
1144987338
2582851730
159607843
4224173218
1122473605
4137009351
1859108466
140046799
3608276151
3755161872
1715239079
2210528921
4149673364
1683676925
3555426962
1903470380
1647594563
3992028616
831939758
1940233614
616234640
1033981562
989110726
3308560842
1362495884
2271865210
2497232294
2166547324
3134965769
1407359056
184303653
876724554
2257276636
1339263453
1505646879
4103125312
602341088
3411146479
4076735898
988798982
2881621101
3835638677
350262003
2083944362
793689959
1796614310
1722728365
1419496784
311460422
988078714
1191131280
685548336
2073528073
1341976830
1380421367
854492684
2349152
2760841279
3512440862
3492462961
955419776
134666263
1515743147
2802649615
343970838
5900423
3640581071
3690344254
33097513
3453017483
2702390881
2881748921
488817210
3179354661
3029418544
70044411
1956963103
1138956191
4099413570
113469500
2905850103
2267006431
990605747
2016466413
1406729175
457735529
1987564886
2555785209
2550678495
1324710456
1215784300
717815828
1894258881
2929394992
2793836849
1428923741
633224565
3516183531
221895161
2798935778
517240774
1906654368
3577752510
1412213936
978042011
741638677
1565247138
2333064112
2549498124
212184199
1539484727
3421514248
1918972072
933315257
1744663538
3834248593
1024107659
112895438
3354823598
3126205726
375723484
2105901209
287450971
669099946
1397558632
2606373532
125689337
3717502670
3258204174
1650199158
600374361
368452551
3686684007
3030953879
492919617
1203996049
863919924
2155962926
2878874316
1081637213
4025621502
969421830
906800845
732593812
3705231669
100350106
2062905253
2394749290
1537677769
2230238191
447840016
1442872240
2024556139
3023217942
4009927781
643221137
1779666873
3953330513
2024171749
795922137
997876381
1924314655
1177794352
3951978155
2649627557
1497778499
1718873438
1921453568
1327068832
2832829727
2225364583
1476350090
2647770592
3820786287
916013620
3982837983
3614316518
308109070
1800544679
2981621084
1428321980
4050055605
1492289670
2386916424
3191268731
580405899
2267245329
1732073940
1096029767
1295821464
3364564864
2652920150
3364522304
488005592
2192878399
160846995
218793067
300953008
3159368600
3645636269
2691580186
827223351
3050975392
1465133880
1478016997
1719998613
652363401
2555898614
4066532621
1765212455
34216921
1638964775
1371429240
838490470
82423487
1714800592
3494875381
3873346547
4054782046
3696936256
4275305812
2168667803
4160190912
3795501892
1459579204
3788779072
265527890
854488955
2942834006
2379627823
518232762
518434777
3944651255
3797616526
3707541025
322349517
474725696
3644506417
298197509
2568152353
2590844880
3117635513
1074315194
4084685556
2962342284
2653600388
3288534723
3794138452
1647860359
4009971876
2133083710
3370033103
47844084
1104447774
1945114365
3574343235
3780282459
3381199373
1018537272
1382098367
1412005134
1344062628
2346644176
722899092
2614932463
2145401890
827890946
255045026
1886847183
2717637818
1153049445
1367369036
2426902133
1836600086
3249356599
3406700718
2782602517
805660530
2582980208
2668716587
1318623475
3718765477
3906582528
2049615170
2266673144
693017899
1850804437
3662076224
1439399599
3609671497
3521926429
661675539
3211764017
3849411286
3961495122
3240515755
3110520252
3247223395
2601642984
531083777
1428656097
2621375427
1425006097
3346815151
1736182994
2749088925
3828456894
522766581
1596198864
1089234568
516631143
1714958540
550383692
2205580129
1129010921
2855807192
843448099
2537619198
2817077189
1862738454
1292393032
1867270512
3245153467
1330535377
63085178
476740794
3784629223
1469948976
2840691011
1501561593
2222500334
1417999206
1501666518
1146520258
853475958
688318779
2212745726
3697365636
4188412866
1971070414
2765322323
3338736319
4106229372
3547088973
3610171853
417218792
2645989082
2625322695
3788226977
866881900
3042410163
3339075441
1434921464
2037891551
4265507318
1488099724
573885128
528293886
863928770
2214944781
3913280213
3752689511
3519398632
549671367
662190591
3578320334
1609736323
1920189717
2049295962
1680309555
3056307661
237881083
1746281815
3988208157
2505692550
533953235
3859868829
3792904168
3181176191
764556169
78617399
3222196435
2366977555
608590681
303423450
559903926
1444205960
2795852572
3461738581
2509323146
2734638697
118860267
1918139288
2567665860
2153622033
3097512138
4224583193
1308314884
1348993134
3573313872
80532767
373807250
3963872687
1414605355
1390608957
1438723366
3335250816
3812365414
1257060108
1155935111
2101397457
1834783042
1751275025
1697354321
2932378401
1665717453
1378885897
3863913849
169333097
1073827664
777437131
3466174585
4046814722
2525749031
2116514103
2240001267
3455152569
579339098
2014028365
3808320943
1577950380
2691778801
3752766002
3849855789
1537004930
384431257
2179992010
36153591
4192751001
1804838630
987326618
4149586235
2231006803
3583701679
820347619
316668661
709355791
3570998394
1949820944
2602827205
4168457060
4281494037
3371936535
2794977651
2859282911
3673967898
13357998
1321990240
1432920498
2348123485
205633677
1467790392
3366396640
382875586
3791338683
478208002
2728443830
2837394277
3723656578
289818980
3607540282
1775363546
2183739548
4177115501
775276465
1690545788
1075449013
572714464
2769169223
3277515030
3206017211
763710358
2535539628
538656028
1428522787
2412864965
2447537924
3399886379
1955069748
73813115
2985639257
3129134081
2902917098
3832348869
2446124823
1520308572
2779582451
3152572003
284626848
2622927684
2243844449
2707184379
3996077339
1143205932
4249437886
4013946423
1243498130
2239561716
2454002725
3202102404
3489290520
568827898
2077682453
1973647425
2311090024
3452693414
566624799
1905493748
3381640023
3228957600
2097911855
3346084948
2492783447
2933529940
2933060277
509789087
4110089257
2789615392
2293641703
3346767700
2861425094
1325878754
2100601638
3154735442
1589556635
543727545
2077077585
2301440962
3562819978
3678224450
88375847
2286883432
810549767
4111034512
672827645
3538058849
3243887391
4260719631
3878976366
1173949115
522599614
2237854030
3700071391
3701211843
2474968151
1856102230
1612779479
417924004
1408725257
3663088753
1092263738
373569884
1394203899
2687184291
2200173651
16483411
2144831293
1953173328
2680701575
1891347549
594615324
2941482356
1349499420
2341998425
3246298001
3915604073
2598997329
2742107968
1706515316
3230227853
1698480626
3171621896
3553701103
3699504403
3264436517
789435265
1540974002
76880268
2021546521
228600347
3120127535
855819397
913492933
1706352147
3824217844
4254086533
4210176230
247387836
3028729765
1294455673
832399118
1989368151
3843532893
4058042419
4176223654
1871853736
2245388136
3396787616
453433399
3628835268
13531968
1038657709
2005262423
409396841
3236752715
504051173
1284135365
1498489066
1951495621
785956452
979254655
1255744440
2124184282
1791931889
2785197261
941345859
2272057653
105734226
1038331147
3859502227
1364397134
1151431380
3572487724
3440271596
3567083908
3969594482
2717167268
2070800249
565656056
2585323347
3710407107
1655322191
2871691151
1578274901
925898023
98152205
2387892947
3688205134
1060122118
3601926463
3963544592
2836575178
3517776876
1116673438
4141604495
3702313624
3321374643
3027449932
446202974
2704262583
1454829930
310100992
4167677094
4283752410
3749990846
3082431927
3668805960
4197104147
2921050366
40497657
1198947069
4265036060
3094866761
732821358
3734577383
3582534668
1453076357
881135315
3444396361
3113501566
2961866531
3235889511
2927326630
151940017
498024918
427292182
4276572621
2573590608
901394328
2351057309
1560851771
836443396
702781140
4143407241
3833119244
1092986235
3835147739
2801574120
2220928350
2773965488
1092717858
2314157136
4281370255
1044194898
4056801311
2672327460
2464844936
2964067147
535238874
34767265
4052881906
277239886
3205998707
4168364957
3390679324
3154285793
3493261782
1364027732
633131904
2306043313
253100060
3085422190
1571296680
1116733249
517969149
2063982173
1580514293
2306636650
211667764
43257052
2187912911
1419556982
2885452390
475014467
4276725894
2112535198
1381468052
3535769995
3030340194
2554618335
701632787
3621637286
200999835
2299787216
148189901
476612087
3139125858
1721355976
2863292989
270189306
1574116759
4001329945
616943685
3636040393
1361384267
1959022335
122277322
2067861043
2294386020
1121565222
1844367203
3119120617
1420612680
1541302975
3197481918
648483752
451388069
856130175
2960393334
988907653
1730735603
1640257249
1832729474
306034410
853922102
2001624344
3253510094
3906676405
37452680
3779097581
1958179154
2395885855
800614078
2085912
3020166783
2260099399
3490922778
2459139074
3886269878
3341685647
1050712773
59317986
3041690572
3236133509
2401182200
1535265086
1663785422
3664887088
3252400434
377629836
1024996414
1518007563
1821746700
1231613438
1709191483
2422047361
1393454235
2346354546
3263498417
3321719966
3652825361
948364811
371026554
2175702095
1880788290
4214724129
503657540

```

The same list of numbers can also be found on Pastebin.

The lower your score is, the better it is. Good luck!

**NOTES:**

* I choose random integers between 0 and 2^32-1, so that computations could be performed in C (unsigned long) or other languages without native support for arbitrary sized integers. However, be careful of overflows!
* When computing your score, check also that the output of your program is correct, it's easy to make errors.
* I wrote a script of 512 characters that got a score of 27782.

# Answer
## Java, Total Score: 46009 operations

*Saved **2000** operations thanks to steveverrill and **1000** thanks to Bob!*

```
z->{String s=Integer.toBinaryString(z),r="=A1";for(int j=s.length()-1;j>=0;j--){if(s.charAt(j)=='1')r+="+CA";r+=j>0?"+AA":"";}return r;};

```

Test it with this full program:

```
public class Calculator {
    public static void main (String[] args) {
        A a = z->{String s=Integer.toBinaryString(z),r="=A1";for(int j=s.length()-1;j>=0;j--){if(s.charAt(j)=='1')r+="+CA";r+=j>0?"+AA":"";}return r;};
        System.out.println(A.a(117));
    }
    public interface A {
        void a(int c);
    }
}

```

Caculates the strings based on the binary representations of the input numbers. Score calculated with this program:

```
public class Calculator
{
    public static void main (String[] args) throws FileNotFoundException {
        FileInputStream is = new FileInputStream(new File("test.txt"));
        System.setIn(is);
        int c = 0;
        Scanner input = new Scanner (System.in);
        while (input.hasNext()) {
            c+=s(new Long(input.nextLine())).length()/3-3;
        }
        System.out.println(c);
    }

    public static String s(long z){String s=Long.toBinaryString(z),r="=A1";for(int j=s.length()-1;j>=0;j--){if(s.charAt(j)=='1')r+="+CA";r+=j>0?"+AA":"";}return r;}
}

```
> 3 votes

# Answer
Since the question got some votes, but only an answer was posted since so far, I post an answer (but not the 512 characters / 27782 score mentioned in the question).

# Python, Score: 35238

```
def f(n):
    cmd = "=B1=C1+C1+C1"
    while n > 0:
        r = n % 3
        n /= 3
        if r == 1:
            cmd += "+AB"
        if r == 2:
            cmd += "-AB"
            n += 1
        if n > 0:
            cmd += "*BC"
    return cmd

```

The idea is the same of GamrCorps's answer, but instead of using binary representation I used balanced ternary representation.

Why does it work better? Because a positive integer `n` has approximately `log(n)/log(2)` digits in base `2`, and on average half of them are `1`'s and the other half are `0`'s, hence about `(1/(2 log(2))) log(n) = 0.72... log(n)` instructions are required. In ternary balanced representation, `n` has about `log(n)/log(3)` digits, on average a third of them equal to `1`, and another third equal to `-1`, hence about `(2/(3 log(3))) log(n) = 0.60... log(n)` instructions are required.
> 1 votes

---
Tags: code-challenge, math
---