Skip to the code
cf.
+25 XP

#87 Deal a Random Hand

medium

A card game deals k cards from deck without shuffling the whole deck. It uses a partial Fisher-Yates shuffle from the front: on a copy of deck, for i from 0 to k - 1, take the random number randoms[i], set j = i + Math.floor(randoms[i] * (n - i)) where n is the deck size, and swap the cards at i and j.

Write dealHand(deck, k, randoms) that returns the first k cards of the copy after those k steps.

Example 1

Input: deck = ["A","K","Q","J","10"], k = 2, randoms = [0.5,0.1]
Output: ["Q","K"]

i = 0: j = 0 + floor(0.5 * 5) = 2, so Q moves to the front. i = 1: j = 1 + floor(0.1 * 4) = 1, so K stays.

Example 2

Input: deck = ["x","y","z"], k = 0, randoms = []
Output: []

Dealing no cards gives an empty hand.

Constraints

  • 0 <= k <= deck.length <= 1000
  • randoms.length === k
  • 0 <= randoms[i] < 1
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).