Search and display the comparison

I need help with the following question, I don't want the whole code but I really need help with this section. (DISPLAY THE NUMBER OF KEY COMPARISON FOR EACH SEARCH). Here is the question.

Method 1A
1A-1. Create one array arr1 of size 1000. Populate it with random numbers in the range from 0 to 2000.
1A-2. Randomly generate 5 numbers and try to search each number in the array.
1A-3. Display the number of key comparison for each search.
1A-4. Display a table like the following:


Target Number # of key comparison
356 (Not Found) 1000

54 256

1568 546

349 (not found) 1000

545 678

Average 696
use an int for the count of key comparisons,

somewhere in your code there will be something like
1
2
3
4
if (itemA == itemB)
{
    // match found!
}


its the comparison that you need to count, regardless of whether the test was successful or not. So..
1
2
3
4
5
if (itemA == itemB)
{
    // found one!
}
comparisonCount++;



Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include<iostream>
#include<ctime>

using namespace std;

int main () {

	srand(time(NULL));

	int arr1[1000];

	// fill with random numbers
	for (int i = 0; i < 1000; i++) {
		arr1[i] = rand() % 2001;
	}

	int arr2[5];

	// 5 more random numbers
	for (int i = 0; i < 5; i++) {
		arr2[i] = rand() % 2001;
	}

	int a = 0;
	
	//find matches and output the results
	for (int j = 0; j < 5; j++) {
		a = 0;
		for (int i = 0; i < 1000; i++) {
			if (arr2[j] == arr1[i]) {
				a++;
			}
		}
		cout << arr2[j] << " Number of matches: " << a << endl;
	}

	cin.get();
	return 0;
}
Op didn't want the number of matches, they wanted the number of comparisons.

1
2
3
4
5
6
		for (int i = 0; i < 1000; i++) {
			if (arr2[j] == arr1[i]) {
                            // here's a match
			}
			a++;
		}
Do you mean the number of comparisons until a match was found?
Like this?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include<iostream>
#include<ctime>

using namespace std;

int main () {

	srand(time(NULL));

	int arr1[1000];

	// fill with random numbers
	for (int i = 0; i < 1000; i++) {
		arr1[i] = rand() % 2001;
	}

	int arr2[5];

	// 5 more random numbers
	for (int i = 0; i < 5; i++) {
		arr2[i] = rand() % 2001;
	}

	int a = 0;
	
	//find matches and output the results
	for (int j = 0; j < 5; j++) {
		a = 0;
		for (int i = 0; i < 1000; i++) {
		    a++;
			if (arr2[j] == arr1[i]) {
				i = 1000;
			}
		}
		if (a < 1000) {
		cout << arr2[j] << " Number of comparisons until match found: " << a << endl;
		}
		else {
		    cout << arr2[j] << " No match found: " << a << endl;
		}
	}

	cin.get();
	return 0;
}
Topic archived. No new replies allowed.