Java случайным образом массив

Класс Random

Класс java.util.Random представляет собой генератор псевдослучайных чисел.

Класс представлен двумя конструкторами

  • Random() — создаёт генератор чисел, использующий уникальное начальное число
  • Random(long seed) — позволяет указать начальное число вручную

Так как класс создаёт псевдослучайное число, то задав начальное число, вы определяете начальную точку случайной последовательности. И будете получать одинаковые случайные последовательности. Чтобы избежать такого совпадения, обычно используют второй конструктор с использованием текущего времени в качестве инициирующего значения.

  • boolean nextBoolean() — возвращает следующее случайное значение типа boolean
  • void nextBytes(byte[] buf) — заполняет массив случайно созданными значениями
  • double nextDouble() — возвращает следующее случайное значение типа double
  • float nextFloat() — возвращает следующее случайное значение типа float
  • synchronized double nextGaussian() — возвращает следующее случайное значение гауссова случайного числа, т.е. значения, центрированное по 0.0 со стандартным отклонением в 1.0 (кривая нормального распределения)
  • int nextInt(int n) — возвращает следующее случайное значение типа int в диапазоне от 0 до n
  • int nextInt() — возвращает следующее случайное значение типа int
  • long nextLong() — возвращает следующее случайное значение типа long
  • synchronized void setSeeD(long seed) — устанавливает начальное значение

Пример для вывода случайного числа.

 final Random random = new Random(); public void onClick(View v)

Случайные числа часто используются в играх. Допустим, мы хотим вывести случайные числа от 1 до 6 при бросании игрального кубика. Попробуем.

 mInfoTextView.setText(String.valueOf(random.nextInt(6))); 

При проверке вы заметите две нестыковки. Во-первых, иногда выпадает число 0, которого нет на кубике, а во-вторых никогда не выпадает число 6. Когда вы помещаете число в параметр метода, то это означает, что выпадают числа в диапазоне от 0 до указанного числа, которое в этот диапазон не входит. Если вы будете использовать число 7, то шестёрка станет выпадать, но по-прежнему будет выпадать число 0. Поэтому пример следует немного отредактировать.

 mInfoTextView.setText(String.valueOf(random.nextInt(6) + 1)); 

Для генерации 10 чисел типа int используйте код:

 String result = ""; for(int i = 0; i < 10; i++)< result += String.valueOf(myRandom.nextInt()) + "\n"; >mInfoTextView.setText(result); 

Генерация в определённом интервале

Нужны случайные числа от 100 до 200? Пишем код.

 int min = 100; int max = 200; int diff = max - min; Random random = new Random(); int i = random.nextInt(diff + 1); i += min; 

Случайные цвета

Работать с числами не слишком интересно. Давайте поработаем со цветом. В Android некоторые цвета имеют конкретные названия, но по сути они являются числами типа int, например, красный цвет имеет константу Color.RED. Вам не надо знать, какое число соответствует этому цвету, так как проще понять по его названию.

 public void onClick(View view) < Random random = new Random(); // Массив из пяти цветов int colors[] = < Color.BLUE, Color.GREEN, Color.MAGENTA, Color.RED, Color.CYAN >; int pos = random.nextInt(colors.length); // Меняем цвет у кнопки mButton.setBackgroundColor(colors[pos]); > 

Щёлкая по кнопке, вы будете менять её цвет случайным образом.

Читайте также:  Php sql query or die

Лотерея «6 из 49»

Сформируем шесть случайных чисел из 49 и занесём их в списочный массив.

 public void onClick(View v) < ArrayListlotteryList = getRandomNumber(); Log.i("Lottery", "" + lotteryList.get(0) + "," + lotteryList.get(1) + "," + lotteryList.get(2) + "," + lotteryList.get(3) + "," + lotteryList.get(4) + "," + lotteryList.get(5)); > private ArrayList getRandomNumber() < ArrayListnumbersGenerated = new ArrayList<>(); for (int i = 0; i < 6; i++) < Random randNumber = new Random(); int iNumber = randNumber.nextInt(48) + 1; if (!numbersGenerated.contains(iNumber)) < numbersGenerated.add(iNumber); >else < i--; >> return numbersGenerated; > 

SecureRandom

Стандартный класс Random обычно используют для простых задач, не связанных с шифрованием. Для криптографии следует использовать схожий класс java.security.SecureRandom.

 SecureRandom secureRandom = new SecureRandom(); mInfoTextView.setText(String.valueOf(secureRandom.nextInt(6))); 

Не забывайте, что в классе Math есть метод random(), возвращающий случайное число от 0 до 1 (единица в диапазон не входит).

В Java 7 появился новый класс java.util.concurrent.ThreadLocalRandom. В Java 8 появился ещё один класс SplittableRandom.

Источник

Как заполнить массив рандомными числами java

Заполнить массив рандомными числами можно разными способами. Можно использовать цикл или стримы. Рассмотрим вариант со стримами:

int size = 10; // Размерность массива // Верхняя граница рандомных чисел, не включая 100 int upperBound = 100; int[] array = new int[size]; // Создаем массив с заданной размерностью Random random = new Random(); // Создаем объект для генерирования рандомных чисел IntStream.range(0, size) // С помощью стрима проходим по всему массиву // Заносим рандомное число в ячейку массива // Рандомные значения могут быть в диапазоне от 0 до 99 включительно .forEach(index -> array[index] = random.nextInt(upperBound)); // Выводим массив в консоль System.out.print(Arrays.toString(array)); // => [10, 85, 84, 85, 47, 79, 96, 43, 50, 7] 

Источник

How to generate Random Numbers in Java

In this tutorial, we’ll learn how to generate a random number, generate a random array or list, get a random element from an array or list, and shuffle the list elements.

Generate Random Number

Java Random class is having many useful built-in methods for generating random numbers as follows:-

import java.util.Random;  class generateRandom   public static void main( String args[] )   //Creating an object of Random class  Random random = new Random();   //Calling the nextInt() method  System.out.println("A random int: " + random.nextInt());   //Calling the overloaded nextInt() method  System.out.println("A random int from 0 to 49: "+ random.nextInt(50));   //Calling the nextDouble() method  System.out.println("A random double: "+ random.nextDouble());   //Calling the nextFloat() method  System.out.println("A random float: "+ random.nextFloat());   //Calling the nextLong() method  System.out.println("A random long: "+ random.nextLong());  > > 

Generate Random Integer within a specific Range

Let’s create a method that uses Random class to generate a random Integer within the specific range of min and max values inclusive.

public static int generateRandomInt(int min, int max)  return min + new Random().nextInt(max-min+1); > 

The method returns a random integer every time you run it.

System.out.println(generateRandomInt(1, 5)); // Prints random integer "4" // Prints random integer "1" // Prints random integer "5" 

Generate Array of Random Numbers within a specific Range

Let’s create a method that uses Random class and Java Streams to generate an Array of random numbers of a given size and all elements of that Array should be in the given range of min and max values inclusive.

public static int[] generateRandomArray(int size, int min, int max)   return IntStream  .generate(() -> min + new Random().nextInt(max - min + 1))  .limit(size)  .toArray(); > 

Let’s use the above method to generate an Array of 5 random numbers between 0 to 9 inclusive. The method will generate a random array every time you run it.

System.out.println(Arrays.toString(generateRandomArray(5, 0, 9))); // Prints random array "[1, 9, 7, 0, 4]" // Prints random array "[7, 1, 2, 8, 5]" // Prints random array "[5, 7, 5, 2, 3]" 

Generate List of Random Numbers within a specific Range

Let’s create a method using Random class and Java Streams to generate a List of random numbers of a given size and all elements in that List should be in the given range of min and max values inclusive.

public static ListInteger> generateRandomList(int size, int min, int max)   return IntStream  .generate(() -> min + new Random().nextInt(max-min+1))  .limit(size)  .boxed()  .collect(Collectors.toList()); > 

Let’s use the above method to generate a List of 5 random numbers between 0 to 9 inclusive. The method will generate a random list every time you run it.

System.out.println(generateRandomList(5, 0, 9)); // Prints random list "[3, 5, 7, 2, 4]" // Prints random list "[8, 7, 7, 5, 4]" // Prints random list "[5, 9, 8, 7, 5]" 

Get Random Element from an Array

You can get a random element from an Array of elements by generating a random index within the length range of the Array.

Let’s run the below code snippet, which prints the random user from the Array every time:-

String[] users = new String[]  "Adam", "Bill", "Charlie", "David", "Eva", "Fang", "George", "Harry", "Ivy", "Jack" >; Random random = new Random(); System.out.println(users[random.nextInt(users.length)]); // Prints random user "Eva" // Prints random user "Charlie" // Prints random user "Fang" 

Get Random Element from a List

You can get a random element from a List of elements by generating a random index within the size range of the List.

Let’s run the below code snippet, which prints the random user from the list every time:-

ListString> users = List.of("Adam", "Bill", "Charlie", "David", "Eva", "Fang", "George", "Harry", "Ivy", "Jack"); Random random = new Random(); System.out.println(users.get(random.nextInt(users.size()))); // Prints random user "David" // Prints random user "George" // Prints random user "Charlie" 

Shuffle Elements in a List

Java Collections provide a built-in shuffle() method to shuffle the elements of a List.

Let’s shuffle the list of users and return users with the random sequence:-

ListString> userList = List.of("Adam", "Bill", "Charlie", "David", "Eva", "Fang", "George", "Harry", "Ivy", "Jack");  Collections.shuffle(userList); System.out.println(userList); // Prints random list everytime "[Charlie, Bill, Harry, George, Jack, Ivy, Fang, Eva, David, Adam]"  Collections.shuffle(userList); System.out.println(userList); // Prints random list everytime "[Eva, Ivy, Fang, Jack, Harry, Bill, Charlie, George, David, Adam]" 

Let’s return 5 random users from the given list of users:-

Collections.shuffle(userList); ListString> fiveUsers = userList.subList(0, 5); System.out.println(fiveUsers); // Prints "[Eva, Bill, David, George, Fang]" 

See Also

Ashish Lahoti avatar

Ashish Lahoti is a Software Engineer with 12+ years of experience in designing and developing distributed and scalable enterprise applications using modern practices. He is a technology enthusiast and has a passion for coding & blogging.

Источник

Оцените статью