第5章で計算量のO記法が扱われたが,「入力のサイズ」を表す変数としては1種類(「O(n log n)」では変数「n」だけ)しか出てこない例しか現れてこなかった.「入力のサイズ」を表す変数が複数ある場合は,O記法の中で複数の変数が用いられる.たとえば,
m x n の行列Aの転置行列(transposed matrix)を作成する以下のプログラムの計算量のオーダーは「O(mn)」になる(もちろん「O(nm)」と書いても良い).
def transpose(a)
m = a.size()
n = a[0].size()
c = make2d(n, m)
for i in 0..(m-1)
for j in 0..(n-1)
c[j][i] = a[i][j]
end
end
c
end
実行例
irb(main):003:0> a=[[1,2,3],[4,5,6]]
a=[[1,2,3],[4,5,6]]
=> [[1, 2, 3], [4, 5, 6]]
irb(main):004:0> transpose(a)
transpose(a)
=> [[1, 4], [2, 5], [3, 6]]
そのクラスがどのようなメソッド呼び出しができるかは,「クラス.methods()」として確認できる.
irb(main):009:0> [].class().methods()
[].class().methods()
=> [:[], :try_convert, :allocate, :new, :superclass, :freeze, :===, :==, :<=>, :<, :<=, :>, :>=, :to_s, :inspect, :included_modules, :include?, :name, :ancestors, :instance_methods, :public_instance_methods, :protected_instance_methods, :private_instance_methods, :constants, :const_get, :const_set, :const_defined?, :const_missing, :class_variables, :remove_class_variable, :class_variable_get, :class_variable_set, :class_variable_defined?, :public_constant, :private_constant, :module_exec, :class_exec, :module_eval, :class_eval, :method_defined?, :public_method_defined?, :private_method_defined?, :protected_method_defined?, :public_class_method, :private_class_method, :autoload, :autoload?, :instance_method, :public_instance_method, :nil?, :=~, :!~, :eql?, :hash, :class, :singleton_class, :clone, :dup, :taint, :tainted?, :untaint, :untrust, :untrusted?, :trust, :frozen?, :methods, :singleton_methods, :protected_methods, :private_methods, :public_methods, :instance_variables, :instance_variable_get, :instance_variable_set, :instance_variable_defined?, :remove_instance_variable, :instance_of?, :kind_of?, :is_a?, :tap, :send, :public_send, :respond_to?, :extend, :display, :method, :public_method, :define_singleton_method, :object_id, :to_enum, :enum_for, :equal?, :!, :!=, :instance_eval, :instance_exec, :__send__, :__id__]