Ruby實現的矩陣連乘演算法

2022-09-26 05:33:10 字數 1861 閱讀 2681

動態規劃解決矩陣連乘問題,隨機產生矩陣序列,輸出形如((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 ahmklorder 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)

def matrix_chain_order(p, m, s)

n = p.size - 1

(1..n).each

for r in (2..n) do

for i in (1..n - ahmklr + 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])

endend

endend

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_o程式設計客棧ptimal_parens(s, s[i][j] + 1, j)

print ")"

endenddef pr 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])

endputs "the given array is:" + p.to_s

process(p, m, s)

#produwww.cppcns.comce a random array

p = array.new

x = rand(10)

(0..x).each

puts "the random array is:" + p.to_s

m, s = array.new(p.size), array.new(p.size)

process(p, m, s)

本文標題: ruby實現的矩陣連乘演算法

本文位址:

矩陣連乘演算法java實現

程式執行的結果是 0 15750 7875 9375 11875 15125 0 0 2625 4375 7125 10500 0 0 0 750 2500 5375 0 0 0 0 1000 3500 0 0 0 0 0 5000 0 0 0 0 0 0 簡單介紹一下 int p 儲存矩陣的資訊 ...

矩陣連乘演算法精講

今天看了好久的矩陣連乘演算法,總算有了一點頭緒,現在來細細總結一下。首先我們知道的是,矩陣連乘演算法是一種動態規劃法,那麼和多段圖和弗洛伊德演算法一樣,它也體現了動態規劃法的特點。像弗洛伊德演算法,它的動體現在每加進乙個節點,那麼d和path者兩個二維表都會發生相應的變化,且朝著全域性最優解的方向去...

演算法設計 矩陣連乘問題

白天什麼也沒學,晚上才終於拿著筆,對著 寫寫畫畫,終於看明白是怎麼計算的了。以這6個矩陣連乘作為例子 a1a2 a3a4 a5a6 30 35 35 15 15 5 5 10 10 20 20 25 1 首先,要明白兩個矩陣相乘所需要做的乘法次數 2 由於連乘的矩陣必須滿足,前乙個矩陣的列數 後乙個...