Как сделать так, чтобы сгенерированные числа никогда не были одинаковыми? - PullRequest
1 голос
/ 16 апреля 2019

Я новичок в программировании, и я пытался сделать мои 3 случайных числа, и ответ никогда не был одинаковым, но как бы я ни пытался, я не получил желаемый результат.Я был бы очень благодарен, если бы кто-то указал мне правильный путь:)

Это фрагмент кода для первого случайно сгенерированного числа, два других абсолютно одинаковы.

//Random number 1
{
    btnAns1.label = "" + random1;
    if(mathOperationL1 == 1)
    {
        random1 = Math.floor(Math.random()* 24) + 1;
        do
        {
            random1 = Math.floor(Math.random()* 24) + 1;
        }
        while((random1 > 24) && (random1 === answerL1) && (random1 === random2) && (random1 === random3));
        btnAns1.label = "" + random1;
    }
    else if (mathOperationL1 == 2)
    {
        random1 = Math.floor(Math.random()* 11) + 1;
        do
        {
            random1 = Math.floor(Math.random()* 11) + 1;
        }
        while((random1 > 11) && (random1 === answerL1) && (random1 === random2) && (random1 === random3));
        btnAns1.label = "" + random1;
    }
    else if (mathOperationL1 == 3)
    {
        random1 = Math.floor(Math.random()* 144) + 1;
        do
        {
            random1 = Math.floor(Math.random()* 144) + 1;
        }
        while((random1 > 144) && (random1 === answerL1) && (random1 === random2) && (random1 === random3));
        btnAns1.label = "" + random1;
    }
    else if (mathOperationL1 == 4)
    {
        random1 = Math.floor(Math.random()* 12) + 1;
        do
        {
            random1 = Math.floor(Math.random()* 12) + 1;
        }
        while((random1 > 12) && (random1 === answerL1) && (random1 === random2) && (random1 === random3));
        btnAns1.label = "" + random1;
    }
}

В коде нет ошибок, и все остальное работает отлично. Это просто строка кода, которая должна сделать числа никогда не одинаковыми, просто не работает и после запускакод в течение нескольких раз я в конечном итоге получаю одинаковые числа.while((random1 > 24) && (random1 === answerL1) && (random1 === random2) && (random1 === random3));

Спасибо за вашу помощь заранее!:)

Ответы [ 2 ]

3 голосов
/ 16 апреля 2019

Ваше состояние while ((random1> 24) ... всегда false , потому что вы генерируете числа от 1 до 24, и они НИКОГДА не превышают 24.

Давайте сделаем это алгоритмически.

var aList:Array = new Array;

// Put the user's input here. Don't forget that
// TextField.text contains String value rather than int.
aList[0] = 5;

// Each line adds a random element different from
// the elements that are already in the Array.
aList[1] = smartRandom(1, 10, aList);
aList[2] = smartRandom(4, 15, aList);
aList[3] = smartRandom(9, 20, aList);

// Let's see what we get this time.
trace(aList);

// Generates a random int from "min" to "max" inclusive,
// while avoiding all the numbers from the "avoid" Array.
// Note that it doesn't actually checks if it is possible
// to do so, thus smartRandom(1, 1, [1]) will result in the
// infinite loop because conditions will never be satisfied.
function smartRandom(min:int, max:int, avoid:Array):int
{
    var result:int;

    do
    {
        result = min + Math.random() * (max - min + 1);
    }
    // The Array.indexOf(...) method returns -1 if the argument
    // is not on the given Array or it returns a 0-based
    // index of the element that is equal to the given argument.
    while (avoid.indexOf(result) > -1);

    return result;
}
2 голосов
/ 16 апреля 2019

while((random1 > 24) || (random1 === answerL1) || (random1 === random2) || (random1 === random3));

Оператор && настаивает на том, что все тесты верны, если он должен быть запущен снова. || - это логическое ИЛИ, поэтому любая протестированная комбинация приведет к повторному запуску цикла.

Редактировать: Я также должен сказать, что в этом коде, похоже, много дублирующихся усилий ... возможно, когда вы освоитесь с поведением своего оператора, вы сможете упростить процесс.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...