title: Help me with differential calculus!

text:
# Question
Title: Help me with differential calculus!
I love programming and know every language, but I suck at math. Unfortunately, my school requires that computers students must take a year of calculus. There's a test next week, and I don't know any of the formulas for derivatives!

Please help me find the formulas. I need a cheat sheet - a program (as short as possible so my teacher won't notice it) that takes an expression (like `4*x^3-2`) as input and outputs the derivative. (I don't care if the input and output uses command line arguments, STDIN, STDOUT, or whatever, since I'm doing all of the calculation in my head anyway.)

The test covers the following types of functions:

* Constants, like `-3` or `8.5`
* Power functions, like `x^0.5` or `x^-7`
* Exponential functions, like `0.5^x` or `7^x` (the base is always positive)
* A constant multiplied by a function, like `3*x^5` or `-0.1*0.3^x`
* The sum and difference of multiple functions, like `-5*x^2+10-3^x`

My teacher always formats his questions in the exact same way, as shown above. He also doesn't use any fractions, numbers like pi or *e*, or really big numbers (bigger than 1,000). He never uses parentheses, and always shows multiplication using an asterisk (`*`). The only variable used is always *x*.

On the other hand, my teacher is pretty lenient about answers. They don't need to be simplified at all or formatted exactly as shown above, as long as it's clear what the answer is saying.

While I can use any language, remember that I can't figure out derivatives by myself. So if the program uses built-in functions to deal with equations or calculate derivatives, I won't be able to use it.

During the test, I won't have access to the Internet or any files other than the program on the cheat sheet.

*Note: This scenario is entirely fictional. In real life, cheating and helping others cheat is wrong and should never be done.*

# Answer
> 8 votes
## Wolfram 136 134 109\[Thanks to Calle for his comment below\]

Limited support for product and chain rules.

```
n=n_?NumberQ;d[v_Plus]:=d/@v;d[v_]:=v/.{x_^n:>x^(n-1)d[x]n,n^x_:>Log[n]d[x]n^x,x_*y__:>d[x]y+d[y]x,n:>0,x:>1}

```

Example:

```
d[3^(x^2)*(x^3+2*x)^2]
>> 2*3^x^2*(2+3*x^2)*(2*x+x^3) + 2*3^x^2*x*(2*x+x^3)^2*Log[3]

```

Note that this does not use any "built-in functions to deal with equations or calculate derivatives": only pattern-matching is involved\*.

\[\*Well... technically the interpreter also parses and builds a sort of AST from the input too\]

---

Ungolfed:

```
d[expr_Plus] := d /@ expr;
d[expr_] := expr /. {
   Power[x_, n_?NumberQ] :> n Power[x, n - 1] d[x],
   Power[n_?NumberQ, x_] :> Log[n] Power[n, x] d[x],
   Times[x_, y__] :> d[x] y + d[y] x,
   n_?NumberQ :> 0,
   x :> 1
}

```

# Answer
> 26 votes
# Perl - 121 ~~122~~

(+2 for `-p`)

```
s/(?<![-\d.*^])-?[\d.]+(?![*^\d.])/0/g;s/(?<!\^)x(?!\^)/1/g;s/x\^(-?[\d.]+)/"$1*x^".($1-1)/ge;s/([\d.]+)\^x/ln($1)*$&/g

```

Test:

```
$ perl -p diff.pl << EOF
> -3
> 8.5
> x^0.5
> x^-7
> 0.5^x
> 7^x
> 3*x^5
> -0.1*0.3^x
> -5*x^2+10-3^x
> EOF
0
0
0.5*x^-0.5
-7*x^-8
ln(0.5)*0.5^x
ln(7)*7^x
3*5*x^4
-0.1*ln(0.3)*0.3^x
-5*2*x^1+0-ln(3)*3^x

```

# Answer
> 7 votes
## Haskell 38 Chars

The function `d` takes a function and returns a function. It is inputted in the form of a power series, and is outputted the same way (which is a type of whatever.)

```
d=zipWith(*)[1..].tail

```

For example, if we input `x->x^2`, we get `x->2*x`.

```
λ <Prelude>: d [0,0,1]
[0,2]

```

And for the exponential function.

```
λ <Prelude>: take 10 exp --exp redefined above to be in power series notation
[1.0,1.0,0.5,0.16666666666666666,4.1666666666666664e-2,8.333333333333333e-3,1.388888888888889e-3,1.984126984126984e-4,2.48015873015873e-5,2.7557319223985893e-6]
λ <Prelude>: let d=zipWith(*)[1..].tail in take 10 $ d exp
[1.0,1.0,0.5,0.16666666666666666,4.1666666666666664e-2,8.333333333333333e-3,1.388888888888889e-3,1.984126984126984e-4,2.48015873015873e-5,2.7557319223985893e-6]

```

# Answer
> 5 votes
## Prolog 176

```
d(N,0):-number(N).
d(x,1).
d(-L,-E):-d(L,E).
d(L+R,E+F):-d(L,E),d(R,F).
d(L-R,E-F):-d(L,E),d(R,F).
d(L*R,E*R+L*F):-d(L,E),d(R,F).
d(L^R,E*R*L^(R-1)+ln(L)*F*L^R):-d(L,E),d(R,F).

```

Supported operators: binary `+`, binary `-`, binary `*`, binary `^`, unary `-`. Note that unary `+` is not supported.

Sample run:

```
49 ?- d(-3,O).
O = 0.

50 ?- d(8.5,O).
O = 0.

51 ?- d(x^0.5,O).
O = 1*0.5*x^ (0.5-1)+ln(x)*0*x^0.5.

52 ?- d(x^-7,O).
ERROR: Syntax error: Operator expected
ERROR: d(x
ERROR: ** here **
ERROR: ^-7,O) .
52 ?- d(x^ -7,O).
O = 1* -7*x^ (-7-1)+ln(x)*0*x^ -7.

53 ?- d(x,O).
O = 1.

54 ?- d(0.5^x,O).
O = 0*x*0.5^ (x-1)+ln(0.5)*1*0.5^x.

55 ?- d(7^x,O).
O = 0*x*7^ (x-1)+ln(7)*1*7^x.

56 ?- d(3*x^5,O).
O = 0*x^5+3* (1*5*x^ (5-1)+ln(x)*0*x^5).

57 ?- d(-0.1*0.3^x,O).
O = 0*0.3^x+ -0.1* (0*x*0.3^ (x-1)+ln(0.3)*1*0.3^x).

58 ?- d(-5*x^2+10-3^x,O).
O = 0*x^2+ -5* (1*2*x^ (2-1)+ln(x)*0*x^2)+0- (0*x*3^ (x-1)+ln(3)*1*3^x).

```

Prolog is confused when it runs into `^-` sequence. A space must be inserted between `^` and `-` for it to parse the expression correctly.

Hope your teacher doesn't mind the mess of equation.

Crazy time:

```
59 ?- d(x^x,O).
O = 1*x*x^ (x-1)+ln(x)*1*x^x.

60 ?- d((x^2-x+1)*4^ -x,O).
O = (1*2*x^ (2-1)+ln(x)*0*x^2-1+0)*4^ -x+ (x^2-x+1)* (0* -x*4^ (-x-1)+ln(4)* - 1*4^ -x).

```

# Answer
> 4 votes
# C, 260 248 bytes

−12 bytes thanks to **ceilingcat**

Hey, I think I know your teacher! Isn't it that one who has the supernatural ability to detect students executing library pattern-matching functions in their head?

So, using `sscanf` is out of question... But don't worry:

```
#define P,s--||printf(
q=94,s,c,t;main(a){char*p,i[999],*e=p=i;for(gets(i);q=c=*p++,t=q^94|c^45?c%26-16?c/46:c%16/3:1,s=(a="30PCqspP#!C@ #cS` #!cpp#q"[s*5+t])/16-3,p[-1]*=~a&1,!t?0 P"*0")P"/x")P"/x*%s",e)P"*ln(%s)",e),s=0:0,e=a&2?p:e,printf(&c););}

```

Running examples (input on `stdin`; output goes to `stdout`):

> 4\*x^3-2

```
4*x^3/x*3-2*0

```

This format is much better than just `12*x^2`, because this way your teacher can be sure that you calculated the answer yourself and didn't cheat by copying it from someone else!

> x+2^x

```
x/x+2^x*ln(2)

```

The output has a slight domain problem at `x=0`, but it's correct *almost everywhere*!

For reference, here is an ungolfed, readable (by mere mortals) version. It uses a state machine with 5 states and 5 categories of input characters.

```
void deriv(char* input)
{
    char* p = input; // current position
    char* exp = p; // base or exponent
    char q = '^'; // previous character

    // State machine has 5 states; here are examples of input:
    // state 0: 123
    // state 1: 123*
    // state 2: 123*x
    // state 3: 123*x^456
    // state 4: 123^x
    int state = 0;

    // Control bits for state machine:
    // bit 0: special action: stop recording base or exponent
    // bit 1: special action: start recording base or exponent
    // bits 4-7: if first column, specify how to calculate the derivative:
    //              3 - multiply the constant term by 0
    //              4 - divide x by x
    //              5 - divide x^n by x and multiply by n
    //              6 - multiply n^x by ln(n)
    // bits 4-7: if not first column, specify the next state
    //              (plus 3, to make the character printable)
    const char* control =
        "\x33\x30\x50\x43\x71"
        "\x73\x70\x50\x23\x21"
        "\x43\x40\x20\x23\x63"
        "\x53\x60\x20\x23\x21"
        "\x63\x70\x70\x23\x71";

    for (;;) {
        int c = *p++;

        // Convert a char to a category:
        // category 0: // - +
        // category 3: // *
        // category 2: // x
        // category 4: // ^
        // category 1: // numbers: 0...9 and decimal point
        int category;
        int action;

        if (q == '^' && c == '-')
            category = 1; // unary minus is a part of a number
        else
            category = c%26==16?c%16/3:c/46; // just does it

        // Load new state and action to do
        action = control[state * 5 + category];

        if (action & 1)
            p[-1] = 0;
        state = (action >> 4) - 3;
        if (category == 0)
        {
            if (state == 0)
                printf("*0");
            if (state == 1)
                printf("/x");
            if (state == 2)
                printf("/x*%s", exp);
            if (state == 3)
                printf("*ln(%s)", exp);
            state = 0;
        }
        if (action & 2)
            exp = p;

        if (c == 0 || c == '\n') // either of these can mark end of input
            break;

        putchar(c);
        q = c;
    }
}

```

P.S. Watch out for that `gets` function: it has a security vulnerability that can let your teacher execute a rootkit in your mind by providing too long input...

# Answer
> 3 votes
# Lua ~~296~~ ~~268~~ 263

```
function d(a)l=""i=a:find"x" if i then if a:sub(i-1,i-1)=="^"then l="log("..a:sub(1,i-2)..")*"..a elseif a:sub(i+1,i+1)=="^"then l=a:sub(i+2).."*"..a:sub(1,i)p=a:sub(i+2)-1 if p~=1 then l= l..a:sub(i+1,i+1)..p end else l=a:sub(1,i-2)end else l="0"end return l end

```

Not very golfed and cannot currently handle multiple terms (you can just run it a few times, right?), but it can handle `n^x`, `x^n` and `n` as input.

---

Ungolfed...

```
function d(a)
   l=""
   i=a:find"x"
   if i then
      if a:sub(i-1,i-1)=="^" then
         l="log("..a:sub(1,i-2)..")*"..a
      elseif a:sub(i+1,i+1)=="^" then
         l=a:sub(i+2).."*"..a:sub(1,i)
         p=a:sub(i+2)-1 -- this actually does math here
         if p~=1 then
            l= l..a:sub(i+1,i+1)..p
         end
      else
         l=a:sub(1,i-2)
      end
   else
      l="0"
   end
   return l
end

```

# Answer
> 3 votes
## ECMAScript 6, 127 bytes

Here is my regex attempt (using a single regex and some logic in the replacement callback):

```
i.replace(/(^|[*+-])(\d+|(?:([\d.]+)\^)?(x)(?:\^(-?[\d.]+))?)(?![.*^])/g,(m,s,a,b,x,e)=>s+(b?'ln'+b+'*'+a:e?e--+'*x^'+e:x?1:0))

```

This expects the input string to be stored in `i` and simply returns the result. Try it out in an ECMAScript 6 compliant console (like Firefox's).

# Answer
> 2 votes
## sed, 110

Taking very literally "They don't need to be simplified at all or formatted exactly as shown above, as long as it's clear what the answer is saying":

```
s/.*/__&_/;s/x\^(-?[0-9.]+)/\1*x^(\1-1)/g;s/([0-9.]+)\^/ln\1*\1^/g;s/([^(][-+_])[0-9.]+([-+_])/\10\2/g;s/_//g

```

The byte count includes 1 for the `r` flag.

Ungolfed, with comments:

```
# Add underscores before and after the string, to help with solo-constant recognition
s/.*/__&_/
# Power rule: replace x^c with c*x^(c-1) where c is a number
s/x\^(-?[0-9.]+)/\1*x^(\1-1)/g
# Exponentials: replace c^ with lnc*c^ where c is a number
# (This assumes that there will be an x after the ^)
s/([0-9.]+)\^/ln\1*\1^/g
# Constants: replace ?c? with ?0? where c is a number and ? is +, -, or _
# Except if it's prededed by a parenthesis then don't, because this matches c*x^(c-1)!
s/([^(][-+_])[0-9.]+([-+_])/\10\2/g
# Get rid of the underscores
s/_//g

```

Sample run:

```
$ cat derivatives.txt
-3
8.5
x^0.5
x^-7
0.5^x
7^x
3*x^5
-0.1*0.3^x
-5*x^2+10-3^x

$ sed -re 's/.*/__&_/;s/x\^(-?[0-9.]+)/\1*x^(\1-1)/g;s/([0-9.]+)\^/ln\1*\1^/g;s/([^(][-+_])[0-9.]+([-+_])/\10\2/g;s/_//g' derivatives.txt
-0
0
0.5*x^(0.5-1)
-7*x^(-7-1)
ln0.5*0.5^x
ln7*7^x
3*5*x^(5-1)
-0.1*ln0.3*0.3^x
-5*2*x^(2-1)+0-ln3*3^x

```

I bet this could be golfed further; it's my first try at `sed`. Fun!

# Answer
> 1 votes
## Ruby, 152

...or 150 if you don't need to print... or 147 if you also are ok with an array that you need to join yourself.

run with `ruby -nal`

```
p gsub(/(?<!\^)([-+])/,'#\1').split(?#).map{|s|s[/x\^/]?$`+$'+"x^(#{$'}-1)":s[/-?(.*)\^(.*)x/]?s+"*ln(#{$1}*#{$2[0]?$2:1})":s[/\*?x/]?($`[0]?$`:1):p}*''

```

ungolfed:

```
p gsub(/(?<!\^)([-+])/,'#\1').split(?#). # insert a # between each additive piece, and then split.
map{ |s|
    if s[/x\^/]                          # if it's c*x^a
        $` + $' + "x^(#{$'}-1)"          #      return c*ax^(a-1)
    elsif s[/-?(.*)\^(.*)x/]             # if it's c*b^(a*x)
        ln = $1 + ?* + ($2[0] ? $2 : 1)  #      return c*b^(a*x)*ln(b*a)
        s+"*ln(#{ln})"
    elsif s[/\*?x/]                      # if it's c*x
        ($`[0] ? $` : 1)                 #      return c
    else                                 # else (constant)
        nil                              #      return nil
    end
}*''

```

My main problem with this one is the number of characters proper splitting takes. The only other way I could think of was `split(/(?<!\^)([-+])/)` which gives `+` and `-` as their own results. Any hints for a better solution?

Also, is there a shorter way to return `s` if it's not empty, but otherwise return `y`? I've used `s[0]?y:s`? In JS I'd just do `s||y`, but `""` is truthy in Ruby.

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


title: 99 Bottles of beer, 99 languages

text:
# Question
Title: 99 Bottles of beer, 99 languages
The goal is to write a simple "99 Bottles of Beer" program .. that is valid in *at least* 2 distinct languages (e.g. not Python 2 and Python 3). It must be a complete file that will run or compile.

Interesting answers should be up-voted, but compactness also counts. (Of course, language diversity is the main goal.)

EDIT: I would say that to have normal C code that does the same thing with C++ and Objective-C counts as derivative. The code should do clever stuff so that lines have different meanings with different languages.

# Answer
## C, Perl, PHP, Python, Ruby

**Update**: I've put together a jsfiddle that helps visualize the path through the code for each of the five languages: http://jsfiddle.net/wK6bD/4/embedded/result/

An alternative version, that removes all comments, and compresses all insignificant strings, regex and replacement patterns: http://jsfiddle.net/wK6bD/5/embedded/result/

And I saved a byte while I was at it. Turns out C had an unnecessary semi-colon ;)

```
#/*<?php ob_clean();"
s='''*/include<stdio.h>
main($y){char*$s,$t[3],$u[3]/*';'''
def printf(a,*b):import sys;sys.stdout.write(a%b)
for y in range(99,-1,-1):
  '''
99.downto(0){|y|$y=y;"/*=;#*/;
for($y=100;$y--;){
  #/*"
  $u=(($t=$y)+99)%100;'*/
  sprintf($t,"%d",$y);sprintf($u,"%d",($y+99)%100);
  #//';#'''
  printf("%s bottle%s of beer on the wall, %s bottle%s of beer.\n%s",
    #/* -- THIS LINE ENDS WITH CR --
    y//1or'No more','s'[:y!=1],y or'no more','''s*/
    +$y>0?$t:"No more",$s=$y!=1?"s":"",$y>0?$t:"no more",$s,$y>0?
    #//'''[:y!=1],y and'''
    "Take one down and pass it around":
    #//'''[6:38]or
    "Go to the store and buy some more");
  printf(", %s bottle%s of beer on the wall.\n\n",
    #/* -- THIS LINE ENDS WITH CR --
    y//1-1and~-y%100or'no more','''s*/
    +$y!=1?$u:"no more",$y!=2?"s":"");}
    #/*?><?php "
    %w;q(*/
    }//";#'''[:y!=2])

```

**Please Note**: This file needs to be saved with *mixed* line endings. All lines should be terminated with `LF` (char *10*, a.k.a. unix-style), except for the two lines marked `-- THIS LINE ENDS WITH CR --`, which should be terminated with `CR` (char *13*, a.k.a. mac-style). I recommend using notepad++, or other text editor which allows you to manually edit line endings.

For PHP, it is assumed that `output_buffering` is enabled. According to the documentation, this is hardcoded to be `Off` when using the CLI, regardless of `ini` settings, so it needs to be explicitly (re)enabled:

```
$ php -d output_buffering=4096 bottles.pl.php.py.rb.c

```

This enables a 4kb buffer, which is the 'recommended' value. If you're using one of the supplied `ini`s this will already be set, so it should run as-is from any web server.

The total file size is *823* bytes (not counting the comments about the line endings), an average of *164.6* bytes per language.

**Versions Tested**
**C** \- gcc 4.8.1, cl 15.00
**Perl** \- 5.16.2
**PHP** \- 5.4.16
**Python** \- 2.7.6, 3.3.4
**Ruby** \- 1.8.7, 1.9.3

Output is identical for all five languages (see below).

---

## Perl, PHP

```
<?php '>#'
;for($i='no more';100>($a="$i bottle".(2^($i+=1)?'s':'').' of beer');$o="
Take one down and pass it around, $b.

".ucfirst($f="$b, $a.$o")){$b="$a on the wall";}print"$f
Go to the store and buy some more, $b.";

```

I like this one because of how short it is, so I'm leaving it. It also demonstrates how much of a Perl-wanna-be PHP is ;)

Sample Usage:

```
$ perl bottles
99 bottles of beer on the wall, 99 bottles of beer.
Take one down and pass it around, 98 bottles of beer on the wall.

98 bottles of beer on the wall, 98 bottles of beer.
Take one down and pass it around, 97 bottles of beer on the wall.

...

2 bottles of beer on the wall, 2 bottles of beer.
Take one down and pass it around, 1 bottle of beer on the wall.

1 bottle of beer on the wall, 1 bottle of beer.
Take one down and pass it around, no more bottles of beer on the wall.

No more bottles of beer on the wall, no more bottles of beer.
Go to the store and buy some more, 99 bottles of beer on the wall.

```
> 58 votes

# Answer
# C + Ruby

```
#define do {
#define then {
#define end }
#define def int
#define nil {
#define print(a,b) printf("%d%s", a, b)

def bottle(i)
    nil

    print(i, (i==1)?" bottle":" bottles");
end

i=0;

def main()
    nil

    i = 99;
    while(i>=1) do
        bottle(i);
        puts(" of beer on the wall, ");
        bottle(i);
        puts(" of beer.\nTake one down and pass it around,");
        if(i==1) then
            break;
        end
        bottle(i-1);
        puts(" of beer on the wall.");
        puts("");
        i-=1;
    end
    puts("no more bottles of beer on the wall.");
    puts("");
    puts("No more bottles of beer on the wall,");
    puts("no more bottles of beer.");
    puts("Go to the store and buy some more,");
    puts("99 bottles of beer on the wall.");

end

#if 0
main
#endif

```

They're actually pretty similar once you normalize the syntax! :P
> 41 votes

# Answer
## JavaScript (SpiderMonkey/NodeJS), Perl, PHP, Ruby

**EDIT:** Added and `Ruby`

**EDIT 2:**

* Prints a title;
* Consistent output in all languages;
* No warnings.

The Code:

```
//#<?php
;
$i = 99;
$php = ![];
$o = 'of beer';
$ruby = 0x0 != '';
$t = $php ? '' : '//#';
$js = !$ruby && 1 + '0' == '10';
$s = 'Go to the store and buy some more, 99 bottles of beer on the wall.';
$c = 'print($t ." 99 BOTTLES OF BEER #\\\\\\\\\\n"); while($i>=0) {  $j = $i; $k = ($i-1); $b = $i!=1 ? " bottles " : " bottle "; print("\\n" .($i > 0 ? $j : "No more") .$b .$o ." on the wall, " .($i > 0 ? $j : "no more") .$b .$o .".\\n" .($i > 0 ? "Take one down and pass it around, " .($i > 1 ? $k : "no more") ." bottle" .($i != 2 ? "s " : " ") .$o ." on the wall." : $s) ."\\n"); $i-=1; }';
$c = $js ? $c.replace('."\\n"','').replace(RegExp(' [.]','g'),'+').replace(RegExp('print','g'), typeof(console) != 'undefined' ? 'console.log' : 'print') : $c;
$c = $ruby ? $c.gsub('{',"do\n").gsub('}',"\nend").gsub(' .',' << ').gsub('$i;','$i.to_s;').gsub('1)','1).to_s') : $c;
eval($c);

```

The output:

```
D:\>node polyglot
//# 99 BOTTLES OF BEER #\\

99 bottles of beer on the wall, 99 bottles of beer.
Take one down and pass it around, 98 bottles of beer on the wall.

98 bottles of beer on the wall, 98 bottles of beer.
Take one down and pass it around, 97 bottles of beer on the wall.
* * *
2 bottles of beer on the wall, 2 bottles of beer.
Take one down and pass it around, 1 bottle of beer on the wall.

1 bottle of beer on the wall, 1 bottle of beer.
Take one down and pass it around, no more bottles of beer on the wall.

No more bottles of beer on the wall, no more bottles of beer.
Go to the store and buy some more, 99 bottles of beer on the wall.

```
> 40 votes

# Answer
# C++ and PHP

I thought I'd give it a go.

EDIT: Compacted it a bit.

```
//99 BOTTLES OF BEER\\<br/><br/><?PHP function cat($a,$b){return $a.$b; }/*
#include<iostream>
#include<string>
#define echo(a) std::cout << a
#define cat(a,b) a<<b
int $bottles;
std::string $endline = "\n";
std::string $bottlesname;
int isset(std::string){ echo("//99 BOTTLES OF BEER\\\\\n\n"); return true; }
int main()
/**/
{
if(!isset($endline))
    $endline = "<br/>";
$bottles = 99;
$bottlesname = " bottles";
while( $bottles > 0 ){
    echo(cat(cat($bottles, $bottlesname ), " of beer on the wall, "));
    echo(cat(cat(cat(cat($bottles, $bottlesname ), " of beer."), $endline), "Take one down and pass it around, "));

    $bottlesname = --$bottles==1?" bottle":" bottles";
    if( $bottles == 0 )
        echo("no more");
    else
        echo($bottles);
    echo(cat(cat(cat($bottlesname," of beer on the wall."),$endline),$endline));
}
echo(cat("No more bottles of beer on the wall, no more bottles of beer.",$endline));
echo(cat(cat("Go to the store and buy some more, 99 bottles of beer on the wall.",$endline),$endline));;
}

```

This will compile fine as C++ and it will spit out some nice HTML if run through PHP. Either way, the output is:

```
//99 BOTTLES OF BEER\\

99 bottles of beer on the wall, 99 bottles of beer.
Take one down, pass it around, 98 bottles of beer on the wall.

98 bottles of beer on the wall, 98 bottles of beer.
Take one down, pass it around, 97 bottles of beer on the wall.

...

3 bottles of beer on the wall, 3 bottles of beer.
Take one down, pass it around, 2 bottles of beer on the wall.

2 bottles of beer on the wall, 2 bottles of beer.
Take one down, pass it around, 1 bottle of beer on the wall.

1 bottle of beer on the wall, 1 bottle of beer.
Take one down and pass it around, no more bottles of beer on the wall.

No more bottles of beer on the wall, no more bottles of beer.
Go to the store and buy some more, 99 bottles of beer on the wall.

```
> 15 votes

# Answer
# Haskell, PHP

Combining a functional and an imperative language!

```
{-0;}
function cast($x){ return $x; }
function bottle($n){
/*-}
import Prelude hiding ((.)){-*///-};(*/) = ($){-
/*-}
(.) = (++)
cast f = show $ f id
f :: Int -> [String]
f n = id */ return (cast($n) . " bottles of beer on the wall, " . cast($n) . "  bottles of beer.\nTake one down and pass it around, " . cast($n-1) . " bottles of beer on the wall.\n\n");
{-0;}};echo"<pre>";for($x=99;$x>1;$x-=1)echo bottle($x);echo/*-}
main = (\x->putStr$(concat$[99,98..2]>>=f)++x)*/"1 bottle of beer on the wall, 1 bottle of beer.\nTake one down and pass it around, no more bottles of beer on the wall.\n\nNo more bottles of beer on the wall, no more bottles of beer.\nGo to the store and buy some more, 99 bottles of beer on the wall.\n\n";

```

In Haskell, I defined the function `*/` that made working with PHP comments a lot easier!
> 14 votes

# Answer
# Brainfuck, English

Source for BF: http://www.99-bottles-of-beer.net/language-brainfuck-1718.html

```
++>+>++>>+>>>++++++++++[->+>+>++++++++++<<<]>>>>++++++++++[->+++++>++++++++++>++
+++++++++>++++++++>++++++++>+++>++++>+<<<<<<<<]+>--+>+++>++++++>--+>+++++>+++>++
+++>+>+>+>+>++>+>+>++[-<]<<<<<<<[->>[>>>>>>>>[<<<<<<<[->[-]>>>>>>>>>>>.<----.>>>
.<<<--.++.+++.+<-.+<<+<<<<<<<<]+>[-<[-]>>>>>[>>>+<<<<+<+<+>>>-]<<<[->>>+<<<]>[>>
>>>>+<<<<<<-]>>>>>[[-]>.<]<<<<[>>>>>-<<<<<-]>>[<<+<+<+>>>>-]<<<<[->>>>+<<<<]>[>>
>>>>+<<<<<<-]>>>>>>.<<<<<[>>>>>-<<<<<-]>>>[-<<<+<+>>>>]<<<<[->>>>+<<<<]>-[[-]>>>
>+<<<<]<<<]+>>>>>>>>>>>>>.<<<<----.>----.+++++..-<++++++++++.-------.<<[[-]>>>.<
<<]>>>>>>.<<<----.<+.>>>>.<<<<----.+++..+>+++.+[>]+>+>[->+<<-<-<<<.<<<----.-.>>>
.<<<++++++.<++.---.>>>>.<<<+++.<----.+++++++++++..------>---->------------------
-------------->>>++.-->..>>>]>>>[->[-]<<<<<<<[<]<[-]>>[>]>>>>>]+>[-<[-]<<<<[->>[
->+<<<<-<<<.<<<----.-.>>>.<<<++++++.<++.---.>>>>.<<<+++.<----.+++++++++++..-----
->---->++++++++++++++++++++++++++++++++>>>.<.>>>>>>]<<]<[->>>>[-<<+<<<<++.-->.[<
]<<<<<<<<[->[-]<]+>[-<[-]>>>>>>>>>>>>>.<<<-----.++++++++++.------.>>>>.<<<----.-
.<.>>>>.<<<<-.>+.++++++++.---------.>>>.<<<<---.>.<+++.>>>>.<<<++.<---.>+++..>>>
.<<<<++++++++.>+.>>>.<<<<--------.>--.---.++++++.-------.<+++.++>+++++>>>>.<.[<]
<<<<<<<]+>>>>>>-<<<+>>[<<[-]<+<+>>>>-]<<<<[>-<[-]]>[->>>+<<<]>[->->+++++++++<<]>
>>>>[>]>>>>]<<<<]>>>>>>]+<<<<<<<[<]<]+<+<<<<<<+<-]>>>>>>>>>>[>]>>>>>[->[-]<]+>[-
<[-]<<<<<<<<<-------------.<<----.>>>.<<<+++++.-----.>>>.<<<+++++.<++.---.>>>>.<
<<-.+.-----.+++.<.>>>>.<<<<----.>----.<+++.>>>>.<<<<--.>+++++++.++++.>>>.<<<----
--.----.--.<+++.>>>>.<<<.++.+++.+<.+>>>>>.<.>>>>>>>>>]+<[-]+<[-]<[-]<[-]+<<<[<]<
[-]<[-]<[-]<[-]++++++++++[->+>+>++++++++++<<<]>->->-<<<<<<[-]+<[-]<+<<]

[99 bottles of beer on the wall, 99 bottles of beer.
Take one down and pass it around, 98 bottles of beer on the wall.

98 bottles of beer on the wall, 98 bottles of beer.
Take one down and pass it around, 97 bottles of beer on the wall.

97 bottles of beer on the wall, 97 bottles of beer.
Take one down and pass it around, 96 bottles of beer on the wall.

96 bottles of beer on the wall, 96 bottles of beer.
Take one down and pass it around, 95 bottles of beer on the wall.

95 bottles of beer on the wall, 95 bottles of beer.
Take one down and pass it around, 94 bottles of beer on the wall.

94 bottles of beer on the wall, 94 bottles of beer.
Take one down and pass it around, 93 bottles of beer on the wall.

93 bottles of beer on the wall, 93 bottles of beer.
Take one down and pass it around, 92 bottles of beer on the wall.

92 bottles of beer on the wall, 92 bottles of beer.
Take one down and pass it around, 91 bottles of beer on the wall.

91 bottles of beer on the wall, 91 bottles of beer.
Take one down and pass it around, 90 bottles of beer on the wall.

90 bottles of beer on the wall, 90 bottles of beer.
Take one down and pass it around, 89 bottles of beer on the wall.

89 bottles of beer on the wall, 89 bottles of beer.
Take one down and pass it around, 88 bottles of beer on the wall.

88 bottles of beer on the wall, 88 bottles of beer.
Take one down and pass it around, 87 bottles of beer on the wall.

87 bottles of beer on the wall, 87 bottles of beer.
Take one down and pass it around, 86 bottles of beer on the wall.

86 bottles of beer on the wall, 86 bottles of beer.
Take one down and pass it around, 85 bottles of beer on the wall.

85 bottles of beer on the wall, 85 bottles of beer.
Take one down and pass it around, 84 bottles of beer on the wall.

84 bottles of beer on the wall, 84 bottles of beer.
Take one down and pass it around, 83 bottles of beer on the wall.

83 bottles of beer on the wall, 83 bottles of beer.
Take one down and pass it around, 82 bottles of beer on the wall.

82 bottles of beer on the wall, 82 bottles of beer.
Take one down and pass it around, 81 bottles of beer on the wall.

81 bottles of beer on the wall, 81 bottles of beer.
Take one down and pass it around, 80 bottles of beer on the wall.

80 bottles of beer on the wall, 80 bottles of beer.
Take one down and pass it around, 79 bottles of beer on the wall.

79 bottles of beer on the wall, 79 bottles of beer.
Take one down and pass it around, 78 bottles of beer on the wall.

78 bottles of beer on the wall, 78 bottles of beer.
Take one down and pass it around, 77 bottles of beer on the wall.

77 bottles of beer on the wall, 77 bottles of beer.
Take one down and pass it around, 76 bottles of beer on the wall.

76 bottles of beer on the wall, 76 bottles of beer.
Take one down and pass it around, 75 bottles of beer on the wall.

75 bottles of beer on the wall, 75 bottles of beer.
Take one down and pass it around, 74 bottles of beer on the wall.

74 bottles of beer on the wall, 74 bottles of beer.
Take one down and pass it around, 73 bottles of beer on the wall.

73 bottles of beer on the wall, 73 bottles of beer.
Take one down and pass it around, 72 bottles of beer on the wall.

72 bottles of beer on the wall, 72 bottles of beer.
Take one down and pass it around, 71 bottles of beer on the wall.

71 bottles of beer on the wall, 71 bottles of beer.
Take one down and pass it around, 70 bottles of beer on the wall.

70 bottles of beer on the wall, 70 bottles of beer.
Take one down and pass it around, 69 bottles of beer on the wall.

69 bottles of beer on the wall, 69 bottles of beer.
Take one down and pass it around, 68 bottles of beer on the wall.

68 bottles of beer on the wall, 68 bottles of beer.
Take one down and pass it around, 67 bottles of beer on the wall.

67 bottles of beer on the wall, 67 bottles of beer.
Take one down and pass it around, 66 bottles of beer on the wall.

66 bottles of beer on the wall, 66 bottles of beer.
Take one down and pass it around, 65 bottles of beer on the wall.

65 bottles of beer on the wall, 65 bottles of beer.
Take one down and pass it around, 64 bottles of beer on the wall.

64 bottles of beer on the wall, 64 bottles of beer.
Take one down and pass it around, 63 bottles of beer on the wall.

63 bottles of beer on the wall, 63 bottles of beer.
Take one down and pass it around, 62 bottles of beer on the wall.

62 bottles of beer on the wall, 62 bottles of beer.
Take one down and pass it around, 61 bottles of beer on the wall.

61 bottles of beer on the wall, 61 bottles of beer.
Take one down and pass it around, 60 bottles of beer on the wall.

60 bottles of beer on the wall, 60 bottles of beer.
Take one down and pass it around, 59 bottles of beer on the wall.

59 bottles of beer on the wall, 59 bottles of beer.
Take one down and pass it around, 58 bottles of beer on the wall.

58 bottles of beer on the wall, 58 bottles of beer.
Take one down and pass it around, 57 bottles of beer on the wall.

57 bottles of beer on the wall, 57 bottles of beer.
Take one down and pass it around, 56 bottles of beer on the wall.

56 bottles of beer on the wall, 56 bottles of beer.
Take one down and pass it around, 55 bottles of beer on the wall.

55 bottles of beer on the wall, 55 bottles of beer.
Take one down and pass it around, 54 bottles of beer on the wall.

54 bottles of beer on the wall, 54 bottles of beer.
Take one down and pass it around, 53 bottles of beer on the wall.

53 bottles of beer on the wall, 53 bottles of beer.
Take one down and pass it around, 52 bottles of beer on the wall.

52 bottles of beer on the wall, 52 bottles of beer.
Take one down and pass it around, 51 bottles of beer on the wall.

51 bottles of beer on the wall, 51 bottles of beer.
Take one down and pass it around, 50 bottles of beer on the wall.

50 bottles of beer on the wall, 50 bottles of beer.
Take one down and pass it around, 49 bottles of beer on the wall.

49 bottles of beer on the wall, 49 bottles of beer.
Take one down and pass it around, 48 bottles of beer on the wall.

48 bottles of beer on the wall, 48 bottles of beer.
Take one down and pass it around, 47 bottles of beer on the wall.

47 bottles of beer on the wall, 47 bottles of beer.
Take one down and pass it around, 46 bottles of beer on the wall.

46 bottles of beer on the wall, 46 bottles of beer.
Take one down and pass it around, 45 bottles of beer on the wall.

45 bottles of beer on the wall, 45 bottles of beer.
Take one down and pass it around, 44 bottles of beer on the wall.

44 bottles of beer on the wall, 44 bottles of beer.
Take one down and pass it around, 43 bottles of beer on the wall.

43 bottles of beer on the wall, 43 bottles of beer.
Take one down and pass it around, 42 bottles of beer on the wall.

42 bottles of beer on the wall, 42 bottles of beer.
Take one down and pass it around, 41 bottles of beer on the wall.

41 bottles of beer on the wall, 41 bottles of beer.
Take one down and pass it around, 40 bottles of beer on the wall.

40 bottles of beer on the wall, 40 bottles of beer.
Take one down and pass it around, 39 bottles of beer on the wall.

39 bottles of beer on the wall, 39 bottles of beer.
Take one down and pass it around, 38 bottles of beer on the wall.

38 bottles of beer on the wall, 38 bottles of beer.
Take one down and pass it around, 37 bottles of beer on the wall.

37 bottles of beer on the wall, 37 bottles of beer.
Take one down and pass it around, 36 bottles of beer on the wall.

36 bottles of beer on the wall, 36 bottles of beer.
Take one down and pass it around, 35 bottles of beer on the wall.

35 bottles of beer on the wall, 35 bottles of beer.
Take one down and pass it around, 34 bottles of beer on the wall.

34 bottles of beer on the wall, 34 bottles of beer.
Take one down and pass it around, 33 bottles of beer on the wall.

33 bottles of beer on the wall, 33 bottles of beer.
Take one down and pass it around, 32 bottles of beer on the wall.

32 bottles of beer on the wall, 32 bottles of beer.
Take one down and pass it around, 31 bottles of beer on the wall.

31 bottles of beer on the wall, 31 bottles of beer.
Take one down and pass it around, 30 bottles of beer on the wall.

30 bottles of beer on the wall, 30 bottles of beer.
Take one down and pass it around, 29 bottles of beer on the wall.

29 bottles of beer on the wall, 29 bottles of beer.
Take one down and pass it around, 28 bottles of beer on the wall.

28 bottles of beer on the wall, 28 bottles of beer.
Take one down and pass it around, 27 bottles of beer on the wall.

27 bottles of beer on the wall, 27 bottles of beer.
Take one down and pass it around, 26 bottles of beer on the wall.

26 bottles of beer on the wall, 26 bottles of beer.
Take one down and pass it around, 25 bottles of beer on the wall.

25 bottles of beer on the wall, 25 bottles of beer.
Take one down and pass it around, 24 bottles of beer on the wall.

24 bottles of beer on the wall, 24 bottles of beer.
Take one down and pass it around, 23 bottles of beer on the wall.

23 bottles of beer on the wall, 23 bottles of beer.
Take one down and pass it around, 22 bottles of beer on the wall.

22 bottles of beer on the wall, 22 bottles of beer.
Take one down and pass it around, 21 bottles of beer on the wall.

21 bottles of beer on the wall, 21 bottles of beer.
Take one down and pass it around, 20 bottles of beer on the wall.

20 bottles of beer on the wall, 20 bottles of beer.
Take one down and pass it around, 19 bottles of beer on the wall.

19 bottles of beer on the wall, 19 bottles of beer.
Take one down and pass it around, 18 bottles of beer on the wall.

18 bottles of beer on the wall, 18 bottles of beer.
Take one down and pass it around, 17 bottles of beer on the wall.

17 bottles of beer on the wall, 17 bottles of beer.
Take one down and pass it around, 16 bottles of beer on the wall.

16 bottles of beer on the wall, 16 bottles of beer.
Take one down and pass it around, 15 bottles of beer on the wall.

15 bottles of beer on the wall, 15 bottles of beer.
Take one down and pass it around, 14 bottles of beer on the wall.

14 bottles of beer on the wall, 14 bottles of beer.
Take one down and pass it around, 13 bottles of beer on the wall.

13 bottles of beer on the wall, 13 bottles of beer.
Take one down and pass it around, 12 bottles of beer on the wall.

12 bottles of beer on the wall, 12 bottles of beer.
Take one down and pass it around, 11 bottles of beer on the wall.

11 bottles of beer on the wall, 11 bottles of beer.
Take one down and pass it around, 10 bottles of beer on the wall.

10 bottles of beer on the wall, 10 bottles of beer.
Take one down and pass it around, 9 bottles of beer on the wall.

9 bottles of beer on the wall, 9 bottles of beer.
Take one down and pass it around, 8 bottles of beer on the wall.

8 bottles of beer on the wall, 8 bottles of beer.
Take one down and pass it around, 7 bottles of beer on the wall.

7 bottles of beer on the wall, 7 bottles of beer.
Take one down and pass it around, 6 bottles of beer on the wall.

6 bottles of beer on the wall, 6 bottles of beer.
Take one down and pass it around, 5 bottles of beer on the wall.

5 bottles of beer on the wall, 5 bottles of beer.
Take one down and pass it around, 4 bottles of beer on the wall.

4 bottles of beer on the wall, 4 bottles of beer.
Take one down and pass it around, 3 bottles of beer on the wall.

3 bottles of beer on the wall, 3 bottles of beer.
Take one down and pass it around, 2 bottles of beer on the wall.

2 bottles of beer on the wall, 2 bottles of beer.
Take one down and pass it around, 1 bottle of beer on the wall.

1 bottle of beer on the wall, 1 bottle of beer.
Take one down and pass it around, no more bottles of beer on the wall.

No more bottles of beer on the wall, no more bottles of beer.
Go to the store and buy some more, 99 bottles of beer on the wall.]

```
> 10 votes

# Answer
# PHP and 아희(Aheui)

```
<?php
$b = 99;
while(true) {
    echo ($b==0 ? "No more" : $b)." bottle".($b==1 ? "" : "s")." of beer on the wall, ".($b==0 ? "no more" : $b)." bottle".($b==1 ? "" : "s")." of beer.\n";
    if($b == 0) {
        echo "Go to the store and buy some more";
        $b = 99;
    }
    else {
        echo "Take one down and pass it around";
        $b--;
    }
    echo ", ".($b==0 ? "no more" : $b)." bottle".($b==1 ? "" : "s")." of beer on the wall.\n\n";
    if($b == 99) break;
}
/*
발발따밤따박박나타삭밤밣따산박밦따밞뚜
우어어어어어어어어어어어어어어어어어어
아우
오사뺘뿌처밞밞따받타맣산빠받다맣삭빠맣산빠박박나다맣빠받다맣빠밦다맣빠밝타맣수
오우어명여어어어어어어어어어어어어어어어어어어어어어어어어어어어어어어어어어어
오삭빠맣산빠발타발타맣빠받다맣빠밣다빠맣맣빠맣빠밝타맣수
오우어어어어어어어어어어어어어어멓더벍뻐선처우텨너벅벅뻐
오우어어어어어어어어어어어어어어어어어어어어어
오아삭빠맣산빠받다맣빠밦타맣삭빠맣산빠발타발타맣빠밝타빠맣맣빠밦다맣삭빠맣산빠받다맣빠박다뭏
오뭏뻐멓더벖더벖뻐석멓뻐멓뻐멓터벖터벌뻐멓더벖더벌뻐선멓뻐석멓터벍뻐멓터범뻐멓더벓뻐선멓뻐석
오사뺘뿌처산빠박다맣빠받다맣삭빠맣산빠박박나다맣빠받다맣빠밦다맣빠밝타맣수
오우어명여어어어어어어어어어어어어어어어어어어어어어어어어어어어어어어어어
오삭빠맣산빠발타발타맣빠받다맣빠밣다빠맣맣빠맣빠밝타맣수
오우어어어어어어어어어어어어어어멓더벍뻐선처우텨너벅벅뻐
오우어어어어어어어어어어어어어어어어어어어어어
오삭빠맣산빠받다맣빠밦타맣삭빠맣산빠발타발타맣빠밝타빠맣맣빠밦다맣밦밝따밤다맣발발다뭏
오우어어어어어어어어어어어어어어어어어어어어어어어어어어어어어어어어어어어어어어어어어
오사뺘우차박밦따밝따맣산빠발타밦타맣빠박박나타맣빠밝타맣삭빠맣산빠받다맣빠박다맣빠밝타뮿
오ㅇㅇ아아밣밣따밝다맣산빠받다맣삭빠맣산빠밣다맣빠받다맣삭빠맣산빠밣다맣빠밤타맣빠밝타뮿
오뮿뻐석멓터벓뻐멓더벅뻐멓터벖터벌뻐선멓뻐석멓더벅뻐멓더벖더벌뻐멓더벋뻐멓터벓뻐선멓뻐석
오유멓터벓뻐멓더벅뻐멓터벖터벌뻐선멓뻐석멓터벍뻐멓더벖뻐멓더벋뻐멓더벓뻐멓더벍뻐선멓뻐석
오삭산빠밤다맣빠발타밦타맣빠밝다빠맣맣삭빠맣산빠받타맣빠밣다맣삭빠뮿
초삭빠맣산빠발타발타맣빠밞다빠맣밤다맣삭빠맣산빠밝다맣빠받다맣빠박박나다맣빠밝타뮿
희유어어어어어멓터벓뻐멓더벅뻐멓더벎뻐멓더벋뻐멓더벖뻐멓터벖터벌뻐선
툐우어어어어어어어어어어어어어어어어어멓터벍뻐멓더벖뻐멓더벅멓뻐더너벅벅뻐선멓뻐석
토삭빠밦다밦다맣빠뭏
노우터너벅벅처불뼈서
복우더터너벅벅뱔뗘따볌
복사뺘뿌처산빠박다맣빠받다맣삭빠맣산빠박박나다맣빠받다맣빠밦다맣빠밝타맣수
또우어명여어어어어어어어어어어어어어어어어어어어어어어어어어어어어어어어어
봄삭빠맣산빠발타발타맣빠받다맣빠밣다빠맣맣빠맣빠밝타맣수
또우어어어어어어어어어어어어어어멓더벍뻐선처우텨너벅벅뻐
볼우어어어어어어어어어어어어어어어어어어어어어
볼아삭빠맣산빠받다맣빠밦타맣삭빠맣산빠발타발타맣빠밝타빠맣맣빠밦다맣삭빠맣산빠받다맣빠박다뭏
뽀불벌멓더벍더벍뻐석멓뻐멓뻐멓터벖터벌뻐멓더벖더벌뻐선멓뻐석멓터벍뻐멓터범뻐멓더벓뻐선멓뻐석
소댜몋빠몋

```

Aheui was tested with naheui.

I know it's cheating, but it works anyway.
> 7 votes

# Answer
This will work in Python 3 and in Julia.

```
[[print(b, " bottles of beer on the wall, ", b, " bottles of beer.\nTake one down and pass it around, ", b-1, " bottles of beer on the wall.\n" ) for b in l] for l in [[12 * i + j + 4 for j in [11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]] for i in [7, 6, 5, 4, 3, 2, 1, 0]]]
print("3 bottles of beer on the wall, 3 bottles of beer.\nTake one down and pass it around, 2 bottles of beer on the wall.\n")
print("2 bottles of beer on the wall, 2 bottles of beer.\nTake one down and pass it around, 1 bottle of beer on the wall.\n")
print("1 bottle of beer on the wall, 1 bottle of beer.\nTake one down and pass it around, no more bottles of beer on the wall.\n")
print("No more bottles of beer on the wall, no more bottles of beer.\nGo to the store and buy some more, 99 bottles of beer on the wall.\n")

```
> 6 votes

# Answer
BrainFuck and Python 2

This will compile and run under CPython2.7 (and probably others) as well as a BrainFuck interpreter. These are two distinct languages, with very little overlap, and this answer is totally cheating.

```
# Thanks to Raphael Bois for the code (taken from http://goo(dot)gl/GddKtS)
# ++>+>++>>+>>>:++++++++++[->+>+>++++++++++<<<]>>>>++++++++++[->+++++>++++++++++>+++++++++++>++++++++>++++++++>+++>++++>+<<<<<<<<]+>--+>+++>++++++>--+>+++++>+++>+++++>+>+>+>+>++>+>+>++[-<]<<<<<<<[->>[>>>>>>>>[<<<<<<<[->[-]>>>>>>>>>>>.<----.>>>.<<<--.++.+++.+<-.+<<+<<<<<<<<]+>[-<[-]>>>>>[>>>+<<<<+<+<+>>>-]<<<[->>>+<<<]>[>>>>>>+<<<<<<-]>>>>>[[-]>.<]<<<<[>>>>>-<<<<<-]>>[<<+<+<+>>>>-]<<<<[->>>>+<<<<]>[>>>>>>+<<<<<<-]>>>>>>.<<<<<[>>>>>-<<<<<-]>>>[-<<<+<+>>>>]<<<<[->>>>+<<<<]>-[[-]>>>>+<<<<]<<<]+>>>>>>>>>>>>>.<<<<----.>----.+++++..-<++++++++++.-------.<<[[-]>>>.<<<]>>===>>>>.<<<----.<+.>>>>.<<<<----.+++..+>+++.+[>]+>+>[->+<<-<-<<<.<<<----.-.>>>.<<<++++++.<++.---.>>>>.<<<+++.<----.+++++++++++..------>---->-------------------------------->>>++.-->..>>>]>>>[->[-]<<<<<<<[<]<[-]>>[>]>>>>>]+>[-<[-]<<<<[->>[->+<<<<-<<<.<<<----.-.>>>.<<<++++++.<++.---.>>>>.<<<+++.<----.+++++++++++..------>---->++++++++++++++++++++++++++++++++>>>.<.>>>>>>]<<]<[->>>>[-<<+<<<<++.-->.[<]<<<<<<<<[->[-]<]+>[-<[-]>>>>>>>>>>>>>.<<<-----.++++++++++.------.>>>>.<<<----.-.<.>>>>.<<<<-.>+.++++++++.---------.>>>.<<<<---.>.<+++.>>>>.<<<++.<---.>+++..>>>.<<<<++++++++.>+.>>>.<<<<--------.>--.---.++++++.-------.<+++.++>+++++>>>>.<.[<]<<<<<<<]+>>>>>>-<<<+>>[<<[-]<+<+>>>>-]<<<<[>-<[-]]>[->>>+<<<]>[->->+++++++++<<]>>>>>[>]>>>>]<<<<]>>>>>>]+<<<<<<<[<]<]+<+<<<<<<+<-]>>>>>>>>>>[>]>>>>>[->[-]<]+>[-<[-]<<<<<<<<<-------------.<<----.>>>.<<<+++++.-----.>>>.<<<+++++.<++.---.>>>>.<<<-.+.-----.+++.<.>>>>.<<<<----.>----.<+++.>>>>.<<<<--.>+++++++.++++.>>>.<<<------.----.--.<+++.>>>>.<<<.++.+++.+<.+>>>>>.<.>>>>>>>>>]+<[-]+<[-]<[-]<[-]+<<<[<]<[-]<[-]<[-]<[-]++++++++++[->+>+>++++++++++<<<]>->->-<<<<<<[-]+<[-]<+<<]

dot = chr(46)
comma = chr(44)

for x in range(99, 2, -1):
    print """%d bottles of beer on the wall%s %d bottles of beer%s
Take one down and pass it around%s %d bottles of beer on the wall%s
""" % (x, comma, x, dot, comma, x - 1, dot)

print """2 bottles of beer on the wall%s 2 bottles of beer%s
Take one down and pass it around%s 1 bottle of beer on the wall%s

1 bottle of beer on the wall%s 1 bottle of beer%s
Take one down and pass it around%s no more bottles of beer on the wall%s

No more bottles of beer on the wall%s no more bottles of beer%s
Go to the store and buy some more%s 99 bottles of beer on the wall%s""" % (comma, dot, comma, dot, comma, dot, comma, dot, comma, dot, comma, dot)

```

The second line is the BrainFuck-run code. BrainFuck interpreters should ignore the rest of the code, and online interpreters will run it.

The rest of the code is the Python code. Originally it was just going to print the entire set of lyrics, but that's not as fun. The same was also going to be done for the BrainFuck code, but it blew by the character restrictions in posts (by about 270,000 characters).
> 5 votes

# Answer
# **Lua and (F)ASM**

```
S=10;--[[
irp x,<display 'The beer song:',13,10>,<rept 101 d:0\{reverse match,\\{j equ 'If one bottle of beer should accidently fall ...',13,10\\}match,\\{p equ 's'\\}match,\\{q equ \`d\\}match=1,d\\{p equ ''\\}match=0,d\\{q equ 'no'\\}match=0,d\\{j equ 'Who drunk all the beer!',13,10\\}match f,q\\{display q,' bottle',p,' of beer on the wall, ',q,' bottle',p,' of beer,',13,10,j\\}\}>{x}
S=10;]]--
S=10; beer=99
S=10; repeat
S=10; print(beer.." bottles of beer on the wall, "..beer.." bottles")
S=10; beer=beer-1
S=10; print("Take one down and pass it around, "..beer.." bottles of beer on the wall.")
S=10; print()
S=10; until beer==1
S=10; print("1 bottle of beer on the wall, 1 bottle of beer.")
S=10; print("Take one down and pass it around, no more bottles of beer on the wall.")
S=10; print()
S=10; print("No more bottles of beer on the wall, no more bottles of beer.")

```

Credits to Revolution for the Fasm one liner, even though everything in between line 1 and 3 is ignored by Lua so I could have writte an aribitrary long fasm program in there.

The trick is that in lua you can use a semicolon to separate instruction, to write multiple instructions on the same line, while in fasm a semicolon is the beginning a comment. S=10; is a valid assignement in both languages, everything else is fairly obvious
> 4 votes

# Answer
# J, Python 2.x

I'm a little late to the party, but oh well. Nothing too fancy here, because it's my first time polyglotting. Python is quite impossible to be properly mixed with J; so I basically commented J out in Python and made Python a string literal in J. I'll probably add more languages later.

```
(''''"_)`(''"_)@.(1) 1
number =: 'No more'"_`('no more'"_)@.([ = 0:)`(":@])@.(] > 0:)
bottle =: number , {.&' bottles'@(8: - =&1@])
verse1 =: 1&bottle, ' of beer on the wall, '"_, bottle, ' of beer.'"_
verse2 =: 'Take one down and pass it around, '"_, bottle@<:, ' of beer on the wall.'"_
verse  =: verse1 ,: verse2
song   =: (<:@[ $: ] , verse@[ , ''"_)`(] , verse1@[)@.([ < 1:)
sing   =: (] song ''"_) , 'Go to the store and buy some more, '"_ , bottle , ' of beer on the wall.'"_
sing ". 2 {. 0 : 0
99''')
print(lambda x:x(x,99,lambda c,w=1,p=0:"%s %s of beer%s"%(c or"nN"[p]+"o more","bottle"+"s"*(c!=1)," on the wall"*w)))(lambda x,c,y:c+1and"%s, %s.\n%s"%(y(c,1,1),y(c,0),"Take one down and pass it around, %s.\n\n"%y(c-1)*(c>0))+x(x,c-1,y)or"Go to the store and buy some more, %s.\n"%y(99)
)

```
> 3 votes

# Answer
## C# + Ruby

```
using System;

namespace bottles
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int i = 99; i >= 0; i--)
                Console.WriteLine("{0} bottles", i);
        }
    }
}

/*
#!/usr/bin/ruby

99.downto(0){|i|
print i.to_s+" bottles\n"
}

__END__
*/

```

to run (Ruby):
ruby -x script.cs
> 2 votes

# Answer
This should work in C, C++ and Objective-C. Objective-C++ has not been tested but will probably work:

```
#include <stdio.h>

int main(void)
{
        int b;

        for (b = 99; b >= 0; b--) {
                switch (b) {
                case 0:
                        printf("No more bottles of beer on the wall, no more bottles of beer.\n");
                        printf("Go to the store and buy some more, 99 bottles of beer on the wall.\n");
                        break;
                case 1:
                        printf("1 bottle of beer on the wall, 1 bottle of beer.\n");
                        printf("Take one down and pass it around, no more bottles of beer on the wall\n");
                        break;
                default:
                        printf("%d bottles of beer on the wall, %d bottles of beer.\n", b, b);
                         printf("Take one down and pass it around, %d %s of beer on the wall.\n" ,b - 1,((b - 1) > 1)? "bottles" : "bottle");
                        break;
                }
        }

        return 0;
}

```
> 0 votes

# Answer
# Ruby, Golfscript

```
"#{File.write('out.txt', "99 bottles of beer on the wall,
99 bottles of beer.
Take one down, pass it around,
98 bottles of beer on the wall.

98 bottles of beer on the wall,
98 bottles of beer.
Take one down, pass it around,
97 bottles of beer on the wall.

97 bottles of beer on the wall,
97 bottles of beer.
Take one down, pass it around,
96 bottles of beer on the wall.

96 bottles of beer on the wall,
96 bottles of beer.
Take one down, pass it around,
95 bottles of beer on the wall.

95 bottles of beer on the wall,
95 bottles of beer.
Take one down, pass it around,
94 bottles of beer on the wall.

94 bottles of beer on the wall,
94 bottles of beer.
Take one down, pass it around,
93 bottles of beer on the wall.

93 bottles of beer on the wall,
93 bottles of beer.
Take one down, pass it around,
92 bottles of beer on the wall.

92 bottles of beer on the wall,
92 bottles of beer.
Take one down, pass it around,
91 bottles of beer on the wall.

91 bottles of beer on the wall,
91 bottles of beer.
Take one down, pass it around,
90 bottles of beer on the wall.

90 bottles of beer on the wall,
90 bottles of beer.
Take one down, pass it around,
89 bottles of beer on the wall.

89 bottles of beer on the wall,
89 bottles of beer.
Take one down, pass it around,
88 bottles of beer on the wall.

88 bottles of beer on the wall,
88 bottles of beer.
Take one down, pass it around,
87 bottles of beer on the wall.

87 bottles of beer on the wall,
87 bottles of beer.
Take one down, pass it around,
86 bottles of beer on the wall.

86 bottles of beer on the wall,
86 bottles of beer.
Take one down, pass it around,
85 bottles of beer on the wall.

85 bottles of beer on the wall,
85 bottles of beer.
Take one down, pass it around,
84 bottles of beer on the wall.

84 bottles of beer on the wall,
84 bottles of beer.
Take one down, pass it around,
83 bottles of beer on the wall.

83 bottles of beer on the wall,
83 bottles of beer.
Take one down, pass it around,
82 bottles of beer on the wall.

82 bottles of beer on the wall,
82 bottles of beer.
Take one down, pass it around,
81 bottles of beer on the wall.

81 bottles of beer on the wall,
81 bottles of beer.
Take one down, pass it around,
80 bottles of beer on the wall.

80 bottles of beer on the wall,
80 bottles of beer.
Take one down, pass it around,
79 bottles of beer on the wall.

79 bottles of beer on the wall,
79 bottles of beer.
Take one down, pass it around,
78 bottles of beer on the wall.

78 bottles of beer on the wall,
78 bottles of beer.
Take one down, pass it around,
77 bottles of beer on the wall.

77 bottles of beer on the wall,
77 bottles of beer.
Take one down, pass it around,
76 bottles of beer on the wall.

76 bottles of beer on the wall,
76 bottles of beer.
Take one down, pass it around,
75 bottles of beer on the wall.

75 bottles of beer on the wall,
75 bottles of beer.
Take one down, pass it around,
74 bottles of beer on the wall.

74 bottles of beer on the wall,
74 bottles of beer.
Take one down, pass it around,
73 bottles of beer on the wall.

73 bottles of beer on the wall,
73 bottles of beer.
Take one down, pass it around,
72 bottles of beer on the wall.

72 bottles of beer on the wall,
72 bottles of beer.
Take one down, pass it around,
71 bottles of beer on the wall.

71 bottles of beer on the wall,
71 bottles of beer.
Take one down, pass it around,
70 bottles of beer on the wall.

70 bottles of beer on the wall,
70 bottles of beer.
Take one down, pass it around,
69 bottles of beer on the wall.

69 bottles of beer on the wall,
69 bottles of beer.
Take one down, pass it around,
68 bottles of beer on the wall.

68 bottles of beer on the wall,
68 bottles of beer.
Take one down, pass it around,
67 bottles of beer on the wall.

67 bottles of beer on the wall,
67 bottles of beer.
Take one down, pass it around,
66 bottles of beer on the wall.

66 bottles of beer on the wall,
66 bottles of beer.
Take one down, pass it around,
65 bottles of beer on the wall.

65 bottles of beer on the wall,
65 bottles of beer.
Take one down, pass it around,
64 bottles of beer on the wall.

64 bottles of beer on the wall,
64 bottles of beer.
Take one down, pass it around,
63 bottles of beer on the wall.

63 bottles of beer on the wall,
63 bottles of beer.
Take one down, pass it around,
62 bottles of beer on the wall.

62 bottles of beer on the wall,
62 bottles of beer.
Take one down, pass it around,
61 bottles of beer on the wall.

61 bottles of beer on the wall,
61 bottles of beer.
Take one down, pass it around,
60 bottles of beer on the wall.

60 bottles of beer on the wall,
60 bottles of beer.
Take one down, pass it around,
59 bottles of beer on the wall.

59 bottles of beer on the wall,
59 bottles of beer.
Take one down, pass it around,
58 bottles of beer on the wall.

58 bottles of beer on the wall,
58 bottles of beer.
Take one down, pass it around,
57 bottles of beer on the wall.

57 bottles of beer on the wall,
57 bottles of beer.
Take one down, pass it around,
56 bottles of beer on the wall.

56 bottles of beer on the wall,
56 bottles of beer.
Take one down, pass it around,
55 bottles of beer on the wall.

55 bottles of beer on the wall,
55 bottles of beer.
Take one down, pass it around,
54 bottles of beer on the wall.

54 bottles of beer on the wall,
54 bottles of beer.
Take one down, pass it around,
53 bottles of beer on the wall.

53 bottles of beer on the wall,
53 bottles of beer.
Take one down, pass it around,
52 bottles of beer on the wall.

52 bottles of beer on the wall,
52 bottles of beer.
Take one down, pass it around,
51 bottles of beer on the wall.

51 bottles of beer on the wall,
51 bottles of beer.
Take one down, pass it around,
50 bottles of beer on the wall.

50 bottles of beer on the wall,
50 bottles of beer.
Take one down, pass it around,
49 bottles of beer on the wall.

49 bottles of beer on the wall,
49 bottles of beer.
Take one down, pass it around,
48 bottles of beer on the wall.

48 bottles of beer on the wall,
48 bottles of beer.
Take one down, pass it around,
47 bottles of beer on the wall.

47 bottles of beer on the wall,
47 bottles of beer.
Take one down, pass it around,
46 bottles of beer on the wall.

46 bottles of beer on the wall,
46 bottles of beer.
Take one down, pass it around,
45 bottles of beer on the wall.

45 bottles of beer on the wall,
45 bottles of beer.
Take one down, pass it around,
44 bottles of beer on the wall.

44 bottles of beer on the wall,
44 bottles of beer.
Take one down, pass it around,
43 bottles of beer on the wall.

43 bottles of beer on the wall,
43 bottles of beer.
Take one down, pass it around,
42 bottles of beer on the wall.

42 bottles of beer on the wall,
42 bottles of beer.
Take one down, pass it around,
41 bottles of beer on the wall.

41 bottles of beer on the wall,
41 bottles of beer.
Take one down, pass it around,
40 bottles of beer on the wall.

40 bottles of beer on the wall,
40 bottles of beer.
Take one down, pass it around,
39 bottles of beer on the wall.

39 bottles of beer on the wall,
39 bottles of beer.
Take one down, pass it around,
38 bottles of beer on the wall.

38 bottles of beer on the wall,
38 bottles of beer.
Take one down, pass it around,
37 bottles of beer on the wall.

37 bottles of beer on the wall,
37 bottles of beer.
Take one down, pass it around,
36 bottles of beer on the wall.

36 bottles of beer on the wall,
36 bottles of beer.
Take one down, pass it around,
35 bottles of beer on the wall.

35 bottles of beer on the wall,
35 bottles of beer.
Take one down, pass it around,
34 bottles of beer on the wall.

34 bottles of beer on the wall,
34 bottles of beer.
Take one down, pass it around,
33 bottles of beer on the wall.

33 bottles of beer on the wall,
33 bottles of beer.
Take one down, pass it around,
32 bottles of beer on the wall.

32 bottles of beer on the wall,
32 bottles of beer.
Take one down, pass it around,
31 bottles of beer on the wall.

31 bottles of beer on the wall,
31 bottles of beer.
Take one down, pass it around,
30 bottles of beer on the wall.

30 bottles of beer on the wall,
30 bottles of beer.
Take one down, pass it around,
29 bottles of beer on the wall.

29 bottles of beer on the wall,
29 bottles of beer.
Take one down, pass it around,
28 bottles of beer on the wall.

28 bottles of beer on the wall,
28 bottles of beer.
Take one down, pass it around,
27 bottles of beer on the wall.

27 bottles of beer on the wall,
27 bottles of beer.
Take one down, pass it around,
26 bottles of beer on the wall.

26 bottles of beer on the wall,
26 bottles of beer.
Take one down, pass it around,
25 bottles of beer on the wall.

25 bottles of beer on the wall,
25 bottles of beer.
Take one down, pass it around,
24 bottles of beer on the wall.

24 bottles of beer on the wall,
24 bottles of beer.
Take one down, pass it around,
23 bottles of beer on the wall.

23 bottles of beer on the wall,
23 bottles of beer.
Take one down, pass it around,
22 bottles of beer on the wall.

22 bottles of beer on the wall,
22 bottles of beer.
Take one down, pass it around,
21 bottles of beer on the wall.

21 bottles of beer on the wall,
21 bottles of beer.
Take one down, pass it around,
20 bottles of beer on the wall.

20 bottles of beer on the wall,
20 bottles of beer.
Take one down, pass it around,
19 bottles of beer on the wall.

19 bottles of beer on the wall,
19 bottles of beer.
Take one down, pass it around,
18 bottles of beer on the wall.

18 bottles of beer on the wall,
18 bottles of beer.
Take one down, pass it around,
17 bottles of beer on the wall.

17 bottles of beer on the wall,
17 bottles of beer.
Take one down, pass it around,
16 bottles of beer on the wall.

16 bottles of beer on the wall,
16 bottles of beer.
Take one down, pass it around,
15 bottles of beer on the wall.

15 bottles of beer on the wall,
15 bottles of beer.
Take one down, pass it around,
14 bottles of beer on the wall.

14 bottles of beer on the wall,
14 bottles of beer.
Take one down, pass it around,
13 bottles of beer on the wall.

13 bottles of beer on the wall,
13 bottles of beer.
Take one down, pass it around,
12 bottles of beer on the wall.

12 bottles of beer on the wall,
12 bottles of beer.
Take one down, pass it around,
11 bottles of beer on the wall.

11 bottles of beer on the wall,
11 bottles of beer.
Take one down, pass it around,
10 bottles of beer on the wall.

10 bottles of beer on the wall,
10 bottles of beer.
Take one down, pass it around,
9 bottles of beer on the wall.

9 bottles of beer on the wall,
9 bottles of beer.
Take one down, pass it around,
8 bottles of beer on the wall.

8 bottles of beer on the wall,
8 bottles of beer.
Take one down, pass it around,
7 bottles of beer on the wall.

7 bottles of beer on the wall,
7 bottles of beer.
Take one down, pass it around,
6 bottles of beer on the wall.

6 bottles of beer on the wall,
6 bottles of beer.
Take one down, pass it around,
5 bottles of beer on the wall.

5 bottles of beer on the wall,
5 bottles of beer.
Take one down, pass it around,
4 bottles of beer on the wall.

4 bottles of beer on the wall,
4 bottles of beer.
Take one down, pass it around,
3 bottles of beer on the wall.

3 bottles of beer on the wall,
3 bottles of beer.
Take one down, pass it around,
2 bottles of beer on the wall.

2 bottles of beer on the wall,
2 bottles of beer.
Take one down, pass it around,
1 bottle of beer on the wall.

1 bottle of beer on the wall,
1 bottle of beer.
Take one down, pass it around,
No bottles of beer on the wall.

No bottles of beer on the wall,
No bottles of beer.
Go to the store, buy some more,
99 bottles of beer on the wall.")}"

```
> 0 votes

---
Tags: popularity-contest, polyglot
---


title: What time is it?

text:
# Question
Title: What time is it?
I really hate looking up to the top right of the screen to look at the time on OS X's clock widget; I'd much rather keep my eyes at least *somewhere* near my workspace to check the time. I also hate other people using *my* clock to check the time as they walk by -- after all, it's called a personal computer, right? But we've got a great community here that can surely help me out, right? So here's my really really so much very hard challenge for you guys that would help me so much: write me a clock app. It can be analog or digital or whatever other amazing forms you can think of. Minimum requirements:

* It should be very visible
* It should display the time in a format that not many people would comprehend (the less people, the better)

This is a popularity contest, so fulfill these requirements creatively, and go above and beyond! Ready... Set... Go!

# Answer
# Bash

```
#!/bin/bash

T="The time is now:"

case $1 in
--12)    F=82;M=0;S=%r;;
--24)    F=120;M=100;S=%R;;
--ipv6)  F=112;M=0;S=%H::%M:%S;T="Started download from:";;
--posix) F=82;M=0;S=%s;;
esac

watch 'notify-send "'"$T"'" "<div style=\"font-size:'"$F"'px;margin-left:'"$M"'px;\">
    $(date +'"$S"')</div>"'

```

Displays the current time as a desktop notification, updating every two seconds.

### Usage

```
whattimeisit FORMAT

--12     May be understood by Australians, Chinese and North Americans.
--24     May be understood by everyone else.
--ipv6   May be understood by illiterates.
--posix  May be understood by nerds.

```

### Example output
> 8 votes

# Answer
# Javascript

This encodes the hours, minutes, and seconds, as hex, and sets the background color of the page to the concatenation of the string. For example, for the time 9:18:13 PM, the background color would be set to `#15120D`. It is right on a webpage for you, all you have to do is drag a little bit of the window to a different place on the screen or flip tabs. Here is a JSFiddle demo.

To tell the time, you can use your handy color-picking and base changing skills.

```
function hex(number) {
    return number.toString(16).length == 1 ? "0" + number.toString(16): number.toString(16);
}
var display = function() {

    var now = new Date();
    var base = "00"
    var hours = hex(now.getHours());
    var minutes = hex(now.getMinutes());
    var seconds = hex(now.getSeconds());
    document.body.style.background = "#" + hours + minutes + seconds;
    console.log("#" + hours + minutes + seconds)
}

setInterval(display, 1000);

```
> 6 votes

# Answer
## HTML + CSS + JavaScript

I made a binary clock, pretty self-explanatory. I have a binary watch and even those who know what binary numbers are may have a hard time telling what time it is sometimes. Like scrblnrd3 said in his answer, all you have to do is position your browser window properly to make it visible. Here's a fiddle of clock in action.

P.S.: The hour part has 5 positions in order to support 24 hour format.

**JavaScript**

```
function pad(number, digits) {
    return Array(Math.max(digits - String(number).length + 1, 0)).join(0) + number;
}

var updateClock = function() {
    var date = new Date();

    var childDivs = [
        document.getElementsByClassName('hours')[0].children,
        document.getElementsByClassName('minutes')[0].children,
        document.getElementsByClassName('seconds')[0].children
    ];

    var binaryTime = [
        pad(date.getHours().toString(2), 5),
        pad(date.getMinutes().toString(2), 6),
        pad(date.getSeconds().toString(2), 6)
    ];

    for(i=0; i < childDivs.length; i++) {
        for(j=0; j < childDivs[i].length; j++) {
            childDivs[i][j].className = binaryTime[i][j] == '1' ? 'highlight' : '';
        }
     }
}

setInterval(updateClock, 1000);

```

**CSS**

```
.wrapper div {
    width: 30px;
    height: 30px;
    border-radius: 50px;
    border: 1px solid black;
    display: inline-block;
    margin: auto;
}

.highlight {
    background-color: green;
}

```

**HTML**

```
<div class="wrapper hours">
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
</div>
<div class="wrapper minutes">
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
</div>
<div class="wrapper seconds">
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
</div>

```
> 1 votes

# Answer
## C

I have been finding it annoying, that though computers can easily keep time with an accuracy of a few ms by using NTP, some software displaying time haven't bothered with updating it at the right time. For example if you display time with hours and minutes by simply displaying the time and then sleep for 60 seconds in a loop, the displayed clock will on average be 30 seconds behind.

Here is my suggestion on how to implement a highly accurate clock (which displays time as seconds since midnight GMT in octal).

```
#include <stdio.h>
#include <time.h>
#include <sys/time.h>

int main()
{
  struct timeval tv;
  struct timespec ts;
  while (1) {
    do {
      gettimeofday(&tv,NULL);
    } while ((ts.tv_nsec=((999999-tv.tv_usec)*1000)-1)<1);
    printf("\x0d%lo    ", tv.tv_sec%86400);
    fflush(stdout);
    ts.tv_sec=0;
    nanosleep(&ts,NULL);
  }
}

```

> Replace the `printf` with `s=ctime(&tv.tv_sec);` `c=strchr(s,'\n');` `if (c) *c=0;` `printf("\x0d%s ",s);` if you want human readable output.
> 1 votes

# Answer
## Javascript

This is an ASCII clock with A=0.

```
<body onload="tick()">
    <p id="p">0</p>
    <script>
        function tick() {
            console.log("tick");
            var a = "A";
            var i = a.charCodeAt(0);
            var dt = new Date();
            var h = String.fromCharCode(i+dt.getHours());
            var m = String.fromCharCode(i+dt.getMinutes());
            var s = String.fromCharCode(i+dt.getSeconds());
            var t = h+":"+m+":"+s;
            document.getElementById("p").innerHTML = t;
            setTimeout('tick()',1000);
        }
    </script>
</body>

```
> 0 votes

---
Tags: popularity-contest, clock
---


title: Let's move the Mars rover!

text:
# Question
Title: Let's move the Mars rover!
## Summary

The task is to navigate the Mars rover and tell its final coordinates and direction.

# Input:

## First input:

First your program must take the input which will be in the following format:

```
[X-Coordinate],[Y-Coordinate],[Direction]

```

The direction must be: `N` or `S` or `E` or `W` (Starting letters of North, South, West, East)

Example: `10,20,N` ( x = 10, y = 20, direction = N(North))

## Second input:

The second input consists of series of `R`, `L`, `M` for right, left and move respectively.

For `R` and `L` (right and left) the direction of rover must change accordingly.

For `M` the rover must move 1 unit ahead in the direction which it was before moving.

Rules for calculating coordinates:

```
N = Y + 1
E = X + 1
S = Y - 1
W = X - 1

```

## Output:

The final coordinates and the current direction of the rover.

---

Example:
```
Enter initial data:      1,2,N

Enter the instructions:  MRMLM

Output:                  2,4,N

```

The coordinates can be any integer and can be **negative**.

All the standard loopholes aren't allowed. If providing demo on sites like http://ideone.com etc. is possible, then please do so, so that I can verify :)

This is a popularity contest so be creative!

Following others' advice, I decide to make this a .

# Answer
## Ruby ≥ 2.0, 101

```
E,N,W,S=*0..3
x,y,i=eval"a="+gets
gets.bytes{|c|x+=c%2*1i**i=i+1-c&3}
$><<[(x+y.i).rect,"NWSE"[i]]*?,

```

This solution can be tested here: https://ideone.com/C4PLdE

Note that the solution linked on ideone is one character longer (`1.i` instead of `1i` in line 3). The reason for this is that ideone only supports Ruby 1.9, which doesn't allow the short-hand syntax for complex literals.
> 7 votes

# Answer
# Javascript (*ES6*) 145 141 127

*Edit:* Removed the need for a translation array using method from edc65's C solution

```
[x,y,d]=(p=prompt)(s='NESW').split(','),[...p(d=s.search(d))].map(c=>c!='M'?(d+=c>'M'||3,d%=4):d%2?x-=d-2:y-=d-1),p([x,y,s[d]])

```

**Ungolfed/Commented:**

```
s='NESW' // initialize variable for direction mapping
[x,y,d]=prompt().split(',') // get first input, split by commas, map to variables x,y,d
d=s.search(d) // get numeric value for direction
[...prompt()].map(c=> // get second input, map a function to every character in it
    c!='M'? // if char is not M
        (d+=c>'M'||3, // increment d by 1 if char greater than M, otherwise 3
         d%=4) // modulo by 4 to wrap direction
    : // else
        d%2? // if odd direction
            x-=d-2 // move x position
        : // else
            y-=d-1 // move y position
)
prompt([x,y,s[d]]) // output result

```
> 5 votes

# Answer
# Javascript (E6) 175

**Edit** Fixed bug, possibly out of range return value for d

139 Logic, 36 I/O

```
F=(x,y,d,m,D='NESW')=>(d=D.search(d),[...m].map(s=>({M:_=>(y-=[-1,0,1,0][d],x-=[0,-1,0,1][d]),R:_=>d+=1,L:_=>d+=3}[s](),d%=4)),[x,y,D[d]]);
p=prompt,p(F(...p().split(','),p()))

```

**Basic ungolfed**

```
function F(x,y,d,m) // In golf code use arrow sintax instead of 'function'
{
  var D='NESW';
  d = D.search(d); // map from letters to offset position 0..3
  var driver = { // driver object, each function map one of  command letters M,R,L
    M: function() {
      y -= [-1, 0, 1, 0][d]; // subtract to be sure to have a numeric and not string result
      x -= [0, -1, 0, 1][d]; // subtract to be sure to have a numeric and not string result
    },
    R: function() {
       d += 1;
    },
    L: function() {
       d += 3; // with modulo 4 will be like -= 1
    }
  }
  m = [...m]; // string to array, to use iteration function
  m.forEach(  // array scan, in golf versione use map do nearly the same and is shorter
    function (s) {
      driver[s](); // call driver function
      d = d % 4;   // restrict value to modulo 4
    }
  );  // in golf version, use comma separated expression to avoid 'return'
  return [x,y, D[d]] // return last status
}

```

**Test** Test in javascript console in Firefox. It's simpler to test the function F avoiding the popups.

```
F(1,2,'N','MRMLM')

```

Output

```
[ 2, 4, "N" ]

```
> 3 votes

# Answer
# Java - 327

```
class R{public static void main(String[]a){char c,e=a[2].charAt(0),z[]={78,69,83,87};Integer x=Integer.valueOf(a[0]),y=x.valueOf(a[1]),d=e<70?1:e==83?2:e>86?3:0,i=0;for(;i<a[3].length();d=c>81?(d+1)%4:c<77?(d+3)%4:d){c=a[3].charAt(i++);if(c==77){x=d==1?x+1:d>2?x-1:x;y=d<1?y+1:d==2?y+1:y;}}System.out.print(x+","+y+","+z[d]);}}

```

With whitespace:

```
class R{
    public static void main(String[]a){
        char c,e=a[2].charAt(0),z[]={78,69,83,87};
        Integer x=Integer.valueOf(a[0]),y=x.valueOf(a[1]),d=e<70?1:e==83?2:e>86?3:0,i=0;
        for(;i<a[3].length();d=c>81?(d+1)%4:c<77?(d+3)%4:d){
            c=a[3].charAt(i++);
            if(c==77){
                x=d==1?x+1:d>2?x-1:x;
                y=d<1?y+1:d==2?y+1:y;
            }
        }
        System.out.print(x+","+y+","+z[d]);
    }
}

```

As usual with Java, about half of this is just parsing the input and forming the output. The logic is pretty straightforward.
> 3 votes

# Answer
# C 164 ~~180 186~~

**Edit** Fixed input format and removed strchr
**Edit** Removed offset array, calc using bits

```
p,x,y;main(){char c,d,l[100];scanf("%d,%d,%c%s",&x,&y,&d,l);for(d=d<83?d&1:d>>2&1|2;c=l[p++];d&=3)c-77?d+=c+1:d&1?x+=d-2:(y+=1-d);printf("%d %d %c",x,y,"NESW"[d]);}

```

**Ungolfed**

```
p, x, y;
main()
{
  char c, d, l[100];
  scanf("%d,%d,%c%s",&x,&y,&d,l);
  for (d = d<'S'?d&1:d>>2&1|2; c = l[p++]; d &= 3)
    c-'M'
    ? d += c+1
    : d & 1 ? x+=d-2 : (y+=1-d);
  printf("%d %d %c", x, y, "NESW"[d]);
}
/*
M 77
R 82 0101 0010 R&3+1==3
L 76 0100 1100 L&3+1==1
*/

```
> 3 votes

# Answer
# C, 148 ~~150~~ ~~151~~

```
p,x[2];main(){char c,d,l[99],*j="%d,%d,%c%s";scanf(j,x,x+1,&d,l);for(d=d%8%5;c=l[p++];d-=c%23)x[d&1]-=c%2*~-(d&2);printf(j,*x,x[1],"ENWS"[d&3],"");}

```

A tweak of @edc65's solution to use my ASCII value abuse approach.

Specifically:

* `d%8%5` maps the characters `ENWS` to `0,1,2,3` respectively
* `c%23` turns `L` into `7`, `M` into `8` and `R` into 13. Because `d` (the direction variable) is always used mod 4, this effectively makes `L` add -1 mod 4, `M` add 0 mod 4, and `R` add 1 mod 4.
* `d&1` is 1 for `NS` and 0 for `EW` directions.
* `d&2` is 2 for `WS` and 0 for `NE` directions.
* `~-(d&2)` is 1 for `WS` and -1 for `NE` directions.
* `c%2` is 1 for `M` and 0 for `LR`.
> 2 votes

# Answer
# Python 3 (with turtle graphics), 251 199 bytes

Wise pythonistas, please be gentle, for this is my first ever attempt at a program written in your fine language.

# Turtles on Mars!

```
from turtle import*
p="NESW"
mode("logo")
x,y,d=input().split(',')
setx(int(x))
sety(int(y))
seth(p.find(d)*90)
for c in input():fd(1)if c=="M"else[lt,rt][c>'L'](90)
print(pos(),p[int(heading()/90)])

```

This challenge maps quite naturally to logo-style turtle graphics, for which python has an import, of course.

Reads input from two lines from STDIN.

Output:

```
$ { echo 1,2,N; echo MRMLM; } | python ./rover.py
(2.00,4.00) N
$

```

What I especially like about this program is it actually graphically displays the rover's path. Add `exitonclick()` to the end of the program so the graphical output persists until user click:

I'm pretty sure this can be golfed significantly more - any suggestions welcome! I'm making this CW, because I hope the community can golf it some more.

Changes:

* s is now a list, inlined.
* Used ternary for body of for loop.
* Inlined n, removed unnecessary slice.
* Removed unnecessary space in import statement.
* Removed import string to use builtin string method
* Switched to Python 3 to shorten raw\_input
> 2 votes

# Answer
# GolfScript, ~~116 98 88 84~~ 71

```
~'NESW':^@?:&;{4%[{&(4%:&;}{&[{)}{\)\}{(}{\(\}]=~}{&)4%:&;}]=~}/]`&^1/=

```

This should get the coordinates and the instructions as arguments the following way:`1 2 'N' 'MRMLM'`. The arguments are made into a string and are pushed into the stack.

If you want to test this online, go to web golfscript and paste a semicolon followed with a string with the arguments (e.g. `;"1 2 'N' 'MRMLM'"`) before the code (here's a link with an example).

Examples of output:

```
1 2 'N' 'MRMLM'                    -> [2 4]N
5 6 'E' 'MMLMRMRRMMML'             -> [5 7]S
1 2 'N' 'MMMMRLMRLMMRMRMLMRMRMMRM' -> [1 8]N

```

## My Previous Attempts

**84 chars:**

```
~:i;'NESW':k\?:d;{i(\:i;4%[{d(4%:d;}{d[{)}{\)\}{(}{\(\}]=~}{d)4%:d;}]=~i}do]`d k 1/=

```

**88 chars:**

```
~:i;'NESW':k\?:d;{i(\:i;'MRL'?[{d[{)}{\)\}{(}{\(\}]=~}{d)4%:d;}{d(4%:d;}]=~i}do]`d k 1/=

```

**98 chars:**

```
 ~1/:i;:d;{'NESW'd?}:k;{k[{)}{\)\}{(}{\(\}]=~}:M;{k'ESWN'1/=:d;}:R;{k'WNES'1/=:d;}:L;{i(\:i;~i}do d

```

**116 chars:**

```
[~])\~"NESW":k 1/:d?{d(1/+:d;}:f*:y;:x;{("MRL"?[{k d 0=?[{y):y}{x):x}{y(:y}{x(:x}]=~;}{f}{d)1/\+:d;}]=~.}do x y d 0=

```
> 2 votes

# Answer
# Javascript (353)

This is my first real attempt at code golf, seems to work at least!

```
var xx=[0,1,0,-1];var yy=[1,0,-1,0];var d=["N","E","S","W"];var e=0;var x,y=0;function sa(p){q=p.split(",");x=+q[0];y=+q[1];e=+d.indexOf(q[2]);}function sb(t){var g=t.split(",");for(var u=0;u<g.length;u++){if(g[u]=='R'){e++;if(e>3)e=0;}if(g[u]=='L'){e--;if(e<0)e=3;}if(g[u]=='M'){x+=+xx[e];y+=+yy[e];}}alert(x+","+y+","+d[e]);}sa(prompt());sb(prompt());

```
> 1 votes

# Answer
## Python (263)

```
input =  raw_input("Initial: ")
input2 = raw_input("Command: ")

position = [int(input[0]), int(input[2]), input[4]]

bearings = "NESW"
turns = {"L" : -1, "M": 0, "R" : 1}
move = {"N" : [0, 1], "E" : [1, 0], "S" : [0, -1], "W" : [-1, 0]}

for c in input2:
    turn = turns[c];
    if (turn == 0):
        position[0] += move[position[2]][0]
        position[1] += move[position[2]][1]
    else:
        position[2] = bearings[(bearings.index(position[2]) + turn)%4]

print "Output: ", ','.join((str(s) for s in position))

```

There must be a more elegant way of doing this also, it doesn't need the branch after the else.

http://ideone.com/eD0FwD

The input is awful, I wanted to do it with `split(',')` but came across casting issues between the ints and strings. Ideally I also wanted to add the old position with the moving position... oh it's code-golf now. Oh well whatever, I'll leave it here, might give inspiration. Other ideas I had were using modulo 4 of the direction after mapping the initial bearing to an index. Also merging the turns and move arrays to one since none of the keys collide.

even so, shortening variable names and removing spaces it's 263:

```
i=raw_input()
j=raw_input()
p=[int(i[0]),int(i[2]),i[4]]
b="NESW"
m={"N":[0,1],"E":[1,0],"S":[0,-1],"W":[-1,0],"L":-1,"M":0,"R":1}
for c in j:
    if (m[c]==0):
        p[0]+=m[p[2]][0]
        p[1]+=m[p[2]][1]
    p[2] = b[(b.index(p[2])+m[c])%4]
print ','.join(str(s) for s in p)

```
> 1 votes

# Answer
# C - 350

Save as `rover.c`:

```
#include<stdio.h>
#include<string.h>
#include<math.h>
int main(){char c,*C="NWSE-WN";float x,y,d,k=M_PI/2;scanf("%f,%f,%c",&x,&y,&c);d=(strchr(C,c)-C)*k;do{switch(getchar()){case'R':d+=k;break;case'L':d-=k;break;case'M':x+=sin(d);y+=cos(d);break;case EOF:printf("%g,%g,%c\n",x,y,C[(int)(sin(d)+2*cos(d)+4.5)]);}}while(!feof(stdin));return 0;}

```

Compile:

```
gcc -o rover rover.c -lm

```

Sample run:

```
$ echo 1,2,N MRMLM | ./rover
2,4,N

```

Ideone

Ungolfed:

```
#include <stdio.h>
#include <string.h>
#include <math.h>

int main()
{
    /* String is used for input and output, pi/2 == 90 degrees */
    char c, *C = "NWSE-WN";
    float x, y, d, k = M_PI/2;

    /* Get starting parameters */
    scanf("%f,%f,%c", &x, &y, &c);

    /* Convert the direction NWSE into radians */
    d = (strchr(C, c) - C) * k;

    /* Process each character */
    do
    {
        /* Recognize R(ight), L(eft), M(ove) or EOF */
        switch (getchar())
        {
            case 'R':
                /* Turn right 90 degrees */
                d += k;
                break;

            case 'L':
                /* Turn left 90 degrees */
                d -= k;
                break;

            case 'M':
                /* Advance 1 unit in the direction specified */
                x += sin(d);
                y += cos(d);
                break;

            case EOF:
                /* Output - formula is specially crafted so that S,E,W,N
                    map to indices 2,3,5,6 to reuse part of string */
                printf("%g,%g,%c\n", x, y, C[(int)(sin(d) + 2*cos(d) + 4.5)]);
        }
    }
    while (!feof(stdin));

    return 0;
}

```
> 1 votes

# Answer
# Python 2.7 - ~~197~~ 192 bytes

```
q='NESW';x,y,d=raw_input().split(',');x=int(x);y=int(y);d=q.find(d);v={0:'y+',1:'x+',2:'y-',3:'x-'}
for c in raw_input():exec['d+','d-',v[d]]['RL'.find(c)]+'=1;d=d%4'
print`x`+','+`y`+','+q[d]

```

I'm actually super proud of this one.

**Explanation**

First, let's clean up this mess. I used semicolons instead of line breaks in a lot of places because I think it makes me cool. Here it is normally (this is still 197 bytes, it hasn't been ungolfed at all). Yes, there's still a semicolon, but that one actually saves a byte.

```
q='NESW'
x,y,d=raw_input().split(',')
x=int(x)
y=int(y)
d=q.find(d)
v={0:'y+',1:'x+',2:'y-',3:'x-'}
for c in raw_input():m=v[d];exec['d+','d-',m]['RL'.find(c)]+'=1;d=d%4'
print`x`+','+`y`+','+q[d]

```

Let's begin!

```
q='NESW'

```

First we define `q` as the string `'NESW'`. We use it twice later, and `len("q='NESW';qq") < len("'NESW''NESW'")`.

```
x,y,d=raw_input().split(',')

```

Here we split the first line of inpupt at each comma. Our x coord is stored in `x`, y in `y`, and the first letter of our direction in `d`.

```
x=int(x)
y=int(y)

```

Then we just make the coords ints. (I was shocked that I couldn't think of a better way to convert two strings to ints. I tried `x,y=map(int,(x,y))` but that turns out to be longer.)

```
d=q.find(d)

```

This converts our direction to an integer. 0 is north, 1 is east, 2 is south and 3 is west.

```
v={0:'y+',1:'x+',2:'y-',3:'x-'}

```

This is where the fun starts.

When we go north, Y increases by 1. So this dictionary takes 0 and gives the string `'y+'`, for "increase y". It gives similar results for other directions: y or x followed by + or -.

We'll come back to this.

```
for c in raw_input():
    m=v[d]
    exec['d+','d-',m]['RL'.find(c)]+'=1;d=d%4'

```

I've gone to the liberty of ungolfing this one slightly.

For each character in the second line of input, we do two things. First, we set the variable `m` to whatever our dictionary from before gives us for our current direction. There's no reason we need this to happen every time, but it's easier than just making it happen when we need it.

Next, we create a list with three elements: `'d+'`, `'d-'`, and `m`. **EDITOR'S NOTE:** I think I can get away with not using the variable `m` at all. I think I can just put `v[d]` in the list directly. That'll save me a couple bytes if it works, but I don't feel like testing it until I'm done this explanation so y'all can deal. **(Yep, it worked.)**

We look for the current character of the input in the string 'RL'. `str.find` returns -1 if it doesn't find the character, so this converts an R to a 0, an L to a 1 and anything else to -1. Of course, the only other input we can have is M, but it's less characters to make it work for everything.

We use that number as the index for the list we created. Python list indices start at the end if they're negative, so we get the first element if the input is R, the second if it's L, and the last if it's M. For for convenience's sake, I'm about to assume that we're facing north, but a similar principle applies for other directions.

The possible values we're working with are `'d+'` for R, `'d-'` for L and `'y+'` for M. Then, we attach `'=1;d=d%4'` to the end of each one. That means our possible values are...

```
d+=1;d=d%4
d-=1;d=d%4
y+=1;d=d%4

```

That's valid python code! That's valid python code that does exactly what we want to do for each of those input characters! (The `d=d%4` part just keeps our directions sane. Again, don't need to do it every time, but it's less characters.)

All we have to do is execute the code we get for each character, print it out (converting our direction back to a string), and we're done!
> 1 votes

# Answer
# Bash+coreutils, 159 bytes

```
t()(tr $2 0-3 $1<<<$d)
IFS=, read x y d
d=`t '' NESW`
for s in `fold -1`;{
[ $s = M ]&&((`t yxyx;t ++-`=1))||d=$[(d`tr LR -+<<<$s`1+4)%4]
}
echo $x,$y,`t NESW`

```

Input is read from 2 lines of STDIN.

Output:

```
$ { echo 1,2,N; echo MRMLM; } | ./rover.sh
2,4,N
$

```
> 1 votes

# Answer
# Haskell - 412 bytes

```
import Text.Parsec
import Text.Parsec.String
n='N'
s='S'
e='E'
w='W'
d(x,y,c)'M'|c==n=(x,y+1,c)|c==s=(x,y-1,c)|c==e=(x+1,y,c)|c==w=(x-1,y,c)
d(x,y,c)e=(x,y,i c e)
i 'N''R'=e
i 'N''L'=w
i 'S''R'=w
i 'S''L'=e
i 'E''R'=s
i 'E''L'=n
i 'W''R'=n
i 'W''L'=s
f=many digit
g=char ','
o=oneOf
main=interact(\s->show$parse(do x<-f;g;y<-f;g;c<-o"NSEW";newline;b<-many$o"MRL";return$foldl(\x c->d x c)(read x,read y,c)b)""s)

```

Tested with :

```
$ printf "1,2,N\nMRMLM" | ./rv
Right (2,4,'N')

```
> 1 votes

# Answer
# Python 2.7, 170 149

```
N,E,S,W=q='NESW'
x,y,d=input()
d=q.find(d)
for c in raw_input():exec['d+','d-','yx'[d%2]+'+-'[d/2]]['RL'.find(c)]+'=1;d%=4'
print`x`+','+`y`+','+q[d]

```

Things I changed from the original:

Aliased raw\_input, changed the v\[d\] dictionary, which should have been a list anyways, to some string selection, used `%=`.

Edit: used tuple unpacking and eval(raw\_input())==input() to save 21 characters.

Heavily borrowed from @undergroundmonorail, but with lots of improvements.
> 1 votes

# Answer
# Python, 135 ~~137~~ ~~138~~

```
S,W,N,E=0,1,2,3;a,b,d=input();v=[b,a]
for c in map(ord,raw_input()):d+=c%23;v[d&1]+=c%2*~-(d&2)
print'%d,%d,%s'%(v[1],v[0],'SWNE'[d&3])

```

Abuses the ASCII values of `L`, `M` and `R` to avoid using any conditional statements.

Try it in ideone.
> 1 votes

# Answer
## PowerShell, ~~170~~ ~~167~~ 166

```
[int]$x,[int]$y,$e,$m="$input"-split'\W'
$d='NESW'.indexof($e)
switch([char[]]$m){'R'{$d++}'L'{$d--}'M'{iex(-split'$y++ $x++ $y-- $x--')[$d%4]}}
"$x,$y,"+'NESW'[$d%4]

```

Can't seem to golf this down further, which is a bit embarrassing. But all the obvious hacks don't really work here.

I can't `iex` the input because a) `N`, `S`, `E` and `W` would have to be functions for that to work (or I'd need to prefix that with `$` and b) `1,2,N` would have to parse the `N` in expression mode, not being able to run a command.

The `switch` seems to be the shortest way of doing the movement. Hash table with script blocks or strings isn't shorter either and for every other way apart from the `switch` I'd have the overhead of the explicit loop.

I can't get rid of the `IndexOf` because a pipeline with `?` is longer, still.

I also can't get rid of the explicit types in the initial declaration because I have mixed types there, so a simple `|%{+$_}` doesn't help and every other option is longer.

Sometimes I hate input handling in PowerShell.
> 1 votes

# Answer
# Python3 (288)

Implementation using heavy use of ternary ifs.

```
m=['N','E','S','W']
cords=[int(n) for n in input().split()] + [input()] #Convert first inputs to integers and retrieve third
for n in input(): #Get instructions
    if n=='M':
        i=[1,0][cords[2] in m[1:3]] #See if vertical or horizontal
        j=[-1,1][cords[2] in m[0:2]] #See if negative or positive
        cords[i]+=j
    else:
        i=[-1,1][n=='R'] #Translate turn to numerals
        cords[2]=m[m.index(cords[2])+i] #Change direction relative to current orientation
print(cords)

```

Omitting the obvious input grumbles, giving the direction strings intrinsic values may have benefited the script size. However, the approach here is perfectly functional (so I believe)
> 0 votes

# Answer
# Bash/SHELF, ~~243~~ 235

"**SHE**ll go**LF**" is a golfing library for Bash which provides a few useful aliases. This is a valid answer as the library existed and was on GitHub before the challenge was posted.

Sorry, I can't get this to work on ideone.

## How to run

This takes the initial position (separated by commas as specified; this adds a lot of characters to the code) as its first argument, and the instructions on standard input.

```
source shelf.sh #you must load SHELF first
source rover.sh 1,2,N<<<MRMLM #now run the script via source so it has access to SHELF

```

## Sample output

```
2,4,N

```

## Code

```
o=$1
D(){ o=`y NESW $1<<<$o`;}
for x in `Y . '& '`;{
d $x R&&D ESWN
d $x L&&D WNES
d $x M&&z=(`y , \ <<<$o`)&&case ${z[2]} in N) z[1]=$[z[1]+1];;S) z[1]=$[z[1]-1];;W) z[0]=$[z[0]-1];;E) z[0]=$[z[0]+1];;esac&&o=`P ${z[@]}|y \  ,`
}
p $o

```

## Explanation

`d` is for comparison; it returns 0 if its two arguments are equal and 1 otherwise, it can then have other commands chained onto it with `&&` and `||`.

`y` is like `tr` (but done through `sed`).

`Y` is like `sed 's/.../.../g'` for its two arguments.

`P` is `echo -e -n`; `p` is just `echo -e`.

```
o=$1 #save first argument to variable
D(){ o=`y NESW $1<<<$o`;} #define an alias to turn R or L
for x in `Y . '& '`;{ #add a space after every character on stdin and loop for each one
d $x R&&D ESWN #turn R using alias
d $x L&&D WNES #turn L using alias

```

The next bit is profoundly ugly, with about 145 chars on one line. If the current command is M, turn the commas in $o into spaces, convert to array and save to $z. Then, do a switch...case block for the last element of $z (the direction the rover is pointing. Change coordinates accordingly, then convert $z back into a comma-separated string and save to $o.

```
d $x M&&z=(`y , \ <<<$o`)&&case ${z[2]} in N) z[1]=$[z[1]+1];;S) z[1]=$[z[1]-1];;W) z[0]=$[z[0]-1];;E) z[0]=$[z[0]+1];;esac&&o=`P ${z[@]}|y \  ,`
} #end loop
p $o #print output

```
> 0 votes

# Answer
# Haskell, 291

```
data D=W|S|E|N deriving(Show,Read,Enum)
main=interact$(\(x,y)->tail$map show y++[show(toEnum x::D)]>>=(',':)).(\(a:b:_)->foldl(\(f,j@[g,h])i->case i of 'M'->(f,[g+rem(f-1)2,h+rem(f-2)2]);'L'->(mod(f+1)4,j);'R'->(mod(f-1)4,j))((\(c,d,e)->(fromEnum(e::D),[c::Int,d]))$read('(':a++")"))b).lines

```

I wasn't sure how flexible the input and output string format was, so I made sure it looked exactly like the example (minus the prompts, of course), but that added a lot of extra characters. Ideone link
> 0 votes

# Answer
# PHP - 224

Well, I gave it a try.

```
$n=explode(",",$argv[1]);$d=($e=$n[2])==W?0:($e==N?1:($e==E?2:3));for(;$i<strlen($n[3]);)if(($o=$n[3][$i++])==M)$n[$d%2]+=$d>1?-1:1;else$d=$o==R?($d+1)%4:($d==0?3:$d-1);echo"{$n[0]},{$n[1]},".($d==1?N:($d==2?E:($d==3?S:W)));

```

Input in STDIN, e.g.:

```
$ php mars_rover.php 1,2,N,MMMRRRRRMM
-1,5,E
$ php mars_rover.php 1,2,N,MMMMRLMRLMMRMRMLMRMRMMRM
1,8,N
$ php mars_rover.php 3,-2,W,MMMMLM
7,-3,S

```
> 0 votes

# Answer
# Python 3 (143)

```
I=input
a,b,D=I().split(',')
w='ENWS'
d=w.find(D)
x=int(a)+int(b)*1j
for c in I():x+=(c=='M')*1j**d;d+='ML'.find(c)
print(x.real,x.imag,w[d%4])

```

http://ideone.com/wYvt7J

We use Python's built-in complex number type to store the pair of coordinates. The direction is computed by taking the imaginary unit `1j` to the power of `d`, which stores the direction mod 4. Rotating is done by incrementing or decrementing `d`. The expression `'ML'.find(c)` gives the amount we want to change `d`: `1` for `L`, `0` for `M`, and `-1` (the default for not found) for `R`.

Python doesn't have a short way to convert a complex number to a tuple, so we have to make costly calls to `.real` and `.imag`.
> 0 votes

---
Tags: code-golf
---


# Question
Title: Deplane! Deplane! (Or: RGBRGBRGB => RRRGGGBBB?)
Imagine bytes in memory for an RGB image--R and G and B represented by bytes in sequence. If an image is NxM then the memory layout will be M repetitions for vertical scanlines of 3\*N bytes in sequence for the horizontal pixels. (As one might expect.)

A mandate has come down from on high that you need to be able to isolate contiguous color planes. You might be asked for the R, G, or B plane. When you give back the plane it must be the N\*M bytes in sequence for that color.

Yet there is a twist: You cannot use additional memory proportional to the size of the image. Thus you must shuffle the bytes somewhere inside of the existing RGB data to provide the contiguous plane for the requested color. *And* you must be able to recover the original image when processing of that color plane is finished.

The image size is actually not relevant to the problem as it operates on the buffer as a whole. Input is bytes *(expressed as hexadecimal ASCII)* followed by which plane to extract:

```
00112233445566778899AABBCCDDEE
G

```

Output is the extracted color plane, then the original input \*(also in hexadecimal ASCII):

```
114477AADD
00112233445566778899AABBCCDDEE

```

Where you shuffle the memory is up to you. But you must actually shuffle the data to produce contiguous bytes *(requiring the client to use an iterator is cheating)*. And you must be able to reverse the operation to restore the original information.

Lowest big-O implementation wins. Between two implementations with equal big-O performance... winner decided by code golf rules.

# Answer
> 3 votes
# C

only shuffle, not print

lenght in bytes, not pixels

plane: 0,1,2 for R,G,B

not checked!

```
void deplane(unsigned char *data, int length, int plane) {
    unsigned char *t = data;
    unsigned char *s = data + plane;
    unsigned char p;
    while (s < data + length) {
        p = *s; *s = *t; *t = p;
        t++; s += 3;
    }
    // now plane start at data
    while (t > data) {
        s -= 3; t--;
        p = *s; *s = *t; *t = p;
    }
    // back to original
}

```

# Answer
> 2 votes
# Javascript (E6)

I don't like the I/O format, these should be byte arrays or the like. Anyway.
Source not golfed.

```
S=(a,p)=>{
  b = a.match(/../g);    // String to array
  l = b.length/3;        // Plane size
  s = p<'G'?2:p>'G'?0:1; // Which plane

  for (j=0, i=s; b[i]; j++, i+=3) // Shuffle
    [b[i],b[j]] = [b[j],b[i]];
  console.log(b.slice(0,l).join('')); // Output plane

  for (; i-=3, j--; ) // Unshuffle
    [b[i],b[j]] = [b[j],b[i]];

  console.log(b.join('')) // Original is back
}

```

**Usage**

In firefox console:

```
S('00112233445566778899AABBCCDDEE','G')

```

**Output**

```
114477AADD
00112233445566778899AABBCCDDEE

```

---
Tags: code-challenge, array
---


title: Calculate n % 12

text:
# Question
Title: Calculate n % 12
Calculate `n` modulo `12` for an unsigned 32 bit integer.

## The Rules:

* Must work for all `n` between 0 and 23. Other numbers optional.
* Must only use any of the operators `+-*`, `~&^|` or `<<`, `>>` as commonly defined on 32 bit uints.
* May use arbitrary number of constant uints.
* May not use any form of pointers, including arrays, or any `if` statements, including things that compile to if statements such as ternary operators or "greater than" operators.

## The scoring:

* Operators `+ -` and the bitwise operators `~ & ^ | << >>` (NOT, AND, XOR, OR, bit shifts) give a score of `1`, `*` gives a score of `2`.
* Lowest total score wins.

# Answer
> 29 votes
# 4

(Language is irrelevant)

```
n-((48&(11-n))>>2)

```

Woo! Got to 4.

`11-n` will ensure all of the high order bits are set if and only if n\>= 12.

`48&(11-n)` == if n\>11 then 48 else 0

`(48&(11-n))>>2` == if n\>11 then 12 else 0

`n-((48&(11-n))>>2)` is the answer

# Answer
> 11 votes
# 4

A solution with a lookup table (it looks up `i ^ (i % 12)`):

```
i ^ (0x1d4c000 >> (i & 0xfc) & 30)

```

# 4

Here's another solution with 4 operations:

```
i - ((0xffff >> (i - 12)) & 12)

```

It assumes that the count operand of bitshifts is implicitly taken mod 32, i.e. `x >> -1` is the same as `x >> 31`.

# 5

Another approach, using a lookup table:

```
i - (16773120 >> i & 1) * 12

```

# Answer
> 7 votes
# bash – 1

```
echo `seq 0 11` `seq 0 11` | awk '{print $(number+1)}'

```

e.g.

```
$ echo `seq 0 11` `seq 0 11` | awk '{print $(0+1)}'
0

$ echo `seq 0 11` `seq 0 11` | awk '{print $(11+1)}'
11

$ echo `seq 0 11` `seq 0 11` | awk '{print $(12+1)}'
0

$ echo `seq 0 11` `seq 0 11` | awk '{print $(23+1)}'
11

```

# Answer
> 5 votes
## C, little-endian - 2

This is probably cheating but I think it satisfies the rules...

```
union {
    int i;
    struct {
        int a:4;
        int b:2;
        int c:10;
    } s;
    struct {
        int a:2;
        int b:14;
    } t;
} u;

u.i = 11-n;
u.s.a = 0;
u.s.c = 0;
result = n-u.t.b;

```

# Answer
> 4 votes
# PHP - score 0

I wonder how is it possible that noone came with this before me!!!

```
$n = 18;
$s = str_repeat("a", $n);
$s2 = preg_replace('/aaaaaaaaaaaa/', '', $s);
echo strlen($s2);

```

# Answer
> 2 votes
# C, score 5

Works up to 23, not guaranteed above that.

```
( ((n+4)>>2)&4 ) + n & 15

```

`((n+4)>>2)&4` returns 4 for n\>=12. Add it to n and you get the right answer in the least significant 4 bits, then truncate the other bits.

# Answer
> 2 votes
### whatever language: 5

not going to win, but participating because fun and maybe because it's easier to understand then others:

```
n - ((n+20)>>5)*12

```

this is equivalent to

```
n - (n>11)*12

```

this is equivalent because when you add 20 to 12, you get 32, thus the 5th bit becomes 1. This is only when n \> 1 as 32 is the smallest number where the 5th bit becomes 1.

also note that is easily expandable for a higher range, as you can do

```
n - ((n+20)>>5)*12 - ((n+41)>>5)*12

```

to reach a range until 35

# Answer
> 1 votes
# C - 6

```
(n - (((n * 0xAAAB) >> 19)) * 12 )

```

# Answer
> 1 votes
# Python 2.x - 4

```
j=input();m=lambda a,b:a*b;a=(m(j,357913942)>>32);print j-m(12,a)

```

Is `=` an operator?

In that case the score is 6.

```
j-12*(j*357913942>>32)

```

BTW @steveverrill 's solution can be directly used in Python as well.

Works for the range 0 .. 23

So whats going on ? Multiply by 357913942 and divide by 2^32 (or right shift 32)

# Answer
> 0 votes
# Kona \- 5

Might be invalid because I'm not sure if the floor operator is allowed, but I've got two `*` and a minus:

```
mod:{x-(_0.08333*x)*12}

```

Which should work for any integer.

# Answer
> 0 votes
# Cobra - 2 (or 3)

```
def modulo12(n as uint32) as uint32
        for i in 11:n to int64:12,n-=12
        return n

```

This *might* be bending the rules a bit, but I've asked and was allowed to use this.

It also works for any number.

---
Tags: math, number-theory, atomic-code-golf
---