基于TypeScript/JavaScript实现Remote Associates Test题目提取函数
实现远距联想测验的题目生成函数(TypeScript/JavaScript)
需求说明
远距联想测验(Remote Associates Test)是衡量创造力的测试,规则是给出三个词/短语,找出能与每个搭配的共同词。我们需要编写函数,输入三个全大写的知名词/短语(三者含同一共同词),提取每个短语去掉共同词后的部分作为测验题目。
示例:
- 输入:
["BATHROOM", "BATH SALTS", "BLOODBATH"] - 输出:
["ROOM", "SALTS", "BLOOD"]
解法思路
- 提取候选子串:从第一个输入短语中拆分出所有非空子串作为共同词候选(三个短语共享同一共同词,因此第一个短语必然包含它)。
- 筛选有效共同词:遍历候选子串,找到同时存在于另外两个短语中的最长子串(优先匹配长串,避免无意义短串干扰)。
- 生成题目片段:对每个输入短语移除共同词,清理多余空格后得到结果。
代码实现
TypeScript版本
function generateRATQuestions(phrases: string[]): string[] { const firstPhrase = phrases[0]; const candidates = new Set<string>(); // 生成第一个短语的所有非空子串候选 for (let i = 0; i < firstPhrase.length; i++) { for (let j = i + 1; j <= firstPhrase.length; j++) { candidates.add(firstPhrase.slice(i, j)); } } // 按长度倒序排列,优先匹配最长共同词 const sortedCandidates = Array.from(candidates).sort((a, b) => b.length - a.length); // 找到三个短语共有的词 let commonWord = ''; for (const candidate of sortedCandidates) { if (phrases.every(phrase => phrase.includes(candidate))) { commonWord = candidate; break; } } // 移除共同词并清理空格 return phrases.map(phrase => phrase.replace(commonWord, '').trim()); } // 测试示例 console.log(generateRATQuestions(["BATHROOM", "BATH SALTS", "BLOODBATH"])); // 输出: ["ROOM", "SALTS", "BLOOD"]
JavaScript版本
function generateRATQuestions(phrases) { const firstPhrase = phrases[0]; const candidates = new Set(); // 生成第一个短语的所有非空子串候选 for (let i = 0; i < firstPhrase.length; i++) { for (let j = i + 1; j <= firstPhrase.length; j++) { candidates.add(firstPhrase.slice(i, j)); } } // 按长度倒序排列,优先匹配最长共同词 const sortedCandidates = Array.from(candidates).sort((a, b) => b.length - a.length); // 找到三个短语共有的词 let commonWord = ''; for (const candidate of sortedCandidates) { if (phrases.every(phrase => phrase.includes(candidate))) { commonWord = candidate; break; } } // 移除共同词并清理空格 return phrases.map(phrase => phrase.replace(commonWord, '').trim()); } // 测试示例 console.log(generateRATQuestions(["BATHROOM", "BATH SALTS", "BLOODBATH"])); // 输出: ["ROOM", "SALTS", "BLOOD"]
代码说明
- 候选去重:用Set存储子串,避免重复候选值。
- 最长匹配优先:按子串长度倒序遍历,确保找到的是语义完整的共同词,而非单个字母这类无意义匹配。
- 空格清理:
trim()处理移除共同词后残留的多余空格,保证输出格式整洁。
内容的提问来源于stack exchange,提问作者Sakeerin
相关产品推荐
相关产品推荐

