w3resource

Ruby Array Exercises: Check whether a given array of integers contains two 6's next to each other, or there are two 6's separated by one element

Ruby Array: Exercise-39 with Solution

Write a Ruby program to check whether a given array of integers contains two 6's next to each other, or there are two 6's separated by one element, such as {6, 2, 6}.

Ruby Array Exercises: Check whether a given array of integers contains two 6's next to each other, or there are two 6's separated by one element

Ruby Code:

def check_array(nums)
   i = 0;
   while i < nums.length
        if(nums[i] == 6)
    		if(nums[i+1] == 6)
				return true
			elsif(i < nums.length - 2 && nums[i+2] == 6)
				return true
			end	
	    end
	i = i + 1
   end
   return false
end
print check_array([6, 3, 6, 5]),"\n"
print check_array([6, 6, 5, 9]),"\n"
print check_array([6, 4, 5, 6]),"\n"

Output:

true
true
false

Flowchart:

Flowchart: Check whether a given array of integers contains two 6's next to each other, or there are two 6's separated by one element

Ruby Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Ruby program to check whether a given array contains a 3 next to a 3 or a 5 next to a 5, but not both.
Next: Write a Ruby program to check whether there is a 2 in the array with a 3 some where later in a given array of integers.

What is the difficulty level of this exercise?