Repository navigation
Expand file tree
/
Copy pathVector.java
More file actions
102 lines (72 loc) · 2.21 KB
/
Copy pathVector.java
File metadata and controls
102 lines (72 loc) · 2.21 KB
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
92
93
94
95
96
97
98
99
100
101
102
// Vector.java
class Vector {
private int dimension;
private double[] elements;
// Constructor
public Vector(int dimension, double[] elements)
throws VectorException {
if (dimension != 2 && dimension != 3) {
throw new VectorException(
"Only 2D or 3D vectors allowed."
);
}
this.dimension = dimension;
this.elements = new double[dimension];
for (int i = 0; i < dimension; i++) {
this.elements[i] = elements[i];
}
}
// Check dimension
private void checkDimension(Vector v)
throws VectorException {
if (this.dimension != v.dimension) {
throw new VectorException(
"Vector dimensions must be same."
);
}
}
// Add vectors
public Vector add(Vector v)
throws VectorException {
checkDimension(v);
double[] result = new double[dimension];
for (int i = 0; i < dimension; i++) {
result[i] =
this.elements[i] + v.elements[i];
}
return new Vector(dimension, result);
}
// Subtract vectors
public Vector subtract(Vector v)
throws VectorException {
checkDimension(v);
double[] result = new double[dimension];
for (int i = 0; i < dimension; i++) {
result[i] =
this.elements[i] - v.elements[i];
}
return new Vector(dimension, result);
}
// Dot product
public double dotProduct(Vector v)
throws VectorException {
checkDimension(v);
double sum = 0;
for (int i = 0; i < dimension; i++) {
sum +=
this.elements[i] * v.elements[i];
}
return sum;
}
// Display vector
public void display() {
System.out.print("Vector: (");
for (int i = 0; i < dimension; i++) {
System.out.print(elements[i]);
if (i < dimension - 1) {
System.out.print(", ");
}
}
System.out.println(")");
}
}