Reputation: 18197
I saw this question: Generating all 5 card poker hands, but I was programming in Python.
I had written my own logic to generate all the possible combinations, but it was running a long time, and although I made sure cards 2 through 5 didn't repeat the prior cards, I forgot to check when incrementing my subscript that the card being generated next hadn't already been used before.
So I'm answer my own question to show what I did.
Upvotes: 0
Views: 753
Reputation: 18197
import itertools
from time import time
import datetime as datetime1
startTime = time()
startDateNowFmt = datetime1.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print("Server Start DateTime=" + str(startDateNowFmt))
# Get all permutations of [1, 2, 3, etc... ]
max_number = 52
cards_per_hand = 5
top_of_range = max_number + 1
list_of_numbers = range(1, top_of_range) # one more than highest number
print("result")
result_list = list(itertools.combinations(list_of_numbers, cards_per_hand))
print("Number of combinations=", len(result_list))
# for testing, show a few, but don't show when generating all 2+ million hands
if len(result_list) < 100:
for item in result_list:
print(item)
endTime = time()
# print("StartTime=" + str(startTime) + " EndTime=" + str(endTime))
elapsedTime = endTime - startTime
endDateNowFmt = datetime1.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print("\n")
print("Server Start DateTime=" + str(startDateNowFmt))
print("Server End DateTime=" + str(endDateNowFmt))
minutes = elapsedTime / 60
print("ElapsedTime=" + str(elapsedTime) + " seconds, or " + str(minutes) + " minutes")
NOTE: I tend to show the elapsed time in all my programs. I was shocked that it ran in under 1 second!
This returns an array of arrays, each one have 5 numbers in it. From there, I should had to match up with my existing logic and class for assigning names, suit, rank, etc... to each card.
output:
Server Start DateTime=2021-02-14 18:04:50
result
Number of combinations= 2598960
Server Start DateTime=2021-02-14 18:04:50
Server End DateTime=2021-02-14 18:04:50
ElapsedTime=0.2652921676635742 seconds, or 0.004421536127726237 minutes
Output with a smaller amount of data where it prints the array (using these variable settings shown below). This helps to illustrate exactly what it is doing.
max_number = 6
cards_per_hand = 5
Number of combinations= 6
(1, 2, 3, 4, 5)
(1, 2, 3, 4, 6)
(1, 2, 3, 5, 6)
(1, 2, 4, 5, 6)
(1, 3, 4, 5, 6)
(2, 3, 4, 5, 6)
Upvotes: 1