
像一个好的小编码器,我写了一个测试.它从该组中挑选100名获胜者,并输出每个参与者被选中的次数.期望它将大致与应该被挑选的次数(基于他们的机会数量)一致.结果是……关闭.
我将问题缩小到一行,如果分成两个单独的语句,则可以完美地运行.该例程的精简版本如下. “坏”版本处于活动状态,“好版本”已被注释掉
def randomInRange(int min,int max) { Random rand = new Random() rand.nextInt((max - min) + 1) + min}def bob = [name:'bob',timesPicked:0]def joe = [name:'joe',timesPicked:0]def don = [name:'don',timesPicked:0]def chanceWheel = []//don should get picked a lot more2.times{chanceWheel << bob}2.times{chanceWheel << joe}6.times{chanceWheel << don}//pick somebody at random from the chance wheel 100.times{ //this will produce timesPicked counts that do NOT sum to 100 and usually under-represents don chanceWheel[randomInRange(0,9)].timesPicked++ //splitting the logic into 2 lines will always have the correct sum of timesPicked with roughly the right distribution of winners //def picked = chanceWheel[randomInRange(0,9)] //picked.timesPicked++}println bobprintln joeprintln don 我的问题是单线版本有什么问题?我的猜测是它的执行顺序问题,但我不能为我的生活找出它的轨道.
解决方法chanceWheel[randomInRange(0,9)].timesPicked++
是
chanceWheel[randomInRange(0,9)].timesPicked = chanceWheel[randomInRange(0,9)].timesPicked + 1
调用randomrange()两次,与调用一次并分配给变量的工作示例相反.
总结以上是内存溢出为你收集整理的Groovy优先级问题全部内容,希望文章能够帮你解决Groovy优先级问题所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)