0

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!

akidta
  • 11
  • 5
  • Iterate over the array, flip a coin and negate the number for heads. What specifically are you having problems with? Do you know how to iterate over an array? How to negate a number? – Felix Kling Dec 26 '15 at 23:21
  • Felix, thanks! I don't know how to randomly negate the number for heads, but will look it up. – akidta Dec 26 '15 at 23:28
  • 1
    Don't use this code to shuffle. The result is not guaranteed by the spec. – Oriol Dec 26 '15 at 23:33

5 Answers5

1
myArray.forEach(function(i,j){

if(i>0){

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

}

})
Muhammad Waqas
  • 1,140
  • 12
  • 20
1

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

Paul S.
  • 64,864
  • 9
  • 122
  • 138
0

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).

madox2
  • 49,493
  • 17
  • 99
  • 99
0

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;
Niklas Vest
  • 872
  • 6
  • 20
0

As you are a new comer this is the easiest way. Used for loop and 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-
for (i = 0; i < 10; i++){
  var arrVal = myArray[Math.floor( Math.random()*myArray.length);]
if(arrVal > 0){
  arrVal = arrVal*(-1);
};
  };
sudo_dudo
  • 573
  • 1
  • 5
  • 18