-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathVector.swift
76 lines (64 loc) · 1.63 KB
/
Vector.swift
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
//
// Vector.swift
// K-Means
//
// Created by Justin Purnell on 9/26/16.
// Copyright © 2016 Justin Purnell. All rights reserved.
//
import Foundation
struct Vector: CustomStringConvertible, Equatable {
private(set) var length = 0
private(set) var data: [Double]
init(_ data: [Double]) {
self.data = data
self.length = data.count
}
var description: String {
return "Vector (\(data))"
}
func distanceTo(other: Vector) -> Double {
var result = 0.0
for idx in 0..<length {
result += pow(data[idx] - other.data[idx], 2.0)
}
return sqrt(result)
}
}
func == (lhs: Vector, rhs: Vector) -> Bool {
for idx in 0..<lhs.length {
if lhs.data[idx] != rhs.data[idx] {
return false
}
}
return true
}
func + (lhs: Vector, rhs: Vector) -> Vector {
var results = [Double]()
for idx in 0..<lhs.length {
results.append(lhs.data[idx] + rhs.data[idx])
}
return Vector(results)
}
func += (lhs: inout Vector, rhs: Vector) {
lhs = lhs + rhs
}
func - (lhs: Vector, rhs: Vector) -> Vector {
var results = [Double]()
for idx in 0..<lhs.length{
results.append(lhs.data[idx] - rhs.data[idx])
}
return Vector(results)
}
func -= (lhs: inout Vector, rhs: Vector) {
lhs = lhs - rhs
}
func / (lhs: Vector, rhs: Double) -> Vector {
var results = [Double](repeating: 0, count: lhs.length)
for (idx, value) in lhs.data.enumerated() {
results[idx] = value / rhs
}
return Vector(results)
}
func /= (lhs: inout Vector, rhs: Double) {
lhs = lhs / rhs
}