【问题标题】:Shuffle an Array coding challenge. trouble understanding one part随机播放数组编码挑战。难以理解某一部分
【发布时间】: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


    【解决方案1】:

    是的,Math.floor(Math.random() * n) 表达式可以多次计算出相同的数字,但这没关系,因为在 swap 中使用了随机数,这会将索引 i 处的数字切换为所选数字随机索引。

    如果随机索引取自原始数组并添加到要返回的数组中,例如

    const randIndex = Math.floor(Math.random() * n);
    arrToBeReturned.push(arr[randIndex]);
    

    你是对的,但这不是算法正在做的事情。想象一下随机排序[1, 2, 3]的数组:

    循环的第一次迭代:i 为 0,选择的随机索引为 2。交换索引 0 和 2:

    [3, 2, 1]
    

    第二次迭代:i 为 1,选择的随机索引为 2。交换索引 1 和 2:

    [3, 1, 2]
    

    第三次迭代:i 为 2,选择的随机索引为 2。交换索引 2 和 2:

    [3, 1, 2]
    

    使用此代码,每个索引与另一个索引随机交换至少一次,确保到最后,数组是随机的,没有偏差(假设 Math.random 是可信的)。 p>

    【讨论】:

      【解决方案2】:

      Math.floor(Math.random() * n) 是的,它可以对相同的索引进行评估,但在这里你使用数字来交换元素,所以这没关系。

      Math.random 会自动撤回已使用的索引吗?

      不,您不需要跟踪以前生成的值

      如果随机生成的索引尚未包含在该变量中,那么您可以使用变量 a objectMap 来跟踪先前添加的索引,而不是将其添加到最终输出中,否则再次生成新的索引,

      但在这种情况下不需要。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-08
        • 1970-01-01
        • 2014-04-21
        • 1970-01-01
        • 1970-01-01
        • 2015-11-09
        相关资源
        最近更新 更多