kyma•tweaky . How . RandomSelectFromSubset

Question (or Task)

I would like to randomly select from a collection of values. But I would like to be able to eliminate some of the values from consideration, based on switches or toggles that I control from the VCS.

Solution(s)

If you paste the following code into a SoundToGlobalController?, it will generate indexes of randomly selected switches, choosing ONLY from among those switches that are currently turned ON. Then you can use these index values to look up other values from an array.

| ctrls index count rand expr  |

"Create a collection of 8 switches."
ctrls := {(1 to: 8) collect: [ :i | !sw suffix2: i]}.

"Create a hot parameter called index."
index := EventVariable new.

"Create an expression that adds up the values of all the switches (1 or 0) to get the number of switches that are ON."
count := ctrls inject: 0 into: [ :a :b | a + b asLogicValue].

"Create an expression that generates a new random number between 0 and count, once per beat.  Save it in rand."
rand := (!BPM bpm s random abs * count) truncated.

"Create expr which will turn into a long concatenation.  If all the switches are zero, this returns 0."
expr := (index <+ (rand + 1)), 0.

"Build an expression by concatenating onto the end of expr.  The expression says that for each switch,
when it is ON, decrement index.  If index is zero, the result is the index number that switch occupies in the
array.  Otherwise, nothing happens.  When switch is OFF, nothing happens.  The result is an expression that
returns the index of the randomly selected switch (selected from only those switches that are currently turned ON)."
ctrls do: [ :sw |
   expr := expr,
      (sw
         true:
            (((index <~ (index - 1)) eq: 0)
               true: (ctrls indexOf: sw)
               false: nil)
         false: nil)].

"This is a Capytalk expression that will return the index of a randomly selected switch from among those that are switched on. 
You can use this index to read from an array of values."

expr

-- CarlaScaletti - 20 Dec 2006

WebForm
Question: How do I randomly select from a collection of values from which some values are excluded?
Keywords: random selection elimination

----- Revision r1.2 - 20 Dec 2006 - 22:46 GMT - CarlaScaletti
Copyright © 1999-2014 by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding kyma•tweaky? Send feedback.