-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnut9.ts
72 lines (64 loc) · 1.9 KB
/
nut9.ts
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
import csv from "csv-parser";
import fs from "fs";
const results = new Array();
fs.createReadStream("./nut9_from_to_city.csv")
.pipe(csv({ separator: ";" }))
.on("data", (data) => {
results.push(data);
})
.on("end", () => {
type DistanceMatrix = number[][];
function tspWithMatrix(
matrix: DistanceMatrix,
startCity: number,
endCity: number,
visited: Set<number> = new Set(),
currentDistance: number = 0,
bestDistance: number = Infinity
): number {
visited.add(startCity);
if (visited.size === matrix.length) {
const totalDistance = currentDistance + matrix[startCity][endCity];
return Math.min(bestDistance, totalDistance);
}
for (let city = 0; city < matrix.length; city++) {
if (!visited.has(city)) {
const newDistance = currentDistance + matrix[startCity][city];
if (newDistance < bestDistance) {
bestDistance = tspWithMatrix(
matrix,
city,
endCity,
new Set(visited),
newDistance,
bestDistance
);
}
}
}
return bestDistance;
}
let distanceMatrix: DistanceMatrix = new Array<Array<number>>();
results.forEach((element) => {
let arrayInput = new Array<number>();
for (const key in element) {
if (element.hasOwnProperty(key) && !Number.isNaN(+element[key])) {
const el: number = +element[key];
console.log(el);
if (!Number.isNaN(el)) {
arrayInput.push(el);
}
}
}
distanceMatrix.push(arrayInput);
});
console.log(distanceMatrix);
const startCity = 5;
const endCity = 5;
const shortestPathDistance = tspWithMatrix(
distanceMatrix,
startCity,
endCity
);
console.log(`Shortest path distance: ${shortestPathDistance}`);
});