Random Number, Which Is Not Equal to the Previous Number

New random number, different from previous random number, range integer 0—5

If the only number you need to skip is oldRand, you could shorten the size of the range by one, and if the generated number is equal or greater to oldRand, add one to it:

function getNewRand(oldRand, max) {
newRand = Math.floor(Math.random() * max);
if (newRand >= oldRand) {
newRand += 1;
}
return newRand;
}

Get a random value from a list which is not equal to a particular number?

import random

k = random.choice([i for i in array if i != x])

Note that the [] are required in this case, as:

random.choice(i for i in array if i != x)

which is equivalent to

gen = (i for i in array if i != x)
random.choice(gen)

doesn't work since choice requires a sequence, which a generator is not.

Random integer in a certain range excluding one number

The fastest way to obtain a random integer number in a certain range [a, b], excluding one value c, is to generate it between a and b-1, and then increment it by one if it's higher than or equal to c.

Here's a working function:

function randomExcluded(min, max, excluded) {
var n = Math.floor(Math.random() * (max-min) + min);
if (n >= excluded) n++;
return n;
}

This solution only has a complexity of O(1).

Generate two numbers that are NOT equal in PHP

$rnd1 = rand(0,9);
do {
$rnd2 = rand(0,9);
} while ($rnd1 == $rnd2);

How to make sure the generated random number is not equal to the next generated number?

You need to make randomNumber a property of your ViewController so that it is remembered between button presses. Each time, there are only 2 valid random numbers, so generate a number in the range 0 to 1 and then change it to 2 if it matches your previous number:

class ViewController: UIViewController {
// Give randomNumber an initial value
var randomNumber = Int(arc4random_uniform(UInt32(3)))

@IBAction func buttonPressed(button: UIButton) {
let currentNumber = randomNumber
randomNumber = Int(arc4random_uniform(UInt32(2)))
if currentNumber == randomNumber {
randomNumber = 2
}
}
}

This has the advantage of only needing 1 random number each button press.



Related Topics



Leave a reply



Submit