2015-01-21 124 views
2

我知道Ruby中有幾個libraries。但我必須創造我自己的(用於學習目的)。稀疏矩陣的紅寶石哈希

我正在考慮這兩種方法:

散列,而關鍵是在形式

myhash["row.col"]這樣我就可以使用默認值爲零,當元素不存在的字符串。

或創建一個稀疏類,然後檢查的元素返回其值:

class SparseMatrix < Array 
    require 'contracts' 
    include Contracts 
    attr_accessor :value, :array 
    attr_reader :row, :col 
    @@array = Array.new 
    Contract Num, Num, Num => nil 
    def initialize(value,row,col) 
    @value = value 
    @row = row 
    @col = col 
    end 
    def self.all_instances 
    @@array 
    end 
    Contract Num, Num => Num 
    def getElement(row,col) 
    flag = false 
    array.each do |x| 
     if x.row == row && x.col == col 
     return x.value 
     end 
    end 
    0 
    end 
end 

我不希望這是主觀的,我不知道對於大多采用的設計模式,這將是一個更合乎邏輯的格式去做? (我的問題是,因爲「row.col」似乎更容易開始,它還涉及到從/到字符串/數字的幾個轉換,它可能會有性能問題(我是ruby的新手,所以我不確定)

回答

4

使用哈希方式,因爲它很容易,快寫,快訪問

對於散列鍵,使用像這樣的數組:

hash[[row,col]] = value 

你可以使用任何的行和col,如字符串,數字,複雜對象等。

F或者學習的目的,你可能會在包裝哈希有趣:

class SparseMatrix 

    def initialize 
    @hash = {} 
    end 

    def [](row, col) 
    @hash[[row, col]] 
    end 

    def []=(row, col, val) 
    @hash[[row, col]] = val 
    end 

end 

用法:

class SparseMatrix 

    def initialize 
    @hash = {} 
    end 

    def [](*keys) 
    @hash[keys] 
    end 

    def []=(*keys, val) 
    @hash[keys] = val 
    end 

end 

用法:

matrix = SparseMatrix.new 
matrix[1,2] = 3 
matrix[1,2] #=> 3 

爲了便於學習,只要你喜歡,你可以使用盡可能多的維度:

matrix = SparseMatrix.new 
matrix[1,2,3,4] = 5 
matrix[1,2,3,4] #=> 5