Home > Back-end >  Why does this random walk I wrote look suspiciously non-random?
Why does this random walk I wrote look suspiciously non-random?

Time:12-12

I'm trying to write a random walk in JavaScript using P5 js. My goal is to let it walk randomly in the x or y direction and randomly through a subset of color-space (just the hue section of HSV). I added modular division into the walk so that it just loops around at the edges.

The problem is nearly all of the random walks seem to move in a very similar way - in a sort of stair-step diagonal pattern. The exact shape of the stairstep is random but it's very clearly not even random to the level of a typical pseudorandom generator. The color walk seems to work but it also tends to spend a suspicious amount of time clustered around red (hue=0). I did very similar code with Python and OpenCV earlier the same day and it produced exactly what one would expect for a random walk (I know python uses a Mersenne twister and JavaScript likely uses something else for their pseudorandom RNG but I suspect that something else is at play here).

The page is hosted here and the code is here I would include it in the post directly but stackoverflow is giving me a weird issue about my code not being formatted like code even though I have tried fencing it with triple backticks and 4 space indenting it etc and I've posted code on SO before without issue but that's not my main concern here my main concern here is fixing the random walk.

I got the issue in both Chrome and Firefox (I didn't test another browser). Attached are some screenshots in case the behavior doesn't occur on your device

First example Second example

edit: the issue was missing the break statements in my switch as suggested below by @NineBerry

CodePudding user response:

Your switch statement misses break statements.

switch (direction) {
      case 0:
          cX -= STEP_SIZE; // move left
          break;
      case 1:
          cX  = STEP_SIZE; // move right
          break;
      case 2:
          cY -= STEP_SIZE; // move up
          break;
      case 3:
          cY  = STEP_SIZE; // move down
          break;
  }

Without the breaks, the later cases will be executed almost every time.

Documentation for the switch statement from Mozilla:

The switch statement evaluates an expression, matching the expression's value against a series of case clauses, and executes statements after the first case clause with a matching value, until a break statement is encountered.

  • Related