开发者

how to get an order-specified subset of an array of variable length from an array of variable length?

I have an array of objects of variable length n. Defined by the number of records in my database.

I need a function to grab subsets (keeping the objects in order and always beginning at index 0) of the array of specified length 开发者_如何学Cm where m can be any integer I pass in.

e.g. if n = 10 and m = 4

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

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

So, I need to programmatically be able to say, "Give me the i-th subset of length m from an array, given the array is length n." Using the previous example: "Give me the second subset of length four from foo" => returns the items at positions [4, 5, 6, 7].

I hope that made sense. Assistance with a ruby solution would be much appreciated! thx!


   foo.each_slice(subset_length).to_a[subset_index]

e.g. foo.each_slice(4).to_a[2] returns "the second subset of length four from foo".


You can use Enumerable#each_slice:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜