arrays - 从Ruby中的整数除法制作数组的正确方法
问题描述
tl;博士我想从除以 5 个结果中创建一个数组:
20 => [5,5,5,5]
16 => [5,5,5,1]
7 => [5,2]
我当前的实现很简单但太大了。我怎样才能使它更简单和更短?
max_count = 5
total_count = input_value
count_array = []
div = total_count / max_count
mod = total_count % max_count
div.times { count_array << max_count }
count_array << mod unless mod == 0
解决方案
- 你不需要
total_count
。 div.times { count_array << max_count }
是[max_count] * count_array
- 使用 splat,我们可以进一步简化它
max_count = 5
[*[max_count] * (input_value / max_count), input_value % max_count] - [0]
或者,使用divmod
max_count = 5
n, mod = input_value.divmod(max_count)
[*[max_count] * n, mod] - [0]
最后一行也可以写成:
(Array.new(n) { max_count } << mod) - [0]
或者正如 Stefan 在评论中建议的那样,使用Numeric#nonzero?:
Array.new(n, max_count).push(*mod.nonzero?)
推荐阅读
- sql-server - 插入和删除同时出现SQL死锁
- ios - 自定义字体不能以编程方式在 Swift 中工作,但可以与 xib/Storyboard 一起使用
- javascript - 使用 Webpack 创建 AudioWorlet 时出现 DOMException 错误
- javascript - 动态更新对象中的 Getter 函数
- visual-studio - 如何在预构建事件中将现有文件添加到 Visual Studio 中的项目?
- javascript - 动态改变网格 React 的结构
- api - 使用 Postman 时在 URL 中包含请求参数
- quickbooks - QuickBooks 桌面集成
- python - Python:反向数组期间的问题 - 变量值更改而不重新分配
- java - Android根据第一个单词读取文本文件并存储到变量中