0

I'm new to JavaScript and trying to solve an optimization problem. How can I create an array with 20 random binary values of [0, 1]? For instance something like:

[0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 1, ...]

The distribution of these binary values in the array should be random. Thanks

4
  • 2
    Show us what you tried.. Commented Nov 26, 2017 at 5:35
  • How is this related to genetic algorithms? Commented Nov 26, 2017 at 5:39
  • ^ I'm with @jrook: This has nothing to do with genetic algorithms! Commented Nov 26, 2017 at 7:46
  • I'm trying to solve an optimization problem related to roads management. So 1: means treat the road ; 0: Don't treat the road . I'm using this array to create an initial random population based on the number of road segments i have. Commented Dec 13, 2017 at 2:36

2 Answers 2

2

Try this for loop

var arr = [];
for (var i=0;i<20;i++){
     arr.push(Math.round(Math.random()))
}
console.log(arr)

Sign up to request clarification or add additional context in comments.

Comments

1

You could create an array using the constructor, which allows you to set the size, then Array#fill it with a value, then Array#map it with either 1 or 0 based on Math.random()

console.log(
  new Array(20).fill(1).map(x => (Math.random() >= .5) ? 1 : 0)
)
<script src="https://codepen.io/synthet1c/pen/KyQQmL.js"></script>

1 Comment

you could return +(Math.random() >= .5), with a casting to number

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.