1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
# Encoding: UTF-8 = Begin Author: xu jin 4100213 Date: Oct 28,201 2 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", 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) |