微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

android – 在Random()方法中有没有一些模式?

我开始做一个有山羊的项目!是的山羊
目前只有一个功能,当我点击一只山羊,它在随机位置创建另一只山羊.
我意识到有一种职位模式:

这是代码

public class GameActivity extends Activity {

    private int[] arrGoats = new int[5];
    private RelativeLayout battlefield;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_game);

        battlefield = (RelativeLayout) findViewById(R.id.rel_battlefield);

        arrGoats[0] = R.drawable.amarelo;
        arrGoats[1] = R.drawable.azul;
        arrGoats[2] = R.drawable.branco;
        arrGoats[3] = R.drawable.verde;
        arrGoats[4] = R.drawable.vermelho;

        criarCabra(60,100);

    }

    private void criarCabra(float x,float y) {
        int cabraimg = arrGoats[new Random().nextInt(4)];

        ImageView cabra = new ImageView(this);
        cabra.setimageResource(cabraimg);
        cabra.setX(x);
        cabra.setY(y);

        LayoutParams params = (LayoutParams) new LayoutParams(MarginLayoutParams.WRAP_CONTENT,MarginLayoutParams.WRAP_CONTENT);
        params.width = 150;
        params.height = 120;
        cabra.setLayoutParams(params);

        cabra.setonClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                criarCabra(new Random().nextInt(2000),new Random().nextInt(1000));
            }
        });

        battlefield.addView(cabra);
    }
}

我想知道为什么这个模式是创建的,尽管我使用Random().NextInt()来定义山羊的位置.

我疯了吗?

解决方法

首先,您每次都要创建一个新的Random对象.在Android中,initial seed is derived from current time and the identity hash code
public Random() {
     // Note: Using identityHashCode() to be hermetic wrt subclasses.
     setSeed(System.currentTimeMillis() + System.identityHashCode(this));
}

对于按顺序创建的两个对象,身份哈希码彼此靠近.在我的Android KitKat Dalvik VM上,我得到的差异仅为32的身份哈希码.

currentTimeMillis()也不会给种子带来很大的不同.

随机本身就是linear congruential generator的形式

random[i+1] = a * random[i] + b (mod c)

其中random [0]是种子,a,b和c是参数.

基于this answer,类似的种子确实在线性同余发生器中产生类似的结果:

The reason you’re seeing similar initial output from nextDouble given similar seeds is that,because the computation of the next integer only involves a multiplication and addition,the magnitude of the next integer is not much affected by differences in the lower bits.

因此,您的两个连续生成的具有认种子的随机数将产生似乎相关的值,并使您的山羊定位在一条线上.

要修复它,使用与线性一致的相同的Random对象和/或更随机的伪随机生成器.

原文地址:https://www.jb51.cc/android/313577.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐