java - 零的外部框架
问题描述
我写了这段代码。出于某种原因,我得到了新矩阵,但原始矩阵的最后一个值似乎丢失了......
public static char[][] Frame_of_zeros(char[][]a)//builds an external frame of zeroes
{
char[][]c3=new char[a.length+1][a[0].length+1];
for(int i=0,j=0;i<c3.length;i++)//left column is composed of zeroes
{
c3[i][j]='0';
}
for(int j=0,i=0;j<c3[0].length;j++)//upper row of zeroes
{
c3[i][j]='0';
}
for(int i=c3.length-1,j=0;j<c3[0].length;j++)//most lower row composed of zeroes
{
c3[i][j]='0';
}
for(int i=0,j=c3[0].length-1;i<c3.length;i++)//right column is composed of zeroes
{
c3[i][j]='0';
}
for(int i=1,k=0;i<c3.length-1&&k<a.length;i++,k++)//i for the modified and k is the original
{
for(int j=1,l=0;j<c3[0].length&&l<a[0].length-1;j++,l++)//j for the modified and l is the original
{
c3[i][j]=a[k][l];
}
}
return c3;
}
解决方案
外部框架意味着您必须分别添加两行/列(左和右/上和下),因此您需要通过额外的行和列来增加新矩阵的大小。
将帧设置为 0 的循环很好。
在最后一个内循环中,您将初始矩阵的减小大小设置为条件,而不是像外循环中那样设置新矩阵。
public static char[][] Frame_of_zeros(char[][]a)//builds an external frame of zeroes
{
char[][]c3=new char[a.length+2][a[0].length+2];
for(int i=0,j=0;i<c3.length;i++)//left column is composed of zeroes
{
c3[i][j]='0';
}
for(int j=0,i=0;j<c3[0].length;j++)//upper row of zeroes
{
c3[i][j]='0';
}
for(int i=c3.length-1,j=0;j<c3[0].length;j++)//most lower row composed of zeroes
{
c3[i][j]='0';
}
for(int i=0,j=c3[0].length-1;i<c3.length;i++)//right column is composed of zeroes
{
c3[i][j]='0';
}
for(int i=1,k=0;i<c3.length-1 && k<a.length;i++,k++)//i for the modified and k is the original
{
for(int j=1,l=0;j<c3[0].length-1 && l<a[0].length;j++,l++)//j for the modified and l is the original
{
c3[i][j]=a[k][l];
}
}
return c3;
}
推荐阅读
- nginx - 我正在尝试使用 Nginx 配置 Flask 应用程序
- python - 空列:对象是 'float' 并且没有 len()
- ios - 如果我有 iPhone,是否可以在 Windows 上调试 Flutter/React Native IOS 应用程序?
- amazon-web-services - 如何通过 IGW 提供对 Internet 的子网访问?
- python - 通过在“;”处拆分值来计算字典列表中特定键的值计数器
- python - 计算缺失数据的数据框的平均值
- javascript - 如何通过 ID 获取用户
- r - 根据 r 中的行和将行值更改为 0
- amazon-web-services - DynamoDB 使用无服务器 Python 模板为正文提供 KeyError
- javascript - ReactJS:如何在循环中维护多个 ReadMore/ReadLess 按钮的索引