Matching Arrays Problem Help me please!

Hi I'm trying to write a function that will match the values within an array and the other;

for for example.. if I have an array of size 16 called dimT=16 and an array of size 4 called dimP=4 where the arrays are T=[0,1,1,1,1,2, 0,1,0,1,1,1,1,2,0,0] and P=[1,1,1,2] then there'll be 2 matches of P in T in the 2 and 10 positions.

I just need my output to be the number of matches..
ps.I need to use while and not do while.

Here there's what I've done atm..

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
  #include<iostream>
using namespace std;
int main()

{
int T[100], P[20], dimT, dimP;
cin>> dimT >> dimP;
int i=0;
while(i<dimT)
{
cin >>T[i];
i++;
}
int j=0;
while ( j<dimP)
{
cin>>T[j];
j++;
}


and here is where i stopped.

I am still a noob in c++ so any help would be great!

Thanks in advance!!!
Last edited on
Try writing a function to check whether P matches T at a specific position pos:
1
2
3
4
bool isMatch(int T[], size_t Tsize, int P[], size_t Psize, size_t pos)
{
   ...
}


Once you have this, you can write another function to count the matches:
1
2
3
4
5
6
7
8
9
10
11
12
size_t countMatches(int T[], size_t Tsize, int P[], size_t Psize)
{
    size_t result =0;  // number of matches
    if (Tsize < Psize) return 0;   // P can't match if it's bigger than T

    for (size_t i=0; i <= Tsize-Psize; ++i) {
        if (isMatch(T, Ssize, P, Psize, i)) {  // Does P match at position i?
            ++result;     // yes - increment result
        }
    }
    return result;
}

}

If user of your program inputs an number into dimT grater than 100 than your while loop will go beyond T[100] 's original size and will cause the program to crash.
Last edited on
thanks for answering! It's been extremely helpful! =)
Topic archived. No new replies allowed.