Skip to content

Instantly share code, notes, and snippets.

@Plankiton
Last active August 4, 2021 14:29
Show Gist options
  • Select an option

  • Save Plankiton/8358582e0985aad557353d57a0f92696 to your computer and use it in GitHub Desktop.

Select an option

Save Plankiton/8358582e0985aad557353d57a0f92696 to your computer and use it in GitHub Desktop.
Thats algorithm make a union between 2 int8 arrays without to repeat values
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
bool contains(char l, char * v, char c);
char * do_union(char n1, char n2, char * v1, char * v2);
int main()
{
char n1, n2;
printf("type length of array 1 and array 2:\n ex: 2 3 ");
scanf("%2" SCNu8 " %2" SCNu8, (uint8_t*)&n1, (uint8_t*)&n2);
char v1[n1], v2[n2];
for (int i = 0; i < n1; i++) {
printf("type array 1 %i position: ", i+1);
scanf("%2" SCNu8, (uint8_t*)&v1[i]);
}
for (int i = 0; i < n2; i++) {
printf("type array 2 %i position: ", i+1);
scanf("%2" SCNu8, (uint8_t*)&v2[i]);
}
printf("Merged array: ");
char *v3 = do_union(n1, n2, v1, v2);
for (int i = 0; i < n1+n2; i++) {
if (v3[i] >= 0) {
printf("%i ", v3[i]);
}
}
puts("");
free(v3);
return 0;
}
bool contains(char l, char * v, char c) {
for (int i = 0; i < l; i++) {
if (c == v[i]) return true;
}
return false;
}
char * do_union(char n1, char n2, char * v1, char * v2) {
int size = n1 + n2, i = 0;
char * v3 = (char *)malloc(size);
for (; i < n1; i++) {
v3[i] = v1[i];
}
for (int j = 0; j < n2; j++) {
if (!contains(size, v3, v2[j])) {
v3[i++] = v2[j];
} else {
v3[i++] = -1;
}
}
return v3;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment