samedi 30 mars 2019

Javascript/Qualtrics: randomly drawing unique pairs of unique elements from an array

I am designing a custom conjoint experiment and have a Javascript issue. Participants repeatedly choose between two options distinguished by one of twelve randomly assigned levels of a single attribute. I am having difficulties with the Javascript necessary for two changes from a standard design: (a) preventing the random selection of identical levels for the two options and (b) preventing the random selection of identical options across choices. The former happens because I am currently randomly drawing two elements with replacement from an array of values. My approach to this is to randomly draw the elements without replacement by creating a new, filtered array. However, this doesn't seem to work:

\\ Define array of attribute levels, randomly draw an element
var foo = ["a", "b", "c", "d"];
bar_a = [ foo[Math.floor(Math.random()*foo.length)] ];

\\ Define a new array without the drawn element
var filtered = array.filter(function(value, index, arr){
    return value != bar; });

\\ Randomly draw an element from smaller array
bar_b = [ filtered[Math.floor(Math.random()*filtered.length)] ];

\\ Save values to embedded data fields to be piped into HTML table
Qualtrics.SurveyEngine.setEmbeddedData('bar_a1', bar_a);
Qualtrics.SurveyEngine.setEmbeddedData('bar_b1', bar_b);

The latter problem entails checking whether the result of the above matches the values of earlier sets of draws. I'd like to repeat the above process (presumably in a loop) until the pair of values drawn are not identical to earlier pairs (i.e. respondents don't face identical choice options ever). Is there a loop perhaps for this? Psuedo-code below:

\\ Take a new set of random draws repeating above
\\ Define array of attribute levels, randomly draw an element
var foo = ["a", "b", "c", "d"];
bar_a = [ foo[Math.floor(Math.random()*foo.length)] ];

\\ Define a new array without the drawn element
var filtered = array.filter(function(value, index, arr){
    return value != bar; });

\\ Randomly draw an element from smaller array
bar_b = [ filtered[Math.floor(Math.random()*filtered.length)] ];

\\ Check if the numbers are different
bar_a == ${e://Field/bar_a1} &&  bar_b == ${e://Field/bar_b1}

\\ If above is TRUE, repeat the above until FALSE




Aucun commentaire:

Enregistrer un commentaire