HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyMinor

Scan array for 3 consecutive numbers that sum to 7

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
scanarraynumbersthatforsumconsecutive

Problem

Write a function lucky_sevens?(numbers), which takes in an array of
integers and returns true if any three consecutive elements sum to 7.

lucky_sevens?([2,1,5,1,0]) == true # => 1 + 5 + 1 == 7
lucky_sevens?([0,-2,1,8]) == true # => -2 + 1 + 8 == 7
lucky_sevens?([7,7,7,7]) == false
lucky_sevens?([3,4,3,4]) == false




Make sure your code correctly checks for edge cases (i.e. the first
and last elements of the array).

While my code does seem to work (I did some test cases), I know it can be improved. There's no reason to have double puts and return statements. I'm also wondering if there are general improvements to the syntax itself that can make it much more readable.

def lucky_sevens?(numbers)
  i = 0
  while i < numbers.length - 2

    if numbers[i] + numbers[i + 1] + numbers[i + 2] == 7
        puts true
        return true
    end
    i+=1
    end 
    puts false
    return false
end

Solution

Your code, is way too imperative to be idiomatic Ruby.

The only reasonable improvement is re-writing it from scratch:

def lucky_sevens?(numbers)
  groups_of_three(numbers)
    .any? {|group| group.inject(:+) == 7}
end


Knowing that inject(:+) means sum, this reads like English. Implementing groups_of_three is left as an exercise for the reader.

Code Snippets

def lucky_sevens?(numbers)
  groups_of_three(numbers)
    .any? {|group| group.inject(:+) == 7}
end

Context

StackExchange Code Review Q#108207, answer score: 4

Revisions (0)

No revisions yet.