Convert GMP integer to a sum of power of two (2n) - php

I'm using GMP library of php to solve a problem of formulary.
public function gmp_sum($aRessource)
{
// Avec le while
$i = 0;
$nb_ressource = count($aRessource);
while ($i < $nb_ressource)
{
if ($i == 0)
{
$tmp = gmp_init($aRessource[$i]);
}
else
{
$tmp = gmp_add(gmp_init($aRessource[$i]),$tmp);
}
$i++;
}
return $tmp;
}
The variable $aRessource is equal to : array(1,2,4,8);
so my function gmp_sum is returning 15.
I want to create an algorithm who does the reverse operation, the function take the integer 15 and return me an array who contains 1 2 4 8. But I do not know where to start.
Thanks for the help
Solution :
Decompose integer to power of 2 in php
public function gmp_reverse($gmp_sum)
{
$res = array();
$i = 1;
while ($i < 64) // 64 bytes
{
$tmp = $gmp_sum & $i; // check if bytes equal to 1
if ($tmp != 0)
{
array_push($res,$i);
}
$i = $i * 2;
}
return $res;
}

Assuming you want an array which adds up to the sum, you want a reverse of that. This function assumes, you have a perfect input, so for example, 17 will not work.
Try it out.
function reversegen($gmpsum)
{
$stack = array();
$limit = $gmpsum;
$cur = 1;
for($sum = 0; $sum < $limit; )
{
echo $cur. "<br>";
array_push($stack,$cur);
$sum = $sum + $cur;
$cur = 2 * $cur;
}
return($stack);
}
$stack = reversegen(15);
print_r($stack);
15 above is for representative purpose. You can use, 31, 63, 127 etc and it will still work fine.

Related

PHP: Getting random combinations to specified input

I am trying to display possibilities for additions of specific numbers but have not been getting the right results.
<?php
$num3 = 20;
$set = null;
$balance = $num3;
$dig = mt_rand(1,5);
for($i = $balance; $i > 0; $i -= $dig ){
echo $dig.'<br>';
if($i < 1){
$set .= $i;
$balance = 0;
}
else{
$set .= $dig.'+';
$dig = mt_rand(1,5);
}
}
echo $set.'='.$num3;
?>
Here are some of the outputs:
2+5+1+4+5+3+=20
1+4+3+5+3+=20
3+1+1+2+3+4+4+1+3+=20
Appreciate any pointers. Thank in advance...
Ok, even though the requirement isn't completely clear, here's an approach:
(edit: demonstrating prevention of endless loop)
$max_loops = 1000;
$balance = 20;
$found = [];
while($balance > 0 && $max_loops-- > 0) {
$r = mt_rand(1, 5);
if ($balance - $r >= 0) {
$found[] = $r;
$balance -= $r;
}
}
echo implode(' + ', $found) . ' = '.array_sum($found);
Note: This code has a small risk of getting caught in an endless loop... though it's doubtful that it'll ever happen :)
Edit: Now the loop contains a hard-limit of 1000 iterations, after which the loop will end for sure...
To provoke an endless loop, set $balance = 7 and modify mt_rand(4, 5).
You can use a recursive function for this:
function randomAddends($target, $maxAddend = 5, $sum = 0, $addends = [])
{
// Return the array of addends when the target is reached
if ($target <= $sum) {
return $addends;
}
// generate a new random addend and add it to the array
$randomAddend = mt_rand(1, min($maxAddend, $target - $sum));
$addends[] = $randomAddend;
// make the recursive call with the new sum
return randomAddends($target, $maxAddend, $sum + $randomAddend, $addends);
}

Functions about random numbers

How can I create functions that answer to:
How many different numbers were generated during simulation?
% Of appearance of the numbers from 0 to 50 ?
What is the number that appeared several times during the simulation?
function randomDigits($numDigits) {
$arrayRange = 1000;
if ($numDigits <= 0) {
return '';
} else{
for($i=0; $i<$arrayRange; $i++){
echo mt_rand(0, 50) ." ";
}
}
}
$maxq = 100;
for ($i = 1; $i <= $maxq; $i++) {
echo $i . "<br>\n";
randomDigits($i) . "<br>\n----<br>\n";
}
If you store all the generated numbers into an array, you could use array_count_values()
This will count the occurrences of multiple key values in your array (e.g. if there are 12 occurrences of the number 7) and return the result in an array. This will only work for strings and integer values.
<?php
$array = ['a', 'a', 'a', 'a', 'b', 'b', 'c'];
print_r(array_count_values($array));
?>
Results from the above:
Array(
[a] => 4
[b] => 2
[c] => 1
)
From there, you should be able to easily do all the methods and outputs that you wish.
Here is the basic integration with your existing code...
<?php
$maxq = 100;
$returned_array = [];
for ($i = 1; $i <= $maxq; $i++) {
$returned_array = randomDigits($i); // return the generated array
// merge 'add' the two arrays, like saying i = i +2 or
// merged_array = merged_array + array
array_merge($returned_array, $returned_array);
// here you now have one array of 1000 random values
// print_r($returned_array);
// lets do some math
print_r(array_count_values($returned_array));
// this will show how many values were duplicates...
// e.g
// Array (
// [43] => 25 the number 43 was generated 25 times
// [25] => 22 the number 25 was generated 22 times
// [1] => 28 ect...
// you can loop through this array here and see which value was generated several times,
// format the results nicely, and do all sorts of maths on it as you wish
}
function randomDigits($numDigits) {
$arrayRange = 1000;
$generated_array = []; // here is an actual array that will store the generated numbers
if ($numDigits <= 0) {
return null;
} else {
for($i = 0; $i < $arrayRange; $i++) {
$random = mt_rand(0, 50);
array_push($generated_array, $random); // add the random value to the array
}
// here you have your array of generated numbers
return $generated_array;
}
}
?>
Example here - http://codepad.org/9Dv1CwR7
Sequence generation contains random integers for given length
function generate_array($count, $min, $max) {
$arr = array();
for ($i=0; $i<$count; $i++) {
$arr[$i] = rand($min, $max);
}
return $arr;
}
Calculating percentage of given interval (with a helper function):
function cnt($element, $arr){
$cnt = array_count_values($arr);
return $cnt[$element];
}
function percentages($min, $max, $arr) {
$total = sizeof($arr);
$occurences = 0;
while ($min < $max) {
if (!array_key_exists($min, $arr)) {
continue;
} else {
$occurences = $occurences + cnt($min, $arr);
}
$min++;
}
return $occurences/$total;
}
Add all simulated values to an array, and use array_count_values to get all unique values.
function randomDigits($numDigits) {
$arrayRange = 1000;
if ($numDigits <= 0) {
return '';
} else{
$arr=array();
for($i=0; $i<$arrayRange; $i++){
$val=mt_rand(0, 50);
$arr[]=$val;
echo $val ." ";
}
echo "\n";
$arr=array_count_values($arr);
echo "Total Unique numbers:".count($arr);
}
}
$maxq = 100;
for ($i = 1; $i <= $maxq; $i++) {
randomDigits($i) . "<br>\n----<br>\n";
}

N random numbers that can duplicate after 2 elements

I want to generate 10 numbers with each ranging from (1 to 5) but can only duplicate after 2 elements
for example 5 3 1 4 2 5(can be duplicated here) 2 (cannot be duplicate here since it occur before 1 element) ...etc.
I have this code in php working but its performance is awful since it sometimes exceeds the maximum 30 seconds execution time.
<?php
function contain($prevItems, $number) {
if (count($prevItems) == 3)
{
array_shift($prevItems);
}
for ($k=0; $k<count($prevItems); $k++) {
if ($prevItems[$k] == $number)
return true;
}
return false;
}
$num[0] = rand(1,5);
$prevItems[0] = $num[0];
for ($i=1; $i<=10; $i++) {
$num[$i] = rand(1,5);
while (contain($prevItems, $num[$i])) {
$num[$i] = rand (1,5);
}
$prevItems[$i] = $num[$i]; //append into the array
}
print_r($num);
?>
Edit:
I have also tried this method, its performance is good but it duplicates elements
<?php
$evalAccurance = array();
$count = 0;
while ( $count < 11)
{
$random = rand(1, 5);
if (in_array($random, $evalAccurance))
{
$p = $random;
for ($k = $p ; $k <5; $k++)
{
$random = $random++;
if (in_array($random, $evalAccurance))
continue 1;
else break 1;
}
if (in_array($random, $evalAccurance))
{
for ($k = $p ; $k >0; $k--)
{
$random = $random--;
if (in_array($random, $evalAccurance))
continue 1;
else break 1;
}
}
}
$evalAccurance[] = $random;
if (count ($evalAccurance) == 4)
array_shift($evalAccurance);
print_r ($evalAccurance);
$count++;
}
?>
One way you could do this:
// pass to function current array of numbers
function randomNumber($ar){
// create a random number from 1 to 5
$num = rand(1,5);
// check backwards 3 elements for same number, if none found return it
if(!in_array($num, array_slice($ar, -3, 3, true))){
return $num;
} else {
// else recall function with same array of numbers
return randomNumber($ar);
}
}
$array = array();
// loop 10 numbers and call randomNumber with current set of results.
for($i=1; $i<=10; $i++){
$array[] = randomNumber($array);
}
print_r($array);
Using PHP SPLQueue:
$queue = new SplQueue();
$values = array(1, 2, 3, 4, 5);
$container = array();
for ($i = 0; $i < 10; $i++) {
$value = give_random($values, $queue);
$container[] = $value;
if ($queue->offsetExists(1) AND $queue->offsetExists(0)) {
$queue->dequeue();
}
$queue->enqueue($value);
}
function give_random(&$values, &$queue) {
$picked_value = $values[array_rand($values)];
if ($queue->offsetExists(1)) {
if ($picked_value == $queue->offsetGet(1)) {
$picked_value = give_random($values, $queue);
}
}
if ($queue->offsetExists(0)) {
if ($picked_value == $queue->offsetGet(0)) {
$picked_value = give_random($values, $queue);
}
}
return $picked_value;
}
print_r($container);
It could be neater, but you can figure what's going on.
Cheers.

Writing merge sort in PHP

I have tried to write a basic merge sort in PHP involving a small array, yet the problem is it takes about a minute or so to execute, and returns:
Fatal error: Allowed memory size of 536870912 bytes exhausted (tried
to allocate 35 bytes) in /Users/web/www/merge.php on line 39
Does anyone have an idea where the code might be going wrong (if at all)? I've been staring at this for a good hour now.
<?php
$array = array(8,1,2,5,6,7);
print_array($array);
merge_sort($array);
print_array($array);
function merge_sort(&$list){
if( count($list) <= 1 ){
return $list;
}
$left = array();
$right = array();
$middle = (int) ( count($list)/2 );
// Make left
for( $i=0; $i < $middle; $i++ ){
$left[] = $list[$i];
}
// Make right
for( $i = $middle; $i < count($list); $i++ ){
$right[] = $list[$i];
}
// Merge sort left & right
merge_sort($left);
merge_sort($right);
// Merge left & right
return merge($left, $right);
}
function merge(&$left, &$right){
$result = array();
while(count($left) > 0 || count(right) > 0){
if(count($left) > 0 && count(right) > 0){
if($left[0] <= $right[0]){
$result[] = array_shift($left);
} else {
$result[] = array_shift($right);
}
} elseif (count($left) > 0){
$result[] = array_shift($left);
} elseif (count($right) > 0){
$result[] = array_shift($right);
}
}
print_array($result);exit;
return $result;
}
function print_array($array){
echo "<pre>";
print_r($array);
echo "<br/>";
echo "</pre>";
}
?>
In your merge function, you call count on right instead of $right. PHP assumes this is a string constant (at least in 5.3.9) and when casted into an array that always has one element. So count(right) is always one, and you never exit the first merge.
Try this approach. Instead of shifting it, slice.
Also, for in while loop for the merge function, you need to do an and && comparison instead
of ||
function mergeSort($array)
{
if(count($array) == 1 )
{
return $array;
}
$mid = count($array) / 2;
$left = array_slice($array, 0, $mid);
$right = array_slice($array, $mid);
$left = mergeSort($left);
$right = mergeSort($right);
return merge($left, $right);
}
function merge($left, $right)
{
$res = array();
while (count($left) > 0 && count($right) > 0)
{
if($left[0] > $right[0])
{
$res[] = $right[0];
$right = array_slice($right , 1);
}
else
{
$res[] = $left[0];
$left = array_slice($left, 1);
}
}
while (count($left) > 0)
{
$res[] = $left[0];
$left = array_slice($left, 1);
}
while (count($right) > 0)
{
$res[] = $right[0];
$right = array_slice($right, 1);
}
return $res;
}
Have a look at this, the algorithm is already implemented, using array_push and array splice instead of just array_shift.
http://www.codecodex.com/wiki/Merge_sort#PHP
I implement merge sort this way
function mergeSort($Array)
{
$len = count($Array);
if($len==1){
return $Array;
}
$mid = (int)$len / 2;
$left = mergeSort(array_slice($Array, 0, $mid));
$right = mergeSort(array_slice($Array, $mid));
return merge($left, $right);
}
function merge($left, $right)
{
$combined = [];
$totalLeft = count($left);
$totalRight = count($right);
$rightIndex = $leftIndex=0;
while ($leftIndex < $totalLeft && $rightIndex < $totalRight) {
if ($left[$leftIndex] > $right[$rightIndex]) {
$combined[]=$right[$rightIndex];
$rightIndex++;
}else {
$combined[] =$left[$leftIndex];
$leftIndex++;
}
}
while($leftIndex<$totalLeft){
$combined[]=$left[$leftIndex];
$leftIndex++;
}
while ($rightIndex<$totalRight){
$combined[] =$right[$rightIndex];
$rightIndex++;
}
return $combined;
}
Here is the class in PHP to implement the Merge Sort -
<?php
class mergeSort{
public $arr;
public function __construct($arr){
$this->arr = $arr;
}
public function mSort($l,$r){
if($l===null || $r===null){
return false;
}
if ($l < $r)
{
// Same as ($l+$r)/2, but avoids overflow for large $l and $r
$m = $l+floor(($r-$l)/2);
// Sort first and second halves
$this->mSort($l, $m);
$this->mSort($m+1, $r);
$this->merge($l, $m, $r);
}
}
// Merges two subarrays of $this->arr[]. First subarray is $this->arr[$l..$m]. Second subarray is $this->arr[$m+1..$r]
public function merge($l, $m, $r)
{
if($l===null || $m===null || $r===null){
return false;
}
$n1 = $m - $l + 1;
$n2 = $r - $m;
/* create temp arrays */
$L=array();
$R=array();
/* Copy data to temp arrays $L[] and $R[] */
for ($i = 0; $i < $n1; $i++)
$L[$i] = $this->arr[$l + $i];
for ($j = 0; $j < $n2; $j++)
$R[$j] = $this->arr[$m + 1+ $j];
/* Merge the temp arrays back into $this->arr[$l..$r]*/
$i = 0; // Initial index of first subarray
$j = 0; // Initial index of second subarray
$k = $l; // Initial index of merged subarray
while ($i < $n1 && $j < $n2)
{
if($L[$i] <= $R[$j])
{
$this->arr[$k] = $L[$i];
$i++;
}
else
{
$this->arr[$k] = $R[$j];
$j++;
}
$k++;
}
/* Copy the remaining elements of $L[], if there are any */
while($i < $n1)
{
$this->arr[$k] = $L[$i];
$i++;
$k++;
}
/* Copy the remaining elements of $R[], if there are any */
while($j < $n2)
{
$this->arr[$k] = $R[$j];
$j++;
$k++;
}
}
}
$arr = array(38, 27, 43, 5, 9, 91, 12);
$obj = new mergeSort($arr);
$obj->mSort(0,6);
print_r($obj->arr);
?>
I was looking for a optimized Mergesort algorithm in PHP. There are 5 algorithms in the answers, so I tested those, and mine too. Using PHP 7.2.7, these are the times:
Sorting 1000 random numbers:
Avanche 1 0.0396 seconds
Avanche 2 0.0347 seconds
Kartik 0.0291 seconds
Kripa 0.0282 seconds
Samuel 0.0247 seconds
Mine 0.0144 seconds
Sorting 10 random numbers:
Avanche 1 0.000222 seconds
Kartik 0.000216 seconds
Kripa 0.000159 seconds
Avanche 2 0.000144 seconds
Samuel 0.000128 seconds
Mine 0.000098 seconds
So, although I encourage to whom read it to make it faster (that was I was looking for, and I believe it can be done), I let you my implementation too, cause seems to be faster than the other answers:
//This function needs start and end limits
function mergeSortRec(&$a,$start,$end){
if($start<$end){
$center=($start+$end)>>1; //Binary right shift is like divide by 2
mergeSortRec($a, $start, $center);
mergeSortRec($a, $center+1, $end);
//Mixing the 2 halfs
$aux=array();
$left=$start; $right=$center;
//Main loop
while($left<$center && $right<=$end){
if($a[$left]<$a[$right]){
$aux[]=$a[$left++];
}else{
$aux[]=$a[$right++];
}
}
//Copy the rest of the first half
while($left<$center) $aux[]=$a[$left++];
//Copy the rest of the second half
while($right<=$end) $aux[]=$a[$right++];
//Copy the aux array to the main array
foreach($aux as $v) $a[$start++]=$v;
}
}
//This is the function easier to call
function mergeSort(&$a) {
mergeSortRec($a,0,count($a)-1);
}
If you post a new answer, let me a comment to test it and add it.
Edit: I did some new optimizations, for those looking for a better implementation.
Your merge sort accepts a list by reference
function merge_sort(&$list)
So you need to assign it the new merged and sorted list. So instead of
return merge($left, $right);
do
$list = $this->merge($left, $right);
That should do it, just remove the exit and fix the count variable
MergeSort in PHP
<?php
class Solution
{
function mergeSort(&$arr)
{
if(count($arr) > 1) {
$mid = floor(count($arr)/2);
$left = array_slice($arr, 0, $mid);
$right = array_slice($arr, $mid);
$this->mergeSort($left);
$this->mergeSort($right);
// Merge the results.
$i = $j = $k = 0;
while(($i < count($left)) && ($j < count($right))) {
if($left[$i] < $right[$j]) {
$arr[$k] = $left[$i];
$i++;
} else {
$arr[$k] = $right[$j];
$j++;
}
$k++;
}
while($i < count($left)) {
$arr[$k] = $left[$i];
$i++;
$k++;
}
while($j < count($right)) {
$arr[$k] = $right[$j];
$j++;
$k++;
}
}
}
}
$s = new Solution();
$tmp = [12, 7, 11, 13, 5, 6, 7];
$s->mergeSort($tmp);
print_r($tmp);

Invert function: base 38 conversion

Can you tell me how the invert function for the following PHP function is?
<?php
function id2secure($old_number) {
$alphabet_en = '1357902468acegikmoqsuwybdfhjlnprtvxz-_';
$new_number = '';
while ($old_number > 0) {
$rest = $old_number%38;
if ($rest >= 38) { return FALSE; }
$new_number .= $alphabet_en[$rest];
$old_number = floor($old_number/38);
}
$new_number = strrev($new_number);
return $new_number;
}
echo id2secure(172293);
?>
Thank you very much in advance!
This is secure :) Took me a few minutes to crack it. Here you go,
function secure2id($new_number) {
$alphabet_en = '1357902468acegikmoqsuwybdfhjlnprtvxz';
$old_number = 0;
$new_number = strrev($new_number);
$len=strlen($new_number);
$n=0;
$base=1;
while($n<$len){
$c=$new_number[$n];
$index = strpos($alphabet_en, $c);
if ($index === false)
break;
$old_number += $base * $index;
$base *= 38;
$n++;
}
return $old_number;
}
Haven't tested this code, but it might work:
<?php function secure2id($sr)
{
$s = strrev($sr);
$alpha = '1357902468acegikmoqsuwybdfhjlnprtvxz';
$alpha2num = array();
$n = strlen($alpha);
for($i = 0; $i < $n; $i++)
{
$alpha2num[$alpha[$i]] = $i;
}
$rez = 0;
$n = strlen($s);
$b = 1;
for($i = 0; $i < $n; $i++)
{
$rez += $b * $alpha2num[$s[$i]];
$b *= 38;
}
return $rez;
} ?>
`
Are you asking how to convert base 38 to base 10? The numerical algorithm is this:
Let N be the new number in base 10. Set N to zero to start with.
Let X be the original number in base 38.
Multiply N by 38.
Let D be the most significant (leftmost) digit of X.
Let T be the value of D in base 10.
Add T to N.
Remove D from X (so the number X is now 1 digit shorter).
If X is empty, goto 10.
Goto 3.
Return N, which is now the fully converted base 10 number.
Now that you understand the math, it should be fairly straightforward to convert these steps to a PHP function.

Categories