generating random numbers from a specific pool

Hello! Im new to this forum and I come here with a question. I have been following the C++ tutorial from this website and I love it! I have been doing that along with a class in college. C++ 1.
For my project I have to generate a 3x3 grid with numbers from 1 - 9 not repeating and all of the rows have to add to 15.

Now I do not want any hints on how to do this, but I have a question about the random numbers generation. I need to generate a box 2x2.
ex.
1
2
1 2
3 4


But spots 1 and 2's sum must be >= to 6 and <= 14. same applies to spot 1 and 4. Spot 1 and 3. spot 3 and 4. spot 3 and 2 and so on.
Yes I can write this using if statements, but then the program working time will be 30 min as it would have to generate a million random numbers.
My question is, can I generate numbers that will add to 6 or more but not greater than 14?
ex. if my first generated number is 1, then spot two will be generated based on this rule. numbers greater than 3. and if the first number generated is 9 then the rule for generating the second number would be numbers less than 6.

I hope I explained it somehow clear.
Any help is appreciated!

Thanks!

Damian
Last edited on
The rand() function has a [set of parameters that function as] min and max-1 of the range. As these are just variables like any other, you can use a value that depends on several variables.
1
2
3
// First number: between 1 and 9
int first = rand()%9 +1; // The '9' is exclusive and the range starts at 0..
// ..but the +1 shifts the range up by one. 

The min and max value of your second number depend on the number thrown by the first. If the first got 9, then the second will have to be [1,4]. If the first was 1, then the second will have to be [5,9].

I'll leave it up to you to find the calculation(s) required to find the correct min and max. Once you have them, you can generate the second number by:
 
int second = rand()%max +min;

Do mind that 'max' in this code isn't the actual maximum of your range, but the adjusted range that depends on 'min'. For example, if your number has to be [4,9], then min is 4 and max is 6 (remember: the 'max' is exclusive).
Last edited on
Topic archived. No new replies allowed.