Home > Net >  Extending a Variable's Length With Random Numbers Doesn't Work
Extending a Variable's Length With Random Numbers Doesn't Work

Time:11-06

I am making an AI that tries to solve a user-inputted "numberle" in JavaScript. I don't want the user to do extra work just to see an AI do it's thing, so on the input field, if the user inputs a number that has less than 5 digits, the JavaScript should add random numbers at the end of the variable, until it has a total of five digits.

I used all the loops I had experience with, under an if statement, so if the length of the input was less than 5 (like 3), the loop will add 5 - the number of digits of the input (2) digits that are random, using the Math.random attribute. Here is the code I currently have:

if (input.length < 5) 
   do {
     input = (input * 10)   Math.floor(Math.random() * 9)   1;
  } while (input.length < 5);
} 
console.log(input)

I have also used the for and while loops with basically the same condition (obviously modified for the if loop; made a variable for input.length so that it has the same value).

Here is what I get in the console:

5 // Inputted number (1 digit)
52 // Inputted digit   random number

As you can see, the loop only runs once, although it should've ran 3 more times. I am using strict mode also. My code editor is github.dev, and I am using the CodeSwing console.

CodePudding user response:

If input is a number, it will not have "length", since it is not a string.

You can achieve the desired result like this:

let input = 5;
let digits = 2;
while (input < 10**(digits-1)) input = ~~((input Math.random())*10);
console.log(input);

Note that ~~ is a compact way of doing Math.floor()

Alternatively, without a while loop:

let input = 5, digits = 2, M = Math; L = x=>~~(M.log(x)/M.log(10)) 1;
input = ~~((input M.random())*10**(digits - L(input)));
console.log(input);

  • Related