Question

Is there a way that I can flag an element in an array sort of on and off, or back and forth between a specific integer like 1 and 2 inside of a nested loop. I'm very stuck on my homework assignment. Basically I have 150 elements in an array and a mailman is going through and opening boxes with multiples of 2, and then multiples of 3, and if he hits a box that's already been opened with a multiple of 2 he closes it and then he goes through the 150 mailboxes with multiples of 4, and so on and so on until 150, and he closes a box if its already open, and opens boxes that are closed, until the outer loop hits 150 and all numbers have been used

I've tried boolean and if statements, and just a bunch of extra counter variables, and idk how to effectively do this

I got it to work once, but the code was so sloppy that I just scratched it because it was probably the wrong answer anyway

by all means I'm not trying to cheat in my course, but I've read the chapter multiple times and have done numerous internet searches and I'm lost. I'm not asking for code, I just want an idea of what would be the best way to kinda mark or tag elements in an array

Was it helpful?

Solution

Use the modulus operator: % to check the remainder.

OTHER TIPS

Here is one example that does what you describe.

To toggle a boolean value, simply use the "not" boolean operator.

#include <vector>
#include <iostream>
class boxes {
private:
    std::vector<bool>open;

    // visit boxes for a given step
    void visit (size_t step)
    {
        for (size_t i = 0 ; i < open.size() ; i+= step)
        {
            open[i] = ! open[i]; // toggle open state
        }
    }

public:
    // constructor
    boxes (size_t size)
    {
        // all boxes initially closed
        open.resize(size, false);

       // visit boxes with all values
       for (size_t i = 2 ; i != size ; i++)
       {
           visit (i);
       }
    }

    // trace function
    void trace (void)
    {
        for (int i = 0 ; i != open.size() ; i++)
        {
            std::cout << "box " << i << (open[i] ? " open" : " closed") << std::endl;
        }
    }
};

int main (void)
{
    boxes sample (10);
    sample.trace();
    return 0;
}

output:

box 0 closed
box 1 closed
box 2 open
box 3 open
box 4 closed
box 5 open
box 6 open
box 7 open
box 8 open
box 9 closed
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top