我有一个按顺序放置的整数列表。我想获取连续整数组作为数组,每个组的第一个和最后一个整数。
例如,对于(2,3,4,5,8,10,11,12,15,16,17,18,25)我想获取包含这些数组的列表:[2,5] [8,8 ] [10,12] [15,18] [25,25]
这是我的代码:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MyRangesTest {
public static void main(String[] args) {
//create list of integers
List<Integer> list=Arrays.asList(2,3,4,5,8,10,11,12,15,16,17,18,25);
System.out.println("list:" + list);
//create a list with integers where a new sequense of consecutive integers starts or ends
List<Integer> sublistsStarsAndEnds= new ArrayList<>();
sublistsStarsAndEnds.add(list.get(0));//1st line (always in sublistsStarsAndEnds list)
for (int i=1; i<list.size()-1; i++){
if (list.get(i)>1+list.get(i-1)){
sublistsStarsAndEnds.add(list.get(i-1));
sublistsStarsAndEnds.add(list.get(i));
}
}
sublistsStarsAndEnds.add(list.get(list.size()-1));//last line (always in sublistsStarsAndEnds list)
System.out.println("sublistsStarsAndEnds: " + sublistsStarsAndEnds);//present the result
//create list with arrays that represents start and end of each subrange of consequent integers
List<Integer[]> ranges= new ArrayList<>();
for (int i=0; i<sublistsStarsAndEnds.size()-1; i=i+2){
Integer[] currentrange=new Integer[2];
currentrange[0]=sublistsStarsAndEnds.get(i);
currentrange[1]=sublistsStarsAndEnds.get(i+1);
ranges.add(currentrange);//present the result
}
//present the result
String rangestxt="";//create result text
for (int i=0; i<ranges.size(); i++){
rangestxt=rangestxt+ranges.get(i)[0]+ " " + ranges.get(i)[1]+ " ";
}
System.out.println("ranges: " + rangestxt);//present the result
}
}
该代码在一般情况下可以满足我的需要,但是当最后一个序列只有1个整数时,它将无法获得正确的结果。
例如,使用以下列表时:(2,3,4,5,8,10,11,12,15,16,17,18,25)而不是获得范围[2,5] [8,8] [ 10,12] [15,18] [25,25]我们得到了范围[2,5] [8,8] [10,12] [15,25]。
问题在于检测范围的开始或结束位置。在我的代码中,这些位置存储在sublistsStarsAndEnds
列表中。在这里,我们得到的不是[2、5、8、8、8、10、12、15、15、25、25],而是得到的[2、5、8、8、10、12、15、25]。我试图更正代码,但结果不理想。
有什么建议吗?
PS有人想得到我想要的结果,然后在这里向Python提问:“识别列表中的连续数字组,但是我不了解Python,所以我尝试了自己的编码。
试试这个
public static void main(String[] args) {
List<Integer> list=Arrays.asList(2,3,4,5,8,10,11,12,15,16,17,18,19,25);
List<List<Integer>>lList=new ArrayList<List<Integer>>(); //list of list of integer
System.out.println("list:" + list);
int i=0;
int start=0;
List<Integer> sList=new ArrayList<Integer>(2);
for( i = 1; i <list.size();i++){
if( list.get(i - 1) + 1 != list.get(i)){
sList.add(list.get(start));
sList.add(list.get(i-1));
lList.add(sList);
sList=new ArrayList<Integer>(2);
start=i;
}
}
sList.add(list.get(start)); // for last range
sList.add(list.get(list.size()-1));
lList.add(sList);
System.out.println("Range :"+lList);
}
输出 :
list:[2, 3, 4, 5, 8, 10, 11, 12, 15, 16, 17, 18, 19, 25]
Range :[[2, 5], [8, 8], [10, 12], [15, 19], [25, 25]]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句