this is my code:
$arry = (10,20,30,40,50)
function pairwiseDifference($arry, $n)
{
$diff = 0;
for ($i = 0; $i < $n - 1; $i++)
{
// absolute difference between
// consecutive numbers
$diff = abs($arry[$i] - $arry[$i + 1]);
echo $diff." ";
}
}
// Driver Code
$n = sizeof($arry);
echo "<br> Percent of commisions are: "; pairwiseDifference($arry,$n); // this echo 10,10,10,10
So now i wanna make the results of pairwise funcition an array to use in another code, i tried to put:
$arru = pairwiseDifference($arry,$n)[1];
$arru1 = pairwiseDifference($arry,$n)[2];
$arru2 = pairwiseDifference($arry,$n)[3];
$arru3 = pairwiseDifference($arry,$n)[4];
echo $arru;
echo $arru1;
echo $arru2;
echo $arru3;
But are not working.
What im wrong?
Thanks in advance!
An array declaration in PHP needs to either have the array keyword or it can just be declared with square brackets []:
$arry = array(10,20,30,40,50);
or
$arry = [10,20,30,40,50];
You can get the size of an array with the count() method, and there is no need to pass it as a parameter to your function:
function pairwiseDifference($arry)
{
$n = count($arry);
// ...
}
Your function doesn't return anything, so the variables $arru, $arru1, ... won't get anything back from the function and will remain empty. In order to return an array of differences and solve your problem you can do this:
function pairwiseDifference($arry)
{
$n = count($arry) - 1; // you can add the -1 here
$diff = 0;
$result = array();
for ($i = 0; $i < $n; $i++)
{
// absolute difference between
// consecutive numbers
$diff = abs($arry[$i] - $arry[$i + 1]);
echo $diff." ";
array_push($result, $diff); // use array_push() to add new items to an array
}
return $result; // return the result array
}
$arry = array(10,20,30,40,50);
echo "<br> Percent of commisions are: ";
// this echos 10,10,10,10 and assigns whatever your function returns
// to the variable $diffArray
$diffArray = pairwiseDifference($arry);
$arru = $diffArray[0]; // array elements start at index 0
$arru1 = $diffArray[1];
$arru2 = $diffArray[2];
$arru3 = $diffArray[3];
echo $arru; // prints 10
echo $arru1; // prints 10
echo $arru2; // prints 10
echo $arru3; // prints 10
Related
I want to make second array that gives all numbers using rand function that are greater than average number of first array.
I've created new array and I've tried with if statement to display all numbers greater than average number, and to put those values into a new empty array
$arrNums = array();
$arrNewNums = array();
$intSum = 0;
$intTotalNum = 20;
for($i = 0; $i < $intTotalNum; $i++)
{
$intRand = rand(9, 99);
$arrNums[] = $intRand;
$intSum = $intSum + $arrNums[$i];
$averageNum = $intSum / count($arrNums);
foreach($arrNums as $key => $value)
{
if($value > $averageNum)
{
$arrNewNums[] = rand();
}
}
}
echo '<pre>';
print_r($arrNums);
echo "<br>";
echo "Average number from array is " . $averageNum;
echo "<br>";
print_r($arrNewNums);
I would like to get the output of 20 numbers greater than average number, for example 56.4, but instead of that I'm getting 100 numbers and they are all for example 864165243, 738017258 and so on and so on...
This is the correct code for your task:
$arrNums = array();
$arrNewNums = array();
$intSum = 0;
$intTotalNum = 20;
for($i = 0; $i < $intTotalNum; $i++)
{
$intRand = rand(9, 99);
$arrNums[] = $intRand;
$intSum += $intRand;
}
// count average value AFTER you have all items in array
// $averageNum = array_sum($arrNums) / count($arrNums);
// Without `array_sum`:
$averageNum = $intSum / count($arrNums);
// check values of array AFTER you have all items in array
foreach($arrNums as $value) {
if($value > $averageNum) {
// add `$value` to `$arrNewNums`, not some random variable.
$arrNewNums[] = $value;
}
}
echo '<pre>';
print_r($arrNums);
echo "<br>";
echo "Average number from array is " . $averageNum;
echo "<br>";
print_r($arrNewNums);
I need to calculate from a given array the number that is equal or higher and closest to a given number in PHP. Example:
Number to fetch:
6.85505196
Array to calculate:
3.11350000
4.38350000
4.04610000
3.99410000
2.86135817
0.50000000
Only correct combination should be:
3.99410000 + 2.86135817 = 6.85545817
Can somebody help me? It's been 3 hours I'm getting mad!
UPDATE: I finally finished my code as following:
$arr = array(3.1135, 4.3835, 4.0461, 3.9941, 2.86135817, 0.5);
$fetch = 6.85505196;
$bestsum = get_fee($arr, $fetch);
print($bestsum);
function get_fee($arr, $fetch) {
$bestsum = 999999999;
$combo = array();
$result = array();
for ($i = 0; $i<count($arr); $i++) {
combinations($arr, $i+1, $combo);
}
foreach ($combo as $idx => $arr) {
$sum = 0;
foreach ($arr as $value) {
$result[$idx] += $value;
}
if ($result[$idx] >= $fetch && $result[$idx] < $bestsum) $bestsum = $result[$idx];
}
return $bestsum;
}
function combinations($arr, $level, &$combo, $curr = array()) {
for($j = 0; $j < count($arr); $j++) {
$new = array_merge($curr, array($arr[$j]));
if($level == 1) {
sort($new);
if (!in_array($new, $combo)) {
$combo[] = $new;
}
} else {
combinations($arr, $level - 1, $combo, $new);
}
}
}
I hope the following example might help you. Please try this
<?php
$array = array(
"3.11350000",
"4.38350000",
"4.04610000",
"3.99410000",
"2.86135817",
"0.50000000"
);
echo "<pre>";
print_r($array);// it will print your array
for($i=0; $i<count($array); $i++)
{
$j=$i+1;
for($j;$j<count($array); $j++)
{
$sum = $array[$i] + $array[$j];
// echo $array[$i]. " + ".$array[$j]." = ".$sum."<br>"; //this will display all the combination of sum
if($sum >= 6.85505196 && ($sum <= round(6.85505196)) )//change the condition according to your requirement
{
echo "The correct combinations are:<br/><br/>";
echo "<b>". $array[$i]. " + ".$array[$j]." = ".$sum."<b>";
echo "<br/>";
}
}
echo "<br/>";
}
?>
We will get the result as below
Array
(
[0] => 3.11350000
[1] => 4.38350000
[2] => 4.04610000
[3] => 3.99410000
[4] => 2.86135817
[5] => 0.50000000
)
The correct combinations are:
4.04610000 + 2.86135817 = 6.90745817
3.99410000 + 2.86135817 = 6.85545817
You should do it in two steps:
a. Work out (or look up) an algorithm to do the job.
b. Implement it.
You don't say what you've managed in the three hours you worked on this, so here's a "brute force" (read: dumb) algorithm that will do the job:
Use a variable that will keep your best sum so far. It can start out as zero:
$bestsum = 0;
Try all single numbers, then all sums of two numbers, then all sums of three numbers, etc.: Every time you find a number that meets your criteria and is better than the current $bestsum, set $bestsum to it. Also set a second variable, $summands, to an array of the numbers you used to get this result. (Otherwise you won't know how you got the solution). Whenever you find an even better solution, update both variables.
When you've tried every number combination, your two variables contain the best solution. Print them out.
That's all. It's guaranteed to work correctly, since it tries all possibilities. There are all sorts of details to fill in, but you can get to work and ask here for help with specific tasks if you get stuck.
Thank you all for your help!
My code is working pretty cool when is needed to fetch one or two numbers (addition) only. But can't figure out how to add more combinations up to the total count of elements in my given array.
I mean if there are, let's say, 8 numbers in my array I want to try all possible combinations (additions to each other) as well.
My actual code is:
$bestsum = 1000000;
for ($i = 0; $i < count($txinfo["vout"]); $i++) {
if ($txinfo["vout"][$i]["value"] >= $spent && $txinfo["vout"][$i]["value"] < $bestsum) {
$bestsum = $txinfo["vout"][$i]["value"];
}
}
for($i = 0; $i < count($txinfo["vout"]); $i++) {
$j = $i + 1;
for($j; $j < count($txinfo["vout"]); $j++) {
$sum = $txinfo["vout"][$i]["value"] + $txinfo["vout"][$j]["value"];
if($sum >= $spent && $sum < $bestsum) {
$bestsum = $sum;
}
}
}
$fee = bcsub($bestsum, $spent, 8);
print("Fee: ".$fee);
New updated code.
<?php
$x = 6.85505196;
$num = array(3.1135, 4.3835, 4.0461, 3.9941, 2.86135817, 0.5);
asort($num); //sort the array
$low = $num[0]; // lowest value in the array
$maxpossible = $x+$low; // this is the maximum possible answer, as we require the number that is equal or higher and closest to a given number
$num = array_values($num);
$iterations = $x/$num[0]; // possible combinations loop, to equate to the sum of the given number using the lowest number
$sum=$num;
$newsum = $sum;
$k=count($num);
for($j=0; $j<=$iterations; $j++){
$l = count($sum);
for($i=0; $i<$l; $i++){
$genSum = $sum[$j]+$sum[$i];
if($genSum <= $maxpossible){
$newsum[$k] = $genSum;
$k++;
}
}
$newsum = array_unique($newsum);
$newsum = array_values($newsum);
$k = count($newsum);
$sum = $newsum;
}
asort($newsum);
$newsum = array_values($newsum);
for($i=0; $i<count($newsum); $i++){
if($x<=$newsum[$i]){
echo "\nMaximum Possible Number = ".$newsum[$i];
break;
}
}
?>
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";
}
i have starting date ..
i need to add months in starting date inside for loop
for ex -
startingdate = 25-03-2015
and my loop runs two time then it generate like below
25-04-2015
25-05-2015
thats it...
$startingdate = $_POST['startingdate'];
$dates = date("d-m-Y", strtotime($startingdate . " +" . " 1MONTHS -1 DAYS"));
for ($i = 0; $i <= 2; $i++)
{
$coupondate = $dates;
}
If your results are returned with commas separting. Then use explode() to return an array of values. Then using max() and min() in php you can set your lower and upper limits to loop through.
But if you're getting all the results anyway, explode() should do the trick, then just loop through them.
$result = "100,101,102,103";
$arr = explode(",", $result);
foreach ($arr as $number) {
echo $number;
}
Or with min / max:
$result = "100,101,102,103";
$arr = explode(",", $result);
$min = min($arr);
$max = max($arr);
for ($i = $min; $i <= $max; $i++) {
echo $i;
}
Take a look at
min() and
max()
$points=array(500,501,502,503,504,505,506);
$min=min($points);
$max=max($points);
for($i=$min;$i<$max+1;++$i{
//do something
}
If your data is stored lower to upper :
$text = '500,501,502,503,504,505,506';
$explode = explode(',',$text);
$index = count($explode)-1;
for ($i=$explode[0]; $i<=$explode[$index]; $i++)
{
echo $i;
}
If order can change, add :
sort($explode);
Try this :
//after connected with a database
$data = (explode(",", $rows["points"]));
for ($i=min($data); $i<=max($data); $i++)
{
}
Note : If the separation between words is ', ' (a comma and space) then change with this :
$data = (explode(", ", $rows["points"]));
I've recently send my CV to one company that was hiring PHP developers. They send me back a task to solve, to mesure if I'm experienced enough.
The task goes like that:
You have an array with 10k unique elements, sorted descendant. Write function that generates this array and next write three different functions which inserts new element into array, in the way that after insert array still will be sorted descendant. Write some code to measure speed of those functions. You can't use PHP sorting functions.
So I've wrote function to generate array and four functions to insert new element to array.
/********** Generating array (because use of range() was to simple :)): *************/
function generateSortedArray($start = 300000, $elementsNum = 10000, $dev = 30){
$arr = array();
for($i = 1; $i <= $elementsNum; $i++){
$rand = mt_rand(1, $dev);
$start -= $rand;
$arr[] = $start;
}
return $arr;
}
/********************** Four insert functions: **************************/
// for loop, and array copying
function insert1(&$arr, $elem){
if(empty($arr)){
$arr[] = $elem;
return true;
}
$c = count($arr);
$lastIndex = $c - 1;
$tmp = array();
$inserted = false;
for($i = 0; $i < $c; $i++){
if(!$inserted && $arr[$i] <= $elem){
$tmp[] = $elem;
$inserted = true;
}
$tmp[] = $arr[$i];
if($lastIndex == $i && !$inserted) $tmp[] = $elem;
}
$arr = $tmp;
return true;
}
// new element inserted at the end of array
// and moved up until correct place
function insert2(&$arr, $elem){
$c = count($arr);
array_push($arr, $elem);
for($i = $c; $i > 0; $i--){
if($arr[$i - 1] >= $arr[$i]) break;
$tmp = $arr[$i - 1];
$arr[$i - 1] = $arr[$i];
$arr[$i] = $tmp;
}
return true;
}
// binary search for correct place + array_splice() to insert element
function insert3(&$arr, $elem){
$startIndex = 0;
$stopIndex = count($arr) - 1;
$middle = 0;
while($startIndex < $stopIndex){
$middle = ceil(($stopIndex + $startIndex) / 2);
if($elem > $arr[$middle]){
$stopIndex = $middle - 1;
}else if($elem <= $arr[$middle]){
$startIndex = $middle;
}
}
$offset = $elem >= $arr[$startIndex] ? $startIndex : $startIndex + 1;
array_splice($arr, $offset, 0, array($elem));
}
// for loop to find correct place + array_splice() to insert
function insert4(&$arr, $elem){
$c = count($arr);
$inserted = false;
for($i = 0; $i < $c; $i++){
if($elem >= $arr[$i]){
array_splice($arr, $i, 0, array($elem));
$inserted = true;
break;
}
}
if(!$inserted) $arr[] = $elem;
return true;
}
/*********************** Speed tests: *************************/
// check if array is sorted descending
function checkIfArrayCorrect($arr, $expectedCount = null){
$c = count($arr);
if(isset($expectedCount) && $c != $expectedCount) return false;
$correct = true;
for($i = 0; $i < $c - 1; $i++){
if(!isset($arr[$i + 1]) || $arr[$i] < $arr[$i + 1]){
$correct = false;
break;
}
}
return $correct;
}
// claculates microtimetime diff
function timeDiff($startTime){
$diff = microtime(true) - $startTime;
return $diff;
}
// prints formatted execution time info
function showTime($func, $time){
printf("Execution time of %s(): %01.7f s\n", $func, $time);
}
// generated elements num
$elementsNum = 10000;
// generate starting point
$start = 300000;
// generated elements random range 1 - $dev
$dev = 50;
echo "Generating array with descending order, $elementsNum elements, begining from $start\n";
$startTime = microtime(true);
$arr = generateSortedArray($start, $elementsNum, $dev);
showTime('generateSortedArray', timeDiff($startTime));
$step = 2;
echo "Generating second array using range range(), $elementsNum elements, begining from $start, step $step\n";
$startTime = microtime(true);
$arr2 = range($start, $start - $elementsNum * $step, $step);
showTime('range', timeDiff($startTime));
echo "Checking if array is correct\n";
$startTime = microtime(true);
$sorted = checkIfArrayCorrect($arr, $elementsNum);
showTime('checkIfArrayCorrect', timeDiff($startTime));
if(!$sorted) die("Array is not in descending order!\n");
echo "Array OK\n";
$toInsert = array();
// number of elements to insert from every range
$randElementNum = 20;
// some ranges of elements to insert near begining, middle and end of generated array
// start value => end value
$ranges = array(
300000 => 280000,
160000 => 140000,
30000 => 0,
);
foreach($ranges as $from => $to){
$values = array();
echo "Generating $randElementNum random elements from range [$from - $to] to insert\n";
while(count($values) < $randElementNum){
$values[mt_rand($from, $to)] = 1;
}
$toInsert = array_merge($toInsert, array_keys($values));
}
// some elements to insert on begining and end of array
array_push($toInsert, 310000);
array_push($toInsert, -1000);
echo "Generated elements: \n";
for($i = 0; $i < count($toInsert); $i++){
if($i > 0 && $i % 5 == 0) echo "\n";
printf("%8d, ", $toInsert[$i]);
if($i == count($toInsert) - 1) echo "\n";
}
// functions to test
$toTest = array('insert1' => null, 'insert2' => null, 'insert3' => null, 'insert4' => null);
foreach($toTest as $func => &$time){
echo "\n\n================== Testing speed of $func() ======================\n\n";
$tmpArr = $arr;
$startTime = microtime(true);
for($i = 0; $i < count($toInsert); $i++){
$func($tmpArr, $toInsert[$i]);
}
$time = timeDiff($startTime, 'checkIfArraySorted');
showTime($func, $time);
echo "Checking if after using $func() array is still correct: \n";
if(!checkIfArrayCorrect($tmpArr, count($arr) + count($toInsert))){
echo "Array INCORRECT!\n\n";
}else{
echo "Array OK!\n\n";
}
echo "Few elements from begining of array:\n";
print_r(array_slice($tmpArr, 0, 5));
echo "Few elements from end of array:\n";
print_r(array_slice($tmpArr, -5));
//echo "\n================== Finished testing $func() ======================\n\n";
}
echo "\n\n================== Functions time summary ======================\n\n";
print_r($toTest);
Results can be found here: http://ideone.com/1xQ3T
Unfortunately I was rated only 13 points out of 30 for this task (don't know how it was calculated or what exactly was taken in account). I can only assume that's because there are better ways to insert new element into sorted array in PHP. I'm searching this topic for some time now but couldn't find anything good. Maby you know of better approach or some articles about that topic?
Btw on my localhost (PHP 5.3.6-13ubuntu3.6 with Suhosin-Patch, AMD Athlon(tm) II X4 620) insert2() is fastest, but on ideone (PHP 5.2.11) insert3() is fastest.
Any ideas why? I suppose that array_splice() is tuned up somehow :).
//EDIT
Yesterday I thought about it again, and figured out the better way to do inserts. If you only need sorted structure and a way to iterate over it and your primary concern is the speed of insert operation, than the best choise would be using SplMaxHeap class. In SplMaxHeap class inserts are damn fast :) I've modified my script to show how fast inserts are. Code is here: http://ideone.com/vfX98 (ideone has php 5.2 so there won't be SplMaxHeap class)
On my localhost I get results like that:
================== Functions time summary ======================
insert1() => 0.5983521938
insert2() => 0.2605950832
insert3() => 0.3288729191
insert4() => 0.3288729191
SplMaxHeap::insert() => 0.0000801086
It may just be me, but maybe they were looking for readability and maintainability as well?
I mean, you're naming your variables $arr, and $c and $middle, without even bothering to place proper documentation.
Example:
/**
* generateSortedArray() Function to generate a descending sorted array
*
* #param int $start Beginning with this number
* #param int $elementsNum Number of elements in array
* #param int $dev Maximum difference between elements
* #return array Sorted descending array.
*/
function generateSortedArray($start = 300000, $elementsNum = 10000, $dev = 30) {
$arr = array(); #Variable definition
for ($i = 1; $i <= $elementsNum; $i++) {
$rand = mt_rand(1, $dev); #Generate a random number
$start -= $rand; #Substract from initial value
$arr[] = $start; #Push to array
}
return $arr;
}