1

12 個の要素の配列totalがあり、各要素は int を表します。たとえばtotal[0] = 1。-という別の配列remainingがあります。 の要素が少なくなります。totaloccupied spacesremainingtotal

total配列内の連続する int 間に >=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

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 に答える