how to create numbers in different variables in JS javascript

Asked

Viewed 71 times

0

I’m developing a website to train multiplication in math. In it, I have a random question. For example, (12x12) and for each question I have to generate three random numbers, where only one of them is the correct answers. In the 12x12 example, one of the 3 numbers has to be the value 144;

Javascript code below:

// essas são as opções.
let option1 = 0;
let option2 = 0;
let option3 = 0;

function geraOptions() {
    **gerando os numeros aleatorios numberLeft*numberRight.**
    const numberLeft = Math.floor(Math.random(1) * 10);
    const numberRight = Math.floor(Math.random(1) * 10);

    const multiplicação = numberLeft * numberRight;

    // agora eu preciso de algo que gere 3 três numeros com apenas um deles sendo o valor correto da multiplicação e os outros 2 sendo incorretos, mas a cada reload da pagina tem que ser criado em um lugar diferente exemplo:
}
geraOptions();

2 answers

1

I believe that’s what you wish to do:

function generateOptions(param1, param2, qtde) {

    do {
        var multi = [], original_calc = 0, calc = 0;
        for (var i=0; i < qtde; i++) {
             var n1 = Math.floor(Math.random() * 10),
                 n2 = Math.floor(Math.random() * 10);
                 calc = n1 * n2;
             if (n1 != n2 && n1 > 0 && n2 > 0) {    
               multi.push({numbers:[n1, n2], result:calc})
             }
        }

        original_calc = (param1 * param2);

    } while(calc != original_calc && calc > 0 && multi.length < qtde);

    var original = {
           numbers:[param1, param2],
           result:original_calc
    }

    return {
       result_params:original,
       others:multi,
       total_send: qtde
    }
}
console.log(generateOptions(12, 12, 3));

If you want to improve, you can take the size of the number of decimals and place the random based on its length:

function pad(str, length) {
  const resto = length - String(str).length;
  return str+'0'.repeat(resto > 0 ? resto : '0');
}

function setSizeRandomic(param)
   var str =(param).toString(),
       leng = str.length,
       pads = pad(Math.floor(Math.random() * leng), leng),
       casas = parseInt(pads);
     return Math.floor(Math.random() * casas); 
}

It would suffice to call so within the first method:

function generateOptions(param1, param2, qtde) {
    
        do {
            var multi = [], original_calc = 0, calc = 0;
            for (var i=0; i < qtde; i++) {
                var n1 = setSizeRamdomic(param1),
                    n2 = setSizeRamdomic(param2);
                    calc = n1 * n2;
                 if (n1 != n2 && n1 > 0 && n2 > 0) {    
                   multi.push({numbers:[n1, n2], result:calc})
                 }
            }
    
            original_calc = (param1 * param2);
    
        } while(calc != original_calc && calc > 0 && multi.length < qtde);
    
        var original = {
               numbers:[param1, param2],
               result:original_calc
        }
    
        return {
           result_params:original,
           others:multi,
           total_send: qtde
        }
    }
    console.log(generateOptions(12, 12, 3));

0


Hello I created a function that meets what you would like, but certainly you will refine as your need, but generally should help you at least to find something that is ideal. Below follows her with comments:

   //num1 - Primeiro numero da expressao
    //num2 -  segundo numero da expressao
    //qtdAlternativas -  qtde de alternativas que você quer q a pergunta venha a ter
    // essa função pega esses 3 argumentos e gera um array de json onde vc tera a 
    // alternativa se e correta ou nao e o valor da alternativa
    // nesse padrao: [{val: 15, correto: false}, {val:10, correto: true},]
    function geraRespostas(num1, num2, qtdAlternativas){

    // aqui quero saber de antemao qual sera o valor correto
    var correct =  num1 * num2;
    
    /* a razao por querer alternativas - 1  é pq ja temos uma alternativa q no caso seria a correta */
    var randAlternativas = qtdAlternativas  - 1;
    
    // array onde armazenaremos as alternativas inclusive claro a correta
    var arrAlternativas = [];
    
  // loop para gerar as alternativas aleatorias no caso sao no range de 1 a 1000
    for(var i = 0; i < randAlternativas; i++){
        var aleat = Math.floor(Math.random() * 1000);
    
        // nao queremos gerar uma alternativa q tenha valor igual a correta
        while(aleat == correct){
            aleat = Math.floor(Math.random() * 1000);
        }
        // colocamos nosssas alternativas incorretas 
        arrAlternativas.push({val: aleat, correto: false});
        
    }
    
    // colocamos nosssa alternativa correta
    arrAlternativas.push({val: correct, correto: true});
    
// abaixo vamos apenas embaralhar as alternativas    
    var currentIndex = arrAlternativas.length, temporaryValue, randomIndex;


  while (0 !== currentIndex) {


    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // realizar trocas de posicoes pra embaralhar
    temporaryValue = arrAlternativas[currentIndex];
    arrAlternativas[currentIndex] = arrAlternativas[randomIndex];
    arrAlternativas[randomIndex] = temporaryValue;
  }
  // e devolver o array de alternativas
  return arrAlternativas;
}

//Experimente!
console.log(geraRespostas(12,12,3));
//(possivel resultado)
//[{val: 200, correto: false}, {val: 144, correto: true}, {val: 386, correto: false}]
  • Man, that’s right, thank you very much helped me a lot, I was not managing to shuffle the replies because always returned in a single position.

  • how can I call JSON numbers? , by having <p> <p> <p>, I want to get 1 value in each P tag

  • Pow good guy q helped you. I always think it’s nice to find what I need here. One time we need to give back. About JSON Numbers, note that it is an array so when you interact on it with a for(key in oArray) you generate the number from the position in the array (key + 1) pq in js the keys start at Zero

  • 1

    vdd bro, now I figured out how to get the numbers, thanks dnv!

  • We’re together little brother dev.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.