Wednesday, October 1, 2014

Creating an Array post an element in an existing array

Ques: Given a non-empty array of ints, return a new array containing the elements from the original array that come after the last 4 in the original array. The original array will contain at least one 4. Note that it is valid in java to create an array of length 0.

Ans:
This can be achieved in 2 different ways-

The usage of System.arraycopy is a strong method which can achieve this in one single command which is covered in method 2.

Method 1:
public int[] post4(int[] nums) {
        int j=0;
        int pos4=0;
        //last Position of 4
        //assign a variable
        //this will store the last position of 4 after detecting the for position in //for loop
        for(int i=0;i<nums.length;i++){
            if(nums[i]==4){
                pos4=i;
            }
        }
     
        int[] temparray=new int[nums.length-pos4-1];
        for(int i=pos4+1;i<nums.length;i++){
        temparray[j]=nums[i];
        j++;
        }
       
        return temparray;
 
}

Method2:

public int[] post4(int[] nums) {
        int j=0;
        int pos4=0;
        //last Position of 4
        //assign a veriable
        //this will store the last pos of 4 after detecting the for position in //for loop
        for(int i=0;i<nums.length;i++){
            if(nums[i]==4){
                pos4=i;
            }
        }
     
        int[] temparray=new int[nums.length-pos4-1];
       System.arraycopy(nums,pos4+1,temparray,0,nums.length-pos4-1);          
        return temparray;

}

No comments:

Post a Comment