Ruby 求算法:从随机长度数组中均匀的取对象!!!!

egg_show · March 23, 2014 · Last by egg_show replied at March 24, 2014 · 2366 hits

一个长度不固定的数组参数,在数组中取 7 个对象,要求这 7 个对象是均匀分布在数组中的,数组首尾 2 个对象必须取,如取数组下标为 0,4,8,12,16,20,25 这样的,不一定要完全按照这样,比如数组长度只有 8,就随机取 7 个就是了,尽量均匀的去,求解!求解!求解!

class Array
  def average_samples(s_count)
    return clone if size <= s_count
    result = [].push first
    step = (size-1).to_f / (s_count-1)
    (s_count - 2).times do |i|
      result.push self[step*(i+1)]
    end
    result.push last
  end
end

(0..25).to_a.average_samples 7

或者

class Array
  def average_samples(s_count)
    return clone if size <= s_count
    step = (size-1).to_f / (s_count-1)
    rest = (1..(s_count - 2)).inject([]) {|a, i| a.push self[step*i]}
    [first, *rest, last]
  end
end

class Array
  def average_samples(s_count)
    return clone if size <= s_count
    step = (size-1).to_f / (s_count-1)
    (0..(s_count - 1)).map {|i| self[step*i]}
  end
end

#2 楼 @5swords 哇哦,研究研究,thanks

You need to Sign in before reply, if you don't have an account, please Sign up first.