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);
}
Related
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);
}
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.
its me again. This time I tried to make a Selection Sort using JavaScript. Everything went well until my code didn't print the specific output that I want. If you tried to run my code below, the second-last index in the array didn't sort properly. Can anyone give me a brief explanation?
Here's the code by the way,
var num = [30,1,90,3,2,34];
var bilnum = num.length,i,j,min;
var temp = 0;
for(i = 0; i < bilnum - 1; i++){
min = i;
for(j = i + 1; j < bilnum ; j++){
if(num[j] < num[min]){
min = j;
}
if(min != i){
temp = num[i];
num[i] = num[min];
num[min] = temp;
}
}
}
document.write(num)
You need to move the below snippet from the inner loop to the end of the outer loop as you need to swap after finding the min index.
if(min != i){
temp = num[i];
num[i] = num[min];
num[min] = temp;
}
So the code will look something like this
var num = [30,1,90,3,2,34];
var bilnum = num.length,i,j,min;
var temp = 0;
for(i = 0; i < bilnum - 1; i++){
min = i;
for(j = i + 1; j < bilnum ; j++){
if(num[j] < num[min]){
min = j;
}
}
if(min != i){
temp = num[i];
num[i] = num[min];
num[min] = temp;
}
}
console.log(num);
My code isn't working . I'm trying to figure out what the bug is . Can someone help ? ! It's a function that is supposed to return an array of the first n triangular numbers.
For example, listTriangularNumbers(5) returns [1,3,6,10,15].
function listTriangularNumbers(n) {
var num;
var array = [];
for (i = 1; i <= n; ++i) {
num = i;
for (j = i; j >= 1; --j) {
num = num + j;
}
array.push(num);
}
return array;
}
Your initial initialization of j is wrong, it's starting at i so it's going too high. Also switched the operators around to make sure the conditions work.
function listTriangularNumbers(n) {
var num;
var array = [];
for (i = 1; i <= n; i++) {
num = i;
for (j = i-1; j >= 1; j--) {
num = num + j;
}
array.push(num);
}
return array;
}
You can try below code to get help:
a = listTriangularNumbers(8);
console.log(a);
function listTriangularNumbers(n) {
var num;
var array = [0];
for (i = 1; i <= n; i++) {
num = 0;
for (j = 1; j <= i; j++) {
num = num + j;
}
array.push(num);
}
return array;
}
You actually don't need 2 for-loops to do this operation. A single for-loop would suffice.
function listTriangularNumbers(n) {
// Initialize result array with first element already inserted
var result = [1];
// Starting the loop from i=2, we sum the value of i
// with the last inserted element in the array.
// Then we push the result in the array
for (i = 2; i <= n; i++) {
result.push(result[result.length - 1] + i);
}
// Return the result
return result;
}
console.log(listTriangularNumbers(5));
function listTriangularNumbers(n) {
var num;
var array = [];
for (i = 1; i <= n; ++i) {
num = i;
for (j = i-1; j >= 1; --j) {
num = num + j;
}
array.push(num);
}
return array;
}
var print=listTriangularNumbers(5);
console.log(print);
I'm trying to get the following code to add each number in the element separately and not the whole array together but the dash seems to stop the loop from calculating the total sum of each element. I can't seem to make it so it'll except any length of number for the variable. Any help is greatly appreciated!
var creditNum = [];
creditNum[0] = ('4916-2600-1804-0530');
creditNum[1] = ('4779-252888-3972');
creditNum[2] = ('4252-278893-7978');
creditNum[3] = ('4556-4242-9283-2260');
var allNum = [];
var total = 0;
var num = 0;
var cnt = 0;
for (var i = 0; i < creditNum.length; i++) {
num = creditNum[i];
for (var j = 1; j <= num.length; j++) {
var num = creditNum[i].substring(cnt, j);
console.log(creditNum[i].charAt(cnt));
console.log(cnt, j);
cnt = cnt + 1;
}
if (num != "-") j = j++;
console.log(parseInt(num));
}
console.log(total);
Assuming the intent is to add '4916-2600-1804-0530' and output the value as 49, then the following modification will achieve that.
var creditNum = ['4916-2600-1804-0530', '4779-252888-3972', '4252-278893-7978','4556-4242-9283-2260'];
for (var i = 0; i < creditNum.length; i++) {
var num = creditNum[i].replace(/\-/g, '');
var total = 0;
for (var j = 0; j < num.length; j++) {
total += Number(num[j]);
}
console.log(creditNum[i], total);
}
Using native array methods, the code can be refactored as the following.
var creditNumbers = ['4916-2600-1804-0530', '4779-252888-3972', '4252-278893-7978','4556-4242-9283-2260'];
creditNumbers.forEach(function(creditNumber) {
var num = creditNumber.replace(/\-/g, '').split('');
var total = num.reduce(function(tally, val) {
return tally += Number(val);
}, 0);
console.log(creditNumber, total);
});