DEV Community

Discussion on: Daily Challenge #192 - Can you Survive the Zombies?

Collapse
 
vidit1999 profile image
Vidit Sarkar

C++

// takes number of bullets and percentage of missing as input
// i.e. 5 for 5% chance of missing
// this functions guarantees that the given percentage of total bullets will miss zombies
vector<bool> hitOrMiss(int numBullets,int percentage){
    vector<bool> hits(numBullets,true);
    for(int i=0;i<numBullets*percentage/100;i++){
        hits[i] = false;
    }
    shuffle(hits.begin(),hits.end(),default_random_engine(time(0)));
    return hits;
}

void zombie_shootout(int totalZombie, float range, int numBullets){
    int tempTotalZombie = totalZombie; // holds the total number of zombies
    int tempNumBullets = numBullets; // holds the total number of bullets
    vector<bool> hits = hitOrMiss(numBullets,5);

    while(numBullets>0 && totalZombie > 0 && range > 0){
        if(hits[numBullets-1]){
            totalZombie--;
        }
        numBullets--;
        if(totalZombie==0)
            break;
        range -= 0.5;
    }

    // If you shoot all the zombies
    if(totalZombie == 0 && range > 0 && numBullets >= 0){
        cout << "You shot all " << tempTotalZombie << " zombies.\n";
        return;
    }

    // If you get eaten before killing all the zombies, and before running out of ammo
    // or If you run out of ammo at the same time as the remaining zombies reach you
    if(range == 0 && totalZombie > 0 && numBullets >= 0){
        cout << "You shot " << tempTotalZombie-totalZombie << " zombies before being eaten: overwhelmed.\n";
        return;
    }

    // If you run out of ammo before shooting all the zombies,
    if(numBullets == 0 && totalZombie > 0){
        cout << "You shot "<< tempTotalZombie-totalZombie <<" zombies before being eaten: ran out of ammo.\n";
        return;
    }
}