简体   繁体   English

在 Smalltalk 中从数组中选择随机元素

[英]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.我在 Smalltalk 中做了一个学期项目,但我在从数组中选择一个随机元素时陷入困境。

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.我找到了 Random 函数,但不知道它是如何工作的。 Anyone help?有人帮忙吗? Thanks!谢谢!

First of all it is written Smalltalk and not SmallTalk.首先,它是写的 Smalltalk 而不是 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.由于您没有指定您的 Smalltalk,我将使用我最了解的 Smalltalk/X-jv 分支。

Your comment shows that you have found the atRandom method which should work as you have specified in your question:您的评论表明您已经找到了atRandom方法,该方法应该按照您在问题中指定的方式工作:

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.我已经在 Smalltalk/X 上试过了,它按预期工作。

Even with your when executed at Workspace it works correctly:即使在 Workspace 执行时,它也能正常工作:

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

You could do it differently, like (this is suboptimal as atRandom works correctly):你可以用不同的方式来做,比如(这是次优的,因为atRandom工作正常):

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

This makes OrderedCollection from Array and shuffles it randomly and picks first position.这使得 OrderedCollection 来自 Array 并随机打乱它并选择第一个位置。

Your method would could look like this:您的方法可能如下所示:

randomName: nameArray
    ^ nameArray atRandom

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM