稀疏矩阵的Ruby哈希

DeM*_*rco 3 ruby oop hash performance design-patterns

我知道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
Run Code Online (Sandbox Code Playgroud)

我不希望这是主观的,我想知道大多数使用的设计模式会更符合逻辑吗?(我的问题是因为“ row.col”一开始似乎比较容易,它还涉及从/到字符串/数字的多次转换,并且可能存在性能问题。(我是ruby的新手,所以我不确定)

joe*_*son 6

使用散列方法是因为它很容易,易于编写且易于访问。

对于哈希键,请使用如下数组:

hash[[row,col]] = value
Run Code Online (Sandbox Code Playgroud)

您可以将任何内容用于行和列,例如字符串,数字,复杂对象等。

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

class SparseMatrix

  def initialize
    @hash = {}
  end

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

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

end
Run Code Online (Sandbox Code Playgroud)

用法:

matrix = SparseMatrix.new
matrix[1,2] = 3
matrix[1,2] #=> 3
Run Code Online (Sandbox Code Playgroud)

出于学习目的,您可以根据需要使用任意多个维度:

class SparseMatrix

  def initialize
    @hash = {}
  end

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

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

end
Run Code Online (Sandbox Code Playgroud)

用法:

matrix = SparseMatrix.new
matrix[1,2,3,4] = 5
matrix[1,2,3,4] #=> 5
Run Code Online (Sandbox Code Playgroud)