Skip to content

Instantly share code, notes, and snippets.

@alimranahmed
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save alimranahmed/bff28228ebb46338c50c to your computer and use it in GitHub Desktop.
Save alimranahmed/bff28228ebb46338c50c to your computer and use it in GitHub Desktop.
‪#‎Javafest_Brain_Tweaker‬ # 1 Link: https://www.facebook.com/therapjavafest/posts/591777984278321
Problem Statement
-----------------------------
Find an Array:
Implement a method that given two arrays as parameters will find the starting index where the second parameter occurs as a sub-array in the array given as the first parameter.
Your implementations should return -1 if the sub-array cannot be found.
Your implementation must implement the FindArray interface given bellow:
public interface FindArray
{
int findArray(int[] array, int[] subArray);
}
Sample Input:
[4,9,3,7,8] and [3,7] should return 2.
[1,3,5] and [1] should return 0.
[7,8,9] and [8,9,10] should return -1.
Sample Code :
public class MyFindArray implements FindArray
{
public int findArray(int[] array, int[] subArray)
{
return -1;
}
}
public interface FindArray
{
int findArray(int[] array, int[] subArray);
}
/**
* @author Al- Imran Ahmed
* @date 16th October 20014
*/
import java.util.Arrays;
public class MyFindArray implements FindArray
{
@Override
public int findArray(int[] array, int[] subArray)
{
int arrayLength = array.length;
int subArrayLength = subArray.length;
boolean hasSubArray = true;
if(subArrayLength < arrayLength)//sub array is smaller than main array
{
for(int i = 0; i < arrayLength; i++)
{
if(arrayLength - i >= subArrayLength)
{
int[] tempArray = Arrays.copyOfRange(array, i, i+subArrayLength);
//System.out.println(Arrays.toString(tempArray));
if(Arrays.equals(tempArray, subArray)) return i;
else hasSubArray = false;
}
else return -1;
}
if(!hasSubArray) return -1; //when no matching found
}
else if(subArrayLength == arrayLength)//else when the length of sub array is equal the length of main array
{
return Arrays.equals(subArray, array) ? 0 : -1;
}
return -1;
}
//Main method
public static void main(String[] CHAND)
{
MyFindArray objFindArray = new MyFindArray();
int[] array = {4, 9, 3, 7, 8};
int[] sub_array = {7, 8};
System.out.println(objFindArray.findArray(array, sub_array));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment