9 個 ImageView 隨機分配 9 張圖片,簡單 Random.nextInt 易導致重複。
List indices = new ArrayList<>();
for (int i = 0; i < 9; i++) indices.add(i);
Collections.shuffle(indices); // Fisher-Yates 洗牌,O(n) 均勻隨機
for (int i = 0; i < 9; i++) {
ImageView iv = findViewById(imageViewIds[i]);
iv.setImageResource(imageResIds[indices.get(i)]);
}
Integer[] arr = {0,1,2,3,4,5,6,7,8};
Random rnd = new Random();
for (int i = arr.length - 1; i > 0; i--) {
int j = rnd.nextInt(i + 1);
int tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp;
}
// arr 即為打亂後的索引順序
若圖片有類別(如顏色),需約束相鄰不重複,可用回溯或模擬退火算法生成滿足條件的排列。