k***t 发帖数: 769 | 1 This question is to define Ruby classes for vectors and matrices.
Define two classes MyVector and MyMatrix with the methods described be-
low.
A MyVector object represents a row vector while a MyMatrix object repre-
sents a matrix that internally organized as an array of MyVector objects.
Methods for MyVector
1. The initialize method takes an array of integers as argument.
2. The length method returns the size of the vector
3. The * method takes an argument a:
if a is a vector, then it returns the inner product of this vector and a.
Verify that the two vectors have the same length and raise an exception
otherwise.
if a is a matrix, then it returns the product of this vector and the matrix.
Verify that the vector length is equal to the number of rows in the matrix
and raise an exception otherwise.
4. The to_s method returns the string representation of this vector.
Methods for MyMatrix
1. The initialize method takes an array of arrays as argument and convert
each inner array into a row vector (of MyVector class) in the matrix.
2. The transpose method returns this matrix transposed
3.The * method takes a MyMatrix object argument and returns the product of
the two matrices.
Verify that the number of columns of this matrix is equal to the number of
rows of the argument and raise an exception otherwise.
4.The to_s method returns string representation of this matrix.
这个是我的code,但是总是不对,
class MyVector
def initialize (a)
if !(a.instance_of? Array)
raise "must be an array"
else
@array = a
end
end
def array
@array
end
def to_s
@array.to_s
end
def length
@array.length
end
def each2(a) #
raise Error, "Integer is not like Vector" if a.kind_of?(Integer)
Vector.Raise Error if length != a.length
return to_enum(:each2, a) unless block_given?
length.times do |i|
yield @array[i], a[i]
end
self
end
def * (a)
Vector.Raise Error if length != a.length
p = 0
each2(a) {|a1, a2|p += a1 * a2}
p
end
end
class MyMatrix
def initialize a
@array=Array.new(a.length)
i=0
while(i
@array[i]=MyVector.new(a[i])
end
end
def to_s
@array.to_s
end
def transpose
size = vectors[0].length
arr = Array.new(size)
i=0
while i < size
a = Array.new(vectors.length)
j = 0
while j < a.length
a [j] = vectors[j].arr[i]
j += 1
end
arr[i] = a
i += 1
end
MyMatrix.new(arr)
end
def *m
if ! (m instance_of? MyMatrix)
raise
a=Array.new(@array.length)
i=0
while (i<@array.length)
a[i]=@array[i]*m (need create something to store this)
i=i+1
end
end
end
end |
|