Alex Rivera | Logout

Array Searching code challenge

Asked 2009-07-03T10:29:22.327
10

Here's my (code golf) challenge: Take two arrays of bytes and determine if the second array is a substring of the first. If it is, output the index at which the contents of the second array appear in the first. If you do not find the second array in the first, then output -1.

Example Input: { 63, 101, 245, 215, 0 } { 245, 215 }

Expected Output: 2

Example Input 2: { 24, 55, 74, 3, 1 } { 24, 56, 74 }

Expected Output 2: -1

Edit: Someone has pointed out that the bool is redundant, so all your function has to do is return an int representing the index of the value or -1 if not found.

Edit
Report

3 Answers

0

C#, works with any type that has equality operator:

first
  .Select((index, item) => 
    first
     .Skip(index)
     .Take(second.Count())
     .SequenceEqual(second) 
    ? index : -1)
  .FirstOrDefault(i => i >= 0)
  .Select(i => i => 0 ? 
     new { Found = true, Index = i } 
    : 
     new { Found = false, Index - 1 });
answered 2009-07-03T21:11:07.917
0

Weird, no one posted the javascript yet..

Solution 1:

r=s=b.length;s>=0&&(r=a.indexOf(b[0]));for(x=0;x<s;)b[x]!=a[r+x++]&&(r=-1);

function f(a, b) {
    r = s = b.length;
    if (s >= 0) r = a.indexOf(b[0]);
    for (x = 0; x < s;)
    if (b[x] != a[r + x++]) r = -1;
    return r;
}

Solution 2:

r=m=-1;b.map(function(d){n=a.indexOf(d);r==m&&(c=r=n);if(n==m||c++!=n)r=m});

function f2(a, b) {
    r = m = -1;
    b.map(function (i) {
        n = a.indexOf(i);
        if (r == m) c = r = n;
        if (n == m || c++ != n) r = m;
    });
    return r;
}
answered 2011-09-24T18:37:03.927
-2

C#

For Lists:

public static int IndexOf<T>( List<T> list1, List<T> list2 )
{
    return !list2.Except( list1 ).Any() ? list1.IndexOf( list2[0] ) : -1;
}

For Arrays:

public static int IndexOf<T>( T[] arr1, T[] arr2 )
{
    return !arr2.Except( arr1 ).Any() ? Array.IndexOf( arr1, arr2[0] ) : -1;
}
answered 2009-07-04T00:57:58.880

Your Answer