How to make a Random Walk, PHP?

544 views Asked by At

I've been trying for several hours to make a random walk (a path) like this one. From top to down.

x  1  x
x  2  3
x  x  4
7  6  5
8  x  x
9  10 x

My greatest difficulty is to calculate the displacement from right to left because the cycles (for, while..) go from left to right.

I am not proficient in math, so I'm using a simple approach. I have two arrays. One with the position of the previous row.

$previousRow=array(1=>"x",2=>"1",3=>"x");

One with the current row I have to fill.

$currentRow=array(1=>"",2=>"",3=>"");

$p   //Is the current position. 1, 2 or 3. Example $currentRow[$p]
$last   //the last number that increases each time the path has a new step.

I'm using some cycles and conditions to set the displacement.

Is this approach wrong?

EDIT: further specifications as requested from comments:

  1. Start point is located in the middle point of the first row
  2. End point is located in the last row
  3. End point can be located in any column of the last row
1

There are 1 answers

0
hakre On

per each field you have three possibilities: left, right, forward.

some cases reduce this, e.g. there is no field to the left or right or that field was visited already.

so find out about possible moves, pick one at random and go on.