您如何对数组列表进行排序以使其多样化而不是相似?

时间:2021-03-16 09:01:14

标签: java arraylist

因此,对于我的一个项目,我必须根据姓氏为游戏创建团队,他们应该尽可能多样化,因此“史密斯”家族只会被添加到与另一个团队相同的团队中”如果没有其他团队没有“史密斯”,则为史密斯家族。

我得到一个包含参与者名单的 ArrayList,其中包括了他们的姓氏。我只需要弄清楚如何对此进行排序,以便 ArrayList 多样化,我只需遍历 ArrayList 并将它们分配给团队

ArrayList<Participant> list = tourney.getUnattatchedParticipants();
//need to sort list somehow

1 个答案:

答案 0 :(得分:0)

我会这样处理你的问题;

  1. 创建一个保存所有团队的数据容器。由于我们不确定我们将拥有多少个团队,因此我会将这个数据容器设为动态(例如 ArrayList
  2. 我将开始与参与者重复您的 ArrayList,对于每个我会检查 Team Nr.1 是否包含具有相似(相同或包含部分姓氏)姓氏的参与者。
  3. 如果是,请检查 Team Nr.2..
  4. 如果我们到达最后一个团队并且它已经包含一个与上一个相似的 Partipant,那么我们创建另一个团队。

也许是这样的:

    public ArrayList<ArrayList<Participant>> divideParticipantsIntoTeams(ArrayList<Participant> participants)
    {
        ArrayList<ArrayList<Participant>> groups = new ArrayList<>(); // This keeps our groups

        groups.add(new ArrayList<>()); // We create our first group.

        // We iterate over all given participants
        participants.forEach(participant ->
        {
            boolean contains = true; // Variable that shows us if we already have it in a group

            // We iterate over all the groups and check if it is contained in them
            for(ArrayList<Participant> group: groups)
            {
                 // Checks if a participant is found with a similar surname
                 contains = containsParticipant(group, participant);

                 // If it doesn't contain such a participant then we add it to the group and we go out of the loop.
                 if(!contains)
                 {
                     group.add(participant);
                     break;
                 }
            }

            // If we iterate all the groups and when finished they all contain some similar Participant, create a new one.
            if(contains)
            {
                groups.add(new ArrayList<>());

                ArrayList<Participant> newGroup = groups.get(groups.size() - 1); // Getting the just created group
                newGroup.add(participant); // Adding the participant to it
            }

        });

        return groups;
    }

    public boolean containsParticipant(ArrayList<Participant> group, Participant participant)
    {
        for(Participant groupParticipant: group)
        {
            // this could use some fine tuning, depends on how you want it.
            if(groupParticipant.getLastName().contains(participant.getLastName()))
            {
                return true;
            }
        }
        return false;
    }