【发布时间】:2019-04-17 04:00:29
【问题描述】:
问题: 随机播放一组不重复的数字。
Example:
// Init an array with set 1, 2, and 3.
int[] nums = {1,2,3};
Solution solution = new Solution(nums);
// Shuffle the array [1,2,3] and return its result. Any permutation of [1,2,3] must equally likely to be returned.
solution.shuffle();
// Resets the array back to its original configuration [1,2,3].
solution.reset();
// Returns the random shuffling of array [1,2,3].
solution.shuffle();
答案:
var Solution = function(nums) {
// hold nums in Solution
this.nums = nums;
};
Solution.prototype.reset = function() {
return this.nums;
};
Solution.prototype.shuffle = function() {
// create a copy of this.nums, shuffle it, and return it0
const shuffled = this.nums.slice();
const n = shuffled.length;
const swap = (arr, i, j) => {
let tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
// swap elements with random elements
for (let i = 0; i < n; i++)
swap(shuffled, i, Math.floor(Math.random() * n));
return shuffled;
};
我的问题: Math.floor(Math.random() * n ) 您正在从数组长度中获取随机索引。我不明白,这段代码不能重复吗?假设长度为3。公式不能得到2的索引和2的另一个索引,从而产生重复的索引。谁能澄清我误解的东西。谢谢。 Math.random 是否会自动撤回已使用的索引?
【问题讨论】:
标签: javascript