我有一個填充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*/
}