QWERTY
QWERTY

Reputation: 2315

Algorithm on random generated numbers with guaranteed that all numbers within the range will be selected once

I was having some problem to come out with a solution for a problem, I am currently still in the thought process. So basically the problem is to random generate numbers between 0 to 12, and get the two numbers to perform multiplication within a time frame.

However, the solution provided must guaranteed that the all 169 random generated number pairs must be shown eventually, so cannot just randomly select a number. I was thinking adding a weight to random selected number helps in this case? Or there is better approach for this?

Thanks!

Upvotes: 1

Views: 48

Answers (1)

Erwin Bolwidt
Erwin Bolwidt

Reputation: 31279

What this boils down to: you don't really want the number pairs to be random, because a random value means that your next value does not depend on any previous value. Instead, you want 169 known number pairs to come up, each only once, but you want the order of them to be random.

As if these number pairs were printed in playing cards, and you were shuffling the playing cards.

And Java has a nice method for that: Collections.shuffle acts like a professional dealer who shuffles a deck of playing cards.

You want an approach where you first generate all the playing cards, and then shuffle them. Something like this:

List<Integer[]> l = new ArrayList<>();
for (int x = 0; x <= 12; x++) {
    for (int y = 0; y <= 12; y++) {
        l.add(new Integer[] {x, y});
    }
}
Collections.shuffle(l);

Upvotes: 2

Related Questions