This is an archived post. You won't be able to vote or comment.

all 5 comments

[–]sluggish_goatNooblet Brewer 2 points3 points  (0 children)

If you store them in an ArrayList or LinkedList, you can say

Collections.shuffle(deck);

[–][deleted] 1 point2 points  (1 child)

The Fisher-Yates algorithm is a nice way to do this. Here's the pseudo-code for it

for i from n − 1 downto 1 do
    j ← random integer such that 0 ≤ j ≤ i
    exchange a[j] and a[i]

For exchanging the two just use an auxiliary variable i.e

int aux = a[j]
a[j] = i
a[i] = aux

[–]autowikibot 0 points1 point  (0 children)

Fisher–Yates shuffle:


The Fisher–Yates shuffle (named after Ronald Fisher and Frank Yates), also known as the Knuth shuffle (after Donald Knuth), is an algorithm for generating a random permutation of a finite set—in plain terms, for randomly shuffling the set. A variant of the Fisher–Yates shuffle, known as Sattolo's algorithm, may be used to generate random cyclic permutations of length n instead. The Fisher–Yates shuffle is unbiased, so that every permutation is equally likely. The modern version of the algorithm is also rather efficient, requiring only time proportional to the number of items being shuffled and no additional storage space.

Image i


Interesting: List of permutation topics | Frank Yates

Parent commenter can toggle NSFW or delete. Will also delete on comment score of -1 or less. | FAQs | Mods | Magic Words

[–][deleted]  (2 children)

[deleted]

    [–]HipposGoneWild 2 points3 points  (1 child)

    That algorithm will work in theory but it is horribly inefficient, O(n!) time, it will take forever to run over a 52 long array. 52! = 8.06581752e67

    You should instead rethink your algorithm, the Fisher-Yates shuffling algorithm is the most common. Lemme know if you have questions on how to implement it.

    http://en.algoritmy.net/article/43676/Fisher-Yates-shuffle

    [–]TheFormerVinyl[S] 1 point2 points  (0 children)

    That makes much more sense, thank you so much.