首页 > 解决方案 > 基于线性键中的间隙分离数组

问题描述

我希望根据键中的间隙将单个数组分成单独的数组。例如采取这种情况:

我正在尝试为每月的连续几天创建单独的数据集(数组)。如果错过了一天,则需要从具有值的第二天开始创建新的数据集。

数据在一个数组中检索,如下所示:

[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();
        }
    }
}

标签: javaarrays

解决方案


这样的事情应该可以解决问题:

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);
}

推荐阅读