I want to allow numbers 1 through 6, not allow 7, but also allow 8. How would I write this line? Also, how would I write a line that allows numbers 1 through 6, skips 7, and allows 8 through 10? Basically eliminating 7 from the list.
Pages 1
You are not logged in. Please login or register.
AudioGames.net Forum → Developers room → skipping numbers in bgt's random generator
I want to allow numbers 1 through 6, not allow 7, but also allow 8. How would I write this line? Also, how would I write a line that allows numbers 1 through 6, skips 7, and allows 8 through 10? Basically eliminating 7 from the list.
You'd probably need a while loop. This is the situation for which do-while would be good, but for some reason everyone's trying to get rid of do-while these days.
So you'd first do the random number as usual, then on the next line, start a while loop that continues while the number is forbidden. In this case, while (num == 7)
This is the kind of loop I'd want to put on one line, but for readability:
int num = random (1, 10);
while (num == 7)
{
num = random (1, 10);
}
If you're curious, the do-while version would be like:
int num;
do { num=random (1, 10); }
while (num == 7);
Most people seem to agree. They're more useful when the script blocks for user input, which really shouldn't be done outside of text-based games. They also make more sense in older versions of C, when you'd declare all the variables at the start of a function, but not assign them values until later.
Mostly, if I have to copy a line of code to be both before and inside a while loop, I'd rather use a do-while. But this is not necessary.
A do while loop is useful when you want something to run at least one time. fore example:
// this is c++ code
#include <iostream>
using namespace std;
void whileLoop(int x);
void doWhileLoop(int x);
int main()
{
int x = 0;
whileLoop(x);
doWhileLoop(x);
return 0;
}
void whileLoop(int x)
{
// loop will check the condition and not run
while (x > 0)
{
cout << "Running while loop. x is: " << x << endl; //
x--; //decrement x
}
}
void doWhileLoop(int x)
{
// loop will run this time because it is a do while
do
{
cout << "Running do while loop. x is: " << x << endl;
x--; // decrement x
}
while (x > 0);
}
This is a bit contrived but i hope you get the point. do whiles can be very useful in many cases. They can help with debugging and protecting against your conditionals acting up because of weird input.
there are many, many ways to do this. Using a while loop to check for a forbidden number is one, you can also create an array with the allowed numbers, then generate a random index. You could also, in your example, generate a random number between 1 and 7, and if it is 7, increase it by one. You can modify this example yourself to remove 7 from a random number between 1 and 10.
AudioGames.net Forum → Developers room → skipping numbers in bgt's random generator
Generated in 0.383 seconds (5% PHP - 95% DB) with 9 queries