union — String Union
Allowed functions: write
Write a program that takes two strings and displays, without doubles, the characters that appear in either one of the strings.
The display will be in the order characters appear in the command line, and will be followed by a newline. If the number of arguments is not 2, the program displays a newline.
Examples
$>./union zpadinton "paqefwtdjetyiytjneytjoeyjnejeyj" | cat -e
zpadintoqefwjy$
$>./union ddf6vewg64f gtwthgdwthdwfteewhrtag6h4ffdhsd | cat -e
df6vewg4thras$
$>./union "rien" "cette phrase ne cache rien" | cat -e
rienct phas$
$>./union | cat -e
$
Solution
Download union.c#include <unistd.h>
int main(int c, char **v) {
if (c != 3) {
write(1, "\n", 1);
return 0;
}
int seen[256] = {0};
int i, j;
j = 1;
while (j <= 2) {
i = 0;
while (v[j][i]) {
if (!seen[(int)(unsigned char)v[j][i]]) {
seen[(int)(unsigned char)v[j][i]] = 1;
write(1, &v[j][i], 1);
}
i++;
}
j++;
}
write(1, "\n", 1);
return 0;
}
How It Works
Goal: Display all unique characters from both strings combined, in the order they first appear.
Approach: Iterate through the first string then the second, printing each character only the first time it is encountered using a lookup table.
Step by step:
- If the argument count is not 3, print a newline and exit.
- Initialize a
seen[256]array to zero (one entry per possibleunsigned charvalue). - Loop through
v[1]thenv[2](usingjfrom 1 to 2). - For each character, if
seenis0, print it and setseento1. - Print a trailing newline.
Key concept: A 256-entry boolean lookup table that maps every possible character value to a "printed" flag, guaranteeing each character is output exactly once.