current position:Home>Random array into an array, requiring that the elements cannot be repeated

Random array into an array, requiring that the elements cannot be repeated

2022-04-29 14:40:48CSDN Q & A

package com.random;

import java.util.Arrays;
import java.util.Random;

/*

  • Generate 5 A random number that doesn't repeat (1-10), If repeated, regenerate .
  • Finally generated 5 Put a random number into the array , Expected in array 5 A random number does not repeat .
  • /

public class RandomTest04 {

public static void main(String[] args) {    Random r = new Random();    int[] array01 = new int[5];    for (int i = 0; i < array01.length; i++) {        array01[i] = -1;    }    int i = 0;    while (i < array01.length) {        int num = r.nextInt(10);        boolean index = true;        for (int j = 0; j < i; j++) {            if (array01[i] == array01[j]) {                index = false;            }        }        if (index) {            array01[i] = num;            i++;        }    }    for (i = 0; i < array01.length; i++) {        System.out.print(array01[i] + " ");    }}

}




Take the answer :

Give me an implementation plan , For reference only :

import java.util.HashSet;import java.util.Random;import java.util.Set;public class App {    public static void main(String[] args) {        Random rand = new Random();        Set<Integer> set = new HashSet<Integer>();        int[] arr = new int[5];        while(set.size()<5){            set.clear();            for(int i=0;i<5;i++){                int num = rand.nextInt(10);                set.add(num);                arr[i] = num;            }        }        for (int i=0;i<arr.length; i++) {            System.out.print(arr[i] + " ");        }    }}

copyright notice
author[CSDN Q & A],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/112/202204222159490205.html

Random recommended