In a method I am calculating the longest row of elements. The 1-dimensional array is filled up with random values (0 or 1). The method looks up the longest row (being 0 or 1, whatever is the longest).
For example:In 1110100
the longest row would be 3开发者_如何学Go (3 * 1)
0110000
the longest row would be 4 (4 * 0)
For 1110100
the position in the array would be 0 to 2.
For 0110000
the position in the array would be 3 to 6.
I have been trying with foreach
loops, for
loops, etc. but I cannot seem to get the proper indexes of both and cannot seem to display both positions properly.
The longest row of similar elements gets calculated as the following based on my previous question:
public int BerekenDeelrij (int [] table)
{
int count = 0;
int value = 0;
int largest = 0;
for (int i=0; i < tabel.Length; i++)
{
if (value == tabel[i])
counter + +;
else
{
largest = Math.Max largest (largest, counter);
final value = value
count = 1;
}
}
return Math.Max(largest, counter);
}
If you replace the foreach()
with a regular for(;;)
you immediately have your indices available at the moment you need them.
I'm not posting complete code, since this is tagged homework, but a completely different approach to solving this problem, would be to find all the occurrences of consecutive items, and aggregate them into a new array:
[0, 1, 1, 0, 0, 0, 0] => ["0", "11", "0000"]
Then you could just order that by item.Length
, descending, select top 1 item, i.e. "0000"
After that, join the aggregated array
["0", "11", "0000"] => "0110000"
And from there, return joinedResult.IndexOf( longestItem )
and that index + longestItem.Length
精彩评论