I am trying to write a function that helps to find a smaller 2D array in another one . I wrote it but the problem is that it always finded the array when it didnt exist . the only thing I want is that to say does it exist or not!
example :
2 3 4 5 6
7 8 9 11 12

13 14 15 16

say if there is a
2 3
7 8 in the array

Recommended Answers

All 3 Replies

What code do you have?

I don't really understand what you're trying to say, but can the arrays be modified? Or must their content remain in-place? If the first I'd probably sort and compare if based on that. Something like this: (something quickly made, not tested)

#include <iostream>
#include <algorithm>

using namespace std;

bool SortedIsPartOf(int first[], const int firstSize, int second[], const int secondSize)
{
    // An empty array is part of any array.
    if (firstSize == 0)
        return true;

     // Something bigger can't be part of something smaller.
    else if (firstSize > secondSize)
        return false;

    else if (first[0] == second[0])
        return SortedIsPartOf(first + 1, firstSize - 1, second + 1, secondSize - 1);

    else
        return SortedIsPartOf(first, firstSize, second + 1, secondSize - 1);
}

// Determine if "first" is part of "second".
bool IsPartOf(int first[], const int firstSize, int second[], const int secondSize)
{
    // Sort both arrays
    sort(first, first + firstSize);
    sort(second, second + secondSize);

    return SortedIsPartOf(first, firstSize, second, secondSize);
}

int main()
{
    // When is a array a part of another one? From a math point of view {3, 3} equals {3} but here I assume the first is not a part of the second.
    int data[]  = { 8, 2, 5, 6, 2, 9, 1 };
    int data2[] = { 5, 8 };

    cout << IsPartOf(data2, sizeof(data2) / sizeof(int), data, sizeof(data) / sizeof(int));

    return 0;
}

@Gonbe, I think he wants to know if an arary is a subarray of another array at same position. For example

1 2
4 5

is a subarray of
1 2 3
4 5 6

however 
2 1
5 4
not a subarray of

1 2 3
4 5 6

because the position differs.

@op, correct me if its not the case.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.