D
D
Dima2019-05-13 15:33:43
Java
Dima, 2019-05-13 15:33:43

How to organize Random without repetition in Java?

There are numbers from 0 to 23. How to make it so that when you click on the button, a random number is generated that has not been encountered at least 2 more times?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
A
Arsen Siyukhov, 2019-05-13
@kleveriwe

Mb to make an array with the numbers that fell out, then shuffle array?

W
Warlodya, 2019-05-13
@Warlodya

spoiler
import java.lang.Math;
import java.util.*;
public class SuperRandom
{
  
  private ArrayList<Integer> numbers;
  private Random rand;
  
  	public static void main(String[] args)
  	{
      		SuperRandom sr=new SuperRandom(10);
      		for(int i=0;i<10;i++)
    		System.out.print(sr.getValue());
  	}
  
  	public SuperRandom(int size){
    rand=new Random();
    numbers=new ArrayList<>();
    		for(int i=0;i<size;i++)
    		numbers.add(i);
 	 }
  
  	public int getValue(){
     		int randomIndex=rand.nextInt(numbers.size());
     		return numbers.remove(randomIndex);
 	}
  
  	public int getSize(){
  		return numbers.size();
 	}
  
}

An alternative solution, just think for yourself how you best handle the end of the values.

A
Andrey Tsvetkov, 2019-05-14
@yellow79

Create an array of 46 elements, fill with numbers, mix, then bite out of it one value at a time, as soon as the length becomes zero, refill the array well, or whatever it should be logically after the
upd. If Java is so godless about memory, then instead of biting out, you can have a separate incremental counter

D
duhbox, 2019-05-14
@duhbox

Remember the last 2 generated numbers.
When you press the button, start the generation cycle until the variant differs from both stored ones. Well, shift the saved pair by 1 for each new number found.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question