-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLab6_Welton.cpp
127 lines (107 loc) · 3.08 KB
/
Lab6_Welton.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
/*
Name: Lab6_Welton
Author: Christopher Welton
Description: This program reads N^2 values from the keyboard and tests wether it is a magical square.
*/
#include<iostream>
#include<set>
#include<vector>
using namespace std;
bool areNumbersUnique(vector<int> nums){
set<int> unique;
for(int i =0; i< nums.size(); i++){
unique.insert(nums[i]);
}
return unique.size() == nums.size();
}
bool isMagicSquare(vector<int> nums, int nValue){
int magicSum = 0;
for(int i=0; i<nums.size(); i += nValue){
int nextRowSum = 0;
for(int j = i; j < nValue + i; j++){
nextRowSum += nums[j];
}
if(i != 0){
if(magicSum != nextRowSum){
return false;
}
} else {
magicSum = nextRowSum;
}
}
for(int i = 0; i < nValue; i ++){
int nextColSum = 0;
for(int j = i; j < nums.size(); j += nValue){
nextColSum += nums[j];
}
if(magicSum != nextColSum){
return false;
}
}
int topBottomDiagSum = 0;
for(int i = 0; i < nums.size(); i+= nValue){
topBottomDiagSum += nums[i];
}
if(magicSum != topBottomDiagSum){
return false;
}
int bottomTopDiagSum = 0;
for(int i = 0; i < nValue; i++){
bottomTopDiagSum += nums[i * nValue + (nValue -1 -i)];
}
if(magicSum != bottomTopDiagSum){
return false;
}
return true;
}
int main() {
int nValue;
cout << "Please enter a N value to determine the size of the matrix: ";
cin >> nValue;
vector<int> numbers(nValue * nValue);
cout << "You will now enter " << nValue * nValue << " numbers." << endl;
cout << "Please ensure your numbers are unique!" << endl;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
for(int i=0; i < numbers.size(); i++){
string numberOrdinal;
int value;
bool validInput = false;
switch(i + 1) {
case 1:
numberOrdinal = "st";
break;
case 2:
numberOrdinal = "nd";
break;
case 3:
numberOrdinal = "rd";
break;
default:
numberOrdinal = "th";
break;
}
do {
cout << "Enter the " << i + 1 << numberOrdinal <<" number: " << endl;
string input;
getline(cin, input);
try {
value = stoi(input);
numbers[i] = value;
validInput = true;
} catch (invalid_argument&){
cout << "Error: Invalid input. Please enter a valid integer" << endl;
}
} while (!validInput);
}
if(!areNumbersUnique(numbers)){
cout << "The numbers you input are not unique, program terminating...." << endl;
return 0;
}
bool magic = isMagicSquare(numbers, nValue);
if(magic){
cout << "This is a magic square!" << endl;
} else {
cout << "This is not a magic square." << endl;
}
return 0;
}