Dynamic programming solves the problem of matrix multiplication, randomly produces matrix sequence, output form ((A1 (A2A3)) (A4A5) results.
Code:
#encoding: Utf-8 =begin author:xu jin, 4100213 date:oct, Matrixchain to find a optimum order by using Matrixch Ain algorithm Example output:the given array is:[30, 5, the optimum Order is: ((A1 (A2A3)) ((A4A5) A6)) T He 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 the 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)} def matrix_chain_order (P, M, s) n = p.size-1 (1. . N). each{|i| m[i][i] = 0} for R in (2..N) doing for I-(1..n-r + 1) Do j = R + i-1 M[i][j] = INF Intiy 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_optimal_parens (S, I, S[i][j]) Print_optimal_parens (S, s[i][j] + 1, j) Print ")" End-def process (P, m, s) Matrix_chain_order (P, m, s) print "The Optimum Order is:" Print_optimal_pare NS (S, 1, p.size-1) printf ("\nthe total number of multiplications are:%d\n\n", m[1][p.size-1]) end puts "the given The 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 (a) + 1} puts "The random array is:" + p.to_s m, s = array.new (p.size) {array.new (p.size)}, Array.new (P.siz
e) {array.new (p.size)} process (p, m, s)