Matrix multiplication algorithm implemented by Ruby

Source: Internet
Author: User
Tags rand


This article mainly introduces the matrix multiplication algorithm implemented by Ruby, this article gives the implementation code directly, and the friends who need it can refer to the following



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 In to find a 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 are: ((A1 (A2A3)) (A4A5)) The total number of 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)} & nbsp Def matrix_chain_order (P, M, s) n = p.size-1 (1..N). each{|i| M[i][i] = 0} for R in (2..N) does for I (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   Def print_optimal_parens (S, I, J) if (i = = j) Then print "A" + i.to_s Else print "(" Print_op Timal_parens (S, I, S[i][j]) Print_optimal_parens (S, s[i][j] + 1, j) print "" End end   def process (P, m, s) matrix_c Hain_order (P, m, s) print "The Optimum Order is:" Print_optimal_parens (S, 1, p.size-1) printf (' nthe total number of mult Iplications is:%dnn ', 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 (0..x). each{|index| P[index] = rand + 1} puts "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)
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.