# Question
Title: The answer to life, the universe, and everything
**Introduction**: Deep Thought calculated *The answer to life the universe and everything* in a period of 7.5 million years, the solution was **`42`**.

Write a program in any programming language that takes approx `75` seconds to calculate, starting from whatever you want, and output the number **`42`**.

N.B. The number `42` must be calculated somehow (random numbers, whatever you prefer), not just hard-coded in your script.

As suggested, you can't use `sleep` or equivalent functions. Be inventive.

# Answer
This takes about 75s on a raspberry pi overclocked to 1GHz

```
#!/usr/bin/env python
from itertools import product, count

for n in count(1):
    i = 0
    for a, b, c, d in product(range(n), repeat=4):
        if a > b > c > d > 0 == (a*b-c*d)%n == (a*c-b*d)%n == (a*d-b*c)%n:
            i += 1
    if i == n:
        break
print i

```

It works because:

> 42 is the only known value that is the number of sets of four distinct positive integers a,b,c,d, each less than the value itself, such that ab-cd, ac-bd, and ad-bc are each multiples of the value. Whether there are other values remains an open question

http://www.mathpages.com/home/kmath255.htm
> 54 votes

# Answer
## Python 2.7

To answer the question, one must *know* the question - and the question is:

> What do you get when you multiply six by nine? Thanks to TRiG for the correction

So **Deep Thought** relies on the handy use of base 13:

> 613 x 913 = 4213

We import our constants:

```
from random import randrange as scrabbleBag, randint
from datetime import datetime,timedelta
life,universe,everything,nothing=6,9,1,-3
endOfTheUniverse = 80

```

We also define our earth-things, being a **bag of scrabble tiles**, **Arthur** (a predictable albeit it slightly odd, computer of sorts), **Trillian** (our rational heroine),

```
tile = lambda i: scrabbleBag(26)
arthur = lambda i: int(`i`,life+universe+everything+nothing)
trillian = lambda i: ''.join(map(str,divmod(i,life+universe+everything+nothing)))

```

We introduce **Zaphod** \- a random sort, who eventually runs out of steam as we near the `endOfTheUniverse`.

```
zaphod = lambda : not(randint(0,(endOfTheUniverse-(datetime.now() - start).seconds)**3))

```

And **Marvin the Paranoid Android**, whose positive attitude could stop any party:

```
marvin = lambda : endOfTheUniverse<(datetime.now() - start).seconds

```

And we continue to run these 4 characters through the mix until they compute ***it***:

```
while answer is not life * universe * everything:
  rack = sum(tile(i) for i in range(7))
  answer = (zaphod or marvin) and arthur(rack)
print trillian(answer)

```

## The complete `deepthought.py`:

```
from random import randrange as scrabbleBag, randint
from datetime import datetime,timedelta
life,universe,everything,nothing=6,9,1,-3
endOfTheUniverse = 80

tile = lambda i: scrabbleBag(26)
arthur = lambda i: int(`i`,life+universe+everything+nothing)
trillian = lambda i: ''.join(map(str,divmod(i,life+universe+everything+nothing)))

start = datetime.now()

zaphod = lambda: not(randint(0,(endOfTheUniverse-(datetime.now() - start).seconds)**3))
marvin = lambda: endOfTheUniverse<(datetime.now() - start).seconds

answer = None
while answer is not life * universe * everything:
  rack = sum(tile(i) for i in range(7))
  answer = (zaphod() or marvin()) and arthur(rack)
print trillian(answer)

```

This should finish somewhere around the 75 second mark, definitely finishing by 80 seconds. Sometimes earlier to to Zaphods *Infinite Improbability Drive*.
> 42 votes

# Answer
# DOS Batch — the answer to life, the Universe and everything

Thanks to mynameiscoffey for his simplification!

Save as `answer.bat`:

```
@ ping 127.0.0.1 -n 76 >nul && @ echo %~z0

```

Then run it, and wait 75 seconds:

```
> answer
42

```
> 13 votes

# Answer
# Bash (OS X)

This could probably be ported to other systems without too much trouble. Replace `say` with whatever you're using as a text-to-speech command line utility. The `-f` option takes input from a named file.

With a bit of luck, it might even output the correct number :-)

This takes almost exactly 1 minute 15 seconds to run on my system (OS X 10.5).

```
#!/bin/bash
grep -E '^life|universe|and.everything|[ultimate]question$' /usr/share/dict/words | sed 's/$/,/' | nl > "$TMPDIR/deepthought"
say -v Alex -f "$TMPDIR/deepthought"
nw=`cat $TMPDIR/deepthought | wc -l`
say -v Alex "The answer, to the ultimate question, is: $nw"
echo $nw
rm "$TMPDIR/deepthought"

```
> 11 votes

# Answer
## MATLAB

This is a tough one. Since we do not really know the question, the only viable method of getting the answer is by means of a global optimisation method. In this case I opted for the simulated annealing method, since this one has given me nice answers to tough questions before.

All this code is doing is looking for the optimal value of a function which input is life itself. And the amazing thing is that it works. So, did I just validate Deep Thought?

```
tic;

the_answer=round(simulannealbnd(@(life)abs(3.7376696-log(life)),140489, ...
           -inf,inf,saoptimset('MaxFunEvals',10^16)))
toc;

```

Output:

```
the_answer =

    42

Elapsed time is 74.892428 seconds.

```
> 10 votes

# Answer
# C - 1089 bytes

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

int answer(int the)
{
   int to = 0;

   while (the != 0) {
      to *= 10;
      to += the%10;
      the /= 10;
   }
   return to;
}

int optimism(int the)
{
    return abs(the);
}

int getRandomNumber()
{
    return 4; // chosen by fair dice roll.
              // guaranteed to be random.
}

int main()
{
    // initialize
    int life = getRandomNumber(), universe, everything;

    // get inverse answer
    int question = clock();
    while (clock()-question < CLOCKS_PER_SEC*75) {
        life += getRandomNumber();
    }
    life = optimism(life); // optimism is the best way to see life
    life %= 1000;

    // avoids unwanted race conditions with the answer by "Lego Stormtroopr"
    if (life<100 || life>997) {life -= getRandomNumber()*100;}
    if (optimism(life/100%10 - life%10) < 2) {life += getRandomNumber();}
    universe = answer(life);
    everything = optimism(life<universe?life-universe:universe-life);

    printf("%d\n", (answer(everything)+everything+3)/26);

    return 0;
}

```

---

## Compressed:

```
#include <time.h>

int f(int d) {
   int e = 0;
   while (d != 0) e = e*10+d%10, d /= 10;
   return e;
}

int main() {
    int a = 4, b, c, d = clock();
    while (clock()-d < CLOCKS_PER_SEC*75) a += 4;
    a = abs(a)%1000;
    a -= a<100||a>997?400:0;
    a += abs(a/100%10-a%10)<2?4:0;
    b = f(a);
    c = abs(a<b?a-b:b-a);
    return (f(c)+c+3)/26;
}

```
> 5 votes

# Answer
# C

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

int i, j;

int main() {
    i = clock();
    while(clock() - i < 75 * CLOCKS_PER_SEC);
    for(i = j = 0 ; i < 48 ; i++)
        j += "The answer to Life, the Universe, and everything"[i];
    printf("%i", j % 157);
}

```
> 4 votes

# Answer
# Ruby

```
t = Time.new.to_i
n = 0
loop{
  break if Random.new(n).rand(2000000) == Random.new(374076).rand(1000000)
  n += 1
}
puts Random.new(n).rand(2000000)
puts "Took #{Time.new.to_i - t} seconds; seed was #{n}"

```

Output on my machine:

```
42
Took 123 seconds; seed was 3771996

```

This abuses the RNG. ;)
> 4 votes

# Answer
## JavaScript - Finding "the answer to life and everything" by solving an equation

Let's have a look at this equation :

```
1 / p  +  1 / q  +  1 / r  =  1 / 2

```

There is many solutions, but if you want `r` to be as big as possible and `p`, `q` and `r` to be naturals there is only two solutions :

`1/3 + 1/7 + 1/42 = 1/2` and `1/7 + 1/3 + 1/42 = 1/2`

with `p <= q <= r`, there is only one solution and `r` always equal to `42`

What is the most (in)efficient way to solve a equation ?

By trying all possibles values !

Here is the code :

```
var n = Math.pow(2, 32);
for (var i = 1; i <= n; i++)
{
    for (var j = 1; j <= n;  j++)
    {
        for (var k = 1; k <= n; k++)
        {
            if ((1 / i + 1 / j + 1 / k) == 1 / 2)
               throw k;
        }
    }
}

```

How much time will it take ? To be honest, I do not know because I have not been able to run it to the end.

However, you can try with small `n` values (it has to be bigger or equal to `42`) and you will get correct result. For small values such as `n = 2000`, it takes almost one minute on my laptop. So i guess with big values given in the example it will take days, weeks, or even years !!!

**Finding the solution in approximately 75 seconds :**

One requirement from initial question is it should take approximately 75 sec to execute. One way to achieve this is to automatically adjust the complexity of the algorithm over the time :

```
var now = new Date().getTime();
var iterations = 0;
var n = Math.pow(2, 32);
for (var i = 1; i <= n; i++)
{
    for (var j = 1; j <= n; j++)
    {
        for (var k = 1; k <= n; k++)
        {
            if ((1 / i + 1 / j + 1 / k) == 1 / 2)
                throw k;

            if (new Date().getTime() - now > 1000) //one second has elapsed
            {
                now *= 2; //never wanna see you again
                n = 42;   //this is the minimum
                while(3 * n * n + 7 * n + 42 < iterations * 74) n++;
                i = j = k = 0; //reset
            }
            iterations++;
        }
    }
}

```

How it works (for the curious) : it checks how many iterations have been done in one second, then multiply this by 74 and adjust `n` to match that value. eg : if it take one second to do 500 iterations, it will take 10 seconds to do 5000 iterations. Note that it multiply by 74 not 75 because we already spent one second for "benchmarking".

source and credits for math
> 4 votes

# Answer
C# - 151 Characters

```
class P
{
   static void Main()
   {
      var w = new System.Diagnostics.Stopwatch();
      w.Start();
      while (w.ElapsedMilliseconds < 75000);
      System.Console.Write((int)'*');
   }
}

```
> 2 votes

# Answer
**C++**

Calculates the partitions of 10 via a rather inefficient method. Took 130s to run in a Release build on my system but someone with a sufficiently fast PC should be able to run it in ~75s...

```
#include <algorithm>
#include <iostream>
#include <numeric>
#include <set>
#include <vector>

using namespace std;

bool NextPermutationWithRepetition(vector<int>& perm, int n) {
    int carry = 1;
    auto it = begin(perm);
    while (it != end(perm) && carry) {
        ++*it;
        carry = (*it - 1) / n;
        *it = ((*it - 1) % n) + 1;
        ++it;
    }
    if (carry) {
        if (perm.size() == n) return false;
        perm.push_back(carry);
    }
    return true;
}

int main() {
    vector<int> perm;
    set<vector<int>> uniquePartitions;
    const int n = 10;
    while (NextPermutationWithRepetition(perm, n)) {
        if (accumulate(begin(perm), end(perm), 0) == n)  {
            auto sortedPerm = perm;
            sort(begin(sortedPerm), end(sortedPerm));
            uniquePartitions.insert(sortedPerm);
        }
    }
    cout << uniquePartitions.size() << endl;
}

```
> 2 votes

# Answer
## Javascript

This will take a while to alert something ... but it's worth since it will show you The answer to life the universe and everything!

```
var x = 0, b = document.body.children[0];
var theAnswer = function(){
  b.textContent = ++x;
  if(x == 125774) alert(Math.pow(x, 1/Math.PI)).toFixed(0);
  else setTimeout(theAnswer);
};
theAnswer();

```

Demo
> 2 votes

# Answer
## Assembly (linked by gcc)

On a sufficiently slow computer (CPU speed ~2Hz) this should take around 75 seconds to run:

```
  .globl        main
main:
  movl  $52, %edx
  movl  $0, %edi
l4:
  addl $1, %edi
  cmp %edx, %edi
  jl l4
  call  putchar
  movl  $50, %edx
  movl  $0, %edi
l2:
  addl $1, %edi
  cmp %edx, %edi
  jl l2
  call  putchar
  movl  $10, %edx
  movl  $0, %edi
ln:
  addl $1, %edi
  cmp %edx, %edi
  jl ln
  call  putchar
  ret

```
> 2 votes

# Answer
# Python

Sometimes an answer is only clear at the very end of a calculation, but aspects of it are visible before termination.

And little known is the sequence of inputs Deep Thought was seeded with:

271, 329, 322, 488, 79, 15, 60, 1, 9

Hence:

```
from datetime import datetime
n = datetime.now
o = n().second

def bs(x,n,t,f):
    return ([t]+bs(x-2**(n-1),n-1,t,f) if x>=2**(n-1) else [f]+bs(x,n-1,t,f)) if n>0 else []

u = [271,329,322,488,79,15,60,1,9,'#',' ','',]
for i, g in enumerate(u[:5]):
    while n().second!=(o+(i+u[7])*u[5])%u[6]:
        pass # the dice
    print u[11].join(bs(g,*u[8:11]))

```

Et voila - the answer is provided after 75 seconds.
> 2 votes

# Answer
# Bash and Linux utils:

```
#!/bin/bash

if [ $(uname) == "Linux" ]; then
    : $(arecord -q | head -c 600000)
    man -s4 random | head -n1 | tr -d ' ' | wc -c
else
    echo "Deep Thought didn't run $(uname)"
fi

```

Deep Thought is listening carefully all the way through the calculation.
> 1 votes

# Answer
# Java (227 characters)

Who says that bitwise manipulations are not fun? Or that java can't be confusing?
We loop for 75 seconds and then boom the answer.

```
public class T{public static void main(String[]b){long d=(1<<16^1<<13^1<<10^31<<3);long t=System.currentTimeMillis();long e=t+d;for(;e>System.currentTimeMillis();){}d=d%((((d&~(1<<16))>>7)^(1<<4))^1<<2);System.out.println(d);}}

```

Ungolfed

```
public class T
{
    public static void main(String[] b)
    {
        long d = (1 << 16 ^ 1 << 13 ^ 1 << 10 ^ 31 << 3);
        long t = System.currentTimeMillis();
        long e = t + d;
        for (; e > System.currentTimeMillis();){}
        d = d % ((((d & ~(1 << 16)) >> 7) ^ (1 << 4)) ^ 1 << 2);
        System.out.println(d);
    }
}

```
> 1 votes

# Answer
# PureBasic

In keeping with the fact that different hardware will produce different results, there is no fixed answer for this. I am using an elapsed time function so I know when to stop calculating.

Basically, it will calculate the largest two prime numbers when subtracted is 42

Faster your machine, the larger the primes will be :-)

```
OpenConsole()

sw = ElapsedMilliseconds()
FoundFigure1 = 0
FoundFigure2 = 0

PreviousPrime = 1

For i = 3 To 10000000000 Step 2
  PrimeFound = #True
  For j = 2 To i-1
    If i % j = 0
      PrimeFound = #False
      Break
    EndIf
  Next
  If PrimeFound = #True
    If i - PreviousPrime = 41+1
      FoundFigure1 = PreviousPrime
      FoundFigure2 = i
    EndIf

    PreviousPrime = i
  EndIf

  If ElapsedMilliseconds() - sw > 75000
    Break
  EndIf
Next

Print("Answer: ")
Print(Str(FoundFigure2 - FoundFigure1))
Input()

```
> 0 votes

# Answer
# Ruby

> A program to add (0.56) power n for 75 times. Value of `n is 1`
>
> Where `n=1` should be obtained from any form of `Time diffrence`

```
def solve
  a=0.56
  i=0
  t1=Time.now
  while(i < 75)
        t1 = Time.now
        while((b=Time.now-t1) < 1.0)
        end
        a += 0.56 ** b.to_i
        i += 1
  end
  a.to_i
end

puts solve

```

Using ruby time difference I've verified the execution time which is approx `75.014267762`
> 0 votes

# Answer
***MeatSpace***

Pace off a distance which takes approximately 70/4 seconds for your `servant^H^H^H^Hcomputer` (it could be human, dog, or anything that can pick up numeral tiles) to walk. Place a large numeral `4` and a large numeral `2` there. Place your `computer` to the output point. Start the timer, have it walk to the numeral depot and bring back one number at a time.

I allocated 5 seconds to pick them up and put them down.
> 0 votes

# Answer
**Another C# Example**

```
using System;
using System.Threading;

namespace FourtyTwo
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime then = DateTime.Now;
            Thread.Sleep(42000);
            DateTime now = DateTime.Now;
            TimeSpan t = now - then;
            Console.WriteLine(t.Seconds);
        }
    }
}

```
> 0 votes

# Answer
**PHP**

```
<?php
set_time_limit(80);
ini_set('max_execution_time', 80);
//$start=time();
$count=0;
do{
$rand=rand(0,(75000000/40+2));
$rand=rand(0,$rand);
    if(($rand==42 || $rand==75-42 || $rand== floor(75/42)) && (!rand(0,(4*2)))
      ){
      $count++;
    }
}while($count!=42);
echo $count;
//echo '<br>elapsed time is '.(time()-$start);
?>

```

This is as close as I'm getting tonight. Running it at tecbrat.com, an old IBM NetVista P4 running Ubuntu 10.04, showed 69 seconds and 78 seconds on my last 2 runs.
> 0 votes

# Answer
# JavaScript (Bitwise obfuscation) (not bad for 136 bytes!)

It may be seen as a bit on the cheaty side, but the functions were meticulously thought out, bearing in mind that the 75000ms value would be calculated prior to the functions used to calculate 42. It's quite poetic when you look at it, really :)

`setTimeout("alert($=((_=_=>(_<<-~-~[])|-~[])(_(-~[])))<<-~[])",($=$=>$<<-~-~-~[]|-~[])((_=_=>_<<-~[]|-~[])(_(_(_($($($(-~[]))))))))^-~[])`
> 0 votes

# Answer
I am not too good with this kind of stuff. I'm an app developer but I've never had any training in C and I mostly make apps that grab stuff from servers and make the information look pretty...

I have no idea if this will work and there's a bit of extra code in there because it's in a iphone app and I display a progress hud and an alert view when 42 has been reached:

```
#import "ViewController.h"
#import "MBProgressHUD.h"

@interface ViewController ()

@property (nonatomic, retain) MBProgressHUD * hud;

-(IBAction)answer:(id)sender;

@end

int number;
int initialCounter;

@implementation ViewController
@synthesize hud;

-(IBAction)answer:(id)sender
{
    hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.mode = MBProgressHUDModeIndeterminate;
    hud.labelText = @"Calculating";

    [self calculate];

    number = arc4random();
}

-(void)calculate
{

    int random = arc4random();

    if (number == 42){
        hud.hidden = YES;
        UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"Complete!"
                                                          message:@"The answer is 42."
                                                         delegate:nil
                                                cancelButtonTitle:@"OK"
                                                otherButtonTitles:nil];

        [message show];
    }

    else if(number<42){
        number = number + random;
        dispatch_async(dispatch_get_main_queue(), ^{
             [self calculate];
        });
    }

    else if(number>42){
        number = number - random;
        dispatch_async(dispatch_get_main_queue(), ^{
             [self calculate];
        });
    }
}

@end

```
> 0 votes

---
Tags: popularity-contest
---


title: Print the time in a digital watch

text:
# Question
Title: Print the time in a digital watch
Write a program that prints the current time in a digital watch.

Rules:

* The program must use the local timezone.
* Time is expressed between 00:00 to 23:59 (with only hours and minutes).
* The program must follow the output rules.
* The smallest program wins.

Output (see example):

* Each digit is represented by 4×3 matrix of the characters  (space), `|` (pipe) and `_` (underscore).
* There are two spaces between two digits.
* The `:` (column) is represented with a 1x3 matrix \[,`.`,`.`\] and is separated with the digits on both sides by 2 spaces.
* A newline at the end of the output is tolerated.

List of digits:

```
 __           __    __          __    __    __    __    __
|  |     |    __|   __|  |__|  |__   |__      |  |__|  |__|
|__|     |   |__    __|     |   __|  |__|     |  |__|   __|

```

Example output: (for 21:08)

```
 __             __    __
 __|     |  .  |  |  |__|
|__      |  .  |__|  |__|

```

Go!

EDIT: corrected the spaces for `:` and `1`

# Answer
## PHP, 229 174

```
<?php $s=" |.. w\$km<]_d\x7F}";for($r=3;$r--;print'
')foreach(str_split(date('H:i'))as$c)echo$c>'9'?$s[$r+2]:$s[($d=ord($s[$c+5])>>$r*3)/2&1].($d&1?@__:'  ').$s[$d/4&1],'  ';

```

`$s` is a lookup table that encodes several things. The first two characters are the vertical segments, when off or on. The next three characters are the characters of the colon on each of the three rows. The character codes of the remaining characters encode in binary the state of the segments of each digit.

---

Old version, 229 chars:

```
<?php foreach([strtr(decbin(735),['    ',' __ ']).' ','|  |   | __| __||__||__ |__    ||__||__|.','|__|   ||__  __|   | __||__|   ||__| __|.']as$r){foreach(str_split(date('H:i'))as$c)echo substr($r,ord($c)-48<<2,4).'  ';echo'
';}

```

Useful fact: the ASCII code of `:` is one greater than the ASCII code of `9`, so `0123456789:` are contiguous.
> 4 votes

# Answer
# C# (407 418)

```
namespace System{using z=String;using w=Console;class P{static void Main(){var t=DateTime.Now.ToString("HH:mm");int k=0;z b="17",d=b+23,e=b+3459,f="56",g=e+2680;Action<z,z,z>q=(l,m,r)=>{foreach(var c in t){if(c==':')w.Write(k++>0?".":" ");else{h(c,l);h(c,m,"_");h(c,m,"_");h(c,r);}w.Write("  ");}w.Write("\n");};q(g,"14",g);q(d,b+0,f);q(e,b+4,"2");}static void h(char x,z m,z y="|"){w.Write(m.Contains(""+x)?" ":y);}}}

```

Edit: digits are now 4x3 instead of 3x3. this adds 11 characters.
> 2 votes

# Answer
# Perl - 289 ~~291 302~~

```
use POSIX;$_=$p=(strftime"%H:%02M\n",localtime)=~s;.;$&  ;rg;s;\S;$&eq':'?'a':$&-1&&$&-4?'abba':'aaaa';eg;$_.=$p;s;\d|:;(caacaaacabbcabbccbbccbbacbbaaaaccbbccbbcd=~/.{0,4}/g)[-48+ord$&];eg;$_.=$p;s;\d|:;(cbbcaaaccbbaabbcaaacabbccbbcaaaccbbcabbcd=~/.{0,4}/g)[-48+ord$&];eg;y;a-d; _|.;;print

```
* `strftime"%H:%02M\n",localtime` \- obtain local time in H:MM format
* `s;.;$& ;rg` \- intersperse with double spaces
the time is saved in `$p` for later usage
* `s;\S;$&eq':'?'a':$&==1||$&==4?'aaaa':'abba';eg` \- replace `:` with `a`, 1 and 4 with `aaaa` and other digits with `abba` (later `a` will turn into , `b` \- into `_`, `c` \- `|`, `d` \- `.`)
`$_.=$p` append `$p` (spaced time)
* `s;\d|:;(caacaaacabbcabbccbbccbbacbbaaaaccbbccbbcd=~/.{0,4}/g)[-48+ord$&];eg`

+ `/.{0,4}/g` \- turn the preceding string into an array of 4-char strings
    + `-48+ord$&` \- turn char code into an index, `0` becomes 0, `1` becomes 1, `:` becomes 10
* then append `$p` again and run a similar substitution
* `y;a-d; _|.;` \- replace `abcd` with `_|.`
> 1 votes

# Answer
## Javascript (444, 436, 417, 402)

```
s="\n";q=[];[0x6606,0x66666,0xfee89,0xff877,0x8e78f,0xef8fe].forEach(function(n){for(i=0;i<20;++i)q.push(1&(n>>i))});function f(j){s+=q[j]?'|':' ';s+=q[j+1]?'_':' ';s+=q[j+2]?'_':' ';s+=q[j+3]?'|':' '}function g(n,l){f(4*Math.floor(n/10)+40*l);s+="  ";f(4*(n%10)+40*l)}d=new Date;h=d.getHours();m=d.getMinutes();p="  .  ";g(h,0);s+="     ";g(m,0);s+="\n";g(h,1);s+=p;g(m,1);s+="\n";g(h,2);s+=p;g(m,2);s

```

**How it works :**
Each line of a number is encoded with 4 bits, `0` is a space, `1` is `_` (for 2nd and 3rd character) or `|` (for 1st and last character).
For example, `5` is `0110`, `0001`, `0111`.
The goal is to create an array of 120 booleans (10 numbers * 3 lines * 4 bits) containing all the numbers.
> 1 votes

# Answer
# JavaScript, 192

**Disclaimer:** This one is a JavaScript port of @Boann's answer.

```
for(o='',D=(o+(new Date)).substr(16,5),s=' |.. w$km<]_d\x7F}',r=3;r--;o+='\n')for(i=0;c=D[i++];o+=c>'9'?s[r+2]:(s[(d=(s[+c+5]).charCodeAt(0)>>r*3)/2&1]+(d&1?'__':'  ')+s[d/4&1])+'  ');alert(o)

```

# JavaScript (ES6), 256

```
for(t=[v='',v,v],d=(v+(new Date)).substr(16,5),i=0;c=d[i++];)for(j=3;j--;t[j]+='0    00    00000 +|22  1 1|1|__ |__  2|1|1.+|12 |__  1 2 1|1 2|1 1.'.replace(/\d/g,e=>!+e?' __ ':e^2?'__|':'  |').split('+')[j].substr(+c==c?c*4:40,4)+'  ');alert(t.join('\n'))

```

Ungolfed:

```
for(
  // Create an array containing 3 empty strings.
  t=[v='',v,v],
  // Convert current date to a string and extract the time part.
  d=(v+(new Date)).substr(16,5),
  i=0;
  // Read current time digit.
  // Break the loop when the end of string is reached.
  c=d[i++];
)
  for(
    // Iterate 3 times in order to fill each line.
    j=3; j--;
    // Append current character.
    t[j]+='0    00    00000 +|22  1 1|1|__ |__  2|1|1.+|12 |__  1 2 1|1 2|1 1.'.replace(
      // Unpack the above string.
      // Convert each digit into a substring as follow:
      /\d/g,e=>
        // 0: Convert current digit into a number and negate it.
        //    Must be done because !'0' equals false.
        !+e?' __ '
        // 1: Convert current digit into a number and check if different than 2.
        //    Since we have handled the 0, we just read a 1.
        :e^2?'__|'
        // 2: Last case.
        :'  |'
    // Split the unpacked string in 3 lines.
    ).split('+')[j]
      // Get the 4 characters representing the current digit.
      .substr(
        // Convert current digit into a number and compare it with itseft.
        // The comparison fails if the digit convertion results in NaN (:).
        +c==c?c*4:40,4
      // Add 2 spaces between each digits
      )+'  '
  );

// Join lines.
// Output ASCII time.
console.log(t.join('\n'))

```
> 1 votes

# Answer
### Delphi XE3 (504 495)

Waay to much, but still fun to do :)
Thanks Manatwork for the tip on multidimensional arrays.

```
const asc:array[0..9,0..2]of string=((' __ ','|  |','|__|'),('    ','   |','   |'),(' __ ',' __|','|__ '),(' __ ',' __|',' __|'),('    ','|__|','   |'),(' __ ','|__ ',' __|'),(' __ ','|__ ','|__|'),(' __ ','   |','   |'),(' __ ','|__|','|__|'),(' __ ','|__|',' __|'));var s,l:string;x,i:int16;begin s:=FormatDateTime('hhnn',now);for I:=0to 2do begin l:='';for x:=1to length(s)do begin l:=l+asc[StrToInt(s[x])][i];if x=2 then if i>0then l:=l+'  .  'else l:=l+'     'end;writeln(l);end;readln;end.

```

### With indent

```
const
asc: array[0..9,0..2] of string = (
  (' __ ','|  |','|__|'),
  ('    ','   |','   |'),
  (' __ ',' __|','|__ '),
  (' __ ',' __|',' __|'),
  ('    ','|__|','   |'),
  (' __ ','|__ ',' __|'),
  (' __ ','|__ ','|__|'),
  (' __ ','   |','   |'),
  (' __ ','|__|','|__|'),
  (' __ ','|__|',' __|'));
var
s,l:string;
x,i:int16;
begin
    s:=FormatDateTime('hhnn',now);
    for I := 0 to 2 do
    begin
      l:='';
      for x := 1 to length(s) do
      begin
        l := l + asc[StrToInt(s[x])][i];
        if x=2 then
          if i>0then
            l:=l+'  .  '
          else l:=l+'     '
      end;
      writeln(l);
    end;
    readln
end.

```
> 0 votes

# Answer
**Ruby (239 ~~335~~)**

```
0.upto(2){|h|s=(0..3).map{|i|'041655023022615032031055011012'.gsub(/./){[' __ ','|__|',' __|','|__ ','|  |','   |',' '*4][$&.to_i]}.scan(/.{12}/)[Time.new.strftime('%H%M').split('')[i].to_i][h*4..h*4+3]}*' ';s[9]='  '+' ..'[h]+'  ';puts s}

```

Edit: Shorted with @manatwork syntax

~~The idea is pretty straightforward: make the array with the numbers and substrings (with \[\]) to print each line of the number. I know is far from perfect, I'm new in Ruby and there is probably a way to make a loop in the printing that takes less chars.~~
> 0 votes

---
Tags: code-golf, date, printable-ascii
---


title: Linkin Park Logo

text:
# Question
Title: Linkin Park Logo
Your goal is to draw the Linkin Park Logo in minimum bytes.

Please add a title with the language and the number of bytes in your code.

# Answer
> 1 votes
## PHP

```
<?=l(11,0).l(3,1)."\n".l(10,0).l(3,1)."\n".l(9,0).l(3,1).l(9,0).l(3,1)."\n".l(8,0).l(3,1).l(9,0).l(5,1)."\n".l(7,0).l(3,1).l(9,0).l(3,1).l(1,0).l(3,1)."\n".l(6,0).l(3,1).l(9,0).l(3,1).l(3,0).l(3,1)."\n".l(5,0).l(3,1).l(9,0).l(3,1).l(5,0).l(3,1)."\n".l(4,0).l(3,1).l(9,0).l(3,1).l(7,0).l(3,1)."\n".l(3,0).l(27,1)."\n".l(14,0).l(3,1)."\n".l(13,0).l(3,1)."\n".l(12,0).l(3,1)."\n".l(11,0).l(3,1)."\n";function l($a,$c,$o=''){if($c){$c='=';}else{$c=' ';};for($i=0;$i<$a;$i++){$o.=$c;}return $o;}

```

Ok actually it's longer than write an echo with the logo but It's the first thing which has hit my mind.

# Answer
> 1 votes
# Python, 169 bytes

```
e=' '
z=6*e
x='==='
f=z+x
for i in[e*10+x,e*9+x,e*8+x,e*7+x+f,e*6+x+f+'==',e*5+x+f+e+x,e*4+x+f+e*3+x,e*3+x+f+e*5+x,
e*2+x+f+e*7+x,e+x*8,x*8,e*8+x,e*7+x,e*6+x]:
    print i

```

I'm sure it can (and will be) done in shorter code. Output:

```
          ===
         ===
        ===
       ===      ===
      ===      =====
     ===      === ===
    ===      ===   ===
   ===      ===     ===
  ===      ===       ===
 ========================
========================
        ===
       ===
      ===
[Finished in 0.1s]

```

Try it for yourself, python 2.7.

# Answer
> 1 votes
## Using C++ (Answering my own question) ;)

```
#include<iostream.h>
#include<conio.h>

void linkinparklogo(int posx, int posy) //Linkin Park Logo Starts
{
     highvideo();
     for(int slant=0; slant<=10; slant++) //Slant Part of "L"
     {
     for(int l=1; l<=3; l++)
         {gotoxy(posx+10-slant+l,posy+1+slant); cprintf("=");}
     }
     getch();
     for(int straight=0; straight<=20; straight++) //Lower Part of Horizontal"L"
     {   gotoxy(posx+4+straight,posy+11); cprintf("=");
     }
     getch();
     for(straight=0; straight<=22; straight++) //Upper Part of Horizontal "L"
     {   gotoxy(posx+3+straight,posy+10); cprintf("=");
     }
     getch();
     for(slant=0; slant<=5; slant++) //Right Slant Part of "P"
     {
         for(int p=1; p<=3; p++)
         {gotoxy(posx+21-slant+p,posy+9-slant); cprintf("=");}
     }
     getch();
     gotoxy(posx+17,posy+5); cprintf("=");
     gotoxy(posx+16,posy+5); cprintf("=");
     getch();
     for(slant=0; slant<=9; slant++) //Left Slant Part of "P"
     {
         for(int ps=1; ps<=3; ps++)
         {gotoxy(posx+14-slant+ps,posy+6+slant); cprintf("=");}
     }
} //Linkin Park Logo Created
void main()
{
     clrscr();
     linkinparklogo(0,0);
     getch();
}

```

## Output:

# Answer
> 0 votes
### Delphi

User gives 2 characters which will be used as foreground and background, spaces will work too.

```
uses idglobal;//Required for IIF function
var
i:int8;
s:string;
fg,bg:char; //Foreground + Background
function soc(c:char;Cnt:integer=3):string;
begin
  Result:=StringOfChar(c, cnt)
end;
begin
writeln('Give foreground and background characters');
Readln(fg,bg);
  for I:=0to 16do
  begin
    s:='';
    if i in[0,16]then
    begin
      s:=soc(bg,29);
      WriteLn(s);
      continue
    end;
    if i in[1,2,3,4,5,6,7,8,9,10,11]then
      s:=soc(bg,17-i-3)+iif(i in[10,11],soc(fg,24),soc(fg))
    else if i in[12,13,14,15]then
      s:=soc(bg,(17-i-3)+8)+soc(fg);
    if i in[4,5,6,7,8,9]then
      s:=s+soc(bg,6);
    case i of
      4:s:=s+soc(fg);
      5:s:=s+soc(fg,5);
      6:s:=s+soc(fg)+bg+soc(fg);
      7:s:=s+soc(fg)+soc(bg)+soc(fg);
      8:s:=s+soc(fg)+soc(bg,5)+soc(fg);
      9:s:=s+soc(fg)+soc(bg,7)+soc(fg);
    end;
    s:=s+soc(bg,29-length(s));
    WriteLn(s);
  end;
  readln;
end.

```

### Results

I must add to this that it looks much better in console lol.

```
Input: $/                       Input: (space)=
Output:                         Output:
/////////////////////////////   =============================
/////////////$$$/////////////   =============   =============
////////////$$$//////////////   ============   ==============
///////////$$$///////////////   ===========   ===============
//////////$$$//////$$$///////   ==========   ======   =======
/////////$$$//////$$$$$//////   =========   ======     ======
////////$$$//////$$$/$$$/////   ========   ======   =   =====
///////$$$//////$$$///$$$////   =======   ======   ===   ====
//////$$$//////$$$/////$$$///   ======   ======   =====   ===
/////$$$//////$$$///////$$$//   =====   ======   =======   ==
////$$$$$$$$$$$$$$$$$$$$$$$$/   ====                        =
///$$$$$$$$$$$$$$$$$$$$$$$$//   ===                        ==
//////////$$$////////////////   ==========   ================
/////////$$$/////////////////   =========   =================
////////$$$//////////////////   ========   ==================
///////$$$///////////////////   =======   ===================
/////////////////////////////   =============================

```

# Dont look to long to the first image.

Feels weird :P

### Images:

---
Tags: code-golf, popularity-contest, graphical-output
---


# Question
Title: Match strings whose length is isolated prime
Isolated prime definition from Wikipedia:

> An isolated prime is a prime number p such that neither p − 2 nor p + 2 is prime. In other words, p is not part of a twin prime pair. For example, 23 is an isolated prime since 21 and 25 are both composite.

Consider strings which consists of character `x` repeated n times, where n ≥ 0. You shall write a regex which matches strings whose length is an isolated prime, and rejects strings whose length is not an isolated prime.

Same rule as my previous question Match strings whose length is a fourth power:

* Any (ir)regular expression syntax is allowed, except for arbitrary code execution (to Perl users).
* Your solution should logically1 work correctly for large number. This means that an answer that lists out all the lengths within certain range is disqualified.
* Please also include a short explanation about your approach to the problem (something like this).

1 Some engine implements `*` with an upper limit. This question assumes that `*` doesn't have an upper limit (and the only limit is the length of the input string).

This question on SO might be useful as a starting point. How to determine if a number is a prime with regex?

**Do you know?**

If you can solve this problem, with trivial modification, you can check whether a number is part of a twin prime, since isolated prime has opposite definition of a twin prime.

# Answer
# Perl, 54

```
/^(?!(..+)\1+$)(?=..(?:|(..+)\2+)$)(?=(..(.*))\4\3*$)/

```

I think this is not possible without the Perl look-ahead expression... Firstly, there is no positive regex to match the prime number. You can only match a non-prime by simulating multiplication: `(..+)\1+`. To negate it, I use negative look-ahead: `/^(?!(..+)\1+$)/` matches prime numbers (neglecting the 0, 1 case).

The beauty of the look-ahead is that it is zero-width, i.e. eats no characters. This means you can actually AND those conditions! My regex is composed of 3 look-aheads, corresponding to AND-ing 3 conditions:

* `(?!(..+)\1+$)` \- N (length of the string) is the prime number
* `(?=..(?:|(..+)\2+)$)` \- N-2 is a non-prime - this is a trival modification of the basic non-prime expression - `(..+)\1+`) - just add two characters. The `(?:|...)` is included to also match an empty string (case N=2 should match too).
* `(?=(..(.*))\4\3*$)` \- N+2 is a non-prime - again, trivial modification of the basic non-prime expression - cut two characters out of one repetition.

Test:

```
$ perl -E'($"x$_)=~/^(?!(..+)\1+$)(?=..(?:|(..+)\2+)$)(?=(..(.*))\4\3*$)/&&say for(2..200)'
2
23
37
47
53
67
79
83
89
97
113
127
131
157
163
167
173

```
> 8 votes

---
Tags: regular-expression, programming-puzzle
---


# Question
Title: Shortest way to generate UUID's version 3,4 and 5 in php
I have this function to generate UUID's:

```
function uuid($v=4,$d=null,$s=false)//$v-> version|$data-> data for version 3 and 5|$s-> add salt and pepper
{
    switch($v.($x=''))
    {
        case 3:
            $x=md5($d.($s?md5(microtime(true).uniqid($d,true)):''));break;
        case 4:default:
            $v=4;for($i=0;$i<=30;++$i)$x.=substr('1234567890abcdef',mt_rand(0,15),1);break;
        case 5:
            $x=sha1($d.($s?sha1(microtime(true).uniqid($d,true)):''));break;
    }
    return preg_replace('@^(.{8})(.{4})(.{3})(.{3})(.{12}).*@','$1-$2-'.$v.'$3-'.substr('89ab',rand(0,3),1).'$4-$5',$x);
}

```

This is far from being short!

The idea is to reduce this at maximum!

Criteria to meet:

* It MUST have the format `xxxxxxxx-xxxx-vxxx-yxxx-xxxxxxxxxxxx`, being x a hexadecimal number, y MUST be 89AB and v has to be the version! (**required**)
* Only `v`can be generated randomly for all versions (non-standard, **optional**)
* Version 3 and 5 have to generate ALWAYS the same UUID (except for the rule above, **required**)
* You must provide a method of making the UUID somewhat random (**required**, except for version 4)
* Version 3 uses `md5` to "pack" the data, while version 5 uses `sha1` (leaving a few chars behind, **required**)
* Function name **MUST** be `uuid` (required)

Scoring:

* Lower number of chars wins
* The score is calculated using (number chars)\*0.75
* Readable code is calculated using (number chars)\*0.50
* If one of the required criteria from above isn't met, the multiplier is increased by 0.5 for each criteria, except for the last which is 1.25 (maximum will be (number chars)\*4.00, which means that 1 char is counting as 4)
* Comments don't count but anything else between `function uuid(...){` and `}` counts!

For example:

My function would have a crappy result:

It has 451 chars on linux.

Since it is somewhat hard to read, it is \*0.75.

Since I fulfilled all the criteria, it stays \*0.75.

Result: 451\*0.75 = 338,25!

# Answer
## PHP - 189 × 0.75 = 141.75

```
function uuid($v,$d,$s=''){
  $u=hash($v^3?sha1:md5,$v^4?$d.$s:gmp_strval(gmp_random(4)));
  $u[12]=$v;$u[16]=dechex(+"0x$u[16]"&3|8);
  return substr(preg_replace('/^.{8}|.{4}/','\0-',$u,4),0,36);
}

```

This implementation should be fully compliant with RFC 4122. If `$s` is provided, it is expected to be the byte string represention of the UUID for the applicable namespace. Otherwise, the default ("NULL") namespace is used.

`gmp_random(4)` is used to generate the 128 bits of entropy, which is just about the best PHP has. If the `gmp` module isn't available, you could also use this:

`openssl_random_pseudo_bytes(16))` (requires `openssl` module to be enabled)

or, as a last resort:

`for(;$i++<4)$r.=mt_rand();`

Sample usage:

```
echo uuid(3,'MyCoolNewApp');

```

Sample output:

```
c478211b-224d-30b1-9116-c06048999ce2

```
> 4 votes

---
Tags: code-golf, php
---


title: Computer Generated Olympic Theme Song

text:
# Question
Title: Computer Generated Olympic Theme Song
Try to regenerate the olympic theme song, "Bugler's Dream" using the programming language of your choice. The language/platform used must be able to emit the physical sound. Only playing the main melody (trumpets) is required, but doing more would be great.

You must generate all the tones yourself - you cannot play back a midi/wav or any other sound file.

Here are the sound files for reference:

http://www.jonfullmer.com/music-of-the-month/buglers\_dream/buglers\_dream.mp4 http://www.armory.com/~keeper/1/bugdream.mid

Good luck!

# Answer
# Mathematica 2576

**Code**

```
Sound[{{d, {0., 1.2}}, {a, {0., 1.2}}, {e, {0., 1.2}}, {f, {1.2, 2.2}}, {e, {1.2, 2.2}}, {e, {2.2, 2.4}}, {f, {2.2, 2.4}}, {a, {2.4, 3.}}, {c, {2.4, 3.}}, {b, {3., 3.6}}, {e, {3., 3.6}}, {d, {3.6, 4.2}}, {a, {3.6, 4.2}}, {e, {3.6, 4.2}}, {a, {4.2, 4.8}}, {c, {4.2, 4.8}}, {b, {4.8, 5.4}}, {e, {4.8, 5.4}}, {b, {5.4, 5.8}}, {e, {5.4, 5.8}}, {b, {5.8, 6.}}, {e, {5.8, 6.}}, {b, {6., 6.6}}, {e, {6., 6.6}}, {d, {6.6, 6.9}}, {a, {6.6, 6.9}}, {b, {6.9, 7.2}}, {e, {6.9, 7.2}}, {c, {7.2, 7.5}}, {a, {7.2, 7.5}}, {a, {7.5, 7.6}}, {c, {7.5, 7.6}}, {b, {7.6, 7.8}}, {e, {7.6, 7.8}}, {d, {7.8, 8.1}}, {a, {7.8, 8.1}}, {a, {8.1, 8.4}}, {c, {8.1, 8.4}}, {b, {8.4, 9.6}}, {e, {8.4, 9.6}}, {d, {9.6, 10.8}}, {a, {9.6, 10.8}}, {e, {9.6, 10.8}}, {f, {10.8, 11.8}}, {e, {10.8, 11.8}}, {e, {11.8, 12.}}, {f, {11.8, 12.}}, {a, {12., 12.6}}, {c, {12., 12.6}}, {b, {12.6, 13.2}}, {e, {12.6, 13.2}}, {d, {13.2, 13.8}}, {a, {13.2, 13.8}}, {e, {13.2, 13.8}}, {a, {13.8, 14.4}}, {c, {13.8, 14.4}}, {b, {14.4, 15.}}, {e, {14.4, 15.}}, {b, {15., 15.4}}, {e, {15., 15.4}}, {b, {15.4, 15.6}}, {e, {15.4, 15.6}}, {b, {15.6, 16.2}}, {e, {15.6, 16.2}}, {d, {16.2, 16.5}}, {a, {16.2, 16.5}}, {b, {16.5, 16.8}}, {e, {16.5, 16.8}}, {c, {16.8, 17.1}}, {a, {16.8, 17.1}}, {a, {17.1, 17.2}}, {c, {17.1, 17.2}}, {b, {17.2, 17.4}}, {e, {17.2, 17.4}}, {d, {17.4, 17.7}}, {a, {17.4, 17.7}}, {a, {17.7, 18.}}, {c, {17.7, 18.}}, {e, {18., 19.2}}, {a, {18., 19.2}}, {c, {18., 19.2}}, {d, {19.2, 20.4}}, {a, {19.2, 20.4}}, {e, {19.2, 20.4}}, {f, {20.4, 21.4}}, {e, {20.4, 21.4}}, {e, {21.4, 21.6}}, {f, {21.4, 21.6}}, {a, {21.6, 22.2}}, {c, {21.6, 22.2}}, {b, {22.2, 22.8}}, {e, {22.2, 22.8}}, {d, {22.8, 23.4}}, {a, {22.8, 23.4}}, {e, {22.8, 23.4}}, {a, {23.4, 24.}}, {c, {23.4, 24.}}, {b, {24., 24.6}}, {e, {24., 24.6}}, {b, {24.6, 25.1}}, {e, {24.6, 25.1}}, {b, {25.1, 25.2}}, {e, {25.1, 25.2}}, {b, {25.2, 25.8}}, {e, {25.2, 25.8}}, {d, {25.8, 26.1}}, {a, {25.8, 26.1}}, {b, {26.1, 26.4}}, {e, {26.1, 26.4}}, {c, {26.4, 26.7}}, {a, {26.4, 26.7}}, {a, {26.7, 26.9}}, {c, {26.7, 26.9}}, {b, {26.9, 27.}}, {e, {26.9, 27.}}, {d, {27., 27.3}}, {a, {27., 27.3}}, {a, {27.3, 27.6}}, {c, {27.3, 27.6}}, {b, {27.6, 28.8}}, {e, {27.6, 28.8}}, {d, {28.8, 30.}}, {a, {28.8, 30.}}, {e, {28.8, 30.}}, {f, {30., 31.}}, {e, {30., 31.}}, {e, {31., 31.2}}, {f, {31., 31.2}}, {a, {31.2, 31.8}}, {c, {31.2, 31.8}}, {b, {31.8, 32.4}}, {e, {31.8, 32.4}}, {d, {32.4, 33.}}, {a, {32.4, 33.}}, {e, {32.4, 33.}}, {a, {33., 33.6}}, {c, {33., 33.6}}, {b, {33.6, 34.2}}, {e, {33.6, 34.2}}, {b, {34.2, 34.7}}, {e, {34.2, 34.7}}, {b, {34.7, 34.8}}, {e, {34.7, 34.8}}, {b, {34.8, 35.4}}, {e, {34.8, 35.4}}, {d, {35.4, 35.7}}, {a, {35.4, 35.7}}, {b, {35.7, 36.}}, {e, {35.7, 36.}}, {c, {36., 36.3}}, {a, {36., 36.3}}, {a, {36.3, 36.4}}, {c, {36.3, 36.4}},{b, {36.4, 36.6}}, {e, {36.4, 36.6}}, {d, {36.6, 36.9}}, {a, {36.6, 36.9}}, {a, {36.9, 37.2}}, {c, {36.9, 37.2}}, {e, {37.2, 38.4}}, {a, {37.2, 38.4}}, {c, {37.2, 38.4}}}
/. {n_, t_} :> SoundNote[n, Round[t, .1], "Trumpet", SoundVolume -> 0.7]]
/. {a -> "C#5", b -> "D#5", c -> "F4", d -> "F5", e -> "G#4", f -> "G#5"}

```

---

## Output

Bugler's Dream, Trumpet track.

---

## Saving to file

```
Export["bugler.mid", bugler]

```

> bugler.mid
> 1 votes

---
Tags: popularity-contest, music
---


title: number of answers and comments

text:
# Question
Title: number of answers and comments
Write a software that prints on stdout the number of answers and the number of comments(visible and collapsed of question and answers) of this question/page.

Your script must run with this page closed when it starts.

Expected example output:

```
A12C40

```

Where A stands for Answers and C for Comments.

# Answer
> 18 votes
# Perl, 91 96 92 chars

```
$_=`curl -sL qr.net/_9`;s/<[^>]+nt="(.+)/$c+=$1/ge;say"A",s/<td.*"ans//g,C,$c+s/<tr.*"com//g

```

---

Some stuff just to break solutions of others ha ha ha :-P

show **93** more comments

href

nt="99" (ha ha crash @Fez Vrasta)

a ,show **99**show **99** ha ha

href href href ha ha haha :-D

jeeez, just broke my own answer! I discovered that one of the above tricks, which I thought does nothing, will start working *after* this answer is not edited for some time! So your solutions will work only for some time. That's why you had seen +1 more answer in your solutions.. It's a timed bomb! My answer is already prone to it :-) Aaah, found a way how to launch it NOW...

# Answer
> 9 votes
### XQuery, 169, 160, 165

```
let$d:=html:parse(fetch:binary('http://qr.net/1_'))return"A"||count($d//*[@class="answer"])||"C"||count($d//*[@class="comment"])+sum($d//*[@class="comments-link"]/b)

```

More readable (with spaces):

```
let $d:= html:parse(fetch:binary('http://qr.net/1_'))
return "A" || count($d//*[@class="answer"]) || "C" || count($d//*[@class="comment"]) + sum($d//*[@class="comments-link"]/b)

```

BaseX was used as XQuery processor.

# Answer
> 7 votes
# Python 3, 180

```
import lxml.html as h
s=h.parse('http://qr.net/1_').find('body').cssselect
print('A',len(s('.answer')),'C',len(s('.comment'))+sum(int(e.text)for e in s('.comments-link b')),sep='')

```

I'm assuming that this question won't have multiple pages of answers.

# Answer
> 6 votes
## BASH + AWK ~~163~~, ~~144~~, ~~138~~, ~~111~~, ~~110~~, ~~114~~, ~~131~~, ~~132~~, 105

```
curl -sL http://qr.net/_9|awk -F'[<>]' '/^[\t]*>s/{c+=$4}/<tr.*"c/{++c}/<t.*"a/{++a}END{print "A"a"C"c}'

```

Which is the same as this, but without redirecting to a file:

```
curl -sL http://qr.net/_9>f
awk -F'[<>]' '/^[\t]*>s/{c+=$4}/<tr.*"c/{++c}/<t.*"a/{++a}END{print "A"a"C"c}' f

```

### Current output

```
A16C76

```

### Explanation

curl

Transfer a URL.

* `-s` in `curl` is for silent. And `-L` to follow redirects.

awk

To parse the file. As some answers had some code to break other answers, the parsing has been changed so that it parses from the beginning of the line `(^`) to make sure it is not broken.

* `-F'[<>]'` set field separators as `<` or `>`. This way the text can be parsed properly for the "show XXX more comments".
* `/^[\t]*>show <b>/{c+=$4}` on lines containing "spaces....\>show", get the 4th field (based on `<`, `>` separators) and add the value to the comments counter.
* `/^[ ]*<tr.*s="comm/{++c}` on lines containing "spaces...
* `/^<td.*rcell">/{++a}` on lines containing "", increment the counter of answers.
* `END{print "A"a"C"c}` print the output.

# Answer
> 5 votes
### R, 326

```
library(XML);b=htmlParse("https://codegolf.stackexchange.com/questions/20277");z=xpathApply;x=do.call(sum,sapply(z(b,"//tbody",xmlAttrs),function(x)as.integer(x[[1]])))+length(z(b,"//tr[@class='comment']",xmlValue));y=gsub("[^0-9]","",z(b,"//div[@class='subheader answers-subheader']/h2",xmlValue)[[1]]);cat("A",y,"C",x,sep="")

```

With indentation and explanations:

```
library(XML)
b=htmlParse("https://codegolf.stackexchange.com/questions/20277")
z=xpathApply
x=do.call(sum,sapply(z(b,"//tbody",xmlAttrs),  #Take the first attribute of tag tbody
                     function(x)as.integer(x[[1]]))) #And sum them (=nb of hidden comments
  +length(z(b,"//tr[@class='comment']",xmlValue)) #+nb of visible comments
y=gsub("[^0-9]","", #This is more straightforward as the number of answers is given on front page.
        z(b,"//div[@class='subheader answers-subheader']/h2",xmlValue)[[1]])
cat("A",y,"C",x,sep="")

```

Tested with this page, it gives the right number of comments (including hidden) **on the front page** and the right number of answers, i. e. `A23C63`.

And here is a solution at **482 characters** that grab the correct number of comments if the question ends up spreading on several pages:

```
library(XML);h=htmlParse;z=xpathApply;v=xmlValue;a=xmlAttrs;s=sapply;c="http://codegolf.stackexchange.com";f=function(b,i){do.call(sum,s(z(b,"//tbody",a)[i],function(x)as.integer(x[[1]])))+length(z(b,"//tr[@class='comment']",v))};b=h(paste0(c,"/questions/20277"));x=f(b);u=unique(s(z(b,"//div[@class='pager-answers']/a",a),`[`,1));if(length(u))x=x+sum(s(u,function(x)f(h(paste0(c,x)),-1)));y=gsub("[^0-9]","",z(b,"//div[@id='answers-header']/div/h2",v)[[1]]);cat("A",y,"C",x,sep="")

```

Indented:

```
library(XML)
h=htmlParse
z=xpathApply
v=xmlValue
a=xmlAttrs
s=sapply
c="http://codegolf.stackexchange.com"
f=function(b,i){do.call(sum,s(z(b,"//tbody",a)[i],function(x)as.integer(x[[1]])))+length(z(b,"//tr[@class='comment']",v))}
b=h(paste0(c,"/questions/20277"))
x=f(b)
u=unique(s(z(b,"//div[@class='pager-answers']/a",a),`[`,1)) #Grab all URLS of pages
if(length(u))x=x+sum(s(u,function(x)f(h(paste0(c,x)),-1))) #Apply comment computation of all URLs
y=gsub("[^0-9]","",z(b,"//div[@id='answers-header']/div/h2",v)[[1]])
cat("A",y,"C",x,sep="")

```

Tried on this question and outputted: `A125C499`.

# Answer
> 5 votes
## PHP which actually works (302 chars)

Unlike all of the other answers so far, this returns the correct answer even when the question spills onto more than one page.

```
<?function g($a,$b,$i){return json_decode(gzinflate(substr(file_get_contents("http://api.stackexchange.com/2.1/$a/$i/$b?site=codegolf"),10,-8)))->items;}$i=array(20277);foreach(g("questions","answers",20277)as$x)$i[]=$x->answer_id;echo"A".(count($i)-1)."C".count(g("posts","comments",implode(";",$i)));

```

# Answer
> 5 votes
## Ruby 175 (counts across pages, using the API instead of the DOM)

```
require'open-uri';require'json'
q=JSON.parse(open("http://qr.net/oyJn").read)["items"][0];a=q["answers"]
puts"A#{a.count}C#{[q,*a].reduce(0){|m,o|m+o["comments"].to_a.count}}"

```

That's 242 without the shortened url:

```
require'open-uri';require'json'
q=JSON.parse(open("http://api.stackexchange.com/2.1/questions/20277?site=codegolf&filter=!azbR89z2Zw*dg.").read)["items"][0]
a=q["answers"]
puts"A#{a.count}C#{[q,*a].reduce(0){|m,o|m+o["comments"].to_a.count}}"

```

Previous 291 answer:

```
require'open-uri';require'json'
def g(o,l,f);JSON.parse(open("http://api.stackexchange.com/2.1/#{o}/#{l}/#{f}?site=codegolf").read)["items"];end
q=20277
p=g("questions",q,"answers").inject([q]){|m,o|m<<o["answer_id"]}
puts"A#{p.count-1}C#{p.map{|i|g("posts",i,"comments").count}.reduce(:+)}"

```

Credits to Peter Tailor for the idea of using the API, and Charles for pointing towards a better API.

# Answer
> 5 votes
## HTML, 37

*Sorry, Blatant rule abuse follows!*

```
<script src=http://q0x.eu/1></script>

```

### Explanation

`q0x.eu/1` redirects to: http://api.stackexchange.com/2.1/questions/20277/comments?site=codegolf&callback=...

where the callback is:

```
(function(d){
    c=d.items.length;
    document.write('<script src="http://q0x.eu/2"></script>')
})

```

`q0x.eu/2` redirects to http://api.stackexchange.com/2.1/questions/20277/answers?site=codegolf&callback=...

```
(function(d){
    a=0;
    g=[];
    d.items.map(function(f){
        a++;
        g.push(f.answer_id)
    });
    document.write('<script src="http://q0x.eu/3?n='+g.pop()+'"></script>')
})

```

and `q0x.eu/3?n=...` redirects to http://api.stackexchange.com/2.1/answers/.../comments?site=codegolf&callback=...

```
(function(d){
    c+=d.items.length;
    g.length ? document.write('<script src="http://q0x.eu/3?n='+g.pop()+'"></script>') : alert('A'+a+'C'+c)
})

```

I was originally trying to do it legitimately and might still have a go, but this was fun nevertheless!

# Answer
> 4 votes
## Python with stackpy 160

**Implementation**

```
s=__import__("stackpy").Site("codegolf");q=s.questions(20277);a=q.answers
print"A%dC%d"%(len(a),sum(len(s.answers(e.id()).comments)for e in a)+len(q.comments))

```

**Output**

```
A13C60

```

**Note**

Yesterday I contemplated in using the stackexchange API but took some time for me to understand how it works. Today, I saw there were couple of answers on the same theme. To make my answer a bit different, I though of using an external library.

Also realize that other answers which relies on parsing for patterns like

are likely to break at anytime soon, so a more definite answer is to rely on a robust method like this one.

# Answer
> 3 votes
## PHP: ~~184~~ 172

```
<?$h=file_get_contents('http://qr.net/_9');preg_match_all('/<t.*nt="([0-9]*)/',$h,$c);echo 'A'.substr_count($h,'rcell">').'C'.(array_sum($c[1])+substr_count($h,'mment">'));

```

Explanation:

```
<? // short open tag
  $h = file_get_contents('http://qr.net/_9'); // store in $h the content of the shortened url of the page
  preg_match_all('/<t.*nt="([0-9]*)/', $h, $c); // find each "show/hide X more comments" and store the numbers in $c
  echo
    'A' // output A
    .substr_count($h,'rcell">') // output the count of the occurrences of 'rcell">' (short for '"answercell">')
    .'C' // output C
    .(
      array_sum( $c[1] ) // output the sum of the collapsed comments found before
      +
      substr_count( $h, 'mment">') // output the count of the occurrences of 'mment">' (short for '"comment">')
    );

```

*For the first time PHP beats other languages in golf-scripts :')*

---

**Some extra markup to this topic to avoid regex "cheats":**

show **9999** more comments

# Answer
> 3 votes
Cannot believe that nobody has came up with it until now! Most direct solution to use :-)

# jQuery, 116 101 chars (off competition)

Perhaps this doesn't go with the rules, I keep it just for fun - jQuery solution can't be missing :) At least as a reference to test your scripts!!! ;-)

Try running from the FireBug console:

```
$('.comments-link').click();
setTimeout("alert('A'+$('.answer').length+'C'+$('.comment').length)",999)

```

If you have slow connection, increase the timeout :-) Thanks @Fez Vrasta for the great idea of clicking the "show more" links!

---

Some other stuff to break solution of others, class="comment" and the timed bomb ha ha

# Answer
> 3 votes
## R 239

```
library(XML);F=function(x,y,f=length,z='')sum(as.double(xpathSApply(htmlParse('http://qr.net/1_'),sprintf('//%s[@class="%s"]%s',x,y,z),f)));cat("A",F("div","answer"),"C",F("a","comments-link ",xmlValue,"//b")+F("td","comment-text"),sep="")

```

After I posted my answer, the output is:

```
A13C60

```

# Answer
> 2 votes
## Node, 403

```
r=require;m='comments'
r('http').get("http://api.stackexchange.com/2.1/questions/20277?site=codegolf&filter=!azbR89z2Zw*dg.").on('response',function(p){p.pipe(r('zlib').createGunzip(o="")).on('readable',function(){o+=this.read()}).on('end',function(){d=JSON.parse(o).items[0]
r('util').print("A",d.answer_count,"C",(d[m].length+d.answers.reduce(function(p,c){return p+(c[m]?c[m].length:0)},0)))})})

```

Only hits the API once... can likely be shortened, but I'm new to Node.

# Answer
> 2 votes
## 153 151 147, C# & CsQuery

C# With CsQuery:

```
    var d = CsQuery.CQ.CreateFromUrl("http://qr.net/1_");
    Console.Write("A" + d[".answer"].Count() + "C" + d[".comment"].Count());

```

Full program:

```
class P{static void Main(){var d =CsQuery.CQ.CreateFromUrl("http://qr.net/1_");Console.Write("A"+d[".answer"].Count()+"C"+d[".comment"].Count());}}

```

### 118 C# & CsQuery in LINQPad or in Roslyn

If running through LINQPad is allowed then:

```
var d =CsQuery.CQ.CreateFromUrl("http://qr.net/1_");Console.Write("A"+d[".answer"].Count()+"C"+d[".comment"].Count());

```

Produces:

> A14C48

Some more fun.

### F# with CsQuery, 143:

```
[<EntryPoint>]
let main x=
 let d=CsQuery.CQ.CreateFromUrl("http://qr.net/1_")
 printfn "A%dC%d" d.[".answer"].Length d.[".comment"].Length
 0

```

---
Tags: code-golf, internet
---


title: tree from string

text:
# Question
Title: tree from string
A string like this one:

"a, 4.25, ((true, 5), 3, (false, false, false)), abc"

Describes a tree with 13 nodes, 9 of which are leaf nodes. In C# the leaf nodes in this example would be of types `string`, `float` and `bool`, this differs between languages and depending on your implementation. The important structure forming symbols here are `,` `(` and `)` with spaces being ignored.

See the diagram in David Carrahers answer for a tree of the desired shape.

```
var a = new cake(4, "abc")

```

The above contains 8 symbols, I'm counting bracket and `"` pairs as a half and things like `.` as 1.

The goal is to write code with the fewest symbols which given a string like the one shown above, creates the tree it represents.

For example in the form of arrays inside each other, or interconnecting node objects.

60 extra points if you don't sort of cheat by adjusting the input string slightly then executing it.

I won't count the symbols that define the input string.

```
daniero
100 - (10 symbols)
+40 points for understanding numbers, strings, bools
    and any other basic types the language understands.
+20 points for using a reasonably general language.
150 total points

fejesjoco
100 - (est 37 symbols)
+20 points for it understanding numbers as well as strings.
+40 points for using a reasonably general language.
97 total points

tomas
100 - (10 symbols)
90 total points

David Carraher
100 - (est 19 symbols)
81 total points

```

# Answer
> 3 votes
**JavaScript**

```
s="a, 4.25, ((true, 5), 3, (false, false, false)), abc"
eval(("["+s+"]").replace(/\(/g,"[").replace(/\)/g,"]").replace(/([a-z]+)/g,"'$1'"))

```

The exact syntax, input and output format weren't exactly defined... I replace every a-z character to become a string, even true/false, which could be booleans, but there's no indication if there should be a distinction. I don't know if other characters are allowed or not (ő, $, \uFA20, ...), so my code doesn't care about that either.

# Answer
> 2 votes
# Mathematica

`StringReplace` replaces all instances of `(` with `List[`; instances of `)` with `]`.

The FullForm of `List` must be used (instead of `{…}`); otherwise `ToExpression` will not parse the string correctly.

```
f@t_:=ToExpression["List["<>StringReplace[t,{"("->"List[",")"->"]"}]<>"]"]

```

---

**Example**

```
f["a, 4.25, ((true, 5), 3, (false, false, false)), abc"]

```

> {a, 4.25, {{true, 5}, 3, {false, false, false}}, abc}

---

**Verification**

`TreeForm[<expression>]` displays the Mathematica expression as a tree.

```
TreeForm[f["a, 4.25, ((true, 5), 3, (false, false, false)), abc"]]

```

# Answer
> 2 votes
# R, 36 chars

```
plot(read.tree(,paste0("(",a,");")))

```

package ape must be loaded.

### Output:

# Answer
> 2 votes
# Common Lisp

I *think* it would count as something around 11 symbols?

Wrap parentheses around the string, remove the commas and evaluate it, and you have a LISP list.

```
(read-from-string (remove #\, (concatenate 'string "(" s ")" )))

```

`s` is the string.

For the given example it returns a list `(A 4.25 ((TRUE 5) 3 (FALSE FALSE FALSE)) ABC)`

---
Tags: atomic-code-golf
---


title: Tennis scores meets Code Golf

text:
# Question
Title: Tennis scores meets Code Golf
In light of the 2014 Australian Open in Melbourne, and the win by Stanislas Wawrinka against Novak Djokovic, I propose the following code golf challenge!

Wawrinka and Djokovic are at it again for the basis of this CGC. Your challenge is to take a string consisting of 1's and 2's and determine the tennis scores based on the tennis scoring system. A "1" indicates that Wawrinka has scored a point, whereas a "2" indicates that Djokovic has scored a point.

For the sake of example: `1211222122111122111` will generate a two-line output:

```
Wawrinka 1 - 40
Djokovic 1 - 30

```

The longer the string, the further into the game the score is.

Rules:

* Shortest code wins, pure and simple.
* The scores when displayed must be right aligned and also column aligned; e.g.
* Sample alignment of output:

```
Wawrinka 7 5 3 -  0
Djokovic 6 7 4 - 15

```
* If a game is in progress, the score must be displayed after the set scores. Game scores must follow set scores with a space-dash-space separator. If this happens to be the first game, a 0-0 set score must be displayed.

```
Wawrinka 0 -  0
Djokovic 0 - 15

```
* A game will go in order of 0, 15, 30, 40, and game point. If a game reaches 40-40, a deuce is declared, and the score must display the deuce on the player row scoring the point:

```
Wawrinka 7 5 3 - 40
Djokovic 6 7 4 - 40 Deuce

```
* If a deuce is reached, the next point will be an advantage to the player scoring the point:

```
Wawrinka 7 5 3 - Ad
Djokovic 6 7 4 - 40

```

The point after that, if scored by the advantaged player, wins the game, else the game goes back to deuce.
* If more than one deuce is scored in between advantage points, the number of the deuce will be indicated by a number in parentheses:

```
Wawrinka 7 5 3 - 40
Djokovic 6 7 4 - 40 Deuce (2)

```
* A set is won if a player reaches 6 games or more and with a two game margin in lead, e.g. 7-5, 6-4... 9-7 (In the case of last night's fifth set)
* Consecutive sets must be separated with a space.
* There are tie breaks in the Australian Open, therefore if a 6-6 set is reached, a tie-break is established by the first player reaching seven points with a two point margin lead. Display of tie breaks are shown within square brackets as follows:

```
Wawrinka 7 6 [6]
Djokovic 6 6 [4]

```

The winner of the tie-break is said to have won the previous set 7-6.
* If the fifth set reaches 6-6, play is continued without tie-break until a two game margin is reached with one player, that player being the winner of that set. There are NO tie-breaks in the fifth set.
* If a player has won three sets, a third line will be displayed saying `Wawrinka wins` or `Djokovic wins` depending on who has won and the code then terminates.

```
Wawrinka 2 6 6 3 9
Djokovic 6 4 2 6 7
Wawrinka wins

```
* If the string ends such that the last point has won a game, set or match, the game score is not displayed...

```
Wawrinka 7 5 3
Djokovic 6 7 4

```
* If the string goes beyond a match being won, the rest of the string is ignored, the score displayed and the winner declared.

# Answer
## Perl - 424 bytes

```
*1=a;*2=b;@1=(Wawrinka,0);@2=(Djokovic,0);
$$_++>${$o=S^$_}&&$$_>3and$1=$2=0,
$w=$w[$_]+=($$_[$.]++>$$o[$.]||(($t=$$_[$.]==$$o[$.])&&!$%&&$.<5))&&
$$_[$.]>5+$%&&!($1[$.]=$2[$.+=!$%]=$w<2&&0,$$_[$.-1]+=$%,$%=$t)for<>=~/./g;
@s=(' 0',15,30,(40)x($e=$$o<3||$$o-2),Ad);
$%and$_="[$_]"for@1[-1],@2[-1];$d[$&]=$1>2&&$1==$2&&' Deuce'.($1>3&&" ($e)");
print"@1",$w<3&&" - $s[$1]$d[1]","\n@2",$w<3&&" - $s[$2]$d[2]",$w>2&&"\n${$&}[0] wins"

```

*Newlines have been added for ~~readability~~ horizontal sanity.*

I believe this to be a complete solution, according to the scoring of the Australian Open:

* Best of five sets (a.k.a. race to three).
* Sets 1-4 are played as a 6-6 tie-breaker.
* Set 5 is played as an advantage set.

### Test Cases

---

```
1211222122111122111

```

#

```
Wawrinka 1 - 40
Djokovic 1 - 30

```

---

```
12112221221111221112

```

#

```
Wawrinka 1 - 40
Djokovic 1 - 40 Deuce

```

---

```
121122212211112211122

```

#

```
Wawrinka 1 - 40
Djokovic 1 - Ad

```

---

```
1211222122111122111221

```

#

```
Wawrinka 1 - 40 Deuce (2)
Djokovic 1 - 40

```

---

```
22111111212122221122111212212112121221212211221121222222112112221121121122221122221211111222121222122211212122111212112211222121211212211212211122121211112222222212211121122

```

#

```
Wawrinka 6 [5] - 30
Djokovic 6 [6] - 40

```

---

```
221111112121222211221112122121121212212122112211212222221121122211211211222211222212111112221212221222112121221112121122112221212112122112122111221212111122222222122111211222

```

#

```
Wawrinka 6 0 -  0
Djokovic 7 0 -  0

```

---

```
1122222211121211121211111121111211221222212212112221211222211222112212211121122122212122212222122212212211221111121222111221211111211112222212122122112111212121221221212211112122212211111111112111212222221112212121122212121111122111222222111212221121221111222122122222111212111111221121122111122122111222222121122221112221221122221121211212111122111121212112112121222122

```

#

```
Wawrinka 5 4 6 6 5 - 15
Djokovic 7 6 4 4 6 - 40

```

---

```
11222222111212111212111111211112112212222122121122212112222112221122122111211221222121222122221222122122112211111212221112212111112111122222121221221121112121212212212122111121222122111111111121112122222211122121211222121211111221112222221112122211212211112221221222221112121111112211211221111221221112222221211222211122212211222211212112121111221111212121121121212221222

```

#

```
Wawrinka 5 4 6 6 5
Djokovic 7 6 4 4 7
Djokovic wins

```

---

```
222221112112212212222111222211111111121111121112211221221211212121122211222112111112122122212222211112122212221111121111121211212112112112221221121122121121112221221222122122211222212121212112112111221221121112222212122222221111112222222221221122211221121111221121222222111111122221122111211121222112112122212122221121222221222121212111121221221112111212212222122212212212112111112112112121112221111221221221121222122211221212211111111222222121221112221212

```

#

```
Wawrinka 6 7 6 4 7 - 40
Djokovic 3 5 7 6 8 - Ad

```

---

```
2222211121122122122221112222111111111211111211122112212212112121211222112221121111121221222122222111121222122211111211111212112121121121122212211211221211211122212212221221222112222121212121121121112212211211122222121222222211111122222222212211222112211211112211212222221111111222211221112111212221121121222121222211212222212221212121111212212211121112122122221222122122121121111121121121211122211112212212211212221222112212122111111112222221212211122212122

```

#

```
Wawrinka 6 7 6 4 7
Djokovic 3 5 7 6 9
Djokovic wins

```

All intermediate scores for the last test case can be seen here: http://codepad.org/FzDIcf0W
> 5 votes

# Answer
**ECMAScript 6 - 635 Characters**

```
f=(p,q,C)=>{B='';T=' ';L=(x)=>(B+x).length;M=(x,y)=>x>y?x:y;E=(a)=>{var x=L(a[0]),y=L(a[1]),q=M(x,y);for(;x++<q;)a[0]=T+a[0];for(;y++<q;)a[1]=T+a[1]};E(a=[p,q]);g=[m=n=o=i=t=z=0,0];s=[0,0];S=[0,0];w=2;O=(i)=>a[i]+(n+o>0?T+s[i]:B)+(o>0?(t?' ['+g[i]+']':' - '+[' 0',15,30,40,'Ad'][g[i]]+(z>0&&g[0]+g[1]==6&&i==w?' Deuce'+(z>1?' ('+z+')':B):B)):B)+'\n';while(W=C[i++]){w=--W;++o;if((d=++g[w])>M(t?6:3,(e=g[l=1-w])+1)){g=[o=z=0,0];j=++s[w];k=s[l];t=++n>11;if(j>M(5,m>4||k<6?k+1:6)){E(s);a[0]+=T+s[0];a[1]+=T+s[1];s=[n=0,0];++m;if(++S[w]>2)break}}else if(!t&&d+e>7){--g[w];--g[l];++z}}E(s);E(g);return O(0)+O(1)+(S[w]>2?(w?q:p)+' wins':B)}

```

**With comments:**

```
// Function f takes arguments:
//   p - Player 1 name
//   q - Player 2 name
//   C - String of 1s and 2s representing points won by players.
f=(p,q,C)=>{
    /* Empty String          */ B='';
    /* Space                 */ T=' ';
    /* String Length Func.   */ L=(x)=>(B+x).length;
    /* Max Function          */ M=(x,y)=>x>y?x:y;
    /* Equalize Length Func. */ E=(a)=>{var x=L(a[0]),y=L(a[1]),q=M(x,y);for(;x++<q;)a[0]=T+a[0];for(;y++<q;)a[1]=T+a[1]};
    /* No. of sets           */ m=0;
    /* No. games in set      */ n=0;
    /* No. points in game    */ o=0;
    /* Input Index           */ i=0;
    /* Output String         */ E(a=[p,q]);
    /* Current Game's Points */ g=[0,0];
    /* Current Set's Games   */ s=[0,0];
    /* No. sets won          */ S=[0,0];
    /* Is a tiebreaker       */ t=0;
    /* No. of deuces         */ z=0;
    /* Current match result  */ w=2;
    /* Output Fnctn  */ O=(i)=>a[i]+(n+o>0?T+s[i]:B)+(o>0?(t?' ['+g[i]+']':' - '+[' 0',15,30,40,'Ad'][g[i]]+(z>0&&g[0]+g[1]==6&&i==w?' Deuce'+(z>1?' ('+z+')':B):B)):B)+'\n';
    while(W=C[i++]){
        w=--W;
        // w - index of winner of current game
        // l - index of loser of current game
        // d - winner of current point's game score
        // e - loser of current point's game score
        ++o;
        if((d=++g[w])>M(t?6:3,(e=g[l=1-w])+1)){
            g=[0,0];  // Reset the game score.
            o=z=0;
            j=++s[w]; // j = Increment the winner's set score
            k=s[l];   // k = Loser's set score
            t=++n>11; // Is a tiebreak?
            if(j>M(5,m>4||k<6?k+1:6)){
                E(s);
                a[0]+=T+s[0]; // Add to output
                a[1]+=T+s[1]; // Add to output
                s=[n=0,0];  // Reset current set's no. of games & no. of deuces.
                ++m;        // Increment no. of sets.
                if(++S[w]>2)break;     // Increment winners no. sets won and check if match won.
            }
        }
        else if(!t&&d+e>7){--g[w];--g[l];++z}// Check if deuces increased.
    }
    E(s); // Format sets strings.
    E(g); // Format games strings.
    return O(0)+O(1)+(S[w]>2?(w?q:p)+' wins':B);
}

```

**Testing**

```
var tests=[
            '',
            '1',
            '2',
            '11',
            '222',
            '1111',
            '2222',
            '1112221',
            '11122212',
            '121212121',
            '1212121212',
            '1211222122111122111',
            '12112221221111221112',
            '121122212211112211122',
            '1211222122111122111221',
            '1111222211112222111122221111222211112222111122221212121212121212121',
            '11111111111111111111111111111111111111111111111111111111111111111111111',
            '111111111111111111111111111111111111111111111111111111111111111111111111',
            '1111111111111111111111111111111111111111111111111111111111111111111111111'
        ];
for(var ex in tests) console.log('Test '+ex+'\n'+tests[ex]+'\n'+f('Wawrinka','Djokovic',tests[ex]));

```

**Test Outputs**

```
Test 0

Wawrinka
Djokovic

Test 1
1
Wawrinka 0 - 15
Djokovic 0 -  0

Test 2
2
Wawrinka 0 -  0
Djokovic 0 - 15

Test 3
11
Wawrinka 0 - 30
Djokovic 0 -  0

Test 4
222
Wawrinka 0 -  0
Djokovic 0 - 40

Test 5
1111
Wawrinka 1
Djokovic 0

Test 6
2222
Wawrinka 0
Djokovic 1

Test 7
1112221
Wawrinka 0 - Ad
Djokovic 0 - 40

Test 8
11122212
Wawrinka 0 - 40
Djokovic 0 - 40 Deuce

Test 9
121212121
Wawrinka 0 - Ad
Djokovic 0 - 40

Test 10
1212121212
Wawrinka 0 - 40
Djokovic 0 - 40 Deuce (2)

Test 11
1211222122111122111
Wawrinka 1 - 40
Djokovic 1 - 30

Test 12
12112221221111221112
Wawrinka 1 - 40
Djokovic 1 - 40

Test 13
121122212211112211122
Wawrinka 1 - 40
Djokovic 1 - Ad

Test 14
1211222122111122111221
Wawrinka 1 - 40 Deuce
Djokovic 1 - 40

Test 15
1111222211112222111122221111222211112222111122221212121212121212121
Wawrinka 6 [10]
Djokovic 6 [ 9]

Test 16
11111111111111111111111111111111111111111111111111111111111111111111111
Wawrinka 6 6 5 - 40
Djokovic 0 0 0 -  0

Test 17
111111111111111111111111111111111111111111111111111111111111111111111111
Wawrinka 6 6 6
Djokovic 0 0 0
Wawrinka wins

Test 18
1111111111111111111111111111111111111111111111111111111111111111111111111
Wawrinka 6 6 6
Djokovic 0 0 0
Wawrinka wins

```
> 2 votes

# Answer
# Javascript - 743 bytes

```
var b=process.argv[2],c=[0,0],e=[],g=[0,0],h=[0,0],k=["0","15","30","40"],l=["Wawrinka","Djokovic"];function m(a){var d="",f;for(f in e)d+=e[f][a]+" ";3<=c[0]||3<=c[1]||(d+=g[a]+" - ",f=h[a],a=h[(a+1)%2],d=n()?d+("["+f+"]"):3>f||3>a?d+k[f]:f>a?d+"Ad":d+k[3]);return d}function n(){return 6<=g[0]&&6<=g[1]}function p(){var a=q;g[a]++;h=[0,0];7<=g[a]?(e.push(g),g=[0,0],c[a]++):6<=g[a]&&g[a]>g[(a+1)%2]+1&&(e.push(g),g=[0,0],c[a]++)} for(var r in b){var q=parseInt(b[r])-1,s=++h[q];n()?7<=s&&(4>e.length?p():s>h[(q+1)%2]+1&&p()):4<=s&&s>h[(q+1)%2]+1&&p()}console.log(l[0]," ",m(0));console.log(l[1]," ",m(1),n()?"":2<h[0]&&2<h[1]&&h[0]==h[1]?"Deuce"+(3<h[0]?" ("+(h[0]-2)+")":""):"");console.log(3<=c[0]||3<=c[1]?(3<=c[0]?l[0]:l[1])+" wins":"");

```

Without closure compiler:

```
var input = process.argv[2];

var score = [0,0];
var match = [];
var set = [0,0];
var game = [0,0];
var gameScore = [ '0', '15', '30', '40' ];
var names = ['Wawrinka', 'Djokovic'];

function printScores(who)
{
    var out = '';
    for (var i in match) {
        out += match[i][who] + ' ';
    }

    if (!isDone()) {
        out += set[who] + ' - ';

        var point = game[who], otherPoint = game[(who+1)%2];

        if (isTieBreaker()) { // Tie breaker
            out += '['+point+']';
        } else {
            if (point < 3 || otherPoint < 3) {
                out += gameScore[point];
            } else if (point > otherPoint) {
                out += 'Ad';
            } else {
                out+= gameScore[3];
            }
        }
    }

    return out;
}

function printDeuce()
{
    if (isTieBreaker()) {
        return '';
    } else {
        return (game[0] > 2 && game[1] > 2 && game[0] == game[1]) ? ('Deuce' + (game[0] > 3 ? ' (' + (game[0] - 2) + ')' : '')) : '';
    }

}

function isDone()
{
    return score[0] >= 3 || score[1] >= 3;
}

function isTieBreaker()
{
    return set[0] >= 6 && set[1] >= 6;
}

function getOther(who)
{
    return (who + 1) % 2;
}

function addPoint(who)
{
    var points = ++game[who];

    if (isTieBreaker()) {
        if (points >= 7) {
            if (match.length < 4) {
                addGame(who);
            } else if (points > (game[getOther(who)]+ 1)) {
                addGame(who);
            }
        }
    } else {
        if (points >= 4 && points > (game[getOther(who)] + 1)) {
            addGame(who);
        }
    }
}

function addGame(who)
{
    set[who]++;
    game = [0,0];

    if (set[who] >= 7) { // Won Tiebreaker
        addSet(who);
    } else if (set[who] >= 6 && set[who] > (set[getOther(who)] + 1)) {
        addSet(who);
    }
}

function addSet(who)
{
    match.push(set);
    set = [0,0];
    score[who]++;
}

// Play game
for(var i in input) {
    addPoint(parseInt(input[i]) - 1);
}

console.log(names[0], ' ', printScores(0));
console.log(names[1], ' ', printScores(1), printDeuce());
console.log(isDone() ? ((score[0] >= 3 ? names[0] : names[1]) + ' wins') : '');

```
> 1 votes

---
Tags: code-golf, game
---


title: Let's learn geometry

text:
# Question
Title: Let's learn geometry
Today our lesson is about rectangles and triangles.

you will be given as an input an `n x n` grid that is based on two characters `#` and `*` you have to classify it into : triangle or rectangle. where `#` represents a point and `*` represents a blank space.

# Example input:

```
 #***
 ##**
 ###*
 ####

```

## Output:

```
 triangle

```

## Another example

```
  ##**
  ##**
  ##**
  ##**

```

# Output:

```
  rectangle

```

Rules:

* You should assume that the input is always either a triangle or a rectangle.
* The only two characters you will receive are: `*` and `#`.
* Assume that n \< 100.
* Be creative, this is a so the most up-voted answer will win.

# Answer
> 5 votes
**TSQL**

Image recognition? Sounds like a job made for SQL :)

```
WITH cte AS (
  SELECT LEN(data)-LEN(REPLACE(data,'#','')) c FROM test_t
)
SELECT
  CASE WHEN COUNT(DISTINCT c)>2                           THEN 'triangle'
       WHEN SUM(CASE WHEN c=0 THEN 0 ELSE 1 END) = MAX(c) THEN 'square'
                                                          ELSE 'rectangle'
       END result
FROM cte;

```

An SQLfiddle with sample data and test.

# Answer
> 3 votes
## Python

**Creativity**

*Triangle*

```
Forward     Reverse
#***        ####      ####
##**  +     *###  =   ####
###*        **##      ####
####        ***#      ####

```

*Rectangle*

```
Forward  Reverse
##**     ##**     ##**
##**  +  ##**  =  ##**
##**     ##**     ##**
##**     ##**     ##**

```

**Implementation**

```
s=raw_input();print["tri","rect"][all(a!=b for a,b in zip(s,s[::-1])if a!='\n')]+"angle"

```

# Answer
> 2 votes
## Python + Sympy

A problem in Geometry should be only solved mathematically

**Creativity**

if s if the number of "#" in the input stream

Triangle: `n**2+n-2s=0` -\> n should be an integer

**Implementation**

```
from sympy import *
s,n=2*raw_input().count("#"),Symbol('n');print["rect","tri"][float(solve(n**2+n-s)[0]).is_integer()]+"angle"

```

# Answer
> 1 votes
## C

**Assumption**: the input does not represent a single-line degenerate rectangle, e.g.

```
****
*##*
****
****

```

as arguably this is also a degenerate triangle, and violates "the input is always one of the two cases."

**Logic**: Count the number of points in the first two non-empty lines. If they are the same, it is a rectangle. Otherwise, it is a triangle.

**Code**:

```
#include <stdio.h>
#include <string.h>
int main() {
    char s[99];
    int cnt1=0, cnt2=0;
    int i;
    while(!cnt1) {
        gets(s);
        for(i=0;i<strlen(s);i++) cnt1+=(s[i]=='#');
    };
    gets(s);
    for(i=0;i<strlen(s);i++) cnt2+=(s[i]=='#');
    puts(cnt1==cnt2?"rectangle":"triangle");
    return 0;
}

```

# Answer
> 1 votes
# Java

A simple straightforward java implementation. It scans the input looking for some 2x2 square which have `#` in two opposing corners with something not a `#` (presumable a `*`) is some other corner. I.E, it searchs for something that shows that the drawing has a diagonal-lined border.

```
import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class TrianglesAndRectangles {
    public static void main(String[] args) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int r;
        while ((r = System.in.read()) != -1) {
            baos.write(r);
        }
        String[] lines = baos.toString().split("\n");
        System.out.println(hasTriangle(lines) ? "triangle" : "rectangle");
    }

    public static boolean hasTriangle(String[] lines) {
        for (int i = 0; i < lines.length - 1; i++) {
            for (int j = 0; j < lines[i].length() - 1; j++) {
                boolean a = lines[i].charAt(j) == '#';
                boolean b = lines[i].charAt(j + 1) == '#';
                boolean c = lines[i + 1].charAt(j) == '#';
                boolean d = lines[i + 1].charAt(j + 1) == '#';
                if ((a && d && (!c || !b)) || (b && c && (!a || !d))) return true;
            }
        }
        return false;
    }
}

```

---
Tags: popularity-contest, geometry
---


title: Create a sophisticated livelock

text:
# Question
Title: Create a sophisticated livelock
The point of the puzzle is to learn about livelocks:

Create a multi-threaded (or a multi-process) program, whose threads (processes) indefinitely try to wait for each other and never finish. Unlike a deadlock situation, the state of threads (processes) in a livelock constantly change as they try to resolve the situation, but never succeeding.

The task isn't to create a shortest or a simplest solution. Try to create a solution that resembles a real situation, something that looks like a genuine piece of code, but with some kind of an error that creates the livelock.

This is a popularity contest. The most up-voted answer in ~10 days wins.

# Answer
> 3 votes
# Ruby

Based on the Dining Philosophers tale - 4 philosophers:

> Five silent philosophers sit at a table around a bowl of spaghetti. A fork is placed between each pair of adjacent philosophers. (An alternative problem formulation uses rice and chopsticks instead of spaghetti and forks.)
>
> Each philosopher must alternately think and eat. However, a philosopher can only eat spaghetti when he has both left and right forks. Each fork can be held by only one philosopher and so a philosopher can use the fork only if it's not being used by another philosopher. After he finishes eating, he needs to put down both forks so they become available to others. A philosopher can grab the fork on his right or the one on his left as they become available, but can't start eating before getting both of them.

```
class Fork

  attr_reader :owner
  def initialize
   @mutex = Mutex.new
  end

  def pickup(new_owner)
    @mutex.synchronize do
      if @owner.nil?
        @owner = new_owner
    return true
      end
      return false
    end
  end

  def release(owner)
     @mutex.synchronize do
      if @owner == owner
        @owner = nil
    return true
      end
      return false
    end
  end
end

class Philosopher

  attr_reader :name, :hungry
  attr_accessor :left_fork, :right_fork

  def initialize(name, left_fork, right_fork)
    @name = name
    @hungry = true
    @left_fork = left_fork
    @right_fork = right_fork
  end

  def eat
    while hungry
      got_left = left_fork.pickup(self)
      think
      got_right = right_fork.pickup(self)
      if got_left && got_right
        @hungry = false
    puts "#{name} has eaten!"
      end
      right_fork.release(self)
      think
      left_fork.release(self)
    end
    puts "#{name} ended"
  end

  def think
    puts "#{name} thinks..."
    sleep 1
  end
end

fork = nil
philosophers = %w(aristotle plato confucius descartes).map { |p| Philosopher.new(p, fork, fork = Fork.new) }
philosophers[0].left_fork = fork

threads = philosophers.map do |p|
  puts p.left_fork.pickup(p)
  Thread.new {
    p.eat
  }
end

threads.map(&:join)

```

# Answer
> 1 votes
## Game Maker Language

Script `add`:

```
subtract=argument0
add(not(subtract))

```

---
Tags: popularity-contest, concurrency
---


title: Euler's Front 9

text:
# Question
Title: Euler's Front 9
**Project Euler** is another fun programming challenge site to compete (well, play) on. Early problems start off gently, but then explode in difficulty beyond the first hundred or so. The first few problems have some commonality between finding primes, multiples, and factors, so there could be some interesting code micro-reuse opportunities to toy with.

So, **write a program that solves, using no *a priori* knowledge, any of the first 9 problems.**

1. The problem is selected by the user, ASCII '1' through '9', inclusive, via an argument when calling or standard input while running. (You can compute all the answers, but only show one.)
2. The correct answer must be printed on a new line, in base 10, using ASCII.
3. Programs should execute in less than a minute (PE suggestion).
4. By "no *a priori* knowledge", I mean *your code* must derive the answer without external resources. A program like this would be considered invalid (otherwise correct though, assuming I didn't make a typo):

```
print[233168,4613732,6857,906609,232792560,25164150,104743,40824,31875000][input()-1]

```

for problem #8 (involves a 1000-digit number), you may read the number from an external file, just specify how it's stored (e.g. binary, text, header, imported module) and/or include it in your answer post (does not count towards the length of the main program).
5. Score is by bytes.
6. Fifteen Unicorn Points™ awarded to the byte-count leader after 2 weeks.

# Answer
> 4 votes
## Python, 505

```
import f
A,B,C,D=map(range,[22,1000,101,500])
R=reduce
M=int.__mul__
a=x=0
b=1
n=2
p=[]
while b<=4e6:a,b=b,a+b;x+=b*(b%2<1)
while len(p)<=1e4:p+=[n]*all(n%i for i in p);n+=1
q=y=R(M,p[:8])
while any(y%(i+1)for i in A):y+=q
print[
    sum(i for i in B if i%3*(i%5)<1),
    x,
    max(i for i in p if 600851475143%i<1),
    max(a*b for a in B for b in B if`a*b`==`a*b`[::-1]),
    y,
    sum(C)**2-sum(i**2for i in C),
    p[-1],
    max(R(M,map(int,f.s[i:i+5]))for i in B),
    [a*b*(1000-a-b)for a in D for b in D if(a+b)*1e3==5e5+a*b][0]
][input()-1]

```

Whitespace is added to the last line for readability. The 1000-digit number is imported from a module named `f.py` containing the line:

```
s="7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450"

```

# Answer
> 3 votes
## Javascript

**Solution: 1785 chars**

execute code with nodeJS

note on problem 7 : algorithm is ok, but it take a moment ! If someone has a more efficient solution...

```
z=process.argv[2]
y=console.log
if(z==1){b=0;for(i=1e3;i--;)if(i%3<1||i%5<1)b+=i;y(b)}
if(z==2){d=e=1;f=0;while(e<=4e6)g=d+e,d=e,e=g,f+=e%2<1?e:0;y(f)}
if(z==3){e=Math.sqrt(d=600851475143)|0+1;f=2;while(f<e){g=d/f;if(g==(g|0))h=f,d=g;f+=f==2?1:2}y(h)}
if(z==4){for(a=b=100,c=0;a+b<1998;){d=a++*b;if(d==(""+d).split("").reverse().join("")&&d>c)c=d;if(a>999)a=b+1,b++}y(c)}
if(z==5){for(a=c=1;c;){for(b=20;b>1;)a%b>0?b=0:b--;b==1?c=0:a++}y(a)}
if(z==6){for(a=100,b=Math.pow(a*(a+1)/2,2),d=a+1;d--;)b-=d*d;y(b)}
if(z==7){for(a=3,c=d=0;c<1e4;){for(b=a;b>2;){b=b>3?b-2:2;if(a%b<1)b=0}if(b>0)c++,d=a;a=a+2}y(d)}
if(z==8){a="7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450";for(e=0,b=996;b--;){d=eval(a.substr(b,5).split("").join("*"));if(d>e)e=d};y(e)}
if(z==9){for(a=b=0;(c=a+b+Math.sqrt(a*a+b*b))!=1e3;)if(++a==500)a=0,b++;y(a,b,c-b-a)}

```

**problem 1: 39 chars**

```
b=0;for(i=1e3;i--;)if(i%3<1||i%5<1)b+=i

```

**problem 2: 49 chars**

```
d=e=1;f=0;while(e<=4e6)g=d+e,d=e,e=g,f+=e%2<1?e:0

```

**problem 3: 85 chars**

```
e=Math.sqrt(d=600851475143)|0+1;f=2;while(f<e){g=d/f;if(g==(g|0))h=f,d=g;f+=f==2?1:2}

```

**problem 4: 105 chars**

```
for(a=b=100,c=0;a+b<1998;){d=a++*b;if(d==(""+d).split("").reverse().join("")&&d>c)c=d;if(a>999)a=b+1,b++}

```

**problem 5: 55 chars**

```
for(a=c=1;c;){for(b=20;b>1;)a%b>0?b=0:b--;b==1?c=0:a++}

```

**problem 6: 51 chars**

```
for(a=100,b=Math.pow(a*(a+1)/2,2),d=a+1;d--;)b-=d*d

```

**problem 7: 82 chars**

```
for(a=3,c=d=0;c<1e4;){for(b=a;b>2;){b=b>3?b-2:2;if(a%b<1)b=0}if(b>0)c++,d=a;a=a+2}

```

**problem 8: 1078 chars ^\_^**

```
a="7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450"
for(e=0,b=996;b--;){d=eval(a.substr(b,5).split("").join("*"));if(d>e)e=d}

```

**problem 9: 58 chars**

```
for(a=b=0;a+b+Math.sqrt(a*a+b*b)!=1e3;)if(++a==500)a=0,b++

```

# Answer
> 1 votes
### R 684 characters

```
f=function(N){r=rowSums;p=function(x,y)r(!outer(x,y,`%%`));S=sum;x=c(1,1);n=600851475143;a=900:999;b=20;c=1:100;m=2:sqrt(n);M=m[!n%%m];A=a%o%a;d=3;P=2;z=1:1e3;Z=expand.grid(z,z);Y=cbind(Z,sqrt(r(Z^2)));W=gsub("\n","",xpathApply(htmlParse("http://projecteuler.net/problem=8"),"//p",xmlValue)[[2]]);switch(N,S(which(p(1:999,c(3,5))>0)),{while(tail(x,1)<4e6)x=c(x,S(tail(x,2)));S(x[!x%%2])},max(M[p(M,M)<2]),max(A[sapply(strsplit(c(A,""),""),function(x)all(x==rev(x)))],na.rm=T),{while(any(b%%1:20>0))b=b+20;b},S(c)^2-S(c^2),{while(P<=1e4){d=d+2;if(sum(!d%%2:d)<2)P=P+1};d},max(sapply(5:nchar(W),function(i)prod(as.integer(strsplit(substr(W,i-4,i),"")[[1]])))),prod(Y[r(Y)==1000,][1,]))}

```

Indented:

```
f=function(N){
    r=rowSums
    p=function(x,y)r(!outer(x,y,`%%`))
    S=sum
    x=c(1,1)
    n=600851475143
    a=900:999
    b=20
    c=1:100
    m=2:sqrt(n)
    M=m[!n%%m]
    A=a%o%a
    d=3
    P=2
    z=1:1e3
    Z=expand.grid(z,z)
    Y=cbind(Z,sqrt(r(Z^2)))
    W=gsub("\n","",xpathApply(htmlParse("http://projecteuler.net/problem=8"),"//p",xmlValue)[[2]])
    switch(N,S(which(p(1:999,c(3,5))>0)),
             {while(tail(x,1)<4e6)x=c(x,S(tail(x,2)));S(x[!x%%2])},
             max(M[p(M,M)<2]),
             max(A[sapply(strsplit(c(A,""),""),function(x)all(x==rev(x)))],na.rm=T),
             {while(any(b%%1:20>0))b=b+20;b},
             S(c)^2-S(c^2),
             {while(P<=1e4){d=d+2;if(sum(!d%%2:d)<2)P=P+1};d},
             max(sapply(5:nchar(W),function(i)prod(as.integer(strsplit(substr(W,i-4,i),"")[[1]])))),
             prod(Y[r(Y)==1000,][1,]))
    }

```

Usage:

```
> f(1)
[1] 233168
> f(2)
[1] 4613732
> f(3)
[1] 6857
> f(4)
[1] 906609
> f(5)
[1] 232792560
> f(6)
[1] 25164150
> f(7)
[1] 104743
> f(8)
[1] 40824
> f(9)
[1] 31875000

```

Separately:

**1: 48 chars** `sum(which(rowSums(!outer(1:999,c(3,5),`%%`))>0))`

**2: 64 chars** `x=c(1,1);while(tail(x,1)<4e6)x=c(x,sum(tail(x,2)));sum(x[!x%%2])`

**3: 73 chars** `n=600851475143;m=2:sqrt(n);M=m[!n%%m];max(M[rowSums(!outer(M,M,`%%`))<2])`

**4: 88 chars** `a=900:999;b=a%o%a;max(b[sapply(strsplit(c(b,""),""),function(x)all(x==rev(x)))],na.rm=T)`

**5: 34 chars** `a=20;while(any(a%%1:20>0))a=a+20;a`

**6: 25 chars** `a=1:100;sum(a)^2-sum(a^2)`

**7: 54 chars** `d=3;P=2;while(P<=1e4){d=d+2;if(sum(!d%%2:d)<2)P=P+1};d`

**8: 181 chars**

First line reads the number from the project euler website, second line actualy perform the computation.

```
W=gsub("\n","",xpathApply(htmlParse("http://projecteuler.net/problem=8"),"//p",xmlValue)[[2]])
max(sapply(5:nchar(W),function(i)prod(as.integer(strsplit(substr(W,i-4,i),"")[[1]]))))

```

**9: 87 chars** `z=1:1e3;Z=expand.grid(z,z);Y=cbind(Z,sqrt(rowSums(Z^2)));prod(Y[rowSums(Y)==1000,][1,])`

# Answer
> 1 votes
## J ~~245~~ ~~236~~ 232

```
load'n'
echo".>(<:".1!:1]1){<;._1'!+/I.+./0=5 3|,:~i.1e3!+/}:(],4&*@:{:+_2&{)^:(4e6>{:)^:_]0 2!{:q:600851475143!>./(#~(-:|.)@":"0),/*/~i.1e3!*./>:i.20!(([:*:+/)-[:+/*:)i.101!p:1e4!>./5*/\"."0 n!x:*/{.(#~1e3=+/"1)(+.,|)"0,j./~i.500'

```

n is a file containing the following:

```
n=:'7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450'

```

# Answer
> 0 votes
## TI-BASIC (Work in Progress)

*For your TI-83 or TI-84 calculator*

Main program, **15 bytes**:

```
Input X:OpenLib(1):X:ExecLib:Disp Ans

```

Library 1 (**4 bytes**) **does** count toward the total number of bytes:

```
L1(Ans

```

Then, we have List #1:

```
work in progress

```

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


# Question
Title: Build a program that creates a minimal one-ohm resistor diagram for a given resistance
You are a contractor for a company who designs electrical circuits for the various products they make. One day, the company accidentally gets a huge shipment of one-ohm resistors and absolutely nothing else, and give you the task of putting them to good use in the newest products they're making.

Your task is to build a program that takes a positive rational number as input, in the following form:

```
a / b

```

and return a resistor diagram with the exact given resistance, that uses as few one-ohm resistors as possible.

Your resistor diagram will consist of:

* The number `N`, to denote how many `SPT`s there are. (I will describe an `SPT` below.)
* `N` lines, each containing two numbers `A` and `B` representing numbered electrodes on a circuit board, followed by one `SPT`.
* One line containing two numbers `P` and `Q` denoting which two electrodes to measure the resistance between.

An `SPT` is a "series-parallel tree", a way to describe a series-parallel circuit in a tree format.

A valid `SPT` is either:

* The number 1, representing a single resistor.
* `S( )`, enclosing a number followed by zero or more `P( )` SPTs.
* `P( )`, enclosing a number followed by zero or more `S( )` SPTs.

Examples of valid `SPT`s:

```
1 <- has a resistance of 1
S(1) <- equivalent to 1 and P(1)
S(2, P(3)) <- has a resistance of 7/3, using 5 resistors
P(1, S(2), S(3), S(4, P(2))) <- has a resistance of 18/37, using 12 resistors

```

Examples of invalid `SPT`s:

```
2 <- the two resistors are in an unknown configuration. Use P(2) or S(2) instead.
P(2, P(1)) <- use P(3) instead.
P(4, P(1, S(3), S(2))) <- use P(5, S(3), S(2)) instead.

```

## Specifications

Your program must work for any numerator and denominator up to `150 000`.

Your program's source code, excluding any imported standard or third-party libraries, must not exceed one megabyte (1,048,576 bytes) total.

Your program will be tested on a specific, randomly chosen set of 10,000 fractions (to be determined at a later date), and scored on how few resistors it requires to build all 10,000 circuits. The program that uses the fewest resistors is the winner.

---

# Testing data

The input

```
3 / 8

```

might return

```
1
1 2 S(0, P(8), P(4))
1 2

```

to represent a series of 8 resistors and then 4 resistors in parallel. This may not be the optimal solution; but for the purposes of this problem, it is valid output.

The input

```
5 / 6

```

might return:

```
12
1 2 1
1 3 1
1 5 1
2 4 1
2 6 1
3 4 1
3 7 1
4 8 1
5 6 1
5 7 1
6 8 1
7 8 1
1 8

```

to represent a cube of one-ohm resistors with vertices numbered `1` through `8`, having its resistance measured between opposite corners. Of course it is possible to just do `S(P(2), P(3))` using just five resistors, but this is an example of how the notation is used to represent non-series-parallel diagrams.

# Answer
For series-parallel circuits with few resistors, the resistances which can be created with `n` resistors but not with fewer are the numbers on the `n`th level of the Stern-Brocot tree. (This breaks later on, with `5/6 = 1/2 + 1/3` apparently a minimal counterexample).

Instead of mapping from position in the Stern-Brocot tree to an S-P expression, it turns out to be much more convenient to use the Calkin-Wilf tree; its nodes at a given depth are permutations of the Stern-Brocot tree's nodes at that depth, but it has a different parent-child relationship: the left child of `m/n` is `m/(m+n) = (1^-1 + (m/n)^-1)^-1 = P(1, m/n)`, and the right child of `m/n` is `(m+n)/n = 1 + m/n = S(1, m/n)`.

## GolfScript

```
# Parse input
'/'/' '*~
# Stack: numerator denominator
{
    # numerator denominator
    1$1$<{
        # n/d is less than 1, so parent is n/(d − n) and we're looking at Parallel
        ', P('@@.2$/@@1$%
        # ', P(' d/n n d%n
    }{
        # n/d >= 1, so parent is (n - d)/d and we're looking at Series
        ', S('@@1$1$/@2$%@
        # ', S(' n/d n%d d
    }if
    # Loop until we get to 0/1 or 1/0
    1$1$*
}do;;
# Stringify
]''*
# Trim leading ', '
2>.
# Close the parentheses
'('/,(')'*+
# Add the boilerplate
'1
0 1 '\'
0 1'

```
> 3 votes

# Answer
# Python

As a last-place reference solution, here is a naïve solution that always works:

```
frac = raw_input().split(" / ")
num = int(frac[0])
den = int(frac[1])
print 1
print 1, 2,

pstr = ""
for x in range(den):
    pstr += "S(%s), " % num
pstr = pstr[:-2]

print "P(%s)" % pstr

print 1, 2

```

Always creates `n` parallel of `m` resistor series for the resistance `m/n`, using `mn` resistors each time.
> 0 votes

---
Tags: code-challenge, optimization, rational-numbers, electrical-engineering, test-battery
---


title: Output in the Correct Order

text:
# Question
Title: Output in the Correct Order
Ok lets say we get a input the following csv file (all entries are quoted strings)

```
ID,    Before,   After,   Value
 1,         3,       5,    Cat
 2,         5,        ,    Apple
 3,         4,       1,    Dog
 4,          ,       3,    Elephant
 5,         1,       2,    Banana

```

Output a csv file in which the entries are usage sequence order.

```
ID,    Before,   After,   Value
 2,         5,        ,    Apple
 5,         1,       2,    Banana
 1,         3,       5,    Cat
 3,         4,       1,    Dog
 4,          ,       3,    Elephant

```

**Notes:** The Values may not necessarily appear in alphabetical order all the time, just that in this example they are. No revaluing of the IDs being use. They must be the same as input.

Input and Output files will be pass as args to program.

# Answer
> 1 votes
# Ruby ~~109~~ 108

Saved one whole character by using randomization instead of searching!

```
h,*t=[*$<]
t.shuffle!until t.each_cons(2).all?{|c|a,b=c.map{|y|y.lstrip.split /[,\s]+/}
a[1]==b[0]}
puts h,t

```

This only prints to stdout, so to save to a file use `ruby csv.rb in.csv > out.csv`.

```
$ cat test.csv
ID,    Before,   After,   Value
 1,         3,       5,    Cat
 2,         5,        ,    Apple
 3,         4,       1,    Dog
 4,          ,       3,    Elephant
 5,         1,       2,    Banana
$ ruby csv.rb test.csv
ID,    Before,   After,   Value
 2,         5,        ,    Apple
 5,         1,       2,    Banana
 1,         3,       5,    Cat
 3,         4,       1,    Dog
 4,          ,       3,    Elephant

```

### Old version

```
puts gets,[*$<].permutation.find{|x|x.each_cons(2).all?{|c|a,b=c.map{|y|y.lstrip.split /[,\s]+/}
a[1]==b[0]}}

```

It simply finds the permutation of the lines where, for each line, the second column (*Before*) equals the first column (*ID*) of the next line.

# Answer
> 0 votes
## VB.net (Non-Golfed)

```
Module Module3
  Public Sub Main(ParamArray args() As String)
    Dim items = CSVFileReader(args(0)).ToDictionary(Function(x) x(0))
    Dim Current = items.First(Function(kvp) kvp.Value(2) = "").Value
    Using out As New IO.StreamWriter(args(1), False) With {.AutoFlush=True }
      Do
        out.WriteLine("""{0}"",""{1}"",""{2}"",""{3}""", Current(0), Current(1), Current(2), Current(3))
        If Current(1) <> "" Then Current = items(Current(1))
      Loop Until Current(1) = ""
      out.WriteLine("""{0}"",""{1}"",""{2}"",""{3}""", Current(0), Current(1), Current(2), Current(3))
    End Using
  End Sub

  Public Iterator Function CSVFileReader(fn As String) As IEnumerable(Of String())
    Using t As New FileIO.TextFieldParser(fn) With {.Delimiters ={","},.HasFieldsEnclosedInQuotes = True, .TextFieldType=FileIO.FieldType.Delimited }
      While Not t.EndOfData
        Yield t.ReadFields
      End While
    End Using
  End Function
End Module

```

Probably a lot of room to golf that code.

# Answer
> 0 votes
## C#, 272 bytes

Not a great answer, but it works. If I understand Linq correctly, this opens the input file repeatedly, once for each line it writes to the output.

```
namespace System.Linq{
    class P{
        static void Main(string[]a)
        {
            var v=IO.File.ReadAllLines(a[0]).Select(y=>y.Split(',').ToList());
            var l=v.First();
            var s="\"\"";
            for(;;){
                IO.File.AppendAllText(a[1],string.Join(",",l)+"\n");
                l=v.FirstOrDefault(x=>x[2]==s);
                if(l==null)break;
                s=l[0];
            }
        }
    }
}

```

Input file:

```
"ID","Before","After","Value"
"1","3","5","Cat"
"2","5","","Apple"
"3","4","1","Dog"
"4","","3","Elephant"
"5","1","2","Banana"

```

Output file:

```
"ID","Before","After","Value"
"2","5","","Apple"
"5","1","2","Banana"
"1","3","5","Cat"
"3","4","1","Dog"
"4","","3","Elephant"

```

---
Tags: code-golf
---