Hello All
This was an online test, which I didn't do very well with, and am looking for guidance of where I went wrong.
The idea is you'd have a matrix $A with values -1, 0, 1 in each position, in rows M and column N where M,N can be up to 1000. The code is evaluated $k times where $k can be up to 1000 as well.
Starting at $A[0][0], evaluate the matrix where -1 means you go down a row and +1 means you go right one column. A 0 value means you continue along your previous direction.
After exiting a position, that positions value is multiplied by -1: 1 = (-1); (-1) = 1; 0 = 0
Once you exit the matrix either on the right or below, you stop and start over
The goal of the code is to return how many times you exited the bottom right corner, ending up below (not to the right) the matrix; When your spot is [M], [N+1]
Here is the code I wrote:
function eval_matrix( $A, $k ) {
$x = 0;
$y = 0;
// dir is x or y for up/down //
$dir = "y";
$ball_count = 0;
// Get columns //
$maxX = count($A);
// Get rows //
$maxY = count($A[0]);
// for $k times
for($i=0; $i<$k; $i++) {
// while we're within the matrix boundaries
while($x < $maxX && $y < $maxY) {
// get the value of our current position
$mode = $A[$x][$y];
// evaluate the value 0,1,-1
switch($mode) {
case 0:
if($dir =="y") {
$y++;
} else {
$x++;
}
break;
case -1:
// Change position value
$A[$x][$y] = 1;
$y++;
$dir = "y";
break;
case 1:
// Change position value
$A[$x][$y] = -1
$x++;
$dir = "x";
break;
}
}
if($x == $maxX-1 && $y == $maxY) {
$ball_count++;
}
$x = 0;
$y = 0;
$dir = "y";
}
return $ball_count;
}
It may be fairly ugly, but I'm looking for help with how to properly code this type of solution. Any pointers, resources, suggestions are greatly appreciated!