# work0201.rb

class Matrix
  def initialize(a=[[1,0,0],[0,1,0],[0,0,1]])
    @m = a
    @size = 3
  end

  attr_accessor :m

  def add(x)
    ans = Matrix.new
    for i in 0...@size
        for j in 0...@size
	    ans.m[i][j] = @m[i][j] + x.m[i][j]     # ミス
	end
    end
    return ans
  end

  def mult(x)
    ans = Matrix.new
    for i in 0...@size
	for j in 0...@size
	    sum = 0
	    for k in 0...@size
		sum += @m[i][k] * x.m[k][j]
	    end
	    ans.m[i][j] = sum                       # ミス
	end
    end
    return ans
  end

  def invers
    ae = [[0,0,0,1,0,0],[0,0,0,0,1,0],[0,0,0,0,0,1]]
    for i in 0...@size
        for j in 0...@size
	    ae[i][j] = @m[i][j]
	end
    end

    for i in 0...@size
	j = i
	while ae[j][i] == 0
	    j += 1
	    if j >= @size
	        return nil
	    end
	end
	if j != i
	    for k in 0...@size*2
		tmp = ae[i][k]
		ae[i][k] = ae[j][k]
		ae[j][k] = tmp
	    end
	end

	p = Float(ae[i][i])                # ミス
	
	for k in i...@size*2
	    ae[i][k] /= p
	end
	for j in 0...@size
	    if i != j
		r = ae[j][i]
		for k in i...@size*2
		    ae[j][k] -= ae[i][k]*r
		end
	    end
	end
    end

    ans = Matrix.new
    for i in 0...@size
	for j in 0...@size
	    ans.m[i][j] = ae[i][j+@size]
	end
    end

    return ans
  end

  def show
    for i in 0...@size
	for j in 0...@size
	    printf(" %5.2f",@m[i][j])  #  ミス
	end
	print "\n"
    end
  end
end

#

x = Matrix.new([[1,0,0],[2,3,0],[1,1,4]])
y = Matrix.new([[1,2,0],[-1,-3,-2],[1,1,3]])
z = x.add(y)
z.show

puts "-----"
z = x.mult(y)
z.show

puts "-----"
z = x.invers
z.show