Skip to content

Instantly share code, notes, and snippets.

@shintakezou
Created April 14, 2019 15:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shintakezou/4bc8b97ec34bbddcb38a6e6c6f242797 to your computer and use it in GitHub Desktop.
Save shintakezou/4bc8b97ec34bbddcb38a6e6c6f242797 to your computer and use it in GitHub Desktop.
Couting unique elements, with a peculiar definition of equality.
#include "elements.h"
#include <stddef.h>
#include <stdbool.h>
static int compare(const element *a, const element *b)
{
if (a->e2 == b->e2)
return 0;
else if (a->e1 != b->e1)
return b->e1 - a->e1;
return b->e2 - a->e2;
}
size_t count_unique(const element *s)
{
size_t c = 0;
bool found;
for (size_t i = 0; s[i].s != NULL; ++i) {
found = false;
for (size_t j = 0; j < i; ++j) {
if (compare(&s[i], &s[j]) == 0) {
found = true;
break;
}
}
if (!found)
c++;
}
return c;
}
#ifndef ELEMENTS_H
#define ELEMENTS_H
#include <stddef.h>
typedef struct
{
const char *s;
int e1;
int e2;
} element;
size_t count_unique(const element *s);
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment