简体   繁体   English

从组织好的ArrayList中挑选一个随机元素

[英]Picking out a random element from an organised ArrayList

So the idea here is that I have an ArrayList with a set of words, I want to sort the list so that it only includes entries with even numbered indecies and then picks out an entry at random. 所以这里的想法是,我有一个带有一组单词的ArrayList,我想对列表进行排序,以便它只包括带有偶数编号的索引的条目,然后随机选择一个条目。 I gave this a bash and I managed to get it to show only odd entries like so: 我给了它一个bash,我设法使其仅显示如下所示的奇数项:

 int i = 0;

    for (Iterator<Phrase> it = phrases.iterator(); it.hasNext(); i++)
    {
        Phrase current = it.next(); 

        if (i % 2 == 0)
        {
            System.out.println(current);    
        }            
    }

And this prints off every odd numbered element on the ArrayList which is fine, but I don't know how to select one at random from the odd numbered ones. 并且这会打印出ArrayList上的每个奇数元素,这很好,但是我不知道如何从奇数元素中随机选择一个。 This is what I tried putting into the if statement but it doesn't do what I want it to, it does print off the elements at random but it also includes the odd numbered elements when I only want the even ones 这是我尝试放入if语句中的内容,但没有达到我想要的效果,它会随机打印出元素,但是当我只需要偶数元素时,它还会包含奇数元素

Random r = new Random();
int x = r.nextInt(phrases.size());
System.out.println(phrases.get(x));

Any help would be very appreciated here, thanks. 在这里,任何帮助将不胜感激,谢谢。

but I don't know how to select one at random from the odd numbered ones. 但我不知道如何从奇数中随机选择一个。

what about ensuring x to be half of the size and multiply it with 2 to have the even index. 如何确保x为大小的一半并将其乘以2以获得偶数索引呢? Try the following: 请尝试以下操作:

 Random r = new Random();
 int x = r.nextInt(phrases.size()/2) + (list.size() & 1) - 1; 
   // size is divided by 2 
  // so that x is randomly 0 to (size/2 -1) inclusive
  System.out.println(phrases.get(x * 2)); // ensuring the accessing index are even

You could loop until you get one, but technically, that may never happen. 您可以循环直到获得一个,但从技术上讲,这可能永远不会发生。 So instead, just make sure x is a multiple of 2. 因此,只需确保x是2的倍数即可。

            Random r = new Random();
            int x = r.nextInt(phrases.size()); // Might be even or odd
            x = x % 2 != 0 ? x + 1 : x; // if x is not divisible by 2, x + 1, else x
            // x  is is now a multiple of two
            if(x >= phrases.size()){ // make sure x is still within the 
                                                  // index boundaries.
                  x = x-2;
                  if(x < 0){
                      x = 0;
                  }   
            }
            System.out.println(phrases.get(x));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM