forked from KiraJS/grokking-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
greedy.js
61 lines (53 loc) · 1.35 KB
/
greedy.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
let states = ['mt', 'wa', 'or', 'id', 'nv', 'ut', 'ca', 'az'];
let stations = {};
stations['one'] = ['id', 'nv', 'ut'];
stations['two'] = ['mt', 'wa', 'id'];
stations['three'] = ['or', 'nv', 'ca'];
stations['four'] = ['ca', 'az'];
stations['five'] = ['nv', 'ut'];
function greedy() {
let finalStations = [];
while(states.length){
let bestStation = null;
let statesCovered = [];
for(let station in stations){
let covered = getIntersection(states, stations[station]);
if(covered.length > statesCovered.length) {
bestStation = station;
statesCovered = covered;
}
}
states = getDifference(states, statesCovered);
finalStations.push(bestStation)
}
return finalStations;
}
function getDifference(arr1, arr2){
let obj = {};
let result = [];
arr1.forEach((item)=>{
obj[item] ? obj[item]++ : obj[item] = 1;
})
arr2.forEach((item)=>{
obj[item] ? obj[item]++ : obj[item] = 1;
})
for(let item in obj){
if(obj[item] === 1) result.push(item);
}
return result;
}
function getIntersection(arr1, arr2) {
let obj = {};
let result = [];
arr1.forEach((item)=>{
obj[item] ? obj[item]++ : obj[item] = 1;
})
arr2.forEach((item)=>{
obj[item] ? obj[item]++ : obj[item] = 1;
})
for(let item in obj){
if(obj[item] > 1) result.push(item);
}
return result;
}
console.log(greedy());