嘿傢伙我試圖洗牌和整數數組。可以說我有這個數組:int [] array = {1,2,3,4,5}; 我想將其整理以便順序變得完全隨機。例如:int [] array = {3,5,1,4,2};對於java如何洗牌整數數組?
-3
A
回答
2
不知道你在用什麼編程語言,但我會用Python來回答它。
from random import shuffle
alist = [[i] for i in range(5)]
shuffle(alist)
1
洗牌的算法很簡單 - 但你需要得到它恰到好處或洗牌並不是隨機的。
在java中:
for (int i=0;i<arr.length;i++) {
int swap = random.nextInt(arr.length-i) + i;
int temp = arr[swap];
arr[swap] = arr[i];
arr[i]=temp;
}
基本上你在列表中有一個交換當前元素列表中的掃描隨手拈從自身到列表的末尾。
重要的是你只能選擇前進,否則你不會以均勻的分配結束。
大多數語言(包括Java)都有一個內置的shuffle函數。
0
我會回答在Java中:
int[] a = int[] { 1, 2, 3, 4, 5 }; // example array
int length = a.length(); // for convenience, store the length of the array
Random random1 = new Random(); // use a standard Java random number generator
int swap = 0; // use an extra variable for storing the swap element
int r1 = 0; // for convenience, store the current randomly generated number
for (int i=0; i<length(); i++) { // iterate over each field of the array
r1 = random1.nextInt(length - 1); // generate a random number representing an index within the range of 0 - a.length - 1, i.e. the first and the last index of the array
swap = a[i]; // swap part 1
a[i] = a[r1]; // swap part 2
a[r1] = swap; // swap part 3
}
//就是這樣,陣列根據Java隨機生成
相關問題
- 1. 如何洗牌數組值
- 2. 如何「洗牌」數組?
- 3. 如何切片數組然後洗牌
- 4. 如何洗牌字符串數組
- 5. 如何洗牌INSPhotoViewable(自定義)數組?
- 6. 如何手動洗牌數組列表
- 7. 洗牌在Objective-C數組
- 8. 隨機洗牌數組
- 9. 洗牌數組元素
- 10. 洗牌Javascript數組優雅
- 11. 洗牌整數測試的方法
- 12. 如何洗牌
- 13. 拆分數組,隨機洗牌
- 14. 洗牌!在ruby中n次數組
- 15. 在java中洗牌兩個數組
- 16. 洗牌二維數組中的perl
- 17. 洗牌PHP數組不相同的值
- 18. 在Java中洗牌二維數組
- 19. 洗牌多維動態數組
- 20. 洗牌()作爲一個關聯數組
- 21. 數組在android中不洗牌
- 22. c + +洗牌動態數組的內容?
- 23. 使用mysql從數組中洗牌
- 24. 如何洗牌對
- 25. 重複數組A到數組B中,洗牌數組中的一個,但是兩個數組都被混洗
- 26. C++:如何洗牌動態數組指針?
- 27. 如何在java中洗牌二維數組
- 28. 如何在JS中專門洗牌數組?
- 29. jquery如何洗牌數組值?什麼時候toggleClass?
- 30. 如何在Java中洗牌對象數組
編程語言shuffeld?你的「嘗試」代碼是? – Hardy