i have this function sort_by_time, the purpose of this function is to swap the time1 if the time2 is greater than time1 but my problem is im having an error of Undefined offset: 0. Sometimes the error is Undefined offset: 1. or Undefined offset: 2. Can someone help me to prevent this error in my code? I'm thinking this in these last 3 days but i can't think of any solution on this.
in this line the error occur.
if (Payroll2::convert_time_in_minutes($_time[$j]->time_in) > Payroll2::convert_time_in_minutes($_time[$j+1]->time_in))
This error occurs because the $_time[0] is not set.
Sample time. This is dynamic not only limited to 3 sometimes it's 4, sometimes it's 5 or 1.
1 => {#6356}
2 => {#6352}
3 => {#6257}
Here's my full function code
public static function sort_by_time($_time)
{
$count = 0;
$n = count($_time);
for ($i = 0; $i < $n-1; $i++)
{
for ($j = 0; $j < $n-$i-1; $j++)
{
if (Payroll2::convert_time_in_minutes($_time[$j]->time_in) > Payroll2::convert_time_in_minutes($_time[$j+1]->time_in))
{
// swap temp and arr[i]
$temp = $_time[$j];
$_time[$j] = $_time[$j+1];
$_time[$j+1] = $temp;
}
}
}
return $_time;
}
Try this:
public static function sort_by_time($_time)
{
usort($_time,function($ad,$bd)
{
$ad = Payroll2::convert_time_in_minutes($ad->time_in);
$bd = Payroll2::convert_time_in_minutes($bd->time_in);
if ($ad == $bd) {
return 0;
}
return $ad < $bd ? -1 : 1;
});
return $_time;
}
if it doesn't work the problem can be in function Payroll2::convert_time_in_minutes
Related
This question already has answers here:
"Fatal error: Cannot redeclare <function>"
(18 answers)
Closed 2 years ago.
I have a nested recursive function it's a task from codewars.
persistence(39) === 3; // because 3 * 9 = 27, 2 * 7 = 14, 1 * 4 = 4
and 4 has only one digit persistence(999) === 4; // because 9 * 9 * 9
= 729, 7 * 2 * 9 = 126, 1 * 2 * 6 = 12, and finally 1 * 2 = 2;
persistence(4) === 0; // because 4 is already a one-digit number
which throws :
Fatal error: Cannot redeclare rec();
function persistence(int $num): int {
$str = (string)$num;
$nums = str_split($str);
$count = count($nums);
if( $count === 0 ){
return 0;
}
$x = 0;
function rec($nums, $n) {
$result = [];
for ($i = 0; $i < count($nums); ++$i) {
if ($i == 0) {
$result = $nums[$i];
} else {
$result *= $nums[$i];
}
}
$num = implode('',$nums);
$diff = $num - $result;
if ( $diff != 0 ) {
$n += 1;
$result = str_split($result,1);
return rec($result, $n);
}
return $n;
}
$result = rec($nums,$x);
return (int)$result;
}
I've tried to use an variable function
$rec = 'rec';
$result = $rec($nums,$n)
but there are another error : `
Fatal error: Cannot redeclare rec()
`
PHP 7.4 version. Can anyone explain me what the problem is ?
Don't define the function inside the other function:
You have:
function persistence(int $num): int {
// code ...
function rec($nums, $n) {
// code ...
}
}
This means that the function rec should be created each time the function persistence gets called.
You should define them first:
function persistence(int $num): int {
// code ...
}
function rec($nums, $n) {
// code ...
}
And then call them to your liking, for example like you already do:
$rec = 'rec';
$result = $rec($nums,$n)
I challenged myself to improve my skills by doing some individual projects and for now I am stuck with the 2048.
I have the text file which stores the present values of the game.
128 64 32 16 32 8 8 8 16 4 4 4 8 2 2 2
<?php
$logs = file("logs-2048.txt");
if ($_SERVER["REQUEST_METHOD"] == "POST") {
file_put_contents('logs-2048.txt', '');
$tableValues = [];
$arrayLine = explode(" ", $logs[0]);
for($g=0; $g<4; $g++) {
$newLine = [];
for($h=0; $h<4; $h++) {
array_push($newLine, htmlspecialchars($arrayLine[$g*4+$h]));
}
array_push($tableValues, $newLine);
}
$direction = $_POST["action-joueur"];
$string = "";
if($direction == "^") {
for($g = 0; $g < 3; $g++) {
for ($h = 0; $h < 4; $h++) {
for ($i = 0; $i < 3; $i++) {
if ($tableValues[$i][$h] == $tableValues[$i+1][$h] || $tableValues[$i][$h] == 0) {
$tableValues[$i][$h] += $tableValues[$i+1][$h];
$tableValues[$i+1][$h] = 0;
}
}
}
}
} else if ($direction == "v") {
//Almost simillar stuff as for ^
} else if ($direction == "<") {
//Almost similar stuff as for ^
} else if ($direction == ">") {
//Almost similar stuff as for ^
}
$arrayEmpty = [];
for($g = 0; $g < 4; $g++) {
for($h = 0; $h < 4; $h++) {
if($tableValues[$g][$h] == 0) {
array_push($arrayEmpty, [$g, $h]);
}
}
}
$findRand = mt_rand(0, count($arrayEmpty)-1);
$tableValues[$arrayEmpty[$findRand][0]][$arrayEmpty[$findRand][1]] = 2;
for($g = 0; $g < 4; $g++) {
for ($h = 0; $h < 4; $h++) {
$string = $string.$tableValues[$g][$h]." ";
}
}
file_put_contents("logs-2048.txt", $string);
}
?>
The first loop is to parse the array that I take from the file, and convert it to a 2 dimensional array(table).
The problem is in the next 4 nested loops which does the summing, I can't figure how can I do other way then just use another loop(first one for each nested loop) which goes 3 times back if some numbers were stuck somewhere adding themselves (EX. 2 2 2 2 in first column => 4 2 2 0 => 4 4 0 0 => 8 0 0 0).
I am 100% sure that the algorithms for summing is terribly inefficient, but I can't figure out what solution I can provide to make it faster and more intuitive, then have 4 for's... I tried also to look at different resources on internet but it's pretty messed up for me because I am starting with php.
Yes, I know that php isn't the best way to do, I'll do myself with
Javascript, but I need it for learning, any ideas or tips to improve the algorithm will be greatly appreciated.
Hello I have this code which selects from a list of 20 items 12 and from those 12 1 is randomly selected and echoed:
class Gamble
{
public static function doPointsCheck()
{
global $Gamble;
$Gamble_points = '2';
if($Gamble_points <= 1)
return false;
else
return true;
}
public static function Spin()
{
global $Wheel;
if(!self::doPointsCheck())
return 'You need way too more points to gamble';
else
{
$Result = array();
$Result = range(1, 12);
shuffle($Result);
$Result = array_slice($Result, 0, 20);
$SendToCheck = self::CheckPrize($Result);
}
}
public static function CheckPrize($Array)
{
global $Wheel;
echo '<h1>List of items you can win today:</h1><form action="class.MysticWheel.php" method="post">';
for($i = 1; $i <= count($Array); $i++)
{
$Won = '<p>'.$Wheel[$Array[$i]]['pseudo'].'</p>';
echo $Won;
}
echo '<input name="Feeling lucky" type="submit" value="Feeling Lucky" /></form>';
if ($_SERVER['REQUEST_METHOD'] === 'POST'){
$i = rand( 1, 12 );
$Prize = '<p>'.$Wheel[$Array[$i]]['pseudo'].'</p>';
echo $Prize;
}
}
}
When I test it I recieve the following error:
Notice: Undefined offset: 12 on line 54
Notice: Undefined index: on line 54
So i won't show the last item, it will only show 11 possible items that could have been won and get the notice.
How can I fix it?
$Result = range(1, 12);
-->
foreach (range(1, 12) as $number) {
$Result[] = $number;
}
Try this.
I've got an excel file like this: Excel example
I want to read the columns F, G ,H ,J when I do:
for ($i = 3; $i <= $data->sheets[0]['numRows']; $i++) {
error_log(
FW_Class_Voucher_Code::cleanCode($data->sheets[0]['cells'][$i][6]).' - '.
FW_Class_Voucher_Code::cleanCode($data->sheets[0]['cells'][$i][7]).' - '.
FW_Class_Voucher_Code::cleanCode($data->sheets[0]['cells'][$i][8]).' - '.
FW_Class_Voucher_Code::cleanCode($data->sheets[0]['cells'][$i][9]));
$count++;
}
I have the problem that I get errors:
PHP Notice: Undefined offset: 7 PHP Notice: Undefined offset: 8
PHP Notice: Undefined offset: 9
the F column is always full, but as you can see I've got problems with the others. How can I escape this error, so the field only gets checked if it's filled with data?
for ($i = 3; $i <= $data->sheets[0]['numRows']; $i++) {
$err=array;
for($j=6; $j<=9; $j++){
if(isset(FW_Class_Voucher_Code::cleanCode($data->sheets[0]['cells'][$i][$j])))
$err[]=FW_Class_Voucher_Code::cleanCode($data->sheets[0]['cells'][$i][$j]) ;
}
if(!empty($err){
$msg=implode('-',$err);
error_log($msg);
}
$count++; //I don't know what you're using $count for
}
if (isset($data->sheets[0]['cells'][$i][7])) {
$col7 = $data->sheets[0]['cells'][$i][7];
} else {
$col7 = '';
}
if (isset($data->sheets[0]['cells'][$i][8])) {
$col8 = $data->sheets[0]['cells'][$i][8];
} else {
$col8 = '';
}
if (isset($data->sheets[0]['cells'][$i][9])) {
$col9 = $data->sheets[0]['cells'][$i][9];
} else {
$col9 = '';
}
looks realy ugly but it works.
I got the answer fine, but when I run the following code,
$total = 0;
$x = 0;
for ($i = 1;; $i++)
{
$x = fib($i);
if ($x >= 4000000)
break;
else if ($x % 2 == 0)
$total += $x;
print("fib($i) = ");
print($x);
print(", total = $total");
}
function fib($n)
{
if ($n == 0)
return 0;
else if ($n == 1)
return 1;
else
return fib($n-1) + fib($n-2);
}
I get the warning that I have exceeded the maximum execution time of 30 seconds. Could you give me some pointers on how to improve this algorithm, or pointers on the code itself? The problem is presented here, by the way.
Let's say $i equal to 13. Then $x = fib(13)
Now in the next iteration, $i is equal to 14, and $x = fib(14)
Now, in the next iteration, $i = 15, so we must calculate $x. And $x must be equal to fib(15). Now, wat would be the cheapest way to calculate $x?
(I'm trying not to give the answer away, since that would ruin the puzzle)
Try this, add caching in fib
<?
$total = 0;
$x = 0;
for ($i = 1;; $i++) {
$x = fib($i);
if ($x >= 4000000) break;
else if ($x % 2 == 0) $total += $x;
print("fib($i) = ");
print($x);
print(", total = $total\n");
}
function fib($n) {
static $cache = array();
if (isset($cache[$n])) return $cache[$n];
if ($n == 0) return 0;
else if ($n == 1) return 1;
else {
$ret = fib($n-1) + fib($n-2);
$cache[$n] = $ret;
return $ret;
}
}
Time:
real 0m0.049s
user 0m0.027s
sys 0m0.013s
You'd be better served storing the running total and printing it at the end of your algorithm.
You could also streamline your fib($n) function like this:
function fib($n)
{
if($n>1)
return fib($n-1) + fib($n-2);
else
return 0;
}
That would reduce the number of conditions you'd need to go through considerably.
** Edited now that I re-read the question **
If you really want to print as you go, use the output buffer. at the start use:
ob_start();
and after all execution, use
ob_flush();
flush();
also you can increase your timeout with
set_time_limit(300); //the value is seconds... so this is 5 minutes.