How to count how many consonants are in a string? - javascript

Am I somewhere near the solution? I always get a double number of the consonants.
I was convinced that this was the correct approach.
function consonants(str) {
var countConsonants = 0;
for (var i = 0; i <= str.length; i++) {
if (str[i] !== "a" || str[i] !== "e" || str[i] !== "i" ||
str[i] !== "o" || str[i] !== "u" || str[i] !== " ") {
countConsonants += 1;
}
}
return (countConsonants);
}
consonants("asdfghaaa");
I am expecting an answer of 5 i.e. sdfgh are the consonants.

Your logic is flawed, The operator in your condition should be AND && not OR ||, since you want to compare all the chars not just one of them :
function consonants(str) {
var countConsonants = 0;
for (var i = 0; i < str.length; i++) {
if (str[i] !== "a" && str[i] !== "e" && str[i] !== "i" &&
str[i] !== "o" && str[i] !== "u" && str[i] !== " ") {
countConsonants++;
}
}
return (countConsonants);
}
console.log(consonants("asdfghaaa"));
NOTE : The loop should stop at length-1 since arrays are 0 based, so replace :
for (var i = 0; i <= str.length; i++) {
__________________^^
By :
for (var i = 0; i < str.length; i++) {
__________________^
Hope this helps.

You can do
let str = 'asdfghaaa';
let result = str.split('').filter(e => e.match(/[^aeiou]/) != null).length;
console.log(result);

The main problem in counts lies within your conditions.
You're increasing the number of consonants whenever one of the conditions fail (that's what || does, known as the OR operator). So whenever a character !== "a" OR !== "e", you're increasing the count, which is wrong. (Imagine that a is !== 'e', so you're counting a as a consonant).
Change the || binary operator to && (AND); this way, you're only increasing the consonant count whenever the current character str[i] is not among the values you're verifying for (a, e, i, o, u, ' ').
As others pointed out, you're also likely to run into an error as the max value of i should be Length-1.
There also other problems you need to consider:
What happens when the character is an uppercase letter?
What happens when the character is a punctuation mark or a number?
For a beginner, this may not be relevant, but it's well worth getting these techniques under your skin: It's more readable to create an array that contains all of the value you're verifying for ["a","e", etc] and then, for each char in the source string, just verify if array.indexOf(str[i]) >= 0 (which means that the character is included in the array).

Your answer is almost right. The only problem is || instead of &&. You're checking that it's not a AND it's not e AND it's not i, etc. Your function comes out true for every letter, since a is (not a || not e), right?

function consonants (str) {
return str.match(/[aeoiu]/gi)||[].length;
}
May be not good for long string.

You need to and your conditions because if you use || the condition always evaluates to true. Your loop should go from 0 to index < str.length.
function consonants(str) {
var countConsonants = 0;
for (var i = 0; i < str.length; i++) {
if (str.charAt(i) !== "a" && str.charAt(i) !== "e" && str.charAt(i) !== "i"
&& str.charAt(i) !== "o" && str.charAt(i) !== "u" && str.charAt(i) !== " ") {
countConsonants++;
}
}
return countConsonants;
}
console.log(consonants("asdfghaaa"));

I had this challenge too here is how i did:
const paragraph = "A quick brow fox is trying to bite me."
paragraph.match(/(?![aeiou])[a-z]/gi, "").length
Source: https://forum.freecodecamp.org/t/regex-for-consonants/282833/4

Here is a working example
let str="Hello world.";
let vowel=str.match(/[aeiou]/gi).length;
let consonant = str.match(/[^aeiou .]/gi).length;
console.log("Vowel "+vowel+"\n");
console.log("Vowel "+consonant+"\n");

Related

For loop to count the number of vowels in a string (javascript)

I'm writing a function that will count the number of vowels in a string.
I decided to use a for-loop and an if-statement to do this.
function vowels (string) {
var counter = 0;
for (let i=0; i < string.length; i++) {
if (i == 'a' || i == 'e' || i == 'i' || i == 'o' || i == 'u') {
counter++;
}return counter;
}
}
This is my code. When I call the function, it only returns 0 no matter how many vowels my string has. What's wrong?
Couple of things.
You're not looping through the string but the length of it. You need to use the length to get the position of the string.
You're returning the counter, exiting the function, on index 0.
I also added a toLowerCase to account for casing. A === a but that depends on your use case.
Always use === operator when validating types. You can learn more here but basically == compares value only and === compares value and type.
e.g. 0 == '0' equals true and 0 === '0' equals false
function vowels (value) {
let counter = 0;
let char = '';
for (let i = 0; i < value.length; i++) {
char = value[i].toLowerCase();
if (char === 'a' || char === 'e' || char === 'i' || char === 'o' || char === 'u') {
counter++
}
}
return counter;
}
vowels("AaBbCcDdEe");
returns 4. AaEe.

node.js – Check if word has an added/changed letter to a previous word

I'm working on a command for my Discord bot that allows for a game to be played, in which the goal is to post words that either change one letter in the previous word, or add a letter. I'm using this function:
function checkDifferentString(str1, str2) {
let diff = 0;
if (str1 === str2) return true;
let lengthDiff = Math.abs(str1.length - str2.length)
if (lengthDiff > 1) return false;
for (let i=0; (i<str1.length || i < str2.length);i++) {
if (diff > 1) return false;
if (str1.charAt(i) !== str2.charAt(i)) diff++
}
if (diff <= 1) return true
else return false;
}
and it works fine if you change a letter, or add a letter to the end of the word (e.g. mat->math). But if you add a letter in the word (e.g. mat->malt), it says that the word doesn't follow the rules, even though it does. How can I change the function so it also catches for added letters inside the words?
I think this is more easier to understand.
function isChanged(prev, curr) {
return (prev.length + 1 === curr.length && curr.slice(0, prev.length) === prev)
|| (prev.length === curr.length && Array.from(prev).filter((ch, idx) => ch != curr[idx]).length === 1)
}
The first condition is true when add one character.
The second conditions is true when there is only one different character.
Updated (I did misread your question)
To check change one letter, use longest common sequence(https://en.wikipedia.org/wiki/Longest_common_subsequence_problem).
If two string has same length N and the length of longest common sequence is N-1, it means one letter is changed.
If two string has length N and N+1, and the length of longest common sequesnce is N, it means one letter is added.
function lengtOfLCS(s1, s2) {
// LCS algorithm..
return result
}
function isChanged(prev, curr) {
return (prev.length === curr.length && lengtOfLCS(prev, curr) === prev.length - 1)
|| (prev.length+1 === curr.length && LCSlengtOfLCSprev, curr) === prev.length)
}

Significant Figures in Numerical Values

I am trying to make a calculator of sorts where you perform an operation and the code returns an answer that follows the rules of significant figures. Here is a boiled down portion of what I have coded:
var x = 0.002.toString().split(""); //to convert the number to a list
for(i = 0; i <= x.length; i++) {
if(x[i] != 0 || ".") {
x.splice(0, i);
{ break; }
}
}
The for loop is supposed to delete all of the non-significant 0's at the beginning, but it isn't working and I don't know what the problem could be.
if( x[i] != 0 || ".")
always succeeds because "." is always truthy. Try
if( !(x[i] === '0' || x[i] === '.') )
to check if the character is neither a zero nor decimal point.

How to determine if a character is alphanumeric using comparison operator?

I'm taking freecodecamp challenge "Check for Palindromes". Write a function to check if a given string is palindrome. Here is my code:
function palindrome(str) {
str = str.toLowerCase();
for(var i=0; i<str.length; i++){
if((str[i] > 'z' || str[i] < 'a') && (str[i] < '0' || str[i] > '9')){
str = str.replace(str[i], '');
}
}
for(i=0; i<str.length/2; i++){
if(str[i] != str[str.length-1-i]){
return false;
}
}
return true;
}
But it not worked properly. When I use replace(/[\W_]/g, ''); :
function palindrome(str) {
str = str.toLowerCase().replace(/[\W_]/g, '');
// for(var i=0; i<str.length; i++){
// if((str[i] > 'z' || str[i] < 'a') && (str[i] < '0' || str[i] > '9')){
// str = str.replace(str[i], '');
// }
// }
for(i=0; i<str.length/2; i++){
if(str[i] != str[str.length-1-i]){
return false;
}
}
return true;
}
The function worked properly. Is my first method not correct?
Palindromes ignore capitalization, spaces, punctuation and newlines and so on.
So:
A man. A plan. A canal: Panama!
Is a valid palindrome.
As such, you need to strip all punctuation and whitespace out of your string before trying to evaluate it, such that the string you're actually evaluating is:
amanaplanacanalpanama
Then it's easy to do whatever comparator you'd like on the remaining characters.
I did one of these a while ago and included some tests, it might be worth looking at: https://github.com/pvencill/palindrome

DashInsert Coderbyte Challenge - Why does arr[i]%2===1 work?

The Coderbyte problem is:
Using the JavaScript language, have the function DashInsert(str) insert dashes ('-') between each two odd numbers in str. For example: if str is 454793 the output should be 4547-9-3. Don't count zero as an odd number.
So when the input is 99946, the output should be 9-9-946.
I had this solution, which wouldn't quite work:
function DashInsert(num) {
var arr = num.toString().split('');
var i = 0;
while(i < arr.length-1){
if( arr[i]%2 !==0 && arr[i+1]%2 !==0){
arr.splice(i+1,0,'-');
}
i++
}
return arr.join('');
}
Then I found this similar answer:
function DashInsert(num) {
var arr = num.toString().split('');
var i = 0
while(i < arr.length-1){
if( arr[i]%2===1 && arr[i+1]%2===1){
arr.splice(i+1,0,'-');
}
i++
}
return arr.join(''); }
str = 99946;
alert(DashInsert(str));
Can anyone explain why it should be arr[i]%2===1?
both are correct .
for example , take 9 : 9%2 != 0 and also 9%2 ==1 . think about it , all odd numbers can be split to
2n+1 . a modulo of 2 will always return 1 , which is not 0.
For anyone else who stumbles upon this in a frustrated googling haze...
After the first hyphen is added, it changes the length of the array, so it gets evaluated in the loop to see if the hyphen element !== 0.
Since a '-' !== 0, another hyphen is added.
This is also why you keep blowing your stack since the hyphen keeps changing the length of your array (side note, always cache your length in a variable outside of your for loop and use that in your loop instead).
To fix it, you could add a bunch more &&'s to your if statement i.e.
if(theArray[x] % 2 !== 0 && theArray[x+1]% 2 !== 0 && theArray[x] !== '-' && theArray[x+1] !== '-')
or you could just be more specific and only look for modulo results that evaluate to 1.
I tried this and it works..
HTH..
private static String createDashedString(String str) {
StringBuilder builder = new StringBuilder();
char[] chararray = str.toCharArray();
for (int i=0;i<chararray.length-1;i++) {
int firstInt = Character.getNumericValue(chararray[i]);
int nextInt = Character.getNumericValue(chararray[i+1]);
if ((firstInt%2 !=0) && (nextInt%2 !=0)) {
builder.append(firstInt);
builder.append("-");
}else {
builder.append(firstInt);
}
}
builder.append(chararray[chararray.length-1]);
return builder.toString();
}
public static void main(String args[]) {
String str = "999999";
//01234
System.out.println(createDashedString(str));
}
function DashInsert(str) {
let bil = 0;
while (bil < str.length-1) {
if (Number(str[bil]) % 2 === 1 && Number(str[bil+1]) % 2 === 1) {
str = str.slice(0,bil+1) + "-" + str.slice(bil+1);
bil = bil + 2;
}
else {
bil++;
}
}
return str;
}
console.log(DashInsert("454793"));
let x = '99946'
let z=[]
for(var i = 0;i<x.length;i++){
if(x[i]%2 == 0 && x[i+1]%2 == 1 ){
z+=x[ i ]
}else if (x[i]%2 == 1 && x[i+1]%2 == 0){
z+=x[i]
}else if (x[i]%2 == 1 && x[i+1]%2 == 1){
z+=x[i]+"-"
}else{
z+=x[i]
}
}
console.log(z)

Categories

Resources