Exercise with a loop in javascript - javascript

I need for an university exercise to display onscreen with a document.write the tree below using a kind of loop:
I used at the beginning a for loop but i printed only the first row... someone can help me?
This is what I tried:
var numbers = [0, 1, 2, 3, 4]
for (var i = 0; i <= numbers.length; i++) {
if (numbers [i] == 0) {
document.write(" * </br>");
}
if (numbers [i] == 1) {
document.write(" *** </br>");
}
if (numbers [i] == 2) {
document.write(" ****** </br>");
}
if (numbers [i] == 3) {
document.write(" ******* </br>"); }
if (numbers [i] == 4) {
document.write("********* </br>");
}
return
}
Thank You!

I'm going to give you a "golfed-ish" (goldfish? should this be a thing?) version of the code. In other words, the smallest, most obscure code I can think of to accomplish the task. You should not use this, because your teacher will undoubtedly ask you what it means and you won't know, but I'm bored XD
var size = 5;
document.write("<center>"+Array.apply(0,new Array(size)).map(function(_,i) {return new Array((i+1)*2).join(" * ");}).join("<br>")+"</center>");
Demo
As I said, don't use this :p

Here is my code for you ...
<html>
<head>
<script type="text/javascript" language="javascript">
document.write("<center>"); //write a center tag to make sure the pyramid displays correctly(try it without this step to see what happens)
for(var i = 0; i <= 10; i++) //a loop, this counts from 0 to 10 (how many rows of stars)
{
for(var x = 0; x <= i; x++)// a loop, counting from 0 to whatever value i is currently on
{
document.write("*");//write a * character
}
document.write("<br/>"); //write a br tag, meaning new line, after every star in the row has been created
}
document.write("</center>"); //close the center tag, opened at the beginning
</script>
</head>
<body>
</body>
</html>

Adds spaces and fully extendable
function pyramid(lines, char) {
var start = 2,html = '<pre>';
for (var i=lines; i--;) {
html += new Array(Math.floor(i+1)).join(' ') + new Array((start=start+2)-2).join(char) + '<br />';
}
return html + '</pre>';
}
document.write( pyramid(5, '*') );
FIDDLE

function pyramidStar(n) {
var str = "";
for(var i=1; i<=n; i++) {
for(var j=1; j<=n-i; j++) {
str += " ";
}
for(var k=n-i+1; k<n+i; k++) {
str += "* ";
}
for(var m=n+i; m<=2*n-1; m++) {
str += " ";
}
str += "\n";
}
return str;
}
document.getElementById("result").innerHTML = pyramidStar(9);
<pre id="result"></pre>
Another way of printing pyramid of stars.

<pre><script>
for (var i = 0; i < 5; i++) {
for (var c = 0; c < 9; c++) {
if (Math.abs(4 - c) <= i)
document.write("*");
else
document.write(" ");
}
document.write("<br />");
}
</script></pre>
It is a simple version with document.write(). The only complicated thing is Math.abs which gives the distance from the middle.
PS: watch out for magic numbers

function star(n) {
for (var i = 1; i <= n; i++) {
for (var j = i; j < n; j++) {
document.write("-");
}
for (var k = 1; k <= (2 * i) - 1; k++) {
document.write("*");
}
document.write("<br/>");
}
}
//function calling
star(9);

Related

Christmas tree in Javascript using stars

I have this loop problem, I really don't understand why my code doesn't work, I've even draw this on paper and for my logic it looks good but it's not working, please help me.
function drawTree(h) {
for(var i=0; i<=h; i++){
var star = '';
for(var k=0; k<=1; k++){
star += " ";
};
for(var j=0; j<=i; j++) {
star += "*";
};
};
console.log(star);
};
drawTree(5);
See comments in the code for changes.
function drawTree(h) {
for(var i=0; i<=h; i++){
var star = '';
//Changed to start high then decrease
for(var k = 1; k <= h - i; k++){
//shortened to one space
star += " ";
};
for(var j=0; j<=i; j++) {
//Added space so there is an odd number
//of symbols and the star above fits
//the space
star += " *";
};
//Moved into the loop
console.log(star);
};
};
drawTree(5);
Note that the code can be substantially shortened using String.prototype.repeat:
function drawTree(h) {
for (var i = 0; i <= h; i++){
console.log(" ".repeat(h - i) + " *".repeat(i + 1));
};
};
drawTree(5);
Also note that your example produces a base line with six stars for a call of drawTree(5). I am unsure whether that is intended. The code above reproduces said behavior, editing it to show a line less should not be too hard.
function drawTree(h) {
for (var i = 0; i < h; i++) {
var star = '';
var space = (h - i);
if (i == 0) {
star += ' '.repeat(space + 1) + '\n';
}
star += ' '.repeat(space + 1);
var zero = 2 * i + 1;
star += '*'.repeat(zero);
console.log(star);
}
}
drawTree(5);
You’re re-setting it each line, but printing it only at the end.
Move console.log(star); to the end of the first loop.
Just for fun:
const tree = ({height: h = 5, stumpHeight: sh = 2, branchChar: bc = '*', emptyChar: ec = ' ', stumpChar: sc = '#'} = {}) => [
... Array .from ({length: h}, (_, n) => ec .repeat (h - n - 1) + bc.repeat (2 * n + 1) + ec .repeat (h - n - 1)),
... Array .from ({length: sh}, () => ec .repeat (h - 1) + sc + ec .repeat (h - 1)),
] .join ('\n')
console .log (tree ())
console .log (tree ({height: 6, emptyChar: '_'}))
console .log (tree ({height: 12, stumpHeight: 3, stumpChar: '#'}))
console .log (tree ({branchChar: '#'}))
.as-console-wrapper {max-height: 100% !important; top: 0}
Because, you know, that's how all those JS 101 instructors expect it to be coded.
function drawTree(n) {
let tag = "#";
for (let i = 0, j = "#"; i < n; i++) {
console.log(tag);
tag = tag + j;
}
}
drawTree(10);
You have to place the console.log statement inside first for loop. That should give a half tree.
If you want correct tree, then pre-pend spaces before star.
Calculate the center of the number of rows and add spaces before it.
Hope this not an assignment problem.
function drawTree(h) {
for(var i=0; i<=h; i++){
var star = '';
for(var k=0; k<=1; k++){
star += " ";
};
for(var j=0; j<=i; j++) {
star += "*";
};
console.log(star);
};
};
drawTree(5);

How to print a half pyramid in javascript

The code works but I don't want the inner for loop to take me to the new line.
for (i = 0; i < 5; i++) {
for (j = 1; j <= i; j++) {
console.log('*');
}
console.log();
}
console.log('-----------------');
console.log will automatically break the line. Concatenate to a string instead of a log. Log at the end.
let str = '';
for(i = 0; i <= 5 ; i++) {
for(j = 1; j <= i; j++) {
str += '*';
}
str += '\n';
}
console.log(str);
You can do this way, with the help of a string variable:
for (i = 0; i < 5; i++) {
var str = '';
for (j = 1; j <= i; j++) {
str+='*';
}
console.log(str);
}
console.log('-----------------');
If you want to print at the page, use like below
for (i = 0; i < 5; i++) {
let j=0;
do{document.write("*");j++;}while(j < i)
document.write("<br/>")
}
You need to break the line with the console.log you can also controle the space between * with output+='*' + " ";
function pyramid() {
var total = 5;
var output="";
for (var i = 1; i <= total; i++) {
for (var j = 1; j <= i; j++) {
output+='*' + " ";
}
console.log(output);
output="";
}
}
pyramid()
You can get rid of second for loop as follows:
var str = '';
for (i = 1; i <= 5; i++) {
str +=Array(i).join("*");
str +='\n';
}
console.log(str);
let string = "";
for (let i = 0; i < 5; i++){
string += '*';
console.log(string);
}
Output:
*
**
***
****
*****
A simple way to solve this "exercise" in JavaScript:
let width = ""
while(width.length < 6) console.log(width += `#` );
Basically, we create a string (width) and increment its value using the while loop till we hit a restriction.
I found the more typical method "bulky"(?)...plus there's the issue of not getting the exact picture of a half pyramid.
let i,j
for (i= 0; i < 6; i++){
for (j = 0; j<=i; j++){
console.log("#")
}
console.log("\n")
}
function pyramid(n){
let result = "";
for(let i=0; i<=n; i++){
result += "*".repeat(i);
result += "\n"
}
return result;
}
console.log(pyramid(5));
//OutPut
*
**
***
****
*****
As we need n number of pyramid structure with '' / '#' / any symbol. by using above code we can achieve. Here you can see we just created a function called pyramid with one parameter 'n'. and inside function we declare a variable 'result'. So inside for loop the length of 'i' is "<=n" and also you can use "repeat() method to print '' 'i' times. So if you call that function like console.log(pyramid(5)); You can able to see your Answer as expected..
shortest code:
console.log('*\n**\n***\n****\n*****');

Building a JavaScript grid with odd and even characters using two loops

This is my first question on StackOverflow.
I have to build gridGenerator(num). If num is 3, it would look like this:
#_#
_#_
#_#
If num is 4, it would look like this:
#_#_
_#_#
#_#_
_#_#
I was able to solve it for odd numbers, but struggle to adjust it to even numbers.
function gridGenerator(num) {
var grid = '';
var row = '';
for (var i = 0; i < num; i++) {
for (var j = 0; j < num; j++) {
if (row.length % 2) {
row += '_';
} else {
row += '#';
}
}
grid += row.slice(-num) + '\n';
}
return grid;
}
console.log(gridGenerator(3));
Need a hint how to solve it for 2, 4, and other even numbers. Thank you!
Try this
if ((i+j) % 2)
function gridGenerator(num) {
var grid = '';
var row = '';
for (var i = 0; i < num; i++) {
for (var j = 0; j < num; j++) {
if ((i+j) % 2) {
row += '_';
} else {
row += '#';
}
}
grid += row.slice(-num) + '\n';
}
return grid;
}
console.log(gridGenerator(4));
You can use the condition num % 2 to determine if a number is even or odd. I would use two loops like you are doing. Make your character addition based on the even / odd state of the row and column. At the end of each row insert the line break.
EDIT: Here you go.
function generateGrid( num ) {
let i, j, grid = "";
for ( i = 0; i < num; i++ ) {
for ( j = 0; j < num; j++ ) {
if ( ( i + j ) % 2 ) {
grid += "_";
} else {
grid += "#";
}
}
grid += "\n";
}
return grid;
}
var grid = generateGrid( 4 );
console.log( grid );
function gridGen(num) {
var even = '';
for (var i = 0; i< num ; i++)
even += (i%2) ? '_' : '#';
odd = even.substring(1) + (num%2 ? '_' : '#');
var out = '';
for (var i = 0; i< num ; i++)
out += ((i%2) ? odd : even) + '\n';
return out;
}
console.log('Even Case');
console.log( gridGen(8));
console.log('Odd Case');
console.log( gridGen(7));
If you are looking for another approach + efficiency try this

Simple Javascript Christmas Tree

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("&nbsp&nbsp");
}
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("&nbsp");
}
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>

changing 2 random numbers in 30 times in number table using java script

In this code each time you open the html page two random numbers are generated and thier location in the matrix will be changed.
for example the random numbers are 2,8
in the main table 2 is in the matrix[0][1],matrix[1][7],matrix[2][4],matrix[3][0],matrix[4][6],matrix[5][3],matrix[6][8],matrix[3][0],matrix[7][5]
,matrix[8][2] .in the result table 8 is set in these location and 2 is set in the current locations of 8.
I want to repeat this, 30 times.
so far I have :
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<body>
<script type="text/javascript">
var matrix = new Array();
matrix[0]=[1,2,3,4,5,6,7,8,9];
matrix[1]=[4,5,6,7,8,9,1,2,3];
matrix[2]=[7,8,9,1,2,3,4,5,6];
matrix[3]=[2,3,4,5,6,7,8,9,1];
matrix[4]=[5,6,7,8,9,1,2,3,4];
matrix[5]=[8,9,1,2,3,4,5,6,7];
matrix[6]=[3,4,5,6,7,8,9,1,2];
matrix[7]=[6,7,8,9,1,2,3,4,5];
matrix[8]=[9,1,2,3,4,5,6,7,8];
document.writeln('<table border="1">');
for (i = 0; i < 9; i++)
{
document.writeln('<tr>');
for (j = 0; j < 9; j++)
document.writeln('<td>' + matrix[i][j] + '</td>');
document.writeln('</tr>');
}
document.writeln('</table>');
document.writeln('<table border="1">');
document.writeln("The random numbers are:");
document.writeln('<br>');
var r1 = Math.ceil(Math.random() * 9);
var r2 = Math.ceil(Math.random() * 9);
document.writeln(r1);
document.writeln(r2);
document.writeln('<br>');
document.writeln("The result table is:");
for(i=0; i<9; i++)
{
document.writeln('<tr>');
for(j=0; j<9; j++)
{
if(matrix[i][j]==r1)
{
matrix[i][j]=r2;
document.writeln('<td>' + matrix[i][j] + '</td>');
}
else if(matrix[i][j]!=r1 && matrix[i][j]!=r2)
document.writeln('<td>' + matrix[i][j] + '</td>');
else if(matrix[i][j]==r2)
{
matrix[i][j]=r1;
document.writeln('<td>' + matrix[i][j] + '</td>');
}
}
document.writeln('</tr>');
}
document.writeln('</table>');
</script>
</body>
</html>
I would change your code slightly.
First, I'd make a method to print the table:
function printMatrix(var matrix)
{
document.writeln('<table border="1">');
for (i = 0; i < 9; i++)
{
document.writeln('<tr>');
for (j = 0; j < 9; j++)
document.writeln('<td>' + matrix[i][j] + '</td>');
document.writeln('</tr>');
}
document.writeln('</table>');
}
Then, I'd make a method for the swapping:
function sawpTwoNumbers(matrix)
{
document.writeln("The random numbers are:");
document.writeln('<br>');
var r1 = Math.ceil(Math.random() * 9);
var r2 = Math.ceil(Math.random() * 9);
document.writeln(r1);
document.writeln(r2);
document.writeln('<br>');
// This is new code:
for(int i=0; i< matrix.length; i++){
var r1Index = matrix[i].indexOf(r1);
var r2Index = matrix[i].indexOf(r2);
matrix[i][r1Index] = r2;
matrix[i][r2Index] = r1;
}
}
Next, I'd put your code in the pageLoad method:
function pageLoad()
{
var matrix = new Array();
matrix[0]=[1,2,3,4,5,6,7,8,9];
matrix[1]=[4,5,6,7,8,9,1,2,3];
matrix[2]=[7,8,9,1,2,3,4,5,6];
matrix[3]=[2,3,4,5,6,7,8,9,1];
matrix[4]=[5,6,7,8,9,1,2,3,4];
matrix[5]=[8,9,1,2,3,4,5,6,7];
matrix[6]=[3,4,5,6,7,8,9,1,2];
matrix[7]=[6,7,8,9,1,2,3,4,5];
matrix[8]=[9,1,2,3,4,5,6,7,8];
printMatrix(matrix);
// This is new code:
// It will call the swap method and the print method 30 times.
for(int i = 0; i < 30; i++)
{
swapTwoNumbers(matrix);
printMatrix(matrix);
}
}
Please Note: I haven't tested this code. I don't guarantee that it works. I hope it'll give you a push in the right direction though.

Categories

Resources