Problem
Given a matrix consisting of nos you can print the max length of sequence possible where in a sequence each consecutive nos have a diff of +1 or -1.
Ex :
3 5 7 3
4 5 8 1
6 4 5 2
here sequence is
3
4 5
4 5
Solution
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
void DisplayMatrix(int* mat, int rows, int cols, string msg)
{
cout << msg << endl;
for(int i = 0; i < rows; ++i){
for(int j = 0; j < cols; ++j){
cout << mat[i * cols + j] << " ";
}
cout << endl;
}
cout << endl;
}
void FindMaxSeq(int* seq, int len)
{
int maxLen = 1;
int maxIdx = 0;
int curLen = 1;
int curIdx = 0;
for(int i = 1; i < len; ++i){
if(abs(seq[i] - seq[i-1]) == 1){
curLen ++;
if(curLen > maxLen){
maxLen = curLen;
maxIdx = curIdx;
}
}
else{
curIdx = i;
curLen = 1;
}
}
for(int i = maxIdx; i < maxIdx + maxLen; ++i){
cout << setw(3) << seq[i];
}
cout << endl;
}
int main(int argc, char* argv[])
{
int arr[][5] = {
{3, 5, 7, 3, 1},
{4, 5, 4, 8, 1},
{6, 4, 5, 2, 1},
{1, 3, 2, 3, 2},
{2, 3, 2, 3, 3}
};
DisplayMatrix((int *)arr, sizeof(arr)/sizeof(arr[0]),
sizeof(arr[0])/sizeof(arr[0][0]), "Array: ");
for(int i = 0; i < sizeof(arr)/sizeof(arr[0]); ++i){
FindMaxSeq(arr[i], sizeof(arr[0])/sizeof(arr[0][0]));
}
return 0;
}
Output
Array:
3 5 7 3 1
4 5 4 8 1
6 4 5 2 1
1 3 2 3 2
2 3 2 3 3
3
4 5 4
4 5
3 2 3 2
2 3 2 3
Press any key to continue . . .