I need to generate 3 fractions with these rules:
I already have a function to generate unique numertors
static randomUnique(range: number, count: number) {
let nums: number[] = [];
while (nums.length < count) {
nums.push(Math.floor(Math.random() * (range) + 1));
}
return [...nums];
}
and a function to check if the fraction is reducable
static isSimplified(numOne: number, numTwo: number) {
let numerator = numOne;
let denominator = numTwo;
for (let i = Math.max(numOne, numTwo); i > 1; i--) {
if ((numOne % i === 0) && (numTwo % i === 0)) {
numOne /= i;
numTwo /= i;
}
}
return numOne === numerator && numTwo === denominator ? false : true;
}
The problem is that the generated numerators can be reducable so I changed the randomUnique function to this
static randomUnique(denominator: number, count: number) {
let nums: number[] = [];
let numerator = 0;
while ((nums.length < count)) {
numerator = Math.floor(Math.random() * (denominator * 3) + 1);
if (!FractionAxisLogic.isSimplified(numerator, denominator))
nums.push(numerator);
}
return [...nums];
}
And now the problem that numerators aren't unique
How can I fix this please?
I fixed this by changing let nums: number[] = []; to using javascript Set() which is an object for storing unique values.