I want to print diamond pattern using *. Please find the code below:
for (let i=0; i<num; i++) {
let str="";
for (let j=i; j<num; j++) {
str+="*";
}
console.log(str);
}
for (let i=num; i>0; i--) {
let spaces=num-i;
let spacesStr="";
for (let j=0; j<spaces; j++) {
spacesStr+=" ";
}
let str=spacesStr;
for (let j=i; j>0; j--) {
str+="*";
}
console.log(str);
}
The output of the above code is as below:
****
***
**
*
****
***
**
*
I know that if I start printing both the patterns from line 1 I can achieve the desired output. But not sure how I can do that. Please let me know.
thanks
You've quite figured out the answer already. You will need 3 for loops inside your main loop inorder to get that pattern.
let num = 5;
let string = "";
for (let i = 0; i <= num; i++) {
// printing star
for (let j = 0; j < num - i; j++) {
string += "*";
}
// printing spaces
for (let k = 0; k < i * 2; k++) {
string += " ";
}
// printing stars
for (let l = num - i; l > 0; l--) {
string += "*";
}
string += "\n";
}
console.log(string);
First, we print the left stars, then we print the spaces, and then again we print the right stars.
The idea is to build each line.
First, let's focus on the top half of the diamond.
On the first line, there are n stars, 0 spaces, n stars.
On the second line, there are n-1 stars, 2 spaces, n-1 stars.
On the third line, there are n-2 stars, 4 spaces, n-2 stars.
And the pattern follows till there are 0 stars.
Now, coming to the bottom half of the diamond, the pattern is same, just reversed. So, for the inner loops, you can just change i to n-i and n-i to i.
const n = 5;
const star = "*";
const space = " ";
// Top half of the diagram
for (let i = 0; i < n; i ++) {
let pattern = ''
for (let j = 0; j < (n - i); j++) pattern += star;
for (let j = 0; j < i; j++) pattern += `${space}${space}`;
for (let j = 0; j < (n - i); j++) pattern += star;
console.log(pattern);
}
// Bottom half of the diagram
for (let i = 1; i <= n; i ++) {
let pattern = ''
for (let j = 0; j < i; j++) pattern += star;
for (let j = 0; j < (n - i); j++) pattern += `${space}${space}`;
for (let j = 0; j < i; j++) pattern += star;
console.log(pattern);
}
Related
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);
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())
}
var s = '';
for (var i = 0; i < 5; i++) {
for (var j = 0; j < 10; j++) {
s += '*'
}
s += '\n';
console.log(s)
}
maybe you just know what makes the asterisks on this loop so much?
even though I only want to repeat it for 5 lines, but why are there so many results?
[1]: https://i.stack.imgur.com/7zzOu.png
Your code is producing the following result:
Because not resetting the var s inside the outter iteration.
Instead, you may do:
for (let i = 0; i < 5; i++) {
let s = '';
for (let j = 0; j < 10; j++) {
s += '*';
}
s += '\n';
console.log(s);
}
which will produce the expected result.
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);
}
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( "  " );
}
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("  ");
}
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");
}