smalltalkvisualworks

Pick random element from array in Smalltalk


I got a semestral project to do in Smalltalk, but I got stuck in choosing a random element from an array.

array = #('Alex' 'Bob' 'Frank' 'Samantha').
^"RandomChoice"

And now I need to pick a random name from the array. I found Random function, but don't know how it works. Anyone help? Thanks!


Solution

  • First of all it is written Smalltalk and not SmallTalk.

    You need to think about what you are trying to achive. Since you did not specify your Smalltalk, I'll be using the one I know the most the Smalltalk/X-jv branch.

    Your comment shows that you have found the atRandom method which should work as you have specified in your question:

    atRandom
        "Return any random element from the receiver"
    
        ^ self atRandom:Random
    
        "
         #(1 2 3) atRandom
    

    I have tried it on Smalltalk/X and it works as expected.

    Even with your when executed at Workspace it works correctly:

    #('Alex' 'Bob' 'Frank' 'Samantha') atRandom.'Frank' ('Frank' is the result of the print it)

    You could do it differently, like (this is suboptimal as atRandom works correctly):

    (#('Alex' 'Bob' 'Frank' 'Samantha') asOrderedColletion randomShuffle) at: 1.

    This makes OrderedCollection from Array and shuffles it randomly and picks first position.

    Your method would could look like this:

    randomName: nameArray
        ^ nameArray atRandom