婷婷综合国产,91蜜桃婷婷狠狠久久综合9色 ,九九九九九精品,国产综合av

主頁 > 知識庫 > Ruby實現的矩陣連乘算法

Ruby實現的矩陣連乘算法

熱門標簽:滴滴外呼系統 地圖標注賺錢項目注冊 白銀外呼paas系統 徐州網絡外呼系統哪個好 高德地圖標注客服 湖州u友防封電銷卡 常德電銷平臺外呼系統軟件價格 電銷機器人廠商代理 百度地圖標注自定義圖片

動態規劃解決矩陣連乘問題,隨機產生矩陣序列,輸出形如((A1(A2A3))(A4A5))的結果。

代碼:

#encoding: utf-8
=begin
author: xu jin, 4100213
date: Oct 28, 2012
MatrixChain
to find an optimum order by using MatrixChain algorithm
example output:
The given array is:[30, 35, 15, 5, 10, 20, 25]
The optimum order is:((A1(A2A3))((A4A5)A6))
The total number of multiplications is: 15125

The random array is:[5, 8, 8, 2, 5, 9]
The optimum order is:((A1(A2A3))(A4A5))
The total number of multiplications is: 388 
=end

INFINTIY = 1 / 0.0
p = [30, 35, 15, 5, 10, 20, 25]
m, s = Array.new(p.size){Array.new(p.size)}, Array.new(p.size){Array.new(p.size)}

def matrix_chain_order(p, m, s)
   n = p.size - 1
   (1..n).each{|i| m[i][i] = 0} 
   for r in (2..n) do
     for i in (1..n - r + 1) do
       j = r + i - 1
       m[i][j] = INFINTIY
       for k in (i...j) do
         q = m[i][k] + m[k + 1][j] + p[i - 1] * p[k] * p[j]                  
         m[i][j], s[i][j] = q, k if(q  m[i][j]) 
       end
     end
   end
end 

def print_optimal_parens(s, i, j)
   if(i == j) then
    print "A" + i.to_s
   else 
    print "("
    print_optimal_parens(s, i, s[i][j])
    print_optimal_parens(s, s[i][j] + 1, j)
    print ")"
   end
end

def process(p, m, s)
   matrix_chain_order(p, m, s)
   print "The optimum order is:"
   print_optimal_parens(s, 1, p.size - 1)
   printf("\nThe total number of multiplications is: %d\n\n", m[1][p.size - 1])
end

puts "The given array is:" + p.to_s
process(p, m, s)

#produce a random array
p = Array.new
x = rand(10)
(0..x).each{|index| p[index] = rand(10) + 1}
puts "The random array is:" + p.to_s
m, s = Array.new(p.size){Array.new(p.size)}, Array.new(p.size){Array.new(p.size)}
process(p, m, s)


您可能感興趣的文章:
  • Ruby實現的各種排序算法
  • ruby實現的插入排序和冒泡排序算法
  • Ruby實現二分搜索(二分查找)算法的簡單示例
  • Ruby實現的3種快速排序算法
  • Ruby實現的合并排序算法
  • Ruby實現的最優二叉查找樹算法
  • Ruby實現的圖片濾鏡算法代碼

標簽:張家界 遼寧 三沙 普洱 荊門 梧州 公主嶺 永州

巨人網絡通訊聲明:本文標題《Ruby實現的矩陣連乘算法》,本文關鍵詞  Ruby,實現,的,矩陣,連乘,;如發現本文內容存在版權問題,煩請提供相關信息告之我們,我們將及時溝通與處理。本站內容系統采集于網絡,涉及言論、版權與本站無關。
  • 相關文章
  • 下面列出與本文章《Ruby實現的矩陣連乘算法》相關的同類信息!
  • 本頁收集關于Ruby實現的矩陣連乘算法的相關信息資訊供網民參考!
  • 推薦文章
    主站蜘蛛池模板: 涟水县| 伊吾县| 多伦县| 阜宁县| 全南县| 九寨沟县| 呼和浩特市| 弥渡县| 京山县| 长寿区| 永登县| 固镇县| 思茅市| 余干县| 象山县| 玉树县| 沂南县| 潢川县| 英德市| 繁昌县| 新干县| 申扎县| 尖扎县| 萨嘎县| 策勒县| 奉化市| 宝应县| 临夏县| 任丘市| 吴江市| 出国| 博罗县| 万载县| 武邑县| 五莲县| 芦溪县| 塔城市| 四川省| 南靖县| 资兴市| 德令哈市|