OUR EXPERT
David Bolton
gets even rustier with two poker programs for shuffling a pack of cards and outputting a text file of 1,000 sets of seven poker cards.
Part Three!
Catch up with previous issues –see page 64!
Part Three!
Catch up with previous issues –see page 64!
I n the previous article, there was a Rust program,PokerGen, that generated a text file of playing cards, seven of them to a line, separated by spaces. Originally, the file output the card suit using Unicode characters; however, it was a bit messy reading those, so we modified it to output text characters instead – ace of diamonds is AD, and so on.
The 280-line program PokerHand accepts the name of the file on the command line, then reads it into memory and processes the 1,000 lines, each with seven cards, and evaluating the best hand for each line.
Git this file
The rust_PokerHand.zip file (available from https://github.com/David-H-Bolton/Projects/blob/main/) contains the project and both 1000_card_hand.txt and test_card_hands.txt.
The program is a direct translation of a C++ program written a few years ago. It evaluated each Explaining a Has hand in about three microseconds on a slightly slower computer, so this is a bit of an experiment to see how it compares. It didn’t disappoint, getting an average for the 1,000 hands of just under 600ns per hand when running a release build.
Let’s examine the program and we’ll try to explain some of the quirks. To run this as release inside VS Code, click in the terminal (View Terminal if necessary), and at a terminal prompt type in: $ cargo run – release card-hands.txt This assumes that the card file is in the main project folder. If it’s not, include the full path to the file.
QUECK TIP
Rust doesn’t allow the ++ or – operators like C/C++ and so on have for integer variables.
Instead, you can use += or -=to add or subtract values – for example, +=9.
QUECK TIP
Rust doesn’t allow the ++ or – operators like C/C++ and so on have for integer variables.
Instead, you can use += or -=to add or subtract values – for example, +=9.
PokerHand structure
It’s quite simple. The program gets a filename from the command, reads in the file of hands, and then processes them line by line. Each line is held as Vec<Card> and all lines are stored in a Vec<Vec <Card>>. A buffered reader (BufReader) is used to read the file in.
Explaining a HashMap holding values.