import java.util.*;
import java.lang.*;
import java.io.*;
class Ideone
{
private static Random RND = new Random(System.currentTimeMillis()); // useful for placing balls
private static char[] BALLS = {'o','⌾','⛣','⏣','◍'}; // symbols being used as balls
public static void main (String[] args) throws java.lang.Exception
{
int w = 27; // width of the tree
int b = 10; // number of balls in the tree
String tree = ""; // this will end up containing the tree
// build tree
w = ( w % 2 == 1 ) ? w : 13; // check whether width is odd
for(int i=1;i<=w;i+=2){
int s = (w - i) / 2;
tree += repeat(' ', s) + repeat('*', i) + repeat(' ', s) + "\n";
}
// randomly replace some parts by balls
int i=0;
while(i < b){
int j = RND.nextInt(tree.length());
if(tree.charAt(j) == '*'){
tree = tree.substring(0, j) + BALLS[RND.nextInt(BALLS.length)] + tree.substring(j+1);
i++;
}
}
// build trunk
tree += repeat(' ', (w - 4) / 2) + repeat('*', 4) + "\n" + repeat(' ', (w - 4) / 2) + repeat('*', 4);
// output
System.out.println(tree);
}
// this function builds a String by repeating a given character a couple of times
private static String repeat(char c, int l){
String s = "";
for(int i=0;i<l;i++)
s += c;
return s;
}
}
function xmas(height) {
// add 1 more level for the trunk, e.g. height+1
return Array.from({length: height+1}, (v, i) => {
return i === height
// that's for the trunk of the tree
? '*'.padStart(Math.round((2 * i)/2), ' ')
// the actual tree "levels"
: '*'.repeat(2 * i + 1).padStart(2 * i + height-i, ' ');
}).join('\n');
}
document.write(`<pre>${xmas(10)}</pre>`);
function christmas(n) {
let tree = '';
for (let i = 1; i <= n; i++) {
for (let j=0; j <= n-i; j++) {
tree += ' ';
}
for (k = 0; k< (i*2)-1; k++) {
tree += '*';
}
tree += '\n';
}
return tree;
}
console.log(christmas(3));
8条答案
按热度按时间ffvjumwh1#
来源:http://codeforwin.org/2015/07/equilateral-triangle-star-pattern-program-in-c.html
C到JavaScript的转换。
wlsrxk512#
我为这个问题编写了下面的代码。
我还加了一个额外的圣诞树装饰品:-)
输出应如下所示:
8yparm6h3#
关键字是思考。
制约因素:* 只是看起来不错 * 从
x = 5
开始。iqxoj9l94#
上面的答案严重依赖于嵌套循环,我曾用“现代”JS发布过另一种方法(当然,仍然使用单个循环,并为
Array.from()
提供map函数):也许尝试让它与
.padStart()
一起工作并不是最优的,因为数学变得有点丑陋,但无论如何,只是为了好玩=)...fdx2calv5#
简易采油树功能:
zxlwwiss6#
如果您正在寻找如何在javascript或typescript的函数中执行此操作
循环使用3,1 -行数2 -空格数3 -字符数
soat7uwm7#
cngwdvgl8#
我只是在参加一个编程课程时做了一个练习,这里有一个简单的for循环,没有任何嵌套循环