0

I am doing a kata from Codewars, and I can not pass 2 test. It is almost there but still missing something. This function must return what is missing from a broken sequence. These are the instructions:

"Find out the missing number; if the sequence is not broken, you should return 0. Each sequence always increments by 1. In short: an invalid sequence (a string with non numeric character) must return 1, an already complete (or empty) sequence must return 0; a broken sequence with more than one number missing should return the lowest missing number; otherwise return the missing number."

This is the link:http://www.codewars.com/kata/broken-sequence/java

function findMissingNumber(sequence) {
  var max = sequence.slice(-1);
  var min = sequence[0];
  var RegExp = /[abcdefghijklmopqrstuvwxyz]/i;
  
  for (var j = 0; j < sequence.length; j++) {
    if (sequence.charAt(j).match(RegExp)) {
      return 1;
    }
  } //loop

  if (sequence === " " || sequence.length == 0) {
    return 0;
  }
  //
  else {
    sequence = sequence.split(" ").sort().map(function number(value) {
      return parseInt(value);
    });

    var numbers = [];

    for (var i = 1; i <= max; i++) {
      numbers.push(i);
    } //loop

    if (sequence[0] != numbers[0]) {
      return numbers[0];
    } else if (sequence[1] != numbers[1]) {
      return numbers[1];
    } else {
      var totala = sequence.reduce(function(a, b) {
        return a + b
      });
      var totalb = numbers.reduce(function(a, b) {
        return a + b
      });
      return Math.abs(totala - totalb);
    }
  } //main else
} //end
console.log(findMissingNumber(""));
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 1
    How you calculate max seems wrong – epascarello Apr 25 '17 at 00:03
  • Calculating totals seems like a strange way to do this. Just loop through the array. If `array[i]` doesn't contain `i+1` then that's the missing number. – Barmar Apr 25 '17 at 00:06
  • And using a loop to calculate the total of `1 .. max` is wasteful, since there's a formula for it: `max * (max + 1) / 2` – Barmar Apr 25 '17 at 00:07
  • `totala - totalb` is only the correct answer if there's just one missing number. If there's more than one missing number, it returns the total of all the missing numbers. – Barmar Apr 25 '17 at 00:09
  • You need to do the sorting *after* you parse the array elements to numbers. And you need to use a sort comparison function that compares them numerically, the default is lexicographic. – Barmar Apr 25 '17 at 00:10

0 Answers0