Can a set have duplicate elements?

前端 未结 4 1899
醉酒成梦
醉酒成梦 2021-02-07 14:25

I have been asked a question that is a little ambiguous for my coursework.

The array of strings is regarded as a set, i.e. unordered.

I\'m not

4条回答
  •  旧巷少年郎
    2021-02-07 15:12

    A set cannot have duplicate elements by its mere definition. The correct structure to allow duplicate elements is Multiset or Bag:

    In mathematics, a multiset (or bag) is a generalization of the concept of a set that, unlike a set, allows multiple instances of the multiset's elements. For example, {a, a, b} and {a, b} are different multisets although they are the same set. However, order does not matter, so {a, a, b} and {a, b, a} are the same multiset.

    A very common and useful example of a Multiset in programming is the collection of values of an object:

    values({a: 1, b: 1}) //=>  Multiset(1,1)
    

    The values here are unordered, yet cannot be reduced to Set(1) that would e.g. break the iteration over the object values.

    Further, quoting from the linked Wikipedia article (see there for the references):

    Multisets have become an important tool in databases.[18][19][20] For instance, multisets are often used to implement relations in database systems. Multisets also play an important role in computer science.

提交回复
热议问题