-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathVideoCache.java
More file actions
67 lines (57 loc) · 2.16 KB
/
Copy pathVideoCache.java
File metadata and controls
67 lines (57 loc) · 2.16 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
import java.util.*;
/**
* Created by royd1990 on 2/23/17.
*/
public class VideoCache {
private int id;
private int cacheLimit;
private ArrayList<Integer> videos=new ArrayList<Integer>();
private HashMap<Integer,Integer> cacheTable = new HashMap<Integer,Integer>();
private HashMap<Integer,Integer> videoSize;
public VideoCache(int id, int cacheLimit,HashMap<Integer,Integer> videoSize){
this.id=id;
this.cacheLimit=cacheLimit;
this.videoSize=videoSize;
}
public void PopulateCacheTable(int videos,int latency){
cacheTable.put(videos,latency);
}
public ArrayList<Integer> computeCacheTable(){
int sum=0;
LinkedHashMap<Integer,Integer> sortedMap = sortHashMapByValues(cacheTable);
Iterator sortedMapIterator = sortedMap.entrySet().iterator();
while(sortedMapIterator.hasNext()){
HashMap.Entry pair = (HashMap.Entry)sortedMapIterator.next();
if(sum<cacheLimit){
sum+=videoSize.get(pair.getKey());
videos.add((int)pair.getKey());
}
}
return videos;
}
private LinkedHashMap<Integer, Integer> sortHashMapByValues(
HashMap<Integer, Integer> passedMap) {
List<Integer> mapKeys = new ArrayList<>(passedMap.keySet());
List<Integer> mapValues = new ArrayList<>(passedMap.values());
Collections.sort(mapValues);
Collections.sort(mapKeys);
LinkedHashMap<Integer, Integer> sortedMap =
new LinkedHashMap<>();
Iterator<Integer> valueIt = mapValues.iterator();
while (valueIt.hasNext()) {
Integer val = valueIt.next();
Iterator<Integer> keyIt = mapKeys.iterator();
while (keyIt.hasNext()) {
Integer key = keyIt.next();
Integer comp1 = passedMap.get(key);
Integer comp2 = val;
if (comp1.equals(comp2)) {
keyIt.remove();
sortedMap.put(key, val);
break;
}
}
}
return sortedMap;
}
}