Skip to content

Instantly share code, notes, and snippets.

@jxcodetw
Created June 1, 2017 05:29
Show Gist options
  • Save jxcodetw/95e0080e462d628a6c9e9d33fd417f49 to your computer and use it in GitHub Desktop.
Save jxcodetw/95e0080e462d628a6c9e9d33fd417f49 to your computer and use it in GitHub Desktop.
class Matrix < Array
def initialize(filename)
# read file
f = File.open(filename) or die("no such file or reading error.")
@row, @col = f.readline.split(' ').map(&:to_i)
f.each_line { |line|
line = line.split(' ').map(&:to_r)
self.push(line)
}
end
def to_rref!()
lead = 0
@row.times { |r|
return if lead == @col
i = r
while self[i][lead] == 0
if (i+=1) == @row
i = r
return if (lead+=1) == @col
end
end
self[r], self[i] = self[i], self[r]
v = self[r][lead]
self[r].map! {|n| n / v}
for k in 0...@row
if not k == r
v = self[k][lead]
self[k].map!.with_index { |n, c| n-v*self[r][c]}
end
end
lead += 1
}
end
def show()
self.each { |row|
row.each { |item| print "#{item.to_i} " }
puts
}
end
end
mtx = Matrix.new(ARGV[0])
mtx.to_rref!
mtx.show
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment