如何创建循环以在给定条件的情况下分配值?

How to creat a loop to assign a value given a condition?

所以我尝试了不同类型的视觉基本代码来解决这个我试图解决的问题,但没有一个有效:(

我有一个锯齿状数组,例如 {{1 10 20 50 53};{5 15 25 55}}

并且我想将此信息转换为二进制矩阵,条件是锯齿状数组中的每个数组对应一行,其中的元素对应一个列号。我说清楚了吗?

矩阵的行数与锯齿状数组 2 中的数组数相同,但矩阵的列数可以达到 200。

1 0 ... 1 ... 1 ... 1 .. 1..................0
0 0 ... 1 ... 1 ... 1 .... 1 ...............0

我最后一次尝试是这个:

    For a = 0 To noRows - 1
        For b = 0 To noCols - 1
            Do While d < jarray(a).GetUpperBound(0)
                If array(a)(d) = b Then
                    matrix(a, b) = 1
                    Exit Do
                Else
                    matrix(a, b) = 0
                    d += 1
                End If
            Loop
        Next
    Next

我该怎么办?

当你创建一个新数组时,它的值会自动初始化为数组中变量类型的默认值 - 对于整数,即 0。因此你不需要将设置设置为零,除非问题中还有其他内容未显示。

你有需要设置为1的位置的索引,所以你可以直接这样做:

Option Infer On
Option Strict On

Module Module1

    Sub Main()
        'Dim jArray = {New Integer() {1, 10, 20, 50, 53}, New Integer() {5, 15, 25, 55}}

        Dim jArray = {New Integer() {1, 3, 4}, New Integer() {2, 5, 6, 7, 9}}

        ' find the number of columns needed for the resultant array
        Dim nCols = jArray.Max(Function(r) r.Max())

        ' find the number of rows needed for the resultant array
        Dim nRows = jArray.GetUpperBound(0) + 1

        ' the resultant array is automatically initialised to zeros
        Dim matrix(nRows, nCols) As Integer

        ' fill in the ones as specified by the locations in jArray:
        For i = 0 To nRows - 1
            For j = 0 To jArray(i).GetUpperBound(0)
                matrix(i, jArray(i)(j) - 1) = 1
            Next
        Next

        ' show the resultant array:
        For i = 0 To nRows - 1
            For j = 0 To nCols - 1
                Console.Write(matrix(i, j) & If(j < nCols - 1, ", ", ""))
            Next
            Console.WriteLine()
        Next

        Console.ReadLine()

    End Sub

End Module

输出:

1, 0, 1, 1, 0, 0, 0, 0, 0
0, 1, 0, 0, 1, 1, 1, 0, 1