Ruby 求数组分组且每组元素数量随机算法

miclle · 2013年09月28日 · 最后由 cisolarix 回复于 2014年01月04日 · 2823 次阅读

目前自己写的版本

def sample_group(array, group_array = [2,3,4,5])
    group = []
    while array.size > 0
      rand = group_array.sample
      group << array.first(rand)
      array = array.drop(rand)
    end
    group
  end

测试数组:[1,2,3,4,5,6,7,8,9] 结果:

[[1, 2, 3, 4], [5, 6, 7, 8], [9]]
[[1, 2], [3, 4], [5, 6, 7, 8, 9]]
[[1, 2], [3, 4, 5], [6, 7, 8, 9]]
p a.slice!(0, rand(a.size) + 1) while a.size > 0
a.chunk {|n| n % (rand(a.size) + 1) == 0 }.each {|_, ary| p ary}

有点意思。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号