I have tried this code that I found online and it worked, but I want it to print out which number makes magic square. In this case it is 83, so instead of cout<<"Magic Square", how do I change it to show 83 instead?
Thank you in advance.
# define my_sizeof(type) ((char *)(&type+1)-(char*)(&type))
using namespace std;
// Returns true if mat[][] is magic
// square, else returns false.
bool isMagicSquare(int mat[][3])
{
int n = my_sizeof(mat)/my_sizeof(mat[0]);
// calculate the sum of
// the prime diagonal
int i=0,j=0;
// sumd1 and sumd2 are the sum of the two diagonals
int sumd1 = 0, sumd2=0;
for (i = 0; i < n; i++)
{
// (i, i) is the diagonal from top-left -> bottom-right
// (i, n - i - 1) is the diagonal from top-right -> bottom-left
sumd1 += mat[i][i];
sumd2 += mat[i][n-1-i];
}
// if the two diagonal sums are unequal then it is not a magic square
if(sumd1!=sumd2)
return false;
// For sums of Rows
for (i = 0; i < n; i++) {
int rowSum = 0, colSum = 0;
for (j = 0; j < n; j++)
{
rowSum += mat[i][j];
colSum += mat[j][i];
}
if (rowSum != colSum || colSum != sumd1)
return false;
}
return true;
}
// driver program to
// test above function
int main()
{
int mat[3][3] = {{ 1, 5, 6 },
{ 8, 2, 7 },
{ 3, 4, 9 }};
if (isMagicSquare(mat))
cout << "Magic Square";
else
cout << "Not a magic Square";
return 0;
}
As per suggested, I have tried to change it to:
int main()
{
int mat[3][3] = {{ 1, 5, 6 },
{ 8, 2, 7 },
{ 3, 4, 9 }};
if (isMagicSquare(mat))
{
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 3; j++)
{
cout<< mat[i][j] << ' ';
}
cout<< endl;
}
}
else
cout << "Not a magic Square";
return 0;
}
But it showed the whole array instead of the correct index in the array. I am sorry, I am somewhat new at the whole thing.
The result is showing up as:
1 5 6
8 2 7
3 4 9
Did I changed it in the wrong place? Or is there any further reading that I should read. Any helps would be appreciate.
The result that I am expecting is
83
as it is the number in the index that is the magic number.
If the given square is a magic square, that means when isMagicSquare(mat) is true, then iterate through the given square and print each of the values.
To do that, you'll have to learn how to print a 2D array.
In your case, you can do like below:
if (isMagicSquare(mat))
{
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 3; j++)
{
cout<< mat[i][j] << ' ';
}
cout<< endl;
}
}
Please check the below resources to learn more about 2D array:
How to print 2D Arrays in C++
Two Dimensional Array in C++
Multidimensional Arrays in C / C++
Related
I have to display the records based on the integer value in an array. For instance, if I have an array i.e.
2, 3, 5, 3, 6, 8, 10, 1, 9, 7
I would need to display 3 and 5 based on the integer 2. Then it should display 6,8 and 10 based on integer 3 and then 9 based on 1. So my display array would be:
3,5
6,8,10
9
So far, I haven't been able to form any algorithm/code.. How to proceed on this one?
tested it with your given array...
void display_records(std::vector<int> vi) {
int tmp = 0;
int index = 0;
for(int i=0;i<vi.size(); i++){
for(int j=1;j<=vi[i];j++){
index = i + j;
tmp = vi[index];
if((i+j) < vi.size()) { //to prevent it going out of range
std::cout << tmp << " " ;
}
}
i = i + vi[i];
std::cout << std::endl;
}
}
Try something like this: (i am not sure if i understood your question) (not tested)
void displayRecords(int* vect, int size, int val)
{
for(int i=0; i<size; i++)
{
if(vect[i]==val)
{
int tmp = val;
int j = i + 1;
while(tmp && j != size)
{
std::cout<<vect[j]<<" ";
j++;
tmp--;
}
break;
}
}
}
I have a row of ten numbers for example:
5 5 6 7 5 9 4 2 2 7
Now I want a program that finds all duplicates and gives them out in the console like 3 times 5, 2 times 2, 2 times 7.
While I did code an algorithm that finds duplicates in a row of numbers I can't give them out in the console as described. My program will output:
3 times 5
2 times 5
2 times 7
2 times 2
How can I solve this problem?
#include <iostream>
using namespace std;
int main()
{
int arr[10];
int i,j;
int z = 1;
for(i = 0; i < 10; i++) {
cin >> arr[i];
}
for(i = 0; i < 10; i++){
for(j = i+1; j < 10; j++){
if(arr[i] == arr[j]){
z++;
}
}
if(z >= 2){
cout << z << " times " << arr[i] << endl;
z = 1;
}
}
return 0;
}
You can use the STL here (C++11):
int arr[10];
std::map<int, int> counters;
for (auto item : arr)
{
cin >> item;
++counters[item];
}
std::for_each(counters.begin(), counters.end(), [](const std::pair<int,int>& item)
{
if(item.second > 1) std::cout << item.second << " times " << item.first << std::endl;
});
You need to check that arr[i] is not already found before, like this for example:
if(z >= 2) {
int found_before = 0;
for(j = 0; j < i; ++j)
if(arr[i] == arr[j])
found_before = 1;
if(!found_before)
cout << z << " times " << arr[i] << endl;
z = 1;
}
which will print:
3 times 5
2 times 7
2 times 2
That way you don't print 5 again.
With your code it would print that it found 5 three times (for the first 5 in your array), and then when it would move to he second 5 in your array, it would forgot about the first 5 in your array, and report that it found 5 twice (itself and the 5th number of the array).
Why not use STL?
std::map<int, int> counter;
for (i = 0; i < 10; i++)
counter[arr[i]] ++;
for (i = 0; i < 10; i++) {
if (counter.count(arr[i]) > 0){
std::cout << counter[arr[i]] << " times "<< arr[i] << std::endl;
counter.erase(arr[i]);
}
}
std::map is a convenient tool for this job. You can easily count up occurrences of a specific number. After counting, you can print the count of each array element. With counter.erase, it's guaranteed that you won't print the same element for multiple times.
Why keeping your algorithm idea, I suggest to create sub method:
std::size_t count(const int* arr, std::size_t start, std::size_t end, int value)
{
std::size_t res = 0;
for (std::size_t i = start; i != end; ++i) {
if (arr[i] == value) {
++res;
}
}
return res;
}
then your fixed algorithm would be:
for (std::size_t i = 0; i != 10; ++i) {
if (count(arr, 0, i, arr[i]) != 0) {
continue; // Already visited
}
auto total = count(arr, i, 10, arr[i]);
if(total >= 2){
std::cout << z << " times " << arr[i] << std::endl;
}
}
An easy way is to make another array for it, especially if the numbers are not that big.
Lets say you have initialized your array like so: int nums[10] = { 5, 5, 6, 7, 5, 9, 4, 2, 2, 7 }
int result[max(nums)]; //Fill with zeroes, max(nums) is the highest number in the array
for(int i = 0; i < 10; i++) {
result[nums[i]]++;
}
for(int i = 0; i < max(nums); i++) {
if (result[i] > 1) cout << result[i];
}
Mind you this isn't optimized for memory. For larger number contents you might want to consider hashmaps.
If you don't need performance but rather compact code, then std::multiset with std::upper_bound is an alternative:
#include<set>
#include<iostream>
#include<algorithm>
int main(int a, char** b)
{
int array[] = {5, 5, 6, 7, 5, 9, 4, 2, 2, 7};
std::multiset<int> a(std::begin(array), std::end(array));
for(auto it = a.begin(); it != a.end(); it = std::upper_bound(a.begin(), a.end(), *it))
{
if(a.count(*it) > 1)
std::cout << *it << " times " << a.count(*it) << std::endl;
}
return 0;
}
I have been playing around with a bit of code for the past few weeks. The code is a display of the number 1. I want to essentially create a dot matrix style print out, where the 1 is continuously shifted to the right.
Here is where I am so far:
#include <iostream>
using namespace std;
/* use function to shift all characters one place to the right */
/* use a function to declare the characters of the fiqure */
int i, j;
int matrix([int i][int j]);//dont think this is right
I have declared my variables, and the matrix with the parameters I and j
int main()
{
//should the matrix be a global function, therefore can be accessed by the move function?
/* the matrix is contained within the matrix function. The goal of main, is to manipulate
the matrix to transponse the elements to the next column*/
// 8 rows and 13 columns
for (i = 0; i < 8; i++)
{
int p = (j + 3)%13;
for (j = p; j < 13 ; j++)
{
matrix[i][j] = matrix[i][j + 3];
//priting out the matrix
cout << matrix[i][j];
}
cout << "\n";
}
cout << endl;
}
int matrix(int i, int j)
/* this function sets up the matrix and returns the value of the matrix.
this function should simply be a display function */
{
int matrix[8][13] = { { 0,1,1,1,1,1,0,0,0,0,0,0,0 },
{ 1,1,1,1,1,1,0,0,0,0,0,0,0 },
{ 0,0,1,1,1,1,0,0,0,0,0,0,0 },
{ 0,0,1,1,1,1,0,0,0,0,0,0,0 },
{ 0,0,1,1,1,1,0,0,0,0,0,0,0 },
{ 0,0,1,1,1,1,0,0,0,0,0,0,0 },
{ 0,0,1,1,1,1,0,0,0,0,0,0,0 },
{ 0,0,1,1,1,1,0,0,0,0,0,0,0 } };
//display the elements
for (i = 0; i < 8; i++)
{
for (j = 0; j < 13; j++)
{
//priting out the matrix
cout << matrix[i][j];
}
cout << "\n";
}
cout << endl;
return matrix[i][j];
}
Here is the main function, where I attempt to assign actual parameters for the matrix and pass them to the matrix display. The main function specifically defines a variable āpā which (the plan is anyway) to use this variable to cause a shift to the right.
I am using the modulo 13 operator to attempt to clear (or return to 0) values after the shift, so the 1 appears to move across the matrix
In addition to the functions above, I have included the last bits from my code which are essentially notes and ideas that I am attempting now.
/*
int array_size = sizeof(matrix) / sizeof(matrix[0]);
for (i = 0; i < 8; i++)
{
for (j = array_size-1; j > 0; j--)
{
matrix[j] = matrix[j - 1];
}
matrix[0]=
cout << "\n";
}
}
*/
/*
int x = i;
int p = (j + 3) % 13;
int matrix(x, p);
return 0;
*/
thanks in advance for any help or guidance :)
Okay, I am pulling out all my hair on this one, though, as a noob, I am sure there are several problems. I want to take a matrix and, by sing elementary row operations, reduced it to row-reduced echelon form. We assume (1) it is solvable and (2) a unique solution. There is no checking for zeros or anything; it just does row operations. Here is the code:
#include <iostream>
#include <cstdlib>
using namespace std;
void printmatrix(float A[][4]);
void RowReduce (float A[][4]);
int main() {
// answer should be { 2, 4, -3 }
float A[3][4] = {
{ 5, -6, -7, 7 },
{ 3, -2, 5, -17 },
{ 2, 4, -3, 29 }
};
printmatrix(A);
RowReduce(A);
}
// Outputs the matrix
void printmatrix(float A[][4]) {
int p = 3;
int q = 4;
for (int i = 0; i < p; i++) {
for (int j = 0; j < q; j++) {
cout << A[i][j] << " ";
}
cout << endl;
}
}
void RowReduce (float A[][4]){
//rows
int p = 3;
//columns
int q = 4;
// the determines the column we are at which holds the diagonal,
// the basis for all elimination above and below
int lead = 0;
cout << endl;
while ( lead < q - 1 ) {
// for each row . . .
for (int i = 0; i < p; i++) {
// ignore the diagonal, and we will not have a tree rref
// as the diagonal will not be divided by itself. I can fix that.
if ( i != lead ) {
cout << A[lead][lead] << " " << A[i][lead];
for (int j = 0; j < q; j++) {
//here is the math . . . . probably where the problem is?
A[i][j] = A[lead][lead] * A[i][j];
A[i][lead] = A[i][lead] * A[lead][j];
A[i][j] = A[i][j] - A[i][lead];
}
cout << endl;
}
}
// now go to the next pivot
lead++;
cout << endl;
}
}
I tried doing it by hand, but what I get is, of course, the right answer, but this gets a diagonal matrix--which is great--but the wrong answer!
The main error in you code is that you are calculating the divisor or multiplier within the for loop. You should calculate them before iterating over the cells.
Hint: debugging is easier if the code is well formated and the variables have meaningful names.
See the implementation of RowReduce():
#include <iostream>
#include <cstdlib>
#include <iomanip>
using namespace std;
void printmatrix(float A[][4]);
void RowReduce(float A[][4]);
int main()
{
float A[3][4] = {{5, -6, -7, 7},
{3, -2, 5, -17},
{2, 4, -3, 29}}; //answer should be {2, 4, -3}
printmatrix(A);
RowReduce(A);
}
void printmatrix(float A[][4]) // Outputs the matrix
{
int p=3;
int q=4;
for (int i=0; i<p; i++) {
for (int j=0; j<q; j++) {
cout << setw(7) << setprecision(4) << A[i][j] << " ";
}
cout << endl;
}
cout << endl;
}
void RowReduce(float A[][4])
{
const int nrows = 3; // number of rows
const int ncols = 4; // number of columns
int lead = 0;
while (lead < nrows) {
float d, m;
for (int r = 0; r < nrows; r++) { // for each row ...
/* calculate divisor and multiplier */
d = A[lead][lead];
m = A[r][lead] / A[lead][lead];
for (int c = 0; c < ncols; c++) { // for each column ...
if (r == lead)
A[r][c] /= d; // make pivot = 1
else
A[r][c] -= A[lead][c] * m; // make other = 0
}
}
lead++;
printmatrix(A);
}
}
The output:
5 -6 -7 7
3 -2 5 -17
2 4 -3 29
1 -1.2 -1.4 1.4
0 1.6 9.2 -21.2
0 6.4 -0.2 26.2
1 0 5.5 -14.5
0 1 5.75 -13.25
0 0 -37 111
1 0 0 2
0 1 0 4
0 0 1 -3
I'm trying to find all possible solutions to the 3X3 magic square.
There should be exactly 8 solutions.
My code gets them all but there are a lot of repeats. I'm having a hard time tracking the recursive steps to see why I'm getting all the repeats.
// This program finds all solutions to the magic square for a 3X3
// square where each column, row and diagonal sum is equal
#include <iostream>
using namespace std;
#define SQUARE_SIZE 9
int anyLine = 0;
int currLine = 0;
int numSolutions = 0;
// swap two values in the square.
void swap(int arr[], int idxa, int idxb)
{
int tmp = arr[idxa];
arr[idxa] = arr[idxb];
arr[idxb] = tmp;
}
void printArray(int arr[])
{
for (int i = 0; i < SQUARE_SIZE; i++)
{
cout << arr[i] << " ";
if ((i + 1) % 3 == 0)
cout << endl;
}
cout << endl;
}
// this function tests to see if we have a "good" arrangement of numbers
// i.e the sum of each row, column and diagonal is equal
bool checkArr(int arr[])
{
anyLine = arr[0] + arr[1] + arr[2];
currLine = 0;
for (int i = 0; i < SQUARE_SIZE; i++)
{
currLine += arr[i];
if ((i + 1) % 3 == 0)
{
if (currLine != anyLine)
return false;
currLine = 0;
}
}
// check vertically
for (int col = 0; col <3; col++)
{
for (int row = 0; row <3; row++)
{
currLine += arr[col + 3 * row];
}
if (currLine != anyLine)
return false;
currLine = 0;
}
// check the diagonals
if ((arr[2] + arr[4] + arr[6]) != anyLine)
return false;
if ((arr[0] + arr[4] + arr[8]) != anyLine)
return false;
return true;
}
void solve(int arr[], int pos)
{
if (pos == 8)
{
if (checkArr(arr))
{
printArray(arr);
numSolutions++;
}
} else
{
for (int i = 0; i < 9; i++)
{
if (i == pos) continue;
if (checkArr(arr))
{
printArray(arr);
numSolutions++;
}
swap(arr, pos, i);
solve(arr, pos + 1);
}
}
}
int main()
{
int arr[SQUARE_SIZE] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
solve(arr, 0);
cout << "number of solutions is: " << numSolutions << endl;
return 0;
}
Basically, you are finding all permutations of the array using a recursive permutation algorithm.
There are 4 things you need to change:
First, start your loop from pos, not 0
Second, swap elements back after recursing (backtracking)
Third, only test once you have generated each complete permutation (when pos = 8), or else you will be testing the same permutations more than once.
Fourth, swapping an element with itself (i.e. not swapping it) is a valid permutation, because the elements are allowed to stay in their original positions.
void solve(int arr[], int pos)
{
if (pos == 8)
{
if (checkArr(arr))
{
printArray(arr);
numSolutions++;
}
}
else
{
for (int i = pos ; i < 9; i++)
{
swap(arr,pos,i);
solve(arr,pos +1);
swap(arr,pos,i);
}
}
}
Demo
Your code calls printArray from two places - the base case of the recursion (i.e. when pos == 8) and in the loop before calling swap. The second call is unnecessary: you would get the same square when you reach the pos == 8 state.
This brings the number of duplicates down, but it does not eliminate them because of the way in which you generate your squares. You need to keep track of what has been printed. One way to do it is to make a set of solutions that you have found, and check it before printing the newly found solution:
set<int> seen;
int key(int arr[]) {
return arr[0]
+ 10 * arr[1]
+ 100 * arr[2]
+ 1000 * arr[3]
+ 10000 * arr[4]
+ 100000 * arr[5]
+ 1000000 * arr[6]
+ 10000000 * arr[7]
+ 100000000 * arr[8];
}
void printArray(int arr[]) {
if (!seen.insert(key(arr)).second) {
// second is set to false when a duplicate is found
return;
}
numSolutions++;
for (int i = 0; i < SQUARE_SIZE; i++) {
cout << arr[i] << " ";
if((i+1) % 3 == 0)
cout << endl;
}
cout << endl;
}
Demo.
A few things to note about the solution above:
key(int[]) converts the square to a single decimal number, so this approach is going to work only for squares composed of decimal digits. You would need a different strategy for arbitrary numbers - for example, using a set of comma-separated strings.
Counting of solutions is moved to printArray(int[]). You could drop numSolutions altogether, and use seen.size() instead; it provides the same answer.
If you don't want to actually solve this recursively for exercise purposes, I'd recommend using std::next_permutation:
void solve(int(&arr)[SQUARE_SIZE], int pos)
{
sort(std::begin(arr), std::end(arr));
do {
if (checkArr(arr)) {
numSolutions++;
printArray(arr);
}
} while (next_permutation(begin(arr), end(arr)));
}