You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于TypeScript/JavaScript实现Remote Associates Test题目提取函数

实现远距联想测验的题目生成函数(TypeScript/JavaScript)

需求说明

远距联想测验(Remote Associates Test)是衡量创造力的测试,规则是给出三个词/短语,找出能与每个搭配的共同词。我们需要编写函数,输入三个全大写的知名词/短语(三者含同一共同词),提取每个短语去掉共同词后的部分作为测验题目。

示例:

  • 输入:["BATHROOM", "BATH SALTS", "BLOODBATH"]
  • 输出:["ROOM", "SALTS", "BLOOD"]

解法思路

  1. 提取候选子串:从第一个输入短语中拆分出所有非空子串作为共同词候选(三个短语共享同一共同词,因此第一个短语必然包含它)。
  2. 筛选有效共同词:遍历候选子串,找到同时存在于另外两个短语中的最长子串(优先匹配长串,避免无意义短串干扰)。
  3. 生成题目片段:对每个输入短语移除共同词,清理多余空格后得到结果。

代码实现

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 17:00:18