배열에서 무작위로 선택하려면 어떻게 해야 합니까?
저는 이것을 하는 훨씬 더 깨끗한 방법이 있는지 알고 싶습니다.기본적으로, 저는 가변 길이의 배열에서 임의의 요소를 선택하고 싶습니다.일반적으로, 저는 다음과 같이 할 것입니다.
myArray = ["stuff", "widget", "ruby", "goodies", "java", "emerald", "etc" ]
item = myArray[rand(myarray.length)]
두 번째 줄을 대체하기 위해 더 읽기 쉽고 간단한 것이 있습니까?아니면 그것이 그것을 하는 가장 좋은 방법입니다.당신은 할 수 있을 것 같아요.myArray.shuffle.first하지만 나는 단지 보았습니다.#shuffle몇 분 전 SO에서, 저는 아직 실제로 그것을 사용하지 않았습니다.
그냥 사용:
[:foo, :bar].sample # => :foo, or :bar :-)
Ruby 1.9.1+ 버전으로 제공됩니다.이전 버전의 Ruby에서도 사용할 수 있습니다.
Ruby 1.8.7에서는 불행한 이름으로 존재합니다.choice그것은 나중 버전에서 이름이 바뀌었기 때문에 당신은 그것을 사용하면 안 됩니다.
이 경우에는 유용하지 않지만,sample에서는 여러 개의 고유한 샘플을 원하는 경우 숫자 인수를 사용할 수 있습니다.
myArray.sample(x)또한 배열에서 x개의 임의 요소를 가져오는 데 도움이 됩니다.
myArray.sample
임의의 값 1개를 반환합니다.
myArray.shuffle.first
또한 랜덤 값 1개를 반환합니다.
배열의 랜덤 항목 수
def random_items(array)
array.sample(1 + rand(array.count))
end
가능한 결과의 예:
my_array = ["one", "two", "three"]
my_array.sample(1 + rand(my_array.count))
=> ["two", "three"]
=> ["one", "three", "two"]
=> ["two"]
다음은 여기에 게시된 답변 중 일부에 대해 수행한 벤치마크 테스트입니다.sample지속적으로 다른 것들보다 빨랐습니다.
test_arr = ["stuff", "widget", "ruby", "goodies", "java", "emerald" ]
Benchmark.ips do |x|
x.report("1 - sample") { test_arr.sample }
x.report("2 - shuffle") { test_arr.shuffle.first }
x.report("3 - length") { rand(test_arr.length) }
x.report("4 - rand rand") { test_arr.sample(1 + rand(test_arr.count)) }
x.report("5 - rand el") { test_arr[rand(test_arr.count)]}
x.report("6 - switch") {
case rand(0..test_arr.length)
when 0
test_arr[0]
when 1
test_arr[1]
when 2
test_arr[2]
when 3
test_arr[3]
when 4
test_arr[4]
when 5
test_arr[5]
end
}
x.compare!
테스트는 MacBook Pro(15인치, 2018), 2.6GHz 6코어 Intel Core i7, 32GB 2400MHz DDR4에서 실행되었습니다.
Warming up --------------------------------------
1 - sample 713.455k i/100ms
2 - shuffle 253.848k i/100ms
3 - length 489.078k i/100ms
4 - rand rand 236.396k i/100ms
5 - rand el 447.244k i/100ms
6 - switch 419.272k i/100ms
Calculating -------------------------------------
1 - sample 7.505M (± 3.2%) i/s - 37.813M in 5.044078s
2 - shuffle 2.661M (± 2.1%) i/s - 13.454M in 5.057659s
3 - length 5.021M (± 1.6%) i/s - 25.432M in 5.066159s
4 - rand rand 2.352M (± 2.4%) i/s - 11.820M in 5.029415s
5 - rand el 4.452M (± 2.2%) i/s - 22.362M in 5.025623s
6 - switch 4.324M (± 1.1%) i/s - 21.802M in 5.043294s
Comparison:
1 - sample: 7504636.7 i/s
3 - length: 5021326.6 i/s - 1.49x (± 0.00) slower
5 - rand el: 4452078.6 i/s - 1.69x (± 0.00) slower
6 - switch: 4323511.6 i/s - 1.74x (± 0.00) slower
2 - shuffle: 2661267.7 i/s - 2.82x (± 0.00) slower
4 - rand rand: 2351630.7 i/s - 3.19x (± 0.00) slower
arr = [1,9,5,2,4,9,5,8,7,9,0,8,2,7,5,8,0,2,9]
arr[rand(arr.count)]
배열에서 임의 요소를 반환합니다.
아래에 언급된 라인을 사용할 경우
arr[1+rand(arr.count)]
경우에 따라 0 또는 0 값을 반환합니다.
아래에 언급된 라인
rand(number)
항상 값을 0에서 1까지 반환합니다.
사용할 경우
1+rand(number)
그런 다음 숫자를 반환하고 arr[number]에 요소가 없을 수 있습니다.
class String
def black
return "\e[30m#{self}\e[0m"
end
def red
return "\e[31m#{self}\e[0m"
end
def light_green
return "\e[32m#{self}\e[0m"
end
def purple
return "\e[35m#{self}\e[0m"
end
def blue_dark
return "\e[34m#{self}\e[0m"
end
def blue_light
return "\e[36m#{self}\e[0m"
end
def white
return "\e[37m#{self}\e[0m"
end
def randColor
array_color = [
"\e[30m#{self}\e[0m",
"\e[31m#{self}\e[0m",
"\e[32m#{self}\e[0m",
"\e[35m#{self}\e[0m",
"\e[34m#{self}\e[0m",
"\e[36m#{self}\e[0m",
"\e[37m#{self}\e[0m" ]
return array_color[rand(0..array_color.size)]
end
end
puts "black".black
puts "red".red
puts "light_green".light_green
puts "purple".purple
puts "dark blue".blue_dark
puts "light blue".blue_light
puts "white".white
puts "random color".randColor
언급URL : https://stackoverflow.com/questions/3482149/how-do-i-pick-randomly-from-an-array
'programing' 카테고리의 다른 글
| set -onnounset을 사용할 때 변수가 Bash에 설정되어 있는지 테스트 (0) | 2023.05.17 |
|---|---|
| 긴 SQL 쿼리를 즉시 종료/정지하는 방법은 무엇입니까? (0) | 2023.05.12 |
| jquery를 사용하여 div가 있는지 확인합니다. (0) | 2023.05.12 |
| Atlas MongoDB 클라우드 서비스에 Heroku 앱 연결하기 (0) | 2023.05.12 |
| @Html.DisplayFor - 날짜 형식("mm/dd/yyyy") (0) | 2023.05.12 |