def almost_increasing_sequence?(sequence)
return false if sequence.length < 2
return true if sequence.length == 2
max1 = sequence[0] # maximum up to the previous item
max2 = sequence[1] # maximum up to the current item
count = 0
sequence[1..-1].each_with_index do |item, index|
prev = sequence[index]
nxt = sequence[index+2]
print(max1,' ',max2,' ',prev,' ',item,' ',nxt,"\n")
if prev >= item
count += 1
return false if count > 1
if index > 0 and item <= max1 and nxt and nxt <= max2
return false
end
end
max1 = prev if prev > max1
max2 = item if item > max2
end
return count == 1
end
Some tests courtesy of @AJFaraday (corrected & extended):
[
[[], false],
[[1], false],
[[1, 2], true],
[[1, 2, 3, 4, 99, 5, 6], true],
[[1, 3, 2], true],
[[10, 1, 2, 3, 4, 5], true],
[[0, -2, 5, 6], true],
[[1, 2, 3, 4, 3, 6], true],
[[1, 1], true],
[[100, 200, 300, 400, 99, 500, 600], true],
[[1, 2, 1, 2], false],
[[1, 2, 3, 4, 5, 3, 5, 6], false],
[[40, 50, 60, 10, 20, 30], false],
[[1, 3, 2, 1], false],
[[1, 4, 10, 4, 2] , false],
[[1, 1, 1, 2, 3], false],
[[10, 1, 2, 3, 4, 5, 6], true],
[[5, 7, 8, 90, 91, 92, 93], false],
[[2,3,1,2], false],
[[1,2,1,2], false],
[[1, 2, 3, 4, 5, 3, 5, 6], false],
[[40, 50, 60, 10, 20, 30], false]
].each do |array, expected|
if almost_increasing_sequence?(array) != expected
puts "FAIL Should get #{expected} for #{array}"
else
puts "PASS"
end
end