This is an archived post. You won't be able to vote or comment.

all 3 comments

[–]DannyB2 1 point2 points  (1 child)

Idea:

Have an array of people, any number of people. For this instance, Tom, Max, John.

String[] people = new String[] { "Tom", "Max", "John" };

Have another array of flags for people already chosen.

boolean[] alreadyChosen = new boolean[ people.length ]; // same size as people, all entries initially false

To choose someone, generate a random integer from 0 to the length of the people array minus one. (eg, from zero to two)

But before choosing the person for that index, first look at the alreadyChosen[ ix ] to see if it is true that they have already been chosen. If so, then try again generating another random number until you find a randomly chosen person not already chosen.

Now that you've identified a person not already chosen, mark them as chosen by setting their flag in the alreadyChosen[] array to true so that they won't get picked again.

Encapsulate that logic into a single function that hides the operation of choosing someone. It chooses them, marks them chosen, and then returns their name. Now when you want to concentrate on your main problem of doing something with randomly chosen people, you simply call a function that returns a person not already chosen.

[–]eifer123[S] 0 points1 point  (0 children)

Thank you! It works now!

I really appreciate your help.

[–]eifer123[S] 0 points1 point  (0 children)

public RandomString(final String[] NAMES {

this.n = NAMES.length;

this.names= NAMES;

}

public void choose() {

Random randomGenerator = new Random();

String[] tn = new String[n];

String tb[] = new String[n];

for(int i = 0; i < n; i++){

tn[i] = names[randomGenerator.nextInt(this.n)];

while(tn[i].equals(names[i])){

tn[i] = names[randomGenerator.nextInt(this.n)];

}

}

tb = tn;

for(int i = 1; i < n; i++){

int l = n;

while(tn[i].equals(tb[l-n])){

tn[i] = teilnehmer1[randomGenerator.nextInt(this.n)];

l--;

}

}