Skip to content

Instantly share code, notes, and snippets.

@chrisdel101
Created May 12, 2019 20:41
Show Gist options
  • Save chrisdel101/ee85a03e408e6109e414bc147b379cea to your computer and use it in GitHub Desktop.
Save chrisdel101/ee85a03e408e6109e414bc147b379cea to your computer and use it in GitHub Desktop.
deleteOccurences
#include <stddef.h>
int delete_nth(size_t szin, int order[szin], int max_e, size_t *szout);
int main(void) {
// 12311223345
int order[] = {1,2,3,1,1,2,1,2,3,3,2,4,5,3,1};
int res = delete_nth(14, order, 3, NULL);
printf("RES:%i\n",res );
}
// used in qsort
int cmpfunc (const void * a, const void * b) {
return ( *(int*)a - *(int*)b );
}
int delete_nth(size_t szin, int order[szin], int max_e, size_t *szout) {
int len = szin;
int k = 0;
int *newArr = calloc( sizeof(int), k+1);
// buffer length
int p = 0;
// add one if p is zero, else no add 1 so there is at least some bufff
int removeLen = p = 0 ? p + 1 : p;
int removeIndexes[removeLen];
// get indexes of all the ones to be removed
for (size_t i = 0; i < szin; i++) {
// reset count on each new value
int count = 0;
for (size_t j = i + 1; j < szin; j++) {
// if a match is found later on
if(order[i] == order[j]){
count++;
// count each occurence
if(count >= max_e){
// assign index of double to arr
removeIndexes[p] = j;
p++;
// decrement len of store and malloc
len--;
}
}
}
}
// sort to remove by index
qsort(removeIndexes, p , sizeof(int), cmpfunc);
printf("P %i\n", p );
// loop over index array and match each index to full arr
int previousRemoved = 0;
for (size_t i = 0; i < p; i++) {
int toRemove = removeIndexes[i];
printf("VAL %i\n", toRemove );
for (size_t j = previousRemoved; j < szin; j++) {
if(j != toRemove){
newArr[k] = order[j];
k++;
} else {
printf("remove %i\n", order[j]);
// set inner loop to start at last index
previousRemoved = toRemove + 1;
if(p > 1){
break;
}
}
}
}
szout = k;
printf("k %i\n",k );
return *newArr;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment