當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Ruby Array bsearch_index()用法及代碼示例


Array#bsearch_index():bsearch_index()是一個Array類方法,用於查找滿足給定條件的數組值的索引。它的複雜度為O(log n),其中n是數組大小。此方法可以同時在兩種模式下工作-find-minimum和find-any模式。

用法: Array.bsearch_index()

參數: 
- Arrays to search elements. 
- condition block

返回: Index value of the array element that satisfy the given condition

代碼#1:bsearch_index()方法示例

# Ruby code for bsearch_index() method 
   
# declaring array 
a = [1, 2, 3, 4] 
   
# declaring array 
b = [111.11, 2.5, 4.3, 2.224] 
  
# array that meets the condition 
puts "search:#{a.bsearch_index {|x| x >=4 }}\n\n"
  
puts "search:#{b.bsearch_index {|x| x >=3 }}\n\n"
  
puts "search:#{a.bsearch_index {|x| x >=2 }}\n\n"
  
puts "search:#{b.bsearch_index {|x| x >=2 }}\n\n"

輸出:


search:3

search:2

search:1

search:0

代碼2:bsearch_index()方法示例

# Ruby code for bsearch_index() method 
   
# declaring array 
a = [1, 2, 3, 4] 
   
# declaring array 
b = [111.11, 2.5, 4.3, 2.224] 
  
# array that meets the condition 
puts "search:#{a.bsearch_index {|x| 1 - x / 4  }}\n\n"
  
puts "search:#{b.bsearch_index {|x| 2*x > 1 }}\n\n"

輸出:

search:3

search:0


相關用法


注:本文由純淨天空篩選整理自mayank5326大神的英文原創作品 Ruby | Array bsearch_index() operation。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。