简体   繁体   English

如何从数组列表中随机抽取一个字符串并将其放入另一个列表中?

[英]How can I randomly pull out a String from an array list and put it in another?

As seen in the code that I tried to write, I want to grab a name from the Array list "names" and either add it to groupA or B. I do not need the groups to be even.如我尝试编写的代码所示,我想从数组列表“名称”中获取一个名称并将其添加到组 A 或 B。我不需要组是偶数。

import java.io.File;
import java.io.FileNotFoundException; 
import java.util.Scanner;
import java.util.Random;
import java.util.ArrayList;

public class GroupPicker{
    public static void main(String[] args) throws FileNotFoundException{
        Scanner input = new Scanner(new File("GroupPicker1.txt"));
        ArrayList<String> names = new ArrayList<String>();
        ArrayList<String> groupA = new ArrayList<String>();
        ArrayList<String> groupB = new ArrayList<String>();
        Random random = new Random();
        while(input.hasNext()){
            String nextName = input.next();
            names.add(nextName);
        }
        for (int i = 0; i < names.size(); i++) {
          names.get(random.nextInt(groupA.add()));
          
          names.get(random.nextInt(groupB.add()));
        }
        System.out.println( "\n" + "project groups: ");
        System.out.println("Group A: " + groupA);
        System.out.println("Group B: " + groupB);   
    }
}

How can I randomly pull out a String from an array list and put it in another如何从数组列表中随机抽取一个字符串并将其放入另一个

List<String> names = new ArrayList<>();
Random r = new Random();
  • nextInt(n) - returns a value between 0 and n-1 inclusive nextInt(n) - 返回介于0 and n-1之间的值(含 0 和 n-1)
  • r.nextInt(names.size()) - will get one random index of all possible indices r.nextInt(names.size()) - 将获得所有可能索引的一个随机索引
String name = names.get(r.nextInt(names.size());
List<String> otherList = new ArrayList<>();
otherList.add(name);

Note you can also shuffle a list if required.请注意,如果需要,您还可以随机播放列表。

Collections.shuffle(names);

Then you can simply iterate across the list, getting names in the new random order.然后您可以简单地遍历列表,以新的随机顺序获取名称。

First you have to make sure the random.nextInt() doesn't give you a too high value, because you only put so much values into names , but random.nextInt() will return any int - this could be even negative!首先,你必须确保random.nextInt()不会给你一个太高的值,因为你只将这么多值放入names ,但random.nextInt()将返回任何 int - 这甚至可能是负数!

So the easiest way would be this:所以最简单的方法是这样的:

  1. shuffle the names list with Collections.shuffle(names)使用Collections.shuffle(names)随机播放names列表
  2. put the first half of names into groupA - with the use of List.subList you would not even have to create a new list, just use the returned result.names的前半部分放入groupA - 使用List.subList您甚至不必创建新列表,只需使用返回的结果即可。
  3. put the second half of names into groupBnames的后半部分放入groupB

You have to take care about the indexes for the "halfes" - and decide what to do if the number of entries in names is odd - put one more into groupA or groupB .您必须注意“halfes”的索引 - 并决定如果names中的条目数为奇数时要做什么 - 将一个多放入groupAgroupB

When I read this problem, two conditions stand out.当我读到这个问题时,有两个情况很突出。

  1. the names must go into one of the lists (meaning not the other) -- you must take it from the names ArrayList名称必须 go 进入列表之一(意思不是另一个) - 你必须从名称 ArrayList 中获取它
  2. the names do not need to be even -- you do not need to keep track of which list they are being added to名称不需要是偶数——您不需要跟踪它们被添加到哪个列表

I would use an enhanced for-loop for ease of use (the less variables the better)为了便于使用,我会使用增强的 for 循环(变量越少越好)

    // this cycles through each index of the names ArrayList
    for(String singleName : names)
    {
        // creates a random number
        java.util.Random number = new java.util.Random();

        // add to groupA if it is an even number and groupB if it is odd
        if(number.nextInt(2) % 2 == 0)
            groupA.add(singleName);
        else
            groupB.add(singleName);
    }

EDIT AFTER SHOWING MY PROFF XD展示我的专业后编辑 XD

For simplicities sake, you could even cut off the % 2 == 0 because 0 and 1 will only ever give you 0 or 1 with that statement.为了简单起见,你甚至可以切断% 2 == 0因为01只会给你01与该声明。 This could look like this:这可能看起来像这样:

    java.util.Random rand = new java.util.Random();
    // true = one list && false = the other
    if(rand.nextBoolean())
        groupA.add(singleName);
    else
        groupB.add(singleName);

This is what I would do if I understand your need:如果我了解您的需求,我会这样做:


// Scanner input = new Scanner(new File("GroupPicker1.txt"));
      String arr[] = new String[] { "A", "B", "C", "D" };
      ArrayList<String> names = new ArrayList(Arrays.asList(arr));
      ArrayList<String> groupA = new ArrayList<String>();
      ArrayList<String> groupB = new ArrayList<String>();
      
      // while(input.hasNext()){
      //     String nextName = input.next();
      //     names.add(nextName);
      // }
      while (!names.isEmpty()) {
        for (int i = 0; i < names.size(); i++) {
          int random = ThreadLocalRandom.current().nextInt(i, names.size());
          boolean randBool = Math.random() < 0.5;
          String name = names.get(random);
          names.remove(random);
          if (randBool){ 
            groupA.add(name);
            break;
          };
          groupB.add(name);
        }  
      }
      
      System.out.println( "\n" + "project groups: ");
      System.out.println("Group A: " + groupA);
      System.out.println("Group B: " + groupB); 

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

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