基于线性键的间隙的分离阵列

问题描述 投票:-1回答:1

我希望根据键的间隙将一个数组分离成不同的数组。比如说这个场景。

我试图为本月的连续几天创建单独的数据集(数组)。如果错过了某一天,就需要从下一天有值的日子开始创建一个新的数据集。

数据被检索到一个数组中,就像这样。

[1:10, 2:8, 4:5, 5:12, 8:6, 9:10, 10:5, 11:4, 13:6, 14:5]

我想输出:

[1:10, 2:8], [4:5, 5:12], [8:6, 9:10, 10:5, 11:4], [13:6, 14:5]

我如何实现这个目标?

我目前是这样的。

ArrayList<Entry> allValues = new ArrayList<>();

// Data Retrieval from the Server is Here (hidden for privacy)
// Each data entry contains key and value
// This is converted into a data model "Entry" which is essentially an x & y coordinate ( Entry(x,y) )
// and then added to the allValues List

List<ArrayList<Entry>> rawDataSets = new ArrayList<>();
ArrayList<Entry> tempDataSet = new ArrayList<>();

for(int i = 0; i < allValues.size(); i++){
    Entry tempEntry = allValues.get(i);
    if(i == tempEntry.getX()){
        tempDataSet.add(tempEntry);
    }else{
        if(tempDataSet.size() > 0) {
            rawDataSets.add(tempDataSet);
            tempDataSet.clear();
        }
    }
}
java arrays
1个回答
2
投票

类似这样的东西应该会有办法。

ArrayList<Entry> allValues = new ArrayList<>();

// Assuming at this point that `allValues` is sorted in ascending order by X values.
// If necessary, it can be sorted with 
//
//    Collections.sort(allValues, Comparator.comparing(Entry::getX));
//
List<ArrayList<Entry>> rawDataSets = new ArrayList<>();
ArrayList<Entry> tempDataSet = new ArrayList<>();

for (Entry tempEntry : allValues){
    if (!tempDataSet.isEmpty() &&
        tempEntry.getX() != tempDataSet.get(tempDataSet.size()-1).getX() + 1)
    {
        // tempDataSet is not empty, and tempEntry's X is not 
        // consecutive with the X of tempDataSet's last entry, so it's
        // it's time finish with the current tempDataSet and start fresh
        // with a new one.  
        rawDataSets.add(tempDataSet);
        tempDataSet = new ArrayList<>();
    }
    // Regardless of what happened, or didn't happen, with tempDataSet above, 
    // the current allValues entry now belongs with the current tempDataSet
    tempDataSet.add(tempEntry);
}
// Now add any final non-empty tempDataSet (there will always be one if
// allValues wasn't empty) onto rawDataSets
if (!tempDataSet.isEmpty()) {
    rawDataSets.add(tempDataSet);
}

1
投票

经过多次尝试,我想我找到了解决方案 虽然我不确定这是否是最有效的方法

List<ArrayList<Entry>> rawDataSets = new ArrayList<>();
ArrayList<Entry> tempDataSet = new ArrayList<>();

for(int i = 0; i <= allValues.get(allValues.size() - 1).getX(); i++){
    int matchedIndex = -1;
    for(int j = 0; j < allValues.size(); j++){
        if(allValues.get(j).getX() == i){
            matchedIndex = j;
        }
    }

    if(matchedIndex != -1) {
        Entry tempEntry = allValues.get(matchedIndex);
        tempDataSet.add(tempEntry);
    } else {
        if (tempDataSet.size() > 0) {
            rawDataSets.add(tempDataSet);
            tempDataSet = new ArrayList<>();
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.