w3resource

Ruby Array Exercises: Check whether there is a 2 in the array with a 3 some where later in a given array of integers

Ruby Array: Exercise-40 with Solution

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.

Ruby Array Exercises: Check whether there is a 2 in the array with a 3 some where later in a given array of integers

Ruby Code:

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

Output:

true
true
true
false
false

Flowchart:

Flowchart: Check whether there is a 2 in the array with a 3 some where later in a given array of integers

Ruby Code Editor:

Contribute your code and comments through Disqus.

Previous: 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}.
Next: Write a Ruby program to check whether the value 2 appears in a given array of integers exactly 2 times, and no 2's are next to each other.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.