Как создать случайные числа определенное c количество раз? - PullRequest
0 голосов
/ 30 мая 2020

Как я могу создать случайное число с определенными c числами времени?

public class Feld  {
    public static void main(String[] args) {
        double k = (int)(Math.random()*1000001);
        int n = 1000000;
        int arr[] = new int[n];
        int i = 0;
        for(i = 0;i<n;i++){
            arr[i] = i;
        }
        boolean found = false;
        i=0;
        while (i < arr.length) {
            if (arr[i] == k) {
                found = true;
                break;
            }
            i++;
        }
        if (found) {
            i++;
            System.out.println(i);
        } 
        else {
            System.out.println((arr.length + 1));
        }
    }
}

Моя проблема в том, что если я помещу k в al oop, чтобы создать его более одного раза, я я получу сообщение об ошибке:

if (arr[i] == k)

!! Я только что узнал, что сделал ошибку, объясняя свою проблему. Массив должен быть заполнен значениями от 0 до 1.000.000, и я должен распечатать позицию случайного сгенерированного числа для указанного c количества раз.

Ответы [ 2 ]

2 голосов
/ 30 мая 2020

Если вы хотите иметь массив, полный случайных чисел, я предлагаю использовать следующее:

int n = 1000000;
int arr[] = new int[n];
for(int i = 0; i < n; i++){
    arr[i] = (int)(Math.random() * 1000001);
}

Это будет работать, и вам даже не понадобится переменная k.


Изменить:

Если вы хотите распечатать, в какой позиции вы найдете заданное значение c (например, x = 543), вы можете использовать следующий код:

int x = 543;
int n = 1000000;
int arr[] = new int[n];
for(int i = 0; i < n; i++){
    arr[i] = (int)(Math.random() * 1000001);
    if(arr[i] == x) {
        System.out.println(i);
        break;
    }
}

Edit2

Одно из возможных решений вашей новой проблемы выглядит так:

public class Feld  {
    public static void main(String[] args) {
        int n = 1000000;
        int arr[] = new int[n];
        int i = 0;
        for(i = 0; i < n; i++){
            arr[i] = i; //Filling array with values 0-1000000
        }
        int number = 20;    //Print out position of a random generated number a specific amount of times
        int randomNumber = (int)(Math.random()*1000001); //The random number

        for(int j = 0; j < number; j++) { //Find number for a specific amount of times 
            for(int k = 0; k < arr.length; k++) { //Find number in array
                if(arr[k] == randomNumber) { 
                    System.out.println(arr[k]); //Print
                    break; //Number found, don't have to search anymore
                }
            }
        }
    }
}

0 голосов
/ 30 мая 2020

Я бы написал метод, который возвращает массив случайных чисел и принимает аргумент int, определяющий длину массива.

Одно из возможных решений:

public static int[] createRandomArray(int length) {
    // create an array of the given length
    int[] result = new int[length];
    // and use a single for loop that puts random int values into every index
    for (int i = 0; i < result.length; i++) {
        result[i] = ThreadLocalRandom.current().nextInt();
    }
    // then simply return the result
    return result;
}

Попробуйте это следующим образом

public static void main(String[] args) {
    // super primitive time measurement:
    // take the moment in time before calling the method
    Instant start = Instant.now();
    // then call the method
    int[] array = createRandomArray(1000000);
    // and take the moment in time after the method returned
    Instant end = Instant.now();
    // then calculate the duration
    Duration duration = Duration.between(start, end);
    // and print the duration in milliseconds
    System.out.printf("Array creation took %d milliseconds\n", duration.toMillis());
}

Результатом будет следующий вывод в моей системе:

Array creation took 10 milliseconds
...