2048记录反查(ruby)

#58640。2048我打的最大分,别人问,你到底最高多少啊。只有最高纪录分数看不到状态,干脆写个程序,告诉别人自己到底打到多少吧,我其实只记得自己是4096+1024,其他的分数忘记了,不过使用这个程序,很容易就分析出来了。
#2048是在合成的时候记录分数,比如4和4合成8,记录8分,类似这个样子。新出现的2或者4是不计分数的。所以可以通过递归,获得块数合成时候的分数。


#coding: UTF-8

def total(n)  #假设全部的数都是2,2的n次方得到的分数,比如n=10,2**10=1024得到的纪录分数
  return 4 if n == 2
  2 * total( n - 1 ) + 2 ** n
end


def total_plus(n)  #随机2或4,比例9:1,获得的分数。
    i = 0
    (2 ** n / 2).times { i += 1 if rand(10) == 0}
    if total(n) >= i * 4
      total(n) - i * 4
    else
      0
    end
end

#{2=>4, 3=>16, 4=>48, 5=>128, 6=>320, 7=>768, 8=>1792, 9=>4096, 10=>9216, 11=>20480, 12=>45056, 13=>98304, 14=>212992, 15=>458752, 16=>983040} # 只有2的时候2**n对应的的得分

@h = {}
(2..16).each {|n| @h[n] = total_plus(n)}  #据传说,不能大于2**16次方
puts @h  # 做一个对应表,2的n次方对应的可能得分数


def max_n(score) #录入一个分数,小于此分数的最大对应n,比如得到5124分,查表得到最大可能的n是9,也就是说盘面最大是2**9=512。
  temp = []
  @h.each  do |k, v|      
    temp << k if v <= score   
  end
  temp.max 
end

def score_to_n(score, temp = []) #输入记录,反查组成此记录的n值数组
  max = max_n(score)
  return  temp << @h.key(score) if @h.key(score) == max #score在hash表内的时候,直接返回
  return temp if @h[max].zero?   #因为有4存在,所以可能会有0,去除0,要不后面就会报错
  div = score.divmod(@h[max])  #求余数
  div[0].times {temp << max } #多个的时候,写入temp多个n
  score_to_n(div[1], temp)
  temp.compact 
end


score = 58640

p score_to_n(score).map {|n| 2 ** n} # 最终的状态集合,可以检查一下是否和自己的状态一致
p [score, score_to_n(score).map {|n| @h[n] } .inject(:+)] #录入分数和校验分数的比较,可能不一样噢

 












posted @ 2014-05-22 22:30  pyp(鹿鸣)  阅读(874)  评论(0编辑  收藏  举报