0

我有这个函数来逐字分隔字符串:

function LetterCount(str) {
var words = str.split(" ");
var letters;
var i;
    for (var i = 0; i < words.length; i++) {
      letters = words[i].split("");
     }
}

这个函数搜索一个字符串并计算每个字母:

function charFreq(s) {
  var i, j;
  var a = new Array();

  for (j = 0; j < s.length; j++) {
    for (i = 0; i < a.length; i++) {
        if (a[i][0] == s[j]) {
         a[i][1]++;
               break;
        }
    }

    if (i == a.length) {

      a[i] = [s[j], 1];
    }
  }

  return a;
}

努力找出一种方法来同步使用这些代码来找出单词数组中哪个单词的重复字母最多。

4

2 回答 2

0

我想这可以满足您的需求:

count = function(ary) { return [].reduce.call(ary, function(o, x) { return o[x] = (o[x]||0) + 1,  o }, {}) }

text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus pretium lobortis arcu, eget rhoncus est commodo sit amet."

letter = "o"

max = text.split(" ").reduce(function(max, word) { return count(word)[letter] > count(max)[letter] ? word : max })

console.log(max) // "commodo"

一些对我有用的代码

// how to write `max(words, key=lambda w: max(Counter(w).values()))` in js

max = function(xs, key) {
    // strictly speaking, there's no need to be schwartzian here, but it's nicer this way
    return xs.map(function(x) {
        return [x, key ? key(x) : x]
    }).reduce(function(m, v) {
        return v[1] > m[1] ? v : m
    })[0];
}

counter = function(xs) {
    return [].reduce.call(xs, function(o, x) {
        return o[x] = (Number(o[x]) || 0) + 1, o
    }, {});
}

values = function(o) {
    return Object.keys(o).map(function(x) { return o[x] })
}

words = "foo bar bbarb foxx abc".split(" ")
word = max(words, function(w) { return max(values(counter(w)))})
// bbarb
于 2013-06-26T21:15:07.780 回答
0
var all_words = str.split(' ');
var all_freq = all_words.map(charFreq);
var max_freq = 0;
var max_word;
for (var i = 0; i < all_freq.length; i++) {
    for (j = 0; j < all_freq[i].length; j++) {
        if (all_freq[i][j][1] > max_freq) {
            max_freq = all_freq[i][j][1];
            max_word = i;
        }
    }
}
console.log("Word with most repeats is "+all_words[max_word]);

演示

于 2013-06-26T22:47:57.443 回答