用Java算法制作直角金字塔

用Java算法制作直角金字塔,第1张

用Java算法制作直角金字塔

这将达到目的。您可以将数字5更改为5以外的其他数字。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);    };}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));    }}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;}

放出这个:

      1    1 2 1  1 2 3 2 11 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


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5615449.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存