Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to check the given random number is not in descending order?

I have generated a 4 digit random number, Where the random number should not be in descending order. It should not be like **7654 **.

Code:

function descendingOrder(n) {
   let num = n.toString();
      for (var i = 0; i <= num.length; i++) {
        if (num.substr(i) > num.substr(++i)) {
             alert('This pattern can't be used');
         }
         else {
             return parseInt(n);
         }
       }
}
descendingOrder(Math.floor(1000 + Math.random() * 9000));

This code just compares first and second digits and gives an **alert message
**. Could someone please help?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks

I’ve tried to generate a random number, which should not be in a descending order. But, it didn’t work.

>Solution :

  1. If you want to use only 4 digits, better to limit max number to 9999.
  2. You can break iteration at the first case, when next digit bigger then previous.
    function descendingOrder(n) {
        let num = n.toString();
        var i = 0;
        while (i<=num.length) {
            if (num.substr(i) < num.substr(i+1)) {
                alert('This pattern can be used');
                return parseInt(n);
            } 
            i++;
        }
        alert('This pattern cannot be used');
    }
    descendingOrder(Math.floor(1000 + Math.random() * 8999));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading