gpt4 book ai didi

java - 如何从给定的随机生成器创建唯一的随机数

转载 作者:搜寻专家 更新时间:2023-10-31 20:04:49 24 4
gpt4 key购买 nike

Write an efficient algorithm to print the following two outputs

You are given a pre-defined function named getrand100() which returns an integer which is one random number from 1-100. You can call this function as many times as you want but beware that this function is quite resource intensive. You cannot use any other random generator. You canNOT change the definition of getrand100().

int getrand100(){
Random rand = new Random();
return (1+rand.nextInt(100));
}
  • 输出 1:以随机顺序打印数字 1-20。 (不是 20 个随机数)
  • 输出 2:以随机顺序打印数字 1-200。 (不是 200 个随机数)

注意:

  • 我。每个数字都应该只打印一次。
  • 二。数字列表中不应有任何模式。列表应该是完全随机的
    也就是说,所有数字在任何地方出现的概率都是相等的。
  • iii.您可以多次调用 getrand100() 来获取随机数从 1 到 100。
  • iv.您不能使用任何其他随机生成器函数除了 getrand100()。

最佳答案

想法是使用给定的随机生成器来计算所需的随机数。

1)对于随机数1-20,只需将100个数字平分代表1到20。

2)生成1-200,求出1到200的偶数,然后加上(-1或0)得到1到200的所有数。

import java.util.*;
public class Rand20_200{
int number20[]=new int[20]; //numbers in random order
int number200[]=new int[200];

public Rand20_200(){
int n=0;
int ngen[]=new int[20]; //to store which random numbers are generated
while(n<20){
int rnd=1 + (getrand100()-1) / 5;
if (ngen[rnd-1]==0){
ngen[rnd-1]=1;
number20[n++]=rnd;
}
}
System.out.println("Random 20 numbers");
print(number20);

ngen=new int[200]; //to store which random numbers are generated
int numoff[]={-1,0}; //offset to add
n=0;
while(n<200){
int rnd=numoff[(getrand100()-1)/50]+ (getrand100()*2);
if (ngen[rnd-1]==0){
ngen[rnd-1]=1;
number200[n++]=rnd;
}
}
System.out.println("\nRandom 200 numbers");
print(number200);
}

int getrand100(){
Random rand = new Random();
return (1+rand.nextInt(100));
}

void print(int arr[]){
for(int i=0;i<arr.length;i++){
System.out.print(arr[i]+" ");
}
}

public static void main(String args[]){
new Rand20_200();
}

}

关于java - 如何从给定的随机生成器创建唯一的随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10890499/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com