获取数组中给定长度的范围总数

时间:2013-06-25 17:46:16

标签: ruby arrays

我有一个包含12个元素的数组total,每个元素代表和int。例如total[0] = 1。我有另一个remaining - total数组occupied spacesremaining的元素数量会减少total

我想编写一个方法,可以在total中查找数组中连续整数之间存在> = size间隙的情况。例如:

If `foo.total = [1,2,6,7,8,9,]`
then when I call `foo.number_of_slots_available(3)`
I get `2` (because 3,4,5 is not included and 10,11,12 is not included)

以下是我方法的开头:

def number_of_slots(size)
  total_array = (1..12).to_a
  occupied_spaces = some_map.to_a
  remaining_array = total_array - occupied_spaces
  return ????
end 

3 个答案:

答案 0 :(得分:2)

Enumerable#chunk是最好的方法。看下面。

arr = [1,2,6,7,8,9]
rng = (1..12).to_a

rng.chunk { |i| arr.include? i }.to_a
# => [[true, [1, 2]],
#     [false, [3, 4, 5]],
#     [true, [6, 7, 8, 9]],
#     [false, [10, 11, 12]]]

rng.chunk { |i| arr.include? i }.count{|j| j[0] == false} 
# => 2 

修改

  

“我想编写一个方法,可以查看数组中连续整数之间存在> =大小差距的实例

arr = [1,2,3,6,7,8,9,10,11]
rng = (1..15).to_a

rng.chunk { |i| arr.include? i }.to_a
# => [[true, [1, 2, 3]],
#     [false, [4, 5]],
#     [true, [6, 7, 8, 9, 10, 11]],
#     [false, [12, 13, 14, 15]]]

rng.chunk { |i| arr.include? i }.count{|j| j[0] == false and j[1].size >= 3 } 
# => 1
rng.chunk { |i| arr.include? i }.count{|j| j[0] == false and j[1].size >= 2 } 
# => 2 
# J[1] is the array,whose size is the actual gap size.

答案 1 :(得分:0)

如果排序total是一个简单的算法,应该是这样的(我可能有一些语法错误):

def containsGaps(total, gap)
   int i = 0;
   int count = 0;
   while i < total.length -1 do
     if total[i+1] - total[i] >= gap then count++;
   end 
   return count;
end

你的回归可能是:

return containsGaps(total_array, size);

答案 2 :(得分:0)

这是我发现的一种方式。我修改了方法,在数组中添加了一些与大小一起传递的方法。

#!/usr/bin/ruby

arr = [1,2,6,7,8,9]
bar = [1,2,3,6,7,10]

def number_of_slots(arr, size)
  count = 0
  range = (1..12).to_a
  # arr.sort! (if the array is not always sorted)
  range.each_cons(size) do |chunk|
    if (chunk & arr).size == 0
      count += 1
    end
  end
  count
end

puts number_of_slots(arr, 3)
puts number_of_slots(bar, 2)

输出:

2
3