[英]Hollow Square of given String
我正在尝试编写一个接受 3 个参数并返回一个空心方块的方法。
第一个方法参数 = 字符串的长度。 第二个方法参数 = 正方形的一个 arm 中有多少个字符。 第三个方法参数 = 字符串。
条件:例如,如果第二个参数是 4,那么形成一个正方形总共需要 12 个字符,如果给定的字符串是排序器,那么它将被重复(abcdefghabcd)。
我写了一个代码,但这并不满足几个条件。
public void patternmaker(int a, int b, String s) {
try {
int p = -2, q = 0, z = 0;
for (int x = 1; x <= b; x++) {
for (int y = 1; y <= b; y++) {
if (x == 1) {
System.out.print(s.charAt(y + b - 2) + " ");
} else if (x == b && y > 1) {
System.out.print(s.charAt(a + z - 1) + " ");
z = z - 1;
} else if (x == b && y == 1) {
System.out.print(s.charAt(0) + " ");
} else if (y == 1 && x > 1 && x < b) {
System.out.print(s.charAt(b + p) + " ");
p = p - 1;
} else if (y == b && x > 1 && x < b) {
System.out.print(s.charAt(2 * b - 2 + x - 1) + " ");
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
catch (Exception e) {
}
}
例如参考图片
有什么建议或意见吗?
这是一个以顺时针螺旋形式写入字符串的答案:
public void patternmaker(int a, int b, String s)
{
for(int y=b-1 ; y >=0 ; y--)
{
for(int x=0; x <b; x++)
{
if ( y == b-1) // top row
{
// left colum string indices 0,1,... such
// that x=0 is index b-1
System.out.print( s.charAt((b-1+x)%a) + " " ) ;
}
else if ( y < b-1 && y > 0) // intermediate rows
{
if ( x==0 )
// left column
System.out.print( s.charAt(y%a) + " " ) ;
else if ( x== b-1 )
// right column top element is index 2*b-2
System.out.print( s.charAt((2*b-2+(b-1-y))%a) + " " ) ;
else
// hole
System.out.print( " " ) ;
}
else // bottom row
{
if ( x > 0 )
// rightmost elemnt is index 3*b-3, increase by 1 if x decreases by 1
System.out.print( s.charAt((3*b-3+(b-1-x)) %a) + " " ) ;
else
System.out.print( s.charAt(0) + " " ) ;
}
}
System.out.println() ;
}
}
有多种方法可以解决这个问题。
创建一个二维数组,其尺寸与正方形的边相同。 遍历字符串元素并填充数组。 打印数组的所有元素。
这虽然很容易实现,但随着正方形的变大,将需要大量的 memory。
与第一种方法相比,这种方法更有效(时间和内存)。
public class Main
{
public static void patternmaker(int length, int side, String s) {
try {
char ch;
int idx = side - 1;
//first row
for (; idx <= 2*(side - 1) ; idx++)
{
ch = s.charAt(idx%length);
System.out.print(ch + " ");
}
System.out.println();
//middle rows
for (; idx < 3*(side - 1) ; idx++)
{
ch = s.charAt((3*(side - 1) - idx)%length);
System.out.print(ch + " ");
for (int spaceNo = 2 ; spaceNo < side ; spaceNo++)
{
System.out.print(" ");//Two spaces inside
}
ch = s.charAt(idx%length);
System.out.println(ch + " ");
}
//last row
System.out.print(s.charAt(0) + " ");
for (idx = 4*(side - 1) - 1 ; idx >= 3*(side -1); idx--)
{
ch = s.charAt(idx%length);
System.out.print(ch + " ");
}
System.out.println();
}
catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
patternmaker(8, 6, "12345678");
System.out.println();
patternmaker(3, 4, "123");
System.out.println();
patternmaker(2, 5, "12");
System.out.println();
patternmaker(5, 5, "13579");
System.out.println();
patternmaker(4, 8, "2468");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.