Hi, I am learning computer science this semester, and having trouble with my homework.
I think I am heading the right way. but it keeps giving me infinite loop when I put
9. duplicate for all the element within the range lowhigh, only print out one copy of the word when they are contiuous duplicates, along with the count of how many times this word appeared continuously.
For example, when the source array has the following words from index 0 to 9:
0: aa
1: aa
2: aa
3: bb
4: cc
5: cc
6: aa
7: aa
8: aa
9: aa
duplicate(words, 0, 9) would produce this output:
'aa' appeared 3 times.
'bb' appeared 1 times.
'cc' appeared 2 times.
1 2 3 4 5 6 7 8 9 10 11 12 13
void duplicate(const string source[], int low, int high) {
int i;
int j;
int count = 0;
for (int i = low; i < high; i++) {
for (int j = low; j < high; j++) {
if (source[i]==source[j]) {
count++;
}
}
}
return;
}
@LB
but if it's not in the function, it will not repeat. It should count every array that is duplicated. so if it's out of function it will only print out once. Isn't it?
I thought about using while loop or another for loop to print it out till there are no duplicates left. but, I am so confused now
Your function does not count individual duplicates, it counts all duplicates. You want to put the output statement after the inner for loop and then reset count to 0 after the output statement.
void duplicate(const string source[], int low, int high) {
int i;
int j;
int count = 0;
for (int i = low; i < high; i++) {
for (int j = low; j < high; j++) {
if (source[i]==source[j]) {
count++;
}
}
cout << "'" << source[i] << "'" << " appeared " << count << " times.\n";
count = 0;
}
return;
}
I did it what you said, but it is giving me weird outputs... It prints out alot of the same values.
'a' appeared 8 times. 'a' appeared 8 times. 'a' appeared 8 times. 'a' appeared 8 times. 'a' appeared 8 times. 'a' appeared 8 times. 'a' appeared 8 times. 'a' appeared 8 times.
like this. I'm pretty sure I did something wrong at the count parts
Yes, because you loop through the entire array without discriminating. If you only want to show the duplicates for the first element, you need to do some more work.
I would recommend instead using a std::map<std::string, int> as it will simplify your code dramatically.