2015-04-30 5 views
0
#include <iostream> 
#include <stdlib.h> 
#include <time.h> 
using namespace std; 

// Functions used in the program. 
bool uniqueCheck(int arr[][3], int num); 
bool magicSquare(int arr[][3]); 
int rTotal(int arr[][3], int row); 
int cTotal(int arr[][3], int col); 
int dTotal(int arr[][3], bool left); 
void display(int arr[][3]); 

int main() 
{ 
    int arr[3][3]; //makes the array 3x3 makes it into the square 
    int test[3][3] = {2, 7, 6, 9, 5, 1 , 4 , 3 ,8}; //numbers from 1-9 in order of magic square. 

    while (1) 
    { 
     for (int i = 0; i < 3; i++) 
      for (int j = 0; j < 3; j++) 
       arr[i][j] = 0;// nested for loop the i is for rows and the j is for columns 

     srand((unsigned)time(NULL));// generates random numbers 
     for (int i = 0; i < 3; i++) 
     { 
      for (int j = 0; j < 3; j++) 
      { 
       while (1) 
       { 
        int num = (rand() % 9) + 1; // Random function will spit out random numbers from 1-9. 
        if (uniqueCheck(arr, num)) 
        { 
         arr[i][j] = num; 
         break; 
        } 
       } 
      } 
     } 

     display(arr); 
     if (magicSquare(arr))//If the magic square array is an actual magic square than this outputs 
     { 
      cout << "This is the Magic Square !" << endl; 
      break; 
     } 
     else //if not than it'll keep looping this until the top one is displayed 
      cout << "This is Not the Magic Square !" << endl; 

    } 
    return 0; 
} 

// check if the random number generated is a unique number 
bool uniqueCheck(int arr[][3], int num) 
{ 
    for (int k = 0; k < 3; k++) 
     for (int i = 0; i < 3; i++) 
      if (arr[k][i] == num) 
       return false; 
    return true; 
} 

bool magicSquare(int arr[][3]) //This will check if the number presented (randomly) correspond with the magic square numbers. 
{ 
    int sum = dTotal(arr, true); // Will check the sum of the diagonal. 

    if (sum != dTotal(arr, false)) 
     return false; 

    for (int i = 0; i < 3; i++) 
    { 
     if (sum != rTotal(arr, i)) // This will check each row and see if its true or false. 
      return false; 

     if (sum != cTotal(arr, i)) // This will check each column and see if its true or false. 
      return false; 
    } 

    return true; 
} 

int rTotal(int arr[][3], int row) // This will calculate the sum of one row at a time. 
{ 
    int sum = 0; 
    for (int i = 0; i < 3; i++) 
     sum += arr[row][i]; 
    return sum; 
} 

int cTotal(int arr[][3], int col) // This will calculate the sum of one column at a time. 
{ 
    int sum = 0; 
    for (int i = 0; i < 3; i++) 
     sum += arr[i][col]; 
    return sum; 
} 

int dTotal(int arr[][3], bool left) // This will calculate the sum of diagonal. if the left is true, it will calculate from the left to the right diagonal. If false it will calculate from the right to the left diagonal. 
{ 
    int sum = 0; 
    if (left == true) 
    { 
     for (int i = 0; i < 3; i++) 
      sum += arr[i][i]; 
     return sum; 
    } 

    for (int i = 0; i < 3; i++) 
     sum += arr[i][3 - i - 1]; 
    return sum; 
} 

void display(int arr[][3]) //This will display the array. 
{ 
    for (int i = 0; i < 3; i++) 
    { 
     for (int j = 0; j < 3; j++) 
      cout << arr[i][j] << " "; 
     cout << endl; 
    } 
    cout << endl; 
} 

Это мой код. Это вычисляет магический квадрат. Единственное, что я не могу получить, это мои числа, которые, как предполагается, переключаются каждый раз, когда они контуров, но он показывает одинаковое число каждый раз, когда он зацикливается, что в основном делает его бесконечным циклом ... то, что я прошу, - это помощь в получении чисел меняться каждый раз, когда он петли. Заранее большое спасибо.Magic square code

+0

Возможный дубликат [Эти же случайные числа для каждой итерации цикла] (http://stackoverflow.com/questions/9251117/same-random-numbers-every-loop-iteration) – Beta

ответ

0

При написании кода вы должны разработать новую функциональность в изоляции, прежде чем интегрировать ее с другим кодом.

Когда вы работали с генератором случайных чисел, вы должны были заметить, что это:

srand((unsigned)time(NULL));// generates random numbers 

возвраты генератора случайных чисел. И так как вы делаете это в каждом проходе через основной цикл, вы получаете одинаковые «случайные» числа каждый раз.

Переместить эту линию вверх, вне петли.

Смежные вопросы