将数字分为相等的部分或最接近的部分 [英] Split number into equal parts or what's closest to that

查看:81
本文介绍了将数字分为相等的部分或最接近的部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个随机数,我希望将其分成几部分(加数),条件是部分不能超过20,并且各部分必须尽可能地彼此靠近.

例如,如果我的随机数为41,加数应为14、14、13.如果随机数为60,加数应为20、20、20.如果随机数是 21,加数应该是 11 和 10等等.

我的代码是用Ruby(Rails)编写的,所以我很希望得到一个答案,该答案可以在Ruby中有效地实现此目的,尽管也欢迎使用伪代码或其他编程语言.

这是我为数组找到的,但是我真的需要用数字来做这件事:"

您可以使用此很酷的单行代码.它应该可以除以您想要的任何数量的片段:

  def split_into n,p[n/p +1] *(n%p)+ [n/p] *(p-n%p)结尾打印(split_into 32,3)#=>[11、11、10] 

它基本上将数字分成相等的部分,然后将剩余部分除以第一个部分(每个为1).事实就是您可以将数组相乘并相加,就像这样:

  [1] * 3#=>[1,1,1][1] + [2]#=>[1,2] 

EDIT :考虑到每件作品的数量应小于20的规则,您可以按照@Cary Swoveland的建议计算理想的作品数量:

  p =(n/20.0).ceil 

I have a random number and I would like to divide it into several parts (addends) with conditions that a part can not be more than 20 and the parts must be as close to each other as possible.

For example, if my random number is 41, addends should be 14, 14, 13. If random number is 60 addends should be 20, 20, 20. If random number is 21 addends should be 11 and 10 and so on.

My code is in Ruby (Rails) so I would most appreciate an answer which gives an efficient implementation of this in Ruby, though pseudo-code or other programming languages are welcome as well.

This is what I found for arrays but I really need to do this thing with numbers: "Splitting an array into equal parts in ruby"

解决方案

You can use this cool one-liner. It should work dividing by any amount of pieces you want:

def split_into n, p
    [n/p + 1] * (n%p) + [n/p] * (p - n%p)
end

print (split_into 32, 3) # => [11, 11, 10]

It basically divides the number into equal parts and splits the remainder by the first ones (1 for each). That and the fact that you can multiply and add arrays together, like so:

[1] * 3     # => [1, 1, 1]
[1] + [2]   # => [1, 2]

EDIT: Considering the rule that each piece should be smaller than 20, you can calculate the ideal amount of pieces as suggested by @Cary Swoveland:

p = (n / 20.0).ceil

这篇关于将数字分为相等的部分或最接近的部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆