Common Characters
May 14, 2019
Today’s exercise comes from a coding challenge site:
Given a list of words containing only lower-case letters, return a list of characters that appear in all the words, with multiplicity. For instance, given the words BELLA, LABEL and ROLLER, the characters E, L and L appear in all three words.
Your task is to return a list of characters that appear in all words of an input list. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
A Haskell version.
In Python.
from collections import Counter from functools import reduce from operator import and_ def common(listofwords): return list(reduce(and_, (Counter(w) for w in listofwords)).elements()) print(common(["BELLA", "LABEL"])) # -> ['B', 'E', 'L', 'L', 'A'] print(common(["BELLA", "LABEL", "ROLLER"])) # -> ['E', 'L', 'L']Here’s a solution in C.
#include <stdio.h> #include <stdlib.h> // Returns the result in s1 void common(char* s1, char* s2) { int a1[26] = {0}; int a2[26] = {0}; char* _s1 = s1; for (; *s1; ++s1) { ++(a1[*s1 - 'a']); } for (; *s2; ++s2) { ++(a2[*s2 - 'a']); } int pos = 0; for (int i = 0; i < 26; ++i) { int count = a1[i] < a2[i] ? a1[i] : a2[i]; for (int j = 0; j < count; ++j) { _s1[pos++] = 'a' + i; } } _s1[pos] = '\0'; } int main(int argc, char* argv[]) { if (argc == 1) return EXIT_FAILURE; for (int i = 1; i < argc; ++i) { common(argv[1], argv[i]); } printf("%s\n", argv[1]); return EXIT_SUCCESS; }Example Usage: