Reputation: 125
I have code for char array unique elements searching. But it works incorrectly. For example, in case of "ABCD" array, I lose "ABD" case. How can I fix it?
#include <stdio.h>
#include <string.h>
void fun(char *str, int size, int depth)
{
int i = 0;
int j = 0;
int k = 0;
while (i < size - depth + 1)
{
j = i + 1;
while (j < size - depth + 2)
{
printf("%c", str[i]);
k = j;
while (k < j + depth - 1)
{
printf("%c", str[k]);
k++;
}
printf("\n");
j++;
}
i++;
}
}
int main(void)
{
char *str = "ABCD";
int i = 0;
while (i < strlen(str))
{
fun(str, strlen(str), i + 1);
i++;
}
return (0);
}
The result is: A A A A B B B C C D AB AC AD BC BD CD ABC ACD BCD ABCD
And I need: A B C D AB AC AD BC BD CD ABC ABD ACD BCD ABCD
So as you can see there are several bugs - repeats of single chars at the beginning and missing ABD case. If the string is "ABCDE" there are more variants will be missing.
Upvotes: 2
Views: 512
Reputation: 399
This code should fix the problem:
#include <string.h>
#include <stdio.h>
void fun(char *str, char *data, int start, int end, int idx, int depth)
{
if (idx == depth)
{
for (int j = 0; j < depth; j++)
printf("%c", data[j]);
printf("\n");
return;
}
for (int i = start; i <= end && end - i + 1 >= depth - idx; i++)
{
data[idx] = str[i];
fun(str, data, i + 1, end, idx + 1, depth);
}
}
int main()
{
char *str = "ABCD";
int i = 0;
while (i < strlen(str))
{
char data[i + 1];
fun(str, data, 0, strlen(str) - 1, 0, i + 1);
i++;
}
return (0);
}
Output:
A B C D AB AC AD BC BD CD ABC ABD ACD BCD ABCD
And also works for "ABCDE" and etc.
Upvotes: 0