msmith1114
msmith1114

Reputation: 3231

C++ Iterators and Vectors

So im solving a hackerrank challenge called "Jumping on the clouds" and it involves taking the least amount of steps to get to the end. Ill summarize the problem:

Emma is playing a new mobile game that starts with consecutively numbered clouds. Some of the clouds are thunderheads and others are cumulus. She can jump on any cumulus cloud having a number that is equal to the number of the current cloud plus 1 or 2 . She must avoid the thunderheads. Determine the minimum number of jumps it will take Emma to jump from her starting postion to the last cloud. It is always possible to win the game.

The "list" of clouds is given in a vector of 0's and 1's. 0's are "safe" 1's Emma can not jump to.

The function we receive is a vector of 0's and 1's like so:

int jumpingOnClouds(vector<int> c) {


}

So I thought to myself "ok"...well since it's always possible to win the game we should ALWAYS check 2 spaces ahead (for a 1) and if not just jump 1 position).

So I wrote up something like so (Im still refreshing on C++ so my code is probably not great):

int jumpingOnClouds(vector<int> c) {
    int jumps = 0;
    vector<int>::iterator it = c.begin();
    vector<int>::iterator it2 = c.begin();

    while(it != c.end())
    {
        it2 = next(it,2);
        if(*it2 == 0){
            jumps++;
            advance(it, 2);
        }
        else {
            jumps++;
            advance(it,1);
        }
    }
    return jumps;
}

However this always ends in a segfault. I am not super familiar with iterators in general and created this just from checking the iterator documentation. My "guess" is that im going 2 past the end if the last element is 0. The first input list is 0 0 1 0 0 1 0 so it seems like it would jump once to pos1, then jump twice to pos3, then once to pos4, then finally jump twice to the last pos then stop. So it doesn't seem like initially it should fail.

Im sure im missing something obvious though.

Upvotes: 0

Views: 78

Answers (1)

bpeikes
bpeikes

Reputation: 3705

it2 = next(it,2)

it2 may be past the end of the vector, once you dereference it with *it2, boom segfault.

Don't want to give you too big a hint to the solution, but there is a flaw in your logic.

This is a path searching problem, I'd use recursion. You need to try all valid paths through the array.

Upvotes: 1

Related Questions