Missing Array Value

Sunday, July 6, 2014

I have this code in php (BFS-based algorithm).. JARAK means DISTANCE (level of node).



$vsourceuser = 'A';

if(!empty($vsourceuser)) {
$queue = array();
$visited_node = array();
$jarak = array();

$queue[0] = $vsourceuser;
$index_vn = 0;
$visited_node[0] = $vsourceuser;
$jarak[0] = 0;
$level = 0;
$max_jarak = 0;
$arrneighbor[] = array();

while(!empty($queue)) {
$level=$level+1;
$m = count($queue);
$j=0;
if($j<$m) {
$fnode=reset($queue);
//$fnode = current($queue);
$rsrow = mysql_query("select * from matrik_trust WHERE row='$fnode' AND connect=1") or die(mysql_error());
$n = mysql_num_rows($rsrow);
if($n>0) { //is there neighbor?
while($row = mysql_fetch_array($rsrow)) {
$arrneighbor[] = $row;
}
array_shift($arrneighbor);
reset($arrneighbor);
for($i=0;$i<$n;$i++) { //15
$neighbor = $arrneighbor[$i]['column'];

array_push($queue,$neighbor); //16
if(in_array(end($queue),$visited_node)) { //17 18
array_pop($queue); //19
} else { //20
$index_vn = $index_vn+1;
$visited_node[$index_vn]=end($queue);
$jarak[$index_vn]=$level;
}
}
reset($queue);
array_shift($queue); //24
} else { //theres no neighbor 25
reset($queue);
array_shift($queue); // 26
}
$j=$j+1;
}
}

if(empty($queue)) {
$max_jarak = $level-1;
if($max_jarak==0) {
echo "Node tidak memiliki neighbor.";
} else {
echo '<br>max jarak :'.$max_jarak.'<br><br>';
echo '<br>visited node :<br>'.print_r($visited_node);
echo '<br>distance :'.print_r($jarak);
}
}
} else {
echo "Must fill the source.";
} ?>


with data access in below..



----------------------------
id | row | column | connect|
----------------------------
AA | A | A | 0 |
AB | A | B | 1 |
AC | A | C | 1 |
AD | A | D | 0 |
BA | B | A | 1 |
BB | B | B | 0 |
BC | B | C | 0 |
BD | B | D | 1 |
.. .. .. ..
(C and D not related to anyone or all connect value to row C and D is 0)


I hope, this can be output..



*************[ I WISH ]**************
maxsimum distance = 2
-------------------------------------------
index| $visited_node | $jarak (distance)
-------------------------------------------
0 | A | 0
1 | B | 1
2 | C | 1
3 | D | 2


I have tracing that algorithm, and my output in my mind is that above. But in reality, the result is always :



********[ REALITY ]********
maxsimum distance = 2
visited node: Array (
[0] => A
[1] => B
[2] => C
)
distance: Array (
[0] => 0
[1] => 1
[2] => 1
)


Can you see.. D is missing and its distance too. As I trace my syntax, D is always exist, but output is always like that. I don't know why.. What's wrong with that syntax? Can anybody help me?







http://ift.tt/VujA9y