Last active
April 19, 2017 17:24
-
-
Save igorrendulic/db2e143af4562fa45f9abd5695632390 to your computer and use it in GitHub Desktop.
Find number of times subarray repeats in an array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Finding number of times subarray repeats in array <br> | |
* @param array must be >= @param subarray | |
* @return # of subarray repeats or 0 | |
*/ | |
public int findSubarrayCount(List<String> array, List<String> subarray, int fromIndex) { | |
int cntTotal = 0; | |
String firstElement = null; | |
if (subarray.size() > 0) { | |
firstElement = subarray.get(0); | |
} else { | |
return 0; | |
} | |
if (array.size() < subarray.size()) { // subarray must be smaller to be contained in array | |
return 0; | |
} | |
boolean matchFound = false; | |
int j=0; // subarray index | |
for (int i=fromIndex; i<array.size(); i++) { | |
String firstArrayElement = array.get(i); | |
if (firstArrayElement.equals(firstElement)) { | |
// found first matching element | |
matchFound = true; | |
j++; | |
if (j < subarray.size()) { | |
firstElement = subarray.get(j); | |
} | |
} else { | |
matchFound = false; | |
j = 0; | |
firstElement = subarray.get(j); | |
} | |
if (j == subarray.size()) { // at the end of subarray | |
if (matchFound) { | |
cntTotal++; | |
} | |
j = 0; | |
firstElement = subarray.get(0); | |
} | |
} | |
return cntTotal; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment