Why is my while loop not iterating through completely? - javascript

So this is my code below, the goal is for this program is to check to see if the letters of the second string can be found in the first string. However I found the problem that i isn't, increasing in value. So the loop is only going through once. So this program ends at the first letter that it finds and returns true. How do I get i to increase so that it's iterating through every character of the string?
function mutation(arr) {
var str = arr[1];
str = str.toLowerCase().split("");
var i = 0;
while (i < arr.length) {
if (arr[0].indexOf(str[i]) > -1) {
//return arr[i].indexOf(str[i], i);
return true;
} else {
return false;
}
i++;
}
}
mutation(["hello", "hey"]);

This maybe?
function mutation(arr) {
var str = arr[1];
str = str.toLowerCase().split("");
// iterating an array screams "for loop"
for (var i=0; i < str.length; i++) {
// if the letter was not found exit immediately
if (arr[0].indexOf(str[i]) == -1) return false;
}
// since it didn't exit before, all the letters must have been found.
return true;
}

function mutation(arr) {
var base = arr[0],
str = arr[1].toLowerCase().split(''),
i = 0,
match = true;
while (i < str.length) {
// if any target letter is not in base, return false
if(base.indexOf(str[i]) === -1){
return false;
}
}
// otherwise they were all in, so return true
return true;
}
mutation(["hello", "hey"]);

Totally different technique.
This function replaces, in the second string, all letters from the first string with empty space. If the length is zero all letters were found.
function mutation(arr) {
return arr[1].replace(new RegExp("[" + arr[0] + "]", "g"), "").length == 0;
}

Related

Palindrome checker does not function properly with "almostomla"

function palindrome(str) {
const forward = str.replace(/[^a-zA-Z ]/g, "").toUpperCase()
const reversed = str.replace(/[^a-zA-Z ]/g, "").toUpperCase()
for (let i = 0; i < forward.length; i++) {
for (let k = reversed.length - 1; k >= 0; k--) {
if (forward[i] === reversed[k]) {
return true
} else {
return false
}
}
}
}
console.log(palindrome("almostomla"));
Why is this not working??
does my loop just creates a new "s"?
You don't need nested loops, that will compare every character with every other character. You just want to compare the first character with the last character, 2nd character with 2nd-to-last character, and so on. So there should just be a single loop that increments i and decrements k in lock step.
You shouldn't return true when you find a match, because there could be later characters that don't match. Return false when you find a mismatch, and return true if you make it through the loop without returning.
You don't need both forward and reversed variables, since they're the same. Just convert the input string to uppercase once, and use that for both.
You don't need to iterate through the whole string, you can stop when you get to the middle.
function palindrome(str) {
const upper = str.replace(/[^a-zA-Z ]/g, "").toUpperCase()
for (let i = 0, k = upper.length - 1; i < upper.length/2; i++, k--) {
if (upper[i] !== upper[k]) {
return false
}
}
return true;
}
console.log(palindrome("almostomla"));
console.log(palindrome("almotomla"));
console.log(palindrome("almottomla"));
You might want this:
function palindrome(str) {
const forward = str.replace(/[^a-zA-Z ]/g, "").toUpperCase()
var n = forward.length
for (let i = 0; i < n; i++) {
if (forward[i] !== forward[n-i-1]) {
return false;
}
}
return true;
}

check the alphabetical order

I am a newbie who is trying hard to have a grip on javascript. please help me to consolidate my fundamentals.
input will be a string of letters.
following are the requirements.
function should return true if following conditions satisfy:
letters are in alphabetical order. (case insensitive)
only one letter is passed as input. example :
isAlphabet ('abc') === true
isAlphabet ('aBc') === true
isAlphabet ('a') === true
isAlphabet ('mnoprqst') === false
isAlphabet ('') === false
isAlphabet ('tt') === false
function isAlphabet(letters) {
const string = letters.toLowerCase();
for (let i = 0; i < string.length; i++) {
const diff = string.charCodeAt(i + 1) - string.charCodeAt(i);
if (diff === 1) {
continue;
} else if (string === '') {
return false;
} else if (string.length === 1) {
return true;
} else {
return false;
}
}
return true;
}
It's generally a better practice to start your function off with dealing with the edge-cases rather than putting them somewhere in the middle. That way, the function returns as soon as it can - and it's a lot easier to read than a waterfall of if..else statements.
function isAlphabet(letters) {
if ("" == letters) {
return false;
}
if (1 == letters.length) {
return true;
}
const string = letters.toLowerCase();
// carry on with your loop here.
}
You've got the right idea, but it can be simplified to just fail on a particular error condition, i.e when a smaller character follows a larger one:
function isAlphabet(letters) {
const string = letters.toLowerCase();
let lastChar;
for (let i = 0; i < string.length; i++) {
// Grab a character
let thisChar = string.charCodeAt(i);
// Check for the failure case, when a lower character follows a higher one
if (i && (thisChar < lastChar)) {
return false;
}
// Store this character to check the next one
lastChar = thisChar;
}
// If it got this far then input is valid
return true;
}
console.log(isAlphabet("abc"));
console.log(isAlphabet("aBc"));
console.log(isAlphabet("acb"));
You can use the simple way to achieve the same as below
function isAlphabet(inputString)
{
var sortedString = inputString.toLowerCase().split("").sort().join("");
return sortedString == inputString.toLowerCase();
}
console.log("abc = " + isAlphabet("abc"));
console.log("aBc = " + isAlphabet("aBc"));
console.log("acb = " + isAlphabet("acb"));
console.log("mnoprqst = " + isAlphabet("mnoprqst"));
Note: Mark the answer is resolves your problem.

CoderByte Letter Changes Java Script

The question is :
Using the JavaScript, have the function LetterChanges(str) take the str parameter being passed and modify it using the following algorithm. Replace every letter in the string with the letter following it in the alphabet (ie. c becomes d, z becomes a). Then capitalize every vowel in this new string (a, e, i, o, u) and finally return this modified string.
function LetterChanges(str){
var result = "";
for(var i = 0; i < str.length; i++) {
var letters = str[i];
if (letters == "a"|| letters == "e"|| letters == "i"|| letters == "o"|| letters =="u") {
letters = letters.toUpperCase();
result+=letters;
} else if (letters == "z") {
letters = "a";
} else {
var answer = "";
var realanswer="";
for (var i =0;i<str.length;i++) {
answer += (String.fromCharCode(str.charCodeAt(i)+1));
}
realanswer += answer
}
}
return realanswer;
return result;
}
LetterChanges();
basically, if return realanswer is placed before return result and LetterChanges is called with "o" i get the output undefined. But if it is called with a non vowel such as "b" it will output "c" which is correct.
now if i place return result before return realanswer it will work properly for vowels but not for other letters. thanks for the help
function LetterChanges(str) {
return str
.replace(/[a-zA-Z]/g, (x) => String.fromCharCode(x.charCodeAt(0)+1))
.replace(/[aeiou]/g, (v) => v.toUpperCase());
}
The first part modifies the consonants by an increment of 1.
Regex is isolating the characters with [] versus no brackets at all. g ensures that the regex is applied anywhere in the string, as opposed to not putting g which gives you the first occurrence of the search.
You have to convert the characters in the string to their Unicode because incrementing is a math operation. x.charCodeAt(0) is saying at the index of 0 of the string in the argument. The increment of 1 is not within the parentheses but outside.
The second part modifies the vowels to upper case.
This is pretty straightforward, the regex only finds the individual characters because [] are used, g for anywhere in the string. and the modifier is to make the characters become upper case.
function LetterChanges(str) {
var lstr = "";// Took a variable to store after changing alphabet//
for(var i=0;i<str.length;i++){
var asVal = (str.charCodeAt(i)+1);// To convert string to Ascii value and 1 to it//
lstr += (String.fromCharCode(asVal));// To convert back to string from Asii value//
}
console.log("Before converting vowels :"+lstr); //Printing in console changed alphabet//
var neword =""; // variable to store word after changing vowels to uppercase//
for(i=0;i<lstr.length;i++){
var strng = lstr[i]; // Storing every letter in strng variable while running loop //
if(strng=="a"||strng=="e"||strng=="i"||strng=="o"||strng=="u"){
neword += strng.toUpperCase(); // If it a vowel it gets uppercased and added //
}
else{
neword += strng; // If not vowel , it just gets added without Uppercase //
}
}
console.log("After converting vowels :"+neword); //Printing in console the word after captilising the vowels //
}
LetterChanges("Goutham"); // Calling a function with string Goutham //
function letterChanges(str) {
let res = '';
let arr = str.toLowerCase().split('');
// Iterate through loop
for(let i = 0; i < str.length; i++) {
// Convert String into ASCII value and add 1
let temp = str.charCodeAt(i) + 1;
// Convert ASCII value back into String to the result
res += (String.fromCharCode(temp));
}
console.log(res);
// Replace only vowel characters to Uppercase using callback in the replace function
return res.replace(/[aeiou]/g, (letters) {
return letters.toUpperCase();
});
}
function LetterChanges(str) {
return str
.split('')
.map((c) => String.fromCharCode((c >= 'a' && c <= 'z') ? (c.charCodeAt(0)-97+1)%26+97 : (c >= 'A' && c <= 'Z') ? (c.charCodeAt(0)+1-65)%26+65 : c.charCodeAt(0)))
.join('').replace(/[aeiou]/g, (letters) => letters.toUpperCase());
}
export const letterChange=(str)=>{
let newStr = str.toLowerCase().replace(/[a-z]/gi, (char)=>{
if(char==="z"){
return "a"
}else{
return String.fromCharCode(char.charCodeAt()+1)
}
})
let wordCap = newStr.replace(/a|e|i|o|u/gi, char => char.toUpperCase())
return wordCap
}
function changeLetters(str) {
var result = "";
for (var i = 0; i < str.length; i++) {
var item = str[i];
if (
item == "a" ||
item == "e" ||
item == "i" ||
item == "o" ||
item == "u"
) {
item = item.toUpperCase();
result += item;
} else if (item == "z") {
letters = "a";
result += item;
} else {
result += String.fromCharCode(str.charCodeAt(i) + 1);
}
}
return result;
}

checking strings in an array

I'm trying to see if the string in the first element of the array contains all of the letters of the string in the second element of the array.
For example
['hello', 'hey'] = false;
['Army', 'Mary'] = true;
Here is my code
function mutation(arr) {
a = arr[0].toLowerCase().split("");
b = arr[1].toLowerCase().split("");
for(i = 0; i < a.length; i++){
if(b.indexOf(a[i]) != -1){
console.log('true');
} else {
console.log('false');
}
}
}
mutation(['Army', 'Mary']);
UPDATED
I need to see if element 1 contains all the letters for element 2 before I return back anything.
This would do, I'm sure there are better and optimal solutions though,
1) Storing the return result in a boolean, as var result = true;.
2) Check if both the Strings are equal/same, no need to loop, return the result which is true.
3) loop through each characters and see if the target element contains them, if found a mismatch set, result to false, break and return result.
function mutation(arr) {
a = arr[0].toLowerCase().split("");
b = arr[1].toLowerCase().split("");
var result = true;
if(a === b)
return result;
for(i = 0; i < a.length; i++){
if(b.indexOf(a[i]) === -1){
result = false;
break;
}
}
return result;
}
mutation(['Army', 'Mary']);
UPDATE Added a condition if (a === b) return true; to skip for loop.
No need of loop, you can take advantage of array functions.
Steps
Sort both arrays
Cast to the string
Check if strings2 contains string1
function mutation(arr) {
var a = arr[0].toLowerCase().split(''),
b = arr[1].toLowerCase().split('');
// For exact equality
return a.sort().toString() === b.sort().toString();
// return b.sort().toString().indexOf(a.sort().toString()) > -1;
}
document.write('Army and Mary: ' + mutation(['Army', 'Mary'])); // true
document.write('<br />a and b: ' + mutation(['a', 'b'])); // false
document.write('<br />ab and abc: ' + mutation(['ab', 'abc'])); // false
Simply you need to loop throught the second element letters and return false if a character doesn't exist in first element, or continue the loop if it exists.
Then check if the counter is equal to your string length then it contains all the given letters and return true:
function mutation(arr) {
a = arr[1].toLowerCase().split("");
b = arr[0].toLowerCase().split("");
if (a === b) return true;
for (i = 0; i < a.length; i++) {
if (b.indexOf(a[i]) === -1) {
return false;
}
}
if (i === a.length) {
return true; // all the letteers of element one exists in the second element
}
}
if (mutation(['Army', 'Mary'])) {
alert("Element one contains all letters of second element !");
} else {
alert("Sorry!");
}
Note:
Make sure you loop throught the second element characters and not the first one, see the a = arr[1].toLowerCase().split("");.
//mutation function work ignoring case and order of character in strings
function mutation(arr) {
var first = arr[0].toLowerCase();
var second = arr[1].toLowerCase();
for(var i = 0; i < second.length; i++){
if(first.indexOf(second[i]) == -1){
return false;
}
}
return true;
}
//this returns true
mutation(["hello", "ol"]);

collecting/pulling numbers from a string in javascript

consider the script below..
$('#accessories').editable({
validate: function(value) {
// solution will be placed here
}
});
if variable 'value' has the string value of "RUST-PROOFING (2),SPOILER (1),ALARM (2),SIDE-SKIRT (1)" , how could i sum (inclosed with parenthesis) the numbers (2) (1) (2) (1) from 'value' variable.
Look at this FIDDLE
I left to you to add some exception like if a number is the last thing in the string, because my code don't look for it and will not add it.
All you have to do is loop the string, check if it's a number, if it is, add it to a var and continu to loop, when the next char is not a number, add what you have build up.
for (var i = 0; i < str.length; i++) {
if (isNumber(str[i])) {
strNumber += str[i];
} else if (strNumber != "") {
retVal += Number(strNumber);
strNumber = "";
}
}
Try the code below. First you setup a regex to look for numbers in your string, this returns an array of matches, then you can pass this array into a custom function which multiplies all numbers in an array together.
var str = "RUST-PROOFING (2),SPOILER (1),ALARM (2),SIDE-SKIRT (1)";
var re = /[\d+]/g //Match only numbers (along the whole string)
var matches = str.match(re);
var total = multiply(matches); //Pass your array of matches to your multiply function;
alert(total); //4
function multiply(arr) { //Multiplies all numbers in an array and returns the total value;
var num = 0;
for(var i = 0, len = arr.length; i < len; i++) {
num += parseInt(arr[i]);
}
return num;
}
Have a look at the fiddle
thanks guys (especially to Shryme and Mark).. here's a wrap-up... hoping this will help a newb like me in the future..
$('#accessories').editable({
validate: function(value) {
$ntot = add(value.toString());
$('#npoints').editable('setValue', $ntot);
}
});
function add(str) {
var retVal = 0;
var strNumber = "";
for (var i = 0; i < str.length; i++) {
if (isNumber(str[i]) && (str[i-1]=="(" || str[i+1]==")")) {
strNumber += str[i];
} else if (strNumber != "") {
retVal += Number(strNumber);
strNumber = "";
}
}
return retVal;
}
function isNumber(n) {
if (n == "") return false;
return !isNaN(n);
}

Categories

Resources