圆形阵列切片 [英] Circular array slicing

查看:47
本文介绍了圆形阵列切片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组,其中元素数目为0..n。例如:

I have an array with a varying number of elements 0..n elements. An example could be:

a = [0,1,2,3,4,5,6,7,8,9]

在一个迭代过程中,我想在数组中移动光标并切出一个最大元素数。如果我到达数组的末端,它应该重新开始并从头开始重新选择:

In an iterative process, I would like to move a cursor in the array and slice out a max number of elements. If I reach the "end" of the array, it should start over and pick from the beginning again:

类似这样的东西:

4.times do |i|
  a.slice(i * 3, 3)
end
# i = 0 => [0,1,2]
# i = 1 => [3,4,5]
# i = 2 => [6,7,8]
# i = 3 => [9,0,1]
# ...

但是最后输出 i = 3 产生 [9] ,因为 .slice 不起作用

However the last output i = 3 produces [9] as .slice does not do exactly what I want.

推荐答案

您可以使用 周期

You could use cycle:

a.cycle.each_slice(3).take(4)
#=> [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 0, 1]]

这篇关于圆形阵列切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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