Sunday, 30 June 2019

Halloween Party Hacker Rank Solution in C, Minimum Height Triangle Hacker Rank Solution in C,Summing the N series Hacker Rank Solution in C,



Minimum Height Triangle

https://www.hackerrank.com/challenges/lowest-triangle/submissions/code/112097635

int lowestTriangle(int base, int area){
 
    return ceil((2.0*area)/base);
}
summing-the-n-series

https://www.hackerrank.com/challenges/summing-the-n-series/problem

Tn = n*n - (n-1)*(n-1) = n*n -n*n - 1 +2n = 2n-1

So the series is 1+3+ 5+....+2*n-1
Sum of n terms in Arithmetic Progression =  (n/2)*(2a+(n-1)*d) here a is 1 (first term)
d is common difference = 2
So sum = (n/2)*(2*1+(n-1)*2)  = (n/2)*(2+2*n-2)  = (n/2)*(2*n) = n*n

int summingSeries(long n) {
return ((n%1000000007)*(n%1000000007))%1000000007;

}
Halloween Party

Here in k lines, some must be horizontal and some vertical. We get maximum 1x1 pieces
if number of horizontal lines and vertical lines are equal

So if k is even then we cut the chocolate by (k/2) horizonatl lines and (k/2) vertical lines
giving (k/2)*(k/2) pieces

when k is odd we give extra one horizontal cut.
(K+1)/2 horizontal and
remaining lines would be k-((k+1)/2) vertical lines


unsigned long long int halloweenParty(unsigned long long int k) {
   
if(k%2 == 0)
    return (k/2)*(k/2);
return((k+1)/2)*((k-((k+1)/2)));

}

Find the Point Hacker Rank solution in C

https://www.hackerrank.com/challenges/find-point/problem

if point P(px,py) is rotated around point Q(qx,qy) by 180 degrees then it reaches a point R(rx,ry)

hence qQ would be mid point between P and R

so (px+rx)/2 = qx  and (py+ry)/2 = qy

from the above equatiions, px,py,qx and qy are given we need to find rx,ry

hence rx = 2*qx-px and ry = 2*qy-py

#include <stdio.h>
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        int px,py,qx,qy,rx,ry;
        scanf("%d%d%d%d",&px,&py,&qx,&qy);
        rx=2*qx-px;
        ry=2*qy-py;
        printf("%d %d\n",rx,ry);
    }
    return 0;
}


Thursday, 27 June 2019

Army game Hacker rank solution in c

If a supply drop can cover 4 blocks. Therefore if the grid is 2x2, 1 suppy drop is enough. But what if the grid is 3x2?
1 suppy drop will cover 2x2 portion of the grid but still there is 1x2 part and you need a supply drop there anyway. Same as how many you would need in a 4x2 grid.
Similarly if the region was 3x3 you would need as much as drops as you would need in a 4x4 grid. Otherwise some blocks would be left empty.
So for simplicity of calculation we increment the odd integer to it's nearest bigger even (yes, that means odd+1) and then multiply n and m and divide it by 4. That's how many supply drops we must need to cover all the blocks.  This explanation is given by user sojal in hacker rank discussions

https://www.hackerrank.com/challenges/game-with-cells/problem

Program:

 #include<stdio.h>
int main()
{
int n,m;
scanf("%d%d",&n,&m);
if(n%2 != 0)
    n++;
if(m%2 != 0)
    m++;
printf("%d",(m*n)/4);
return 0;
}

Sunday, 23 June 2019

Sub array Programs in C


Q) Number of sub arrays in a given array and sum of sub array elements.
For example given an array as shown below
23
14
39
42

Subarrays that can be formed are
[23], [23, 14], [23 , 14, 39], [23, 14, 39, 42]
[14], [14, 39], [14, 39, 42]
[39], [39, 42]
[42]
here 0th index element 23 occurs 4 times as first element in subarray.
1st index element 14 occurs 6 times of which
3 times it occurs as first element in subarray and
remaining 3 times it occurs in combination with first element 23

 2nd index element 39 occurs 6 times of which
2 times it occurs as first element in subarray and
2 times it occurs in combination with first element 23
2 times it occurs in combination with second element 14

3rd index element 42 occurs 4 times of which
1 times it occurs as first element in subarray and
1 times it occurs in combination with first element 23
1 times it occurs in combination with second element 14
1 times it occurs in combination with third element 39

if n is the number of elements in an array, here n=4
23 occurs n-i times as first element where i =0 as 23 is 0th index element
14 occurs n-i times as first element where i =1 as 14 is 1st index element.
remaining n-i times it occurs in combination with first element.
39 occurs n- i times as first element where i=2
n-i times in combination with first element 23
n-I times in combination with second element 14….so i *(n-i) times
and so on..
so general formula is
number of times ith element occurs = (n – i)+ i* (n-i)
Sum of sub array elements = number of times it occurs * element
So the program is:

#include <stdio.h>
int main()
{
               int n;
               printf("enter the number of elements\n");
               scanf("%d",&n);
               int a[n],sum=0,i;
               printf("\nEnter array elements\n");
               for(i=0;i<n;i++)
                              scanf("%d",&a[i]);
               for(i=0;i<n;i++)
               {
                              sum = sum+((n-i)+(n-i)*i)*a[i];
               }
               printf("sum = %d",sum);
}

Output:


Q) find the maximum possible length of subarray In that subarray a[i+1]%a[i]==0 Every element in subarray is divisible by its previous element Your task is to find maximum length of subarray.

#include <stdio.h>
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
{
    int n;
scanf("%d",&n);
    int a[n],i,j,max1=0,res=0,max2;
    for(i=0;i<n;i++)
    scanf("%d",&a[i]);
   
    for(i = 0 ; i < n ; i++)
    if(max1 < a[i])
    max1=a[i];
    
    int cnt[max1+1] = {0};
    int dp[max1+1] = {0};
    
    for( i = 0 ; i < n ; i++)
    cnt[ a[i] ]++ ;
    
    for (i = max1 ; i > 0 ; i--)
    {
        max2=0;
        for( j = 2*i ; j <= max1 ; j+=i )
        if(max2<dp[j])
        max2 = dp[j];
            dp[i] = cnt[i] + max2;
    }
    
    
    for( i = 0 ; i < max1+1 ; i++)
    if(res<dp[i])
    res = dp[i];
    printf("%d\n",res);
   
    }
    return 0;

}

Wednesday, 19 June 2019

Merge two strings picking a character alternatively from each string

#include<stdio.h>
#include <string.h>
int main() {
   char st1[100],st2[100],st3[200];
   scanf("%s%s",st1,st2);
   int l1,l2,i,k=0,j=0;
   l1=strlen(st1);
   l2=strlen(st2);

   for(i=0;j<l1 && k<l2;i++)
   {
       if(i%2 == 0)
            st3[i]=st1[j++];
       else
            st3[i]=st2[k++];
   }
   while(j<l1)
        st3[i++] = st1[j++];
   while(k<l2)
        st3[i++] = st2[k++];
   st3[i]='\0';
   printf("%s",st3);
}

Sunday, 16 June 2019

Print the maximum number of composite numbers that sum up to n.

Example:
given n = 81

81 can be represented as 18 * 4 + 9
so n can be represented as 18 4's and one 9. So together 18+1 = 19 number of composite numbers

Output: 19

The least composite number is 4.
so when n is represented as multiple of 4, we get maximum number of composite numbers.
When n is not divisible by 4 we get a remainder 1,2,3
When remainder is 1 then
excess = 1
to make number divisible by 4
we cannot subtract 4+1 = 5 as 5 from as 5  is not composite number
so we take two 4's = 8 and 8+1 = 9 is next least composite number and hence we subtract 9 from n to make n divisible by 4.

When remainder is 2 then
excess = 2
to make number divisible by 4 we subtract 4+2 = 6 from n.

When remainder is 3 then
excess = 3
we cannot use 4+3= 7 as 7 is not composite number
so  we take two 4's = 8 and 8+3 = 11 is not composite number
so  we take three 4's= 12 and 12+3 = 15 is next least composite number and hence we subtract  15 from to make n divisible by 4.
and 15 can be expressed as 9 and 5

#include<stdio.h>

int main()
{
   int n,ans= -1,r;
   scanf("%d",&n);
   if(n >= 4)
   {
       r=n%4;
       if(r == 0)
            ans = n/4;
       else if (r == 1)
       {
           if(n >= 9)
                ans = (n - 9)/4+1;
       }
       else if(r == 2)
            ans = (n - 6)/4 + 1;
       else if(r == 3)
       {
           if(n >= 15)
                ans = (n - 15)/4+2;
       }
   }
   if(ans == -1)
         printf("Not Possible");
  else
         printf("%d",ans);
}

Efficient Solution
If the number is 5, 7, 11 then it is impossible to represent it as sum of composite numbers.

#include<stdio.h>

int main()
{
   int n,ans= -1,r;
   scanf("%d",&n);
   if( n == 5 || n == 7 || n == 11)
          ans = -1;
   else if(n >= 4)
   {
       r=n%4;
       if(r == 0 || r == 2)
            ans = n/4;
       else if (r == 1 || r == 3)
                ans = n /4-1;
    }
    if(ans == -1)
         printf("Not Possible");
    else
         printf("%d",ans);
}

Tuesday, 11 June 2019

Data preparation basics using tidyr package in RStudio


install.packages("tidyr")      to install packages
library(tidyr)       to bring the package to R env
df3<-read.csv(file.choose())    to open .csv file
> df3
   state X2018 X2017 X2016 X2015
1     AP   557   212   344   239
2     WB   126   551   175   492
3     KA    85   450   471    90
4     DE   378   766   736   914
5     MP   227   614   135   182
6     RJ   177   925   544   795
7     TN   489   872   607   313
8     TS   253   127   138   608
9     MA   508   418   389   641
10    HP   527   832   887   918

> names(df3)[names(df3) == 'X2018']<-2018
> names(df3)[names(df3) == 'X2017']<-2017
> names(df3)[names(df3) == 'X2016']<-2016
> names(df3)[names(df3) == 'X2015']<-2015
> df3
   state 2018 2017 2016 2015
1     AP  557  212  344  239
2     WB  126  551  175  492
3     KA   85  450  471   90
4     DE  378  766  736  914
5     MP  227  614  135  182
6     RJ  177  925  544  795
7     TN  489  872  607  313
8     TS  253  127  138  608
9     MA  508  418  389  641
10    HP  527  832  887  918
dg = gather(df3,'year','n',2:5)
> dg
   state year   n
1     AP 2018 557
2     WB 2018 126
3     KA 2018  85
4     DE 2018 378
5     MP 2018 227
6     RJ 2018 177
7     TN 2018 489
8     TS 2018 253
9     MA 2018 508
10    HP 2018 527
11    AP 2017 212
12    WB 2017 551
13    KA 2017 450
14    DE 2017 766
15    MP 2017 614
16    RJ 2017 925
17    TN 2017 872
18    TS 2017 127
19    MA 2017 418
20    HP 2017 832
21    AP 2016 344
22    WB 2016 175
23    KA 2016 471
24    DE 2016 736
25    MP 2016 135
26    RJ 2016 544
27    TN 2016 607
28    TS 2016 138
29    MA 2016 389
30    HP 2016 887
31    AP 2015 239
32    WB 2015 492
33    KA 2015  90
34    DE 2015 914
35    MP 2015 182
36    RJ 2015 795
37    TN 2015 313
38    TS 2015 608
39    MA 2015 641
40    HP 2015 918
spread(dg,year,n)
   state 2015 2016 2017 2018
1     AP  239  344  212  557
2     DE  914  736  766  378
3     HP  918  887  832  527
4     KA   90  471  450   85
5     MA  641  389  418  508
6     MP  182  135  614  227
7     RJ  795  544  925  177
8     TN  313  607  872  489
9     TS  608  138  127  253
10    WB  492  175  551  126

date<-scan(what='char')
1: 2018-06-11
2: 2019-02-10
3: 2016-05-22
4: 2015-06-12
5: 2016-11-12
6:
Read 5 items
> sno<-c(1,2,3,4,5)
> d4<-data.frame(sno,date)
> d4
  sno       date
1   1 2018-06-11
2   2 2019-02-10
3   3 2016-05-22
4   4 2015-06-12
s1<-separate(d4,date,c('year','month','day'),sep='-')
> s1
  sno year month day
1   1 2018    06  11
2   2 2019    02  10
3   3 2016    05  22
4   4 2015    06  12
5   5 2016    11  12
 
> unite(s1,'date',year,month,day,sep='/')
  sno       date
1   1 2018/06/11
2   2 2019/02/10
3   3 2016/05/22
4   4 2015/06/12
5   5 2016/11/12
 


Friday, 7 June 2019

Print all possible combinations of r elements in a given array of size n

Using exclude and include


#include <stdio.h>
int a[100],temp[100],n,r;
void fun(int index, int i)
{
    if (index == r)
    {
        for (int j = 0; j < r; j++)
            printf("%d", temp[j]);
        printf("\n");
        return;
    }

    if (i >= n)
        return;

    temp[index] = a[i];       
   
    fun(index + 1, i + 1);     //current element is included

    fun(index,i+1);              // current element is excluded, replace it with next element

}
int main()
{
    int i;
    printf("enter the number of elements\n");
    scanf("%d",&n);
    printf("enter the array elements");
    for(i=0;i<n;i++)
        scanf("%d",&a[i]);
    printf("\n enter the number of digits");
    scanf("%d",&r);
    int temp[r];
    fun(0,0);
}

  =============================================================
#include <stdio.h>
int a[100],temp[100],n,r;
void fun(int start, int end, int index)
{
    if (index == r)
    {
        for (int j = 0; j < r; j++)
            printf("%d", temp[j]);
        printf("\n");
        return;
    }

    for (int i = start; i <= end && end - i + 1 >= r - index; i++)
    {
        temp[index] = a[i];
        fun(i+1,end, index+1);
    } 
}
int main()
{
    int i;
    printf("enter the number of elements\n");
    scanf("%d",&n);
    printf("enter the array elements");
    for(i=0;i<n;i++)
        scanf("%d",&a[i]);
    printf("\n enter the number of digits");
    scanf("%d",&r);
    int temp[r];
    fun(0,n-1,0);
}



Thursday, 6 June 2019

Extern variables and Functions example in C

Save the below code as ext1.c program

#include <stdio.h>
#include "ext2.c"
/* By using 'extern', you are telling the compiler that whatever
follows it will be found (non-static) at link time; don't reserve
anything for it in the current pass since it will be encountered later.
 Functions and variables are treated equally in this regard.*/
extern void fun(void);
extern int a;
int main(void)
{
    fun();
    printf("%d",a);
  return 0;
}


Save the below code as ext2.c program
#include <stdio.h>
int a=10;
void fun(void)
{
      printf("Hello, world!\n");
}


When you compile and run ext1.c , we get the below output

decimal to binary and alternatively merging binary numbers and then converting merged binary back to decimal python3

st=input();
l1=list(map(int,st))

print(l1)
ans=[]
for x in l1:
    result=''
    c=0
    while x != 0:
        r = x % 2  # gives the exact remainder
        x = x // 2
        result = str(r) + result
        c=c+1
    while(c<4):
        result='0'+result
        c=c+1
    ans.append(result)
f=''
for j in range(4):
    for i in range(len(ans)):
        f=f+ans[i][j]
print(int(f,2))


Input:
23

output:
[2, 3]
['0010', '0011']
00001101
13

merge two strings with alternate characters in python3

st="sar"
st1="lax"
ans=''.join(map(''.join, zip(st, st1))) 
print(ans)

Finding second largest in a string of numbers

#include <stdio.h>
#include <limits.h>

main()
{
char st[100];
printf("\nEnter a string\n");
scanf("%s",st);
int i,first,second;
first = second =INT_MIN;
for(i=0;st[i]!='\0';i++)
{
if(st[i]-'0' > first)
{
second = first;
first=st[i]-'0';
}
else if(st[i]-'0' > second && st[i]-'0' != first)
second=st[i]-'0';
}
if(second == INT_MIN)
printf("there is no second minimum");
else
printf("second min = %d",second);
}

=========================Using sorting=========================


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int co(const void *p, const void *q)
{
   return *(char *)p-*(char *)q;
}
main()
{
char st[100];
printf("\nEnter a string\n");
int i,max=0,l=strlen(st);
qsort(st,l,sizeof(char),co); // for sorting characters in string
max=st[l-1]-'0';
for(i=l-2;i>=0;i--)
{
if(max != st[i]-'0'){

printf("%d",st[i]-'0');
break;
}
}
}

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

Sunday, 2 June 2019

Regular Expressions in Java



To check it is a valid mobile or not:
A mobile number is valid if the starting digit is either 7 or 8 or 9
and must also contain 10 digits

String st="7123456789"

if(st.matches("[7-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]"))
        System.out.println("valid mobile");

(or)
if(st.matches("[7-9][0-9]{9}"))
        System.out.println("valid mobile");
(or)
if(st.matches("[789][0-9]{9}"))
        System.out.println("valid mobile");

if u want to allow 11 digit mobile number then first digit must be zero
if(st.matches("0? [7-9][0-9]{9}"))
        System.out.println("valid mobile");

0? means atmost one zero as first digit 
0 means compulsory one zero as first digit
0+ atleast one 0
0* means  0 may be there or may not be there and 0 can occur any number of times.

if u want to allow 10 or 11 or 12 digit mobile number then 
if(st.matches("(0|91)? [7-9][0-9]{9}"))
        System.out.println("valid mobile");

For email the regular expressions is
[a-z A-Z 0-9]@[a-z A-Z]. [a-z]{2-3}

=========
[^abc]  --means except abc