-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
129 lines (116 loc) · 2.69 KB
/
app.js
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
const fs = require("fs");
class Point {
constructor(x, y) {
this.x = parseInt(x);
this.y = parseInt(y);
}
}
class motors {
constructor(position) {
this.position = position;
this.priority = [];
this.consumption = 0;
}
}
class Ride {
constructor(id, startPoint, endPoint, startTime, endTime) {
this.id = id;
this.startPoint = startPoint;
this.endPoint = endPoint;
this.startTime = parseInt(startTime);
this.endTime = parseInt(endTime);
this.prioritized = false;
}
attributeTomotors(motors, cost) {
motors.priority.push(this);
motors.position = this.endPoint;
motors.consumption += cost;
this.prioritized = true;
}
}
readRides = lines => {
ret = [];
for (i = 0; i < lines.length; i++) {
ll = lines[i].split(" ");
ret.push(
new Ride(
i,
new Point(ll[0], ll[1]),
new Point(ll[2], ll[3]),
ll[4],
ll[5]
)
);
}
return ret;
};
readmotors = n => {
ret = [];
for (i = 0; i < n; i++) {
ret.push(new motors(new Point(0, 0)));
}
return ret;
};
distance = (a, b) => {
return Math.abs(a.x - b.x) + Math.abs(a.y - b.y);
};
calculateCost = (motors, ride) => {
return (
ride.startTime +
distance(motors.position, ride.startPoint) +
distance(ride.startPoint, ride.endPoint) +
motors.consumption
);
};
// calculateTotalConsumption = (motors) => {
// sum = 0;
// for (i = 0; i < motors.length; i++) {
// sum += motors[i].consumption;
// }
// return sum;
// }
prioritizeRides = (motors, rides) => {
min_cost = Infinity;
for (i = 0; i < rides.length; i++) {
if (!rides[i].prioritized) {
for (j = 0; j < motors.length; j++) {
cost = calculateCost(motors[j], rides[i]);
if (cost < min_cost) {
min_cost = cost;
min_motors = j;
min_ride = i;
}
}
}
}
rides[min_ride].attributeTomotors(motors[min_motors], min_cost);
};
printRides = motors => {
out = "";
for (i = 0; i < motors.length; i++) {
if (motors[i].priority.length > 0) {
out +=
motors[i].priority.length +
" " +
motors[i].priority.map(p => p.id).join(" ") +
"\n";
}
}
return out;
};
fs.readFile("mansour.csv", "utf8", function(err, contents) {
let lines = contents.trim().split("\n");
const [R, C, F, N, B, T] = lines[0].split(" ");
lines.shift();
rides = readRides(lines);
motors = readmotors(F);
while (rides.filter(r => r.prioritized === false).length > 0) {
prioritizeRides(motors, rides);
}
fs.writeFile("mansourOUT.csv", printRides(motors), function(err) {
if (err) {
return console.log(err);
}
console.log("The file was saved!");
});
});