This Q needs some dedup itself. Remove duplicates... But since this is my third version of the inner loop I take advantage of a fresh start.
This inoffensive assignment
int j = i + 1;
, originally packed into the for-expression-list, does more than just initialize j
for the last i: it makes m[j]
illegal/undefined.
The goal (?) is to avoid the dup
flag and to "normalize" the loops. I think this rearrangement is worth it:
int j;
for (int i = 0; i < ARRAY_SIZE; i++) {
j = i;
do
if (++j == ARRAY_SIZE) { // already past end?
p[k++] = m[i]; // copy this one
break; // and finish
}
while (m[i] != m[j]); // if match, then just finish
}
Now everything is at the natural place.
I wrote do statement while (expr);
without braces to illustrate the structure. What is a bit hidden is the loop increment if (++j...
.
Instead of a real (sorted) structure one can use the new unique array to search for duplicates. Because of the 0
already in the new array I first copy the first element unconditionally, and then start the loop with the second element.
int k = 1;
/* First is always unique */
printf("m[0] -> p[0]\n");
p[0] = m[0];
for (int i = 1; i < ARRAY_SIZE; i++)
for (int j = 0;; j++) {
if (j == k) {
printf("m[i=%d] -> p[k=%d]\n", i, k);
p[k++] = m[i];
break;
}
if (p[j] == m[i])
break;
}
Still this if (p[j] == m[i])
has to be logically after if (j == k)
, so the for-loop has to be freestyled a bit.
The printf
s illustrate:
Enter number: 6
Enter number: 6
Enter number: 0
Enter number: 0
Enter number: 8
m[0] -> p[0]
m[i=2] -> p[k=1]
m[i=4] -> p[k=2]
The array without repeated values
6
0
8
Side effect: the order is now preserved.
I guess this is a bit tricky because the searching and inserting are so closely connected. The k
index must be handled precisely. (the other ones also)
Performance: I don't even know if using the new array up to k is faster than OP searching the rest of the original. It seems to amount to the same at least for some cases.
Problem is the new array is not sorted. Keeping it sorted costs too much if done naively, after every insert.
So one would have to "spread" out first in order to search efficiently. For (random) integers, modulo 10 can create ten different arrays - or buckets. With a 2D b[][]
(instead of OP p[]
)
b[0] {100}
b[1] {1, 31, 20001}
b[2] {12, 32, 502}
b[3] {}
b[4] {94}
...
Every (sub)array needs the original ARRAY_SIZE
for the worst case. But now the array to search for dups is 10 times shorter on average.
So you could change the interactive input into a one-million-integers array generator and do some tests.
All because of that dup
loop flag ;)