3

如果用户输入 5 个数字,可以说4, 4, 7, 7, 4...... 4 发生了 3 次(最多)次。所以输出应该是4

如何使用 JavaScript 做到这一点?非常感谢您的帮助。谢谢!

到目前为止,我已经尝试过了。行得通,但是太长了,找个短小简单的办法。

PS这不是我的作业!

    var n = parseInt(prompt("How many numbers do you like to enter?", ""));
    var num = new Array();

    for (i = 1; i <= n; i++) {
        num[i] = parseInt(prompt("Enter a number", ""));
        document.write("Entered numbers are: " + num[i] + "<br/>");
    }

    var total = new Array();
    for (i = 1; i <= n; i++) {
        var count = 1;
        for (j = i + 1; j <= n; j++) {
            if (num[i] == num[j]) {
                count++;
            }
            total[i] = count;
        }
    }

    var most = 0;
    for (i = 0; i < n; i++) {
        if (most < total[i]) {
            most = total[i];
        }
        var val = i;
    }
    document.write("<br/>" + num[val] + " is occurred " + most + " times");
4

5 回答 5

4

使用数组 文字创建一个a包含大量数字的数组:

var a = [1, 2, 3, 4, 4, 5, 1, 2, 3, 1, 2, 1, 1];

o使用对象文字创建一个普通对象。

var o = {},          /* Creates a new object */
    i = 0,           /* Declare variable i, initialise value at 0*/
    m = {m:0,t:null},
    t,               /* Declare variable t */
    len = a.length;  /* Declare variable len, set value to the array's length */

a使用for(;;)-loop循环遍历数组并递增计数器。计数器存储在 object 上的 hashmap 中o
(o[a[i]] || 0)键的第一次出现需要:当它没有找到时,0使用该值而不是undefined. 另见短路评估:逻辑或

for ( ; i < len ; i++ ) {
    o[ a[i] ] = ( o[ a[i] ] || 0 ) + 1;
}

然后你有一个o看起来像这样的对象:

o = {
    "1": 5,
    "2": 3,
    "3": 2,
    "4": 2,
    "5": 1
}

o然后使用for(.. in ..)-loop循环并找到出现的最大次数。
在循环的底部,使用了条件三元.. ? .. : ..运算符:

for ( i in o ) {
    t = { 
        m: o[i], 
        i: i 
    };
    m = m.m < t.m ? t : m;
}

此循环后m等于:

m = { 
    i: "1", 
    m: "5"
};

并且可以使用以下方法捕获最大值:

o[m];

女巫给你:

5

演示

http://jsbin.com/utiqey/

var a = [1, 2, 3, 4, 4, 5, 1, 2, 3, 1, 2, 1, 1]; 

var o = {}, 
    i = 0, 
    m = {m:0,t:null}, 
    t,
    len = a.length; 

for ( ; i < len ; i++ ) { 
    o[ a[i] ] = ( o[ a[i] ] || 0 ) + 1; 
} 


for ( i in o ) { 
    t = { 
        m: o[i], 
        i: i 
    };
    m = m.m < t.m ? t : m;
} 

alert(m.i + " is the highest presented " + m.m + " times"); 
于 2012-04-08T09:21:37.430 回答
3

无需进行两次通过,以下会累积最大值:

var g = [4, 4, 7, 7, 4, 5, 6, 7, 8, 6, 5, 2, 2, 2, 3, 4, 5]; //your array

for (var t = {}, maxn = g[0], max = 0, gi, i = g.length; i--;) {
  if (max < (t[gi = g[i]] = (t[gi] || 0) + 1)) {
    max = t[gi];
    maxn = gi;
  }
}

document.write ('The number ' + maxn + ' occurs ' + max + 'times');

编辑

一个很好的解决方案,但 OP 可能需要一些解释和一些更合适的变量名。集合中最常出现的值是mode

// Use any member of g to seed the mode
var mode = g[0];
// The number of times the current mode has occurred
var count = 0;
// Results object
var t = {};
var i = g.length;
var gi;

// Loop over all the members
while (i--) {

  // Get the value at i
  gi = g[i];

  // Keep track of how many times the value has been found  
  // If the number hasn't occured before, add it with count 1
  // Otherwise, add 1 to its count
  t[gi] = (t[gi] || 0) + 1;

  // Set the mode to the current value if it has occurred 
  // more often than the current mode
  if (count < t[gi]) {
    count = t[gi];
    mode = gi;
  }
}

alert('The mode is ' + mode + ' and occurs ' + count + ' times.');

如果有多个模式,则从数组末尾开始计数第一个找到的模式获胜。

于 2012-04-08T09:54:50.493 回答
2

http://jsbin.com/ageyol/3/edit

var g = [4, 4, 7, 7, 4, 5, 6, 7, 8, 6, 5, 2, 2, 2, 3, 4, 5]; //your array
var t = {}; // object which contain the numbers as properties.

for (var i = 0; i < g.length; i++)
{
    if (!t[g[i]]) t[g[i]] = 0; //if the property doesnt exists , so create one with counter 0.
    t[g[i]]++; // also - increase the property VALUE.
}

var max = 0;

for (i in t)
{
    if (t[i] > max) max = t[i]; //check if property value is larger then the current MAX val.
    document.write(i + "  " + t[i] + "<br/>");
}
document.write(t[max]);

ps 如果超过最大值 - 所以你应该迭代。

于 2012-04-08T08:57:43.677 回答
2

对数组进行排序,然后相同的值彼此相邻,这样您就可以遍历它们并查找最长的连续:

arr.sort();

var maxValue, maxCount = 0, cnt = 1, last = arr[0];
for (var i = 1; i <= arr.length; i++) {
  if (i = arr.length || arr[i] != last) {
    if (cnt > maxCount) {
      maxCount = cnt;
      maxValue = last;
    }
    cnt = 1;
    if (i < arr.length) last = arr[i];
  } else {
    cnt++;
  }
}
于 2012-04-08T11:08:08.247 回答
0

只是为了摆脱其他答案之一,一旦您形成了值对象,您就可以将值推送到数组中并用于Math.max获取上限。通常Math.max接受一系列数字,但如果你使用.apply它也可以接受一个array. 对于Math.min.

var o = { 1: 5, 2: 3, 3: 2, 4: 2, 5: 1 };

var out = [];
for (var k in o) {
  out.push(o[k]);
}

var upperbound = Math.max.apply(null, out); // 5
于 2013-12-07T15:15:12.480 回答