Double Consonant in JavaScript - javascript

I made a function double consonant(). Here it's all well. But when I try to change little the logic with symbol !== in second function double_consonant_2() my program work wrong and i'm confused.
i want to say that each element from sentence which is not equal with vowel. i mean equal with consonant. Double the words and between them add the letter o.
// double consonant with consonant variable.
function double_consonant(sentence) {
var result = "";
var consonant = "qwrtypsdfghjklzxcvbnm";
for (var i = 0; i < sentence.length; i++) {
for (var j = 0; j < consonant.length; j++) {
if (sentence[i] === consonant[j]) {
result += sentence[i] + "o" + sentence[i];
}
}
}
return result;
}
console.log(double_consonant("good"));
// dobule consonant with vowel variable.
function dobule_consonant_2(sentence) {
var result = "";
var vowel = "aeouiAEOUI";
for (var i = 0; i < sentence.length; i++) {
for (var j = 0; j < vowel.length; j++) {
if (sentence[i] !== vowel[j]) {
result += sentence[i] + "o" + sentence[i];
}
}
}
return result;
}
console.log(dobule_consonant_2("here"));

The problem with your second function is that your if filters each vowels independently.
In your example with here, when reaching the e, the second loop will check if the letter is different from a, which is true, and so add the o between, and then continue to check the other vowels.
What you could do is check for all the vowels and then decide :
var isVowel = false;
for (var j = 0; j < vowel.length; j++) {
if (sentence[i] === vowel[j]) {
isVowel = true;
break;
}
}
if(!isVowel) {
result += sentence[i] + "o" + sentence[i];
}
Note that it's not the fastest way, using indexOf in the first method seems easier.

Related

Code works in console but not in Hackerank

My code works in console but gives the wrong result in hackerank
Problem: Print count of all substrings that are palindromes from a string
function isPalindrome(str) {
var len = str.length;
var mid = Math.floor(len / 2);
for (var i = 0; i < mid; i++) {
if (str[i] !== str[len - 1 - i]) {
return false;
}
}
//Had to use this lengthy function because in
//str == str.split('').reverse().join('');
//I was getting error that split is not a function
return true;
}
function scatterPalindrome(str) {
var result = [],
c = 0;
for (let i = 0; i < str.length; i++) {
for (let j = i + 1; j < str.length + 1; j++) {
result.push(str.slice(i, j));
}
}
for (let i = 0; i < result.length; i++) {
let k = result[i];
if (isPalindrome(k))
c++;
}
return c; // the answer was always 1
}
console.log(scatterPalindrome("abc"));
input: "abc"
expected output: 3
actual output:1
As I can't comment, so answering here, I will say you should check if they have mentioned there are many test cases, and in each test case you have to do the query then this is reasonable that your output and their output will not match
take no.of testcases input
while(testcases counter doesn't reach 0 )
take string input
call your function for answer for input and print
decrement testcases counter

How do I log some tests for javascript?

I was hoping to get your assistance with this "Is Unique" algorithm in Javascript.
var allUniqueChars = function(string) {
// O(n^2) approach, no additional data structures used
// for each character, check remaining characters for duplicates
for (var i = 0; i < string.length; i++) {
console.log(i);
for (var j = i + 1; j < string.length; j++) {
if (string[i] === string[j]) {
return false; // if match, return false
}
}
}
return true; // if no match, return true
};
/* TESTS */
// log some tests here
allUniqueChars('er412344');
I am looking to log some tests, to see it display in the console. How do I call the function with unique strings to test it?
John
You can always create an Array with your strings and test like:
var allUniqueChars = function(string) {
// O(n^2) approach, no additional data structures used
// for each character, check remaining characters for duplicates
for (var i = 0; i < string.length; i++) {
for (var j = i + 1; j < string.length; j++) {
if (string[i] === string[j]) {
return false; // if match, return false
}
}
}
return true; // if no match, return true
};
/* TESTS */
// log some tests here
[
'er412344',
'ghtu',
'1234',
'abba'
].forEach(v => console.log(allUniqueChars(v)));
MDN Array.prototype.foreach
Run the snippet multiple times to generate unique random strings and display results:
var allUniqueChars = function(string) {
for (var i = 0; i < string.length; i++)
for (var j = i + 1; j < string.length; j++)
if (string[i] === string[j])
return false;
return true;
};
var getUniqueStr = () => Math.random().toString(36).substr(2, 9);
let myStringArray = [];
for(var i =0 ; i<8; i++) // 8 test cases in this example
myStringArray.push(getUniqueStr());
console.log(myStringArray.map(e=>e + " : " + allUniqueChars(e)));
You can use this function found here to generate random strings for testing (not mine!):
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < 5; i++)
text += possible.charAt(Math.floor(Math.random() * possible.length));

How do I skip a comparison between two of the same arrays index?

I'm doing this really simple codewars kata below is the problem:
An isogram is a word that has no repeating letters, consecutive or
non-consecutive. Implement a function that determines whether a string
that contains only letters is an isogram. Assume the empty string is
an isogram. Ignore letter case.
function isIsogram(str){
var letter = str.toLowerCase().split("");
for(var i = 0; i < letter.length; i++) {
if(letter.indexOf(letter[i].toLowerCase()) > -1){
return false;
}
}
return true;
}
My solution always returns false because my array within indexOf compares every letter within my string. The solution is supposed to compare the array with itself and return true if there are no repeating letters. But unfortunately for me when comparing the array with itself it is going to compare each letter within the array on itself so basically even if there is only one letter of that char in the array, because again it is comparing with itself, it is going to return a false statement.
This problem is killing me.
Check if the Array#lastIndexOf (it searches from the end) is the same as current index. If not, it's not unique:
function isIsogram(str){
var letter = str.toLowerCase().split("");
for(var i = 0; i < letter.length; i++) {
if(letter.lastIndexOf(letter[i]) !== i){
return false;
}
}
return true;
}
console.log(isIsogram('subdermatoglyphic'));
console.log(isIsogram('rare'));
A better solution is to compare the number of unique characters using Set vs. the number of characters in the original string:
const isIsogram = (str) => new Set(str.toLowerCase()).size === str.length;
console.log(isIsogram('subdermatoglyphic'));
console.log(isIsogram('rare'));
More simple:
check = str => new Set( str.toLowerCase() ).size === str.length;
Or if you wanna fix your code, use two loops:
for(var i = 0; i < letter.length; i++) {
for(var j = i+1; j < letter.length; j++){
if(letter[i] === letter[j]) return false;
}
}
function isIsogram(str){
var letter = str.toLowerCase().split("");
for(var i = 0; i < letter.length; i++) {
for (var y = i + 1; y < letter.length; y++) {
if (letter[i] === letter[y])
return false;
}
}
return true;
}
extra efficiency by not duplicating comparisons
Here's a more efficient solution using the approach proposed by #rafael: reorder the word alphabetically and incrementally compare each letter to the next. If there's a match, immediately return false.
function isIsogram(word) {
word = word.split('').sort().join('').toLowerCase();
for (var i = 0; i < word.length; i++) {
if (word[i] === word[i+1]) {
return false;
}
}
return true;
}

Why doesn't .toUpperCase() capitalize str[i]?

Doing a CoderByte challenge:
Using the JavaScript language, 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.
my solution:
function LetterChanges(str) {
var alphabet = "abcdefghijklmnopqrstuvwxyza",
vowels = "aiueo",
newstr = '';
for (var i = 0; i < str.length; i++) {
if (alphabet.indexOf(str[i]) != -1) {
newstr += alphabet[alphabet.indexOf(str[i]) + 1];
} else {
newstr += str[i];
}
}
for (var i = 0; i < vowels.length; i++) {
for (var j = 0; j < newstr.length; j++) {
//toUppercase the vowel in the newstring once found
if (newstr[j] == vowels[i]) {
newstr[j] = newstr[j].toUpperCase();
}
}
}
return newstr;
}
show(LetterChanges("fun times"));
show(LetterChanges("hello*3"));
The toUpperCase() does not capitalize the vowel I want. It seems correct though. I've even tried something like this:
if (newstr[j] == vowels[i]) {
var toCap = newstr[j].toString();
newstr[j] = toCap.toUpperCase();
}
If you think of a better solution, then please answer the toUpperCase() part and then recommend another solution.
Strings in Javascript are primitive types, not objects.
When you set a property in a primitive type (eg, str[i] = 'a'), Javascript creates a new boxed object for that value, mutates it, then throws it away.
For more details, see the spec.
Instead, you should assemble the new string in a mutable array, then call .join('') to convert it to a string.
You can create another string to build the return string, see bellow a fix in your code
function LetterChanges(str) {
var alphabet = "abcdefghijklmnopqrstuvwxyza",
vowels = "aiueo",
newstr = '',
returnStr = ''; //added to next step
for (var i = 0; i < str.length; i++) {
if (alphabet.indexOf(str[i]) != -1) {
newstr += alphabet[alphabet.indexOf(str[i]) + 1];
} else {
newstr += str[i];
}
}
for (var i = 0; i < vowels.length; i++) {
for (var j = 0; j < newstr.length; j++) {
//toUppercase the vowel in the newstring once found
if (newstr[j] == vowels[i]) {
returnStr += newstr[j].toUpperCase();
}else{
returnStr += newstr[j];
}
}
}
return returnStr ;
}
You can capitalize the vowels via replace and an uppercasing function:
newstr = newstr.replace(
/[aeiou]/g, // replace all vowels
function(letter) { // called for each match
return letter.toUpperCase();
}
);
Example: http://codepen.io/paulroub/pen/tvhcF
The contents of a string cannot be changed, I.E. they are immutable. Create a new string instead of trying to edit one in-place.
You can make your life easy with the following code
function LetterChanges(str) {
return str.replace(/[a-zA-Z]/g,function(x) {
return String.fromCharCode(x.charCodeAt(0)+1); }).replace(/[aeiou]/g,function(y) {
return y.toUpperCase();
});
}

Find first longest word in a string, excluding symbols

function longestWord(string) {
var str = string.split(" ");
var longest = 0;
var word = null;
for (var i = 0; i < str.length; i++) {
var checkedLetters = "";
for (var j = 0; j < str[j].length; j++) {
if (j == /[^a-zA-Z]/) {
checkedLetters += j;
}
if (longest < checkedLetters.length) {
longest = checkedLetters.length;
word = checkedLetters;
}
}
}
return word;
}
Is there something wrong with my use of regex? When I call longestWord("Hello, I am here") I want it to return "Hello" (without the comma), but it returns null.
Just wrote this little snippet, might help you out:
function longestWord(string){
return string.match(/[a-zA-Z]+/g)
.reduce(function(a,b){
return a.length>=b.length?a:b;
})
}
/[a-zA-Z]+/g matches all words in the string, and returns an array of them. Your test string above ("Hello, I am here") will become ["Hello","I","am","here"] when this RegEx is run on it.
Once I have this array, it is simply a matter of looping through it to find the longest word. I accomplished this by using .reduce.
There are some mistake in your code:
for (var j = 0; j < str[j].length; j++) {
should be
for (var j = 0; j < str[i].length; j++) {
And
if (j == /[^a-zA-Z]/) {
Should be:
if (/[a-zA-Z]/.test(str[i][j])) {
Your final code should be:
function longestWord(string) {
var str = string.split(" ");
var longest = 0;
var word = null;
for (var i = 0; i < str.length; i++) {
var checkedLetters = "";
for (var j = 0; j < str[i].length; j++) {
if (/[a-zA-Z]/.test(str[i][j])) {
checkedLetters += str[i][j];
}
}
if (longest < checkedLetters.length) {
longest = checkedLetters.length;
word = checkedLetters;
}
}
return word;
}
Check demo
The big (non-typo) problem with how you’re using regular expressions is that the method is .test; == will test whether the string is equal to the string representation of the regular expression.
Just use .match and a little bit of sort magic!
function longestWord(string){
var words = string.match(/\w+/g);
words.sort(function(a, b) { return b.length - a.length; });
// Firefox 22.0 promotion:
// words.sort((a, b) => a.length - b.length);
return words[0];
}
You don't need to use Regex, you can just use .length to search for the longest string.
i.e.
function longestWord(string) {
var str = string.replace(/[\.,-\/#!$%\^&\*;:{}=\-_`~()]/g,"").split(" ");
longest = str[0].length;
longestWord = str[0];
for (var i = 1; i < str.length; i++) {
if (longest < str[i].length) {
longest = str[i].length;
longestWord= str[i];
}
}
return longestWord;
}
EDIT: You do have to use some Regex...

Categories

Resources