in reply to randomly choosing elements from an array

From this I want to randomly pick out an x number (in this case let's say we want to pull back 2) words from the list.

Introduce a level of indirection. Instead of picking from the list, pick from a set of indices into the list. Randomize the set of indices, and pick the first X.

  • Comment on Re: randomly choosing elements from an array

Replies are listed 'Best First'.
Re: Re: randomly choosing elements from an array
by sulfericacid (Deacon) on Mar 19, 2003 at 06:05 UTC
    Sorry, I'm still what you can call perl-iliterate. I didn't understand a word you just said. Do you have any links to thinks which may help clear things up?

    Thanks.

    "Age is nothing more than an inaccurate number bestowed upon us at birth as just another means for others to judge and classify us"

    sulfericacid

      What dws mean is:
      1. create an index array containing all valid index. For example, if you have a list of 5 words, then this index array world be (0,1,2,3,4).
      2. Shuffle this inddex array randomly, so it becomes something like (3,0,4,2,1). (I guess, the difficulty to you would be how to shuffle this array ;-)
      3. Now pick the words. For example, continue from step 2, say you want pick 2 words. As the first two elements of the shuffled index array is 3 and 0, so you just pick the words at index 3 and 0 of your word list.
        Thanks so much for the explanation on how to do this. I surely don't know how to shuffle but now that I know the easiest way to get this done, shuffle shouldn't be so hard :)

        Thanks for your help!!

        "Age is nothing more than an inaccurate number bestowed upon us at birth as just another means for others to judge and classify us"

        sulfericacid

      Do you have any links to thinks which may help clear things up?

      pg catches my meaning. The logic you need to shuffle the indices can be found in Fisher-Yates shuffle?.