How to output the arguments of a Function in the Function itself - php
<?php
$l = 4000;
function flip($h, $t)
{
if ($h + $t <= 29) {
$a = mt_rand(0, 1);
if ($a == 1) {
flip($h + 1, $t);
} else {
flip($h, $t + 1);
}
} else {
echo "$h,$t" . "</br>";
}
}
$ar = array( "test");
for ($i = 0; $i <= $l; $i++) {
array_push($ar, flip(0, 0));
}
?>
My code is supposed to give the number of tails and heads upon spinnings 30 times. And this process is done 4000 times. I want to store all the results of the 4000 times in an array using the above code. But I think the way I defined by flip is wrong. I didn't know how to store the value of the arguments of flip after it is done therefore I used an echo.
When i run this code.. for some reason it is printing out all the answers like this : http://searchr.us/testing/ip.php instead of just making an array. I have pin pointed that the way I took the vfilanl values of flip wrong. Can someone tell me the difference between echo , print and how DO i use return. When i just use return(); after echo.It gives me an error.
Please clarify my doubt on how I can output these values.
You should use something like this:
<?php
function flip($h, $t)
{
if ($h + $t > 29) return $h . ',' . $t;
$a = mt_rand(0, 1);
return $a == 1 ? flip($h + 1, $t) : flip($h, $t + 1);
}
$ar = array( "test");
$l = 4000;
for ($i = 0; $i <= $l; ++$i) {
array_push($ar, flip(0, 0));
}
?>
Note that echo outputs to the client.
But you want to decide what you get when you call flip, and that is done using return.
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); }
Looking for opposite of pow() in PHP
I am working on mathematical problem where the formula is: A[i] * (-2) power of i where i=0,1,2,3,... A is an array having values 0 or 1 Input array: [0,1,1,0,0,1,0,1,1,1,0,1,0,1,1] Output is: 5730 Code $totalA = 0; foreach ($A as $i => $a) { $totalA += $a * pow(-2, $i); } This is correct. Now I am looking for its opposite like: Input is: 5730 Output will be: [0,1,1,0,0,1,0,1,1,1,0,1,0,1,1] I am not asking for the exact code but looking for some logic from where I should start. I tried to use log() method but that did not return the desired output.
You were not looking for exact code, but I found this problem too interesting. This works: function sign($n) { return ($n > 0) - ($n < 0); } $target = -2396; $i = 0; $currentSum = 0; // Look for max $i while (true) { $val = pow(-2, $i); $candidate = $currentSum + $val; if (abs($target) <= abs($candidate)) { // Found max $i break; } if (abs($target - $candidate) < abs($target - $currentSum)) { // We are getting closer $currentSum = $candidate; } $i++; } $result = []; for ($j = $i; 0 <= $j; $j--) { $val = pow(-2, $j); $border = $val / 4; if (sign($val) == sign($target) && abs($border) < abs($target)) { array_unshift($result, 1); $target -= $val; } else { array_unshift($result, 0); } } echo json_encode($result); First I look for the $i that gets me on or slightly above the $target. When found, I walk down and decide for each bit if it should be in the result.
Working with giant numbers in PHP
Morning Guys. I'm looking for a way/extension, so that I can calculate FAST with really big numbers in PHP, e.g. multiplication with 50-digit numbers. And please don't tell me, I shall use BC Math or GMP. They were my second idea, but both are so useless, when the result has more than 38 digits both just returning "false". I allready tried writing an own calculation function, which is actually working, but I believe it's a bit to slow. It's saving every digit of a number in an array, and calcs like I learned it in Elementary school. it's working perfect only when the incoming numbers are arrays too. cause elseway the computer will break them before he can save them. Is there a way to make my function a bit faster, or does there exist a lib which really calcs with bignumbers? function multiplicate($A, $B) { if (!is_array($A)) { $A = preg_split("//", strval($A), -1, PREG_SPLIT_NO_EMPTY); } if (!is_array($B)) { $B = preg_split("//", strval($B), -1, PREG_SPLIT_NO_EMPTY); } if ( $A[0]=='-') { array_splice($A, 0, 1); $negA=-1; } else { $negA=1; }; if ( $B[0]=='-') { array_splice($B, 0, 1); $negB=-1; } else { $negB=1; }; $l = 0; $m = 0; $Erg[0] = 0; for ( $i=0; $i < count($A); $i++) { for ( $j=0; $j < count($B); $j++) { $ZwErg = preg_split("//", strval($A[$i]*$B[$j]), -1, PREG_SPLIT_NO_EMPTY); if ($i==0&&$j==0&&count($ZwErg)==2) { $l = 1; } if (count($ZwErg)==2) { $m = -1; } for ( $k=0; $k < count($ZwErg); $k++) { $s = $i + $j + $l + $m + 1; if (isset($Erg[$s])) { $Erg[$s] = intval($Erg[$s]) + intval($ZwErg[$k]); for ( $n=$s; $n >= 0; $n--) { if (intval($Erg[$n])>9) { $Erg[$n-1] = intval($Erg[$n-1]) + 1 ; $Erg[$n] = intval($Erg[$n] - 10); } }; } else { $Erg[$s] = $ZwErg[$k]; } $m = 0; } } } if ($Erg[0]==0) { array_splice($Erg,0,1); } if ($negA*$negB==-1) { array_splice($Erg,0,0,"-"); } //$Erg = implode("", $Erg); return $Erg; } . $time_start = microtime(true); require'mathlab.php'; $a=array(1,2,3,4,3,1,0,9,5,8,7,6,4,2,5,6,1,2,3,9,5,2,6,7,9,0,4,6,3,9,5,2,6,7,9,0,4,6,7,1,2,3,4,3,1,0,9,5,8,7,6,4,2,5,6,7,8,9,0,3,8,1,5,2,8,1,4,0,7,1,2,3,4,3,1,0,9,5,8,7,6,4,2,5,6,7,8,9,0,3,8,1,5,2,8,1,4,0,3,4,3,1,0,9,5,8,7,6,4,2,5,6,7,8,9,0,7,8,9,0); // 100-digits $b=array(3,9,5,2,6,7,9,0,4,6,7,1,2,3,4,3,1,0,9,5,8,7,3,9,5,2,6,7,9,3,9,5,2,6,7,9,0,4,6,7,1,2,3,4,3,1,0,9,5,8,7,6,4,2,5,6,7,8,9,0,3,8,1,5,2,8,1,4,0,0,4,6,7,1,2,3,4,3,1,0,9,5,8,7,6,4,2,5,6,7,8,9,0,3,8,1,5,2,8,1,4,0,6,4,2,5,6,7,8,9,0,3,8,1,5,2,8,1,4,0); // 100-digits $a2=123431095876425612395267904639526790467123431095876425678903815281407123431095876425678903815281403431095876425678907890; $b2=395267904671234310958739526793952679046712343109587642567890381528140046712343109587642567890381528140642567890381528140; $d=multiplicate($a, $b); $time_end = microtime(true); $time = $time_end - $time_start; $erg= implode("", $d); echo $erg; // returns 48788350638348981414888625840026024706504222587793349182466850334644805413224925671434030836485835140547446449665876539897036829747577622276768694829991017552834308659985345098432904112370002027411248553582029194707890154740774064503024600 echo $time; // returns 0.75173783302307 $erg3=bcmul($a2, $b2); $erg4=bcmul(123431095876425612395267904639526790467123431095876425678903815281407123431095876425678903815281403431095876425678907890, 395267904671234310958739526793952679046712343109587642567890381528140046712343109587642567890381528140642567890381528140); $erg2=gmp_mul($a2, $b2); $erg5=gmp_mul(123431095876425612395267904639526790467123431095876425678903815281407123431095876425678903815281403431095876425678907890, 395267904671234310958739526793952679046712343109587642567890381528140046712343109587642567890381528140642567890381528140); echo gmp_strval($erg2); // returns 0 echo gmp_strval($erg5); // returns 0 echo $erg3; // returns 0 echo $erg4; // returns 0
Use bcmath or GMP. For example, echo bcmul("123431095876425612395267904639526790467123431095876425678903815281407123431095876425678903815281403431095876425678907890", "395267904671234310958739526793952679046712343109587642567890381528140046712343109587642567890381528140642567890381528140"); Gives the output: 48788350638348981414888625840026024706504222587793349182466850334644805413224925671434030836485835140547446449665876539897036829747577622276768694829991017552834308659985345098432904112370002027411248553582029194707890154740774064503024600
php - shifting variable value by if else simplification
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
Fixtures PHP algorithm
Struggling with this tournament fixtures algorithm. The code is working perfectly but I need help inserting the data to mysql I cant seem to access the $varables.. any tweaking by a php pro greatly appreciated ... $teamnames = "Arsenal|Tottenham|Leeds|Man United|Liverpool"; # XXX check for int print show_fixtures(isset($_GET['teams']) ? nums(intval($_GET['teams'])) : explode("|", trim($teamnames))); function nums($n) { $ns = array(); for ($i = 1; $i <= $n; $i++) { $ns[] = $i; } return $ns; } function show_fixtures($names) { $teams = sizeof($names); print "<p>Fixtures for $teams teams.</p>"; // If odd number of teams add a "ghost". $ghost = false; if ($teams % 2 == 1) { $teams++; $ghost = true; } // Generate the fixtures using the cyclic algorithm. $totalRounds = $teams - 1; $matchesPerRound = $teams / 2; $rounds = array(); for ($i = 0; $i < $totalRounds; $i++) { $rounds[$i] = array(); } for ($round = 0; $round < $totalRounds; $round++) { for ($match = 0; $match < $matchesPerRound; $match++) { $home = ($round + $match) % ($teams - 1); $away = ($teams - 1 - $match + $round) % ($teams - 1); // Last team stays in the same place while the others // rotate around it. if ($match == 0) { $away = $teams - 1; } $rounds[$round][$match] = team_name($home + 1, $names) . " v " . team_name($away + 1, $names); } } // Interleave so that home and away games are fairly evenly dispersed. $interleaved = array(); for ($i = 0; $i < $totalRounds; $i++) { $interleaved[$i] = array(); } $evn = 0; $odd = ($teams / 2); for ($i = 0; $i < sizeof($rounds); $i++) { if ($i % 2 == 0) { $interleaved[$i] = $rounds[$evn++]; } else { $interleaved[$i] = $rounds[$odd++]; } } $rounds = $interleaved; // Last team can't be away for every game so flip them // to home on odd rounds. for ($round = 0; $round < sizeof($rounds); $round++) { if ($round % 2 == 1) { $rounds[$round][0] = flip($rounds[$round][0]); } } // Display the fixtures for ($i = 0; $i < sizeof($rounds); $i++) { print "<hr><p>Round " . ($i + 1) . "</p>\n"; foreach ($rounds[$i] as $r) { print $r . "<br />"; } print "<br />"; } print "<hr>Second half is mirror of first half"; $round_counter = sizeof($rounds) + 1; for ($i = sizeof($rounds) - 1; $i >= 0; $i--) { print "<hr><p>Round " . $round_counter . "</p>\n"; $round_counter += 1; foreach ($rounds[$i] as $r) { print flip($r) . "<br />"; } print "<br />"; } print "<br />"; if ($ghost) { print "Matches against team " . $teams . " are byes."; } } function flip($match) { $components = split(' v ', $match); return "$components[1]" . " v " . "$components[0]"; } function team_name($num, $names) { $i = $num - 1; if (sizeof($names) > $i && strlen(trim($names[$i])) > 0) { return trim($names[$i]); } else { return "BYE"; } }
I'm not entirely sure what you're hung up on (you should really be more specific in your questions, as specified by the FAQ), but I suspect it is a matter of scope. When you set a variable within a function, that variable is only accessible within that function. For example: function do_something() { $a = 'something!'; } do_something(); echo $a; This should result in PHP notice telling you that PHP doesn't know what $a is in the scope that it is trying to echo. Now, if I modify this script... $a = ''; function do_something() { global $a; // Lets PHP know we want to use $a from the global scope $a = 'something!'; } do_something(); echo $a; This will work and output "something!", because $a is being "defined" in the scope outside of the function. You can read more about variable scope in the PHP documentation: http://php.net/manual/en/language.variables.scope.php Now, something else you need to pay attention to is outputting user data. In your script, you take data straight from $_GET and print it out to the page. Why is this bad? Someone could inject some nice JavaScript into your page (or anything they wanted) and steal users' sessions. You should be using htmlspecialchars() any time you need to output a variable. Even if it is just a team name, you never know when some team will stick a ; or < or > or some other reserved character in there. Finally, I strongly recommend not mixing your logic with your computation. Let your program figure everything out, and then loop through the data for your output. You should be able to save the entire data for this type of problem in a nice associative array, or some crafty object you come up with.