Thursday 26 December 2019

Use of Functions in programming languages

For example:

an Account has account_no, balance;
if person has withdrawn some amount then balance = balance - amount;
after withdraw if we want to print the account_no and balance

you have to write print account_no, balance

again if we deposit amount

balance = balance + amount;

you have to write print account_no, balance

again and again we have to print account_no and balance after every withdrawal and deposit

so we can put display() and write account_no and balance in that method display()
and call display() inside withdraw() and deposit()
int acno,bal;
void withdraw(int amt)
{
        bal=bal-amt;
}
void deposit(int amt)
{
        bal=bal-amt;
}
void display()
{
      printf("acc number = %d and Balance = %d", acno, bal);
}
int main()
{
       printf("Press 1. for withdraw 2. for deposit 3. display 4. exit");
       int choice;
       scanf("%d",&choice);
       switch(choice)
      {
             case 1:
                          printf("enter amount to withdraw");
                          int amt;
                          scanf("%d",&amt);
                          withdraw(amt);
                          display();
                          break;
           case 2:
                          printf("enter amount to deposit");
                          int amt;
                          scanf("%d",&amt);
                          deposit(amt);
                          display();
                          break;
           case 3:
                       display();
                       break;
           case 4: exit(0);
     }
}


Saturday 21 December 2019

String of concatenation, rotating the matrix, turning binary matrix

string concatenation
A string is called a pString if it can be represented as p concatenated copies of some string. For example, the string "aabaabaabaab" is at the same time a 1String, a 2String and a 4String, but it is not a 3String, a 5String, or a 6String and so on. Obviously any string is a 1String.
You are given a string s, consisting of lowercase English letters and a positive integer p. Your task is to find if it is possible to reorder the letters in the string s in such a way that the resulting string is a pString.
Input Format
The first input line contains integer p.
The second line contains s, all characters in s are lowercase English letters.
Constraints
1 ≤ p ≤ 1000
1 ≤ |s| ≤ 1000
Output Format
Print "YES" if it is possible to rearrange the letters in string s in such a way that the result is a pString. Print the result on a single output line. If it is not possible print "NO". (without quotes).
Sample Input 0
2
aazz
Sample Output 0
YES
Explanation 0
aazz can be rearranged to azaz which is a 2String

int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */  
    int n;
    scanf("%d",&n);
    char s[1010];
    scanf("%s",s);
    int h[26]={0},i;
    for(i=0;s[i]!='\0';i++)
        h[s[i]-'a']++;
    for(i=0;i<26;i++)
    {
        if(h[i]!=0 )
        {
            if(h[i]%n != 0)
            {
                printf("NO\n");
            return 0;
            }
        }
           
        }
    printf("YES");
    return 0;
}

=============
rotating the matrix
Thomas, a computer programmer, is led to fight an underground war against powerful computers who now rule the world with a system called 'The Matrix'.
To win against the system, he must rotate the Matrix clockwise by an angle of 90 degrees.
Unfortunately the system has wiped Thomas' memory and it is now in your hands to save the world.
The matrix can be considered as a 2Dimensional Array of size NxN.
SEE THE SAMPLE INPUT OUTPUT FOR CLARITY
Input Format
The first line contains the size of the matrix N.
The next N lines contain N integers each, together denoting the square matrix of size NxN.
Constraints
1 <= N <= 10
Output Format
Output the final matrix after rotation.
Sample Input 0
2
1 2
3 4
Sample Output 0
3 1
4 2

int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */   
    int n;
    scanf("%d",&n);
    int a[n][n],b[n][n],i,j;
    for(i=0;i<n;i++)
        for(j=0;j<n;j++)
            scanf("%d",&a[i][j]);
    for(i=0;i<n;i++)
        for(j=0;j<n;j++)
            b[i][j]=a[n-j-1][i];
    for(i=0;i<n;i++){
        for(j=0;j<n;j++)
            printf("%d ",b[i][j]);
        printf("\n");
    }
    return 0;
}
Turning binary matrix


Consider a binary matrix A of size N X N. Now, consider the following matrices : A90 - obtained by rotating A clockwise by 90 degrees. A180 - obtained by rotating A clockwise by 180 degrees. A270 - obtained by rotating A clockwise by 270 degrees.
Note : Binary matrix implies that every element will be either 0 or 1.
Your task is to construct another binary matrix B of size N X N such that : B(i,j) = 1 iff either A(i,j) = 1 OR A90(i,j) = 1 OR A180(i,j) = 1 OR A270(i,j) = 1 B(i,j) = 0 otherwise
INPUT
First line contains the size of the matrix N (1 ≤ N ≤ 100) Next N lines contain N integers each (Only 0 or 1) denoting the matrix A
OUTPUT
Print N X N integers, denoting the matrix B.
Sample Input 0
4
0 0 0 0
0 0 0 0
0 0 1 0
1 0 0 0
Sample Output 0
1 0 0 1
0 1 1 0
0 1 1 0
1 0 0 1
int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */   
    int n;
    scanf("%d",&n);
    int a[n][n],b[n][n],i,j;
    for(i=0;i<n;i++)
        for(j=0;j<n;j++)
            scanf("%d",&a[i][j]);
    for(i=0;i<n;i++)
        for(j=0;j<n;j++)
            b[i][j]=a[i][j]|a[n-j-1][i]|a[n-i-1][n-j-1]|a[j][n-i-1];//for 360,90,180,270 rotations
    for(i=0;i<n;i++){
        for(j=0;j<n;j++)
            printf("%d ",b[i][j]);
        printf("\n");
    }
    return 0;
}

Monday 11 November 2019

Mark and Toys,Priyanka and Toys, Jim and the Orders Hacker Rank Solution in C++

Mark and Toys
#include <bits/stdc++.h>

using namespace std;

int main()
{
    int n,k;
    scanf("%d%d",&n,&k);
    int a[n],i,c=0,bill=0;
    for(i=0;i<n;i++)
        scanf("%d",&a[i]);
    sort(a,a+n);
    for(i=0;i<n;i++)
    {
        bill=bill+a[i];
        if(bill>k)
            break;
        else
            c++;
    }
    printf("%d",c);
}

Priyanka and Toys
#include <bits/stdc++.h>

using namespace std;

int main()
{
    int n;
    scanf("%d",&n);
    int a[n],i;
    for(i=0;i<n;i++)
        scanf("%d",&a[i]);
    sort(a,a+n);
    int minwt=a[0];
    int noc=1;
    for(i=0;i<n;i++)
    {
        if(a[i]<=4+minwt)
            continue;
        noc++;
        minwt=a[i];
    }
    printf("%d",noc);
    return 0;
}




Jim and the Orders
#include <bits/stdc++.h>

using namespace std;

int main()
{
    int n;
    scanf("%d",&n);
    int i;
    vector<pair<int,int>> v;
    int ono, ptime;
    for(i=0;i<n;i++)
    {
        scanf("%d%d",&ono,&ptime);
        v.push_back(make_pair(ono+ptime,i+1));
    }
    sort(v.begin(),v.end());
    for(i=0;i<n;i++)
        printf("%d ",v[i].second);

}

Monday 14 October 2019

Given 2 integers a,k. Find if kth bit is set or not using bitwise right shift operator

//Given 2 integers a,k. Find if kth bit is set or not using bitwise right shift operator
#include<stdio.h>

int main() {
    int a,k,t;
    scanf("%d%d",&a,&k);
    t=a>>(k-1);
    if(t&1 == 0)
        printf("%d th bit is not set",k);
    else
        printf("%dth bit is set",k);
}

Check whether 3 numbers are equal or not using bitwise operators

//Given 3 integers a,b,c. Find if all the 3 numbers are same or not using bitwise operators
#include<stdio.h>

int main() {
    int a,b,c,t;
    scanf("%d%d%d",&a,&b,&c);
    t=(a^b)|(b^c);
    if(t==0)
        printf("same");
    else
        printf("not same");
}

You are given two integers a and b. You need to find number of digits in element a (let us call it n) and print out maximum number obtained by doing xor of 10^n and k, where k lies from 1 to b

//You are given two integers a and b. You need to find number of digits in element a (let us call it n) and print out maximum number obtained by doing xor of 10^n and k, where k lies from 1 to b
#include<stdio.h>
#include<math.h>
int main() {
    int a,b,n=0,k,max=0,temp,t,i,c=0;
    scanf("%d%d",&a,&b);
    //n=log(a)+1;
    t=a;
    while(t)
    {
        n++;
        t=t/10;
    }
    //printf("number of digits=%d\n",n);
    t=1;
    for(i=1;i<=n;i++)
        t=t*10;
    //printf("10 to power of n=%d\n",t);
    for(k=1;k<=b;k++)
    {
       
        temp=t^k;
        if(max<temp)
            max=temp;
    }
    printf("%d",max);
}

Monday 23 September 2019

Little Boy is Uttering His First Words and Snake Procession Code chef solution in C

Little Boy is uttering his first words. If there is sub sequence mom in the words he uttered, print Mom and if it contains sub sequence dad print Dad and if it has both print the one that whose sub sequence has occurred first. If it has no words at all, print Goo-goo

Program:
#include<stdio.h>

int main() {
    char st[100],s1[]="mom",s2[]="dad";
    scanf("%s",st);
    int i,j=0,k=0;
 
    for(i=0;st[i]!='\0';i++)
    {
        if(st[i] == s1[j])
        {
            j++;
            if(j==3)
                break;
        }
        if(st[i] == s1[k])
        {
            k++;
            if(k==3)
                break;
        }
    }
    if(j==3)
        printf("Mom");
    else if(k==3)
        printf("Dad");
    else
        printf("Goo-goo");
 
        return 0;

}

here in order to check whether a sub sequence is present or not in a given string, the best way to check is given in the above program.
Also once we found the sub sequence mom first we need to break because we need to print the first sub sequence that was uttered first.

=======================================================================

Snake Procession

Problem Code: SNAKPROC

Solution:


#include <stdio.h>
#include <string.h>
int main(void) {
int t;
scanf("%d",&t);
while(t--)
{
    int n,i,j=0,f=0,k;
    scanf("%d",&n);
    char st[n+1],temp[n+1];
    scanf("%s",st);
    int l =strlen(st);
    for(i=0;i<l;i++)
        if(st[i] !='.')
            temp[j++]=st[i];
    if(j == 0)
        f=1;
    else if (j%2 == 0)
        for(k=0;k+1<j;k=k+2)
            if(temp[k] == 'H' && temp[k+1] == 'T')
                f=1;
            else
            {
                f=0;
                break;
            }
   if(f == 1)
    printf("Valid\n");
   else
    printf("Invalid\n");
 
}
return 0;
}

in the above program never write  st[k+1] !='\0' and always use string length and compare whether index+1 exceeds string length or not.
Here as the index, k is not incremented by 1 but by 2 and hence we are not supposed to use
st[k+1]!='\0'

Saturday 31 August 2019

I Love T code chef solution in C

Read sentences until user enters 0
for each sentence, if the first character in each word in the given sentence is vowel, append T and if it is not vowel replace that character by T. 
Also only first character in each word only must be capital letter.

Sample Input:
love apples
apples are gOOOd for HelatHH
0

Sample Output:
Tove Tapples
Tapples Tare Toood Tor Telathh



#include<stdio.h>
int isvowel(char ch)
{
    if(ch >='A' && ch <= 'Z')
        ch=ch+32;
    if(ch == 'a' ||ch == 'e'||ch == 'i'||ch == 'o'||ch == 'u')
        return 1;
    else
        return 0;
}

int main()
{
    char st[1000001];
    scanf("\n%[^\n]\n",st);
    while(st[0] != '0')
    {
        int i;
        for(i=0;st[i]!='\0';i++)
        {
        if(st[i] >= 'A' && st[i] <= 'Z')
                st[i]=st[i]+32;
        if(i == 0|| (st[i-1] == ' ' && st[i] != ' '))
        {
         
            if(isvowel(st[i]))
                printf("T%c",st[i]);
            else
                printf("T");
        }
        else
            printf("%c",st[i]);
        }
        printf("\n");
        scanf("\n%[^\n]\n",st);
    }
    return 0;
 
}

Monday 26 August 2019

Migratory Birds Hacker Rank Solution in C

Problem:

https://www.hackerrank.com/challenges/migratory-birds/problem


#include <stdio.h> int main() { int n,i,max,ans; scanf("%d", &n); int a[n],h[6]={0}; for(i = 0; i < n; i++) { scanf("%d",&a[i]); h[a[i]]++; } max=h[1]; for(i = 2; i < 6; i++) { if(max<h[i]) { max=h[i]; ans=i; } } printf("%d",ans); return 0; }

Friday 23 August 2019

Binary Numbers Hacker Rank Solution in C

 #include <stdio.h>
int main()
{
    int n,r,c=0,t=0;
    scanf("%d",&n);
    while(n>0)
    {
        r=n%2;
        if(r==1)
        {
            c++;
            if(c>t)
                t=c;
        }
        else
            c=0;
        n=n/2;
    }
    printf("%d",t);
    return 0;

}


Find Product Hacker Earth Solution in C,Let Us Understand Computer Hacker Earth Solution in C,Count Numbers Hacker Earth Solution in C

#include <stdio.h>
#define ma 1000000007
int main(){
int num,i,a;
unsigned long long int ans=1;
scanf("%d", &num);

for(i=0;i<num;i++){
   scanf("%d", &a);
   ans=(ans*a)%ma;
}
printf("%d", ans);

}

===============or=================
#include <stdio.h>
const int ma = 1e9+7;
int main(){
int num,i,a;
unsigned long long int ans=1;
scanf("%d", &num);

for(i=0;i<num;i++){
   scanf("%d", &a);
   ans=(ans*a)%ma;
}
printf("%d", ans);

}

=============================================================
Let Us Understand Computer Hacker Earth Solution in C

#include <stdio.h>
#include <math.h>
int main()
{
unsigned long long int t;
scanf("%llu",&t);
while(t--)
{
unsigned long long int k,n,ans,i;
scanf("%lld",&n);
i=1;
while(i<=sqrt(n))
{
i=i*2;
}
if(n/i>=i/2)
ans=n-n/i;
else
ans=(n-(i/2))+1;
  printf("%lld\n",ans);
}
}

===========Count Numbers Hacker Earth Solution in C==============
  1. #include <stdio.h>
  2. #include <ctype.h>
  3. int main()
  4. {
  5. int t,i;
  6. scanf("%d",&t);
  7. for(i=1;i<=t;i++)
  8. {
  9. int n,j,c=0;
  10. scanf("%d",&n);
  11. n++;
  12. char s[n];
  13. scanf("%s",s);
  14. for(j=0;s[j]!='\0';j++)
  15. {
  16. if(isdigit(s[j]) && !isdigit(s[j-1]))
  17. c++;
  18. }
  19. printf("%d\n",c);
  20. }
  21. return 0;
  22. }

Thursday 22 August 2019

Finalized without bounds infix to postfix

#include<stdio.h>
#include <process.h>
#define MAX 50
char stack[MAX];
int top=-1;
int getpriority(char);
void push(char);
char pop();
main()
{
char infix[50],temp,ch,postfix[50];
int i=0,j=0;
printf("enter the infix expression\n");
scanf("%s",&infix);
while(infix[i] != '\0')
{
ch=infix[i];
if(ch == '(')
push(ch);
else if(ch == ')')
{
while(stack[top]!='(')
postfix[j++]=pop();
temp=pop();// popping the (
}
else if(isdigit(ch)||isalpha(ch))
postfix[j++]=ch;
else
{
while(getpriority(stack[top])>=getpriority(ch))
postfix[j++]=pop();
push(ch);
}
i++;
}
while(top != -1)
postfix[j++]=pop();
postfix[j]='\0';
puts(postfix);
}
int getpriority(char ch)
{
if( ch == '*'|| ch == '/'|| ch == '%')
return 2;
else if(ch == '+' || ch == '-')
return 1;
else
return 0;
}
void push(char item)
{
if(top == MAX-1)
{
printf("stack is full");
return;
}
top=top+1;
stack[top]=item;
}

char pop()
{
if(top == -1)
{
printf("stack empty");
return;
}
char temp;
temp=stack[top];
top=top-1;
return temp;
}

Resize an image keeping Aspect Ratio using Python

import cv2
import numpy as np

img = cv2.imread('flower.jpg');
# To resize the image keeping aspect ratio
rows=100.0/img.shape[1] #img.shape[1] gives the number of rows
dimensions = (100, int(img.shape[0]*rows))
resized = cv2.resize(img, dimensions, interpolation = cv2.INTER_AREA)
cv2.imshow("Original", img)
cv2.imshow("Resized", resized)
cv2.waitKey(0)
cv2.destroyAllWindows


Output:





















Resized Image:


Tuesday 20 August 2019

Add the integral and decimal part of a floating number without using . in scanf in C

#include<stdio.h>
int main()
{
    float x=12.25;
    int y=x,c=0;
    float d = x-y;
 
    for(; x !=((int)x);x = x*10)
    {
        c++;
    }
    while(c>0)
    {
        d=d*10;
        c--;
    }
    printf("%d",y+(int)d);

}

Friday 2 August 2019

Questions on Conditional Statements in C:


Library fine:
https://www.hackerrank.com/challenges/library-fine/problem

#include<stdio.h>
int main()
{
int dr,mr,yr,de,me,ye,fine=0;
scanf("%d%d%d",&dr,&mr,&yr);
scanf("%d%d%d",&de,&me,&ye);
if(yr == ye)
{
if(mr > me)
fine =(mr-me)*500;
else if(mr == me)
{
if(dr>de)
fine = (dr-de)*15;
}
}
else if(yr>ye)
fine =10000;
printf("%d",fine);
return 0;
}


Given an integer, , perform the following conditional actions:
  • If  is odd, print Weird
  • If  is even and in the inclusive range of  to , print Not Weird
  • If  is even and in the inclusive range of  to , print Weird
  • If  is even and greater than , print Not Weird
The above statements can be converted to 

 if the number is from 6 to 20 and the number is odd then  print "Weird" and if the number is even also print "Weird" and so we conclude if the number is even or odd and is from 6 to 20 then print "Weird"
so the condition becomes

if( n %2 != 0 || (n>=6 && n<= 20))
                   printf("Weird");
else
                  printf("Not Weird");