JavaScript中两个字符串之间的常见字母

时间:2018-04-28 03:36:10

标签: javascript jquery string increment

我试图计算用户input与生成的数字之间的公共字母数。我正在计算它,以便它们之间的位置不重要(因此411和004应该说" 1个共同的数字和#34;)。

我已将code放在下面的代码段中。它工作正常,除此之外,当生成的string有两个相同的数字时,它无法正常工作。您可以通过输入" 4&来看到它#34;,它会说有两个字符。共同的,当真的只有一个(它计算四次。)

所以,在这之后,我问inputgenerated number?

之间显示常用字母的最佳方法是什么?

我可以使用jQuery和/或JavaScript,对不起,如果我的代码不是很好,我根本不是很先进。

提前感谢您的帮助! :)



  // on ".check" click...

$(".check").click(function() {
  var nmb = $(".number").text();
  var ltr = $(".input").val();
  var count = $(".cnt");

  // Set logged text to 0
  
  count.text("0");

  // Test for numbers in common

  if (ltr.includes(nmb.charAt(0))) {
    count.html(function(i, val) {
      return val * 1 + 1
    });
  }
  if (ltr.includes(nmb.charAt(1))) {
    count.html(function(i, val) {
      return val * 1 + 1
    });
  }
  if (ltr.includes(nmb.charAt(2))) {
    count.html(function(i, val) {
      return val * 1 + 1
    });
  }
  if (ltr.includes(nmb.charAt(3))) {
    count.html(function(i, val) {
      return val * 1 + 1
    });
  }
  
  $(".res1").html(" numbers in common");
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Generated Number: <span class="number">4410</span><br><br>
<input type="text" class="input" placeholder="Try typing 4 to see the issue" maxlength="4">
<input class="check" type="submit" value="CHECK">
<br><br>
<span id="full_res">
  <span class="cnt"></span>
  <span class="res1"></span>
</span>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:3)

首先,您可以将每个字符串减少为仅包含唯一字符,即4410可以减少到410,因为您不需要多次测试4次。您可以通过创建每个字符串的Set来执行此操作:

var numberSet = new Set(nmb);
var inputSet = new Set(ltr);

然后你可以迭代其中一个,至少是最短的迭代次数,并使用has()方法查看该字符是否在另一个Set

var counter = 0;
for(letter of inputSet){
  if(numberSet.has(letter)){
    counter++;
  }
}

&#13;
&#13;
// on ".check" click...

$(".check").click(function() {
  var nmb = new Set( $(".number").text() );
  var ltr = new Set( $(".input").val() );
  var count = $(".cnt");

  var counter = 0;
  for(let letter of nmb){
     if(ltr.has(letter)){
       counter++;
     }
  }
  //No need to continually update text / html as each update wont be
  //seen anyway so just set it once outside the loop.
  count.text(counter);
  
  $(".res1").html(" numbers in common");
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Generated Number: <span class="number">4410</span><br><br>
<input type="text" class="input" placeholder="Try typing 4 to see the issue" maxlength="4">
<input class="check" type="submit" value="CHECK">
<br><br>
<span id="full_res">
  <span class="cnt"></span>
  <span class="res1"></span>
</span>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您可以执行以下操作:

&#13;
&#13;
$(".check").click(function() {
  var nmb = $(".number").text().trim().split('');   //Get the text and convert to string
  var ltr = $(".input").val().trim().split('');     //Get the value and convert to string
  var commonLetters = [];                           //The common letters will be stored on this variable

  ltr.forEach(function(v) {                         //Loop thru the user's input letters
    var idx = nmb.indexOf(v);                       //Find its index
    if (idx !== -1) {                               //Check if found
      commonLetters.push(4);                        //If found, push the letters to commonLetters
      nmb[idx] = '';                                //Clear the index
    }
  })

  $(".cnt").text(commonLetters.length);
  $(".res1").html(" numbers in common");
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Generated Number: <span class="number">4410</span><br><br>
<input type="text" class="input" placeholder="Try typing 4 to see the issue" maxlength="4">
<input class="check" type="submit" value="CHECK">
<br><br>
<span id="full_res">
   <span class="cnt"></span>
   <span class="res1"></span>
</span>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

这并非完全无足轻重。例如,您无法自行使用filterincludeshas测试,因为一旦找到某个字符,您必须将其从中删除< / em>集合所以它不会再次匹配。每次找到匹配项时,我都会使用reducesplice字符数组来删除找到的字符。 (不需要jQuery)

&#13;
&#13;
document.querySelector('.check').addEventListener('click', () => {
  const numChars = [...document.querySelector('.number').textContent];
  const inputChars = [...document.querySelector('.input').value];
  const matchingCharCount = inputChars.reduce(
    ({ remainingNumChars = numChars, matchCount = 0 } = {}, inputChar) => {
      if (remainingNumChars.includes(inputChar)) {
        remainingNumChars.splice(remainingNumChars.indexOf(inputChar), 1);
        matchCount++;
      }
      return { remainingNumChars, matchCount };
    }, { remainingNumChars: numChars, matchCount: 0 })
    .matchCount;
  document.querySelector('.cnt').textContent = matchingCharCount;
  document.querySelector('.res1').textContent = " numbers in common"
});
&#13;
Generated Number: <span class="number">4410</span><br><br>
<input type="text" class="input" maxlength="4">
<input class="check" type="submit" value="CHECK">
<br><br>
<span id="full_res">
  <span class="cnt"></span>
  <span class="res1"></span>
</span>
&#13;
&#13;
&#13;