Work the Shell - Coping with Aces
Somehow, writing this Blackjack game is starting to feel like the programmatic equivalent of that Three Stooges skit where “slowly he turned, step by step...”, but we're still going to have to work on the core logic of the game before we're ready to write the fun interface elements.
This month, in fact, we might well find that we have to tear some of the earlier script apart and rebuild it to compensate for a troubling aspect of the game of Blackjack: an Ace can be either high or low, which is to say that it can be worth one or 11 points. Dealt two aces, you then have a number of different possible values, and that's a problem.
It turns out that there's a sneaky way you can solve this problem simply by maximizing the value of the first Ace encountered, as long as the overall value of the hand doesn't exceed our cap of 21 points. So, two Aces would be worth 11 + 1 automatically (the first is maximized, but the second is not because it would push us over 21 points).
The portion of the code that must be rewritten to compensate for this Ace valuation strategy is the handValue function:
function handValue
{
# feed this as many cards as are in the hand
handvalue=0 # initialize
for cardvalue
do
rankvalue=$(( $cardvalue % 13 ))
case $rankvalue in
0|11|12 ) rankvalue=10 ;;
1 ) rankvalue=11 ;;
esac
handvalue=$(( $handvalue + $rankvalue ))
done
}
This is the “before” picture from last month. Notice that the second line in the case statement currently assigns a rank value of 11 to every Ace encountered. Clearly that's a bug!
To change it, however, I need to add a new variable that keeps track of whether I've already seen a previous Ace in the hand. I ingeniously call that seenAce:
function handValue
{
# feed this as many cards as are in the hand
handvalue=0 # initialize
seenAce=0
for cardvalue
do
rankvalue=$(( $cardvalue % 13 ))
case $rankvalue in
0|11|12 ) rankvalue=10 ;;
1 ) if [ $seenAce -eq 1 ] ; then
rankvalue=1
else
rankvalue=11 ; seenAce=1
fi ;;
esac
handvalue=$(( $handvalue + $rankvalue ))
done
}
Looks like it'll do the job—or will it?
The problem here is best illustrated with a hand like 9 + 10 + A. That's a valid Blackjack hand and should be worth 20 points. But handValue will score it as 30 points, and the program will incorrectly classify that hand as a bust.
Solving this isn't too hard once the problem is recognized, but that's the great challenge of writing any code, isn't it? To anticipate and characterize bugs and glitches properly. The solution is often quite simple, but knowing there's a bug in the first place, ah, that's where the great programmers find their calling!
The solution in this situation is that we need to deduct ten points from the hand score if it's more than 21 points and there's an Ace—a condition that turns out to be added easily to the tail end of the function:
handvalue=$(( $handvalue + $rankvalue ))
done
if [ $handvalue -gt 21 -a $seenAce -eq 1 ] ; then
handvalue=$(( $handvalue - 10 ))
fi
}
This is the first time I've used a complex conditional statement in our script, but you're already familiar with this type of multi-expression conditional. If we were using a C-like language, the conditional might look like:
if ( ( handvalue > 21 ) && (seenAce == 1))
The snippet in the shell script shown above is the equivalent conditional, with the -a serving as the logical AND statement. It wouldn't work in this context, but -o is the logical OR statement in a shell test conditional too, and if you need to, you can use parentheses for grouping.
To test our new code, I'm going to replace the main body of the program temporarily with a few preloaded test hands and see what kind of hand values are returned:
echo "Starting out with two aces..." handValue 1 14 echo "handvalue = $handvalue" echo "now testing 9 + 10 + A" handValue 9 10 1 echo "handvalue = $handvalue" echo "and, for good luck, testing K + A" handValue 12 1 echo "handvalue = $handvalue"
First, I'll run this with the original handValue function, anticipating mistakes:
Starting out with two aces... handvalue = 22 now testing 9 + 10 + A handvalue = 30 and, for good luck, testing K + A handvalue = 21
Yup. That's not good. We'd be quickly run out of Vegas for that sort of counting.
Now, I'll slip in the new seenAce code segments explained earlier and try this same set of test hands:
Starting out with two aces... handvalue = 12 now testing 9 + 10 + A handvalue = 20 and, for good luck, testing K + A handvalue = 21
What do you know, it looks like we've come up with a savvy way to allow the Ace to have two possible values without a major rewrite of the code.
Dave Taylor has been hacking shell scripts for over thirty years. Really. He's the author of the popular "Wicked Cool Shell Scripts" and can be found on Twitter as @DaveTaylor and more generally at www.DaveTaylorOnline.com.
Realizing the promise of Apache® Hadoop® requires the effective deployment of compute, memory, storage and networking to achieve optimal results. With its flexibility and multitude of options, it is easy to over or under provision the server infrastructure, resulting in poor performance and high TCO. Join us for an in depth, technical discussion with industry experts from leading Hadoop and server companies who will provide insights into the key considerations for designing and deploying an optimal Hadoop cluster.
Sponsored by AMD
Built-in forensics, incident response, and security with Red Hat Enterprise Linux 6
Every security policy provides guidance and requirements for ensuring adequate protection of information and data, as well as high-level technical and administrative security requirements for a system in a given environment. Traditionally, providing security for a system focuses on the confidentiality of the information on it. However, protecting the data integrity and system and data availability is just as important. For example, when processing United States intelligence information, there are three attributes that require protection: confidentiality, integrity, and availability.
Learn more about catching the bad guy in this free white paper.
Sponsored by DLT Solutions
| Designing Electronics with Linux | May 22, 2013 |
| Dynamic DNS—an Object Lesson in Problem Solving | May 21, 2013 |
| Using Salt Stack and Vagrant for Drupal Development | May 20, 2013 |
| Making Linux and Android Get Along (It's Not as Hard as It Sounds) | May 16, 2013 |
| Drupal Is a Framework: Why Everyone Needs to Understand This | May 15, 2013 |
| Home, My Backup Data Center | May 13, 2013 |
- Designing Electronics with Linux
- Making Linux and Android Get Along (It's Not as Hard as It Sounds)
- Dynamic DNS—an Object Lesson in Problem Solving
- Using Salt Stack and Vagrant for Drupal Development
- Build a Skype Server for Your Home Phone System
- New Products
- A Topic for Discussion - Open Source Feature-Richness?
- Why Python?
- Validate an E-Mail Address with PHP, the Right Way
- Tech Tip: Really Simple HTTP Server with Python
Enter to Win an Adafruit Pi Cobbler Breakout Kit for Raspberry Pi

It's Raspberry Pi month at Linux Journal. Each week in May, Adafruit will be giving away a Pi-related prize to a lucky, randomly drawn LJ reader. Winners will be announced weekly.
Fill out the fields below to enter to win this week's prize-- a Pi Cobbler Breakout Kit for Raspberry Pi.
Congratulations to our winners so far:
- 5-8-13, Pi Starter Pack: Jack Davis
- 5-15-13, Pi Model B 512MB RAM: Patrick Dunn
- 5-21-13, Prototyping Pi Plate Kit: Philip Kirby
- Next winner announced on 5-27-13!
Free Webinar: Hadoop
How to Build an Optimal Hadoop Cluster to Store and Maintain Unlimited Amounts of Data Using Microservers
Realizing the promise of Apache® Hadoop® requires the effective deployment of compute, memory, storage and networking to achieve optimal results. With its flexibility and multitude of options, it is easy to over or under provision the server infrastructure, resulting in poor performance and high TCO. Join us for an in depth, technical discussion with industry experts from leading Hadoop and server companies who will provide insights into the key considerations for designing and deploying an optimal Hadoop cluster.
Some of key questions to be discussed are:
- What is the “typical” Hadoop cluster and what should be installed on the different machine types?
- Why should you consider the typical workload patterns when making your hardware decisions?
- Are all microservers created equal for Hadoop deployments?
- How do I plan for expansion if I require more compute, memory, storage or networking?




2 hours 3 min ago
4 hours 33 min ago
14 hours 36 min ago
19 hours 3 min ago
22 hours 39 min ago
23 hours 11 min ago
1 day 1 hour ago
1 day 1 hour ago
1 day 1 hour ago
1 day 6 hours ago