随机将数组拆分为2个均分的数组 [英] Randomly Split Array into 2 Evenly Divided Arrays

查看:108
本文介绍了随机将数组拆分为2个均分的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我试图在一个方法中将一个数组均匀且随机地分为2个其他数组.

So I am trying to divide an array into 2 other arrays evenly and randomly in a Method.

我对Java还是很陌生,我几乎不知道任何Array方法,也不知道在哪里可以找到它们.

I am very new to Java, and I don't know almost any Array methods, and don't know where to find them.

这是我到目前为止所拥有的:

Here is what I have so far:

public void makeTeams(){
        Player[] online = this.getServer().getOnlinePlayers();
        Player[] team1;
        Player[] team2;
    }

我正在使用Minecraft API Bukkit中的Player类型.

I am using the Player type from Bukkit, a Minecraft API.

推荐答案

Collections 框架有更多好处-除非确实需要使用数组,否则通常应避免使用数组.不过,由于您要使用数组,因此可以使用 Collections 为您完成繁重的工作.

The Collections framework has more goodies - you should in general avoid arrays unless you really need to use them. Nevertheless, since you have asked for arrays, here's how you can use Collections to do the heavy lifting for you.

要创建两个规模相等的团队,请从组中随机选择团队成员:

To create two teams of equal size, selecting team members randomly from a group:

Player[] online = getServer().getOnlinePlayers(); // don't need to code "this."
List<Player> list = Arrays.asList(online);
Collections.shuffle(list);
Player[] team1 = list.subList(0, list.size() / 2).toArray(online);
Player[] team2 = list.subList(list.size() / 2, list.size()).toArray(online);

此代码可满足组中奇数玩家的需求.

This code cater for an odd number of players in the group.

如果您使用集合(集合是要使用的正确集合)而不是数组,那么任务会简单得多.

If you were working with Collections (a Set would be the right Collection to use) and not arrays, the task would be far simpler.

这篇关于随机将数组拆分为2个均分的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆