Skip to main content

inter — String Intersection

Allowed functions: write

Write a program that takes two strings and displays, without doubles, the characters that appear in both strings, in the order they appear in the first one.

The display will be followed by a newline. If the number of arguments is not 2, the program displays a newline.

Examples

$>./inter "padinton" "paqefwtdjetyiytjneytjoeyjnejeyj" | cat -e
padinto$
$>./inter ddf6vewg64f gtwthgdwthdwfteewhrtag6h4ffdhsd | cat -e
df6ewg4$
$>./inter "rien" "cette phrase ne cache rien" | cat -e
rien$
$>./inter | cat -e
$

Solution

Download inter.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 = 0;
int j;

while (v[1][i]) {
j = 0;

while (v[2][j]) {
if (v[2][j] == v[1][i] && !seen[(int)(unsigned char)v[2][j]]) {

write(1, &v[1][i], 1);
seen[(int)(unsigned char)v[2][j]] = 1;
}
j++;
}

i++;
}
write(1, "\n", 1);

return 0;
}

How It Works

Goal: Display the characters common to both strings, without duplicates, in the order they appear in the first string.

Approach: For each character in the first string, scan the second string for a match, using a lookup table to avoid printing duplicates.

Step by step:

  1. If the argument count is not 3, print a newline and exit.
  2. Initialize a seen[256] array to zero (one slot per possible unsigned char value).
  3. For each character in v[1], iterate through v[2] looking for a match.
  4. When a match is found and seen is still 0 for that character, print it and mark it as seen.
  5. Print a trailing newline.

Key concept: Using a 256-entry boolean lookup table to track which characters have already been printed, ensuring each common character appears only once.