将oneD阵列转换为2D阵列?

时间:2017-11-24 11:13:01

标签: arrays vb.net console-application

我搜索了我的问题,但我变得无望,我想通过记录我需要一般解决方案(不知道数组的长度)将一维数组的值转换为二维数组也是我不想使用像Array.copy这样的就绪函数。 PS:长度将由用户确定,但必须是方阵。 这是我将二维阵列转换为一维阵列的代码,但我却反对做相反的事情:

Public Sub TransferTo1D(ByRef B(,) As Integer)
   Dim ARR1D(B.Length - 1) As Integer, e As Integer = 0
    For i = 0 To B.GetUpperBound(0)
        For j = 0 To B.GetUpperBound(1)
            ARR1D(e) = B(i, j)
            e += 1
        Next
    Next
End Sube

感谢您的帮助< 3

1 个答案:

答案 0 :(得分:0)

这是一个可能的解决方案。

Public Function TransferTo2D(ByRef inArray() As Integer) As Integer(,)
    Dim dimSize as Integer

    'Size of one dimention of outArray needs to be the square root of inArray's size
    dimSize = Math.Sqrt(inArray.length)

    'If inArray isn't convertable to a square matrix build a square matrix that is just big enough to hold inArray's values
    While (dimSize*dimSize) < inArray.length
        dimSize = dimSize + 1

    End While

    Dim outArray(dimSize, dimSize) As Integer
    Dim counter as Integer

    counter = 0;

    'Brainless copying
    For i = 0 To dimSize - 1
        For j = 0 To dimSize - 1
            If counter < inArray.length Then ' If inArray still has values
                outArray(i, j) = inArray(counter)
                counter = counter + 1

            Else ' If inArray is out of values and outArray isn't already filled
                outArray(i, j) = 0

            End If
        Next

    Next

    Return outArray

End Function

首先计算inArray.length的平方根并将其分配给dimSize。之后dimSize增加,直到它足够大以容纳inArray(inArray可能没有自然平方根计数)。之后,我们只需逐行复制到大小为(dimArray, dimArray)的新数组中。