[英]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.