小编Sam*_*m P的帖子

ruby - 计算超市排队时间

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

输入:

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

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 …
Run Code Online (Sandbox Code Playgroud)

ruby arrays methods event-simulation

3
推荐指数
1
解决办法
140
查看次数

如何在数组中找到唯一的数字并在 ruby​​ 中仅返回该数字?

有一个包含一些数字的数组。除了 1 之外,所有数字都相等。我正在尝试得到这种类型的东西:

find_uniq([ 1, 1, 1, 2, 1, 1 ]) == 2

find_uniq([ 0, 0, 0.55, 0, 0 ]) == 0.55
Run Code Online (Sandbox Code Playgroud)

我试过这个:

def find_uniq(arr)
   arr.uniq.each{|e| arr.count(e)}
end
Run Code Online (Sandbox Code Playgroud)

它为我提供了数组中的两个不同值,但我不确定如何选择唯一的。我可以使用某种计数吗?谢谢!

这有效:

def find_uniq(arr)
  return nil if arr.size < 3
  if arr[0] != arr[1]
    return arr[1] == arr[2] ? arr[0] : arr[1]
  end
  arr.each_cons(2) { |x, y| return y if y != x }
end
Run Code Online (Sandbox Code Playgroud)

谢谢 pjs 和卡里·斯沃夫兰。

ruby arrays methods unique

0
推荐指数
1
解决办法
1190
查看次数

标签 统计

arrays ×2

methods ×2

ruby ×2

event-simulation ×1

unique ×1