2014-05-20 35 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);