【问题标题】:How to creat a loop to assign a value given a condition?如何创建循环以在给定条件的情况下分配值?
【发布时间】:2018-05-02 21:40:47
【问题描述】:

因此,我尝试了不同类型的 Visual Basic 代码来解决我正在尝试解决的问题,但它们都不起作用:(

我有一个锯齿状数组,例如 {{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

我该怎么办?

【问题讨论】:

    标签: arrays vb.net for-loop do-while jagged-arrays


    【解决方案1】:

    当你创建一个新数组时,它的值会自动初始化为数组中变量类型的默认值 - 对于整数,即 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

    【讨论】:

    • 非常感谢!我只是太复杂了!它确实符合您在我的代码中提出的逻辑!万事如意!
    猜你喜欢
    • 2020-10-17
    • 2013-07-16
    • 2021-05-23
    • 1970-01-01
    • 1970-01-01
    • 2011-10-15
    • 2011-02-14
    • 2021-08-24
    • 2011-03-30
    相关资源
    最近更新 更多