【问题标题】:How to get the most frequent item (number or string) in an array?如何获取数组中出现频率最高的项目(数字或字符串)?
【发布时间】:2020-08-11 01:24:47
【问题描述】:

我正在尝试获取由 Dialogflow 聊天机器人使用完整代码构建的 javascript 数组中最常见的项目。 但是,如果我可以显示数组,我尝试的函数似乎不能很好地找到最常见的项目:

const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
const {Card, Suggestion} = require('dialogflow-fulfillment');
var answers = [];

process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements

exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
  const agent = new WebhookClient({ request, response });
  console.log('Dialogflow Request headers: ' + JSON.stringify(request.headers));
  console.log('Dialogflow Request body: ' + JSON.stringify(request.body));

  function welcome(agent) {
    agent.add(`Welcome to my agent!`);
  }

  function fallback(agent) {
    agent.add(`I didn't understand FULLFILMENT`);
    agent.add(`I'm sorry, can you try again? FULLFILMENT`);
  }

  function rhymingWordHandler(agent){
    agent.add('Intent called');
  }

  function answer1Handler(agent){
    agent.add('Intent answer1 called');
    const answer = agent.parameters.number;
    answers.push(answer);
  }

  function answer2Handler(agent){
    agent.add('Intent answer2 called');
    const answer = agent.parameters.number;
    answers.push(answer);
  }

  function answer3Handler(agent){
    agent.add('Intent answer3 called');
    const answer = agent.parameters.number;
    answers.push(answer);
    agent.add('Here is the mode');
    const mfi = mode(answers);
    agent.add(mfi.toString());
  }

  function mode(arr1){
    var mf = 1; //default maximum frequency
    var m = 0;  //counter
    var item;  //to store item with maximum frequency
    for (var i=0; i<arr1.length; i++)    //select element (current element)
    {
            for (var j=i; j<arr1.length; j++)   //loop through next elements in array to compare calculate frequency of current element
            {
                    if (arr1[i] == arr1[j])    //see if element occurs again in the array
                     m++;   //increment counter if it does
                    if (mf<m)   //compare current items frequency with maximum frequency
                    {
                      mf=m;      //if m>mf store m in mf for upcoming elements
                      item = arr1[i];   // store the current element.
                    }
            }
            m=0;   // make counter 0 for next element.
    }
    return item;
  }

  // Run the proper function handler based on the matched Dialogflow intent name
  let intentMap = new Map();
  intentMap.set('Default Fallback Intent', fallback);
  intentMap.set('RhymingWord', rhymingWordHandler);
  intentMap.set('answer1', answer1Handler);
  intentMap.set('answer2', answer2Handler);
  intentMap.set('answer3', answer3Handler);

  agent.handleRequest(intentMap);
});

我的输入是 1,2 和 1。所以数组是 [1,2,1],它应该输出 1。我猜我的模式函数不适用于数字?我怎样才能让它多才多艺?

我关注了this answer,应该没问题的。

【问题讨论】:

  • 使用全局 answers 数组会很糟糕;它将在您的机器人的所有客户端之间共享。除非那是你想做的,当然……
  • @AKX Ho,没有。当然不是,我希望每个客户都特定于每个客户

标签: javascript arrays frequency


【解决方案1】:

这样的东西应该适用于您的 mode 函数:

function mode(arr) {
  const counts = {};
  let maxCount = 0;
  let maxKey;
  // Count how many times each object (or really its string representation)
  // appears, and keep track of the highest count we've seen.
  for (let i = 0; i < arr.length; i++) {
    const key = arr[i];
    const count = (counts[key] = (counts[key] || 0) + 1);
    if (count > maxCount) {
      maxCount = count;
      maxKey = key;
    }
  }
  // Return (one of) the highest keys we've seen, or undefined.
  return maxKey;
}

【讨论】:

    猜你喜欢
    • 2021-10-10
    • 1970-01-01
    • 2023-04-04
    • 2011-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-20
    相关资源
    最近更新 更多