Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Wednesday, May 9, 2012

Printing numbers in spiral form using Java



import java.io.*;
public class spiral
{
    public static void main(String args[])throws IOException
    {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter the value of n:");
        int n=Integer.parseInt(br.readLine());
        int a[][]=new int[n][n];
        int i,j,x=1,p=0,q=n-1;
        while(x<=(n*n))
        {
            for(i=p;i<=q;i++)
            {
                a[p][i]=x;
                x++;
            }
            for(i=(p+1);i<=q;i++)
            {
                a[i][q]=x;
                x++;
            }
            for(i=(q-1);i>=p;i--)
            {
                a[q][i]=x;
                x++;
            }
            for(i=(q-1);i>=(p+1);i--)
            {
                a[i][p]=x;
                x++;
            }
            p++;
            q--;
        }
        for(i=0;i<n;i++)
        {
            for(j=0;j<n;j++)
            {
                System.out.print(a[i][j]+" ");
            }
            System.out.println();
        }
    }
}

Decimal to Roman Conversion using Java



import java.io.*;
public class RomanConversion
{  
    // Parallel arrays used in the conversion process.
    private static final String[] RCODE = {"M", "CM", "D", "CD", "C", "XC", "L","XL","X","IX", "V","IV","I"};
    private static final int[]    BVAL  = {1000, 900, 500, 400,  100,  90,  50, 40,  10,   9,   5,  4,   1};
    public static String binaryToRoman(int binary)
    {
       if (binary <= 0 || binary >= 4000)
       throw new NumberFormatException("Value Outside Roman Numeral Range");
       String roman="";// Roman notation will be accumualated here.      
       // Loop from biggest value to smallest, successively subtracting,
       // from the binary value while adding to the roman representation.
       for (int i=0;i<RCODE.length;i++)
       {
           while (binary>=BVAL[i])
           {
               binary-=BVAL[i];
                roman+=RCODE[i];
           }
       }
       return roman;
   }
   public static void main(String args[])throws IOException
   {
     BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
     System.out.print("Enter The Number:");
     int no=Integer.parseInt(br.readLine());
     System.out.print("Roman: "+binaryToRoman(no));
   }
}
//--------------------------------------------------------------------------
/**
 Output:-

 Enter The Number:1995
 Roman: MCMXCV

 Enter The Number:880
 Roman: DCCCLXXX

 Enter The Number:3818
 Roman: MMMDCCCXVIII
 */

Magic Square using JAVA


import java.io.*;
public class MagicSquare
{
    public static void main(String args[])throws IOException
        {
            BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
            System.out.print("Enter the value of n:");
            int n=Integer.parseInt(br.readLine());
            if(n%2==0)
            {              
                System.out.print("N must be odd!!...Please re-enter:");
                n=Integer.parseInt(br.readLine());
            }
            int[][] magic=new int[n][n];
            int row=n-1;
            int col=n/2;
            magic[row][col]=1;
            for (int i=2;i<=n*n;i++)
            {
                if(magic[(row+1)%n][(col+1)%n]==0)
                 {
                     row=(row+1)%n;
                     col=(col+1)%n;
                    }
                    else
                    {
                        row=(row-1+n)%n;
                    }
                    magic[row][col]=i;
                }
                for(int i=0;i<n;i++)
                {
                    for(int j=0;j<n;j++)
                    {
                        if(magic[i][j]<10) System.out.print(" ");//for alignment
                        if(magic[i][j]<100) System.out.print(" ");//for alignment
                        System.out.print(magic[i][j]+" ");
                    }
                    System.out.println();
                }
            }
        }
//------------------------------------------------------------------------------
/**
 Output:-

 Enter the value of n:3

  4   9   2
  3   5   7
  8   1   6
 
 Enter the value of n:5

 11  18  25   2   9
 10  12  19  21   3
  4   6  13  20  22
 23   5   7  14  16
 17  24   1   8  15

 Enter the value of n:6
 N must be odd!!...Please re-enter:7

 22  31  40  49   2  11  20
 21  23  32  41  43   3  12
 13  15  24  33  42  44   4
  5  14  16  25  34  36  45
 46   6   8  17  26  35  37
 38  47   7   9  18  27  29
 30  39  48   1  10  19  28
 */      

Linked List Using JAVA


import java.io.*;
 class Node{
     protected int data;
     protected Node link;
   
     public Node(){
         link=null;
         data=0;
        }
        public Node (int d,Node n)
        {
            data=d;
            link=n;
        }
        public void setlink(Node n)
        {
            link=n;
        }
        public void setData(int d)
        {
            data=d;
        }
        public Node getlink()
        {
            return link;
        }
        public int getData(){
            return data;
        }
    }
   

class linklist{
        protected Node start;
        public linklist()
        {
            start=null;
        }
        public boolean isEmpty()
        {
            return start==null;
        }
        public void Insert(int val)
        {
            Node nptr,ptr,save=null;
            nptr=new Node(val,null);
            boolean ins=false;
            if(start==null)
            start=nptr;
            else if(val<=start.getData())
            {
                nptr.setlink(start);
                start=nptr;
            }
            else {
                save=start;
                ptr=start.getlink();
                while(ptr!=null)
                {
                    if(val>=save.getData() && val<=ptr.getData())
                    {
                        save.setlink(nptr);
                        nptr.setlink(ptr);
                        ins=true;
                        break;
                    }
                    else{
                        save=ptr;
                        ptr=ptr.getlink();
                    }
                }
                if(ins==false)
                {
                    save.setlink(nptr);
                }
            }
        }
        public void Traverse()
        {
            Node ptr=start;
           System.out.print(start.getData()+"-->");
            ptr=start.getlink();
            while(ptr.getlink()!=null)
            {
               System.out.print(ptr.getData()+"-->");
                ptr=ptr.getlink();
            }
            System.out.print(ptr.getData()+".");
            System.out.println();
        }

    public void split(linklist L1,linklist L2)
    {
        Node ptr=start;
        int n=0;
           n=start.getData();
           if(prime(n)==true)
           L1.Insert(n);
           else if(prime(n)==false)
           L2.Insert(n);
            ptr=start.getlink();
            while(ptr.getlink()!=null)
            {
               n=ptr.getData();
               if(prime(n)==true)
               L1.Insert(n);
               else if(prime(n)==false)
               L2.Insert(n);
               ptr=ptr.getlink();
            }
            n=ptr.getData();
            if(prime(n)==true)
            L1.Insert(n);
            else if(prime(n)==false)
            L2.Insert(n);
            System.out.println();
    }
    public boolean prime(int n)
    {
       boolean flag=true;
       for(int i=2;i<n;i++)
       {
           if(n%i==0)
           {
           flag=false;
           break;
        }
    }
    if(flag==true)
    return true;
    else
    return false;
  }      
}
     
   
   


     
       

Infix To Post Fix using Java



import java.io.*;
public class InToPost
 {
  private Stack theStack;
  private String input;
  private String output="";
  public InToPost(String in)
  {
    input=in;
    int stackSize=input.length();
    theStack=new Stack(stackSize);
  }
  public String doTrans()
  {
    for (int i=0;i<input.length();i++)
    {
      char ch=input.charAt(i);
      switch(ch)
      {
      case '+':
      case '-':
        gotOper(ch,1);
        break; //   (precedence 1)
      case '*': // it's * or /
      case '/':
        gotOper(ch,2); // go pop operators
        break; //   (precedence 2)
      case '(': // it's a left paren
        theStack.push(ch); // push it
        break;
      case ')': // it's a right paren
        gotParen(ch); // go pop operators
        break;
      default: // must be an operand
        output=output+ch; // write it to output
        break;
      }
    }
    while(!theStack.isEmpty())
    {
      output=output+theStack.pop();
    }
    return output; // return postfix
  }
  public void gotOper(char opThis,int prec1)
  {
    while (!theStack.isEmpty())
    {
      char opTop=theStack.pop();
      if(opTop=='(')
      {
        theStack.push(opTop);
        break;
      }// it's an operator
      else
      {// precedence of new op
        int prec2;
        if(opTop=='+'||opTop=='-')
          prec2=1;
        else
          prec2=2;        if (prec2<prec1) // if prec of new op less
        { //    than prec of old
          theStack.push(opTop); // save newly-popped op
          break;
        } else
          // prec of new not less
          output=output+opTop; // than prec of old
      }
    }
    theStack.push(opThis);
  }
  public void gotParen(char ch)
  {
    while(!theStack.isEmpty())
    {
      char chx=theStack.pop();
      if(chx=='(')
        break;
      else
        output=output+chx;
    }
  }
  public static void main(String[] args) throws IOException
  {
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    System.out.print("Enter the infix expression:");
    String input=br.readLine();
    String output;
    InToPost theTrans=new InToPost(input);
    output=theTrans.doTrans();
    System.out.println("Postfix expression is:"+output);
  }
}
//-----------------------------------------------------------------------
/**
 Output:-

 Enter the infix expression:a/(b+c)+d*(e-f)
 Postfix expression is:abc+/def-*+

 Enter the infix expression:a+(b/c)*d-(e*f)
 Postfix expression is:abc/d*+ef*-

 */

Employee Database Using JAVA



import java.io.*;
public class employee
{
    public static void write()throws IOException
    {
        long empcode;
        String empname;
        int hrsworked;
        double rate;
        boolean con=true;
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        FileOutputStream obj=new FileOutputStream("emp.dat");
        DataOutputStream fl=new DataOutputStream(obj);
        while(con)
        {
            System.out.print("Enter Employee name:");
            empname=br.readLine();
            System.out.print("Enter employee code:");
            empcode=Long.parseLong(br.readLine());
            System.out.print("Enter Hours Worked:");
            hrsworked=Integer.parseInt(br.readLine());
            System.out.print("Enter rate:");
            rate=Double.parseDouble(br.readLine());
            fl.writeUTF(empname);
            fl.writeLong(empcode);
            fl.writeInt(hrsworked);
            fl.writeDouble(rate);
            System.out.print("Continue(y/n)?:");
            String c=br.readLine();
            if(c.equalsIgnoreCase("n")==true)
            con=false;
            System.out.println();
        }
        obj.close();
        fl.close();
        System.out.println("Data added to file successfully!!");
        System.out.println();
    }
    public static void append()throws IOException
    {
        long empcode;
        String empname;
        int hrsworked;
        double rate;
        boolean con=true;
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        FileOutputStream std=new FileOutputStream("emp.dat",true);
        DataOutputStream mat=new DataOutputStream(std);
        while(con)
        {
            System.out.print("Enter Employee name:");
            empname=br.readLine();
            System.out.print("Enter employee code:");
            empcode=Long.parseLong(br.readLine());
            System.out.print("Enter Hours Worked:");
            hrsworked=Integer.parseInt(br.readLine());
            System.out.print("Enter rate:");
            rate=Double.parseDouble(br.readLine());
            mat.writeUTF(empname);
            mat.writeLong(empcode);
            mat.writeInt(hrsworked);
            mat.writeDouble(rate);
            System.out.print("Continue(y/n)?:");
            String c=br.readLine();
            if(c.equalsIgnoreCase("n")==true)
            con=false;
        }
        std.close();
        mat.close();
        System.out.println("Data added to file successfully!!");
        System.out.println();
    }
       
    public static void read()throws IOException
    {
        long empcode[]=new long[100];
        String empname[]=new String[100];
        int hrsworked[]=new int[100];;
        double rate[]=new double[100];
        boolean con=true;
        int x=0;
        FileInputStream obj=new FileInputStream("emp.dat");
        DataInputStream fl=new DataInputStream(obj);
        boolean eof=false;
        while(!eof)
        {
            try
            {
                empname[x]=fl.readUTF();
                empcode[x]=fl.readLong();
                hrsworked[x]=fl.readInt();
                rate[x]=fl.readDouble();
                x++;
            }
            catch(EOFException e)
            {
                eof=true;
            }
        }
        for(int i=0;i<x;i++)
        {
            for(int j=0;j<x-1;j++)
            {
                if(empname[j].compareTo(empname[j+1])>1)
                {
                    long lt;
                    int it;
                    String st;
                    double dt;
                    st=empname[j];
                    lt=empcode[j];
                    it=hrsworked[j];
                    dt=rate[j];
                    empname[j]=empname[j+1];
                    empcode[j]=empcode[j+1];
                    hrsworked[j]=hrsworked[j+1];
                    rate[j]=rate[j+1];
                    empname[j+1]=st;
                    empcode[j+1]=lt;
                    hrsworked[j+1]=it;
                    rate[j+1]=dt;
                }
            }
        }
        System.out.println("Employee Code\t Name\t\tHours Worked\tRate\t\tWeekly Wages");
        for(int i=0;i<x;i++)
        {
            System.out.println(empcode[i]+"\t\t "+empname[i]+"\t\t"+hrsworked[i]+"\t\tRs."+rate[i]+"\t\tRs."+(hrsworked[i]*rate[i]));
        }
            x=0;
            System.out.println();
    }
    public static void main(String args[])throws IOException
    {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        boolean con=true;
        while(con)
        {
            System.out.println("       Menu");
            System.out.println("1:Write to file");
            System.out.println("2:Read from file");
            System.out.println("3:Modify to file");
            System.out.print("Enter your option:");
            int n=Integer.parseInt(br.readLine());
            System.out.println();
            if(n==1)
            write();
            else if(n==2)
            read();
            else if(n==3)
            append();
            else
            System.out.println("Wrong Entry!!!!");
            System.out.print("Continue with menu options(y/n)?:");
            String c=br.readLine();
            if(c.equalsIgnoreCase("n")==true)
            con=false;
        }
    }
}
//---------------------------------------------------------------------------
/**
 Output:-
       Menu
1:Write to file
2:Read from file
3:Modify to file
Enter your option:1

Enter Employee name:abc
Enter employee code:47
Enter Hours Worked:56
Enter rate:25
Continue(y/n)?:y

Enter Employee name:pqr
Enter employee code:96
Enter Hours Worked:45
Enter rate:65
Continue(y/n)?:y

Enter Employee name:xyz
Enter employee code:87
Enter Hours Worked:85
Enter rate:51
Continue(y/n)?:n

Data added to file successfully!!

Continue with menu options(y/n)?:y
       Menu
1:Write to file
2:Read from file
3:Modify to file
Enter your option:2

Employee Code    Name       Hours Worked    Rate        Weekly Wages
47               abc        56              Rs.25.0     Rs.1400.0
96               pqr        45              Rs.65.0     Rs.2925.0
87               xyz        85              Rs.51.0     Rs.4335.0

Continue with menu options(y/n)?:y
       Menu
1:Write to file
2:Read from file
3:Modify to file
Enter your option:3

Enter Employee name:lmn
Enter employee code:69
Enter Hours Worked:20
Enter rate:90
Continue(y/n)?:n
Data added to file successfully!!

Continue with menu options(y/n)?:y
       Menu
1:Write to file
2:Read from file
3:Modify to file
Enter your option:2

Employee Code    Name       Hours Worked    Rate        Weekly Wages
47               abc        56              Rs.25.0     Rs.1400.0
69               lmn        20              Rs.90.0     Rs.1800.0
96               pqr        45              Rs.65.0     Rs.2925.0
87               xyz        85              Rs.51.0     Rs.4335.0
   
Continue with menu options(y/n)?:n

*/
       

                   
                   

               
       


 

Program to calculate the day using dates



import java.io.*;
public class day_calculator
{
    int date,month,year;
    String day,s;
    int m[]={31,28,31,30,31,30,31,31,30,31,30,31};
    int y[]={31,59,90,120,151,181,212,243,273,304,334,365};
    String d[]={"Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"};
    private void input()throws IOException
    {
       BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
       System.out.print("Enter Date(dd/mm/yyyy):");
       s=br.readLine();
       date=Integer.parseInt(s.substring(0,2));
       month=Integer.parseInt(s.substring(3,5));
       year=Integer.parseInt(s.substring(6));
       System.out.print("Enter the day on 1st January:");
       day=br.readLine();
    }
    private void calculate()
    {
        int nod=0;
        if(year%4!=0)
        nod=y[month-1]-(m[month-1]-date);
        else if(year%4==0)
        {
            m[1]=29;
            y[11]=366;
        nod=y[month-1]-(m[month-1]-date);
    }
        int mod=nod%7;
        int add=-1;
        for(int i=0;i<7;i++)
        {
            if(d[i].equalsIgnoreCase(day)==true)
            add=i;
        }
        if(add==-1)
        {
        System.out.print("Error in day or date....please re-enter");
        System.exit(0);
    }
        add=add+mod;
        if(add!=0)
        add--;
        System.out.print("Day on:"+s+":"+d[add]);
    }
    public static void main(String args[])throws IOException
    {
        day_calculator obj=new day_calculator();
        obj.input();
        obj.calculate();
    }
}
   

     

Boundary Of A Matrix


import java.io.*;
public class boundary
{
    int a[][],b[][],c[],x,y,sum=0,index=0;
    boundary(int m,int n)
    {
        a=new int[m][n];
        b=new int[m][n];
        c=new int[m*n];
        x=m;
        y=n;
        for(int i=0;i<m;i++)
        {
            for(int j=0;j<n;j++)
            {
                a[i][j]=0;
                b[i][j]=0;
            }
        }
    }
    public void input()throws IOException
    {    
         BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        for(int i=0;i<x;i++)
        {
            for(int j=0;j<y;j++)
            {
                System.out.print("Enter the element:");
                a[i][j]=Integer.parseInt(br.readLine());
            }
        }
        System.out.println();
    }
    public void original_display()
    {
        for(int i=0;i<x;i++)
        {
            for(int j=0;j<y;j++)
            {
                System.out.print(a[i][j]+"\t");
            }
            System.out.println();
        }
        System.out.println();
    }
    public void extract()
    {
        for(int i=0;i<y;i++)
        {
            c[index]=a[0][i];
            index++;
        }
        for(int i=1;i<x;i++)
        {
            c[index]=a[i][y-1];
            index++;
        }
        for(int i=(y-2);i>=1;i--)
        {
            c[index]=a[x-1][i];
            index++;
        }
        for(int i=x-1;i>=1;i--)
        {
            c[index]=a[i][0];
            index++;
        }
        for(int i=0;i<index;i++)
        {
            sum=sum+c[i];
        }
    }
    public void sort()
    {
        for(int i=0;i<index;i++)
        {
            for(int j=0;j<index-1;j++)
            {
                if(c[j]>c[j+1])
                {
                    int temp=c[j];
                    c[j]=c[j+1];
                    c[j+1]=temp;
                }
            }
        }                  
    }
    public void modify_part1()
    {
        for(int i=0;i<x;i++)
        {
            for(int j=0;j<y;j++)
            {
                a[i][j]=-1;
            }
        }
    }
    public void modify_part2()
    {
        int index=0;
        for(int i=0;i<y;i++)
        {
            a[0][i]=c[index];
            index++;
        }
        for(int i=1;i<x;i++)
        {
            a[i][y-1]=c[index];
            index++;
        }
        for(int i=(y-2);i>=1;i--)
        {
            a[x-1][i]=c[index];
            index++;
        }
        for(int i=x-1;i>=1;i--)
        {
            a[i][0]=c[index];
            index++;
        }
    }
    public void modify_display()
    {
        for(int i=0;i<x;i++)
        {
            for(int j=0;j<y;j++)
            {
                if(a[i][j]!=-1)
                {
                    System.out.print(a[i][j]+"\t");
                }
                else if(a[i][j]==-1)
                {
                    System.out.print("\t");
                }
            }
            System.out.println();
        }
        System.out.println();
    }      
    public static void main(String args[])throws IOException
    {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter the value of m:");
        int m=Integer.parseInt(br.readLine());
        System.out.print("Enter the value of n:");
        int n=Integer.parseInt(br.readLine());
        boundary obj=new boundary(m,n);
        obj.input();
        System.out.println("ORIGINAL MATRIX:-");
        obj.original_display();
        obj.extract();
        System.out.println("REARRANGED  MATRIX:-");
        obj.sort();
        obj.modify_part2();
        obj.modify_display();
        System.out.println("BOUNDARY ELEMENTS:-");
        obj.sort();
        obj.modify_part1();
        obj.modify_part2();
        obj.modify_display();
        System.out.print("The sum is ="+obj.sum);
    }
}

Program to print all combinations of a string


import java.io.*;
public class combinations
{
    private static void printPermsAux(String s,String so)
    {
        if(s.equals(""))
        System.out.println(so);
        for (int i=0;i<s.length();++i)
        {
            printPermsAux(s.substring(0,i)+s.substring(i+1),so+s.charAt(i));
        }
    }
    private static void printPerms(String n)
    {
        printPermsAux(n,"");
    }
    public static void main(String args[])throws IOException
    {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter The Characters:");
        String input=br.readLine();
        System.out.println("Possible Combinations......");
        printPerms(input);
    }
}
//-------------------------------------------------------------------------
/**
 Output:-

 Enter The Characters:ABC
 Possible Combinations......
 ABC
 ACB
 BAC
 BCA
 CAB
 CBA

 Enter The Characters:AZBY
 Possible Combinations......
 AZBY
 AZYB
 ABZY
 ABYZ
 AYZB
 AYBZ
 ZABY
 ZAYB
 ZBAY
 ZBYA
 ZYAB
 ZYBA
 BAZY
 BAYZ
 BZAY
 BZYA
 BYAZ
 BYZA
 YAZB
 YABZ
 YZAB
 YZBA
 YBAZ
 YBZA
 */