什么是随机回报 [英] What does this random return

查看:125
本文介绍了什么是随机回报的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,





我试图了解随机函数在此函数中的作用。这是此函数的最初目的



此函数返回一个包含加扰值列表的数组。阵列中正好有四对数字(1,2,3和4)和一对未配对数字(5)。使用array.sort()方法以伪随机方式对数组进行排序,从而对数组中的值进行加扰。



Hello,


I am trying to understand what the random function does in this function. here is the original purpose of this function

This function returns an array that contains a scrambled list of values. There are exactly four pairs of numbers (1,2,3 and 4) and one unpaired number (5) in the array. The values in the array are scrambled by using the array.sort() method to sort the array in a pseudo random way.

function randomAnswers(){
    var answers = [1,1,2,2,3,3,4,4,5];
    answers.sort(function(item){
        return .5 - Math.random();
    })
    return answers;
}





我的尝试:



我知道随机返回0(包括)到1(不包括)之间的数字。但我得不到.5 -Math.random();在这个函数中



What I have tried:

I know that random returns numbers between 0(included) to 1(not included). but I dont get .5 -Math.random(); in this function

推荐答案

有什么不明白的?



这只是数学。生成0到1(包括0和1)之间的随机数,从0.5中减去该值,然后将结果返回到代码中的任何代码。
What's not to understand?

It's just math. Generate a random number between 0 and 1 (inclusive), subtract that from 0.5 and return the result to whatever code called this code.


如果它的工作方式类似于.net的CompareTo,则排序需要两个对象的比较返回值...



If it works like .net's CompareTo, the Sort expects a comparison of two objects to return a value of...

=0 -- if the objects are "equal"
<0 -- if the first object is "less than" the second
>0 -- if the first object is "greater than" the second





排序然后可以根据他们的比较排列对象,

但是!在这里它接收-0.5和+0.5之间的随机值 - 从而导致不可预测的排列对象序列。



The Sort can then arrange the objects according to their comparisons,
BUT! Here it receives a "random" value between -0.5 and +0.5 -- thereby resulting in an unpredictably arranged sequence of objects.


这篇关于什么是随机回报的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆