Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if array of integers increments in Ruby

Tags:

arrays

ruby

I want to check if an arrays values once sorted are incrementing by 1

For example

[1, 2, 3, 4, 5] = TRUE
[1, 2, 8, 9, 10] = FALSE

Any suggestions are much appreciated

like image 746
Julio Avatar asked Apr 15 '11 22:04

Julio


2 Answers

array = [1,2,4,3]
array.sort.each_cons(2).all? { |x,y| y == x + 1 }
like image 145
fgb Avatar answered Oct 30 '22 03:10

fgb


This one doesn't require sort.

a = [2, 8, 1, 9, 10]
b = a.dup
x = b.delete(b.min)
nil while b.delete(x+=1)
b.empty?
like image 31
sawa Avatar answered Oct 30 '22 01:10

sawa