There is a task: to write a program that calculates how many times each number is found in a number. I wrote something - it works, but there is one problem.

Here, for example, the user enters the number 123345. The number 3 is repeated 2 times and the alert displays the same message twice. That is, for other digits that are found there only once the alert displays one message and everything is fine.
Help me please.

function same_numbers() { var number = document.getElementById('number').value; var number_copy = number; var s_1 = ""; var s_2 = ""; var same = 0; for (i = 0; i < number.length; ++i) { same = 0; s_1 = number.charAt(i); for (y = 0; y < number_copy.length; ++y) { s_2 = number_copy.charAt(y); if (s_1 == s_2) { same += 1; } } alert(s_1 + ": " + same + ";"); } } 
 <input type="text" id="number" /> <input type="button" onclick="same_numbers()" value="Click Me" /> 

  • 2
    You have an alert in the loop, and therefore displays several times - stackanon
  • Sorry for the small cycle, it would be more windows. - nick_n_a
  • @stackanon when I pull it out of the cycle, then for some reason only the last number is output and that's where it ends - Mark_8
  • I suggest using the leaf and pen to step through the entire cycle (and there are only 6 iterations) with the analysis of the values ​​of all variables. I am more than sure that there will be a solution right away) - carapuz
  • @carapuz open debug and press 1 key, inspecting the values ​​of all variables. Like we live in the 21st century) - Vasily Barbashev

2 answers 2

The problem is that the outer loop goes through all the digits, and if the digit is repeated, the count is repeated for it and the output again occurs.

To avoid this, you can change the string, removing from it already verified characters.

For example:

 function same_numbers() { var number = document.getElementById('number').value; var replaced; var same; var s_1; while (number.length) { s_1 = number[0]; replaced = number.split(s_1).join(''); same = number.length - replaced.length; console.log(s_1 + ": " + same + ";"); number = replaced; } } 
 <input type="text" id="number" /> <input type="button" onclick="same_numbers()" value="Click Me" /> 

    Better to use the object to store the result.

     function same_numbers() { var number = document.getElementById('number').value; var numbersCount = {}; var val; for (i = 0; i < number.length; ++i) { val = number[i]; numbersCount[val] ? numbersCount[val]++ : (numbersCount[val]=1) } alert(JSON.stringify(numbersCount, null, ' ')); } 
     <input type="text" id="number" /> <input type="button" onclick="same_numbers()" value="Click Me" />