lundi 30 novembre 2015

Generate unique random number- Logic error

I have the below logic to generate unique random numbers and further, load images referenced by these unique random numbers (from the images Array) at 9 positions:

1) Initially for position 0, generate a random number and load the image referenced by this random number in position 0. 2) Simultaneously load a new Array list with random number already loaded in the previous step. 3) Again for positions 1 to 8, 3.1) generate random number each time. 3.2) compare the random number with the already loaded Array list 3.3) if the newly generated random number already exists in the loaded Array list, Generate another random number; else populate the image corresponding to the unique random number in that position.

Here's the code:

But somehow I am missing out the logic somewhere and get same random numbers repeatedly. Please guide me on the same. Thanks.

    ImageView[] baseimages = {(ImageView) findViewById(R.id.image1), (ImageView) findViewById(R.id.image2), (ImageView) findViewById(R.id.image3), (ImageView) findViewById(R.id.image4), (ImageView) findViewById(R.id.image5), (ImageView) findViewById(R.id.image6), (ImageView) findViewById(R.id.image7), (ImageView) findViewById(R.id.image8), (ImageView) findViewById(R.id.image9)};
    ArrayList<String> Loadimgs = new ArrayList<String>();

    for (i = 0; i < 9; i++) {
        if (first = true)  //initially true
      {
       String alpha[] = {"r1", "r2", "r3", "g1", "g2", "g3", "b1", "b2", "b3", "p1", "p2", "p3", "b1", "br2", "br3"};

 int ran1 = new Random().nextInt(alpha.length);

            baseimages[i].setImageResource(getResources().getIdentifier(alpha[ran1], "drawable", getPackageName()));
            first = false;
            Loadimgs.add(i,alpha[ran1]);

        } else {
            String alpha[] = {"r1", "r2", "r3", "g1", "g2", "g3", "b1", "b2", "b3", "p1", "p2", "p3", "b1", "br2", "br3"};
            int ran1 = new Random().nextInt(alpha.length);
            genimg = alpha[ran1];

            for (j = 0; j < Loadimgs.size(); j++) {
                if (genimg == Loadimgs.get(j)) {
                    j = Loadimgs.size();
                    i--;
                    second = "No";
                } else {
                    continue;
                }
            }
            if (second == "yes")    //initially 'yes'
              {
         baseimages[i].setImageResource(getResources().getIdentifier(genimg,    "drawable", getPackageName()));
         Loadimgs.add(i,genimg);
              }
        }
    }  




Aucun commentaire:

Enregistrer un commentaire