ruby - Given integers how do I find asc and desc sequences of three? -
i have integers i.e. 9
, 5
, 4
, 3
, 1
, 6
, 7
, 8
. want return index sequence of 3 descending or ascending integers exists. in example above indices 1
, 5
. ruby code this?
def seq array = [9,5,4,3,1,6,7,8] array.each_with_index |val, index| if (val < (array[index + 1]).val < (array[index + 1]).val) puts "#{index}" # skip 2 indexes end end
i think logic behind solution correct, syntax pretty far off valid ruby.
here pair of pretty verbose solutions (hopefully) obvious:
numbers = [9, 6, 5, 4, 3, 1, 6, 7, 8] # find non-overlapping sets = 0 until > numbers.length - 2 a, b, c = numbers[i..i + 2] if (a - b == b - c) && (a - b).abs == 1 puts "#{i} (#{a},#{b},#{c})" # skip next 2 indexes += 3 else += 1 end end # find overlapping sets (same solution, don't skip indexes) (0...numbers.length - 2).each |i| a, b, c = numbers[i..i + 2] if (a - b == b - c) && (a - b).abs == 1 puts "#{i} (#{a},#{b},#{c})" end end
Comments
Post a Comment