So I'm working on a Lo Shu Magic Square for my first programming class and I'm stuck. I'm sure everyone here will know what that is but just in case, it's a 2D array that takes 9 numbers from user input, but they have to be between that range (1-9) and also non repeating (where I'm stuck).
I can validate for numbers within the 1-9 range, but I'm having trouble also validating for the second condition of non-repeating numbers
Here's my code for the function that takes user input:
(Oh yea, the 2D array is 3x3 so ROWS = 3 and COLS = 3 and they're being passed to this function)
// Get numbers
void getNumbers(int magicSquare[][COLS], int ROWS)
{
cout << "\nEnter Nine Numbers (1-9)" << endl;
int num;
int n = 0;
for (int r = 0; r < ROWS; r++)
{
for (int c = 0; c < COLS; c++)
{
cout << "\tNumber " << (n + 1) << ": ";
cin >> num;
magicSquare[r][c] = num;
n++;
// Input validation
// Validate against numbers outside the range
while (num < 1 || num > 9)
{
cout << "\tError ... Invalid number. Try again" << endl
<< endl;
cout << "\tNumber " << (n) << ": ";
cin >> num;
magicSquare[r][c] = num;
}
// Validate against repeating numbers
while (...) //OMEGA STUCK
{
cout << "\tError ... " << num << " is already in the
Lo Shu Square. Try again" << endl <<endl;
cout << "\tNumber " << (n) << ": ";
cin >> num;
magicSquare[r][c] = num;
}
}
}
cout << endl;
}
I have tried several approaches, from using while loops, to trying temp arrays, and I'm currently attempting to create a new bool function and pass the array and input to it but with little success.
// Validate against repeating numbers
while (repeatNumbers(magicSquare, num)) // Calling boolean function (defined below)
{
cout << "\tError ... " << num << " is already in the Lo Shu Square.
Try again" << endl << endl;
cout << "\tNumber " << (n) << ": ";
cin >> num;
magicSquare[r][c] = num;
}
...
// Validate against repeating numbers function
bool repeatNumbers(int magicSquare[][COLS], int num)
{
bool status;
if (num == magicSquare[COLS][COLS]) //Here I get an error:
{ //"Reading invalid data from
status = true; //'magicSquare[COLS]'.
}
else
{
status = false;
}
return status;
}
Is there a way to ensure that reading a partially filled-in array is well-behaved, what's the best approach? I can't arrive at the correct way, and I just KNOW I'm missing something that is quite logical which my tired brain can't think of at this point.
Any ideas on how to test for both conditions?