AD1

Saturday, 23 September 2017

Count pairs with given sum

Problem :

Solution :

#include <iostream>
using namespace std;
int main()
{
int T;
cin>>T;
for(int i=0;i<T;i++)
{
int N,K;
int counter=0;
cin>>N>>K;
int array[N];
for(int j=0;j<N;j++)
{
cin>>array[j];
}
for(int m=0;m<N-1;m++)
{
for(int l=m+1;l<N;l++)
{
if(array[m]+array[l]==K)
{
counter++;
}
}
}
cout<<counter<<endl;
}
return 0;
}
view raw pairs.cpp hosted with ❤ by GitHub

Monday, 18 September 2017

Matrix Transpose

Given a 2D array A, your task is to convert all rows to columns and columns to rows.
Input:
First line contains 2 space separated integers, N - total rows, M - total columns.
Each of the next N lines will contain M space separated integers.
Output:
Print M lines each containing N space separated integers.
Constraints:
1N10
1M10
0A[i][j]100 where 1iN and 1jM

Solution

 
#include <iostream>
using namespace std;
int main()
{
int row,col;
cin>>row>>col;
int m[row][col];
int mt[col][row];
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
cin>>m[i][j];
mt[j][i]=m[i][j];
}
}
for(int k=0;k<col;k++)
{
for(int l=0;l<row;l++)
{
cout<<mt[k][l]<<" ";
}
cout<<endl;
}
return 0;
}
view raw trans.cpp hosted with ❤ by GitHub

Saturday, 16 September 2017

Count frequency of each element in array

Write a program to count the frequency of each element in array , as example if we have 
int a[10]={5, 10, 2, 5, 50, 5, 10, 1, 2, 2};
the output should be 
number     frequency
5          3
10         2
2          3
50         1
1          1

#include <iostream>
#include <cstdlib>
using namespace std;
int main(int argc, char** argv) {
int a[10]={5, 10, 2, 5, 50, 5, 10, 1, 2, 2};
int flag[10]={0};
//count frequency of each number
int counter=1;
for(int i=0;i<=9;i++)
{
for(int j=i+1;j<=9;j++)
{
if (a[i]==a[j]){counter++;flag[j]=1;}
}
if(flag[i]!=1){cout<<a[i]<<"\t"<<counter<<endl;}
counter=1;
}
return 0;
}
view raw freq.cpp hosted with ❤ by GitHub