配列がソート済みかどうかを調べるコードです。(昇順)
module Enumerable
def sorted?
each_cons(2).all? {|a, b| a <= b }
end
def sorted_by?
each_cons(2).all? {|a, b| yield(a) <= yield(b) }
end
end
p [3,2,1].sorted? #=> false
p [1,2,3].sorted? #=> true
p ['1','2','13'].sorted? #=> false
p ['1','2','13'].sorted_by?(&:to_i) #=> true
each_cons
で要素を2つずつ取り出し <=
を使って値の比較を行っています。比較を行った結果が全て true なら昇順で並んでいます。降順で並んでいるかどうかを確かめるときには >=
を使用します。
追記
@scivola さんのコメントを元に修正を行いました。ありがとうございます
使い道
class Array
def bogosort!
shuffle! until sorted?
self
end
end
p [*1..5].shuffle.bogosort! #=> [1, 2, 3, 4, 5]
bsearch
前のチェック
ary = [0, 4, 7, 10, 12].shuffle
ary.sort! unless ary.sorted?
p ary.bsearch {|x| x >= 4 } # => 4
etc...
参考サイト
https://docs.ruby-lang.org/ja/latest/class/Array.html
https://docs.ruby-lang.org/ja/latest/class/Enumerator.html