0

How would I go about printing every color in the following array only once each?? The output I'm looking for is something like RED BLUE WHITE ...

char *my_array[20]={"RED","BLUE","WHITE","BLUE","YELLOW","BLUE","RED","YELLOW","WHITE","BLUE","BLACK","BLACK","WHITE","RED","YELLOW","BLACK","WHITE","BLUE","RED","YELLOW"};

1 Answers1

0

If you sort them, then you can check whether the last repeated element was the previous element and print it, otherwise keeps searching like this

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int
compare(const void *const str1, const void *const str2)
{
    return strcmp(str1, str2);
}

int 
main(void)
{
    const char *my_array[20] = {
        "RED", "BLUE", "WHITE", "BLUE", "YELLOW", "BLUE", "RED",
        "YELLOW", "WHITE", "BLUE", "BLACK", "BLACK", "WHITE",
        "RED", "YELLOW", "BLACK", "WHITE", "BLUE", "RED",
        "YELLOW"
    };
    const char *last;
    size_t count;

    count = sizeof(my_array) / sizeof(*my_array);
    if (count == 0) // What?
        return -1;
    qsort(my_array, count, sizeof(*my_array), compare);

    last = my_array[0];
    for (size_t i = 1 ; i < count ; ++i)
    {
        if (strcmp(last, my_array[i]) == 0)
            continue;
        fprintf(stdout, "%s\n", last);
        last = my_array[i];
    }
    // The last one
    fprintf(stdout, "%s\n", last);
    return 0;
}
Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97