Skip to content

Instantly share code, notes, and snippets.

@asarver
Created December 1, 2011 21:05
Show Gist options
  • Select an option

  • Save asarver/1419857 to your computer and use it in GitHub Desktop.

Select an option

Save asarver/1419857 to your computer and use it in GitHub Desktop.
Magic Square
#include <iostream>
using namespace std;
bool check(int num) {
if (num % 2 == 0) {
return false;
}
if (num <= 0 || num > 99) {
return false;
}
return true;
}
void findNextPos(int * pos, int ** dynamicArray, int dim) {
int * newPos = new int[2];
if (pos[0] - 1 < 0) {
newPos[0] = dim - 1;
} else {
newPos[0] = pos[0] - 1;
}
if (pos[1] + 1 >= dim) {
newPos[1] = 0;
} else {
newPos[1] = pos[1] + 1;
}
bool validPos = false;
if (dynamicArray[newPos[0]][newPos[1]] == 0) {
validPos = true;
pos[0] = newPos[0];
pos[1] = newPos[1];
}
while (!validPos) {
if (dynamicArray[pos[0] + 1][pos[1]] == 0) {
validPos = true;
pos[0] = pos[0] + 1;
} else {
cout << "doesn't happen";
}
}
delete [] newPos;
}
void makePerfectSquare(int ** dynamicArray, int dim) {
dynamicArray[0][dim/2] = 1;
int num = 2;
int * pos = new int[2];
pos[0] = 0;
pos[1] = dim / 2;
while (num <= dim*dim) {
findNextPos(pos, dynamicArray, dim);
dynamicArray[pos[0]][pos[1]] = num;
num++;
}
for (int i = 0; i < dim; i++) {
for (int j = 0; j < dim; j++) {
cout << dynamicArray[i][j] << " ";
if (j == dim - 1) {
cout << endl;
}
}
}
delete [] pos;
}
bool checkIfPerfect(int ** dynamicArray, int dim) {
int * sum = new int[dim];
int summationOne = 0;
int summationTwo = 0;
for (int i = 0; i < dim; i++) {
for (int j = 0; j < dim; j++) {
summationOne += dynamicArray[i][j];
summationTwo += dynamicArray[j][i];
}
if (summationOne != summationTwo) {
return false;
}
sum[i] = summationOne;
summationOne = 0;
summationTwo = 0;
}
for (int i = 0; i < dim; i++) {
summationOne += dynamicArray[i][i];
}
for (int i = 0; i < dim; i++) {
if (sum[i] != summationOne) {
return false;
}
}
return true;
}
int main() {
int dim;
cout << "Enter a dimension from 1 to 99 that is odd." << endl;
cin >> dim;
while (!check(dim)){
cin >> dim;
cout << "Wrong input. Enter a new number." << endl;
}
int ** dynamicArray = 0;
dynamicArray = new int *[dim] ;
//memory allocated for elements of each column.
for( int i = 0; i < dim; i++) {
dynamicArray[i] = new int[dim];
}
makePerfectSquare(dynamicArray, dim);
if (checkIfPerfect(dynamicArray, dim)) {
cout << "this is correct." << endl;
} else {
cout << "wrong." << endl;
}
//free the allocated memory
for( int i = 0; i < dim; i++) {
delete [] dynamicArray[i];
}
delete [] dynamicArray;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment