Showing posts with label MISC. Show all posts
Showing posts with label MISC. Show all posts

Familiarisation of java lists

Posted On // Leave a Comment

 What are Lists?


The java.util.List interface is a subtype of the java.util.Collection interface.
The List interface extends Collection and declares the behavior of a collection that stores a sequence of elements.
  • Elements can be inserted or accessed by their position in the list, using a zero-based index.
  • A list may contain duplicate elements.
  • In addition to the methods defined by Collection, List defines some of its own, which are summarized in the following below Table.
  • Several of the list methods will throw an UnsupportedOperationException if the collection cannot be modified, and a ClassCastException is generated when one object is incompatible with another.



How to initialise?


Since List is an interface you need to instantiate a concrete implementation of the interface in order to use it. You can choose between the following List implementations in the Java Collections API:
  • java.util.ArrayList
  • java.util.LinkedList
  • java.util.Vector
  • java.util.Stack
We can instantiate lists with above as:

List<E> AL = new ArrayList<>();
List<E> LL= new LinkedList<>();
List<E> V = new Vector<>();
List<E> S = new Stack<>();

We should give the generic class otherwise there would be unchecked/unsafe operation error. generic classes can be any predefined or user defined classes.

As with standard linked list and array operations, the various methods will have different algorithmic runtimes.
For LinkedList<E>
  • get(int index) is O(n)
  • add(E element) is O(1)
  • add(int index, E element) is O(n)
  • remove(int index) is O(n)
  • Iterator.remove() is O(1) <--- main benefit of LinkedList<E>
  • ListIterator.add(E element) is O(1) <--- main benefit of LinkedList<E>
For ArrayList<E>
  • get(int index) is O(1) <--- main benefit of ArrayList<E>
  • add(E element) is O(1) amortized, but O(n) worst-case since the array must be resized and copied
  • add(int index, E element) is O(n - index) amortized, but O(n) worst-case (as above)
  • remove(int index) is O(n - index) (i.e. removing last is O(1))
  • Iterator.remove() is O(n - index)
  • ListIterator.add(E element) is O(n - index)

How to add elements?


List interface supports these functions for adding elements
  • void add(E obj)
  Adds objects to the end of the list.
  • void add(int index,E obj)  
          Inserts obj into the invoking list at the index passed in index. Any pre-existing elements at or beyond the point of insertion are shifted up. Thus, no elements are overwritten.
  • boolean addAll(int index, Collection c)
          Inserts all elements of c into the invoking list at the index passed in index. Any pre-existing elements at or beyond the point of insertion are shifted up. Thus, no elements are overwritten. Returns true if the invoking list changes and returns false otherwise.

 Here are a few examples:

List<Integer> AL = new ArrayList<>();
AL.add(0);
AL.add(5);//adding elements at the end of list
AL.add(1,4);// adding elements at a specified index
List<Integer> tmp = new LinkedList<>();
tmp.add(1);
tmp.add(2);
tmp.add(3);
AL.addAll(1,tmp);// adding an another collection

System.out.println(AL);
//Now the above statement yields output
[0, 1, 2, 3, 4, 5]


How to access elements?

The functions used to access elements are:
  • E get(int index)
 Returns the object stored at the specified index within the invoking collection.
  •  ListIterator listIterator( )
Returns an iterator to the start of the invoking list. 
  • ListIterator listIterator(int index)
Returns an iterator to the invoking list that begins at the specified index.
  
The order in which the elements are added to the List is stored, so you can access the elements in the same order. You can do so using either the get(int index) method, or via the Iterator returned by the iterator() method. Here is how:
List listA = new ArrayList();

listA.add("element 0");
listA.add("element 1");
listA.add("element 2");

//access via index
String element0 = listA.get(0);
String element1 = listA.get(1);
String element3 = listA.get(2);


//access via Iterator
Iterator iterator = listA.iterator();
while(iterator.hasNext(){
  String element = (String) iterator.next();
}


//access via new for-loop
for(E object : listA) {
    String element = (String) object;
}
When iterating the list via its Iterator or via the for-loop (which also uses the 
Iterator behind the scene), the elements are iterated in the same sequence they 
are stored in the list. 
 

How to delete elements?

These functions are used to remove elements:
  • remove(E element) 
remove(E element) removes that element in the list, if it is present. All subsequent elements in the list are then moved up in the list. Their index thus decreases by 1. 
  • remove(int index)
remove(int index) removes the element at the given index. All subsequent elements in the list are then moved up in the list. Their index thus decreases by 1. 

How to delete elements?

The list elements can be changed by the function E set(int index, E element) which replaces the element at the specified position in this list with the specified element

[Read more]

JAVA program to handle same function with different number of parameters

Posted On // Leave a Comment
In this post i would like show you a cool feature of java to handle functions with different parameter sets. For example if you want to find sum of a set of parameters which maybe 2or 3or400 you can use this feature instead of doing messy convertions to array.

public class threeDots{

    static void sumIt(int...x){
        int t=0;
        for(int i:x)
            t+=i;
        System.out.println(t);
    }

    public static void main(String[] args) {
        sumIt(1);
        sumIt(1,2);
        sumIt(1,2,3);
        sumIt(1,2,3,4);
        sumIt(1,2,3,4,5);
        sumIt(1,2,3,4,5,6);       
    }
}

Output:
1
3
6
10
15
21
[Read more]

JAVA program to implement Eller's algorithm to generate random maze

Posted On // Leave a Comment

Algorithm:

    Eller's algorithm creates 'perfect' mazes, having only a single path between any two cells, one row at a time. The algorithm itself is incredibly fast, and far more memory efficient than other popular algorithms (such as Prim's and Kruskal's) requiring storage proportional to only a single row. This makes it possible to create mazes of indefinite length on systems with limited memory.

The algorithm is explained below:
  1. Create the first row. No cells will be members of any set

  2. Join any cells not members of a set to their own unique set

  3. Create right-walls, moving from left to right:
    1. Randomly decide to add a wall or not
      • If the current cell and the cell to the right are members of the same set, always create a wall between them. (This prevents loops)
      • If you decide not to add a wall, union the sets to which the current cell and the cell to the right are members.

  4. Create bottom-walls, moving from left to right:
    1. Randomly decide to add a wall or not. Make sure that each set has at least one cell without a bottom-wall (This prevents isolations)
      • If a cell is the only member of its set, do not create a bottom-wall
      • If a cell is the only member of its set without a bottom-wall, do not create a bottom-wall

  5. Decide to keep adding rows, or stop and complete the maze
    1. If you decide to add another row:
      1. Output the current row
      2. Remove all right walls
      3. Remove cells with a bottom-wall from their set
      4. Remove all bottom walls
      5. Continue from Step 2

    2. If you decide to complete the maze
      1. Add a bottom wall to every cell
      2. Moving from left to right:
        • If the current cell and the cell to the right are members of a different set:
          1. Remove the right wall
          2. Union the sets to which the current cell and cell to the right are members.
          3. Output the final row

CODE:

// a utility class to represent single cell
import java.util.*;

public class Cel{
 public boolean right,down;
 
 public List<Cel> set;
 
 public int x,y;
 
 Cel(int a,int b){
  
  x=a;
  
  y=b;
  
  right=false;
  
  down=true;
  
  set=null;
  
 }
 
}
// class to implement the algorithm
import java.util.*;



public class maze{
 
 static Random randomizer = new Random();
 
 static int size;
 
 static int[][] maze;
 
 static Scanner in = new Scanner(System.in);
 
 
 
 /*  Step 2: Grouping ungrouped cells to form new sets    */
 
 static Cel[] makeSet(Cel[] row) {
  
  for(int index = 0; index < row.length; ) {
   
   Cel cell = row[index++];
   
   if(cell.set == null) {
    
    List<Cel> list = new ArrayList<Cel>();
    
    list.add(cell);
    
    cell.set=list;
    
   }
   
  }
  
  return row;
  
 }
 
 /*********************************************************/
 
 
 
 /*  Step 3: Creating right walls                         */
 
 static Cel[] makeRightWalls(Cel[] row) {
  
  for(int i = 1; i < row.length; i++) {
   
   if(isContainsInList(row[i-1].set,row[i])) {
    
    row[i-1].right=true;
    
    continue;
    
   }
   
   if(randomizer.nextBoolean())
   
   row[i-1].right=true;
   
   else
    
   row=merge(row,i);
   
  }
  
  return row;
  
 }
 
 
 
 static Cel[] merge(Cel[] row,int i) {  //utility function
  
  List<Cel> currentList = row[i-1].set;
  
  List<Cel> nextList = row[i].set;
  
  for(Cel j : nextList) {
   
   currentList.add(j);
   
   j.set=currentList;
   
  }
  
  return row;
  
 }
 
 
 
 static boolean isContainsInList(List<Cel> set,Cel cell) {  //utility function
  
  for(Cel i : set) {
   
   if(i==cell)
   
   return true;
   
  }
  
  return false;
  
 }
 
 /*********************************************************/
 
 
 
 /*  Step 4: Creating down walls                          */
 
 static boolean isNotDone(List<Cel> set){    //utility function
  
  boolean rslt=true;
  
  for(Cel x:set)
  
  rslt=rslt&&x.down;
  
  return rslt;
  
 }
 
 
 
 static Cel[] makeDown(Cel[] row){
  
  for(int i=0;i<row.length;i++){
   
   for(Cel x:row[i].set)x.down=true;
   
   while(isNotDone(row[i].set)){
    
    do{
     
     row[i].set.get(randomizer.nextInt(row[i].set.size())).down=false;
     
    }while(randomizer.nextBoolean() || );
    
   }
   
  }
  
  return row;
  
 }
 
 /*********************************************************/
 
 
 
 /*  Driver function to execute the algorithm             */
 
 static public void driver(){
  
  System.out.print("Enter size: ");
  
  size=in.nextInt();
  
  maze=new int[2*size+1][2*size+1];
  
  Cel[] cur=new Cel[size];
  
  for(int i=0;i<size;i++)
  
  cur[i]=new Cel(0,i);
  
  for(int i=2;i<=2*size;i++)
  
  for(int j=2;j<=2*size;j++)
  
  maze[i][j]=0;
  
  for(int i=0;i<size;i++){
   
   cur=makeSet(cur);
   
   cur=makeRightWalls(cur);
   
   cur=makeDown(cur);
   
   if(i==size-1)
   
   cur=end(cur);
   
   printMaze(cur,i);
   
   if(i!=size-1)
   
   cur=genNextRow(cur);
   
  }
  
  //Creating upper and left boundary
  
  for(int i=0;i<=2*size;i++)
  
  maze[i][0]=maze[0][i]=maze[i][2*size]=maze[2*size][i]=1;
  
  for(int i=2;i<=2*size;i+=2)
  
  for(int j=2;j<=2*size;j+=2)
  
  maze[i][j]=1;
  
  for(int i=0;i<2*size+1;i++){
   
   System.out.println();
   
   for(int j=0;j<2*size+1;j++)
   
   System.out.print(maze[i][j]+" ");
   
  }
  
 }
 
 static Cel[] end(Cel[] row) {
  
  for(int i = 1; i < row.length; i++) {
   
   if(findPos(row[i-1].set,row[i]) == -1) {
    
    row[i-1].right=false;
    
    row=merge(row,i);
    
   }
   
  }
  
  return row;
  
 }
 
 
 
 static int findPos(List<Cel> set,Cel x){
  
  Cel[] tmpArray = new Cel[set.size()];
  
  tmpArray = set.toArray(tmpArray);
  
  for(int i=0;i<tmpArray.length;i++)
  
  if(tmpArray[i]==x)
  
  return i;
  
  return -1;
  
 }
 
 
 
 static Cel[] genNextRow(Cel[] pre){
  
  for(int i = 0; i < pre.length;i++ ) {
   
   pre[i].right=false;
   
   pre[i].x++;
   
   if(pre[i].down) {
    
    pre[i].set.remove(findPos(pre[i].set, pre[i]));
    
    pre[i].set=null;
    
    pre[i].down=false;
    
   }
   
  }
  
  return pre;
  
 }
 
 
 
 static void printMaze(Cel[] row,int rowPos){
  
  rowPos=2*rowPos+1;
  
  for(int i=0;i<row.length;i++){
   
   if(row[i].right)
   
   maze[rowPos][2*i+2]=1;
   
   if(row[i].down)
   
   maze[rowPos+1][2*i+1]=1;
   
  }
  
 }
 
 
 
}

// driver class to execute the algorithm
public class runMe{
 
 public static void main(String[] args) {
  
  maze t =new maze();
  
  maze.driver();
  
 }
 
}

SOURCE:  

[Read more]

JAVA program to print all permutations of a string

Posted On // Leave a Comment

ALGORITHM:

The permutation of a string is the rearrangement of the string in different orders to form different strings of the same length. A string of length n can have n! permutations.
Source: Mathworld
We will start with each letter of the string and then we found all the possible combinations for the string beginning with that letter. And once we picked a letter in the 2nd position, we then found all the possible combinations that begin with that 2 letter sequence before we changed any of the letters in the first 2 positions. So, basically what we did was choose a letter and then peformed the permutation process starting at the next position to the right before we come back and change the character on the left. 

CODE:

import java.util.Scanner;

public class permutations{
   
    static char[] swap(char[] a,int i,int j){
        char tmp =a[i];
        a[i]=a[j];
        a[j]=tmp;
        return a;
    }
   
    static void printArray(char[] a){
        for (int i=0;i<a.length;i++)
            System.out.print(a[i]);
        System.out.println();
    }

    static void permute(char[] a,int index){
        if(index==a.length){
            printArray(a);
            return;
        }
        for(int i=index;i<a.length;i++){
            a=swap(a,i,index);
            permute(a,index+1);
            a=swap(a,i,index);
        }
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter the string: ");
        permute(in.next().toCharArray(),0);
    }
}

OUTPUT:

Enter the string: abc
abc
acb
bac
bca
cba
cab


[Read more]

JAVA program to print all combinations(NOT PERMUTATIONS) of a string

Posted On // Leave a Comment

ALGORITHM:

The problem is to find all combination of letters in a string ,the question should not be mistaken with permutation of string.To find all combinations of a string we follow a simple method: take each element and and group it with rest of the elements and do the same for thus formed new groups.

A diagramatic representation for the string ABC is:

So this logic can be implemented using a recursive algorithm :
  •  Take each group(each elements in beginning) and form new groups for each group by combining it with the rest of elements and repeat this procedure for each newly formed groups until the group size becomes equal to the string size.


CODE:

import java.util.Scanner;

public class comb{

    static void printArray(char[] a,int len){
        for (int i=0;i<=len;i++)
            System.out.print(a[i]);
        System.out.println();
    }

    static void printCombination(char[] a,char[] b,int aBeg,int bEnd){
        for(int i=aBeg;i<a.length;i++){
            b[bEnd+1]=a[i];
            printArray(b,bEnd+1);
            if(i<a.length-1)
                printCombination(a,b,i+1,bEnd+1);
        }
    }

    public static void main(String[] args) {
        System.out.print("Enter string: ");
        char[] a;
        Scanner in = new Scanner(System.in);
        a=in.next().toCharArray();
        char[] b = new char[a.length];
        printCombination(a,b,0,-1);
    }
}

OUTPUT:

Enter string: abc
a
ab
abc
ac
b
bc
c


[Read more]

JAVA program to find all numbers whose sum of digits is equal to an input number

Posted On // Leave a Comment

ALGORITHM:

The problem is to input a number and find all numbers whose digits sum is equal to the input number.
i.e. if the input number is 5 then program should print numbers 5 14 23 32 41.
The problem can be solved by doing a recursive algorithm given below:
  1. Start with first digit 1 to 9
  2. Check whether the number digit's sum has exceeded the target or has reached the target; if it has reached target then print the number; if so return from the function.
  3. If the digit's sum is less than target then try adding digits 1 to 9 to the LSB of the number and recurse the function(from step 2) for each such made new numbers.
The program of algorithm is given below since java has a stack limit of about 1k bytes the program won't work for large numbers :P.

CODE:

import java.util.Scanner;

public class digitSum{

    static boolean isInArray(int[] a,int ele){
        for(int i=0;i<a.length;i++)
            if(a[i]==ele)
                return false;
        return true;
    }

    static int findSum(int[] ar,int end){
        int sum=0;
        for(int i=0;i<=end;i++)
            sum+=ar[i];
        return sum;
    }

    static void printNum(int[] ar,int index,int num){
       
        int sum = findSum(ar,index);
        int diff = num-sum;
        if(diff<0)
            return;
        if(diff==0){
            for (int i=0;i<=index;i++)
                System.out.print(ar[i]);
            System.out.println();  
            return;
        }
        for(int i=1;i<10;i++){
            if(isInArray(ar,i)){
                ar[index+1]=i;
                printNum(ar,index+1,num);
            }
        }
       
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("\nEnter the number: ");
        int num=in.nextInt();
        int[] ar = new int[9];
        for (int i=1;i<=9;i++ ) {
            ar[0]=i;
            printNum(ar,0,num);
        }
    }
}

OUTPUT:

Enter the number: 8
125
134
143
152
17
215
251
26
314
341
35
413
431
512
521
53
62
71
8
[Read more]

JAVA program to print IP address

Posted On // Leave a Comment
import java.net.InetAddress;

class IP{
    public static void main(String[] args) throws Exception {
        System.out.print("IP address:"+InetAddress.getLocalHost());
    }
}
[Read more]

JAVA program to find the maximum number that can be made from an integer array

Posted On // Leave a Comment

ALGORITHM:

This problem can be simply solved by changing the comparison criteria of any sorting algorithms.

Comparison should be changed as explained
if the two numbers to be compared are a & b then two numbers should be made tempA and tempB such that:
               tempA = a*10^(number of digits in b)+b
               tempB = b*10^(number of digits in a)+a
if tempA>tempB then a is larger than b and vice versa

Code of the above logic implemented with bubble sort is given below:

CODE:

import java.util.Scanner;

class maxNo{

    static int size(int a){                //simple utility function count no of digits
        int count=0;
        do{
            count++;
            a/=10;
        }while(a!=0);
        return count;
    }
//utility function to implement modified comparison criteria of the sort
    static int[] compare(int[] a,int i,int j){          
        double t1,t2;
        int tmp;
        t1=a[i]*Math.pow(10,size(a[j]))+a[j];
        t2=a[j]*Math.pow(10,size(a[i]))+a[i];
        if(t1<t2){
            tmp=a[i];                //swapping ith and jth elements
            a[i]=a[j];
            a[j]=tmp;
        }
        return a;
    }

    static int[] bubSort(int[] a,int size){         //simple bubble sort with comparison criteria changed
        int i,j;
        for(i=0;i<size-1;i++)
            for(j=0;j<size-i-1;j++)
                a=compare(a,j,j+1);
        return a;
    }

    //driver function
    public static void main(String[] args) {
        int n,i;
        Scanner in = new Scanner(System.in);
        System.out.print("\nEnter size of array:");
        n=in.nextInt();
        int[] ar = new int[n];
        System.out.println("Enter the array:");
        for (i=0;i<n;i++)
            ar[i]=in.nextInt();
        ar=bubSort(ar,n);
        System.out.println("Maximum num made from the array is:");
        for (i=0;i<n;i++)
            System.out.print(ar[i]);
    }
}

OUTPUT:

Enter size of array:5
Enter the array:
1 10 11 100 110
Maximum num made from the array is:
11111010100
[Read more]

JAVA Program to print hailstone sequence of a numer

Posted On // Leave a Comment
Save as "Hail.java"



import java.util.*;

public class Hail
{
public static void main(String[] args)
{
int i,n;
Scanner in = new Scanner(System.in);
int[] arr = new int[20];
System.out.println("Enter the number from which Hailstone sequence is to be found:");
n = in.nextInt();
System.out.println("The Hailstone sequence is:");
while(n!=1)
{
if(n%2==0)
{ n =n/2;
System.out.println(n);
}
else
{
n = ((n*3)+1);
System.out.println(n);
}
}
}
}
[Read more]

JAVA Program to find 2 neighouring elements in an array with the smallest distance to each other

Posted On // Leave a Comment
Save as "Sdis.java"



public static void main(String[] args)
{
int n, i;
Scanner in = new Scanner(System.in);
int[] arr = new int[20];
System.out.println("Enter the number of elements in the array:");
n = in.nextInt();
System.out.println("Enter array elements:");
for(i=1;i<=n;i++)
arr[i] = in.nextInt();
if(n == 0 || n == 1)
System.out.println("Array empty or lacks the minimum no of elements required to find the distance!!");
else
{
int spos = Sdisfind(arr,n);
System.out.println("The smallest distance exists between " + arr[spos] + " at pos " + spos + " and "  + arr[spos+1] + " at pos " + (spos+1));
}
}
public static int Sdisfind(int[] array, int arrlength )
{
int sdis, tdis, pos1,i;
pos1 = 1;
sdis = Math.abs(array[1] - array[2]);
for (i = 1; i < arrlength; i++)
{
tdis = Math.abs(array[i] - array[i+1]);
if (tdis < sdis)
{
sdis = tdis;
pos1 = i;
}
}
return pos1;
}
}
[Read more]

JAVA Program to find repeated occourence of number in an array

Posted On // Leave a Comment
Save as "Search.java"...



import java.util.*;

public class Search
{
public static void main(String[] args)
{
int n , find = 0 , i , count = 0;
Scanner in = new Scanner(System.in);
int[] arr = new int[20];
System.out.println("Enter the number of elements in the array:");
n = in.nextInt();
System.out.println("Enter array elements:");
for(i=1;i<=n;i++)
arr[i] = in.nextInt();
System.out.println("Enter the element whose no of occurrence is to be found:");
find = in.nextInt();
for(i=1;i<=n;i++)
if(arr[i]==find)
count++;
if(count!=0)
System.out.println("The no of occurrence of the element is found to be:" + count);
else
System.out.println("Element not found in the array:");
}
}
[Read more]