0

i want to ask how do i make that the generator would break when it generates a number that is even using cycles and arrays. I tried to do it using if (i%2) {break} , but it does not work for me. Also can you help me to put all the negative number generated to the arrays end ? Thank you for the help. This is my javascript code

  <script>
    var text = "";
    let mas = [];
    const y = 200;
    const y1 = -20;
    for (let i = 0; i != 15; i++) {
        mas.push(Math.floor(Math.random() * y) + y1);
        mas.sort();
    }
    document.getElementById("demo").innerHTML = mas;
</script>
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
mdstt
  • 35
  • 4
  • which numbers do you want to compare? and what *"cycle"* are you refering? and how should the negative numbers are sorted? – Nina Scholz Jan 13 '21 at 08:26
  • `mas.sort()` doesn't work for numeric arrays. [How to sort an array of integers correctly](https://stackoverflow.com/q/1063007) – adiga Jan 13 '21 at 08:27
  • And `if (i%2) {break}` will break for odd numbers not even numbers. You *probably* want to check the value `Math.floor(Math.random() * y) + y1` for even or odd before pushing. Not `i % 2` – adiga Jan 13 '21 at 08:28
  • Also sorting the array after every `.push()` doesn't make that much sense. Call it once after the `for` loop. – Andreas Jan 13 '21 at 08:29
  • @NinaScholz i need my generator to break when it generates a number that can divide without residue – mdstt Jan 13 '21 at 08:31
  • @mdstt, by which number? please add an example of wanted result. – Nina Scholz Jan 13 '21 at 08:31
  • for example it would generate random numbers 43; -27; -31; 121 10 . And it would stop generating on number 10 because that number can divide without residue – mdstt Jan 13 '21 at 08:33
  • @mdstt, and what about the ordering? – Nina Scholz Jan 13 '21 at 08:37
  • i need to make the negative numbers to be at the end of the array, for example in this example i gave it would be [43; 121; 10; -27; -31] – mdstt Jan 13 '21 at 08:38

1 Answers1

0

You could break the array by having a look to the random value and sort by sign.

const
    mas = [],
    y = 200,
    y1 = -20;
    
for (let i = 0; i < 15; i++) {
    const value = Math.floor(Math.random() * y) + y1;
    mas.push(value);
    if (value % 2 === 0) break;
}

mas.sort((a, b) => Math.sign(b) - Math.sign(a));

console.log(...mas);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • thank you, it works.. could you help me to change the elements of an array which are uneven to be changed and named as X in the array. For example x, x, 2 – mdstt Jan 13 '21 at 08:52