OLW: #War #Card #Game

Here is a #ruby #one-liner to perform the decision portion when solving for the winner of the popular card game “War.”

def calc_war(deck1,deck2,pot)
  winner=[];var1=deck1.shift.to_i;var2=deck2.shift.to_i;
    pot+=[var1] if (var1>0);pot+=[var2] if (var2>0);
    (var1>var2)?(deck1+=pot;pot.clear):((var1<var2)?
    (deck2+=pot;pot.clear):(pot+=deck1.shift(3)+deck2.shift(3);
  return calc_war(deck1,deck2,pot)))

  return calc_war(deck1,deck2,pot) if (!(winner[2] = deck1.empty?) &&
    !(winner[1] = deck2.empty?))

  return winner.index(true)
end

You can use it like this:
full_deck = (2..14).to_a*4
full_deck.sort! {|a,b| rand <=> rand}
calc_war(full_deck.values_at(0..25),full_deck.values_at(26..51),[])

“The first guy who persuaded a blind person they needed sunglasses – he must have been a hell of a salesmen.” – Jimmy Carr

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s