Shuffle and Deal
Updated
•2 min read
-- shuffle and deal (dealing 2 cards to 5 players, change as needed)
with suites as (select 'clubs' name from dual
union all select 'diamonds' name from dual
union all select 'hearts' name from dual
union all select 'spades' name from dual
) -- generate suites
,cards as (select level l
,case when level between 2 and 10
then to_char(level)
else case level when 1 then 'A'
when 11 then 'J'
when 12 then 'Q'
else 'K'
end
end num
from dual
connect by level <= 13
) -- generate 2-10,A,J,Q,K
,deck as (select cards.num || ' ' || suites.name card
,cards.num num
,suites.name suite
from suites
,cards
order by suites.name
,cards.l
) -- cartesian suites and cards
-- select * from deck -- check the deck
,shuffle as (select card
,num
,suite
from deck
order by dbms_random.value
) -- shuffle
--select * from shuffle -- check the shuffle
--
,deal as (select card
,r
,case when mod(r ,5) = 0 then 5
else mod(r ,5)
end player_number -- max :player count
,case when mod(r ,2) = 0 then 2
else mod(r ,2)
end card_number -- max :card count
,num
,suite
from (select rownum r
,card
,num
,suite
from shuffle
where rownum <= 5 * 2
) -- deal till run out of cards (:players * :cards)
)
-- main query
select 'Player ' || player_number player_number_str
,listagg(card ,', ') cards
from deal
group by player_number
order by player_number
;
-- end shuffle and deal
Sample result:
PLAYER_NUMBER_STR CARDS
Player 1 9 hearts, K clubs
Player 2 7 diamonds, 10 clubs
Player 3 Q spades, 10 diamonds
Player 4 J hearts, 7 hearts
Player 5 8 diamonds, 6 hearts