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对象和/或更随机的伪随机生成器.

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...