【问题标题】:randomly remove element from array java从数组java中随机删除元素
【发布时间】:2016-05-17 04:38:25
【问题描述】:

我在下面的代码中从数组中删除元素。在此特定代码中,我将删除位置 2 处的元素。我将如何删除此数组中的随机元素?

public class QuestionOneA2 {

public static void main(String[] args) {
    int size = 5;
    int pos = 2;

    String[] countries = {"Brazil", "France", "Germany", "Canada", "Italy", "England"};

        for (int i = 0; i < size; i++) {
            if(i == pos) {
                countries[i] = countries[size];
            }
            System.out.println(countries[i]);
        }   
    }
}

【问题讨论】:

  • 使用例如int size = countries.length - 1 或只是 countries.length - 1 而不是固定大小;否则你做错了。

标签: java arrays random


【解决方案1】:

如果你不介意元素的顺序,你也可以在恒定时间内实现这种行为:

public <E> E removeRandom(List<E> list, Random random) {
    if (list.isEmpty())
        throw new IllegalArgumentException();

    int index = random.nextInt(list.size());
    int lastIndex = list.size() - 1;

    E element = list.get(index);
    list.set(index, list.get(lastIndex));
    list.remove(lastIndex);

    return element;
}

【讨论】:

    【解决方案2】:

    删除此元素:

    int randomLocation = new Random().nextInt(countries.length);
    // countries[randomLocation]  <--- this is the "random" element.
    

    或在 1 行中:

    countries[(new Random()).nextInt(countries.length)];
    

    因此,为了实际删除元素,您可以使用ArrayUtils: 先导入这些

    import java.util.Arrays;
    import org.apache.commons.lang.ArrayUtils;
    

    然后:

    countries = ArrayUtils.removeElement(countries, countries[(new Random()).nextInt(countries.length)]);
    

    如果你真的不想使用ArrayUtils,那么你可以使用:

    List<String> list = new ArrayList<String>(Arrays.asList(countries));
    list.removeAll(Arrays.asList(countries[(new Random()).nextInt(countries.length)]));
    countries = list.toArray(countries);
    

    【讨论】:

    • 如果我这样做,我应该在我的 for 循环中放什么?
    • @StudentCoder 我用更清晰的命令编辑了我的答案(删除你的for循环)
    • 谢谢,我实际上是在尝试使用 for 循环来解决这个问题
    • 在这个程序中没有使用for循环,这是浪费空间和时间。
    • 这是我正在尝试做的两部分问题的第一部分,然后要求用户输入缺少的国家,并指示我使用 for 循环,我是否正在查看他的完整内容走错路了?
    【解决方案3】:
    Random r = new Random();
    int result = r.nextInt(size);
    //and select/remove countries[result]
    

    这会为您提供一个介于 0 和 5(不包括在内)之间的伪随机数。 小心你的 size 变量,我认为它没有很好地定义。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-18
      • 1970-01-01
      • 2022-01-13
      • 2018-07-19
      • 2014-03-06
      • 2017-12-06
      • 1970-01-01
      • 2010-10-13
      相关资源
      最近更新 更多