-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMatrix.rb
91 lines (79 loc) · 1.71 KB
/
Matrix.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
class Matrix
## Wrapper class Matrix makes it easy to work with 2D lists
attr_reader :rows, :cols
#Fill data (leave col as 0 unless planning on setting vals)
def initialize(rows, cols)
@rows = rows
@cols = cols
@data = []
for i in (0...rows)
@data[i] = []
for j in (0...cols)
@data[i][j] = 0
end
end
end
def reset(rows, cols)
@rows = rows
@cols = cols
@data = []
for i in (0...rows)
@data[i] = []
for j in (0...cols)
@data[i][j] = 0
end
end
end
# For compatablity
def to_str to_s; end
#Neatly represent data
def to_s
ret = "\n" + @rows.to_s + 'x' + @cols.to_s + " matrix:\n"
for row in @data
for datum in row
ret+= "nil" if !datum
ret+= datum.to_f.to_s + "\t"
end
ret+= "\n"
end
return ret + "\n"
end
#Set a coord
def set(row, col, val)
return nil if row >= @rows || col >= @cols || row < 0 || col < 0
@data[row][col] = val
end
# Get a number
def get(row, col)
return nil if row >= @rows || row < 0 || col >= @cols || col < 0
return @data[row][col]
end
def get_row(row)
return nil if row >= @rows || row < 0
return @data[row]
end
def get_col(col)
return nil if col >= @cols || col < 0
ret = []
for i in (0...@rows)
ret.push(@data[i][col])
end
return ret
end
#Add a collumn. Data is a list of what should be entered
def add_col(data)
for i in (0...@rows)
@data[i][@cols] = data[i].to_f
end
@cols += 1
end
def copy()
ret = Matrix.new(@rows, @cols)
for i in (0...@rows)
for j in (0...@cols)
ret.set(i, j, get(i, j))
end
end
return ret
end
end