I am creating a tournament generator where there are 8 teams that the user inputs. I need to do a quarter-final where there are 4 matches between random teams. This is my code so far:
import java.util.Scanner;
public class A4Q1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("-----------------------------------------------------");
System.out.println(" Welcome to Tournament Outcome Predictor Program");
System.out.println("-----------------------------------------------------");
Scanner sc = new Scanner(System.in);
System.out.print("\nPlease enter a name for the football tournament: ");
String tName = sc.nextLine(); //name of tournament
int nbTeams = 8;
String[] footballTeams = new String [nbTeams];
System.out.println("\nPlease enter 8 participating teams: ");
for (int i = 0; i<nbTeams; i++) {
footballTeams[i] = sc.nextLine(); //storing 8 teams in array
}
My problem is that I do not know how to generate 8 random unique numbers. I was thinking of storing these number 0 to 7 in a new array but I am out of ideas!
-
You can use Math.random() to generate a random number between 0 and 1 if that is what you are looking for.To make it unique, compare the generated random number with the elements that are already in the array before storing that value in the array.Supun Amarasinghe– Supun Amarasinghe2017年11月07日 03:44:41 +00:00Commented Nov 7, 2017 at 3:44
-
I want to make 4 matches where you can have Team 2 facing Team 5 and so onMohanad– Mohanad2017年11月07日 03:50:14 +00:00Commented Nov 7, 2017 at 3:50
2 Answers 2
Here is a very simple method that generates a random arrays of Integer containing each element between 0 and length (exclusive).
import java.util.*;
Integer[] randomArray(int length) {
Random random = new Random();
List<Integer> list = new LinkedList<>();
for (int k = 0; k < length; k++)
list.add(k);
Collections.shuffle(list);
return list.toArray(new Integer[] {});
}
Calling it leads to a different output each time:
System.out.println(Arrays.toString(randomArray(8)));
For example, it could print: [2, 4, 0, 5, 3, 6, 1, 7].
The idea is very simple, we generate an list containing all elements that interest you, and then, use the built-in Collections.shuffle from the standard library.
Comments
Use Math.random function like this;
(int)(Math.random() * ((upperbound - lowerbound) + 1) + lowerbound);
where lowerbound is inclusive and upperbound exclusive.
to generate random values.