【问题标题】:Please help me to random it without repeat element.请帮我在没有重复元素的情况下随机选择它。
【发布时间】:2014-03-22 11:01:15
【问题描述】:

下面的代码是通过重复相同的元素运行的, 我想要的是随机而不重复。

public class khmerAlphabetExercise extends Activity {

    AlphabetData data;
    MediaPlayer mp;
    int dataType;
    int dataKey;    
    Random random;
    private ImageView iv1, iv2, iv3,iv4;
    private ImageView[] imgs = { iv1, iv3, iv3,iv4 };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_khmer_exercise);       

        int[] imageViews={R.id.ex_con1,R.id.ex_con2,R.id.ex_con3,R.id.ex_con4};
        //int images[]={R.drawable.con_ex_01,R.drawable.con_ex_02,R.drawable.con_ex_03,R.drawable.con_ex_04,R.drawable.con_ex_05,R.drawable.con_ex_06,R.drawable.con_ex_07,R.drawable.con_ex_08,R.drawable.con_ex_09,R.drawable.con_ex_10};
        int[] images={data.getImageId()};
        random = new Random(System.currentTimeMillis());

        for(int v : imageViews)     
        {
            ImageView iv = (ImageView)findViewById(v);
            iv.setImageResource(images[random.nextInt(images.length)]);                
        }   
    }
}

【问题讨论】:

    标签: java html random


    【解决方案1】:

    您可以保留一个可供选择的图像计数器。每次选择一个时,您都会在原始数组中将其与最后一个未选中的交换。

    因此,例如,您有一个数组 {0,1,2,3,4}。未选中的长度为 5,我们称之为 l

    1. 在 0 到 l-1 之间选择一个随机数 n
    2. 您的新元素是 n 处的元素。
    3. n 处的元素与 l-1 处的元素交换,l 减去 1 并返回点 1 如果 l 大于 0。转到第 4 点如果 l == 0
    4. 你完成了

    【讨论】:

    • 感谢您的宝贵帮助。
    【解决方案2】:

    你可以使用 Collections.shuffle

    Collections.shuffle(Arrays.asList(images));
    

    然后您可以使用简单的 for 循环一张一张地添加这些图像,而无需随机化位置。顺便说一句,您的示例图像中只包含一个元素..

    【讨论】:

    • 感谢您的宝贵帮助
    猜你喜欢
    • 2021-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-05
    • 2014-06-01
    • 1970-01-01
    • 2012-01-23
    • 1970-01-01
    相关资源
    最近更新 更多