Master PostgreSQL: Generate a Deck of Cards and Randomly Deal Any Hand Size with Just SQL.



Master PostgreSQL: Generate a Deck of Cards and Randomly Deal Any Hand Size with Just SQL.

Master PostgreSQL: Generate a Deck of Cards and Randomly Deal Any Hand Size with Just SQL.

The program begins by creating a table named “deck” with a single primary key column called “card”. The column data type is varchar with a maximum length of 20 characters. This table will be used to store the 52 cards in a standard deck of cards.

The first function, “populate_deck()”, initializes the “deck” table by filling it with all 52 unique cards. This is achieved by declaring two arrays, “card_suit” and “rank_value”. These arrays hold the different suits and ranks of the cards, respectively. A nested loop is then used to create all possible card combinations. The “card_value” variable is created by concatenating a rank value and a card suit. Then, each card is inserted into the “deck” table using an INSERT statement. Before populating the table, the “TRUNCATE” command is used to clear any existing data in the table.

The second function, “pick_random_cards(number_of_cards_requested integer)”, allows the user to request a certain number of random cards from the “deck” table. If the number of cards requested is greater than the number of cards in the table, the “populate_deck()” function is called to refill the table with the 52 cards.

To randomly select the requested number of cards, a loop is used. First, the function initializes an empty array called “selected_cards” to hold the selected cards. The total number of cards in the “deck” table is then counted using the “SELECT COUNT(*) INTO” statement, and this number is stored in the “number_of_cards_in_the_deck” variable.

If the requested number of cards is greater than the number of cards in the “deck” table, the “populate_deck()” function is called to refill the table with the 52 cards.

Then, for each card requested, a subquery is used to select a random card from the “deck” table using the “ORDER BY RANDOM() LIMIT 1” statement. The selected card is then added to the “selected_cards” array using the “array_append(selected_cards, selected_cards_temp)” statement. Finally, the selected card is deleted from the “deck” table using the “DELETE FROM deck WHERE card = selected_cards_temp” statement.

After all requested cards are selected and removed from the “deck” table, the “RETURN QUERY” statement returns the “selected_cards” array to the user.

@SoftwareNuggets #softwarenuggets

Comments are closed.