PHP Random Gen. Limit and Sorting [duplicate] - php

This question already has answers here:
PHP loop X amount of times
(10 answers)
Random Numbers without duplication using an array in PHP
(1 answer)
Closed 4 years ago.
How can I create a loop or limit for random number generation? I need 30 random numbers from (0,100).
I know I can use rand(0,100), for general generation of numbers. But I need to make this happen 30 times before I can sort out the data.
Repetition of numbers is NO issue, but I also need to sort the values into x<50 and x>50. Any idea how I can pull numbers from the array into 2 separate groups once generated?

Try this:
$lessFifty = array(); // Array to hold less than fifty numbers
$moreFifty = array(); // Array to hold more than fifty numbers
for ($i = 1; $i<=30; $i++) {
$number = rand(0, 100); // Variable $number holds random number
// Conditional statements
if ($number < 50 ) { // Check if value is less than fifty
$lessFifty[] = $number; // Add number to this array
} else { // Check if value is greater than fifty
$moreFifty[] = $number; // Add number to this array
}
}
// Display numbers in arrays
print_r($lessFifty);
print_r($moreFifty);
The for loop will will run the rand() function 30 times and insert each random number generated into the array $randomNum.
You can also use the while or do while loop to do the same action. It is up to you.

Related

PHP write a number out of an array

I have a PHP problem.
I need to write a number from a sets of digits 0-9. Each set has 10 digits, each digit once.
I need to count the number of sets that I have to use to write the number.
For example number 10 is written from one set, but number 300 uses 2 sets because it has two zeros.
But, the problem is that 6 and 9 are considered the same. They can be rotated by 180 degrees.
Number 266 will be using one set, 369 also is using one set, but 5666 is using 2 sets.
I would be very grateful if you could somehow help me.
Here is how I have started and stuck up, have no more clue how to loop through it. Tried many things, nothing successful.
<?php
function countSet($num) {
$array = str_split($num);
$statarr = [0,1,2,3,4,5,6,7,8,9];
$a1 = $array; $a2 = $statarr;
$result = array_intersect($a1,$a2);
$count = array_count_values($result); }
?>
If you just need to know how many sets you need for a number, you can solve by counting the numbers. For the case of the 9, just replace every 9 by a 6 and divide the number of 6 by two. Something like this (sorry if there's any syntax error, I'm on mobile):
function countSet($input) {
// Convert the input into a string and replace every 9 by a 6. Then convert it to array
$numbers = str_split(str_replace("9", "6", strval($input)));
// Count occurrences for each number
$usedNumbers = array_count_values($numbers);
// If we have a 6, must divide it by 2 (6 represents 6 and 9
if (array_key_exists("6", $usedNumbers)) {
$usedNumbers["6"] = ceil($usedNumbers["6"] / 2);
}
// Now we just need to know the max number of occurrences for a single number as our result.
return max($usedNumbers);
}
See an online demo here

Pair all elements of an array in all possible combinations php

I've done some searching all i could find is this unfortunately thats not exactly what i'm looking for.
My problem is, i have a list of user ids in an array that could vary in size from 0 to 30+ users.
looks somehting like:
$arr = array(1,2,3);
What i need is to be able to find all pairs possible with this users:
(1 - 2)
(1 - 3)
(2 - 1)
(2 - 3)
(3 - 1)
(3 - 2)
the idea is to be able to create contact lists on a messaging platform so each one has each other on their contact list.
the examples on the question linked above gives me repeating elements and i can't have repeating elements also don't need 3 elements pared together only 2.
You have two objectives from the way I see it:
Display all possible pairs between a and b numbers
Don't display the same combination twice
You can achieve this with two loops and by keeping track of what you've processed already:
$arr = range(1, 30);
$alreadyProcessed = array();
foreach ($arr as $first) {
// Loop the array twice (as #Dagon mentioned)
foreach ($arr as $second) {
// Keep track of what you've already processed
$combination = array($first, $second);
// Sorting the numbers will ensure that 2 - 1 and 1 - 2 are the same
sort($combination);
// Ensure they aren't the same number and you haven't already processed them
if ($first === $second || in_array($combination, $alreadyProcessed)) {
continue;
}
// Output as per your example
echo "($first - $second)" . PHP_EOL;
// Add it to the list of what you've already processed
$alreadyProcessed[] = $combination;
}
}
NOTE: this kind of logic is bad. You're performing an exponential number of repetitions because you're looping an array inside a loop of the same array. This particular example will perform 30 to-the-power-of 30 repetitions (a big, big number of cycles). That's only with 30 entries. What happens if your user base grows to 10,000? Bye bye server.

Concat unique or delete duplicate string php/mysql

I need to remove duplicates from a table row.
to Combine the 3 numbers and generate all possible combinations, posted by .html form
(will be 6 if all numbers are different) Numbers must have 6 numbers each, like:
123, 234,etc.... Reduces the number of combinations if one number is the same of another,
like 112.
What i did, till now...
to isolate the numbers and store it in a row:
$cc=GetRow("SELECT numbers FROM table");
$n1=substr($cc, 0, 1);
$n2=substr($cc, 1, 1);
$n3=substr($cc, 2, 1);
//scrambling the numbers
$n1n2n3=$n1.$n2.$n3; //123 number stored
$n1n3n2=$n1.$n3.$n2; //132 number stored
$n2n1n3=$n2.$n1.$n3; //213 number stored
$n2n3n1=$n2.$n3.$n1; //231 number stored
$n3n1n2=$n3.$n1.$n2; //312 number stored
$n3n2n1=$n3.$n2.$n1; //321 number stored
$sql = sqlQuery("UPDATE table SET cc_concat = CONCAT_WS(',', '$n1n2n3', '$n1n3n2','$n2n1n3','$n2n3n1','$n3n1n2','$n3n2n1')");
But hereĀ“s the problem:
if the number is 112 will generate duplicates, only 3 are uniques:
$n1n2n3=$n1.$n2.$n3; //112 number stored
$n1n3n2=$n1.$n3.$n2; //121 number stored
$n2n1n3=$n2.$n1.$n3; //112 number stored
$n2n3n1=$n2.$n3.$n1; //121 number stored
$n3n1n2=$n3.$n1.$n2; //211 number stored
$n3n2n1=$n3.$n2.$n1; //211 number stored
Is there a way to update the table without the duplicates? or remove the duplicates
after update?
Thanks!
You could use an array to store the combinations and take advantage of the in_array() function to make sure you won't have duplicates:
$combinations = array();
if ( !in_array( $n1n2n3, $combinations ) ) $combinations[] = $n1n2n3;
if ( !in_array( $n1n3n2, $combinations ) ) $combinations[] = $n1n3n2;
// Do the same for the rest
// Then you could easily concatenate the result set from PHP.
$cc_concat = implode( ',', $combinations );
// Finally update the database.
$sql = sqlQuery("UPDATE table SET cc_concat = '{$cc_concat}' ");
Something like that should solve the problem.
Additionally you might prefer to use an algorithm to generate the combinations for you from an array of the three digits. For such algorithm you can check this thread out:
Get all permutations of a PHP array?

PHP List all possible 6-digit numbers with specific digits [duplicate]

This question already has answers here:
Algorithm to get all possible string combinations from array up to certain length
(12 answers)
Closed 9 years ago.
How could I generate every possible number of a given amount of digits and using specific digits?
So basically, I would like to have a 6 digit number for example using only the numbers ['1','2','3']. I've tried a few methods of recursion, however, I can't get it to work correctly due to my other complication, which is adding a separator of "|" in between each 2 digits. So the list would be like so:
11|11|11
11|11|12
11|11|13
11|11|21
11|11|22
11|11|23
etc..
Would be appreciated if someone could point me in the right direction.
Also a way of dumping each of the combinations into my MySQL database would be great.
Here is a much updated answer (originally updated from this answer]1) to your question:
function findPermutations($arr, $arrLen, $size, $perArr = array(), $pos = 0, &$found = array()) {
if ($size==$pos) { //if $pos reach $size then we have found one permutation
$found[] = vsprintf("%s%s|%s%s|%s%s", $perArr);
return;
}
for ($i=0; $i<$arrLen; $i++) {
$perArr[$pos] = $arr[$i]; //put i'th char in current position
//The recursive call that move to next position with $pos+1
findPermutations($arr, $arrLen, $size, $perArr, $pos+1, $found);
}
return $found;
}
$permutations = array();
$letters = array('1','2','3');
$max_length = 6;
$permutations = findPermutations($letters, count($letters), $max_length);
for($i = 0; $i < count($permutations); $i++) {
print ($permutations[$i].'<br/>');
}
Here is what I'm doing. I'm passing in an empty array called $permutations by reference, and as I find new permutations, I'm appending them to it. When the function findPermutations() is complete, I end up with an array of all permutation, that I can iterate over or insert. To get the formatting I'm using vsprintf, that lets me pass an array of data and apply a format (in this case %s%s|%s%s|%s%s). Lastly I'm using default argument values to make calling this function cleaner.
you mean something like this?
$letters='123'; // add other numbers
for($i=0;$i<3;$i++) { //generate 3 pairs
$pairs[]=$letters[rand(0,2)] . $letters[rand(0,2)];
}
//then join them together
$finalstring=implode('-',$pairs);

PHP Unique Random Numbers

What would be a good way to generate 7 unique random numbers between 1 and 10.
I can't have any duplicates.
I could write a chunk of PHP to do this (using rand() and pushing used numbers onto an array) but there must be a quick way to do it.
any advice would be great.
Create an array from 1 to 10 (range).
Put it in random order
(shuffle).
Select 7 items from the array (array_slice)
Populate an array with ten elements (the numbers one through ten), shuffle the array, and remove the first (or last) three elements.
Simple one-liner:
print_r(array_rand(array_fill(1, 10, true), 7));
Check out the comments in the php manual, there are several solutions for this.
An easy one is this one:
$min = 1;
$max = 10;
$total = 7;
$rand = array();
while (count($rand) < $total ) {
$r = mt_rand($min,$max);
if (!in_array($r,$rand)) $rand[] = $r;
}
Whole numbers? Well, if you want 7 out of 10 then you more efficiently DON'T want 3 out of 10.
Feel free to use any of the other responses but instead of creating 7 numbers start with 10 and eliminate 3. That will tend to speed things up by more than double.
The "shuffle" method has a MAJOR FALW. When the numbers are big, shuffle 3 billion indexs will instantly CAUSE 500 error. Here comes a best solution for really big numbers.
function getRandomNumbers($min, $max, $total) {
$temp_arr = array();
while(sizeof($temp_arr) < $total) $temp_arr[rand($min, $max)] = true;
return $temp_arr;
}
Say I want to get 10 unique random numbers from 1 billion to 4 billion.
$random_numbers = getRandomNumbers(1000000000,4000000000,10);
PS: Execution time: 0.027 microseconds

Categories