ruby - 计算超市排队时间

Sam*_*m P 3 ruby arrays methods event-simulation

所以假设超市里有一个自助结账柜台排队。我正在尝试编写一个函数来计算所有客户结账所需的总时间!

输入:

客户:代表队列的正整数数组。每个整数代表一个客户,其值是他们需要结账的时间。

n:正整数,结账台数。

输出:

该函数应返回一个整数,即所需的总时间。例子:

queue_time([5,3,4], 1)
# should return 12
# because when n=1, the total time is just the sum of the times

queue_time([10,2,3,3], 2)
# should return 10
# because here n=2 and the 2nd, 3rd, and 4th people in the 
# queue finish before the 1st person has finished.

queue_time([2,3,10], 2)
# should return 12
Run Code Online (Sandbox Code Playgroud)

只有一个队列服务多个收银台,队列的顺序永远不会改变。队列中的最前面的人(数组/列表中的第一个元素)一有空就进入直到。我试过这个,但它不能正常工作,我不知道如何让下一个人进入,直到它打开。

def queue_time(customers, n)
  if customers == []
    n=0
  else
    x= customers.reduce(:+) / n 
    if x < customers.max
      customers.max
    else 
      x
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

例如,测试

customers = [751, 304, 2, 629, 36, 674, 1] 
n = 2
expected: 1461, instead got: 1198
Run Code Online (Sandbox Code Playgroud)

. 谢谢 :-)

Ste*_*fan 5

给定输入:

customers = [751, 304, 2, 629, 36, 674, 1]
n = 2
Run Code Online (Sandbox Code Playgroud)

你可以创建一个数组:(每个都是一个数组本身)

tills = Array.new(n) { [] }
#=> [[], []]
Run Code Online (Sandbox Code Playgroud)

现在,对于每个客户,您将其价值添加到最短的时间:

customers.each do |customer|
  tills.min_by(&:sum) << customer
end
Run Code Online (Sandbox Code Playgroud)

最后,这给了你:

tills
#=> [[751, 36, 674], [304, 2, 629, 1]]
Run Code Online (Sandbox Code Playgroud)

第一个总和为 1,461。