根据上排给出十个数,在其下排填出对应的十个数 要求下排每个数都是先前上排那十个数在下排出现的次数。

腾讯面试题: 
给你10分钟时间,根据上排给出十个数,在其下排填出对应的十个数 
要求下排每个数都是先前上排那十个数在下排出现的次数。 
上排的十个数如下: 
【0,1,2,3,4,5,6,7,8,9】

举一个例子, 
数值: 0,1,2,3,4,5,6,7,8,9 
分配: 6,2,1,0,0,0,1,0,0,0 
0在下排出现了6次,1在下排出现了2次, 
2在下排出现了1次,3在下排出现了0次.... 
以此类推..

a = [0,1,2,3,4,5,6]
b = Array.new(a.length,0)

#p a.repeated_combination(2).to_a

def get_index_arr len,n  
  temp = []
  1.upto(len){|index| temp<<index}
  if n>len and len > 0
    temp << n
  end
  temp
end

def all_possible_arr arr, length
    ret = []
    length.times do
        if ret.empty?
            ret = arr.map {|i| [i]}      
        else
            new_ret = []
            ret.each do |r|
                arr.each do |e|
                    new_ret << r.clone.unshift(e)
                end
            end      
            ret = new_ret    
      #p ret      
        end
    end
    ret
end

def valid? arr
  arr.each_with_index do |v, i|
    return false if arr.select {|j| j == i}.size != v
  end
  true
end

def get_arr a,b
  for i in 0..a.length-1
    b[0] = i
    len = b.length-2-i
    temp = get_index_arr len,i
    l = temp.length
    sum = a.length - i
    return if l==0
    l_ = (sum.to_f/l).ceil
    temp_ = []
    1.upto(l_){|index| temp_ << index}
    all = all_possible_arr temp_,l
    #all = temp_.repeated_permutation(l).to_a
    all.each{|arr|
      if arr.inject(&:+) == sum        
        temp.each_index{|t|
          b[temp[t].to_i] = arr[t]          
        }        
        if valid? b
          p b
          return
        else
          b = Array.new(a.length,0)
          b[0] = i
        end
      end
    }
  end
end
get_arr a,b

 

posted on 2013-09-22 11:55  张飞_  阅读(552)  评论(0编辑  收藏  举报

导航