text:
Markov Chain Beatbox Generator
Just an idea I had the other day: Making beats following a Markov Chain of predefined sounds.
I remember someone did a beatbox with Google Translate and the German language (follow the link and press listen).
So, the challenge is to build a text input to Google Translate from a given chain. Or you can use musical notes and play it yourself :).

You can make a program reading a line with the number of beats, another with their names and a matrix representation of the probabilities (you can choose the representation).
You may also make a function with those three arguments.
E.g.
[input]
20
pv zk bschk kkkk
[[.1, .4, .5, 0.],
 [.3, .2, .3, .2],
 [0., .3, .2, .5],
 [.1, .8, .1, 0.]]

[output] something like:
pv zk bschk zk pv bschk zk pv zk bschk kkkk pv bschk zk bschk bschk bschk zk kkkk bschk

The starting probability is the same for each beat.
That's not a code-golf challenge because I would like to see some nice solutions (be creative).
Extra points if you invent new beats and/or choose a table of probabilities that gives nice beats most of the time.
If you want, you can use real beats (In many languages it's easy to open .wav files, like the wave module in Python) and generate music! Here are some free sample beats.
I may post a reference implementation if needed.

Do you allow preprocessed forms of the matrix? That is, a form in which the numbers as such do not occur any more?

@hstoerr Yes. You can have it as function argument if you want

Please suggest a file hosting for sharing our random .WAVs :)

@belisarius Well I know Songcloud is good for that, but you can use any file hosting.

Would it be acceptable to use multiple-note prefixes in the model?

@Sparr Yes, if you want to.

I made these tracks:
http://soundcloud.com/belisarius/sets/golf-music
Using the following transition matrix:
{{10,  1,  3/2, 2},
 {1/2, 10, 3/2, 2},
 {1/2, 1,  10,  2},
 {1/2, 1,  3/2, 10}}

And the following program in Mathematica:
musicGen[n_, notes_, transMatrix_] :=
 Module[{
          im := IdentityMatrix[Length@notes],
          a  := Array[2^(# - 1) &, Length@notes],
          soundLength = .1  n,
          which
          },
  which[x_] := Position[x, 1][[1, 1]];
  Sound[Join[
    (SoundNote /@ notes[[
        which[#] & /@
         NestList[
          RandomChoice[transMatrix[[which@#]] -> im] &,
          RandomChoice@im,
          n - 1]
        ]]
     )
    ],
   soundLength]
  ]
tm = {{10, 1, 3/2, 2}, {1/2, 10, 3/2, 2}, {1/2, 1, 10, 2}, {1/2, 1, 3/2, 10}}
notesSet = {"Snare", {"Slap", "Shaker"}, {"OpenTriangle", "Maracas"}, "RideBell"};
m = Array[If[#2 == 5 || #2 == #1, 10, #2/2] &, {Length@notesSet,Length@notesSet}];
mg = musicGen[100, notesSet, tm]

Oh, nice. I tried make some sounds too, but I think there was something wrong with the beats I used (there was some silence between them).

It looks like you superposed the beats

@JBernardo There are four "chords" in the sample: 1) "Snare", 2) {"Slap" & "Shaker"}, 3) {"OpenTriangle" & "Maracas"}, 4) "RideBell"; That is the superposition you hear there

Being German, I was almost falling off my chair laughing at this creative abuse of our language. :-)
Here is some Scala. I am encoding the probabilities in a map that maps the beat to a list of successor beats in which the beats occure with a frequency proportional to their probability. An infinite lazy evaluated stream of beats is created, whose first 10 beats are skipped to get the appropriate randomness of the first output beat. We return the appropriate number of beats from the beginning of that stream. I use the type parameter T to be shorter and generic.
def markovChain[T](length : Int, nodes : Seq[T], probabilities : Map[T, Seq[T]]) : Seq[T] = {
  def randomElement(seq : Seq[T]) = seq(Random.nextInt(seq.length))
  def chain(node: T): Stream[T] =
    Stream.cons(node, chain(randomElement(probabilities(node))))
  return chain(randomElement(nodes)) drop(10) take(length)
}

which can be called like this:
val nodes = List("pv", "zk", "bschk", "kkkk")

val probabilities = Map(
  "pv" -> List("pv", "zk", "zk", "zk", "zk", "bschk", "bschk", "bschk", "bschk", "bschk"),
  "zk" -> List("pv", "pv", "pv", "zk", "zk", "bschk", "bschk", "bschk", "kkkk", "kkkk") ,
  "bschk" -> List("zk", "zk", "zk", "bschk", "bschk", "kkkk", "kkkk", "kkkk", "kkkk", "kkkk"),
  "kkkk" -> List("pv", "zk", "zk", "zk", "zk", "zk", "zk", "zk", "zk", "bschk"))

markovChain(20, nodes, probabilities) foreach (s => print (s + " "))

I wrote a Javascript function. However, it have begun beatboxing itself...
function bschk(jk,pv,kkkk){jkjk='pv jk bschk kkkk'.split(' ');boom='indexOf';eval(
function(jkpv){for(pvpv=0,bschkpv='';pvpv<jkpv.length;jkpvpv=jkpv[pvpv++].split(' '),
bschkpv+=String.fromCharCode(jkjk[boom](jkpvpv[0])+jkjk[boom](jkpvpv[1])*4+jkjk[
boom](jkpvpv[2])*16+jkjk[boom](jkpvpv[3])*64));return bschkpv}((
'bschk jk bschk jk  kkkk kkkk bschk jk  bschk pv kkkk jk  pv bschk bschk pv  bschk '
+'jk kkkk jk  jk pv bschk jk  bschk pv kkkk jk  pv pv bschk pv  jk jk bschk jk  jk '
+'kkkk kkkk pv  bschk kkkk kkkk jk  bschk kkkk kkkk jk  pv bschk bschk pv  jk kkkk '
+'pv jk  jk pv bschk jk  pv jk kkkk jk  pv bschk bschk jk  bschk kkkk bschk pv  bsc'
+'hk pv kkkk jk  jk pv bschk jk  bschk kkkk bschk jk  pv jk bschk jk  kkkk kkkk bsc'
+'hk jk  jk kkkk bschk jk  pv bschk bschk pv  jk bschk bschk pv  bschk bschk bschk '
+'pv  pv pv kkkk jk  bschk jk kkkk jk  bschk kkkk bschk pv  pv kkkk bschk jk  jk jk'
+' bschk jk  bschk kkkk bschk jk  kkkk jk bschk jk  pv jk kkkk jk  pv bschk bschk j'
+'k  jk bschk bschk pv  pv kkkk bschk pv  jk bschk bschk jk  jk kkkk kkkk pv  pv pv'
+' kkkk pv  pv kkkk bschk pv  bschk jk bschk jk  pv kkkk bschk pv  kkkk jk bschk jk'
+'  pv kkkk bschk pv  kkkk pv bschk jk  kkkk bschk bschk jk  kkkk pv bschk jk  kkkk'
+' bschk bschk jk  bschk pv bschk jk  kkkk kkkk bschk jk  kkkk kkkk bschk jk  jk kk'
+'kk bschk jk  jk kkkk kkkk pv  kkkk jk bschk pv  kkkk jk bschk pv  kkkk bschk kkkk'
+' pv  jk bschk bschk jk  pv kkkk kkkk pv  bschk bschk bschk jk  kkkk bschk bschk j'
+'k  kkkk bschk kkkk pv  jk bschk bschk jk  kkkk bschk bschk pv  kkkk bschk bschk p'
+'v  jk bschk bschk pv  kkkk bschk kkkk jk  kkkk pv bschk jk  kkkk bschk bschk jk  '
+'kkkk pv bschk jk  kkkk bschk bschk jk  bschk pv bschk jk  kkkk kkkk bschk jk  kkk'
+'k kkkk bschk jk  jk kkkk bschk jk  kkkk bschk bschk pv  jk kkkk kkkk pv  pv pv kk'
+'kk jk  bschk jk kkkk jk  kkkk bschk jk jk  jk jk bschk jk  jk kkkk jk jk  kkkk bs'
+'chk bschk pv  kkkk jk bschk pv  pv pv bschk pv  kkkk jk bschk pv  kkkk bschk kkkk'
+' pv  kkkk jk bschk jk  jk kkkk kkkk pv  jk kkkk pv jk  jk pv bschk jk  pv jk kkkk'
+' jk  pv bschk bschk jk  bschk kkkk bschk pv  bschk pv kkkk jk  jk pv bschk jk  bs'
+'chk kkkk bschk jk  pv jk bschk jk  kkkk kkkk bschk jk  jk kkkk bschk jk  pv bschk'
+' bschk pv  jk bschk bschk pv  kkkk bschk kkkk pv  bschk jk bschk jk  jk kkkk kkkk'
+' pv  jk kkkk bschk pv  jk pv kkkk pv  kkkk bschk kkkk pv  kkkk jk kkkk jk  pv bsc'
+'hk bschk jk  jk bschk bschk jk  pv kkkk bschk jk  jk jk bschk jk  pv bschk bschk '
+'pv  kkkk jk bschk jk  bschk kkkk kkkk pv  jk kkkk kkkk pv  pv pv kkkk pv  jk bsch'
+'k bschk pv  kkkk jk bschk jk  jk kkkk bschk pv  jk kkkk kkkk pv  kkkk bschk bschk'
+' jk  kkkk bschk bschk jk  kkkk bschk bschk jk  kkkk bschk bschk jk  kkkk bschk jk'
+' jk  jk jk bschk jk  jk kkkk jk jk  kkkk bschk jk jk  kkkk bschk bschk pv  kkkk b'
+'schk bschk pv  bschk jk bschk jk  jk kkkk jk jk  kkkk bschk kkkk pv  jk jk bschk '
+'jk  jk kkkk kkkk pv  bschk jk bschk jk  kkkk bschk kkkk pv  jk kkkk kkkk jk').split
('  ')));return ckckboom;}

Usage example : bschk(20,'pv jk bschk kkkk'.split(' '),[[.1,.4,.5,0],[.3,.2,.3,.2],[0,.3,.2,.5],[.1,.8,.1,0]])

Just a reference implementation in Python:
from random import random

def find(num, pdf):
    ''' Find position of number in CDF from PDF (must sum 100%) '''
    cdf = (sum(pdf[:i+1]) for i in range(len(pdf)))
    for i,j in enumerate(cdf):
        if num < j:
            return i

def build(t, beats, table):
    node = int(random()*len(table))
    nodes = [node]
    for i in range(t-1):
        node = find(random(), table[node])
        nodes.append(node)
    return ' '.join(beats[i] for i in nodes)

And a test program:
table = [[.1, .4, .5, 0.],
         [.3, .2, .3, .2],
         [0., .3, .2, .5],
         [.1, .8, .1, 0.]]

print(build(20, 'pv zk bschk kkkk'.split(), table))

And some outputs:
pv zk bschk zk kkkk zk bschk kkkk zk zk zk bschk kkkk zk bschk zk pv bschk kkkk zk
zk bschk kkkk zk zk kkkk zk bschk kkkk zk bschk zk pv zk pv zk zk bschk kkkk bschk
kkkk zk zk pv bschk bschk zk zk kkkk zk kkkk zk zk kkkk zk pv zk bschk kkkk zk

But none of them makes a really good beatbox because there's too much kkkk :).


text:
Determining the winner of a Chess game
Challenge
Being someone who plays far too much chess in his spare time, I thought I'd set a code golf challenge inspired by the game of chess (with a software flavour), for those interested.

The challenge is to determine the winner of a game of standard chess given a PGN (Portable Game Notation) file as input -- or in the case of a draw/stalemate, be able to recognise it.
Write a full program that takes via the standard input stream a PGN file except the final result string and outputs the winner of the game. (See the Wikipedia article for a simple description of the text format.) The program should determine the winner from the provided move information and output 1-0 for White winning, 0-1 for Black winning, and 1/2-1/2 for a draw (by stalemate). Mutually agreed draws and resignations should be denoted ? since they cannot be differentiated on this basis alone. White is always assumed to move first.
Note that the Result metadata tag nor the game result at the end of the PGN block itself is to be included in any input, as this must be determined by the program's algorithm. The checkmate symbol (usually #) is also never present. All other metadata and comments are valid input to the program.

Example (from Wikipedia page):
Input:

[Event "F/S Return Match"]
[Site "Belgrade, Serbia Yugoslavia|JUG"]
[Date "1992.11.04"]
[Round "29"]
[White "Fischer, Robert J."]
[Black "Spassky, Boris V."]
[Result "1/2-1/2"]

1. e4 e5 2. Nf3 Nc6 3. Bb5 {This opening is called the Ruy Lopez.} 3... a6
4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 d6 8. c3 O-O 9. h3 Nb8  10. d4 Nbd7
11. c4 c6 12. cxb5 axb5 13. Nc3 Bb7 14. Bg5 b4 15. Nb1 h6 16. Bh4 c5 17. dxe5
Nxe4 18. Bxe7 Qxe7 19. exd6 Qf6 20. Nbd2 Nxd6 21. Nc4 Nxc4 22. Bxc4 Nb6
23. Ne5 Rae8 24. Bxf7+ Rxf7 25. Nxf7 Rxe1+ 26. Qxe1 Kxf7 27. Qe3 Qg5 28. Qxg5
hxg5 29. b3 Ke6 30. a3 Kd6 31. axb4 cxb4 32. Ra5 Nd5 33. f3 Bc8 34. Kf2 Bf5
35. Ra7 g6 36. Ra6+ Kc5 37. Ke1 Nf4 38. g3 Nxh3 39. Kd2 Kb5 40. Rd6 Kc5 41. Ra6
Nf2 42. g4 Bd3 43. Re6 1/2-1/2

Output: ?
(since it was a mutually agreed draw)
Rules
Other than mentioned in the problem statement, there are no further restrictions. You may write the program in any compiled/interpreted programming language. The code for the program must be complete, i.e. compile without any modifications or external reference.
The aim as always is to solve the task with the smallest number of characters of code.
(Saying that, I can't promise to accept the answer with the shortest code. I'll also be looking at elegance of the code and time complexity of the algorithm, especially in the case of verbose language, and hope others will do the same!)
My Solution
I'll be attempting an F# solution while this question is open -- will post it here when I have something.

Format
Please post your answers in the following format for the purpose of easy comparison:

Language
Number of characters: ???
Fully golfed code:
(code here)

Clear (ideally commented) code:
(code here)

Any notes on the algorithm/clever shortcuts the program takes.

Migrated from StackOverflow, per request.

There is no way to determine the result in your example - it was an agreed-upon draw.

@BlueRaja-DannyPflughoeft: You're right. That's a really bad example! I'll try to replace it soon. Let's assume for now that it's an actual checkmate or stalemate, alright?

@BlueRaja-DannyPflughoeft: Actually, I take that back. An agreed-upon draw can be determined easily, because after the last move it will neither be checkmate nor stalemate, and all games are assumed to be complete.

The majority of actual games end neither in stalemate nor checkmate but in resignation or offer and acceptance, so this is an impossible task.

@Peter: Then output that it's unfinished. ;) Quite possible.

@Noldorin: If the last move is neither stalemate nor checkmate, it could be a resignation or an agreed-upon draw.

Various unnecessarily combative comments deleted. Acceptance is at the discretion of the asker, but [code-golf] implies that minimum length (along with correctness) is the primary criterion for a good solution.

Ruby 1.9
Number of characters: 93
Assuming that all inputs are valid games, and that games always end in checkmates or stalemates (as per Noldorin's response in the comments), then we only need to check who played the last move and whether it was a checkmate or not.
Golfed code:
*a,b,c=$<.read.gsub(/{[^}]*}|;.*$/,"").split;puts c=~/#/?(b=~/[^.]\.$/?"1-0":"0-1"):"1/2-1/2"

Ungolfed code:
# read entire input
game = $<.read
# strip comments
game = game.gsub(/{[^}]*}|;.*$/,"")
# split the input and get the last two words
*rest, second, last = game.split
# check if the last move has a checkmate symbol
if last =~ /#/
# if so, then determine whether the last move is white or black based
# on the number of periods in the second-to-last word
  puts second =~ /[^.]\.$/ ? "1-0" : "0-1"
else
# if not, then it's a draw
  puts "1/2-1/2"
end

Sneaky! This does indeed solve the challenge. I think I'm going to have to edit the original task slightly, to make it more challenging I'm afraid...sorry.

Python 3 (with python-chess)
Number of characters: 173 168 150 130
-5 characters thanks to Unrelated String
import io,chess.pgn as c
g=c.read_game(open(0))
b=g.board()
for m in g.mainline_moves():b.push(m)
print(b.result().replace(*'*?'))

Figured I might as well do this, since I already studied python-chess to answer another chess challenge.
Attempt This Online! - the provided test case (outcome cannot be determined)
Attempt This Online! - an example of a stalemate
Attempt This Online! - an example of a checkmate
Attempt This Online! - an example of a real game that ended by threefold repetition at move #34w, extrapolated to hypothetical move #38w to make this program detect a draw
Attempt This Online! - an example of a real game that ended by threefold repetition at move #25b, extrapolated to hypothetical move #29b to make this program detect a draw

I can't get either version to work on repl.it, but would this work for 168?

@UnrelatedString Thanks, that does work. In what way did it not work for you on repl.it? Just click Run (at which point you should see a blank screen with a cursor on the top right), then paste the same text into it as I put in the TIO link's Input box, press Enter, then press Ctrl+D. It then prints 1/2-1/2 for me. And pasting the challenge's example in the same way does print the result ?.

source: Stack Exchange

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

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

sort: votes


text:
Solve the knapsack problem
Knapsack Problem
(Actually, this is a subset of real knapsack problem.... - there's nothing to optimize!)
The knapsack problem is:

Given positive integers , and an integer S, find non-negative integers  satisfies

... or in (my bad) English...

Suppose you have many stuffs which weights , find configurations of those stuffs which weights S.

Problem

Find all configurations of stuffs, which information is given by input.

Input
You can make your own format, but you should enable users to input the sum of stuffs(S), weights of stuffs , and names of each stuffs.
Stuffs' name may contain [a-zA-Z0-9 _] (alphanumeric + _ + space).
You may assume that the input is correct,  are positive, and S is non-negative.
For example, consider this pseudo-real world situation, where a man orders appetizers worth exactly $15.05:

A possible input is:
1505
215 Mixed fruit
275 French fries
335 Side salad
355 Hot wings
420 Mozzarella sticks
580 Sampler plate

Output
Print all possible configurations (no same configurations, one configuration per one line, each line contains pairs of amount of a stuff and name of the stuff).
Stuff with zero amount can be omitted.
If there's no configuration possible, simply print X.
Example
Input and output format (and order) can be vary.
This is JS code I made roughly:
var s=prompt(),a=s.split('/'),b=[],c,i=1,t=a[0];while(i<a.length){c=a[i].split(/^([^ ]*) /);c.shift();b.push(c);i++;}
var d=[],l=b.length,p=0,_=0;for(i=0;i<l;i++)d[i]=0;
function as(x,y){for(var i=0,s=0;i<x.length;i++)s+=x[i][0]*y[i];return s}
function cs(x,y){for(var i=0,s='';i<x.length;i++)s+=y[i]+' '+x[i][1]+', ';return s}
while(p>=0){
    p=0;
    while((q=as(b,d))>=t){
        if(q==t){console.log(cs(b,d));_=1}
        d[p]=0;p++;if(p>=l){p=-1;break;}
        d[p]++;
    }
    if(p==0) d[0]++;
}
if(!_) console.log('X');

Input
1505/215 Mixed fruit/275 French fries/335 Side salad/355 Hot wings/420 Mozzarella sticks/580 Sampler plate
Output
7 Mixed fruit, 0 French fries, 0 Side salad, 0 Hot wings, 0 Mozzarella sticks, 0 Sampler plate,
1 Mixed fruit, 0 French fries, 0 Side salad, 2 Hot wings, 0 Mozzarella sticks, 1 Sampler plate,

Input
5/1 A/1 B/1 C
Output
5 A, 0 B, 0 C,
4 A, 1 B, 0 C,
3 A, 2 B, 0 C,
2 A, 3 B, 0 C,
1 A, 4 B, 0 C,
0 A, 5 B, 0 C,
4 A, 0 B, 1 C,
3 A, 1 B, 1 C,
2 A, 2 B, 1 C,
1 A, 3 B, 1 C,
0 A, 4 B, 1 C,
3 A, 0 B, 2 C,
2 A, 1 B, 2 C,
1 A, 2 B, 2 C,
0 A, 3 B, 2 C,
2 A, 0 B, 3 C,
1 A, 1 B, 3 C,
0 A, 2 B, 3 C,
1 A, 0 B, 4 C,
0 A, 1 B, 4 C,
0 A, 0 B, 5 C,

Input
10/20 A/11 B
Output
X

Input
250/35 Portal 2/21 Minecraft/12 Braid
Output
5 Portal 2, 3 Minecraft, 1 Braid,
2 Portal 2, 8 Minecraft, 1 Braid,
2 Portal 2, 4 Minecraft, 8 Braid,
2 Portal 2, 0 Minecraft, 15 Braid,

Input
250/33 Portal 2/21 Minecraft/12 Braid
Output
X

Winner
Since this is the code golf game, person with shortest code win.
If two codes have same length, then a code with highest votes win.

How does it make sense to count \n but not \r?  That's just favoring certain platforms, and/or tools that don't care which you use.

@Matthew It's for Windows - since it uses \r\n while Linux uses \n, the amount of code in Windows is increased by number of lines.

Wait, does Mac use \r?

OK, -1 then.  There are so many things wrong with that (besides the bias that is in no way related to the problem).  To start: I use Linux line endings in my files on Windows, and the code samples here don't tell you what's what.

@MatthewRead I removed that. If you can't understand example inputs and outputs (BTW, the dirty javascript code is for testing purpose..), then I'll tell you that first input example is same to the input under A possible input is:.

This has been beaten to death already, the consensus is that line endings are equal on whatever platform, no need to discuss/even mention it over and over again.  http://meta.codegolf.stackexchange.com/questions/167/line-break-formats-and-character-numbers

xkcd is on SE?

Python, 185 chars
S,C,N=input()
R=range(len(C))
F=lambda i,w:sum([[x+[j]for x in F(j,w-C[j])]for j in R[i:]],[])if w>0 else[[]][w<0:]
for L in F(0,S):print[(L.count(i),N[i])for i in R];S=0
if S:print'X'

run it with input like this:
echo "[1505,[215,275,335,355,420,580],['MF','FF','SS','HW','MS','SP']]" | ./knapsack.py

which encodes S, a list of costs, and a list of item names corresponding to those costs.
It outputs list of item counts and item names:
[(7, 'MF'), (0, 'FF'), (0, 'SS'), (0, 'HW'), (0, 'MS'), (0, 'SP')]
[(1, 'MF'), (0, 'FF'), (0, 'SS'), (2, 'HW'), (0, 'MS'), (1, 'SP')]

 Mathematica, 59 chars
Tally/@IntegerPartitions[#1,All,#2/._[x_,_]->x]/.#2/.{}->X&

Invoke with
%[1505, {215 -> "MF", 275 -> "FF", 335 -> "SS", 355 -> "HW", 420 -> "MS", 580 -> "SP"}]

Ruby, 136 characters
a,*b=*$<
c=->s,u,e{f,*r=e;f ?(0..s/h=f.to_i).map{|n|c[s-n*h,u+[n.to_s+f[/ .*/]],r]}:s>0?[]:u*?,}
r=c[a.to_i,[],b].flatten
puts r[0]?r:?X

Input must be given on STDIN, one line for the total amount and then one line per item (weight, followed by space, followed by name).
Example input:
250
35 Portal 2
21 Minecraft
12 Braid

Output:
2 Portal 2,0 Minecraft,15 Braid
2 Portal 2,4 Minecraft,8 Braid
2 Portal 2,8 Minecraft,1 Braid
5 Portal 2,3 Minecraft,1 Braid

Python, 356 characters
I took a slight hit for reading from the command line:
from sys import argv
x=int(argv[1])
t=argv[3::2]
c=argv[2::2]
n=len(t)
s=[0]*n
d=1
g=1
while d:
    i=0
    s[i]+=1
    while int(c[i])*s[i]>x:
        s[i]=0
        if i+1>=n:
            d=0
        else:
            i+=1
            s[i]+=1
    if d and sum(map(lambda y:int(c[y])*s[y],range(n)))==x:
        g=0
        print zip(t, s)
if g:print"X"

Example input:
python stuff.py 1505 215 'Mixed fruit' 275 'French fries' 335 'Side salad' 355 'Hot wings' 420 'Mozzarella sticks' 580 'Sampler plate'

Output:
[('Mixed fruit', 7), ('French fries', 0), ('Side salad', 0), ('Hot wings', 0), ('Mozzarella sticks', 0), ('Sampler plate', 0)]
[('Mixed fruit', 1), ('French fries', 0), ('Side salad', 0), ('Hot wings', 2), ('Mozzarella sticks', 0), ('Sampler plate', 1)]

JavaScript (V8), 225 bytes
(t,k,l,a=d=0)=>[...Array(t+1)].flatMap((_,j)=>[...Array(k[L="length"]**j)].map((_,i)=>eval("r=[];while(j-r[L])r.push(i%k[L]),i=i/k[L]|0;r")).filter(p=>(a=m=d=0,p.map(i=>(a+=k[i],d|=i<m,m=i)),a==t&&!d)).map(p=>p.map(i=>l[i])))

I had a bunch of really neat ideas for how to golf this but they ended up not working.

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


text:
Hexadecimal To Decimal
Read input of up to 8 characters presented as hexadecimal number and print this number as decimal number. In case that input can not be presented as hexadecimal input it has to print 0
Rules:
It is not allowed to use any function that takes or returns strings/characters, beside function that reads string/char from input and return strings/char as-is, function that takes integer and prints that integer to output as decimal number and function (if needed) that takes character and return its ASCII/UNICODE represented integer.
Shortest code wins
Example input
C0cAc01a
output
3234512922

I'm not sure whether I understood the rules right; is it: (No fun a except (b, c, d)) or is it (No fun (a, except b), c, d)?

You are not allowed any functions that returns or accepts chars/strings except mentioned one. Is that clear?

@ralu you should narrow that down. Operators are functions. Methods are functions. If only in/out is accepted, how are we supposed to compute anything?

So im not quite sure here.. The function tonumber in lua is not allowed or is it?
I can do it in 38 characters if thats allowed.

Ruby, 74 characters
n=0;p gets.gsub(/./).all?{|x|n=n*16+(x>?9?9:0)+x.ord%16;/[\da-f]/i=~x}?n:0

Input must be given on STDIN. With command line option -ln (counted as 4) it can be shortened to 69 characters.
n=0;p chars.all?{|x|n=n*16+(x>?9?9:0)+x.ord%16;/[\da-f]/i=~x}?n:0

With options -ln you mean $_.chars instead of chars probably?

Haskell, 114 106
x#y=16*x+mod y 16
main=getLine>>=print.maybe 0(foldl(#)0).mapM(`lookup`zip"ABCDEF0123456789abcdef"[-6..])

Handles input of arbitrary size.

c -- 181
Input passed on the commandline (one argument only). Relies on K&R function typing defaults. ASCII specific, but has no reliance on the language or library to know how to parse numbers. Lots of characters given up to specifying a large integer type for this purpose.
#include <stdio.h>
main(int c,char**v){unsigned long b=0;char*d=v[1]-1,e;while(e=*++d){
e-=(e>96)?87:(e>64)?55:(e>57)?33:(e>47)?48:0;if(e>15){b=0;break;}
b=b*16+e;}printf("%lu\n",b);}

Ungolfed:
#include <stdio.h>
main(int c,char**v){
  unsigned long b=0;
  char*d=v[1]-1,e;
  while(e=*++d){
    if(e>'`')e-=87; // reduce lowercase letters to 10--
    if(e>'@')e-=55; // reduce uppercase letters to 10--
    if(e>'9')e-=33; // reduce punctioation immediately above the
                      // digits so it does not iterfere
    if(e>'/')e-='0';// reduce digits to 0-9
    if(e>15){b=0;break;} // terminate immediately on bad input
    b=b*16+e;
  }
printf("%lu\n",b);}

Validation:
$ gcc -o dehex dehex_golfed.c
$ ./dehex C0cAc01a
3234512922
$ ./dehex 1
1
$ ./dehex 1f
31
$ ./dehex g
0
$ ./dehex 1g
1
$ ./dehex 1:2
0

input 1:2 should return 0

Spoil sport. Pfffsssssththththth...and fixed.

Since you use *d quite often I think you can assign it to a new variable (while(z=*++d)...) and save some chars.

Yes. I'd meant to get around to that.

Just saw another one you may use for each if: if(e>96)e-=87; => e-=e>96?87:0; or if you like e-=(e>96)*87;. With latter you can also combine all those ifs into one expression.

Oh. That's cute. But you can't combine the ()* form the logic depend on sequence points between each operation (e must get updated). Another "ah!"...you can chain the trinary conditionals.

Ah sorry for the confusion. That's what I meant.

I don't see anything in your code that depends on the difference between signed and unsigned arithmetic (at least assuming two's complement representation, which seems reasonable enough), so you could just lose the unsigned  to save 9 chars.  Also, you could use while(e=e>15?b=0:*++d) to get rid of the break.

The unsigned was to get the largest available integer space supported by the '89 standard. because 16^8 = 2^32 means that a 32 bit signed integer wouldn't have the range to support the specified input. True, long is a 64 bit value on most modern machines but that isn't guaranteed so I wrote the code to get as close as possible to guaranteeing it consistent with the standard. The while improvement is nice.

Well, it was introduced in the c99 spec, but you could use long long to guarantee at least 64 bits without library dependence. You could also move the variable declaration to the global scope in order to take advantage of the fact that global variables automatically attain the value of 0 on creation. You can also save 7 characters by putting the &&e>15 condition in to the while loop, getting rid of if(e>15){b=0;break;}, and use e>15?0:b as the number variable for the printf.

main(c,v)char**v; is 2 shorter than main(int c,char**v)

JavaScript, 127 119 characters (thanks trinithis!)
Code-Golfed:
function f(n){for(o=i=0,c=1;l=n[i++];)o*=16,l=l.charCodeAt(0),o+=l-(l>96?87:l>64?55:48);return /[\W_g-z]/i.test(n)?0:o}

Formatted:
function hexToDec(hexChars) {
    //Iterate through hex chars
    for (dec=i=0,count = 1; hexChar = hexChars[i++];) {
        dec *= 16;
        hexCharCode = hexChar.charCodeAt(0);

        //Get the hex number and add it
        hex = hexCharCode;
        if(hexCharCode > 96){
            hex -= 87;//For lower case letters
        } else if (hexCharCode > 64){
            hex -= 55;//For upper case letters
        } else {
            hex -= 48;//For numbers
        }
        dec += hex;
    }

    //Return 0 if invalid, decimal value otherwise
    if(/[\W_g-z]/i.test(hexChars)){
        return 0;
    }
    return dec;
}

/[^(0-9|a-f|A-F)]/ -> /[^0-9|a-f|A-F]/ -> /[^0-9|a-f]/i -> /[\W_g-z]/i

return n.match(/regex/)?0:o -> return!/regex/.test(n)&&o

@trinithis:  Thanks much, you are a regex-rockstar!  For the second one, I changed match to test, but decided to keep the original flow so it would return 0 instead of false for bad hex numbers (saved 1 char instead of 2).  Thanks again!

o=i=0,c=1 -> o=i=0, /[\W_g-z]/i.test(n)?0:o -> o*!/[\W_g-z]/i.test(n), o*=16,l=l.charCodeAt(0),o+=l-(l>96?87:l>64?55:48) -> o=o*16+(l=l.charCodeAt(0))-(l>96?87:l>64?55:48)

Ruby 1.9 (84)
gets.chomp!;n=0;p~/[^0-9A-Fa-f]/?0:($_.chars{|c|o=c.ord-48;n=16*n+(o>9?o%32-7:o)};n)

If we're allowed to use command line options, this is shortened to 72 characters + 4 for -ln:
n=0;p~/[^0-9A-Fa-f]/?0:($_.chars{|c|o=c.ord-48;n=16*n+(o>9?o%32-7:o)};n)

Python, 106 characters
n=0
e=9e9
for c in raw_input():n=n*16+ord(c)-[e,48,e,55,e,87,e][sum(c>x for x in'/9@F`f')]
print[n,0][n<0]

Scheme, 24 chars
(string->number(read)16)

I hope this is not considered cheating. If it is:
(string->number(string-append "#x"(read)))

String to number conversion is mandatory.
In Scheme, if your program is not simple, something is wrong and you should start over until it is made simple. Scheme's power relies on removing restrictions instead of adding features so that the language can be easily extended. Scheme is, with Lisp-derived languages, a programmable programming language.

you are not following the rules

D 194 chars
void main(string[] a){ulong r;foreach(c;a[1]){switch(c){case '0'..'9':r+=c-'0';break;case 'a'..'f':r+=c-'a'+10;break;case 'A'..'F':r+=c-'A'+10;break;default: write(0); return;}r*=16;}write(r);}

I could get some profit by replacing the char literals with the numerals and get thus get rid of the +10 for the a-f but this doesn't depend on char encoding though D defines ascii support IIRC

Mathematica, 64
By the rules:
FromDigits[#-If[#<58,48,If[#<97,55,87]]&/@ToCharacterCode@#,16]&

JavaScript, 48 chars
function h(n){return 0/0==+("0x"+n)?0:+("0x"+n)}

Formatted + Uncompressed
function h(n){
    if(+("0x"+n)==NaN) {
        return 0;
    }
    else {
        return +("0x"+n);
    }
}

 The plus operator set before a string converts it into a decimal number. So I just had to prepend a "0x" and return 0 if it isn't a valid number to conform the rules.

Arguably, operators are just shorthand built-in functions, so in a way this is violating the rule "It is not allowed to use any function that takes or returns strings/characters". We also have two standard loopholes for these kinds of terminology quibbles.

@MartinBüttner JavaScript's plus operator is not intended to convert int to string. The language just automatically converts the string to an int because it saw the plus. Also there is no builtin function to add two numbers.

function h(n){return+('0x'+n)||0} does the same in 33 chars.

Groovy, 74
i={it.inject(0){a,v->a*16L+('0123456789abcdef'.indexOf(v.toLowerCase()))}}

test case:
assert 3234512922 == i('C0cAc01a')

Not sure I understood the rules, though.

Perl, 39 characters
print<>=~m/^[[:xdigit:]]{1,8}$/?hex$&:0

I kind of feel weird doing it this way in Perl but I believe it follows the rules, since the hex() function is a language construct and not a library function. If not...
Perl, 64 characters
print<>!~m/^[[:xdigit:]]{1,8}$/?0:unpack 'L',reverse pack'H8',$&

I hope is fine.

C# - 192 189
oldschool, uses Console arguments for input, Console.WriteLine() for output. could possibly save a few chars, but can't get rid of most lengthy keywords. Makes evil use of foreach, ternary operator madness, bitwise complement ~ and signedness.
Reads any length input and aborts on bad characters ([^0-9a-fA-F]).
namespace _{class _{static void Main(string[]a){long b=0;foreach(int c in a.Length>0?a[0]:"")b=b<<4|(c-'0'<10?c-'0':c-'A'<6?c-'A'+10:c-'a'<6?c-'a'+10:~0L);System.Console.Write(b<0?0:b);}}}

A little deobfuscated (old ver):
using System;
namespace CodeGolf
{
    class Program
    {
        static void Main()
        {
            long ret = 0;
            int nextChar;

            while ((nextChar = Console.Read()) != '\r')
            {
                ret <<= 4;
                ret |= nextChar - '0' < 10 ?
                        nextChar - '0' :
                        nextChar - 'A' < 6 ?
                            nextChar - 'A' + 10 :
                            nextChar - 'a' < 6 ?
                                nextChar - 'a' + 10 :
                                ~0L;
            }

            Console.WriteLine(ret < 0 ? 0 : ret);
        }
    }
}

Would love to see a C# implementation in hardcore MSIL ;)

Python, 98 chars
print sum(16**n*i for i,n in zip(((ord(c)|32)-[48,87][c>'9']for c in raw_input()[::-1]),range(9)))

A one-liner with the nifty bonus that you can use characters > 'f' for shorthand notation, e.g 'g' counts for 16, 'h' for 17 etc :D

Mathematica 93 92 chars
Fold[16 #1 + #2 &, 0,ToExpression[Characters@n /. Thread@Rule["a"~CharacterRange~"f", 10~Range~15]]]

Not as streamlined as Mr.Wizard's answer, but I'll include it for variety. It makes use of no native base conversion routines.  There is a shortcoming in my answer: I assumed that characters a to f would be given in lowercase.

Perl - 77 chars
@h{0..9,'a'..'f'}=0..15;$n+=$h{lc$_}*16**($a++-1)for reverse split//,<>;say$n


text:
JAxH obfuscated method, not text
A JAPH is a grand tradition of making a program that prints "Just another Perl hacker,". We already have a question about JAPH on this site but they seem more concerned with hiding the text, but JAPH has always been more about hiding the method by which it does what it does. Therefore I challenge you to show off your favorite language's cool features, and don't worry too much about hiding the text (unless you want to).
Here's mine, in Perl, which shouldn't be to hard for an experienced velociraptor to understand, but may be interesting for others.
(*STORE,*TIESCALAR)=map{eval"sub{$_}"}qw'map{print&&sleep$|}split//,pop bless\$|++';tie$t,main;$t="Just another Perl hacker,\n"

Judged subjectively on votes by you guys, lets see some mind-benders!

Maybe you should update the Wikipedia article on JAPH, because most of its examples seem to be about hiding the text.

@PeterTaylor, Ok there are plenty that DO try to hide the text, and those are not wrong, but I wanted one that did explore the method. See for example many of those posted in http://www.cpan.org/misc/japh

"shouldn't be to hard for an experienced velociraptor to understand, but may be interesting for others" that's true of any Perl program, I don't belong to the velociraptor category so I'll just give you my obfuscated Hello World in Bash as a form of revenge _2=($_1/*/*); ${_2[34]} -${_2[34]:5:1}'\110\145\154\154\157\54\40\127\157\162\154\144\41'

C
Must be compiled to 32bit. On 64bit machines use gcc -m32 or such.
#include <stdlib.h>

int main() {
    char *c = "echo Just another C hacker";
    int foo=123; //unused                          /* Warning: there's a
    int k=(int)1                                    * (long) system
    //now for the fun part!                         * of chinese boxes
    //behold:                                       * in this code. */
    +0;
    -1;
    ((int(*)(char *))k)(c);
}

Disclaimer: not my idea. I found it years ago hidden in some piece of code. Seriously. Theirs was even better, I forgot several little details. But the gist is there.
When you see it, you'll sh*t bricks.

What the...? Can you explain how/why this works?

HA! @arshajii, it's all smoke and mirrors. I don't want to explain it away here, but read the code more closely.

... That's fairly horrible. +1

@Hasturkun Thanks. I did strive for the worst. For a moment I considered putting an "rm -rf ~" somewhere, but it'd have been unkind ;-)

@breadbox Gah! How does it work?! :-P something to do with (long) system maybe?

(1*system+0)("echo Just another C hacker");

@DoorknobofSnow Nested/conflicting comments hide the fact that line 6 is fully uncommented and extends to line 9.

@bread Ah! The /* is commented out! facepalm :-P

Select the text from /* to */.

Not sure if this helps or hurts but gcc lets you drop the char * in the next to last line. Alternatively, you can see what happens when you replace it with another type :)

 Mathematica:
TextRecognize@
 ImageAssemble@
  Transpose@
   ImagePartition[Import@"https://i.stack.imgur.com/S9fci.png", 5]

Dart
class Print{
  var PrinT,print,prinT;
  get PRint() => PrinT;
  get pRInt() => 'A$prinT';
  get pRint() => print;
  set pRInt(PrinT){print=PrinT;}
  set prInt(pRInt){prinT='n$pRInt';}
  Print(prinT,PRINT){
    PrinT = prinT;
    prInt = PRINT;
  }
  PRINT(print,PrinT){
    pRint.PRint('$print ${pRint.pRInt} $PRint $PrinT');
  }
  Print.print(print,prinT){
    pRInt = new Print(print,'other');
    PrinT = prinT;
  }
}
main(){
  Print print = new Print.print(print,'Dart');
  print.PRINT('Just','Hacker');
}

Edit : less boring setter, less boring getter.
I have studied this language for a day, so I think other people may think this as a child's mess... :(

props for early adoption, I will bend my rules and vote you up. Lets see what the judges (community) thinks

I agree with Joel.

PRNG
It's in C, but it actually shows off that you can do cool things using PRNGs and outputs Just another PRNG hacker:
#include <stdio.h>

#define P 0x3A4B5C6D

char s[6];
int j, t;

void r(int d) {
  t = ((P * d + P) << 17) + ((P * d - P) >> 15) + P;
  for (j = 0; j < 5; j++) {
    s[j] = (t % 51) + 67;
    t /= 51;
    if ((s[j] >= 91) && (s[j] <= 96)) s[j] = 32;
  }
  printf("%s", s);
}

int main() {
  r(0x444C725);
  r(0x2D65DD4B);
  r(0x6C5C71A);
  r(0xB2A4BBD);
  r(0x275BD6F);
  return 0;
}

Using the built-in PRNG (srand, rand) would be possible, too, but less portable.

WOW. what... I... oh man

C
int main(int _)
{
    putchar(~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
    putchar(-~-~-~-~-~-~-~-~-~-~-~-~-~
    putchar(~-~-~-~-~-~-
    putchar(-~-~-~-~-~-~-~-~
    putchar(-~-~
    putchar(~-~-~-~-~-~-~-
    putchar(-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
    putchar(~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
    putchar(-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
    putchar(~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
    putchar(-~-~-~-~-~-~-~-~-~-~-~-~-~
    putchar(~-~-~-
    putchar(~-~-~-~-~-~-~-~-~-~-~-~-
    putchar(-~-~-~-~-~
    putchar(-~
    putchar(-~-~-~-~-~-~-~-~-~-~-~-~-~
    putchar(-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
    putchar(~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
    putchar(-~
    putchar(~-~-
    putchar(-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
    putchar(-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~_
    ))))))))))))))))))))));
}

Python
credits.__class__(0,'Just another Python hacker')()

What is obfuscated about this?

The method, of couse

Javascript
eval('Acy419yt=12-14;'.split('').map(function(x){return String.fromCharCode(
0240-x.charCodeAt(0))}).join(''))[_]((___='splitulengthureverseujoinufilter'
.split('\x75'),function __(_){return _[___[1]]?__(_[___[0][0]+___[___[3]](''
)[___[0]]('')[___[4]](function(_,__){return ~~(__/2)==1})[___[3]]('')+'ce'](
1))+_[0]:_}("Just Another JavaScript Hacker"))[___[0]]('')[___[2]]()[___[3]](''));

In my code, JAJSH text was encrypted by reversing it, not only once, but twice!! Ha! Can you find it?

QBasic
Here's my implementation in QBasic.  The program must be called "JAQBH.BAS" in or for this to execute properly, as it reads its own source as part of the program.  And I couldn't find any sane way of determining the name of the currently running script.
COMMON SHARED JAQBH$
COMMON SHARED F$
IF F$ = "" THEN F$ = "A.BAS"
OPEN F$ FOR OUTPUT AS #1
PRINT #1, JAQBH$
DATA 20,16,28,24,16
DATA "Just Another QBasic Hacker"
OPEN "JAQBH.BAS" FOR INPUT AS #2
FOR i% = 1 TO 5
        READ l%
        y$ = INPUT$(l%, #2)
        PRINT #1, y$
        y$ = INPUT$(2, #2)
NEXT
CLOSE #1
CLOSE #2
F$ = "CON"
READ JAQBH$
CHAIN "A.BAS"

is there any good way to compile or run qbasic under ubuntu? I tried a google search, installed freebasic and its giving me all kinds of errors.

this might work - http://repl.it/
(Uh, just tried it for this and it fails.)

I don't imagine any online versions would allow writing of files

Perhaps you could run it in DOSBOX

I tested it in DOSBOX and it works perfectly.

good to know, I will give it a try soon

Haskell
I did this one with some help.
{-# LANGUAGE ForeignFunctionInterface #-}

import Control.Applicative
import Control.Monad
import Foreign
import Foreign.C

foreign import ccall "stdio.h puts"
    puts :: CString -> IO ()

main :: IO ()
main = liftM2 allocaBytes length
       ((<*> puts) . ((>>) .) . flip (flip zipWithM_ [0..] . pokeElemOff))
     $ map (fromIntegral . fromEnum) "Just another Haskell hacker\0"

And just for fun:
{-# LANGUAGE ForeignFunctionInterface #-}

import Control.Exception
import Control.Monad
import Data.Bits
import Data.Word
import Foreign
import Foreign.C

foreign import ccall "stdlib.h realloc"
    c_realloc :: Ptr a -> CSize -> IO (Ptr a)

foreign import ccall "stdlib.h free"
    c_free :: Ptr a -> IO ()

foreign import ccall "stdio.h puts"
    c_puts :: CString -> IO ()

-- | Write a UTF-8 character into a buffer.
--
-- Return the length of the character in bytes, which will be a number from 1-4.
pokeUtf8 :: Ptr Word8 -> Char -> IO Int
pokeUtf8 ptr char =
    case (fromIntegral . fromEnum) char :: Word32 of
        c | c <= 0x7F -> do
            put ptr c
            return 1
        c | c <= 0x7FF -> do
            put ptr                 (0xC0 .|. c `shiftR` 6)
            put (ptr `plusPtr` 1)   (0x80 .|. c .&. 0x3F)
            return 2
        c | c <= 0xFFFF ->
            if c >= 0xD800 && c <= 0xDFFF
                then replacement
                else do
                    put ptr                 (0xE0 .|. c `shiftR` 12)
                    put (ptr `plusPtr` 1)   (0x80 .|. c `shiftR` 6 .&. 0x3F)
                    put (ptr `plusPtr` 2)   (0x80 .|. c .&. 0x3F)
                    return 3
        c | c <= 0x10FFFF -> do
            put ptr                 (0xF0 .|. c `shiftR` 18)
            put (ptr `plusPtr` 1)   (0x80 .|. c `shiftR` 12 .&. 0x3F)
            put (ptr `plusPtr` 2)   (0x80 .|. c `shiftR` 6 .&. 0x3F)
            put (ptr `plusPtr` 3)   (0x80 .|. c .&. 0x3F)
            return 4
        _ -> replacement
    where
        put p c = poke p (fromIntegral c :: Word8)
        replacement = pokeUtf8 ptr '\xFFFD'

withUtf8 :: String -> (CStringLen -> IO a) -> IO a
withUtf8 string action = expand nullPtr 64 0 string where
    expand buf bufsize pos str = do
        buf' <- c_realloc buf (fromIntegral bufsize)
        when (buf' == nullPtr) $ do
            c_free buf
            ioError $ userError "Out of memory"
        write buf' bufsize pos str

    write buf bufsize pos str
        | bufsize - pos < 4 = expand buf (bufsize * 2) pos str
        | otherwise = do
            case str of
                (c:cs) -> do
                    len <- pokeUtf8 (buf `plusPtr` pos) c
                    write buf bufsize (pos + len) cs
                [] -> do
                    pokeByteOff buf pos (0 :: Word8)
                    finish buf pos

    finish buf len =
        finally (action (buf, len)) (c_free buf)

puts :: String -> IO ()
puts str = withUtf8 str (c_puts . fst)

main :: IO ()
main = puts "\x266B Just another C hacker using Haskell \x266B"

JavaScript
Run in console
({}+[])[!''+!''+!![]] + (!![]+[])[!''+!''] + (![]+[])[!''+!''+!''] + (!![]+[])[+![]] + ({}+[])[!![]+!''+!''+!''+!''+!''+!''] + (![]+[])[+!![]] + ([][{}]+[])[+!![]] + ({}+[])[+!''] +
(!![]+[])[+![]] + 'h' + (![]+[])[!''+!''+!![]+!![]] + (!![]+[])[+!![]] + ({}+[])[!![]+!![]+!''+!''+!''+!''+!''] + ({}+[])[!![]+!''+!![]] + (![]+[])[!![]+!''+!![]] +
({}+[])[!![]+!![]+!![]+!![]+!''+!![]+!![]] + 'h' + (![]+[])[+!![]] + ({}+[])[!![]+!![]+!''+!![]+!![]] + 'k' + (![]+[])[!''+!![]+!![]+!''] + (!![]+[])[+!'']

Python 2.x (single expression)
Now, while this is quite easy to figure out for Pythoneers, others might find it at least interesting. If you wonder why there's so many lambdas, I wanted to have maximum underscoreness, but minimal repetition. Who doesn't love underscores? Ideone
(lambda ______________:(lambda ______,_______,________:(lambda _____:(lambda _,___,__,____,_____________:(lambda _________,__________:(lambda ___________,____________:___________(____________,____[_________**(_________+__________)-__________::_________+_________+_________]+_[__________::_________]+__[_________+__________])(____________,______________))((lambda _,__:________(______(_))[__]),(________(__import__(_[_________]+__[_________*_________+__________]+_[_________]))[_[_________:_________+_________]+___[__________/_________]+__[__________]+_____(u'')[__________/_________]+_[_________+__________]])))((_____________(_)+_____________(_))/_____________(_),_____________(_)/_____________(_)))(_____([]),_____({}),_____(None),_____({}.__iter__),lambda _:len(_)))(lambda _:_______(______(_))))((lambda _:_.__class__),(lambda _:_.__name__),(lambda _:_.__dict__)))('Just another Python Hacker\n')

An indented version if you prefer:
(lambda ______________:
    (lambda ______,_______,________:
        (lambda _____:
            (lambda _,___,__,____,_____________:
                (lambda _________,__________:
                    (lambda ___________,____________:
                        ___________(____________,____[_________**(_________+__________)-__________::_________+_________+_________]+_[__________::_________]+__[_________+__________])(____________,______________)) (
                        (lambda _,__:________(______(_))[__]),
                        (________(__import__(_[_________]+__[_________*_________+__________]+_[_________]))[_[_________:_________+_________]+___[__________/_________]+__[__________]+_____(u'')[__________/_________]+_[_________+__________]]))) (
                    (_____________(_)+_____________(_))/_____________(_),
                    _____________(_)/_____________(_))) (
                _____([]),
                _____({}),
                _____(None),
                _____({}.__iter__),
                lambda _:len(_))) (
            lambda _:_______(______(_)))) (
        (lambda _:_.__class__),
        (lambda _:_.__name__),
        (lambda _:_.__dict__)))('Just another Python Hacker\n')

This defines a function and calls it with 'Just another Python Hacker'. Now, it didn't have to be a function, but I thought it would be more elegant.
f = (lambda ______________:(lambda ______,_______,________:(lambda _____:(lambda _,___,__,____,_____________:(lambda _________,__________:(lambda ___________,____________:___________(____________,____[_________**(_________+__________)-__________::_________+_________+_________]+_[__________::_________]+__[_________+__________])(____________,______________))((lambda _,__:________(______(_))[__]),(________(__import__(_[_________]+__[_________*_________+__________]+_[_________]))[_[_________:_________+_________]+___[__________/_________]+__[__________]+_____(u'')[__________/_________]+_[_________+__________]])))((_____________(_)+_____________(_))/_____________(_),_____________(_)/_____________(_)))(_____([]),_____({}),_____(None),_____({}.__iter__),lambda _:len(_)))(lambda _:_______(______(_))))((lambda _:_.__class__),(lambda _:_.__name__),(lambda _:_.__dict__)))
f('Hello.\n')
f('Just another Python Hacker here.\n')

Oh, it's exactly 900 bytes. That is completely unintentional and awesome.

And apparently it only works with Python 2.x

Python
My JAPH in Python
class Foo:
    def __init__(s, t='Just another Python hacker'):
        def g():
            return [100,101,102,32,102,
                    40,120,41,58,112,114,
                    105,110,116,32,120],t
        s.g = g()
        class Z():
            def __add__(s,x):return x
        s.z = sum((chr(i)for i in s.g[0]),Z())
    def __call__(s,t):
        return t.join(map(chr,s))
    def __iter__(s):
        return (ord(i) for i in `s`)
    def __repr__(s):
        return s.g[-1]
    def __getitem__(s, x):
        exec s.z
        f(s(x))
Foo()['']

Haskell
Fun with monad transformers:
import Control.Monad.State
import Control.Monad.Writer

newtype A a = A (Maybe a)
newtype B = B { c :: String }

instance Show a => Show (A a) where
   show (A x) = show x

instance Show B where
   show = c

s = [97, 13, 1, 5, -12, -3, 13, -82, 40, 25, 18,
     -8, -6, 7, 0, -76, 72, -7, 2, 8, -6, 13]

main = print . A . fmap B . execWriterT . flip evalStateT 0 . mapM f $ s
  where f x = modify (+x) >> get >>= tell . return . toEnum

Scala
val bi = BigInt ("467385418330892203511763656169505613527047619265237915231602")
bi.toByteArray.map (_.toChar).mkString

Postscript.
Creates a custom font with which to display the text.
%!
100 200[>>begin
(Encoding{}FontType 3
 BuildChar{exch begin 10 0 setcharwidth load exec stroke end}
 FontMatrix .1 0 0 .1 0 0 FontBBox 0 0 10 10)
{token{exch}{exit}ifelse}loop
{4 6}{array astore def}forall
/c{1 string cvs 0 get}4{def}repeat
/J c{7 9 moveto 7 2 lineto 6 4 1 360 190 arcn}
/A c{2 2 moveto 5 8 lineto 8 2 lineto}
/P c{3 2 moveto 3 8 lineto 3 6 2 90 270 arcn}
/s c{5 7 2 0 270 arc 5 3 2 90 180 arcn}
/H c{2 2 moveto 2 8 lineto 8 8 moveto 8 2 lineto 2 4 moveto 8 4 lineto}5{def}repeat
/F currentdict end definefont 20 scalefont setfont
moveto(JAPsH)show

Ruby 1.9
Cheesy, highly implementation-dependent, but I hope you find it spooky.
class Object
    define_method(:!) do |n=3|
        send(methods.find{|la|la[/[slappy]{#{n}}/]})
    end
end

(!!!:!).!(5) unless respond_to?('Just another ruby hacker,')

Edit: Proof

Ruby
Had two ideas and ended up combining them.
def Object.const_missing(const)
  define_method(:method_missing) do |meth,*args|
    "#{meth}"['i'] ? ->a{not$*<<a.pop} :print(meth)
  end[const,$\=' ']
end

Begin

case %w[Just another ruby hacker]
when tick
  puts 'tock'
when tick
  puts 'tock'
when tick
  puts 'tock'
when tick
  puts 'tock'
else
  eval($**$\)
end

JavaScript
eval (atob("ZnVuY3Rpb24gcHJpbnQoKSB7CmZ1bmN0aW9uIHRyKGEsYikgewogICAgcmV0dXJuIGEubWFwKGZ1bmN0aW9uKHgpewogICAgICAgIHJldHVybiB4LnRvU3RyaW5nKGIpOwogICAgfSkuam9pbignICcpOwp9CgoKdmFyIGEgPSJXemt5TmpNNE1Td3lNekl3TURJek1UYzNPU3d4TVRnMU5UTTNMREV3TkRVek1EYzBOelZkIjsKYSA9IGF0b2IoYSk7CmEgPSBKU09OLnBhcnNlKGEpOwphID0gdHIoYSwzNik7CmNvbnNvbGUubG9nKGEpOwp9"));
print();

Perl on OSX 10.7+ (requires Xcode)
#!/usr/bin/perl
use Inline C=>q{int g(){atexit("j\31\350\31\0\0\0Just \
another Perl hacker\n1\300@\220\17\204\n\0\0\0j\1k\4\x\
cd\x80\203\304\20\303^j\1_Z\270\4\0\0\2\17\5\303");}};g

Lua/RProgN
print "Just "           --                         Write Just to the Console--
print "Another "        --                      Write Another to the Console--
print "Lua "            --           Write Lua, definitely NOT  [ 'RProgN' ]--
print "Hacker "         -- Do u really thing u r an hacker like i [ ur NOT ]--

I'm sure there's a better and sneakier way to combine these two languages.
Hiding in comments is just so overused.
Try the Lua Out
Try the RProgN Out

Operation Flashpoint scripting language
removeAllWeapons player
s = primaryWeapon player
call = "scripting " else "language "

a = [if true, if false]
b = ["s=s+(call select 0)", format["s=s+(call select 1)%1%2=%3", {;}, "call", {nil}]]

a select 0 then b
a select 1 then b

a = a + getPos player + [{Just another} + format ([" %1 %2 "] + ("Operation" ELSE "Flashpoint"))]

"b = format[""%2%1%3."", s, _x, call""""""hacker""""""]" count a

titleText (b else "plain")

exit

Save as ofp.sqs (or any other name), and call with [] exec "ofp.sqs".
Output:

Canvas
³｛┤：js nte avshce＠；utaohrcna akr＠｝）∑╷

...which should work, but ╷ on strings hasn't been implemented yet.  Hooray for dead projects! The working version uses the same logic, but is a bit... less obfuscated.
Try it online! (working version)


text:
Implement Rijndael's S-box
Rijndael's S-box is a frequently used operation in AES encryption and decryption.  It is typically implemented as a 256-byte lookup table.  That's fast, but means you need to enumerate a 256-byte lookup table in your code.  I bet someone in this crowd could do it with less code, given the underlying mathematical structure.
Write a function in your favorite language that implements Rijndael's S-box.  Shortest code wins.

Bonus points (upvotes from me) if the resulting function is constant-time (i.e. no data-dependent code paths or array accesses or whatever your language supports).

@PaŭloEbermann array accesses are constant time in many languages (it's adding a (scaled) value to a pointer and dereferencing it, this is why a lookup table is so very fast)

@ratchetfreak Array accesses are O(1), but the actual access time depends on cache hits or misses, for example, which leads to side-channel attacks on AES.

@PaŭloEbermann, but you can use the shorter code to fill a lookup table, which will then fit in well under a page of memory.

@PaŭloEbermann and if the 256-length table is stored along the code (as enum generated at compile time) you nearly guaranteed a cache hit

There is some discussion about the relevance of cache timing attacks on AES in the Cryptography chat. (@ratchet freak)

@PaŭloEbermann you can't argue that my ubyte to ubyte version is fully branchless (except for 1 if in the mulInv() which is 1 instruction over 256 iterations and then it continues with searching the full space)

Ruby, 161 characters
R=0..255
S=R.map{|t|t=b=R.select{|y|x=t;z=0;8.times{z^=y*(x&1);x/=2;y*=2};r=283<<8;8.times{r/=2;z^r<z/2&&z^=r};z==1}[0]||0;4.times{|r|t^=b<<1+r^b>>4+r};t&255^99}

In order to check the output you can use the following code to print it in tabular form:
S.map{|x|"%02x"%x}.each_slice(16){|l|puts l*' '}

this seems to fail by printing 63s sporadically

x86-64 Machine code - 23 22 20 19 bytes
Uses the AES-NI instruction set
66 0F 6E C1          movd        xmm0,ecx
66 0F 38 DD C1       aesenclast  xmm0,xmm1
0F 57 C1             xorps       xmm0,xmm1
66 0F 3A 14 C0 00    pextrb      eax,xmm0,0
C3                   ret

Using Windows calling conventions, takes in a byte and outputs a byte. It is not necessary to reverse the ShiftRows as it does not affect the first byte.

For once, x86_64 pulls a mathematica, and has a builtin for that.

GolfScript, 60 characters
{[[0 1{.283{1$2*.255>@*^}:r~^}255*].@?~)={257r}4*99]{^}*}:S;

This code defines a function named S that takes in a byte and applies the Rijndael S-box to it.  (It also uses an internal helper function named r to save a few chars.)
This implementation uses a logarithm table to compute the GF(28) inverses, as suggested by Thomas Pornin.  To save a few chars, the whole logarithm table is recalculated for each input byte; even so, and despite GolfScript being a very slow language in general, this code takes only about 10 ms to process a byte on my old laptop.  Precalculating the logarithm table (as L) speeds it up to about 0.5 ms per byte, at the modest cost of three more chars:
[0 1{.283{1$2*.255>@*^}:r~^}255*]:L;{[L?~)L={257r}4*99]{^}*}:S;

For convenience, here's a simple test harness that calls the function S, as defined above, to compute and print out the whole S-box in hex like on Wikipedia:
"0123456789abcdef"1/:h; 256, {S .16/h= \16%h= " "++ }% 16/ n*

Try this code online.
(The online demo precalculates the logarithm table to avoid taking too much time.  Even so, the online GolfScript site may sometimes randomly time out; this is a known issue with the site, and a reload usually fixes it.)
Explanation:
Let's start with the logarithm table calculation, and specifically with the helper function r:
{1$2*.255>@*^}:r

This function takes two inputs on the stack: a byte and a reduction bitmask (a constant between 256 and 511).  It duplicates the input byte, multiplies the copy by 2 and, if the result exceeds 255, XORs it with the bitmask to bring it back under 256.
Within the log-table generating code, the function r is called with the reduction bitmask 283 = 0x11b (which corresponds to the Rijndael GF(28) reduction polynomial x8 + x4 + x3 + x + 1), and result is XORed with the original byte, effectively multiplying it by 3 (= x + 1, as a polynomial) in the Rijndael finite field.  This multiplication is repeated 255 times, starting from the byte 1, and the results (plus an initial zero byte) are collected into a 257-element array L that looks like this (middle part omitted):
[0 1 3 5 15 17 51 85 255 26 46 ... 180 199 82 246 1]

The reason why there are 257 elements is that, with the prepended 0 and with 1 occurring twice, we can find the modular inverse of any given byte simply by looking up its (zero-based) index in this array, negating it, and looking up the byte at the negated index in the same array.  (In GolfScript, as in many other programming languages, negative array indexes count backwards from the end of the array.)  Indeed, this is exactly what the code L?~)L= at the beginning of the function S does.
The rest of the code calls the helper function r four times with the reduction bitmask 257 = 28 + 1 to create four bit-rotated copies of the inverted input byte.  These are all collected into an array, together with the constant 99 = 0x63, and XORed together to produce the final output.

The table can be generated without computing inverses in the finite field GF(256), by using logarithms. It would look like this (Java code, using int to avoid problems with the signed byte type):
int[] t = new int[256];
for (int i = 0, x = 1; i < 256; i ++) {
    t[i] = x;
    x ^= (x << 1) ^ ((x >>> 7) * 0x11B);
}
int[] S = new int[256];
S[0] = 0x63;
for (int i = 0; i < 255; i ++) {
    int x = t[255 - i];
    x |= x << 8;
    x ^= (x >> 4) ^ (x >> 5) ^ (x >> 6) ^ (x >> 7);
    S[t[i]] = (x ^ 0x63) & 0xFF;
}

The idea is that 3 is a multiplicative generator of GF(256)*. The table t[] is such that t[x] is equal to 3x; since 3255 = 1, we get that 1/(3x) = 3255-x.

shouldn't it be 0x1B (one 1 in the hex literal) instead of 0x11B

@ratchetfreak: no, it must be 0x11B (I tried). The int type is 32-bit in Java; I must cancel out the higher bit.

ah didn't realize that

Is that a >>> instead of a >> in line 4?

@JoeZeng: both would work. In Java, '>>>' is the "unsigned shift", '>>' is the "signed shift". They differ by how they handle the sign bit. Here, the values will never be wide enough for the sign bit to be non-zero, so it makes no real difference.

I was wondering whether that was just a typo or not. Seems like it isn't.

GolfScript (82 chars)
{256:B,{0\2${@1$3$1&*^@2/@2*.B/283*^}8*;;1=},\+0=B)*:A.2*^4A*^8A*^128/A^99^B(&}:S;

Uses global variables A and B, and creates the function as global variable S.
The Galois inversion is brute-force; I experimented with having a separate mul function which could be reused for the post-inversion affine transform, but it turned out to be more expensive because of the different overflow behaviour.
This is too slow for an online demo - it would time out even on the first two rows of the table.

Mine's faster (and shorter ;). +1 anyway, though.

Python, 176 chars
This answer is for Paŭlo Ebermann's comment-question about making the function constant time.  This code fits the bill.
def S(x):
 i=0
 for y in range(256):
  p,a,b=0,x,y
  for j in range(8):p^=b%2*a;a*=2;a^=a/256*283;b/=2
  m=(p^1)-1>>8;i=y&m|i&~m
 i|=i*256;return(i^i/16^i/32^i/64^i/128^99)&255

Multiplication being constant-time is platform dependent (even on 32-bit platforms, e.g. ARM Cortex M0). See this related question

@fgrieu Sure, but these are all multiplications by constants, which can be easily implemented in constant time using shifts and adds.

APL (Dyalog Unicode), 70 bytes
⎕⊃99,1↓(2⊥¨(⊂b⊤99)≠≠⌿(⍳5)∘.⌽⌽p)[⍋2⊥¨p←{(2≠/⍵,0)≠b⊤27×⊃⍵}\,b⍴⊂1⊤⍨b←8⍴2]

Try it online!

d
ubyte[256] getLookup(){

    ubyte[256] t=void;
    foreach(i;0..256){
        t[i] = x;
        x ^= (x << 1) ^ ((x >>> 7) * 0x1B);
    }
    ubyte[256] S=void;
    S[0] = 0x63;
    foreach(i;0..255){
        int x = t[255 - i];
        x |= x << 8;
        x ^= (x >> 4) ^ (x >> 5) ^ (x >> 6) ^ (x >> 7);
        S[t[i]] = cast(ubyte)(x & 0xFF) ^ 0x63 ;
    }
    return S;

}

this can generate the lookup table at compile time, I could save some by making ubyte a generic param
edit direct ubyte to ubyte without array lookups, no branching and fully unrollable loops
B[256] S(B:ubyte)(B i){
    B mulInv(B x){
        B r;
        foreach(i;0..256){
            B p=0,h,a=i,b=x;
            foreach(c;0..8){
                p^=(b&1)*a;
                h=a>>>7;
                a<<=1;
                a^=h*0x1b;//h is 0 or 1
                b>>=1;
            }
            if(p==1)r=i;//happens 1 or less times over 256 iterations
        }
        return r;
    }
    B s= x=mulInv(i);
    foreach(j,0..4){
        x^=(s=s<<1|(s>>>7));
    }
    return x^99;
}

edit2 used @Thomas' algo for creating the lookup table

Stax, 53 bytes
ë■ÿÆ♂◄º5hUø√!«mr¿¡ƒR3Å←ç≥#/$taJkαn∩╓▒ÿ╔τy╫π§╪S♫╔┴H╔║Ö

Run and debug it
I have no particular understanding of S-boxes.  This is a conversion of Thomas Pornin's (8 year old!) solution.


text:
Illuminate a Mirrored Room
Goal
In this competition, you are given a random room with one candle inside. The goal is to write the shortest program (this is golf) that determines what parts of the room are illuminated by the candle, by replacing the dark spots with @'s. The program should take a room from STDIN, with the output printed to STDOUT.
Example Input/Room
+------+
|  C   |
|      +--+
|  \      |
+---------+

The candle is represented with a C, and the walls/mirrors are represented with |,-,/, or \. The walls themselves are mirrors. The corners of the room are represented with a +.
Rooms will never have diagonal walls, and light will never be able to escape out of the room.
Also, the first character on a line is always going to be part of the wall off the room. The absolute last character on each line is going to be the opposite wall of the room. No characters between these two are going to be outside of the room.
Light and Reflection
The candle emits eight (laser-like) beams of light in eight basic directions: N, S, E, W, NE, SE, SW, and NW. These rays of light bounce off of the mirrors as described below:
Old Direction of Travel | Mirror | New Direction
N S E W NE SE SW NW       /        E W N S -- -- -- --
N S E W NE SE SW NW       \        W E S N -- -- -- --
N S E W NE SE SW NW       |        - - - - NW SW NE SW
N S E W NE SE SW NW       -        - - - - SE NE SW NE

A - represents the light being absorbed. Light is always absorbed by C's or +'s.  It is important to note that the lights reflects off of a mirror only when it is occupying the same space as the mirror. These rules are much easier to understand when you draw the reflection out on paper.
Example Output
As output, the program should print an image of the illuminated room, with dark spots written as an @, light spots left blank, and mirrors unaffected. For the above example, the output would be:
+------+
|  C   |
|@   @ +--+
| @\      |
+---------+

This means that, if you drew out the beams of light, they will never reach the spaces marked with @.
More examples
Input:
+-----+
|     |
|     |
|  C  |
|     |
|     |
+-----+
Output:
+-----+
| @ @ |
|@   @|
|  C  |
|@   @|
| @ @ |
+-----+

Input:
+-----+
|  \  |
|/ C \+-+
|       |
|  \ - ++
+------+
Output:
+-----+
|  \ @|
|/ C \+-+
|      @|
| @\ -@++
+------+

In your example, shouldn't the bottom-left corner be @ too?

@Peter Taylor:  The SW beam hits that spot.

Bears some similarities to the very well received Lasers challenge on Stack Overflow. Enough similarities to make the methods used therein interesting with enough differences to require some considerable thought about how they might be applied.

Could use more validation cases.

@dmckee I added two more examples.

Python, 292 chars
import sys
R=''
for x in sys.stdin:R+='%-97s\n'%x[:-1].replace(' ','@')
M={'/':'-98/d','\\':'98/d'}
for d in(-98,-1,1,98,99,97,-97,-99):
 if d>98:M={'|':'d^2','-':'-d^2'}
 p=R.find('C')
 while 1:
  p+=d
  if R[p]in' @':R=R[:p]+' '+R[p+1:]
  elif R[p]in M:d=eval(M[R[p]])
  else:break
print R,

Reads in the room, makes it rectangular, then walks out from the candle in all directions.  M contains the active mirror characters and their effect (/\ for the cardinal directions, |- for the others)
Can handle rooms up to 97 characters wide.

c -- 504
Relies on K&R default function calling semantics.
Very straight forward implementation except for the fiddle stuff with bouncing the rays.
#define N M[x+y*97]
#define Y abs(y)
#define O M[c]==
#define E else break;
int j[]={-98,-97,-96,-1,1,96,97,98},c,x,y,p,s,M[9409];main(){for(;
(c=getchar())!=-1;){if(c==10)x=0,++y;else{if(c==67)p=x+y*97;if(c==32)
c=64;N=c;++x;}}for(x=0;x<8;++x){y=j[x];c=p;do{c+=y;if(O'@')M[c]=32;s=y/Y;
if(O 92)if(y%2){y=s*(98-Y);}E if(O'/')if(y%2){y=s*-(98-Y);}E if(O'|')
if(~y%2){y=s*(97+(97-Y));}E if(O'-')if(~y%2){y=s*-(97+(97-Y));}E}while
(!(O'+')&&!(O'C'));}for(y=0;x=0,N!=0;++y){for(;N!=0;++x)putchar(N);
putchar(10);}}

Ungolfed
//#include <stdio.h>
int j[]={ -98, -97, -96, /* Increments to move around the array */
           -1,       1,
           96,  97,  98},
  c, x, y, p, s, /* take advantage of static initialization to zero */
  M[9409]; /* treat as 97*97 */

main(){
  /* read the map */
  while((c=getchar())!=-1/*Assume the deffinition of EOF*/){
    /* putchar(c);  */
    if (c=='\n')
      x=0,++y;
    else {
      if (c=='C') p=x+y*97; /* set start position */
      if (c==' ') c='@'; /* The room starts dark */
      M[x+y*97]=c; ++x;
    }
  }
  /* printf("Start position is %d (%d, %d)\n",p,p%97,p/97); */
  /* Now loop through all the direction clearing '@' cells as we
   * encounter them
   */
  for(x=0;x<8;++x){
    y=j[x];c=p; /* y the increment, c the position */
    /* printf("\tposition %d (%d, %d) '%c'\n",c,c%97,c/97,M[c]); */
    /* printf("\tdirection = %d (%d, %d)\n",y,-(abs(y)-97),(y+98)/97-1); */
    do {
      c+=y;
      /* printf("\t\tposition %d (%d, %d) '%c'\n",c,c%97,c/97,M[c]); */
      /* We ought to do bounds checking here, but we rely on  *
       * the guarantee that the room will be bounded instead. */
      if(M[c]=='@') M[c]=' ';
      /* The reflections are handles
       *   + Stop or not stop based on the even/oddness of the increment
       *   + New direction is a little fiddly, look for yourself
       */
      s=y/abs(y); /* sign of y (need for some reflections) */
      if (M[c]=='\\') if (y%2){ y=s* (98-abs(y));     }else break;
      if (M[c]=='/')  if (y%2){ y=s*-(98-abs(y));     }else break;
      if (M[c]=='|')  if (~y%2){y=s* (97+(97-abs(y)));}else break;
      if (M[c]=='-')  if (~y%2){y=s*-(97+(97-abs(y)));}else break;
      /* printf("\t\t\tdirection = %d (%d, %d)\n",y,97-abs(y),(y+98)/97-1); */
    } while (!(M[c]=='+')&&!(M[c]=='C'));
    /* printf("\t...hit a %c. Done\n",M[c]); */
  }
  /* print the result */
  for(y=0;x=0,M[x+y*97]!=0;++y){
    for(;M[x+y*97]!=0;++x)
      putchar(M[x+y*97]);
    putchar('\n');
  }
}

Validation
$ gcc -g -o candle candle_golfed.c
$ for f in candle_room*; do (./candle < $f) ; done
+------+
|  C   |
|@   @ +--+
| @\      |
+---------+
+------+
|  C   |
|@   @ +--+
|  /@ @ @ |
+---------+
+------+
| @/   |
|@   @ +--+
|  C      |
+---------+
+------+
|  \@ @|
|@   @ +--+
|  C      |
+---------+
+-----+
| @ @ |
|@   @|
|  C  |
|@   @|
| @ @ |
+-----+


text:
Implement wc (word count) shortest code wins
Write a stripped down version of the wc command. The program can simply open a file which does not need to be configurable or read from stdin until it encounters the end of file. When the program is finished reading, it should print:

# bytes read
# characters read
# lines read
max line length
# words read

Program must at least work with ascii but bonus points if it works on other encodings.
Shortest code wins.

criteria 1 & 2 should be the same on ascii.

As yet "words" are undefined (see below for one way that is profitable for a terse c implementation). This is the kind of issue that could have been profitably hammered out in the puzzle-lab chat or in the sandbox on meta.

in this problem, a word is a sequence of characters delimited by spaces. They can even include special characters. Consider them chunks, actually.

Some testcases would be fine.

Haskell - 80 characters
l=length
main=interact$ \s->show$map($s)[l,l,l.lines,maximum.map l.lines,l.words]

That's actually 81 chars (not including a final newline)

This isn't C or C++ where not ending in a newline results in undefined behavior... or am I wrong, and the Haskell specs mandate it?

@trinithis There is no such mandate in c or c++. There were (in the misty depth of time) some antique unix systems that boggled on unterminated final lines: thus the purely human convention of always appending a newline. Line endings (like any other whitespace have no significance to c or c++ except to the preprocessor; examine the grammar and to separate tokens.

C++ Standard [2.1.1.2]: If a source file that is not empty does not end in a new-line character, or ends in a new-line character immediately preceded by a backslash character before any such splicing takes place, the behavior is undefined.

Perl - 71

$c+=$x=y!!!c,$w+=split,$m=$m<$x?$x-1:$m,$l++for<>;say"$c,$c,$l,$m,$w"

I think it can be shortened further but I don't know how.
(edit: used Zaid's suggestion)
(edit 2: changed length to y!!!c)
(edit 3: changed print to say)

Replace the while with a for to save two chars.

Use say instead of print that is allowed without penalties (http://meta.codegolf.stackexchange.com/questions/273/on-interactive-answers-and-other-special-conditions) and save 2 chars.

c -- 214
Implementation is almost right out of K&R. Relies on K&R semantics for main (unspecified return type), but I think it otherwise conforms to c89. Output format is specified below (but it assumes that chars == bytes).
#include <stdio.h>
int b,w,l,t,L;main(int c,char**v){FILE*f=fopen(v[1],"r");for(;(c=getc(f))
!=-1;++b){t++;if(c=='\n')l++,L=t>L?t:L,t=0;else if(c==' '||c=='\t')w++;}
L=t>L?t:L;printf("%d (%d) %d %d %d\n",l,L,w,b,b);}

There is some ambiguity in the meaning of "words" as yet. This version defines words as breaking only on '[ \t\n] and does not account for a word that ends with EOF. This will work for files following the old unix convention of always ending with a newline, but break for those that stop hard on EOF.
It does test lines that end of EOF for maximal length.
Un-golfed
#include <stdio.h>
int b, /* bytes */
  w, /* words */
  l, /* lines */
  t, /*this line*/
  L; /* longest line */
main(int c,char**v){
  FILE*f=fopen(v[1],"r");
  for(;(c=getc(f))!=-1;++b){
    t++;
    if(c=='\n') l++, L = t>L ? t : L, t=0;
    else if(c==' '||c=='\t')w++;
  }
  L = t>L ? t : L;
  /* Output format is lines (max line length) words chars bytes */
  printf("%d (%d) %d %d %d\n",l,L,w,b,b);
}

Validation
$ gcc -o wc wordcount_golf.c
$ ./wc wordcount.c
17 (67) 82 410 410
$ ./wc wordcount_golf.c
4 (74) 9 217 217
$ wc wordcount.c
 17  67 410 wordcount.c
$ wc wordcount_golf.c
  4  13 217 wordcount_golf.c

How about 198? I am actually happy that gcc don't refuses to eat's that...

ruby (72 characters)
t=readlines;s=t*'';p [s.size]*2+[t.size,t.map(&:size).max,s.split.size]

This solution uses a functional style similar to trinithis's Haskell solution.
I assume ASCII text and space-separated words.

awk - 58
awk 'x=1+length{w+=NF;if(m<x)m=x;c+=x}END{print NR,w,c,m}'

This deserves more thumbs up, but I really need to see an non-obfuscated version of it. Awk is truly the winner, and then I noticed K what on earth? I stick with awk.

Groovy, 85 81
a={it.size()};[s=a(t=f.text),s,a(z=t.split"\n"),z*.size().max(),a(t.split(/\s/))]

Perl - 66 characters
for(<>){$t+=$l=y!!!c,$m=$l-1if$m<$l,$w+=split}say"$. $w $t $m $t"

I managed to save a couple of bytes by letting Perl handle the number of lines, using the $. variable.  Other than that, even without looking, I ended up with what Marinus got, for the most part.
Here's the program I used to verify it:
#!/bin/bash

function test1() {
    cat <<EOF
Lorem ipsum dolor sit amet,
consectetur adipiscing elit. Duis eget
neque vel ipsum porta bibendum
dictum in ante. Ut accumsan
magna id nisl bibendum et
tincidunt turpis eleifend. Duis nec
mi hendrerit lorem hendrerit convallis.
Quisque sit amet tincidunt diam.
Sed vehicula velit sed risus
pellentesque vitae auctor nisi semper.
Nulla erat massa, semper sit
amet luctus non, bibendum id
eros. Etiam non lacus odio.
Donec vitae nisl vitae nisi
elementum suscipit. Cras ut mollis
mauris.
EOF
}

function test2() {
    cat <<EOF
Curabitur quis elit turpis. Vestibulum
ut elementum magna. Lorem ipsum
dolor sit amet, consectetur adipiscing
elit. Nam sit amet quam
ante. Nullam in risus est,
quis cursus magna. Vestibulum feugiat
nisl nec velit scelerisque molestie.
Pellentesque habitant morbi tristique senectus
et netus et malesuada fames
ac turpis egestas. Vestibulum feugiat
sem vitae mauris aliquet eget
ullamcorper velit molestie.
EOF
}

function test3() {
    cat <<EOF
Proin diam elit, imperdiet id
gravida et, facilisis nec lectus.
Nullam placerat enim sed nulla
porttitor hendrerit. Praesent eu quam
enim, et commodo orci. Nam
eu purus ut ipsum malesuada
rhoncus vitae ut turpis. Morbi
a risus eu ligula faucibus
tincidunt. Cum sociis natoque penatibus
et magnis dis parturient montes,
nascetur ridiculus mus. Nulla faucibus
vehicula diam at tempus. Aliquam
tristique, erat vel fringilla scelerisque,
magna purus venenatis nulla, at
elementum mi lectus vitae nibh.
Phasellus nibh neque, tempus commodo
pretium eget, gravida quis felis.
Vivamus venenatis tristique volutpat. Nunc
vulputate accumsan magna, sit amet
vehicula orci imperdiet vel. Nam
vitae laoreet purus.
EOF
}

PROG1=wc
PROG2='perl5.14.2 -Mv5.10 wc-golfed.pl'

for((i=1;i<4;i++)); do
    wc=( $(test$i | $PROG1) )
    golf=( $(test$i | $PROG2) )
    for((j=0;j<2;j++)); do
    if [ ! ${wc[$j]} = ${golf[$j]} ]; then
        echo "Test #$i failed"
        echo "     wc: ${wc[@]}"
        echo "   golf: ${golf[@]}"
        continue 2
    fi
    done
    echo "Test #$i passed"
done

C - 164 chars
This is based on dmckee's code with FUZxxl's improvements, but shortened further and converted to standard C.  The code reads from standard input only.  Any sequence of one or more consecutive characters with ASCII code >= 33 is counted as a word.
#include<stdio.h>
int b,w,l,t,L,c,s;int main(void){for(;c=getchar()+1;++b)t-=c==11?l++,t>L?L=t:t:-1,s=c>33?w+=!s:0;printf("%d %d %d %d\n",l,t>L?t:L,w,b);return 0;}

Un-golfed
#include <stdio.h>
int b, /* bytes */
     w, /* words */
     l, /* lines */
     t, /* this line */
     L, /* longest line */
     c, /* current character */
     s; /* s==1 if the current word has been counted */
int main(void) {
  for (; c = getchar()+1; ++b)
       t -= (c==11 ? (l++, (t>L ? L=t : t))
                   : -1),
       s = (c>33 ? w += !s
                 : 0);
  printf("%d %d %d %d\n", l, (t>L ? t : L), w, b);
  return 0;
}

You can remove #include<stdio.h>. It'll compile and run without those 19 chars.

R, 91 characters
Golfed
x=scan(w="c",se="\n");n=nchar(x);sum(n);length(x);max(n);sum(sapply(strsplit(x," "),length))

Ungolfed
x=scan(what="c",sep="\n")
n=nchar(x)
num.char=sum(n)
num.lines=length(x)
max.line.length=max(n)
word.count=sum(sapply(strsplit(x," "),length))

Output
> x=scan(what="c",sep="\n");n=nchar(x);sum(n);length(x);max(n);sum(sapply(strsplit(x," "),length))
1: This is a test
2: of how well
3: the program works!
4:
Read 3 items
[1] 43
[1] 3
[1] 18
[1] 10

Alternatives
x=scan(w="c",se="\n");n=nchar(x);sum(n);length(x);max(n);length(unlist(gregexpr("\\w+",x)))

Saves a character at the expense of not really matching everything.

A little shorter: x=scan(,"",se="\n");n=nchar(x);sum(n);l=length;l(x);max(n);sum(sapply(strsplit(x," "),l))

@Tommy Yup.  And I believe that's actually 91 characters if you count the \ and the n separately :-O

We can define variable in argument + define length() to save some characters - 87 now. sum(n<-nchar(x<-scan(,"",se="\n")));(l=length)(x);max(n);sum(sapply(strsplit(x," "),l))

Javscript (runs in Rhino) - 213 chars
The java file i/o calls take up a lot of space. But I didn't realize you call java so easily from javascript and thought that was pretty neat:
var r=new BufferedReader(new FileReader(f));var s=true;var n=0,l=0,m=0,w=0;while(s){s=r.readLine();if(s){n+=s.length();l+=1;m=m<s.length()?s.length():m;w+=s.split("\\s+").length;}}print(n+','+n+','+l+','+m+','+w);

Ungolfed:
        var reader = new BufferedReader( new FileReader(filename) );
        var s = true;
        var n=0,l=0,m=0,w=0;

        while (s) {
            s = reader.readLine();
            if (s) {
                n+=s.length();
                l+=1;
                m = m<s.length()?s.length():m;
                w += s.split("\\s+").length;
            }
        }
        System.out.println('bytes/chars: '+n+', Lines: '+l+', Max Line: '+m+', Words: '+w);

Python 160
Your file name is assigned to variable q.
g=len
z=open(q,'r')
w=z.read()
z.close()
b,e,f=g(w),g(w.replace('\n',' ').split()),w.split('\n')
d,c,a=g(max(f)),g(f),g(open(q,'rb').read())
for i in 'abcde':
     print eval(i)

This prints the 5 requirements in order:
bytes read
characters read
lines read
max line length
words read
(TyrantWaves suggestion implemented)

one problem with this, is that it will think the\nbear is one word, while it should be two. you could do w.split(w.replace('\n', ' '))

Could also do l=len to save 3 more characters. (5 len's = 15, whilst \nl=len\n + 5 l's = 12)

Thanks, taken into consideration!  (I didn't even know you could assign a function to a variable like that! :O Living in the dark ages)

You could laso get rid of close and the read/write mode. do z=open(q).read()

Of course, but what terrible practise! ;)  Does open(q) open the file in binary read?

K, 40
{a:0:x;(#a;+/b;max b:#:'a;+/#:'" "\:'a)}

Prints linecount, char count, max line length, word count.
Words are space-separated.

Python, 98
l=len
f=open(q).read()
j=f.split("\n")
for i in (l(f),l(f),l(j),max(j,key=l),l(f.split())):print i

98 is including newlines. Do newlines count?

It fails on Windows for \r\n newlines (invalid bytes count). q is not defined (OP allows a fixed name such as 'q' or use sys.stdin). It expects only ascii (invalid character count). There is missing l() call around max() (it prints line instead of its length)

Open in binary mode

PHP, 163
<?$f=file($argv[1]);$l=0;foreach($f as$i)$l=$l<strlen($i)?strlen($i):$l;$n=count($f);$c=strlen($g=implode($f));$w=count(explode(' ',$g))+$n-1;echo"$c $c $n $l $w";


text:
Change a non-floating point number the largest step
Declare a numeric variable that is not floating point and do an operation that changes the value with the largest amount of difference so the result of the variable is far from the original value.
Solutions will be scored based on the magnitude of the difference between initial value and the value after changed, and shortness of code.
Edit:
 I realize that this was a bit vague - sorry about that, it's my first try on code golf...
I want to also emphasize that the result must not cause overflow. So once the variable is declared with a specific type (which must not be floating point), the result would have to be valid within that type.

Is the problem the following: Given an integer N, return an integer D such that max(|N-D|,|D-N|) is maximized?

You do realise that there are languages which allow arbitrarily large integers?

@trinithis: Not "return an integer". You must change the value of an integer variable that results in max diference.

@PeterTaylor: No, I just realized it with the Phyton answer by JiminP. I have not very broad experience with such languages, and in my narrow mind, a numeric type has bounds, so I'm feeling his answer is cheating, but...

Python and Java are not eligible for this contest since their integers are immutable.

@awe, for a type with a fixed size this is a boring question. Initialise variable to maximum; change it to minimum. For a type with an arbitrary size it's slightly more interesting, but not an objective challenge until you specify the scoring more precisely.

@Peter Taylor:  awe specifies on the the comments that "you must change the value of an integer variable that results in max diference".  I'm pretty sure he means that he wants the value at the original memory location changed.

@StevenRumbalski, and why would that be a problem in Java?

@Peter Taylor:  Whoops.  I'd not looked at Java recently.  My memory of strings being immutable somehow got cast onto Java primitives.

It is not an objective winning criterion, if you have 2 goals to reach. Person A might have the shortest code, Person B the greatest difference, Person C might have something in between for both aspects. You could solve the problem by a combined measure: Maximise (100-code-size)*difference, or by ordering the winning criteria: Shortest code wins. For two equal shortest codes, the bigger difference wins. Prepare your questions on meta or in chat next time, to solve such problems and ambiguities before starting the quiz.

This is (yet another) busy beaver problem.  Boo.

Java (55 26 19 chars, Diff: 2^64-1 = 18446744073709551615)
Given a very unclear spec on what we're supposed to be doing, here's a best try :-)  Obviously I will easily be beat out by languages that have arbitrary precision integers like Python or APL/J.
long o=Long.MIN_VALUE;o+=Long.MAX_VALUE+Long.MAX_VALUE;

Demo: http://www.ideone.com/7HyCW
EDIT: Shorter version, making use of Long underflow to wrap around from MIN_VALUE to MAX_VALUE (26 chars):
long o=Long.MIN_VALUE;o--;

Demo: http://www.ideone.com/Qfao7
EDIT 2: Shortest yet taking into account @ratchet freak's suggestions:
long o=1L<<63;o=~o;

Demo: http://www.ideone.com/2M9oa

wouldn't o=~o; also work without overflow (and isn't 1<<63 or -1>>>1 a shorter initialization)

@ratchetfreak: Updated with your suggestion.  Note have to use 1L<<63 otherwise it overflows at 2^32 because 1 is integer by default.

D (15 chars 2^64-1 difference)
ulong o=0;o=~o;

uses unsigned long and logical NOT to get max value
note that using ucent would get me to 2^128-1 difference (if it were to be implemented at least)

Just curious - what is ucent?

@awe a 128 bit unsigned integer but it's not yet part of the language (it's planned for when processors go 128 bit)

You will have one less char if you do o-- instead of o=~o. It will both result in the inverted value, because o-- will "wrap around" and use the max value of ulong (at least in C# where I tested it).

I haven't found the wrapping rules of unsigned types in D (which I think would undefined like in C)

Haskell - 8 characters (Infinite difference)
f=f.(+1)
Use f on Integer.

Strictly speaking, you defined a function; you didn't "do an operation."

Heh, well this problem cannot be done in Haskell otherwise. Yes, there are MVars and such, but that doesn't exactly cut it either.

The closest I can think of would be an action, but my main point is: from within Haskell, it's not possible to even verify that yours yields a number greater than the one it was given.

C with SSE2 (79 chars, Difference: 2^128-1 = 3.4e38)
#include<emmintrin.h>
main(){__m128i v=_mm_set1_epi8(-1);v=_mm_xor_si128(v,v);}

This initially sets the 128 bit unsigned int v to its maximum value, and then changes this value to 0 by XORing v with itself.

Golfscript
2{.?}9*

7 chars, unimaginably large difference. (The loop executes 9 times. The first time maps 2 -> 2^2 = 4. The second time maps 4 -> 4^4 = 256. The third time maps 256 -> 256^256 ~= 3.23 * 10^616. The fourth time overflows memory, but not the datatype...)

The requrements was to first declare a numeric variable (not float), then do the operation(s) on that variable.

@awe, in GolfScript a variable is just a value on the stack. If you want to write something which isn't GolfScript in GolfScript I suppose you could do 2:a;{a.?:a;}9*

... which would be 14 chars?

@userunknown, yes, like that. The problem is that the challenge isn't well enough specified for me to know how many of those characters are necessary; this was more a protest answer than anything.

J - 16 characters
a=.<.<:(a=.2)^31

The value of a changes from 2 to 2147483647. The calculation makes the value become float, but the final result is integer.
There are also extended integers, but I don't know if they would be acceptable.
a=.(a=.0)+!100000x

Yes, that really spells out mathematically as !100000. J can crunch it (in a few minutes), brute force.

Python (13 chars, Difference: 9^(9^9) (369,693,100 digits!))
a=0;a=9**9**9

I believe that the result of this operation is not a float, isn't it?
If that's problem because it doesn't yield the result...
Mathematica (11 chars, Difference: only 15,151,335 digits)

If it's still a problem because this value is not the maximum possible, then,
a=2^1073741696;a*=-1 (20 chars) will do the work.

What type is a declared as? (implicit declaration?) Is this not causing overflow on the type of a?

@awe Python has arbitrary-precision integer. For example, 4**4**4 returns 13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084096L. (PS: It is 4**(4**4); (4**4)**4 returns only 4294967296L.)

I added the calculation of Mathematica. If this is a problem because the difference isn't the maximum possible, then I'll go with a=2^1073741696;a*=-1

arbitrary-precision integer: I feel cheated...

bc 15chars:
On my system I can go until 8^8^8 without error, but 6^6^6 would already be too long to report it here, so take 5^5^5 as an example; 7^7^7 is in the range of one minute on a single core 2Ghz machine. With 8 you should have some time left.
echo "k=8^8^8;k*=-1;k" | bc

printable result for one page:
echo "k=5^5^5;k*=-1;k" | bc

-1911012597945477520356404559703964599198081048990094337139512789246\
    52053024261580301205938651973985026558644015579446223535921278867380\
    69722884101469159866020879618967571957018392816603380476112259755336\
    26101001482651123413147768252411493094447176965282756285196737514395\
    35754247909321920664188301178716912255242107005070906467438287085144\
    99502565861944615431835113798491336917799281274338404315492368555267\
    83596374102105331546031353725325748636909159778690328266459182983815\
    23028693657287369142264813129174376213632573032164528297948686257624\
    53622180176732249405676428193600787207138370723553054463561539464011\
    85348493792719514594505508232749221605848912910945189959948686199543\
    14766693801303717616359259447974616422005088507946980448713320513316\
    07391342305401988725700383298012460501970134673971759090273894939238\
    17315786996845899794781068042822436093783946335265422815704302832442\
    38551508231649096728571217170812323279048181726832751011274678231741\
    09858886837085220007117334922539133223007561471804290075276777933523\
    06200618286012455254243061006894805446584704820650982664319360960388\
    73625851074707434063628697657670269925864995355797631817390255089133\
    12232947439303439561613283340728316634982581452268620043077990846881\
    03804187368324800903873596212919633602583120781673673742533322879296\
    90720549059562140688882599124458184237959786347648431567376092362509\
    03715117989414242622702200662864868678687101829808728025606931019492\
    80830825044198424796792058908817112327192301455582916746795197430548\
    02640464685400273399386079859446596150175258696581144756851004156868\
    77309037124825353438392853975987494584970500382250124892840018265900\
    56251286187629938044407340142347062055785305325034918189589707199305\
    66218851296318750174353596028220103821161604854512103931331225633226\
    07664362366882968502088394961428304847391139916696226499485636852347\
    12873294796680884509405893951104650944137909502276545653133018670633\
    52132302846051943438139981056140065259530073179077271106578349417464\
    26847209561346473277485842382748996687550525043942182321913572230540\
    66715373374248543645663782045701654593218154053548393614250664498585\
    40330746646854189014813434771465031503795417577862281177658587694168\
    0908203125

BrainF***, 3 characters, theoretically unlimited difference
[+]

Some implementations of BF wrap. "True" BF allows for unlimited integers. This has a difference of whatever you want it to be, plus it's only 3 characters long :)


text:
Simulate a (gravity-based) billiard-ball-type computer
The Machine
A billiard-ball type machine is composed of only the symbols \ _ / along with upper- and lower-case letters, spaces, and the number 1.
\ and / are ramps. A ball coming from above will be deflected to either the right or left side, respectively. For both ramps, if a ball comes from either side, it will be deflected downward.
_ is a logic element. The logic performed by it is the most un-billiard-like part of the computer. First, a ball coming from the left or right continues in the same direction. A ball coming from above will be stopped. Then, after the end of its execution (see Running the Machine below), if the number of balls crossing/landing on it is positive even number, then a single ball is released from the bottom of the element.
A space does nothing. Any balls coming from any direction fall straight down due to gravity.
Lowercase letters are inputs. All inputs will either be a single 1 or 0.
Uppercase letters are outputs. The number outputted will be the number of billiard balls that hit its location.
The number 1 releases a extra billiard-ball at that location. It represents a logical 1.
All characters besides \_/ cause any ball coming from any direction to fall straight down due to gravity.
Balls never combine, split, or collide. They are only created when released from an input, a _, or a 1. They are only destroyed when they fall straight down onto a _.
Example machine-
1 a
\_/ b
  \_/
 \/
 /\ /
_  _
A  B

There will never be any blank lines in a machine, but the _'s may make it appear that there is a blank line.
Running the Machine
A machine is run in layers, or rows. All billiard-ball movement on the top layer is performed before anything happens on the second layer.
The machine
ab
\_A
 C

is run as follows:
First, it prompts for the input a in the form a:. The user will then input a 1 or 0 (followed by enter). It repeats this for the input b. This is the end of the first layer. I am going to assume that the user entered a 1 for both inputs.
It then traces out the path of the first ball (from a), which goes along the \, across the _, into the A, and falls down to the spot under the A. It then traces out the path for the second ball (from b), which goes straight down onto the _ and terminates. This is the end of the second layer.
Now, before the third layer, since the _ has had two balls cross over it, it releases one ball. The output A has had one ball cross over it, so it outputs A:1.
For the third layer, it traces the path of the first ball (from the _), which goes though the C and falls straight down. The second ball (which fell through the A) also falls straight down.
Now, before the fourth layer, since the output C had one ball travel over it, it outputs C:1.
Since the fourth layer is blank, the program terminates.
The total result should look like
a:1     (the user entered the one)
b:1     (same here)
A:1
C:1

The Goal
Your goal is to take a machine from STDIN and simulate it by taking inputs and printing output as needed to STDOUT. The first part of the input to your program will consist of the machine to be run, followed by a blank line. Any input letters encountered should cause your program to prompt for input in the form of the input name followed by a colon. Any output should be shown in the form of the output name, followed by a colon, followed by the number of balls passing over that spot.
This is golf.
Examples
A wire crossing
ab
\/
AB

An XOR gate
ab1
\_/
 C

A full adder
1 a
\_/ b
  \_/
 \/
 /\
_ __/
 \_/
  \/c
 \\_/
  _S1
\  \/
 __/
  /
 _
\__
 C

In your first example, why does the first ball fall down under the A? Is there an unwritten rule that balls stop when they pass onto a character which isn't \_/?

@PeterTaylor Yes, I should add that all letter behave as an empty space when it comes to affecting the ball, and gravity pulls the ball down.

Do you, by any chance, mean 'flipper', not 'billard'?

MAKE DIS AN ESOLANG

@MatthewRoh Working on it.

@MatthewRoh I've built the main framework, and I'm working on adding new things. Also, I made a somewhat user-friendly 0+0 to 3+3 adder, and I'm working on a vertically stackable module.

@AlexL. Also relevant: Marbelous

That's interesting. That's more or less the kind of thing I'm going for, but without marbles having values themselves.

https://github.com/alexander-liao/java-public/tree/master/programs/ball-simulator

@MatthewRoh ^ Made something to start

@AlexL. :D Looks nice!

JavaScript (392 423)
Assumes machine is set in a variable called m, then alerts the final output.
l=m.split(q='\n');o='';for(r=Array(z=l[i=0].length);i<l.length;i++){L=l[i];n=Array(z);for(c=0;c<z;n[c]=N,r[c++]=R){C=L[c];N=~~n[c];R=~~r[c];if(C>'`'){N+=x=~~prompt(C);R+=x;o+=C+': '+x+q}else if(C=='\\'||C=='/'){for(d=c+(g=C=='/'?-1:1);L[d]=='_';r[d]+=R,d+=g);if(L[d]>'@'&L[d]<'[')r[d]+=r[c];n[d]=~~n[d]+R}else if(C<'2')N+=R+=~~C;else if(C!='_')o+=C+': '+R+q}for(c=0;c<z;c++)if(L[c]=='_')n[c]+=(r[c]%2)?0:r[c]>0;r=n}alert(o)

Sample source (runs adder machine, see history for less golfed sources): http://jsfiddle.net/96yLj/12/
Spoilers:

 - r tracks the # of balls across current row, n tracks # of balls across next row.
 - Algorithm: process each row character by character, but process _'s last.
 - Algorithm: \ -> follow _ and increase r until non-_. Same for / but in reverse direction.  At the end increase n for gravity pulling balls down. g holds direction.
 - if(L[d]>'@'&L[d]<'[')r[d]+=r[c]; is for the bug mentioned in Edit 1.  The reason we can't just say r[d]+=r[c]; is because \_/ will double-count balls when processing /
 - else if(C<'2') handles both cases '1' and ' ', which ~~C turns into 1 and 0, respectively.

Edit 1: Fix bug with ball running over _ not included in A for sample code.

Note that I always ignore STDIN and STDOUT requirements because they are uninteresting restrictions.  I am using prompt for input and alert for output which is pretty standard for JavaScript :-)