Reputation: 108
I am working on a scratch card in PHP and i need to build the backbone behind it.
My plan is as following:
Generate 15 random numbers ( there are 8 containers and 15 images to choose from. ).
Each number correspondences with a image ( 1 is image 1, 2 is image 2 etc. ).
Show a random image (1/15) on container 1, show random image (1/15) on container 2 etc. There are 8 containers to be filled.
What i currently can't figure out is to check if there are duplicate numbers, and if so it is fine to have 2 duplicates but not 3 since that would mean a win.
What i have now is this:
$images = array();
for ($i = 0; $i < 8; $i++) {
$random[$i] = rand(1,15);
}
This will fill $random with 15 numbers i can use. Now i want to check if within those 15 there are duplicates. But the trick is that duplicates are no problem ( and even preferred on some degree ) but once there are 3 of the same numbers i want one of those to change again in a random number ( and re-check for duplicates).
So what should be fine ( 2x 8 is fine, 2x 1 is fine ):
Container 1: 14
Container 2: 8
Container 3: 8
Container 4: 4
Container 5: 1
Container 6: 9
Container 7: 1
Container 8: 12
What should be incorrect ( 3x 14 is not fine ):
Container 1: 14
Container 2: 8
Container 3: 4
Container 4: 14
Container 5: 14
Container 6: 9
Container 7: 1
Container 8: 12
You guys have any advice on what the right way is here? I am trying to stay away from a lot of "if's".
Upvotes: 0
Views: 191
Reputation: 23958
Two sets of 15 ranges and shuffle them.
Then slice out 8 items from the array.
$random = array_merge(range(1,15), range(1,15));
shuffle($random);
$random = array_slice($random, 1,8);
Print_r($random);
Upvotes: 1
Reputation: 22997
You could create an array with each selectable element twice.
Then, 8 times, pick a random index from the array and remove it from the array.
$random = [ ];
for ($i = 1; $i <= 15; $i++) {
$random[] = $i;
$random[] = $i; // Twice
}
for ($i = 0; $i < 8; $i++) {
$pick = rand(0, count($random));
// Use $random[$pick]
// Remove array key at index $pick
}
Upvotes: 0