Sunday, September 29, 2019

C++: Print matrix in counter-clockwise spiral form

We are given a matrix of any dimension and we need to print the matrix elements in counter clockwise direction.


void counterClockspiralPrint(int R, int C, int mat[][MAX]) {
int row = 0, col = 0;
int m = R, n = C;
while(row < m && col < n) {
for(int i= row; i < m ; i++)
cout<<mat[i][col]<<" ";
col++;
for(int i = col; i< n-1; i++)
cout<<mat[m-1][i]<<" ";
m--;
for(int i = m; i >= row; i--)
cout<<mat[i][n-1]<<" ";
n--;
for(int i = n-1; i >= col; i--)
cout<<mat[row][i]<<" ";
row++;
}
}
int main()
{
int R = 3;
int C = 4;
int mat[][MAX] = {{ 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 } };
counterClockspiralPrint(R, C, mat);
return 0;
}
Output: 1 5 9 10 11 12 8 4 3 2 6 7

C++: Find all the unique elements in a matrix

We are given a matrix of any dimension and wee need to print all the elements that are unique i.e appearing only once. So here is the c++ code for the algorithm.

#include <bits/stdc++.h>
using namespace std;
#define R 4
#define C 4
void uniqueElement(int mat[][MAX]){
map<int, int> cnt;
for(int i=0; i<R; i++){
for(int j=0; j<C; j++) {
cnt[mat[i][j]]++;
}
}
cout<<"The unique elements in the matrix are "<<endl;
for(auto i: cnt){
if(i.second == 1)
cout<<i.first<<" ";
}
}
int main()
{
int mat[][MAX] = { {2, 1, 4, 3},
{1, 2, 3, 2},
{3, 6, 2, 3},
{5, 2, 5, 9} };
uniqueElement(mat);
return 0;
}
Output:
The unique elements in the matrix are 4 6 9

Explanation:

First, in the 'main' function, we create the matrix 'mat' of size 4 with 16 elements. Then we call the function 'uniqueElement' with the matrix 'mat' as the parameter. Note, at the top of the program, we have defined R(row) as 4 and C(col) as 4.

In the function 'uniqueElement', we first declare a map 'cnt' of integer type. Then we loop through all the elements of the matrix and increment the frequency of all the elements using 'cnt[mat[i][j]++'. After the loop, all the elements in the matrix will be mapped to its corresponding frequency.

After this, we loop through the map 'cnt' and print the elements with frequency 1.

Thursday, September 26, 2019

C++: Turn a matrix by 180 degree.

We are given a matrix of any dimension and we need to turn it by 180 degree. Here is the source code for the algorithm in c++.


#include <bits/stdc++.h>
using namespace std;
#define R 3
#define C 4
void printMatrix(int mat[][S]);
void turnOneEighty(int mat[R][C]) {
int row = 0, m = R-1;
while(row < m) {
for(int i=0; i < C; i++)
swap(mat[row][i], mat[m][C-1-i]);
row++;
m--;
if(row == m) {
int col = 0, n = C-1;
while(col < n)
swap(mat[row][col++], mat[row][n--]);
}
}
cout<<"\n\nMatrix turned 180 degree "<<endl;
printMatrix(mat);
}
int main() {
int mat[R][C] = { {1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12} };
cout<<"\nOriginal matrix is "<<endl;
printMatrix(mat);
turnOneEighty(mat);
return 0;
}
Output:  12  11  10  9
               8    7    6   5
               4    3    2    1
             

Wednesday, September 25, 2019

C++: Print a Matrix in Spiral Form

We are given a matrix of any dimension, say 3x3, 4x4 or 4x3, and we are required to print the elements of the matrix in spiral form.


#include <bits/stdc++.h>
using namespace std;
#define R 3
#define C 4
void printMatrixSpiral(int m, int n, int mat[R][C]) {
int row = 0, col = 0;
while(row<m && col<n) {
for(int i=col; i<n; i++) {
cout<<mat[row][i]<<" ";
}
row++;
for(int i = row; i<m; i++) {
cout<<mat[i][n-1]<<" ";
}
n--;
if(row<m) {
for(int i=n-1; i>=col; i--){
cout<<mat[m-1][i]<<" ";
}
}
m--;
if(col<n) {
for(int i= m-1; i>=row; i--) {
cout<<mat[i][col]<<" ";
}
}
col++;
}
}
int main() {
int mat[R][C] = {{1, 2, 3, 4},
{5, 6, 7,8},
{9, 10, 11, 12}
};
printMatrixSpiral(R, C, mat);
return 0;
}
Output: 1 2 3 4 8 12 11 10 9 5 6 7

C++: Rotate Matrix to the right.

Given a square matrix and we need to write a program to rotate the matrix to the right. Here is the code for the program.

#include <bits/stdc++.h>
using namespace std;
#define R 4
#define C 4
void rotateMatrix(int m, int n, int mat[R][C]) {
int row = 0, col =0;
int curr, prev;
while(row<m && col<n) {
if(row+1 == m || col+1 == n)
break;
prev = mat[row+1][col];
for(int i= col; i<n; i++) {
curr = mat[row][i];
mat[row][i] = prev;
prev = curr;
}
row++;
for(int i=row; i<m; i++) {
curr = mat[i][n-1];
mat[i][n-1] = prev;
prev = curr;
}
n--;
if(row<m) {
for(int i= n-1; i>=col; i--) {
curr = mat[m-1][i];
mat[m-1][i] = prev;
prev = curr;
}
}
m--;
if(col<n){
for(int i=m-1; i>=row; i--) {
curr = mat[i][col];
mat[i][col] = prev;
prev = curr;
}
}
col++;
}
for(int i=0; i<R; i++) {
for(int j=0; j<C; j++)
cout<<mat[i][j]<<" ";
cout<<endl;
}
}
int main() {
int mat[R][C] = {{1,2,3,4}, {5,6,7,8}, {9,10,11,12}, {13,14,15,16}};
rotateMatrix(R,C,mat);
return 0;
}
Output:
5    1    2    3
9    10   6    4
13   11   7    8
14   15   16   12


Saturday, September 21, 2019

C++: Find common elements in three sorted arrays.

We are given three sorted arrays and we need to find the elements that are common to the three arrays.

#include <iostream>
using namespace std;
bool binarySearch(int arr[], int l, int r, int key) {
if(l>r)
return false;
int mid = l + (r-l)/2;
if(arr[mid] == key)
return true;
if(key < arr[mid])
return binarySearch(arr, l, mid-1, key);
return binarySearch(arr, mid+1, r, key);
}
void findCommon(int ar1[], int ar2[], int ar3[], int n1, int n2, int n3) {
for(int i = 0; i<n1; i++) {
if(binarySearch(ar1, 0, n1-1, ar1[i])
&& binarySearch(ar2, 0, n2-1, ar1[i])
&& binarySearch(ar3, 0, n3-1, ar1[i]))
cout<<ar1[i]<<" ";
}
}
int main()
{
int ar1[] = {1, 5, 10, 20, 40, 80};
int ar2[] = {6, 7, 20, 80, 100};
int ar3[] = {3, 4, 15, 20, 30, 70, 80, 120};
int n1 = sizeof(ar1)/sizeof(ar1[0]);
int n2 = sizeof(ar2)/sizeof(ar2[0]);
int n3 = sizeof(ar3)/sizeof(ar3[0]);
cout << "Common Elements are ";
findCommon(ar1, ar2, ar3, n1, n2, n3);
return 0;
}
Output: 20 80

Here we use binary search to check if the element is present in the array or not. We iterate only the first array and check if each element in the first array is present in other two arrays. The function 'binarySearch()' returns 'true' if the element is found in any of the array and at last if all the three arrays does contain the element, then that element is printed.

Thursday, September 12, 2019

C++: Find the second largest element in an array

In this tutorial, we will see how to find the second largest element in an array. There are different ways to do it- like sorting the array first in descending order and then printing the second element or by double iteration- first for finding the largest element and second for finding the number just less than the largest. But there is one way to find the second largest element just in single iteration. Here is the code for the program.


#include<iostream>
#include<climits>
using namespace std;
int secondLargest(int arr[], int n) {
int first = INT_MIN;
int second = INT_MIN;
for(int i = 0; i<n; i++) {
if(arr[i]>first) {
second = first;
first = arr[i];
}
if(arr[i]<first && arr[i]>second) {
second = arr[i];
}
}
return second;
}
int main() {
int arr[] = {8,5,6,8,3,4,9,1,2};
int n = sizeof(arr) / sizeof(arr[0]);
cout<<"The second largest element is "<<secondLargest(arr, n);
return 0;
}
Output: The second largest element is 8.

Saturday, September 7, 2019

C++: Rearrange and array in maximum, minimum form

We are given a sorted array and we want to rearrange the array in the form of {max, min, max-1, min+1, max-2, min+2.........}. So here is the code:


#include<iostream>
using namespace std;
void printArray(int arr[], int n);
void maxMin(int arr[], int n) {
int arr2[n];
int mid = n/2;
for(int i = 0,j = n-1, k =0; i< mid, j>=mid, k<n; k++) {
if(k%2 != 0) {
arr2[k] = arr[i];
i++;
}
else {
arr2[k] = arr[j], j-- ;
}
}
printArray(arr2, n);
}
void printArray(int arr[], int n) {
for(int i = 0; i< n; i++) {
cout<<arr[i]<<" ";
}
}
int main() {
int arr[] = {1,2,3,4,5,6,7};
int n = sizeof(arr)/sizeof(arr[0]);
maxMin(arr, n);
return 0;
}
view raw maxmin.cpp hosted with ❤ by GitHub
Output: {7,1,6,2,5,3,4}

C++: Make the largest number from the array of elements.

Here is a C++ program where you are given an array of numbers. Append each element one after another in a way that the resulting number is the largest possible number you can make out of all the given array elements.


#include<iostream>
#include<vector>
#include<string>
#include <bits/stdc++.h>
using namespace std;
void printArray(int arr[], int n);
void rearrangeArray(int arr[], int n);
long append(int arr[], int n);
bool firstDigitLarger(int a, int b);
bool firstDigitLarger(int a, int b) {
int aFirst, bFirst, digit1, digit2;
while(a != 0) {
digit1 = a;
a /= 10;
}
aFirst = digit1;
while(b != 0) {
digit2 = b;
b /= 10;
}
bFirst = digit2;
return aFirst > bFirst;
}
long append(int arr[], int n) {
string appended;
for(int i = 0; i<n; i++) {
std::string base = std::to_string(arr[i]);
appended += base;
}
return std::stol(appended);
}
void rearrangeArray(int arr[], int n) {
sort(arr, arr+n, greater<int>());
sort(arr, arr+n, firstDigitLarger);
}
void printArray(int arr[], int n) {
for(int i = 0; i< n; i++) {
cout<<arr[i]<<" ";
}
}
int main() {
int arr[] = {546,548,60,9,696};
int n = sizeof(arr)/sizeof(arr[0]);
rearrangeArray(arr,n);
cout<<append(arr,n);
return 0;
}
view raw append.cpp hosted with ❤ by GitHub
Output: 969660548546

Tuesday, September 3, 2019

C++: Reverse an array.

In this tutorial, we will see how we can reverse an array in C++. So here goes the code:


#include<iostream>
using namespace std;
void reverseArray(int arr[], int n);
void printArray(int arr[], int n);
void reverseArray(int arr[], int n) {
int l = 0; int r = n-1;
while(l != r && l<r) {
swap(arr[l++], arr[r--]); }
}
void printArray(int arr[], int n) {
for(int i = 0; i<n; i++) {
cout<<arr[i]<<" "; }}
int main(){
int arr[] = {1,2,3,4,5,6,7,8,9};
int n = sizeof(arr)/sizeof(arr[0]);
cout<<"Original Array: ";
printArray(arr, n);
cout<<"\nReversed Array: ";
reverseArray(arr, n);
printArray(arr, n);
return 0;
}

Here when the 'reverseArray' function is called, it takes in the array and its size as the parameter. After that we set 'l' as left index and 'r' as right index. The while loop starts swapping the array with given indices, where the 'l' increases and 'r' decreases after each iteration. Thus when they reach the middle index two things happen:

 1. If n is odd, the array has a mid point which is (n/2+1). In that case l=r and the loop stops.
 2. If n is even, the array does not have a middle point, so we give the condition 'l<r' inside the while loop, so that the 'l' index does not increment after 'r'.


Output:

Original Array: 1,2,3,4,5,6,7,8,9.
Reversed Array: 9,8,7,6,5,4,3,2,1.


Monday, September 2, 2019

C++: Finding a pair with given sum in an array.

In this programming tutorial, we will read an unsorted array, sort it, and then will find the pair with the given sum.

We maintain a search space in the while loop with 'l' for left index and 'r' for right index. 'l' and 'r' will increment or decrements respectively depending on the sum of the pairs being tested inside the 'while' loop.

Given below is the source code for the algorithm:


#include<iostream>
#include<algorithm>
using namespace std;
void sumPair(int arr[], int n, int sum);
void sumPair(int arr[], int n, int sum) {
std::sort(arr, arr+n);
int l = 0;
int r = n-1;
while( l < r){
if(arr[l]+arr[r] == sum){
cout<<"The pair is "<<arr[l]<<" and "<<arr[r]<<endl;
return;
}
(arr[l]+arr[r] < sum) ? l++: r--;
}
cout<<"The pair with given sum is not found"<<endl;}
int main(){
int arr[] = {5,3,4,6,2,7,1,8,9};
int n = sizeof(arr)/sizeof(arr[0]);
int sum = 10;
sumPair(arr, n, sum);
return 0;
}
view raw find_pair.cpp hosted with ❤ by GitHub