[英]Finding first and last true values in a matrix
在二維數組的情況下,您可以嘗試嵌套循環; 您可能想要第 1 個和最后一個1
秒的索引:
int[,] data = new int[,] {
{ 0, 0, 0, 1, 1, 1, 0, 0, 0, 0},
{ 0, 1, 1, 1, 1, 0, 0, 0, 0, 0},
};
(int first, int last)[] result = new (int first, int last)[data.GetLength(0)];
for (int r = 0; r < data.GetLength(0); ++r) {
int min = -1;
int max = -1;
for (int c = 0; c < data.GetLength(1); ++c) {
//ToDo: change into "if (data[r, c]) {" if data is of type bool[,]
if (data[r, c] == 1) {
max = c;
min = min < 0 ? c : min;
}
}
result[r] = (min, max);
}
現在您可以使用result
數組進行操作,例如
int FirstRowLast = result[0].last;
int SecondRowFirst = result[1].first;
我們來看看:
Console.Write(string.Join(Environment.NewLine, result));
結果:
(3, 5)
(1, 4)
using System;
public class Program
{
public static void Main()
{
int[,] arr = new int[2, 10]{
{0,0,0,1,1,1,0,0,0,0},
{0,1,1,1,1,0,0,0,0,0}
};
int last = -1;
int first = -1;
for(int i = 0; i < 2; i++){
for(int j = 0; j < 10; j++){
if(arr[i,j] == 1){
if(first == -1){
first = j;
}
last = j;
}
}
Console.WriteLine("Row " + i + " -> " + "First : " + (first + 1) + " | Last: " + (last + 1));
first = -1;
last = -1;
}
}
}
輸出
Row 1 -> First : 4 | Last: 6
Row 2 -> First : 2 | Last: 5
在輸出中假設第一個索引為 1。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.