text:
Incremental Betting
Several months ago I had this question as a pre-screening puzzle for an interview.  Recently when thinking about blog material, it popped in my head as a good example to use for solving a problem functionally.  I'll post my solution to this as soon as I'm done writing my blog post.
NOTE: This question was asked on StackOverflow a year ago, and was downvoted after a few (incorrect) answers.  I assume it was downvoted for being an obvious interview or homework question.  Our answers here should be code golfed deep enough for someone not to think about using them!

In a race, you bet using the following strategy. Whenever you lose a bet, you double the value of the bet for the next round. Whenever you win, the bet for the next round will be one dollar. You start the round by betting one dollar.
For example, if you start with 20 dollars, and you win the bet in the first round, lose the bet in the next two rounds and then win the bet in the fourth round, you will end up with 20+1-1-2+4 = 22 dollars.
You are expected to complete the function, g, which takes two arguments:

The first argument is an integer a which is the initial money we amount we have when we start the betting.
The second argument is a string r. The ith character of outcome will be either 'W' (win) or 'L' (lose), denoting the result of the ith round.

Your function should return the amount of money you will have after all the rounds are played.
If at some point you don't have enough money in your account to cover the value of the bet, you must stop and return the sum you have at that point.
Sample run
1st round - Loss: 15-1 = 14
2nd round - Loss: 14-2 = 12 (Bet doubles)
3rd round - Loss: 12-4 = 8
4th round - Win: 8 + 8 = 16
5th round - Loss:16-1 = 15 (Since the previous bet was a win, this bet has a value of 1 dollar)
6th round - Loss: 15-2 = 13
7th round - Loss: 13-4 = 9
8th round - Loss: 9-8 = 1

The function returns 1 in this case
The winner is determined by least number of characters INSIDE of the implied function definition. Cooperate by language if desired. I know mine can be improved!

All questions on this site must have an objective winning criterion. You didn't mention what determines the winner of the challenge.

Moreover, you state that Your function should return the amount of money you will have after all the rounds are played. although you show a much more detailed information in the Expected output section. Which is the desired behavior of the function?

Also, if every tag you are using is one that you created just for the question, something is wrong.

Judging from "Our answers here should be code golfed deep enough for someone not to think about using them!", I think you wanted a [code-golf], so I tagged it as such. Also, I adjusted the "Example Output" to be a "Sample Run" to better match what it seems you wanted.

@quincunx sorry, I've never posted here but interestingly posted many of the original questions that migrated here when it was created. In a way, I'm one of the reasons this stackexchange was made. I thought it was all code golf, and my laptop battery was dying so I was in a hurry to finish up. Sorry. Long night.

No problem. If you want a better reception, you can send your challenges through the sandbox first.

What should happen if the function receives invalid input, e.g., f(-42,"LOL")? Can we assume that the initial amount of money will be positive?

If after successive losses, I have 20 as an amount, and the value of the bet is 32. Now I win a bet. So, according to "If at some point you don't have enough money in your account to cover the value of the bet, you must stop and return the sum you have at that point", should I stop and return 20 or add up 32(due to the win) to my account and continue with more losses/wins ?

@GaurangTandon You cannot play a round if you cannot afford to lose.  If you have 20 and the bet is 32, you return 20.

What you should really output, given a seed, is how many rounds it takes you to lose all your money =P. (i.e. Martingale betting doesn't work in the long run)

@TheSoftwareJedi so in the case of your sample output, the string parameter was "LLLWLLLL" correct?

@wallywest correct

GolfScript, 33 characters
{
1\{2$2$<!{1&{+1}{:b-b.+}if.}*;}/;
}:g;

Examples (online):
> 13 'LLLWLLLL'
6
> 4 'LWWLWLWWWL'
9
> 5 'LLLWWWLLWLWW'
2
> 2 'LW'
1

Annotated code:
1\            # prepare stack a b r
{             # for each char in r
  2$2$<!{     #   if a>=b
    1&        #     take last bit of character (i.e. 0 for L and 1 for W)
    {         #     if W
      +       #       a <- a+b
      1       #       b <- 1
    }{        #     else
      :b-     #       a <- a-b
      b.+     #       b <- 2*b
    }if       #     end if
    .         #     create dummy value
  }*          #   end if
  ;           #   drop (i.e. either the dummy or the character)
}/            # end for
;             # discard current bet value

Python 2, 72 68 62 bytes
def g(a,s,n=1):
 for c in s:
    if a>=n:a,n=((a+n,1),(a-n,2*n))[c<'W']
 return a

Call it like so: g(15,'LLLWLLLL').
This simply loops through the string, changing the value of the money that we have based on the character.
Here is a sample program that runs tests on this function:
import random
def g(a,s,n=1):
 for c in s:
    if a>=n:a,n=((a+n,1),(a-n,2*n))[c<'W']
 return a

for i in range(14):
    s=''.join(('L','W')[random.randint(0, 1)] for e in range(random.randint(10, 15)))
    print'g(%i,%s):'%(i,`s`),
    print g(i,s)

Sample output:
g(0,'LLWWWWWWLWWWWW'): 0
g(1,'WLLWWWWWWWW'): 1
g(2,'WWWLLLWLLW'): 2
g(3,'LLLLWLWLWWWWLL'): 0
g(4,'LWWWWLWLWWW'): 12
g(5,'WWLWWLLWWW'): 12
g(6,'LLLWWWLLLLWLLWL'): 3
g(7,'WWLLWWLWLWLWLLL'): 7
g(8,'WLLLWWWWWLLWLL'): 2
g(9,'WWWLLWLLLLLWL'): 6
g(10,'LWWWWLLLWL'): 7
g(11,'WLLLLWLWWWW'): 5
g(12,'WLLWWLWWWL'): 17
g(13,'LLLWLLWLWLWLWW'): 6

With a little change to the tester, we can get the average profit of many runs:
import random
def g(a,s,n=1):
 for c in s:
    if a>=n:a,n=((a+n,1),(a-n,2*n))[c<'W']
 return a

r=[]
for i in range(5000):
    for i in range(1000):
        s=''.join(('L','W')[random.randint(0, 1)] for e in range(random.randint(10, 15)))
        r+=[i-g(i,s)]
a=0
for n in r:
    a+=n
print float(a)/len(r)

Sample output (took quite a while, since we are calling the function 5000000 times):
-0.0156148

Edit: Thanks to Howard and Danny for further golfing.
EDIT: now the program checks for whether there is enough money to make the bet. This actually saves bytes.

Some minor savings: you may replace c=='L' with c<'W'=. You can also write b,n=((n,1),(-n,2*n))[c<'W'] which then saves you more chars (if a<-b:break,a+=b).

@Howard Hmm. I tried the b,n= trick (with [s on the outside), but python complained. Let's try again.

Strange, have a look here.

@Howard Ah, that's what the c<'W' does. < is a strange python syntax for "is in"

I think your function yields the wrong result for 2 LW. It assumes you can place a bet for winning but you actually don't have enough money.

@Howard fixed, and it saves bytes :-)

Wouldn't if n<=a and save you some char since you won't have to break then?

@Quincinx: No, < just means less than. Strings are ordered lexicographically, so 'L'<'W' returns True, which is interpreted as 1, while 'W'<'W' returns False, which is interpreted as 0.

R, 95 characters
g=function(a,r){n=1;for(i in 1:nchar(r)){s=substr(r,i,i);if(s=='L'){a=a-n;n=n*2}else{a=a+n;n=1};if(n>a)break};a}

Indented:
g=function(a,r){
    n=1
    for(i in 1:nchar(r)){
        s=substr(r,i,i)
        if(s=='L'){
            a=a-n
            n=n*2
            }else{
                a=a+n
                n=1
                }
        if(n>a)break
        }
    a
    }

Usage:
> g(15,'LLWLLLL')
[1] 1
> g(20,'WLLW')
[1] 22
> g(13,'LLWLLLLWWLWWWLWLWW')
[1] 7

J - 63 55 char
Now with the added bonus of not being incorrect! It's even exactly as long as before.
((+/\@,(0{<#[)_,~|@]);@('W'<@(2^i.@#);.1@,}:)*_1^=&'L')

Takes the starting amount of money as the left argument and the win/loss streak on the right.
Explanation: The program splits evenly into something like a composition of two functions, both detailed below. The first turns the win/loss streak into the values of the bets, with corresponding sign, and then the second actually figures out the answer given the initial money and this transformed win/loss streak.
;@('W'<@(2^i.@#);.1@,}:)*_1^=&'L'   NB. win/loss as sole argument
                         _1^=&'L'   NB. -1 for every L, +1 for W
      <@(      );.1                 NB. split vector into streaks:
   'W'              ,}:             NB.  cut on wins, shift right by 1
         2^i.@#                     NB. for each, make doubling run
;@(                    )*           NB. unsplit, multiply by signs

(+/\@,(0{<#[)_,~|@])   NB. money on left, above result on right
                |@]    NB. absolute value of bets
             _,~       NB. append infinity to end
 +/\@,                 NB. partial sums with initial money
      (  <  )          NB. 1 whenever money in account < bet
          #[           NB. select those money values corresp. to 1s
       0{              NB. take first such item

Note that we prepend the money to the bets before taking the partial sums, but we append the infinite bet to the end of the list of bet values. This is what shifts the value of the account overtop of the next bet, and using infinity allows us to always have the last element as a catch-all.
Usage:
   15 ((+/\@,(0{<#[)_,~|@]);@('W'<@(2^i.@#);.1@,}:)*_1^=&'L') 'LLLWLLLL'
1
   NB. naming for convenience
   f =: ((+/\@,(0{<#[)_,~|@]);@('W'<@(2^i.@#);.1@,}:)*_1^=&'L')
   20 f 'WLLW'
22
   2 f 'LW'
1
   13 f 'LLWLLLLWWLWWWLWLWW'
7
   12 13 14 15 28 29 30 31 (f"0 _) 'LLWLLLLWWLWWWLWLWW'  NB. for each left argument
6 7 0 1 14 15 39 40

I tested your code and it also returns 3 for the test case 2 LW. Unfortunately after the first loss you don't have enough money to even bet for the second run.

With 14 f 'LLWLLLLWWLWWWLWLWW', we get this sequence: 14, 13, 11, 15, 14, 12, 8, 0,.. at the 0, we don't have enough money to bid, so the program should output 0.

Is this code is correct now?  I need to designate a winner and don't have a J compiler (nor time to start the experience).

@TheSoftwareJedi Yes, it is correct. There is actually an online Javascript version of the J interpreter, now, that you can try at tryj.tk.

Now the dilemma, does Golfscript count?!

@TheSoftwareJedi Why wouldn't it?

JavaScript (ECMAScript 6 Draft) - 62 51 50 Characters (in function body)
function g(a,r,t=0,b=1)
a>=b&&(c=r[t])?g((c=c>'L')?a+b:a-b,r,t+1,c||2*b):a

Defines a recursive function g with two arguments:

a - the current amount of money you have; and
r - the string of wins/losses.

And two optional arguments:

t - the index of the current round of betting (initially 0)
b - the amount of money for the current bet (again initially 1).

Ungolfed:
function g(a,r,t=0,b=1){      // declare a function g with arguments a,r,t,b where
                              // t defaults to 0 and b defaults to 1
c = r[t];                     // get the character in the win/loss string for the current
                              // round.
if (   a>=b                   // check if we have enough money
    && c )                    // and if the string has not ended
{
  if ( c > 'L' )              // check if we've won the round
  {
    return g(a+b,r,t+1,1);    // if so call g again adding the winnings and resetting the
                              // cost.
  } else {
    return g(a-b,r,t+1,2*b);  // otherwise, subtract from the total money and double the
                              // cost.
  }
} else {
  return a;                   // If we've run out of money or got to the end then return
                              // the current total.
}}

JavaScript (ECMAScript 6) - 61 58 54 Characters (in function body)
function g(a,r)
(b=1,[b=b>a?b:x>'L'?(a+=b,1):(a-=b,b*2)for(x of r)],a)

Explanation:
(b=1,                        // Initialise the cost to 1
 [                           // for each character x of r using array comprehension
     b=
       b>a?b                 // if we have run out of money do b=b
       :x>'L'?(a+=b,1)       // else if we've won collect the winnings and reset b=1
             :(a-=b,2*b)     // else subtract the cost from the total money and double
                             // the cost for next round.
  for(x of r)]               // Repeat for each character
                             // array.
,a)                          // Finally, return a.

Tests
console.log(g(0,'LLLLLWWLWWLW')) // 0
console.log(g(1,'WWWLLLWWWWLLWW')) //1
console.log(g(2,'LLWLWWWWWWWL')) //1
console.log(g(3,'WWWWWWWLLLWL')) //3
console.log(g(4,'LWWLWLWWWL')) //9
console.log(g(5,'LLLWWWLLWLWW')) //2
console.log(g(6,'LWLLLLWWLWWW')) //0
console.log(g(7,'WWLWWLLLWLWLW')) //4
console.log(g(8,'WWLWWLLWLWL')) //13
console.log(g(9,'WWWLLLWLLWLWWW')) //5
console.log(g(10,'WLWLLWWWWWWWL')) //18
console.log(g(11,'WLWLWLWLLLWLLW')) //17
console.log(g(12,'WWLWWWLLWL')) //17
console.log(g(13,'WWWWLWLWWW')) //21
console.log(g(15,'LLLW')) //16
console.log(g(15,'LLLL')) //0
console.log(g(14,'LLLL')) //7
console.log(g(2,'LW')) //1
console.log(g(2,'LL')) //1
console.log(g(2,'WLL')) //0

You can save 3 bytes changing b=1,r.split('').map( to [b=1].map.call(r,

Thanks, I'd not considered manipulating the String directly like that.

Chop another 4 bytes using array comprehension :) (b=1,[b=b>a?b:x>'L'?(a+=b,1):(a-=b,b*2)for(x of r)],a)

-1 byte: a>=b&&(c=r[t])?g((c=c>'L')?a+b:a-b,r,t+1,c||2*b):a

C#, 123
return q.Aggregate(new{b=1,c=w,x=1},(l,o)=>l.x<0?l:o=='W'?new{b=1,c=l.c+l.b,x=1}:new{b=l.b*2,c=l.c-l.b,x=l.c-l.b-l.b*2}).c;

The .NET Fiddle
A blog post explaining

Instead of just posting those two links with the code, bring the explanations there over here.

I'd love to man, and will edit in the AM. It was a hurry up and finish ordeal. I've not been active on SO in a while, bear with me as I accept that it's not in it's infancy anymore. :)

According to your .NET Fiddle, you are taking your arguments backwards. Is this allowed?

I'd made the function definition irrelevant to the solution in the question.  The fiddle isn't part of the answer, just a way to execute it.

Python, 74 bytes
def g(a,r,b=1):
 for l in r:
  if l>"L":a+=b;b=1
  else:a-=b;b*=2
 return a

I defined function g which takes a (the amount of money you have at start) and r (which is the results of the bets)
It initializes the amount of the first bet at 1.
Then for each result of the bets, if it is a win ("W" in r) you gain the money and bet comes back to 1. Else you lose the amount of the bet, and the amount for the next bet doubles.
Finally it returns the money you have.
You can use it like this:
print g(20,"WLLW") # 22
print g(15,"LLLWLLLL") # 1

I think this can be golfed furthermore.

This is basically a duplicate of http://codegolf.stackexchange.com/a/26238/9498.

C, 107 characters
f(int a,char*r,int n){return*r&&n<a?*r<77?f(a-n,r+1,n*2):f(a+n,r+1,1):a;}g(int a, char*r){return f(a,r,1);}

I'm using a recursive function here, because most of the time the implementation is shorter. But I'm not quite sure if it is the case here, because I needed to make an additional wrapper function so my function does in fact only take 2 arguments. The third argument in function f is needed for the current bet (the accumulator).
Without the wrapper function this solution would only be 73 characters long, but you would need to pass an additional parameter with the value 1 (the inital bet) to get the proper result.
ungolfed:
f(int a,char*r,int n){
    return *r&&n<a
                ?*r<77
                    ?f(a-n,r+1,n*2)
                    :f(a+n,r+1,1)
                :a;
}
g(int a,char*r){
    return f(a,r,1);
}

Ruby, 76 64 (in function body) bytes
EDIT :
improved the answer by removing 3 bytes :
n=1;r.each_char{|c|;c>'L'?(a+=n;n=1):(a-=n;n*=2);break if n>a};a

using func (82 bytes) :
def g(a,r);n=1;r.each_char{|c|;c>'L'?(a,n=a+n,1):(a,n=a-n,n*2);break if n>a};a;end

using lambda (76 bytes) :
g=->a,r{n=1;r.each_char{|c|;c>'L'?(a,n=a+n,1):(a,n=a-n,n*2);break if n>a};a}

the run :
p g.call(15, 'LLLWLLLL') # 1
p g.call(20, 'WLLW') # 22
p g.call(13, 'LLWLLLLWWLWWWLWLWW') # 7

C, 90
g(int a,char*r){int c=1;while(*r){*r++%2?c=1,a++:(c*=2);if(c>a){c/=2;break;}}return++a-c;}

Javascript, 63
function g(a,s){x=1;for(i in s)if(x<=a)s[i]>'L'?(a+=x,x=1):(a-=x,x*=2);return a}

Sample runs:
console.log(g(15, 'LLLWLLLL'));  //1
console.log(g(20, 'WLLW'));  //22
console.log(g(13, 'LLWLLLLWWLWWWLWLWW')); //7

JSFiddle w/ logging
Ungolfed:
function g(a,s){
  x=1;                //bet starts at 1
  for(i in s)         //loop through win/lose string
    if(x<=a)          //check if we still have money to bet
      s[i]>'L'?
        (a+=x,x=1):   //win: add the bet amount to your total, and reset bet to 1
        (a-=x,x*=2);  //lose: subtract the bet amount from your total, and double your bet
  return a            //return your money
}

Javascript (ES5) 69 64 60 bytes within function
function g(a,r){b=1;for(i in r)b=b>a?b:r[i]>'L'?(a+=b,1):(a-=b,b*2);return a}

Variation: (same length)
function g(a,r,b){for(i in r)b=b?b>a?b:r[i]>'L'?(a+=b,1):(a-=b,b*2):1;return a}

Test cases: (taken from plannapus's solution)
g(15,'LLWLLLL'); // 1
g(20,'WLLW'); // 22
g(13,'LLWLLLLWWLWWWLWLWW'); // 7

g(20,'WLLW') returns 25 in my FireFox console - the for...in loop picks up three extra properties in the string and iterates over them as well.

@MT0 same thing happens in my Firefox console. However if I open a new private browsing window I get 22 in my console. Thinking maybe some site that your on when you have the console open modified the String prototype. I know stackexchange does modify it and add three extra functions.

For some reason, it doesn't happen with a new tab: http://i.imgur.com/BgSUSIe.png

Golfscript, 51 41 36 35 bytes
Inner function
1\{@2$-@2*@(1&{@@+1@}*.3$3$<!*}do;;

This assumes that we start with a positive amount of money and that the win-loss string will be non-empty, so that at least one bet can be performed.
Example
{
  # Push initial bet amount.
  1\
  # STACK: Money Bet Outcomes
  {
    # Subtract bet amount from money.
    @2$-
    # STACK: Bet Outcomes Money
    # Double bet amount.
    @2*
    # STACK: Outcomes Money Bet
    # Remove first character from win-loss string and check if its ASCII code is odd.
    @(1&
    # STACK: Money Bet Outcomes Boolean
    # If it is, we've won, so add the doubled bet amount to the money and push 1 as the
    # new bet amont.
    {@@+1@}*
    # STACK: Money Bet Outcomes
    # Duplicate win-loss string, bet amonut and money.
    .3$3$
    # STACK: Money Bet Outcomes Outcomes Bet Money
    # If the next bet amount is less than our money and the win-loss string is not empty,
    # repeat the loop.
    <!*
    # STACK: Money Bet Outcomes Boolean
  }do
  # STACK: Money Bet Outcomes
  ;;
  # STACK: Money
}:f                                      # Define function.

];                                       # Clear stack.

20 'WLLW'               f
2  'LW'                 f
13 'LLWLLLLWWLWWWLWLWW' f
14 'LLWLLLLWWLWWWLWLWW' f

]p                                       # Print results as array.

gives
[22 1 7 0]

Try it online.

Haskell, 62
g a=fst.foldl(\(t,b)l->if l=='W'then(t+b,1)else(t-b,2*t))(a,1)

or with both arguments named (65 chars):
g a r=fst$foldl(\(t,b)l->if l=='W'then(t+b,1)else(t-b,2*t))(a,1)r

Note that g a r = 1 + a + the number of Ws in r + the number of trailing Ls in r (69):
g a r=a+1+l(filter(=='W')r)-2^l(takeWhile(/='W')(reverse r))
l=length

This is only a partial solution. It doesn't cover the case when the player runs out of money.

There are a lot of solutions to this problem which allow the bettor to be in the negative.  The problem never stated that you had to check whether this was the case.

@zaq Actually yes, the question explicitly stated that was the case.

Python 2 – 65 bytes
Now beaten by the current best Python solution, but I cannot not share it:
def g(r,a,b=1):
    if r>"">a>=b:a=g(r[1:],*[(a+b,1),(a-b,b*2)][r[0]<"W"])
    return a

As some other Python solutions, I use the function arguments for declaring b outside the function definition, but as the function is recursive, this actually serves some purpose other than golfing here.
I also needed to change the order of the function arguments in order for the tuple unpacking into function arguments to work.
In case you wonder, r>"">a>=b is short for r and a>=b.

C#, 74 characters inside method
My very first attempt on this site...
int b=1;foreach(var c in r)if(b<=a){a+=c>'L'?b:-b;b=c>'L'?1:b*2;}return a;

Or, more readable:
int bet = 1;
foreach (var chr in r)
{                       // these brackets are left out in short version
   if (bet <= a)
   {
       a += chr > 'L' ? bet : -bet;
       bet = chr > 'L' ? 1 : bet * 2;
   }
}
return a;

Pretty naive, not that many tricks... mainly taking advantage of char being ordinal and string being enumerable. Saving a few characters by extraneous looping when player runs out of money.

Java, 93 bytes (inside function)
-2 bytes thanks to ceilingcat
int b=1;for(int c:r.getBytes()){if(m<b)return m;if(c<87){m-=b;b*=2;}else{m+=b;b=1;}}return m;

Try it online!

@ceilingcat fair

Suggest break instead of the first return m

Ruby, 84 characters
def g(a,r,n=1)
return a if !r[0]||n>a
s=r[1..-1]
r[0]<?M?g(a-n,s,n*2):g(a+n,s,1)
end

Same approach as my other answer in C, but I wanted to try ruby for Code-Golfing. The advantage to the C version is that I don't need to create a wrapper function, I can simply use the default values for parameters.

K, 76
g:{x+/-1_last'{(,1_*x),(("LW"!/:((2*;{1});(-:;::)))@\:**x)@\:x 1}\[(y;1;0)]}

.
k)g[15;"LLLWLLLL"]
1
k)g[20;"WLLW"]
22
k)g[50;"WLLLWLWLWLWLW"]
56

C - 64 59 (Inside function)
Yet another C answer. It takes advantage of the fact that the value of the variable stays on the stack. So this my fail with some compilers, but it did work properly wherever I tested. Also, I took the %2 from tia to save a character. Sorry!
f(int s,char*r){
    int a=1;
    for(;*r&&(*r++%2?s+=a,a=1:s<a?0:(s-=a,a*=2)););
    a=s;
}

Python, 86
def y(a,s):
 for l in s.split('W'):
    a+=1;k=2**len(l)
    if k>a:return int(bin(a)[3:],2)
 return a-k

I know this is nowhere near the shortest solution, but I wanted to demonstrate a different approach, that iterates over loss streaks rather than individual bets. int(bin(a)[3:],2) gives the integer with the most significant bit from the binary representation of a deleted, which is the amount of money the person will have after losing increasing powers of 2 until he or she can no longer bet, because a is currently 1 higher than his or her actual amount of money. This version assumes the initial capital is positive.

Batch - 212
@echo off&setlocal enabledelayedexpansion&set r=%2&set a=%1&set c=1&powershell "&{'%2'.length-1}">f&set/pl=<f
for /l %%a in (0,1,%l%)do if "!r:~%%a,1!"=="L" (set/aa-=!c!&set/ac*=2) else set/aa+=!c!&set c=1
echo %a%

Expample -
H:\uprof>bet.bat 15 LLLWLLLL
1

Japt, 38 bytes
V¬r@Z=WX<Z?X:Y¶'L?W=ZÑX-Z:(W=1X+Z}UW=1

Try it
Probably needs some golfing :) But it seems to getting correct results.
NOTE This is a full program that is trivial to turn into a function by prepending UV{. The byte count inside the function will be the same.
Transpiled JS Explained:
// V: input string of W's and L's
V
  // split V into an array of characters
  .q()
  // reduce
  .r(function(X, Y, Z) {
    return
      // W contains the current bet,
      // save it to a temp variable Z
      Z = W,
      // do we have enough to bet?
      X < Z
        // not enough to bet, return the previous amount
        ? X
         // we can bet, did we lose this round
         : Y === "L"
           // we lost, increment bet and decrease holdings
           ? (W = Z * 2, X - Z)
           // we won, reset bet and increase holdings
           : (W = 1, X + Z)
   },
   // U: initial holdings
   U,
   // initialize bet to 1
   W = 1
 )

35 bytes?

This question has kind of a strange requirement that you must write a "function". I probably should translate my answer to a function, but I am thinking some of the extra bytes are needed. This would probably be ok though: https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=VqxyQD1XWDxVP1g6WbYnTD9XPVXRWC1VOihXPTFYK1V9VVc9MQ==&input=NQonTExMV1dXTExXTFdXJw==

PowerShell, 68 81 bytes
param($n,$s)$w=1;$s|% t*y|%{if($n-ge$w){$n+=(-$w,$w)[$_%2];$w/=(.5,$w)[$_%2]}};$n

Try it online!
This challenge needs some very awkward assignments meaning I couldn't chain together one big update. It does use the fact that 'W' is 87 in ASCII and 'L' is 76 so modding by 2 gives you access to easy true/false values. |% t*y is the standard toCharArray shortcut and updating the wager using division turned out to be the cheapest way I could find (divides it either by a half on a loss (doubling it), or divides it by itself on a win (setting it to 1)).
Plus many bytes because I missed constraint. Will work on golfing down the patch

05AB1E, 19 bytes
vDX@iy'WQiX+1UëXxU-

Port of @Howard's GolfScript answer, so make sure to upvote him as well!
Note that 05AB1E has no functions, so this is a full program instead.
Takes the string input first, and the integer input second (newline delimited in STDIN).
Try it online or verify some more test cases.
Explanation:
v               # Loop over each character `y` of the (implicit) input-string:
 D              #  Duplicate the current integer
                #  (which is the implicit input-integer in the first iteration)
  X@i           #  If the integer is larger than or equal to variable `X`:
                #  (NOTE: variable `X` is 1 by default)
     y'WQi     '#   If the current character `y` is a 'W':
          X+    #    Increase the integer by `X`
          1U    #    And reset variable `X` to 1
         ë      #   Else (the current character `y` is an 'L' instead):
          X  -  #    Decrease the integer by `X`
           xU   #    And set variable `X` to double its current value
                # (the integer at the top of the stack is implicitly output after the loop)

all_licenses: 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/


text:
Build an EBCDIC converter using NAND logic gates
In this question, a mapping is defined between EBCDIC and a superset of ISO-8859-1.
Your task is to build a network of two-input NAND gates that will take eight inputs A1, A2, A4, ..., A128 representing an EBCDIC character and return eight outputs B1, B2, B4, ..., B128 that represent the corresponding "ISO-8859-1" character according to that mapping.
To simplify things, you may use AND, OR, NOT, and XOR gates in your diagram, with the following corresponding scores:

NOT: 1
AND: 2
OR: 3
XOR: 4

Each of these scores corresponds to the number of NAND gates that it takes to construct the corresponding gate.
The logic circuit that uses the fewest NAND gates to correctly implement all the above requirements wins.

727 Gates

How I did it:

turned the code page translation from wikipedia into an appropriately formatted truth table using Excel (15 minutes)
minimized the truth table using Espresso (5 minutes, 30 minutes on 1st iteration getting back into the saddle)
fed the minimized truth table into a schematic generator (1 minute)
iterated on 2&3 until I got a reasonable answer (<1 hour)
turned the schematic into an uploadable image (30 min, %$#@! Microsoft)

Here's the 100% NAND gate result:

If I was actually going to implement this, I'd drop the NAND-centric scoring. Building XOR gates out of NANDs is a big waste of transistors. Then I'd start worrying about UMC, fire up the FPGA design tools, maybe break out the HDL manuals, etc. Whew! I love software.

NB, for hobbyists interested in FPGAs, I'll recommend FPGA4fun.

even when viewing image in new tab parts are unrecognizable :(

I decided to upload the largest image that fit on my screen. The original, at 23339x8538, kills browsers -- literally. Chrome "Aw, snap!"ed and Firefox just refused to load it. IE displays it, but hangs for a while preparing it.

zipping and then uploading that to your favourite cloud hoster should work case browser sdon't display images in zips

@masterX244 I could upload the gigantic bitmap, but (1) StackExchange wants us to upload to imgur.com to avoid link-rot and Imgur would have reduced the resolution anyway. (2) If Imgur didn't reduce the resolution, every visitor to this page using Chrome would see "Aw, snap!" as it tried to read the entire image before scaling. (3) WYSIWYG; this answer ain't worth revising again.

#309 NANDs#
A really low solution in the number of NANDs, but I can go even lower. One just have to stop somewhere, some time, and 309 seems good for that.
No pencil drawn image of the circuit this time. Perhaps later if I some day return to this problem and hit a lower edge, ledge, limit, in the increasingly dense thicket of wrong circuits.
The circuit is presented in obvious Verilog code, ready for running with test included.
Verilog code:
// EBCDIC to ISO-latin-1 converter circuit
// Made of just 309 NANDs
//
// By Kim Øyhus 2018 (c) into (CC BY-SA 3.0)
// This work is licensed under the Creative Commons Attribution     3.0
// Unported License. To view a copy of this license, visit
// https://creativecommons.org/licenses/by-sa/3.0/
//
// This is my entry to win this Programming Puzzle & Code Golf
// at Stack Exchange:
// https://codegolf.stackexchange.com/questions/26252/build-an-ebcdic-converter-using-nand-logic-gates
//
// There are even simpler solutions to this puzzle,
// but I just had to stop somewhere, and 309 NAND gates is
// a very low number anyway.

module EBCDIC_to_ISO_latin_1 ( in_000, in_001, in_002, in_003, in_004, in_005, in_006, in_007, out000, out001, out002, out003, out004, out005, out006, out007 );
  input  in_000, in_001, in_002, in_003, in_004, in_005, in_006, in_007;
  output out000, out001, out002, out003, out004, out005, out006, out007;
  wire   wir000, wir001, wir002, wir003, wir004, wir005, wir006, wir007, wir008, wir009, wir010, wir011, wir012, wir013, wir014, wir015, wir016, wir017, wir018, wir019, wir020, wir021, wir022, wir023, wir024, wir025, wir026, wir027, wir028, wir029, wir030, wir031, wir032, wir033, wir034, wir035, wir036, wir037, wir038, wir039, wir040, wir041, wir042, wir043, wir044, wir045, wir046, wir047, wir048, wir049, wir050, wir051, wir052, wir053, wir054, wir055, wir056, wir057, wir058, wir059, wir060, wir061, wir062, wir063, wir064, wir065, wir066, wir067, wir068, wir069, wir070, wir071, wir072, wir073, wir074, wir075, wir076, wir077, wir078, wir079, wir080, wir081, wir082, wir083, wir084, wir085, wir086, wir087, wir088, wir089, wir090, wir091, wir092, wir093, wir094, wir095, wir096, wir097, wir098, wir099, wir100, wir101, wir102, wir103, wir104, wir105, wir106, wir107, wir108, wir109, wir110, wir111, wir112, wir113, wir114, wir115, wir116, wir117, wir118, wir119, wir120, wir121, wir122, wir123, wir124, wir125, wir126, wir127, wir128, wir129, wir130, wir131, wir132, wir133, wir134, wir135, wir136, wir137, wir138, wir139, wir140, wir141, wir142, wir143, wir144, wir145, wir146, wir147, wir148, wir149, wir150, wir151, wir152, wir153, wir154, wir155, wir156, wir157, wir158, wir159, wir160, wir161, wir162, wir163, wir164, wir165, wir166, wir167, wir168, wir169, wir170, wir171, wir172, wir173, wir174, wir175, wir176, wir177, wir178, wir179, wir180, wir181, wir182, wir183, wir184, wir185, wir186, wir187, wir188, wir189, wir190, wir191, wir192, wir193, wir194, wir195, wir196, wir197, wir198, wir199, wir200, wir201, wir202, wir203, wir204, wir205, wir206, wir207, wir208, wir209, wir210, wir211, wir212, wir213, wir214, wir215, wir216, wir217, wir218, wir219, wir220, wir221, wir222, wir223, wir224, wir225, wir226, wir227, wir228, wir229, wir230, wir231, wir232, wir233, wir234, wir235, wir236, wir237, wir238, wir239, wir240, wir241, wir242, wir243, wir244, wir245, wir246, wir247, wir248, wir249, wir250, wir251, wir252, wir253, wir254, wir255, wir256, wir257, wir258, wir259, wir260, wir261, wir262, wir263, wir264, wir265, wir266, wir267, wir268, wir269, wir270, wir271, wir272, wir273, wir274, wir275, wir276, wir277, wir278, wir279, wir280, wir281, wir282, wir283, wir284, wir285, wir286, wir287, wir288, wir289, wir290, wir291, wir292, wir293, wir294, wir295, wir296, wir297, wir298, wir299, wir300, wir301, wir302;

  nand gate000 ( wir000, in_003, in_000 );
  nand gate001 ( wir001, in_002, in_002 );
  nand gate002 ( wir002, in_000, in_000 );
  nand gate003 ( wir003, in_000, in_004 );
  nand gate004 ( wir004, wir003, in_001 );
  nand gate005 ( wir005, in_006, in_003 );
  nand gate006 ( wir006, wir003, wir005 );
  nand gate007 ( wir007, in_007, in_007 );
  nand gate008 ( wir008, wir003, wir004 );
  nand gate009 ( wir009, wir003, wir006 );
  nand gate010 ( wir010, in_005, wir009 );
  nand gate011 ( wir011, wir008, wir009 );
  nand gate012 ( wir012, wir009, wir011 );
  nand gate013 ( wir013, in_004, wir002 );
  nand gate014 ( wir014, wir013, wir009 );
  nand gate015 ( wir015, in_006, wir007 );
  nand gate016 ( wir016, wir001, wir015 );
  nand gate017 ( wir017, wir015, wir015 );
  nand gate018 ( wir018, in_003, wir015 );
  nand gate019 ( wir019, wir018, wir018 );
  nand gate020 ( wir020, wir000, wir007 );
  nand gate021 ( wir021, wir005, wir017 );
  nand gate022 ( wir022, wir018, wir011 );
  nand gate023 ( wir023, in_002, wir018 );
  nand gate024 ( wir024, in_001, in_003 );
  nand gate025 ( wir025, wir010, in_004 );
  nand gate026 ( wir026, wir017, wir024 );
  nand gate027 ( wir027, wir001, wir007 );
  nand gate028 ( wir028, in_004, wir024 );
  nand gate029 ( wir029, wir024, wir024 );
  nand gate030 ( wir030, in_004, wir023 );
  nand gate031 ( wir031, wir022, wir030 );
  nand gate032 ( wir032, wir026, wir030 );
  nand gate033 ( wir033, wir030, wir020 );
  nand gate034 ( wir034, wir001, wir026 );
  nand gate035 ( wir035, wir022, in_007 );
  nand gate036 ( wir036, wir020, wir034 );
  nand gate037 ( wir037, wir007, wir023 );
  nand gate038 ( wir038, wir034, wir023 );
  nand gate039 ( wir039, wir031, wir033 );
  nand gate040 ( wir040, wir028, wir019 );
  nand gate041 ( wir041, wir036, wir040 );
  nand gate042 ( wir042, in_001, wir025 );
  nand gate043 ( wir043, wir041, wir010 );
  nand gate044 ( wir044, wir038, wir000 );
  nand gate045 ( wir045, wir033, wir004 );
  nand gate046 ( wir046, wir039, wir045 );
  nand gate047 ( wir047, in_002, wir046 );
  nand gate048 ( wir048, wir011, wir037 );
  nand gate049 ( wir049, wir012, in_006 );
  nand gate050 ( wir050, wir048, wir007 );
  nand gate051 ( wir051, wir048, wir049 );
  nand gate052 ( wir052, in_006, in_004 );
  nand gate053 ( wir053, wir043, wir001 );
  nand gate054 ( wir054, wir042, wir053 );
  nand gate055 ( wir055, wir019, wir007 );
  nand gate056 ( wir056, wir016, wir039 );
  nand gate057 ( wir057, in_003, wir026 );
  nand gate058 ( wir058, wir029, in_007 );
  nand gate059 ( wir059, in_005, wir055 );
  nand gate060 ( wir060, wir035, wir054 );
  nand gate061 ( wir061, wir055, wir060 );
  nand gate062 ( wir062, wir032, in_003 );
  nand gate063 ( wir063, wir002, wir059 );
  nand gate064 ( wir064, wir062, wir025 );
  nand gate065 ( wir065, wir063, wir036 );
  nand gate066 ( wir066, wir060, wir065 );
  nand gate067 ( wir067, wir037, wir065 );
  nand gate068 ( wir068, wir029, in_006 );
  nand gate069 ( wir069, wir067, wir043 );
  nand gate070 ( wir070, wir061, wir069 );
  nand gate071 ( wir071, wir047, wir070 );
  nand gate072 ( wir072, wir071, wir071 );
  nand gate073 ( wir073, wir071, wir038 );
  nand gate074 ( wir074, wir010, wir073 );
  nand gate075 ( wir075, wir021, wir038 );
  nand gate076 ( wir076, wir028, wir066 );
  nand gate077 ( wir077, wir076, wir056 );
  nand gate078 ( wir078, wir077, wir077 );
  nand gate079 ( wir079, wir072, wir013 );
  nand gate080 ( wir080, wir079, wir026 );
  nand gate081 ( wir081, wir080, wir080 );
  nand gate082 ( wir082, wir078, wir025 );
  nand gate083 ( wir083, wir022, wir082 );
  nand gate084 ( wir084, in_001, wir083 );
  nand gate085 ( wir085, wir044, wir083 );
  nand gate086 ( wir086, wir085, wir081 );
  nand gate087 ( wir087, wir027, wir086 );
  nand gate088 ( wir088, wir087, wir007 );
  nand gate089 ( wir089, wir074, wir087 );
  nand gate090 ( wir090, wir051, wir075 );
  nand gate091 ( wir091, wir068, wir089 );
  nand gate092 ( wir092, wir091, wir091 );
  nand gate093 ( wir093, wir084, wir002 );
  nand gate094 ( wir094, wir051, wir091 );
  nand gate095 ( wir095, wir094, wir042 );
  nand gate096 ( wir096, wir021, wir094 );
  nand gate097 ( wir097, wir093, wir096 );
  nand gate098 ( wir098, wir096, wir044 );
  nand gate099 ( wir099, wir063, wir096 );
  nand gate100 ( wir100, wir088, wir026 );
  nand gate101 ( wir101, wir090, wir099 );
  nand gate102 ( wir102, wir101, wir101 );
  nand gate103 ( wir103, wir100, wir066 );
  nand gate104 ( wir104, wir057, wir102 );
  nand gate105 ( wir105, wir102, wir092 );
  nand gate106 ( wir106, wir102, wir059 );
  nand gate107 ( wir107, wir038, wir103 );
  nand gate108 ( wir108, wir072, wir102 );
  nand gate109 ( wir109, wir108, wir052 );
  nand gate110 ( wir110, wir052, wir021 );
  nand gate111 ( wir111, wir100, wir110 );
  nand gate112 ( wir112, wir110, wir106 );
  nand gate113 ( wir113, wir109, wir112 );
  nand gate114 ( wir114, wir104, wir038 );
  nand gate115 ( wir115, in_007, wir113 );
  nand gate116 ( wir116, wir060, wir115 );
  nand gate117 ( wir117, wir115, wir058 );
  nand gate118 ( wir118, wir117, wir038 );
  nand gate119 ( wir119, wir117, wir117 );
  nand gate120 ( wir120, wir116, in_006 );
  nand gate121 ( wir121, wir093, wir081 );
  nand gate122 ( wir122, wir119, wir120 );
  nand gate123 ( wir123, wir120, wir002 );
  nand gate124 ( wir124, wir119, in_007 );
  nand gate125 ( wir125, wir052, wir120 );
  nand gate126 ( wir126, wir120, wir020 );
  nand gate127 ( wir127, wir020, wir126 );
  nand gate128 ( wir128, wir126, wir124 );
  nand gate129 ( wir129, wir128, wir106 );
  nand gate130 ( wir130, wir100, wir104 );
  nand gate131 ( wir131, in_007, wir128 );
  nand gate132 ( wir132, wir061, wir128 );
  nand gate133 ( wir133, wir064, wir050 );
  nand gate134 ( wir134, wir068, wir093 );
  nand gate135 ( wir135, wir134, wir044 );
  nand gate136 ( wir136, wir127, wir121 );
  nand gate137 ( wir137, wir095, wir136 );
  nand gate138 ( wir138, wir105, wir137 );
  nand gate139 ( wir139, wir058, wir138 );
  nand gate140 ( wir140, wir138, wir118 );
  nand gate141 ( wir141, wir078, wir131 );
  nand gate142 ( wir142, wir140, wir140 );
  nand gate143 ( wir143, wir129, wir140 );
  nand gate144 ( wir144, wir129, wir109 );
  nand gate145 ( wir145, wir090, in_005 );
  nand gate146 ( wir146, wir145, wir145 );
  nand gate147 ( wir147, wir133, wir059 );
  nand gate148 ( wir148, wir093, wir147 );
  nand gate149 ( wir149, wir148, wir148 );
  nand gate150 ( wir150, wir131, wir131 );
  nand gate151 ( wir151, wir143, wir116 );
  nand gate152 ( wir152, wir021, wir132 );
  nand gate153 ( wir153, wir144, wir051 );
  nand gate154 ( wir154, wir122, wir149 );
  nand gate155 ( wir155, wir149, wir142 );
  nand gate156 ( wir156, in_001, wir149 );
  nand gate157 ( wir157, wir123, wir098 );
  nand gate158 ( wir158, wir058, wir133 );
  nand gate159 ( wir159, in_007, wir158 );
  nand gate160 ( wir160, wir133, wir157 );
  nand gate161 ( wir161, wir129, wir159 );
  nand gate162 ( wir162, wir059, wir100 );
  nand gate163 ( wir163, wir130, wir159 );
  nand gate164 ( wir164, wir152, wir146 );
  nand gate165 ( wir165, wir164, wir155 );
  nand gate166 ( wir166, wir121, wir164 );
  nand gate167 ( wir167, wir166, wir157 );
  nand gate168 ( wir168, wir167, wir058 );
  nand gate169 ( wir169, wir059, wir104 );
  nand gate170 ( wir170, wir139, wir169 );
  nand gate171 ( wir171, wir135, wir168 );
  nand gate172 ( wir172, wir171, wir156 );
  nand gate173 ( wir173, wir025, in_004 );
  nand gate174 ( wir174, wir172, wir143 );
  nand gate175 ( wir175, wir000, wir172 );
  nand gate176 ( wir176, wir154, wir172 );
  nand gate177 ( wir177, wir176, wir162 );
  nand gate178 ( wir178, wir111, in_005 );
  nand gate179 ( wir179, in_004, wir144 );
  nand gate180 ( wir180, wir162, wir178 );
  nand gate181 ( wir181, wir173, wir141 );
  nand gate182 ( wir182, wir180, wir131 );
  nand gate183 ( wir183, wir154, wir182 );
  nand gate184 ( wir184, wir090, wir183 );
  nand gate185 ( wir185, wir184, wir179 );
  nand gate186 ( wir186, wir107, wir058 );
  nand gate187 ( wir187, wir097, wir184 );
  nand gate188 ( wir188, wir016, wir177 );
  nand gate189 ( wir189, wir114, wir188 );
  nand gate190 ( wir190, wir189, wir143 );
  nand gate191 ( wir191, wir109, wir190 );
  nand gate192 ( wir192, wir185, wir190 );
  nand gate193 ( wir193, wir190, in_004 );
  nand gate194 ( wir194, wir193, wir135 );
  nand gate195 ( wir195, wir192, wir165 );
  nand gate196 ( wir196, wir194, wir161 );
  nand gate197 ( wir197, wir161, wir196 );
  nand gate198 ( wir198, wir196, wir185 );
  nand gate199 ( wir199, wir198, wir198 );
  nand gate200 ( wir200, wir155, wir181 );
  nand gate201 ( wir201, wir200, wir119 );
  nand gate202 ( wir202, in_006, wir090 );
  nand gate203 ( wir203, in_001, wir052 );
  nand gate204 ( wir204, wir185, wir202 );
  nand gate205 ( wir205, wir175, wir198 );
  nand gate206 ( wir206, wir205, wir150 );
  nand gate207 ( wir207, wir205, wir200 );
  nand gate208 ( wir208, wir207, wir168 );
  nand gate209 ( wir209, wir208, wir185 );
  nand gate210 ( wir210, wir144, wir199 );
  nand gate211 ( wir211, wir210, wir187 );
  nand gate212 ( wir212, wir210, wir135 );
  nand gate213 ( wir213, wir187, wir144 );
  nand gate214 ( wir214, wir151, wir210 );
  nand gate215 ( wir215, wir143, wir105 );
  nand gate216 ( wir216, wir021, wir215 );
  nand gate217 ( wir217, wir160, wir160 );
  nand gate218 ( wir218, wir186, wir061 );
  nand gate219 ( wir219, wir216, wir025 );
  nand gate220 ( wir220, wir219, wir122 );
  nand gate221 ( wir221, wir212, wir219 );
  nand gate222 ( wir222, wir209, wir105 );
  nand gate223 ( wir223, wir191, wir213 );
  nand gate224 ( wir224, wir168, wir221 );
  nand gate225 ( wir225, wir224, wir224 );
  nand gate226 ( wir226, wir144, wir209 );
  nand gate227 ( wir227, wir020, wir222 );
  nand gate228 ( wir228, wir129, wir226 );
  nand gate229 ( wir229, wir228, wir160 );
  nand gate230 ( wir230, wir229, wir229 );
  nand gate231 ( wir231, wir197, wir230 );
  nand gate232 ( wir232, wir230, wir214 );
  nand gate233 ( wir233, wir173, wir230 );
  nand gate234 ( wir234, wir056, wir174 );
  nand gate235 ( wir235, wir146, wir181 );
  nand gate236 ( wir236, wir235, wir225 );
  nand gate237 ( wir237, wir236, wir014 );
  nand gate238 ( wir238, wir236, wir174 );
  nand gate239 ( wir239, wir155, wir203 );
  nand gate240 ( wir240, wir209, wir236 );
  nand gate241 ( wir241, wir146, wir225 );
  nand gate242 ( wir242, wir191, wir241 );
  nand gate243 ( wir243, wir241, wir209 );
  nand gate244 ( wir244, wir206, wir111 );
  nand gate245 ( wir245, wir243, wir233 );
  nand gate246 ( wir246, wir223, wir234 );
  nand gate247 ( wir247, wir191, wir186 );
  nand gate248 ( wir248, wir056, wir238 );
  nand gate249 ( wir249, wir248, wir218 );
  nand gate250 ( wir250, wir243, wir249 );
  nand gate251 ( wir251, wir239, wir174 );
  nand gate252 ( wir252, wir251, wir231 );
  nand gate253 ( wir253, wir249, wir244 );
  nand gate254 ( wir254, wir240, wir150 );
  nand gate255 ( wir255, wir253, wir139 );
  nand gate256 ( wir256, wir242, wir253 );
  nand gate257 ( wir257, wir244, wir195 );
  nand gate258 ( wir258, wir204, wir201 );
  nand gate259 ( out007, wir254, wir255 );
  nand gate260 ( wir259, wir217, wir253 );
  nand gate261 ( wir260, wir258, wir259 );
  nand gate262 ( wir261, wir197, wir260 );
  nand gate263 ( wir262, wir220, wir261 );
  nand gate264 ( wir263, wir261, wir192 );
  nand gate265 ( wir264, wir262, wir263 );
  nand gate266 ( wir265, wir201, wir125 );
  nand gate267 ( wir266, wir265, wir250 );
  nand gate268 ( wir267, wir266, wir237 );
  nand gate269 ( wir268, wir266, wir199 );
  nand gate270 ( wir269, wir136, wir244 );
  nand gate271 ( wir270, wir264, wir195 );
  nand gate272 ( wir271, wir256, wir268 );
  nand gate273 ( wir272, wir247, wir269 );
  nand gate274 ( wir273, wir271, in_001 );
  nand gate275 ( wir274, wir256, wir271 );
  nand gate276 ( wir275, wir273, wir274 );
  nand gate277 ( wir276, wir275, wir275 );
  nand gate278 ( wir277, wir249, wir227 );
  nand gate279 ( wir278, wir222, in_006 );
  nand gate280 ( wir279, wir278, wir153 );
  nand gate281 ( wir280, wir272, wir163 );
  nand gate282 ( wir281, wir278, wir170 );
  nand gate283 ( wir282, wir245, wir281 );
  nand gate284 ( wir283, wir204, wir282 );
  nand gate285 ( out005, wir283, wir254 );
  nand gate286 ( wir284, wir232, wir201 );
  nand gate287 ( wir285, wir284, wir197 );
  nand gate288 ( wir286, wir257, wir285 );
  nand gate289 ( wir287, out007, wir279 );
  nand gate290 ( wir288, wir163, wir287 );
  nand gate291 ( wir289, wir245, wir288 );
  nand gate292 ( wir290, wir288, wir247 );
  nand gate293 ( wir291, wir252, wir211 );
  nand gate294 ( wir292, wir277, wir232 );
  nand gate295 ( wir293, wir192, wir292 );
  nand gate296 ( wir294, wir290, wir280 );
  nand gate297 ( wir295, wir264, wir292 );
  nand gate298 ( wir296, wir217, wir264 );
  nand gate299 ( wir297, wir221, wir295 );
  nand gate300 ( out003, wir294, wir295 );
  nand gate301 ( wir298, wir273, wir297 );
  nand gate302 ( out002, wir298, wir246 );
  nand gate303 ( out006, wir240, wir289 );
  nand gate304 ( wir299, wir293, wir250 );
  nand gate305 ( out000, wir270, wir267 );
  nand gate306 ( out001, wir276, wir291 );
  nand gate307 ( wir300, wir299, wir296 );
  nand gate308 ( out004, wir286, wir300 );
endmodule

module test;
   reg  [7:0] AB; // C=A*B
   wire [7:0] C;

  EBCDIC_to_ISO_latin_1 U1 (
  .in_000 (AB[0]),
  .in_001 (AB[1]),
  .in_002 (AB[2]),
  .in_003 (AB[3]),
  .in_004 (AB[4]),
  .in_005 (AB[5]),
  .in_006 (AB[6]),
  .in_007 (AB[7]),
  .out000 (C[0]),
  .out001 (C[1]),
  .out002 (C[2]),
  .out003 (C[3]),
  .out004 (C[4]),
  .out005 (C[5]),
  .out006 (C[6]),
  .out007 (C[7])
  );

  initial  AB=0;
  always  #1  AB = AB+1;
  initial  begin
    $display("\t\ttime,\tEBCDIC   \tISO-latin-1");
    $monitor("%d,\t%b %b\t%b %b\t%c",$time, AB[7:4], AB[3:0], C[7:4], C[3:0], C);
  end
  initial  #255  $finish;
endmodule

// iverilog -o EBCDIC_309 EBCDIC_309.v
// vvp EBCDIC_309

/*
https://codegolf.stackexchange.com/questions/24925/ebcdic-code-golf-happy-birthday-system-360

 EBCDIC037_to_Latin1 = [
    0x00,0x01,0x02,0x03,0x9c,0x09,0x86,0x7f,0x97,0x8d,0x8e,0x0b,0x0c,0x0d,0x0e,0x0f,
    0x10,0x11,0x12,0x13,0x9d,0x85,0x08,0x87,0x18,0x19,0x92,0x8f,0x1c,0x1d,0x1e,0x1f,
    0x80,0x81,0x82,0x83,0x84,0x0a,0x17,0x1b,0x88,0x89,0x8a,0x8b,0x8c,0x05,0x06,0x07,
    0x90,0x91,0x16,0x93,0x94,0x95,0x96,0x04,0x98,0x99,0x9a,0x9b,0x14,0x15,0x9e,0x1a,
    0x20,0xa0,0xe2,0xe4,0xe0,0xe1,0xe3,0xe5,0xe7,0xf1,0xa2,0x2e,0x3c,0x28,0x2b,0x7c,
    0x26,0xe9,0xea,0xeb,0xe8,0xed,0xee,0xef,0xec,0xdf,0x21,0x24,0x2a,0x29,0x3b,0xac,
    0x2d,0x2f,0xc2,0xc4,0xc0,0xc1,0xc3,0xc5,0xc7,0xd1,0xa6,0x2c,0x25,0x5f,0x3e,0x3f,
    0xf8,0xc9,0xca,0xcb,0xc8,0xcd,0xce,0xcf,0xcc,0x60,0x3a,0x23,0x40,0x27,0x3d,0x22,
    0xd8,0x61,0x62,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0xab,0xbb,0xf0,0xfd,0xfe,0xb1,
    0xb0,0x6a,0x6b,0x6c,0x6d,0x6e,0x6f,0x70,0x71,0x72,0xaa,0xba,0xe6,0xb8,0xc6,0xa4,
    0xb5,0x7e,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7a,0xa1,0xbf,0xd0,0xdd,0xde,0xae,
    0x5e,0xa3,0xa5,0xb7,0xa9,0xa7,0xb6,0xbc,0xbd,0xbe,0x5b,0x5d,0xaf,0xa8,0xb4,0xd7,
    0x7b,0x41,0x42,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0xad,0xf4,0xf6,0xf2,0xf3,0xf5,
    0x7d,0x4a,0x4b,0x4c,0x4d,0x4e,0x4f,0x50,0x51,0x52,0xb9,0xfb,0xfc,0xf9,0xfa,0xff,
    0x5c,0xf7,0x53,0x54,0x55,0x56,0x57,0x58,0x59,0x5a,0xb2,0xd4,0xd6,0xd2,0xd3,0xd5,
    0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39,0xb3,0xdb,0xdc,0xd9,0xda,0x9f];
 */

Kim Øyhus

source: Stack Exchange

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

sort: votes


text:
Hash collision: "NO" means "YES"
This Code Golf was inspired by the recent Daily WTF article You Can't Handle the True!, which features a string comparison written as:
String yes = "YES";
if ((delay.hashCode()) == yes.hashCode())

Imagine the trouble it would have caused for Steve's team if Java's String.hashCode method just happened to be implemented in a way that "YES".hashCode() == "NO".hashCode().  So, the challenge I propose here is:

Write, in as few characters as possible, a hash function (I'll call it
  h) with a string parameter and integer return value, such that
  h("YES") is equal to h("NO").

Of course, this would be trivial to do with a function like def h(s): return 0, which makes a hash collision for every string.  To make this challenge more interesting, you must abide by the following additional rule:

Of the other 18 277 possible strings consisting of three or fewer
  uppercase ASCII letters (^[A-Z]{0,3}$), there must be no hash
  collisions.

Clarification (pointed out by Heiko Oberdiek): The input string may contain characters other than A-Z, and your code must be able to hash arbitrary strings.  (You may, however, assume that the input is a character string rather than a null pointer or an object of some other data type.)  However, it does not matter what the return value is for strings that do not match ^[A-Z]{0,3}$, as long as it's an integer.
Furthermore, to obfuscate the intent of this function:

Your code must not include any of the letters 'Y', 'E', 'S', 'N', or
  'O' (in either upper- or lowercase) within character or string
  literals.

Of course, this restriction doesn't apply to language keywords, so else, return, etc. are fine.

It kind of doesn't help that we can still use the numeric ASCII values of YESNO to check for this specific exception.

Reading the article one can't not remember the "for reasons" comic: http://threewordphrase.com/pardonme.gif

GolfScript: 19 chars (24 chars for named function)
26base.2107=59934*+

This is the body of the function.  Assigning it to a named function h takes five more chars:
{26base.2107=59934*+}:h;

(The final semicolon can be omitted, if you don't mind leaving a copy of the code lying on the stack.)
The core of the hash function is 26base, which calculates sum(26n − k · ak; k = 1 .. n), where n is the number of characters in the input and ak denotes the ASCII code of the k-th input character.  For inputs consisting of uppercase ASCII letters, this is a collision-free hash function.  The rest of the code compares the result to 2107 (the hash code of NO) and, if they're equal, adds 59934 to yield 2701 + 59934 = 62041, the hash code of YES.
For example output, see this online demo with test cases.

How did you test this? I just found a bunch of collisions. Example: h('DXP') == h('KK') == 65884.

(Python equivalent of what you wrote, for my testing purposes: lambda w:sum(ord(c)*26**i for i,c in enumerate(reversed(w*9)))%102983)

@nneonneo: Obviously, not well enough. I thought I generated the full set of three-letter-or-less inputs, hashed all of them and checked that the set of hashes had one element less than the set of inputs. Clearly, my test harness had a bug somewhere. :-( I'll revert to the original 19-char version until/unless I can fix the shorter one.

32-bit Python 2.x (19)
hash(w*9)%537105043

RSA uses a semiprime modulus, and that makes it secure, so using one with my hash algorithm should surely make it even better!1
This is a pure math function, works for all strings (hell, works for any hashable Python object), and doesn't contain any conditionals or special-casing! 32-bit Python can typically be called as python-32 on most systems that have both installed2.
I've tested this, and it returns 18,278 different values for the 18,279 3-letter-or-less uppercase strings. Assigning this to a function takes 11 more bytes:
h=lambda w:hash(w*9)%537105043

and h('YES') == h('NO') == 188338253.
64-bit Python 2.x (19)
hash(w*2)%105706823

Same deal as above.

To come up with these numbers, a little bit of modular math was used. I was looking for a function f and a modulus n such that hash(f('YES')) % n == hash(f('NO')) % n. This is equivalent to testing that n divides d = hash(f('YES')) - hash(f('NO')), i.e. we only have to check the factors of d for suitable values of n.
The ideal n is in the neighbourhood of 20000**2 to reduce the chance of a birthday paradox collision. Finding a suitable n turns out to be a bit of trial and error, playing with all the factors of d (there usually aren't many) and different choices for the function f. Notice though that the trial and error is only needed because I wanted to make n as small as possible (for golfing). If that wasn't a requirement, I could just choose d as my modulus, which is usually sufficiently large.
Note too that you can't pull this trick off using just f(s) = s (the identity function) because the rightmost character of the string has essentially a linear relationship (actually an XOR relationship) with the final hash (the other characters contribute in a much more nonlinear way). The repetition of the string therefore ensures that the differences between the strings are amplified to eliminate the effect of changing only the rightmost character.

1 This is patent nonsense.
2 Python string hashing depends on major version (2 vs 3) and bitness (32-bit vs 64-bit). It does not depend on platform AFAIK.

You've got my vote. :D

Unfortunately, this doesn't work on recent versions of Python due to the new hash randomization feature.

@dan04: Odd, I thought I'd specified that this was for Python 2.x only. I've edited it in again.

May I know how you found these magic numbers? I see hash('YES'*9) has 34876679 as a factor, while hash('NO'*9) has 34876679+537105043 as a factor. But how do you knew that  537105043 was a good modulus? i.e. it didn't make other collisions?

@AntonioRagagnin: Added that to the answer.

Perl, 53 49 40 bytes
sub h{hex(unpack H6,pop)-20047||5830404}

Test:
h('YES') = 5830404
h('NO')  = 5830404
Keys:   18279
Values: 18278

The hash values for YES and NO are the same and there are 18279 strings ^[A-Z]{0,3}$, which are collision free except for the only collision for YES and NO.
Ungolfed:
sub h {
    hex(unpack("H6", pop())) - 20047 || 5830404;
    # The argument is the first and only element in the argument array @_.
    # "pop" gets the argument from array @_ (from the end).
    # The first three bytes of the argument or less, if the argument
    # is shorter, are converted to a hex string, examples:
    #   "YES" -> "594553"
    #   "NO"  -> "4e4f"
    # Then the hex string is converted to a number by function "hex":
    #   0x594553 = 5850451
    #   0x4e4f   =   20047
    # The value for "NO" is subtracted, examples:
    #   case "YES": 5850451 - 20047 = 5830404
    #   case "NO":    20047 - 20047 =       0
    # If the argument is "NO", the subtraction is zero, therefore
    # 5830404 is returned, the result of "YES".
}

# Test
my %cache;
sub addcache ($) {$cache{$_[0]} = h($_[0])}

# Check entries 'YES' and 'NO'
addcache 'YES';
addcache 'NO';
print "h('YES') = $cache{'YES'}\n";
print "h('NO')  = $cache{'NO'}\n";

# Fill cache with all strings /^[A-Z]{0-3}$/
addcache '';
for my $one (A..Z) {
    addcache $one;
    for (A..Z) {
        my $two = "$one$_";
        addcache $two;
        for (A..Z) {
            my $three = "$two$_";
            addcache $three;
        }
    }
}
# Compare number of keys with number of unique values
my $keys = keys %cache;
my %hash;
@hash{values %cache} = 1 x $keys;
$values = keys %hash;
print "Keys:   $keys\n";
print "Values: $values\n";

Older version, 49 bytes
Since the new algorithm is slightly different, I keep the old version.
sub h{($_=unpack V,pop."\0"x4)==20302?5457241:$_}

Test:
h('YES') = 5457241
h('NO')  = 5457241
Keys:   18279
Values: 18278

Ungolfed:
sub h {
    $_ = unpack('V', pop() . ($" x 4);
        # pop():  gets the argument (we have only one).
        # $" x 4: generates the string "    " (four spaces);
        #   adding the four spaces ensures that the string is long
        #   enough for unpack's template "V".
        # unpack('V', ...): takes the first four bytes as
        #   unsigned long 32-bit integer in little-endian ("VAX") order.
    $_ == 20302 ? 5457241 : $_;
        # If the hash code would be "NO", return the value for "YES".
}

Edits:

Using "\0" as fill byte saves 4 bytes in comparison to $".

Where do 5457241 and 20047 come from? How do you calculate these numbers? Thanks in advance.

@n.1: YES in hex is 594553. 0x594553 = 5850451. NO in hex is 4e4f. 0x4e4f = 20047.

Python: 63
An incredibly lame solution:
def h(s):
 try:r=int(s,36)
 except:r=0
 return(r,44596)[r==852]

It works by interpreting alphanumeric strings as base-36 numbers, and returning 0 for everything else.  There's an explicit special case to check for a return value of 852 (NO), and return 44596 (YES) instead.

Unless I misunderstand: It's code golf, you're allowed to assume the input is accurate. You can ditch try: and the entire third line. You can also save a few bites by having every logical line on the same actual line, separated by semicolons (def h(s):r=int(s,36);return(r,44596)[r==852])

@undergroundmonorail: The string parameter for the hash function is not restricted in the question. For a certain class of strings (up to three uppercase letters) there is a restriction regarding the return values of the hash function. However it does not matter, what is returned for other strings, if the return value is an integer.

I like the boolean-indexing of your array there

Pure Bash, 29 bytes (function body)
h()(echo $[n=36#$1,n-852?n:44596])

This simply treats the input string as a base 36 number and converts to decimal, then deals with the special NO case.
Output:

$ h A
10
$ h B
11
$ h CAT
15941
$ h NO
44596
$ h YES
44596
$ h ZZZ
46655
$

Ruby, 51 bytes
h=->s{d=s.unpack('C*').join;d=~/896983|^7879$/?0:d}

testing code :
h=->s{d=s.unpack('C*').join;d=~/896983|^7879$/?0:d}

puts 'YES : '+h.call('YES').to_s # 0
puts 'NO : '+h.call('NO').to_s # 0
puts 'NOX : '+h.call('NOX').to_s # 787988
puts 'FNO : '+h.call('FNO').to_s # 707879
puts ''

values = Hash[]
n = 0
('A'..'Z').each{|c|
    values[c] = h.call(c)
    ('A'..'Z').each{|c2|
        values[c+c2] = h.call(c+c2)
        ('A'..'Z').each{|c3|
            values[c+c2+c3] = h.call(c+c2+c3)
            n += 1
        }
    }
}
puts 'tested '+n.to_s
duplicate = Hash.new()

values.each{|k, e|
    if duplicate.has_key?(e)
        puts 'duplicate : "'+k+'" = "'+duplicate[e].to_s+'" ('+e.to_s+')'
    else
        duplicate[e] = k
    end
}

output :
YES : 0
NO : 0
NOX : 787988
FNO : 707879

tested 17576
duplicate : "YES" = "NO" (0)

Java - 94 77
int h=new BigInteger(s.getBytes()).intValue();return Math.abs(h-(h^5835548));

Unrolled:
int hashCode(String s) {
    int h = new BigInteger(s.getBytes()).intValue();
    return Math.abs(h - (h ^ 5835548));
}

Narrative - for f(s) = BigInteger(s.getBytes()):

f("YES") xor f("NO") = 5835548
So f("YES") xor 5835548 = f("NO")
So f("YES") - (f("YES") xor 5835548) = f("NO") - (f("NO") xor 5835548) am I right?

Can't you inline the BigInteger?

@mafutrct - YES!!! Thank you.

Javascript (ES6) 54 bytes
f=s=>[x.charCodeAt()for(x of s)].join('')^7879||897296

f('YES'); // 897296
f('NO'); // 897296
f('MAYBE'); // -824036582

CJam, 15 bytes
q42b_*81991617%

Works as the GolfScript solution below. Try it online.

GolfScript, 17 bytes
42base.*81991617%

This approach builds on the answers of nneonneo and Ilmari Karonen.
How it works
42base    # Interpret the input string as a base 42 number.
          # "YES" is [ 89 69 83 ] in ASCII, so it becomes 42 * (42 * 89 + 69) + 83 = 159977.
          # "NO" is [ 78 79 ] in ASCII, so it becomes 42 * 78 + 79 = 3355.
          #
.*        # Square. "YES" becomes 25592640529, "NO" becomes 11256025.
          #
81991617% # "YES" becomes 11256025.

Choosing an algorithm
We start with {b base}:h, i.e., the input string is considered a base-b number. As long as b > 25, h is inyective.
We get a collision for strings "YES" and "NO" if we modify h in the following way: {x base n}:h, where n is a divisor of "YES" h "NO" h -.
Unfortunately, this means we'll also get a collision for, e.g., YET and NP. To prevent this, we have to modify the base-b number in a non-linear fashion before taken the modulus.
The shortest way to accomplish this in GolfScript is to multiply the base-b number with itself (i.e., squaring it). h is now {base b .* n %}:h.
All that remains to do is finding suitable values for b and n. We can accomplish this by brute force:
for((b=26;b<100;b++)){
    P=($(golfscript <<< "['YES' 'NO']{$b base.*}/-" | factor | cut -d\  -f 2-))

    for n in $(for((i=0;i<2**${#P[@]};i++)){
        for((n=1,j=0;j<${#P[@]};n*=${P[j]}**((i>>j)&1),j++)){ :;};echo $n;} | sort -nu);{
            [[ $n -ge 18277 && $(echo -n '' {A..Z}{,{A..Z}{,{A..Z}}} |
                golfscript <(echo "' '/[{$b base.*$n%}/].&,")) = 18278 ]] &&
            echo $b $n && break
    }
}

The shortest possible values for b n are:
37 92176978
42 81991617

Testing
$ echo -n '' {A..Z}{,{A..Z}{,{A..Z}}} |
     golfscript <(echo '{42base.*81991617%}:h;" "/{.`"\t"+\h+puts}/') |
     sort -k 2n |
     uniq -Df 1
"NO"    11256025
"YES"   11256025

JavaScript (ES6) - 38 characters (33 char function body)
h=s=>(a=btoa(s))=="WUVT"|a=="Tk8="||+s

Test Cases:
var l = console.log;
l(  h("YES")  );                // 1
l(  h("NO")  );                 // 1
l(  h("ABC")  );                // NaN
l(  h("WIN")  );                // NaN
l(  h("YES") === h("NO")  );    // true
l(  h("ABC") === h("WIN")  );   // false
l(  h("WIN") === h("YES")  );   // false

l(  NaN === NaN  );             // false

Explanation:
First of all, let me introduce you to NaN - "Not A Number" - in JavaScript. It is a number:
typeof NaN  // number

Just like:
typeof 42   // number

Its special property is that it never equals itself. My function returns 1 if the string is YES or NO, and NaN for any other string.
So, this doesn't break the rules, because there would be no hash collision for any other string ;) ( NaN !== NaN shown above in test cases).
And my dream comes true: beating Bash, Perl and Ruby in code length!
Ungolfed Code:
h =  // h is a function
s => // s = string argument

( ( a = btoa(s) )  ==  "WUVT" | a == "Tk8=" )
        ^-- returns some value stored in `a`

If that value is "WUVT" or "Tk8=", return 1. Else, return
+s // parseInt(s, 10)

which would be NaN.

NaN might be a number, but it is not an "integer" in any sense of the word.

@PaŭloEbermann  From wiki, "An integer is a number that is written without a fractional component". The question does not explicitly say that the integer has to be ^\d+$. And JS does treat NaN as a number. You can multiply it by a number, add, divide, subtract just as with numbers. It is a special property of JavaScript. There's no harm in using it. That's what we call bending of rules ;)

I could use Object.is() and claim it's still a collision…

@user2428118 Thanks for bringing Object.is to my knowledge. I never knew it. But I would like you to note that the OP uses the equality operator (==) for comparison, which will guarantee no hash collision happens for any string apart from "YES" or "NO".

Ignoring the fact that claiming NaN doesn't count as collision seems cheap, this solution has collisions with strings NA through NP and YEQ through YET

@nderscore Thanks for testing my program and bringing its faulty implementation to my notice. It has been corrected. Please have a look.

From the rules: "Your code must not include any of the letters 'Y', 'E', 'S', 'N', or 'O' (in either upper- or lowercase) within character or string literals."

@nderscore I lose hopes. I have updated my answer to include this fact.

@nderscore Ok, I have corrected this bug. And hopefully it does work now.

Python 92
n=int("".join(map(str,map(ord,raw_input()))))    # hashing function
print n if 1+(n**2-904862*n)/7067329057 else-1   # input validation

The hashing function concatenates the ordinal values of the ASCII characters, the print statement ensures that the two desired inputs collide.

ECMAScript 6 (30 bytes)
I've tried to avoid variable assignment, return, and function keyword, and this looks like a great way to avoid all that nonsense (it also looks like functional programming, in a way). Unlike other solutions, it doesn't depend on btoa or atob, which isn't ECMAScript 6, but HTML5. 0+ is needed, so it could parse arbitrary strings.
a=>parseInt(0+a,36)-852||43744

Nice! I didn't know they added other bases for parseInt. You can cut a lot of bytes though. :) a=>parseInt(0+a,36)-852||43744

@nderscore: Thanks for suggestion. It really improved my script a lot.

Java - 45 (or 62?)
I have no idea how to fairly score given what one needs to run a program in Java, do I need to include the function definition? Feel free to edit and adjust my score appropriately. Currently I'm scoring the same way as the @OldCurmudgeon answer. Add 17 for int h(String t){} if it's required:
int h=t.hashCode();return h*h*3%1607172496;

Ungolfed with test harness:
import static org.junit.Assert.*;

import java.util.*;

import org.junit.Test;

public class YesNo {
  @Test
  public void testHashValue() {
    YesNo yesNo = new YesNo();
    Set<Integer> set = new HashSet<>();

    assertEquals(yesNo.hash("YES"), yesNo.hash("NO"));

    set.add(yesNo.hash(""));
    for(char i = 'A'; i <= 'Z'; i++) {
      set.add(yesNo.hash("" + i));
      for(char j = 'A'; j <= 'Z'; j++) {
        set.add(yesNo.hash("" + i + j));
        for(char k = 'A'; k <= 'Z'; k++) {
          set.add(yesNo.hash("" + i + j + k));
        }
      }
    }
    assertEquals(18278, set.size());
  }

  int hash(String toHash) {
    int hashValue=toHash.hashCode();
    return hashValue*hashValue*3%1607172496;
  }
}

And the looser is...
Conveyor, 145 chars
 I
>#<
 26*)2**\88
 >========*
 ^    \ \+-
 ^=====#==<
5**222P:
5======<
5***26*)*(\P\:@e25*:*)4*,F
>==============#=========
             P,F

Basically this program does some kind of base 26 thing on the chars. After that it checks if the hash is equal to 12999 (The hash code of YES) and if so print 404 (the hashcode of NO), else it will just print the hashcode.
Conveyor is a language made by me that is currently in beta-stages but an interpreter along with some examples and source code can be found here: https://github.com/loovjo/Conveyor

C# 4.5 (112 bytes)
int h(string s){int code=s.Select((v,i)=>((int)v)<<(2*(i-1))).Sum();return(code|1073742225)|(code|-2147483569);}

Working (?) version of undergroundmonorail's attempt, in C#. Concats the bytes in the string into a 32-bit integer (only works up to 4 characters), then ORs the result against the result for "YES" and "NO" respectively, then ORs those together.
While it may collide at some point, it shouldn't happen for any ^[A-Z]{2,3}$ other than "YES" and "NO".

You hash function will have many more collisions. Your "hash function" is essentially ignoring many bits in the concatenation. All string pairs which only differ in those bits will have the same hash code.

No Comment - 31 (function content: 26)
'=|*==|,,|+|"#|[|,  |+|-%3|]*|:

Pretty simple solution. ;) Works for any and all UTF-8 strings.
EXPLANATION: ' is, obviously, the function. First, it checks whether * (it's input) is equal to |,,|+|"#| (|NO|). If it is, it returns |,  |+|-%3| (|YES|) - otherwise, it just returns *.

I've never worked with No Comment, would it be possible for you to explain your solution like is often done with opaque Golfscript, J, or APL answers?

@Kaya Oh, yes, sorry, I'll edit the post.

No apologies necessary, I was just curious how it worked.

C 54
h(char *c){int d=*(int*)c-20302;return d*(d-5436939);}

Convert string to integer -"NO" and multiply that by by same value + "NO"-"YES" to get 0 for "NO" and "YES" and non-zero for any other string in the range specified.
All values on Windows 7 machine if there are any endian concerns.

Stax, 12 11 bytes
ì≤ïøZ‼kESa←

Run and debug it
Translates input as base-36, subtracts 852, then replaces 0 with 43744.  It's a port of Konrad's excellent solution.

Here's a super lame one. SO LAME IT DOESN'T EVEN WORK
Python 2.7 - 79 bytes
def h(s):n=sum(100**i*ord(c)for i,c in enumerate(s));return (n-7978)*(n-836989)

First we get the sum of (each character's ascii value) * 100^(that character's position in the string). Then we multiply (that result - 7978) and (that result - 836989) to get our final answer. 7978 and 836989 are the results for "YES" and "NO" of the first bit, so for YES and NO we're multiplying by 0.
This shouldn't have any collisions? I don't feel like testing against 18000 possible counterexamples, but if there was an unintended collision I can throw another 0 on that 100 and then there really shouldn't be any collisions.
Disappointed that I couldn't use a lambda for this, but I didn't want to do the whole calculation twice so I had to save it to a variable.
Please don't let this win. It's super lame and I don't deserve it.

Doesn't meet the "no other collisions" requirement: There are only 18012 unique hashes out of the 18277-string set that shouldn't have collisions.

@dan Damn, give me a second

@dan I can't get it to work. Maybe there's something inherently wrong with the algorithm. I don't want to delete it because someone else might know what's wrong, but I'll put up a note

This works for me, h=lambda s:(hash(s)+997192582)*(hash(s)-480644903)

as did defining a hash function similar to yours but with 99**i*int(c,36)

CoffeeScript - 36
Should return 1 for YES and NO, and whatever garbled nonsense atob produces for everything else that's not a base64 string.
h=(s)->_=atob s;_ in["`D","4"]&&1||_

The JavaScript equivalent (not the JS code from the CS compiler):
function h( s ) {
    var _ = atob( s );

    if( _ === "`D" || _ === "4" )
        return 1;
    else
        return _;
}

"The function should have an integer return value" - I suppose yours returns the _ when the input is not "YES" or "NO".


text:
Closest fraction
Task:
Your program is given a proper, positive simple fraction in the format <numerator>/<denominator>.
For this input, it must find two fractions.

A fraction that is less than the input.
A fraction that is greater than the input.

Both fractions must have a lower denominator than the input. Of all possible fractions, they should have the lowest difference to the input.
Output:
Your program's output must be:

A fraction that is smaller than the input, in the format <numerator>/<denominator>.
Followed by a space character (ASCII-code 32).
Followed by a fraction that is greater than the input, in the format <numerator>/<denominator>.

As follows:
«fraction that is < input» «fraction that is > input»

Rules:

All fractions outputted must be in lowest terms.
All fractions outputted must be proper fractions.
If there are no proper fractions possible that are allowed by the rules, you must output 0 instead of a fraction < input, and 1 instead of a fraction > input.
You can choose whether you want to receive the fraction as a command-line argument (e.g. yourprogram.exe 2/5) or prompt for user input.
You may assume your program won't receive invalid input.
The shortest code (in bytes, in any language) wins.
Any non-standard command-line arguments (arguments that aren't normally required to run a script) count towards the total character count.
What your program must not do:

Depend on any external resources.
Depend on having a specific file name.
Output anything other than the required output.
Take exceptionally long to run. If your program runs over a minute for fractions with a 6-digit numerator and denominator (e.g. 179565/987657) on an average home user's computer, it's invalid.
Output fractions with 0 as the denominator. You can't divide by zero.
Output fractions with 0 as the numerator. Your program must output 0 instead of a fraction.
Reduce an inputted fraction. If the fraction given as input is reducible, you must use the fraction as it is inputted.

Your program must not be written in a programming language for which there did not exist a publicly available compiler / interpreter before this challenge was posted.

Examples:
Input: 2/5
Output: 1/3 1/2
Input: 1/2
Output: 0 1
Input: 5/9
Output: 1/2 4/7
Input: 1/3
Output: 0 1/2
Input: 2/4
Output: 1/3 2/3
Input: 179565/987657
Output: 170496/937775 128779/708320

Your first example does not match the specification: Both fractions must have a lower denominator than the input.

First example, output should be 1/3 1/2.

@HeikoOberdiek You're right. Fixed.

Could we have an example where the input is reducible? Oh, right.

Are 0/1 and 1/1 accepted if they replace 0 and 1 ?

@Michael 1/1 isn't a proper fraction. As for 0/1, I hadn't realized that it is a proper fraction, so I've added a rule to say that isn't allowed.

If my language of choice uses double slashes to denote rationals, is that valid for input and output as well, or do they have to be single slashes?

Define "average home user's computer". Is 90 seconds on a 1.6GHz Intel Atom machine acceptable?

Are negative fractions allowed?

@JanDvorak I think that would be okay. I won't be too strict, if I think it's likely that it runs in about one minute on recent customer-grade hardware, I'll probably accept it (unless the chosen kind of computer isn't very common and vastly outperforms others). The reason for this rule was mainly to exclude brute-force solutions that take almost forever to complete.

@m.buettner I'd rather not make exceptions for specific programming languages. The rules will remain the same, even if that puts your language of choice at a disadvantage

@user80551 No, the rules explicitly state your program is given a proper, positive simple fraction in the format specified.

Your last example is incorrect.  The input fraction equals the first of the output fractions.

@David Oops, you're right. Fixed now (I hope). (Just in case I got it wrong again: I wrote this piece of code to calculate the closest lower fraction. I am linking it here so people can see if there are any bugs in it.)

Unfortunately, this means all the answers are wrong as well...

Sage – 119 117
x,X=map(int,raw_input().split('/'))
a=0
A=c=C=1
while C<X:exec("ab,,AB"[c*X>C*x::2]+"=c,C");c=a+b;C=A+B
print a/A,b/B

Sage is only needed in the last line, which takes care of the output. Everything else also works in Python.
Replace raw_input() with sys.argv[1] to have the input read from a command-line argument instead of a prompt. This does not change the character count. (Does not work in Python without importing sys first.)
This essentially recursively constructs the respective Farey sequence using mediants of the existing elements, but restricts itself to those elements closest to the input. From another point of view, it runs a nested-interval search on the respective Farey sequences.
It correctly processes all of the examples in less than a second on my machine.
Here is an ungolfed version:
x,X = map(Integer,sys.argv[1].split('/'))
x = x/X
a = 0
c = b = 1
while c.denominator() < X:
    if c > x:
        b = c
    else:
        a = c
    c = ( a.numerator() + b.numerator() ) / ( a.denominator() + b.denominator() )
print a,b

I was already afraid that I wouldn't get any new submissions for this bounty. Great work.

Nice trick with the exec!

As the only answer submitted within the bounty period, I am hereby awarding you the bounty. Congratulations.

I just fixed an error in one of the examples. You may want to correct your submission (even though it's been half a year since you submitted it).

Python 2.7 - 138
x,y=n,d=map(int,raw_input().split('/'))
while y:x,y=y,x%y
def f(p,a=d):
 while(a*n+p)%d:a-=1
 print`(a*n+p)/d`+('/'+`a`)*(a>1),
f(-x);f(x)

I started with the obvious brute-force solution, but I realized that since the OP wanted to be able to solve instances with six digit numerators and denominators in under a minute, I need a better solution than trying a trillion possibilities. I found a handy formula on the Wikipedia page for the Farey sequence: If a/b, c/d are neighbors in one of the Farey sequences, with a/b<c/d, then b*c-a*b=1. The while loop inside f in my program extends this fact to non-reduced numbers, using the gcd, which the other while loop calculates.
I've golfed this pretty hard already, but I'd love to hear any suggestions.
Edits:
166->162: Removed a and b from the outer program. They were unnecessary.
162->155: str() -> ``
155->154: Added k.
154->152: Removed x from inside the function, passed it as an argument instead.
152->150: Gave a a default value instead of passing it as an argument.
150->146: Changed the initialization of x and y.
146->145: Removed k.
145->144: Changed ... and ... or ... to (...,...)[...], thereby saving a space.
144->138: Changed (...,...)[...] to ...+...*(...). Thanks to @mbomb007.
Test cases:
2/5
1/3 1/2

1/2
0 1

2/4
1/3 2/3

179565/987657
170496/937775 128779/708320

12345678/87654321
12174209/86436891 11145405/79132382

The second to last test took under a second on my computer, while the last one took about 5-10 seconds.

This k=1 is pure wickedness.

@Evpok: I was trying to get k=y=n to work, but apparently if you modify a variable inside a function, python wants it to be local. This was the only way to get a local variable in 4 characters. Also, since the fraction is positive and proper, the denominator can't be 1.

Command-line arguments are easy with Python, so they should have been used for input as instructed here.

"You can choose whether you want to receive the fraction as a command-line argument (e.g. yourprogram.exe 2/5) or prompt for user input."

Save 6 chars: print`(a*n+p)/d`+('/'+`a`)*(a>1),

Mathematica, 163 bytes
{a,b}=FromDigits/@InputString[]~StringSplit~"/";r=Range[b-1];""<>Riffle[#~ToString~InputForm&/@(#@DeleteCases[#2[a/b*r]/r,a/b]&@@@{{Max,Floor},{Min,Ceiling}})," "]

This is severely limited by the input/output requirement as user input and strings. Dealing with strings is really cumbersome in Mathematica (at least when you want to golf). Doing this the natural way in Mathematica, (using just integers and rationals) I'd probably get this down to 50% of the size.
It can do 6-digit numbers in a few seconds on my machine.
Slightly more readable (not really ungolfed though):
{a, b} = FromDigits /@ InputString[]~StringSplit~"/";
r = Range[b - 1];
"" <> Riffle[#~ToString~
     InputForm & /@ (#[DeleteCases[#2[a/b*r]/r, a/b]] & @@@ {{Max,
       Floor}, {Min, Ceiling}}), " "]

For the fun of it, doing this "the natural way", i.e. as a function taking numerator and denominator and returning two rationals, this is only 84 characters (so my 50% estimate was actually pretty close):
f[a_,b_]:=#@DeleteCases[#2[a/b*(r=Range[b-1])]/r,a/b]&@@@{{Max,Floor},{Min,Ceiling}}

Julia - 127 125 bytes
I've approached this from a mathematical perspective to avoid need for loops, so this code runs quite fast for large inputs (note: if a/b is the input, then a*b must fit within Int64 (Int32 on 32 bit systems), otherwise nonsense answers are generated - if a and b are both expressible in Int32 (Int16 on 32 bit systems), no problems occur).
UPDATE: There's no longer a need to overload backslash for div, by using ÷, a net saving 2 bytes.
a,b=int(split(readline(),"/"));k=gcd(a,b);f=b-invmod(a÷k,b÷k);d=2b-f-b÷k;print(a*d÷b,d<2?" ":"/$d ",a*f÷b+1,"/$f"^(f>1))

Ungolfed:
a,b=int(split(readline(),"/")) # Read in STDIN in form a/b, convert to int
k=gcd(a,b)           # Get the greatest common denominator
f=b-invmod(a÷k,b÷k)  # Calculate the denominator of the next biggest fraction
d=2b-f-b÷k           # Calculate the denominator of the next smallest fraction
print(a*d÷b,d<2?" ":"/$d ",a*f÷b+1,"/$f"^(f>1)) # Calculate numerators and print

Basic idea: find the largest d and f less than b that satisfies ad-bc=gcd(a,b) (next smallest) and be-af=gcd(a,b) (next largest), then calculate c and e from there. Resulting output is c/d e/f, unless either d or f is 1, in which case the /d or /f is omitted.
Interestingly, this means that the code also works for positive improper fractions, so long as the input is not an integer (that is, gcd(a,b)=a).
On my system, inputting 194857602/34512958303 takes no perceivable time to output 171085289/30302433084 23772313/4210525219

Testing with 55552/999999 gives me -396/920632 486/936509.

@user2428118 - Are you on a 32 bit system (or using a 32 bit Julia)? I've used "int", which means that on a 32 bit system, it'll use Int32 rather than Int64. int32(55552*999999) gives -282630400. For me, with that test, I get 51143/920632 52025/936509 - note that the denominators are the same, and that 52025-51143 = 486-(-396). I'll add a note to mention this issue.

If you want to ensure that the code will work for all Int64 size inputs, you can replace "int" with "int128". With that change, inputting 1234567891234567/2145768375829475878 results in 869253326028691/1510825213275018197 365314565205876/634943162554457681. This change adds just 3 extra characters.

Yes, I'm using a 32-bit computer. I'll try it on a 64-bit machine sometime when I've got the time for it.

Testing on a 64-bit computer gives the correct result, so I'm accepting this answer.

JavaScript, 131
With fat arrow notation and eval calls :
m=>{for(e=eval,n=e(m),i=p=0,q=1;++i</\d+$/.exec(m);)if(n*i>(f=n*i|0))g=f+1,p=f/i>e(p)?f+'/'+i:p,q=g/i<e(q)?g+'/'+i:q;return p+' '+q}

The 179565/987657 stress test is executed in approximately 35 seconds on Firefox, a lot more on Chrome (~ 6 minutes)
Faster method and without eval and fat arrow notation
for(n=eval(m=prompt(a=i=p=0,b=c=d=q=1));++i<m.match(/\d+$/);)if(n*i>(f=n*i|0))g=f+1,p=f*c>i*a?(a=f)+'/'+(c=i):p,q=g*d<i*b?(b=g)+'/'+(d=i):q;alert(p+' '+q)

The 179565/987657 stress test is executed in approximately 5 seconds.
Not golfed :
m=prompt(); //get input
a=0; c=1; //first fraction
b=1; d=1; //second fraction
n=eval(m); //evaluate input
for (i=1; i<m.match(/\d+$/); i++) { //loop from 1 to input denominator
  f=Math.floor(n*i);
  if (n*i > f) { //if fraction not equal to simplification of input
    g=f+1; // f/i and g/i are fractions closer to input
    if (f/i>a/c) a=f, c=i;
    if (g/i<b/d) b=g; d=i;
  }
}
alert(a+'/'+c+' '+b+'/'+d); //output values handling 0 and 1 correctly

too... much... eval. EEK

Testing with 2/6 gives 1/3 2/5, however 1/3 is not less than but equal to 2/6.

@user2428118 fixed

Why has this answer been accepted so early?

@user2428118: You know, you can allow a couple days to pass before accepting solutions. Also, this solution is no longer the shortest.

@isaacg I'll change the accepted answer when a shorter solution becomes available. The JavaScript answer is now shorter, though.

On a second thought, accepting an answer already may discourage people from posting. I'll wait, then.

Save two bytes: m=>{for(e=eval,n=e(m),i=p=0,q=1;++i</\d+$/.exec(m);n*i>f&&(g=f+1,p=f/i>e(p)?f+'/'+i:p,q=g/i<e(q)?g+'/'+i:q))f=n*i|0;return p+' '+q}

@nderscore, thanks for the regex reduction but the && trick seems to not work.

Your ungolfed code is broken.

I just fixed an error in one of the examples. You may want to correct your submission (even though it's been a year since you submitted it).

perl, 142 bytes (155 without CPAN)
use bare A..Z;$/="/";N=<>;D=<>;F=N/D;K=G=1;for$H(1..D){J<F&&J>E?(E,I):J>F&&J<G?(G,K):()=(J=$_/H,"$_/$H")for(Z=int F*H)..Z+1}print I||0," $K\n"

Or if CPAN modules are disallowed / 3-4 times faster code is needed:
$/="/";$N=<>;$D=<>;$F=$N/$D;$g=$G=1;for$d(1..$D){$f<$F&&$f>$E?($E,$e):$f>$F&&$f<$G?($G,$g):()=($f=$_/$d,"$_/$d")for($z=int$F*$d)..$z+1}print$e||0," $g\n"

The former version takes 9.55 seconds on my machine, the latter version 2.44 seconds.
Less unreadable:
($N, $D) = split(m[/], <>);
$F = $N / $D;
$G = 1;
foreach $d (1 .. $D) {
    $z = int $F * $d;
    foreach $_ ($z .. $z + 1) {
        $f = $_ / $d;
        ($f < $F && $f > $E ? ($E, $e) :
        ($f > $F && $f < $G ? ($G, $g) : ())) = ($f, "$_/$d");
    }
}
print $e || 0, ' ', $g || 1, "\n";


text:
Fix your trees!
In informatics, we often use trees in lots of different forms and representations. The three major methods of serialising binary trees are prefix, infix and postfix notation. For example, the following binary tree:
   (source: Dutch Olympiad in Informatics, finals, 2012/13)
can be represented in prefix notation as abrxdbe, in infix as rbxabde and in postfix as rxbbeda.
In this case, you are confronted with a complete binary tree represented in infix notation. Your task is to convert this tree to prefix notation. Your input on stdin will be 2n-1 lowercase alphabet characters, a-z and no more, ended with a newline character, for any integer n such that 1 ≤ n ≤ 16. Thus, the maximum number of characters you will get is 65535. Output the tree to stdout in the same way, but then in prefix format.
This is code golf, so the shortest code, counted in bytes, will win. Votes will act as a tie breaker, and if those tie up as well, submission date and time.

possible duplicate of Convert from Infix Notation to Prefix Notation

@PeterTaylor Thanks for mentioning, but I think this challenge is actually different because you don't need to evaluate an entire expression, just a simple 2n-1 binary tree.

Ok, the restriction to complete binary trees does simplify things quite a lot.

GolfScript, 23 chars
.,\{;).2base{)!}do}$/n-

This solution uses a different approach than Howard's: basically, it sorts the input characters according to the list of branches needed to reach that character from the root of the tree.
Note that the newline at the end of the input is required (i.e. the input length must be a power of two).  The n- at the end of the code is required to suppress an extra newline at the beginning of the output; if such a newline is acceptable, those characters can be omitted for a score of 21 chars.
As usual, you can test this code online.
Explanation:

.,\ calculates the length of the input, and moves it below the input string on the stack.  It will be used as the starting value of the loop counter used to construct the sort keys below.  (The code relies on this being a power of two; otherwise the bit manipulation below will not produce the expected results.  Any sufficiently large power of two would work, though.)
{ }$ sorts the characters in the input string according to the sort key computed inside the block:

; just throws away the character given as input to the block; we don't care about the actual character values here, just about their positions within the string.
). increments the loop counter on the stack (which was initialized to the length of the input string) and makes a copy of it.
2base converts this copy to an array of bits (omitting leading zeros; that's why we need to start counting from a large enough power of two, rather than simply from zero).
{)!}do repeatedly chops off the lowest bit from the array until the chopped-off bit is a 1.

Since the resulting sort keys are arrays, the $ compares them lexicographically.  Thus, for example, the array [1] (which corresponds to the root node) sorts before [1 0] (which corresponds to the left child of the root node) and [1 1] (the right child of the root node).
At the end, / gets rid of the loop counter by using it as the length of chunks to split the output string into (thanks, Peter!), and n- strips the newline off the sorted input string.  (The GolfScript interpreter will append another newline to the output after printing the contents of the stack.)

Nicely done! You can still save one more: instead of \; to get rid of the loop counter, you can / to split the string into sections larger than it is. (The n- will even then pull it back out of the array so created).

GolfScript, 28 characters
{.,1>{.,)2//([)\c]\~c+}*}:c~

You may test the code online.
Annotated code:
# define an operator c acting on the top of stack which does the conversion
{
  # if the input string is more than a single character
  .,1>{
    # split string into two halves (rounded up)
    .,)2//
    # take first part last character
    ([)
    # take first part rest and call c recursively
    \c]
    # get second part
    \~
    # call c recursively on second part
    c
    # join all three together
    +
  }*
}:c
# call c
~

GolfScript (29 chars)
{.,1>{.,)2//~\[)](f@f++}*}:f~

Online demo
Works with or without the trailing newline in input.

It took me too much time to write down my solution... As expected the solutions look quite similar.

APL (48)
(Yes, the APL charset does fit in a byte.)
{1=⍴⍵:⍵⋄(⊃a),⊃,/∇¨1↓a←1⌽⌽⍵⊂⍨(⍳⍴⍵)∊1,0 1+⌈.5×⍴⍵}⍞

Explanation:

{...}⍞: read input, feed to function
1=⍴⍵:⍵: if the input length is one, we're done
⋄: otherwise:
(⍳⍴⍵)∊1,0 1+⌈.5×⍴⍵: make a bitfield of places to split the input (first character, middle character and character past the middle character)
⍵⊂⍨: split the input at these places
a←1⌽⌽: rotate the  sub-arrays so that the middle character is first, the left hand is second and the right hand is third, and store in a.
⊃,/∇¨1↓a: run the function again on the last two elements of a and concatenate the results
(⊃a),: and concatenate that to the first item in a

Python 3 - 76
def f(x):a=len(x)//2;return x and x[a]+f(x[:a])+f(x[a+1:])
print(f(input()))

C, 108 chars
My code uses a recursive function, which always prints the character in the middle of the buffer, and calls itself with the part of the string before and the part of the string after the character printed. (Divide and Conquer)
char b[65536];d(s,e){int c=s+(e-s)/2;putchar(b[c]);if(c^s)d(s,c-1),d(c+1,e);}main(){gets(b);d(0,strlen(b));}

ungolfed:
char b[65536];
d(s,e){
    int c=s+(e-s)/2;
    putchar(b[c]);
    if(c^s)d(s,c-1),d(c+1,e);
}
main(){
    gets(b);
    d(0,strlen(b));
}

That's also the approach I took in my personal non-golfed solution. Doesn't seem to be the shortest though...