简体   繁体   English

我的javascript代码返回最常见的字母有什么问题?

[英]Whats wrong with my javascript code to return most common letter?

I am trying to write a solution that will return the most common letter in a string, and the number of times that letter appears. 我正在尝试编写一个解决方案,它将返回字符串中最常见的字母,以及该字母出现的次数。 The solution I came up was to loop through the string, holding one letter at a time in a variable called letter, and comparing all other letters to this. 我提出的解决方案是循环遍历字符串,一次在一个名为letter的变量中保持一个字母,并将所有其他字母与此进行比较。 Then once the string ended, the loop would hold the second letter and repeat. 然后一旦字符串结束,循环将保持第二个字母并重复。

The problem I am getting is it just returns the first letter in the string ever time. 我得到的问题是它只是返回字符串中的第一个字母。 It gets the number of matches correct, but it ignores the fact that other letters have more matches. 它得到的匹配数正确,但它忽略了其他字母有更多匹配的事实。

What am I doing wrong? 我究竟做错了什么?

 var match = 0; var matchCount = 0; var letter = 0; var count = 0; indx1 = 0; indx2 = 0; function problemTen(a) { while (indx1 < a.length) { letter = a[indx1]; //hold the first letter in the string in the letter variable while (indx2 < a.length) { //now rotate through every other letter to compare if (a[indx2] == letter) { //compare count += 1; // if there is a match, add one to the count variable to hold the number of matches } indx2 += 1; //cycle through the rest of the string } if (matchCount === 0 || count > matchCount) { // if it's the first time around, or if this letter had more matches than the previous letter match = letter; // hold the letter in the match variable matchCount = count; //hold the number of matches in the count variable } indx1 += 1; //cycle through the first variable that you compare } return [match, matchCount]; //return results } console.log(problemTen("astrings")); 

edit: here is the solution I came up with. 编辑:这是我提出的解决方案。

function problemTen (a) {
  var match = 0;
  var matchCount = 0;
  var letter;

  for(var indx1 = 0; indx1<a.length; indx1++) {
    letter = a[indx1];              
    var count = 1;                  

    for(var indx2 = indx1 + 1; indx2<a.length; indx2++) {         
      if(a[indx2] == letter) {        
        count +=1;                 
      }
    }
    if(matchCount === 0 || count>matchCount) { 
      match = letter;                  
      matchCount =count;               
    }   
  }
  return [match, matchCount];       
}

console.log(problemTen("iamatinystring"));

Maybe check this solution, it's time complexity is linear compared to the one you're trying to achieve, which is quadraple: 也许检查这个解决方案,它的时间复杂度是线性的,与你想要实现的相比,这是四倍:

function problemTen(a) {
  var array = a.split('');
  var max = 0;
  var letter;

  var counter = array.reduce(function(memo, item) {
    memo[item] = memo[item] ? memo[item] + 1 : 1;
    if (memo[item] > max) {
      max = memo[item];
      letter = item;
    }
    return memo;
  }, {});

  return [letter, max];
}

console.log(problemTen("astrings"));

If you want to stick to your solution though, the problem is, when you run the outer while loop again, you're not resetting the indx2 and count variables, so, indx2 = a.length already, and the inner while loop doesn't run anymore to count letters. 如果你想坚持你的解决方案,问题是,当你再次运行外部while循环时,你没有重置indx2和count变量,所以,indx2 = a.length已经,而内部while循环没有再跑去计算字母。 with adding these resets, your code should be something like this: 添加这些重置,您的代码应该是这样的:

function problemTen(a) {
  var match = 0;
  var matchCount = 0
  var letter = 0;
  var count = 0;
  indx1 = 0;
  indx2 = 0;

  while (indx1 < a.length) {
    letter = a[indx1]; //hold the first letter in the string in the letter variable

    while (indx2 < a.length) { //now rotate through every other letter to compare
      if (a[indx2] === letter) { //compare 
        count += 1; // if there is a match, add one to the count variable to hold the number of matches
      }
      indx2 += 1; //cycle through the rest of the string  
    }
    if (matchCount === 0 || count > matchCount) { // if it’s the first time around,     or if this letter had more matches than the previous letter
      match = letter; // hold the letter in the match variable
      matchCount = count; //hold the number of matches in the count     variable
    }
    indx1 += 1; //cycle through the first variable that you compare

    // HERE WE RESET indx2 and match to 0
    indx2 = 0;
    match = 0;

  }
  return [match, matchCount]; //return results
}

console.log(problemTen("astrings"));

In fact, to achieve O(n) time complexity, you don't necessarily use reduce, you can do it just using one loop as well, and it will surely be much faster, I just prefer functional programming as it results better readibility: 事实上,要实现O(n)时间复杂度,你不一定使用reduce,你也可以只使用一个循环,它肯定会快得多,我只是喜欢函数式编程,因为它带来更好的可读性:

function problemTen(a) {
  var max = 0;
  var letter;
  var counter = {};

  for (var i = 0, l = a.length; i<l; i++) {
    counter[a[i]] = counter[a[i]] ? counter[a[i]] + 1 : 1;
    if (counter[a[i]] > max) {
      max = counter[a[i]];
      letter = a[i];
    }
  }

  return [letter, max];
}

console.log(problemTen("astrings"));

Hope this helps. 希望这可以帮助。

You task is to find the (first) character with the highest number of occurences in a given string. 您的任务是找到给定字符串中出现次数最多的(第一个)字符。 If you do not want to use extra memory like in Ahmet Cetin's answer you really need two loops here. 如果你不想像Ahmet Cetin的回答那样使用额外的内存,你真的需要两个循环。 You also need on point for the current character and its number of occurences and one for the actaul top postion and its number of occurances, four variables. 你还需要当前字符及其出现次数的点,以及一个用于actaul顶部位置及其出现次数的四个变量。

This is a place where a for loop would be better suited than your while -loops but both would work. 这是一个for循环比你的while循环更适合的地方,但两者都可以。

var teststring = "teststring";

function problemTen(s){
  var count = 0;      // counter for current character
  var last = 0;       // counter for actual highest character
  var character = ""; // current character
  var top = "";       // highest character

  for(var i = 0;i < s.length;i++){     // Loop over the full string
    character = s[i];                  // set current character
    for(var j = 0;j < s.length; j++){  // Loop over the full string
      if(s[j] === character){          // we found another occurence
        count++;                       // increment the counter
      }
    }
    if(last < count){   // the actual char. has more occ. than the last one
      last = count;     // set the top counter to the current counter
      top = character;  // set the top character to the current character
    }
    count = 0;        // reset the current counter
  }
  return [top,last];    // return the character and count of the to one
}

problemTen(teststring);

As is, the code loops through the string only once. 原样,代码只循环一次字符串。 For that you should reset indx2 to 0 before the inner while loop. 为此,您应该在内部while循环之前将indx2重置为0。 Done that then you will have to also reset the 'count' variable at every inner loop. 完成后,您还必须在每个内循环处重置'count'变量。

An optimization is to have indx2 start from indx1+1, and have count=1 at the beginning of the inner loop. 优化是让indx2从indx1 + 1开始,并在内循环的开头有count = 1。

 var match = 0; var matchCount = 0; var letter = 0; var count = 0; indx1 = 0; indx2 = 0; function problemTen(a) { while (indx1 < a.length) { letter = a[indx1]; //hold the first letter in the string in the letter variable indx2 = 0; // <---- [sal] reset the inner loop starting point count = 0; // <---- [sal] reset the inner loop counter while (indx2 < a.length) { //now rotate through every other letter to compare if (a[indx2] == letter) { //compare count += 1; // if there is a match, add one to the count variable to hold the number of matches } console.log(letter, a[indx2], count); indx2 += 1; //cycle through the rest of the string } if (matchCount === 0 || count > matchCount) { // if it's the first time around, or if this letter had more matches than the previous letter match = letter; // hold the letter in the match variable matchCount = count; //hold the number of matches in the count variable } indx1 += 1; //cycle through the first variable that you compare } return [match, matchCount]; //return results } console.log(problemTen("astrings")); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM