|
#encoding: Utf-8 =begin author:xu jin, 4100213 date:oct In to find a 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 are: ((A1 (A2A3)) (A4A5)) The total number of multiplications is:388 =end infintiy = 1 /0.0 p = [5] m, s = array.new (p.size) {array.new (p.size)}, Array.new (p.size) {array.new (p.size)} & nbsp Def matrix_chain_order (P, M, s) n = p.size-1 (1..N). each{|i| M[i][i] = 0} for R in (2..N) does for I (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 Def print_optimal_parens (S, I, J) if (i = = j) Then print "A" + i.to_s Else print "(" Print_op Timal_parens (S, I, S[i][j]) Print_optimal_parens (S, s[i][j] + 1, j) print "" End end def process (P, m, s) matrix_c Hain_order (P, m, s) print "The Optimum Order is:" Print_optimal_parens (S, 1, p.size-1) printf (' nthe total number of mult Iplications is:%dnn ', 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 (0..x). each{|index| P[index] = rand + 1} puts "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) |