5 kyu

Vector class

3,313 of 8,805eugene-bulkin

Description:

Create a Vector object that supports addition, subtraction, dot products, and norms. So, for example:

a = new Vector([1, 2, 3])
b = new Vector([3, 4, 5])
c = new Vector([5, 6, 7, 8])

a.add(b)      # should return a new Vector([4, 6, 8])
a.subtract(b) # should return a new Vector([-2, -2, -2])
a.dot(b)      # should return 1*3 + 2*4 + 3*5 = 26
a.norm()      # should return sqrt(1^2 + 2^2 + 3^2) = sqrt(14)
a.add(c)      # throws an error
var a = new Vector([1, 2, 3]);
var b = new Vector([3, 4, 5]);
var c = new Vector([5, 6, 7, 8]);

a.add(b);      // should return a new Vector([4, 6, 8])
a.subtract(b); // should return a new Vector([-2, -2, -2])
a.dot(b);      // should return 1*3 + 2*4 + 3*5 = 26
a.norm();      // should return sqrt(1^2 + 2^2 + 3^2) = sqrt(14)
a.add(c);      // throws an error
a = Vector([1, 2, 3])
b = Vector([3, 4, 5])
c = Vector([5, 6, 7, 8])

a.add(b)      # should return a new Vector([4, 6, 8])
a.subtract(b) # should return a new Vector([-2, -2, -2])
a.dot(b)      # should return 1*3 + 2*4 + 3*5 = 26
a.norm()      # should return sqrt(1^2 + 2^2 + 3^2) = sqrt(14)
a.add(c)      # raises an exception

If you try to add, subtract, or dot two vectors with different lengths, you must throw an error!

Also provide:

  • a toString method, so that using the vectors from above, a.toString() === '(1,2,3)' (in Python, this is a __str__ method, so that str(a) == '(1,2,3)')
  • an equals method, to check that two vectors that have the same components are equal

Note: the test cases will utilize the user-provided equals method.

Object-oriented Programming
Algorithms
Linear Algebra

Stats:

CreatedOct 28, 2013
PublishedOct 28, 2013
Warriors Trained23098
Total Skips5878
Total Code Submissions98480
Total Times Completed8805
JavaScript Completions3313
CoffeeScript Completions164
Python Completions4820
TypeScript Completions728
Total Stars628
% of votes with a positive feedback rating87% of 915
Total "Very Satisfied" Votes721
Total "Somewhat Satisfied" Votes156
Total "Not Satisfied" Votes38
Ad
Contributors
  • eugene-bulkin Avatar
  • jhoffner Avatar
  • anter69 Avatar
  • Blind4Basics Avatar
  • hobovsky Avatar
  • stellartux Avatar
  • Formula-9 Avatar
Ad