mercredi 6 février 2019

Vector Function: Is this a bug or is it just wrong

I have written a function for my 2048 game which takes in a certain range of values in a vector and pushed them to the left just like the game. If any movement happens, it also returns a true statement.

For example:

The input range is such that LB is inclusive and UB is not. e.g bi <= x < ei

if the range was the whole vector ( bi = 0 to ei = 4) v in : 1001 v out : 2000

Another example:

if the range if (bi = 0 and ei = 4) v in : 101010101 v out: 200010101

Simple function it would seem:

Here is what I wrote for it:

bool left_push(std::vector<int>& v, int bi, int ei){

std::vector<int> tmp;
bool check = false;

for(int i= bi ; i< ei ; i++){
    if(v[i]!= 0){
        tmp.push_back(v[i]);
        check = true;
    }
}


for(int i = 0; i< tmp.size(); i++){
    if( tmp[i]==tmp[i-1] && tmp[i]!=0 && i>0){
       tmp[i-1] = tmp[i]+tmp[i];
       tmp[i] = 0;
       check = true;
    }
}


int x = bi;

for( int i = 0; i < tmp.size(); i++ ){
    if(tmp[i]!=0){

        v[x] = tmp[i];
        x++;
    }
}

for( int i = x; x < ei ; x++ ){
    v[i] = 0;
}

return check;

}

This function: prints non zero values into another vector to add them. Then adds adjacent numbers if they are equal and replaces empty index with zero. Then prints back non zero values back in to the original vector. And finally prints zeros in rest of indexes in range to complete what is needed.

All the loops work perfectly I tested them all and they are fine however the last loop here:

for( int i = x; x < ei ; x++ ){
    v[i] = 0;
}

Just simply does not work and does not overwrite the values to zero?

Is this a bug or have I just done something wrong?

Aucun commentaire:

Enregistrer un commentaire