c# - 检查矩阵行是否是回文(数组中的数组)
问题描述
任务是我需要检查数组(二维数组)中的数组是否是回文问题是我在第 40 行得到一个“超出范围”异常,并且无法弄清楚如何告诉计算机在那里进行正确的计算: if (arr[i, j] != arr[arr.GetLength(1) - i, j - 1])
我需要解释 if (arr[i] != arr[n - i - 1])
二维数组。到目前为止,这是我的代码:```
class Program
{
static void Main(string[] args)
{
Random rnd = new Random();
int n;
n = Convert.ToInt32(Console.ReadLine());
int[,] arr = new int[n, n];
for (int i = 0; i < arr.GetLength(0); i++)
{
for(int j = 0; j < arr.GetLength(1); j++)
{
arr[i, j] = rnd.Next(1, 15);
}
}
for (int i = 0; i < arr.GetLength(0); i++)
{
for (int j = 0; j < arr.GetLength(1); j++)
{
Console.WriteLine(arr[i, j]);
}
}
int flag = 0;
for (int i = 0; i < arr.GetLength(0); i++)
{
for (int j = 0; j <= arr.GetLength(1) / 2 && n != 0; j++)
{
if (arr[i, j] != arr[arr.GetLength(1) - i, j - 1])
{
Console.WriteLine(i);
flag = 1;
break;
}
}
}
if (flag == 1)
{
Console.WriteLine("pali");
}
else
{
Console.WriteLine("not pali");
}
}
}
解决方案
正在寻找这样的东西吗?
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
int[,] arr = new int[,]
{
{ 1, 2, 3, 4, 5, 6 },
{ 1, 2, 3, 4, 5, 6 },
{ 1, 2, 3, 3, 2, 1 }, // Palindrome
{ 1, 2, 3, 4, 5, 6 },
{ 1, 2, 3, 4, 5, 6 }
};
PrintArray(arr);
CheckForPalindrome(arr);
}
static void PrintArray(int[,] arr)
{
for (int i = 0; i < arr.GetLength(0); i++)
{
for (int j = 0; j < arr.GetLength(1); j++)
{
Console.Write($"{arr[i, j]} ");
}
Console.WriteLine();
}
}
static void CheckForPalindrome(int[,] arr)
{
for (int i = 0; i < arr.GetLength(0); i++)
{
var equals = true;
for (int j = 0; j < arr.GetLength(1) / 2; j++)
{
equals = arr[i, j] == arr[i, arr.GetLength(1) - j - 1];
if (equals == false)
break;
}
if (equals == true)
Console.WriteLine($"Row {i + 1} is palindrome");
}
}
}
}
推荐阅读
- git - Git 日志以按类型排序显示用户修改过的文件
- php - Contact Form 7 中需要做什么才能将数据发送到 php?
- mongodb - mongo更新的内部实现是什么,创建一个新的文档弃用现有的或者重写现有的值
- java - 如何修复错误:无法将类型“java.lang.String”的值转换为所需类型“java.lang.Long”;
- awk - gawk -e 'BEGIN {' -e 'print "hello" }' 是如何工作的?
- mysql - 如何关联数据,但前提是在特定日期之前?
- javascript - 有没有办法在 VS Code 的外部模块中获取所有建议?
- python-3.x - 使用 Pandas to_sql 将数据帧写入 DB2 时出错
- r - 为什么我的 xts 对象在索引字段中有一个 X?
- android - 尝试使用 exoplayer 流式传输加密视频时出错