Java programming examples: create a useful application to generate random matches of doubles teams

In this article, I set out to show how real-life problems can be solved easily in the Java programming language.

Assignment

Together, we will create a program that, out of N registered individuals, forms unique pairs and randomly generates 2 teams of pairs to play against each other. The goal is to create all possible variations of matches so that every team can play against the remaining teams.

Proposal for a solution

If you are solving a more complex assignment, it is recommended to break it down into smaller parts and solve them separately. In this assignment, it could be broken down into the following steps:

  • retrieving the logged people and saving them in the program memory,
  • creating variations of pairs without repetition,
  • creating all possible games of two pairs,
  • random shuffling of generated matches,
  • listing of results.

We will now look at each step in more detail.

Loading logged people and storing them in the program’s memory

In this section, we read the list of logged in people’s names from the file and store them in the people list. One person will be represented by the Osoba class.

Creating variations of pairs without repeating

When we have loaded people we need to create all possible pairs of them, so that the persons in them do not repeat and of course each pair should be unique. In a pair, we don’t care about the order of who is first, or second member. Such a two-person team will be represented by the class Pair and the results will be stored in the UniquelyPairs list.

Creating all possible games of two pairs

From the two-person teams formed, we will create all possible games for each team to play with each other. However, we must ensure that each pair plays in only one match on one team, meaning a pair cannot play against itself in a match, and at the same time, no player can play simultaneously in two teams.

One game will be represented by the Zapas class and these will be saved in the Zapas list for further processing.

Random shuffling of generated matches

As an enhancement, we’ll add an element of randomness by randomly shuffling the generated matches.

Listing of results

For this type of console application, it will be sufficient to output the results to the console.

Design implementation in Java programming language

Once we have identified the key steps of the program, we have no choice but to program the program. We will create a tournament system for matches between groups of teams (pairs of people). To give you a better idea of what the program does, I’ll explain it step by step:

Osoba.java

package entities;

public class Osoba {
    public String meno;

    public Osoba(String meno) {
        this.meno = meno;
    }
}

Defines a Osoba class with one name attribute that represents the name of the person.

Dvojica.java

package entities;

public class Dvojica {
    public Osoba osoba1;
    public Osoba osoba2;

    public Dvojica(Osoba osoba1, Osoba osoba2) {
        this.osoba1 = osoba1;
        this.osoba2 = osoba2;
    }
}

Defines the class Dvojica, which contains two persons (osoba1 and osoba2) and represents a pair of people, or a two-man team.

Zapas.java

package entities;

public class Zapas {
    public Dvojica tim1;
    public Dvojica tim2;

    public Zapas(Dvojica tim1, Dvojica tim2) {
        this.tim1 = tim1;
        this.tim2 = tim2;
    }
}

The Zapas class represents one match between two pairs, or teams (tim1 and tim2).

Generator.java

package entities;

import entities.*;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

public class Generator {
    private List<Osoba> ludia;
    private List<Dvojica> unikatneDvojice;
    private List<Zapas> zapasy;

    public void Generator() {
        ludia = null;
        unikatneDvojice = null;
        zapasy = null;
    }

    public void nacitajVstupneData() throws IOException {
        ludia = new ArrayList<>();
        for(String line : Files.readAllLines(Paths.get("vstupy.txt"))) {
            ludia.add(new Osoba(line));
        }
    }

    // Vytvori všetky možné dvojice z ľudí
    public void vygenerujUnikatneDvojice() {
        unikatneDvojice = new ArrayList<>();
        for (int i = 0; i < ludia.size(); i++) {
            for (int j = i + 1; j < ludia.size(); j++) {
                Dvojica dvojica = new Dvojica(ludia.get(i), ludia.get(j));
                unikatneDvojice.add(dvojica);
            }
        }
    }

    // Vytvori všetky možné zápasy s danými dvojicami
    public void vygenerujUnikatneZapasy() {
        zapasy = new ArrayList();

        for (int i = 0; i < unikatneDvojice.size(); i++) {
            for (int j = i + 1; j < unikatneDvojice.size(); j++) {
                Dvojica tim1 = unikatneDvojice.get(i);
                Dvojica tim2 = unikatneDvojice.get(j);
                if(tim1.osoba1.equals(tim2.osoba1) || tim1.osoba1.equals(tim2.osoba2) || tim1.osoba2.equals(tim2.osoba1) || tim1.osoba2.equals(tim2.osoba2))
                    continue;
                zapasy.add(new Zapas(tim1, tim2));
            }
        }
    }

    public List<Osoba> getLudia() {
        return ludia;
    }

    public List<Dvojica> getUnikatneDvojice() {
        return unikatneDvojice;
    }

    public List<Zapas> getZapasy() {
        return zapasy;
    }
}

The Generator class is responsible for loading, processing the data and generating the results. It uses three lists (ludia, unikatneDvojice a zapasy) to manage data about people, teams and matches.

Generator() constructor – initializes lists to null.

Method nacitajInputData() – reads data about people from the file inputs.txt and creates from them objects of the Osoba type, which it stores in the list of ludia.

GenerateUniqueDoubles() method – creates all possible pairs from people and stores them in the unikatneDvojice list.

GenerateUniqueMatches() method – creates all possible matches between pairs and stores them in the list of zapasy. Ensures that no two individuals are repeated in different pairs.

Access methods getLudia(), getUnikatneDvojice(), getZapasy() – provide access to individual lists.

Main.java

import java.io.IOException;
import java.util.Collections;
import java.util.Random;

import entities.*;

public class Main {
    public static void main(String[] args) throws IOException {
        Generator generator = new Generator();
        generator.nacitajVstupneData();

        System.out.println("Prihlaseni ludia [" +  generator.getLudia().size() + "]: ");
        for (Osoba osoba : generator.getLudia()) {
            System.out.println(osoba.meno);
        }
        System.out.println();

        generator.vygenerujUnikatneDvojice();
        System.out.println("Mozne dvojice [" +  generator.getUnikatneDvojice().size() + "]: ");
        for (Dvojica dvojica : generator.getUnikatneDvojice()) {
            System.out.println(dvojica.osoba1.meno + " a " + dvojica.osoba2.meno);
        }
        System.out.println();

        generator.vygenerujUnikatneZapasy();
        Collections.shuffle(generator.getZapasy(), new Random());
        System.out.println("Zapasy kazdy s kazdym v nahodnom poradi [" +  generator.getZapasy().size() + "]: ");
        for (Zapas zapas : generator.getZapasy()) {
            System.out.println(zapas.tim1.osoba1.meno + " a " + zapas.tim1.osoba2.meno + " vs. " +
                    zapas.tim2.osoba1.meno + " a " + zapas.tim2.osoba2.meno);
        }
    }
}

Contains the main() method, which demonstrates the functionality of the program. Creates an instance of the Generator class. Retrieves the input data about people and lists the people logged in. Generates all possible unique pairs and lists them. It generates all possible matches, then randomly sorts them and prints them to the console.

The program works for any number of people and can be easily modified and adapted to fit your own requirements.

Program Input:

Creates an instance of the Generator class. Retrieves input data about people and lists the logged in people. Generates all possible unique pairs and lists them.

Program Output:

The program works for any number of people and can be easily modified and adapted to fit your own requirements.

Exercise 1

Extend the Osoba class with the gender attribute (male, female).

Modify the method vygenerujUnikatneDvojice() to generate all possible pairs of people so that each team consists of one man and one woman. Then generate possible matches.

Save the results to the output file.

Exercise 2 (challenge)

When creating an instance of the generator, specify a number that will determine how many teams will need to be created. Then modify the code from the example to work for arbitrarily large teams.

Java code example

We have prepared the files with the above example in the form of code that you can run directly in Java. Please download the Java code example from here.

If creating code from an assignment isn’t a problem for you and you’re an experienced Java developer, check out our employee benefits and respond to job offers.

About the author

Jozef Wagner

Java Developer Senior

Viac ako 10 rokov programujem v Jave, momentálne pracujem v msg life Slovakia ako Java programátor senior a pomáham zákazníkom implementovať ich požiadavky do poistného softvéru Life Factory. Vo voľnom čase si rád oddýchnem v lese, prípadne si zahrám nejakú dobrú počítačovú hru.

Let us know about you