如何计算二维数组

时间:2014-09-24 15:41:25

标签: vb.net

我有一个字段,[答案]

2;3;3;3;3;3;3;3;3
2;3;4;3;1;1;1;2;2
3;1;3;2;1;1;1;1;1
2;1;4;2;1;1;1;1;1

答案来自1(最低)4(最高)。我需要计算列数。例如,对于问题1,有3个数字2&#;;有1个数字3.问题2 - 有2个数字3和2个数字1和#s等。假设数据表中的所有行和拆分函数都很好。 我曾尝试使用二维数组,但计数不正确。

Dim ansArr(16, 3) As Integer   '2-D array; 17 questions and 4 possible answers
    For I As Integer = 0 To dt.Rows.Count - 1    'loop through a row of datatable
        Dim Answer() As String = dt.Rows(I).Item(3).Split(";") 'split answer and store into array
        For j As Integer = 0 To 16
            For k As Integer = 0 To 3
                k = (Val(Answer(j)))
                ansArr(j, k - 1) += 1
            Next
        Next
 Next
For Each a_ansArr As Integer In ansArr
        MessageBox.Show(a_ansArr.ToString)
Next

2 个答案:

答案 0 :(得分:1)

如果我理解你的想法,我相信我会看到这个问题。

For k As Integer = 0 To 3 
   k = (Val(Answer(j)))
   ansArr(j, k - 1) += 1
Next

似乎正在计数然后在j位置多次回答你应该只计算每个答案一次。我相信For循环是redunandt,应该用

代替
k = (Val(Answer(j)))
ansArr(j,k-1) += 1

因此修改后的代码将是

Dim ansArr(16, 3) As Integer   '2-D array; 17 questions and 4 possible answers
For I As Integer = 0 To dt.Rows.Count - 1    'loop through a row of datatable
    Dim Answer() As String = dt.Rows(I).Item(3).Split(";") 'split answer and store into array
    For j As Integer = 0 To 16
       k = (Val(Answer(j)))
       ansArr(j, k - 1) += 1
    Next
Next
For Each a_ansArr As Integer In ansArr
    MessageBox.Show(a_ansArr.ToString) 
Next

答案 1 :(得分:1)

我是在控制台而不是WinForms中完成的,但原理是一样的。我将切换到SortedList(Of Integer, Integer),而不是使用库存二维数组。由于您为每个问题保留了一笔款项,因此您的问题是“键入的”#34;按编号,您应该最终得到17个条目的列表,每个条目按问题编号键入。您存储在列表中的值是当前"运行"总和,然后最终通过密钥(问题编号)访问:

    Dim answerSums As New SortedList(Of Integer, Integer)

    ' I have substituted a simple string array in place
    ' Of your data source. 
    Dim rows As String() = {
        "1;2;3;1;2;3;2;2;2;1;2;3;1;2;3;2;2",
        "1;2;3;1;2;3;2;2;2;1;2;3;1;2;3;2;2",
        "1;2;3;1;2;3;2;2;2;1;2;3;1;2;3;2;2",
        "1;2;3;1;2;3;2;2;2;1;2;3;1;2;3;2;2"
    }

    ' Cycle through your data rows
    For I As Integer = 0 To rows.Count - 1

        ' Get your split questions values
        Dim Answer() As String = rows(I).Split(";")

        ' Cycle through each answer value
        For J As Integer = 1 To Answer.Length

            ' Convert it to a calculable number
            Dim newSum As Integer = Convert.ToInt32(Answer(J - 1))

            ' If it already exists in your SortedList, add it to the previous value
            If (answerSums.ContainsKey(J)) Then
                newSum += answerSums(J)
            End If

            ' Set the SortedList value to the new summation
            answerSums(J) = newSum
        Next
    Next

    For Each key As Integer In answerSums.Keys
        Console.WriteLine("Answer {0} sum: {1}{2}", key.ToString(), answerSums(key).ToString(), Environment.NewLine)
    Next

    Console.ReadLine()