mardi 3 mars 2020

Using JavaScript to get random 2-digit numbers in a specific range where both the 1st and 2nd digits are constrained

I've got a bit of an interesting mathematical puzzle to solve.

I'm writing a test to verify that values outside of a range of a field in a window are not allowed to be input. For the most part this is extremely easy.

I'm using a function like this:

function getRanInt(min, max)
{
    let min = Math.ceil(min);
    let max = Math.floor(max);
    return Math.floor(Math.random() * (max - min) + min);
}

to set the range of "erroneous" values I want to test.

However, there is one field which throws a wrench in this method. One field has constraints on each digit. So the first digit can only be between 0-7 and the second digit can only be between 0-3.

My first thought was to simply concatenate two numbers together that I could separately constrain like this:

let m1_1;
let m1_2;

m1_1 = getRanInt(8,9);
m1_2 = getRanInt(0,7);

m1 = m1_1.toString() + m1_2.toString();
m1 = Number(m1);

until I thought about it for half a second and realized that this would only get me erroneous values > 83 but leave out an entire array of possible erroneous values like 24, 36, 18 etc...

I've been wracking my brain to try and come up with a solution that isn't massively convoluted but I've been drawing a blank. I thought I'd turn to you fine braniacs here and see if you could maybe help unstick my gears.

ADDITIONAL: If anyone's interested, the tool tip for the field in question explicitly says this:

2 Digits:
1st = 0 - 7
2nd = 0 - 3



Aucun commentaire:

Enregistrer un commentaire