稀疏矩阵的 Ruby 哈希

标签 ruby performance oop design-patterns hash

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

我正在考虑两种方法:

哈希,而键是形式为字符串

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

最佳答案

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

对于散列键,使用这样的数组:

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 哈希,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28058871/

相关文章:

ruby - 如何最好地循环 Ruby 中的多个函数?

ruby - 为什么我得到 "undefined method ` + @' for "是一个信用 : ":String (NoMethodError)" here?

MySQL my.cnf 性能调优建议

c - 确定数字是否出现在字符串中的最快方法是什么?

pythons 'print' 语句不调用 .write() 方法?

arrays - ruby 基础 : Pop Method in Array

css - 使用转换 :all when only transitioning one property

architecture - 游戏对象绘制和更新自身的架构有什么问题?

Javascript - OOP 引用循环

ruby - 使用 upstart 通过 rbenv install ruby​​ 运行 ruby​​ 脚本