有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何随机分配一个分散的ArrayList?

我正在尝试做一个应用程序,为比赛制定一个比赛计划

我有一个方法:

public List<Match> creerMatchsTousContreTous(List<Equipe> lEquipe) {
        List<Match> lMatch = new ArrayList<>();
        for (int i = 0; i < lEquipe.size(); i++) {
            for (int j = i + 1; j < lEquipe.size(); j++) {
                Match match = new Match();
                match.setEquA(lEquipe.get(i));
                match.setEquB(lEquipe.get(j));
                lMatch.add(match);
            }
        }
        return lMatch;
    }

这种方法收到了一份团队列表。每个人都必须相互配合。这将返回一个播放列表(匹配)

我现在想随机播放。我需要的是第一场比赛的a队,而不是下一场比赛。还有更多

我使用:

Collections.shuffle(lMatch);

但这是一个剧本列表,一个特马有可能连续上演两个剧本

我怎样才能做到这一点? 谢谢 致意

编辑:

例如:

该方法返回游戏列表:

  1. 第一组:第二组

  2. 第二组:第三组

  3. 第一组:第三组

  4. 第四组:第三组

  5. 第二组:第四组

  6. 第四组:第三组

creerMatchsTousContreTous()在本例中返回一个包含6个值的列表。但这里举个例子,在第一场比赛中,2队在比赛,在第二场比赛中,他也在比赛,这是不可能的


共 (1) 个答案

  1. # 1 楼答案

    下面是一种递归方法。我认为它能以比@Sonedring建议的更快的方式提供解决方案,因为每次随机化后都会应用约束

    如果你的队伍少于4支,那么在角落里也更安全。在这种情况下,你将找不到解决方案,也不需要无休止地循环

    希望这有帮助

    public static void randomize(List<Match> matches) {
        List<Match> randomizedList = new ArrayList<>();
        int numberOfAttempts = 256;
    
        // tmpSubList is a temporary list that contains all matches
        // (excluding unwanted) after n-th iteration (randomization).
        List<Match> tmpSubList = new ArrayList<Match>(matches);
        while (matches.size() > 0) {
    
            // if tmpSubList contains - it means there is no match that can be added.
            // Need to restart randomization algorithm.
            if (tmpSubList.size() == 0) {
                System.out.println("Restarting algorithm.");
    
                if ( numberOfAttempts == 0) {
                    throw new ArithmeticException("Could not find solution.");
                }
                // Need to restart:
                matches.addAll(randomizedList);
                tmpSubList.addAll(randomizedList);
                randomizedList.clear();
            }
    
            int randomIndex = (int) (tmpSubList.size() * Math.random());
    
            Match match = tmpSubList.remove(randomIndex);
            matches.remove(match); // remove also from the main list;
            randomizedList.add(match);
    
            Equipe lastTeam1 = match.getEquA();
            Equipe lastTeam2 = match.getEquB();
    
            tmpSubList.clear();
            matches.stream()
                .filter( x -> !x.getEquA().equals(lastTeam1) && !x.getEquB().equals(lastTeam1) )
                .filter( x -> !x.getEquA().equals(lastTeam2) && !x.getEquB().equals(lastTeam2) )
                .forEach( x -> tmpSubList.add(x));
        }
        matches.addAll(randomizedList);
    }