Saturday, 25 November 2017

C Program to print the next palindrome

#include <stdio.h>
#include <conio.h>
void main()
{
int n,i,k,r,s;
clrscr();
scanf("%d",&n);
for(i=n+1;;i++)
{
s=0;
k=i;
while(k>0)
{
r=k%10;
s=s*10+r;
k=k/10;
}
if(s == i)
{
printf("%d",i);
break;
}
}
getch();
}

count steps in matrix solution in C

#include<stdio.h>
 #include <conio.h>
#include <math.h>
int a[10][10],y,z,r,c;
int fun(int n)
{
                int k,i,j,f=0;
                for(i=0;i<r;i++)
                {
                                for(j=0;j<c;j++)
                                {
                                                if(n == a[i][j])
                                                {       f=1;
                                                                break;
                                                }
                                }
                                if(f ==1)
                                                break;
                }
      //      printf("\n%d\t%d",i,j);
                k=abs(y-i)+abs(z-j);
                y=i;
                z=j;
                return k;
}
int main()
{
           int count,i,j,c1,t,test;
           scanf("%d",&test);
           while(test--)
            {           
                count=0;
                scanf("%d%d",&r,&c);
                for(i=0;i<r;i++)
                                for(j=0;j<c;j++)
                                                scanf("%d",&a[i][j]);
                y=0;z=0;
                 for(i=a[0][0]+1,c1=0;c1<r*c-1;c1++,i++)
                {
                                t=fun(i);
                                count =count+t;
                }
                printf("%d",count);
          }
           return 0;

}

C Program to check whether an integer array is present in another array

#include<stdio.h>
#include <conio.h>
void main()
{
int a[100],b[100],i,n,m,j,k,flag,flag1=0;
clrscr();
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
scanf("%d",&m);
for(i=0;i<m;i++)
scanf("%d",&b[i]);
for(i=0;i<n;i++)
{
    if(a[i] == b[0] && i+m <= n)
    {
                for(j=i,k=1;k<m;k++,j++)
                {
                         if(a[j] != b[k])
                                 break;
                }
                if(k == m-1)
                {
                                flag1=1;
                                break;
                }
     }
}
if(flag1 ==1)
                printf("Present");
else
                printf("not present");

getch();

Chef and Dolls Code Chef solution in C

#include <stdio.h>
 int main()
 {
int t,n,a,i;
scanf("%d",&t);
while(t--)
{
 int b[100000]={0},a[100000];
 scanf("%d",&n);
 for(i=0;i<n;i++)
 {
     scanf("%d",&a[i]);
     b[a[i]]++;
 }
 for(i=0;i<=100000;i++)
 {
     if(b[i]%2!=0)
     {
         printf("%d\n",i);
         break;
     }
 }
                }
                return 0;

}  

Friday, 24 November 2017

Divisible Sum Pairs, Non Divisible Subset Hacker Rank Solution in C

https://www.hackerrank.com/challenges/divisible-sum-pairs/problem

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>

int main() {
    int n,result=0;
    int k,j;
    scanf("%i %i", &n, &k);
    int *ar = malloc(sizeof(int) * n);
    for(int ar_i = 0; ar_i < n; ar_i++){
       scanf("%i",&ar[ar_i]);
    }
    for(int ar_i = 0; ar_i < n-1; ar_i++){
      for(j=ar_i+1;j<n;j++)
          if((ar[ar_i]+ar[j])%k == 0)
              result++;
    }
    printf("%d\n", result);
    return 0;
}

========================================================================
https://www.hackerrank.com/challenges/non-divisible-subset/problem


#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>
int max(int a,int b)
{
    if(a>b)
        return a;
    return b;
}

int nonDivisibleSubset(int k, int arr_size, int* arr) {
    // Complete this function
    int h[101]={0},result=0,i,j;
    for(i=0;i<arr_size;i++)
        h[(arr[i]%k)]++;
    if(h[0] != 0) result++;
    for(i=1,j=k-1;i<j;i++,j--)
    {
        result=result+max(h[i],h[j]);
    }
    if(k%2 == 0 && h[k/2] != 0)
        result++;
    return result;
}

int main() {
    int n;
    int k;
    scanf("%i %i", &n, &k);
    int *arr = malloc(sizeof(int) * n);
    for (int arr_i = 0; arr_i < n; arr_i++) {
       scanf("%i",&arr[arr_i]);
    }
    int result = nonDivisibleSubset(k, n, arr);
    printf("%d\n", result);
    return 0;
}

Breaking Records Hacker Rank Solution in C

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>



int main() {
    int n,result_size=2,max,min;
    scanf("%d",&n);
    int *s = malloc(sizeof(int) * n);
    int result[2];
    result[0]=0;
    result[1]=0;
    for(int s_i = 0; s_i < n; s_i++){
       scanf("%d",&s[s_i]);
        if(s_i == 0)
            max=min=s[s_i];
        else
        {
            if(s[s_i]> max)
            {
                result[0]++;
                max=s[s_i];
            }
            if(s[s_i]< min)
            {
                result[1]++;
                min=s[s_i];
            }
        }
    }
  
  
    for(int i = 0; i < result_size; i++) {
        if (i) {
            printf(" ");
        }
        printf("%d", result[i]);
    }
    puts("");
    return 0;
}

Between Two Sets Hacker Rank Solution in C


#include<stdio.h>
int main() {
    int n,t,flag1,flag2,j,total=0,i;
    int m;
    scanf("%i %i", &n, &m);
    int a[n],b[m];
    for (i = 0; i < n; i++) 
       scanf("%i",&a[i]);
    
    for (i = 0; i < m; i++) 
       scanf("%i",&b[i]);
    
    for(t=n;t<=b[0];t++)
    {
        flag1=0;
        flag2=0;
        for(i=0;i<n;i++)
        {
            if(t%a[i] !=0)
            {
                flag1=1;
                break;
            }
        }
        if(flag1 == 0)
        {
            for(j=0;j<m;j++)
            {
                if(b[j]%t !=0)
                {
                    flag2=1;
                    break;
                }
            }
        }
        if(flag1 == 0 && flag2 == 0)
            total++;
    }
    printf("%d\n", total);
    return 0;
}

Kangaroo Hacker Rank Solution in C

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>

char* kangaroo(int x1, int v1, int x2, int v2) {
    // Complete this function
  
if(v1>v2)
{
    if((x2-x1)%(v1-v2) == 0)
        return("YES");
    else
        return("NO");
}
else
    return("NO");
}
int main() {
    int x1;
    int v1;
    int x2;
    int v2;
    scanf("%i %i %i %i", &x1, &v1, &x2, &v2);
    int result_size;
    char* result = kangaroo(x1, v1, x2, v2);
    printf("%s\n", result);
    return 0;
}

Apple and Orange Hacker Rank solution in C

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>

int main(){
    int s,ac=0,oc=0;
    int t;
    scanf("%d %d",&s,&t);
    int a;
    int b;
    scanf("%d %d",&a,&b);
    int m;
    int n;
    scanf("%d %d",&m,&n);
    int *apple = malloc(sizeof(int) * m);
    for(int apple_i = 0; apple_i < m; apple_i++){
       scanf("%d",&apple[apple_i]);
        if(a+apple[apple_i] >= s && a+apple[apple_i] <= t)
            ac++;
    }
    printf("%d\n",ac);
    int *orange = malloc(sizeof(int) * n);
    for(int orange_i = 0; orange_i < n; orange_i++){
       scanf("%d",&orange[orange_i]);
    if(b+orange[orange_i] >= s && b+orange[orange_i] <= t)
            oc++;
    }
    printf("%d",oc);
  
    return 0;
}

Grading Students Hacker Rank Solution in C

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>


int main() {
    int n,c,j=0,result_size;
    scanf("%d", &n);
    int *grades = malloc(sizeof(int) * n);
    int result[n];
    for(int grades_i = 0; grades_i < n; grades_i++){
       scanf("%d",&grades[grades_i]);
       if(grades[grades_i]%5 != 0 )
        {
            c=grades[grades_i];
            while(c%5 !=0)
                c++;
            if((c-grades[grades_i])<3 && c >= 40)
                    result[grades_i]=c;
            else
                result[grades_i]=grades[grades_i];
         }
        else
             result[grades_i]=grades[grades_i];
    }
    result_size=n;
    for(int result_i = 0; result_i < result_size; result_i++) {
        if(result_i) {
            printf("\n");
        }
        printf("%d", result[result_i]);
    }
    puts("");
    return 0;
}

Thursday, 23 November 2017

C Program to print the element that is repeated maximum number of times in an array

If two elements are repeated same number of times, then the smallest element is printed

#include <stdio.h>
main()
{
    int n,i,c,high,max,a[100];
    scanf("%d",&n);
    for(i=0;i<n;i++)
    {
        scanf("%d",&a[i]);
    }
    for(i=0;i<n;i++)
    {
        c=0;
        for(j=i;j<n;j++)
        {
            if(a[i] == a[j])           
                c++;
        }
        if( i == 0)
        {
            max=c;
            high=i;
        }
        else
        {
            if( max<c)
            {
               
                max=c;
                high=i;

            }
            else if( max == c && a[high]> a[i])
                high=i;
        }
    }
printf("%d\t%d",a[high],max);
}

Sunday, 19 November 2017

python code to send SMS data in excel automatically through way2sms

The below code is modification of code found at URL
https://github.com/PratikBodawala/way2sms

 Requirements:
 requests==2.12.4
beautifulsoup4==4.5.3
python 2.7.13

You can also download the code from
https://drive.google.com/file/d/1b-gySD2S5tlyhuwX0LnkyfzEFNMsD_9J/view?usp=sharing

Usage:
Create excel file with msgs in A1,A2,A3 ...cells 
and corresponding phone number in B1,B2,B3 ...cells as shown in below figure



Output:

Once u run the python code
you will be asked to
Enter the way2sms account username i.e, mobile number
Enter the way2sms password
Enter the path where the excel file is
here i have saved the excel file at C:\Users\SARVANI\Desktop\SEC8.xlsx
The excel file name is SEC8.xlsx




===============================================
import getpass
import urllib
import textwrap
import requests
import time
import os
import datetime
from bs4 import BeautifulSoup
import cPickle as pickle
import sys
import openpyxl
sys.stdout.flush()
url = 'http://www.way2sms.com'

class Way2sms(object):
    """mobile and string are keywords parameter of sms method."""
    def __init__(self):
        if os.path.exists('.token'):
            with open('.token', 'r') as Token:
                self.ses, self.token, self.new_url = pickle.load(Token)
            page = self.ses.get(self.new_url+'ebrdg?id='+self.token).text
            if 'Welcome to Way2SMS' in page:
                print 'session is ok'

            else:
                print 'session expired'
                response = requests.head(url, allow_redirects=True)
                self.new_url = response.url
                self.ses = requests.session()
                self.ses.headers.update({'Connection': 'keep-alive', 'Pragma': 'no-cache', 'Cache-Control': 'no-cache', 'Upgrade-Insecure-Requests': '1', 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36', 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'DNT': '1', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'en-US,en;q=0.8'})
                usr = str(raw_input('Enter your mobile number:'))
                pas = getpass.getpass()
                if self.ses.post(self.new_url + 'Login1.action', 'username=' + str(usr) + '&password=' + str(pas)).ok:
                    print "Login successfully"
                    self.token = self.ses.cookies['JSESSIONID']
                    self.token = self.token[4:]
                    with open('.token', 'w') as Token:
                        pickle.dump((self.ses, self.token, self.new_url), Token)
                else:
                    print "Login failed"

        else:
            response = requests.head(url, allow_redirects=True)
            self.new_url = response.url
            self.ses = requests.session()
            self.ses.headers.update({'Connection': 'keep-alive', 'Pragma': 'no-cache', 'Cache-Control': 'no-cache',
                                     'Upgrade-Insecure-Requests': '1',
                                     'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36',
                                     'Content-Type': 'application/x-www-form-urlencoded',
                                     'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
                                     'DNT': '1', 'Accept-Encoding': 'gzip, deflate',
                                     'Accept-Language': 'en-US,en;q=0.8'})
            usr = str(raw_input('Enter your mobile number:'))
            pas = getpass.getpass()
            if self.ses.post(self.new_url + 'Login1.action', 'username=' + str(usr) + '&password=' + str(pas)).ok:
                print "Login successfully"
                self.token = self.ses.cookies['JSESSIONID']
                self.token = self.token[4:]
                with open('.token', 'w') as Token:
                    pickle.dump((self.ses, self.token, self.new_url), Token)
            else:
                print "Login failed"
    def successfully_sent(self, mobile, text):
        date = datetime.date.today().strftime('%d/%m/%Y')
        page = self.ses.post(self.new_url + 'sentSMS.action?dt=' + str(date) + '&Token=' + str(self.token))
        soup = BeautifulSoup(page.text, 'html.parser')
        first = soup.find('div', {'class': 'mess'})
        no = str(first.find('b').text)
        divrb = first.find('div', {'class': 'rb'})
        p = str(divrb.find('p').text)
        if (no == mobile) and (p == text):
            return True
        else:
            return False

    def sms(self):
        filename=str(raw_input('enter path to excel file: '))
        wb = openpyxl.load_workbook(filename)
        ws = wb.get_sheet_by_name('Sheet1')
        #print sheet['B1'].value
        rowcount=ws.max_row
        print rowcount
        for i in range(rowcount):
            mobile = str(ws.cell(row=i+1,column=2).value)
            string = str(ws.cell(row=i+1,column=1).value)       
            if type(mobile) is str:
                mobile = list(str(mobile).split(','))
            if type(mobile) is list:
                for mobile_no in mobile:
                    if len(mobile_no) is not 10:
                        print mobile_no, 'is not valid'
                    else:
                        lofstr = textwrap.wrap(string, 140)
                        for string in lofstr:
                            msglen = len(string)
                            qstring = urllib.quote(string)
                            page = self.ses.post(self.new_url+'smstoss.action', 'ssaction=ss&Token='+str(self.token)+'&mobile='+str(mobile_no)+'&message='+qstring+'&msgLen='+str(140-msglen)).text
                            print 'Sending SMS to', mobile_no,
                            for dot in range(3):
                                print '.',
                                time.sleep(1)
                            if "Rejected : Can't submit your message, finished your day quota." not in page:
                                if self.successfully_sent(mobile_no, string):
                                    print 'sent successfully.'
                                else:
                                    print 'failed to send.'
                            else:
                                print 'quota finished!'
                                sys.exit(1)
    def logout(self):
        self.ses.get(self.new_url+'main.action')
        try:
            os.remove('.token')
        finally:
            print 'Log-out!'
            sys.exit(0)       
if __name__ == '__main__':
   
        Way2sms().sms()
        Way2sms().logout()
================================


Wednesday, 15 November 2017

Recursive function that decodes a string of 0's and 1's into a two-digit number.



Write a recursive function that decodes a string of 0's and 1's into a two-digit number. The input string will consist of a sequence of 0's - representing the first digit, followed by a sequence of 1's - representing the second digit.


For example, the string: "0001111"
Represents the number 34

Solution:
#include <stdio.h>
void rec(char *st, int i, int c,int d)
{
    if(st[i] == '\0')
        printf("%d %d",c,d);
    if(st[i] == '0')
        rec(st,i+1,c+1,d);
    if(st[i] == '1')
        rec(st,i+1,c,d+1);
}           
int main()
{
    char st[8];
    scanf("%s",st);
    rec(st,0,0,0);
    return 0;
}


Friday, 10 November 2017

Calendar program in C

#include<stdio.h>
void main()
{
                int d,dd,mm,y,i,j,count=0,k=1,m;
                printf("enter date");
                scanf("%d",&d);
                printf("enter month");
                scanf("%d",&mm);
                printf("enter year");
                scanf("%d",&y);
                dd=1;
                if(mm == 4 || mm == 6||mm == 9||mm == 11)
                                m=30;
                else if(mm == 2)
                {
                                if(y%4 == 0)
                                                m=29;
                                else
                                                m=28;
                }
                else
                                m=31;
                if(y==2000&&mm<=2)
                                dd=dd-1;

                count=count+(dd%7);
                if(mm==1)
                                count=count+0;
                else if(mm==2)
                                count=count+3;
                else if(mm==3)
                                count=count+3;
                else if(mm==4)
                                count=count+6;
                else if(mm==5)
                                count=count+1;
                else if(mm==6)
                                count=count+4;
                else if(mm==7)
                                count=count+6;
                else if(mm==8)
                                count=count+2;
                else if(mm==9)
                                count=count+5;
                else if(mm==10)
                                count=count+0;
                else if(mm==11)
                                count=count+3;
                else if(mm==12)
                                count=count+5;
                else
                                printf("wrong entry");
                i=y%100;
                count=count+(i/4)+(i%7);
                if(y>=1800&&y<=1899)
                                count=count+2;
                else if(y>=1900&&y<=1999)
                                count=count+0;
                else if(y>=2000&&y<=2099)
                                count=count+6;
                else if(y>=2100&&y<=2199)
                                count=count+4;
                else
                                printf("enter year between 1800 to 2199 only");
                j=count%7;
                printf("sun mon tue wed thu fri sat \n");
                printf("\n");
                for(i=0;i<m+j;i++)
                {
                                if(i<j)
                                                printf("    ");
                                else
                                {
                                                if(i%7 == 0)
                                                                printf("\n");
                                                if(i == d+j-1)
                                                {
                                                                if(k<10)
                                                                                printf(" *%d ",k++);
                                                                else
                                                                                printf("*%d ",k++);
                                                }
                                                else
                                                {
                                                                if(k<10)
                                                                                printf("  %d ",k++);
                                                                else
                                                                                printf(" %d ",k++);
                                            }
                                }
                    }
}




Output:


Wednesday, 8 November 2017

Delete duplicate-value nodes from a sorted linked list Hacker rank solution in C

Node* RemoveDuplicates(Node *head)
{
    Node *c=head;
    if(head == NULL || head ->next == NULL)
        return head;
    while(c->next != NULL)
    {
        if(c->data == c->next->data)
        {
            c->next = c->next->next;
        }
        else
            c=c->next;           
    }
    return head;
}