tags:

views:

93

answers:

4

Hey there, So I'm knocking together a random pattern generation thing.

My code so far:

  int permutes = 100;
  int y = 31;
  int x = 63;

  while (permutes > 0) {
    int rndTurn = random(1, 4);

    if (rndTurn == 1) { y = y - 1; } //go up
    if (rndTurn == 2) { y = y + 1; } //go down
    if (rndTurn == 3) { x = x - 1; } //go right
    if (rndTurn == 4) { x = x + 1; } //go left

    setP(x, y, 1);
    delay(250);
  }

My question is, how would I go about getting the code to not go back on itself?

e.g. The code says "Go Left" but the next loop through it says "Go Right", how can I stop this?

NOTE: setP turns a specific pixel on.

Cheers peoples!

+1  A: 

You remember the last direction and, using random(1,3), pick either of the remaining three, then store that as the last one.

sbi
+6  A: 

It depends on what you mean.

If you mean "avoid going back to a step I was most previously on" then you have to remember the direction of the last movement. That is if you move up your next movement can't be down.

If you mean "avoid going back on a spot you've ever been on" then you're going to have to remember every spot you've been on. This can be implemented efficiently with a hash table using a key with a class representing a coordinate with appropriate Equals/HashCode functions.

cletus
Also you would need to implement backtracking as there could come a point where you can't move anywhere.
Yacoby
+2  A: 

Since each square corresponds to a pixel, your coordinate space must be finite, so you could keep track of coordinates you've already visited.

If there's a corresponding getP function to determine if a pixel has already been turned on, you could just use that.

jamesdlin
A: 

Not sure if this approach will work.

Create a new variable called lastRndTurn as int, and assign this after your if statements. Then add a new while loop after your int rndTurn = random(1, 4).

while (lastRndTurn == rndTurn)
{
    rndTurn = random(1, 4);
}
Ardman
Exactly what I was looking for!
Neurofluxation
Except that the random generator might come up with 'lastRndTurn' several times in a row. Not that this would matter while you wait 25mms after each turn...
sbi
While this would work it's generally not good practice to brute force an acceptable value. I think the solution below is much better. Store the last movement (say 2, for up) as an integer. Create an array, and with a for-next loop, add the numbers 1 2 3 4, but only if the number isn't the same as the last movement. Then do a random on that. You'll have to reverse the answer.
SLC
I agree, but now I have the building blocks to get started.
Neurofluxation