D
D
Drunya20182018-11-04 21:35:36
Java
Drunya2018, 2018-11-04 21:35:36

Java. How to write random with an exception?

Tell me please. I need to assign a random array index to a variable, except for a specific one. How to implement it?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
C
carabia, 2018-11-04
@Drunya2018

If I understand your problem correctly

int[] array = {1, 2, 3};

int badIndex = 1;
int variable;

int i;

Random random = new Random();

do {
    i = random.nextInt(array.length);
}while (i == badIndex);

variable = i;

G
GavriKos, 2018-11-04
@GavriKos

You create an array of valid indices, throw a random from 0 to the size of this array, take this random element of the array - it will be the index.
Pseudocode like this:

int[] validIndexes = {0,1,2,5,6,7,9,10};
int random = random.nextInt(validIndexes.length);
int validIndex = randomIndexes[random];

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question