-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvector.cpp
More file actions
133 lines (105 loc) · 2.34 KB
/
vector.cpp
File metadata and controls
133 lines (105 loc) · 2.34 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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
#include<iostream>
#include<cmath>
#define MAX_SIZE 10000
using namespace std;
class Vector{
private:
float coords[MAX_SIZE];
int dimension;
public:
Vector(float coords[], int dimension){
if(dimension <= 0 || dimension > MAX_SIZE){
this->dimension = 3;
this->coords[0] = this->coords[1] = this->coords[2] = 0;
cout<<"Dimension invalid, Making a zero vector of 3 dimension.";
}else{
this->dimension = dimension;
for(int i = 0; i < dimension; i++){
this->coords[i] = coords[i];
}
}
}
Vector(){
this->dimension = 3;
this->coords[0] = this->coords[1] = this->coords[2] = 0;
}
Vector(const Vector &v){
dimension = v.get_dimension();
for(int i = 0; i < dimension; i++){
coords[i] = v.get_ith_coord(i);
}
}
int get_dimension() const{
return dimension;
}
float get_ith_coord(int i) const{
return coords[i];
}
int length(){
return dimension;
}
Vector operator+(Vector other){
if(dimension != other.dimension){
return Vector();
}
float new_coords[MAX_SIZE];
for(int i = 0; i < dimension; i++){
new_coords[i] = coords[i] + other.coords[i];
}
return Vector(new_coords, dimension);
}
float operator*(Vector other){
if(dimension != other.dimension){
return -1.0;
}
float scalar_prod = 0.0;
for(int i = 0; i < dimension; i++){
scalar_prod += coords[i] * other.coords[i];
}
return scalar_prod;
}
float sum(){
float tot = 0.0;
for(int i = 0; i < dimension; i++){
tot += coords[i];
}
return tot;
}
float magnitude(){
float ss = 0.0; //Squared Sum
for(int i = 0; i < dimension; i++){
ss += coords[i] * coords[i];
}
return sqrt(ss);
}
Vector direction(){
float mg = magnitude();
float new_coords[MAX_SIZE];
for(int i = 0; i < dimension; i++){
new_coords[i] = coords[i] / mg;
}
return Vector(new_coords, dimension);
}
void print(){
cout<<"<";
for(int i = 0; i < dimension-1; i++){
cout<<coords[i]<<",";
}
cout<<coords[dimension-1]<<">";
}
};
int main(){
float coords[] = {1, 2, 3};
Vector v1(coords, 3);
Vector v2(coords, 3);
Vector v = v1 + v2;
Vector v1_unit = v1.direction();
v.print();
Vector v3(v);
cout<<endl;
v1_unit.print();
cout<<endl;
v3.print();
cout<<"\n"<<v1*v2;
return 0;
}