ruby 如何创建返回数组中回飞棒总数的函数

2guxujil  于 2022-12-26  发布在  Ruby
关注(0)|答案(4)|浏览(97)

回旋镖是一个V形序列,可以是直立的,也可以是倒置的。具体来说,回旋镖可以定义为:长度为3的子数组,第一位和最后一位相同,中间位不同。一些回飞棒示例:

[3, 7, 3], [1, -1, 1], [5, 6, 5]

创建一个函数,返回数组中回飞棒的总数。

[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]

要知道,回飞棒可以重叠,就像这样:

[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]

示例:

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

注意:[5,5,5](三个相同的数字)不被认为是回飞棒,因为中间的数字与第一个和最后一个相同。

sr4lhrrt

sr4lhrrt1#

一些冗长的方法来做到这一点:

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
e37o9pze

e37o9pze2#

非常简单的方法(抱歉,用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]))
nfeuvbwi

nfeuvbwi3#

def count_boomerangs(arr)
  arr.each_cons(3).count { |a,b,c| a == c && a !=b }
end
count_boomerangs [3, 7, 3, 2, 1, 5, 1, 2, 2, -2, 2] #=> 3
count_boomerangs [1, 7, 1, 7, 1, 7, 1]              #=> 5
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

请参见可枚举的#each_cons。

py49o6xq

py49o6xq4#

get_bommerangs = lambda arr: sum(
    arr[i - 1] == arr[i + 1] and arr[i - 1] != arr[i] for i in range(1, len(arr) - 1)
)

bommerangs = get_bommerangs([2, 1, 2, 3, 3, 4, 2, 4])

相关问题