如何随机化然后将ArrayList <string>拆分为两个偶数ArrayLists </string>

时间:2011-06-02 13:57:18

标签: java random arraylist split

我几乎不知道java,但我正在尝试为这个项目学习一些东西。我正在尝试修改一个名为GyaPickupBot的程序,这个程序基本上是IRC上的“拾取游戏”机器人,玩家可以在其中键入:!添加以添加到想要玩游戏的玩家列表和足够的玩家!添加机器人宣布游戏将要播放的游戏服务器(即地震服务器)的IP。现在,当指定数量的玩家!添加并且游戏启动时,机器人仅列出之前在添加最大玩家数量之前添加的玩家。我想把它分成所有玩家!加入到2个相同大小的随机队伍中。我已经使用Collections.shuffle完成了随机部分,但我不知道如何将玩家划分为2个同等大小的团队。我几周前给位于日本的作者发了电子邮件,他今天早上回答了一些关于如何做到这一点的非常模糊的提示:

嗯......在这个时候,我没有太多动力来维护这段代码。 我只能建议你一些提示。

private boolean handleReady(String channel, String sender, String login, String hostname, String message) {
boolean isUpdate = false;
String readyGameID = mgr.getReadyGameID();
if (null != readyGameID) {
// *** add some code here to choose teams and store that result to string variable. something like: "team1: ,,,, team2: ,,,,,"
// *** you can get players list by mgr.getPlayers(readyGameID) in order to divide players to 2 teams randomly 

for (String ch : getChannels()) {
sendMessage(ch, mgr.getPickupReadyString(readyGameID));
// sendNotice(ch, mgr.getPickupReadyString(readyGameID));
// *** then, send that string to channel
}
mgr.setLastGame(Calendar.getInstance().getTimeInMillis(), mgr.getPickupReadyString(readyGameID));
ArrayList<String> players = mgr.getPlayers(readyGameID);
for (String nick : players) {
sendNotice(nick, mgr.getPickupReadyPMString(readyGameID));
// *** and send that string to players too
}
isUpdate = mgr.clearPlayers(players);
}
return isUpdate;

我知道这可能比这里提出的更多,但我真的想学习这个,但我无法弄明白,任何帮助都会受到赞赏

1 个答案:

答案 0 :(得分:6)

以下代码未经测试,但应该让您知道如何继续。祝你好运。

// retrieve all players
ArrayList<String> players = mgr.getPlayers(readyGameID);
// randomize the list
Collections.shuffle(players);
// instantiate two arraylists for the teams
ArrayList<String> teamRed = new ArrayList<String>();
ArrayList<String> teamBlue = new ArrayList<String>();

// add the first half of players to teamRed
teamRed.addAll(players.subList(0, players.size() / 2 + players.size()%2));
// and the second half to teamBlue
teamBlue.addAll(players.subList(players.size() / 2 + players.size()%2, players.size()));

// now do whatever you need to do with the two teams