1

我有一个包含 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 
4

3 回答 3

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.
于 2013-06-25T18:00:48.297 回答
0

If totalis sorted 是一个简单的算法,应该是这样的(我可能有一些语法错误):

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);
于 2013-06-25T18:16:00.513 回答
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
于 2013-06-25T18:32:44.520 回答