# Question
Title: Get list of badges on this site that nobody received yet
Make a code that gets list of badges that nobody received yet (for example, by using this website API for badges), and output the sorted list of such badges, with new line after each.

Example output (may be smaller, depending on when you do this challenge):

```
Archaeologist
Caucus
Constituent
Copy Editor
Deputy
Electorate
Epic
Generalist
Hacker
Legendary
Marshal
Outspoken
Research Assistant
Sheriff
Steward
Strunk & White
Tenacious
Unsung Hero

```

Smallest code wins.

# Answer
# JavaScript with jQuery (loaded onto SE sites by default), 58

```
$('.badge',$('.badge-count:not(:has(*))').parent()).text()

```

Must be run on https://codegolf.stackexchange.com/help/badges. ;)

Strictly conforming output, 116 chars:

```
[].join.call($('.badge',$('.badge-count:not(:has(*))').parent()).map(function(){return $(this).text()}).sort(),'\n')

```

Screenshot of console output (click to enlarge):
> 8 votes

# Answer
**Bash, 173 characters**

```
curl "https://api.stackexchange.com/2.1/badges?page="{0..50}"&pagesize=100&order=desc&sort=type&site=codegolf"|gunzip|grep -Po '{"name".*?award_count":0.*?}'|cut -d'"' -f 4

```

Though you could probably shave some characters off by using url shortening.

**WARNING:** Note that running this script a couple of times *will* result in this:

```
{"error_name":"throttle_violation","error_message":"too many requests from this IP, more requests available in 84495 seconds","error_id":502}

```

**Output for codegolf.SE:**

```
code-golf
Informed
Research Assistant
Caucus
Constituent
Outspoken
Deputy
Vox Populi
Excavator
Analytical
Self-Learner
Hacker
Beta
Legendary
Electorate
Investor
Tenacious
Unsung Hero

```

EDIT: tweaked it a bit.
> 6 votes

# Answer
# PHP - ~~92~~ 86 characters

```
<?=html_entity_decode(substr(file_get_contents("http://tinyurl.com/q9zlwfr"),12937,190));

```

Inspired by Victor's solution. Very volatile.
> 1 votes

# Answer
# Java - 280 267 260

```
class A{public static void main(String[]z)throws Exception{String s="";int y;java.io.InputStream x=new java.net.URL("http://tinyurl.com/q9zlwfr").openStream();while((y=x.read())!=-1)s+=(char)y;System.out.println(s.substring(12937,13126).replace("amp;",""));}}

```
> 0 votes

---
Tags: code-golf, stack-exchange-api
---


title: Portal Maze Shortest Path

text:
# Question
Title: Portal Maze Shortest Path
Your goal is to write a program that creates a random 10x10 map using `0`, `1`, and `2`, and finds the shortest path from top-left to bottom-right, assuming that:

**0** represents a grass field: anyone can walk on it;
**1** represents a wall: you cannot cross it;
**2** represents a portal: when entering a portal, you can move to any other portal in the map.

**Specs:**

* The top-left element and the bottom-right one must be **0**;
* When creating the random map, every field should have 60% chance of being a **0**, 30% of being a **1** and 10% of being a **2**;
* You can move in any adjacent field (even diagonal ones);
* Your program should output the map and the number of steps of the shortest path;
* If there isn't a valid path that leads to the bottom-right field, your program should output the map only;
* You can use any resource you'd like to;
* Shortest code wins.

**Calculating steps:**
A step is an actual movement; every time you change field, you increment the counter.

**Output:**

```
0000100200
0100100010
1000000111
0002001000
1111100020
0001111111
0001001000
0020001111
1100110000
0000020100

9

```

# Answer
> 3 votes
### GolfScript, 182 characters

```
;0`{41 3 10rand?/3%`}98*0`]10/n*n+.[12n*.]*.0{[`/(,\+{,)1$+}*;]}:K~\2K:P+${[.12=(]}%.,,{.{\1==}+2$\,{~;.P?0<!P*3,{10+}%1+{2$1$-\3$+}%+~}%`{2$~0<@@?-1>&2$[~;@)](\@if}++%}/-1=1=.0<{;}*

```

Examples:

```
0000001002
1010000001
0011010000
2001020000
0100100011
0110100000
0100000100
0010002010
0100110000
0012000210
6

0000100000
0100000001
1100000000
1011010000
0010001100
0101010200
0000200012
1100100110
0000011001
2201010000
11

0012010000
1000100122
0000001000
0111010100
0010012001
1020100110
1010101000
0102011111
0100100010
2102100110

```

# Answer
> 4 votes
# Mathematica (344)

Bonus: highlighting of the path

```
n = 10;
m = RandomChoice[{6, 3, 1} -> {0, 1, 2}, {n, n}];
m[[1, 1]] = m[[n, n]] = 0;

p = FindShortestPath[Graph@DeleteDuplicates@Join[Cases[#, Rule[{ij__}, {k_, l_}] /;
      0 < k <= n && 0 < l <= n && m[[ij]] != 1 && m[[k, l]] != 1] &@
   Flatten@Table[{i, j} -> {i, j} + d, {i, n}, {j, n}, {d, Tuples[{-1, 0, 1}, 2]}],
  Rule @@@ Tuples[Position[m, 2], 2]], {1, 1}, {n, n}];

Grid@MapAt[Style[#, Red] &, m, p]
If[# > 0, #-1] &@Length[p]

```

I create the graph of all possible movies to neighbor vertices and add all possible "teleports".

# Answer
> 4 votes
# Mathematica, ~~208~~ 202 chars

Base on David Carraher and ybeltukov's solutions. And thanks to ybeltukov's suggestion.

```
m=RandomChoice[{6,3,1}->{0,1,2},n={10,10}];m〚1,1〛=m〚10,10〛=0;Grid@m
{s,u}=m~Position~#&/@{0,2};If[#<∞,#]&@GraphDistance[Graph[{n/n,n},#<->#2&@@@Select[Subsets[s⋃u,{2}],Norm[#-#2]&@@#<2||#⋃u==u&]],n/n,n]

```

# Answer
> 2 votes
## Python 3, 279

Some Dijkstra variant. Ugly, but golfed as much as I could...

```
from random import*
R=range(10)
A={(i,j):choice([0,0,1]*3+[2])for i in R for j in R}
A[0,0]=A[9,9]=0
for y in R:print(*(A[x,y]for x in R))
S=[(0,0,0,0)]
for x,y,a,c in S:A[x,y]=1;x*y-81or print(c)+exit();S+=[(X,Y,b,c+1)for(X,Y),b in A.items()if a+b>3or~-b and-2<X-x<2and-2<Y-y<2]

```

**Sample Run**

```
0 1 1 1 0 0 1 0 1 0
0 0 0 1 0 1 0 1 0 0
0 1 2 1 2 1 0 0 1 0
0 1 0 1 0 0 0 0 0 1
0 1 0 1 0 0 1 0 0 1
0 0 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 1 0 1
1 0 0 1 0 0 1 1 1 0
0 0 0 0 1 0 0 0 0 1
0 1 2 1 0 1 1 0 0 0
10

```

# Answer
> 1 votes
# Python 3 (695)

```
import random as r
if __name__=='__main__':
    x=144
    g,t=[1]*x,[]
    p=lambda i:12<i<131 and 0<i%12<11
    for i in range(x):
        if p(i):
            v=r.random()
            g[i]=int((v<=0.6 or i in (13,130)) and .1 or v<=0.9 and 1 or 2)
            if g[i]>1:t+=[i]
            print(g[i],end='\n' if i%12==10 else '')
    d=[99]*x
    d[13]=0
    n = list(range(x))
    m = lambda i:[i-1,i+1,i-12,i+12,i-13,i+11,i+11,i+13]
    while n:
        v = min(n,key=lambda x:d[x])
        n.remove(v)
        for s in m(v)+(t if g[v]==2 else []):
            if p(s) and g[s]!=1 and d[v]+(g[s]+g[v]<4)<d[s]:
                d[s]=d[v]+(g[s]+g[v]<3)
    if d[130]<99:print('\n'+str(d[130]))

```

Dijkstra !

## Example output:

```
0000202000
2011000111
0000002000
0101001000
0000100110
1110100101
0020101000
0011200000
1010101010
0000001000

6

```

# Answer
> 1 votes
# Mathematica ~~316 279~~ 275

The basic object is a 10x10 array with approximately 60 0's, 30 1's and 10 2's. The array is used to modify a 10x10 `GridGraph`, with all edges connected. Those nodes which correspond to cells holding 1 in the array are removed from the graph. Those nodes "holding 2's" are all connected to each other. Then the Shortest Path is sought between vertex 1 and vertex 100. If such a path does not exist, the map is returned; if such a path does exist, the map and the shortest path length are shown.

```
m = Join[{0}, RandomChoice[{6, 3, 1} -> {0, 1, 2}, 98], {0}];
{s,t,u}=(Flatten@Position[m,#]&/@{0,1,2});
g=Graph@Union[EdgeList[VertexDelete[GridGraph@{10,10},t]],Subsets[u,{2}]
/.{a_,b_}:>a \[UndirectedEdge] b];
If[IntegerQ@GraphDistance[g,1,100],{w=Grid@Partition[m,10],
Length@FindShortestPath[g,1,100]-1},w]

```

**Sample Run**:

# Answer
> 0 votes
# Python (1923)

Backtracking Search

Admittedly not the shortest or the most efficient, although there is some memoization present.

```
import random
l = 10
map = [
    [(lambda i: 0 if i < 7 else 1 if i < 10 else 2)(random.randint(1, 10))
     for i in range(0, l)]
    for i in range(0, l)
    ]
map[0][0] = map[l-1][l-1] = 0
print "\n".join([" ".join([str(i) for i in x]) for x in map])

paths = {}
def step(past_path, x, y):
    shortest = float("inf")
    shortest_path = []

    current_path = past_path + [(x, y)]
    pos = map[x][y]
    if (x, y) != (0, 0):
        past_pos = map[past_path[-1][0]][past_path[-1][1]]

    if (((x, y) in paths or str(current_path) in paths)
        and (pos != 2 or past_pos == 2)):
        return paths[(x, y)]
    elif x == l-1 and y == l-1:
        return ([(x, y)], 1)

    if pos == 1:
        return (shortest_path, shortest)
    if pos == 2 and past_pos != 2:
        for i2 in range(0, l):
            for j2 in range(0, l):
                pos2 = map[i2][j2]
                if pos2 == 2 and (i2, j2) not in current_path:
                    path, dist = step(current_path, i2, j2)
                    if dist < shortest and (x, y) not in path:
                        shortest = dist
                        shortest_path = path
    else:
        for i in range(x - 1, x + 2):
            for j in range(y - 1, y + 2):
                if i in range(0, l) and j in range(0, l):
                    pos = map[i][j]
                    if pos in [0, 2] and (i, j) not in current_path:
                        path, dist = step(current_path, i, j)
                        if dist < shortest and (x, y) not in path:
                            shortest = dist
                            shortest_path = path
    dist = 1 + shortest
    path = [(x, y)] + shortest_path
    if dist != float("inf"):
        paths[(x, y)] = (path, dist)
    else:
        paths[str(current_path)] = (path, dist)
    return (path, dist)

p, d = step([], 0, 0)
if d != float("inf"):
    print p, d

```

# Answer
> 0 votes
# JavaScript (541)

```
z=10
l=[[0]]
p=[]
f=[[0]]
P=[]
for(i=0;++i<z;)l[i]=[],f[i]=[]
for(i=0;++i<99;)P[i]=0,l[i/z|0][i%z]=99,f[i/z|0][i%z]=(m=Math.random(),m<=.6?0:m<=.9?1:(p.push(i),2))
f[9][9]=0
l[9][9]=99
Q=[0]
for(o=Math.min;Q.length;){if(!P[s=Q.splice(0,1)[0]]){P[s]=1
for(i=-2;++i<2;)for(j=-2;++j<2;){a=i+s/z|0,b=j+s%z
if(!(a<0||a>9||b<0||b>9)){q=l[a][b]=o(l[s/z|0][s%z]+1,l[a][b])
if(f[a][b]>1){Q=Q.concat(p)
for(m=0;t=p[m];m++)l[t/z|0][t%z]=o(l[t/z|0][t%z],q+1)}!f[a][b]?Q.push(a*z+b):''}}}}for(i=0;i<z;)console.log(f[i++])
console.log((k=l[9][9])>98?"":k)

```

Graph generation happens in the first five lines. `f` contains the fields, `p` holds the portals. The actual search is implemented via BFS.

## Example output:

```
> node maze.js
[ 0, 0, 0, 0, 1, 0, 0, 0, 2, 0 ]
[ 0, 1, 1, 0, 0, 1, 0, 0, 0, 2 ]
[ 0, 0, 0, 1, 0, 0, 0, 0, 1, 0 ]
[ 1, 1, 1, 0, 2, 2, 0, 1, 0, 1 ]
[ 1, 1, 0, 0, 0, 0, 1, 0, 0, 0 ]
[ 1, 1, 0, 0, 1, 0, 0, 0, 1, 1 ]
[ 0, 0, 1, 1, 0, 1, 0, 0, 2, 0 ]
[ 0, 0, 1, 0, 1, 2, 0, 1, 0, 1 ]
[ 1, 0, 0, 0, 1, 1, 1, 0, 1, 1 ]
[ 0, 1, 0, 0, 0, 0, 0, 0, 1, 0 ]

```

```
>node maze.js
[ 0, 0, 0, 0, 1, 0, 1, 0, 0, 1 ]
[ 0, 2, 0, 1, 1, 2, 0, 0, 0, 0 ]
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ]
[ 0, 0, 0, 1, 2, 1, 1, 0, 1, 0 ]
[ 2, 0, 1, 0, 2, 2, 2, 0, 1, 0 ]
[ 1, 0, 0, 0, 1, 0, 0, 0, 1, 0 ]
[ 0, 0, 1, 0, 0, 1, 0, 1, 0, 0 ]
[ 0, 1, 2, 0, 0, 0, 0, 0, 0, 1 ]
[ 1, 0, 2, 1, 0, 1, 2, 0, 0, 1 ]
[ 0, 1, 2, 0, 0, 0, 0, 0, 0, 0 ]
5
```

# Answer
> 0 votes
## Python, 314

```
import random,itertools as t
r=range(10)
a,d=[[random.choice([0]*6+[1]*3+[2])for i in r]for j in r],eval(`[[99]*10]*10`)
a[0][0]=a[9][9]=d[0][0]=0
for q,i,j,m,n in t.product(r*10,r,r,r,r):
 if a[m][n]!=1and abs(m-i)<2and abs(n-j)<2or a[i][j]==a[m][n]==2:d[m][n]=min(d[i][j]+1,d[m][n])
w=d[9][9]
print a,`w`*(w!=99)

```

It's a disgusting implementation of Bellman-Ford. This algorithm is O(n^6)! (Which is okay for n=10)

---
Tags: code-golf, path-finding, maze
---


title: Self-contained hello-world program

text:
# Question
Title: Self-contained hello-world program
I want a program that outputs "hello world" on console on my x86\_64 based Linux computer. Yes, a complete program, not something silly that needs an interpreter or a compiler to work.

You may:

* use all glibc functionality
* submit a static executable
* submit a dynamic executable with dependencies if you outline them
* compile an ELF file
* dig into the ELF format and remove all unneeded stuff
* be creative and work around the ELF format

Describe here how you create and execute the program.

The shortest program wins.

# Answer
> 2 votes
## MS-DOS .COM - 21 bytes

From the comments:

> marinus may use any platform he likes to go below the 45 bytes from muppetlabs.com/~breadbox/software/tiny/teensy.html – Thorsten Staerk

So now I had to. (So don't accept this answer because it's cheating.)

He made a mistake, because that allows me to do:

```
BITS 16
              org     0x100
              mov     ah,9
              mov     dx,hello
              int     0x21
              int     0x20
hello:        db      "hello world$"

```

Compile with:

```
nasm -f bin -o hello.com hello.asm

```

And then DOSBOX or something will run the resulting `.com`, which is **21** bytes in size.

No hacks are even needed because `.com` files have no structure.

# Answer
> 1 votes
This is what you had in mind? Or you want any more hacky?

`EDITED(2)`

## Assembler (NASM) { source: 155 bytes, compiled: 384 bytes }

### Source code: helloworld.nasm

```
global _start
_start:
write:
 mov eax, 4
 mov ebx, 1
 mov ecx, h
 mov edx, 12
 int 0x80
exit:
 mov eax, 1
 mov ebx, 0
 int 0x80
h: db 'hello world', 10, 0

```

### Compile

```
$ nasm helloworld.nasm -f elf64 -o helloworld.o
$ ld helloworld.o -s -o helloworld

```

### Execution

```
$ ./helloworld
hello world

```

### Size

```
$ ls -al helloworld.nasm helloworld
-rw-rw-r-- 1 user user 155 Jan  5 11:08 helloworld.nasm
-rwxrwxr-x 1 user user 384 Jan  5 11:09 helloworld

```

### Platform:

```
$ uname -io
x86_64 GNU/Linux
$ nasm -v
NASM version 2.09.10 compiled on Oct 17 2011

```

# Answer
> 1 votes
## Assembly - compiled: 76 bytes

This is a 32-bit executable, but taking advantage of backwards compatibility it will run on x86\_64 systems too. At least it did on mine. It's based on breadbox's "tiny.asm" and it's hackier still so I wouldn't be that surprised if some Linuxes didn't want to touch it.

I tried it on Debian 7 in a VM, and it worked.

```
BITS 32
              org     0x00200000
              db      0x7F, "ELF"
hello:        db      "hello world", 10
              dw      2
              dw      3
              ; nasm insisted on aligning them properly so let's do it this way
exit:         dd      0x80cd4066 ; inc eax - int 0x80
              dd      start
              dd      phdr - $$
phdr:         dd      1
              dd      0
              dd      $$
              dw      1
              dw      0
              dd      filesize
              dd      filesize
start:        mov     ecx, hello ; B9 0400 0200 -> flag 1 set -> executable
              mov     edx, 12
              inc     eax
              shl     eax,2
              int     0x80
              xor     eax, eax
              jmp     exit
filesize      equ     $ - $$

```

It actually works:

```
~$ nasm -f bin -o hello hello.asm;chmod +x hello
~$ ./hello
hello world
~$ wc -c hello
76 hello
~$

```

It even neatly outputs a newline as I had a byte to spare in the ELF header.

---
Tags: code-golf, assembly, machine-code
---


# Question
Title: Finding n'th character in a Lucky String
Lucky numbers are those numbers which contain only "4" and/or "5". For example 4, 5, 44, 54,55,444 are lucky numbers while 457, 987 ,154 are not.

Lucky number sequence is one in which all lucky numbers exist in increasing order for example 4,5,44,45,54,55,444,445,454,455...

Now we concatenate all the lucky numbers (in ascending order) to make a lucky string "4544455455444445454455..."

Given n, your task is to find the nth digit of the lucky string. If the digit is 4 then you have to print "F" else you have to print "E".

```
1<=n<=10^15

```

# Answer
> 10 votes
## JavaScript - 49

```
for(s=i=0;!(r=s[n+i++]);s+=i.toString(2));"FE"[r]

```

Execute this on a JavaScript console (tested on Node), with `n` set to the 1-based index of the digit you want.

Explanation:

The script builds a version of the lucky string, and stops when the character we're looking for exists.

```
Lucky string:        4 5 44 45 54 55
Generated string: 011011100101110111

```

The lucky string is equivalent to the concatenation of all binary numbers with the leading one stripped. We can get the index of the appropriate character in `s` from `n` by adding the number of leading ones in the string to skip, or, equivalently, how many binary numbers we generated. Luckily for us, we can just grab the current value of `i`.

It greatly helps to see the final values of `s` and `i` after running. For sake of brevity, I won't post a table here, but you can certainly check their values in the console.

Details:

```
s=i=0

```

Initializes `s` and `i`. `s` later becomes a string, but rather than initialize to `"0"`, `0` works fine because of implicit type conversion.

```
i++

```

Increments i every iteration.

```
r=s[n+i++]

```

Gets the character of `s` at `n+i` (0 or 1) and stores it in `r`.

```
!(r=s[n+i++])

```

Loops while the character we are looking for is still undefined.

```
s+=i.toString(2)

```

Appends the next binary number in sequence to `s`.

```
"FE"[r]

```

Causes the expression to evaluate to `F` if `r` is `0`, `E` if `r` is `1`.

# Answer
> 3 votes
## GolfScript: 48

```
10 15?,{''+{.52=\53=|}%{&}*},{''++}*=52='F''E'if

```

Very inefficient. Can definitely be improved.

Explanation: `10 15?,` builds a sequence of the first `10^15` numbers. The next block preceding the next comma filters the sequence down to so-called lucky numbers by converting to a string, mapping characters of the string to `1` if they equal `'4'` (52) or `'5'` (53), and then folding `&` over the elements. Finally, fold string concatenation across the lucky sequence to form a big string, take the nth element, and convert to `'F'` or `'E'` appropriately.

# Answer
> 2 votes
# GolfScript, 34

Based on Kendall Frey's solution, uses 0-based indices.

```
~''{0):0 2base(;+.,2$)<}do='FE'1/=

```

Alternative solution, 44 bytes:

```
~0{-.0):0.2\?*.@)<}do 1$+0/2base\0%)='FE'1/=

```

This has the advantage that it's **MUCH** faster, in fact it's instant even for 15-digit inputs.

Java equivalent (more or less):

```
public static void f(long n) {
    long k = 0; // number of digits
    long t = 0;
    while (true) {
        k++;
        t = k << k;
        if (t > n) break;
        n -= t;
    }
    // the lucky number with 0s and 1s, prefixed with a 1
    String s = Long.toBinaryString((n + t) / k);
    int d = s.charAt((int) (n % k + 1)) - '0'; // the digit we want
    System.out.println("FE".charAt(d));
}

```

# Answer
> 1 votes
# Haskell, fast

I'm aiming for the fastest program. The hidden structure of this question, as explained by Kendall Frey, is that the lucky numbers can be explained as binary numbers. But his answer is searching each number in succession, making for a terrible runtime for large numbers. Can we do better? How do we solve for `n=10^15` in a speedy manner?

The length of each lucky number is the following:

```
x  lucky length
1  4     1
2  5     1
3  44    2
4  45    2
5  54    2
6  55    2
7  444   3
8  445   3
9  454   3
10 455   3
11 544   3
e  t     c

```

Note the pattern in the length increase. We first have a run of 2 same-length numbers, then 4, 8, 16, 32, ...

I'm going to use this fact to find the length of my number fast, by multiplying by two until I find the "block" of similar-length numbers, and accumulate the length up to that block. I then use divison to find out which number inside that block is the one I'm looking for, and modulo to find what digit it has.

```
find n =
  let (digits, n') = block n
      num = n' `div` digits
      digit = digits - (n' `rem` digits) - 1
  in case (num `div` (2^digit)) `rem` 2 of
    0 -> 'F'
    1 -> 'E'

-- Return (digits in each number in block, n-(length up to block)-1)
block n = block' n 2 0 2 1
  where
    block' n add acc pow length
      | acc+add >= n = (length, n-acc-1)
      | otherwise=
        let len' = length+1
            pow' = pow*2
            add' = len'*pow'
        in block' n add' (acc+add) pow' len'

```

(I stumbled across lots of off-by-one pitfalls while implementing this. Also, I didn't see aditsus speed-edit until I had already written this, but at least I bring an explanation :-) )

# Answer
> 1 votes
**Python 2.7** based on Kendall Frey somewhat deduction of the problem xD ... well spot

```
s = "";n=10;i=2
while len(s) < n:
    i+=1; s+=bin(i)[3:]
print "FE"[int(s[n-1])]

```

---
Tags: popularity-contest
---


title: Thar she blows!

text:
# Question
Title: Thar she blows!
Arrr... Ahoy there, me maties! Unfurl tha' mainsail! Full to starboard! Ah, feel th' wind in yer hair!

Right, me hearties... I be needin' a bit of yer codin' skills! Me crew are a li'l more modernized than meself... I still be preferrin' th' points of th' compass (see here for more info, Arrr...) while me crew are always usin' a headin'... I be wantin' an easy way of convertin' this twaddle they call a headin' into what I be able to understand, Arrr!

What I be needin' is code tha' be takin' input of a number (decimals are okay) such tha' `0 <= the headin' < 360` and it be spittin' out th' answer as th' closest compass point! Arrr!

Here be some examples:

`> heading 0.1`

`North`

`> heading 11.25`

`North by East`

`> heading 22.7`

`North Northeast`

`> heading 44.99`

`Northeast`

`> heading 91`

`East`

Now, if'n th' headin' ye be givin' be such that it falls exactly in th' middle of two compass points, don' ye be frettin', me hearties... I be expectin' th' code to spit out `Between <point 1> and <point 2>`, e.g. `heading 5.625` will say `Between North and North by East` This only be happenin' for a headin' tha' be satisfyin' the equation `H = 5.625 + 11.25(N)` where H be th' headin' and N be an integer between 0 and 31 inclusive...

Two restrictions tho'...

1) I not be wantin' ye to use arrays for storin' yer data for the points or th' headin's... Tha' be cheatin', sir, an' ye be gettin' a taste of me blunderbuss... This has t' be calculated, jus' like th' old days! Arrr!

2) Shortest code wins, or I'll be makin' ye walk th' plank... Arrr!

# Answer
## Perl 5.10 using substitution, 231 228 226 224

```
@c=(north,east,south,west);
@q=qw(P PbR P-Q QbP Q QbR R-Q RbP);
sub p{$j=$_[0]>>3&3;$_=$q[7&pop];s/P/$c[$j]/;s/Q/$c[$j+1&2]$c[$j|1]/;s/R/$c[$j+1&3]/;s/b/ by /;ucfirst}
$a=<>/11.25+.5;
say$a==int$a&&'Between '.p($a-1).' and ',p$a

```

Four newlines added for readability.

**Edit:** Golfed 2 more bytes using `pop`. Thanks @Dom Hastings

**Edit:** 2 bytes less using `qw()`
> 6 votes

# Answer
I be spendin' way too much time on this here treasure hunt, but here's a solution in **Java**:

```
public class Aaaaarrrr {

    public static void main(String[] aaarrrgs) {

        float heading = Float.parseFloat(aaarrrgs[0]);

        final List<String> points = Arrays.asList("North",
                "North by east", "North-northeast", "Northeast by north",
                "Northeast", "Northeast by east", "East-northeast",
                "East by north", "East", "East by south", "East-southeast",
                "Southeast by east", "Southeast", "Southeast by south",
                "South-southeast", "South by east", "South", "South by west",
                "South-southwest", "Southwest by south", "Southwest",
                "Southwest by west", "West-southwest", "West by south", "West",
                "West by north", "West-northwest", "Northwest by west",
                "Northwest", "Northwest by north", "North-northwest",
                "North by west");

        float cp = heading / 360.0f * 32.0f;
        if (cp % 1 == 0.5f)
             System.out.print("Between " + points.get((int)Math.floor(cp)) + " and ");

         System.out.println(points.get(Math.round(cp)));

    }
}

```

*edit* If I minimize the above code and make it real ugly it would become this:

## Java, 770 chars

```
import java.util.*;class A{public static void main(String[] r){List<String> l=Arrays.asList("North","North by east","North-northeast","Northeast by north","Northeast","Northeast by east","East-northeast","East by north","East","East by south","East-southeast","Southeast by east","Southeast","Southeast by south","South-southeast","South by east","South","South by west","South-southwest","Southwest by south","Southwest","Southwest by west","West-southwest","West by south", "West","West by north","West-northwest","Northwest by west","Northwest","Northwest by north","North-northwest","North by west");float c=Float.parseFloat(r[0])/360.0f*32.0f;if (c%1==0.5f) System.out.print("Between "+l.get((int)Math.floor(c))+" and ");System.out.println(l.get(Math.round(c)));}}

```
> 22 votes

# Answer
## Python, 264

```
n='north'
e='east'
s='south'
w='west'
b=' by '
def f(H):x,y,z=(n,e,s,w,e,s,w,n,n+e,s+e,s+w,n+w)[int(H%360/90)::4];return(x,x+b+y,x+'-'+z,z+b+x,z,z+b+y,y+'-'+z,y+b+x)[int(H%90*4/45)].capitalize()
h=input()+5.625
print h%11.25and f(h)or'Between '+f(h-1)+' and '+f(h)

```

This uses capitalisation as per the wikipedia page and should work for any number.
> 6 votes

# Answer
### Arrr Python, 336

```
A,R,r=int,input()/360.*32,' by #South#north#West#East#south#North#west#east#-#/#Between#and'.split('#')
a=''.join(r[A(c,16)]for c in'6A608A6928A6802A68A6808A4928A402A4A405A4958A1808A18A1805A1958A108A1A107A1957A1705A17A1707A3957A305A3A302A3927A6707A67A6702A6927A607').split('/')
if R%1==.5:print r[11],a[A(R)],r[12],
print a[A(round(R))]

```

Thanks @Jeen
> 4 votes

# Answer
## Perl 5.10, 262 257 254

Somewhat similar to one of the Python solutions:

```
$n=north;$e=east;$s=south;$w=west;
@d=($n,$n.$e,$e,$s.$e,$s,$s.$w,$w,$n.$w,$n);
sub p{$j=pop;$i=$j>>2;ucfirst(($d[$i],"$d[$i] by $d[$i+2&~1]","$d[$i+1&~1]-$d[$i|1]","$d[$i+1] by $d[$i&~1]")[$j&3])}
$a=<>/11.25+.5;
say$a==int$a&&'Between '.p($a-1).' and ',p$a

```

Four newlines added for readability.

**Edit:** Three bytes less thanks to @Dom Hastings
> 2 votes

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


# Question
Title: Backtickify code snippets on Stack Exchange
Your goal is to input any arbitrary text, such as:

```
This is some text

```

And output that text formatted as code for posts (SE-flavored Markdown) and comments (mini-Markdown) on Stack Exchange, such as:

```
`This is some text`
`This is some text`

```

However, it gets trickier. Consider the input:

```
Perl has a variable called $`

```

The output must be

```
`` Perl has a variable called $` ``
`Perl has a varaible called $\``

```

The full rules for the formatting are:

* Full posts (full SE Markdown)

+ Step 1: count the least number for which there are not exactly that many consecutive backticks in the string. Let's call this `n`. (For example, for the string `potato`, `n` is 1, for `this is a backtick: ``, `n` is 2, and for `` `` ``` ````` ```````, `n` is 4.)
    + Step 2: wrap the string in `n` backticks. If the string starts or ends with a backtick, you must wrap with spaces as well. (For example, `potato` becomes ``potato``, `this is a backtick: `` becomes ``` this is a backtick: ` ```, and `` `` ``` ````` ``````` becomes ````` ` `` ``` ````` `````` `````.
* Comments (mini-Markdown)

+ Wrap in ``` and escape all ```'s with `\``. (For example, `potato` becomes ``potato``, `this is a backtick: `` becomes `this is a backtick: \``, and `` `` ``` ````` ``````` becomes `\` \`\` \`\`\` \`\`\`\`\` \`\`\`\`\`\``.

This is ; the shortest answer in byte count wins.

# Answer
## APL (90)

(Yes, the APL charset does fit in a byte, here's IBM's codepage 907.)

```
{⎕ML←3⋄(,/m,m,⍨{⍵=m:'\`'⋄⍵}¨⍵),⊂(⌽g),⍵,g←(''↑⍨∨/t[1,⍴t]),m/⍨0⍳⍨z∊⍨⍳⌈/0,z←,⊃⍴¨⍵⊂⍨t←⍵=m←'`'}

```

This is a function that takes a string, and returns an array of two strings, where the first string is the *comment* representation and the second string is the *full post* representation.

Tests:

      backtickify←{⎕ML←3⋄(,/m,m,⍨{⍵=m:'\`'⋄⍵}¨⍵),⊂(⌽g),⍵,g←(''↑⍨∨/t[1,⍴t]),m/⍨0⍳⍨z∊⍨⍳⌈/0,z←,⊃⍴¨⍵⊂⍨t←⍵=m←'`'}
      ↑backtickify 'potato'
`potato`
`potato`

      ↑backtickify 'this is a backtick: `'
`this is a backtick: \``
`` this is a backtick: ` ``

      ↑backtickify '` `` ``` ````` ``````'
`\` \`\` \`\`\` \`\`\`\`\` \`\`\`\`\`\``
```` ` `` ``` ````` `````` ````

      ⍝ testcase for not wrapping with spaces
      ↑backtickify 'no`spaces``at````the`edges'
`no\`spaces\`\`at\`\`\`\`the\`edges`
```no`spaces``at````the`edges```

Note: I gave the function a name for readability's sake, this is not strictly necessary to use it (you can just put the argument next to the anonymous function) so I didn't count it.
> 4 votes

# Answer
## Ruby, 119

```
s=gets.chop
c=1
c+=1while s=~/([^`]|\A)#{?`*c}([^`]|\z)/
puts ?`+s.gsub('`','\\\\`')+'`
'+?`*c+(s=~/$`|`^/?" #{s} ":s)+?`*c

```

Ungolfed:

```
def backtickify str, comment = false
  return "`#{str.gsub '`', '\\\\`'}`" if comment
  c = 1
  c += 1 while str =~ /([^`]|\A)#{?` * c}([^`]|\z)/
  str = ' ' + str + ' ' if str[0] == ?` || str[-1] == ?`
  return ?` * c + str + ?` * c
end

```
> 2 votes

---
Tags: code-golf
---


title: Implementing the SHA-1 hash algorithm

text:
# Question
Title: Implementing the SHA-1 hash algorithm
The goal of this code-golf is to create a program that takes a string as input, and you have to output the SHA-1 hash value as a hexadecimal number. You can find the pseudocode for SHA-1 here

Other rules:

1. No network access
2. You're not allowed to run external programs
3. You're not allowed to use built-in methods to hash the input
4. The shortest code wins
5. It's only necessary to handle ASCII input
6. Output can be either lowercase or uppercase
7. The input can be provided using:

1. Prompting for input
    2. Using command-line arguments
    3. Using STDIN

Test cases:

```
Input: The quick brown fox jumps over the lazy dog
Output: 2fd4e1c67a2d28fced849ee1bb76e7391b93eb12
----------------------------------------------------------
Input: The quick brown fox jumps right over the lazy dog
Output: 1c3aff41d97ada6a25ae62f9522e4abd358d741f
------------------------------------------------------------
Input: This is a code golf challenge
Output: f52ff9edd95d98e707bd16a7dead459cb8db8693

```

# Answer
> 5 votes
### GolfScript, 374 322 characters

```
[128]+.,.~55+64%1,*\(8*2
32?:?.*+256{base}:B~1>++"!Vi9y BRQ+@phoKD5Vj=]30z0"{96@32-*+}*?B\64/{4/{256B}%{0'=820'{64-
2$=^}/2*.?/+?%+}64*1$'&4$?(^3$&|1518500249{++[]@+@+@?*4/.?/+?%+2$+\@32*.?/++@(@+?%@-1%+}:Y~
^2$^1859775393Y
&4$3$&|3$3$&|2400959708Y
^2$^3395469782Y'n/{'~3$3$'\+20*~}/+]zip{~+?%}%}/{?+16B{.9>7*+48+}%1>}%''+

```

This is based on an exact implementation of the pseudo-code in GolfScript plus some minor encodings to shorten the code (try it online). Input will be read from STDIN.

# Answer
> 5 votes
## Python 3 - 645 chars

```
h=0x67452301,0xEFCDAB89,0x98BADCFE,0x10325476,0xC3D2E1F0
L=lambda v,s:(v<<s|v>>B-s)%2**B
B=32
R=range
m=input().encode()
l=len(m)
m+=b'\x80'+bytes((55-l)%64)+m.fromhex(hex(2**64+l*8)[3:])
for C in [m[i:i+64]for i in R(0,len(m),64)]:
 w=[sum(C[i+j]<<8*(3-j)for j in R(4))for i in R(0,64,4)];a,b,c,d,e=h
 for i in R(16,80):w+=[L(w[i-3]^w[i-8]^w[i-14]^w[i-16],1)]
 for i in R(80):f=[b&c|~b&d,b^c^d,b&c|b&d|c&d,b^c^d][i//20];k=[0x5A827999,0x6ED9EBA1,0x8F1BBCDC,0xCA62C1D6][i//20];t=L(a,5)+f+e+k+w[i];e=d;d=c;c=L(b,30);b=a;a=t%2**32
 g=a,b,c,d,e;h=[(h[i]+g[i])%2**32for i in R(5)]
B=160
print('%x'%(L(h[0],128)|L(h[1],96)|L(h[2],64)|L(h[3],32)|h[4]))

```

Just a golfed version of the pseudocode.

# Answer
> 2 votes
# D (759 chars)

Online executable version: http://dpaste.dzfl.pl/f0c8508f

```
import std.range,std.algorithm,std.bitmanip,std.stdio:g=writef;
void main(char[][]x){
    auto m=cast(ubyte[])x[1];
    uint a=0x67452301,b=0xEFCDAB89,i,t,f,k;
    uint[5]h=[a,b,~a,~b,0xC3D2E1F0],s;
    uint[80]w;
    auto r=(uint u,uint b)=>u<<b|u>>32-b;
    auto u=(uint i)=>[r(s[0],5)+f+s[4]+k+w[i],s[0],r(s[1],30),s[2],s[3]];
    ubyte[64]p;
    p[0]=128;
    m~=p[0..64-(m.length+8)%64]~nativeToBigEndian(8*m.length);
    foreach(ch;m.chunks(64)){
        16.iota.map!(i=>w[i]=ch[i*4..$][0..4].bigEndianToNative!uint).array;
        iota(16,80).map!(i=>w[i]=r(w[i-3]^w[i-8]^w[i-14]^w[i-16],1)).array;
        s=h;
        80.iota.map!(i=>(i<20?f=s[3]^s[1]&(s[2]^s[3]),k=0x5A827999:i<40?f=s[1]^s[2]^s[3],k=0x6ED9EBA1:i<60?f=s[1]&s[2]|s[3]&(s[1]|s[2]),k=0x8F1BBCDC:(f=s[1]^s[2]^s[3],k=0xCA62C1D6),s[]=u(i)[])).array;
        h[]+=s[];
    }
    g("%(%08x%)",h);
}

```

# Answer
> 2 votes
## C, 546 characters

The program calculates the SHA-1 of the contents of its standard input.

```
unsigned b[16],k[]={1732584193,0xEFCDAB89,0,271733878,0xC3D2E1F0},i,j,n,p,t,u,v,w,x;
char*d=b;a(c){for(d[p++^3]=c,c=0,t=*k,u=k[1],v=k[2],w=k[3],x=k[4];
c>79?*k+=t,k[1]+=u,k[2]+=v,k[3]+=w,k[4]+=x,p=0:p>63;x=w,w=v,v=u<<30|u/4,u=t,t=i)
i=b[c-3&15]^b[c+8&15]^b[c+2&15]^b[j=c&15],c++>15?b[j]=i*2|i>>31:0,i=u^v^w,
i=(t<<5|t>>27)+x+b[j]+(c<21?(w^u&(v^w))+1518500249:c<41?i+1859775393:
c<61?(u&v|w&(u|v))-1894007588:i-899497514);}
main(){for(k[2]=~*k;i=~getchar();++n)a(~i);for(a(128);p-56;a(0));
for(;p<20?printf("%02x",(d=k)[p^3]&255):p>55;a(n*8L>>504-p*8));}

```

A couple of notes:

1. This program assumes that `int` is exactly 32 bits. For platforms where this is not the case, the `unsigned` declaration at the very beginning should be replaced by the platform's unsigned 32-bit type. (`uint32_t` would be the obvious choice, if it didn't require `#include <stdint.h>`.)
2. This program assumes a little-endian platform. For a big-endian platform, simply remove the two occurrences of `^3` in the program, and replace the initialization of `k[]` with the following block: `{19088743,0x89ABCDEF,0,1985229328,0xF0E1D2C3}`, for a size of 541 characters.
3. For implementations where `char` is unsigned by default, one can delete the `&255` that appears on the final line to save four more characters.

# Answer
> 1 votes
My python code is a little longer but it is fully working.

```
data="hello world"
bytes = ""
h0,h1,h2,h3,h4=0x67452301,0xEFCDAB89,0x98BADCFE,0x10325476,0xC3D2E1F0
for n in range(len(data)):bytes+='{0:08b}'.format(ord(data[n]))
bits=bytes+"1"
pBits=bits
while len(pBits)%512!=448:pBits+="0"
pBits+='{0:064b}'.format(len(bits)-1)
def chunks(l,n):return[l[i:i+n]for i in range(0,len(l),n)]
def rol(n,b):return((n<<b)|(n>>(32-b)))&0xffffffff
for c in chunks(pBits,4512):
    words=chunks(c,32)
    w=[0]*80
    for n in range(0,16):w[n]=int(words[n],2)
    for i in range(16,80):w[i]=rol((w[i-3]^w[i-8]^w[i-14]^w[i-16]),1)
    a,b,c,d,e=h0,h1,h2,h3,h4
    for i in range(0,80):
        if 0<=i<=19:f=(b&c)|((~b)&d);k=0x5A827999
        elif 20<=i<=39:f=b^c^d;k=0x6ED9EBA1
        elif 40<=i<=59:f=(b&c)|(b&d)|(c&d);k=0x8F1BBCDC
        elif 60<=i<=79:f=b^c^d;k=0xCA62C1D6
        temp=rol(a,5)+f+e+k+w[i]&0xffffffff
        e,d,c,b,a=d,c,rol(b,30),a,temp
    h0+=a
    h1+=b
    h2+=c
    h3+=d
    h4+=e
print '%08x%08x%08x%08x%08x'%(h0,h1,h2,h3,h4)

```

---
Tags: code-golf, hashing
---


# Question
Title: Sorting a List with a Another Sorted List
Say i have a list (unorder):

```
Score = ['score1','score10','score6','score2','score22','score12']
Names = ['name1','name10','name6','name2','name22','name12']
email = ['email1','email10','email6','email2','email22','email12']

```

and then Score is sorted to be

```
ScoreSorted = ['score1','score2','score6','score10','score12','score22'].

```

The shortest code (in byte) to sort Name and Email with Score list wins

result of email and names list should be

```
EmailSorted = ['email1','email2','email6','email10','email12','email22'].
NamesSorted = ['name1','name2','name6','name10','name12','name22'].

```

# Answer
> 2 votes
## Ruby 81 bytes

```
m=Score.each_index.sort_by{|i|Score[i]}
p m.map{|i|Names[i]}
p m.map{|i|Email[i]}

```

A golfed implemention of the algorithm below, assuming `Score`, `Names`, and `Email` are all already defined, and that only output of the post-sorted `Names` and `Email` is required.

Sample usage:

```
Score = ['score1','score10','score6','score2','score22','score12']
Names = ['name1','name10','name6','name2','name22','name12']
Email = ['email1','email10','email6','email2','email22','email12']

m=Score.each_index.sort_by{|i|Score[i]}
p m.map{|i|Names[i]}
p m.map{|i|Email[i]}

```

Sample output:

```
["name1", "name10", "name12", "name2", "name22", "name6"]
["email1", "email10", "email12", "email2", "email22", "email6"]

```

---

## Ruby (with natural sort) 123 bytes

```
m=Score.each_index.sort_by{|i|Score[i].scan(/\d+|\D+/).map{|i|i=~/\d/?i.to_i: i}}
p m.map{|i|Names[i]}
p m.map{|i|Email[i]}

```

Correctly sorts strings with any number of digital groupings, as one would sort them 'naturally'. The only caveat is that all strings in the `Score` array must start with a digit, or all must start with a non-digit.

Sample output:

```
["name1", "name2", "name6", "name10", "name12", "name22"]
["email1", "email2", "email6", "email10", "email12", "email22"]

```

---

## Python

Not a code-golf answer.

1. Find the inverse permutation of the list which is to be sorted in lexicographical order (in the problem description, this `Scores` array). This can be achieved in *O(n log n)* time (as the problem is analog to sorting), although the implementation below is *O(n²)*.
2. Apply this permutation to each list. The permute function is *O(n)* complexity.

Sample implementation:

```
def get_inv_perm(items):
  size = len(items)
  perm = [0]*size
  for i in range(size):
    for j in range(size): perm[j] += items[j] > items[i]
  return perm

def permute(arr, perm):
  size = len(arr)
  out = [0] * size
  for i in range(size):
    val = perm[i]
    out[i] = arr[val]
  return out

if __name__ == "__main__":
  Score = ['score1','score10','score6','score2','score22','score12']
  Names = ['name1','name10','name6','name2','name22','name12']
  Email = ['email1','email10','email6','email2','email22','email12']

  perm = get_inv_perm(Score)

  print permute(Score, perm)
  print permute(Names, perm)
  print permute(Email, perm)

```

Sample output:

```
['score1', 'score10', 'score12', 'score2', 'score22', 'score6']
['name1', 'name10', 'name12', 'name2', 'name22', 'name6']
['email1', 'email10', 'email12', 'email2', 'email22', 'email6']

```

Because the sort is lexicographical, `score10` and `score12` appear directly after `score1`. The `get_inv_perm` function assumes the items list is unique. The remaining lists need not be.

# Answer
> 1 votes
Python, 172 bytes. Assumes names and emails are unique. Not particularly efficient as you have to do a lookup for each comparison.

```
NamesSorted=sorted(Names,lambda l,r:cmp(Score[Names.index(l)],Score[Names.index(r)]))
EmailSorted=sorted(email,lambda l,r:cmp(Score[email.index(l)],Score[email.index(r)]))

```

# Answer
> 1 votes
**Ruby** 108 bytes

```
[names, email, score].map do |z|
  z.sort! {|x, y| x.scan(/\d/).join.to_i <=> y.scan(/\d/).join.to_i }
end
puts "#{names}\n#{email}\n#{score}"

```

# Answer
> 1 votes
## C++ 117 bytes

```
#define S(a)a##Sorted.push_back(a[i])
for(auto a:ScoreSorted){int i=0;for(auto b:Score)a==b?S(Names),S(Email),0:++i;}

```

Notice that I am making two assumptions:

* strings vectors for to represent all lists
* it is OK to capitalize the name of the unsorted email list (email -\> Email)

Sample usage:

```
#include <string>
#include <vector>
#include <iostream>

using namespace std;

int main()
{
    vector<string> Score = {"score1","score10","score6","score2","score22","score12"};
    vector<string> Names = {"name1","name10","name6","name2","name22","name12"};
    vector<string> Email = {"email1","email10","email6","email2","email22","email12"};

    vector<string> ScoreSorted = {"score1","score2","score6","score10","score12","score22"};
    vector<string> NamesSorted;
    vector<string> EmailSorted;

#define S(a)a##Sorted.push_back(a[i])
for(auto a:ScoreSorted){int i=0;for(auto b:Score)a==b?S(Names),S(Email),0:++i;}

    for (auto i : NamesSorted) {
        cout << i << endl;
    }
    for (auto i : EmailSorted) {
        cout << i << endl;
    }
}

```

---
Tags: code-golf
---


title: Weird string calculation

text:
# Question
Title: Weird string calculation
String is given in form of a variable. Let's call that variable `s`. It is known that the string looks like a calculation expression using `+`, `-`, `*`, `/`. There's no parentheses.

**Calculate the expression inside the string** and store the result in variable `r` (you can assume it's already declared). All the divisions can be performed without remainders (`4-6*3/8` is invalid because 8 is not divisible by 3). Length of string is not limited. String can't contain `0`.

Challenge is not supposed to give advantage for some languages, so I decided to change some math rules:

Operators precedence is a little bit different than it is in math and programming language expressions: multiplication/division is still higher than addition/substraction. However, if there're some multiplications/divisions in a row, it is performed right-to-left. Addition/substraction is preformed left-to-right.

Sample `s` and `r`:

`2+5-6/9*8+7` -\> `2`

`1/3*6-6` -\> `12`

The shortest code (in bytes) wins.

# Answer
> 2 votes
# Perl 5, ~~27~~ 20

~~```
s/(.)\//1\/$1*/g;print eval

```~~

**Edit:**

```
s/\//**-1*/g;$r=eval

```

---

Assuming the input of:

> $\_ = "2+5-6/9\*8+7";
> \> $r = 2

and

> $\_ = "1/3\*6-6";
> \> $r = 12

This regex is based in the mathematical theory of `@ybeltukov`, I'm new to regex so it probably could be much better.

# Answer
> 6 votes
# Mathematica (41)

```
s = "2+5-6/9*8+7";
ToExpression@StringReplace[s,"/"->"^-1 "]

```

> 2

Correct me if I'm wrong

# Answer
> 3 votes
## Ruby, 24

```
 r=eval s.gsub ?/,'**-1*'

```

Thank you to @ybeltukov for the Mathematica technique. I *thought* there might be a substitution that could be used to leverage `eval` and yours was much simpler than the crazy regexes I was trying!

This shortcut effectively changes the operator precedence in `s` to what the question requires. It has the side effect of sometimes resulting in a `Rational` object type (e.g. `2/1` == `2`). The results are correct for the cases I've tried.

# Answer
> 2 votes
## JavaScript (213 characters compacted, 133 if I'm willing to sacrifice my soul)

For clarity, this is the code *before* I compacted it down (JS-Fiddle of it):

```
function math(match, leftDigit, operator, rightDigit, offset, string) {
    var L = parseInt(leftDigit)
    var R = parseInt(rightDigit)
    switch (operator)
    {
        case '*': return R*L;
        case '\/': return R/L;
        case '+': return L+R;
        case '-': return L-R;
    }
};

multAndDivRegex = /(\-?\d+)([\*\/])(\-?\d+)(?=[^\*\/]*$)/; //Right to left
addAndSubRegex = /(\-?\d+)([\+\-])(\-?\d+)/; // Left to right

while(multAndDivRegex.test(str)) {
    str = str.replace(multAndDivRegex, math);
}

while(addAndSubRegex.test(str)) {
    str = str.replace(addAndSubRegex, math);
}

```

Here it is compacted down to 213 characters (containing some extra help from **Toni Almeida**) (JS-Fiddle of it):

```
function m(x,l,o,r){
    L=~~l;R=~~r;
    return o=='*'?R*L:o=='/'?R/L:o=='+'?L+R:L-R
}

for(M=/(\-?\d+)([\*\/])(\-?\d+)(?=[^\*\/]*$)/;M.test(s);s=s.replace(M,m));
for(A=/(\-?\d+)([\+\-])(\-?\d+)/;A.test(r=s);s=s.replace(A,m));

```

Since I'm ending lines with semi-colons, all *removable* whitespace was ignored for character counting, but left in for clarity.

I can get it down to 133 characters if I use `eval()`, but that's not how I roll... (JS-Fiddle)

```
function m(x,l,o,r){return o=='*'?~~r*~~l:~~r/~~l}for(M=/(\-?\d+)([\*\/])(\-?\d+)(?=[^\*\/]*$)/;M.test(s);s=s.replace(M,m));r=eval(s)

```

This solution would mean that people can enter ANY JavaScript code they want! The 303 character version does not execute any JavaScript; it only does math.

# Answer
> 1 votes
## **Python 3, 35**

```
r=int(eval(s.replace("/","**-1*")))

```

## **Python 3, 30**

If you are not scared of floating point value, try this one.

```
r=eval(s.replace("/","**-1*"))

```

Both of them evaluate the string `s` and store the result in variable `r`

# Answer
> 0 votes
## GTB, 6

```
x?_)→R

```

6 chars and 6 bytes

**EDIT** \- now that the original question has changed, here's some bloated code:

```
@iS_,"*")\\iS_,"/$_4;I,1,l?A;)-1:s;A;,2I,1)+A;&s;A;,1I→_&x?_)→R

```

I think I did a pretty good job; I made it only 63 characters ;) more than 1,000% bloat

---
Tags: code-golf
---