Ruby 每个逻辑问题
我正在尝试解决七周七种语言
打印数组的内容 十六个数字,四个数字在一个 时间,仅使用
each
这是我想出的,这可以用简单的方式完成还是可以做得更好?
a = (1..16).to_a
i = 0
j = []
a.each do |item|
i += 1
j << item
if(i % 4 == 0)
p j
j = []
end
end
它可以在一行中使用 each_slice
完成
a.each_slice(4){|x| px}
I am trying to solve a simple Ruby problem from Seven Languages in Seven Weeks
Print the contents of an array of
sixteen numbers, four numbers at a
time, using justeach
Here is what I came up with, can this be done in a simple way or make it better??
a = (1..16).to_a
i = 0
j = []
a.each do |item|
i += 1
j << item
if(i % 4 == 0)
p j
j = []
end
end
It can done using each_slice
in one line
a.each_slice(4){|x| p x}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
Teja,你的解决方案没问题。由于您需要使用每一个,算法的复杂性将受到数组大小的限制。
我想出了下面的解决方案。它与你的想法相同,只是它不使用 aux var (j) 来存储部分结果。
Teja, your solution is ok. As you need to use each, the algorithm complexity is going to be bounded to the size of your array.
I came up with the solution bellow. It is the same idea of yours except that it does not use an aux var (j) to store partial results.
格伦·麦克唐纳的很短,但它使用了不允许的切片(记住,只有每个切片)。这是我的:
它也适用于其他数组大小,这里应用于 18 大小的数组:
Glenn Macdonald's is short, but it uses slice which is not allowed (only each, remember). Here is mine:
which also works well for other array sizes, here applied to an 18 sized array:
我认为这应该适用于任何大小的数组和任何块大小的 x:
I think this ought to work for any size array and any chunk-size x:
试试这个:
Try this:
该问题并未说明 16 个数字的数组是连续的或从 1 开始...让我们创建一个适用于任何 16 个数字的解决方案。
The problem did not state that the array of sixteen numbers were sequential or started at one... let's created a solution that works for any 16 numbers.
我使用了类似于 Miguel 的东西,尽管他的更干净:
I used something similar to Miguel's, though his is cleaner:
您是否被禁止使用
each_with_index
?如果没有,则以@Miguel的答案为基础:我还用听起来像英语的东西替换了
i % 4 == 0
(“i modulo 4 is zero”)Are you forbidden from using
each_with_index
? If not, building on @Miguel's answer:I also replaced
i % 4 == 0
with something that sounds like English ("i modulo 4 is zero")没有切片的单行:
A one-liner without slice: