I'm a JS newcomer. 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]
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
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
You can transform your array using Array.prototype.map() to get random +/- like this:
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).
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.random()*myArray.length
and for loop
to generate a random number and change the value of the index corresponding to the number value eg- for (i = 0; i < 10; i++){
var arrVal = myArray[Math.floor( Math.random()*myArray.length);]
if(arrVal > 0){
arrVal = arrVal*(-1);
};
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.