Javascript功能。缺什么?

时间:2017-05-24 22:16:11

标签: javascript arrays function

编写程序以查找数组中最常用项的计数。假设输入是整数数组。

示例:

输入数组:[3, -1, -1, -1, 2, 3, -1, 3, -1, 2, 4, 9, 3]

Ouptut:5

示例数组中最常见的数字是-1。它在输入数组中出现5次。

这是我的代码:

function mostFrequentItemCount(collection) {

  var copy = collection.slice(0);

  for (var i = 0; i < collection.length; i++) {
    var output = 0;
    for (var x = 0; x < copy.length; x++) {
      if (collection[i] == copy[x]) {
        output++; 
      }
    }
  }
  return output; 
}

似乎只计算数组中第一个数字的重现次数,而不是最多出现的数字。我无法弄清楚如何计算最常出现的一个。

5 个答案:

答案 0 :(得分:1)

如果我没有错过任何内容,如果你真的想找到数组中最频繁项目的数量,我猜一种方法就是这个:

&#13;
&#13;
function existsInCollection(item, collection) {
    for(var i = 0; i < collection.length; i++) {
        if(collection[i] === item) {
            return true;
        }
    }
    
    return false;
}

function mostFrequentItemCount(collection) {
        var most_frequent_count = 0;
        var item_count = 0;
        var already_checked = [];
        
        for(var i = 0; i < collection.length; i++) {
            // if the item was already checked, passes to the next
            if(existsInCollection(collection[i], already_checked)) {
                continue;
            } else {
                // if it doesn't, adds to the already_checked list
                already_checked.push(collection[i]);
            }
            
            for(var j = 0; j < collection.length; j++)
                if(collection[j] === collection[i])
                    item_count++;

            if(item_count > most_frequent_count)
                most_frequent_count = item_count;

            item_count = 0;

        }

        return most_frequent_count;
    }
    
    var items = [3, -1, -1, -1, 2, 3, -1, 3, -1, 2, 4, 9, 3];
    
    alert(mostFrequentItemCount(items));
&#13;
&#13;
&#13;

这里发生的是:

在每个项目上(&#39; i&#39;循环),它将在所有项目中运行另一个循环(&#39; j&#39;),并计算等于[i]项目的数量。在第二个循环之后,将验证该项目计数是否大于我们已经拥有的most_frequent_count,如果是,则更新它。 因为我们总是使用相同的变量&#39; item_count&#39;检查每个数字,在验证每个数字后,我们将其重置为0。

这可能不是最好的答案,但这是我此刻发生的事情。

编辑: 我添加了一个函数来检查一个项目是否已存在于列表中,以避免循环再次检查相同的项目。

答案 1 :(得分:0)

问题是你在每次循环迭代时都覆盖output变量,因此在for循环结束后,output变量会保留输入数组的最后一个元素的出现。

您应该使用var best_element = collection[0]var best_element_count = -1等变量(如此初始化)。在每个内部循环之后,检查algo是否找到了更好的解决方案(best_element_count < output)并更新best_element

编辑:在@Alnitak注释后,您还应该在每次内循环迭代后重置output变量。

答案 2 :(得分:0)

首先,您需要构建一个包含元素和出现次数的集合(或对象)。其次,您需要迭代结果以找到具有最高值的密钥。

JSFiddle

&#13;
&#13;
function mostFrequentItemCount(collection) {
  var output = {};
  for (var i = 0; i < collection.length; i++) {
    var item = collection[i];
    if (!(item in output))
      output[item] = 0;
    output[item]++;
  }
  var result = [0, 5e-324];
  for (var item in output) {
    if (output[item] > result[1]) {
      result[0] = parseFloat(item);
      result[1] = output[item];
    }
  }
  return result;
}
var input = [3, -1, -1, -1, 2, 3, -1, 3, -1, 2, 4, 9, 3];
var result = mostFrequentItemCount(input);
console.log(result);
&#13;
&#13;
&#13;

上面的代码段只是创建一个新对象(output),其中包含数组中每个唯一元素的属性。结果就像是。

2:2
3:4
4:1
9:1
-1:5

所以现在我们有一个对象,其中包含出现的数字和值的属性。接下来,我们将对输出for(var item in output)中的每个属性进行交互,并确定哪个值最大。

现在返回一个数组,其索引0的值为数字,索引1的值为元素的数量。

答案 3 :(得分:0)

检查此解决方案。

&#13;
&#13;
var store = [3, -1, -1, -1, 2, 3, -1, 3, -1, 2, 4, 9, 3];
var frequency = {};  // array of frequency.
var max = 0;  // holds the max frequency.
var result;   // holds the max frequency element.
for(var v in store) {
        frequency[store[v]]=(frequency[store[v]] || 0)+1; // increment frequency.
        if(frequency[store[v]] > max) { // is this frequency > max so far ?
                max = frequency[store[v]];  // update max.
                result = store[v];          // update result.
        }
}
alert(max);
&#13;
&#13;
&#13;

答案 4 :(得分:-1)

因此,对方法的此更新将返回一个对象,其中包含每个键以及该数组中该键的计数。如何格式化输出以说明哪个键具有哪些数量取决于您。

编辑:已更新,以包含问题的完整解决方案。

function mostFrequentItemCount(collection) {
  var copy = collection.slice(0);
  var results = {};
  for (var i = 0; i < collection.length; i++) {
    var count = 0;
    for (var x = 0; x < copy.length; x++) {
      if (collection[i] == copy[x]) {
        count++; 
      }
    }
    results[collection[i]] = count;
  }
  
  return results; 
}

var inputArray = [3, -1, -1, -1, 2, 3, -1, 3, -1, 2, 4, 9, 3];
var occurances = mostFrequentItemCount(inputArray);
var keyWithHighestOccurance = Object.keys(occurances).reduce(function(a, b){ return occurances[a] > occurances[b] ? a : b });
var highestOccurance = occurances[keyWithHighestOccurance];
console.log("Most frequent number in example array is " + keyWithHighestOccurance + ". It occurs " + highestOccurance + " times in the input array.");