Friday 8 November 2013

Standard Deviation of a sentence



Write a program to input a piece of text consisting of sentences terminated by either ‘.’ or ‘!’ or ‘?’. The program should output the mean and standard deviation of the lengths of sentences (measured in words). Each word is separated by a blank space.
Mean =>                     x’         = n
                                                     å x i
                                                         i= 1
                                                ---------------
                               n  

where x i is the length of the ith sentence and n is the total number of sentences.

Standard Deviation
          n
s = Ö å( xi – x’)2
            i=1
      -----------------
            n
  ( Assume a maximum of 10 sentences ) . Test your program for the following input :
HELLO!HOW ARE YOU?HOPE EVERYTHING IS FINE.BEST OF LUCK.

Answer 2.

class Q2_1998
{
 //Data members
 private String para;
 private int len;
 private String []sentences;
 private int nos;
 private int []lensent;
 //Constructor
 public Q2_1998(String par)
 {
     para=par+" ";
     len = para.length();
     sentences=new String[10];
     nos=0;
     lensent=new int[10];
     int i;
     //Initilizing array for storing length of sentences
     for(i=0;i<10;i++)
       lensent[i]=0;
 }
 //method to extract sentences
 public void Extract()
 {
        para=para.toUpperCase();
        String word="",sent="";
        int i;
        char letr;
        for(i=0;i<len;i++)
        {
            letr=para.charAt(i);
            if(letr!=' ')
                word+=letr;
           
            if(letr==' ')
            {
                sent+=word;
                sent+=" ";
                word="";
            }
          
            if(letr=='.'||letr=='!'||letr=='?')
            {
                sent+=word;
                sent+=" ";
                i++;//so as not to pick up the blank after the ., ? or !
                sentences[nos]=sent;
                sent="";
                nos++;
                word="";
            }
        }
    }
  
   //method to find length of sentences
   public void findlength()
   {
       int i,j;
       char letter;
       Extract();
       for(i=0;i<nos;i++)
       {
           for(j=0;j<sentences[i].length();j++)
           {
               letter=sentences[i].charAt(j);
               if(letter==' ')
                 lensent[i]++;
            }
      }
    }
    //method to find standard deviation
    public void standarddeviation()
    {
        int i,sum=0;
        double mean,std=0;
        findlength();
      //Finding total length of all sentences
      for(i=0;i<nos;i++)
        sum+=lensent[i];
      mean=sum/nos;
      //Finding standard deviation
      for(i=0;i<nos;i++)
      {
          std=Math.sqrt((Math.pow((lensent[i]-std),2))/nos);
          System.out.println(sentences[i]+"\t\t\t deviates from mean by \t\t"+ std);
      }
    }
}
       
       
 import java.io.*;
class Q2_1998main
{
 public static void main(String args[])
 throws IOException
    {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        String para;
        System.out.println("Enter a paragraph ");
        para=br.readLine();
        Q2_1998 obj= new Q2_1998(para);
        obj.standarddeviation();
    }
}          


              

Output


  Enter a paragraph
HELLO! HOW ARE YOU? HOPE EVERYTHING IS FINE. BEST OF LUCK.

HELLO!                                               deviates from mean by                      0.5
HOW ARE YOU?                                deviates from mean by                      1.25
HOPE EVERYTHING IS FINE.          deviates from mean by                      1.375
BEST OF LUCK.                                 deviates from mean by                      0.8125

Wednesday 30 October 2013

Mersenne Numbers

In mathematics, a Mersenne prime is a prime number of the form . They are named after the French monk Marin Mersenne who studied them in the early 17th century.

If n is a composite number then so is 2n − 1. The definition is therefore unchanged when written where p is assumed prime.

More generally, numbers of the form without the primality requirement are called Mersenne numbers. Mersenne numbers are sometimes defined to have the additional requirement that n be prime, equivalently that they bepernicious Mersenne numbers, namely those pernicious numbers whose binary representation contains no zeros. The smallest composite pernicious Mersenne number arises with p = 11.

A double Mersenne number is a Mersenne number of the form

where p is a Mersenne prime exponent.


import java.util.Scanner;
public class Numbers
{
long number;
Numbers(long n)
{
number=n;
}
boolean isMersenne(){
long n=0;
for(int i=1;i<=20;i++)
{
n=(long)(Math.pow(2,i)-1);
if(n==number){
return true;
}
}
return false;
}
boolean isDoubleMersenne(){
long n=0;long pwr=0;
for(int i=1;i<=20;i++)
{
pwr=(long)Math.pow(2,i)-1;
n=(long)(Math.pow(2,pwr)-1);
if(n==number)
{
return true;
}
}
return false;
}
public void genMersenneNos(){
long num=0;
System.out.println("Generated Mersenne numbers are :");
for(int i=1;i<=10;i++)
{
num=(long)(Math.pow(2,i)-1);
System.out.print(num+" ");
}
System.out.println();
}
public void genDoubleMersenneNos()
{
long num=0;long pwr=0;
System.out.println("Generated double Mersenne Numbers are:");
for(int i=1;i<=6;i++)
{
pwr=(long)Math.pow(2,i)-1;
num=(long)(Math.pow(2,pwr)-1);
System.out.print(num+" ");
}
System.out.println();
}
public static void main(String[]args){
Scanner in=new Scanner(System.in);
long n;
System.out.println("Enter a number");
n=in.nextLong();
Numbers numObject=new Numbers(n);
if(numObject.isDoubleMersenne()==true)
{
System.out.println(n+"is a double Mersenne Number");
numObject.genDoubleMersenneNos();
}
else if(numObject.isMersenne()==true)
{
System.out.println(n+"is a Mersenne Number");
numObject.genMersenneNos();
}
else
System.out.println(n+"is neither a Mersenne Number nor a Double Mersenne Number");
}
}

Catalan Numbers

In combinatorial mathematics, the Catalan numbers form a sequence of natural numbers that occur in various counting problems, often involving recursively defined objects. They are named after the Belgian mathematician Eugène Charles Catalan(1814–1894).

The nth Catalan number is given directly in terms of binomial coefficients by


The first Catalan numbers for n = 0, 1, 2, 3, … are
1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796, 58786, 208012, 742900, 2674440, 9694845, 35357670, 129644790, 477638700, 1767263190, 6564120420, 24466267020, 91482563640, 343059613650, 1289904147324, 4861946401452, …


import java.util.Scanner;
class Catalan
{
public static void main(String[ ] args)
{
Scanner in=new Scanner (System.in);
System.out.println("Enter value of n(1...10):");
int n=in.nextInt();
long n1,n2,a;
long CatNumber;
int cnt=1;
if(n>=1 && n<=10)
{
for(a=1;a<=n;a++)
{
long factofa=1,factof2a=1;
for(long i=1;i<=a;i++)
factofa*=i;
for(long i=1;i<=2*a;i++)
factof2a*=i;
CatNumber=factof2a/((factofa*factofa)*(a+1));
System.out.println(" "+cnt++ +". "+CatNumber);
}
}
}
}

Monday 28 October 2013

Printing a sentence in reverse order of words

The input in this problem will consist of a number of lines of English text consisting of the letters of the English alphabet, the punctuation marks (‘) apostrophe, (.) full stop, (,) comma, (;) semicolon, (:) colon and white space characters (blank, newline). Your task is to print the words of the text in reverse order without any punctuation marks other than blanks.
For example consider the following input text :
This is a simple piece of text to illustrate this problem.

If you are smart you will solve this right.

The corresponding output would read as:

right this solve will you smart are you If problem this illustrate to text of piece sample a is This

That is, the lines are printed in reverse order.
Note:- Individual words are not reversed.

Input format

The first line of input contains a single integer N (<=20), indicating the number of lines in the input. This is followed by N lines of input text. Each line should accept a maximum of 80 characters.

Output format

Output the text containing the input lines in reverse order without punctuations except blanks as illustrated above.

Test your program for the following data and some random data.

SAMPLE DATA

INPUT :

2
Emotions, controlled and directed to work, is character. By Swami Vivekananda.

OUTPUT :
Vivekananda Swami By character is work to directed and controlled Emotions


INPUT :

1
Do not judge a book by its cover.

OUTPUT :
cover by its book a judge not Do


Answer 2.
import java.io.*;
class Q2_2007
{
  //Data members
  private String para;
  private String newpara;
  int len;
  int n;
  //Constructor
  public Q2_2007()
  {
      para="";
      newpara="";
      len=0;
  }
  //Function to input string
  public void Input()
  throws IOException
  {
     BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
     System.out.print("Enter number of lines ::");
     n=Integer.parseInt(br.readLine());
     System.out.println("Enter a paragraph of "+ n + " lines ");
     para=br.readLine();
     para=" "+para;
     len=para.length();
  }
  //Function to reverse para
  public void Reversepara()
  {
      int i;
      String word="";
      char letter;
      for(i=(len-1);i>=0;i--)
      {
          letter = para.charAt(i);
          if(letter!='\'' && letter!='.'&&letter!=','&&letter!=';'&&letter!=':'&&letter!=' ')
            word=letter+word;
          else
          {
              newpara+=word;
              newpara+=" ";
              word="";
            }
        }
        System.out.println("\n new paragraph ::\n"+newpara);
    }
}
 
import java.io.*;
class Q2_2007main
{
   public static void main(String args[])
   throws IOException
    {
        Q2_2007 obj = new Q2_2007();
        obj.Input();
        obj.Reversepara();
    }
}

Output
Enter number of lines ::2
Enter a paragraph of 2 lines
Emotions, controlled and directed to work, is character. By Swami Vivekanda.

 new paragraph ::
 Vivekanda Swami By  character is  work to directed and controlled  Emotions

Enter number of lines ::1
Enter a paragraph of 1 lines
Do not judge a book by its cover.

 new paragraph ::
 cover its by book a judge not Do  

Friday 25 October 2013

Anagrams

We would like to generate all possible anagrams of a word. For example if the given word is 'TOP', there will be 6 possible anagrams:
       TOP
       TPO
       OPT
       OTP
       PTO
       POT

An anagram must be printed only once. You may output the anagrams in any order. Also output the total number of anagrams. You assume that the number of letter, n, in the word will be 7 at most, i.e. n<= 7
Test your program for the given data and some random data.

SAMPLE DATA:
     INPUT:
                       TO

OUTPUT:
                     TO
                     OT
Total number of anagrams = 2

INPUT :
                     LEAN
OUTPUT:
                     LEAN
                     LENA
                     LAEN
                     LANE
                     LNEA
                     LNAE
                     EALN
                     EANL
                     ELAN
                     ELNA
                     ENLA
                     ENAL
                     ALNE
                     ALEN
                     ANLE
                     ANEL
                     AENL
                     NLEA
                     NLAE
                     NELA
                     NEAL
                     NALE
                     NAEL
Total number of anagrams = 24




import java.io.*;
public class Anagrams
{
    String str;
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    int counter=0;
    public void take()throws Exception
    {
        System.out.println("\nEnter the word:");
        str=br.readLine();
        show("", str);
        System.out.println("Total number of anagrams ="+counter);
    }

    public void show(String s, String str)
    {
        if(str.length()<= 1)
        {
            counter++;
            System.out.println(s+str);
        }
        else
        {
            for(int i = 0; i< str.length(); i++)
            {
                String str1 = str.substring(i, i + 1);
                String str2 = str.substring(0, i);
                String str3 = str.substring(i + 1);
                show(s + str1, str2 + str3);
            }
        }
    }

    public static void main(String args[])throws Exception
    {
        Anagrams ob=new Anagrams();
        ob.take();
    }
}