Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shuffles Random Numbers with no repetition in Javascript/PHP

I've searched through some of the answers here but it doesn't seem the thing that I needed or I just don't know how to apply it though.

I haven't started any codes and I'm only thinking on how to do it and I have no idea how to do it. I need your help guys.

Let's assume that I have an array which consists of these values below

[1,2,3,4,5,6,7,8,9]

And I need to shuffle it without repeating the position of each numbers of the last result. so it would probably like

[5,3,9,6,2,8,1,4,7]

if I shuffle it again it would be like

[4,7,2,1,8,3,6,9,5]

And so on.

Well I don't know if there' any relevance to it but, would rather not to use rand() though. Any solution for this stuff?

like image 554
Wesley Brian Lachenal Avatar asked Oct 21 '22 16:10

Wesley Brian Lachenal


2 Answers

Try this,

$count = 15;
$values = range(1, $count);
shuffle($values);
$values = array_slice($values, 0, 15);

OR

$numbers = array();
do {
   $possible = rand(1,15);
   if (!isset($numbers[$possible])) {
      $numbers[$possible] = true;
   }
} while (count($numbers) < 15);
print_r(array_keys($numbers));

may this help you.

like image 159
Tony Stark Avatar answered Oct 24 '22 13:10

Tony Stark


What you want to do is to add elements from your array to another array, randomly, but to ensure that elements are not in the same indexed position. Try this:

$array = [1,2,3,4,5,6,7,8,9];
$new = array();
for($i = 0; $i < $array.length; $i++){
  $rand = $i;
  do {
    $rand = Math.floor( Math.random() * ( $array.length + 1 ) );
  } while ($rand == $i || array_key_exists($rand, $new))
  // Check that new position is not equal to current index
  // and that it doesnt contain another element

  $new[$rand] = $array[i];
}

Not the most efficient, but guaranteed to put elements in non same indices.

like image 32
Husman Avatar answered Oct 24 '22 11:10

Husman