Last active
December 13, 2015 22:08
-
-
Save aeg/4981905 to your computer and use it in GitHub Desktop.
リストからランダムに1つだけ要素を選ぶ
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Case #1 | |
| // リストからランダムに1つだけ要素を選ぶ | |
| def list1 = ['a', 'b', 'c', 'd'] | |
| def item = list1[new Random().nextInt(list1.size())] | |
| println item | |
| // 実行結果例(実行する度に結果が異なる) | |
| // c | |
| // Case #2 | |
| // リスト(ArrayList) にランダムで1つだけ要素を返すメソッドを追加する。 | |
| ArrayList.metaClass.define { | |
| random { | |
| int size = delegate.size() | |
| delegate[new Random().nextInt(size)] | |
| } | |
| } | |
| println list1.random() | |
| // 実行結果例(実行する度に結果が異なる) | |
| // a |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment