+ 1

How can I write a ruby code that takes in an array of integers and return true if any three consecutive elements sum to 7

=begin THIS ISN'T CORRECT, CAN SOMEONE EXPLAIN IT DEEPLY WHY IT ALWAYS RETURN THE DEFAULT "ELSE" TO ME? =end arr = [2,1,5,1,0] case arr when ([2 + 1 + 0] == 7) puts "False" when ([2 + 1 + 5] == 7) puts "False" when ([1 + 5 + 1] == 7) else puts "None is added up to 7" end

11th Apr 2017, 7:56 PM
Safianu Mohammed
Safianu Mohammed - avatar
1 Resposta
0
I think it's because you're testing a list with the element 7 to be the number 7, like that: [1 + 5 + 1] = [7] =/= 7 try a for loop: arr = [2,1,5,1,0] seven = false for i in (0..arr.length-3) if (arr[i] + arr[i+1] + arr[i+2]) == 7 seven = true end end puts seven
12th Apr 2017, 12:29 PM
merkrafter