A boomerang is a V-shaped sequence that is either upright or upside down. Specifically, a boomerang can be defined as: sub-array of length 3, with the first and last digits being the same and the middle digit being different. Some boomerang examples:
[3, 7, 3], [1, -1, 1], [5, 6, 5]
Create a function that returns the total number of boomerangs in an array. To illustrate:
[3, 7, 3, 2, 1, 5, 1, 2, 2, -2, 2]
# 3 boomerangs in this sequence: [3, 7, 3], [1, 5, 1], [2, -2, 2]
Be aware that boomerangs can overlap, like so:
[1, 7, 1, 7, 1, 7, 1]
# 5 boomerangs (from left to right): [1, 7, 1], [7, 1, 7], [1, 7, 1], [7, 1, 7], and [1, 7, 1]
Examples:
count_boomerangs([9, 5, 9, 5, 1, 1, 1]) ➞ 2
count_boomerangs([5, 6, 6, 7, 6, 3, 9]) ➞ 1
count_boomerangs([4, 4, 4, 9, 9, 9, 9]) ➞ 0
Note: [5, 5, 5] (triple identical digits) is NOT considered a boomerang because the middle digit is identical to the first and last.
Very simple approach (sorry, in Python):
def boomerangs(l):
count = 0
for i in range(len(l) - 2):
if l[i] == l[i+2] and l[i] != l[i+1]:
count += 1
return count
print(boomerangs([3, 7, 3, 2, 1, 5, 1, 2, 2, -2, 2]))
print(boomerangs([1, 7, 1, 7, 1, 7, 1]))
Some verbose way to do this:
class Array
def same_values?
self.uniq.length == 1
end
end
def find_boomerangs(arr)
split_amount = 3 # count of a possible boomerang
scan_amount = split_amount - 1 # scanning by index for array
new_arr = []
arr.each_with_index { |_, indx| # we only care for the indx
end_of_indx = indx + scan_amount
arry = arr[indx .. end_of_indx] # collect new possible boomerang from array
next unless arry.count == split_amount # only check if possible boomerang is length of three
new_arr << arry if arry.values_at(0, -1).same_values? && !arry.values_at(0, 1).same_values? # checks that the values at the start and end are the same and that the middle value is not the same as the first
}
new_arr # holds the boomerangs | call .count if you want the count
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With