Yeah, #2 is both more space efficient and more time efficient.
How I’d generally do something like that:
- Create an empty linked list.
- Generate a random integer between 0 and 51 inclusive.
- Iterate over the linked list and increment the random integer by one for each integer in the linked list less than or equal to your newly-generated random integer. You can break out of that loop as soon as you hit the first integer in the linked list greater than the newly-generated integer.
- Binary insert that integer into the sorted linked list.
- For the denomination, output the newly-generated integer modulus 13 plus one. Translate 1 to ace, 11 to jack, etc.
- For the suit, output floor of the newly-generated integer divided by 4 plus one. (Translate zero to “hearts”, one to “diamonds”, etc.)
- Loop back to step 2 51 more times.
Step 3 can definitely be optimized much more with a B-tree and a little thought. If you want jokers included, it’s pretty straightforward. (Just change step 2 to generate a random integer between 0 and 53 and tweak steps 5, 6, and 7.)
Good call on both counts!
I went ahead and fixed the suit/denomination mixup. I’ll leave the reast as-is so folks can learn from my mistakes and your post continues to make sense.
Cheers!