i'm trying to figure out how to fill a multidimentional array in this way:
Input: rows = 3 , cols = 3 :
1 4 7
2 5 8
3 6 9
can somebody give me an idea?
P.S My task is to find how many nubers stay in the same position in both arrangements. Ex:
1 4 7 1 2 3
2 5 8 4 5 6
3 6 9 7 8 9
so the numbers that are in the same position are : 1 5 9.
i've tryied :
//n = 3 , m = 3
for(int i = 0; i <n; i++) {
for(int j = 0; j <m; j++){
if(array[i][j] == array2[i][j]) {
lol++;
}
}
}
cout<<lol;
/*
1 2 3
4 5 6
7 8 9
1 4 7
2 5 8
3 8 9
*/
it must show me 3 , but it shows 0, where is the problem?
Populate at initialization:
int a[3][3] = { { 1, 4, 7},
{ 2, 5, 8},
{ 3, 6, 9}
};
EDIT (unsure if resolved):
After update to question here is an example application that (with modification to accept input from user) will diff two arrays and construct an array indicating the elements that were the same and a count of the number of identical elements:
#include <iostream>
int** make_array(const size_t a_rows, const size_t a_columns)
{
int** result = new int*[a_rows];
for (size_t i = 0; i < a_rows; i++)
{
*(result + i) = new int[a_columns];
}
return result;
}
void print_array(int** a_array, const size_t a_rows, const size_t a_columns)
{
for (size_t r = 0; r < a_rows; r++)
{
for (size_t c = 0; c < a_columns; c++)
{
std::cout << *(*(a_array + r) + c) << " ";
}
std::cout << "\n";
}
std::cout << "\n";
}
int main()
{
// Example data.
int a[3][3] = { { 1, 4, 7},
{ 2, 5, 8},
{ 3, 6, 9}
};
int b[3][3] = { { 1, 2, 3},
{ 4, 5, 6},
{ 7, 8, 9}
};
size_t rows = 3;
size_t columns = 3;
// Create three arrays:
// - two input arrays
// - array that represents which elements are the same
int** in_1 = make_array(rows, columns);
int** in_2 = make_array(rows, columns);
int** diff = make_array(rows, columns);
// Populate with example data.
for (size_t r = 0; r < rows; r++)
{
for (size_t c = 0; c < columns; c++)
{
*(*(in_1 + r) + c) = a[r][c];
*(*(in_2 + r) + c) = b[r][c];
}
}
// Diff.
// The 'diff' array will hold '1' for elements that
// were the same and '0' for elements that were not.
size_t same_count = 0;
for (size_t r = 0; r < rows; r++)
{
for (size_t c = 0; c < columns; c++)
{
*(*(diff + r) + c) = *(*(in_1 + r) + c) == *(*(in_2 + r) + c);
same_count += *(*(diff + r) + c);
}
}
std::cout << "\n";
// Results.
print_array(in_1, rows, columns);
print_array(in_2, rows, columns);
print_array(diff, rows, columns);
std::cout << "Same element count: " << same_count << "\n";
// Free...
return 0;
}
Output:
$ ./cpp/main.exe
1 4 7
2 5 8
3 6 9
1 2 3
4 5 6
7 8 9
1 0 0
0 1 0
0 0 1
Same element count: 3
Create a dynamically allocated array if you only know the dimensions at runtime:
int** x = new int*[rows];
for ( int i = 0 ; i < rows ; i++ )
x[i] = new int[cols];
And then populate it:
for ( int i = 0 ; i < rows ; i++ )
for ( int j = 0 ; i < cols ; j++ )
x[i][j] = y;
Or better yet, use a vector of vectors, this will give you more flexibility:
std::vector<std::vector<int> > x;
A simple solution would be this:-
int k = 1;
for(int i = 0; i < row; i++){
for(int j = 0; j < col; j++){
a[j][i] = k; // filling it in the column first order
++k;
}
}
Related
Given this 3x3(nxm) matrix, how can I traverse and get the sum of all possible square-submatrices i.e(1x1,2x2 in this particular case)
2 2 3
3 4 5
4 5 5
I know here,
every element is an individual submatrix(1x1),
and the rest square-submatrices are as follow:
2 2
3 4
2 3
4 5
3 4
4 5
4 5
5 5
I've tried my approach and failed multiple times, the main reason is I get confused with matrices in programming.
My Approach:
Here, 'l' is size of square-sub matrix, 'n' size of rows of main matrix, 'm' size of cols of main matrix,
for (i=0; i<n-l; i++){
for (j=1; j<n-i+1; j++){
sum = 0;
for (p=i; p<l+i; p++){
for (q=1; q<l+j+1; q++){
sum += a[p][q];
}
}
cout << sum << endl;
}
l++;
}
This is the solution of your case.
for(int i=0; i+(l-1)<n; i++){
for(int j=0; j+(l-1)<m; j++){
int sum = 0;
for(int a=0; a<l; a++){
for(int b=0; b<l; b++){
sum += matrix[i+a][j+b];
}
}
cout << sum << endl;
}
}
or you can try to run the full code on Tio.run
I rewrote your code to make it correct, also made full example:
Try it online!
#include <vector>
#include <algorithm>
#include <iostream>
int main() {
std::vector<std::vector<int>> a = {{2, 2, 3}, {3, 4, 5}, {4, 5, 5}};
size_t n = a.size(), m = a.size() > 0 ? a[0].size() : 0;
for (size_t l = 1; l <= std::min(n, m); ++l)
for (size_t i = 0; i < n - l + 1; ++i)
for (size_t j = 0; j < m - l + 1; ++j) {
int sum = 0;
for (size_t p = i; p < i + l; ++p)
for (size_t q = j; q < j + l; ++q)
sum += a[p][q];
std::cout << l << ", " << i << ", " << j << ": " << sum << std::endl;
}
}
Input:
2 2 3
3 4 5
4 5 5
Output:
1, 0, 0: 2
1, 0, 1: 2
1, 0, 2: 3
1, 1, 0: 3
1, 1, 1: 4
1, 1, 2: 5
1, 2, 0: 4
1, 2, 1: 5
1, 2, 2: 5
2, 0, 0: 11
2, 0, 1: 14
2, 1, 0: 16
2, 1, 1: 19
3, 0, 0: 33
I'm stuck on this. Could you please help me?
Write a function which initialize a two-dimensional array. The array is a square
matrix (i.e., its width and height are identical.) The array should be initialized in the
zig-zag style. Specifically, we start at the top-left corner and go downward, and put a
number starting from 1. Once we hit the bottom, we go to the next column and fill in
the numbers from bottom to top. We fill the numbers downward in the third
column, upward in the fourth column, and so on. The process ends when all the
elements in the array are filled.
However, How do I get my output like this?
1 10 11 20 21
2 9 12 19 22
3 8 13 18 23
4 7 14 17 24
5 6 15 16 25
#include <iomanip>
#include <iostream>
using namespace std;
const int SIZE = 5; // Note SIZE can be anything between 1 to 9
void initGrid(int grid[SIZE][SIZE]);
void printGrid(int grid[SIZE][SIZE]);
int main() {
int grid[SIZE][SIZE];
initGrid(grid);
printGrid(grid);
}
void initGrid(int grid[SIZE][SIZE]) {
int inc = 1;
for (int j = 0; j < SIZE; j++) {
for (int i = 0; i < SIZE; i++) {
grid[i][j] = inc;
inc++;
}
}
}
void printGrid(int grid[SIZE][SIZE]) {
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
// setw() function handles the printing format.
cout << setw(2) << grid[i][j] << " ";
}
cout << endl;
}
}
Every two columns of the grid share the same filling pattern, the odd ones are filled in ascending order, the even ones in descending order. All you have to do is translate that into code:
template<size_t Rows, size_t Cols>
void initGrid(int (&grid)[Rows][Cols]) {
int value = 1;
for (size_t j = 0; j < Cols; ++j) {
// first fill the odd column in descending order
for (size_t i = 0; i < Rows; ++i, ++value) {
grid[i][j] = value;
}
// then, if there is one, fill the even column
++j;
if (j == Cols )
break;
for (size_t i = Rows; i > 0; ++value) {
--i; // size_t is unsigned, so I have to check i before decrementing
grid[i][j] = value;
}
}
}
I used the same data structure you used (but a different function signature) only to focus on the algorithm, but I'd use a class instead.
If you don't want to traverse the array column-wise (which, for big arrays, could result in performance drop due to cache misses) you can calculate the differences between values in every row:
template<size_t Rows, size_t Cols>
void zig_zag_fill(int (&grid)[Rows][Cols])
{
int diff_up = 1;
int diff_down = Rows * 2 - 1;
for (size_t i = 0; i < Rows; ++i, diff_down -= 2, diff_up += 2)
{
int value = i + 1;
size_t j = 0;
while ( j < Cols )
{
grid[i][j] = value;
value += diff_down;
++j;
if ( j == Cols )
break;
grid[i][j] = value;
value += diff_up;
++j;
}
}
}
A complete test program like this:
#include <iostream>
#include <iomanip>
template<size_t Rows, size_t Cols>
void zig_zag_fill(int (&grid)[Rows][Cols]);
template<size_t Rows, size_t Cols>
void printGrid(int (&grid)[Rows][Cols]);
int main() {
int grid[5][6];
zig_zag_fill(grid);
printGrid(grid);
std::cout << '\n';
int grid2[6][5];
zig_zag_fill(grid2);
printGrid(grid2);
std::cout << '\n';
int grid3[5][5];
zig_zag_fill(grid3);
printGrid(grid3);
std::cout << '\n';
int grid4[6][6];
zig_zag_fill(grid4);
printGrid(grid4);
std::cout << '\n';
}
template<size_t Rows, size_t Cols>
void initGrid(int (&grid)[Rows][Cols]) {
int value = 1;
for (size_t j = 0; j < Cols; ++j) {
for (size_t i = 0; i < Rows; ++i, ++value) {
grid[i][j] = value;
}
++j;
if (j == Cols )
break;
for (size_t i = Rows; i > 0; ++value) {
--i;
grid[i][j] = value;
}
}
}
template<size_t Rows, size_t Cols>
void zig_zag_fill(int (&grid)[Rows][Cols])
{
int diff_up = 1;
int diff_down = Rows * 2 - 1;
for (size_t i = 0; i < Rows; ++i, diff_down -= 2, diff_up += 2)
{
int value = i + 1;
size_t j = 0;
while ( j < Cols )
{
grid[i][j] = value;
value += diff_down;
++j;
if ( j == Cols )
break;
grid[i][j] = value;
value += diff_up;
++j;
}
}
}
template<size_t Rows, size_t Cols>
void printGrid(int (&grid)[Rows][Cols]) {
for (size_t i = 0; i < Rows; ++i) {
for (size_t j = 0; j < Cols; ++j) {
std::cout << std::setw(2) << grid[i][j] << " ";
}
std::cout << '\n';
}
}
Would output:
1 10 11 20 21 30
2 9 12 19 22 29
3 8 13 18 23 28
4 7 14 17 24 27
5 6 15 16 25 26
1 12 13 24 25
2 11 14 23 26
3 10 15 22 27
4 9 16 21 28
5 8 17 20 29
6 7 18 19 30
1 10 11 20 21
2 9 12 19 22
3 8 13 18 23
4 7 14 17 24
5 6 15 16 25
1 12 13 24 25 36
2 11 14 23 26 35
3 10 15 22 27 34
4 9 16 21 28 33
5 8 17 20 29 32
6 7 18 19 30 31
Firstly, if I was writing this program I would represent my data in a different manner. I.e. I would likely use a vector and avoid global size constants. The being said, here is how I would do this. Let's write out the sequence the indexes follow and try to see if we can create some kind of sequence.
1 4 7
2 5 8
3 6 9
Is what is in your array after creating it and we want
1 6 7
2 5 8
3 4 9
Our indexes to the original array looks like this
(0, 0) (2, 1) (0, 2)
(1, 0) (1, 1) (1, 2)
(2, 0) (0, 1) (2, 2)
Well our j component is easy, it's just a simple arithmetic sequence where you add 1, i.e. 1, 2, 3, 4, 5...
for (int j = 0; j < 3; j++){
...
}
Now we need a sequence that follows the patten 0, 1, 2, 2, 1, 0, 0, 1, 2, ... repeating. Since we have repeating digits, I am thinking of clock arithmetic or modular arithmetic. Let's start with the sequence 0, 1, 2, 0, 1, 2 ... repeating. I.e the integers mod 3 (Z mod 3). For the first column we want the indicies straight up as they are (Z mod 3). Then for the reversed columns let's say we are given this sequence and we are iterating through it from 0 to 2. We can cleverly use modular arithmetic to get to our reversed sequence. For example if we had (2 mod 3), (4 mod 3), (6 mod 3), we would have 2, 1, 0. How do we get 0, 1, 2 to 2, 4, 6? Like this f(x) : (x + 1) * 2.
bool reversed = false;
for (int i = 0; i < 3; i++){
int idx = i;
if(reversed){
int offset = (i + 1) * 2;
idx = (offset) % 3;
}
}
reversed = !reversed;
Now we just have to put it all together. This should be our new init grid as the print function is fine.
for (int j = 0; j < SIZE; j++){
bool reversed = false;
for (int i = 0; i < SIZE; i++){
int idx = i;
if(reversed){
int offset = (i + 1) * (SIZE - 1);
idx = (offset) % SIZE;
}
arr[idx][j] = inc;
inc++;
}
reversed = !reversed;
}
That should do it. I got it to work in repl.it, hopefully this helps.
I have a loop in each iterate an array is printed. now I need this array so I want to put them in a 2 dimension vector. I wrote this code but I dont know why it does not work!
when I run it does not print any thing and it dont show any error!
int main() {
int i, u;
const int j = 9;
vector<vector<int>> V;
int B[9] = {};
for (int r = 0; r<10; r++) {
B[r] = 1;
for (int t = 0; t<V.size(); t++) {
for (int w = 0; w<j; w++, u++) {
V[t][w] = B[u];
}
}
}
for (int m = 0; m<V.size(); m++) {
for (int k = 0; k<j; k++) {
cout << "V=" << " " << V[m][k];
}
}
return 0;
}
For example in the first loop in each iterate B changes and I want to store all of them in a matrix! for example I have:
first iterate: B=(1,0,0)
second iterate: B=(0,1,0)
third iterate: B=(0,0,1)
now I want to have:
V={{1,0,0},{0,1,0},{0,0,1}}
Let's say that you have N int[N] values, and you want 1 vector<vector<int>> value.
std::vector<int> fromArray(int (&B)[N])
{
return { std::begin(B), std::end(B) };
}
This is a function that will turn a 1D array into a 1D vector. you will need to call it N times.
std::vector<std::vector<int>> fromArrays(int (&Bs)[N][N])
{
std::vector<std::vector<int>> result{ N };
std::transform(std::begin(Bs), std::end(Bs), result.begin(), fromArray);
return result;
}
Here we take a 2D array and turn it into a 2D vector. This requires you have all the Bs together.
int main()
{
constexpr int N = 3;
std::vector<std::vector<int>> V;
for (int i = 0; i < N; ++i)
{
int B[N] = {};
B[i] = 1;
V.emplace_back(fromArray(B));
}
for (std::vector<int> & v : V)
{
for (int i : v)
{
std::cout << i << " ";
}
std::cout << "\n";
}
return 0;
}
Alternately, if you don't have all the Bs all in one go, just loop N times getting one B
If guessing, there is a my implementation:
int main() {
int len = 9;
int div = 3;
int total = len / div;
int B[len]={1, 0, 0, 0, 1, 0, 0, 0, 1};
vector<vector<int> > V(total);
int cnt = 0;
for (int i = 0; i < len && cnt < total; i += div) {
for (int j = i; j < i + div; j++) {
V[cnt].push_back(B[j]);
}cnt++;
}
for (int i = 0; i < total; i++) {
for (int j = 0; j < V[i].size(); j++) {
cout << V[i][j] << " ";
}cout << endl;
}
return 0;
}
V is like this:
1 0 0
0 1 0
0 0 1
You probably want this:
int main() {
const int Bsize = 9;
const int NumberOfLines = 4; // number of iterations
int B[Bsize] = { 1,2,3,4,5,6,7,8,9 };
vector<vector<int>> V;
V.resize(NumberOfLines);
int bIndex = 0;
for (int r = 0; r < NumberOfLines; r++) {
// add code that changes B here
V[r].resize(Bsize);
for (int w = 0; w < Bsize; w++) {
V[r][w] = B[w];
}
}
for (int m = 0; m < V.size(); m++) {
for (int k = 0; k < V[m].size(); k++) {
cout << " " << V[m][k];
}
cout << endl;
}
return 0;
}
In this sample we'll generate 4 lines (one for each iteration), but B is each time the same here. If you want B to change between each iteration, you need to insert the corresponding code that changes B.
The output of the sample will be:
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
I am trying to transpose a 4 by 5 matrix to a 5 by 4 matrix. This is what I have done so far:
#include <stdio.h>
void transposeMatrix(int A2[4][5],int A1[5][4])
{
int i, j;
for (i = 0; i < 5; ++i){
for (j = 0; j < 4; ++j)
A1[j][i]=A2[i][j];
}
}
int main(void)
{
int A2[4][5] = {
{ 7, 4, 2, 1, 12 },
{ 4, 6, 22, 11, 6 },
{ 12, 10, 3, 1, 2 },
{ 20, 4, 1, 3, 4 },
};
int A1[5][4];
int i, j;
printf("Original matrix:\n ");
for (i = 0; i < 4; ++i){
for (j = 0; j < 5; ++j)
printf("%5i", A2[i][j]);
printf("\n");
}
printf("Transposed matrix:\n");
transposeMatrix(A2, A1);
for (i = 0; i < 5; ++i){
for (j = 0; j < 4; ++j)
printf("%5i", A1[i][j]);
printf("\n");
}
return 0;
}
When I run my code, this is what I get:
Original matrix:
7 4 2 1 12
4 6 22 11 6
12 10 3 1 2
20 4 1 3 4
Transposed matrix:
7 4 12 20
-858993460 6 10 4
998952744 22 3 1
11599080 11 1 3
10495049-858993460-858993460-858993460
It looks like it only transposes the first row. What am I doing wrong?
You have one error in your code.
It is an index problem in the transpose function.
for (i = 0; i < 5; ++i){
for (j = 0; j < 4; ++j)
A1[i][j]=A2[j][i];
}
and not A1[j][i]=A2[i][j].
I've seen several questions here that don't quite answer my question. I'm trying to do a rendition of the classic matrix rotation question used so often in interview questions. Instead of focusing on the square matrix, I'm interested in M x N matrices.
For input matrix
1 2 3
4 5 6
7 8 9
1 2 3
I'd like to transform the matrix into
3 2 1
9 8 7
6 5 4
3 2 1
Here is the code I've written:
#include <iostream>
#include <vector>
#include <algorithm>
void do_swaps(int& a, int& b, int& c, int& d) {
std::swap(a, b);
std::swap(c, d);
}
void rotate(std::vector<std::vector<int>>& v) {
size_t m = v.size();
size_t n = v[0].size();
for(size_t i = 0; i < m/2; ++i) {
for(size_t j = 0; j <= n/2; ++j) {
do_swaps(v[i][j], v[m-i-1][n-j-1], v[m-j-1][i], v[j][n-i-1]);
}
}
}
void print(const std::vector<std::vector<int>>& v) {
size_t m = v.size();
size_t n = v[0].size();
for(size_t i = 0; i < m; ++i) {
for(size_t j = 0; j < n; ++j) {
std::cout << v[i][j] << ' ';
}
std::cout << '\n';
}
}
int main() {
std::vector<std::vector<int>> m{{1,2,3}, {4,5,6}, {7,8,9}, {1, 2, 3}};
std::cout << "Before: \n";
print(m);
rotate(m);
std::cout << "\nAfter: \n";
print(m);
}
And here's my output:
Before:
1 2 3
4 5 6
7 8 9
1 2 3
After:
3 2 1
9 5 7
6 8 4
3 2 1
My code works for 3 x 3 matrices (haven't tested higher dimensional matrices), but I seem to have an off by one error in my code causing the inner-most elements to remain unswapped.
In the line for(size_t j = 0; j <= n/2; ++j) {, I've tried adjusting the stop condition to several things including j < (n+1)/2; and j < (n-1)/2;, but it remains the same.
Can someone explain where I've gone wrong in my algorithm?
You don't take care of middle line in case when lines number is odd.
Further, you swap elements that lie on the middle column (when columns number is odd) twice. You can check if m is odd with a bitwise-and with 1.
The following is an easier way to project swapped values is presented above and you don't even have to care about the middle column in this case.
void rotate(std::vector<std::vector<int>>& v) {
size_t m = v.size();
size_t n = v[0].size();
for (size_t i = 0; i < m / 2; ++i)
{
for (size_t j = 0; j < n; ++j)
std::swap(v[i][j], v[m - i - 1][n - j - 1]);
}
if (m&1)
for (size_t i = 0; i< n/2; ++i)
std::swap(v[m/2][i], v[m/2][n-i-1]);
}
I would use mirror x and then mirror y or vice versa. It is in-place and safe for any resolution (even/odd). So first swap all rows and then all columns (or vice versa). Here some code for this.
void rotate(std::vector<std::vector<int>>& v) {
size_t m= v.size();
size_t n=v[0].size();
for(size_t i=0;i<m;i++) {
for(size_t j=0,k=n-1;j<k;j++,k--) {
std::swap(v[i][j],v[i][k]);
}
}
for(size_t j=0;j<n;j++) {
for(size_t i=0, k=m-1; i<k; i++, k--) {
std::swap(v[i][j],v[k][j]);
}
}
}
A pythonish way (not in place):
d = (1, 2, 3), (4, 5, 6), (7, 8, 9), (1, 2, 3)
[r[::-1] for r in d[::-1]]