如何随机生成Java中的数组一unqiue号 [英] how to randomly generate a unqiue number from an array in java

查看:217
本文介绍了如何随机生成Java中的数组一unqiue号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要生成数字FRM的数组随机,&安培;每一个数字应该是唯一的为好,我给C $ c.Kindly这块$帮助我,和放大器; PLZ天玑建议为ArrayList中,bcoz我建立了黑莓应用程序,和放大器;黑莓API犯规支持的ArrayList或者集合HashSet的,所以好心建议我用数组只在DIS件code的。

 随机RGen元=新的随机(); //随机数发生器    // ---初始化数组
    的for(int i = 0; I< 20;我++){
        quesNum [我] =我;
    }

// ---每个元素随机交换洗牌

 的for(int i = 0; I< 20;我++){
        INT randomPosition = rgen.nextInt(20);        INT TEMP = quesNum [I]        quesNum [I] = quesNum [randomPosition]        quesNum [randomPosition] =温度;
    }


解决方案

您code几乎是好的,因为它是,但你应该使用修改后的费雪耶茨洗牌来代替:

 的for(int i = 0; I< 20;我++){
    //阵列划分为洗牌的开始
    //和unshuffled结尾。选择一个随机
    // unshuffled之一,并与一个在其交换
    //混洗/ unshuffled边界
    INT randomPosition = I + rgen.nextInt(20 - I)
    INT TEMP = quesNum [I]
    quesNum [I] = quesNum [randomPosition]
    quesNum [randomPosition] =温度;
}

这是不是从你的问题真正清楚你问什么 - 你正在沿着正确的方向想验证?如果这个答案不帮你,请澄清问题(不理想的文本说话的缩写)。

i want to generate numbers frm an array randomly,& every number should be unique as well,i am giving the piece of code.Kindly help me out,& plz dnt suggest for arraylist,bcoz i am building for blackberry app,& blackberry api doesnt support arraylist or collection or hashset,so kindly suggest me with array only in dis piece of code.

 Random rgen = new Random();  // Random number generator

    //--- Initialize the array 
    for (int i=0; i<20; i++) {
        quesNum[i] = i;
    }

//--- Shuffle by exchanging each element randomly

   for (int i=0; i< 20; i++) {
        int randomPosition = rgen.nextInt(20);

        int temp = quesNum[i];

        quesNum[i] = quesNum[randomPosition];

        quesNum[randomPosition] = temp;


    }

解决方案

Your code is nearly okay as it is, but you should use a modified Fisher-Yates shuffle instead:

for (int i=0; i < 20; i++) {
    // Partition the array into "shuffled" at the start
    // and "unshuffled" at the end. Select a random
    // unshuffled one, and swap it with the one at the
    // border of shuffled/unshuffled
    int randomPosition = i + rgen.nextInt(20 - i);
    int temp = quesNum[i];
    quesNum[i] = quesNum[randomPosition];
    quesNum[randomPosition] = temp;
}

It wasn't really clear from your question what you were asking for - validation that you were thinking along the right lines? If this answer doesn't help you, please clarify the question (ideally without text-speak abbreviations).

这篇关于如何随机生成Java中的数组一unqiue号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆