【问题标题】:Checking every element of two dimensional array is sorted in ascending order or not检查二维数组的每个元素是否按升序排序
【发布时间】:2018-02-03 13:59:02
【问题描述】:

实际上,我正在尝试制作一个数字益智游戏,在该游戏中,您必须将打乱的数字移动到空白处,并最终将所有 15 个数字按升序排列。我可以玩游戏的所有数字并对其进行排序,但是在检查所有数字是否按升序(即从 1 到 15)排序时,我没有得到所需的结果。这是完成检查并宣布结果的游戏的最后一部分。我尝试了很多,最终我输入了愚蠢的 if else 条件。 我不想要现成的代码,一个小的提示或过程将不胜感激。

/*My two dimensional array is of 4 * 4 dimension.
Initially to test whether all the elements are sorted in ascending order or 
not
I took a casual approach, the same we use in for one dimensional array.*/

for(int i = 0; i < row; i++) //row = 4
{
    for(int j = 0; j < col; j++) // col = 4
    {
        int k = j + 1;
        if(k != 4)
        {
            if(array[i][j] < array[i][k])
                continue;
        }
    }
}

/*But this above code isn't the right code because it checks whether each 
 and every row is correctly sorted or not
 So even if my output is 
 1 2 3 4
 5 6 7 8
 9 10 13 14
 11 12 15 _ 
 it will say game completed or you have won whereas my expected output was 
 this 
 1 2 3 4
 5 6 7 8
 9 10 11 12
 13 14 15 _  ***UNDERSCORE SIGN IS MEANT FOR BLANK SPACE */`

【问题讨论】:

  • 您好,欢迎来到 SO。你能告诉我们更多吗?我们在这里谈论的是什么语言?您能否向我们展示您有问题的部分代码?
  • 抱歉没有上传代码。这里是! @rsm

标签: arrays sorting multidimensional-array


【解决方案1】:

如果您不使用 VB,那么这将是伪代码:

Function ArrayIsOrdered(arr(,) As Integer) As Boolean
    Dim xSize = arr.GetUpperBound(0)
    Dim ySize = arr.GetUpperBound(1)

    ' set a temporary variable to the lowest possible value
    Dim x = Integer.MinValue

    ' iterate over the array
    For j = 0 To ySize
        For i = 0 To xSize
            ' if this value is less than the previous value
            ' then the array is not in order
            If arr(i, j) < x Then
                Return False
            End If
            ' save this value for the next comparison
            x = arr(i, j)
        Next
    Next

    ' everything must have been in order
    Return True

End Function

以撇号开头的行是 cmets。

您需要确定您使用的是横向和向下的数组维度。

如果您有一个未占用方格的魔法值,那么您当然需要忽略具有该值的单元格。

【讨论】:

    猜你喜欢
    • 2022-01-20
    • 1970-01-01
    • 2021-02-03
    • 2021-05-23
    • 1970-01-01
    • 2016-02-17
    • 2021-12-06
    • 2018-08-01
    • 2021-03-27
    相关资源
    最近更新 更多