2014-05-20 34 views
0

获得5个数字的序列我想从一个数组中获得5个数字的序列。 例如:如何从一个数组

int arr1[] = {3,88,99,5,4,6,22,32,7,45}; // array where there is the sequence 3,4,5,6,7 
Vector<Integer> myVec = new Vector<Integer>(); // vector wehre to save the sequence 

现在我有什么做的就是从数组的顺序? 我在这里有一个代码,但它不能正常工作:

for(int i = 0; i < arr1.length -1; i++) { 

    int a = arr1[i]; 
    int b = arr1[i+1]; 
    int c = b - a; 

    if(c == 1) { 
     myvec.add(arr1[i]); 
    } 
} 

我应该如何改变我的代码来解决这个问题?

+4

使用Arrays.sort(),然后套用您的逻辑 – TheLostMind

+1

不知道它是什么,你要acheive – Ar3s

+0

我想把序列“3,4,5,6, 7“从arr1在myvec。 – CMS

回答

1

此程序将打印阵列中的所有序列不排序阵列。你可以选择大小的列表..说如果你想匹配5序列获得大小为5的列表希望这个帮助。 (修改根据自己的需要。)

import java.util.ArrayList; 
import java.util.List; 

public class Sequence { 

    private static int arr1[] = { 3, 88, 99, 5, 4, 6, 22, 32, 7, 45 }; 

    private static int findNextInSequence(int start) { 
     int next = -1; 

     for(int i = 0; i < arr1.length; i++){ 
      if((start - arr1[i]) == -1){ 
       next = arr1[i]; 
      } 
     } 

     return next; 
    } 

    public static void main(String[] args) { 


     for (int i = 0; i < arr1.length; i++) { 

      List<Integer> sequence = new ArrayList<Integer>(); 
      int nextSequence = arr1[i]; 
      do{ 
       sequence.add(nextSequence); 
       nextSequence = findNextInSequence(nextSequence); 
      } while(nextSequence != -1); 

      System.out.println(sequence); 
     } 
    } 
} 
0

你的代码检查从ARR1阵列两个连续值之间的差值。因为它没有排序,它的工作原理是这样的:

88-3 !=1 (value not added) 
99-88 !=1 (value not added) 
5-99 !=1 (value not added) 
... 
45-7 !=1 (value not added). 

您必须确保数组中的值先排序。使用Arrays.sort()并在已排序的数组上应用该方法。这应该添加值:3,4,5,6,但它不会增加7(因为它会是你改编[I + 1]在循环执行的时间价值

4-3 ==1 (value added) 
5-4 ==1 (value added) 
6-5 ==1 (value added) 
7-6 ==1 (value added, but it is only number 6 that is added!) 
+0

有没有其他的可能性没有使用Arrays.sort()? – CMS

+0

您可以编写自己的排序方法,也可以比较每个数字。 – Niemand

+0

写自己的方法也无济于事,因为在排序的数组会发现“3”,然后跳过“5”,然后添加“4”。你将无法回到“5”。如果你不想排序数组,你可以尝试使用两个循环,但这是一个不同的错误做法。 – pshemek

0

你应该。计数连续计数高达5,并把结果存入ArrayList代替Vector。因为,ArrayListVector更有效。尝试,

int arr1[] = {3, 88, 99, 5, 4, 6, 22, 32, 7, 45, 11, 12, 13, 14, 15}; 
List<Integer> myVec = new ArrayList<>(); 

Arrays.sort(arr1); 

    int count = 0; 
    int lastValue = 0; 
    for (int i = 0; i < arr1.length - 1; i++) { 
     if (arr1[i + 1] - arr1[i] == 1) { 
      count++; 
      System.out.println(arr1[i]); 
      lastValue = arr1[i + 1]; 
     } else { 
      System.out.println(count); 
      if (count >= 4) { 
       for (int j = 0; j <= count; j++) { 
        myVec.add(lastValue - 4 + j); 
       } 
      } 
      count = 0; 
     } 
    } 
    System.out.println(myVec);