【发布时间】:2015-09-24 01:56:25
【问题描述】:
我正在寻找一种不太复杂的方法(如果可能)将元素插入到二维数组的下一个空垂直索引,同时随机循环遍历水平索引。
例如:
制作一张表格,显示来自 8 支球队的 32 名球员,随机分配到 4 个回合中。所以,我们希望每轮有 8 名玩家。
考虑以下内容:roundsTable[x][y] 是表格,而 x 代表每个玩家参加的回合,y 代表每个回合中的玩家。玩家将从另一个二维数组players[t][p] 中收集,并将按索引顺序 t(0,1,2,3,4,5,6,7) p(0,1,2,3) 收集。但是,它们将在每次随机循环x 中存储在roundsTable[][] 中。问题是,我怎样才能在每个被选中的随机x 中将每个玩家放在y 的下一个空白位置。
//playersRoundOrder[] is 32 long and contains the random rounds in a range of 1-4. It looks something like that: {1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,3,3,3...} then I shuffle it to become something like this: {4,1,1,3,2,3,4...}. Then, I take the first index of that array and I set it as the round for the first index of player in the first team, then the second index to the second player of the first team...etc
private void example(int[] playersRoundOrder) {
String[][] roundsTable = new String[4][8]; //The table that I will use to store each player based on their round. So, the player whose round is 3, will be stored at roundsTable[3][*Here is where I need the solution. I want to insert each player in round three in the next available spot etc.*]
int t = 0; //count the index of each team. So, it will only increase when I set a random round for each player in the first team.
int p = 0; //count the index of each player in t. So, it will increase after each 1 loop, and it returns to zero when t increase.
for (int i = 0; i < playersRoundOrder.length; i++) {// loop 32 times
//String players[][] is the other two dimensional array that contains 32 players
//(8 teams - 4 players for each)
if ((p + 1) == players[t].length) { //If there is no more players in this team t, go to the next team and start from the index of the first player
roundsTable[playersRoundOrder[i]] [**PROBLEM**] = players[++t][p = 0];
} else { //If there is still players on the team, go to the next player
roundsTable[playersRoundOrder[i]] [**PROBLEM**] = players[t][p++];
}
}
}
【问题讨论】:
-
您能否提供您正在寻找的内容的视觉效果?
-
@MarquisBlount 我添加了一个视觉近似。
-
对不起,我应该更具体一点,我的意思是您要构建的矩阵的视觉效果。 “在随机遍历水平索引时”是什么意思。我对您如何尝试构建此矩阵感到有些困惑。您是否要在每列中存储 0-3(或 1-4)的随机数?
-
@MarquisBlount 很抱歉造成混乱。我找不到更好的方法来解释这个想法。我会尝试改变我的问题,让它更明显一点。另外,关于您的问题,我正在尝试将数字 1-4 存储在
playersRoundOrder数组中重复 8 次。所以,它看起来像 {1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2...} 然后它改组以提取随机数(1-4)个。 -
我建议在您的问题中创建一个格式化的示例矩阵。 “一张图胜过千言万语”
标签: java multidimensional-array