-
Notifications
You must be signed in to change notification settings - Fork 153
Expand file tree
/
Copy pathindex.js
More file actions
79 lines (72 loc) · 2.18 KB
/
Copy pathindex.js
File metadata and controls
79 lines (72 loc) · 2.18 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
const fs = require("fs");
const readline = require("readline");
const inputFile = fs.createReadStream("input.txt");
const outputFile = fs.createWriteStream("output.txt");
const bestCity = async () => {
try {
const rl = readline.createInterface({
input: inputFile,
crlfDelay: Infinity,
});
let cityData = {};
for await (const line of rl) {
if (line !== "") {
const [city, product, priceStr] = line.split(",");
const price = parseFloat(priceStr);
if (city in cityData) {
// check if the product is in list
if (product in cityData[city].product) {
let ind = cityData[city].product[product];
// change the value of the product to cheapes one
if (cityData[city].price[ind].price > price) {
cityData[city].price[ind].price = price;
}
} else {
// add new product
cityData[city].product[product] = cityData[city].index;
cityData[city].price.push({ name: product, price: price });
cityData[city].index += 1;
}
cityData[city].sum += price;
} else {
// add new city
cityData[city] = {
product: {},
price: [{ name: product, price: price }],
sum: price,
index: 1,
};
cityData[city].product[product] = 0;
}
}
}
let smallestSum = Infinity;
let bestCity = "";
for (let city in cityData) {
if (cityData[city].sum < smallestSum) {
smallestSum = cityData[city].sum;
bestCity = city;
}
}
cityData[bestCity].price.sort((a, b) => {
if (a.price === b.price) {
if (a.name > b.name) return 1;
else if (a.name < b.name) return -1;
else return 0;
}
return a.price - b.price;
});
let result = `${bestCity} ${smallestSum.toFixed(2)} \n`;
let i = 0;
while (i < 5) {
let t = cityData[bestCity].price[i].name;
result += t + " " + cityData[bestCity].price[i].price.toFixed(2) + "\n";
i++;
}
outputFile.write(result);
outputFile.end();
} catch (e) {
console.log(e);
}
};
bestCity();