{"id":2941,"date":"2023-12-01T16:00:08","date_gmt":"2023-12-01T16:00:08","guid":{"rendered":"https:\/\/msgprogramator.sk\/?p=2941"},"modified":"2025-10-22T11:21:54","modified_gmt":"2025-10-22T11:21:54","slug":"java-programming-example","status":"publish","type":"post","link":"https:\/\/msgprogramator.sk\/en\/java-programming-example\/","title":{"rendered":"Java programming examples: Create a useful application to generate random matches of doubles teams"},"content":{"rendered":"<p>In this article, I would like to show how real-life problems can be easily solved using the <a href=\"https:\/\/msgprogramator.sk\/java\/\">Java programming language<\/a>.<\/p>\n<h2>Assignment<\/h2>\n<p>Together we are going to write a program that will create unique pairs out of N registered individuals and randomly generate 2 teams of pairs to play against each other. The aim is to create all possible match variations so that each team can play against the remaining teams. <\/p>\n\n<h2>Suggested solution<\/h2>\n<p>If you are solving a more complex problem, it is advisable to break it down into smaller parts and solve them separately. In the case of this task, it could be divided into the following steps: <\/p>\n<ul>\n<li>retrieving the registered persons and storing them in the program memory,<\/li>\n<li>creating variations of pairs without repetition,<\/li>\n<li>creating all possible games for two pairs,<\/li>\n<li>randomly shuffling the generated games,<\/li>\n<li>listing the results.<\/li>\n<\/ul>\n<p>We will now look at each step in more detail.<\/p>\n<h2>Retrieve the registered persons and store them in the program memory<\/h2>\n<p>In this section we read the list of logged in people from the file and store them in the <em>people <\/em> list. A person is represented by the <strong>Person <\/strong> class. <\/p>\n<h2>Create variations of pairs without repetition<\/h2>\n<p>When we have loaded people, we need to create all possible pairs of them, so that the people in them do not repeat, and of course each pair should be unique. In a pair, we don&#8217;t care about the order of who is the first or second member. Such a pair is represented by the class <strong>Pair<\/strong>, and the results are stored in the <em>UniquePairs <\/em> list.   <\/p>\n<h2>Create all possible games for two pairs<\/h2>\n<p>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.<\/p>\n<p>One game will be represented by the <strong>Zapas<\/strong> class and these will be saved in the <em>Zapas<\/em> list for further processing.<\/p>\n<h2>Shuffle generated matches randomly<\/h2>\n<p>As an extension, we&#8217;ll add an element of randomness by randomly shuffling the generated matches.<\/p>\n<h2>List the results<\/h2>\n<p>For this type of console application, it will be sufficient to output the results to the console.<\/p>\n<h2>Design implementation in the Java programming language<\/h2>\n<p>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&#8217;ll explain it step by step:  <\/p>\n<p><u>Person.java<\/u><\/p>\n<pre><code class=\"language-java\" data-line=\"\">package entities;\n\npublic class Osoba {\n    public String meno;\n\n    public Osoba(String meno) {\n        this.meno = meno;\n    }\n}\n<\/code><\/pre>\n<p>It defines a <strong>Person <\/strong> class with a Name attribute representing the person&#8217;s name.<\/p>\n<p><u>Pair.java<\/u><\/p>\n<pre><code class=\"language-java\" data-line=\"\">package entities;\n\npublic class Dvojica {\n    public Osoba osoba1;\n    public Osoba osoba2;\n\n    public Dvojica(Osoba osoba1, Osoba osoba2) {\n        this.osoba1 = osoba1;\n        this.osoba2 = osoba2;\n    }\n}\n<\/code><\/pre>\n<p>It defines the <strong>Pair<\/strong> class, which contains two people (person1 and person2) and represents a pair of people or a two-man team. <\/p>\n<p><u>Match.java<\/u><\/p>\n<pre><code class=\"language-java\" data-line=\"\">package entities;\n\npublic class Zapas {\n    public Dvojica tim1;\n    public Dvojica tim2;\n\n    public Zapas(Dvojica tim1, Dvojica tim2) {\n        this.tim1 = tim1;\n        this.tim2 = tim2;\n    }\n}\n<\/code><\/pre>\n<p>The <strong>Match <\/strong> class represents a match between two pairs or teams (team1 and team2). <\/p>\n<p><u>Generator.java<\/u><\/p>\n<pre><code class=\"language-java\" data-line=\"\">package entities;\n\nimport entities.*;\nimport java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Paths;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class Generator {\n    private List&lt;Osoba&gt; ludia;\n    private List&lt;Dvojica&gt; unikatneDvojice;\n    private List&lt;Zapas&gt; zapasy;\n\n    public void Generator() {\n        ludia = null;\n        unikatneDvojice = null;\n        zapasy = null;\n    }\n\n    public void nacitajVstupneData() throws IOException {\n        ludia = new ArrayList&lt;&gt;();\n        for(String line : Files.readAllLines(Paths.get(&quot;vstupy.txt&quot;))) {\n            ludia.add(new Osoba(line));\n        }\n    }\n\n    \/\/ Vytvori v\u0161etky mo\u017en\u00e9 dvojice z \u013eud\u00ed\n    public void vygenerujUnikatneDvojice() {\n        unikatneDvojice = new ArrayList&lt;&gt;();\n        for (int i = 0; i &lt; ludia.size(); i++) {\n            for (int j = i + 1; j &lt; ludia.size(); j++) {\n                Dvojica dvojica = new Dvojica(ludia.get(i), ludia.get(j));\n                unikatneDvojice.add(dvojica);\n            }\n        }\n    }\n\n    \/\/ Vytvori v\u0161etky mo\u017en\u00e9 z\u00e1pasy s dan\u00fdmi dvojicami\n    public void vygenerujUnikatneZapasy() {\n        zapasy = new ArrayList();\n\n        for (int i = 0; i &lt; unikatneDvojice.size(); i++) {\n            for (int j = i + 1; j &lt; unikatneDvojice.size(); j++) {\n                Dvojica tim1 = unikatneDvojice.get(i);\n                Dvojica tim2 = unikatneDvojice.get(j);\n                if(tim1.osoba1.equals(tim2.osoba1) || tim1.osoba1.equals(tim2.osoba2) || tim1.osoba2.equals(tim2.osoba1) || tim1.osoba2.equals(tim2.osoba2))\n                    continue;\n                zapasy.add(new Zapas(tim1, tim2));\n            }\n        }\n    }\n\n    public List&lt;Osoba&gt; getLudia() {\n        return ludia;\n    }\n\n    public List&lt;Dvojica&gt; getUnikatneDvojice() {\n        return unikatneDvojice;\n    }\n\n    public List&lt;Zapas&gt; getZapasy() {\n        return zapasy;\n    }\n}\n<\/code><\/pre>\n<p>The <strong>Generator<\/strong> 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. <\/p>\n<p>Generator() constructor &#8211; initializes the lists to null.<\/p>\n<p>Method nacitajInputData() &#8211; reads data about people from the file <em>inputs.txt<\/em> and creates objects of <strong>Person <\/strong> type from it, which it stores in the <em>People <\/em> list.<\/p>\n<p>GenerateUniqueDoubles() method &#8211; creates all possible pairs of people and stores them in the <em>uniquePairs<\/em> list.<\/p>\n<p>GenerateUniqueMatches() method &#8211; creates all possible matches between pairs and stores them in the <em>Matches <\/em> list. It ensures that no two individuals are repeated in different pairs.<\/p>\n<p>Access methods getPeople(), getUniquePairs(), getMatches() &#8211; provide access to individual lists.<\/p>\n<p><u>Main.java<\/u><\/p>\n<pre><code class=\"language-java\" data-line=\"\">import java.io.IOException;\nimport java.util.Collections;\nimport java.util.Random;\n\nimport entities.*;\n\npublic class Main {\n    public static void main(String[] args) throws IOException {\n        Generator generator = new Generator();\n        generator.nacitajVstupneData();\n\n        System.out.println(&quot;Prihlaseni ludia [&quot; +  generator.getLudia().size() + &quot;]: &quot;);\n        for (Osoba osoba : generator.getLudia()) {\n            System.out.println(osoba.meno);\n        }\n        System.out.println();\n\n        generator.vygenerujUnikatneDvojice();\n        System.out.println(&quot;Mozne dvojice [&quot; +  generator.getUnikatneDvojice().size() + &quot;]: &quot;);\n        for (Dvojica dvojica : generator.getUnikatneDvojice()) {\n            System.out.println(dvojica.osoba1.meno + &quot; a &quot; + dvojica.osoba2.meno);\n        }\n        System.out.println();\n\n        generator.vygenerujUnikatneZapasy();\n        Collections.shuffle(generator.getZapasy(), new Random());\n        System.out.println(&quot;Zapasy kazdy s kazdym v nahodnom poradi [&quot; +  generator.getZapasy().size() + &quot;]: &quot;);\n        for (Zapas zapas : generator.getZapasy()) {\n            System.out.println(zapas.tim1.osoba1.meno + &quot; a &quot; + zapas.tim1.osoba2.meno + &quot; vs. &quot; +\n                    zapas.tim2.osoba1.meno + &quot; a &quot; + zapas.tim2.osoba2.meno);\n        }\n    }\n}\n<\/code><\/pre>\n<p>Contains the main() method, which demonstrates the functionality of the program. Creates an instance of the <strong>Generator<\/strong> class. It 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.    <\/p>\n<p>The program works for any number of people and can be easily modified and adapted to suit your own needs.<\/p>\n<p><u>Program Input:<\/u><\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone wp-image-2142 size-thumbnail\" src=\"https:\/\/msgprogramator.sk\/wp-content\/uploads\/2023\/12\/vstup-programu-440-490-150x150.webp\" alt=\"It creates an instance of the Generator class. It retrieves input data about people and lists the logged in people. It generates all possible unique pairs and lists them. \" width=\"150\" height=\"150\"><\/p>\n<p><u>Program Output:<\/u><\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"wp-image-2144 size-full\" src=\"https:\/\/msgprogramator.sk\/wp-content\/uploads\/2023\/12\/vystup-programu-420-920.webp\" alt=\"The program works for any number of people and can be easily modified and adapted to suit your own needs.\" width=\"420\" height=\"920\" srcset=\"https:\/\/msgprogramator.sk\/wp-content\/uploads\/2023\/12\/vystup-programu-420-920.webp 420w, https:\/\/msgprogramator.sk\/wp-content\/uploads\/2023\/12\/vystup-programu-420-920-137x300.webp 137w\" sizes=\"auto, (max-width: 420px) 100vw, 420px\" \/><\/p>\n<h2>Exercise 1<\/h2>\n<p>Extend the Osoba class with the gender attribute (male, female).<\/p>\n<p>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.<\/p>\n<p>Save the results to the output file.<\/p>\n<h2>Exercise 2 (challenge)<\/h2>\n<p>When creating a generator instance, specify a number that determines how many members the teams you are creating will have. Then modify the code in the example to work for teams with any number of members. <\/p>\n<h2>Java code example<\/h2>\n<p>We have prepared the files with the above example in the form of code that you can run directly in Java. Please download the <a href=\"https:\/\/msgprogramator.sk\/wp-content\/uploads\/2023\/11\/GerneratorZapasov.zip\">Java code example from here.<\/a> <\/p>\n<p>If you&#8217;re comfortable creating code from scratch and you&#8217;re an experienced <a href=\"https:\/\/msg-life.sk\/en\/jobs\/java-programmer-senior\/\">Java developer<\/a>, check out our <a href=\"https:\/\/msg-life.sk\/en\/benefits\/\">employee benefits<\/a> and respond to our <a href=\"https:\/\/msg-life.sk\/en\/jobs\/\">job offers<\/a>!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>We have a Java programming example task for you to test your Java skills and then you can check. <\/p>\n","protected":false},"author":14,"featured_media":2147,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[57],"tags":[],"class_list":["post-2941","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java"],"acf":[],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/posts\/2941","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/users\/14"}],"replies":[{"embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/comments?post=2941"}],"version-history":[{"count":4,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/posts\/2941\/revisions"}],"predecessor-version":[{"id":9343,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/posts\/2941\/revisions\/9343"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/media\/2147"}],"wp:attachment":[{"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/media?parent=2941"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/categories?post=2941"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/tags?post=2941"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}