Ruby Implementation of matrix concatenation

Source: Internet
Author: User

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)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.