Shorter Way of Prinitng Triangle Patterns JavaScript - javascript

I'm trying to find a shorter way to print a right-triangle and an isosceles triangle without using that many nested loops. Please help, here is my code so far, it works I just have trouble finding a shorter way to write it:
//right-triangle
let triangleStr = "";
let num = 5;
for (let i = 1; i <= num; i++) {
for (let j = 0; j < num - i; j++) {
triangleStr += " ";
}
for (let k = 0; k < i; k++) {
triangleStr += "*";
}
triangleStr += "\n";
}
console.log(triangleStr);
//isosceles-triangle
triangleString = "";
for (let i = 1; i <= num; i++) {
for (let j = 1; j <= num - i; j++) {
triangleString += " ";
}
for (let k = 1; k <= 2 * i - 1; k++) {
triangleString += "*";
}
triangleString += "\n";
}
console.log(triangleString);

If you want to use only one loop, you can use repeat() method in ECMAScript6 or higher.
For Right triangle:
const line = 5;
let rightTriangle = "";
for (let l = 1; l <= line ; l++) {
const indent = line-l;
rightTriangle += `${" ".repeat(indent)}${"*".repeat(l)}${"\n"}`;
}
console.log(rightTriangle);
For Isosceles triangle:
const line = 5;
let isoscelesTriangle = "";
for (let l = 1; l <= line ; l++) {
const indent = line - l;
isoscelesTriangle += `${" ".repeat(indent)}${"*".repeat(2*l-1)}${"\n"}`;
}
console.log(isoscelesTriangle);

Related

I'm trying to create a star pyramid which should contain 1 * in the first row, 2* with equal spaces in the second row, like wise 3rd and 4th row

[enter image description here][1]
List item
let x = 4;
let text = "";
for(let i = 1; i <= x; i++) {
for(let j = 1; j <= x - i; j++) {
text += " ";
}
for(let k = 0; k < 2 * i - 1; k++) {
text += "*";
}
text +="\n";
}
console.log(text);
---Output I want is like this. I'm new to this. Thank you in advance
[1]: https://i.stack.imgur.com/AJvaZ.png
Small change:
let x = 4;
let text = "";
for(let i = 1; i <= x; i++) {
for(let j = 1; j <= x - i; j++) {
text += " ";
}
text += "*";
for(let k = 0; k + 1 < i; k++) {
text += " *";
}
text +="\n";
}
console.log(text);

How do I make this JavaScript console.log into 6 rows with 6 indexes? [duplicate]

This question already has answers here:
Print an output in one line using console.log()
(13 answers)
Closed last year.
Instead of 1 index on each row, I want horizontal not vertical returns.
let n = [6];
function staircase() {
for (let i = 1; i <= n; i++) {
for (let j = 1; j <= n - i; j++) {
console.log("0");
}
for (let k = 1; k <= i; k++) {
console.log('#');
}
}
}
staircase();
But I need it to render like this. (This works using Java; it's the same logic, but renders differently.)
#
##
###
####
#####
######
console.log prints one line each therefore i put 2 variables to keep the empty string and hash string and after the loops logged the concatenation of the strings
let n = 6
function staircase() {
for (let i = 1; i <= n; i++) {
let emptyString = '';
let hashString = '';
for (let j = 1; j <= n - i; j++) {
emptyString += " ";
}
for (let k = 1; k <= i; k++) {
hashString += '#'
}
console.log(emptyString + hashString)
}
}
staircase();
const n = [6]
for (let i = 1; i <= n; i++) {
//
// this array stores the results;
//
const array = [];
//
for (let j = 1; j <= n - i; j++) {
array.push("0");
}
for (let k = 1; k <= i; k++) {
array.push('#');
}
// adding `toString`, does the magic
console.log(array.toString())
}

Print all possibilities by rotating a string in Javascript

How to rotate a string in javascript and print the rotated versions of string without using any javascript functions, only for loops.
Given a string:
"hell"
Output:
"lhel", "llhe", "ellh", "hell"
I have tried but not succeded
var str1 = "hell";
let i = 0;
let len = str1.length - 1;
let temp;
for (let j = 0; j < len+1; j++) {
temp = str1[len]
while (i < len) {
console.log(str1[i]);
temp += str1[i];
i++;
}
console.log(temp);
//console.log(typeof temp, typeof str1)
str1 = temp;
}
You are almost there ! There is one thing missing, i should be reset at each iteration of the for loop, otherwise, the while (i < len) will be "played" only once :
var str1 = "hell";
let len = str1.length - 1;
let temp;
for (let j = 0; j < len+1; j++) {
let i = 0; // <-------------------- notice this
temp = str1[len]
while (i < len) {
//console.log(str1[i]);
temp += str1[i];
i++;
}
console.log(temp);
//console.log(typeof temp, typeof str1)
str1 = temp;
}
You could take a nested loop and get the characters at the position of i and j and take the reminder operator % for preventing characters outside of the string.
var string = "hell",
i, j,
temp;
for (i = 0; i < string.length; i++) {
temp = '';
for (j = 1; j <= string.length; j++) temp += string[(i + j) % string.length];
console.log(temp);
}
You can try this method. Basically you have two loops the first loop with (i) is for the possibilities the second one is for the shifting
var strValue = "hell";
var temp;
for(var i = 0; i < strValue.length; i++){
temp = "";
for(var j = 1; j < strValue.length; j++){
temp += strValue[j];
}
temp += strValue[0]
strValue = temp;
console.log(strValue)
}
In first loop add all symbols which indexes are greater then amount of shift steps (i in this case).
And add rest symbols after it the second loop.
const str = 'hello';
for (let i = 0; i < str.length; i++) {
let shifted = '';
for (let j = i; j < str.length; j++) {
shifted += str[j];
}
for (let j = 0; j < i; j++) {
shifted += str[j];
}
console.log(shifted);
}
i know this has already been answered so.. this is how i'd do it.
maybe you can learn from it.
const str = "hell";
// this loop will set the offset. so if it's 1, "hell" will become "ellh"
for (let offset = 0; offset < str.length; offset++) {
// this will contain the final string
let output = "";
// here we iterate through all the characters
for (let index = 0; index < str.length; index++) {
// and use modulo to switch 5 to 1 (in case length is 4)
output += str[(index + offset) % str.length];
}
// there we go
console.log(output);
}
let str = 'hell';
for(let i=0;i<str.length;i++){
str = str.substring(1,str.length) + str[0];
console.log(str);
}

Inclined pyramid pattern

I want to create a pyramid-pattern (on the side).
I've gotten the first part, but I need help to count the last part down.
So far I've got this:
var out = document.getElementById("out");
for (var i = 0; i < 20; i++ ){
if ( i <= 10){
for ( var j = 0; j < i; j++ ){
out.innerHTML += "*";
}
} else if (i > 10){
for (var j = 9; j > 0; j--){
out.innerHTML += "*";
}
}
out.innerHTML += "<br>";
}
<p id="out"></p>
You can run a loop from 19-i to 0, and while i increments further the value of 19-i gets smaller and smaller:
var out = document.getElementById("out");
for (var i = 0; i < 20; i++ ){
if ( i <= 10){
for ( var j = 0; j < i; j++ ){
out.innerHTML += "*";
}
} else if (i > 10){
for ( var j = 19-i; j >= 0; j--){ // <-- run loop so that number of iterations gets lower and lower
out.innerHTML += "*";
}
}
out.innerHTML += "<br>";
}
<p id="out"></p>
Simple solution to draw Pyramid shape based on the given steps/count:
var steps = 5, outputStr = "", isTriangle = false;
var newLine = "<br />"; // "\n" for String, <br /> for element break line.
for (var i = 1; i <= steps; i++) {
// Forward
for (var j = 1; j <= i; j++) {
outputStr += i;
}
outputStr += newLine;
if (i == steps && !isTriangle) {
// Backward - After completing Forward
var k = i - 1;
while (k > 0) {
for (var j = k; j > 0; j--) {
outputStr += k;
}
k--;
outputStr += newLine;
}
}
}
var out = document.getElementById("out");
out.innerHTML = outputStr;
<p id="out"></p>
for java see: Draw Pyramid

How to make a triangle using for loop javascript

I have a simple question although i cannot manage to resolve this problem. Hope you can help. I need to make triangle using for loop and from this 4 exercises I don't know what to do with the third one. I haven't used Javascript before, so any help would be appreciated.
# # # # #
# # # #
# # # <----- here is triangle i need to make. Just in case
# #
#
var i;
var j;
for (i = 0; i <= 5; i++ )
{
document.write("</br>");
for ( j = 0; j < 6-i; j++ )
{
document.write( "&nbsp&nbsp" );
}
for ( j = 6-i; j <= 5; j++ )
{
document.write( "*" );
}
}
This is code I wrote for D in photo.
And I'm sorry i did not add it at first.
for (let line = "*"; line.length < 8; line += "*")
console.log(line);
this question came in this book: http://eloquentjavascript.net
I don't know why there are so bad answers on google for this one.
function leftTriangle(rows){
let result = '';
for(let i=rows;i>0;i--){
if(i===rows) {
result += '*'.repeat(i) + '\n';
}else{
let empty = rows-i
result+= ' '.repeat(empty) + '*'.repeat(i)+ '\n'
}
}
return result;
}
console.log(leftTriangle(5))
I'm sure there are better solutions (simply left-padding with spaces comes to mind), but here's the quick and dirty one I created from your own solution.
for (var i = 0; i < 5; i++) {
for (var j = 0; j < i; j++) {
document.write(" ");
}
for (var j = 5; j > i; j--) {
document.write("#");
if (j > i + 1) document.write(" ");
}
document.write('<br/>')
}
https://js.do/code/diamondsinthesky
Something like this?
var rows = 5;
for (var i = rows; i--;) {
var columns = 0;
while (columns <= i) {
document.write('#');
columns++
}
document.write('<br />\n');
}
Thank you for your help. I did it. It was too obvious but somehow I couldn't find it. Thank you one more time. Here is how i did it.
for (i = 5; i > 0; i--) {
document.write("</br>");
for (j = 0; j < 6 - i; j++) {
document.write("&nbsp&nbsp");
}
for (j = 6 - i; j <= 5; j++) {
document.write("*");
}
}
var rows = 5;
for (var i = rows; i--;) {
var columns = 0;
while (columns <= i) {
document.write('#');
columns++
}
document.write('<br />\n');
}
You can also do this if you are looking for something different.
This code is for a triangle of 7 lines.
let size = 8;
let y = "#";
for (let x = 0; x < size; x++)
{
console.log(y);
y += "#";
}
// Second method
for (let i = 1; i < size;i++)
{
let me ="#".repeat(`${i}`)
console.log(me);
}
var size = 5;
for (var i = 0; i < size; i++) {
for (var j = 0; j <= i; j++) {
document.write("*");
}
document.write("<br />\n");
}

Categories