How to print a half pyramid in javascript - 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*****');

Related

How do I print on a new line after every 6th number?

So I'm making a loop that's supposed to print from 0-99 and it's supposed to make a new line after every 6th number like in the example below;
012345
678910
But right now it doesn't make a new line it just increases space between the "chunks" it's displaying. How do I get it to make a new line after every 6th number?
for (var i = 0; i < 100; i++) {
for (var j = 0; j < 6 && i <= 100; j++) {
document.body.innerHTML += i;
i++;
}
document.body.innerHTML += '\n';
i--;
}
A literal newline doesn't result in a visual newline in HTML:
foo
bar
You need <br> instead:
for (var i = 0; i < 100; i++) {
for (var j = 0; j < 6 && i <= 100; j++) {
document.body.innerHTML += i;
i++;
}
document.body.innerHTML += '<br>';
i--;
}
Or, I'd prefer to surround each block in a <div> - and you can increment the i only inside the inner loop to make the logic clearer:
for (var i = 0; i < 100;) {
const div = document.body.appendChild(document.createElement('div'));
for (var j = 0; j < 6 && i <= 100; j++, i++) {
div.textContent += i;
}
}
You could use a modulus to insert a br every sixth item - save you doing loops inside loops:
for (var i = 0; i < 100; i++) {
document.body.innerHTML += i;
if ((i + 1) % 6 === 0) { // using i plus one as you start at 0
document.body.innerHTML += '<br>';
}
}
I am answering
supposed to print from 0-99 and supposed to make a new line after every 6th number
We need a PRE to not use a <br>
document.getElementById("res").innerHTML =
Array.from(Array(100).keys())
.map(i => `${i.toString().padStart(3," ")}${(i + 1) % 6 === 0 ? '\n' : ''}`)
.join("");
<pre id="res"></pre>

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>

Exercise with a loop in 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);

How to modify this function to return string instead of int

please take a quick look at this function that I have found on the web.
function longestCommonSubstring(string1, string2){
// init max value
var longestCommonSubstring = 0;
// init 2D array with 0
var table = Array(string1.length);
for(a = 0; a <= string1.length; a++){
table[a] = Array(string2.length);
for(b = 0; b <= string2.length; b++){
table[a][b] = 0;
}
}
// fill table
for(var i = 0; i < string1.length; i++){
for(var j = 0; j < string2.length; j++){
if(string1[i]==string2[j]){
if(table[i][j] == 0){
table[i+1][j+1] = 1;
} else {
table[i+1][j+1] = table[i][j] + 1;
}
if(table[i+1][j+1] > longestCommonSubstring){
longestCommonSubstring = table[i+1][j+1];
}
} else {
table[i+1][j+1] = 0;
}
}
}
return longestCommonSubstring;
}
It returns the length of the longest common substring as an int. Now to my question, is it possible to modify this function, so that it returns the actual string instead of just returning the length of the substring, I'm quite new at programming and thought that just modifying this secetion would help if(string1[i]==string2[j]){ push(string1[i]}, but it isn't that easy, because I don't want every single character that is the same in those 2 strings to be added in that array, only those that are exactly the same.
Thanks in advance =)
Well for minimal changes to the existing function you could declare a new variable:
var theCommonString = '';
Then in the middle of the function add a line after this existing one:
longestCommonSubstring = table[i+1][j+1];
that says something like:
theCommonString = string1.substr(i + 1 - longestCommonSubstring,
longestCommonSubstring);
(That i + 1 index may be a little off, I haven't bothered working it out carefully.)
Then at the end just return your new variable instead of the existing one.
Note that if there is more than one common sub string of the same length this will return the last one.
You can just store the whole common substring in the table instead of its length:
function longestCommonSubstring(string1, string2){
// init max value
var longestCommonSubstring = "";
// init 2D array with 0
var table = Array(string1.length);
for(a = 0; a <= string1.length; a++){
table[a] = Array(string2.length);
for(b = 0; b <= string2.length; b++){
table[a][b] = 0;
}
}
// fill table
for(var i = 0; i < string1.length; i++){
for(var j = 0; j < string2.length; j++){
if(string1[i]==string2[j]){
if(table[i][j] == 0){
table[i+1][j+1] = string1[i];
} else {
table[i+1][j+1] = table[i][j] + string1[i];
}
if(table[i+1][j+1].length > longestCommonSubstring.length){
longestCommonSubstring = table[i+1][j+1];
}
} else {
table[i+1][j+1] = 0;
}
}
}
return longestCommonSubstring;
}

Categories

Resources