Dynamic Planning solves the problem of matrix concatenation, generates matrix sequences randomly, and outputs results in the form of (A1 (a2a3) (a4a5.
Code:
# Encoding: UTF-8 = beginauthor: Xu Jin, 4100213 Date: Oct 28,201 2 matrixchainto find an optimum order by using matrixchain algorithmexample 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: 15125the random array is: [5, 8, 8, 2, 5, 9] The Optimum Order is :( (A1 (a2a3) (a4a5) the total number of multiplications is: 388 = endinfintiy = 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 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_optimal_parens (S, s [I] [J] + 1, J) print ") "endenddef 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", M [1] [p. size-1]) endputs "the given array is:" + P. to_sprocess (p, M, S) # produce a random arrayp = array. newx = rand (10) (0 .. x ). each {| index | P [Index] = rand (10) + 1} puts "the random array is:" + P. to_sm, S = array. new (P. size) {array. new (P. size)}, array. new (P. size) {array. new (P. size)} process (p, M, S)