1

I want to use Fisher Yates shuffle algorithm to shuffle each integer from Math.random()after the ". (dot)". I split them into string and use the Fisher Yates shuffle algorithm but I am stuck on how to convert it back to number.

From: ["0", ".", "4", "1", "2", "7", "2", "9", "5", "8", "6", "7", "0", "7", "4", "2", "8", "1"]

To: 0.4127295867074281

    var randomNum = Math.random();
    var stringNum = randomNum.toString();
    var stringArray = stringNum.split("");

    var i = stringArray;
    var j;
    var temp;

    while (--i > 1) {
        j = Math.floor(Math.random() * (i + 1));
        temp = stringArray[j];
        stringArray[j] = stringArray[i];
        stringArray[i] = temp;
    }
1
  • If you can't trust your RNG to give you a random number, how can you trust your RNG to shuffle your random number.
    – psaxton
    Commented Mar 12, 2016 at 2:14

3 Answers 3

3

First join the array and then cast to number Number(strArray.join(""))

var strArray = ["0", ".", "4", "1", "2", "7", "2", "9", "5", "8", "6", "7", "0", "7", "4", "2", "8", "1"];

var num = Number(strArray.join(""));

// this prints 0.4127295867074281
document.write(num);

2
  • Glad that it helped :) Commented Mar 12, 2016 at 1:45
  • You can also use String(randomNum) instead of randomNum.toString(); Commented Mar 12, 2016 at 1:46
3
var str = "42";
var num = str * 1;

For the full number:

var fullNum = stringArray.join("") * 1
0

I'm amazing with logic, but not so much with each language but here is a basic, idea in logic. Remember below I am concatenating

x = 0 y = 0

while( y > 10)

z = generate random number greater that 0 and less than 10;

x = "x" + "." + "z"

end

answer = x

answer = answer + x

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.