For in random order no repeating numbers - php

Whats the best way to do a random "for" without repeating any number?
for ($i = 1; $i <= 10; $i++) {
echo $i;
}
I think some ways but are so complicated with a lot amount of code..
There is a standard function to do what im willing?

$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.

$range = range(1,10);
shuffle($range);
foreach ($range as $i) {
echo $i;
}

Create an array with a range of numbers and then shuffle:
$array = range(1, 10);
shuffle($array);
for ($i=0,$c=count($array); $i<$c; $i++) {
echo $array[$i] . "\n";
}

Related

PHP - get random integer using random_int() without repeating and looping

I need to get 50 random numbers out of range 1-100 without repeating. The current way i do is :
$array = array();
while (count($array) <= 50) {
$temp = random_int(1,100);
if (!in_array($temp, $array))
$array[] = $temp;
}
However, the looping is too many because I need to generate for more than 100,000 times.
Is there other ways that I can get a 50 random non-repeating numbers without looping ?
For example:
$number= range(1,100);
$array = array_slice(shuffle($number),0,50);
I can't use shuffle because it uses pseudo random number.
Is there other ways to achieve what I need, or ways that could shorten time.
pre fill a array of numbers and pick from them, and then remove it.
it prevents the unnecessary random generations you have
$numbers = [];
for ($i = 1; $i <= 100; $i++) {
$numbers[] = $i;
}
$randomNumbers = [];
for ($i = 1; $i <= 50; $i++) {
$r = rand(0, count($numbers) - 1);
$randomNumbers[] = $numbers[$r];
array_splice($numbers, $r, 1);
}
This would be my approach:
This gives you 50 numbers in any case, and they are defenitely different from each other. PLUS: you dont have to prefill some other array:
$start = microtime(true);
for($i = 0; $i <= 100000; $i++){
$arr = [];
while(sizeof($arr) < 50){
$num = rand(1, 100);
$arr[$num] = $num;
}
if(array_unique($arr) !== $arr || sizeof($arr) !== 50 ){
print("FAIL");
}
//print(array_unique($arr) == $arr ? "true" : "false");print("<br>");
//print(sizeof($arr));print("<br>");
//print_r(array_count_values ($arr));print("<br>");
//print_r($arr);print("<br>");
}
$time_elapsed_secs = microtime(true) - $start;
print($time_elapsed_secs);print("<br>");
Running this 100000 times takes about 0.4sec for me.
The actual generation is done in this part:
$arr = [];
while(sizeof($arr) < 50){
$num = rand(1, 100);
$arr[$num] = $num;
}
We can do in 2 steps:
$x = 0;
$arr = [];
while($x < 50){
$tmp = rand(1, 100);
if(!in_array($tmp, $arr)){
$arr[] = $tmp;
$x++;
}
}

Max Amount of Loops

i have loops script like this
for($i=0; $i < count($json); $i++) {
}
for example, amount of $json is "12" or anything more than 10, but i want the max of that loops is 10, but, if i use this script
for ($x = 0; $x < 10; $x++) {
}
the result will be 10, but what if the $json amount I got is less than 10? means there will be NULL results, is there any suggestion?
You can use min() (http://php.net/manual/en/function.min.php)
$count = min (count($json), 10);
for($i=0; $i < $count; $i++) {
}
It's best to do the min outside the for so that it's only done once.
$count=count($json);
if($count > 10){
$count = 10;
}
for ($x = 0; $x < $count; $x++) {
}
You can use array_slice to grab the first 10 of the array and foreach them.
This way you will always just loop 10 times at the most.
$json =[1,2,3,4,5,6,7,8,9,10,11,12,13,14];
//$json =[1,2,3,4,5,6]; //uncomment if you want to test with smaller array
$arr = array_slice($json, 0,10);
Foreach($arr as $val){
Echo $val ."\n";
}
This can also be written like this:
Foreach(array_slice($json, 0,10) as $val){
Echo $val ."\n";
}
But I spelled it out just to make it clear.
You can try the code here: https://3v4l.org/7pV3X

How to replace a value in array by another different value in PHP?

I'm trying to find a way to replace any duplicated value but the only solution I have found so far is array_unique which doesn't really work for me as I need the duplicate to be replaced by another number which itself is not a duplicate.
function generate_random_numbers($rows, $delimiter)
{
$numbers = array();
for($i = 0; $i < $delimiter; $i++)
{
$numbers[$i] = rand(1, $rows);
if(in_array($i, $numbers))
{
$numbers[$i] = rand(1, $row);
}
}
return $numbers;
}
$numbers = generate_random_numbers(20, 10);
print_r($numbers);
would anyone help me out on this one please?
You can do this way easier and faster.
Just create an array for all possible numbers with range(). Then shuffle() the array and take an array_slice() as big as you want.
<?php
function generate_random_numbers($max, $amount) {
if($amount > $max)
return [];
$numbers = range(1, $max);
shuffle($numbers);
return array_slice($numbers, 0, $amount);
}
$numbers = generate_random_numbers(20, 10);
print_r($numbers);
?>
And if you want to get 490 unique elements from a range from 1 - 500, 10'000 times:
My version: ~ 0.7 secs
Your version: Order 2 birthday cakes, you will need them.
You are inserting a random number and then, if it is already in the array (which it MUST be because you just inserted it), you use a new random number, which might be a duplicate. So, you have to get a number that is not a duplicate:
do {
$num = rand(1,$rows);
} while(!in_array($num, $numbers));
Now, you know that $num is not in $numbers, so you can insert it:
$numbers[] = $num;
You were pretty close.
The if-clause needs to be a loop, to get new random number.
(Also your in_array was slightly wrong)
function generate_random_numbers($rows, $delimiter) {
$numbers = array();
for($i = 0; $i < $delimiter; $i++) {
do {
$number = rand(1, $rows);
}
while(in_array($number, $numbers));
$numbers[] = $number;
}
return $numbers;
}

sorting array value without using built in php like sort() etc

<?php
function sortArray() {
$inputArray = array(8, 2, 7, 4, 5);
$outArray = array();
for($x=1; $x<=100; $x++) {
if (in_array($x, $inputArray)) {
array_push($outArray, $x);
}
}
return $outArray;
}
$sortArray = sortArray();
foreach ($sortArray as $value) {
echo $value . "<br />";
}
?>
I have this code but there are two problems
What if my numbers in array are greater than 100?
Also, I'd like to see more than one method of sorting
Here is the way of sorting.
<?php
$array=array('2','4','8','5','1','7','6','9','10','3');
echo "Unsorted array is: ";
echo "<br />";
print_r($array);
for($j = 0; $j < count($array); $j ++) {
for($i = 0; $i < count($array)-1; $i ++){
if($array[$i] > $array[$i+1]) {
$temp = $array[$i+1];
$array[$i+1]=$array[$i];
$array[$i]=$temp;
}
}
}
echo "Sorted Array is: ";
echo "<br />";
print_r($array);
?>
Most of the other answers use two for loops to sort an array. At first the code seemed fairly straight and even I thought of the same. But then I wanted to investigate further. How efficient is this method? So using an array of 10,000 values, I used the two for loops method and got an execution time of 7.5 seconds
This is way too much. I'm sure PHP can't be this sloppy. So next I tested the in-built PHP rsort() function and got a time of 0.003 seconds.
Some research gave me the answer that PHP uses a quicksort algorithm to sort indexed arrays with a recursive function. I dug deeper and found a few examples of quicksearch for C++, Java etc. So, I replicated them in PHP, as follows:
/*
The main function that implements QuickSort
arr --> Array to be sorted,
low --> Starting index,
high --> Ending index
*/
function quickSort(&$arr, $low, $high)
{
if ($low < $high)
{
/* pi is partitioning index, arr[p] is now
at right place */
$pi = partition($arr, $low, $high);
// Separately sort elements before
// partition and after partition
quickSort($arr, $low, $pi - 1);
quickSort($arr, $pi + 1, $high);
}
return $arr;
}
function partition (&$arr, $low = 0, $high)
{
$pivot = $arr[$high]; // pivot
$i = ($low - 1); // Index of smaller element
for ($j = $low; $j <= $high-1; $j++)
{
// If current element is smaller than or
// equal to pivot
if ($arr[$j] <= $pivot)
{
$i++; // increment index of smaller element
swap($arr[$i], $arr[$j]);
}
}
swap($arr[$i + 1], $arr[$high]);
return ($i + 1);
}
function swap(&$a, &$b){
$t = $a;
$a = $b;
$b = $t;
}
The time taken by this algorithm came out be: 0.023 seconds. Not as fast as rsort() but satisfactory.
This is my Quicksort algorithm in PHP:
<?php
$array = [1, 4, 3, 5, 9, 6, 1, 6, 4, 1, 1, 4, 5, 6, 6, 7, 2, 1, 4, 0];
$j = count($array);
$t = $j-1;
while($j>=0){
for ($i=0; $i < $t; $i++) {
$aux = $array[$i];
if($array[$i]>$array[$i+1]){
$array[$i] = $array[$i+1];
$array[$i+1] = $aux;
}
}
$j--;
}
print_r($array);
Sorting an array without using the built-in method but all the answers use the pre-defined method count.
I am just trying to refactor it. Please find the below answer.
$array = [50,12, 30, 10, 9, 14];
$count = 0;
foreach($array as $elem){
$count++;
}
for ($i = 0; $i < $count; $i++) {
for ($j = 0; $j < $count - 1; $j++) {
if ($array[$j] > $array[$j + 1]) {
$temp = $array[$j];
$array[$j] = $array[$j + 1];
$array[$j +1] = $temp;
}
}
}
print_r($array);

Generating numbers and randomly displaying them

I want generate a list of numbers from 0000 to 9999. I would then like to take all the results and echo them out randomly. (not in order) How would I do this?
Thank you in advance!
$numbers = range(0,9999);
shuffle($numbers);
foreach($numbers as $number) {
echo str_pad($number,4,'0',STR_PAD_LEFT),'<br />';
}
To generate a list of 0000 to 9999, you can do something like this:
<?php
$array_list = array();
$end =9999;
for($idx=0; $idx<=$end; $idx++)
{
$array_list[$idx] = str_pad($idx, 4, 0, STR_PAD_LEFT);
}
?>
To generate that list randomly, you can use array_rand():
<?php
for($idx=0; $idx<=9; $idx++)
{
echo array_rand( $array_list );
}
?>
Edit:
Here..
$randarr = array();
for ($i = 0; $i < 9999; $i++) {
array_push($randarr, $i);
}
shuffle($randarr);
foreach($randarr as $randval) {
echo $randval . "\n";
}
PHP does have some basic functions to generate this range:
$aRange = range(0, 9999);
shuffle($aRange);
print_r($aRange);
print the 4 digits output:
foreach($aRange as $number) {
print str_pad($number, 4, 0, STR_PAD_LEFT);
}
Check out PHP's rand() function.
You could do something like:
for ( $counter=0; $counter < 10000; $counter += 1) {
$rand=rand(0,9999); echo $rand."<br />";
}

Categories