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
}
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With