My code crashes javascript console

My code is freezing Chrome (and Firefox), won't execute on Coderbyte console but when I submit the code as an answer to the exercise, it does take.

var numOrdered = 0;
var numReversed = 0;
var tries = 0;
function KaprekarsConstant(num) {
  var arr = [];
  while (num > 0) {
    arr.unshift(num % 10);
    num = num / 10 | 0;
  }
  arr.sort();
  numOrdered = Number(arr.join(''));
  numReversed = Number(arr.reverse().join(''));

  while (num !== 6174) {
    num = numReversed - numOrdered;
    tries += 1;
  }
  return tries;
};

KaprekarsConstant(8593);

Why is it crashing? How can I prevent it?

Thank you guys!

5 answers

  • answered 2018-04-17 04:22 31piy

    the actual problem is the second while loop:

    while (num !== 6174) {
      num = numReversed - numOrdered;
      tries += 1;
    }
    

    Removing it, your code doesn't hang the browser:

    var numOrdered = 0;
    var numReversed = 0;
    var tries = 0;
    function KaprekarsConstant(num) {
      var arr = [];
      while (num > 0) {
        arr.unshift(num % 10);
        num = num / 10 | 0;
      }
      arr.sort();
      numOrdered = Number(arr.join(''));
      numReversed = Number(arr.reverse().join(''));
    
      
      return tries;
    };
    
    console.log(KaprekarsConstant(8593));

    You need to revisit the logic in the second loop so that it doesn't become infinite.

  • answered 2018-04-17 04:22 Gokul Sandeep

    The second loop makes your code to hang up.Try this. I have made some changes.

    var numOrdered = 0;
    var numReversed = 0;
    var tries = 0;
    function KaprekarsConstant(num) {
    
      while (num !== 6174) {
         var arr = [];
        while(num >0){  
        arr.unshift(num % 10);
        num = num / 10 | 0;
      }
      arr.sort();
      numOrdered = Number(arr.join(''));
      numReversed = Number(arr.reverse().join(''));
      num = numReversed - numOrdered;
      tries += 1;
      }
      return tries;
    };
    
    KaprekarsConstant(8593);
    

  • answered 2018-04-17 04:22 traktor53

    The while loop in the post keeps calculating the same value for num, so it it is not immediately 6174, the loop continues forever.

    Basically the code is not following the algorithm for demonstrating Kaprekar's constant as shown on Wikipedia:

    • pad numbers of less than 4 digits with leading zeroes,
    • subtract the smaller number from the larger of { number, number with reversed digits), and
    • repeat from the step of extracting digits from the latest subtraction result.

    Spoiler alert - here's a working example of a recursive function with the extra pieces of logic:

    "use strict";
    
    function KaprekarsConstant(num, tries=0) {
    
      if( num == 6174)  // Kaprekar's constant.
         return tries;
      if( num == 0)     // degenerate case, digits are the same
         return -tries;
    
      var arr = [];
      while (num > 0) {
        arr.unshift(num % 10);
        num = num / 10 | 0;
      }
      while( arr.length<4) {  // leading zeroes as required
        arr.unshift(0);
      }
      arr.sort();
      var numOrdered = Number(arr.join(''));
      var numReversed = Number(arr.reverse().join(''));
    
      num = Math.abs( numOrdered - numReversed)  // larger - smaller
      return KaprekarsConstant( num, ++tries);   // try again
    };
    
    // and test
    function test() {
      var num = Number(input.value);
      if( Number.isNaN(num) || num < 1 || num > 9999) {
        throw new Error("Enter number between 1 and 9999");
      }
      console.log("Tries = %s", KaprekarsConstant(num)  );
    }
    <label> Enter 1 to 4 digit number: <input type="text" id="input"></label><br>
    <button type="button" onclick="test()">Calculate tries</button>

  • answered 2018-04-17 04:22 Dinesh Chand

    While the answers do address your question, the solutions and the code are missing the part about leading zeros as in wiki Kaprekar's constant and the whole solution is very simple

    function KaprekarsConstant(num)
    {
        var tries=0;
        var numOrdered =0;
        var numRevesed=0;
        while(num!=6174)
        {
            numOrdered=("0000" + num).substr(-4,4).split("").sort().join("");
            numRevesed=numOrdered.split("").reverse().join("");
            num = numRevesed-numOrdered;
            tries+=1;
        }
        return tries;
    }
    KaprekarsConstant(8593);
    

  • answered 2018-04-17 04:22 Manu AVS

    To the reason for 'Why is it crashing?', its maybe due to Infinite Loop .

    The response I got when I try to run your code

    Possible infinite loop detected. 
    Error: Infinite loop
        at KaprekarsConstant (script 19:68)
        at script 27:1