Monday, April 11, 2011

Add hashset integers to int array in java

static int [] hashset_to_int_array(HashSet<Integer> hs){
  
  int array[] = new array[hs.size()];
  
  Iterator itr = hs.iterator();

  int i=0;

  while(itr.hasNext()){
  array[i++] = Integer.parseInt(itr.next().toString());
  }

  return array;
 }

take mirror image of a int array in java

Okay so lets say you have a array and you just wanna take the mirror image of it. how do you do it ? well there are several ways of doing it. One way is to just make another array , copy the first one to the second one by looping through the first one in the reverse direction. like this.

// this is the first array
int firstArray [] = {5 , 7, 98 , 44, 33 };

// this is how you make the second array
int secondArray[] = new int[firstArray.length];


Now you have to insert the above two arrays within a for loop to make the copy in reverse direction.

for(int i = firstArray.length - 1 ; i >= 0 ; i--){
secondArray[firstArray.length - 1- i]=firstArray[i];
}


wow now the secondArray is the mirror image of the first one. This method as you can see does not modify the firstArray. What you can do is make firstArray refer to the secondArray. Like this

firstArray = secondArray;


Now you may be wondering what happened to the firstArray memory segment. Well that will be garbage collected by the garbage collector because there is no reference to it in the code. Hey but this method is not recommended because it makes another copy of the original.

The one iam gonna show you below actually does the modification within the first array itself without requiring another array. but this method is a bit tricky. If i have time in the future i will show you how this code segment works using a diagram.

public static void mirror_int_array(int[] array) {

  if (array.length % 2 == 0) {

   int temp = 0;

   for (int i = 0; i < array.length / 2 - 1; i++) {

    temp = array[i];
    array[i] = array[array.length - 1 - i];
    array[array.length - 1 - i] = temp;

   }

  }

  else {

   int temp = 0;

   for (int i = 0; i < (array.length + 1) / 2 - 1; i++) {

    temp = array[i];
    array[i] = array[array.length - 1 - i];
    array[array.length - 1 - i] = temp;

   }

  }

 }

swap 2 integers in int array when index is specified java


 public static void swap_int_array(int []array , int index1 , int index2){
  int temp=array[index1];
  array[index1] = array[index2];
  array[index2]= temp; 
 }

rotate a int array by specific amount java

public class rotate {

 public static void rotate_int_array(int []array , int amount){

  int array_size = array.length ;

  if(amount % array_size ==0) return;

  if(amount < 0){

   amount = (-1) * amount;

   int temp=0;

   for(int i =0 ; i < amount ; i++){

    temp=array[array.length-1];
    for(int shift=array.length-1; shift >0 ; shift--){
     array[shift] = array[shift-1]; 
    }
    array[0] = temp;
   }
  }
  else{

   if(amount > array_size) amount = amount % array_size;

   int temp=0;

   for(int i =0 ; i < amount ; i++){

    temp=array[0];
    for(int shift=0; shift < array.length -1 ; shift++){
     array[shift] = array[shift+1]; 
    
                                }
    array[array.length -1] = temp;
   }
  }
 }
}

Saturday, April 9, 2011

remove numbers that are outside the range from int array java

The code below removes any negative numbers from the supplied array that are outside the range and returns a new array.

static int[] remove_outside_range(int array[] , int lower_bound , int upper_bound){

ArrayList<Integer> al = new ArrayList<Integer>();

    for(int i=0; i < array.length; i++){

    if(array[i] > lower_bound){
    al.add(array[i]);
    }

    if(array[i] < upper_bound){
    al.add(array[i]);
    }

}

    int new_array[] = new int[al.size()];

    for(int i =0 ; i < al.size() ; i++){
    new_array[i] = al.get(i);
    }

    return new_array;
}

remove negative numbers from int array java

Well you may be wondering how on earth can you remove negative numbers from a int array. You cannot physically remove negative numbers that would result in a reduction in the size of the array because arrays are immutable. One thing that you can do is that if the array is used in a situation where certain numbers are ignored then you can assign that number in place of negatives. Like this

int myArray[] = {6,-5,44,33,2,-66,7};

int x = 0;  // here x is a number that has no effect on the array's use

for(int i =0; i < array.length; i++){

if(myArray[i] > 0 ) myArray[i]=x;

}

}


The other thing that you can do is copy only the positive numbers to a new array. Wow thats fun right. But the problem is how can you determine the size of the new array ? Well obviously you can loop throught the first array once to find out the number of positive integers. And next create a new array whose length is equal to that positive integer count.

int myArray[] = {66,88,4,-4,66,-33};

int count = 0 ;

for(int i =0; i < myArray.length; i++){

if(myArray[i] >=0) count++;

}


next step is to create a new array whose size = count

int newArray[] = new int[count];


and the last step is to loop throught the myArray once again and copy only the positives

int position = 0;

for(int i =0; i < myArray.length; i++){

if(myArray[i] >=0) newArray[position] = myArray[i];
position++;
}


Okay so you end up with two arrays. any newArray contains the required result. However you can make myArray to refer to newArray and make the old reference to myArray garbage collected.

myArray = newArray;


Okay so we have removed negative integers by using two loops.

The method below makes use of arrayLists. It first scans through the array and inserts the positive integers into a arraylist. Next a new array is created whose size matches the arraylist. And the array list contents are then copied to the new array. And finally this method returns the newly created int array reference.

static int[] remove_negative(int array[]){

ArrayList<Integer> al = new ArrayList<Integer>();

for(int i =0; i < array.length; i++){

if(array[i] >= 0){
al.add(array[i]);
}

}

int new_array[] = new int[al.size()];

for(int i =0 ; i < al.size() ; i++){
new_array[i] = al.get(i);
}

return new_array;
}

remove duplicates from int array in java

Ok so now you have a int array that has duplicate integers in it and you wanna remove them and have only unique elements. This is how i will do it.

Step 1:- Copy all the int elements into a HashSet. Reason for doing this is that the HashSet only stores unique elements.

Step 2:- Create a int array of size = HashSet's size

Step 3:- Copy all the the HashSet elements into the newly created int array

static int [] remove_duplicates(int array[]){

HashSet<Integer> hs = new HashSet<Integer>();

for(int i =0 ; i < array.length ; i++){
hs.add(array[i]);
}

int new_array[] = new int[hs.size()];

Iterator<Integer> itr = hs.iterator();
int i =0;
while(itr.hasNext()){
new_array[i]=itr.next();
i++;
}

return new_array;
}

validate a ip address in java (ipv4)


static boolean validate(String ipv4_address) {

  int seperators = 0;
  int digits = 0;
  int partval = 0;

  if (ipv4_address.length() > 16)  return false; // length condition satisfied
  
  else {
    for (int i = 0; i < ipv4_address.length(); i++) {

      if (ipv4_address.charAt(i) == '.') {
      seperators++;
      digits = 0;
      partval = 0;
       
        if (seperators >= 4)
        return false; // checked the no of . 's in the address
        } else {

            if (!Character.isDigit(ipv4_address.charAt(i))) {
            return false;
            }
     
          partval = partval * 10 + Integer.parseInt(Character.toString(ipv4_address.charAt(i)));
    
             if (++digits > 3)
             return false;
             
               if (digits == 3) {

                 if (partval > 255) return false;
               }
       }
    }

  }

  return true;
}

java generate random number within range

static int randomNumberWithinRange(int lower,int upper){
  
  Random rnd = new Random();
  
  return lower + rnd.nextInt(upper-lower);
}

draw square shape in command prompt java (no fill)

 public static String outline(char c,int size, int spaces_from_left_margin,int spaces_from_top, int spaces_from_bottom){
  
  StringBuffer sb = new StringBuffer();

  for(int i = 0 ; i <spaces_from_top;i++) sb.append("\n");

  for(int outer=0; outer < (size) ; outer++){

   for(int sflm=0 ; sflm < spaces_from_left_margin ; sflm++){
    sb.append(" ");     
   }

   if(outer!=0 && outer!=(size-1)){
    
    sb.append(c);

    for(int inner=0; inner < (size -2) ; inner++){
     sb.append(" ");  
    }

    sb.append(c);    
    sb.append("\n");
   
   }
   
   else{
    
    for(int inner=0; inner < size ; inner++){
     sb.append(c);
    }
   
   sb.append("\n");

   }
   
  }
  
  for(int i = 0 ; i <spaces_from_bottom;i++) sb.append("\n");
  
  return sb.toString();

 }

draw square on command prompt in java (fill)

public static String fill(char c,int size, int spaces_from_left_margin,int spaces_from_top , int spaces_from_bottom){

 StringBuffer sb = new StringBuffer();

  for(int i = 0 ; i < spaces_from_top;i++) sb.append("\n");
 
  for(int outer=0; outer < size ; outer++){

  for(int sflm=0 ; sflm 7lt spaces_from_left_margin ; sflm++){
  sb.append(" ");     
  }

  for(int inner=0; inner < size ; inner++){
  sb.append(c);
  }

  sb.append("\n");
  }

  for(int i = 0 ; i < spaces_from_bottom;i++) sb.append("\n");
  
  return sb.toString();
}
Below is the screenshot of the output when the method is called with fill('*',10,10,10,10).