爪哇算法做出直金字塔 [英] Java algorithm to make a straight pyramid

查看:104
本文介绍了爪哇算法做出直金字塔的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

___________1
__________1 2 1
_________1 2 3 2 1
________1 2 3 4 3 2 1
______1 2 3 4 5 4 3 2 1
_____1 2 3 4 4 4 4 4 3 2 1
___1 2 3 3 3 3 3 3 3 3 3 2 1
__1 2 2 2 2 2 2 2 2 2 2 2 2 2 1
_1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1

我想使用Java这个金字塔?任何建议?

I would like to create this pyramid using java? Any suggestion?

推荐答案

这将surve的目的。您可以更改号码5至另一号码比5。如其他。 1,2,3,...,6,8

This will surve the purpose. You can change the number 5 to another number other than 5. eg. 1,2,3,.. , 6,8

public static void main(String[] args) {


    List<String> list = new LinkedList<String>();

    for(int i = 5; i > 0; i-- ){
        wrapWithNumber(list, i);
    }


    for (String string : editListToBeInTriangleShape(list)) {
        System.out.println(string);
    };
}

/**
      * Wrap the number strings in the llist with a perticular number.
 * @param list list of Strings
 * @param ba number which need to wrapp the list with.
 */
private void wrapWithNumber(List<String> list, final int ba) {

    list.add(0, String.format("%d",ba));

    for (int i = 1; i < list.size(); i++) {
        String newformat = "%1$d " + list.get(i) + " %1$d";
        list.remove(list.get(i));
        list.add(i,String.format(newformat, ba));
    }

    String lastFormat = "%1$d";
    for(int i = 0; i < 2 * list.size();i++){
        lastFormat += " %1$d";
    }

    if(list.size() != 1) {
        list.add(String.format(lastFormat, ba));
    }
}

/**
 * Arrage the Strings in the list in triangular manner.
 * @param list list of Strings.
 */
private List<String> editListToBeInTriangleShape(final List<String> list) {

    final List<String> returnList = new LinkedList<String>();

    for (int i = list.size(); i > 0; i--) {
        String s = list.get(list.size()-i);
        int possition = list.size()*2 + s.length()/2;
        returnList.add(String.format("%"+possition+"s", s));
    }

    return returnList;
}

放出来了这一点:

out put of this :

                 1
               1 2 1
             1 2 3 2 1
           1 2 3 4 3 2 1
         1 2 3 4 5 4 3 2 1
       1 2 3 4 4 4 4 4 3 2 1
     1 2 3 3 3 3 3 3 3 3 3 2 1
   1 2 2 2 2 2 2 2 2 2 2 2 2 2 1
 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1

这篇关于爪哇算法做出直金字塔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆