Find first longest word in a string, excluding symbols - javascript

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...

Related

Double Consonant in 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.

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

Get all substrings of a string in JavaScript

I have the following function to get all of the substrings from a string in JavaScript. I know it's not correct but I feel like I am going about it the right way. Any advice would be great.
var theString = 'somerandomword',
allSubstrings = [];
getAllSubstrings(theString);
function getAllSubstrings(str) {
var start = 1;
for ( var i = 0; i < str.length; i++ ) {
allSubstrings.push( str.substring(start,i) );
}
}
console.log(allSubstrings)
Edit: Apologies if my question is unclear. By substring I mean all combinations of letters from the string (do not have to be actual words) So if the string was 'abc' you could have [a, ab, abc, b, ba, bac etc...] Thank you for all the responses.
You need two nested loop for the sub strings.
function getAllSubstrings(str) {
var i, j, result = [];
for (i = 0; i < str.length; i++) {
for (j = i + 1; j < str.length + 1; j++) {
result.push(str.slice(i, j));
}
}
return result;
}
var theString = 'somerandomword';
console.log(getAllSubstrings(theString));
.as-console-wrapper { max-height: 100% !important; top: 0; }
A modified version of Accepted Answer. In order to give the minimum string length for permutation
function getAllSubstrings(str, size) {
var i, j, result = [];
size = (size || 0);
for (i = 0; i < str.length; i++) {
for (j = str.length; j - i >= size; j--) {
result.push(str.slice(i, j));
}
}
return result;
}
var theString = 'somerandomword';
console.log(getAllSubstrings(theString, 6));
Below is a recursive solution to the problem
let result = [];
function subsetsOfString(str, curr = '', index = 0) {
if (index == str.length) {
result.push(curr);
return result;
}
subsetsOfString(str, curr, index + 1);
subsetsOfString(str, curr + str[index], index + 1);
}
subsetsOfString("somerandomword");
console.log(result);
An answer with the use of substring function.
function getAllSubstrings(str) {
var res = [];
for (let i = 0; i < str.length; i++) {
for (let j = i + 1; j <= str.length; j++) {
res.push(str.substring(i, j));
}
}
return res;
}
var word = "randomword";
console.log(getAllSubstrings(word));
function generateALlSubstrings(N,str){
for(let i=0; i<N; i++){
for(let j=i+1; j<=N; j++){
console.log(str.substring(i, j));
}
}
}
Below is a simple approach to find all substrings
var arr = "abcde";
for(let i=0; i < arr.length; i++){
for(let j=i; j < arr.length; j++){
let bag ="";
for(let k=i; k<j; k++){
bag = bag + arr[k]
}
console.log(bag)
}
}
function getSubstrings(s){
//if string passed is null or undefined or empty string
if(!s) return [];
let substrings = [];
for(let length = 1 ; length <= s.length; length++){
for(let i = 0 ; (i + length) <= s.length ; i++){
substrings.push(s.substr(i, length));
}
}
return substrings;
}

How to combine(iterate through) 2 strings, mixing the letters in each string with different length?

EDIT: the output should be t1h2i3s4oneislong
I am trying to write a function which returns a new word,combining the letters in 2 words which are being passed the function. If word1 is hello and word2 is 12345 it should return h1e2l3l4o5 - mixing all the letters of both words. The problem is that if one word is longer than the other one, I get undefinedundefinedundefined etc.
I thought I could just ask is word1.length
Could someone explain why this doesn't work (I am learning) and how I could make it work? Thank you!!
function creatingWord(one,two){
var string="";
if (one.length==1 &&two.length==1){
string=one+two;
}
else if (one.length==two.length){
for (var i=0; i<one.length;i++){
string+=one[i];
string+=two[i];
}
}
else if (one.length>two.length){
for (var j=0; j<one.length;j++){
string+=one[j];
string+=two[j];
}
}
return string;
}
var result = creatingWord('thisoneislong', '1234');
result;
I think there are two possible answers here, depending on what you want the output to be.
This code gives you the output "t1h2i3s4oneislong" (continuing with the longer word once the other is exhausted):
function creatingWord(one, two){
var output = "";
for (var i = 0; i < Math.max(one.length, two.length); i++) {
if (one.length > i) {
output += one[i];
}
if (two.length > i) {
output += two[i];
}
}
return output;
}
Here's a version that gives the output "t1h2i3s4" (truncates to the smaller word):
function creatingWord(one, two){
var output = "";
for (var i = 0; i < Math.min(one.length, two.length); i++) {
output += one[i] + two[i];
}
return output;
}
EDIT:
Answering a comment below, here's a version that takes a variable number of arguments:
// takes a variable number of words
function creatingWord() {
var output = "";
var words = Array.prototype.slice.call(arguments);
var maxLength = 0;
for (var i = 0; i < words.length; i++) {
var word = words[i];
if (word.length > maxLength) {
maxLength = word.length;
}
}
for (var i = 0; i < maxLength; i++) {
for (var j = 0; j < words.length; j++) {
var word = words[j];
if (word.length > i) {
output += word[i];
}
}
}
return output;
}
Using the length of the first word as the output length, we can use the following to combine any list of words as stated in your question:
var zip = array => array[0].map((a, i) => array.map(a => a[i]));
var words = ["aaaa", "bbb", "cc", "d", "........"],
combined = zip(words.map(w => w.split(""))).map(a => a.join("")).join("");
console.log(combined); // abcd.abc.ab.a.
You can split your words to work with Array functions like reduce(), code looks cleaner :
let a = 'HelloWorld';
let b = '_____';
let combineWords = (a,b) => b.split('') &&
a.split('').reduce((prev, curr, i)=> prev += curr + (b[i] || ''),'');
console.log(combineWords(a, b));
console.log(combineWords(b, a));
Note that combineWords(a, b) will return all the posible combinations attending to a.length

removing characters from a string - javascript algorithm

I'm practicing algorithm problems and am trying to remove given letters from a string in o(n) time.
My attempt below is wrong in a couple of ways:
the last index in the outputString array is "undefined" and I'm not sure why.
my output is the right letter, but it's being returned for the length of the original string.
How can I fix these and why are these errors occurring?
function removeChars(lettersToDelete, string) {
var flags = {}; // a hash of letters to delete.
var outputString = string.split("");
var lettersToDelete = lettersToDelete.split("");
var i, j;
for (i = 0; i < lettersToDelete.length; i++) {
flags[lettersToDelete[i]] = true;
}
console.log(flags);
for (var j = 0; j < string.length; j++) {
if (flags[string[j]]) {
outputString[j++] = string[j];
}
}
console.log(outputString); //[ 'a', 'a', 'a', 'a', undefined ]
return outputString.join(""); // 'aaaa'
}
function removeChars(lettersToDelete, string) {
var flags = {}; // a hash of letters to delete.
var outputString = []; //string.split("");
var lettersToDelete = lettersToDelete.split("");
var i, j;
for (i = 0; i < lettersToDelete.length; i++) {
flags[lettersToDelete[i]] = true;
}
for (var j = 0; j < string.length; j++) {
if (!flags[string[j]]) {
outputString.push( string[j] );
}
}
console.log(outputString);
return outputString.join(""); // 'aaaa'
}
removeChars("itu", "mitul");

Categories

Resources