Ruby 如何';逆和';用红宝石?
我不知道如何用正确的数学术语来称呼它。考虑一个两位数的方法:Ruby 如何';逆和';用红宝石?,ruby,math,Ruby,Math,我不知道如何用正确的数学术语来称呼它。考虑一个两位数的方法: def num_of_sum(total, group_count) end 其中,total为整数,group\u count为整数 我如何得到一组长度为group\u count-的整数的“很好”分组数组,这些整数的总和一直到total 我的规格如下所示: describe "number to sum of" do it "grabs all numbers" do expect(num_of_sum(10,
def num_of_sum(total, group_count)
end
其中,total
为整数,group\u count
为整数
我如何得到一组长度为group\u count
-的整数的“很好”分组数组,这些整数的总和一直到total
我的规格如下所示:
describe "number to sum of" do
it "grabs all numbers" do
expect(num_of_sum(10, 2)).to eq([5,5])
expect(num_of_sum(10, 3)).to eq([3,3,4])
expect(num_of_sum(20, 3)).to eq([6,7,7])
expect(num_of_sum(100, 3)).to eq([33,33,34])
expect(num_of_sum(100, 2)).to eq([50,50])
end
end
我试过这个,效果很好:
def num_of_sum(total, in_groups_of)
result = []
section_count ||= (total.to_f / in_groups_of.to_f).round
while(total > 0)
total -= section_count
if (total - section_count) < 0 && (total + section_count).even?
section_count += total
total -= total
end
result << section_count
end
result
end
我需要数组包含尽可能接近彼此的数字。但该数组仅限于组计数的长度
有人知道这个词的数学名称吗,这样我可以更准确地搜索它吗?我不知道它叫什么,但这里有一个解决方案:
def num_of_sum sum, count
result = [i = sum / count] * count # prepare an array e.g. [3,3,3] for 10,3
result[sum - i * count..-1] + # these should be left intact
result[0...sum - i * count].map { |i| i + 1 } # these are ++’ed
end
希望有帮助。一个简单的实现是这样的:
让我们以(20,3)
为例。因此,您需要三个数字
20 / 3 # => 6
这是您的“基本”值。创建一个包含三个6的数组,[6,6,6]
。那你就18岁了。现在,您必须尽可能平均地分配剩余的2个。例如,枚举数组元素并将每个元素递增1,直到没有值可分配为止。结果是[7,7,6]
。我想这已经足够好了
可能的(工作)实施:
def breakdown(total, group_count)
avg_value, extra = total.divmod(group_count)
result = Array.new(group_count, avg_value)
extra.times do |i|
result[i] += 1
end
result
end
breakdown(10, 2) == [5, 5] # => true
breakdown(10, 3) == [4, 3, 3] # => true
breakdown(20, 3) # => [7, 7, 6]
这个的数学术语是一个整数
一种更直接的方法是观察到,如果用组数对总数进行整数除法(向下舍入),那么您的总和将短于组数的mod number总和,因此您只需要在整个数组中分配该数量:
def even_partition(total, number_of_groups)
quotient, remainder = total.divmod(number_of_groups)
(number_of_groups-remainder).times.collect {quotient} +
remainder.times.collect { quotient + 1}
end
将文档发送到和另一种方式:
def floors_then_ceils(n, groups)
floor, ceils = n.divmod(groups)
groups.times.map { |i| (i < groups-ceils) ? floor : floor + 1 }
end
floors_then_ceils(10, 3)
#=> [3, 3, 4]
floors_then_ceils(9, 3)
#=> [3, 3, 3]
经过一番费解,我终于想出了这个答案!:)感谢您,尽管阵列添加行可以节省15个字节。[d]*(g-m)+[d+1]*m
可以节省更多。:-)这将是第一个喜欢steenslag的@Fietsband。
def n_parts(num, groupcount)
div, mod = num.divmod(groupcount)
Array.new(groupcount-mod, div) + Array.new(mod, div+1)
end
n_parts(100,3) => [33, 33, 34]
def floors_then_ceils(n, groups)
floor, ceils = n.divmod(groups)
groups.times.map { |i| (i < groups-ceils) ? floor : floor + 1 }
end
floors_then_ceils(10, 3)
#=> [3, 3, 4]
floors_then_ceils(9, 3)
#=> [3, 3, 3]
Array.new(groups-ceils, floor).concat(Array.new(ceils, floor+1))