0

I have a created a grid like this (some gaps has an obstacle, but it is not important for the question):

 private function newGrid()
    {
        $grid = array();

        for ($i = 0; $i < 10; $i++) {
            for ($j = 0 ; $j < 10; $j++) {
                $grid[$i][$j] = ['obstacle' => rand(0,1)];
            }
        }

        return $grid;
    }

So, the initial location is an array:

$loc = array('x' => 1, 'y' => 3);   

For example, if i'm moving to x direction, I want wrapping from one edge of the grid to another(like an sphere). (Forward and backward)

When i'm going forward I'm using the modulus like this:

$loc['x'] = ($loc['x'] + 1) % 10 ; 

But if I want to do the same, but going backwards, which is the better way to do that? when x gets to 0, go to position x = 9

Any suggestion?

2
  • 1
    Are you looking for array_reverse()? The wording in your question is kind of confusing to mne Commented Sep 15, 2017 at 17:34
  • Thanks for replying @GrumpyCrouton. What is confusing you? It is a grid of 10x10 positions, I would like to set the position every movement, but when i'm getting to the edge (like an sphere), the location has to be "reseted" and start again. Same as going backwards Hope this is clearer Commented Sep 15, 2017 at 17:43

1 Answer 1

1

For going backwards you can do:

$loc['x'] = ($loc['x'] + 9) % 10 ;

If you have dynamic "direction" variable which can take values 1 (forward) and -1 (backwards), then:

$loc['x'] = ($loc['x'] + 10 + $direction) % 10 ;

Maybe this would be a practical function:

function move($loc, $deltaX, $deltaY) {
    $loc['x'] = ($loc['x'] + 10 + $deltaX) % 10;
    $loc['y'] = ($loc['y'] + 10 + $deltaY) % 10;
    return $loc;
}
Sign up to request clarification or add additional context in comments.

4 Comments

@Albeis, you can see the +9 as a -1, in modulo 10, that is the same operation.
@trincot Thanks for replying. This only work when x = 1, it will move x till x=9, that is what I'm looking for, but when x= 3 if I apply that, I want x to be equal 2, not 1 using $loc['x'] = ($loc['x'] + 9 - 1) % 10. Note -1 giving backward direction. Regards
@MateiRogoz yes, but what happen when x is going from 0 to -1? I want x to be 9 instead of -1..
@Albeis I was trying to say I realized you were stuck on the fact that you'd get to -1 and that you can view the +9 in trincot's answer as the equivalent of doing a -1 operation in modulo 10.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.