簡體   English   中英

在矩陣中查找第一個和最后一個真值

[英]Finding first and last true values in a matrix

我有一個包含 bool 值的二維數組。 我需要我的腳本來查找數組第一行的第一個和最后一個“真”值,並對第二行執行相同的操作(矩陣將始終有兩行)。 下面是我可以擁有的矩陣示例,黃色值是我必須對其執行指令的值: 在此處輸入圖片說明

如果之前有人問過這個問題,我很抱歉,但我找不到任何有用的東西。

在二維數組的情況下,您可以嘗試嵌套循環 您可能想要第 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM