简体   繁体   English

将数组的随机正值转换为负数

[英]Convert random positive values of an array to negative

I'm a JS newcomer. 我是JS新手。 I have a scrambled array of numbers and need to convert random positive values of the array into negative. 我有一个混乱的数字数组,需要将数组的随机正值转换为负数。 At that point I only know how to randomize the array: 那时我只知道如何随机化数组:

var myArray = [1,2,3,4,5,6,7,8,9,10];
myArray.sort(function() {
    return 0.5 - Math.random()
}) 

But need the result look something like this: [8,-2,3,9,-5,-1,4,7,6,-10] 但是需要结果看起来像这样:[8,-2,3,9,-5,-1,4,7,6,-10]

Please suggest. 请提出建议。 Thank you! 谢谢!

myArray.forEach(function(i,j){

if(i>0){

  var negative=i*(-1);/*convert your positive values to negative*/
  myArray[j]=negative;

}

})

Modified Fisher–Yates shuffle to randomly negate the item 改良的Fisher-Yates随机播放以随机否定该物品

function shuffle2(arr) {
    var i, j, e;
    for (i = 0; i < arr.length; ++i) { // for every index
        j = Math.floor(Math.random() * (arr.length - i)); // choose random index to right
        e = arr[i]; // swap with current index
        arr[i] = arr[i + j];
        arr[i + j] = e;
        if (.5 > Math.random()) // then, randomly
            arr[i] = -arr[i]; // flip to negative
    }
    return arr;
}

Now can do 现在可以做

shuffle2(myArray); // [-5, 2, 6, -7, -10, 1, 3, -4, -9, -8]

Please note if you were to stop the loop at arr.length - 1 you will need a final random flip outside of the loop for the last index 请注意,如果要在arr.length - 1处停止循环,则需要在循环外进行最后的随机翻转以获取最后一个索引

You can transform your array using Array.prototype.map() to get random +/- like this: 您可以使用Array.prototype.map()转换数组以获取随机+/-,如下所示:

myArray = myArray.map(function(item) {
    return Math.random() > 0.5 ? item : -item; // random +/-
});

Map function does not modify your array but only returns new mapped one (so you have to reassign it or assign to a new variable). Map函数不会修改您的数组,而只会返回新的映射数组(因此您必须重新分配它或将其分配给新变量)。

How about adding a second random number for positiv / negative (Flipping coin): 如何为正/负数添加第二个随机数(翻转硬币):

var pos = Math.floor(Math.random()*10) % 2;
var num = Math.random() * 10;
var result;
// pos will evaluate false if it is 0
// or true if it is 1
result = pos ? num : -num;

return result;

As you are a new comer this is the easiest way. 当您是新手时,这是最简单的方法。 Used for loop and Math.floor() 用于循环Math.floor()

  1. First randomize the array. 首先将数组随机化。
  2. Use math.random()*myArray.length and for loop to generate a random number and change the value of the index corresponding to the number value eg- 使用math.random()*myArray.lengthfor loop生成一个随机数,并更改与该数值对应的索引值,例如-
for (i = 0; i < 10; i++){
  var arrVal = myArray[Math.floor( Math.random()*myArray.length);]
if(arrVal > 0){
  arrVal = arrVal*(-1);
};
  };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM