Javascript计算字符串的频率字母

时间:2016-09-29 16:49:49

标签: javascript string

我一直试图想出这个练习的答案,但是我不能看到它的错误。我将分享练习的描述,我的代码,最后是我的输出。

描述:

现在我们将在一个名为array_lengths

的新数组中保存每个数组的最长长度

打开控制台并重新加载索引页以查看代码的结果。

编写一个charFreq()函数,它接受一个字符串并构建其中包含的字符的频率列表。

作为条件,您必须使用对象freqCounter。

将频率列表表示为Javascript对象。尝试使用像charFreq(“abbabcbdbabdbdbabababcbcbab”)这样的东西。

CODE:

function charFreq(string) {

  var array_lengths = [];

  // compute frequencies of each value
  for (var i = 0; i < string.length; i++) {
    value = string[i];
    if (value in array_lengths) {
      array_lengths[value] ++;
    } else {
      array_lengths[value] = 1;
    }
  }


  // make array from the frequency object to de-duplicate
  var freqCounter = [];
  for (value in array_lengths) {
    freqCounter.push(value);
  }

  // sort the uniques array in descending order by frequency
  function compareFrequency(a, b) {
    return array_lengths[b] - array_lengths[a];
  }

  return freqCounter.sort(compareFrequency);
}

//OUTPUT: 

// if I had it right I should get "true" from every of the following values of the function but the point is that I'm getting all false...where's the error?

counter = charFreq("abbabcbdbabdbdbabababcbcbab");

console.log(counter['a'] === 7);

console.log(counter.b === 14);

console.log(counter['c'] === 3);

4 个答案:

答案 0 :(得分:4)

两个问题

  • 使用对象

    var array_lengths = {}; // object
    
  • 返回该对象而不进行排序和其他内容

    return array_lengths;
    

function charFreq( string ) {
    var array_lengths = {}; // object

    // compute frequencies of each value
    for(var i = 0; i < string.length; i++) {
        value = string[i];
        if(value in array_lengths) {
            array_lengths[value]++;
        } else {
            array_lengths[value] = 1;
        }
    }
    return array_lengths;
}

//OUTPUT:
// if I had it right I should get "true" from every of the following values of the function but the point is that I'm getting all false...where's the error?

counter = charFreq("abbabcbdbabdbdbabababcbcbab");
console.log(counter);
console.log( counter['a'] === 7);
console.log( counter.b === 14);
console.log( counter['c'] === 3);

答案 1 :(得分:1)

分解。你需要迭代字符串的每个部分,对吗?将其拆分为数组并为对象中的每个元素创建一个计数器:

var counter = {};
var string = "abbabcbdbabdbdbabababcbcbab";
var stringArray = string.split('');
stringArray.forEach(function(character){
  if(!counter.hasOwnProperty(character)){
    counter[character] = 0;
  }
  counter[character]++;
});
console.log(counter);

答案 2 :(得分:0)

您可以使用ES6执行此操作 - 使用Set通过将字符串转换为数组并将整个内容传递到let path = NSBundle.mainBundle().pathForResource("movielist2", ofType: "txt") let filemgr = NSFileManager.defaultManager() if filemgr.fileExistsAtPath(path!){ do{ let fullText = try String(contentsOfFile: path!, encoding: NSUTF8StringEncoding) let readings = fullText.componentsSeparatedByString("@") as [String] for i in 1..<readings.count { let movieData = readings[i].componentsSeparatedByString("\t") dictMovies["MovieTitle1"] = "\(movieData[0])" dictMovies["MovieYear"] = "\(movieData[1])" arrayMovies.addObject(dictMovies) } } catch let error as NSError{ print("Error: \(error)") } }

来获取数组中的唯一项
new Set

答案 3 :(得分:0)

您正在使用数组作为对象 我留下了var freqCounter = Object.keys(array_lengths);,因为它是字符串中的唯一字符。但是,它在您描述的代码中没有为您做任何事情。

&#13;
&#13;
function charFreq(string) {

  var array_lengths = {};
  var value;
  // compute frequencies of each value
  for (var i = 0; i < string.length; i++) {
    value = string[i];
    if (value in array_lengths) {
      array_lengths[value] ++;
    } else {
      array_lengths[value] = 1;
    }
  }


  // make array from the frequency object to de-duplicate
  var freqCounter = Object.keys(array_lengths);

  // sort the uniques array in descending order by frequency
  function compareFrequency(a, b) {
    return array_lengths[b] - array_lengths[a];
  }

  return array_lengths;
}

//OUTPUT: 

// if I had it right I should get "true" from every of the following values of the function but the point is that I'm getting all false...where's the error?

counter = charFreq("abbabcbdbabdbdbabababcbcbab");
console.log(counter);
console.log(counter['a'] === 7);

console.log(counter.b === 14);

console.log(counter['c'] === 3);
&#13;
&#13;
&#13;