nunnly / everycode

Javascript 每日一练
116 stars 26 forks source link

统计字符串内字符出现的个数 #46

Open cuining opened 9 years ago

cuining commented 9 years ago

var genCode = 'TCCAGAAAGGTAAGCCTCGCGTTGCG' //只限4个字母。可考虑实现多个字母的情况 var result = getCountedNucleotides(getCode); console.log(result) // {"A":0, "C":0, "G":0, "T":0}

singone commented 9 years ago

表示没看懂需求

XadillaX commented 9 years ago
function getCountedNucleotides(str) {
    return str.split("").reduce(function(ans, ch) {
        return ans[ch] = (ans[ch] !== undefined ? ans[ch] + 1 : 0), ans;
    }, {});
}
IrisZhang commented 9 years ago
function getCountedNucleotides(str){
        var result = {};
        for(var i = 0; i<str.length; i++){
            if(str[i] in result){
                result[str[i]] = result[str[i]] + 1;
            }else{
                result[str[i]] = 0;
            }
        }
        return result;
    }
Sanford2020 commented 9 years ago
 function getCountedNucleotides (str){
      var reg = /(\w)?\1*/g,
          match = str.match(reg),
          ret = {},
          i=match.length;
      for(;i--;){
        var mi = match[i],
            fc = mi[0];
        ret[fc] = (!!ret[fc])?(+ret[fc])+mi.length:mi.length
      }
      return ret;
    }