A bag, also called a multiset, is an unordered collection. You can call it a set that allows duplicates, or a list (or an array) that is not ordered/indexed. In this challenge, you are asked to implement bag operations: addition, difference, multiplication, division, counting and equality test.
Operations
The specified operations may not be conventional.
- addition combines two bags into one, conserving the total number of each value
[1,2,2,3] + [1,2,4] = [1,1,2,2,2,3,4]
- difference removes from a bag each element of another bag, or does nothing if no such element
[1,2,2,4] - [1,2] = [2,4]
[1,2,3] - [2,4] = [1,3]
- multiplication multiplies each element in the bag.
[1,2,3,3,4] * 3 = [1,1,1,2,2,2,3,3,3,3,3,3,4,4,4]
2 * [1,3] = [1,1,3,3]
- division is an uncommon one: each n equal elements are put in n equal new bags, elements that cannot form an n-group remain in the bag. Return any one of the n new bags.
[1,1,2,2,2] / 2 = [1,2]
[1,2,2,3,3,3] / 3 = [3]
- counting counts how many divisor bags can be produced from the dividend bag
[1,1,2,2,2,2,3,3,3] c [1,2,3] = 2
- equality test checks if two bags have the same numbers of each element
[1,2,2,3] == [3,2,1,2] = truthy
[1,2,3] == [1,2,2,3] = falsy
(can also use=
for this)
If you are using your own symbols for the operators, please specify.
Formats
Bags will be displayed as lists of the form [1,1,2,3,4]
. You can use any other bracket than square ones, or even use quotes, or nothing at all. The elements will be integers(mathematically, not necessarily int
) for the purpose of this question. Bags do not have to be sorted.
The input format will be two bags or a bag and an integer, with an operator. You can specify your own format as long as it contains these three.
The output format should be a single bag of the same format.
Rules
- you may not use built-in functions, operations or libraries (including the standard library) that already implement these; it's ok though to use list concatenation and multiplication since they are by definition list operations, not bag operations (which happen to basically do the same thing)
- standard loopholes apply
- shortest answer wins
Test cases
[1,2,2,3] + [1,2,4]
[1,1,2,2,2,3,4]
[1,2,2,4] - [1,2]
[2,4]
[1,2,3] - [2,4]
[1,3]
[1,2,3,3,4] * 3
[1,1,1,2,2,2,3,3,3,3,3,3,4,4,4]
2 * [1,3]
[1,1,3,3]
[1,1,2,2,2] / 2
[1,2]
[1,2,2,3,3,3] / 3
[3]
[1,1,2,2,2,2,3,3,3] c [1,2,3]
2
[3,2,1,2] == [1,2,2,3]
truthy
[1,2,3] == [1,2,2,3]
falsy