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 Two!
Don’t miss next issue, subscribe on page 16!
Part Two!
Don’t miss next issue, subscribe on page 16!
I
n this article, we’re writing and running two programs. One, called
CardShuffle,
does the timing of three slightly different ways of shuffling a deck of 52 cards to see which is fastest. The second program,
PokerGen, outputs a text file of 1,000 lines of seven cards per line. You can download a ZIP file containing the Rust sources and project files from GitHub at https://bit.ly/lxf326code. Unzip and then openVSCin either project folder.
In next month’s instalment, a third program (PokerHand) will read this file line by line and determine the best five-card hand from the seven cards for each set as quickly as possible.
As usual, the project files were created with the cargo new command. For details on installing Rust, VS Code and the two extensions needed, please see the article in LXF325. Let’s look at CardShuffle first.
CardShuffle
This generates a deck of cards in the Deck::new() method. Remember the ::new method is like a constructor in other languages but is not called that. Deck is a struct with a cards field, which is a Vec<Card>, and a Card is a struct with two enums for Rank and Suit. These are:
struct Card { rank: Rank, suit: Suit, } struct Deck { cards: Vec<Card>, }
If you look at the source file, you’ll also see lines like #[derive(Debug, Clone, PartialEq)] , which are declared above each enum and struct. These are called traits and specify basic implementations but you can provide your own as well. These are the standard traits available:
Comparison traits: Eq, PartialEq, Ord, PartialOrd. Clone, to create T from &T via a copy.
• Copy, to give a type copy semantics instead of move semantics.
Hash, to compute a hash from &T.