# Question
Title: Generate a random program in your favorite language
We all heard of testing compilers using randomly generated inputs. Your task is to write a program to generate a valid program (including no undefined behavior) in your favorite language. The generating program language doesn't have to be the same as the generated program language.

Your program will receive an integer as the argument which you can use as seed for your random number generator. The generated programs should be structurally different (given different seeds) not just different variable names or constants.

Examples:

```
$ ./generate 1
int main() { return 0; }

$ ./generate 2
#include <math.h>
int main() { return (int) pow(4, 3); }

```

Please include a couple of outputs in your answers.

The shortest solution wins. I will give a small bonus based on the number of votes, so please vote the most creative solutions.

# Answer
## Python → Brainf\*ck (185 223 233 255 285 287 303 characters)

### Code

```
import random as r,sys
r.seed(int(sys.argv[1]))
c=list('<>.,+-')+['']
n=9/r.random()
def b():
 global n
 s=''
 while n>0:n-=1;o=r.choice(c);s+=o if o else'[%s]'%b()
 return s
print b()

```
* **303 → 287 Characters**: Removed `math.ceil` (it's not really necessary).
* **287 → 285 Characters**: Switched to an empty string to denote the branch operator.
* **285 → 255 Characters**: Condensed the if statement in the while loop.
* **255 → 233 Characters**: Implemented JBernardo's suggestions from the comments.
* **233 → 223 Characters**: Implemented tjko's suggestion from the comments.
* **223 → 185 Characters**: Implemented some whitespace reduction suggestions from the comments.

### Examples

```
$ python generate.py 1
-->,,+-<<-,-<,->[[<<,[.>.<>,,>>>,.<-,+>[[<.-+[.-+.+[-,+<>-.>,++.,,-,.,<<+[+]]]]]]]]
$ python generate.py 2
[<<--+.+++>]
$ python generate.py 3
,.++<<->>[,-,+>+[,-+<-+.<[,-[+[.-,[[<<>[,+.]]]]]]]]

```

Actually figuring out what the resulting BF programs *do* is left as an exercise to the reader.
> 18 votes

# Answer
**Python -\> Piet, 385 345 char**

It's possible to generate any Piet program with this. I could've just stopped at random pixels, but I wanted to make "interesting" programs. The function `m` paints a pixel a color, and recursively steps into each of that pixels neighbors. There are better ways to draw random blobs, but this is tuned to terminate in a reasonable number of steps, so it's good enough for golf. The function `R(w,h,n)` draws *n* random blobs onto a (*w* x *h*) white image, and prints the result in PPM format.

I'm especially proud of how I generate the colors -- for a random choice of `0 <= c < 20`,

```
`[0,192,255][int(x)]`for x in'0002212220200101121100'[c:c+3]

```

is the decimal code for a valid color in the Piet palette by way of a single-track Gray code. That is, each color is represented by 3 adjacent bits, and every slice `'0003...0'[c:c+3]` represents a different color. Since this isn't the full list of 27 words on 3 letters, I really lucked out in finding the Gray code.

```
from random import*
r=randint
def R(w,h,n):
 M=[6]*h*w
 def m(x,y,c,d):M[y%h*w+x%w]=c;t=r(0,15)*(r(0,d)<2);t&8and m(x+1,y,c,d+1);t&4and m(x-1,y,c,d+1);t&2and m(x,y+1,c,d+1);t&1and m(x,y-1,c,d+1)
 while n:m(r(0,w),r(0,h),r(0,19),0);n-=1
 print"P3 %s %s 255 "%(w,h)+' '.join(`[0,192,255][int(x)]`for c in M for x in'0002212220200101121100'[c:c+3])

```

Sample output, generated by the command `R(30,40,500)`

Without the import, I can write it as a proper (semicolon-free) 1-liner, too:

```
import random
R=(lambda P,I,E,T:lambda w,h,n:E(w,h,I(w,h,n,lambda z,c,d,t:sum((((z,c),)*t*T(0,1)or m((z[0]+a,z[1]+b),c,d+1,T(0,d)>1)for a,b in((0,1),(1,0),(-1,0),(0,-1))),()))))(range,lambda w,h,n,m:dict(sum((m((T(0,w),T(0,h)),T(0,19),0,0)for _ in P(n)),())),lambda w,h,M:"P3 %s %s 255 "%(w,h)+' '.join(' '.join(`(x&1)*255+(x&2)*96`for x in map(int,'0001121110100202212200'[c:c+3]))for c in(M[z]if z in M else 6for z in((x,y)for y in P(h)for x in P(w)))),random.randint)

```

but it's *ridiculously* slow (and almost 100 characters longer)... though I'm not entirely sure why (and not terribly inclined to find out).
> 17 votes

# Answer
## Python -\> Python, 135 chars

```
import random,sys
random.seed(int(sys.argv[1]))
R=range(9)
print'print 1'+''.join(random.choice('+*')+'%d'%random.choice(R)for x in R)

```

Generates little random expression evaluations, like this:

```
> ./genprogram.py 1
print 1+7*2+4*7+0*3*0+6+8
> ./genprogram.py 2
print 1*8+0*6*2*5*1+3*8*4
> ./genprogram.py 3
print 1+4+5*0+7+2*4*4*1*7
> ./genprogram.py 4
print 1+0+1+3*7*1*2+0+8*7

```
> 9 votes

# Answer
**Python -\> HQ9+ : 108 chars**

```
import random
def g(): return ''.join([random.choice(['H','Q','9','+']) for x in range(random.randint(1,9))])

```
> 8 votes

# Answer
# PHP, 352 characters

Generates PHP code in PHP.

I decided I didn't care as much about length, but instead wanted an interesting and diverse set of solutions. This is my answer to that.

## Code

```
<?php mt_srand(0+$argv[1]);$r=mt_rand(1,100);$s="\$i=rand(1,$r);";while($r>0){$s.='$i';if(!($r%10))$s.='*=2;';if(!($r%9))$s.='++;';if(!($r%8))$s.='=pow($i,rand(1,$i));';if(!($r%7))$s.='--;';if(!($r%6))$s.='=substr($i,0,2);';if(!($r%5))$s.='/=2;';if(!($r%4))$s.='+=4;';if(!($r%3))$s.='*=-1;';$r-=mt_rand(1,5);}$s.='var_dump($i);';echo"<?php $s
";

```

### Ungolfed

```
<?php
mt_srand(0+$argv[1]);
$r = mt_rand(1,100);
$s = "\$i=rand(1,$r);";
while ($r > 0)
{
    if (!($r%10)) $s .= '$i*=2;';
    if (!($r%9))  $s .= '$i++;';
    if (!($r%8))  $s .= '$i=pow($i,rand(1,$i));';
    if (!($r%7))  $s .= '$i--;';
    if (!($r%6))  $s .= '$i=substr($i,0,2);';
    if (!($r%5))  $s .= '$i/=2;';
    if (!($r%4))  $s .= '$i+=4;';
    if (!($r%3))  $s .= '$i*=-1;';
    $r -= mt_rand(1,5);
}
$s .= 'var_dump($i);';
echo "<?php $s
";

```

## Example

```
> php r.php 1
<?php $i=rand(1,58);$i*=-1;$i=pow($i,rand(1,$i));$i=substr($i,0,2);$i+=4;$i*=-1;$i=pow($i,rand(1,$i));$i=substr($i,0,2);$i+=4;$i*=-1;$i*=2;$i/=2;$i+=4;$i/=2;$i*=-1;$i*=2;$i/=2;$i=substr($i,0,2);$i*=-1;var_dump($i);
> php r.php 2
<?php $i=rand(1,57);$i*=-1;$i+=4;$i--;$i=substr($i,0,2);$i*=-1;$i*=-1;$i--;$i+=4;$i/=2;$i++;$i=substr($i,0,2);$i*=-1;$i=pow($i,rand(1,$i));$i+=4;$i--;$i=substr($i,0,2);$i+=4;$i*=-1;$i--;$i+=4;var_dump($i);

```
> 6 votes

# Answer
### scala: 1543 (scala =\> scala)

I have variables (x, y, z), functions (mul, add, neg, abs), values and balanced parenthesis.

```
<!--code:language-scala-->
object FormelBauer {
    val fun = List (" mul10 (", " add1 (", " neg (", " abs (")
    val ops = List (" * ", " + ", " - ", " / ")
    def c(maxLen: Int, m: Int) : String = {
        def f()= new StringBuffer (fun (r.nextInt (fun.length)))
        def w()= new StringBuffer ("" + (r.nextInt (180) - 90))
        def v()= new StringBuffer ("" + ('x' + r.nextInt (3)).toChar)
        def o()= new StringBuffer (ops (r.nextInt (ops.length)))
        def g(t: Int, b: Int, d: List [Char]) : StringBuffer ={
            var a = d.filterNot (x => if (b > 0) x == '.' else x == ')')
            if (b > m) a = a.filterNot (_ == 'k')
            if (b > m) a = a.filterNot (_ == 'f')
            if (t > maxLen) a = a.filterNot (_ == '+')
            val elem = r.nextInt (a.length)
            val start = a(elem)
            start match {
                case '.' => new StringBuffer ("")
                case 'f' => f.append(g (t + 1, b + 1, List ('(', '8', 'x')))
                case '(' => new StringBuffer ("(").append   (g (t + 1, b + 1, List ('(', '8', 'x')))
                case '8' => w.append(g (t + 1, b, List ('.', ')', '+')))
                case 'x' => v.append(g (t + 1, b, List ('.', ')', '+')))
                case ')' => new StringBuffer (") ").append  (g (t + 1, b -1, List ('.', ')', '+')))
                case '+' => o.append(g (t + 1, b, List ('f', '(', '8', 'x')))
        }}
        (g (0,0,List('f','(','8','x'))).toString
    }
import util._
  var r : Random = _
    def main (as: Array [String]) : Unit = {
      val s=as(0).toInt
        r=new Random(s)
        "xyz".map(c=>println("val "+c+"="+(c+r.nextInt(s))))
        println("""def mul10(i:Int)=10*i
def add1(i:Int)=i+1
def neg(i:Int)= -i
def abs(i:Int)=if(i<0)-i else i
"""+c(45,5))}
}

```

As you see, it is not very golfed. Because, it will not get me close to the other solutions, but a problem is, that more variation costs more. 3 variables, 4 functions could be easily reduced to two, for example.

Generating some samples:

```
for i in {1..7} ; do scala FormelBauer $i; echo; done

val x=120
val y=121
val z=122
def mul10(i:Int)=10*i
def add1(i:Int)=i+1
def neg(i:Int)= -i
def abs(i:Int)=if(i<0)-i else i
(y)  / 79

val x=121
val y=121
val z=123
def mul10(i:Int)=10*i
def add1(i:Int)=i+1
def neg(i:Int)= -i
def abs(i:Int)=if(i<0)-i else i
 add1 ((((78 +  neg (z * z) )  / x) ) )  + -23 - ((-83)  * y)

val x=122
val y=123
val z=122
def mul10(i:Int)=10*i
def add1(i:Int)=i+1
def neg(i:Int)= -i
def abs(i:Int)=if(i<0)-i else i
x / -71 - (y)

val x=122
val y=124
val z=125
def mul10(i:Int)=10*i
def add1(i:Int)=i+1
def neg(i:Int)= -i
def abs(i:Int)=if(i<0)-i else i
x

val x=122
val y=123
val z=126
def mul10(i:Int)=10*i
def add1(i:Int)=i+1
def neg(i:Int)= -i
def abs(i:Int)=if(i<0)-i else i
-24 + z

val x=121
val y=121
val z=124
def mul10(i:Int)=10*i
def add1(i:Int)=i+1
def neg(i:Int)= -i
def abs(i:Int)=if(i<0)-i else i
 abs (z)

val x=123
val y=126
val z=126
def mul10(i:Int)=10*i
def add1(i:Int)=i+1
def neg(i:Int)= -i
def abs(i:Int)=if(i<0)-i else i
 add1 (-62 - 30 * (-68)  /  neg (x - 69 + 33 / 45 + x * x)  -  abs (-18 * (y + x)  /  neg (x)  - y)  *  abs ((61) ) )  + (y)

```

Testing the longest one:

```
add1 (-62 - 30 * (-68)  /  neg (x - 69 + 33 / 45 + x * x)  -  abs (-18 * (y + x)  /  neg (x)  - y)  *  abs ((61) ) )  + (y)

```

res6: Int = -5425
> 5 votes

# Answer
## Perl -\> shell : 66 chars

```
@p=split(':',$ENV{PATH});
@c=`ls @p[@ARGV[0]]`;
print @c[rand($#c)];

```

Possibly a little off topic, but maybe so.

```
s153254@helios:/home/s153254/lab$ perl code.p 1
telnet
s153254@helios:/home/s153254/lab$ perl code.p 2
in.rlogind
s153254@helios:/home/s153254/lab$ perl code.p 2
df
s153254@helios:/home/s153254/lab$ perl code.p 3
svenv

```
> 5 votes

# Answer
## Ruby → Brainfuck (110 107 characters)

```
s="";m=%w:< > . , + -:;rand(99).downto(r=0){s<<(rand(40)==0? (r+=1)&&'[%s':'%s')%m.shuffle[0]};p(s<<']'*r)

```

### Usage

```
$ ruby bf.rb

```

Produces an executable brainfuck program.

Sort of a shameless ripoff of ESultanik's, so I will credit him for the idea.

* Changed .zero? to ==0
> 4 votes

# Answer
## Javascript -\> Brainf\*ck: 119 chars

```
s=prompt();a=["+","-",">","<",".",",","[-]"];i=0;b="";while(i++<s*s){b+=a[Math.floor(((Math.random()*s)%1)*7)]}alert(b)

```

Sample I/O:

```
10
.--.+,-><->.<+.[-].->.>[-][-]<+,[-]>><-[-]>,,>>[-].-+<[-]+>,<[-][-]<<[-]<[-]+,+[-][-][-].-[-],[-]>.<<[-]-..<-.->.++,>+-[-],.[-]..+,<-[-].+-[-]
11
,..[-]--,[-].,[-]>[-]->..[-]<,<..>[-]<>++-.[-].,,<[-].<+<[-]>-->[-]+-[-]+>-[-][-]>-,[-]->>-,-..++<+,,-,.,[-]->[-]<,+[-][-]+.,-,>+->.[-],.>..,++,.[-],+[-]-,.,--.--,

```

The code could definitely be shorter, but some things would, IMHO, make it less interesting. But if someone else comes up with a shorter program, I'll cut down more.
> 3 votes

# Answer
## Python -\> Fractran (117)

```
import random as r,sys
r.seed(int(sys.argv[1]))
z=r.randint
print','.join(`z(1,99)`+'/'+`z(1,99)`for q in[0]*z(1,99))

```
> 3 votes

# Answer
### Python -\> Python, 148 chars

Longer than the other Python entries at the expense of being (subjectively) a little more interesting.

```
import sys as s,random as r
w,o=s.stdout.write,__builtins__
r.seed(s.argv[1])
w('print\\')
for i in'\n....':n=r.choice(dir(o));o=getattr(o,n);w(i+n)

```

This prints a deeply nested attribute of a built-in object.

```
$ python randprog.py 1
print\
round.__setattr__.__delattr__.__init__.__class__

```
> 2 votes

# Answer
## PowerShell, generating PowerShell – 43

In the spirit of Keith's solution:

```
-join(0.."$input"|%{'-','+'|random;random})

```

generates random expressions of additions and subtractions:

```
PS> -join(0..(random 9)|%{'-','+'|random;random 9})
+2-0-0+3-7
PS> -join(0..(random 9)|%{'-','+'|random;random 9})
-7+1+7+1-5+2+8
PS> -join(0..(random 9)|%{'-','+'|random;random 9})
-1+7+7-0-6-0-2
PS> -join(0..(random 9)|%{'-','+'|random;random 9})
+2-6-5+3-2+7
PS> -join(0..(random 9)|%{'-','+'|random;random 9})
-6

```
> 2 votes

# Answer
## Game Maker Language -\> Arduino or Ti84-Basic, 63 characters

```
a=argument0;if a mod 2{return("void setup(){Serial.begin(9600);}void loop(){Serial.print"+string(a*random(9))+";delay("+string(floor(random(999)))+")}"}else{return(":Lbl A:Horizontal "+string(a*random(9))+":Goto A")}

```

Explanation:

`a=argument0` Puts the input into variable `a`

`if a mod 2` Basically, half the chance the program will be Arduino, half Ti-Basic 84

The Arduino program outputs random stuff at random intervals, randomly skipping random things.

The Ti-Basic Program draws horizontal lines like crazy.

Also, there is a bonus - the generated programs are already golfed! Not sure if that would be helpful...
> 2 votes

# Answer
**Perl -\> HQ9+ (42 Characters)**

```
$a="HQ9+";for(1..<>%4){chop$a}print chop$a

```

Example input

```
4264532623562346

```

Output

```
Q

```
> 1 votes

# Answer
**JavaScript -\> Javascript (44 characters)**

```
alert('alert("'+Math.random()*prompt()+'")')

```

And with **43** characters, it can execute the generated program instead of displaying it's source:

```
eval('alert("'+Math.random()*prompt()+'")')

```

Examples:

Seed: 5
Executed 3 times:

```
alert("2.335241624386981")
alert("0.4577956395223737")
alert("0.8359265828039497")

```
> 1 votes

---
Tags: code-golf, generation
---


title: Tic Tac Tae Toe

text:
# Question
Title: Tic Tac Tae Toe
(Better known as 3D Tic Tac Toe; I just made up a name that sounded catchy ;-) )

Let two people play this game against each other.

Specifications:

* Output

+ the easiest way of explaining this will be with an example:

    ```
    +-+-+-+-+
    |X| | | |
    +-+-+-+-+
    | |O| | |
    +-+-+-+-+
    | | | | |
    +-+-+-+-+
    |O| | | |
    +-+-+-+-+

    +-+-+-+-+
    | | | | |
    +-+-+-+-+
    | |X| | |
    +-+-+-+-+
    | | | |O|
    +-+-+-+-+
    | | | | |
    +-+-+-+-+

    +-+-+-+-+
    | | | | |
    +-+-+-+-+
    | |O| | |
    +-+-+-+-+
    |O| |X| |
    +-+-+-+-+
    | | | |X|
    +-+-+-+-+

    +-+-+-+-+
    | | | | |
    +-+-+-+-+
    | | | | |
    +-+-+-+-+
    | | | | |
    +-+-+-+-+
    | | | |X|
    +-+-+-+-+

    ```

    in this case X has won (top left corner of layer #1 to bottom right corner of layer #2)
    + it is also okay to display the four layers horizontally, with one space between them
    + grids may be non-text; in this case you must represent a third dimension in a reasonable way; see also scoring section below
    + after each player's turn, output "{player} wins" if a player wins, "tie" if the board fills up and nobody has won, or the board if the game is not over yet (or notifiy the user of a win/tie in a reasonable way)
* Input

+ xyz coordinates, 0-based
    + example: input `031` is this location:

    ```
    +-+-+-+-+
    | | | | |
    +-+-+-+-+
    | | | | |
    +-+-+-+-+
    | | | | |
    +-+-+-+-+
    | | | | |
    +-+-+-+-+

    +-+-+-+-+
    | | | | |
    +-+-+-+-+
    | | | | |
    +-+-+-+-+
    | | | | |
    +-+-+-+-+
    |X| | | |
    +-+-+-+-+

    +-+-+-+-+
    | | | | |
    +-+-+-+-+
    | | | | |
    +-+-+-+-+
    | | | | |
    +-+-+-+-+
    | | | | |
    +-+-+-+-+

    +-+-+-+-+
    | | | | |
    +-+-+-+-+
    | | | | |
    +-+-+-+-+
    | | | | |
    +-+-+-+-+
    | | | | |
    +-+-+-+-+

    ```
    + alternate between X and O, starting with X, and prompt the user with the text "{player}'s turn: "
* Winning condition
    + a player wins if the player gets 4 of their symbol (X or O) in a row, horizontally, vertically, or diagonally. For example, these are all wins (in the input format I have specified) if a player has played any of them:
    + 000, 001, 002, 003
    + 120, 130, 100, 110
    + 000, 110, 220, 330
    + 300, 122, 033, 211
* Scoring
    + `[ws]` 10 base points for a working solution
    + `[gr]` +20 points if you have a graphical (meaning non-text) grid
        - `[cc]` +30 points if you can click on a cell to go there
    + `[cp]` +20 points for building a computer player to play against
        - `[ai]` +10 to 100 points for how good the AI is (judged by me)
        - `[ot]` +15 points if you can choose between one and two player
    + `[ex]` +3 points for each interesting or confusing thing in your code that you explain in your answer (**interesting**, so don't say "n++ adds one to n" and expect to get 3 points. just be reasonable.)
        - for example, you could say "I used `[a,b,c].map(max).sum%10` because it takes the foos and converts them into a bar, because {{insert explanation here}}, which I use to frob the baz."
        - if you golf part of or all of your code, you will of course find many more interesting things to explain, but golfing is not required.
    + `[wl]` +10 points for showing the winning line, for example "000 001 002 003," or highlighting the squares in some way (if you're using a GUI)
    + +5 points for every upvote (this is the part)
    + downvotes don't count
    + include your score in the answer by using the IDs I have placed for the bonuses
        - example: 10 \[ws\] + 20 \[gr\] + 20 \[cp\] = 50
        - don't include upvotes since those change often; I will count those myself
    + I will accept the highest scored answer in one week; if a higher scored answer appears I will accept it
    + if two answers tie, the earlier posted answer will win

# Answer
> 4 votes
## HTML/CSS/JS+JQuery

10\[ws\] + 20\[gr\] + 30\[cc\] + 20\[cp\] + ?\[ai\] + 15\[ot\] + 10\[wl\] + ?\[ex\] = 105+
Finished the AI, though a really crappy one.

> "Is there any way to make it play itself?"
> "Yes. Number of players: zero."

For those who don't get the reference: http://www.youtube.com/watch?v=NHWjlCaIrQo
* sign\* It's much less cool of a reference now that I have explained it...

JSFiddle

---

**AI**

The AI logic goes like this:

1. If there is a winning move for me, take it.
2. If there is a winning move for opponent, block it.
3. Take the "best" unoccupied corner.
4. Take a random unoccupied space.

---

HTML

```
<span>X</span>'s turn
<div>
<table>
    <tr><td></td><td></td><td></td><td></td></tr>
    <tr><td></td><td></td><td></td><td></td></tr>
    <tr><td></td><td></td><td></td><td></td></tr>
    <tr><td></td><td></td><td></td><td></td></tr>
</table>
<table>
    <tr><td></td><td></td><td></td><td></td></tr>
    <tr><td></td><td></td><td></td><td></td></tr>
    <tr><td></td><td></td><td></td><td></td></tr>
    <tr><td></td><td></td><td></td><td></td></tr>
</table>
<table>
    <tr><td></td><td></td><td></td><td></td></tr>
    <tr><td></td><td></td><td></td><td></td></tr>
    <tr><td></td><td></td><td></td><td></td></tr>
    <tr><td></td><td></td><td></td><td></td></tr>
</table>
<table>
    <tr><td></td><td></td><td></td><td></td></tr>
    <tr><td></td><td></td><td></td><td></td></tr>
    <tr><td></td><td></td><td></td><td></td></tr>
    <tr><td></td><td></td><td></td><td></td></tr>
</table>
</div>

```

JS

```
var currentPlayer = true, end = false, players = parseInt(prompt('Number of players":'));

function cell(x,y,z){return $('td').eq(x*16+y*4+z);}
function f(i,x){switch(x){case -1: return i; case -2: return 3-i; default: return x;}}
function line(x,y,z){
    var t = $();
    for(var i=0; i<4; i++) t = t.add(cell(f(i,x),f(i,y),f(i,z)));
    return t;
}
function check(x,y,z,t){
    var u = line(x,y,z);
    if(u.map(function(){return $(this).text()==t;}).get().reduce(function(a,b){return a&&b;})) u.css({color: 'red'});
    else return false;
    return end = true;
}
function move(x,y,z){
    if(end) return false;
    var t = currentPlayer?'X':'O';
    cell(x,y,z).text(t);
    if(check(-1,y,z,t)) return true;
    if(check(x,-1,z,t)) return true;
    if(check(x,y,-1,t)) return true;
    if(check(x,-1,-1,t)) return true;
    if(check(x,-1,-2,t)) return true;
    if(check(-1,y,-1,t)) return true;
    if(check(-1,y,-2,t)) return true;
    if(check(-1,-1,z,t)) return true;
    if(check(-1,-2,z,t)) return true;
    if(check(-1,-1,-1,t)) return true;
    if(check(-2,-1,-1,t)) return true;
    if(check(-1,-2,-1,t)) return true;
    if(check(-1,-1,-2,t)) return true;
    currentPlayer = !currentPlayer;
    $('span').text(currentPlayer?'X':'O');
    if(players==2||players==1&&currentPlayer) return false;
    else return ai();
}

function ai_tri(x1,y1,z1,x2,y2,z2,t){
    var u = false;
    for(var i=0;i<4;i++) for(var j=0;j<4;j++)
        if(x1==x2){
            if(cell(x1,i,j).text()==t)
                if(i==y2&&(j==1||j==2) || j==z2&&(i==1||i==2))
                    if(u) return false;
                    else u = true;
                else return false;
        }else if(y1==y2){
            if(cell(i,y2,j).text()==t)
                if(i==x2&&(j==1||j==2) || j==z2&&(i==1||i==2))
                    if(u) return false;
                    else u = true;
                else return false;
        }else{
            if(cell(i,j,z1).text()==t)
                if(i==x2&&(j==1||j==2) || j==y2&&(i==1||i==2))
                    if(u) return false;
                    else u = true;
                else return false;
        }
    return true;
}
function ai_tri2(x1,y1,z1,x2,y2,z2,t){
    var u = false;
    for(var i=0;i<4;i++) for(var j=0;j<4;j++)
        if(x1!=x2){
            if(cell(i,j,j).text()==t)
                if(j==y2&&(i==1||i==2) || i==x2&&(j==1||j==2))
                    if(u) return false;
                    else u = true;
                else return false;
        }else if(y1!=y2){
            if(cell(j,i,j).text()==t)
                if(i==z2&&(j==1||j==2) || j==y2&&(i==1||i==2))
                    if(u) return false;
                    else u = true;
                else return false;
        }else{
            if(cell(j,j,i).text()==t)
                if(i==x2&&(j==1||j==2) || j==z2&&(i==1||i==2))
                    if(u) return false;
                    else u = true;
                else return false;
        }
    return true;
}
function ai_cn(x,y,z,t){
    return ai_tri(x,y,z,x,!y*3,!z*3,t) + ai_tri(x,y,z,!x*3,y,!z*3,t) + ai_tri(x,y,z,!x*3,!y*3,z,t) + ai_tri2(x,y,z,!x*3,y,z,t) + ai_tri2(x,y,z,x,!y*3,z,t) + ai_tri2(x,y,z,x,y,!z*3,t) + ai_tri(!x*3,y,z,x,!y*3,z,t) + ai_tri(!x*3,y,z,x,y,!z*3,t) + ai_tri(x,!y*3,z,!x*3,y,z,t) + ai_tri(x,!y*3,z,x,y,!z*3,t) + ai_tri(x,y,!z*3,!x*3,y,z,t) + ai_tri(x,y,!z*3,x,!y*3,z,t) + ai_tri2(x,!y*3,!z*3,!x*3,!y*3,!z*3,t) + ai_tri2(!x*3,y,!z*3,!x*3,!y*3,!z*3,t) + ai_tri2(!x*3,!y*3,z,!x*3,!y*3,!z*3,t);
}
function ai_check(x,y,z,t){
    var v = [$(),$(),$()], u = line(x,y,z);
    $.each(u.map(function(){return $(this).text();}).get(),function(i,e){if(e=='X') v[0]=v[0].add(u.eq(i)); else if(e=='O') v[1]=v[1].add(u.eq(i)); else v[2]=v[2].add(u.eq(i));});
    if((t==='X'?v[0]:v[1]).length==3 && v[2].length==1) return [true,v[2]];
    else if((t==='X'?v[1]:v[0]).length==3 && v[2].length==1) return [false,v[2]];
    else return null;
}
function ai_check_all(t){
    var u = null, v = null;
    for(var i=0;i<4;i++){
        for(var j=0;j<4;j++){
            if((u=ai_check(i,j,-1,t))!==null) if(u[0] || v!==null) return u[1]; else v = u[1];
            if((u=ai_check(i,-1,j,t))!==null) if(u[0] || v!==null) return u[1]; else v = u[1];
            if((u=ai_check(-1,i,j,t))!==null) if(u[0] || v!==null) return u[1]; else v = u[1];
        }
        if((u=ai_check(i,-1,-1,t))!==null) if(u[0] || v!==null) return u[1]; else v = u[1];
        if((u=ai_check(i,-1,-2,t))!==null) if(u[0] || v!==null) return u[1]; else v = u[1];
        if((u=ai_check(-1,i,-1,t))!==null) if(u[0] || v!==null) return u[1]; else v = u[1];
        if((u=ai_check(-1,i,-2,t))!==null) if(u[0] || v!==null) return u[1]; else v = u[1];
        if((u=ai_check(-1,-1,i,t))!==null) if(u[0] || v!==null) return u[1]; else v = u[1];
        if((u=ai_check(-1,-2,i,t))!==null) if(u[0] || v!==null) return u[1]; else v = u[1];
    }
    if((u=ai_check(-1,-1,-1,t))!==null) if(u[0] || v!==null) return u[1]; else v = u[1];
    if((u=ai_check(-1,-1,-2,t))!==null) if(u[0] || v!==null) return u[1]; else v = u[1];
    if((u=ai_check(-1,-2,-1,t))!==null) if(u[0] || v!==null) return u[1]; else v = u[1];
    if((u=ai_check(-2,-1,-1,t))!==null) if(u[0] || v!==null) return u[1]; else v = u[1];
    return v;
}
function ai(){
    var t1 = currentPlayer?'X':'O', t2 = currentPlayer?'O':'X', u = [0,0,0,0], v = 0, w = ai_check_all();
    if(w!==null) return move(w.closest('table').index(),w.closest('tr').index(),w.index());
    for(var i=0;i<4;i+=3) for(var j=0;j<4;j+=3) for(var k=0;k<4;k+=3)
        if(cell(i,j,k).text()==='' && (v=ai_cn(i,j,k,t2))>u[3]) u = [i,j,k,v];
    if(u[3]>0) return move(u[0],u[1],u[2]);
    u = $('td').filter(function(){return $(this).text()=='';});
    if(u.length===0) return end = true;
    w = u.eq(Math.floor(Math.random()*u.length));
    return move(w.closest('table').index(),w.closest('tr').index(),w.index());
}

$('table').on('click','td',function(){
    if(end || $(this).text() !== '') return true;
    move($(this).closest('table').index(),$(this).closest('tr').index(),$(this).index());
});

if(players == 0) ai();

```

CSS

```
body{font-family: Arial, san-serif;}
table{float:left; margin-right: 20px; border-collapse: collapse;}
td{width:20px; height:20px; border:1px solid black; text-align: center;}

```

# Answer
> 2 votes
# Java

10\[ws\] + 20\[gr\] + 30\[cc\] + 4\*3\[ex\] = 72

```
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.event.MouseInputListener;

public class Game {

    public static void main(String[] args) {
        //Initial threads
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Game();
            }
        });
    }
    JFrame frame;
    Grid grid;

    Game() {
        grid = new Grid();
        frame = new JFrame("Tic Tac Tae Toe");

        frame.add(grid);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }
}

class Grid extends JPanel implements MouseInputListener {

    static final int BEGIN_X = 50, BEGIN_Y = 50;
    static final int GAP = 50;
    static final int TILE_WIDTH = 40;
    XO[][][] grid;
    int lastX, lastY, lastZ;
    int mouse_x, mouse_y;
    JLabel turn;
    boolean won;

    public Grid() {
        // Just because. I felt like copy-paste.
        grid = new XO[][][]{
            {
                {XO.N, XO.N, XO.N, XO.N},
                {XO.N, XO.N, XO.N, XO.N},
                {XO.N, XO.N, XO.N, XO.N},
                {XO.N, XO.N, XO.N, XO.N}
            },
            {
                {XO.N, XO.N, XO.N, XO.N},
                {XO.N, XO.N, XO.N, XO.N},
                {XO.N, XO.N, XO.N, XO.N},
                {XO.N, XO.N, XO.N, XO.N}
            },
            {
                {XO.N, XO.N, XO.N, XO.N},
                {XO.N, XO.N, XO.N, XO.N},
                {XO.N, XO.N, XO.N, XO.N},
                {XO.N, XO.N, XO.N, XO.N}
            },
            {
                {XO.N, XO.N, XO.N, XO.N},
                {XO.N, XO.N, XO.N, XO.N},
                {XO.N, XO.N, XO.N, XO.N},
                {XO.N, XO.N, XO.N, XO.N}
            }
        };

        lastX = -1;
        lastY = -1;
        lastZ = -1;
        won = false;

        turn = new JLabel("X");

        add(turn);

        this.setPreferredSize(new Dimension(2 * BEGIN_X + 4 * TILE_WIDTH,
                2 * BEGIN_Y + 4 * (4 * TILE_WIDTH + GAP) - GAP));
        this.addMouseListener(this);
        this.addMouseMotionListener(this);
    }

    public XO determineWinner() {
        XO type = grid[lastZ][lastY][lastX];

        //start on same z-plane

        for (int x = 0; x < 4; x++) {
            if (grid[lastZ][lastY][x] != type) {
                break;
            }
            if (x == 3) {
                return type; //type won!
            }
        }
        for (int y = 0; y < 4; y++) {
            if (grid[lastZ][y][lastX] != type) {
                break;
            }
            if (y == 3) {
                return type; //type won!
            }
        }
        //first diagonal
        if (lastX == lastY) {
            for (int x = 0, y = 0; x < 4; x++, y++) {
                if (grid[lastZ][y][x] != type) {
                    break;
                }
                if (x == 3) {
                    return type; //type won!
                }
            }
        } //second diagonal
        else if (lastX == 3 - lastY) {
            for (int x = 0, y = 3; x < 4; x++, y--) {
                if (grid[lastZ][y][x] != type) {
                    break;
                }
                if (x == 3) {
                    return type; //type won!
                }
            }
        }
        //first plane finished
        //now onto changing z's
        //vertical column
        for (int z = 0; z < 4; z++) {
            if (grid[z][lastY][lastX] != type) {
                break;
            }
            if (z == 3) {
                return type; //type won!
            }
        }
        //descending y. note: descending means stair-like (diagonal)
        if (lastZ == lastY) {
            for (int z = 0, y = 0; z < 4; z++, y++) {
                if (grid[z][y][lastX] != type) {
                    break;
                }
                if (z == 3) {
                    return type; //type won!
                }
            }
        } //ascending y
        else if (lastZ == 3 - lastY) {
            for (int z = 0, y = 3; z < 4; z++, y--) {
                if (grid[z][y][lastX] != type) {
                    break;
                }
                if (z == 3) {
                    return type; //type won!
                }
            }
        } //ascending x. note: ascending means stair-like, but other way
        if (lastZ == 3 - lastX) {
            for (int z = 0, x = 3; z < 4; z++, x--) {
                if (grid[z][lastY][x] != type) {
                    break;
                }
                if (z == 3) {
                    return type; //type won!
                }
            }
        } //descending x
        else if (lastZ == lastX) {
            for (int z = 0, x = 0; z < 4; z++, x++) {
                if (grid[z][lastY][x] != type) {
                    break;
                }
                if (z == 3) {
                    return type; //type won!
                }
            }
        }

        //diagonals, changing all three
        if (lastZ == lastX && lastZ == lastY) {
            for (int z = 0, x = 0, y = 0; z < 4; z++, x++, y++) {
                if (grid[z][y][x] != type) {
                    break;
                }
                if (z == 3) {
                    return type; //type won!
                }
            }
        } else if (3 - lastZ == lastX && 3 - lastZ == lastY) {
            for (int z = 3, x = 0, y = 0; z < 4; z--, x++, y++) {
                if (grid[z][y][x] != type) {
                    break;
                }
                if (x == 3) {
                    return type; //type won!
                }
            }
        } else if (lastZ == lastX && lastZ == 3 - lastY) {
            for (int z = 0, x = 0, y = 3; z < 4; z++, x++, y--) {
                if (grid[z][y][x] != type) {
                    break;
                }
                if (z == 3) {
                    return type; //type won!
                }
            }
        } else if (lastZ == 3 - lastX && lastZ == lastY) {
            for (int z = 0, x = 3, y = 0; z < 4; z++, x--, y++) {
                if (grid[z][y][x] != type) {
                    break;
                }
                if (z == 3) {
                    return type; //type won!
                }
            }
        }

        //check for tie
        out: for (int z = 0; z < 4; z++){
            for (int y = 0; y < 4; y++){
                for (int x = 0; x < 4;x++){
                    if (grid[z][y][x] == XO.N){
                        break out;
                    }
                }
            }
            if (z == 3){
                return XO.N;
            }
        }

        return null;
    }

    @Override
    public void paintComponent(Graphics graphics) {
        super.paintComponent(graphics);

        Graphics2D g = (Graphics2D) graphics;
        g.setColor(Color.BLACK);

        //Looks a little nicer, but this could be left out.
        g.setFont(new Font("Courier New", Font.BOLD, 20));

        //paint grid rectangles.
        for (int z = 0; z < 4; z++) {
            int begin_y = BEGIN_Y + z * (4 * TILE_WIDTH + GAP);

            //draw left line
            g.drawLine(BEGIN_X, begin_y,
                    BEGIN_X, begin_y + 4 * TILE_WIDTH);

            //draw bottom line
            g.drawLine(BEGIN_X, begin_y + 4 * TILE_WIDTH,
                    BEGIN_X + 4 * TILE_WIDTH, begin_y + 4 * TILE_WIDTH);

            for (int y = 0; y < 4; y++) {
                for (int x = 0; x < 4; x++) {
                    //draw individual grid lines
                    g.drawLine(BEGIN_X + (x + 1) * TILE_WIDTH, begin_y + y * TILE_WIDTH,
                            BEGIN_X + (x + 1) * TILE_WIDTH, begin_y + (y + 1) * TILE_WIDTH);
                    g.drawLine(BEGIN_X + x * TILE_WIDTH, begin_y + y * TILE_WIDTH,
                            BEGIN_X + (x + 1) * TILE_WIDTH, begin_y + y * TILE_WIDTH);

                    //if this was the last chosen square...
                    if (lastX == x && lastY == y && lastZ == z) {
                        g.setColor(Color.ORANGE);
                        //fill it orange! (not required, but I think it looks nice)
                        g.fillRect(BEGIN_X + x * TILE_WIDTH + 1,
                                begin_y + y * TILE_WIDTH + 1,
                                TILE_WIDTH - 1, TILE_WIDTH - 1);
                        g.setColor(Color.BLACK);
                    }

                    //if mouse is over this square...
                    if ((BEGIN_X + x * TILE_WIDTH) < mouse_x
                            && (BEGIN_X + (x + 1) * TILE_WIDTH) > mouse_x
                            && (begin_y + y * TILE_WIDTH) < mouse_y
                            && (begin_y + (y + 1) * TILE_WIDTH) > mouse_y) {
                        g.setColor(new Color(100, 100, 255));
                        //fill it blue! (not required, but I think it looks nice)
                        g.fillRect(BEGIN_X + x * TILE_WIDTH + 1,
                                begin_y + y * TILE_WIDTH + 1,
                                TILE_WIDTH - 1, TILE_WIDTH - 1);
                        g.setColor(Color.BLACK);
                    }

                    //paint value of tile
                    g.drawString(grid[z][y][x].val,
                            BEGIN_X + x * TILE_WIDTH + TILE_WIDTH / 2,
                            begin_y + y * TILE_WIDTH + TILE_WIDTH / 2);

                }
            }
        }
    }

    @Override
    public void mouseClicked(MouseEvent e) {
        if (!won) {
            int x = e.getX(), y = e.getY();
            x -= BEGIN_X;
            x /= TILE_WIDTH;

            y -= BEGIN_Y;

            int z = 0;
            while (y > 4 * TILE_WIDTH) {
                z++;
                y -= 4 * TILE_WIDTH + GAP;
            }

            y /= TILE_WIDTH;

            //**********************************
            //DOES NOT ALWAYS GET PAST HERE!
            //**********************************
            if (x < 0 || y < 0 || z < 0 || x >= 4 || y >= 4 || z >= 4) {
                return;
            }
            if (grid[z][y][x] == XO.N) {
                grid[z][y][x] = XO.valueOf(turn.getText());
            } else {
                return;
            }

            lastX = x;
            lastY = y;
            lastZ = z;

            XO who_won = determineWinner();
            if (who_won == null){
                if (turn.getText().equals("X")) {
                    turn.setText("O");
                } else {
                    turn.setText("X");
                }
            }
            else if (who_won != XO.N) {
                turn.setText(who_won.toString() + " wins");
            } else{
                turn.setText("tie");
            }
            repaint();
        }
    }

    @Override
    public void mousePressed(MouseEvent e) {
    }

    @Override
    public void mouseReleased(MouseEvent e) {
    }

    @Override
    public void mouseEntered(MouseEvent e) {
    }

    @Override
    public void mouseExited(MouseEvent e) {
    }

    @Override
    public void mouseDragged(MouseEvent e) {
    }

    @Override
    public void mouseMoved(MouseEvent e) {
        mouse_x = e.getX();
        mouse_y = e.getY();
        repaint();
    }
}

enum XO {

    X("X"), O("O"), N(" ");
    String val;

    XO(String c) {
        val = c;
    }
}

```

This is a working solution, but I will work on it a lot more.

\[ex\]:

* runs using Initial Threads
* informs player's whose turn it is (letter at top of window, will be improved) using a `JLabel` called `turn`. This label is also used to say who won.
* shows the last move by storing the last x, y and z values and painting the corresponding square orange during `paintComponent()`
* shows the location of the mouse pointer (blue square) by computing it during `paintComponent()`

---

Screenshot:

# Answer
> -2 votes
## Ti-Basic 84

10\[ws\]+20\[gr\]+20\[cp\]+10\[ai\]+15\[ot\]+3\[ex\]=**78**

Programmable and playable from a Ti-84 calculator. +100?

Also, `->` represents the `STO->` button.

```
:Disp LOOKS-LIKE-THIS-MIGHT-BE-SOMETHING-INTERESTING-IN-THE-CODE
:ClrHome
:Disp "TIC TAC TAE TOE"
:Disp "HOW MANY PLAYERS"
:Input P
:If P=1 :Disp "YOUR OPPONENTS NAME IS AI BOB"
:If P=2 :Disp "YOUR OPPONENTS NAME IS AI BOB EVEN THOUGH YOU WANT TO PLAY TWO PLAYERS"
:Horizontal -10
:Horizontal -5
:Horizontal 0
:Horizontal 5
:Horizontal 10
:Vertical -10
:Vertical -5
:Vertical 0
:Vertical 5
:Vertical 10
:0->A
:Lbl M
:Disp "YOUR MOVE X-POS"
:Input X
:Disp "YOUR MOVE Y-POS"
:Input Y
:Circle(2,X,Y)
:Circle(2,rand,rand)
:Disp "UGH, HE DIDNT ALIGN IT CORRECTLY"
:Disp "YOU MIGHT WANT TO STOP PLAYING"
:If A=>4 :Goto W
:If A<4 :A+1->A
:Goto M
:Lbl W
:Disp "HAVE YOU WON, 1 IS YES, 0 IS NO"
:Input W
:If W=1 :Goto E
:Goto M
:Lbl E
:Disp "YOU HAVE WON! GOOD JOB!"
:Disp "ENTER TO EXIT"
:Pause

```

Something interesting: the line of code at the beginning (`:Disp LOOKS-LIKE-THIS-MIGHT-BE-SOMETHING-INTERESTING-IN-THE-CODE`) prints 0 and then is immediately cleared from the screen.

Feel free to give me more points for my AI's skill, but I'm pretty sure you'll stick with 10.

---
Tags: code-challenge, popularity-contest, tic-tac-toe
---


title: Display Continued Fractions

text:
# Question
Title: Display Continued Fractions
Your challenge is to convert a positive rational number into a finite simple continued fraction., in 2D, with horizontal fraction bars separating numerator from denominator. \[A simple continued fraction only has numerators equal to 1.\] Your solution should be able to represent a continued fraction with up to 8 terms.

**Input**: The rational number may be input in any format, including (but not restricted to)

* string: "7/16"
* list: {7, 16}, (7, 16), \[7, 16\]
* simple ordered pair: 7 16
* function: f\[7,16\]
* decimal number: 0.657

**Output**: A continued fraction, in 2D, with horizontal fraction bars separating numerator from denominator. **Only continued fractions with numerators equal to 1 are valid.** It is not necessary to make the font size vary according to depth. A leading zero (for proper fractions) is optional.

**Depth**: Your code must be able to display at least 8 levels of depth.

**Winning criterion**: Shortest code wins. You must include several test cases showing input and output.

**Test Examples** (Input followed by output)

| Input | 2D Output |
| --- | --- |
| \\$\frac 5 4\\$ | \\$1 + \cfrac 1 4\\$ |
| \\$\frac 5 3\\$ | \\$1 + \cfrac 1 {1 + \cfrac 1 2}\\$ |
| \\$\frac 5 7\\$ | \\$0 + \cfrac 1 {1 + \cfrac 1 {2 + \cfrac 1 2}}\\$ |
| \\$\frac 9 {16}\\$ | \\$0 + \cfrac 1 {1 + \cfrac 1 {1 + \cfrac 1 {3 + \cfrac 1 2}}}\\$ |
| \\$\frac {89} {150}\\$ | \\$0 + \cfrac 1 {1 + \cfrac 1 {1 + \cfrac 1 {2 + \cfrac 1 {5 + \cfrac 1 {1 + \cfrac 1 {1 + \cfrac 1 2}}}}}}\\$ |

# Answer
# Mathematica, ~~40~~ 36 chars

```
f=If[⌊#⌋≠#,⌊#⌋+"1"/#0[1/(#-⌊#⌋)],#]&

```

**Example:**

```
f[89/150]

```

**Output:**
> 5 votes

# Answer
## Python 2, ~~158~~ ~~155~~ ~~147~~ 142

```
a,b=input()
c=[]
while b:c+=[a/b];a,b=b,a%b
n=len(c)
while b<n-1:print'  '*(n+b),'1\n',' '*4*b,c[b],'+','-'*(4*(n-b)-7);b+=1
print' '*4*b,c[b]

```

Test:

```
$ python cfrac.py
(89,150)
                 1
 0 + -------------------------
                   1
     1 + ---------------------
                     1
         1 + -----------------
                       1
             2 + -------------
                         1
                 5 + ---------
                           1
                     1 + -----
                             1
                         1 + -
                             2

```

---

## Python 2, alt. version, 95

Basically a port of breadbox's answer. Safer output.

```
a,b=input();i=2
while a%b:print'%*d\n%*d + ---'%(i+5,1,i,a/b);a,b=b,a%b;i+=5
print'%*d'%(i,a/b)

```

Test:

```
$ python cfrac2.py
(98,15)
      1
 6 + ---
           1
      1 + ---
                1
           1 + ---
                7

```
> 10 votes

# Answer
## XSLT 1.0

I thought it'd be nice to display the fractions with HTML, so here's an XSLT solution.

```
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                              xmlns:msxsl="urn:schemas-microsoft-com:xslt" >
  <xsl:template match="/f">
    <xsl:variable name="c" select="floor(@a div @b)"/>
    <xsl:variable name="next">
      <f a="{@b}" b="{@a mod @b}"/>
    </xsl:variable>
    <table>
      <tr>
        <td valign="top" rowspan="2" style="padding-top:12px">
          <xsl:value-of select="$c"/>+
        </td>
        <td align="center" style="border-bottom:1px solid black">1</td>
      </tr>
      <tr>
        <td>
          <xsl:apply-templates select="msxsl:node-set($next)"/>
        </td>
      </tr>
    </table>
  </xsl:template>
  <xsl:template match="/f[@a mod @b=0]">
    <xsl:value-of select="@a div @b"/>
  </xsl:template>
</xsl:stylesheet>

```

To test it, save the xslt as fraction.xslt and open the following file in IE:

```
<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet  href="fraction.xslt" type="text/xsl"?>
<f a="89" b="150"/>

```
> 7 votes

# Answer
# Ruby, 175 (with ASCII art) or 47 (without)

## Without ASCII art, 47

```
n,d=eval gets
while d!=0
puts n/d
n,d=d,n%d
end

```

Since Ruby can't really do graphics like that, I just output the blue numbers in your examples.

```
c:\a\ruby>cont
[5,4]
1
4

c:\a\ruby>cont
[5,3]
1
1
2

c:\a\ruby>cont
[5,7]
0
1
2
2

c:\a\ruby>cont
[9,16]
0
1
1
3
2

c:\a\ruby>cont
[89,150]
0
1
1
2
5
1
1
2

```

## With ASCII Art, ~~181~~ ~~178~~ 175

```
n,d=eval gets
a=[]
n,d=d,n%d,a.push(n/d)while d!=0
i=0
j=2*a.size-3
k=a.size-2
a.map{|x|puts' '*i+"#{x}+"+' '*k+?1
i+=2
k-=1
puts' '*i+?-*j
j-=2}rescue 0
puts' '*i+a.last.to_s

```

Wow, that ASCII art took up a lot of code, and I was even being evil and using `rescue 0` :P Sample:

```
c:\a\ruby>cont
[89,150]
0+      1
  -------------
  1+     1
    -----------
    1+    1
      ---------
      2+   1
        -------
        5+  1
          -----
          1+ 1
            ---
            1+1
              -
              2

```
> 4 votes

# Answer
## C, 119 characters

```
n,d,r;main(i){for(scanf("%d%d",&n,&d);r=n%d;n=d,d=r,i+=5)
printf("%*d\n%*d + ---\n",i+5,1,i,n/d);printf("%*d\n",i,n/d);}

```

Here are some examples of output:

```
$ echo 15 98 | ./cfrac
     1
0 + ---
          1
     6 + ---
               1
          1 + ---
                    1
               1 + ---
                    7
$ echo 98 15 | ./cfrac
     1
6 + ---
          1
     1 + ---
               1
          1 + ---
               7
$ echo 98 14 | ./cfrac
7

```

While the truncated fraction line isn't as pretty-looking as some of the examples here, I wish to point out that this was a common technique for formatting continued fractions back in the days before desktop computers were ubiquitous.

---

Okay, here's a much longer version (247 characters) that does full-on formatting of the output:

```
c,h,i,j,n,d,w[99];char s[99][99];main(r){for(scanf("%d%d",&n,&r);d=r;n=d)
h+=w[c++]=sprintf(s[c],"%d + ",n/d,r=n%d);for(;j+=w[i],i<c-1;puts(""))
for(printf("%*d\n%*s",j+(r=h-j)/2,1,j,s[i++]);--r;printf("-"));
s[i][w[i]-2]=0;printf("%*s\n",j-1,s[i]);}

```

Some examples of its output:

```
$ echo 89 150 | ./cfr
                 1
0 + ---------------------------
                   1
    1 + -----------------------
                     1
        1 + -------------------
                       1
            2 + ---------------
                         1
                5 + -----------
                           1
                    1 + -------
                             1
                        1 + ---
                             2
$ echo 151 8919829 | ./cfr
                 1
0 + ----------------------------
                     1
    59071 + --------------------
                       1
            1 + ----------------
                         1
                2 + ------------
                           1
                    1 + --------
                             1
                        1 + ----
                             21
$ echo 293993561 26142953 | ./cfr
               1
11 + ---------------------
                 1
     4 + -----------------
                   1
         14 + ------------
                       1
              4410 + -----
                      104

```
> 4 votes

# Answer
## Sage Notebook, 80

```
c=continued_fraction(n)
LatexExpr('{'+'+\\frac{1}{'.join(map(str,c))+'}'*len(c))

```

Here `n` can be anything Sage can approximate by a rational / floating point number. Default precision is 53 bits, unless `n` is a `Rational`. Gotta love MathJax.
> 4 votes

# Answer
## APL (78)

```
{(v↑' '⍪⍉⍪⍕⍺),(' +'↑⍨v←⊃⍴x),x←('1'↑⍨⊃⌽⍴v)⍪v←'─'⍪⍕⍪⍵}/⊃{⍵≤1:⍺⋄a w←0⍵⊤⍺⋄a,⍵∇w}/⎕

```

Example:

```
      {(v↑' '⍪⍉⍪⍕⍺),(' +'↑⍨v←⊃⍴x),x←('1'↑⍨⊃⌽⍴v)⍪v←'─'⍪⍕⍪⍵}/⊃{⍵≤1:⍺⋄a w←0⍵⊤⍺⋄a,⍵∇w}/⎕
⎕:
      89 150
   1
 0+─────────────
     1
   1+───────────
       1
     1+─────────
         1
       2+───────
           1
         5+─────
             1
           1+───
               1
             1+─
               2

```
> 3 votes

# Answer
## Mathematica, 77

```
Fold[#2+1/ToString[#1]&,First[#1],Rest[#1]]&[Reverse[ContinuedFraction[#1]]]&

```

Just learned Mathematica for this. Takes a surprisingly long program to do this.
> 2 votes

# Answer
### Perl ~~128~~ 114 chars

```
($a,$b)=split;$_=" "x7;until($b<2){$==$a/$b;($a,$b)=($b,$a%$b);$_.="1\e[B\e[7D$= + ---------\e[B\e[4D"}$_.="$a\n"

```

But as this use console placement, you have to clear console in order before run:

```
clear
perl -pe '($a,$b)=split;$_=" "x7;until($b<2){$==$a/$b;($a,$b)=($b,$a%$b);$_.=
"1\e[B\e[7D$= + ---------\e[B\e[4D"}$_.="$a\n"' <<<$'5 7 \n189 53 \n9 16 \n89 150 '

```

output:

```
       1
 0 + ---------
          1
    1 + ---------
             1
       2 + ---------
                2
       1
 3 + ---------
          1
    1 + ---------
             1
       1 + ---------
                1
          3 + ---------
                   1
             3 + ---------
                      2
       1
 0 + ---------
          1
    1 + ---------
             1
       1 + ---------
                1
          3 + ---------
                   2
       1
 0 + ---------
          1
    1 + ---------
             1
       1 + ---------
                1
          2 + ---------
                   1
             5 + ---------
                      1
                1 + ---------
                         1
                   1 + ---------
                            2

```

### First post: 128 chars

```
($a,$b)=split;$c=7;while($b>1){$==$a/$b;($a,$b)=($b,$a%$b);printf"%s1\n%${c}d + %s\n"," "x($c+=5),$=,"-"x9}printf" %${c}d\n",$=

```

Splitted for *cut'n paste*:

```
perl -ne '($a,$b)=split;$c=7;while($b>1){$==$a/$b;($a,$b)=($b,$a%$b);printf
"%s1\n%${c}d + %s\n"," "x($c+=5),$=,"-"x9}printf" %${c}d\n",$a' \
    <<<$'5 7 \n189 53 \n9 16 \n89 150 '

```

Will render:

```
            1
      0 + ---------
                 1
           1 + ---------
                      1
                2 + ---------
                      2
            1
      3 + ---------
                 1
           1 + ---------
                      1
                1 + ---------
                           1
                     3 + ---------
                                1
                          3 + ---------
                                2
            1
      0 + ---------
                 1
           1 + ---------
                      1
                1 + ---------
                           1
                     3 + ---------
                           2
            1
      0 + ---------
                 1
           1 + ---------
                      1
                1 + ---------
                           1
                     2 + ---------
                                1
                          5 + ---------
                                     1
                               1 + ---------
                                          1
                                    1 + ---------
                                          2

```

### Same using LaTeX:

```
perl -ne 'END{print "\\end{document}\n";};BEGIN{print "\\documentclass{article}\\pagestyle".
  "{empty}\\begin{document}\n";};($a,$b)=split;$c="";print "\$ $a / $b = ";while($b>1){$==$a
  /$b;($a,$b)=($b,$a%$b);printf"%s + \\frac{1}{",$=;$c.="}";}printf"%d%s\$\n\n",$a,$c'  \
   <<<$'5 7 \n189 53 \n9 16 \n89 150 ' >fracts.tex

pslatex fracts.tex

dvips -f -ta4 <fracts.dvi |
  gs -sDEVICE=pnmraw -r600 -sOutputFile=- -q -dNOPAUSE - -c quit |
  pnmcrop |
  pnmscale .3 |
  pnmtopng >fracts.png

```
> 2 votes

# Answer
# Perl : *~~140~~* ,*~~133~~* 121 chars

```
($a,$b)=<STDIN>;while($b>1)
{$g=$i+++4;print" "x$g."1\n"." "x$i,int($a/$b)."+---\n";($a=$b)=($b,$a%$b)}
print" "x$g."$a\n"

```

**example :**
#perl fraction.pl
5
7

```
   1
0+---
    1
 1+---
     1
  2+---
     2

```
> 1 votes

# Answer
## Game Maker Language (Script), 61 71

```
a=argument0;b=argument1;while b!=0{c+=string(a/b)a,b=b,a mod b}return c

```

Compile with all uninitialized variables as `0`.
> 0 votes

# Answer
## Razor Leaf on Firefox, 108 ~~127~~

```
%r=(i,n,d)=>
    mn"#{n/d|0}"
    if i<8&&n%d
        mo"+"
        mfrac
            mn"1"
            me%r(i+1,d,n%d)
math%[a,b]=data;r(0,a,b)

```

~~The prompt really hurts there…~~ Oh, you mean I get to pick? Okay, it’s a list. Anyways, good luck getting this to run.
> 0 votes

# Answer
Assuming the input numbers as co-prime, call this process function with numerator and denominator. It can go to any depth until it finds the continued form, no limit

Written in JAVA (238 characters)

```
String space = "";
private void process(int n, int d) {
    System.out.println(space+(n/d)+" + 1");
    space += "    ";
    System.out.println(space+"------");
    if((n % d)==1)
        System.out.println(space+d);
    else
        process(d,(n % d));
}

```

process(89,150);

```
0 + 1
    ------
    1 + 1
        ------
        1 + 1
            ------
            2 + 1
                ------
                5 + 1
                    ------
                    1 + 1
                        ------
                        1 + 1
                            ------
                            2

```

process(973,13421);

```
0 + 1
    ------
    13 + 1
        ------
        1 + 1
            ------
            3 + 1
                ------
                1 + 1
                    ------
                    5 + 1
                        ------
                        3 + 1
                            ------
                            1 + 1
                                ------
                                1 + 1
                                    ------
                                    4

```
> 0 votes

# Answer
# K, 136

```
{-1@((!#j)#\:" "),'j:(,/{(x,"+ 1";(" ",(2*y)#"-"),"\t")}'[a;1+|!#a:$-1_i]),$*|i:*:'1_{(i;x 2;x[1]-(i:x[1]div x 2)*x@2)}\[{~0~*|x};1,x];}

```

.

```
k)f:{-1@((!#j)#\:" "),'j:(,/{(x,"+ 1";(" ",(2*y)#"-"),"\t")}'[a;1+|!#a:$-1_i]),$*|i:*:'1_{(i;x 2;x[1]-(i:x[1]div x 2)*x@2)}\[{~0~*|x};1,x];}
k)f[5 4]
1+ 1
  --
  4

k)f[5 3]
1+ 1
  ----
  1+ 1
    --
    2

k)f[5 7]
0+ 1
  ------
  1+ 1
    ----
    2+ 1
      --
      2

k)f[9 16]
0+ 1
  --------
  1+ 1
    ------
    1+ 1
      ----
      3+ 1
        --
        2

k)f[89 150]
0+ 1
  --------------
  1+ 1
    ------------
    1+ 1
      ----------
      2+ 1
        --------
        5+ 1
          ------
          1+ 1
            ----
            1+ 1
              --
              2

```
> 0 votes

---
Tags: code-golf, rational-numbers
---


title: Simulate the Monty Hall Problem

text:
# Question
Title: Simulate the Monty Hall Problem
I've never been able to wrap my head around the Monty Hall problem. Here's the premise:

> Suppose you're on a game show, and you're given the choice of three doors: Behind one door is a car; behind the others, goats. You pick a door, say No. 1, and the host, who knows what's behind the doors, opens another door, say No. 3, which has a goat. He then says to you, "Do you want to pick door No. 2?" Is it to your advantage to switch your choice?

Run 10,000 simulations. Output the win percentage of switching. For example:

```
> 66.66733%

```

# Answer
> 4 votes
## JavaScript 52

```
for(i=s=0;i++<1e4;)s+=Math.random()<2/3;alert(s/100)

```

Doors are 1:\[0,1/3), 2:\[1/3,2/3), 3:\[2/3, 1)

Assume the prize is always in door 3. If the guest picks doors 1 or 2, which is range \[0,2/3), and they switch, they've won the prize.

# Answer
> 3 votes
## J: ~~17~~ 15

```
100%~+/2>?1e4$3

```

It picks a random door—let's label these 0, 1, or 2 where 2 is the door with the car—and computes the benefit of switching based on this logic:

* If the player picked door 0, the host will open door 1. Switching will earn the player a new car (`1`).
* If the player picked door 1, the host will open door 0. Switching will earn the player a new car (`1`).
* If the player picked door 2, the winning door, the host will open either door 0 or door 1. Either way, if the player switches, he or she will find a goat (`0`).

It then computes the result as the sum of the previous array, divided by 100.

I'm pretty shaky with J so I'm sure this could be improved further.

# Answer
> 3 votes
## R ~~115~~ 100

The *pseudo-simulation* answer is 23 characters long:

```
sum(runif(1e4)>1/3)/100

```

but here is an actual simulation:

```
D=1:3
S=function(x)x[sample(length(x),1)]
sum(replicate(1e4,{
C=S(D)
P=S(D)
H=S(D[-c(C,P)])
F=D[-c(P,H)]
C==F
}))/100

```
1. `D` are the possible doors
2. `S` is a function to randomly select one item from a vector
3. `C` is the the door with the car (random among `D`)
4. `P` is the the door picked by the player (random among `D`)
5. `H` is the door picked by the host (random among `D` minus `C` and `P`)
6. `F` is the final door picked by the player (deterministic: `D` minus `P` and `H`)
7. success is measured by `C==F`.

returns: \[1\] 66.731

**Edit**

I can save a few characters by not assigning to variables and assuming without loss of generality that `C==1`:

```
D=1:3;S=function(x)x[sample(length(x),1)];sum(replicate(1e4,{P=S(D);1==D[-c(P,S(D[-c(1,P)]))]}))/100

```

# Answer
> 2 votes
## Perl, ~~98~~ ~~89~~ ~~83~~ ~~75~~ ~~72~~ 71 characters

Here's a serious answer that actually runs the simulation:

```
sub c{($==rand 2)-"@_"?$=:&c}$n+=$%==c c($%=rand 3)for 1..1e4;say$n/100

```

In each loop iteration, the player's initial choice is always door #2. First the door with the car is stored in `$%`, then a different door is selected for Monty Hall to expose. If the remaining door is equal to `$%`, the round is won.

(Perl puncutation variables `$%` and `$=` are used because they do integer truncation for free.)

# Answer
> 2 votes
## Powershell - 168 131 125 115

**Golfed code:**

```
nal g Random;1..1e4|%{$C=g 3;$P=g 3;$T+=$C-eq(0..2|?{$_-ne$P-and$_-ne(0..2|?{$_-ne$P-and$_-ne$C}|g)})};"$($T/100)%"

```

> **Changes from Original:**
> Trimmed 53 characters off the original script with some modifications.
>
> * Removed spaces and parenthesis where PowerShell is forgiving of it.
> * Used a `ForEach-Object` loop, via the `%` alias, instead of `while`.
> * Used number ranges (e.g.: `0..2`) instead of explicitly defined arrays.
> * Removed `write` from the last command - turns out I don't need it after all.
> * Flipped the expression for the host's choice around to use the shorter pipelining syntax.
> * Replaced 10000 with 1e4.
> * Took Joey's suggestion and omitted `Get-` from `Get-Random`. (Note: This modification *significantly* bloats the run time. On my system it jumped from about 20 seconds to nearly a half-hour per run!)
> * Used Rynant's trick of doing `$T+=...` instead of `if(...){$T++}`.

**Some notes:**

This script is intended to be as concise as possible, while also being as thorough a simulation of the Monty Hall scenario as possible. It makes no assumptions as to where the car will be, or which door the player will choose first. Assumptions are not even made for which specific door the host will choose in any given scenario. The only remaining assumptions are those which are actually stated in the Monty Hall problem:

* The host will choose a door that the player did not pick first, which does not contain the car.
    + If the player picked the door with the car first, that means there are two possible choices for the host.
* The player's final choice will be neither his initial choice nor the host's choice.

---

**Ungolfed, with comments:**

```
# Setup a single-character alias for Random, to save characters later.
# Note: Script will run a lot (about 500 times) faster if you use Get-Random here.
# Seriously, as it currently is, this script will take about a half-hour or more to run.
# With Get-Random, it'll take less than a minute.
nal g Random;

# Run a Monty Hall simulation for each number from 1 to 10,000 (1e4).
1..1e4|%{

    # Set car location ($C) and player's first pick ($P) to random picks from a pool of 3.
    # Used in this way, Random chooses from 0..2.
    $C=g 3;$P=g 3;

    # Increment win total ($T) if the car is behind the door the player finally chooses.
    # (Player's final choice represented by nested script.)
    $T+=$C-eq(

        # Filter the doors (0..2) to determine player's final choice.
        0..2|?{

            # Player's final choice will be neither their original choice, nor the host's pick.
            # (Host's pick represented by nested script.)
            $_-ne$P-and$_-ne(

                # Filter the doors to determine host's pick.
                0..2|?{

                    # Host picks from door(s) which do not contain the car and were not originally picked by the player.
                    $_-ne$P-and$_-ne$C

                # Send filtered doors to Random for host's pick.
                }|g
            )
        }
    )
};

# After all simulations are complete, output overall win percentage.
"$($T/100)%"

# Variable & alias cleanup. Not included in golfed script.
rv C,P,T;ri alias:g

```

---

I've run this script several times and it consistently outputs results very near to two-thirds probability. Some samples:

(As above)

* 67.02%

(Using `Get-Random` as the alias definition, instead of just `Random`)

* 66.92%
* 67.71%
* 66.6%
* 66.88%
* 66.68%
* 66.16%
* 66.96%
* 66.7%
* 65.96%
* 66.87%

# Answer
> 2 votes
# Ruby 48 40 38

My code doesn't make any assumptions about which door the prize will always be behind or which door the player will always open. Instead, I focused on what causes the player to lose. As per the Wikipedia article:

> \[...\] 2/3 of the time, the initial choice of the player is a door hiding a goat. When that is the case, the host is forced to open the other goat door \[...\] "Switching" only fails to give the car when the player picks the "right" door (the door hiding the car) to begin with.

So to simulate this (instead of using fixed values), I modeled it as so:

* the show randomly picks 1 of the 3 doors to hide the prize behind
* the player then randomly picks 1 of the 3 doors as his first choice
* the player always switches, so if his first choice was the same as the show's choice, he loses

The code v1:

```
w=0;10000.times{w+=rand(3)==rand(3)?0:1};p w/1e2

```

The code v3 (thanks to steenslag and Iszi!):

```
p (1..1e4).count{rand(3)!=rand(3)}/1e2

```

Some sample return values:

* 66.44
* 66.98
* 66.33
* 67.2
* 65.7

# Answer
> 1 votes
# Mathematica 42

```
Count[RandomReal[1,10^4],x_/;x>1/3]/100// N

```

> 66.79

# Answer
> 1 votes
**Python 2: 72 66 64**

```
from random import*
i=10000
exec"i-=randint(0,2)&1;"*i
print.01*i

```

Example output: 66.49

# Answer
> 1 votes
**PowerShell, 90**

```
$i=0
1..10000|%{$g=random 3;$n=0..2-ne$g;$g=($n,2)[!!($n-eq2)]|random;$i+=$g-eq2}
$i/10000

```

Commented:

```
# Winning door is always #2

$i=0

# Run simulation 1,000 times
1..10000|%{

# Guess a random door
$g=random 3

# Get the doors Not guessed
$n=0..2-ne$g

# Of the doors not guessed, if either is the
# winning door, switch to that door.
# Else, switch to a random door.
$g=($n,2)[!!($n-eq2)]|random

# Increment $i if
$i+=$g-eq2}

# Result
$i/10000

```

# Answer
> 1 votes
## C, ~~101~~ 95

```
float c,s,t,i;main(){for(;i<1e5;i++,c=rand()%3,s=rand()%3)i>5e4&c!=s?t++:t;printf("%f",t/5e4);}

```

That's for the actual simulation. For some cheaty rule-bending code, it's only ~~71~~ ~~65~~ 59:

```
p,i;main(){for(;i<1e5;rand()%5>1?i++:p++)printf("%f",p/1e5);}

```

I didn't do srand() because the rules didn't say I had to. Also, the cheaty version prints out about 30,000 extra numbers because it saves a character. I'm probably missing quite a few tricks, but I did the best I could.

# Answer
> 0 votes
**Fish \- ~~46~~ 43**

This is using the same assumptions that Tristin made:

```
aa*v>1-:?v$aa*,n;
v*a<$v+1$x! <
>a*0^<  $<

```

The down direction on `x` represents you initially picking the correct door, left and right are the cases that you picked a different door, and up is nothing, and will roll again.

Originally, I initialized `10000` with `"dd"*`, but `"dd"` had to all be on the same line, and I wasted some whitespace. By snaking `aa*a*a*` I was able to remove a column, and ultimately 3 characters. There's a little bit of whitespace left that I haven't been able to get rid of, I think this is pretty good though!

# Answer
> 0 votes
**PHP 140**

But i think that this is not working right. Any tip? I'm getting values from 49 to 50.

```
$v=0;//victorys
for($i=0;$i<1e4;$i++){
    //while the selection of the host ($r) equals the player selection or the car
    //h=removed by host, p=player, c=car
    while(in_array($h=rand(1,3),[$p=rand(1,3),$c=rand(1,3)])){}
    ($p!=$c)?$v+=1:0; //if the player changes the selection
}
echo ($v/1e4)*100;

```

# Answer
> 0 votes
## Game Maker Language, 19 (51 w/ loop)

```
show_message(200/3)

```

It outputs 66.67! This is the correct probability ;)

---

The serious-mode code, **51** characters:

```
repeat(10000)p+=(random(1)<2/3);show_message(p/100)

```

Make sure to compile with treat all uninitialized variables as 0.

---

The oldest code, **59** characters:

```
for(i=0;i<10000;i+=1)p+=(random(1)<2/3);show_message(p/100)

```

Again, make sure to compile with treat all uninitialized variables as 0.

The output was `66.23`

---
Tags: code-golf
---


title: Christmas Countdown

text:
# Question
Title: Christmas Countdown
In the spirit of the holidays, and as someone already started the winter theme(Build a snowman!) I propose a new challenge.

Print the number of days, hours, minutes, and seconds until Christmas(midnight(00:00:00) December 25th) on a stand alone window(not a console) in any unambiguous format you see fit, and continually update it as these values change.

Input - nothing, must read system time.

Shortest code wins :) The strings "Days", "Hours", "Minutes", "Seconds", and "Until Christmas" are free code. You can also flavour them up if you like. Flavouring them up is sheerly for the purpose of producing a nice output. You can not flavour strings for the purpose of making a magic number to save code.

# Answer
> 5 votes
# Ruby with Shoes, 96 - 33 = 63

```
Shoes.app{p=para
animate{p.text="0 days 0 hours 0 minutes #{1387951200-Time.new.to_f} seconds"}}

```

Well, you never said we *couldn't*. ;)

Updates once every frame.

The magic number `1387951200` is Christmas - Dec 25, 2013 00:00.

Sample IRB session for where I got the numbers:

```
irb(main):211:0> "0 days 0 hours 0 minutes  seconds".size
=> 33
irb(main):212:0> Time.new(2013,12,25,00,00,00).to_i
=> 1387951200
irb(main):213:0>

```

# Answer
> 3 votes
# Mathematica 167 - 44 = 123

The following continually updates a table showing the days, hours, minutes and seconds (in thousandths) until the beginning of Christmas day. I am unsure how to count discount for the free strings.

```
Dynamic[Grid[Join[{{"Countdown", "until Christmas"}},
{DateDifference[Date[], {2013, 12, 25, 0, 0, 0}, {"Day", "Hour", "Minute", "Second"}],
Clock[{1, 1}, 1]}[[1]] /. d_String :> d <> "s"]] ]

```

---

**A quick and dirty solution**: 104-19 = 85 chars

```
Dynamic@{DateDifference[Date[], {2013, 12, 25, 0, 0, 0}, {"Day", "Hour", "Minute",
 "Second"}], Clock[{1, 1}, 1]}[[1]]

```

> {{17, "Day"}, {10, "Hour"}, {59, "Minute"}, {51.4011, "Second"}}

# Answer
> 3 votes
# PowerShell: 279

*Character count does not take into account any freebies. @Cruncher - please adjust accordingly.*

## Golfed

```
($t=($a='New-Object Windows.Forms')+".Label"|iex).Text=($i={((New-TimeSpan -en 12/25|Out-String)-split"`n")[2..6]});$t.Height=99;($x=iex $a".Form").Controls.Add($t);$x.Text='Time Until Christmas';($s=iex $a".Timer").add_tick({$t.Text=&$i;$x.Refresh()});$s.Start();$x.ShowDialog()

```

This ain't the prettiest thing, either as code or as a window, but it works.

One nice bit is that this isn't just good for 2013 - it'll work in any year, from 00:00 on January 1 until 00:00 on December 25th.

***Warning: The window may become unresponsive - it will continue to update, but you might not be able to move or close it.***

## Un-golfed with comments

```
(
    # $t will be the label that displays our countdown clock on the form.
    $t=(
        # $a is used as a shortcut to address the Forms class later.
        $a='New-Object Windows.Forms'
    # Tack ".Label" onto the end with iex to finish making $t.
    )+".Label"|iex

# Set the text for our label.
).Text=(
    # $i will be a script block shortcut for later.
    $i={
        (
            (
                # Get the current "Time until Christmas", and output it as a string.
                New-TimeSpan -en 12/25|Out-String
            # Break the string into newline-delimeted array.
            )-split"`n"
        # Only output elements 2..6 - Days, Hours, Minutes, Seconds, Milliseconds.
        )[2..6]
    }
);

# Make sure the label is tall enough to show all the info.
$t.Height=99;

(
    # Use iex and $a as shortcut to make $x a "New-Object Windows.Forms.Form".
    $x=iex $a".Form"

# Add the label to the form.
).Controls.Add($t);

# Put 'Time Until Christmas' in the title bar for flavor.
$x.Text='Time Until Christmas';

(
    # Use iex and $a as shortcut to make $s a "New-Object Windows.Forms.Timer".
    $s=iex $a".Timer"

# Tell the timer what to do when it ticks.
).add_tick(
    {
        # Use the $i script block to update $t.Text.
        $t.Text=&$i;
        # Reload the form so the updated text displays.
        $x.Refresh()
    }
);

# Start the timer.
$s.Start();

# Show the form.
$x.ShowDialog();

# Variable cleanup - omit from golfed code.
rv t,a,x,i,s

```

# Answer
> 2 votes
# Python 136

I'm sure someone can do this better - I've never used Tkinter before. In particular I bet the `l.pack()` and `l["text"]` can are avoidable.

## Golfed

```
from Tkinter import*
from datetime import datetime as d
r=Tk()
l=Label(r)
l.pack()
while 1:
    l["text"]=d(2013,12,25)-d.now()
    r.update()

```

# Answer
> 1 votes
# R

Here is a solution for R using GTK+ via the gWidgets package. This is pretty ugly code since I am not familiar with the gWidgets/GTK+ package at all.

## Code

Here is the code:

```
library(gWidgets)
options(guiToolkit="RGtk2")

# FUNCTION compute the hours minutes and seconds from time in seconds
fnHMS = function(timeInSec) {
  hours = timeInSec %/% 3600
  minutes = (timeInSec %% 3600) %/% 60
  seconds = (timeInSec %% 3600) %% 60
  return(list(hours = hours, minutes = minutes, seconds = seconds))
}

# test the function
fnHMS(1478843)

# container for the label and the button widget
christmasCountdownContainer = gwindow('Christmas Countdown!!', visible = TRUE)
christmasCountdownGroup = ggroup(horizontal = FALSE,
                                 container = christmasCountdownContainer)
ccWidget1 = glabel(sprintf('%4.0f hours, %4.0f minutes, %4.0f seconds till Christmas!!',
                           (liHMS <- fnHMS(as.double(difftime(as.POSIXct(strptime('25-12-2013 00:00:01',
                                      format = '%d-%m-%Y %H:%M:%S')),
                  Sys.time(), units = 'secs'))))[[1]], liHMS[[2]], liHMS[[3]]),
                            container = christmasCountdownGroup)

ccWidget2 = gbutton("Update!", handler = function(h, ...) {
  # retrieve the old value of the ccWidget1
  oldValue = svalue(ccWidget1)
  liHMS = fnHMS(as.double(difftime(as.POSIXct(strptime('25-12-2013 00:00:01',
                                                       format = '%d-%m-%Y %H:%M:%S')),
                                   Sys.time(), units = 'secs')))
  svalue(ccWidget1) = sprintf('%4.0f hours, %4.0f minutes, %4.0f seconds till Christmas!!',
                              liHMS[[1]], liHMS[[2]], liHMS[[3]])
  }, container = christmasCountdownGroup)

```

## Output

Here is what the output looks like:

# Answer
> 1 votes
## Dyalog APL, 61

```
{⎕SM[1;]←1 1,⍨⊂⍕(1 4⍴2↓2013 12 24 23 59 59 1000-⎕TS)⍪'Days' 'Hours' 'Minutes' 'Seconds'⋄∇1}1

```

# Answer
> 0 votes
# C# 128

Golfed

```
using D=System.DateTime;using System.Windows.Forms;class C{static void Main(){MessageBox.Show(""+(new D(2013, 12, 25)-D.Now));}}

```

Ungolfed

```
using D=System.DateTime;
using System.Windows.Forms;
class C
{
    static void Main()
    {
        MessageBox.Show(""+(new D(2013,12,25)-D.Now));
    }
}

```

# Answer
> 0 votes
## Python 2, 115

```
from datetime import datetime as d
n=d.now()
print str(24-n.day),str(23-n.hour),str(59-n.minute),str(60-n.second)

```

This counts newlines as 2 characters.

---
Tags: code-golf
---


title: Triforce ReBoot

text:
# Question
Title: Triforce ReBoot
Seeing how hello world has backfired terribly, here is a harder one.

I love Zelda and I love ReBoot.

Create the following

**Requirements:**
It must be a window (can be ANY window even browsers and such).
The window can be of any size.
Window may not contain anything else except the picture.
Window should not close itself right away.
Triangles must be any shade of blue.
Circle must be any shade of green.
Smaller triangle must touch edges of the
No stealing images by providing links.

**Condition:** Shortest code wins.

PS: Yes ReBoot logo is slightly different but this is close enough to make it fun.

EDIT: I added another requirement. It seems like we have a lot of very genius people who enjoy finding loopholes :P I love you guys.

# Answer
# Mathematica ~~118 119 118 107~~ 97

Edit: Shortened to 107 chars with help from Belisarius and to 97 with alephalpha.

```
CreateDialog[Graphics@{Blue,Polygon@Outer[Plus,#,#,1]&@{{0,0},{1,1},{2,0}}, Green,
{2,1}~Circle~1}]

```
> 10 votes

# Answer
## Dyalog APL (~~121~~ ~~116~~ 115)

(Edit: use triangles 8 elements wide instead of 10, to shorten code a bit)

(Edit 2: I was only ever using , so included the `¨` in the definition of `M`)

```
M←{' ',⍵,⍺,⍨4/0}¨⋄⎕SM←↑(256M⊃,/(⊂8 0)(⊂8 32)(⊂0 16)∘.+⊂(,⍳⍴Z)/⍨≤/¨,Z←⊖Z,⌽Z←2/⍳2/8),512M⌈0 16∘+¨1 2∘×¨8+8×1 2∘○¨⍳1e4

```

Graphics? Who needs graphics?

(Also, black is the default background, you didn't say to change it)
> 7 votes

# Answer
# Shell script: ~~166~~ 163 characters

```
f=-fill
d=-draw
convert -size 64x32 xc: $f blue $d 'polygon 32,0 0,32 64,32' $f white $d 'polygon 32,32 16,16 48,16' $f none -stroke lime $d 'circle 32,16 32,0' x:

```

Sample output:
> 4 votes

# Answer
# R, 124, 122, 111

```
frame()
p=polygon
p(c(1,3,5)/5,c(1,3,1)/5,c=4)
p(c(2,4,3)/5,c(2,2,1)/5,c="white")
symbols(.6,.4,.1,i=1,a=T,f=3)

```

This produces the following picture in a plot window:
> 4 votes

# Answer
## Java, 434 358 349

```
import java.awt.*;
public class T
{
    public static void main(String[] a)
    {
        new Frame()
        {
            public void paint(Graphics g)
            {
                g.setColor(Color.BLUE);
                Polygon p=new Polygon(new int[]{50, 75, 100},new int[]{75, 50, 75},3);
                g.fillPolygon(p);
                p.translate(-25, 25);
                g.fillPolygon(p);
                p.translate(50, 0);
                g.fillPolygon(p);
                g.setColor(Color.green);
                g.drawOval(50, 50, 50, 50);
            }
        }.show();
    }
}

```

golfed

```
import java.awt.*;public class T{public static void main(String[] a){new Frame(){public void paint(Graphics g){g.setColor(Color.BLUE);Polygon p=new Polygon(new int[]{50,75,100},new int[]{75,50,75},3);g.fillPolygon(p);p.translate(-25,25);g.fillPolygon(p);p.translate(50,0);g.fillPolygon(p);g.setColor(Color.green);g.drawOval(50,50,50,50);}}.show();}}

```

Who knew golfing reduces code so much.

EDIT: Thanks manatwork for all your suggestions.
> 3 votes

# Answer
## Game Maker Language, 167 165 155

EDIT 1 - I shaved off two characters by replacing `c_green` with `32768`, the same value. The other color's values were longer than their predefined names.

EDIT 2 - Epic golf! Used variables for frequently used values, and forgot that newlines aren't needed (newlines count as two spaces).

The room (`r`) is predefined 64 by 32 with a white background. Object `d` is anywhere in room `r`. Draw Event code:

```
a=16b=32draw_set_color(c_blue)draw_triangle(0,b,64,b,b,0,0)draw_set_color(32768)draw_circle(b,a,a,1)draw_set_color(c_white)draw_triangle(a,a,48,a,b,b,0)

```

Result:

## Ti84-Basic - 54 characters (but output is black and white)

```
:Line(0,0,2,0
:Line(0,0,1,1
:Line(2,0,1,1
:Circle(1,.5,.5

```
> 3 votes

# Answer
## HTML, 101

```
<img style=position:absolute;clip:rect(30px,130px,110px,20px) src=https://i.stack.imgur.com/iE6m9.png>

```
> 2 votes

# Answer
## HTML+CSS, ~~352~~ ~~290~~ ~~261~~ 257

```
<div style="width:0;border:50px solid #fff;border-bottom-color:#00f">
<p style="border:25px solid #00f;border-top-color:#fff;border-bottom:0;margin:25px 0 0 -25px">
<p style="border:1px solid #0f0;border-radius:50px;width:50px;height:50px;margin:-52px -26px">

```

http://jsfiddle.net/WF3hP/6/

Ungolfed:

```
<style>
    #blue-triangle {
        width:0;
        border:50px solid #fff;
        border-bottom-color:#00f
    }
    #white-triangle {
       border:25px solid #00f;
       border-top-color:#fff;
       border-bottom:0;
       margin:25px 0 0 -25px
    }
    #circle {
       border:1px solid #0f0;
       border-radius:50px;
       width:50px;
       height:50px;
       margin:-52px -26px
     }
</style>
<div id="blue-triangle">
<p id="white-triangle">
<p id="circle">

```
> 2 votes

# Answer
## R, 108 characters

Very similar to Sven Hohenstein solution but differs in two interesting points, so I thought I would add it:

```
frame()
p=polygon
p(c(0:3,1:4)/5,c(0:1,0:1,1:2,1:0)/5,c=4)
t=seq(0,2*pi,.1)
p(.2*cos(t)+.4,.2*sin(t)+.2,b=3)

```

Instead of drawing a large blue triangle and a small white one, I draw a polygon representing already the three triangles. As for the circle, this one (whose code is clearly longer than Sven's) doesn't lose its contacts with the triangles on resize.
Finally instead of using the color names I used their number in R's default color palette (4 for blue and 3 for green).
> 2 votes

# Answer
### JavaScript (canvas, Firefox), ~~237~~ 231 characters

```
<body onload=with(c=document.all.a.getContext('2d'))fillStyle='#00F',strokeStyle='#0F0',mozFillRule='evenodd',c.f=lineTo,moveTo(4,0),f(8,4),f(0,4),f(2,2),f(6,2),f(4,4),f(2,2),fill(),beginPath(),arc(4,2,2,0,7),stroke()><canvas id=a>

```

I couldn't find any hard requirements on the dimensions, so I decided to abuse that a bit and go with 8×4 pixels to cut down code size... also, relies on the Mozilla extension mozFillRule to get even-odd filling for the triforce.

jsbin (small), jsbin (bigger)
> 1 votes

# Answer
### SVG ~~305~~ 296

```
<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="1 3 9 10">
<path d="M 5,4 2.5,7 7.5,7 5,4 z M 7.5,7 5,10 10,10 7.5,7 z M 5,10 2.5,7 0,10 5,10 z"
fill="#00f" /><path d="m 7.5,7 a 2.5,3 0 0 1 -5,0 2.5,3 0 1 1 5,0 z"
fill="none" stroke="#0f0" stroke-width="0.02" /></svg>

```
> 1 votes

# Answer
## Sage (CLI), ~~111~~ 106

```
p=polygon;circle((2,1),1,color=(0,1,0))+p([(0,0),(2,2),(4,0)])+p([(1,1),(3,1),(2,0)],axes=0,color=(1,1,1))

```

This is via the Sage command line interface. (This works also in a Sage Notebook, but although the image appears in its own cell, that probably doesn't qualify as a "window".)

EDIT: Eliminated 5 minus signs and replaced the screenshot of a Sage Notebook cell with one of a Sage CLI window. (Credit @boothby)
> 1 votes

# Answer
# HTML 118

```
<svg><path fill=#00f d="M0,2 2,0 4,2 2,2 3,1 1,1 2,2z"/><circle fill=none stroke-width=.1 stroke=#0f0 cx=2 cy=1 r=1 />

```
> 1 votes

# Answer
## Golf-Basic 84, 36 characters (Output is Black and White)

```
l;0,0,2,0l;0,0,1,1l;2,0,1,1c;1,.5,.5

```
> 0 votes

---
Tags: code-golf
---


title: Type out Green Eggs and Ham in vim

text:
# Question
Title: Type out Green Eggs and Ham in vim
The book Green Eggs and Ham by Dr. Seuss is famous for only having 50 different words in the entire story of the book.

Your task is to create a sequence of keystrokes that will result in the entire text of Green Eggs and Ham when applied to an empty file in the vim text editor, starting in normal mode with all default settings. Your keystrokes must not load any other files as part of their operation - all text must be generated within the editor itself.

Your final buffer must look exactly like this file, although it can remain in whichever mode it ends up being in (you don't have to have a final `<Esc>` to return it to normal mode).

Chorded keystrokes like `<C-o>` or using Shift to type a capital letter count as a single keystroke.

The sequence of the fewest keystrokes to achieve this goal wins.

# Answer
> 10 votes
## 1864 keystrokes

Somebody could probably write some code that produces a more optimal solution, but this beats the reference case for now. This is a damn mess, and I am ashamed I did it by hand.

First, we enter insert mode.

```
i

```

Then all this

```
That ]! That ]!
IDNlike that ]!

Do Y like$?

|;].
IDNlike$.

WPY LTB or tB?

IZ LTB or tB.
IZ LTanywB.
IDNlike$.
|;].

WPY LTin a h@?
WPY LT=a m@?

|in a h@.
|=a m@.
|B or tB.
|.
IDNlike$.
|;].

WPY ETin a box?
WPY ET=a fox?

Not_a box. Not =a fox.
Not_a h@. Not =a m@.
IZ ETB or tB.
IZ ETanywB.
IZ eat$.
|;].

WPY? CPY? In a car?
Eat them! Eat them! B they are.

IZ,X,_a car.

You may LT. You will see.
You may LTin a tree!

IZ,X_a tree.
Not_a car! You let me be.

|in a box.
|=a fox.
|in a h@.
|=a m@.
|B or tB.
|.
IDNlike$.
|;].

AQ! AQ! AQ! AQ!
CPY;wPY;on aQ?

Not_aQ! Not_a tree!
Not_a car! Sam! Let me be!

IZ,X,_a box.
IX,Z;=a fox.
:=a m@.
:in a h@.
:B or tB.
:anywB.
IDNlike$.
|;].

Say! In +? B_+!
WPY;cPY,_+?

IZ,X,_+.

WPY;cPY,_the rain?

IZ,X,_the rain.
Not_+. Not on aQ.
Not_a car. Not_a tree.
|;Sam;Y see.
Not_a h@. Not_a box.
Not =a m@. Not =a fox.
:B or tB.
|!

You do not like$?
|;].

CPY;wPY;=a g^?

IZ,X;=a g^!

WPY;cPY;on a b^?

IX,Z;on a b^.
IWN,WN;=a g^.

:in the rain.
:on aQ.
Not_+! Not_a tree!
Not_a car! You let me be!
|in a box.
|=a fox.
:in a h@.
|=a m@.
|B or tB.
|!

IDNlike$!
|;].

You do not LT. So Y say.
Try them! Try them! & Y may.
Try them and Y may;I say.

Sam! If Y will let me be,
I will try them. You will see.

Say! I like$!
I do! I LT;]!
& I wPETin a b^.
& I wPET=a g^.

!ETin the rain.
&_+. & on aQ.
&_a car. &_a tree.
They are so good;so good;Y see!

So I will ETin a box.
!ET=a fox.
!ETin a h@.
!ET=a m@.
!ETB and tB.
Say! I will ETanywB!

I do so like$!

Thank Y! Thank Y;]!

```

Hit escape to enter command mode. And unravel the compressed stuff. Order matters, as I've compressed some compressed text.

```
<Esc>
%s/|/|anywB/g
%s/:/IWNET/g
%s/|/IDNLT/g
%s/Z/ wPnot/g
%s/X/ cPnot/g
%s/&/And/g
%s/+/the dark/g
%s/@/ouse/g
%s/^/oat/g
%s/Y/you/g
%s/IDN/I do not /g
%s/LT/like them /g
%s/]/Sam-I-am/g
%s/ET/eat them /g
%s/WN/ will not/g
%s/$/ green eggs and ham/g
%s/P/ould /g
%s/!/And I will /g
%s/Q/ train/g
%s/B/here/g
%s/_/ in /g
%s/=/with /g
%s/;/, /g

```

# Answer
> 6 votes
# 3,470 keystrokes

```
i<entire text of file>

```

The text file is 3,469 characters long, so typing "i" to put it in insert mode and typing out each character individually will take 3,470 keystrokes.

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


title: Relative dates in words

text:
# Question
Title: Relative dates in words
Given a specific date, have the code output a relative reference:

1. If the date entered is ahead of the current date, express as "x days from now" or "x weeks, y days from now", or "x years, y weeks, z days from now". Zero units need not be mentioned.
2. If the date is the current simply have it output "Today"
3. If the date entered is earlier than the current date, express as "x days ago" or "x weeks, y days ago", or "x years, y weeks, z days ago". Zero units need not be mentioned.

Smallest solutions are the winners here...

Good luck!

# Answer
> 2 votes
## JavaScript, 146

Input is a timestamp as number of milliseconds from 1970-01-01 (Unix timestamp × 1000), since this makes things more conventient for me (and no input format was specified).

```
D=new Date-prompt()
d=Math.abs(D/864e5)
e=d%365%7|0
alert(e?[d/365|0,"years,",d%365/7|0,"weeks,",e,"days",D>0?"ago":"from now"].join(" "):"Today")

```

# Answer
> 5 votes
# R, 102, 98

## (kinda cheating: literal interpretation of the question)

```
cat(if(x<-as.Date(readline())-Sys.Date())c(abs(x),"days",c("from now","ago")[(x<0)+1])else"today")

```

Examples:

```
2013-12-08
today

2010-01-13
1425 days ago

2015-12-2
724 days from now

```

# Answer
> 4 votes
# Ruby, kinda cheating - 89, less cheaty - 140

## Kinda cheating, 89

```
f=->d{i=((d-Time.now)/86400).ceil;["Today","#{-i} days ago","#{i} days from now"][0<=>i]}

```

It's a function that takes the date as an argument and returns the string.

Examples:

```
irb(main):036:0> f[Time.new(2013, 12, 1)]
=> "7 days ago"
irb(main):037:0> f[Time.new(2013, 12, 10)]
=> "2 days from now"
irb(main):038:0> f[Time.new(2013, 12, 8)]
=> "Today"
irb(main):039:0> f[Time.new(2011, 10, 8)]
=> "792 days ago"

```

Hey, you never said we couldn't use only days!

> express as "x days from now" **or** "x weeks, y days from now", **or** "x years, y weeks, z days from now". \[emphasis mine\]

Well, I choose the first one :P Abusing the rules is so fun!

## Less cheaty, 140

```
f=->d{t=Time.new
a=((d-t)/86400).ceil
g='from now'
a,g=-a,'ago'if a<0
a==0?'Today':"#{a/365} years, #{a%365/7} weeks, #{a%365%7} days #{g}"}

```

Examples:

```
irb(main):111:0> f[Time.new 2013, 12, 10]
=> "0 years, 0 weeks, 2 days from now"
irb(main):112:0> f[Time.new 2013, 12, 17]
=> "0 years, 1 weeks, 2 days from now"
irb(main):113:0> f[Time.new 2014, 12, 17]
=> "1 years, 1 weeks, 2 days from now"
irb(main):114:0> f[Time.new 2012, 12, 17]
=> "0 years, 50 weeks, 6 days ago"
irb(main):115:0> f[Time.new 2012, 1, 1]
=> "1 years, 48 weeks, 6 days ago"
irb(main):116:0> f[Time.new 2013, 12, 8]
=> "Today"

```

It said

> Zero units need not be mentioned.

But you never said they **can**not be mentioned.

# Answer
> 2 votes
## C - 348

First CodeGolf post, so I figured that I would have fun with it.

```
#include<time.h>main(int a,char *v[]){a--;struct tm t={0};char* n=strtok(v[1],"/");while(n!=0){switch(a++){case 1:t.tm_mon=atoi(n)-1;case 2:t.tm_mday=atoi(n);case 3:t.tm_year=atoi(n)-1900;}n=strtok(0,"/");}a=(int)difftime(time(0),mktime(&t))/86400;printf("%s\n",a=0?"today":(a>0?strcat(itoa(a)," days ago"):strcat(itoa(abs(a))," days from now")));}

```

Ungolfed:

```
#include <time.h>
main (int a,char *v[])
{
  a--;
  struct tm t={0};
  char* n=strtok(v[1],"/");
  while(n!=0)
  {
    switch(a++)
    {
                case 1:t.tm_mon=atoi(n)-1;
                case 2:t.tm_mday=atoi(n);
                case 3:t.tm_year=atoi(n)-1900;
    }
    n=strtok(0,"/");
  }
  a=(int)difftime(time(0),mktime(&t))/86400;
  printf("%s\n",a=0?"today":(a>0?strcat(itoa(a)," days ago"):strcat(itoa(abs(a))," days from now")));
}

```

---

Test runs:

```
$ ./date 12/8/2013
1 days ago
$ ./date 12/10/2013
1 days from now
$ ./date 12/9/2013
today

```

# Answer
> 1 votes
## Python 2 - 134

This is a bit abusive as this assumes the objects given is a `datetime.date()` object. But you did say it would be given as a date, so...

```
from datetime import*
D=input()
t=datetime.now().date()
w=str(D-t).split(',')[0]
print[w[1:]+" ago","today",w+" from now"][cmp(D,t)+1]

```

---
Tags: code-golf, date
---


title: Code Golf - Word Clock

text:
# Question
Title: Code Golf - Word Clock
Write a program which takes the current time of the system clock, rounds to the nearest minute (you may choose how to round halves) and displays it formatted as the following:

```
A quarter past one in the morning.
A quarter to two in the afternoon.
Two o'clock in the afternoon.
Twenty-five minutes to three in the morning.
Twenty-seven minutes to seven in the evening.
One minute past twelve in the afternoon.
Twelve o'clock noon.
Twelve o'clock midnight.

```

Rules:

* 12:01am to 11:59am is deemed as morning.
* 12:01pm to 5:59pm is deemed as afternoon.
* 6:00pm to 11:59pm is deemed as evening.
* 15 minutes past the hour must be expressed as `A quarter past` the hour
* 30 minutes past the hour must be expressed as `Half past` the hour
* 45 minutes past the hour must be expressed as `A quarter to` the upcoming hour
* On-the-hour times must be expressed as the hour `o'clock`, with the addition of noon and midnight being expressed with the addition of `noon` or `midnight` respectively.
* Other times in hh:01 to hh:29 must be expressed as (number of minutes) `past` the hour.
* Other times in hh:31 to hh:59 must be expressed as (number of minutes) `to` the upcoming hour.
* Twenty-one to twenty-nine must be hyphenated.
* The first letter of the output must be capitalised. The other letters must be lower-case.

It would be useful to provide a testing version of your code so that it can be tested without manipulating the system clock.

# Answer
## Python 2.7, ~~159~~ ~~162~~ ~~156~~ 161

```
from datetime import*
n=datetime.now()
if n.hour()<12:
 t="morning"
elif n.hour()<18:
 t="afternoon"
else:
 t="evening"
print"%i in the %s."%(n.hour(),t)

```

**Edit #1** \- Added a period at the end of the output.

**Edit #2** \- Shortened the imports, lengthened code to correct syntax.
> 0 votes

# Answer
# Mathematica 450

`Date[]` calls for the current date and time. `[[{4,5}]]` returns the hour and minutes

```
f[]:=f[Date[][[{4,5}]]];
f[{h_,m_}]:=Module[{p,w,s},
p@h1_:=Which[0<h<12," in the morning.",12<h<18," in the afternoon.",18<h<24, " in the evening."];
s[t_]:=WolframAlpha["spell "<>ToString@t,{{"Result",1},"Plaintext"}];
w=s[h~Mod~12]<>p@h;
Which[
m==0, Switch[h,12, "noon", 0|24,"midnight",_,s[h~Mod~12]<>p@h],
m==15,"a quarter past "<>w,
m==30,"half past "<>w,
m==45,"a quarter to "<>s[h~Mod~12+1]<>p@h,
m<30,s@m<>" minutes after "<>w,
m>29,s[60-m]<>" minutes before "<>s[h~Mod~12+1]<>p@h]]

```

**Current Time**

```
f[]

```

> "ten minutes past three in the afternoon."

**Specific times**

```
f[{4, 45}]
f[{10, 30}]
f[{11, 0}]
f[{12, 0}]
f[{13, 15}]
f[{15, 0}]
f[{22, 17}]
f[{24, 0}]

```

> "a quarter to five in the morning."
> "half past ten in the morning."
> "eleven in the morning."
> "noon"
> "a quarter past one in the afternoon."
> "three in the afternoon."
> "seventeen minutes past ten in the evening."
> "midnight"
> 2 votes

---
Tags: code-golf
---


# Question
Title: Write a function that results the sum of two integers using bitwise operations, w\o conditional operation
* You cannot use `if`,`while`,`for`, `?:`, `||`, `&&` etc., or recursion!
* Assume it is Int.32
* Shortest answer wins

# Answer
> 2 votes
## C - 91

Based on Kogge-Stone, there is probably ways to cut parts of this off, but it seems good enough to start the race.

```
g,p;t(h){g|=p&g<<h;p&=p<<h;}d(a,b){g=a&b,p=a^b;t(1);t(2);t(4);t(8);t(16);return a^b^g<<1;}

```

An ungolfed version and possibly some explanation can be found from http://chessprogramming.wikispaces.com/Parallel+Prefix+Algorithms

# Answer
> 1 votes
# Python 3 (66 chars)

```
def a(i,j):v=locals();exec("i,j=i^j,(i&j)<<1;"*32,v);return v['i']

```

# Answer
> 0 votes
## J - 814

A better version

```
+&.(1&(32 b.))

```

Which does: sum under rotate bits which means (for people who don't speak J): do rotate on both arguments, sum them, inverse the rotation.

This way the bit operation is really used in the result.

# Answer
> 0 votes
# Golfscript, 3 (or 7, if it needs to be assigned to a function)

Since you never said `+` was forbidden

```
0|+

```

`0|` basically does nothing (if the top of the stack is a number), because `n [bitwise or] 0` is `n`.

`+` adds them.

If it needs to be a function:

```
{0|+}:s

```

Assigned to function `s`.

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