How to search for elements of sub-array from parent-array, if parent-array have the same elements of sub-array?

Vivek Dharek :

I am new to java. I have a problem that, I have two arrays parentArray and subArray:

  • parentArray has values, {1,4,4,3,6}
  • subArray has values {4,4,3}

So, the second array or so-called subArray values are included in the first-array the so-called parentArray, with indexes starting from [1,2,3]. My question is how can we return the index value of the first element of subArray which is also part of parentArray.

i.e.

int[] parentArray = new int[]{1,4,4,3,6};
int[] subArray = new int[]{4,4,3};

As subArray's values are in parentArray starting index from [1], I want my program to return 1.

I have tried comparing two arrays and returning the common elements from both arrays. But ahead of that, I can not think any of logic as I am a beginner.

taygetos :

you can use the Collections.indexOfSubList() as follows:

List<Integer> parentArray = Arrays.asList(1,4,4,3,6);
List<Integer> subArray = Arrays.asList(4,4,3);

int index = Collections.indexOfSubList(parentArray , subArray);
// index is 1

if you want to implement for arrays, check out the source from that and modify it a bit:

public static int indexOfSubList(int[] source, int[] target) {
  int sourceSize = source.length;
  int targetSize = target.length;
  int maxCandidate = sourceSize - targetSize;

  nextCand:
    for (int candidate = 0; candidate <= maxCandidate; candidate++) {
      for (int i=0, j=candidate; i<targetSize; i++, j++)
        if (!(target[i] == source[j]))
          continue nextCand;  // Element mismatch, try next cand
      return candidate;  // All elements of candidate matched target
    }
  return -1;  // No candidate matched the target
}

usage:

int[] parentArray = new int[]{1,1,1,4,4,3,6};
int[] subArray = new int[]{4,4,3};
int index = indexOfSubList(parentArray, subArray);
// index is 3
System.out.println(index);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=127180&siteId=1