HOW to compare all the elements of a matrix in C++? - c++

I've been trying for like a week, and i've found nothing that can help me out. Does someone know how to do it?
I need to compare each elements matrix and have an affirmative expression if there are not repeated numbers; and negative expression if there are repeated numbers.
my matrix is 3*3
THANK YOU SO MUCH

if you want to check if all elements of the matrix are equal you can try this code
int matrix[3][3];
int testMatrix(int* m, int size)
{
for(int i = 0; i < size * size; i++)
{
for(int j = i + 1; j < size * size; j++)
if(m[i] == m[j])
return -1;
}
return 1;
}
And use it like this:
testMatrix(&matrix[0][0], 3);
In memory your 3x3 matrix is looks the same as just array of 9 elements

Related

How do I fill the contents of a matrix using 9 other matrixes?

I am creating a sudoku game
I have 9 3x3 matrixes and a large 9x9 matrix. The methods I tried didn't work so please help me:
void matrix_full_creation()
{
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
matrix_full[i][j]==matrix1[i][j];
matrix_full[i][j+3]=matrix2[i][j];
matrix_full[i][j+6]=matrix3[i][j];
matrix_full[i+3][j]=matrix4[i][j];
matrix_full[i+3][j+3]=matrix5[i][j];
matrix_full[i+3][j+3]=matrix6[i][j];
matrix_full[i+6][j]=matrix7[i][j];
matrix_full[i+6][j+3]=matrix8[i][j];
matrix_full[i+6][j+6]=matrix9[i][j];
}
}
}
Given a submatrix index n, and a pair of indexes within that submatrix, i.e. row index i and column index j, and
considering you want to place each submatrix at positions (0,0), (0,1)..., (3,3) of the full matrix,
you can walk each cell of each submatrix, and
use the following formula to calculate the destination cell in the full matrix:
matrix_full[3*(n / 3) + i][3*(n % 3) + j] = submatrix[i][j];
[Demo]
Let's break your task into smaller pieces.
First, write a function that copies your small matrix into specific position
void Copy(int** small, int i, int j);
So if you pass 0, 0 for i, j... It should copy contents of small into top left 3x3 submatrix of the big 9x9 matrix.
When you complete this task, just run a for loop (similar to the one you already did)
int** bigMatrix; // assume we have it here
void Copy(int** small, int i, int j) {
for(int ii = 0; ii < 3; ++ii) {
for(int jj = 0; jj < 3; ++jj) {
bigMatrix[i + ii][j + jj] = small[ii][jj];
}
}
}
int main() {
int smalls[3][3][3] = {...}; // assume we have 3x3 init here
for(int i = 0; i < 9; i += 3) {
for(int j = 0; j < 9; j += 3) {
Copy(smalls[0], i, j];
}
}
return 0;
}
Good tip: divide and conquer!
I have corrected your code. Try this:
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
matrix_full[i][j]=matrix1[i][j];
matrix_full[i][j+3]=matrix2[i][j];
matrix_full[i][j+6]=matrix3[i][j];
matrix_full[i+3][j]=matrix4[i][j];
matrix_full[i+3][j+3]=matrix5[i][j];
matrix_full[i+3][j+6]=matrix6[i][j];
matrix_full[i+6][j]=matrix7[i][j];
matrix_full[i+6][j+3]=matrix8[i][j];
matrix_full[i+6][j+6]=matrix9[i][j];
}
}
Hope this helps! :D

How find parallel diagonal reverse at other diagonal in matrix 2D in C++

I have a problem to manage a two-dimensional matrix nxn in C++. My problem is create a function that control if exists any diagonal, parallel line at the principal diagonal, that is reverse to other. I controlled the two index, necessary for the rows and columns, if are different and maybe I could help me with support arrays, which reverse the elements. Perhaps it's not a good idea with a huge matrix(such as 8x8, 14 arrays) so, I am asking your help.
Thanks
This is my code:
bool funct(short **M, int rows, int columns){
bool found = false;
for(int i = 0; i < rows; i++){
for(int j = 0; j < colums; j++){
if(i != j){
//control the reverse array
}
}
}
}
ps: my primary problem is general algorithm(nxn).
In a quadratic matrix, every diagonal has exactly one other diagonal with the same length (except the principal diagonal). So you just need to check this one:
for(int diagonal = 1; diagonal < cols - 1; ++diagonal)
{
//inspect the diagonal that starts at (0, diagonal)
//the other diagonal starts at (diagonal, 0)
int diagonalLength = cols - diagonal;
//Assume that this diagonal has a reverse counterpart
bool diagonalHasReverse = true;
//Now check if it really has
for(int i = 0; i < diagonalLength; ++i)
{
if(M[i][diagonal + i] !=
M[diagonal + diagonalLength - 1 - i][diagonalLength - 1 - i])
{
diagonalHasReverse = false;
break;
}
}
//do whatever you want with diagonalHasReverse
}
The outer loop does not process the very last (one-element) diagonal. If you want to include that, you have to modify the loop as follows:
for(int diagonal = 1; diagonal < cols; ++diagonal)

Trouble calculating product of upper triangular matrix using 1-D array (c++)

I'm trying to multiply two upper triangular matrices together. The matrices are stored in single dimensional arrays instead of the usual 2-D arrays by omitting the zeros that would be under the diagonal (to conserve space). I've figured out how to map elements given a pair of indices to the index for the single array. but I'm having trouble with the actual calculation (The calculation works for smaller n x n square matrices, but for some reason gives incorrect results for larger n x n matrices). I believe that I might be passing in incorrect parameters to the getValue() function, but I think they should be right considering the general formula for matrix multiplication. Any help will be appreciated!
Here's my relevant code:
// mat is an array containing the upper triangle data for a square matrix of size n
// returns element at (i,j), or 0 for the lower triangle
int val(int *mat, int n, int i, int j)
{
if (i > j) {
return 0; // lower triangle
} else {
return mat[j + (i*n) - i*(i+1)/2];
}
}
user101263,
You might not want to map your 2D array into a 1D array for simplification, beacuse in reality, it just complicates the simple matrix-multiplication algorithm.
Here is an implementation of the MM algorithm:
int main()
{
int[5][5] result;
/* omitted: create your 2 2D arrays a & b */
matrixMulitplcation(a,b, result)
}
int** matrixMultiplcation(int a[5][5], int b[5][5], result[5][5])
{
for(int R=0;R<5;R++)
{
for(int C=0;C<5;C++)
{
result[R][C]=0;
for(int T=0;T<5;T++)
result[R][C]+=a[R][T]*b[T][C];
}
}
return result;
}
Please let me know if you have any questions!
for(int i = 0; i < n; i++)
{
for(int j = 0; j < m; j++)
{
for(int k = 0;k < n; k++)
{
C[ij_to_k(i,j,n)] += A[ij_to_k(i,k,n)] * B[ij_to_k(k,j,n)];
}
}
}
Just create the ij_to_k() function and you are good to go.

Return the count of negative numbers in the optimal way

A variation of "Searching in a Matrix that is sorted rowwise and columnwise"
Given a 2D Matrix that is sorted rowwise and columnwise. You have to return the count of negative numbers in most optimal way.
I could think of this solution
initialise rowindex=0
if rowindex>0 rowindex++
else apply binary search
And implemented in with this code for 5X5 matrix
#include<iostream>
#include<cstdio>
using namespace std;
int arr[5][5];
int func(int row)
{
int hi=4;
int lo=0;
int mid=(lo+hi)/2;
while(hi>=lo)
{
mid=(lo+hi)/2;
.
if(mid==4)
{
return 5;
}
if(arr[row][mid]<0 && arr[row][mid+1]<0)
{
lo=mid+1;
}
else if(arr[row][mid]>0 && arr[row][mid+1]>0)
{
hi=mid-1;
}
else if(arr[row][mid]<0 && arr[row][mid+1]>0)
{
return mid+1;
}
}
}
int main()
{
int ri,ci,sum;
ri=0; //rowindex
ci=0; //columnindex
sum=0;
for(int i=0; i<5; i++)
{
for(int j=0; j<5; j++)
{
cin>>arr[i][j];
}
}
while(ri<5)
{
if(arr[ri][ci]>=0)
{
ri++;
}
else if(arr[ri][ci]<0)
{
int p=func(ri);
sum+=p;
ri++;
}
}
printf("%d\n",sum);
}
I ran the code here http://ideone.com/PIlNd2
runtime O(xlogy) for a matrix of x rows and y columns
Correct me if i am wrong in time complexity or implementation of code
Does anyone have any better idea than this to improve Run-time complexity?
O(m+n) algorithm, where m and n are the dimensions of the array, working by sliding down the top of the negative portion, finding the last negative number in each row. This is most likely what Prashant was talking about in the comments:
int negativeCount(int m, int n, int **array) {
// array is a pointer to m pointers to n ints each.
int count = 0;
int j = n-1;
for (int i = 0, i < m; i++) {
// Find the last negative number in row i, starting from the index of
// the last negative number in row i-1 (or from n-1 when i==0).
while (j >= 0 && array[i][j] >= 0) {
j--;
}
if (j < 0) {
return count;
}
count += j+1;
}
return count;
}
We can't do better than worst-case O(m+n), but if you're expecting far fewer than m+n negative numbers, you may be able to get a better usual-case time.
Suppose you have an n by n array, where array[i][j] < 0 iff i < n-j. In that case, the only way the algorithm can tell that array[i][n-1-i] < 0 for any i is by looking at that cell. Thus, the algorithm has to look at at least n cells.
You are conducting a binary search. Whereby you divide n by 2 to find the midpoint then continue to divide, before returning a value. That looks like a binary search, even though you are dividing columns for each row. Therefore, you are performing O(log n). Or something like O(x log n/y).

sum of squares matrices

I want to do a function that given 2 matrix returns the sum of both.I think the problem is in how I initialize the Matrix 't'.
#include <iostream>
#include <vector>
using namespace std;
typedef vector< vector<int> > Matrix;
Matrix sum(const Matrix&a,const Matrix&b){
Matrix t;
for(int i=0;i<a.size();i++)
for(int j=0;j<a.size();j++)
t[i][j] = a[i][j] + b[i][j];
return t;
}
You'll need to initialize the rows and columns of t with something like:
Matrix t = vector< vector<int> >(row_count, vector<int>(col_count, 0));
That will make a row_count by col_count matrix filled with zeroes.
On a side note about performance: comparing to .size() in a for loop means that before each iteration, .size() has to be calculated again. You can save a bit of processing (which adds up for massive data sets) by pre-calculating it like so:
for (int row = 0, row_ct = mat.size(); row < row_ct; ++row)
You don't have a rectangular data set in general: each a[i] is a vector of a possibly different length. Supposing you do in fact take care to have a rectangular grid, your for loop is still off; it should be like this:
for (int i = 0; i < a.size(); i++)
{
assert(a.size() <= b.size() && a.size() <= t.size());
for (int j = 0; j < a[i].size(); j++) // !!
{
assert(a[i].size() <= b[i].size() && a[i].size() <= t[i].size());
t[i][j] = a[i][j] + b[i][j];
}
}
I added some assertions to indicate which preconditions you have to satisfy.
To initialize a rectangular array, you can do something like this:
std::vector<std::vector<int>> v(n_rows, std::vector<int>(n_cols, 0));