数组中的数组(2D数组?)

时间:2015-08-11 21:45:20

标签: ios arrays class swift2

标题可能不清楚,我不确定如何在没有具体细节的情况下表达这个想法,所以这里是简要说明:

我的代码有一个Players数组(我写的一个类)。我想在给定数量的团队之间平均分割数组中的条目(基于它们的Players.rating)。问题出现了团队的数量是var teamAmount并且可以设置在2到8之间。我试图找到一种简单的方法来创建一些等于值的Player类数组teamAmount的(不必写7个开关盒)。我正在考虑一个2D数组,但我想不出如何初始化它。我觉得它可能很简单,但我似乎无法解决它

2 个答案:

答案 0 :(得分:1)

我在下面发布了一些伪代码。你必须修改它以适应Swift语法(我现在离开了Mac,当我把它扔进游乐场后回家时会编辑它。)

func generate2DArray(players: Array<Player>, numTeams: Int) -> Array<Array<String>>{
  var teams = Array<Array<Player>>()

  for index in 0...numTeams{
      //init the first dimension of empty arrays for each team
      teams.append([Player]())
  }

  for var i = 0; i < players.count; ++i{
    //Place the player in the correct team respectively... (sorry about array syntax, I know its wrong)
      teams[i % numTeams].append(players[i]);
  }
  return teams;
}

基本的想法是你知道你想要多少个团队,你可以通过简单的for循环初始化2D数组的第一维。

然后将球员放在各自的球队中,只需使用魔法模数。

理论

  • 球员1%4球队=属于球队1。
  • 球员2%4球队=属于球队2
  • 球员3%4球队=属于球队3。
  • 球员4%4球队=属于球队0。
  • 球员5%4球队=属于球队1。
  • 球员6%4球队=属于球队2。
  • 球员7%4球队=属于球队3。
  • 球员8%4球队=属于球队0。

(由于4%4为0,你必须抵消你的数组,或者提供一些简单的逻辑来覆盖这种情况,最简单的就是让团队0而不是团队4)

<强>更新

注意到你希望它们按球员评分均匀分布。在这种情况下,只需确保在将玩家放入团队之前按照他们的评级对玩家进行排序(假设您知道如何在Swift中对数组进行排序,我将省略显示如何执行此操作,如果有帮助则请注释需要的。)

<强>更新

我测试了我添加的代码并进行了一些修改,以便它在Swift中正常运行

以下是预期的结果

generate2DArray([player1, player2, player3, player4, player5, player6], 2)
//Returns [player1, player3, player5] , [player2, player4, player6]
generate2DArray([player1, player2, player3, player4, player5, player6], 4)
//Returns [player1, player5] , [player2, player6] , [player3] , [player4]

答案 1 :(得分:1)

这里有一个选项:

// e.g. setting up Player(s)
struct Player {
  var rating = 0
}
let players = [Player(rating: 1), Player(rating: 3), Player(rating: 2), Player(rating: 7), Player(rating: 5), Player(rating: 4), Player(rating: 3)]
let sortedPlayers = players.sort { $0.rating > $1.rating }

print(sortedPlayers)
// [Player(rating: 7), Player(rating: 5), Player(rating: 4), Player(rating: 3), Player(rating: 3), Player(rating: 2), Player(rating: 1)]

// e.g. setting up Team(s)
let numberOfTeams = 3
typealias Team = [Player]

// now do the work
let teams = sortedPlayers.enumerate().reduce(
  Array(count: numberOfTeams, repeatedValue: Team()),
  combine: { (var teams, let player) in
    let (playerIndex, player) = player
    teams[playerIndex % numberOfTeams].append(player)
    return teams
  }
)

print(teams)
// [[Player(rating: 7), Player(rating: 3), Player(rating: 1)], [Player(rating: 5), Player(rating: 3)], [Player(rating: 4), Player(rating: 2)]]