如何按指定字母数组中的唯一字母数量排序JS单词数组
需求实现思路与代码
实现思路
- 排序逻辑:针对每个单词,计算它包含的、当前
letters数组中的唯一字母数量,按该数量降序排序——数量越多的单词越靠前。每次处理前都要重新排序,因为letters数组会动态变化,单词的有效字母数也会随之改变。 - 字母移除与重置:每次取排序后的首个单词,提取它在当前
letters里的所有唯一字母,从letters中移除这些字母;当letters为空时,立即将其重置为初始的「A-Y不含X」数组,重复上述流程。
具体代码实现
首先定义初始数据与核心工具函数,再实现完整处理逻辑:
1. 初始化数据
// 生成初始字母数组:A-Y(不含X) const initialLetters = Array.from({length: 24}, (_, i) => { const charCode = 65 + i; // 跳过X的ASCII码88,后续字母顺位+1 return charCode >= 88 ? String.fromCharCode(charCode + 1) : String.fromCharCode(charCode); }); let currentLetters = [...initialLetters]; // 给定的单词数组 const wordList = [ "aa", "aah", "aahed", "aahing", "aahs", "aal", "aalii", "aaliis", "aals", "aardvark", "aardvarks", "aardwolf", "aardwolves", "aargh", "aarrgh", "aarrghh", "aarti", "aartis", "aas", "aasvogel", "aasvogels", ];
2. 核心工具函数
// 计算单个单词在当前letters数组中的唯一字母数量 function getUniqueLetterCount(word, letters) { const validLetters = new Set(letters); const uniqueValidChars = new Set(); // 统一转大写,避免大小写不匹配 for (const char of word.toUpperCase()) { if (validLetters.has(char)) { uniqueValidChars.add(char); } } return uniqueValidChars.size; } // 根据当前letters数组对wordList进行排序 function sortWordList(wordList, letters) { // 拷贝原数组避免修改原数据 return [...wordList].sort((wordA, wordB) => { const countA = getUniqueLetterCount(wordA, letters); const countB = getUniqueLetterCount(wordB, letters); // 降序排序,有效字母数多的在前 return countB - countA; }); }
3. 主处理逻辑
function processLetters() { // 这里可以根据需求添加终止条件,比如循环指定次数 let loopCount = 0; const maxLoops = 10; while (loopCount < maxLoops) { const sortedWords = sortWordList(wordList, currentLetters); const topWord = sortedWords[0]; console.log(`当前选中单词: ${topWord}`); // 提取该单词中需要移除的有效字母 const validLetters = new Set(currentLetters); const lettersToRemove = new Set(); for (const char of topWord.toUpperCase()) { if (validLetters.has(char)) { lettersToRemove.add(char); } } // 移除字母 currentLetters = currentLetters.filter(letter => !lettersToRemove.has(letter)); console.log(`移除后剩余字母: ${currentLetters.join(', ')}`); // 重置判断 if (currentLetters.length === 0) { console.log('字母数组已空,重置为初始状态'); currentLetters = [...initialLetters]; console.log(`重置后字母: ${currentLetters.join(', ')}`); } loopCount++; } } // 启动处理 processLetters();
代码说明
- 大小写兼容:所有字符统一转大写判断,避免单词小写、字母数组大写导致的匹配失败。
- 效率优化:使用
Set存储有效字母,将查找操作的时间复杂度从O(n)降到O(1)。 - 无副作用处理:排序时拷贝原数组,避免修改原始的
wordList;重置时拷贝初始数组,防止引用指向同一内存地址。
内容的提问来源于stack exchange,提问作者The Gaming Weirdo
相关产品推荐
相关产品推荐

