2013-06-26 44 views
0

我有了這個功能,通過字單獨的字符串中的一個字母的最occurances查找字符串字的Javascript:</p> <pre><code>function LetterCount(str) { var words = str.split(" "); var letters; var i; for (var i = 0; i < words.length; i++) { letters = words[i].split(""); } } </code></pre> <p>這個功能來搜索字符串並計算每個字母:與

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; 
} 

努力找出一種方法來同步使用這些代碼,以找出單詞數組中哪個單詞有最重複的字母。

+1

什麼'j'在'LetterCount '功能? – Barmar

+0

只是一個佔位符變量,用於對輸入的字符串進行排序 – JSNewb

+0

但是在執行'letters [j] = ...'之前,您從未設置過它。 – Barmar

回答

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]); 

DEMO

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 
+0

找到最多使用「o」的單詞,而不是通常重複最多的字母(例如「mississippi」)。 – Barmar

+0

@Barmar:我給他們的想法,而不是codez。 – georg

+0

我太簡陋了,甚至不理解所有的簡寫= [ – JSNewb

相關問題