Double round robin tournament - java

I am developing a sport torunament in Java based on round robin scheduling algorithm. For n teams I want to generate 2(n-1) rounds with n/2 matches. That is that every team must play a match in a round, and every 2 teams meet twice, once away and once home. I managed to implement the algoritm except for the home/away part. I am able to generate the rounds, but can not "swap" the teams in the second half of rounds so they play both away and home.
Here is what I have so far:
public class sports {
public static void main(String[] args) {
//obtain the number of teams from user input
Scanner input = new Scanner(System.in);
System.out.print("How many teams should the fixture table have?");
int teams = input.nextInt();
// Generate the schedule using round robin algorithm.
int totalRounds = (teams - 1) * 2;
int matchesPerRound = teams / 2;
String[][] rounds = new String[totalRounds][matchesPerRound];
for (int round = 0; round < totalRounds; round++) {
for (int match = 0; match < matchesPerRound; match++) {
int home = (round + match) % (teams - 1);
int away = (teams - 1 - match + round) % (teams - 1);
// Last team stays in the same place
// while the others rotate around it.
if (match == 0) {
away = teams - 1;
}
// Add one so teams are number 1 to teams
// not 0 to teams - 1 upon display.
rounds[round][match] = ("team " + (home + 1)
+ " plays against team " + (away + 1));
}
}
// Display the rounds
for (int i = 0; i < rounds.length; i++) {
System.out.println("Round " + (i + 1));
System.out.println(Arrays.asList(rounds[i]));
System.out.println();
}
}
}
Don't mind even/odd number of teams, for now I am only interested in even teams number.

To codify True Soft's answer,
String roundString;
if (round < halfRoundMark) {
roundString = ("team " + (home + 1)
+ " plays against team " + (away + 1));
} else {
roundString = ("team " + (away + 1)
+ " plays against team " + (home + 1));
}
rounds[round][match] = roundString;
where
int halfRoundMark = (totalRounds / 2);

You have to see when you get to the half of the rounds, and then switch the home and away teams.

Pleas Refer this link which described Round Robin Algorithm for "Odd-Number of teams" as well as "Even-Number of teams".
Ref this link:- https://nrich.maths.org/1443
1) Odd Number of teams :-
For Odd number of teams, Consider following formulas and conditions
Abbreviations :-
TNR = Total Number Of Rounds
NOT = Number Of Teams
MPR = Match Per Round
Formulas :-
Total Number Of Rounds = Number Of Teams
Match Per Round = [ ( Number Of Teams - 1 ) / 2 ]
Conditions :- There must be only one team in round, which gets bye(would not play game). So each round has only one bye and each team will play once in round with other team.
Lets consider this algorithm's implementation in c# (Odd-Number Of Teams)
Suppose we have 5 Teams
Teams :-
Barcilona (0)
Brazil (1)
Madrid (2)
Colambo (3)
Woshington DC (4)
Here ,
Number Of Teams (NOT)= 5
Total Number Of Rounds (TNR) = 5
Matches Per Round (MPR) = [ ( NOT - 1 ) / 2 ] = [ ( 5 - 1 ) /2 ] = 2
Now Conside the link in which each round has one team which gets bye, and other team play once in round with another team.
now put all teams in array named Teams
int[] teams = new int[NOT];
so, int[] teams = new int[5];
now teams = [0,1,2,3,4]
now we will rotate array by 1 step left while moving on next round and teams[0] will always gets By and play games between other team but the problem is that how we can decide which team plays game with which team. so to resolve those issue, refere Reference Link. So you can identify that In round 0, matched will be played with following teams
Teams[0] = 0 = Barcilona Gets Bye(Not played game)
Teams[1] - Teams[4] = (Brazil - Woshington DC)
Teams[2] - Teams[3] = (Madrid - Colambo)
so, consider the following implementation
public class Teams {
public int Team1 { get; set; }
public int Team2 { get; set; }
}
//Dictionary< round , matches >
var matchScheduling = new Dictionary<int, List<Teams>>();
for (int round = 0; round < TNR; round++) {
List<Teams> matches = new List<Teams>();
int team1 = teams[0];
int team2 = -1;
matches.Add(new Teams() { Team1 = team1, Team2 = team2 });
for (int match = 0; match < MPR; match++) {
team1 = teams[match + 1];
team2 = teams[(NOT.Length - 1) - match];
roundTeams.Add(new Teams() { Team1 = team1, Team2 = team2 });
}
matchScheduling.Add(round, roundTeams);
//Now for next round, Rotate team Array
int length = teams.Length;
int tmp = teams[length - 1];
for (int i = length - 1; i > 0; i--) {
teams[i] = teams[i - 1];
}
teams[0] = tmp;
}

Related

Java percentage calculation based on multiple inputs

I'm little bit confused how to calculate percentage based on input values (eg: pick for team)
Scanner input = new Scanner(System.in);
System.out.println("1 for Team one, 2 for Team two, 3 for draw, 9 for quit");
int pick = 0;
int team1 = 0;
int team2 = 0;
int draw = 0;
while (pick != 9) {
pick = input.nextInt();
if (pick == 1) {
team1 += 1;
} else if (pick == 2) {
team2 += 1;
} else if (pick == 3) {
draw += 1;
}
}
System.out.println(team1);
System.out.println(team2);
System.out.println(draw);
int total = team1 + team2 + draw;
System.out.println(total);
This will print individually and total.
l want to print for example if all values are picked 2 times from input:
"Team 1 = 33.3%, Team 2 = 33.3%, draw = 33.3%" and so one for different type of picks. Thanks
You are almost there. Now, all you just need is a counter to count the iterations and finally divide the score of team1, team2 and draw by the value of the counter after multiplying them with 100.0 to get the percentage score.
Demo:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("1 for Team one, 2 for Team two, 3 for draw, 9 for quit");
int pick = 0;
int team1 = 0;
int team2 = 0;
int draw = 0;
int count = -1;
while (pick != 9) {
pick = input.nextInt();
if (pick == 1) {
team1 += 1;
} else if (pick == 2) {
team2 += 1;
} else if (pick == 3) {
draw += 1;
}
count++;
}
System.out.printf("Percentage score of team1: %.1f%n", (team1 * 100.0 / count));
System.out.printf("Percentage score of team2: %.1f%n", (team2 * 100.0 / count));
System.out.printf("Percentage score of draw: %.1f%n", (draw * 100.0 / count));
}
}
A sample run:
1 for Team one, 2 for Team two, 3 for draw, 9 for quit
1
2
3
3
2
1
9
Percentage score of team1: 33.3
Percentage score of team2: 33.3
Percentage score of draw: 33.3
To get the percentage of each price you have to do:
int persentageteam1 = team1*100/(team1+team2+team3);
and the same for the others...
Explanation:
What you do here is divide the price of which you want to find the persentage with the sum of the rest of the other and do this x100
A percentage of a number is calculated basing on the following principle (or at least as it is taught is my school) :
Say, you need to figure out a number percent ratio of another one, let it be firstNumber and secondNumber. Then, firstNumber=100% and secondNumber=x. From that we get the proportion: firstNumber/secondNumber = 100%/x, consequently, x=(secondNumber*100)/firstNumber. That is, in your case, the firstNumber is the pick summary of all teams and the secondNumber - the team which percentage you want to determine. For example
//your code
int pickSummary=team1+team2+team3+draw;
int team1Percentage=team1*100/pickSummary;
System.out.println(team1Percentage);
//and so on

having a problem with java for game simulation

User inputs integer value for gamblers starting bankroll
User inputs integer value for gamblers desired bankroll – if the gambler’s bankroll reaches this value he quits the game
User inputs integer value for the number of trials to perform – each trial will consist of enough games to either reduce the gamblers bankroll to zero or increase it to the desired bankroll
Declare an integer variable (set to zero) to keep track of the number of wins
The solution, obviously, will consist of nested looping structures and selection structures
First (outer loop) will loop to perform the required number of trials
Set cash equal to stake
Second (inner loop) will simulate the results of one card game. This loop will repeat as long as cash is greater than zero and less than the desired bankroll
Assume that the gambler has chance of winning the game of less than 50%
Use a random number generator to determine if the gambler won the game
If the gambler won, add $1.00 to his cash
Otherwise subtract $1.00 from his cash
At the end of the inner loop (one game is run) -
If the value of cash equals the gamblers desired bankroll, then increment wins by one
After the outer loop stops, print to the screen the number of wins out of the number of trials and the percent of games won.
trying to get a game simulator to count the number of games won after the total starting amount reaches the end amount. part of it works but not all of it
then it should do that x number of times. https://github.com/samuelatlas/gamesimulation/tree/master
'''
// demonstrating the Java for loop
import java.util.Scanner; // import a scanner c
import java.security.SecureRandom; // imports a secure random class
class newLoopTest1
{
public static void main(String[] args)
{
// OUTER -------LOOP
Scanner input = new Scanner(System.in);
System.out.print("Enter the start bankroll ");
int startBankRoll = input.nextInt();
//int desiredBankRoll = 5;
System.out.print("Enter the desired bankroll ");
int desiredBankRoll = input.nextInt();
System.out.print("Enter the number of trials ");
int numberTrials = input.nextInt();
//int startBankRoll = 2;
int i = 1;
int current = startBankRoll;
int wins = 0;
//int numberTrials = 0;
//OUTER----LOOP
while(i <= numberTrials)
//while(numberTrials <= 4)
{
i++;
int innerloop = 0;
System.out.println("printing from outer");
//INNER----LOOP
while((startBankRoll < desiredBankRoll) && (startBankRoll > 0))
{
SecureRandom randomNumber = new SecureRandom();
int number = randomNumber.nextInt(101);
System.out.println("Before hand start amount of " +
startBankRoll + " end amount of " + desiredBankRoll);
System.out.println("Rolled " + number);
if( number <= 50)
{
System.out.println("lost");
startBankRoll--;
System.out.println("After hand start amount of " +
startBankRoll + " end amount of " + desiredBankRoll);
}
else
{
System.out.println("won");
startBankRoll++;
System.out.println("After hand start amount of " +
startBankRoll + " end amount of " + desiredBankRoll);
}
System.out.println(" Outerloop ran " + numberTrials + "
Innerloop ran " + innerloop);
innerloop++;
//INNER----LOOP
}
//OUTER----LOOP
numberTrials += 1;
//wins++;
System.out.println("Current" + current);
if(startBankRoll == desiredBankRoll)
{
wins += 1;
startBankRoll = current;
System.out.println("wins" + wins);
}
else
{
startBankRoll = current;
System.out.println(" lost all cash");
}
//OUTER----LOOP
}
int totalWins = (wins/(numberTrials-1));
System.out.println("Won " + wins + " out of " + (numberTrials-1));
//System.out.println("total percent" + wins/totalWins );
}
}
The main problem with your code seems to lie with understanding the problem. I took at look at the Github page you linked (I noticed your assignment is due tomorrow -- please do not wait until the last minute to ask for help in the future, and always ask the teacher first, rather than some stranger on Stack Overflow). Let's break down the assignment properly.
The player starts with cash (in your case, 2 units), so we know how to initialize startCash, which you've done properly
His goal is to get to 10 units or bust, so we know the upper and lower limits that define the parameters for his participation in the game. In other words, he only plays while he has > 0 and < 10 units. An outer loop checking to see if he has enough cash is pointless.
While those conditions are true, he plays a coin flipping game, where 50 or less is a loss of one unit and 51 or more is a win of one unit. Each time he flips, we increment a counter so we know how many coin flips he conducted to get to either 0 or 10.
Notice how I've rephrased the question: While cash > 0 and cash < 10, flip coin. If flip < 50, player loss, else win. Increment counter. That's all there is to it, all in one loop.
You confused yourself by adding an outer loop which you don't need at all -- maybe you put it there to keep flipping while the player has money, but it's redundant because your do...while is checking both the lower and upper limits for whether the game should be played. That outer loop is also running 5 times, but what if it takes more than 5 trials to bust or get 10?
I've simplified the code here by basically rearranging what you already had. Compare what you have to what I have and you'll see that I more or less just stripped away the useless outer loop. Run the code a few times and you'll see that you already had more or less the correct logic before you shot yourself in the foot.
import java.security.SecureRandom;
public class Homework
{
public static void main(String[] args)
{
int startCash = 2;
int endCash = 10;
int currentCash = startCash;
int counter = 0;
while(currentCash > 0 && currentCash < endCash)
{
SecureRandom randomNumber = new SecureRandom();
int number = randomNumber.nextInt(101);
if(number <= 50)
{
// lost
currentCash--;
}
else
{
// won
currentCash++;
}
counter++;
}
System.out.println("Current Cash: " + currentCash);
System.out.println("Trials: " + counter);
}
}
The only "major" change other than removing the extra loop is changing your do...while into a while loop. The difference is that a do...while will always run at least once because the exit condition isn't checked until after the code block runs, which doesn't seem correct because what if startCash is already 0 or 10? The while loop checks the condition before running the code block, so if the player is ineligible to play (too much or too little cash), then he doesn't play.
well i figured it all out just took a while and lots of versions. here is the final code. most of the earlier code was to see where the numbers where going.
{import java.util.Scanner; // import a scanner class.
import java.security.SecureRandom; // imports a secure random class.
class TheGambler
public static void main(String[] args)
{
// OUTER -------LOOP AREA
// create scanner for object.
Scanner input = new Scanner(System.in);
//prompt users for the starting bankroll amount.
System.out.print("Enter the start bankroll ");
int startBankRoll = input.nextInt();
//prompt users for the desired bank roll amount.
System.out.print("Enter the desired bankroll ");
int desiredBankRoll = input.nextInt();
//prompt users for the number of tirals.
System.out.print("Enter the number of trials ");
int aNumber = input.nextInt();
//to reset the value after to inner loop has ran.
int current = startBankRoll;
// keep track of number of wins.
int wins = 0;
// keep track of numberTrials.
int numberTrials = 1;
//OUTER----LOOP AREA
//condition for the outer while loop to continue.
while(numberTrials <= aNumber)
{
// number of time inner loops executes.
int innerloop = 0;
//INNER----LOOP
// condition for the inner while loop to continue.
while((startBankRoll < desiredBankRoll) && (startBankRoll > 0))
{
//create a random number and assign it an integer named number.
SecureRandom randomNumber = new SecureRandom();
int number = randomNumber.nextInt(101);
//condition to determine if player wins or a losses.
if( number <= 50)
{
// if losses subtract one from startamount.
startBankRoll--;
}
else
{
// if wins adds one to startamount.
startBankRoll++;
}
// add one to the inner loop count.
innerloop++;
//INNER----LOOP AREA
}
//OUTER----LOOP AREA
//add to the total number of trials ran
numberTrials += 1;
// condition to add one to wins if startamount is equal to desiredamount.
if(startBankRoll == desiredBankRoll)
{
// adds one to the wins count and resets the startamount.
wins += 1;
startBankRoll = current;
}
else
{
//if startamount equals zero reset the startamount.
startBankRoll = current;
}
//OUTER----LOOP AREA
}
// determine total number of games played.
int total = (numberTrials-1);
// converts the amount of wins to a percent.
int percent = wins * 100 / total;
//displays how many wins out of total amount of games played.
System.out.println("Won " + wins + " out of " + total);
//displayes the percent of games won.
System.out.println(percent + "%");
}
}

Getting pricing for tickets

I am trying to make a simple java program, that calculates how much tickets would cost.
1 adult ticket is 10$, a child cost 5$ but a family ticket (2 adults and 2 children) is 26$. An obvious saving
So when input from the user, it needs to calculate how many family tickets (if applicable) and then pricing of items if they dont fit into a family bundle.
I.e.
Number of adults: 2
Number of children: 4
Number of family tickets: 1
Number of child tickets: 2
Total cost: $36
I cannot figure out the logic behind getting the pairings, comparing and taking out the extra items from both adults and children if needed. Here is what ive gotten so far:
double adultPairs,childPairs;
if (numberAdults <= 1) {
adultPairs = 0;
}
else if (isEven(numberAdults)) {
adultPairs = numberAdults / 2;
adultTickets = 0;
}
else {
adultPairs = numberAdults / 2;
adultTickets = 1;
}
if (numberChildren <= 1) {
childPairs = 0;
}
else if (isEven(numberChildren)) {
childPairs = numberChildren / 2;
childTickets = 0;
}
else {
childPairs = numberChildren / 2;
childTickets = 1;
}
What about this one?
int familyTickets = Math.min(adults/2, childs/2);
int adultTickets = adults - familyTickets*2;
int childTickets = childs - familyTickets*2;
First line compares the half of adults and childs (rounded down) and returns the minimum value of it. For example, if you have 9 adults and 25 children, it takes 9/2 and 25/2 which is 4 and 12, therefore it returns 4. And thats how much family tickets you want.
In next two lines, you just takes all adults/children and substract the adults/children family tickets, which is number of family tickets multiplied by two.
Even without Math.min method, it is quite easy :
int familyTickets = 0;
if (adults > childs){
familyTickets = childs/2;
} else {
familyTickets = adults/2;
}
int adultTickets = adults - familyTickets*2;
int childTickets = childs - familyTickets*2;
PS : Also note, that in Java, if you divide integer with integer, it returns another integer "rounded" down (it is not technically rounded, it just cut off anything less than 1) and it is what we need here. This is reason why I do not use double.

Beginner Java Programming - Rolling 2 Dice Game

I'm trying to create a java program for my class that throws 3 dice. The player rolls the dice and earns a profit in dollars based on the three values obtained. In particular, the profit is equal to the number of even values multiplied by the sum of those values, plus the number of odd values multiplied by the sum of those values.
For example, if the player rolls 4, 5, and 2 we calculate:
2 x 6 (two even values summing to 6)
And
1 x 5 (one odd value summing to 5).
So the profit is 12 + 5 = $17.
Here is what I have so far -
import java.util.Scanner;
public class Maiorca_Hw2
{
public static void main (String [] args)
{
Scanner keyboard = new Scanner (System.in);
System.out.println("Enter Values of Dice 1");
d1 = keyboard.nextDouble();
System.out.println("Enter Values of Dice 2");
d2 = keyboard.nextDouble();
System.out.println("Enter Values of Dice 3");
d3 = keyboard.nextDouble();
double numbers = 1,2,3,4,5,6;
double profit, dice, d1, d2, d3, oddsum, evensum;
if (d1 == 1 || d1 == 3 || d1 == 5)
oddsum =
I personally think that the program should be done in a different way and you should also use clases.
I hope this little code helps you!
First of all we must create a class called Dice, where we will set the behaviour of a dice and the interactions allowed.
You say that the player rolls, so there must be a random event, I think.
//CODE:
import java.util.Random;
public class Dice {
private final int SIDES;
//Constructor for a dice
public Dice(int sides){
//Establishes the number of sides of the dice we're using.
SIDES = sides;
}
//Methods:
public int roll(){
Random rnd = new Random();
return rnd.nextInt(SIDES) + 1;
}
}
After that, in the main class, we put it to the test.
The why of everything is in the comments
//CODE:
public class MainClass {
public static void main(String[] args) {
int moneyEarned = 0;
//We generate 3 dices with 6 sides each.
Dice d1 = new Dice(6);
Dice d2 = new Dice(6);
Dice d3 = new Dice(6);
// Then we start the simulation:
int res1, res2, res3;
res1 = d1.roll();
res2 = d2.roll();
res3 = d3.roll();
//Show results:
System.out.println("Roll results: dice 1 = " + res1 +
"; dice 2 = " + res2 + "; dice 3 = " + res3);
//We obtain the money the player must earn:
//An even number modulo 2 can only be either 1 or 0 so the same number + 1 will
//switch from 0 to 1 and the opposite thing.
//With this number we can choose which numbers we want to sum:
int oddNumbersPoints = ((res1 * (res1%2))+(res2 * (res2 % 2))+( res3 * (res3 % 2)));
int evenNumbersPoints = ((res1 * ((res1 + 1) %2)) + (res2 * ((res2+1) % 2))+( res3 * ((res3+1) % 2)));
moneyEarned = (evenNumbersPoints * 2) + oddNumbersPoints;
//Finally display the final result:
System.out.println("Even Numbers Points: " + evenNumbersPoints);
System.out.println("Odd Numbers Points: " + oddNumbersPoints);
System.out.println("Congratulations, you just earned: " + moneyEarned + "$");
}
}
/////
Finally you can change the main class to change the number of dices, the scores, so on...
(Add '}' and the main class head)
What you can do declaring primitive types, in this case double, is:
double profit = 0, dice = 2, d2 = 3;
To declare an array of doubles:
double[] numbers = {1,2,3,4,5,6};

Dice roll combinations java

I'm having some troubles getting this code to look neat since there are som many IF & OR statement that needs to be evaulated.
Idea: You throw five dices and pick out e.g. three of the same type 1,1,1 and throw dice the other two again and go gather points.
The tricky thing is to compare dice1,dice2,dice3,dice4,dice5 with the set of rules in order to determine how many points the player get. What code would check all the possible combination "if dicex=1 & dicex=1 & dicex=1" give player 1000 points?
int player1points = 0;
int player2points = 0;
Scanner in = new Scanner(System.in);
Random n1 = new Random();
int dice1 = n1.nextInt(6) + 1;
int dice2 = n1.nextInt(6) + 1;
System.out.println("Dice 1 shows " +dice1);
System.out.println("Dice 2 shows " +dice2);
System.out.println("Dice 3 shows " +dice3);
System.out.println("Dice 4 shows " +dice4);
System.out.println("Dice 5 shows " +dice5);
if /* 1+1+1+1+1 = 2000 */ (dice1==1&&dice2==1&&dice3==1&&dice4==1&&dice5==1){
System.out.println("You got 2000 points! Throw again?");
int points2000 = 2000;
player1points = player1points + points2000;
System.out.print("You have ");
System.out.print(player1points);
System.out.print(" points. Do you want to throw again?");
System.out.println("Yes/No?");
s = in.nextLine();
}
else if /* 1+1+1 = 1000 */ (dice1==1&&dice2==1&&dice3==1||dice2==1&&dice3==1&&dice4==1||dice3==1&&dice4==1&&dice5==1|| dice4==1&&dice5==1&&dice1==1||dice5==1&&dice1==1&&dice2==1||dice1==1&&dice2==1&&dice4==1||d ice2==1&&dice3==1&&dice5==1||dice3==1&&dice4==1&&dice1==1||dice4==1&&dice5==1&&dice1==1||dice1==1&&dice3==1&&dice5==1){
System.out.println("You got 1000 points!");
int points1000 = 1000;
player1points = player1points + points1000;
System.out.print("You have ");
System.out.print(player1points);
System.out.print(" points. Do you want to throw again?");
System.out.println("Yes/No?");
s = in.nextLine();
}
Put the results of the rolls into an arrayList, then just count the number of times the same number shows up in that array list? If there are 3 1's, give 1000 points, else if there are 5 1's give 2000 points.
So for your code you'll have the same beginning for the most part. Add in methods to populate the array list, and to iterate though/count the results of the dice rolls and return the most common and the number of times it shows up.
int player1points = 0;
int player2points = 0;
int count = 0;
int mostCommon = 0;
int maxCount = 0;
ArrayList<Integer> diceRolls = new ArrayList<Integer>();
Scanner in = new Scanner(System.in);
Random n1 = new Random();
//rollDice method (parameter would be number of dice to roll)
//checkResults method (count number of times each number 1-6 shows up)
if(maxCount == 3){
player1points += 1000;
//re-roll 2 dice if necessary
else if(maxCount == 5){
player2points += 2000;
//re-roll dice if wanted
That's just one way you could do it. Also it's always good practice to break big blocks of code down into more reader-friendly functions, and it makes debugging easier! If you need anymore help feel free to ask!

Categories

Resources