I'm a beginner in PHP and I was given the assignment to print out the harmonic series. Through my work, you can see that I have printed the correct algorithim for the harmonic series, but I can't seem to find a way to add them all up.
$total = 0;
if ($f1 = "proof") {
$i = $_GET["i"];
for($j= 1;$j<=$i;$j++) {
$total = $total +( 1/$j);
}
echo $total;
Thanks for your time
Thanks! It worked! Here is what I used
$i = 3;
$total = 0;
for($j= 1; $j<=$i ;$j++){
$total += $j/($j + 1);
}
echo $total;
As mentioned in the comments, the bug is here:
if ($f1 = "proof")
The = assigns the value of "proof" to the variable $f1 and doesn't evaluate equality like you want. What you really want is
if ($f1 === "proof")
which does an equality check. == works as well, it just doesn't check that types are the same (so 0=="0" evaluates to true, while 0==="0" would not)
Here is a shorter version:
<?php
$total = 0;
foreach(range(1, 3) as $v)
$total += $v/($v+1);
echo $total;
?>
Output:
1.9166666666667
BTW: In your if statement you make a assignment! You don't compare! you would have to use == OR ===
Related
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;
}
}
?>
I'm trying to determine if three sequential integers exist within an array. I've tested the code on several PHP sandbox sites, but as they don't allow the use of fgets, I've tested with an array that I have pre-filled with the 5 integers. The code works just fine under those circumstances, but fails miserably when run with an array filled by user-input. I'm not sure where the problem is, but any assistance would be greatly appreciated.
<?php
echo "Enter 5 Numbers:";
//{Write your code here
$arr = array();
for($i = 0; $i < 5; $i++){
$arr[$i] = trim(fgets(STDIN));
}
sort($arr);
function FindSeq($arr){
for($i = 0; $i < 3; $i++){
while($i < 3) {
$a = $i;
$b = $a + 1;
$c = $b + 1;
if(((($arr[$a]) + 1) === $arr[$b]) && ((($arr[$b]) + 1) === $arr[$c]) !== FALSE) {
exit("true");
}
else {
$i++;
}
}
}
}
FindSeq($arr);
echo "false";
?>
The lines are read in as strings, however you add + 1 which casts it to an integer. Then you use a strict comparison === with a string. Either use loose comparisons == or cast the values to an integer:
$arr[$i] = (int)trim(fgets(STDIN));
Here's a quick way to do this:
for($i = 2; $i=count($arr)-2; $i++)
if(($arr[$i-1] == $arr[$i]+1) && ($arr[$i+1] == $arr[$i] + 1))
return true;
return false;
The loop numbers account for your use of $arr[1] as the first element of the array. Something prettier would be more general.
I'm trying to make something like this to my variable data value...
$maxvalue = 0;
$basevalue = 0;
if($basevalue == 0) {$maxvalue = 0;}
else if ($basevalue == 1) {$maxvalue = 884;}
else if ($basevalue == 2) {$maxvalue = 1819;}
else if ($basevalue == 3) {$maxvalue = 2839;}
and so on.. i believe there is no exact computation on how the $maxvalue shifts as the basevalue increase. Can someone suggest me a simplier way to do this? thanks in advance!
$maxvalues = array(0, 884, 1819, 2839, ...);
$maxvalue = $maxvalues[$basevalue];
It looks like there's a pattern, almost like a faculty, but also with some other calculations. All numbers are multiples of 17. The following function returns the numbers you provided, so I think it might work for the higher numbers too:
function getMaxValue($base)
{
// Factor of $base = 51 + $base^2 + Factor($base - 1). You
// could solve that in a recursion, but a loop is generally better.
$factor = 0;
for ($i = 1; $i <= $base; $i++)
$factor += 51 + ($i * $i);
return $factor * 17;
}
// Test
for ($i = 0; $i < 100; $i++)
{
echo "$i -- " . getMaxValue($i) . "<br>\n";
}
Here's the solution that prevented me putting all of them in an array..
$maxvalue = 17/6*(2*($basevalue*$basevalue*$basevalue)+3
($basevalue*$basevalue)+307*$basevalue);
Thanks for all the help
Starter with the logic implementation through programming so please find my honest efforts for project Euler Ques, although i tried various attempts to solve but could not get through it :(
Sum I am getting from this is - 257112. I added +2 in the sum to count for a[1] = 2 in the series, but its not working, also I am currently passing a static value 45 for $num but i think it is not the correct way, let me know where I am lagging in logic for the question.
Each new term in the Fibonacci sequence is generated by adding the
previous two terms. By starting with 1 and 2, the first 10 terms will
be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not
exceed four million, find the sum of the even-valued terms.
this is the code I tried -->
$a = array();
$a[0] = 1; $a[1] = 2; $num = 45; $i= 0; $sum = 0; $stop = $num -2;
for($i; $i < $stop ; $i++ ) {
$a[$i+2] = $a[$i+1] + $a[$i];
if( $a[$i+2]%2 == 0 && $a[$i+2] <= 400000 )
{
$sum += $a[$i+2];
}
}
echo "<pre>";
print_r($a);
echo "<br>"."Sum is : ".$sum;
EDIT - It was an error to add an extra zero to make it 4 million, although I am looking something for $num not to be static (as 45 I just mentioned randomly, although its working but its not a clean solution)
Make it simple, no arrays and make it quick. You are only looking for the sum, nothing else:
$a=1;$b=2;$sum=2;
while($b<4000000){
$c=$b+$a;
if($c%2==0)
$sum+=$c;
$a=$b;
$b=$c;
}
echo $sum;
If 4,000,000 counted, then it would be $b<=4000000
<?php
$f0=0;/* declaring variables */
$f1=1;
$f2=0;
$n=0; /* the series range */
while($n<20)
{
$f2=$f0+$f1;
echo $f2."<br>";
$f0=$f1;
$f1=$f2;
$n++;
}
?>
<?php
$f0=0;/* declaring variables */
$f1=1;
$f2=0;
$n=0; /* the series range */
while($n < $stop){
$f2=$f0+$f1;
$temp[] = $f2;
$f0=$f1;
$f1=$f2;
$n++;
}
var_dump($temp);
?>
You can check out same example here
This is pretty simple:
$prev = 0;
$curr = 1;
$next = 1;
for ($i=0; $i <= 10; $i++) {
$prev = $next;
$curr = $i;
$next = $prev + $curr;
echo $next.'<br/>';
}
Try this:
function fibonacci_series($n) {
$f1 = -1;
$f2 = 1;
for ($i = 1; $i <= $n; $i++) {
$f = $f1 + $f2;
$f1 = $f2;
$f2 = $f;
echo "$f<br />";
}
}
echo fibonacci_series(5);
I'm working on another developers old code and there are tons of Notice: Undefined index errors when data is being set using the += operator. Essentially the index is not set yet in the array so the error is generated.
Example:
$myArray = array();
$myValue = 1;
for ($i = 1; $i <= 10; $i++)
{
$myArray['test'] += 1;
}
Will generate an error on the first run since the test index is not set yet.
I know I can remove this error with the following code:
$myArray = array();
$myValue = 1;
for ($i = 1; $i <= 10; $i++)
{
if ( ! isset($myArray['test']) )
{
$myArray['test'] = $myValue;
}
else
{
$myArray['test'] += $myValue;
}
}
However, there are around 50 of things like this to change. Is it worth writing all these isset statements or is there a better way I am not aware of?
EDIT: I should note that the array indexes aren't always the same and sometimes aren't set so I can't preset the index in this circumstance to avoid the error.
This is a bit shorter, but perhaps still a bit complicated if you have many edits.
$myArray = array();
$myValue = 1;
for ($i = 1; $i <= 10; $i++)
{
isset($myArray['test']) ? $myArray['test'] += $myValue : $myArray['test'] = $myValue;
}
You could also write a global function (not tested)..
$myArray = array();
$myValue = 1;
for ($i = 1; $i <= 10; $i++)
{
increment($myArray['test'], $myValue);
}
function increment(&$var, $inc){
$var = isset($var) ? $var += $inc : $var = $inc
}
If you are using PHP 7 and above, you can use the Null Coalescing Operator to make this code cleaner.
$myArray = [];
$myValue = 1;
for ($i = 1; $i <= 10; $i++)
{
$myArray['test'] = $myValue + ($myArray['test'] ?? 0);
}
The benefit here is not only that the code is cleaner, but you're also being more explicit about the default value (0)
Old/Deprecaded/Unrecommended but the shortest solution is
#$myArray['test'] += $myValue;