Random variable that is not the same as another variable in AutoHotKey

Viewed 61

I want to be able to print randomized variables one after the other without repeats. Here is what I've tried:

   Random WINa1, 1,4
SendInput, va%WINa1%
Loop, 
{
    Random WINa2, 1,4
 } Until %WINa2% not %WINa1%
SendInput, vb%WINa2%

However, i think I must be using Until wrong? As the first portion will work but then it gets stuck in the loop?

2 Answers

One way I like to get a random order with no repeats is to generate all possible outputs in sequence (1-4 in this case), then just shuffle the order. This guarantees no repeats without checking the list a lot of times or risking getting stuck in a while loop.

outputs := ["1", "2", "3", "4"]
randomOutputs := fn_shuffleArr(outputs)
; => ["3", "4", "1", "2"]
return

fn_shuffleArr(param_array)
{
    array := param_array.clone()

    index := array.count()
    loop, % index - 1 {
        random, randomIndex, 1, % index
        tempVar := array[index]
        array[index] := array[randomIndex]
        array[randomIndex] := tempVar
        index--
    }
    return array
}

The problem here is trying to use legacy syntax in something that only accepts the newer and better expression syntax and also misuse of the legacy NOT.
The legacy NOT operator is not a not-equals operator, so it's not going to do the trick here.
But anyway, lets get rid of all this legacy stuff and do it the right way.

Random WINa1, 1,4
SendInput, % "va" WINa1
Loop
    Random WINa2, 1,4
Until (WINa2 != WINa1)
SendInput, % "vb" WINa2

I also switched over to expression syntax on the SendInputs, not really needed, but you'll never catch me using legacy syntax, it's not 2008 anymore.
Also omitted the brackets, since they're not needed on 1liner statements.

So we switched over to using the != (not-equals) operator and added brackets around the statement. The brackets are not technically needed in this instance, but they usually indicate we're in expression mode, so I'd say it's good practice to use them here.

To learn more about the AHK scripting language (legacy vs expression), get started here:
https://www.autohotkey.com/docs/Language.htm

Related