Shuffles Random Numbers with No Repetition in JavaScript/Php

Shuffles Random Numbers with no repetition in Javascript/PHP

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.

How to randomly generate numbers without repetition in javascript?

Generate a range of numbers:

var numbers = [1, 2, 3, 4];

And then shuffle it:

function shuffle(o) {
for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
};

var random = shuffle(numbers);

Javascript randomize array without having element in starting position

Try --m, not m--:

function shuffle(array){
var m = array.length, t, i;
while(m){
i = Math.floor(Math.random() * --m);
t = array[m];
array[m] = array[i];
array[i] = t;
}
return array;
};

Because if you use m-- you can possibly get i == m and swap array element with itself.

Generate 15 random numbers that may be the same 2 times but not 3 times

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);

PHP random number no repeat

Your idea with a shuffled array is fine, just store it in a session variable:

session_start();
if (!isset($_SESSION["numbers"]) || !count($_SESSION["numbers"])) {
$_SESSION["numbers"] = range(1, 99);
shuffle($_SESSION["numbers"]);
}
$next = array_pop($_SESSION["numbers"]);

For in random order no repeating numbers

$numbers = range(1,10);
shuffle($numbers);
foreach($numbers as $i) {
// do stuff
}

That will give you the numbers 1 to 10 with no repetition in a random order.

Generating random numbers without repeats

Easiest solution:

$numbers = range(1, 20);
shuffle($numbers);

Alternative:

<?php

function randomGen($min, $max, $quantity) {
$numbers = range($min, $max);
shuffle($numbers);
return array_slice($numbers, 0, $quantity);
}

print_r(randomGen(0,20,20)); //generates 20 unique random numbers

?>

Similar question: #5612656

Codepad: http://codepad.org/cBaGHxFU

Update:

You're getting all the listings in an array called $businesses.

  1. Generate a random listing ID using the method given above, and then store it your database table.
  2. On each page refresh, generate a random listing ID, and check if it matches the value in your database. If not, display that listing and add that value to your table.
  3. Go to step 1.

When this is completed, you will have displayed all the 20 listings at once.

Hope this helps!



Related Topics



Leave a reply



Submit