如何创建整数数组的直方图?例如:
data = [0,1,2,2,2,2,2,3,3,3,3,3,3,4,4,4,4,5,5,6,6,6,7,7,7,7,7,8,9,9,10]
Run Code Online (Sandbox Code Playgroud)
我想基于有多少项有用于创建直方图0,1,2,等等.在Ruby中有一个简单的方法吗?
输出应该是两个数组.第一个数组应包含组(bin),第二个数组应包含出现次数(频率).
对于data上面给出的,我希望以下输出:
bins # => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
frequencies # => [1, 1, 5, 6, 4, 2, 3, 5, 1, 2, 1]
Run Code Online (Sandbox Code Playgroud) 我正在迭代一个相当大的数组的2个元素的组合.在计算组合的元素时,我发现了一些奇怪的东西.以下示例显示了我的意思:
[1] pry(main)> 10000.times.to_a.combination(2).count
=> 49995000 # correct
[2] pry(main)> 100000.times.to_a.combination(2).count
=> 704982704 # wrong, should be 4999950000
[3] pry(main)> count = 0; 100000.times.to_a.combination(2).each { count+=1 }; count
=> 4999950000 # correct
Run Code Online (Sandbox Code Playgroud)
我用wolframalpha仔细检查了结果:
我的问题是,为什么Array#count在这种情况下不可靠?
另请参阅https://ruby-doc.org/core-2.2.0/Array.html#method-i-combination和https://ruby-doc.org/core-2.2.0/Array.html#method -i-count.
非常感谢.