Union Of Two Bags
November 8, 2019
Today’s exercise is somebody’s homework:
A bag is a list of key/count pairs: for instance, a bag containing three of item E, three of item R, and three of item A can be written E3R3A3. The union of two bags is a single bag containing a list of key/count pairs in which each item in each of the two bags has its count combined in a single item: for instance, the union of bags E3R3A3 and B3R3F3 is E3R6A3B3F3. The order of items in the bags is not significant.
Your task is to write three programs to compute the union of two bags, with time complexities O(mn), O((m+n) log (m+n)), and O(m+n), where m and n are the sizes of the two bags. 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.
Here is a solution in R7RS Scheme plus a few well-known helpers. It
is a bit more general than @programmingpraxis’s solution for bag
element types but uses a sorted representation of bags for the
linear-time version (instead of hashing).
In my earlier code, there is a missing reverse in the third cond clause.
Here’s a solution in Python.
Output:
Solutions in Racket.