Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The most efficient solution will partly depend on how often you're going to pick random elements, whether you want to pick <em>different</em> random elements, and what proportion of the elements meet the criterion</p> <p>A few options:</p> <ul> <li>Create a copy containing only the elements meeting the criterion. You can then either shuffle that and iterate over it for successive distinct random elements, or just pick arbitrary random elements by picking a random index. This is obviously O(n) setup in both time and space, but efficient thereafter.</li> <li>Shuffle the collection once, then iterate over as you are doing - but keep the iterator. Alternatively, perform the iteration manually using the index. This will allow you to get distinct random elements. This is O(n) setup again.</li> <li>Keep picking random elements from the original list until you find one which meets the criteria. This has could take a very long time if you have a large list with only a few "valid" items though. This requires no setup, but you could end up "wasting" work by repeatedly testing the same elements.</li> <li>A hybrid approach: keep picking random elements from the original list, but <em>remove</em> them if they don't meet the criterion. Unfortunately removal from the middle of a list is O(n) operation too for the common case of <code>ArrayList</code> :(</li> </ul> <p>(Note that this I've been mostly assuming <code>ArrayList</code> complexity. Getting to a specific index in a <code>LinkedList</code> is O(n) for example, but then removal is cheap.)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload