for my school project, i need to write an algorithm which is gonna check if both halfs of array are palindromes, and if array has odd values, i should skip one in the middle. For example:
[1,2,1,6,4,2,5] should check if [1,2,1] is palindrome, and if [4,2,5] is palindrome, skipping the middle value cause its odd.
This is what i've wrote so far:
$somearray = ['1','1','1','1','1','2','1','1','2','1','1'];
$array_size = count($tablica);
function check_palindrome($arr, $start, $end)
{
for($i=$start; $i < $end; $i++){
if($arr[$i] != $arr[$start+$end-$i])
{
return false;
}
}
return true;
}
if($array_size%2 == 0){
$start1 = 0;
$start2 = $array_size/2;
$end1 = $array_size/2 - 1;
$end2 = $array_size - 1;
} else {
$start1 = 0;
$start2 = round($array_size/2);
$end1 = round($array_size/2, 0, PHP_ROUND_HALF_DOWN)-1;
$end2 = $array_size -1;
}
$foo1 = check_palindrome($somearray, $start1, $end1);
$foo2 = check_palindrome($somearray, $start2, $end2);
if($foo1 && $foo2){
echo 'Halfs are palindromes';
} else {
echo 'Halfs are not palindromes';
}
And it works, but first most important part - my algorithm checks if first half is palindrome, then calling function twice i check second half - my teacher doesn't like that and tells me i should write it in one function, but i really don't have an idea how.
My second problem is how to improve my for loop, because for now it check half like this:
A=[1,2,4,2,1]
1=1, 2=2, 2=2, 1=1 if its true, but it should stop after checking 1=1 and 2=2
it's happening because of this statement in for loop: $i < $end but also don't know how to improve it :/
I really need your help. Thanks.