var i, j;
for (i = 1; i <= 19; i++) {
for (k = 1; k <= i; k++) {
document.write("*");
}
document.write("<br/>");
}
<div id="output"></div>
Trying to create this pattern and not sure of the best way of how to get it decrement after 10th row:
*
**
***
****
*****
******
*******
********
*********
**********
*********
********
*******
******
*****
****
***
**
*
First increase the loop from 1 to 10 then make a loop that decreases from 9 to 1.
const max = 10;
for (let i = 1; i <= max; i++) {
document.write("*".repeat(i) + "<br/>");
}
for (let i = max - 1; i >= 1; i--) {
document.write("*".repeat(i) + "<br/>");
}
For fun i added a slowly growing example
let max = 1;
setInterval(() => {
document.body.textContent = "";
for (let i = 1; i <= max; i++) {
document.write("*".repeat(i) + "<br/>");
}
for (let i = max - 1; i >= 1; i--) {
document.write("*".repeat(i) + "<br/>");
}
max++;
}, 500)
Some notes on your code:
You should avoid document.write
Instead of having nested loops you could use String#repeat, to replicate the * character.
To manage the descend you just have to check whether the index has surpassed the half way point, and if it has print totalHeight - index + 1 amount of *;
Here is a interactive example based on the above notes.
function printTree(size, dom) {
if (!(dom instanceof HTMLElement)) dom = document.body; // if the element hasn't been defined get the body element
dom.innerHTML = ""; // clear any old content of the element
var half = Math.ceil(size / 2); // get the halfway point to compare (and avoid extra calculations inside loop);
for (var index = 1; index <= size; index++) {
dom.appendChild(document.createElement("div")).textContent = "*".repeat(index > half ? size - index + 1 : index);
}
}
var input = document.querySelector("#num"),
content = document.querySelector("#content");
input.addEventListener("input", refresh);
refresh();
function refresh() {
printTree(+input.value, content);
}
<input type="number" id="num" value="5" />
<div id="content"></div>
Related
I need my output to look like this:
The best I could achieve was that:
Here is my code:
let pyramidComplete = (rows) => {
let array = [];
let str = '';
for (let i = 1; i <= rows; i++) {
//Add the white space to the left
for (let k = 1; k <= (rows - i); k++) {
str += ' ';
}
//Add the '*' for each row
for (let j = 0; j != (2 * i - 1); j++) {
str += "#".repeat(2 * i - 1);
}
//Add the white space to the right
for (let k = i + 1; k <= rows; k++) {
str += ' ';
}
//Print the pyramid pattern for each row
array.push(str)
str = '';
}
}
pyramidComplete(5);
I thought of assembling a line per loop and then, pushing it into an array but, I can't get the desired result.
The logic is fairly direct: for each row, the number of whitespaces is n - i - 1 where i is the row number. The number of # per row is i + 1. You can produce these substrings using String#repeat. Concatenate the two chunks together per line and use the index argument to Array#map's callback to produce each row.
const pyramid = n => Array(n).fill().map((_, i) =>
" ".repeat(n - i - 1) + "#".repeat(i + 1)
);
console.log(pyramid(5));
If the functions used here are incomprehensible, this can be simplified to use rudimentary language features as follows. It's similar to your approach, but the counts for each character per row are different, I iterate from 0 < n rather than 1 <= n and str should be scoped to the outer loop block.
function pyramid (n) {
var result = [];
for (var i = 0; i < n; i++) {
var line = "";
for (var j = 0; j < n - i - 1; j++) {
line += " ";
}
for (var j = 0; j < i + 1; j++) {
line += "#";
}
result.push(line);
}
return result;
}
console.log(pyramid(5));
If you need a true pyramid (which your current output seems to be shooting for, contrary to the expected output):
const pyramid = n => Array(n).fill().map((_, i) => {
const size = i * 2 + 1;
const pad = n - size / 2;
return " ".repeat(pad) + "#".repeat(size) + " ".repeat(pad);
});
console.log(pyramid(5));
I think you want to do this:
let doc, htm, bod, nav, M, I, mobile, S, Q, CharPyr; // for use on other loads
addEventListener('load', ()=>{
doc = document; htm = doc.documentElement; bod = doc.body; nav = navigator; M = tag=>doc.createElement(tag); I = id=>doc.getElementById(id);
mobile = nav.userAgent.match(/Mobi/i) ? true : false;
S = (selector, within)=>{
var w = within || doc;
return w.querySelector(selector);
}
Q = (selector, within)=>{
var w = within || doc;
return w.querySelectorAll(selector);
}
CharPyr = function(char = '#', className = 'pyr'){
this.char = char; this.className = className;
this.build = (height = 9)=>{
const p = M('div');
p.className = this.className;
for(let i=0,c=this.char,x=c,d; i<height; i++){
d = M('div'); d.textContent = x; p.appendChild(d); x += c;
}
return p;
}
}
// magic happens here
const out1 = I('out1'), out2 = I('out2'), out3 = I('out3'), pyr = new CharPyr;
out1.appendChild(pyr.build(5)); out2.appendChild(pyr.build(7)); out3.appendChild(pyr.build());
}); // end load
*{
box-sizing:border-box;
}
.out{
margin-bottom:7px;
}
.pyr>div{
color:#070; text-align:center;
}
<div class='out' id='out1'></div>
<div class='out' id='out2'></div>
<div class='out' id='out3'></div>
Trying to make a simple script that draws a tree of certain height in console with simple JS loops. It should look like that.
For height = 4 :
*
***
*****
*******
so far have this but somehow it's not working:
function drawTree(height) {
for ( var i = 0; i < height ; i++ ) {
var star = '*';
var space = ' ';
for ( var j = 1; j <= i; j++ ) {
star = star + '***';
}
for ( var k = height - 1 ; k > 0; k-- ) {
spacesBefore = space.repeat(k);
star = spacesBefore + star;
}
console.log(star);
}
}
var levels = prompt('How many levels high should be the tree?');
drawTree(levels);
alert('Check console')
any advice where I'm wrong? thx <3
You had 2 minor problems with your code.
There should be an odd number of stars per level (1, 3, 5, 7, ...) and you were adding 3n + 1 stars which will alternate between even and odd. The change to make for that is star = star + "**" instead of ... + "***"
There is no need for the for (var k = ...) loop for counting the spaces. Your logic is right, but looping over the entire height for each row will yield you the same number of spaces per row, which is what your output is showing, which is wrong. What you want to do instead for the number of spaces is height - i - 1.
A working solution would look like the following:
function drawTree(height) {
for ( var i = 0; i < height ; i++ ) {
var star = '*';
var space = ' ';
for ( var j = 1; j <= i; j++ ) {
star = star + '**';
}
var spacesBefore = space.repeat(height-i-1);
star = spacesBefore + star;
console.log(star);
}
}
var levels = prompt('How many levels high should be the tree?');
drawTree(levels);
A more concise version of this code would look like the following:
function drawTree(height) {
for (var i = 0; i < height; i++) {
// 2n+1 stars per row i.e. 1, 3, 5, 7, ...
var stars = '*'.repeat(2 * i + 1);
var spacesBefore = ' '.repeat(height - i - 1);
console.log(spacesBefore + stars);
}
}
drawTree(prompt('How many levels high should be the tree?'));
Would like to calculate width first and then use that width. Spaces are depended upon width and number of * in each height.
width = height*2 - 1;
Code for tree:
function tree(h) {
let i =0, j = 1;
w = h*2 - 1;
let space = parseInt(w / 2);
while (space >= 0) {
let str = '';
for (i = 0; i < space; i++) str += ' ';
for (i = 0; i<j; i++) str += '*';
console.log(str);
// Since every next line got 2 more *
j += 2;
// Number of space reduce by 1
space--;
}
}
function drawTree(h) {
let star = "*";
let space = " ";
let spaceCount = h-1;
let starCount = 1;
for(let i = 0; i < h; i++) {
console.log(`${space.repeat(spaceCount)}${star.repeat(starCount)}${space.repeat(spaceCount)}`);
spaceCount -= 1;
starCount += 2;
}
}
drawTree(20)
I have a problem with the following task. I want to achieve this output for n = 5:
* 2 3 4 5
* * 3 4 5
* * * 4 5
* * * * 5
* * * * *
* * * * *
* * * * 5
* * * 4 5
* * 3 4 5
* 2 3 4 5
I'm stuck in the second part of the exercise. My code for now:
var n = 5;
var numbers = '';
for (var i = 1; i <= n; i++) {
numbers += i;
}
for (var i = 0; i < n; i++) {
numbers = numbers.replace(numbers[i], '*');
console.log(numbers);
}
So far I have this result:
*2345
**345
***45
****5
*****
So now I need to add the spaces between numbers/stars, and make a reverse loop. I have no idea how to do it.
In addition, there is probably a faster solution to this task than I did.
You can save each of the numbers you generate on a stack (an array), and then pop them from the stack in reverse order:
var n = 5;
var numbers = '';
var stack = []; // <--- add this
for (var i = 1; i <= n; i++) {
numbers += i + ' '; // add a space here
}
for (var i = 0; i < n; i++) {
numbers = numbers.replace(i, '*'); // find/replace the digit
console.log(numbers);
stack.push(numbers); // <--- push on stack
}
while (stack.length > 0) {
numbers = stack.pop(); // <--- pull in reverse order
console.log(numbers); // <--- and print
}
.as-console-wrapper { max-height: 100% !important; top: 0; }
A similar way, without the use of a stack, delays the output, and gathers all the strings in two longer strings which each will have multiple lines of output:
var n = 5;
var numbers = '';
var stack = [];
var output1 = ''; // <-- add this
var output2 = ''; //
for (var i = 1; i <= n; i++) {
numbers += i + ' ';
}
numbers += '\n'; // <-- add a newline character
for (var i = 0; i < n; i++) {
numbers = numbers.replace(i, '*');
output1 += numbers;
output2 = numbers + output2; // <-- add reversed
}
console.log(output1 + output2); // <-- output both
.as-console-wrapper { max-height: 100% !important; top: 0; }
Sticking with something similar to your approach:
var n = 5;
var numbers = '';
for (var i = 1; i <= n; i++) {
numbers += i + ' ';
}
for (var i = 0; i < n; i++) {
numbers = numbers.substr (0, i * 2) + '*' + numbers.substr (i * 2 + 1);
console.log(numbers);
};
for (var i = n - 1; i >= 0; i--) {
console.log(numbers);
numbers = numbers.substr (0, i * 2) + (i + 1) + numbers.substr (i * 2 + 1);
};
The disadvantage of this approach is that it only works for 0-9 because the string positions break when the numbers aren't single digits.
The way I might approach the problem is by having a variable that keeps track of up to which number needs to be an asterisk, doing the first half, then using a whole new for loop to do the second half.
For instance,
String result = '';
String line = '';
int counter = 1;
for (int line = 1; line =< 5; line++) {
for (int i = 1; i =< 5; i++) { // note that we start at 1, since the numbers do
if (i <= counter) {
line += '*'; // use asterisk for positions less than or equal to counter
else {
line += i; // otherwise use the number itself
}
line += ' '; // a space always needs to be added
}
result += line + '\n'; // add the newline character after each line
counter++; // move the counter over after each line
}
Then you can do the same loop, but make the counter go backwards. To do that, set counter to 5 before you begin the loop (since Strings are zero-indexed) and do counter-- after each line.
Alternatively if you don't want to write two loops, you can increase the outer for loop's limit to 10 and have an if statement check if you should be subtracting from counter instead of adding, based on the value of line
Decided to use this as an excuse to get more practice with immutable mapping and reducing. I used an array to hold all the rows, and reduce them at the end to a string. Each row starts as an array holding 1 to n, and each column number is then mapped to an asterisk based on the case:
if rowIndex <= number:
rowIndex.
else:
rowIndex - (2 * (rowIndex - number) - 1)
Essentially, [n + 1, n * 2] maps to (1, 3, 5, ..., n - 3, n - 1), which subtracted from the original range becomes [n, 1]. For the row, check if the currently selected column is less than or equal to its row's translated index, and return an asterisk or the number.
// expansion number (n by 2n)
const maxNum = 5;
// make an array to size to hold all the rows
const result = Array(maxNum * 2)
// Fill each row with an array of maxNum elements
.fill(Array(maxNum).fill())
// iterate over each row
.map((row, rowIndex) =>
// iterate over each column
row.map((v, column) => (
// check if the column is less than the translated rowIndex number (as mentioned above)
column < ((rowIndex <= maxNum) ?
rowIndex + 1 :
2 * maxNum - rowIndex
// if it is, replace it with an asterisk
)) ? "*" : column + 1)
// combine the row into a string with each column separated by a space
.reduce((rowAsString, col) => rowAsString + " " + col)
// combine all rows so they're on new lines
).reduce((rowAccum, row) => rowAccum + "\n" + row);
console.log(result);
I created a half of the Christmas Tree but here I got blocked. Some one please help me to understand how to do the left side too.
for (var i = 0; i < 8; i++) {
for (var j = 0; j <= i; j++) {
document.write("^");
}
document.write("<br>");
}
<pre>
<script>
//Reads number of rows to be printed
var n = 8;
for(i=1; i<=n; i++)
{
//Prints trailing spaces
for(j=i; j<n; j++)
{
document.write(" ");
}
//Prints the pyramid pattern
for(j=1; j<=(2*i-1); j++)
{
document.write("*");
}
document.write("<br>");
}
</script>
</pre>
Source: http://codeforwin.org/2015/07/equilateral-triangle-star-pattern-program-in-c.html
C to JavaScript by me.
I wrote the following code for this problem.
I also added a nice extra, christmas-tree ornaments :-)
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;
}
}
The output should look something like this:
⏣
***
*o***
**⌾*o**
*****⛣**⛣
*****⌾****⏣
**◍*◍********
****
****
The keyword is think.
var x = 8;
for (let i = 0; i < x; i++) {
for (let j=x-1; j>i; j--) {
document.write("  ");
}
for (let k=0; k<=(i*2); k++) {
document.write("^");
}
document.write("<br>");
}
for (let i=0; i<2; i++) {
for (let j=0; j<(x*2)-3; j++) {
document.write(" ");
}
document.write("^<br>");
}
Constraints: Only looks good starting from x = 5.
Original code by me
The answers above heavily rely on nested loops, thought I post another approach with "modern" JS (of course still using a single loop with the map function given to Array.from()):
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>`);
maybe the attempt to make it work with .padStart() is not optimal because the math gets a bit ugly, but anyways, just for fun =)...
Here's a solution with a simple for loop without any nested loop.
let row = ""
let l = 9
for (let i = 0; i < l; i++) {
row += " ".repeat(l - i) + "*" + "*".repeat(i * 2) + `\n`;
}
console.log(row);
Simple christmas tree function:
function christmasTree(x) {
if(x < 3) {
return "";
}
let tree = "";
for(let i = 1; i <= x; i++) {
for(let j = 1; j <= x + x - 1; j++) {
if(j <= x - i || j >= x + i) {
tree += " ";
} else {
tree += "*";
}
}
tree += "\n";
}
return tree;
}
Incase you are looking for how to do this in a function for javascript or typescript
Use 3 for loops,
1 - Number of rows
2 - Number of spaces
3 - Number of characters
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));
<pre>
<script>
//Reads number of rows to be printed
var n = 8;
for(i=1; i<=n; i++)
{
//Prints trailing spaces
for(j=i; j<n; j++)
{
document.write(" ");
}
//Prints the pyramid pattern
for(j=1; j<=(2*i-1); j++)
{
document.write("*");
}
document.write("<br>");
}
</script>
</pre>
*******
* *
* * *
* *
*******
It should look like the above arrangement of asterisks. I'm new to programming. So far I have written:
<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<body>
<script>
var maxCount = 7;
var iterationCount = 0;
while (iterationCount < maxCount) {
iterationCount = iterationCount + 1;
document.write('*');
}
I have a strong feeling so far that's incorrect, and even if it's correct, I don't know how to go on from there.
I know I have to use for and nested loops, but I'm extremely confused.
Try
var width = 7,
height = 7, // for example
boxElem = document.getElementById("box"); // this is the element which will hold your box
for(var i = 0; i < height; i++) {
for(var j = 0; j < width; j++) {
if(i === 0 || i === height - 1 || j === 0 || j === width - 1 || (i === Math.floor(height / 2) && j === Math.floor(width / 2))) {
// check if it's the first or last row or column, or if it's the centre of the box
boxElem.innerHTML += "*";
} else {
boxElem.innerHTML += " "; // otherwise, don't add an asterisk but an empty space
}
}
boxElem.innerHTML += "\n"; // new line
}