Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find an array inside another larger array

Tags:

java

arrays

I was recently asked to write 3 test programs for a job. They would be written using just core Java API's and any test framework of my choice. Unit tests should be implemented where appropriate.

Although I haven't received any feedback at all, I suppose they didn't like my solutions (otherwise I would have heard from them), so I decided to show my programs here and ask if this implementation can be considered good, and, if not, then why?

To avoid confusion, I'll ask only first one for now.

Implement a function that finds an array in another larger array. It should accept two arrays as parameters and it will return the index of the first array where the second array first occurs in full. Eg, findArray([2,3,7,1,20], [7,1]) should return 2.

I didn't try to find any existing solution, but instead wanted to do it myself.

Possible reasons: 1. Should be static. 2. Should use line comments instead of block ones. 3. Didn't check for null values first (I know, just spotted too late). 4. ?

UPDATE:
Quite a few reasons have been presented, and it's very difficult for me to choose one answer as many answers have a good solution. As @adietrich mentioned, I tend to believe they wanted me to demonstrate knowledge of core API (they even asked to write a function, not to write an algorithm).

I believe the best way to secure the job was to provide as many solutions as possible, including: 1. Implementation using Collections.indexOfSubList() method to show that I know core collections API. 2. Implement using brute-force approach, but provide a more elegant solution. 3. Implement using a search algorithm, for example Boyer-Moore. 4. Implement using combination of System.arraycopy() and Arrays.equal(). However not the best solution in terms of performance, it would show my knowledge of standard array routines.

Thank you all for your answers!
END OF UPDATE.

Here is what I wrote:

Actual program:

package com.example.common.utils;  /**  * This class contains functions for array manipulations.  *   * @author Roman  *  */ public class ArrayUtils {      /**      * Finds a sub array in a large array      *       * @param largeArray      * @param subArray      * @return index of sub array      */     public int findArray(int[] largeArray, int[] subArray) {          /* If any of the arrays is empty then not found */         if (largeArray.length == 0 || subArray.length == 0) {             return -1;         }          /* If subarray is larger than large array then not found */         if (subArray.length > largeArray.length) {             return -1;         }          for (int i = 0; i < largeArray.length; i++) {             /* Check if the next element of large array is the same as the first element of subarray */             if (largeArray[i] == subArray[0]) {                  boolean subArrayFound = true;                 for (int j = 0; j < subArray.length; j++) {                     /* If outside of large array or elements not equal then leave the loop */                     if (largeArray.length <= i+j || subArray[j] != largeArray[i+j]) {                         subArrayFound = false;                         break;                     }                 }                  /* Sub array found - return its index */                 if (subArrayFound) {                     return i;                 }              }         }          /* Return default value */         return -1;     }  } 

Test code:

package com.example.common.utils;  import com.example.common.utils.ArrayUtils;  import junit.framework.TestCase;  public class ArrayUtilsTest extends TestCase {      private ArrayUtils arrayUtils = new ArrayUtils();      public void testFindArrayDoesntExist() {          int[] largeArray = {1,2,3,4,5,6,7};         int[] subArray = {8,9,10};          int expected = -1;         int actual = arrayUtils.findArray(largeArray, subArray);          assertEquals(expected, actual);     }      public void testFindArrayExistSimple() {          int[] largeArray = {1,2,3,4,5,6,7};         int[] subArray = {3,4,5};          int expected = 2;         int actual = arrayUtils.findArray(largeArray, subArray);          assertEquals(expected, actual);     }      public void testFindArrayExistFirstPosition() {          int[] largeArray = {1,2,3,4,5,6,7};         int[] subArray = {1,2,3};          int expected = 0;         int actual = arrayUtils.findArray(largeArray, subArray);          assertEquals(expected, actual);     }      public void testFindArrayExistLastPosition() {          int[] largeArray = {1,2,3,4,5,6,7};         int[] subArray = {5,6,7};          int expected = 4;         int actual = arrayUtils.findArray(largeArray, subArray);          assertEquals(expected, actual);     }      public void testFindArrayDoesntExistPartiallyEqual() {          int[] largeArray = {1,2,3,4,5,6,7};         int[] subArray = {6,7,8};          int expected = -1;         int actual = arrayUtils.findArray(largeArray, subArray);          assertEquals(expected, actual);     }      public void testFindArrayExistPartiallyEqual() {          int[] largeArray = {1,2,3,1,2,3,4,5,6,7};         int[] subArray = {1,2,3,4};          int expected = 3;         int actual = arrayUtils.findArray(largeArray, subArray);          assertEquals(expected, actual);     }      public void testFindArraySubArrayEmpty() {          int[] largeArray = {1,2,3,4,5,6,7};         int[] subArray = {};          int expected = -1;         int actual = arrayUtils.findArray(largeArray, subArray);          assertEquals(expected, actual);     }      public void testFindArraySubArrayLargerThanArray() {          int[] largeArray = {1,2,3,4,5,6,7};         int[] subArray = {4,5,6,7,8,9,10,11};          int expected = -1;         int actual = arrayUtils.findArray(largeArray, subArray);          assertEquals(expected, actual);     }      public void testFindArrayExistsVeryComplex() {          int[] largeArray = {1234, 56, -345, 789, 23456, 6745};         int[] subArray = {56, -345, 789};          int expected = 1;         int actual = arrayUtils.findArray(largeArray, subArray);          assertEquals(expected, actual);     }  } 
like image 885
Roman Avatar asked Oct 15 '10 07:10

Roman


People also ask

How do you check if an array is inside another array?

Create an empty object and loop through first array. Check if the elements from the first array exist in the object or not. If it doesn't exist then assign properties === elements in the array. Loop through second array and check if elements in the second array exists on created object.

How do you find an array within an array?

Use filter if you want to find all items in an array that meet a specific condition. Use find if you want to check if that at least one item meets a specific condition. Use includes if you want to check if an array contains a particular value. Use indexOf if you want to find the index of a particular item in an array.


2 Answers

The requirement of "using just core Java API's" could also mean that they wanted to see whether you would reinvent the wheel. So in addition to your own implementation, you could give the one-line solution, just to be safe:

public static int findArray(Integer[] array, Integer[] subArray) {     return Collections.indexOfSubList(Arrays.asList(array), Arrays.asList(subArray)); } 

It may or may not be a good idea to point out that the example given contains invalid array literals.

like image 101
adietrich Avatar answered Sep 22 '22 23:09

adietrich


Clean and improved code   public static int findArrayIndex(int[] subArray, int[] parentArray) {     if(subArray.length==0){         return -1;     }     int sL = subArray.length;     int l = parentArray.length - subArray.length;     int k = 0;     for (int i = 0; i < l; i++) {         if (parentArray[i] == subArray[k]) {             for (int j = 0; j < subArray.length; j++) {                 if (parentArray[i + j] == subArray[j]) {                     sL--;                     if (sL == 0) {                         return i;                     }                  }              }         }      }     return -1; } 
like image 34
Amit Kumar Sharma Avatar answered Sep 20 '22 23:09

Amit Kumar Sharma