I have a javascript question, I want to make a Triangle like this
*
**
***
****
*****
this is my code which makes opposite direction
for(let i = 0;i<=5;i++){
let str = "";
for(let j = 0;j<i;j++){
str += "*";
}
console.log(str)
}
I wanna use for loop to make this triangle down bellow instead of using "repeat".
for(let i = 0;i<=5;i++){
let str = "";
str = " ".repeat(5-i);
str2 = "*".repeat(i);
console.log(str+str2);
}
You could use for loop with ternary operator
for (let i = 0; i <= 5; i++) {
let str = "";
for (let j = 0; j <= 5; j++) {
str += j < 5 - i ? " " : "*";
}
console.log(str);
}
Use padStart method
for (let i = 0; i <= 5; i++) {
let str = "";
for (let j = 0; j < i; j++) {
str += "*";
}
console.log(str.padStart(5, " "));
}
Further simplify to one liner
for (let i = 0; i <= 5; i++) {
console.log('*'.repeat(i).padStart(5, " "));
}
You can write it like this:
for(let i = 0;i<=5;i++){
let str = "";
for(let j = i;j<5;j++){
str += " ";
}
for(let j = 0;j<i;j++){
str += "*";
}
console.log(str)
}
This method can be used in all other programming languages, cause there's no special js syntax or special js built-in function.
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);
Im working on an algorithm to return the provided string with the first letter of each word capitalized. While leaving the rest of the word in lower case. Looking for some insight to why this code isn't working. Thanks.
function titleCase(str) {
let result = "";
let words = str.split(" ");
for(let i = 0; i <= words.length; i++){
let word = words[i];
for(let j = 0; j <= word.length; j++){
if(j === 0){
result += word[j].toUpperCase();
} else{
result += word[j].toLowerCase();
}
}
return result += " "
}
return result.slice(0, result.length - 1)
}
There are three errors in your program, that are stopping it from working:
You need to change i <= words.length to i < words.length (or i <= words.length - 1), since indexes start from 0 in javascript like most
programming languages.
You need to change j <= word.length to j < word.length (or j <= word.length - 1), same reason as above.
You need to not return prematurely, and need to change return result += " " to just result += " ".
Also although it does not stop your function from working you could simplify your return line by utilizing trimEnd.
function titleCase(str) {
let result = "";
let words = str.split(" ");
for (let i = 0; i < words.length; i++) {
let word = words[i];
for (let j = 0; j < word.length; j++) {
if (j === 0) {
result += word[j].toUpperCase();
} else {
result += word[j].toLowerCase();
}
}
result += " "
}
return result.trimEnd();
}
console.log(titleCase("The quick brown fox jumps over the lazy dog"));
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");
}