如何创建特定次数的随机数?

huangapple go评论79阅读模式
英文:

How to create random numbers a specific number of times?

问题

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;
        }
        int numberOfTimes = 5; // Change this to the desired number of times
        for (int j = 0; j < numberOfTimes; j++) {
            double k = (int)(Math.random() * (n + 1)); // Generate a random number between 0 and n (inclusive)
            boolean found = false;
            i = 0;
            while (i < arr.length) {
                if (arr[i] == k) {
                    found = true;
                    break;
                }
                i++;
            }
            if (found) {
                i++;
                System.out.println("Position of " + k + ": " + i);
            } 
            else {
                System.out.println("Position of " + k + ": " + (arr.length + 1));
            }
        }
    }
}

(Note: The code above is the translated and modified version of your original code snippet. It generates a random number between 0 and 1,000,000, and then finds its position in the array containing values from 0 to 1,000,000. The process is repeated a specific number of times, and the position of the random number is printed each time.)

英文:

How can i create a random number a specific numbers of time?

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&lt;n;i++){
            arr[i] = i;
        }
        boolean found = false;
        i=0;
        while (i &lt; arr.length) {
            if (arr[i] == k) {
                found = true;
                break;
            }
			i++;
        }
        if (found) {
			i++;
            System.out.println(i);
        } 
		else {
            System.out.println((arr.length + 1));
        }
    }
}

My problem is, that if i put k into a loop to create it more than one time i'll get an error at:

if (arr[i] == k)

!!I just found out that i made a mistake explaining my problem. The array should be filled with values from 0-1.000.000 and i am supposed to print out the position of a random generated number for a specific amount of times.

答案1

得分: 2

以下是翻译好的部分:

如果你想要一个装满随机数字的数组,我建议使用以下代码:

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

这将有效,并且你甚至不需要变量 k

编辑:

如果你想要打印出你找到特定值(例如 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;
    }
}

编辑2:

解决你新问题的一个可能的解决方案如下:

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; // 用值 0-1000000 填充数组
        }
        int number = 20; // 打印出特定次数的随机生成数的位置
        int randomNumber = (int)(Math.random()*1000001); // 随机数
        
        for(int j = 0; j < number; j++) { // 特定次数内寻找数
            for(int k = 0; k < arr.length; k++) { // 在数组中寻找数
                if(arr[k] == randomNumber) { 
                    System.out.println(arr[k]); // 打印
                    break; // 数字找到,无需继续搜索
                }
            }
        }
    }
}
英文:

If you want to have an array full of random numbers, I suggest using the following:

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

That will work and you don't even need the variable k.


Edit:

If you want to print at what position you find a specific value (for example x = 543), you can use the following code:

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

Edit2

One possible solution to your new problem looks like this:

public class Feld  {
    public static void main(String[] args) {
        int n = 1000000;
        int arr[] = new int[n];
        int i = 0;
        for(i = 0; i &lt; 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 &lt; number; j++) { //Find number for a specific amount of times 
        	for(int k = 0; k &lt; arr.length; k++) { //Find number in array
        		if(arr[k] == randomNumber) { 
        			System.out.println(arr[k]); //Print
        			break; //Number found, don&#39;t have to search anymore
        		}
        	}
        }
    }
}

答案2

得分: 0

我会编写一个方法,该方法返回一个随机数数组,并接受一个 int 参数来定义数组的长度。

一个可能的解决方案是这样的:

public static int[] createRandomArray(int length) {
	// 创建一个给定长度的数组
	int[] result = new int[length];
	// 使用一个for循环,将随机int值放入每个索引
	for (int i = 0; i < result.length; i++) {
		result[i] = ThreadLocalRandom.current().nextInt();
	}
	// 然后简单地返回结果
	return result;
}

尝试如下使用:

public static void main(String[] args) {
	// 超级原始的时间测量:
	// 在调用方法之前记录时间点
	Instant start = Instant.now();
	// 然后调用方法
	int[] array = createRandomArray(1000000);
	// 在方法返回后记录时间点
	Instant end = Instant.now();
	// 然后计算持续时间
	Duration duration = Duration.between(start, end);
	// 并以毫秒为单位打印持续时间
	System.out.printf("数组创建花费了 %d 毫秒\n", duration.toMillis());
}

在我的系统上,结果是以下输出:

数组创建花费了 10 毫秒
英文:

I would write a method that returns an array of random numbers and takes an int argument that defines the length of the array.

One possible solution is this:

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 &lt; result.length; i++) {
		result[i] = ThreadLocalRandom.current().nextInt();
	}
	// then simply return the result
	return result;
}

Try it as follows

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(&quot;Array creation took %d milliseconds\n&quot;, duration.toMillis());
}

The result is the following output on my system:

Array creation took 10 milliseconds

huangapple
  • 本文由 发表于 2020年5月30日 15:29:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/62099226.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定