0

What is a good ways to make random strings of length n, where the strings consist of only 0's and 1's?

  • (obviously strings will repeat after some point, but assume we have enough length so we don't hit this ).

Would using math.random() and round and then just joining the generating numbers be good?

Maybe there is a way to generate all $n$ digits at once instead of in a loop as in above?

majmun
  • 131
  • 9

5 Answers5

2

Here are two methods:

  1. concat strings using a for loop
function buildStrForLoop(n) {
   let str = ''
   for (let i = 0; i < n; i++) {
      str += Math.floor(Math.random() + 0.5)
   }
   return str
}
  1. generate an array using Array.from and then join
function buildStrArrayFrom(n) {
   return Array.from({ length: n }, () => Math.floor(Math.random() + 0.5)).join('')
}

Note i use floor and add 0.5 instead of using round as it was slightly faster.

I timed this on my M1 mac setting n=10000000 and got ~1000ms for both methods.

Erlend
  • 1,711
  • 1
  • 22
  • 25
1

This solution uses .toString(2) to convert our random number to base 2 and get a bunch of 0's and 1's all at the same time (as opposed to only yielding one 0 or 1 with rounding), which greatly reduces the amount of times our loop has to execute. It also uses rando.js to be cryptographically secure, but you could just as easily use Math.random() instead of rando() if you chose to.

function get01String(length){
  var str = "";
  while(str.length < length) str += rando().toString(2).slice(2);
  return str.slice(-length);
}

console.log(get01String(5));
<script src="https://randojs.com/2.0.0.js"></script>
Aaron Plocharczyk
  • 2,776
  • 2
  • 7
  • 15
  • 1
    +1 for mentioning rando.js and being cryptographically secure. I don't need that (for my application it doesn't matter if the number is predictable, so long as I am not getting multiple repeats), but its a worthwhile consideration in general. – majmun Sep 16 '21 at 20:39
0

Here's a one-liner that might do what you need:

(Math.floor(Math.random() * (999999999 - 111111111)) + 111111111).toString(2)

Truncate from the left to the length you need.

Bill in Kansas City
  • 360
  • 1
  • 5
  • 21
0

Here is what I would do. I made a function, which creates a string with 0s and 1s.

Maybe there are better options, but it may help you.

function stringMaker(lenght) {
            let string = "";
            for (let i = 0; i < lenght; i++) {
                string += Math.round(Math.random());
            }
            document.getElementById("number").innerHTML = string;
        }
Tschogge
  • 86
  • 1
  • 7
0

There might be a better way, and this is not cryptographically secure:

generateRandomStringOfLength = n => {
  let string = ''
  while (string.length < n) {
    if (Math.random() > 0.5) {
      string = string.concat(1)
    } else string = string.concat(0)
  }
  return string;
}
Slbox
  • 10,957
  • 15
  • 54
  • 106