Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

181
Visualizações
How to generate 3 unique fractions without being reducable in Javascript?

I need to generate 3 fractions with these rules:

  • denominator is the same
  • numerator must be unique and between 1 and denominator * 3
  • Fraction must not be reducable (for example: 2 / 6 can be reduced to 1 /3 which ins't allowed)

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?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I fixed this by changing let nums: number[] = []; to using javascript Set() which is an object for storing unique values.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda