【问题标题】:Ruby hash for Sparse Matrix稀疏矩阵的 Ruby 哈希
【发布时间】:2015-03-19 11:30:50
【问题描述】:

我知道在 Ruby 中有几个 libraries 。但我必须创建自己的(出于学习目的)。

我正在考虑两种方法:

散列,而键是格式为字符串的字符串

myhash["row.col"] 所以当元素不存在时我可以使用默认值为零。

或者创建一个 Sparse 类,然后检查元素以返回其值:

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​​ 新手,所以我不确定)

【问题讨论】:

    标签: ruby performance oop design-patterns hash


    【解决方案1】:

    使用散列方式,因为它简单、编写速度快、访问速度快。

    对于哈希键,使用这样的数组:

    hash[[row,col]] = value
    

    行和列可以使用任何东西,例如字符串、数字、复杂对象等。

    出于学习目的,你可能会对包装Hash感兴趣:

    class SparseMatrix
    
      def initialize
        @hash = {}
      end
    
      def [](row, col)
        @hash[[row, col]]
      end
    
      def []=(row, col, val)
        @hash[[row, col]] = val
      end
    
    end
    

    用法:

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

    出于学习目的,您可以使用任意数量的维度:

    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,4] = 5
    matrix[1,2,3,4] #=> 5
    

    【讨论】:

    • 非常类似于 ruby​​ 的简单实现 Joel!
    猜你喜欢
    • 2011-10-07
    • 2012-05-25
    • 1970-01-01
    • 1970-01-01
    • 2018-01-19
    • 2012-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多