减少数组以设置项目数?

时间:2014-01-03 19:42:26

标签: ruby arrays

我有一个包含300个项目的Ruby数组。我想将该数组减少到一定数量的项目,从数组中均匀选取。

数组中的项目数量每次都不一样,所需的项目数量也不一样。

这样的事情:

arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
num_of_items = 4
final_arr = [0, 5, 10, 15]

3 个答案:

答案 0 :(得分:1)

如果您从此数组中随机选择一定数量的项目,请使用sample -

$ arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
$ arr.sample(5)
 => [1, 3, 5, 4, 12]
$ arr.sample(5)
 => [15, 6, 13, 5, 11]

答案 1 :(得分:1)

您可以使用Enumerable#each_slice

arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
#=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
num_of_items = 4
#=> 4
arr.each_slice(arr.size/num_of_items + 1).map(&:first)
#=> [0, 5, 10, 15] 

arr = (0..16).to_a
#=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]

num_of_items = 5
#=> 5
arr.each_slice(arr.size/num_of_items + 1).map(&:first)
#=> [0, 4, 8, 12, 16]

OR

Numeric#step

arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
#=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
num_of_items = 4
#=> 4
arr.first.step(arr.size, arr.size/num_of_items + 1).map { |i| arr[i] }
#=> [0, 5, 10, 15]
arr = (0..16).to_a
#=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]

num_of_items = 5
#=> 5
arr.first.step(arr.size, arr.size/num_of_items + 1).map { |i| arr[i] }
#=> [0, 4, 8, 12, 16]

答案 2 :(得分:0)

如果您的算法的目标完全如上所示,您可以使用in_groups_of,然后获取每个子数组的第一个元素:

1.9.3p484 :014 > num_of_items = 5
 => 5 

1.9.3p484 :011 > arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
 => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] 

1.9.3p484 :012 > arr.in_groups_of(num_of_items)
 => [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, nil, nil, nil, nil]] 

1.9.3p484 :013 > arr.in_groups_of(num_of_items).map(&:first)
 => [0, 5, 10, 15]