The task was to Generate an array of random numbers, in which exactly two units standing in random positions

You need to write native js.

You need to write native js.

asked March 25th 20 at 13:45

3 answers

answered on

Solution

It is not clear from the job is in the array must be unit or units must be in numbers of a given array.

The solution for the case where the array of random ones, the solution is not elegant but simple and clear

The solution for the case where the array of random ones, the solution is not elegant but simple and clear

```
function create(length, range) {
//create the array
let arr = [];
//fill the array with random numbers from a specified range
for (const i = 0; i < length; i++) {
if (i = pos1 || i=pos2)
continue;
arr[i].push(Math.random(range));
}
//choose 2 random positions in the array
let pos1 = Math.random(length);
let pos2 = Math.random(length);
//if positions are the same change one of them to a new random
while (pos1 == pos2){
pos2 = Math.random(length);
}
//add units in the selected random position
arr[pos1] = 1;
arr[pos2] = 1;
}
```

answered on March 25th 20 at 13:49

You can play with dewatering system. Times does the digit "1" is special, and the remaining nine regular. Take a random number, store it in dewatering system

`n.toString(9)`

– using the numbers from 0 to 8 and for sure there are no nines. Unit change on the nines. It remains to add two units at random positions.```
tworandom function() {
const arr = Math.floor(Math.random() * 9e8).toString(9).replace(/1/g,9).split(");
for (let i = 2; i > 0; i--) arr.splice(Math.floor(Math.random() * arr.length), 0, 1);
return +arr.join(");
}
[...Array(5)].map(tworandom)
// 6401715726, 950818173966, 915469690179, 4191464422, 223063891715
```

answered on March 25th 20 at 13:51

Alexander, You signed that PHP developer, write a function in php, and we will help to translate js. There is already written 100,500 options, but still issue free ordering different things. A function well just simple... do you really have no idea how to do? Write in the issue of the algorithm as You see it, then it makes sense to help with the code, where You lack of knowledge of js.

Find more questions by tags JavaScript

Working solution:

- jesse_Schaden63 commented on March 25th 20 at 13:50

- estefania commented on March 25th 20 at 13:53