Bug moving a box problem

The assignment is "A SpiralBug can occupy any integer coordinates (x, y), where x and y can be 0, negative, or positive. It starts at (0, 0). For the next n steps, it moves to the right. Then it makes n steps up. Then it makes 2n steps to the left, 2n steps down, and so on, tracing a spiral. (Hence its name. Google it if you dare.) Each call to move should carry out one step."

As for now, I have put 4 bool functions in my class file as private, and I am thinking to do something like this

since the bug can move in 4 directions

if(right==true)
x=x+size, y=y; //size is n


any help will be appreciated thanks!
I'm not exactly sure what your question is. Note that in general, I wouldn't use the comma operator for separate commands like that. And also, that y=y doesn't do anything. You're assigning something to itself.

Since the bug can only move in 4 directions, and not 8, I think you're going about this slightly wrong. It makes no sense for both right and left to be true, or right and up to be true. Instead, I would just make the direction be an integer (or an enum) and base the logic off that.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// Example program

int main()
{
    enum Direction {Left, Up, Right, Down};
    
    Direction dir = Left;
    
    int x = 0;
    int y = 0;
    int size = 1;
    
    // ...
    if (dir == Right)
    {
        x = x + size;
        dir = Down;
    }
    else if (dir == Down)
    {
        y = y - size;
        dir = Left;
    }
    // ...
    
}


You could probably simplify the logic with modular arithmetic, but that's another subject.
Thanks!Ganado, I think the question is if n is 2, the bug moves twice with the size of 2, then twice with the size of 2*2 and then twice with 2*3...i am thinking a for loop here maybe?
Yes, that sounds correct, I believe. Every other movement, you increase the length you need to move, for a square spiral. Yes, a loop will be necessary to loop on the number of iterations that you want the bug to spiral out to.

You can do something like this, a bit different than my design before:
1
2
3
4
5
6
7
8
9
10
11
int num_full_spirals = 5;
for (int i = 0; i < num_full_spirals; i++)
{
    go left
    go up
    increase size

    go right
    go down
    increase size
}
Last edited on
Topic archived. No new replies allowed.