我有一个有趣的问题。
这是对象结构:
public class Testdata {
//Which is a consecutive running number i.e 1,2,3..etc
private int sequence;
//classified based on this again any random numbers
private int window;
//need to calculate
private int windowposition;
}
现在基于序列和窗口,我需要导出与窗口相关的
windowposition
测试数据
所以对于测试数据序列/窗口
1 / 2
2 / 3
3 / 2
4 / 3
5 / 3
预期输出
sequence/window : window position would be (in the same order)
1 / 2 : 1
2 / 3 : 1
3 / 2 : 2
4 / 3 : 2
5 / 3 : 3
更新:
是的,确实,我已经实现了可比较并将列表按以下顺序排序
1 / 2
3 / 2
2 / 3
4 / 3
5 / 3
现在,如何计算每个元素相对于其窗口的
windowposition
?
实施Comparable可能是有意义的。这允许您对对象进行排序。你可以像这样实现
compareTo(T)
:
int compareTo(Testdata o) {
return ((Integer)this.sequence).compareTo(o.sequence);
}
这样您的对象就可以按顺序排序。
现在将所有带有
window
1 的对象收集到 List
中,将带有 window
2 的对象收集到另一个列表中,等等
HashMap<Integer, ArrayList<Testdata>> map = new HashMap<Integer, ArrayList<Testdata>>();
// Add all the objects like this
while (...) { // While there are more objects
Testdata td = ... // Get next object
List<TestData> list = map.get(td.window);
if (list == null) {
list = new ArrayList<Testdata>();
map.put(td.window, list);
}
list.add(td.sequence);
}
对所有列表进行排序
for (ArrayList<TestData> list : map) {
Collections.sort(list);
}
然后,每个窗口都有一个列表,可通过
map.get(window)
访问。每个列表都将 sequence
最低的对象作为第一个对象,第二低的作为第二个对象,依此类推。 -> 窗口位置是对象的索引 + 1。
编辑:
如果您的对象已经按窗口和顺序排序(到单个列表中),您可以执行以下操作来分配窗口位置:
int window = 1;
int wp = 0;
for (Testdata td : list) {
if (td.window > window) {
wp = 1;
window = td.window;
} else {
wp++;
}
td.windowposition = wp;
}
所以,windowposition只是另一个序列。我会在每个窗口的最后一个
windowposition中放入
Map<Integer,Integer>
。
您不一定要对对象进行排序。
So its basically window's no. of occurrence in the array of objects.
Seq/Window:Position
1 / 2 : 1 => Window 2 , 1st position (1st occurrence of Window 2)
2 / 3 : 1 => Window 3 , 1st position (1st occurrence of Window 3)
3 / 2 : 2 => Window 2 , 2nd position (since Window 2 has already positioned in sequence 1)
4 / 3 : 2 => Window 3 , 2nd position (since Window 3 has already positioned in sequence 2)
5 / 3 : 3 => Window 3 , 3rd position (since Window 3 has already positioned in sequence 2 and 4)
Is that right?
List<Window> windows = new ArrayList<Window>();
windows.add(new Window(2, 3));
windows.add(new Window(1, 2));
windows.add(new Window(3, 2));
windows.add(new Window(4, 3));
windows.add(new Window(5, 3));
Collections.sort(windows);
HashMap<Integer, Integer> wpMap = new HashMap<Integer, Integer>();
Integer wpos;
for (Window w : windows) {
wpos = wpMap.get(w.window);
if ( wpos == null ) {
wpos = 1;
} else {
wpos++;
}
w.setWindowPosition(wpos);
wpMap.put(w.window, wpos);
}
for (Window w : windows) {
System.out.println(w.sequence+"/"+w.window+":"+w.windowposition);
}
试试这个代码
windowposition = sequence - window < 0 ? 1 : sequence - window + 1;