text:
Check if number is a sum of consecutive numbers or not
Write a program that checks if a given positive integer can be represented as sum of two or more consecutive positive integers.
Example:
43 can be represented as 21 + 22
10 = 1+2+3+4
but 4 cannot be represented in this way.
Input spec:  positive integer (as argument or stdin)
Output spec: truthy or falsy
Sample i/o
43 -> true
4 -> false

Shortest code wins.

I assume ./check 1 should return false?

@mellamokb, I've fixed the spec and it's now clear that 1 gives false.

Is case important for the output?

Not really, that should not be a problem :)

Any odd number greater than 1 would return true?

I edited the question to be clearer, and only code-golf.

Good edit, @mbomb007

Related OEIS sequence

JavaScript (31)
alert(!!((n=~~prompt())&(n-1)))

From my testing, I believe this gives correct solutions.
http://jsfiddle.net/3e9FZ/
Edit: (SPOILER ALERT!) Here is the justification for this answer:

All odd numbers greater than 1 can be trivially written as the sum of two consecutive numbers (ex 15 = 7+8, 23=11+12, etc.).
For even numbers having an odd factor where the odd factor is less than twice the even factor.  For example, 4*7, because 7 < (2*4 = 8).  Simply add 7 numbers with 4 at the center, 1+2+3+4+5+6+7.
For even numbers having an odd factor where the odd factor is more than twice the even factor.  For example, 4*9, because 9 > (2 * 4 = 8).  Double the even factor, and halve the odd factor to get 8*4.5.  You will add the 8 numbers centered at 4.5, i.e., 1+2+3+4+5+6+7+8.
The only numbers left are the even numbers having no odd factor, i.e., the powers of two.  The formula for the sum of a consecutive set of numbers is (avg * count).  Now if the count is odd, then avg is a whole number, and (avg * count) has an odd factor.  If count is even, then avg must be #.5, and thus avg * 2 is odd, and so avg * count has an odd factor.  Therefore, any sum using the formula (avg * count) must have an odd factor, which powers of two do not, and therefore have no solution.

It easy to see that odd numbers can be written as a sum of two consecutive numbers, and therefore any number that's not a power of two can be written as a sum of consecutive numbers.

How do you get from "all odd numbers" to "all numbers that are not a power of 2" ?

@Paul R: I have updated the answer with justification for why this should be correct.

@Alexandru: That is the basic idea, but you can't jump directly to powers of 2 without covering all the cases as I've given above with rules #2 and #3.

+1 for the proof (although to be pedantic, all odd numbers greater than 1).

@mellamokb: to be pedantic you still need to prove lack of solution for powers of two.

@Alexandru, @Peter Taylor: Duly updated, thanks for the input!

Bloody brilliant

About the JavaScript code: Does JavaScript guarantee strict left-to-right evaluation of the arguments to &? In C that expression would be undefined behaviour.

What's your source?  According to sources I found by Googling, both Javascript and C have operator precendence charts listing & as left-to-right associative.  Why would it be undefined behavior?

great work with the math man!

You can change it to an anonymous function: x=>!!(x&x-1) (12 bytes)

Edit: you can also get rid of the !!(), because positive integer values are considered truthy. This yields x=>x&x-1 (8 bytes)

Golfscript, 20 chars
~.(&!!"falsetrue"5/=

Someone had to.

Ruby (23)
only 3 chars longer than golfscript :)
p 0<(n=$*[0].to_i)&n-1

output:
$ ruby gc2958.rb 4
false
$ ruby gc2958.rb 43
true
$ wc gc2958.rb
  1       2      23 gc2958.rb

Haskell, 74
Felt like doing the brute force way.
import List
main=print.f=<<readLn
f n=elem n$map sum$tails=<<inits[1..n-1]

JavaScript (81)
n=prompt(r=i=1)|0;while(r&++i*i/2<n)if(i%2&!(n%i)|!(i%2|(n+i/2)%i))r=!r;alert(!r)

I'm cheating with & and | - even though they are technically bit-wise operations, they do the job quite nicely because the result is a 1/0 which are valid conditionals!
http://jsfiddle.net/HCqK2/4/

C, 67
As mellamokb suggested all numbers, except powers of two, can be written as sum of positive consecutive numbers:
main(int i,char**a){
printf((i=atoi(a[1]))&i-1?"true\n":"false\n");
}

your kinda stealing his idea...

Python 3 REPL, 34
bool(int(bin(2*int(input()))[3:]))

I took an alternative approach to the solution, but can't seem to squeeze anything else out of it. This code takes the input, multiplies it by two (this fixes the input case of 1 which breaks otherwise), converts it to binary, strips out the first 3 characters (0b1), converts the remainder to an integer (which is 0 iff the input was a power of two), and then converts that to a boolean.
As mentioned above, you can remove the 2* to get a 32-char solution that fails on an input of 1 but is otherwise perfect.

i assume you need a truthy value, so the bool() is not needed?

C
return 1 or 0:
int i(int j){return((j%2)?!(j==1):i(j/2));}

doesnt fulfill the task - it has to output "true" or "false".

Python 2 REPL, 24 chars
Shortest python atm, borrowing bin() from @Fraxtil :)
bin(input()).count('1')>1

bin(input()).count('1')>=2?

Haha, that's kinda obvious really :D thanks. And >=2 == >1 ;)

Is this not repl snippet?

Python 2 REPL, 19 17 16

x=input()
x>x&-x

Nice. You can actually shave off two characters on the second line: ~-x&x>0

@daniero Nice trick!!

x&-x<x saves yet 1 character

@AMK great trick!! updated the code.

Mathematica, 23 bytes
N[2~Log~#]~MatchQ~_Real

For once it's actually useful

TI-Basic, 6 bytes
fPart(logBASE(Ans,2

Operating system ≥2.53 required due to logBASE(. Without logBASE, there are alternatives:
7 bytes: fPart(ln(Ans)/ln(2
7 bytes: fPart(log(Ans)/log(2

Befunge-93, 28 bytes
Try it Online!
&v@.1<@.0<
:</2_^#!_^#-1\%2:

Instead of checking if the given integer is an element in this sequence, it's much easier to check if it isn't in the complimentary sequence (powers of 2 with 0 instead of 1). This functions very similarly to mellamokb's answer in that sense.
Note that the linked sequences are not exact representations of all truthy/falsey results of each integer, because the sequence uses non-negative integers instead of strictly positive. Thus, 1 is in the linked sequence, even though for this specific problem it should be in its compliment.

not actually the powers of two... It is actually the powers of two with 1 replaced by 0

also you are using the wrong sequence. that one includes 1 as a number by virtue of 1+0, as it uses non negative rather than positive

@DestructibleWatermelon I realize that the sequence doesn't completely match the problem, but only in regards to the base case of 1. The complimentary sequence for the one that matches the problem is the powers of 2 (possibly in addition to 0, depending on where the sequence starts).

Why don't you just use the actual powers of two instead of that sequence of two? (0 is not a positive number anyway, so no need to cover it)

Wren, 18 17 bytes
Umm, it's shorter than GolfScript...
Fn.new{|n|n&-n<n}

Try it online!

Vyxal, 2 bytes
‹⋏

Try it Online!
Just a port of Jelly and JS. Bitwise AND with n-1. Returns positive integer for true, 0 for false.
Prolog (SWI), 13 bytes
\N:-0<N-1/\N.

Try it online!
-4 thanks to Jo King

the prolog could just be 0<N-1/\N

Dyalog APL, 7 bytes
0≠1|2∘⍟

Checks if a number is not a power of 2.
Attempt This Online!
    2∘⍟  log base 2 of
  1|     mod 1
0≠       is not zero

My 14-byte brute-force attempt before learning that the question is equivalent to asking if a number is not a power of 2:
⊢∊∘∊1↓+/¨∘⊂⍥⍳⍨

Using 3 as an example:
             ⍨  put the argument on both sides: 3 ... 3
           ⍥⍳   integers from 1 to n on both sides: 1 2 3 ... 1 2 3
      +/¨∘⊂     sums of length-1, 2, and 3 windows in 1 2 3: (1 2 3)(3 5)(6)
    1↓          drop the length-1 sums
   ∊            flatten into a list
⊢∊∘             is the argument in this list?

Python 2 REPL, 33 chars
It seems that there's a way shorter way to do this though:
s=input()
n=2
while n<s:n*=2
n!=s

Perl, 51 bytes
print(((log($ARGV[0])/log(2))=~ /\./ )?true:false);

Example:
$perl Soc.pl 45

true

$perl Soc.pl 8

false

J, 12
It doesn't follow the spec 'true'/'false'. Rather I stick with 1/0. It checks if log base 2 of a number has a decimal mark.
+/=&'.'":2^.
   +/=&'.'":2^.1
0
   +/=&'.'":2^.4
0
   +/=&'.'":2^.43
1

Jelly, 2 bytes
&’

Try it online!
Just a translation of the accepted JavaScript solution.

Vyxal, 10 bytes
Ṅ's¯1J≈;Ṫḃ

Try it Online!
A non-bitwise answer that doesn't port Javascript.
Explained
Ṅ's¯1J≈;Ṫḃ
Ṅ           # Integer partitions of the input
 '     ;    # Filtered by:
  s¯        #  Are the deltas of the sorted partition
    1J≈     #  All 1?
        Ṫḃ  # Remove the tail of the list because that's just the input as a single item and then return whether there's any items in the list.

You can use ₃ instead of Ṫḃ (using reversed booleans).


text:
Find 10 large prime numbers with n digits
You are given n (200 ≤ n < 250) as a command line argument. Print 10 prime numbers with n digits. Your program should run under 1s and must be shorter than 5000 bytes (excluding).
Sum the digits of all your 500 primes. Program with the largest sum wins.
An example (more here):
$ ./find_large_primes 200
58021664585639791181184025950440248398226136069516938232493687505822471836536824298822733710342250697739996825938232641940670857624514103125986134050997697160127301547995788468137887651823707102007839
29072553456409183479268752003825253455672839222789445223234915115682921921621182714164684048719891059149763352939888629001652768286998932224000980861127751097886364432307005283784155195197202827350411
41184172451867371867686906412307989908388177848827102865167949679167771021417488428983978626721272105583120243720400358313998904049755363682307706550788498535402989510396285940007396534556364659633739
54661163828798316406139641599131347203445399912295442826728168170210404446004717881354193865401223990331513412680314853190460368937597393179445867548835085746203514200061810259071519181681661892618329
71611195866368241734230315014260885890178941731009368469658803702463720956633120935294831101757574996161931982864195542669330457046568876289241536680683601749507786059442920003278263334056542642264651
28591045597720075832628274729885724490653298360003309382769144463123258670807750560985604954275365591715208615509779345682419533206637382048824349415329839450792353652240682445321955199147316594996133
49790921912819110019003521637763748399072771256062128988437189616228355821145834783451215869998723492323628198577054239101181556609916127864608488018093426129641387774385490891035446702272744866010729
15474811206486587193258690501682404626361341756658894201908294153626080782693777003022566996735796983239343580281979005677758015801189957392350213806122307985157041153484138150252828152419133170303749
12654646219963267405298825104551142450213038420566798208417393291567314379831789259173233506811083774527183953999862675239292185131178671317061020444490733287588383918793095608410078925861028249824377
40992408416096028179761232532587525402909285099086220133403920525409552083528606215439915948260875718893797824735118621138192569490840098061133066650255608065609253901288801302035441884878187944219033

You can use this program to test for primality.
EDIT:
Use the following program to compute your score:
#!/usr/bin/python
# Usage: ./v.py ./find_large_primes

import subprocess
import sys

sum_ = 0
for n in xrange(200, 250):
  p = subprocess.Popen(
                   args=[sys.argv[1], str(n)],
                   stdout=subprocess.PIPE)
  p.wait()

  sum_ += sum(int(e) for e in p.stdout.read() if e.isdigit())
  p.stdout.close()

print sum_

Which 500 primes do we sum?  Run the program 50 times?

You should be able to print 500 different integers, 10 for each value of n = 200..249. So yes, run the program 50 times.

Do I get to use a quantum computer to solve it?

C++ with GMP
#include <stdio.h>
#include <stdlib.h>
#include <gmp.h>

int main(int argc, char *argv[]) {
  int d = atoi(argv[1]);
  int i = 0;
  mpz_t n;
  mpz_init(n);
  mpz_ui_pow_ui(n, 10, d);
  mpz_sub_ui(n, n, 1);
  while (i < 10) {
    if (mpz_probab_prime_p(n, 100)) {
      printf("%s\n", mpz_get_str(NULL, 10, n));
      i += 1;
    }
    mpz_sub_ui(n, n, 2);
  }
}

It runs in just under a second on my machine.  I'm too lazy to run it 50 times and sum up the digits, but it should be pretty good, as most of the digits (all but the last 4 of each number) are 9s.
> ./a.out 250
9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999967
9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999323
9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999017
9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999998731
9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999997471
9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999996959
9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999995077
9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999993529
9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999993511
9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999992459

Your score is: 1002616. GMP makes it so easy.

You might be able to improve it slightly if you can find numbers where only one or two digits are not 9, but they don't necessarily have to be at the end of the number...

@mellamokb: True.  I'll let someone else try that...

That is C, not c++

@kylek: It's both.

Perl
use Math::Prime::Util ":all";
my $n = "1"."0"x shift;
print $n=prev_prime($n),"\n" for 1..10;

score 1002616, On 4770K, takes about 0.1s for an argument between 200 and 250; under 4 seconds for the score program.  Time for a given run stays under 1s until 455 digits.  Note that the Math::Prime::Util and Math::Prime::Util::GMP modules should be installed.
prev_prime uses ES BPSW as the primality test, so a little more stringent than Pari's precprime.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Generating guitar tabs?
Write the shortest program that generates guitar tabs for the chords given as input.
So that the guitarists among you don't have an advantage, and to make it deterministic (and probably easier to code), here are the only forms of the chords authorized:
Major chords:

  E   F   F#  G   G#  A   A#  B   C   C#  D   D#
e 0---1---2---3---4---0---1---2---3---4---5---6---
B 0---1---2---3---4---2---3---4---5---6---7---8---
G 1---2---3---4---5---2---3---4---5---6---7---8---
D 2---3---4---5---6---2---3---4---5---6---7---8---
A 2---3---4---5---6---0---1---2---3---4---5---6---
E 0---1---2---3---4---0---1---2---3---4---5---6---

Minor chords:

  Em  Fm  F#m Gm  G#m Am  A#m Bm  Cm  C#m Dm  D#m
e 0---1---2---3---4---0---1---2---3---4---5---6---
B 0---1---2---3---4---1---2---3---4---5---6---7---
G 0---1---2---3---4---2---3---4---5---6---7---8---
D 2---3---4---5---6---2---3---4---5---6---7---8---
A 2---3---4---5---6---0---1---2---3---4---5---6---
E 0---1---2---3---4---0---1---2---3---4---5---6---

Note that the 5 first chords and the 7 last chords of each series have different forms.
All the chords are simple major or minor chords (no 7th or other variations).
You should take care of flats too. Reminder:
A# = Bb
C# = Db
D# = Eb
F# = Gb
G# = Ab

B#, Cb, E# and Fb are not used

Output must include the first column with the cord names, as shown above. It does not have to include the chord name on top. Chords must be separated by 3 - as shown above. The final 3 - are optional.
Input is a string consisting of chord names, separated by spaces.
An example input is:
Bm Gb A E G D Em F#

and the corresponding output is:
e 2---2---0---0---3---5---0---2---
B 3---2---2---0---3---7---0---2---
G 4---3---2---1---4---7---0---3---
D 4---4---2---2---5---7---2---4---
A 2---4---0---2---5---5---2---4---
E 2---2---0---0---3---5---0---2---

... and side question: what's the example song? :)

Hotel California :P

Yep, you win! :)

Cool idea. Wish I had time to play!

JavaScript, 297 277 262 235 223 chars
No carriage returns in the golfed version are significant; they are there only to make the answer readable. Semicolons are significant.
Edit: Replaced the outer map with a while loop and other edits. Finally inside of 2× the size of the Golfscript version (for now)!
Edit: Replaced the indexOf with math, broke down the lookup table, other small improvements.
Edit: Another map to for and put in a final \n I had been unnecessarily eating. Finally inside of Jules's Python version.
i=prompt(o='').split(' ');for(r=6;o+=' EADGBe'[r]+' ',r--;o+='\n')
for(j=0;n=i[j++];o+=(([84,13,52,5][2*/m/.test(n)+x]*8>>2*r&3)+y-7*x)+'---')
y=n.charCodeAt(0),y=(2*y-(y>66)-(y>69)+(n[1]<'$')-(n[1]=='b')+2)%12,x=y>6;alert(o)

Output no longer takes advantage of the trailing --- being optional as:
e 2---2---0---0---3---5---0---2---
B 3---2---2---0---3---7---0---2---
G 4---3---2---1---4---7---0---3---
D 4---4---2---2---5---7---2---4---
A 2---4---0---2---5---5---2---4---
E 2---2---0---0---3---5---0---2---

Damn, I've got javascript peen-envy I think.  Nicely done.

Golfscript, 136 chars
[["eBGDAE"{[]+" "+}/]]\" "/{.-2\{"bm#A B C D E F G"?.)!!*(+}/14%.3>-.8>-.7/@109?0>2*+[963 780 882 753]{3base(;}%=\7%{+'---'+}+%}%+zip n*

Fully 23 chars (17.5%) deal with those two characters at the start of each output row.
Sample output, testing the edge cases:
$ golfscript.rb tabs.gs <<<"E G# Ab A Db D# Em G#m Abm Am D#m"
e 0---4---4---0---4---6---0---4---4---0---5---
B 0---4---4---2---6---8---0---4---4---1---6---
G 1---5---5---2---6---8---0---4---4---2---7---
D 2---6---6---2---6---8---2---6---6---2---7---
A 2---6---6---0---4---6---2---6---6---0---5---
E 0---4---4---0---4---6---0---4---4---0---5---

I've only spent about an hour on this, so it can probably be reduced by 5 to 10 chars at least. Conceptually it turns out to be quite similar to DocMax's solution: lookup table for four cases, then increment by an offset and join the strings in the right order.

+1: Man I love Golfscript! Several times today I have found places to trim my code, but not by 50%! I don't have an interpreter handy: does it return D# for Eb?

BTW, the last note in your sample matches C#m although the command line shows D#m. Typo or bug?

@DocMax, bug. I don't understand why it only affects D#m and not D# - this is going to be interesting to debug. I reorder things because it's convenient to have the block of 7 first, so Eb isn't really an edge case.

Turns out that the last one was getting a \n included, which not being in the lookup table was pulling the value down by the equivalent of a letter.

After coding this up, I realized I could have done this a lot smarter...maybe I'll make another entry. Hopefully I'll just get points for being the quickest!
Anyway, there is 962 characters of Perl.
%c =(B=>{E=>0,F=>1,Gb=>2,G=>3,Ab=>4,A=>2,Bb=>3,B=>4,C=>5,Db=>6,D=>7,Eb=>8,Em=>0,Fm=>1,Gbm=>2,Gm=>3,Abm=>0,Am=>1,Bbm=>2,Bm=>3,Cm=>4,Dbm=>5,Dm=>6,Ebm=>7},G=>{E=>1,F=>2,Gb=>3,G=>4,Ab=>5,A=>2,Bb=>3,B=>4,C=>5,Db=>6,D=>7,Eb=>8,Em=>0,Fm=>1,Gbm=>2,Gm=>3,Abm=>4,Am=>2,Bbm=>3,Bm=>4,Cm=>5,Dbm=>6,Dm=>7,Ebm=>8},D=>{E=>2,F=>3,Gb=>4,G=>5,Ab=>6,A=>2,Bb=>3,B=>4,C=>5,Db=>6,D=>7,Eb=>8,Em=>2,Fm=>3,Gbm=>4,Gm=>5,Abm=>6,Am=>2,Bbm=>3,Bm=>4,Cm=>5,Dbm=>6,Dm=>7,Ebm=>8},A=>{E=>2,F=>3,Gb=>4,G=>5,Ab=>6,A=>0,Bb=>1,B=>2,C=>3,Db=>4,D=>5,Eb=>6,Em=>2,Fm=>3,Gbm=>4,Gm=>5,Abm=>6,Am=>0,Bbm=>1,Bm=>2,Cm=>3,Dbm=>4,Dm=>5,Ebm=>6},E=>{E=>0,F=>1,Gb=>2,G=>3,Ab=>4,A=>0,Bb=>1,B=>2,C=>3,Db=>4,D=>5,Eb=>6,Em=>0,Fm=>1,Gbm=>2,Gm=>3,Abm=>4,Am=>0,Bbm=>1,Bm=>2,Cm=>3,Dbm=>4,Dm=>5,Ebm=>6});
%b=('A#'=>'Bb','C#'=>'Db','D#'=>'Eb','F#'=>'Gb','G#'=>'Ab');
foreach(qw(e B G D A E)){p($_,@ARGV)}
sub p{$s = shift;print "$s ";$s = uc($s);foreach(@_){while(($h,$f)=each(%b)){s/$h/$f/}print "$c{$s}->{$_}---"}print "\n"}

Here is the corresponding output.
dhrasmus:Desktop standage$ perl guitar Bm Gb A E G D Em F#
e 2---2---0---0---3---5---0---2---
B 3---2---2---0---3---7---0---2---
G 4---3---2---1---4---7---0---3---
D 4---4---2---2---5---7---2---4---
A 2---4---0---2---5---5---2---4---
E 2---2---0---0---3---5---0---2---

Since shorter solutions have been given already (damn you GolfScript!), here is mine:
Python, 229 chars
s=[("E EmF FmF#GbG GmG#AbA AmA#BbB BmC CmC#DbD DmD#Eb".find("%-02s"%s[:2])/4,s[-1]!='m')for s in raw_input().split()]
for c in range(6):
 l='eBGDAE'[c]+' '
 for(i,M)in s:x=i>4;l+=`i-5*x+2*(2<c+x<5)+(M+x)*(c==2-x)`+"---"
 print l

Output:
> echo "Bm Gb A E G D Em F#" | python guitar.py
e 2---2---0---0---3---5---0---2---
B 3---2---2---0---3---7---0---2---
G 4---3---2---1---4---7---0---3---
D 4---4---2---2---5---7---2---4---
A 2---4---0---2---5---5---2---4---
E 2---2---0---0---3---5---0---2---

Python, 449 chars
z=int
f=str
r=range
j=''.join
n='E F F# G G# A A# B C C# D D#'.split()
n+=[x+'m'for x in n]
c=[j([f(z(x)+i)for x in'001220'])for i in r(5)]+[j([f(z(x)+i)for x in'022200'])for i in r(7)]
c+=[x[:2]+f(z(x[2])-1)+x[3:]for x in c[:5]]+[x[0]+f(z(x[1])-1)+x[2:]for x in c[5:]]
a=[c[n.index((chr(ord(i[0])-1)+'#'+i[2:]).replace('@','G')if len(i)-1 and i[1]=='b'else i)]for i in raw_input().split()]
for i in r(6):print'eBGDAE'[i],j([x[i]+'-'*3 for x in a])

C99 - 231 characters
The chords are given on the command line, one argument per chord, and of course there is no input validation of any kind.
#include<stdio.h>
int main(int c,char**v){for(char*o="e0)B2)G2*D2+A0+E0)",i,m;*o;o+=3,v-=c,puts(""))for(printf("%c ",*o);*++v;printf("%c---",i-(i>2)-i/9+o[1+i/8]-(*o-66-i/8*5?0:m?m+2[*v]>99:0)))m=1[*v],i=(**v*2-4+m/35-m/98*3)%14;}

Sample run:
$ ./a.out Bm Gb A E G D Em F#
e 2---2---0---0---3---5---0---2---
B 3---2---2---0---3---7---0---2---
G 4---3---2---1---4---7---0---3---
D 4---4---2---2---5---7---2---4---
A 2---4---0---2---5---5---2---4---
E 2---2---0---0---3---5---0---2---

Un-golfed
#include<stdio.h>
int main(int c,char**v){
     // o points to three characters per output line:
     //   string name, number for A, adjusted number for E (ASCII code minus 7)
     char* o="e0)B2)G2*D2+A0+E0)",
          i, // chord: A=0, A#=1, ..., G#=13, allowing also 3="E#" and 9="B#"
          m; // second character in chord name
     for (; *o; o+=3) {
          printf("%c ", *o);
          for (; *++v; ) {
               m = 1[*v],
               i = (**v*2-4+m/35-m/98*3)%14; // parse & adjust for sharp, flat
               printf("%c---",
                      i-(i>2)-i/9 // eliminate "E#", "B#"
                      +o[1+i/8] // get the number for a major chord
                      // adjust for minor...
                      -(*o-66-i/8*5
                        ? 0
                        : m ? m+2[*v]>99 : 0));
          }
          v -= c; // rewind argument pointer
          puts("");
     }
}

Nonstandard C - 206 characters
If we don't care about language specifications, GCC can compile the following one-liner into a functional binary, even though it mixes C99 variable declarations with a K&R style argument declaration (and an implicit declaration of printf).
main(c,v)char**v;{for(char*o="e0)B2)G2*D2+A0+E0)",i,m;*o;o+=3,v-=c,puts(""))for(printf("%c ",*o);*++v;printf("%c---",i-(i>2)-i/9+o[1+i/8]-(*o-66-i/8*5?0:m?m+2[*v]>99:0)))m=1[*v],i=(**v*2-4+m/35-m/98*3)%14;}

C++, 432
#include <cmath>
#include <iostream>
F(int c){c-=65;return c*1.6+sin(c/5.+.3);}
T(int a,int s){if(s)return(a=(T(a,s-1)+2)%3)-=(a==1&s>2);return(a<7)*2;}
#define c(a,b) while(*(++j)==a)b;--j;
#define O std::cout<<
main(int a,char*p[]){
int P=2;for(int i=-1;++i<6;P=2){O p[1][i];O" ";while(P<a){char*j=p[P++];
int f=F(*j);c('#',++f)c('b',--f)
int t=T(f,i)*3.5;if(*(++j)!='m'){--j;t+=(t==3);}
O(f-F(p[1][i])+t+24)%12;O"---";
}O'\n';}}

Note that this needs the guitar tuning as the first parameter. (Most non-standard-tunings will give you ridiculous fingerbreaking results, but I guess you're content with standard tuning.)
For Hotel California, you can do $./a.out EBGDAE Cbm Gb Bbb Fb G D Em F# Bm F# G## D## F## C## D##m E##. Result:
E 2---2---0---0---3---5---0---2---2---2---5---0---3---5---0---2---
B 3---2---2---0---3---7---0---2---3---2---5---0---3---7---0---2---
G 4---3---2---1---4---7---0---3---4---3---6---1---4---7---0---3---
D 4---4---2---2---5---7---2---4---4---4---7---2---5---7---2---4---
A 2---4---0---2---5---5---2---4---2---4---7---2---5---5---2---4---
E 2---2---0---0---3---5---0---2---2---2---5---0---3---5---0---2---

Tuning the upper four strings to minor thirds makes it very easy to play three- and four-string chords in many inversions, without open strings, and without having to place a finger "over" a string without touching it.  Using strings DFG#B, a chord sequence like "Bbm F Bbm Gb Db Ebm Db F Bbm F F7 Bbm" (Mermaid Song) works out very easily.  It's only necessary to shift up and down one fret.  There's a half-step keychange, but that just means moving up a fret.  Haven't figured out what best to do with the other two strings, though.

@supercat: interesting, I shall try this on my guitar tomorrow...

I'd like to hear what you think.  I'd picked up a guitar a few times, years apart, and kept giving up because the fingerings seemed both arbitrary and awkward.  Then I got to thinking about what tunings would allow simple fingering.  Since closed-form chords have intervals which range from a minor third to a perfect fourth, tuning strings to minor thirds means each string will be damped at a point which is no lower than the string below.  If I can try a left-handed guitar, I might try perfect fourths with string order reversed, since it should be similar.

As it is, tuning to minor thirds means that for each position of the first finger on the lowest string, there will be three major chord inversions and three minor chord inversions available.  One can also play a seventh chord by placing the second finger across the top three strings.  For Mermaid Song, start on the third fret and play F-Bb-D-F (with fingers 1-3-3-4).  Then F is F-A-C-F (1-2-2-4).  Gb is up a fret, fingered 1-2-2-4 (like F).  Db is back down a fret, 1-3-4-4.  Ebm is back up, 1-2-4-4.

It took me only a few hours to get to the point where I could smoothly play some pieces (including the aforementioned Mermaid Song) after working out with the aid of a keyboard what the proper chord notes should be.  Once I tried this style, it felt amazingly natural, and I really like the way one can use all three inversions of each major and minor chord.  If one just wanted major and minor chords, a tuning like F-Ab-B-Eb-Gb-D could theoretically allow six-finger major and minor chords with easy fingerings (1-2-2-3-4-4 or 1-1-2-3-3-4) but without the inversions.

Had a chance to try the tuning yet?

390 345 340 Postscript
Simplified to a guitar-pragmatic approach (the E shape is just a variation of the A shape, shifted down a string, with one finger change). Borrowed the encoded-string idea from the other answers.
[/p{print}/x{exch}/e{cvx exec}/d{dup 0
get}/f{forall}(A0#1B2C3D5E7F8G:b;){}forall/m{dup
4 2 copy get 1 sub put}109{m 48}/+{[3 1 roll x{1
index add x}f]}/*{[0 0 2 2 2 0 0]x{load e 48 sub
+}f d 12 gt{-12 +}if d 6 gt{m -7 + 1}{0}ifelse 6
getinterval}>>begin[ARGUMENTS{*}f][(E)(A)(D)(G)(B)(e)]6{[x
e p( )p]x[x{[x e( )cvs p(---)p]}f]x()=}repeat

Previously:
450 442 418 Postscript
I fixed the output format with this one, too. (Previous versions began "E---" rather than "e ".)
<</i{index}/a{add}/p{pop}/x{exch}/g{getinterval}/r{print}/f{forall}/e{exec}>>begin<<65[0
2 3 5 -5 -4 -2]{1 i 1 a}f p 35{1 a}98{1 sub}109{x dup
4 20 put x}>>begin[ARGUMENTS{[x[0 5 12 17 21 24 29
0]x{load e}f x{1 i a x}f]dup 0 get 0 ge{0}{1}ifelse 7
g[0 -5 -10 -15 -19 -24 -29]0 1 6{2 copy get 3 i 2 i
get a 3 copy put p p}for x p 0 6
g}f][(E)(A)(D)(G)(B)(e)]6{[x cvx e r( )r]x[x{[x cvx
e( )cvs r(---)r]}f]x(\n)r}repeat

How to run it: gsnd -q -- tab.ps Bm Gb A E G D Em F\# (hide the sharp from the shell).
The un-golfed version was almost more difficult than the golfed one. But I tried to be thorough. Edit: a few more comments on the tricksy-bits.
%!PS
<<    %axioms and operations
/t{2 2 1}    %major tetrachord
/m{t t 2}    %mixolydian mode
/u{2 1 2}    %minor tetrachord
/a{u u}      %aolian mode
/s{m m t}    %2.5-octave mixolydian intervals
/r{3 1 roll}
/${[exch 0 exch{1 index add}forall]}    %running sum: convert (relative)intervals to (abstract)fretstops
/+{[r exch{1 index add exch}forall pop]}    %scale array by scalar
/@{[r{2 copy get r pop}forall pop]}    %select array elements from array of indices
/&{0 1 3 index length 1 sub{    %array2 += array1
    2 copy get 3 index 2 index get add 3 copy put pop pop}for exch pop}
>>begin<<    %map ascii values to scaling functions
65[a]$    %generate fretstops of the A aolian scale to assign scalars to note names
[0 0 0 0 -12 -12 -12]&    %drop E F and G down an octave
{[exch/+ cvx]cvx 1 index 1 add}forall pop    %generate the pairs 'A'->{0 +}, 'B'->{2 +}
35{1 +}     %'#'-> scale up by one
98{-1 +}    %'b'-> scale down by one
109{dup 4 2 copy get 1 sub put}     %'m'-> tweak the 'third' down by one
%generate chord pattern from (string)
/*{[s]$       %generate fretstops of the E mixolydian scale
  [1 4 8 11 13 15 18]    %A-shape figured bass: IV chord of E mixolydian
  -1 +       %convert scale degrees to array indices
  @       %generate chord template by selecting indices from mixolydian scale
  exch{load exec}forall       %execute ascii values, scaling the pattern
  dup 0 get 0 ge{0}{1}ifelse 6 getinterval    %discard first note if it has fallen off the bottom
  [0 -5 -10 -15 -19 -24]&}    %subtract the string offsets
>>begin    %activate definitions
%(A)* pstack()= clear    %[0 0 2 2 2 0]
%(B)* pstack()= clear    %[2 2 4 4 4 2]
%(F#)* pstack()= clear    %[2 4 4 3 2 2]
%(Abm)* pstack()=    %[4 6 6 4 4 4]
[ARGUMENTS{*}forall]    %convert array of strings to array of patterns
[(E)(A)(D)(G)(B)(e)]    %array of string names
6{    %for each "string"
    [exch cvx exec print( )print]    %pop string name and print with space
    exch       %put names behind numbers
    [exch{     %for each "chord"
        [exch cvx exec( )cvs print(---)print]    %pop number, convert, print with trailing hyphens
    }forall]    %zip up chord array for next iteration
    ()=         %print a newline
    exch        %put numbers behind names
}repeat

And how about House of the Rising Sun as a test?
04:51 PM:~ 0> gsnd -q -- tabb.ps Em G A C Em G B B Em G A C Em B Em B|sed 's/^/    /'
e 0---3---0---3---0---3---2---2---0---3---0---3---0---2---0---2---
B 0---3---2---5---0---3---4---4---0---3---2---5---0---4---0---4---
G 0---4---2---5---0---4---4---4---0---4---2---5---0---4---0---4---
D 2---5---2---5---2---5---4---4---2---5---2---5---2---4---2---4---
A 2---5---0---3---2---5---2---2---2---5---0---3---2---2---2---2---
E 0---3---0---3---0---3---2---2---0---3---0---3---0---2---0---2---

I written a commentary of this code in another answer here.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Traffic light synchronization problem
I'm not a 100% sure if this qualifies under this stack exchange; however, I asked this question on the stats stackexchange with no answers. I wonder if you can solve it:
Traffic light synchronization nowadays is not a tedious project, Image:

For a personal research project I'm trying to build a statistical model to solve such problems in two and higher dimensions.
I would like to synchronize x 4 legged (approaches) intersections such that:

The intersections are all located within the same area in a grid type format. I'd like to think of this as a 1/0 matrix, where 1 indicates a signalized intersection and 0 doesn't:
Matrix Example
[1 1 1 1]
[0 1 0 1]
[1 1 1 1]
This assumes that all nodes are connected in a vertical or horizontal but not diagonal manner and that they could have a direction of either one or two way.
Each Intersection has a traffic light on each approach
The allowable movements per leg are left, right, and Through (lrt) and no U-Turns
Each Leg can be one lane, i.e. one lane that allows for lrt or approaches can have combined, through and right (1 lane), and left (1 lane, or dedicated such as alpha left lanes, beta through lanes, and gamma right lanes. Some intersections should allow for restricted or no movement, as in an intersection could be setup as "no-left turns allowed"
Each lane should have a distinct vehicle flow (vehicles / minutes (Time)) per movement, so a two lane (left + through, and right) approach could have the following movement:
Left + Through lane: 10 vehicles / minute (through) and 5 vehicles per minute turning left
Right lane: 15 vehicles per minute
Assume green cycle time (time from beginning of green to beginning second green to depend on the vehicle volumes, yet could only be between t1 and t2 seconds. Green time = red time + yellow time). Yellow time should be assumed as a constant either 1, 2, or 3 seconds (depending on the jurisdiction). if pedestrian crossing is warranted, the red time should be assumed to be "white go ped: 4 seconds x lane" + "blinking ped: 4 seconds x lane". remember that the number of lanes would be from the opposing approaches combined.
The system should optimize green time so that maximum flow is passed through the system at all intersections depending no the existing volumes and on historical values.
Although there are historical data on the number of vehicles that enter the green network, I assume it is best to use a Monte Carlo simulation to simulate vehicle entry into the system and then calibrated to historical data.
The end result should be an equation or system of equations that will give you the green time for each intersection depending on volumes and what to expect from the other intersections.

I know this might not be the clearest question, but I'm happy to answer any questions and or comments.

Welcome to CodeGolf.SE! This is a site for posting programming games, and I'm not at all sure that this qualifies as it appears to define a major (and actually quite interesting) research project. I am closing this for now, but am willing to be convinced if I have made a mistake.

Actually, I agree with you somewhat, and perhaps, it could be migrated to the programmer's stack exchange? the biggest reason, I posted here, is that for the most part, code golfers are looking for a good challenge to solve

It would be off-topic on Programmers and Stack Overflow.  I would think it would be more on-topic on [Math] than on Stats.  Or perhaps [cstheory].

sure, feel free to migrate the question to any stack exchange that you see fit

since no one has migrated the question, I'm going to put a bounty on stats for it


text:
Compose a Vim quine!
Goal:
Create and save file in Vim containing at least 25 ASCII characters. The exact keystrokes used during the creation and saving of this file must also produce identical contents in Windows Notepad (without having to save in Notepad).
Rules:

For the purposes of this challenge, Vim begins open in command mode.
The mouse is not allowed.
Shift is allowed. Ctrl, alt, or any other modifier keys are not allowed.
Your solution must work with the default "terminal" (non-GUI) Vim shipped with either Ubuntu 11.04 or OS X 10.6.7 (one of the two). Assume this Vim's .vimrc contains only set nocompatible (with no line break after it), which is itself located at ~/.vimrc. Pretend your operating system was just installed before opening Vim.
You must not open any pre-existing files except for your .vimrc. Any files you create while solving this puzzle may be saved and re-opened as many times as necessary.
Vim cannot be closed!

Disclosure, and  a possible reason to close: I do not have a solution.

-1 for mentioning Notepad.

user unknown: That's a quite stupid reason for downvoting, actually.

@Joey Don't try to find logic in a fanboy's reasoning.

You should add an objective winning criterium, like amount of votes or character/byte count.

The edited sequence (the first version was mangled).
2 A 2 A Esc 2 A 2 A Esc 2 A 2 A Esc
2 A 2 A Esc 2 A 2 A Esc 2 A 2 A Esc
2 A 2 A Esc 2 A 2 A Esc A : w q Enter
Esc Backspace Backspace Backspace
Backspace Backspace : w q Enter
Should do the trick, if I'm counting my keystrokes correctly. No wait, is the escape key allowed?

All I get is a file containing ":wq" followed by a couple newlines.

Oops, I've mangled the sequence. Will fix in a moment.

Hmmm, what about the Vim cannot be closed requirement? I suppose the solution is simple enough: remove the two q's and one of the backspaces.

Also, by A, do you mean Shift+a ?

@asoundmove ah yes, missed that part. Removing both "q"s and a backspace should fix it. @Joey Adams; I mean Shift+A indeed, but this notation takes too much space, enough is enough!

Awesome. Well done. :)

I Backspace H E L LO , Space W O R LDEsc Shift+; W Enter I Backspace Backspace Backspace Backspace.
Produces "hello, world" in both.

34 keystrokes. Produces twenty-two A's followed by :x and a new line.
i Backspace
a a a a a a a a a a a
a a a a a a a a a a a
: x Enter Esc Backspace Backspace Backspace : x Enter


text:
The strange life of a beehive
Researchers recently discovered an interesting bee colony that lives in an
infinite field of honeycomb:

Each cell can house a bee or not. In fact, the lives of those creatures
appear to be a bit ... chaotic. It could be calculated that a colony
always starts with the following pattern:

(Bee drawn by
Emmanuel Boutet
on Wikimedia Commons. This
honeycomb-and-bees image thus is released under
CC-By-SA.
grumbles)
After that the bee's life cycles are divided into so-called generations.
Each generation old bees die and new ones hatch and it primarily depends
on their cell's neighbors:

If a bee has less than two neighbors it dies due to loneliness.
If a bee has more than three neighbors it dies due to overcrowding.
If a cell has two, three or four living bees in neighboring cells a new
bee hatches there in the next generation.

Dying bees don't die until the end of a generation so they still affect
surrounding cells that might hatch bees in the next generation.
Now that we know how such a colony works, we can simulate it through any
number of generations.
Input
Input is a single number N, given on standard input, terminated by a line
break. 0 ≤ N ≤ 150. This is the number of generations to simulate.
Output
Output is a single number, on standard output and optionally followed by a
single line break, which represents the number of living bees after N
generations.
Additional output on standard error is ignored.
Sample inputs
0
5
42
100

Sample outputs
6
44
1029
5296

Winning condition
Shortest code wins, as is customary in golf. In case of a tie, the earlier
solution wins.
Test cases
There are two tests scripts, containing identical test cases:

bash
PowerShell

Invocation is in both cases: <test script> <my program> [arguments],
e.g. ./test ruby beehive.rb or ./test.ps1 ./beehive.exe.
I know there are only 22 tests instead of 151 (mainly because solutions are often quite slow). Please refrain from
embedding the exact test cases instead of solving the task. These scripts
are a convenience for you to test whether a change still causes the
program to behave correctly; not that you can adapt your code to the
specific test cases.
Another note
This task was part of a golf contest held at my university during
2011-W24. The scores and languages of our contestants were as follows:

336 – C
363 – C
387 – C
389 – Haskell
455 – C

Our own solution was

230 – Ruby

This sounds a bit like Conway's game of life.

Of course; that's why it's tagged that way, too. It's very thinly veiled, indeed.

Ruby, 181 163 153 146 characters
h=[0]*4e4
[0,-200,201,202,2,3].map{|i|h[i]=1}
gets.to_i.times{h=h.map{[g=1,200,201].map{|x|g+=h[x]+h[-x]};g>5-h.rotate![-1]||g<3?0:1}}
p h.count 1

This implementation follows a standard approach using an array h (dimensions 200 x 200 flattened), where each element is either 0 (no bee) or 1 (bee included). The array [0,-200,201,202,2,3] describes the initial positions of bees (relative to any initial cell).
Input and output as specified above, passes all test cases defined.
Edit 1: changed back to a wrapping solution instead of the "additional space"-version (which was shorter in an intermediate version but now is several characters longer).
Edit 2: removed variable b completely.
Edit 3: warning: this edit made the program horribly slow. I thus reduced the dimensions to 200 each which still is sufficient for up to 150 iterations. Instead of indexing the array by a variable we constantly rotate the array forward. Not really good design, but now we are considerably below the 150.

Python, 152 characters
P=[0,2,3,1j,1+1j,1-1j]
for i in' '*input():Q=[p+d for d in(1,-1,1j,-1j,1j-1,1-1j)for p in P];P=set(p for p in Q if 1<Q.count(p)<5-(p in P))
print len(P)

This solution keeps track of bee locations with a set of complex numbers.  It is pretty slow because the inner loop is quadratic in the number of bees.  I've tested up to 50 and it works.

Python2.7 has set comprehensions

I thought of tracking the bees, but doing it with complex numbers like that is really neat! Also you can save 3 chars by replacing the for loop with an exec (like I did).

Python2.7 also has set literals, so you can write P={0,2,3,1j,1+1j,1-1j} and then use {p}<P to test for membership (saves 1 char)

Python, 171 169 158 chars
w=300
s=w*w
x=[0]*297
h=[1,1,0]+x+[1,0,1,1]+x+[1]+x*s
exec('h=[1<sum(h[(i+x)%s]for x in[-1,-w-1,-w,1,w+1,w])<5-h[i]for i in range(s)];'*input())
print sum(h)

I model the world as a 300*300=900000 1D array (h is actually bigger, but the end is not used), where a bee is a 1 and empty is 0. Size of 300 is fine because at most the growth would be of 2 in each dimension for each generation, and there is no more than 150 generations.
Here is a slightly ungolfed and commented version:
w=300 # width and height of the world
s=w*w
# create initial grid
l=[1,1]+[0]*298+[1,0,1,1]+[0]*297+[1]+[0]*s

for k in range(input()):
  h=l[:]

  for i in range(s):

    # for each point, compute the number of neighbors
    n=sum(map(lambda x:h[(i+x)%s],[-1,-w-1,-w,1,w+1,w]))

    # if that number verifies the conditions, put 1 here, if not put 0
    l[i]=1<n<5-h[i]

print sum(l)

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Implement strategy for Jacks or Better Video
You are dealt five cards from a single deck. Implement a strategy for Jacks or Better Video Poker that has an expected revenue of at least 99.46%. Output the cards you want to hold.
The shortest code wins.
You are not required to implement the suggested strategy. Optimum play is also acceptable.
Input is read from standard input, output is written to standard output. Cards are identified as pairs of number (2,...,9,T,J,Q,K,A) and suit (S,H,D,C - spades, hearts, diamonds, clubs): 3C - three of clubs, QH - queen of hearts.

Examples:
$ ./jacks                               |
3C JC 5C QC 3H                          |<< input
3C 3H                                   |<< output
$ ./jacks                               |
3C 4C 5C 6C 7C                          |<< input
3C 4C 5C 6C 7C                          |<< output

Is this a single deck?  It simplifies the logic because, for example, if a hand is 4 to a flush it can't have a 3 of a kind.

@Keith: Single deck.

Can we use T instead of 10, it would simplify things greatly!

@mellamokb: My bad. Yes. I'm updating now.

I did it!!!
import java.io.*;
// 427 lines 200
public class Base {

    static char suit (String tokens) {  return  tokens.charAt (1); }
    public static char num (String tokens) { return tokens.charAt (0);}

    public static void checkPair (String [] tokens)
    {
        for (int a = 0; a < 4; ++a)
        for (int b = a+1; b < 5; ++b)
            if (num (tokens [a]) == num (tokens [b]))
                System.out.print (tokens [a] + " " + tokens [b]);
    }

    public static void checkThreeKind (String [] tokens)
    {
        for (int a = 0; a < 3; ++a)
            if (num (tokens [a]) == num (tokens [a+1]))
                for (int b = 2; b < 5; ++b)
                    if (num (tokens [a]) == num (tokens [b]))
                        System.out.print (tokens [a] + " " + tokens [a+1] + " " + tokens [b]);
    }

    static void checkTwoPair (String [] tokens)
    {
        for (int i = 0; i < 5; i++)
        for (int j = 1; j < 5; j++)
            //First Increment is pair 1 2, followed by 1 3, 1 4, and 1, 5 then 2 3, 2 4, 2 5, then 3 4, 3 5 then 4 5
            if (num (tokens [i]) == num (tokens [j]))
                for (int y = 0; y <= 4; y++)
                    for (int x = 1; x <= 4; x++)
                        if ((i != y) && (j != x) && (y != x) && (i != j))
                            if (num (tokens [y]) == num (tokens [x]))
                                if ((tokens [i] != tokens [j]) && (tokens [i] != tokens [y]) && (tokens [j] != tokens [y]) &&
                                        (tokens [i] != tokens [x]) && (tokens [j] != tokens [x]) && (tokens [y] != tokens [x]))
                                    eblock (tokens);
    }

    static void checkHighFlush (String [] tokens)
    {
        if (suit (tokens [0]) == suit (tokens [1]) &&
            suit (tokens [0]) == suit (tokens [2]) &&
            suit (tokens [0]) == suit (tokens [3]) &&
            suit (tokens [0]) == suit (tokens [4]))
        {
            String outputString = "";
            for (int i = 0; i < tokens.length; i++)
                outputString  += tokens [i] + " ";
            System.out.println (outputString);
            System.exit (0);
        }
        for (int i = 0; i <= 4; i++)
            for (int j= 1; j<= 4; j++)
                //First Increment is pair 1 2, followed by 1 3, 1 4, and 1, 5 then 2 3, 2 4, 2 5, then 3 4, 3 5 then 4 5
                if (suit (tokens [i]) == suit (tokens [j]))
                    for (int y = 0; y <= 4; y++)
                        for (int x = 1; x <= 4; x++)
                            if ((i != y) && (j != x) && (y != x) && (i != j))
                            {
                                if (suit (tokens [i]) == suit (tokens [x]) &&
                                        suit (tokens [i]) == suit (tokens [y]))
                                {
                                    if ((tokens [i] != tokens [j]) && (tokens [i] != tokens [y]) && (tokens [j] != tokens [y]) &&
                                            (tokens [i] != tokens [x]) && (tokens [j] != tokens [x]) && (tokens [y] != tokens [x]))
                                        eblock (tokens);
                                }
                            }
    }

     static void checkFourKind (String [] tokens)
     {
        if (num (tokens [0]) == num (tokens [1]))
        {
            if (num (tokens [0]) == num (tokens [2]))
                if (num (tokens [0]) == num (tokens [3]) || num (tokens [0]) == num (tokens [4]))
                    eblock (tokens);
            if (num (tokens [0]) == num (tokens [3]))
                if (num (tokens [0]) == num (tokens [4]))
                    eblock (tokens);
        }
        if (num (tokens [1]) == num (tokens [2]))
            if (num (tokens [1]) == num (tokens [3]))
                if (num (tokens [1]) == num (tokens [4]))
                    eblock (tokens);
    }

    static void checkStraight (String [] tokens)
    {
        int [] ints = new int [5];
        for (int i = 0; i <= 4; i++)
        {
            switch (num (tokens [i]))        {
            case 'T': ints [i] = 10;
            case 'J': ints [i] = 11;
            case 'Q': ints [i] = 12;
            case 'K': ints [i] = 13;
            case 'A': ints [i] = 14;
            default:  ints [i] = num (tokens [i]) - '0';
        }
        }
        for (int i = 0; i <= 3; i++)
        for (int j= 1; j<= 4; j++)
            //First Increment is pair 1 2, followed by 1 3, 1 4, and 1, 5 then 2 3, 2 4, 2 5, then 3 4, 3 5 then 4 5
            if ((ints [i]+1) == ints [i+1])
                for (int y = 0; y <= 4; y++)
                    for (int x = 1; x <= 4; x++)
                        if ((i != y) && (j != x) && (y != x) && (i != j))
                        {
                            if (ints[i] + 2 == ints[y] && ints[i] + 3 == ints [x])
                            {
                                if ((tokens [i] != tokens [j]) && (tokens [i] != tokens [y]) && (tokens [j] != tokens [y]) &&
                                        (tokens [i] != tokens [x]) && (tokens [j] != tokens [x]) && (tokens [y] != tokens [x]))
                                {
                                    for (int a : new int[] {i, j, y, x})
                                        System.out.print (tokens [a] + " ");
                                    System.out.println ();
                                    System.exit (0);
                                }
                            }
                            java.util.Arrays.sort (ints);
                            if (( (ints [i]+1 == ints [j]) && (ints [i]+3 == ints [y]) && (ints [i]+4 == ints [x])))
                            {
                                for (int a : new int[] {i, j, y, x})
                                    System.out.print (tokens [a] + " ");
                                System.out.println ();
                                System.exit (0);
                            }
                        }
    }

    static void checkHighCard (String [] tokens)
    {
        int [] ints = new int [5];
        for (int i = 0; i <= 4; i++)
        {
            switch (num (tokens [i]))        {
            case 'T': ints [i] = 10;
            case 'J': ints [i] = 11;
            case 'Q': ints [i] = 12;
            case 'K': ints [i] = 13;
            case 'A': ints [i] = 14;
            default:  ints [i] = num (tokens [i]) - '0';
        }
        }
        int marker = 0;
        if (ints [0] > ints [1]) marker = 1;
        if (ints [1] > ints [2]) marker = 2;
        if (ints [2] > ints [3]) marker = 3;
        if (ints [3] > ints [4]) marker = 4;
        System.out.println (tokens [marker]);
    }

    static void eblock (String[] tokens)
    {
        for (int i = 0; i < 5; i++)
            System.out.print (tokens [i] + " ");
        System.out.println ();
        System.exit (0);
    }

    static void checkFullHouse (String [] tokens)
    {
        String [] test = new String [5];
        int counter = 0;
        int sum = 0;

        for (int i = 0; i <= 4; i++)
        test [i] = tokens [i];
        for (int i = 0; i <=4; i++)
        {
        for (int j = 1; j <= 4; j++)
        {
            if (num (test [i]) == num (tokens [j]))
                counter++;
        }
        if (counter > 1)
            sum++;
        counter = 0;
        }
        if (sum == 5) eblock (tokens);
    }

    public static void main (String [] args) throws IOException
    {
        String inputString = new BufferedReader (new InputStreamReader (System.in)).readLine ();
        String [] tokens = inputString.split (" ");
        java.util.Arrays.sort (tokens);
        checkFourKind (tokens);
        checkHighFlush (tokens);
        checkFullHouse (tokens);
        checkStraight (tokens);
        checkTwoPair (tokens);
        checkThreeKind (tokens);
        checkPair (tokens);
        checkHighCard (tokens);
    }
}

shouldn't the answer be golfed? even if there are no competitors, it's still code-golf

I made a first step towards golfing: Reduced from about 12k to about 6k. Roll it back if you don't like it.

This was my first post.  Thanks for editing, did I have it right?  How does one get points!?!


text:
Lottery Ball Problem
A woman works at a lottery ball factory.  She's instructed to open up a lottery ball creation kit composed of 1 red rubber ball and n strips of digits from 0 through 9.
She's instructed to do the following:

Starting with 1, write the current number on the ball using the digits available on the n strips.
Put unused digits into a bowl where they can be used later for when she runs out of available digits in step 1.
Open up another lottery ball creation kit and continue to step 1 for the next number.

The question is, at what number will she arrive at before she runs out of digits to write the number?  Edited: Given n where n is the number of digit strips from 0 through 9 provided in each lottery ball creation kit, write a program that can solve this (not trivially) in the least amount of time.
Edit:  Additional notes - 6 and 9 are different numbers.  Assume there are no limits to the number of digits that can be pasted on the ball.
Hint:  If she counted in base 2 rather than base 10, how would that change the result and would that be easier to calculate?  What could you derive from solutions in base 2?

Are 6 and 9 considered to be different ?

@Paul R, irrelevant. It's easy to prove that the first digit which runs out is 1.

I think we need some more detail.  The way I'm reading the question, she'll run out of digits on the strips at ball #111 (since there are only two 1's) and then need to go into the bowl.  Are we talking about running out of digits in the bowl?  That too should have a relatively simple solution, and I'm not sure it's interesting to see which language can be compiled most efficiently since there's not much room for algorithmic differences in a simple increment+check problem.

@Matthew, she can use the 1s from the bowl for 111. The solution will be somewhere just short of 10^10, so increment and check won't be the fastest approach.

How many digits can she fit on one ball ?

I think the shortest answer for this question will be something like print X.

@Alexandru: I think that's already covered by the "(not trivially)" clause.

@Peter I guess I'm confused about how you can do anything intelligent beyond increment and check without making it trivial. It seems kind of silly to take advantage of various properties of the problem while ignoring the obvious one, that it has a direct and fixed solution. I don't think this is a good question.

@matthew you can iterate through it through the magnitude; the digits you need for 1 through 1e(X+1) is equal to 10 times the digits you need for 1 through 1eX. plus 1e(X-1) for the ending digits (with some caveats though)

@Matthew, it should be possible to do something binary-searchy. (If anyone can be bothered to check which Project Euler problem is very similar to this question I might check my solution). But I agree that fixed mathematical problems are bad questions. Perhaps the problem should be fixed by making the number of strips in each kit an input variable?

All good points.  Making relevant corrections to the question.

@Matthew:  She places 1 on the ball and places the rest of that strip (0 and 2 through 9) in a bowl along with any additional strips (0 through 9) every number.  For example for n = 2, when she finishes with number 2, she's got 3 ones, 3 twos, and 4 of numbers three through nine at her disposal (she's gone through 4 digit strips total only to use a 1 digit and a 2 digit).

I'm assuming the result will be of the order of 10^21, i.e. a 21 digit integer, give or take a digit ? In which case 64 bit ints aren't going to be much use ?

@Paul, seems like a pretty good assumption with hindsight for n=2. Or 10^31 for n=3...

I think static value types are out of the question, in fact.

Found it: Project Euler problem 156 is related (but different).

@Peter Taylor: how can it be proven that the first digit to run out is 1?

@Lowjacker: I don't know about a formal proof, but it's fairly self-evident that the digits 1-9 all get consumed at the same aggregate rate over any given order of magnitude, but the 1s will always get used first, e.g. consider the ranges 1..9, 10..99, 100..999, etc.

@Lowjacker, let f(d, n) be the number of digits d used up by the first n balls. Then for d in [2,9], f(d-1, n) >= f(d, n). Proof: consider the set of (number, digit position) pairs which contribute towards f(d, n). Replacing the digit d at that position in that number you get a smaller number, so if the first number is <= n, the one with the digit replaced also is, and that contributes to f(d-1, n). QED. 1 is a special case because leading 0s are ignored.

@Peter Taylor I thought about your argument and don't come around one point. I think you'll have to add another argument. If I understand correctly, for f(2,21) the numbers 2, 12, 20 and 21 contribute. Replacing digit 2 by 1 we get numbers 1, 11, 10 and 11. Note that 11 is actually a duplicate but must not be counted twice for f(1,21)!

@Howard: incorrect. 11 must be counted twice for f(1, 21) because it contains the digit 1 twice.

@Peter Taylor. yes, it counts 2 ones. But that's not what I meant. You would take it a third time if you think of f(2,22) because then also 22 would be mapped to 11.

@Howard, no: 22 would be mapped to 12 and 21. I was quite careful to set up my replacements to only replace one digit at a time.

@Peter now I understand your point. thank you for the clarification.

@Neil: you say "Answer for n=1 is 199991 since technically 199990 is the last number she could make" yet the question says "what number will she arrive at before she runs out of digits". My understanding is that if she runs out of digits writing 199991, then the answer is the number before, hence 199990.

@atnnn You're right of course, though if you gave me 199991, I'd consider it the right answer anyway.

I’m voting to close this question because it's tagged [tag:fastest-code] but is missing details about the specs of the computer on which answers are timed etc.

edit 2: fixed
General solution for n > 1:
-- lottery2.hs

import System
import Control.Monad
import Data.Maybe

main = mapM_ print . map (solve . read) =<< getArgs

rdigits 0 = []
rdigits n = (n `mod` 10) : rdigits (n `div` 10)

digits = reverse . rdigits

undigits = foldl ((+) . (10*)) 0

c1 = c . digits

c [] = 0
c [0] = 0
c [_] = 1
c (0:xs) = c xs
c (1:xs) = d xs + c xs + undigits xs
c (x:xs) = c xs + x * (d xs - 1) + 10 ^ length xs

d xs = ds !! length xs

ds = map d' [0..]
  where d' n = c1 (10 ^ n - 1) + 1

maxVal n =
  fst . head . filter (uncurry $ (<) . (*n))
  . map (liftM2 (,) undigits c . (1:) . flip replicate 9) $ [0..]

search f p q a b = s f (uncurry p) q (a, f a) (b, f b)
  where
    s f p q a b
      | not (p a) = Nothing
      | fst a + 1 == fst b = guard (not $ p b) >> return (fst a)
      | a >= b = Nothing
      | q a b = maybe (s f p q k b) Just (s f p q a k)
      | otherwise = Nothing
        where k = ((fst a + fst b) `div` 2, f (fst k))

solve n = fromJust $ search c1 ((>=) . (*n)) q 1 m
  where
    m = maxVal n
    q (a, fa) (b, fb) = (a * n) - fa <= fb - fa

There seems to be a pattern here:

$ ghc -O --make lottery2.hs
Linking lottery2 ...
$ time ./lottery 1 2 3 4 5 6
199990
1999919999999980
19999199999999919999999970
199991999999999199999999919999999960
1999919999999991999999999199999999919999999950
19999199999999919999999991999999999199999999919999999940

real    0m3.580s
user    0m3.508s
sys     0m0.020s
$ time ./lottery 7 8 9 10 11 12
199991999999999199999999919999999991999999999199999999919999999930
1999919999999991999999999199999999919999999991999999999199999999919999999920
19999199999999919999999991999999999199999999919999999991999999999199999999919999999918
199991999999999199999999919999999991999999999199999999919999999991999999999199999999919999999917
1999919999999991999999999199999999919999999991999999999199999999919999999991999999999199999999919999999916
19999199999999919999999991999999999199999999919999999991999999999199999999919999999991999999999199999999919999999915

real    1m10.855s
user    1m3.868s
sys     0m0.324s

What answer did you get and how long did it take to get there ?

199990
real    0m0.742s
user    0m0.532s
sys     0m0.020s

That looks like the answer for only 1 strip of numbers - for 2 strips it should be of the order of 10^20.

Answer for n=1 is 199991 since technically 199990 is the last number she could make.  @Paul:  For n=2, actually it's a bit less.  Mind you, still not a small number..

@Neil Why do you think it is less? I thin you're right but do you have any "proof"? I did some tests with other bases than 10. Thus you can brute-force the solutions within reasonable times. It always scaled like (b^b)^(n-1) for base b and n strips and this I would assume something around 199990*10^10. The first few numbers even look like there is a quite simple formula behind, but it breaks for larger bases or strip numbers.

@atnnn I don't know if you can guarantee a correct result from your bisection algorithm. It is only defined if you know that there exists exactly one point where there is the cross over (i.e. c1 x <= n x and c1 (x+1) > n (x+1) ). But I suppose that there may be more than one in the function you try to solve.

@Howard: There is at least one 1 in each number in the range I bisect over, so there is only one cross over point

Sorry, that is a wrong assumption on my part. I will try to formalize my reasoning and adapt the code if necessary.

It's commendable that you found what seems to be the most efficient solution to solve the problem, though unfortunately the answers aren't correct.  If you get it right, you'll see a pattern begin to form.

@Neil: How did you get the answers?

I'm guessing that the answer for n = 2 should be 19999999999999999991 - is that right ?

@Paul R: No. writing all the numbers in [1..19999999999999999991] takes 47999999999999999992 ones, which is a lot more than 2 * 19999999999999999991

@Howard: I replaced my bisect function with a search function that tries all possible ranges

OK - maybe I got one too many 9s - how about 1999999999999999991 then ?

@Paul R: see my updated answer. I give my results for n in [1..12]

@atnnn: oh - sorry - I hadn't notice that you'd fixed it - congratulations. Not quite the pattern I was expecting, but neat all the same...

Congrats.  Nicely done.  :)

I'll give it to you, though it should be composed of only 1s and 9s (and 0s if it's the last number she could make). n=1:199991, n=2:1999919999999990, n=3:19999199999999919999999990.  Strange pattern isn't it?

@Neil: It is a strange pattern. How did you get those answers? I get c1 1999919999999981 = 3999839999999963, which is more than 2 * 1999919999999981.

@atnnn: I read it in a math enthusiast magazine and thinking about how I would implement a program to search for these values led me to make this code golf question.

@Neil: I figured it out. To get the answers from your magazine, you need to start with n-1 strips. It is like starting from 0 instead of 1, and finding the first number that uses up the last 1. If you start from 0, it is possible to write 1999919999999992 even though, after writing 1999919999999991, there are no 1s left in the bowl. But if you start from 1 and find the last number that can be written, then my answers are correct.

@atnn:  But you wrote 1999919999999980, not 1999919999999991 (or even 1999919999999990).

awk (109)
brute force solution
yes|awk -F "" '{c("0123456789",1);c(NR,-1)}function c(C,m,i){for($0=C;NF-i++;)if((t[$i]+=m)<0){print NR-1;exit}}'

The awk does not count in the character count if I understand the rules correctly.
The trick with yes| + NR is a shorter way to define a loop counter than a BEGIN + while or for clause.
Replace ,1 with ,[value of n]. With 1 it returns 199990, with 2 it is still trying to find the answer.
Could write it as:
yes|awk -F "" -v n=1 '{c("0123456789",n);c(NR,-1)}function c(C,m,i){for($0=C;NF-i++;)if((t[$i]+=m)<0){print NR-1;exit}}'

And replace n=1 with n=[whatever value] (now a parameter of the program, for an extra 6 characters plus the number of characters for the value of n. But like I said since it is still trying to compute for n=2, there may be no need to parameterise this version.
I'm sure there must be a much more clever algorithm than plain increment and count. Like a bit of algebra. No time for this... I'll leave that to someone else.

This is code-challenge rather than code-golf, so it doesn't matter whether awk counts or not.

We're dealing with enormous numbers, so large in fact that I think it makes choice of language irrelevant in the ultimate performance of the program.  As for your answer, it's technically 199991, since 199990 is the last number she could make.

@Neil: you said "what number she would arrive at before she runs out", so yes, I printed the last number before she ran out. You do not have enough digits to print 199991.

... I hate it when I'm wrong.

C
Here's a non-golf brute force solution in C which seems to give the right answer for 1 strip, but I haven't had the patience to let it run long enough to see if it gets to a solution for 2 strips (in fact if I extrapolate the progress output I'm not sure it will finish within my life-time !).
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    const int MAX_DIGITS = 24;
    char buff[MAX_DIGITS + 1];
    int num_strips = 1;
    int64_t digits[10] = { 0 };
    int64_t i;

    if (argc > 1)
    {
        num_strips = atoi(argv[1]);
        if (num_strips < 1 || num_strips > 2)
        {
            fprintf(stderr, "num_strips must be 1 or 2\n");
            exit(1);
        }
    }

    memset(buff, ' ', MAX_DIGITS - 1);
    buff[MAX_DIGITS - 1] = '1';
    buff[MAX_DIGITS] = '\0';

    for (i = 1 ; ; ++i)
    {
        int d;

        // add 2 to each remaining digit count

        for (d = 0; d < 10; ++d)
        {
            digits[d] += num_strips;
        }

        // update counts of remaining digits based on current i

        for (d = MAX_DIGITS - 1; d >= 0; --d)
        {
            char ch = buff[d];

            if (ch != ' ')
            {
                int digit = ch - '0';
                digits[digit]--;
            }
            else
            {
                break;
            }
        }

        // check to see whether we found solution

        for (d = 0; d < 10; ++d)
        {
            if (digits[d] < 0)
            {
                printf("Found solution at i = %s, digits = { %24lld %24lld %24lld ... %24lld }\n", buff, digits[0], digits[1], digits[2], digits[9]);
                goto done;
            }
        }

        // log progress when i == 2^n

        if ((i & (i - 1)) == 0)
        {
            printf("i = %s, digits = { %24lld %24lld %24lld ... %24lld }\n", buff, digits[0], digits[1], digits[2], digits[9]);
        }

        // increment "i"

        for (d = MAX_DIGITS - 1; d >= 0; --d)
        {
            char ch = buff[d];

            switch (ch)
            {
                case ' ':
                    buff[d] = '1';
                    break;
                case '9':
                    buff[d] = '0';
                    continue;
                    break;
                default:
                    buff[d] = ch + 1;
                    break;
            }
            break;
        }
    }
done:
    return 0;
}

Nice try, though exceeding n=2 for brute force is a mess.


text:
Find largest sum of subsequence
Given a sequence of integers find the largest sum of a subsequence (integers on consecutive positions) of the sequence. The subsequence can be empty (in which case the sum is 0).
Input is read from standard input, one integer per line. The largest sum must be written to standard output.
I wrote a small generator for you:
#include <stdio.h>
#include <assert.h>

/* From http://en.wikipedia.org/wiki/Random_number_generation */
unsigned m_w;
unsigned m_z;

unsigned get_random()
{
  m_z = 36969 * (m_z & 65535) + (m_z >> 16);
  m_w = 18000 * (m_w & 65535) + (m_w >> 16);
  return (m_z << 16) + m_w;  /* 32-bit result */
}

int main(int argc, char **argv)
{
  int i;

  assert(argc == 3);
  m_w = atoi(argv[1]);
  m_z = atoi(argv[2]);

  i = 10;
  while (i--);
    get_random();

  i = atoi(argv[2]);
  while (i--)
    printf("%d\n", (int) get_random() << 8 >> 22);

  return 0;
}

Examples:
$ printf "1\n2\n-1\n4\n" | ./sum
6
$ printf "0\n-2\n-3\n" | ./sum
0

$ ./a.out 1 1 | ./sum
387
$ ./a.out 1 10 | ./sum
571
$ ./a.out 1 100 | ./sum
5867
$ ./a.out 1 1000 | ./sum
7531
$ ./a.out 1 10000 | ./sum
27268
$ ./a.out 1 100000 | ./sum
101332
$ ./a.out 1 1000000 | ./sum
187480
$ ./a.out 1 10000000 | ./sum
666307

./sum is my solution
./a.out is the generator

Your solution must run in reasonable time for all tests above (mine runs in 1.2s on the last test case).
Shortest code wins.
Edit: Please provide an example run on one of the tests above.

You need #include <stdlib.h> for atoi().

My own c solution take 4 seconds for last test case, very interested about your solution.

Make sure you write first to a file and then read from file, and not use pipes.

I guess there is an error in your generator, line 25,while (i--); shouldn't end in an semicolon, should it?

assert(argc==3) :-) That's what I call a user friendly program! :-)

Ruby, 53 characters
p$<.inject(-1.0/s=0){|a,b|[s=[0,s+b.to_i].max,a].max}

Takes about 28 seconds for the last testcase here.

Python, 91 84 64 chars
s=m=0
try:
 while 1:s=max(s+input(),0);m=max(m,s)
except:print m

Takes about 14 12 72 seconds on the last test case.  Edit: using algorithm Paul R found. Edit: nixed the import, using input().

C, 100 characters

main(){char s[80];int i,m=0,n=0;while(gets(s)){i=atoi(s);n=n+i>0?n+i:0;m=m>n?m:n;}printf("%d\n",m);}

Run time = 1.14 s for final test case (10000000) on 2.67 GHz Core i7 with ICC 11.1 (previously: 1.44 s with gcc 4.2.1).
Note: The algorithm used for the above solution comes from Programming Pearls by Jon Bentley. Apparently this algorithm is known as Kadane's Algorithm.

Haskell (88 64)
Implementing Kadane's algorithm.
main=interact$show.maximum.scanr(\x->max x.(x+))0.map read.lines

Python - 114 chars
import sys
s=map(int,sys.stdin.readlines())
l=range(len(s)+1)
print`max(sum(s[i:j])for i in l[:-1]for j in l[i:])`

It surely isn't as fast as required, but it works allright.

This is O(N^2) which certainly doesn't meet requirements of the challenge.

Python, using dynamic programming - 92 chars
import sys
s=map(int,sys.stdin.readlines())
f=h=0
for x in s:h=max(0,h+x);f=max(f,h)
print f

J (34 33 characters)
This solution implements a variant of Kadane's algorithm and is reasonable fast.
echo>./0,([>.+)/\.0".];._2(1!:1)3

Here is an explanation:

u/ y – The verb u inserted between items of y. E.g., +/ 1 2 3 4 is like 1 + 2 + 3 + 4. Notice that all verbs in J are right-associated, that is, -/ 1 2 3 4 is like 1 - (2 - (3 - 4)) and computes the alternating sum of 1 2 3 4.
x >. y – the maximum of x and y.
x ([ >. +) y – The maximum of x and x + y. [ >. + is a verb in tacit notation and evaluates to the same as x >. x + y.
([ >. +)/ y – the non-empty prefix of y with the largest sum.
u\. y – u applied to all suffixes of y. Notice that special code handles the common case u/\. y such that this runs in linear instead of quadratic time.
([ >. +)/\. y – A vector denoting the largest non-empty subarray that starts at each position of y.
0 , ([ >. +)/\. y – 0 preprended to the previous result as 0 is the length of an empty subarray of y.
>./ 0 , ([ >. +)/\. y – The largest subarray of y.
0 ". ];._2 (1!:1) 3 – Standard input marshalled into a vector of numbers.
>./ 0 , ([ >. +)/\. 0 ". ];._2 (1!:1) 3 – The largest subarray in standard input.

Ruby, 68 chars
m=-2**31;n=0;$<.lines.map{|x|n+=x.to_i;n=0 if n<0;m=n if n>m};puts m

Also a bit slow, but completes the 1-10000000 tests in a bit over half minute, most of the time spent in the last test...
Indented version:
m=-2**31
n=0
$<.lines.map {|x|
  n+=x.to_i
  n=0 if n<0
  m=n if n>m
}
puts m

C++, 192 chars
#include <iostream>
#include <string>
#include <stdlib.h>
#define S std::
main(){long a=0,m=0,M=0;char s[9];while(S cin.getline(s,9)){a+=atoi(s);if(m>a)m=a;if(M<a-m)M=a-m;}S cout<<M<<S endl;}

Works reasonably fast on my laptop (4 seconds for the last test).

cstdlib not stdlib.h

{if((r+$1)>0)
   r=r+$1
 else r=0;
 if(m<r)
   m=r;
}
END{print m}

awk Code (66), very slow, 8+ seconds for last test case
dwang@dwang-ws ~/Playground/lss $ time ./random 1 10000000 | awk -f lss.awk
666307

real    0m6.705s
user    0m8.671s
sys 0m0.052s


text:
Add two vectors modulo 5
Interpret a triple of 32-bit integers as a vector of 32 integers modulo 5.  Write an addition routine for these vectors.
Example:
def add32((a0,a1,a2),(b0,b1,b2)):
    c0 = c1 = c2 = 0
    m = 1
    for i in range(32):
        a  = ((a0//m)&1) + 2*((a1//m)&1) + 4*((a2//m)&1)
        b  = ((b0//m)&1) + 2*((b1//m)&1) + 4*((b2//m)&1)
        c  = (a+b)%5
        c0+= m*(c&1)
        c1+= m*((c&2)//2)
        c2+= m*((c&4)//4)
        m += m
    return c0,c1,c2

Note:
You only need to be internally consistent, not consistent with my sample code.  If you use a different representation of the integers mod 5, that's fine as long as you provide a translation table of the form:
0 = 000 or 101
1 = 001 or 110
2 = 010 or 111
3 = 011
4 = 100

Scoring:
Characters + number of arithmetic operations required.  The sample code takes 331 characters and 34 operations per bit (note that I'm not counting the function call or iteration, nor interpreter overhead); hence gets a score of 331+1056=1686.
Clarification:
This is a trick called bitslicing.  It's natural to pack integers mod 5 directly into words (spaces added for clarity:
0 1 2 3 4 -> 000 001 010 001 101

but you end up sacrificing a few bits at the end of each word.  To keep your data aligned but pack the most in, store the data in slices
                 0 0 0 0 1 = a2
a = 0 1 2 3 4 -> 0 0 1 1 0 = a1
                 0 1 0 1 0 = a0

Example 2
A language-agnostic example was requested, so here it is.  Suppose we use the representation
0 = 100
1 = 001
2 = 010 or 101
3 = 110
4 = 011

and 111 and 000 are meaningless.  Then, the following sum is valid according to our representation:
                  1 0 0 1 1 0 1 0
0 1 2 2 3 4 0 2 = 0 0 1 0 1 1 0 1
                  0 1 0 1 0 1 0 0
+
                  0 1 0 0 1 0 1 1
1 2 1 2 0 1 0 3 = 0 0 0 1 0 0 0 1
                  1 1 1 0 0 1 0 0
---------------------------------
                  0 1 1 0 1 1 1 1
1 3 3 4 3 0 0 0 = 0 1 1 1 1 0 0 0
                  1 0 0 1 0 0 0 0

Remark
As Keith Randall has demonstrated, this can be done with all bits in parallel using logical operators.  We can view such a solution as a circuit with a certain number of gates.  Perhaps I should call this "circuit golf".  I chose 5 instead of 3 because it's too easy to brute-force (optimal is 6 gates/trit).

BORING!!! No more plain math, please.

Can you give some small samples, maybe using bytes instead of 32-bit ints.

I count 34 ops inside the loop, not 32.  By lines: 10 + 10 + 2 + 3 + 4 + 4 + 1 = 34.

Can you please give a language-agnostic description of what the code is supposed to do, and some sample input/output, or do you only want answers in Python ?

It is difficult to count the number of "ops" in different languages. If you take eg. Brainfuck, you need a lot of ops while in another language it might be only a few. That said, some languages provide more powerful ops than others, so the rating is a bit biased.

Python, score=215 166 (167 118 chars, at most 48 ops)
def A(x,y,z,p,q,r):
 u,c=x^p,x&p;v,d=y^q^c,y&q|y&c|q&c;w,e=z^r^d,z&r|z&d|r&d
 if e:u,v,w=A(e,e,0,u,v,w)
 return u,v,w

Does addition in bit-parallel.  The c,d,e are the 32 carries from one position to the next.  e represents multiples of 8 that carry out of the vector, so if e has any bits set in it, we add 8%5=3 back in using a recursive call.
The translation table is the same as the one given in the question.

You can save 43 chars by using single-digit names. And another 3 by concatenating assignments to d0,c0 and d1,c1 and d2,c2 by commas.


text:
Indent a string using given parentheses
Given the following input to the program:

List of block start characters
List of block end characters
A string to format

format the string with the blocks delimited by the two character sets indented.
Formatting is done with two spaces per level and the parentheses are placed as shown in the example below. You may assume the sets of opening and closing characters to be disjoint.
E.g. for {[(< and }])> as the opening and closing character sets and the following string:
abc{xyz{text[note{comment(t{ex}t)abc}]}}

the following output would be expected:
abc
{
  xyz
  {
    text
    [
      note
      {
        comment
        (
          t
          {
            ex
          }
          t
        )
        abc
      }
    ]
  }
}

You may not hard-code the list of “parentheses” characters. How input is given is not specified, though; this could be either command-line arguments or via standard input, as you wish.

Can we assume that for each parenthesis there's a closing one, and in the same order?

Does the program have to support any parenthesis characters given as arguments?  e.g. ./program 'p' 'q' <<< '1p23p45q67q8'  Or does it need only support {[(< and }])> ?

@Joey, I'd assume not, though that would be all the more impressive.

joey : input are 1. open parenthesis characters 2.close parenthesis chars 3. string to indent.   Juan : we can assume that, though code need not rely on that, what I mean is if delim is part of opening parenthesis chars, increase indent, else if part of closing parenthesis chars decrease indent.

I rewrote the task specification. Could you look over it and figure out whether that's roughly what you meant? I've tried to be clearer on the exact specifications as the previous wording gave rise to four wrong answers.

Another thing: Is this supposed to be a Code Golf? Your solution doesn't seem to imply this, but as a challenge it's fairly trivial. Please clarify.

considering forum yes you are right , changed answer to reflect the same. I was trying it in java and so posted it here !

Are leading/trailing newlines allowed?

Lowjacker assume that no newlines in the input

@Phrasant Bhate: And in the output?

Perl - 131 96 94 chars
$i="";for$_(split/([\Q$ARGV[0]$ARGV[1]\E])/,$ARGV[2]){$i=~s/..// if/[\Q$ARGV[1]\E]/;print "$i$_\n"if$_;$i.='  'if/[\Q$ARGV[0]\E]/;}

Seems like there should be room for eliminating common expressions, at least, but it's a quick take that handles the example, as well as Joey Adams's hypothetical about arbitrary brackets.

There was, indeed, plenty of room for improvement:
$_=pop;($s,$e)=map"[\Q$_\E]",@ARGV;for(split/($s|$e)/){print"  "x($i-=/$e/),"$_\n"if$_;$i+=/$s/}

...and still a little more:
$_=pop;($s,$e)=map"[\Q$_\E]",@ARGV;map{print"  "x($i-=/$e/),"$_\n"if$_;$i+=/$s/}split/($s|$e)/

Ruby, 106 101 96 95
s,e,i=$*
i.scan(/[#{z=Regexp.quote s+e}]|[^#{z}]*/){|l|puts'  '*(s[l]?~-$.+=1:e[l]?$.-=1:$.)+l}

Input is provided via the command line.

You can save 4 characters by using ~-j+=1 instead of (j+=1;j-1). Additionally, using $. everywhere instead of j allows you to remove the j=0, which saves another character.

JavaScript, 255 227 205 characters
Hey, its length fits perfectly in a byte! :D
function(s,e,t){R=eval.bind(0,"Array(n).join(' ')");for(i=n=0,b=r='';c=t[i++];)~s.indexOf(c)?(r+=b,b='\n'+R(++n)+c+'\n '+R(++n)):~e.indexOf(c)?b+='\n'+((n-=2)?R()+' ':'')+c+'\n'+(n?R()+' ':''):b+=c;return r+b}

It's a function, pass it the start characters, the end characters, then the text.

Your own edit comment has been used against you. :D

@Doorknob: I… I thought I had never done that. D: I am so sorry. (Were you hunting?)

@Doorknob: And thanks for reminding me about this; shortened :)

No I wasn't hunting, just stumbled upon this question, but I decided to, and I found this :O :P

Python – 162 chars
i=f=0
s=""
l,r,z=[raw_input()for c in'   ']
o=lambda:s+("\n"+"  "*i)*f+c
for c in z:
 if c in l:f=1;s=o();i+=1
 elif c in r:i-=1;f=1;s=o()
 else:s=o();f=0
print s

Note that the task calls for the two sets of parentheses to be part of the input, not hardcoded.

@Joey noted, I'll get around to fixing that in a while. Thanks

Python 2.7.X - 136 chars
import sys
a,c=sys.argv,0
for i in a[3]:
 if not(i in a[2]):print ' '*c+i
 else:print ' '*(c-4)+i
 if i in a[1]:c+=4
 if i in a[2]:c-=4

Usage : $ ./foo.py '(' ')' '(ab(cd(ef)gh)ij)'
Resulting Output:
(
    a
    b
    (
        c
        d
        (
            e
            f
        )
        g
        h
    )
    i
    j
)

Do you need the spaces after the print statements?

C - 213 209
I hate stupid mistakes... >.<
#include<stdio.h>
#include<string.h>
int main(int i,char**s){for(char q,r,c,t,a=0;~(c=getchar());t=q|r){q=!!strchr(s[1],c);a-=r=!!strchr(s[2],c);for(i=0;t|q|r&&i<2*a+1;putchar(i++?' ':'\n'));a+=q;putchar(c);}}

Reads left-parens from first command-line argument, right-parens from second argument, and input to indent on stdin.
Pretty-printed & commented:
int main(int i, char **s) {
  for (char q, r, /* is left-paren? is right-paren? */
            c,    /* character read from input */
            t,    /* last char was a paren-char */
            a=0;  /* indentation */
       ~(c = getchar());
       t = q|r) {
         q = !!strchr(s[1],c);
    a -= r = !!strchr(s[2],c);
    for (i=0; t|q|r && i<2*a+1; putchar(i++? ' ' : '\n'));
    a += q;
    putchar(c);
  }
}

C (159 225 chars)
#define q(s,c)strchr(s,c)
#define p(i,j,k)printf("\n%*s%c%c%*s",i,"",*s,k,j,"")
g(char*b,char*e,char*s){int i;for(i=0;*s;s++)q(b,*s)?p(i-2,i+=2,'\n'):q(e,*s)?q(b,*(s+1))||q(e,*(s+1))?p(i-=2,i-2,0):p(i-=2,i-2,'\n'):putchar(*s);}

It cost me 66 extra characters just to fix the bug with the empty lines :( Frankly, I need a fresh approach, but I'll call it a day for now.
#define p(i,j)printf("\n%*s%c\n%*s",i,"",*s,j,"")
f(char*b,char*e,char*s){int i;for(i=0;*s;s++){strchr(b,*s)?p(i-2,i+=2):strchr(e,*s)?p(i-=2,i-2):putchar(*s);}}

A rather quick & dirty approach. It has a bug of producing empty lines between consecutive closing parenthesis, but otherwise it does the job (or so I think). I will revisit it for a better & cleaner solution, sometime this week.
char *b is the opening parenthesis set, char *e is the closing parenthesis set and char *s is the input string.

Python3, 184 182 chars
import sys
_,p,q,t=sys.argv
i,f,x=0,1,print
for e in t:
 if e in p:f or x();x(' '*i+e);i+=2;f=1
 elif e in q:f or x();i-=2;f=1;x(' '*i+e)
 else:not f or x(' '*i,end='');f=x(e,end='')

Example:
$ python3 ./a.py '{[(<' '}])>' 'abc{xyz{text[note{comment(t{ex}t)abc}]}}'
abc
{
  xyz
  {
    text
    [
      note
      {
        comment
        (
          t
          {
            ex
          }
          t
        )
        abc
      }
    ]
  }
}

heinrich5991 suggested saving two characters by changing the second line to _,p,q,t=sys.argv

Scala(2.9), 211 characters
object P extends App{def x(j:Int)={"\n"+"  "*j}
var(i,n)=(0,"")
for(c<-args(2)){if(args(0).exists(_==c)){print(x(i)+c)
i+=1
n=x(i)}else{if(args(1).exists(_==c)){i-=1
print(x(i)+c)
n=x(i)}else{print(n+c)
n=""}}}}

Perl - 89 85 bytes
A version of Hojung Youn's answer which accepts the block characters via two arguments.
#!perl -p
BEGIN{$b=pop;$a=pop}s/([$a])|([$b])|\w+/"  "x($1?$t++:$2?--$t:$t)."$&
"/ge

Called like:
perl golf.pl<<<'abc{xyz{text[note{comment(t{ex}t)abc}]}}' '[{(<' ']})>'

Very nice concept, @Hojung and Sorpigal.  It is a bit fragile, though.  For example, swap the ] and } in the close-paren argument, and the ] closes the character class, leading to an unmatched paren error.  Similarly, suppose the open set starts with ^, perhaps to match v in the close set; you'll get the complement of the intended [$a] class.  That's why I used \Q...\E in my answer.  The \w+ for non-paren characters works for the example, but what about input like 'x(foo-bar)y' '(' ')'?  Of course, it isn't clear the code needs to handle something like that.

Groovy, 125
p=args;i=0;s={a,b->"\n"+"\t"*(b?i++:--i)+a+"\n"+"\t"*i};p[0].each{c->print p[1].contains(c)?s(c,1):p[2].contains(c)?s(c,0):c}

You can save the script in a file indent.groovy and try it with:
groovy indent.groovy "abc{xyz{text[note{comment(t{ex}t)abc}]}}" "{[(" ")]}"

I tried around in groovy for an hour before seeing your answer, I used a similar aproach, but mine is much longer than yours so I won't even bother to post.. Good job! :)

Python - 407
from sys import*;o=argv[1];c=argv[2];t=argv[3];p=0;n=False;a=lambda:h not in e;b=lambda s:print(s+(" "*p)+h);r="";e=o+c
for h in t:
 for k in o:
  if h==k:
   if(r in e)and(r!=""):b("")
   else:b("\n")
   p+=2;n=True;break
 for k in c:
  if h==k:
   p-=2
   if(r in e)and(r!=""):b("")
   else:b("\n")
   n=True;break
 if a()and n:print((" "*p)+h,end="");n=False
 elif a():print(h,end="")
 r=h

An ungolfed version of the program:
import sys

open_set = sys.argv[1]
close_set = sys.argv[2]
text = sys.argv[3]
spaces = 0
newline = False
a = lambda : char not in b_set
b = lambda s: print(s + (" " * spaces) + char)
prev = ""
b_set = open_set + close_set

for char in text:
    for bracket in open_set:
        if char == bracket:
            if (prev in b_set) and (prev != ""):
                b("")
            else:
            b("\n")
        spaces += 2
        newline = True
        break
    for bracket in close_set:
        if char == bracket:
            spaces -= 2
            if (prev in b_set) and (prev != ""):
                b("")
            else:
                b("\n")
            newline = True
            break
    if a() and newline:
        print((" " * spaces) + char, end="")
        newline = False
    elif a():
        print(char, end="")
    prev = char

The arguments to the program are (in order): the opening parentheses, the closing parentheses, and the text to indent.
Example ($ is command line prompt):
$ python indent.py "{[(<" "}])>" "abc{xyz{text[note{comment(t{ex}t)abc}]}}"
abc
{
  xyz
  {
    text
    [
      note
      {
        comment
        (
          t
          {
            ex
          }
          t
        )
        abc
      }
    ]
  }
}

php (187) (153)
function a($s,$o,$e){while(''!=$c=$s[$i++]){$a=strpbrk($c,$o)?2:0;$b=strpbrk($c,$e)?2:0;echo ($a+$b||$r)?"\n".str_pad('',$t-=$b):'',$c;$t+=$a;$r=$a+$b;}}

Function takes string, opening delimiters, ending delimiters as arguments.

C 284 Non White space Characters
I'm no fan of obfuscation  but well...
#include<cstdio>
#include<cstring>
#define g printf
#define j char
int main(int a,j**b){int c=0;for(j*f=b[3];*f!='\0';++f){if(strchr(b[1],*f)!=0){g("\n%*c\n%*c",c,*f,c+2,'\0');c+=2;}else if(strchr(b[2],*(f))!=0){c-=2;g("\n%*c",c,*f);if(strchr(b[2],*(f+1))==0)g("\n%*c",c,'\0');}else putchar(*f);}}

Usage: ./program start_brackets end_brackets string_to_parse

C, 256
Parameters:

e is the ending char,
n is the indentation,
b the opening brackets,
d the closing brackets.

I broke the code up to avoid the horizontal scrollbar.
#define r char
#define P(c) putchar(c);
#define N P(x)
#define W printf("%*s",n,"");
r*s,x='\n';i(r e,int n,r*b,r*d){r*t=s,*p;int l=0;W while(*s!=e)
{if(p=strchr(b,*s)){if(s!=t){N W}P(*s++)N i(d[p-b],n+2,b,d); N W
P(*s++);l=1;}else{if(l){N W l=0;}P(*s++)}}}

Complete program is 363 characters.
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#define r char
#define P(c) putchar(c);
#define N P(x)
#define W printf("%*s",n,"");
r*s,x='\n';i(r e,int n,r*b,r*d)
{r*t=s,*p;int l=0;W while(*s!=e)
{if(p=strchr(b,*s)){if(s!=t){N W}
P(*s++)N i(d[p-b],n+2,b,d); N W
P(*s++);l=1;}else{if(l){N W l=0;}
P(*s++)}}}main(int c,r*v[]){s =
v[3];i('\0',0,v[1],v[2]);}

Powershell, 146 Bytes
param([char[]]$s,[char[]]$e,[char[]]$f)$f|%{}{if($_-in$s){$o;'  '*$i+$_;$o='  '*++$i;}elseif($_-in$e){$o;'  '*--$i+$_;$o='  '*$i}else{$o+=$_}}{$o}

Ungolfed Explanation
param([char[]]$start,             # Cast as array of Chars
      [char[]]$end,
      [char[]]$string)
$string | foreach-object { } {    # For every char in string. Empty Begin block
    if ( $_ -in $start ) {        # If char is in start
        $o                        # Print stack ($o)
        '  ' * $i + $_            # Newline, indent, insert start char
        $o = '  ' * ++$i          # Set stack to ident (incremented)
    } elseif ( $_ -in $end ) {    # If char is in end
        $o                        # Print stack
        '  ' * --$i + $_          # Newline, decrement indent, insert end char
        $o = '  ' * $i            # Set stack to indent
    } else {
        $o+ = $_                  # Otherwise add character to stack
    }
} { $o }                          # Print remaining stack (if any)

C, 181 characters
#define d(m,f)if(strchr(v[m],*s)){puts("");for(j=f;j--;)printf("  ");}
i;main(j,v,s)char**v,*s;{for(s=v[3];*s;s++){d(1,i++)d(2,--i)putchar(*s);d(1,i)if(!strchr(v[2],*(s+1)))d(2,i)}}

Pretty much the most straightforward approach imaginable. Iterate through the string (v[3]), if it's a left brace (as defined in v[1]), increase the indent level, if it's a right brace (as defined in v[2]), decrease the indent level.


text:
Paint that fence
You are Tom Sawyer and you have to paint a fence of 102400 m long. Luckily, your friends decided to help you in exchange of various things. Each friend will paint L meters, starting from S with color C. S, L are integer amount of meters and 1 ≤ C ≤ 97. Getting bored you decide to find out how many meters of each color you have.
Input
Input is read from standard input. Each line contains three numbers S, L, C as described above.
Ouput
Output is written to standard output. For each color that appears on the final fence print the color number and the number of times it appears. Order by colors.
Examples
Input 0
                           ..............
0 3 1                      111...........
2 4 2                      112222........
1 2 3                      133222........
0 4 1                      111122........
7 3 5                      111122.555....

Output 0
1 4
2 2
5 3

Input 1
 0 100 1
 50 150 2

Output 1
 1 50
 2 150

Input 2
 500 1000 1
 0 2000 2

Output 2
 2 2000

More examples
Here is a small generator:
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>

/* From http://en.wikipedia.org/wiki/Random_number_generation */
unsigned m_w;
unsigned m_z;

unsigned get_random()
{
  m_z = 36969 * (m_z & 65535) + (m_z >> 16);
  m_w = 18000 * (m_w & 65535) + (m_w >> 16);
  return (m_z << 16) + m_w;  /* 32-bit result */
}

int main(int argc, char **argv)
{
  int i;

  assert(argc == 2);
  m_w = 0xbabecafe;
  m_z = atoi(argv[1]);

  i = 10;
  while (i--);
    get_random();

  i = atoi(argv[1]);
  while (i--) {
    int s = (int) ((get_random() << 8) % 102397);
    int l = (int) ((get_random() << 8) % (102397 - s));
    int c = (int) ((get_random() << 8) % 97 + 1);
    printf("%d %d %d\n", s, l, c);
  }

  return 0;
}

Running examples:
$ ./gen 1 | ./paint
6 535
$ ./gen 10 | ./paint
28 82343
36 3476
41 1802
49 4102
82 1656
$ ./gen 100 | ./paint
2 2379
22 17357
24 4097
25 1051
34 55429
42 9028
45 9716
66 1495
71 196
85 640
97 706
$ ./gen 1000 | ./paint
16 719
26 29
28 24
33 1616
55 371
65 35
69 644
74 16
84 10891
86 36896
87 50832
89 19
$ ./gen 10000 | ./paint
3 800
6 5712
14 3022
17 16
26 1
29 18770
31 65372
37 387
44 40
49 37
50 93
55 11
68 278
70 19
71 64
72 170
77 119
78 6509
89 960
97 15
$ ./gen 100000 | ./paint
2 6
8 26
12 272
24 38576
26 1
34 1553
35 8
36 19505
43 2
45 11
46 2
47 9
49 27339
50 139
53 3109
69 11744
92 89
$ ./gen 1000000 | ./paint
1 1
3 4854
6 523
13 1
16 11
18 416
22 7
24 3920
25 96
31 10249
32 241
37 1135
45 10
57 758
62 2348
65 11
66 7422
78 6
85 13361
87 3833
88 187
91 46
93 7524
96 45436

Your program must run in reasonable time. My solution runs in a few seconds on the last example.
Shortest code wins.
Include running time and your output for the last test.
EDIT: This problem is not intended to be brute-forced, so a trivial solution is not acceptable.

Seems to me that the simplest way (allocate array, fill it, count # of each color in array, output) would run in a reasonable time.  It seems like you intended coming up with an algorithm to be part of the challenge, though -- am I wrong?

I was thinking that 1000000 ops X 25000 average length = 25 * 10 ^ 9 would not run in reasonable time. I can increase the fence length if you think otherwise.

Ah, I missed that the input was a million lines, my bad.

Tom Sawyer would have used English measurements...

@Keith: ITYM Imperial Units: http://en.wikipedia.org/wiki/Imperial_units

Keith: I think you can assume that a Tom Sawyer today would be much more sensible and use SI.

Is it ok to post my own solution?

Python, 221 239 chars
import sys
F=[]
for L in sys.stdin:s,l,c=map(int,L.split());F=sum([[(a,min(b,s),d)]*(a<s)+[(max(a,s+l),b,d)]*(b>s+l)for a,b,d in F],[(s,s+l,c)])
C=[0]*98
for a,b,c in F:C[c]+=b-a
for c in range(98):
 if C[c]:print c,C[c]

Keeps F as an unordered list of triples (start of run, end of run, color) representing the current state of the fence.  Since the random painting in the generator overpaints larges swathes fairly frequently, this list is never too long (typically in the 15-40 range).
Runs in 37 seconds on the 1M example.

you can use G+=[(a,min(b,s),d)]*(a<s) etc. to get the for loop on  one line

for C in sorted(f[2] for f in F):print C,sum(b-a for a,b,c in F if c==C) saves a couple of characters over your last four lines, and avoids the need to know the magic number 98.

@Gareth: I think that would print duplicates if the same color was used by more than one range.  There would need to be uniqification in there somewhere...

You're right: it would need to be sorted(set(...)) which is no longer an improvement.

Haskell, 251 261 269 294 characters
import Data.List
w@(y@(f,d,e):z)§x@[a,b,c]|e<=d=z§x|a+b>d=(f,d,e`min`a):((f,a+b,e):z)§x
w§[a,b,c]=(c,a,a+b):w
r(c,a,b)=replicate(b-a)c
f l=shows(l!!0)" "++shows(length l)"\n"
main=interact$(>>=f).group.(>>=r).sort.foldl'(§)[].map(map read.words).lines

Something isn't quite right about this as it takes far too much time and stack... But it does produce the right answers:
$> ghc -O3 --make -rtsopts -with-rtsopts -K32m 3095-PaintTheFence.hs
Linking 3095-PaintTheFence ...

$> ./3095-gen 1000000 | time ./3095-PaintTheFence
1 1
3 4854
6 523
13 1
16 11
18 416
22 7
24 3920
25 96
31 10249
32 241
37 1135
45 10
57 758
62 2348
65 11
66 7422
78 6
85 13361
87 3833
88 187
91 46
93 7524
96 45436
       43.99 real        43.42 user         0.46 sys

Edit (294 → 269) replicate and group is just as efficient way of counting up the paint, and takes less code than the custom function s
Edit (269 → 261) no need for max call
Edit (261 → 251) no need for to cull paint 0 in f

It is too slow.

It's code-golf, no? For code-golf, usually restrictions like "reasonable time" mean, that for the target input size, it can't take days. Is there some criteria whereby 37 seconds (the other answer's time) is okay, but 44 seconds is too slow? I could just time mine on a faster CPU if you'd like!

In this case it should take a few seconds * language slowdown. Correct me if I'm wrong, but isn't Haskell much faster than Python? (which is why I didn't down vote Keith's solution). There was a C brute force solution posted that took around the same time which, by the rules, was not permitted.

Measured on the same machine, it does run much faster than the Python solution. The Python solution takes 133.556 seconds on my machine. The Haskell solution is 3x faster.
Also, note that this Haskell solution isn't a "brute force" solution (by which I'm guessing you mean simply building an array of colors the length of the wall.)

Perl - 148 bytes
It seems that Perl is the best to play with. easy to code shorter and faster. ;)
code:
#!perl -n
($a,$b,$c)=split;substr($s,$a,$b,chr($c)x$b)}BEGIN{$s="z"x102400}{$s=~s/([^z])\1*/$H{$1}+=length$&/ge;print ord," $H{$_}
"for sort keys%H

time:
time ./gen 1000000 | perl paint.pl
...
real    0m9.767s
user    0m10.117s
sys 0m0.036s

JavaScript, 183 chars, 1.3 seconds
Sadly, I did have to cut the stdin/out part of the requirement, which JavaScript doesn't support. Instead, I get the input from a file upload <input> instead (which I don't count in my char count, although I probably should).
Here is the ungolfed version. It's a function that takes the full input string... all 14MB of it! This is the one that takes 1.3 seconds; the golfed version takes about twice as long -- but it still beats the other solutions! Interestingly, it's twice as fast in Firefox than in Chrome. Live demo here.
function Q(input) {

    var c = [];
    var l = input.trim().split(/\s/g);
    input = null
    var length = l.length;

    // Loop through each meter of the wall...
    for (var i = 0; i <= 102400; i++) {

        // ...and loop through each of the friends, finding
        // the last one who painted this meter...
        for (var j = length; j > 0; ) {
            j -= 3;

            // Start = +l[j]
            // Length = +l[j + 1]
            // Color = +l[j + 2]

            var S = +l[j];
            if (S <= i && +l[j + 1] + S > i) {

                // ...and incrementing the color array.
                var C = +l[j + 2];
                if (!++c[C])
                    c[C] = 1;

                break;
            }
        }
    }

    console.log(c.map(function (a,b) {return b + ' ' + a}).filter(function (a) { return a }).join('\n'));
}

And here's the golfed version.
function G(i){l=i.trim(c=[]).split(/\s/)
for(i=0;i<102401;i++)for(j=l.length;j>0;)if(l[j-=3]<=i&&i-l[j+1]<l[j]){if(!++c[l[j+2]])c[l[j+2]]=1
break}for(k in c)console.log(k+' '+c[k])}

$ cat input.txt
0 3 1
2 4 2
1 2 3
0 4 1
7 3 5

$ cat input.txt  | perl -anE '@a[$F[0]..$F[0]+$F[1]]=($F[2])x$F[1];END{$i[$_]++for@a;$i[$_]&&say"$_ $i[$_]"for 1..$#i}'
1 4
2 1
5 3

$ cat input2.txt
500 1000 1
0 2000 2

$ cat input2.txt  | perl -anE '@a[$F[0]..$F[0]+$F[1]]=($F[2])x$F[1];END{$i[$_]++for@a;$i[$_]&&say"$_ $i[$_]"for 1..$#i}'
2 2000