Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 如何实现多维数组生成方法_Ruby_Algorithm_Optimization_Dynamic Programming - Fatal编程技术网

Ruby 如何实现多维数组生成方法

Ruby 如何实现多维数组生成方法,ruby,algorithm,optimization,dynamic-programming,Ruby,Algorithm,Optimization,Dynamic Programming,我有一个table\u data方法,用于构建乘法表的多维数组。表的第一行和第一列是相同的,每个单元格包含对应行和列的产品。下面是它最终打印的内容: 2 3 4 . . n 2 4 6 8 3 6 9 12 4 8 12 16 . . n 正如你所看到的,有很多副本可以被记忆。以下是生成多维数组的代码: def table_data(n) table_header(n).map do |x| table_header(n).map

我有一个
table\u data
方法,用于构建乘法表的多维数组。表的第一行和第一列是相同的,每个单元格包含对应行和列的产品。下面是它最终打印的内容:

    2   3   4 . . n

2   4   6   8

3   6   9  12

4   8  12  16
.
.
n
正如你所看到的,有很多副本可以被记忆。以下是生成多维数组的代码:

def table_data(n)
  table_header(n).map do |x|
    table_header(n).map do |y|
      x*y
    end
  end
end

def table_header(n)
  @header_data ||= (1..n).to_a
end

table_data
方法需要二次时间;它正在做双倍的必要工作(对于
x*y
y*x
)。如何在减少运行时间的前提下,对该方法进行修改和修改,以减少运行时?

,这取决于您是否考虑了<代码> x*y 一个微不足道的操作。如果您用某种SQL查询或具有更实际成本的东西来替换它,那么缓存它是有意义的。但就大O复杂度而言,这里的动态变量是表的宽度/高度,例如,我认为减少迭代次数不是一个好方法

无论如何,要缓存
x*y
,您可以创建这样的帮助器类

class MultiplicationCache
  def initialize
    @cache = {}
  end
  def multiply(a,b)
    @cache[[a,b].sort] ||= a * b
  end
end

# usage
cache = MultiplicationCache.new
puts cache.multiply(1,2) # => 2
同样,除非用计算成本非常高的东西替换
x*y
,否则这样做是没有意义的