Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/305.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 生成小于n的k个不同数字_Java_Algorithm - Fatal编程技术网

Java 生成小于n的k个不同数字

Java 生成小于n的k个不同数字,java,algorithm,Java,Algorithm,任务是:生成小于n的k个不同正数而不重复 我的方法如下 首先创建数组大小k,我们应该在其中写入以下数字: int a[] = new int[k]; //Now I am going to create another array where I check if (at given number //position is 1 then generate number again, else put this number in an //array and continue cycle.

任务是:生成小于n的k个不同正数而不重复

我的方法如下

首先创建数组大小k,我们应该在其中写入以下数字:

int a[] = new int[k];

//Now I am going to create another array where I check if (at given number
//position is 1 then generate number again, else put this number in an
//array and continue cycle.
我在这里放了一段代码和解释

int a[]=new int[k];
int t[]=new int[n+1];
Random r=new Random();
for (int i==0;i<t.length;i++){
    t[i]=0;//initialize it to zero
}

int m=0;//initialize it also
for (int i=0;i<a.length;i++){
    m=r.nextInt(n);//random element between  0 and  n
    if (t[m]==1){
        //I have problems with this. I want in case of duplication element
        //occurs repeat this steps afain until there will be different number.
    else{
        t[m]=1;
        x[i]=m;
    }
}
inta[]=新的int[k];
int t[]=新的int[n+1];
随机r=新随机();

对于(inti==0;i来说,您似乎需要一个随机抽样算法。您希望能够从集合{0,1,2,3…,n-1}中选择m个随机项

看,我在那里写了5个有效的随机抽样算法

以下是Floyd的实现,在您的案例中很有用:

private static Random rnd = new Random();
...
public static Set<Integer> randomSample(int n, int m){
    HashSet<Integer> res = new HashSet<Integer>(m);
    for(int i = n - m; i < n; i++){
        int item = rnd.nextInt(i + 1);
        if (res.contains(item))
            res.add(i);
        else
            res.add(item); 
    }
    return res;
} 
private static Random rnd=new Random();
...
公共静态集随机样本(int n,int m){
HashSet res=新的HashSet(m);
对于(int i=n-m;i
大写多少?另外,你需要把你的代码片段放在
code
块中。根据同一个人之前提出的问题:这是家庭作业吗?天哪,你的评论绝对正确:)我很惊讶根据你对问题的陈述,你可以简单地使用
0
k-1
的数字,顺序。这个解是O(k*n),而它本可以是O(k)。通过使用项交换替换“delete”步骤,可以将其改进为O(n),但这仍然不是最优的.pseudo代码,尽管我正在考虑一个PHP解决方案。我没有注意到OP在谈论Java,但是对于一个严格的PHP解决方案,我已经洗牌了arr,然后切掉了第一个k个entries,您可能希望从链接的post@Will:谢谢,实际上我博客文章中的最后一个算法就是这个。然而,我不知道它的共同名称。我会修好的。
Create an array arr with n elements (1..n);
for i=1 to k {
  result[i] = arr[rand]
  delete arr[result[1]]
}
private static Random rnd = new Random();
...
public static Set<Integer> randomSample(int n, int m){
    HashSet<Integer> res = new HashSet<Integer>(m);
    for(int i = n - m; i < n; i++){
        int item = rnd.nextInt(i + 1);
        if (res.contains(item))
            res.add(i);
        else
            res.add(item); 
    }
    return res;
}