Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Supported by

Constrain randomisation in Javascript

Hello,

I hava a question about constraining max number of repeats of a variable created with Javascripts.

I have created a variable that selects a random number between 1-10 in an inline_javascript:

function randomInteger(minval, maxval) {

return minval + Math.floor(Math.random() * (maxval - minval + 1))

}

vars.num = randomInteger(1,10)

console.log(vars.num)

is there any javascript code that works similar to "constrain var maxrep = 1" in the loop script?

For example, i dont want that the variable "num" does repeat the same number in the next trial.


Thank you very much!!!!!!!😃

Comments

  • Hi Ana,

    There is no ready made function, but you could use a while loop to make this happen. I apologize for not providing Javascript code (I am not very familiar with it), but I think this Python code can be translated in a rather straightforward way.

    import random
    # save your previous array in a new variable
    # This only works if var.num has been created before!
    # So, on the second block and so on. Alternatively, you can create a fake list in the 
    # beginning of the experiment to make this comparison easier
    if var.block_no 1:
         var.prev_num = var.num
    while True: 
        var.num = random.randint(1,11) 
        # compare the current first trial with the last trial of the previous sequence. 
        if var.num[0] != var.prev_num[-1]:
             break
    
    

    I hope this helps,

    Eduard

    Buy Me A Coffee

Sign In or Register to comment.