Wednesday 23 May 2012

Cards Arrangement Program in Java

Aim

Write a program to print the source sequence of cards, for one card below the deck & every alternate card opened & discarded ?

Code
import java.io.*;

class OutSequenceException extends Exception
{
 public String toString()
 {
  return "OutSequenceException: Invalid Number Entered !\nProgram Terminating....";
 }
}

class Card
{
 public static void main(String[] args)
 {
  try
  {

   BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
   
   //Array to store inputs and sorted sequence
   int[] a = new int[60];
   int[] b = new int[60];

   boolean flag=false;
 
   int count=0, index=0, skips, n;

   System.out.print("Enter Limit (13,26,39,52) :");
   n = Integer.parseInt(br.readLine());

   if(n!=13 && n!=26 && n!=39 && n!=52)
    throw new OutSequenceException();
    

   System.out.println("Provide Inputs");
   
   for(int i=0; i<n; i++)
   {
    a[i]=Integer.parseInt(br.readLine());

    if(a[i]>n)
     throw new OutSequenceException();

   }

   System.out.print("Enter number of skips: ");
   skips = Integer.parseInt(br.readLine());
   

   for(int i=0; i<n; i++)
   {
    //if flag is true means skips are done and b[i]=0 so no element placed there
    if(flag  && b[i]==0)
    {
     b[i]=a[count];
     count++;//next card to be placed
     flag=false;
    }


    /* 
       if previous if not executed because flag=false but some element 
       is there then also this will not execute hence skip will not 
       be incremented rather i will increase and next position 
       will be checked 
    */

    if(b[i]==0) //means previous if is not executed and no element is placed there
    {
     index++; 
     if(index==skips)
     {
      flag=true;
      index=0;
     }
     else
      flag=false;
    }

    //Reset the loop
    if(i==(n-1))
     i=-1;

    //Exit
    if(count==n)
     break;    
    
   }   
 
   //Finally print the result
   for(int i=0; i<n; i++)
    System.out.println(b[i]);

  }
  catch(Exception e)
  {
   System.out.println(e);
  }  
 }
}

No comments:

Post a Comment

Your comments are very much valuable for us. Thanks for giving your precious time.

Do you like this article?