Repeating characters that should be deleted are not.

Pages: 12
// a. For each character beyond the one the outer loop is on
Outer loop is at i. Beyond that is [i+1..size[
Hint for syntax: the outer loop (line 4) does range [0..size[ correctly.

// 1. For all characters beyond the current one
That would be [j+1..size[ would it not?

And the array index is not j. What use is k otherwise?
Try:
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
46
47
48
49
50
51
52
53
54
55
56
#include <iostream>
#include <string.h>
/*
 * first duplicate (e) found:
 * cfleece
 *    ^^
 *    ||
 *    ji
 *
 * cflece
 * ^  ^^
 * |  ||
 * ?  ji
 *
 * second duplicate (c) missed
 */
void delete_repeats(char array[], int size)
{
  std::cout << "original array = " << array << std::endl;
  std::cout << "with size = " << size << std::endl;
  int i, j, k;
  for (i=0; i<size; i++) {
    for (j=0; j<i; j++) {
      if (array[i] == array[j]) {
	std::cout << "duplicate " << array[i] << " found at i=" << i
		  << " and j=" << j << std::endl;
	for (k=i; k<size; k++) {
	  array[k]=array[k+1];
	}
	--size;
	std::cout << "new array = " << array << std::endl;
	std::cout << "with size = " << size << std::endl;
	--i; /* need to restart j-loop with current i because
	      * new array[i] can already be duplicated for arrays[]
	      * values that j has stepped past */
	break;
      }
    }
  }
  std::cout << array << std::endl;
  std::cout << "size = " << size << std::endl;
}

int main()
{
  char str[] = "cfleece";

  std::cout << str << std::endl;

  delete_repeats(str, strlen(str));

  std::cout << str << std::endl;

  return 0;
}


cfleece
original array = cfleece
with size = 7
duplicate e found at i=4 and j=3
new array = cflece
with size = 6
duplicate c found at i=4 and j=0
new array = cflee
with size = 5
duplicate e found at i=4 and j=3
new array = cfle
with size = 4
cfle
size = 4
cfle
@ShodanHo:
Your line 23 loops [0..i[ rather than [i+1..size[ and that is why you do resort to lines 33-35.
Your loop in 27-29 references array[size], which might not exist.
Here's another thread by jer311 that you may find useful. It is literally the same homework problem.

http://www.cplusplus.com/forum/beginner/115307/
Thanks for sharing "booradley60" I need that info too ...
Topic archived. No new replies allowed.
Pages: 12