算法 —— 3行3列包括9个字符的图形

试题描述:下图是一个3行3列包括9个字符的图形。
# #
 #
# #
第一层次的的打印效果和原图一样:
# #
 #
# #
第二层次的打印效果是一种9行9列的嵌套显示:
# #   # #
 #     #
# #   # #
   # #   
    #    
   # #   
# #   # #
 #     #
# #   # #
程序代码如下,请补充完整。

纯属个人见解,如果有什么问题、疑惑或者更好的算法,欢迎在评论区留言

 1 package cn.tudou;
 2 
 3 public class Demo9 {
 4     public static void main(String[] args) {
 5         String template[] = { "* *", " * ", "* *" };
 6         int level = 2;
 7         copy(template, template, level);
 8     }
 9 
10     private static void copy(String[] template1, String[] template2, int level) {
11         --level;
12         if (level > 0) {
13             int n1 = template1.length;
14             int n2 = template2.length;
15             String[] tmpTemplate = new String[n2 * n1]; // 第1行所缺代码
16             int k = 0;
17             String spaceS = spaceStr(n2);
18             for (int i = 0; i < n1; ++i) {
19                 for (int j = 0; j < n1; ++j) {
20                     k = i * n2;
21                     if (template1[i].charAt(j) == ' ') {
22                         for (int x = 0; x < n2; ++x) {
23                             if (tmpTemplate[k] != null)
24                                 tmpTemplate[k] += (spaceS);
25                             else
26                                 tmpTemplate[k] = new String(spaceS);
27                             k++;
28                         }
29                     } else {
30                         for (int x = 0; x < n2; ++x) {
31                             if (tmpTemplate[k] != null)
32                                 tmpTemplate[k] += template1[x]; // 第2行所缺代码
33                             else
34                                 tmpTemplate[k] = new String(template1[x]); // 第3行所缺代码
35                             k++;
36                         }
37                     }
38                 }
39             }
40             copy(template1, tmpTemplate, level); // 第4行所缺代码
41         } else
42             print(template2); // 第5行所缺代码
43     }
44 
45     private static String spaceStr(int n) {
46         StringBuilder sb = new StringBuilder();
47         for (int i = 0; i < n; ++i) {
48             sb.append(" ");
49         }
50         return sb.toString();
51     }
52 
53     private static void print(String[] template) {
54         int n = template.length;
55         for (int i = 0; i < n; ++i) {
56             System.out.print(template[i]);
57             System.out.println();
58         }
59     }
60 }

 

转载于:https://www.cnblogs.com/tudou1179006580/p/6940128.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值