Last active
February 19, 2024 10:36
-
-
Save tobiamos/5cb0fa8316ec98e2e5b47b462d2844e5 to your computer and use it in GitHub Desktop.
Calculates the maximum product of the lengths of two words in an array,
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Converts a word into a bitmask. | |
* @param {string} word - The word to convert. | |
* @returns {number} The bitmask representing the word. | |
*/ | |
const wordToBitmask = (word) => { | |
let bitmask = 0; | |
for (let char of word) { | |
bitmask |= 1 << (char.charCodeAt(0) - 'a'.charCodeAt(0)); | |
} | |
return bitmask; | |
} | |
/** | |
* Calculates the maximum product of the lengths of two words in an array, | |
* where the words do not share any common letters. | |
* | |
* @param {string[]} words - An array of words. | |
* @returns {number} The maximum product of the lengths of two words. | |
*/ | |
const wordLengthProduct = (words) => { | |
// Create an array to hold the bitmask representation of each word | |
let bitmasks = words.map(word => wordToBitmask(word)); | |
let maxProduct = 0; | |
for (let i = 0; i < words.length; i++) { | |
for (let j = i + 1; j < words.length; j++) { | |
// If the words do not share common letters | |
if ((bitmasks[i] & bitmasks[j]) === 0) { | |
// Calculate the product of their lengths | |
let product = words[i].length * words[j].length; | |
// Update maxProduct if this product is greater | |
maxProduct = Math.max(maxProduct, product); | |
} | |
} | |
} | |
return maxProduct; | |
} | |
// Example usage | |
console.log(wordLengthProduct(["fish","fear","boo","egg","cake","abcdef"])); // Output: 16 | |
console.log(wordLengthProduct(["a","aa","aaa","aaaa"])); // Output: 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment