Troubleshooting Algorithm - javascript

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"));

Related

Why the Double mirror pascal star pattern is not printed?

Here is the my javascript code for printing the pattern shown below in the image.
please check the code and solve the error.
<script>
var n = prompt("Enter the number of n you want to print");
//rows = Math.floor(n / 2)
let str = ""
var i, j, k
for(i = 1; i <= n; i++){
for(j = 1; j <= i; j++){
str += "*"
}
for(k = n + 1; k >= i; k--){
str += " "
}
for(k = n + 1; k >= i; k--){
str += " "
}
for(j = 1; j <= i; j++){
str += "*"
}
str += "\n"
}
for(i = 1; i <=n + 2; i++){
for(j = n + 2; j > i; j--){
str += "*"
}
for(k = 1; k <= i; k++){
str = " "
}
for(k = 1; k <= i; k++){
str = " "
}
for(j = n + 2; j > i; j--){
str += "*"
}
str += "\n"
}
console.log(str)
</script>
I want Output like this :
but I got just 2 spaces in output
Convert your input to Number:
n = Number(n);
and then change your code as #TomLV mentioned:
var n = prompt("Enter the number of n you want to print");
//rows = Math.floor(n / 2)
n = Number(n);
let str = ""
var i, j, k
for(i = 1; i <= n; i++){
for(j = 1; j <= i; j++){
str += "*"
}
for(k = n + 1; k >= i; k--){
str += " "
}
for(k = n + 1; k >= i; k--){
str += " "
}
for(j = 1; j <= i; j++){
str += "*"
}
str += "\n"
}
for(i = 1; i <=n + 2; i++){
for(j = n + 2; j > i; j--){
str += "*"
}
for(k = 1; k <= i; k++){
str += " "
}
for(k = 1; k <= i; k++){
str += " "
}
for(j = n + 2; j > i; j--){
str += "*"
}
str += "\n"
}
console.log(str)
You are setting str equal to " " in both "k loops" in the second "i for loop".
e.g:
for(k = 1; k <= i; k++){
str = " "
}
for(k = 1; k <= i; k++){
str = " "
}
If you update those to += it works.
Some issues:
prompt returns a string, you need to convert it to a number. You can use the unary plus for that.
str = " " occurs at two places where you should have done str += " "
The generated pattern has two spaces in the center line, while you are asked to only have one space there. To make that happen have the k loops make one iteration less, and add str += " " as a separate statement outside of those loops.
The output has an empty line at the very end. This is because the second i loop is making one iteration too many.
Not a problem, but:
Use semi-colons to separate statements. Although JavaScript provides automatic semi-colon insertion, you wouldn't be the first to fall into one of the pitfalls. It is better to take control of this yourself and have the habit of adding the semi-colons.
There really is no need here to declare loop variables at the top. Just declare them at the moment you need them with only the scope they need to have.
I'll assume that the number of lines in the output is supposed to be n*2+1 and that there was no error concerning that aspect.
Corrected code:
// Convert string to number using unary plus:
const n = +prompt("Enter the number of n you want to print");
let str = "";
for (let i = 1; i <= n; i++) {
for (let j = 1; j <= i; j++) {
str += "*";
}
// Reduced the number of iterations here:
for (let k = n; k >= i; k--) {
str += " ";
}
// Add one space for the center column
// that is the only column without asterisks
str += " ";
// Reduced the number of iterations here:
for (let k = n; k >= i; k--) {
str += " ";
}
for (let j = 1; j <= i; j++) {
str += "*";
}
str += "\n";
}
// Reduced number of iterations. i should not become equal to n + 2
for (let i = 1; i <= n + 1; i++) {
for (let j = n + 2; j > i; j--) {
str += "*";
}
// Reduced the number of iterations here:
for (let k = 1; k < i; k++) {
str += " "; // Fixed assignment
}
// Add one space for the center column
// that is the only column without asterisks
str += " ";
// Reduced the number of iterations here:
for (let k = 1; k < i; k++) {
str += " "; // Fixed assignment
}
for (let j = n + 2; j > i; j--) {
str += "*";
}
str += "\n";
}
console.log(str);
Note that JavaScript has functions that can facilitate this proces, like "*".repeat(i) can be used instead of a loop to produce the same string.
So then it becomes:
const n = +prompt("Enter the number of n you want to print");
let str = "";
for (let i = 1; i <= n + 1; i++) {
str += "*".repeat(i) + " ".repeat(2*n + 3 - 2*i) + "*".repeat(i) + "\n";
}
for (let i = n; i >= 1; i--) {
str += "*".repeat(i) + " ".repeat(2*n + 3 - 2*i) + "*".repeat(i) + "\n";
}
console.log(str);
And you could also reuse the results of the first loop to derive the second half of the output by storing the lines in an array. You can then reverse that array to get the second half (without the middle line):
const n = +prompt("Enter the number of n you want to print");
const arr = Array.from({length: n + 1}, (_, i) =>
"*".repeat(i+1) + " ".repeat(2*(n-i)+1) + "*".repeat(i+1)
);
console.log([...arr, ...arr.reverse().slice(1)].join("\n"));

Replacing all of the repeated characters in javascript

function duplicateEncode(word){
var i;
var j;
for(i = 0; i < word.length; i++) {
for(j = i + 1; j < word.length; j++) {
if (word[i] == word[j]) {
word = word.replace(/word[i]/gi, ')');
}
else word = word.replace(/word[i]/gi, '(');
};
};
return word;
}
I need to get ( if character is not repeated in the word and this ) if it is and this code doesnt work it just gives me the word back that I type in.
You are not using regex properly. Here is one possible solution based off of your original code. As you know, Strings are immutable in Javascript so we need to rebuild the string every time using your approach.
function duplicateEncode(word){
for(i = 0; i < word.length; i++) {
if (word[i] == word[i+1]) {
word = word.substring(0,i) + ')' + word.substring(i+1);
}
else {
word = word.substring(0,i) + '(' + word.substring(i+1);
}
}
return word;
}
To avoid rebuilding the string we can store the characters in an array and then join them at the end for a performance boost for large strings.
function duplicateEncode(word){
const newWordArr = [];
for(i = 0; i < word.length; i++) {
if (word[i] == word[i+1]) {
newWordArr.push(')');
}
else {
newWordArr.push('(');
}
}
return newWordArr.join('');
}

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);
}

naive string matching algorithm gone wrong

I am trying to implement naive search and I do not get the expected result. Can anyone point out here, what could be the possible error.
function naive(string, str) {
for (let i = 0; i <= string.length - str.length; i++) {
if (string[i] == str[0]) {
let counter = 1
for (let j = 1; j <= str.length; j++) {
if (string[i + j] == str[j]) {
counter++;
console.log(counter)
} else
counter = 0;
}
if (counter == str.length) {
console.log(`${counter} pattern matched at ${i}`)
}
} else
console.log('nothing matched')
}
}
var match_found = false;
function naive(string, str){
for(let i =0; i <= string.length - str.length; i++){
if(string[i] == str[0]){
let counter= 1
for(let j = 1; j < str.length; j++){
if(string[i + j] == str[j]){
counter++;
}else{
break;
}
}
if(counter == str.length){
console.log('Pattern matched at ' + i);
match_found = true;// can break; here if you wish to, else it will give you all matches present
}
}
}
if(match_found === false){
console.log(str + ' not found in ' + string);
}
}
naive('abcdgggabcdggg','ggg');
You increment the counter when there is a match, but you need to break the loop where there is a mismatch.
Your inner for loop condition needs to have j < str.length instead of j <= str.length, because index starts from 0.
else console.log('nothing matched'). You can't just instantly decide that. If a string index doesn't match, you need to still keep looking for the rest of the indexes.
Best way to go about it is to maintain a boolean flag for it as shown in the above code.
You don't need to do all that iteration and comparison by yourself. Here's a simpler version of your function:
function naive(string, str) {
var counter = 0,
i = string.indexOf(str, 0); //find first occurance of str in string
while(i !== -1){
++counter; //we have a match, count one up
console.log(`counter %i, index %i`, counter, i);
i = string.indexOf(str, i+1); //find next occurance
}
return counter;
}
console.log("result", naive("lorem upsum", "m"));

Quickest way to achieve this sequence?

I'm trying to create a simple algorithm that builds an array with a dynamic length.
Then, it will, one by one, replace an item, and then two, then three and so on until the only items left are the first and last.
like this:
12345
1*345 // it never touches the first
12*45
123*5 // it doesn't ever touch the last item
1**45
12**5
1***5 // done, nowhere else to go
I put together a simple demo to show what I'm trying to do.
var length = 6,
array = [],
log = document.getElementById("log"),
edited,
j,
i;
for (i = 1; i <= length; i++) {
array.push(i);
}
log.innerHTML += array.join(" ") + "<br><br>";
for (i = 1; i < (length - 1); i++) {
edited = array.concat();
for (j = i; j < (length - 1); j++) {
edited[j] = "*";
log.innerHTML += edited.join(" ") + "<br>";
}
log.innerHTML += "<br>";
}
Fiddle
It works fine, the only problem is it's out of order.
Right now it seems to only iterate by number of asterisks, then by index. I need it to do the opposite.
// it does this
12345
1*345
1**45
1***5
12*45
12**5
123*5 // out of order
If someone could help that would be great because I am really at a loss!
This should get it done.
var a = 6, // array length
b = [], // array
log = document.getElementById("log"),
c,
d,
e;
for (c = 1; c <= a; c++) {
b.push(c);
}
log.innerHTML += b.join(" ") + "<br><br>";
//the size of the asterisk chunk
for(i = 1; i < b.length - 1; i ++)
{
//position to start asterisk chunk
for(j = 1; j < b.length - i; j ++)
{
var tempArr = b.concat();
//the position inside of the asterisk chunk
for(k = 0; k < i; k ++)
{
tempArr[k + j] = "*";
}
log.innerHTML += tempArr.join(" ") + "<br>";
}
}
JSFiddle
This seems to work well:
str = "1234567"
len = str.length;
for(var stars = 1; stars < len - 1; stars++) {
for(var pos = 1; pos < len - stars; pos++) {
var s = str.substr(0, pos)
+ new Array(stars + 1).join("*")
+ str.substr(pos + stars);
document.write(s + "<br>");
}
}

Categories