Home > Mobile >  Javascript Serial Number CoderByte problem
Javascript Serial Number CoderByte problem

Time:06-23

I'm currently solving a problem at CoderByte. Here's the scenario.

Have the function SerialNumber(str) take the str parameter being passed and determine if it is a valid serial number with the following constraints:

  1. It needs to contain three sets each with three digits (1 through 9) separated by a period.
  2. The first set of digits must add up to an even number.
  3. The second set of digits must add up to an odd number.
  4. The last digit in each set must be larger than the two previous digits in the same set.

If all the above constraints are met within the string, the your program should return the string true, otherwise your program should return the string false. For example: if str is "224.315.218" then your program should return "true".

Examples
Input: "11.124.667"
Output: false

Input: "114.568.112"
Output: true

Here's my JS code for this problem.

function SerialNumber(str) { 

  // code goes here
  if(str.length < 11) {
    return "false";
  }

  for (let x = 0; x < str.length; x  ) {
    if(str[x] === '0') {
      return "false";
    }
  }
  
  first = str[0]   str[1]   str[2];
  second = str[4]   str[5]  str[6];

  if (first % 2 !== 0 || second % 2 === 0) {
    return "false";
  }

  if (str[2] < str[1] || str[2] < str[0] || str[6] < str[5] || str[6] < str[4] || str[10] < str[8] || str[10] < str[9]) {
    return "false";
  } else {
    return "true";
  }
}

When I input "11.124.667", it will return to false (which is correct). And when I input "114.568.112", it will also return to false (which is not correct). Any tips on how can I obtain this? Thanks for the feedback.

CodePudding user response:

I tried your code and the problem comes from the third return false for the 2nd example, when you set second, you concatenate strings instead of adding numbers, thus %2 is always equal to 0 since
I added console.log before each return false to see which condition failed.
Here's the fixed code in which I added parseInt for first and second

function SerialNumber(str) {

    if (str.length < 11) {
        console.log("first")
        return "false";
    }

    for (let x = 0; x < str.length; x  ) {
        if (str[x] === '0') {
            console.log("second")
            return "false";
        }
    }

    const first = parseInt(str[0])   parseInt(str[1])   parseInt(str[2]);
    const second = parseInt(str[4])   parseInt(str[5])   parseInt(str[6]);

    if (first % 2 !== 0 || second % 2 === 0) {
        console.log("third")
        return "false";
    }

    if (str[2] < str[1] || str[2] < str[0] || str[6] < str[5] || str[6] < str[4] || str[10] < str[8] || str[10] < str[9]) {
        console.log("fourth")
        return "false";
    } else {
        return "true";
    }
}

console.log("11.124.667 : "   SerialNumber("11.124.667"));
console.log("114.568.112 : "   SerialNumber("114.568.112"))

  • Related