Shift contents of array using parameters in C++ - c++

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 :)

Related

How do I print out the value that make magic square?

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++

Print the array value which can produce the input by using addition operator

How do I edit the given program to get all possible combinations of array values which will provide the given data using addition operator?
The following code works fine only if there is only one combination. For example, in the array = {1,2,3,4,5}, the given value = 6; the only possibility is the sum of 2 and 4. Thus the output desired is array [1] & array[3]. Attached coding works fine for this. But for array ={1, 3, 3, 4, 2}, there is two possibilities but the code returns nothing...
#include<iostream>
using namespace std;
int main() {
int n = 5; int m = 0;
int givendata;
int a[n];
for (int i = 0; i < n; i++) {
cin >> a[i];
}
cin >> givendata;
if (m < n) {
for (int i = 0; i < n; i++) {
int sum = a[n - i] + a[m];
if (sum == givendata) {
cout << m << " " << n - i;
}
}
}
m = m + 1;
return 0;
}
You need to use a double loop to compare all the values:
// start at 0, the first position of the array. Loop until the 2nd to last element
for (int i=0; i<n-1;i++)
{
// start this index at one higher than i. Since a+b == b+a, there's no need to
// add the later values in the array with the previous ones, we've already
// done that
for (int j=i+1; j<n; j++)
{
int sum = a[i]+a[j];
if (sum == givendata)
{
std::cout << a[i] << " + " << a[j] << " = " << givendata << std::endl;
}
}
}
Demonstration
Also see Why is "using namespace std;" considered bad practice?

writing values to an array from another array excluding unwanted values c++

For context, I can't use anything that isn't taught in csc101 (what you learned may have been different) so I can't use things like vectors, structs, and classes. More context, I have an assignment which requests I have a function which takes an array numarray with random values, and removes the values from 20 to 40. As I understand it, the best way to do that is to make a new array and take the valid values from numarray and put them in a new array temparray. I tried implementing this the best way I could figure up, but it seems to only spit out a set number which is a long negative number over and over in a loop. I know it is this function because when not called I don't have a problem. The problem also doesn't occur if I comment out the while loop at the end of the function. I will first attach the function in question, and then the whole of the program for added context. Open to any criticism, but passing the class is my priority over elegance, and efficiency. If the professor wants something done a certain way, I must oblige. Thanks for your time.
The required function:
void Delete(int* numarray, int *temparray) {
int arrayindex = 0;
for (int index = 0; index < 100; index++) {
if (numarray[index] < 20 && numarray[index] > 40) {
temparray[arrayindex] = numarray[index];
} arrayindex++;
}
cout << arrayindex << endl;
cout << temparray[arrayindex] << endl;
while (arrayindex <! 0) {
cout << temparray[arrayindex - 1] << endl;
}
}
The whole project:
#include <iostream>
#include <fstream>
#include <time.h>
#include <stdlib.h>
#include <cstddef>
#include <array>
using namespace std;
ofstream randomData;
ifstream inputrandomData;
void randomgenerator();
void read(int *numarray);
void printArray(int *numarray);
void searchArray(int* numarray);
void Delete(int* numarray, int* temparray);
void randomgenerator() {
srand(time(0));
randomData.open("randomData.txt");
for (int counter = 0; counter < 100; counter++) {
randomData << rand() % 100+1 << endl;
}
randomData.close();
}
void read(int *numarray) {
inputrandomData.open("randomData.txt");
for (int i = 0; i < 100; i++) {
inputrandomData >> numarray[i];
}
inputrandomData.close();
}
void printArray(int *numarray) {
for (int index = 0; index < 100; index++) {
cout << numarray[index] << endl;
}
}
void searchArray(int* numarray) {
int searchedArray[6] = {};
for (int index=0; index < 100; index++) {
if (numarray[index] > searchedArray[0]) {
searchedArray[0] = numarray[index];
searchedArray[1] = index;
}
}
for (int index = 0; index < 100; index++) {
if (numarray[index] > searchedArray[2] && numarray[index] < searchedArray[0]) {
searchedArray[2] = numarray[index];
searchedArray[3] = index;
}
}
for (int index = 0; index < 100; index++) {
if (numarray[index] > searchedArray[4] && numarray[index] < searchedArray[2]) {
searchedArray[4] = numarray[index];
searchedArray[5] = index;
}
}
cout << "Largest Number: " << searchedArray[0] << " " << "Index: " << searchedArray[1] << endl;
cout << "Second Largest Number: " << searchedArray[2] << " " << "Index: " << searchedArray[3] << endl;
cout << "Third Largest Number: " << searchedArray[4] << " " << "Index: " << searchedArray[5] << endl;
}
void Delete(int* numarray, int *temparray) {
int arrayindex = 0;
for (int index = 0; index < 100; index++) {
if (numarray[index] < 20 && numarray[index] > 40) {
temparray[arrayindex] = numarray[index];
} arrayindex++;
}
cout << arrayindex << endl;
cout << temparray[arrayindex] << endl;
while (arrayindex <! 0) {
cout << temparray[arrayindex - 1] << endl;
}
}
int main() {
int numarray[100] = {};
int temparray[100] = {};
randomgenerator();
read(numarray);
printArray(numarray);
searchArray(numarray);
Delete(numarray, temparray);
return 0;
}
Here was the solution I was prompted to come up with. There were a couple logical flaws.
First, my conditional would never be true as I used the && operator which means the number would have to be lower than 20 AND greater than 40. Changed that to || operator to check for one or the other. Then, as stated in the comments, I had been overthinking it by creating another array. You have to have two different index counters in order to read from the original data set, and to write the new data set in behind it. Now, when ran, the numarray takes values at the numarray[arrayindex] which is only incremented when the conditional is called, and reads from numarray[index] which increments on every for loop. Here is the edited function below:
void Delete(int* numarray) {
int arrayindex = 0;
for (int index = 0; index < 100; index++) {
if (numarray[index] < 20 || numarray[index] > 40) {
numarray[arrayindex] = numarray[index];
arrayindex++;
}
}
cout << arrayindex << endl;
for (int newindex = 0; newindex < arrayindex; newindex++) {
cout << numarray[newindex] << endl;
}
}
I removed temparray from the program entirely. Thanks for the help.
You can break up the problem into many pieces at first so that it is easier to program and understand. If you're struggling, keep splitting up the task into smaller simpler functions, like this:
// remove a range of values from arr
void remove_range(int *arr, int size, int from, int to) {
for (int r = from; r <= to; r++) {
remove_all(arr, size, r);
}
}
// remove all of a single value from arr
void remove_all(int *arr, int size, int value) {
for (int i = 0; i < size; i++) {
if (arr[i] == value) {
remove_one(arr, size, value);
}
}
}
// remove the first occurrence of a value from arr
void remove_one(int *arr, int size, int value) {
for (int i = 0; i < size; i++) {
if (arr[i] == value) {
remove_i(arr, size, value);
}
}
}
// remove the value at an index of arr by shifting all the entries after it left one
// and putting a 0 at the end in case this is the first removal
void remove_i(int *arr, int size, int i) {
for (; i < size - 1; i++) {
arr[i] = arr[i + 1];
}
arr[i] = 0;
}
If I'm understanding your project correctly, you have the following main objectives:
Without using std::vector or other classes/structs, copy an array into another
The copied-to array must not contain values from 20-40 (assuming inclusive)
With that in mind, there are some other things you may want to keep in mind. For example, does speed or memory matter more?
If speed matters more, you can create an array (named copy_to) with equal size of copy_from array. Then, just test every value in copy_from to make sure it's not within [20, 40] before copying it to copy_to. However, If memory management matters more, not only would I do everything from the "speed" method, but I would also keep track of how many elements are being added to copy_to. After they are copied, make a new array (copy_to_final) of the exact size needed, copy copy_to to copy_to_final, and delete copy_to.
Here's what the code would look like for the speed method:
int* make_prejudice_array(int[] copy_from, size_t size)
{
// Make array to store new values in
int* copy_to = new int[size];
size_t copy_to_size = 0;
// Copy valid values into 'copy_to'
for (size_t i = 0; i < size; ++i)
{
if (copy_from[i] < 20 || copy_from[i] > 40)
{
copy_to[copy_to_size] = copy_from[i];
copy_to_size++;
}
}
return copy_to;
}
And, for the memory management way, just a small addition:
int* make_prejudice_array(int[] copy_from, size_t size)
{
int* copy_to = new int[size];
size_t copy_to_size = 0;
for (size_t i = 0; i < size; ++i)
{
if (copy_from[i] < 20 || copy_from[i] > 40)
{
copy_to[copy_to_size] = copy_from[i];
copy_to_size++;
}
}
// Make new array to hold the exact number of elements needed
int* copy_to_final = new int[copy_to_size];
for (size_t i = 0; i < copy_to_size; ++i)
copy_to_final[i] = copy_to[i];
// Don't forget to delete 'copy_to' to prevent a mem leak
delete[] copy_to;
copy_to = nullptr;
return copy_to_final;
}
If I missed something from your question. Let me know and I'll do my best to incorporate it. Hope that helps!

Generate numbers from 2 to 10,000. The numbers printed can only be a multiple of 2 prime numbers

Homework: I'm just stumped as hell. I have algorithms set up, but I have no idea how to code this
Just to be clear you do not need arrays or to pass variables by reference.
The purpose of the project is to take a problem apart and using Top-Down_Design or scratch pad method develop the algorithm.
Problem:
Examine the numbers from 2 to 10000. Output the number if it is a Dual_Prime.
I will call a DualPrime a number that is the product of two primes. Ad where the two primes are not equal . So 9 is not a dual prime. 15 is ( 3 * 5 ) .
The output has 10 numbers on each line.
My Algorithm set-up
Step 1: find prime numbers.:
bool Prime_Number(int number)
{
for (int i = 2; i <= sqrt(number); i++)
{
if (number % 1 == 0)
return false;
}
return true;
}
Step 2: store prime numbers in a array
Step 3: Multiply each array to each other
void Multiply_Prime_Numbers(int Array[], int Size)
{
for (int j = 0; j < Size- 1; j++)
{
Dual_Prime[] = Arr[j] * Arr[j + 1]
}
}
Step 4: Bubble sort
void Bubble_Sort(int Array[], int Size) // Sends largest number to the right
{
for (int i = Size - 1; i > 0; i--)
for (int j = 0; j < i; j++)
if (Array[j] > Array[j + 1])
{
int Temp = Array[j + 1];
Array[j + 1] = Array[j];
Array[j] = Temp;
}
}
Step 5: Display New Array by rows of 10
void Print_Array(int Array[], int Size)
{
for (int i = 0; i < Size; i++)
{
cout << Dual_Prime[i] << (((j % 10) == 9) ? '\n' : '\t');
}
cout << endl;
}
I haven't learned dynamic arrays yet,
Although dynamic arrays and the sieve of Eratosthenes are more preferable, I tried to write minimally fixed version of your code.
First, we define following global variables which are used in your original implementation of Multiply_Prime_Numbers.
(Please check this post.)
constexpr int DP_Size_Max = 10000;
int DP_Size = 0;
int Dual_Prime[DP_Size_Max];
Next we fix Prime_Number as follows.
The condition number%1==0 in the original code is not appropriate:
bool Prime_Number(int number)
{
if(number<=1){
return false;
}
for (int i = 2; i*i <= number; i++)
{
if (number % i == 0)
return false;
}
return true;
}
In addition, Multiply_Prime_Numbers should be implemented by double for-loops as follows:
void Multiply_Prime_Numbers(int Array[], int Size)
{
for (int i = 0; i < Size; ++i)
{
for (int j = i+1; j < Size; ++j)
{
Dual_Prime[DP_Size] = Array[i]*Array[j];
if(Dual_Prime[DP_Size] >= DP_Size_Max){
return;
}
++DP_Size;
}
}
}
Then these functions work as follows.
Here's a DEMO of this minimally fixed version.
int main()
{
int prime_numbers[DP_Size_Max];
int size = 0;
for(int j=2; j<DP_Size_Max; ++j)
{
if(Prime_Number(j)){
prime_numbers[size]=j;
++size;
}
}
Multiply_Prime_Numbers(prime_numbers, size);
Bubble_Sort(Dual_Prime, DP_Size);
for(int i=0; i<DP_Size;++i){
std::cout << Dual_Prime[i] << (((i % 10) == 9) ? '\n' : '\t');;
}
std::cout << std::endl;
return 0;
}
The Sieve of Eratosthenes is a known algorithm which speeds up the search of all the primes up to a certain number.
The OP can use it to implement the first steps of their implementation, but they can also adapt it to avoid the sorting step.
Given the list of all primes (up to half the maximum number to examine):
Create an array of bool as big as the range of numbers to be examined.
Multiply each distinct couple of primes, using two nested loops.
If the product is less than 10000 (the maximum) set the corrisponding element of the array to true. Otherwise break out the inner loop.
Once finished, traverse the array and if the value is true, print the corresponding index.
Here there's a proof of concept (implemented without the OP's assignment restrictions).
// Ex10_TwoPrimes.cpp : This file contains the 'main' function. Program execution begins and ends there.
#include "pch.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void Homework_Header(string Title);
void Do_Exercise();
void Sieve_Of_Eratosthenes(int n);
void Generate_Semi_Prime();
bool Semi_Prime(int candidate);
bool prime[5000 + 1];
int main()
{
Do_Exercise();
cin.get();
return 0;
}
void Do_Exercise()
{
int n = 5000;
Sieve_Of_Eratosthenes(n);
cout << endl;
Generate_Semi_Prime();
}
void Sieve_Of_Eratosthenes(int n)
{
// Create a boolean array "prime[0..n]" and initialize
// all entries it as true. A value in prime[i] will
// finally be false if i is Not a prime, else true.
memset(prime, true, sizeof(prime));
for (int p = 2; p*p <= n; p++)
{
// If prime[p] is not changed, then it is a prime
if (prime[p] == true)
{
// Update all multiples of p
for (int i = p * p; i <= n; i += p)
prime[i] = false;
}
}
}
bool Semi_Prime(int candidate)
{
for (int index = 2; index <= candidate / 2; index++)
{
if (prime[index])
{
if (candidate % index == 0)
{
int q = candidate / index;
if (prime[q] && q != index)
return true;
}
}
}
return false;
}
void Generate_Semi_Prime()
{
for (int i = 2; i <= 10000; i++)
if (Semi_Prime(i)) cout << i << "\t";
}

How to extract the indexes of the cells in the same diagonal of a 2D matrix C++

As stated above, I am trying to get the elements of a 2D matrix using only C++
The matrix has MxN dimensions, and it may be so that N!=M, N >= M or M < N (basically the dimensions can be anything and are determined in execution time)
I have tried to go about it using 2 nested for loops but so far the code just keeps getting more & more complex & does not produce consistent results.
Visual aid:
I am trying to get the 2nd for loop to iterate through the colored cells of the matrix starting from top left - i.e. in every loop the amount/position of the cells that the 2nd loop iterates through keeps changing & I am starting to wonder whether this can be done at all given that N & M are not known on compile time.
Thanks for your time in advance.
~EDIT1:
Here is what the iteration of the elements would look like for a non square matrix (same thing applies if the rows where more than the columns)
~EDIT2:
Here is the code so far: (testable!)
#include <iostream>
#include <string>
#include <stdio.h>
using namespace std;
void func(void);
// use these variables to specify the dimensions arbitrarily
// keep in mind I need this to work with relatively big matrices
int row = 5, col = 5;
string arr[][10]= {{"0", "0", "0", "0", "0", "0", "0", "0", "0", "0" },
{"0", "1,1", "1,2", "1,3", "1,4", "1,5", "1,6", "1,7", "1,8", "1,9" },
{"0", "2,1", "2,2", "2,3", "2,4", "2,5", "2,6", "2,7", "2,8", "2,9" },
{"0", "3,1", "3,2", "3,3", "3,4", "3,5", "3,6", "3,7", "3,8", "3,9" },
{"0", "4,1", "4,2", "4,3", "4,4", "4,5", "4,6", "4,7", "4,8", "4,9" },
{"0", "5,1", "5,2", "5,3", "5,4", "5,5", "5,6", "5,7", "5,8", "5,9" },
{"0", "6,1", "6,2", "6,3", "6,4", "6,5", "6,6", "6,7", "6,8", "6,9" },
{"0", "7,1", "7,2", "7,3", "7,4", "7,5", "7,6", "7,7", "7,8", "7,9" },
{"0", "8,1", "8,2", "8,3", "8,4", "8,5", "8,6", "8,7", "8,8", "8,9" },
{"0", "9,1", "9,2", "9,3", "9,4", "9,5", "9,6", "9,7", "9,8", "9,9" } };
bool f = false, f2 = false;
int main (void)
{
func();
return 0;
}
void func(void)
{
if(row < col)
{
//remember that row > col
f = true;
}
unsigned short m_i; //mask for the counter of the outer for loop (i) - counts how many times the
unsigned short j_end = 1; //stores the max number of iterations the inner loop should do - increments accordingly
unsigned short k = 1; //stores the starting index of the inner loop - starts incrementing once (j_end == col)
cout << "row = " << row << ", col = " << col << endl;
cout << "total \"i\" loops " << (row + col -1) << endl << endl;
for (unsigned short i=1; i<=row + col -1; i++) // row + col -1 is the total number of diagonals in any matrix
{ // and also the total number of iterations we need
if( i > row) // here I implement the row > col scenario, the rest should be similar
{
m_i = row; // the mask should never go above the max row number
}else if(i == row)
{
m_i = row;
if (f = true) f2 = true; // using f2 remember that we've reached the max number for rows
}else{
m_i = i; // (i < row) so just pass i
}
for(unsigned short j=k; j<=j_end; j++){
cout<< arr[m_i][j]<<" ";
if(m_i > 1){
m_i--;
}else{
m_i = 1;
}
}
cout<<endl<< "*************" << endl;
if(j_end == col )
{
k++; // increment starting index of inner loop
}else{
j_end++; // max number for inner loop not yet achieved so increment max number
}
if(m_i == row)
{
k++;
}
} // end outer loop
} // end func
You can use this code to test it for yourself the output should be something like this:
And you can change the row & col values to test for different dimensions.
So far I believe this code works for square matrices, but not so much when row != col
~EDIT3:
func() should take performance into consideration as I said before I expect the matrices to be quite large!
for( int manhattan_distance = 0; manhattan_distance < M + N - 1; ++manhattan_distance )
{
for( int i = 0; i <= manhattan_distance; ++i )
{
int j = manhattan_distance - i;
if( j < N && i < M )
{
...
}
}
}
Code:
#include <vector>
#include <utility>
#include <iostream>
int main() {
int n, m;
std::cin >> n >> m;
std::vector<std::pair<int, int> > result;
for (int k = 0; k < m; k++) {
int i = 0, j = k;
while (i < n && j >= 0)
{
result.push_back({ i, j });
i++;
j--;
}
}
for (int k = 1; k < n; k++) {
int i = k, j = m - 1;
while (i < n && j >= 0)
{
result.push_back({ i, j });
i++;
j--;
}
}
return 0;
}
Explanations:
If you look at the picture, you can see that diagonal is when you move i + 1 and j - 1. Until the first half, we start from the first row and try to go in direction specified. When we hit the end, we just go to the next column. Basically, every iteration we are just changing the starting point. The second part is a bit trickier, because we already traversed some of the lines, so we start from 1 (because we already traversed first row. Then applying the same direction as in the first half, we traverse the rest of the matrix.
You can do it like this:
void foo(int rows,int cols){
// first go vertically down
for (int start_row = 0;start_row<rows;start_row++){
int col = 0;
int row = start_row;
while (col < cols && row >= 0){
std::cout << row << "," << col << " ";
row--;
col++;
}
std::cout << std::endl;
}
// now horizantally
for (int start_col = 0;start_col<cols;start_col++){
int col = start_col;
int row = rows-1;
while (col < cols && row >= 0){
std::cout << row << "," << col << " ";
row--;
col++;
}
std::cout << std::endl;
}
}
It might be possible to write it more compact, but it works.
OK I got an answer for this, all thought its not refined.
It is working properly but it is not optimized.
EDIT: c#... did not see it was for c++, but the idea is the same
using System;
Random r = new Random();
int rows = r.Next(10,13); // or any range of rows
int cols = r.Next(10,20); // same applies
int[,] matrix = new int[rows,cols];
// mark upper diagonal
for(var i=0; i<= cols; i++)
markByCol(i,0,cols-i);
// mark lower diagonal
for(var i=1; i<= rows; i++)
markByCol(cols+1+i,i,cols-1);
// stringify matrix to view it properly
string line = string.Empty;
for(int i=0; i< rows; i++)
{
line = string.Empty;
for(int j=0; j< cols; j++)
{
line+= matrix[i,j]+" | ";
}
Console.WriteLine(line);
}
// the actual function
int markByCol(int marker,int row,int col){
if((row > -1 && row < rows) && (col > -1 && col < cols))
{
matrix[row,col] = marker;
return markByCol(marker,row+1,col-1);
}
else
return 0;
}
Here is a jsFiddle. just hit play. This implementation marks each diagonal with a specific integer so you can scan and categorize each cell by its value, in terms of which diagonal crosses it.
https://dotnetfiddle.net/Qy8J1O