2014-08-28 5 views
0
$.each(string.split(''), function(){ 
    if(!check[this]){ 
     count++; 
     check[this]=true; 
    } 
}) 

Pour mes fonctions ci-dessus, il est capable de comptabiliser le nombre de caractères uniques. Par exemple, pour 1113, le résultat serait 2, comme il n'y a que 1 et 3. Pour 1134, le résultat serait 3, comme il y a 1,3 et 4.Comptage des occurrences de nombres dans une chaîne en JavaScript

Mais je veux par exemple 1133 et 1113, il y a du même 2 nombre unique qui est 1 et 3. Comment compter l'occurrence maximum de 1 et 3? Pour 1133 ce serait 2, alors que pour 1113 il serait 3 puisque 1 apparait 3 fois.

J'ai juste besoin de compter l'occurrence du nombre le plus survenu dans la chaîne (nombre seulement).

Répondre

0

Stockez les comptes et trouvez le maximum des comptes. Voici le code mis en fonction:

function getMostOccurrence(str) { 
    var check = {}; 
    var maxOccurrences = 0; 

    // This part you already have...kind of 
    str.split('').forEach(function(num) { 
     // Set it the first time 
     if (typeof check[num] === 'undefined') { 
      check[num] = 0; 
     } 

     // Increase it 
     check[num] += 1; 
    }); 

    // Find the max of that 
    for (var num in check) { 
     if (check.hasOwnProperty(num)) { 
      if (check[num] > maxOccurrences) { 
       maxOccurrences = check[num]; 
      } 
     } 
    } 

    return maxOccurrences; 
} 
1

Vous aurez besoin d'un ou deux aides:

// Given an object, it returns the values in an array 
// {a:1, b:2} => [1,2] 
var values = function(x) { 
    return Object.keys(x).map(function(k){return x[k]}) 
} 

// Given an array, it counts occurrences 
// by using an object lookup. 
// It will return an object where each key is an array item 
// and each value is the number of occurrences 
// [1,1,1,3] => {'1':3, '3':1} 
var occurrences = function(xs) { 
    return xs.reduce(function(acc, x) { 
    // If key exists, then increment, otherwise initialize to 1 
    acc[x] = ++acc[x] || 1 
    return acc 
    },{}) 
} 

// Composing both helpers 
var maxNumberOccurrence = function(n) { 
    // To get the maximum value of occurrences 
    // we use Math.max with `apply` to call the function 
    // with an array of arguments 
    return Math.max.apply(0, values(occurrences(n.toString().split('')))) 
} 

maxNumberOccurrence(1113) //=> 3 
+0

Votre approche semble plus sophistiquée. Cela vous dérangerait-il de le commenter/de l'expliquer afin que nous puissions tous apprendre ce qui se passe ici sans le décoder manuellement? –

+0

Vérifiez modifier, j'ai ajouté quelques commentaires. – elclanrs

+0

Très bien. Bien que je me demande s'il y a une raison pour laquelle vous avez utilisé 'Array.prototype.reduce' ici comme l'itérateur? –

Questions connexes