Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check that an array is increasing [duplicate]

Tags:

ruby

I am just wondering if there is a way to check if the array is increasing ?

Here is my solution, but I am searching for more beautiful way:

n = - 1

@arr.flatten.each { |e| 
    return false if e < n
    n = e
}
like image 670
ceth Avatar asked Mar 25 '13 12:03

ceth


2 Answers

You can do the following:

> arr = [1, 4, 5, 6]
> arr.each_cons(2).all? { |a, b| (a <=> b) <= 0 }
 => true

You can add it to Array class

class Array
  def is_sorted?
    each_cons(2).all? { |a, b| (a <=> b) <= 0 }
  end
end
like image 168
toch Avatar answered Sep 29 '22 20:09

toch


Try this,

if @arr.sort.uniq == @arr
  # array is increasing
else 
  # array not increasing
end

This will sort the array and drop duplicate values, then compare it to the original array.

If your original array is always increasing, it should match the sorted, de-duplicated array.

EDIT:

While this solution gives the desired result, this is not the best solution (see comment below). I would suggest going with toch's solution instead.

like image 44
Sam Avatar answered Sep 29 '22 20:09

Sam