Monday, 30 June 2014

Sum of Integers

Write a program that reads numbers which are in the range 0 to 100, till it encounters -1. Print the sum of all the integers that you have read before you encountered -1

INPUT:
A sequence of integers separated by whitespace. There may be other integers following -1.

OUTPUT:
Sum of all integers in the sequence before you encounter -1. Any integer that is input after -1 in the sequence should be ignored.

CONSTRAINTS:
Atmost 10 integers will be given in the input. One of them is guaranteed to be a -1.
Inputs will be in the range 0 to 100 (both included).

Solution:
#include<stdio.h>
int main()
{
int sum=0;
int number=0;
do
{
sum=sum+number; //update partial sum
scanf("%d",&number); //read a number from the input
}while(number!=-1); //check whether recently added number is -1 or not
printf("%d",sum); //print the final sum
return 0;
}

Points in a Line

Given three points (x1, y1), (x2, y2) and (x3, y3), write a program to check if all the three points fall on one straight line.

INPUT:
Six integers x1, y1, x2, y2, x3, y3 separated by whitespace.

OUTPUT:
Print “Yes” if all the points fall on straight line, “No” otherwise.
CONSTRAINTS:
-1000 <= x1, y1, x2, y2, x3, y3 <= 1000

Solution:
#include<stdio.h>
int main() {
int x1,y1,x2,y2,x3,y3;
//Reading all 6 integers from the input using scanf()
scanf("%d %d %d %d %d %d", &x1,&y1,&x2,&y2,&x3,&y3);
//Checking if the slopes (y2-y1)/(x2-x1) == (y3-y2)/(x3-x2). If they are equal, then all the points lie on the same line.
//Instead of performing division in LHS and RHS, we cross multiply (x2-x1) and (x3-x2) to handle the case when either (x2-x1) = 0 or (x3-x2) = 0.
if ((y2-y1)*(x3-x2) == (y3-y2)*(x2-x1)) {
printf("Yes");
} else {
printf("No");
}
return 0;
}

Digital Root

The digital root (also called repeated digital sum) of a number is a single digit value obtained by an iterative process of summing digits. Digital sum of 65536 is 7, because 6+5+5+3+6=25 and 2+5 = 7. Write a program that takes an integer as input and prints its digital root.

INPUT:
A single integer N

OUTPUT:
Digital root of the number N.

CONSTRAINTS:
1 <= N <= 10^7

Solution:

#include<stdio.h>
int main()
{
int N, sum=0;
scanf("%d",&N);
while(N>9){
sum=0;
while(N>0){
sum += N%10;
N = N/10;
}
N = sum;
}
printf("%d",N);
return 0;
}

Factors of an Integer

Write a program to print all the factors of a positive integer A.

INPUT:
A single integer A

OUTPUT:
Factors of the number A, in ascending order, separated by whitespace. 1 and A are also factors of A.

CONSTRAINTS:
2 <= A <= 10000

Solution:

#include<stdio.h>
int main()
{
int number;
int i=1;
scanf("%d",&number);
printf("%d",i);
for(i=2;i<=number;i++) //iterating over all numbers from 2 to number
{
if(number%i==0) //checking whether 'i' is a factor of number or not
{
printf(" %d",i); //printing a factor with a preceding whitespace
}
}
return 0;
}

Most Frequent Element in a Sequence

Write a program to read a sequence of N integers and print the number that appears the maximum number of times in the sequence.

INPUT:
Input contains two lines. First line in the input indicates N, the number of integers in the sequence. Second line contains N integers, separated by white space.

OUTPUT:
Element with the maximum frequency. If two numbers have the same highest frequency, print the number that appears first in the sequence.

CONSTRAINTS:
1 <= N <= 10000
The integers will be in the range [-100,100].

Solution:
#include<stdio.h>
int main() {
int n, i, j;
scanf("%d", &n);
int arr[n];
for(i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
int freq = -1, maxEl = 0,tempFreq = 0;
for(i = 0; i < n; i++) {
//tempFreq stores the frequency of element arr[i] in the sequence
tempFreq = 0;
for(j = i; j < n; j++) {
//counting frequency of arr[i] only on the right side of i is enough; since if arr[i] occurred on left side of i, it’s frequency would have been more anyways
if (arr[i] == arr[j]) {
//if you encounter element equal to arr[i], increment tempFreq;
tempFreq++;
}
}
if (tempFreq > freq) {
//variable freq stores the maximum frequency that has been encountered so far
//maxEl stores the array element that has the maximum frequency encountered so far
freq = tempFreq; maxEl = arr[i];
}
}
printf("%d", maxEl);
}

Matrix in Spiral Order

Write a program that reads an MxN matrix A and prints its elements in spiral order.
You should start from the element in the 0th row and 0th column in the matrix and proceed in a spiral order as shown below.
 1 →  2 → 3 → 4
                          ↓
5 →  6 → 7       8
↑               ↓       ↓
9    10 ← 11     12
↑                        ↓
13←14←15←16
Output for the above matrix: 1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10

INPUT:
First line contains two integers M and N separated by whitespace. The next M lines contain elements of matrix A, starting with the topmost row. Within each row, the elements are given from left to right.

OUTPUT:
Elements of the matrix printed in a spiral order. All the elements should be separated by whitespace.

CONSTRAINTS:
1 <= M <= 5, 1 <= N <= 5.
Elements in the matrix will be in the range [-100,100]

Solution:

#include<stdio.h>
int main()
{
int A[5][5];
int B[25];
int M, N;
int i,j;
int cnt=0;
int cnt1=0;
int top, bot, right, left;
scanf("%d%d",&M,&N);
for(i=0; i<M; i++){
for(j=0; j<N; j++){
scanf("%d",&A[i][j]);
}
}
top = 0; bot = M-1;
left = 0; right = N-1;
for(cnt1=1; cnt1 <= M/2 && cnt1 <= N/2; cnt1++){
for(i=left; i<= right; i++){
B[cnt++]= A[top][i];
}
for(i=top+1;i<=bot;i++){
B[cnt++]= A[i][right];
}
for(i=right-1; i>=left; i--){
B[cnt++]= A[bot][i];
}
for(i=bot-1; i>=top+1; i--){
B[cnt++] = A[i][left];
}
top++; bot--;
left++; right--;
}
if(top==bot && left==right){
B[cnt++]=A[top][left];
}
else if(top<bot){
for(i=top;i<=bot;i++){
B[cnt++]=A[i][left];
}
}
else if(left<right){
for(i=left; i<=right;i++){
B[cnt++]=A[top][i];
}
}
for(i=0;i<M*N-1;i++){
printf("%d ",B[i]);
}
printf("%d",B[i]);
return 0;
}

Maximum Sum

Write a program that reads an NxN square matrix M that calculates the sum of the elements in individual rows, individual columns and the two main diagonals. Among these sums, print the largest.
Consider the following matrix of order 3x3:
1 10 13
2 14 12
3  9   8
The row sum values are 1+10+13=24, 2+14+12=28 and 3+9+8=20. The column sum values are 1+2+3=6, 10+14+9=33 and 13+12+8=33. The diagonal sums are 1+14+8=23 and 13+14+3=30. The expected output is maximum among these sums, which is 33.

INPUT:
First line contains a value N representing the dimension of the input matrix M, followed by N lines, each line representing a row of the matrix. Within each row, N values are given and are separated by whitespace.

OUTPUT:
A value which is the maximum among N row sums, N column sums and the two main diagonal sums in M.

CONSTRAINTS:
The entries in M are integers.
1<=N<=100
-100 <= Mij <= 100

Solution:

#include<stdio.h>
int main()
{
int a[100][100];//input matrix
int n;//dimension of the square matrix
int i,j;//loop variables
int sum=-10001;//variable that holds the maximum among a set of rows/columns/diagonals that are considered so far
int temp_sum;//variable that holds partial sum of values in a row/column/diagonal
scanf("%d",&n); //read dimension
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);//read input values
for(i=0;i<n;i++)
{ temp_sum=0;//reset the variable before storing the partial sum of values in a row under consideration
for(j=0;j<n;j++)
{
temp_sum=temp_sum+a[i][j]; //calculate the sum of elements in the i^th row
}
if(temp_sum>sum)//check whether the sum of values in the i^th row is better than the current maximum
{
sum=temp_sum;
}
}
for(i=0;i<n;i++)
{ temp_sum=0;//reset the variable before storing the partial sum of values in a column under consideration
for(j=0;j<n;j++)
{
temp_sum=temp_sum+a[j][i];//calculate the sum of elements in the i^th column
}
if(temp_sum>sum)
{
sum=temp_sum;//check whether the sum of values in the i^th column is better than the current maximum
}
}
temp_sum=0;//reset the variable before storing the partial sum of values in the first diagonal
for(i=0;i<n;i++)
{
temp_sum+=a[i][i];//calculate the sum of elements in the first diagonal
}
if(temp_sum>sum)
{
sum=temp_sum;//check whether the sum of values in the first diagonal is better than the current maximum
}
temp_sum=0;//reset the variable before storing the partial sum of values in the second diagonal
for(i=0;i<n;i++)
{
temp_sum+=a[i][n-1-i];//calculate the sum of elements in the second diagonal
}
if(temp_sum>sum)
{
sum=temp_sum;//check whether the sum of values in the second diagonal is better than the current maximum
}
printf("%d",sum);
return 0;
}

Substrings

Write a program that takes two input strings S1 and S2 and finds if S2 is a substring of S1 or not. If S2 is a substring of S1, the program should print the index at S1 at which there is a match. If S2 is not a substring of S1, the program should print -1. If S2 appears in S1 multiple times, print the first index in S1 at which the match occurred.

INPUT:
Two strings S1 and S2, separated by whitespace.

OUTPUT:
One integer, which is either the index at which the match occurred or -1. Remember, the indices start at 0 for arrays.

CONSTRAINTS:
Each string contains at most 19 characters.
The strings will contain only letters from the alphabet (a-z and A-Z).
Match has to be case-sensitive.

Solution:

#include<stdio.h>
#include<string.h>
#define MAXLENGTH 20
#define INVALID_POSITION -1
int main(){
char str[MAXLENGTH];
char substr[MAXLENGTH];
scanf("%s%s",str,substr); // scan the string and the substring
int size_of_str = strlen(str);
int size_of_substr = strlen(substr);
int str_index=0;
int substr_index=0;
/* position of match. initialized to -1*/
int position_of_match = INVALID_POSITION;
/* Search till the end of string or till a match is found. */
while(str_index<size_of_str){
/* Match first character of sub string.
Once the first character is matched check if the required substring
starts there. */
if(substr[0] == str[str_index]){
for(substr_index=1;substr_index<size_of_substr;substr_index++){
if((str_index+substr_index)>= size_of_str)
break; // We have reached the end of string before end of substring. No match...
if(substr[substr_index] != str[str_index+substr_index])
break; // a miss match between two strings at this position. No match here.
}
if(substr_index == size_of_substr){ // Great!!! we have matched the string
position_of_match = str_index;
break; // we have got the match. Now stop searching.
}
}
str_index++;
}
printf("%d",position_of_match);
return 0;
}