algorithm - PHP beginner palindrome script -
algorithm - PHP beginner palindrome script -
i working on (for fun) writing script recognize palindromes. far, i'm successful "kayak", "racecar", "anna", "a man plan canal panama": yet variations on latter phrase such "amanaplana canalpan ama" gives me problems.
as side note: understand using pcre create things lot easier me, i'm not fluent in , 1 of major aims understand algorithm behind checking palindromes.
<?php $word = "amanaplana canalpan ama"; $space = " "; $word_smallcase = strtolower($word); $word_array = str_split($word_smallcase); if(in_array($space, $word_array)){ for($m = 0; $m<count($word_array); $m = $m + 1){ if($word_array[$m] == $space) unset($word_array[$m]); } } $count = 0; $scan_count = -1; for($i = 0; $i < (count($word_array)/2); $i = $i + 1){ for($j = count($word_array); $j > (count($word_array)/2); $j = $j - 1){ if($word_array[$i]==$word_array[$j]){ $count = $count + 1; break; } } $scan_count = $scan_count + 1; } if ($count == $scan_count){ echo $word." palindrome"; } else{ echo $word ." not palindrome"; } ?>
i'd appreciate response regarding:
the identification of bug i'm having. recommendations how perchance improve code (i'd happy if create things work without resorting $count or $scan_count seem, eye, relatively amateurish).thanks in advance.
there's few things going on here...
first, i'm not sure if you're aware unset
'ing array doesn't remove indices:
$array = array(0, 1, 2, 3); unset($array[2]); var_dump($array); /* array(3) { [0]=> int(0) [1]=> int(1) [3]=> int(3) } */
so you're going have undefined offsets when iterate on elements in array. go 1 one, should utilize foreach
loop control.
another issue lies in nested loop here:
for($i = 0; $i < (count($word_array)/2); $i = $i + 1){ for($j = count($word_array); $j > (count($word_array)/2); $j = $j - 1){
given "amanaplanacanalpanama", @ you're doing:
comparing, step step (btw, you're off 1 on initializer $j... $word_array[count($word_array)]
pointing @ 'm' in panama, not 'a'.):
a eq a? j 22 0 scan_count: -1 count: 1 m eq a? j 22 1 m eq m? j 21 1 scan_count: 0 count: 2 eq a? j 22 2 scan_count: 1 count: 3
a eq a
fine, , matches... m found on next iteration, when next 'a', you're finding original 'a' @ end of panama...
as side note, since starting on end every time, horribly inefficient o(n^2)
given sufficiently big string...
obligatory solution:
$word = "amanaplana canalpan ama"; $j = strlen ($word)-1; $pal = true; ($i = 0; $i < strlen($word)/2; ++$i, --$j) { // skip spaces while ($word[$i] === " ") {$i++;} while ($word[$j] === " ") {$j--;} echo "$word[$i] eq $word[$j]?\n"; if ($word[$i] !== $word[$j]) { $pal = false; break; } } if ($pal) print "yes"; else print "no";
php algorithm palindrome
Comments
Post a Comment