Matrix multiplication algorithm implemented by Ruby _ruby Special topic

Source: Internet
Author: User
Tags rand

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)


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.