2009-12-29 63 views
3

我正在經歷railstutorial,看到一個班輪以下紅寶石oneliner VS常規

('a'..'z').to_a.shuffle[0..7].join 

它創建隨機7個字符的域名類似以下內容:

hwpcbmze.heroku.com 
seyjhflo.heroku.com 
jhyicevg.heroku.com 

我試圖轉換一個襯墊的Groovy但我只能拿出:

def range = ('a'..'z') 
def tempList = new ArrayList (range) 
Collections.shuffle(tempList) 
println tempList[0..7].join()+".heroku.com" 

以上可以改善並作出一個班輪?我試圖通過

println Collections.shuffle(new ArrayList (('a'..'z')))[0..7].join()+".heroku.com" 

然而,爲了使上面的代碼更短,顯然Collections.shuffle(new ArrayList (('a'..'z')))null

回答

3

由於沒有洗牌內置增添最給長,但這裏有一個內襯會做:

('a'..'z').toList().sort{new Random().nextInt()}[1..7].join()+".heroku.com" 

你不工作,因爲Collections.shuffle做一個就地洗牌但不返回任何東西。要使用它作爲一個襯墊,你需要這樣做:

('a'..'z').toList().with{Collections.shuffle(it); it[1..7].join()+".heroku.com"} 
+2

好...略短:。( 'A' .. 'Z')toList(){排序Math.random()} [1..7] .join()+「。heroku.com」 – mbrevoort 2009-12-29 07:37:23

+0

請注意,在Java 7中,它們有時會失敗,因爲它們默認情況下會使用Timsort,並且預計會比較2值保持不變。 – 2013-10-31 10:23:31

2

它不是一個班輪,但另一個Groovy的方式做,這是一個洗牌方法添加到字符串...

String.metaClass.shuffle = { range -> 
def r = new Random() 
delegate.toList().sort { r.nextInt() }.join()[range]} 

然後你有一些非常紅寶石般的...

('a'..'z').join().shuffle(0..7)+'.heroku.com' 
+1

我最喜歡這一款;我認爲這是Groovier解決方案= D儘管我認爲使用Collections.shuffle來完成擴展方法中的工作會更清楚一些。 – epidemian 2011-11-11 02:09:59

0

這是我的嘗試。這是一個單線,但允許重複字符。它不會執行隨機播放,儘管它​​會爲隨機域名生成合適的輸出。

我張貼它作爲一個遞歸的匿名閉包的例子:

{ i -> i > 0 ? "${(97 + new Random().nextInt(26) as char)}" + call(i-1) : "" }.call(7) + ".heroku.com" 
0

這絕對不是因爲紅寶石對方漂亮,但正如特德mentioned,這主要是因爲這樣的事實shuffle方法是Collections中的一種靜態方法。

[*'a'..'z'].with{ Collections.shuffle it; it }.take(7).join() + '.heroku.com' 

我使用的傳播運營商招範圍轉換成一個列表:)