samedi 28 octobre 2017

Generating random numbers in c which does not overlap with another range of random numbers

I'm new to programming and just started to learn c. I was hoping to create a simple battleship game but then I face a problem while generating random numbers. I wants to generate a random number that doesn't overlap with another range of number. Let's say I got 40 as my first random number and I don't want 40, 41, 42, 43 and 44 to appear again. So following is my code, I can't figure out what's wrong with it.

srand(time(NULL));
    for(counter = 0; counter < ship_num; counter++){
        checked = 0;
        while (!checked){
            ship_x[counter] = 1 + rand()%56;
            ship_y[counter] = 1 + rand()%20;
            checked = 1;
            for(check = 0; check < counter; check++){
                if(ship_y[counter] == ship_y[check]){
                    int check_x = ship_x[check] + 5;
                    if(ship_x[counter] >= ship_x[check] && ship_x[counter] <= check_x){
                        checked = 0;
                    }
                }
            }
        }
    }

All the variable is defined so I won't define it again here.




Aucun commentaire:

Enregistrer un commentaire