Thursday, September 23, 2010

search for array within an array

import junit.framework.Assert;

import org.junit.Test;


public class SearchArray {


    public static void main(String[] args) {
        System.out.println( new SearchArray().findArray(new int[] {1,2,3,4,5,1,2,3,4,5}, new int[]{2,3,4})  );

    }
   
    /**
     * This method returns a -1 if no match is found else returns the index where
     * the sub array exists.
     * @param array1
     * @param array2
     * @return
     */
    private int findArray(int[] array1, int[] array2){
        int startIndex = -1;
        if(array1 !=null && array2 != null ){
            for (int i = 0; i < array1.length; i++){
                if(startIndex != -1){
                    break;
                }
                if( array2[0] == array1[i] ){
                    startIndex = i;    //we have found a starting point
                    for (int j = 0; j < array2.length; j++){                   
                        if( array2[j] != array1[startIndex + j]){
                            startIndex = -1;
                            break;
                        }                   
                    }
                }
            }
        }else{
            throw new IllegalArgumentException("The arrays should not be null");
        }
        return startIndex;       
    }
   
    @Test
    public void testNotFound() {   
        Assert.assertEquals( -1,  new SearchArray().findArray(new int[] {1,2,3,4,5,6,7,8,9,0}, new int[]{5,9,7}) );
    }
   
    @Test
    public void testFoundFirst() {   
        Assert.assertEquals( 1,  new SearchArray().findArray(new int[] {1,2,3,4,5,1,2,3,4,5}, new int[]{2,3,4}) );
    }
   
    @Test
    public void testFound() {   
        Assert.assertEquals( 4,  new SearchArray().findArray(new int[] {1,2,3,4,5,6,7,8,9,0}, new int[]{5,6,7}) );
    }

    @Test
    public void testException() {   
        try{
         new SearchArray().findArray( null, null) ;
        }catch(Exception e){
            Assert.assertTrue(e instanceof IllegalArgumentException);
           
        }
    }
}

No comments:

Post a Comment