2010-05-23 32 views
0

我有一個填充40個隨機元素(所有的值都是0或1)表的一維數組。我想找到最長的連續值。1維陣列計數相同的元素

例如:

111100101最長的行會是1111因爲它有1連續四個值。

011100結果是111

我不知道如何檢查「下一個元素」,並檢查它是否爲0或1. 像第一個將是1111(第4個),但接下來將是0值,這意味着我必須停止計數。

我的想法是將這個值(4)放在另一個數組(例如:111100101)中,並將1的值置回零。並重新開始整個過程​​。

要找到最大的值,我已經做了另一種方法來檢查數組中最大的值,以跟蹤0的數量1,這不是問題。

但我找不到填充數組tabelLdr的方式,具有相同類型的元素組(0或1)的所有值。

在下面的代碼我有2如果的,當然它決不會進入第二,如果(檢查,如果陣列中的下一個值是!=到其當前狀態(即0或1)。

public void BerekenDeelrij(byte[] tabel, byte[] tabelLdr) 
{ 
    byte LdrNul = 0, Ldréén = 0; 
    //byte teller = 0; 

    for (byte i = 0; i < tabel.Length; i++) 
    { 
     if (tabel[i] == 0) 
     { 
      LdrNul++; 
      //this 2nd if cleary does not work, but i have no idea how to implend this sort of idea in my program. 
      if (tabel[i] == 1) //if value != 0 then the total value gets put in the second array tabelLdr, 
      { 
       tabelLdr[i] = LdrNul; 
       LdrNul = 0 
      } 
     } 

     if (tabel[i] == 1) 
     { 
      Ldréén++; 
      if (tabel[i] == 0) 
      { 
       tabelLdr[i] = Ldréén; 
       Ldréén = 0; 
      } 
     } 

    }/*for*/ 
} 

回答

1

這個方法應該做你需要的東西:

public int LargestSequence(byte[] array) { 
    byte? last = null; 
    int count = 0; 
    int largest = 0; 
    foreach (byte b in array) { 
    if (last == b) 
     ++count; 
    else { 
     largest = Math.Max(largest, count); 
     last = b; 
     count = 1; 
    } 
    } 
    return Math.Max(largest, count); 
} 
0

即使在i是循環計數器,它仍然只是一個變量。有效for語句是for (;;),這是一個無限循環。注意for聲明增量i,爲i++,表達i = i + 1作品一樣好。

0

林不確定,如果你需要的是0或1的人的最長的「行」或最長的行這將後者

var max = 0; 
var start = 0; 
var current = -1; 
var count = 0; 
for(int i = 0;i<table.Length;i++) 
{ 
    if(current = table[i]) 
    { 
     count++; 
    } 
    else 
    { 
     current = table[i]; 
     if(max < count) 
     { 
     max = count; 
     start = i-count; 
     } 
     count = 1; 
    } 
} 

if(max < count) 
     { 
     max = count; 
     start = i-count; 
     } 

工作// max是從開始處開始的行的長度;