Friday, 24 November 2017

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: