如何将数组值随机放入另一个数组?

时间:2016-05-11 21:37:11

标签: java android arrays

我有长度为6的图像数组(我们先调用数组)。我想将这6个值保存在另一个长度为12的数组中,这样第一个数组的每个值在第二个数组中重复两次并将值放在第二个数组的随机位置。

例如:first array = {3,4,20,33,1,25}

第二个数组可以= {4,20,33,1,20,25,25,3,4,1,3,33}

public class PlayActivity extends AppCompatActivity {

public static boolean isTheSameOk = true;
final Random rnd = new Random();
int saverandom;
int dontsame = 0 ;
int [] allimages = {R.drawable.img1, R.drawable.img2, R.drawable.img3, R.drawable.img4, R.drawable.img5,
        R.drawable.img6, R.drawable.img7, R.drawable.img8, R.drawable.img9, R.drawable.img10, R.drawable.img11,
        R.drawable.img12, R.drawable.img13, R.drawable.img14, R.drawable.img15, R.drawable.img16, R.drawable.img17,
        R.drawable.img18, R.drawable.img19, R.drawable.img20, R.drawable.img21, R.drawable.img22, R.drawable.img23,
        R.drawable.img24, R.drawable.img25, R.drawable.img26, R.drawable.img27, R.drawable.img28, R.drawable.img29,
        R.drawable.img30, R.drawable.img31, R.drawable.img32, R.drawable.img33, R.drawable.img34, R.drawable.img35,
        R.drawable.img36, R.drawable.img37, R.drawable.img38, R.drawable.img39, R.drawable.img40};
int [] chooseimages = new int [6];
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_play);


    //choose 6 image from 40 image we have for putting into buttons
    for(int counter = 0 ; counter<6 ; counter++){
        saverandom = rnd.nextInt(39);

        if(DontSameChoose(allimages[saverandom])){
            chooseimages[counter] = saverandom;
        }else {
            counter--;
        }
    }

    //put the select images in buttons


}
protected boolean DontSameChoose (int imageid){

    for(int c = 0 ; c<6 ; c++){
        if(imageid == chooseimages[c]){
            isTheSameOk = false;
        }
    }
    return isTheSameOk;
}
}

第一个数组是选择具有6个id的图像的图像,我想以上述方式保存值,在另一个数组中,长度为12。

2 个答案:

答案 0 :(得分:4)

如果您将数组转换为ArrayList,这是一个简短的解决方案:

ArrayList<Integer> secondList = new ArrayList<>(firstList);
secondList.addAll(firstList);
Collections.shuffle(secondList);

答案 1 :(得分:0)

使用此代码

   HashMap <Integer,Integer> mapa;
            mapa = new HashMap<>();
            int cont=0;
            int arr[] = new int[12];
            int arr2[] = new int[]{3,4,20,33,1,25};
            for(int i=0;i<12;i++){
                arr[i] = (int)Math.random()*100;
            }
            while(true){
                int random = (int)Math.random()*12;

                if(mapa.containsKey(random)){
                }else{
                    mapa.put(random, 1);
                    arr[random] = arr2[cont++];
                }
                if(cont >= 6){
                    break;
                }
}