-
Notifications
You must be signed in to change notification settings - Fork 0
/
vector.h
67 lines (52 loc) · 1.44 KB
/
vector.h
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
// Copyright (C) 2024 Ethan Uppal. All rights reserved.
#pragma once
#include <cmath>
/** An element of in 2-dimensional Euclidean space. */
struct Vector {
Vector(double x, double y): x(x), y(y) {}
double x;
double y;
Vector operator+(const Vector& other) const {
return Vector(x + other.x, y + other.y);
}
Vector operator-(const Vector& other) const {
return Vector(x - other.x, y - other.y);
}
Vector operator-() const {
return Vector(-x, -y);
}
Vector operator*(double scalar) const {
return Vector(x * scalar, y * scalar);
}
friend Vector operator*(double scalar, const Vector& v) {
return Vector(scalar * v.x, scalar * v.y);
}
Vector operator/(double scalar) const {
return Vector(x / scalar, y / scalar);
}
Vector& operator+=(const Vector& other) {
x += other.x;
y += other.y;
return *this;
}
Vector& operator*=(double scalar) {
x *= scalar;
y *= scalar;
return *this;
}
double dist(const Vector& other) {
double dx = x - other.x;
double dy = y - other.y;
return std::sqrt(dx * dx + dy * dy);
}
double length() {
return std::sqrt(x * x + y * y);
}
void normalize() {
double length_computed = length();
if (length_computed != 0) {
x /= length_computed;
y /= length_computed;
}
}
};