Choose random array element satisfying certain property

后端 未结 5 1593
隐瞒了意图╮
隐瞒了意图╮ 2020-12-16 15:34

Suppose I have a list, called elements, each of which does or does not satisfy some boolean property p. I want to choose one of the elements that

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-16 16:13

    For clarity's sake, I would try:

    pickRandElement(elements, p)
         OrderedCollection coll = new OrderedCollection
         foreach element in elements
              if (p(element))
                   coll.add(element)
         if (coll.size == 0) return null
         else return coll.get(randInt(coll.size))
    

    To me, that makes it MUCH clearer what you're trying to do and is self-documenting. On top of that, it's simpler and more elegant, and it's now obvious that each will be picked with an even distribution.

提交回复
热议问题