Saturday, April 7, 2012

Java program to find the ascending combinational sequences of first 5 numbers


My friend has asked me a very interesting program. I would like to share that with you... (Not the very difficult problem though).
Problem: With a combination of five numbers 1, 2, 3, 4, 5 all the possible sequences in ascending order should be displayed. i.e.; (1, 1, 1, 1, 1), (1, 1, 1, 1, 2), and.... (5, 5, 5, 5, 5).
First we need to find out all the possible sequences availabe and then find out wheather they're in the ascending order.

public class ArrayListSort
{
  public static void main(String args[])
  {
    int a[]={1,2,3,4,5};
    int count = 0;
    for(int x:a)
    {
      for(int y:a)
      {
        for(int z:a)
        {
          for(int p:a)
          {
            for(int q:a)
            {
              int arr[]={x, y, z, p, q};
              if(isArrayInSortOrder(arr))
              {
                System.out.println("("+x+", "+y+", "+z+", "+p+", "+q+")");
                count++;
              }
            }
          }
        }
      }
    }
    System.out.println("Total number of combinatios: "+count);
  }
  public static boolean isArrayInSortOrder(int a[])
  {
    boolean valid = true;
    for(int i=0;i<a.length;i++)
    {
      for(int j=i;j<a.length;j++)
      {
        if(a[i]>a[j])
        {
          valid = false;
          break;
        }
      }
    }
    return valid;
  }
}

No comments:

Post a Comment