The Programming Project

Thursday, October 16, 2014

Number letter counts : Problem 17 : JAVA CODE

Number letter counts : Problem 17 : Project Euler

 

If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.
If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used?

NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of "and" when writing out numbers is in compliance with British usage.

JAVA CODE

import java.util.*;
public class NumberLetterCount {
    public static void main(String[] args) {
        ToWords numbObject = new ToWords();
        for(int i = 1; i <=1000; i++) {
            numbObject.toWord(i);
            }
        System.out.println("Letters used:"+numbObject.totalLetterCount());   
        }
    }
class ToWords {
    public void toWord(int numb) {
        this.number = numb;
        this.word = "";
        String temp = "";
        temp +=number;
        switch(temp.length()) {
            case 1:
                word = oneTwoDigit[number-1];
                           
            break;
           
            case 2:
                if ( number <= 20)
                    word = oneTwoDigit[number-1];
                   
                else {
                    if ( (temp.charAt(1)-48) == 0 )
                         word += tens[(temp.charAt(0)-48)-1];
                       
                    else    
                         word += tens[(temp.charAt(0)-48)-1]+ " "+oneTwoDigit[(temp.charAt(1)-48)-1];
                       
                    }
            break;
           
            case 3:
                if ( (temp.charAt(1)-48) == 0 && (temp.charAt(2)-48) == 0)
                    word += hundreds[(temp.charAt(0)-48)-1];
                   
                else if ( (temp.charAt(2)-48) == 0 )    
                    word += hundreds[(temp.charAt(0)-48)-1]+" and "+tens[(temp.charAt(1)-48)-1];
                   
                else {
                    if ( (temp.charAt(1)-48) == 0 )
                        word += hundreds[(temp.charAt(0)-48)-1]+" and "+oneTwoDigit[(temp.charAt(2)-48)-1];
                       
                    else   
                        if ( (temp.charAt(1)-48) == 1 )
                             word += hundreds[(temp.charAt(0)-48)-1]+" and "+oneTwoDigit[(temp.charAt(2)-48)-1+10];
                        else   
                            word += hundreds[(temp.charAt(0)-48)-1]+" and "+tens[(temp.charAt(1)-48)-1]+"-"+oneTwoDigit[(temp.charAt(2)-48)-1];   
                       
                    }
            break;
           
            case 4:
                word = "One Thousand";
               
            break;
            }   
        System.out.println(number+" in words: "+word);
        lettersCount(word);   
        }   
    private void lettersCount(String word) {   
        for( int i = 0; i < word.length(); i++ )
            if (word.charAt(i) == ' ' || word.charAt(i) == '-')
                continue;
            else
                letterCount +=1;   
        }
    public int totalLetterCount() {
        return letterCount;
        }   
    private String[] oneTwoDigit =  {"One","Two","Three","Four","Five","Six","Seven",
                    "Eight","Nine","Ten","Eleven","Twelve",
                    "Thirteen","Fourteen","Fifteen","Sixteen",
                    "Seventeen","Eighteen","Nineteen","Twenty"};   
                   
    private String[] tens =     {"Ten","Twenty","Thirty","Forty","Fifty","Sixty",
                     "Seventy","Eighty","Ninety"};
               
    private String[] hundreds =     {"One Hundred","Two Hundred","Three Hundred","Four Hundred","Five Hundred",
                         "Six Hundred","Seven Hundred","Eight Hundred","Nine Hundred"};               
    private int number;
    private int letterCount = 0;
    private String word;   
    }           

Wednesday, October 15, 2014

Goldbach's other conjecture : Problem 46 Pyhton Code

Goldbach's other conjecture : Problem 46

It was proposed by Christian Goldbach that every odd composite number can be written as the sum of a prime and twice a square.
9 = 7 + 2×12
15 = 7 + 2×22
21 = 3 + 2×32
25 = 7 + 2×32
27 = 19 + 2×22
33 = 31 + 2×12
It turns out that the conjecture was false.
What is the smallest odd composite that cannot be written as the sum of a prime and twice a square?

Problem Source :  Euler Project

Python Code

import math
def goldbachConjecture():
    found = False
    def checkPrime(numb):
        prime = True
        if numb == 1:
            return False
        for i in range(int(math.sqrt(numb))):
            i = i+2
            if numb%i == 0:
                prime = False
                break
        if numb == 2:
            return True
        else:           
            return prime
    def nextOddCompositeNumber(numb):
        numb = numb+1
        while checkPrime(numb) == True or numb %2 == 0:
            numb = numb+1
        return numb;           
    numb = 9    
    while found == False:
        k = 1
        goldtrue = False
        while numb-2*k**2 > 0 :
            if checkPrime(numb-2*k**2) == True:
                goldtrue = True
                break
            k = k+1   
        if goldtrue == True:
            found = False
            numb = nextOddCompositeNumber(numb)
        else:
            found = True
            print "smallest odd composite that cannot be written as the sum of a prime and twice a square",numb
goldbachConjecture()           

Friday, October 10, 2014

Insertion Sort : Python Code & Linked List implementation

Insertion sort iterates, consuming one input element each repetition, and growing a sorted output list. Each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list, and inserts it there. It repeats until no input elements remain.
Sorting is typically done in-place, by iterating up the array, growing the sorted list behind it. At each array-position, it checks the value there against the largest value in the sorted list (which happens to be next to it, in the previous array-position checked). If larger, it leaves the element in place and moves to the next. If smaller, it finds the correct position within the sorted list, shifts all the larger values up to make a space, and inserts into that correct position.


Python Code

import random
def InsertionSort():
    N = input("Enter the number of elements in the list:")
    unsortedList = [0 for i in range(N)]
    for i in range(N):
        """ user input can be taken here"""
        unsortedList[i] = int(random.random()*N)
        i = i + 1
    print 'Unsorted list is:',unsortedList
    i = 0
    sortedList = [0 for i in range(N)]
    sortedList[0] = unsortedList[0]
    """ counter holds the number of elements inserted in the sorted list"""
    counter = 1
    for i in range (N-1):
        i = i + 1
        temp = counter
        while unsortedList[i] < sortedList[counter-1] and counter > 0:
            sortedList[counter] = sortedList[counter-1]
            counter = counter - 1
        sortedList[counter] = unsortedList[i]
        temp = temp+1
        counter = temp
    print 'Sorted list is:',sortedList           
InsertionSort()   

Wednesday, October 8, 2014

Binary Tree Traversal : C Code


Binary Tree Traversals inorder,preorder and postorder.  

#include<stdlib.h>
#include<stdio.h>
struct binaryTree {
   int key;
   struct binaryTree *right, *left;
};

typedef struct binaryTree node;

void insert(node **tree, int val);
void preorderTraversal(node *root);
void inorderTraversal(node *root);
void postorderTraversal(node *root);

int main() {
   node *root;
   int i,val,search;
   root = NULL;
   while(1) {
      printf("\n Enter the value (-1 to exit):");
      scanf("%d",&val);   
      if( val == -1)
          break;
      insert(&root, val);
   }
   printf("\n Pre-order Traversal:");
   preorderTraversal(root);
   printf("\n");
   printf("\n Inorder Traversal:");
   inorderTraversal(root);
   printf("\n");
   printf("\n Postorder Traversal:");
   postorderTraversal(root);
   printf("\n");
   return 0;
}
void postorderTraversal(node *root) {
    if (root != NULL) {
            postorderTraversal(root->left);
            postorderTraversal(root->right);
              printf("%d ",root->key);
                }
    }
void inorderTraversal(node *root) {
    if (root != NULL) {
            inorderTraversal(root->left);
              printf("%d ",root->key);
                inorderTraversal(root->right);
               }
    }
void preorderTraversal(node *root) {
    if (root != NULL)
        printf("%d ",root->key);
    if (root->left != NULL)
        preorderTraversal(root->left);   
    if (root->right != NULL)
        preorderTraversal(root->right);       
    }
void insert(node **tree, int val) {
   if((*tree) == NULL) {
      *tree = (node *)malloc(sizeof(node));
      (*tree)->key = val;
      (*tree)->right=(*tree)->left=NULL;
      return;
   }
   if(val < (*tree)->key)
      insert(&(*tree)->left, val);
   else if(val > (*tree)->key)
      insert(&(*tree)->right, val);
    }

Binary Search Tree (BST) : Finding Leaves : C Code

 Binary Search Tree (BST) : Finding Leaves : C Code

The following C code prints all the leaves nodes of a Binary Search Tree. A leaf-node is a node which has not left or right child. The code first scans the root node and looks whether it has a left and right child or not. If the condition is satisfied, it  is a leave node or else we recursively examine the left and right child.

#include<stdlib.h>
#include<stdio.h>
struct binaryTree {
   int key;
   struct binaryTree *right, *left;
};

typedef struct binaryTree node;

void insert(node **tree, int val);
void printLeaves(node *root);

int main() {
   node *root;
   int i,val,search;
   root = NULL;
   while(1) {
      printf("\n Enter the value (-1 to exit):");
      scanf("%d",&val);   
      if( val == -1)
          break;
      insert(&root, val);
   }
  
   printLeaves(root);
   printf("\n");
   
   return 0;
}
void printLeaves(node *root) {
    if (root->right == NULL && root->left == NULL) {
        printf("\n Leaf Node: %d",root->key);
        return;
        }
    if(root->right != NULL)    
        printLeaves(root->right);
    if(root->left != NULL)   
    printLeaves(root->left);
    }
void insert(node **tree, int val) {
   if((*tree) == NULL) {
      *tree = (node *)malloc(sizeof(node));
      (*tree)->key = val;
      (*tree)->right=(*tree)->left=NULL;
      return;
   }
   if(val < (*tree)->key)
      insert(&(*tree)->left, val);
   else if(val > (*tree)->key)
      insert(&(*tree)->right, val);
    }

Tuesday, October 7, 2014

Binary Tree C Code : Insertion : Find Max & MIn

In computer science, a binary search tree (BST), sometimes also called an ordered or sorted binary tree, is a node-based binary tree data structure where each node has a comparable key (and an associated value) and satisfies the restriction that the key in any node is larger than the keys in all nodes in that node's left subtree and smaller than the keys in all nodes in that node's right sub-tree.

Insertion begins as a search would begin; if the key is not equal to that of the root, we search the left or right subtrees as before. Eventually, we will reach an external node and add the new key-value pair  as its right or left child, depending on the node's key. In other words, we examine the root and recursively insert the new node to the left subtree if its key is less than that of the root, or the right subtree if its key is greater than or equal to the root. Self referential structure has been used to link the nodes starting from the root node. In the code below, maximum and minimum value in the BST has been also calculated.


#include<stdlib.h>
#include<stdio.h>
struct binaryTree {
   int key;
   struct binaryTree *right, *left;
};

typedef struct binaryTree node;

void insert(node **tree, int val);
void findMax(node *root);
void findMin(node *root);
void searchKey(node *,int key);

int main() {
   node  *root;
   int i,val,search;
   root = NULL;
   while(1) {
      printf("\n Enter the value (-1 to exit):");
      scanf("%d",&val);  
      if( val == -1)
          break;
      insert(&root, val);
   }
 
   findMin(root);
   printf("\n");
 
   findMax(root);
   printf("\n");
 
   printf("\n Enter the value to be searched:");
   scanf("%d",&search);
   searchKey(root,search);
   printf("\n");
  
   return 0;
}
void searchKey(node *root,int search) {
    if (root == NULL) {
        printf("\n Element Not Found:");
        return;
        }
    if (root->key == search) {
        printf("\n Key found:");
        return;
        }
    root->key < search ? searchKey(root->right,search) : searchKey(root->left,search);
    }
  
void findMax(node *root) {
    while(root->right != NULL)
        root = root->right;
    printf("\n Maximum value is:%d",root->key);
    }
  
void findMin(node *root) {
    while(root->left != NULL)
        root = root->left;
    printf("\n Minimum value is:%d",root->key);
    }  
  
void insert(node **tree, int val) {
   if((*tree) == NULL) {
      *tree = (node *)malloc(sizeof(node));
      (*tree)->key = val;
      (*tree)->right=(*tree)->left=NULL;
      return;
   }
   if(val < (*tree)->key)
      insert(&(*tree)->left, val);
   else if(val > (*tree)->key)
      insert(&(*tree)->right, val);
    }

Monday, October 6, 2014

Addition of positive numbers using linked list: C code

Addition of large positive integers in C is quite difficult since there will be overflow error once the range of 'int' is crossed. But this problem can be overcome by the use of linked list. Happy addition! 



#include<stdio.h>
#include<stdlib.h>
struct numberList {
    int data;
    struct numberList *nextDigit;
    struct numberList *revDigit;
    };
    typedef struct numberList node;
void inputNumber(node*);
void display(node*,int);   
void addNumber(node*,node*);
int main() {
   
    node *firstNumber,*secondNumber,*sum;
    firstNumber = (node *)malloc(sizeof(node));
    secondNumber = (node *)malloc(sizeof(node));
    printf("\n Enter the first number(one digit at a time) type -1 to terminate the number:");
    printf("\n Enter the digit:");
    scanf("%d",&firstNumber->data);
    inputNumber(firstNumber);
   
    printf("\n Enter the second number(one digit at a time) type -1 to terminate the number:");
    printf("\n Enter the digit:");
    scanf("%d",&secondNumber->data);
    inputNumber(secondNumber);
   
    display(firstNumber,1);
    display(secondNumber,2);
   
    addNumber(firstNumber,secondNumber);   
    return 0;
    }   
void addNumber(node *p,node *q) {
    int len1=0,len2=0,min,i,once=0;
    while (p->nextDigit !=NULL) {
        len1++;
        p = p->nextDigit;
        }
    p = p->revDigit;   
    while (q->nextDigit !=NULL) {
        len2++;
        q = q->nextDigit;
        }
    q = q->revDigit;
    min = len1 <= len2 ? len1:len2;
    node *sum,*tmp,*sum1;   
    sum = (node *)malloc(sizeof(node));
    sum1 = sum;
    sum->revDigit = NULL;
    for ( i = 1; i <= min; i++) {
        sum->data = (p->data+q->data+once)%10;
        tmp = sum;
        once = (p->data+q->data+once)/10;
        p=p->revDigit;
        q=q->revDigit;
        sum->nextDigit = (node *)malloc(sizeof(node));
        sum = sum->nextDigit;
        sum->revDigit=tmp;
        }
    if ( len1 == len2 && once !=0) {
        sum->data = once;
        sum->revDigit=tmp;
        }   
    if (len1 > len2) {
        int t = len1-len2;
        sum = sum->revDigit;
        for ( i = 1; i<=t; i++) {
            tmp = sum;
            sum->nextDigit = (node *)malloc(sizeof(node));
            sum = sum->nextDigit;
            sum->revDigit=tmp;
            sum->data = (p->data+once)%10;
            once = (p->data+once)/10;
            p = p->revDigit;
            } 
        if ( once !=0) {
            tmp = sum;
            sum->nextDigit = (node *)malloc(sizeof(node));
            sum = sum->nextDigit;
            sum->data = once;
            sum->revDigit=tmp;
            }
               
        }   
    if (len1 < len2) {
        sum = sum->revDigit;
        int t = len2-len1;
        for ( i = 1; i<=t; i++) {
            tmp = sum;
            sum->nextDigit = (node *)malloc(sizeof(node));
            sum = sum->nextDigit;
            sum->revDigit=tmp;
            sum->data = (q->data+once)%10;
            once = (q->data+once)/10;
            q = q->revDigit;
            }
        if ( once !=0) {
            tmp = sum;
            sum->nextDigit = (node *)malloc(sizeof(node));
            sum = sum->nextDigit;
            sum->data = once;
            sum->revDigit=tmp;
            }   
        }   
    sum->nextDigit = NULL;   
    printf("\n Sum of the numbers is:");
    while (sum1->nextDigit !=NULL) {
        //printf("\n%d",sum1->data);
        sum1 = sum1->nextDigit;
        }
    //sum1 = sum1->revDigit;   
    while (sum1 !=NULL) {
        printf("%d",sum1->data);
        sum1 = sum1->revDigit;
        }
    printf("\n");   
    }   
void display(node *p,int tx) {
    if (tx==1)
        printf("\nFirst Number\n");
    else
        printf("\nSecond Number\n");
    while (p->nextDigit !=NULL) {
        printf("%d",p->data);
        p = p->nextDigit;
        }
    p = p->revDigit;   
    /*while (p !=NULL) {
        //printf("%d",p->data);
        p = p->revDigit;
        }*/   
    }   
void inputNumber(node *p) {
    node *q;
    p->revDigit = NULL;
    while (1) {
        q = p;
        p->nextDigit = (node *)malloc(sizeof(node));
        p = p->nextDigit;
        printf("\n Enter the digit:");
        scanf("%d",&p->data);
        p->revDigit = q;
        if (p->data == -1)
            break;
        }
    p->nextDigit = NULL;
    }