SurveyCTO Random Draw of Beneficiaries 2
Hat-tip to SurveyCTO for the inspiration behind this example.
Best Practice
In this example we describe an elegant manner of randomly selecting/arranging a group of IDs/participants/beneficiaries using only a small repeat group. A list of IDs 1 to N is randomly ordered, which could be utilized in many situations. It also is able to be scaled much easier than the other randomization example presented in the Wiki.
It is NOT recommended for use in data collection forms as it is not replicable in this format, though it is a nice illustration of how think about programming solutions to this kind of problem in general.
Code Example
Here is the code example for this form.
- First we select how many IDs (in this case association members) we want to randomly order.
- The repeat group is 'powered' through the dynamic repeat-count,
if(${num}>0, if(count-selected(${unique_ids})>=${num}, count(${rand}), count(${random_draws})+1), 0)
which continues producing randomly selected IDs until the conditioncount-selected(${unique_ids})>=${num}
is fulfilled - i.e. there are the same number of unique draws (deduplicated previous draws) as there are numbers to draw from, implying that all potential IDs to draw from have been exhausted. Deduplication of the draws ensures that all potential IDs are covered. - The second repeat group shows the draw unfold, and is not necessary if this was to be used in a form.
- The field ${unique_ids} contains the randomly ordered IDs, which can be accessed using a selected-at() command as shown in the other randomization example.
It could also be amended to only select a certain number of draws from the entire pool by changing the expression in the repeat-count of the repeat group to be equal to a specific or predefined (in another integer field) value.
Back to Parent
This article is part of the topic SurveyCTO Coding Practices