Home > database >  Distinct Digit Year -Codewars Challenge-
Distinct Digit Year -Codewars Challenge-

Time:04-07

I was solving a codewars challenge and got stuck in an endless loop. The task is to find from a given input like year 1987 the next greater integer that has only distinct digits. In that case it would be 2013 as 1988, 1998,2000 etc. do not have 4 distinct digits. I wanted to solve this task with an Object and see where the length of the Object.keys(obj) is equal to 4.

Here is my try

function distinctDigitYear(year) {
  
  let obj = {}
  let count = 1
  let yearCounter = year   count
  
  while (Object.keys(obj).length !==4) {
    obj = {}
    yearCounter.toString().split('').forEach(el=> {
      if(!Object.keys(obj).includes(el)){
        obj[el] = 1
      } else {
        obj[el]  =1
      }
    }
    )
   
      count  
  }
  return yearCounter   1
}

distinctDigitYear(2000)

Thanks for reading!

CodePudding user response:

Details are commented in eample below

// Pass a 4 digit year -- 1987
function distinctDigitYear(year) {
    year; // Increment -- 1988
  /*
  Convert year number into a String. Spread the String into 4 
  separate characters with the spread operator ... then convert an 
  Array into a Set eliminates any duplicates, then convert it back to an Array.
  */
  let yyyy = [...new Set([...year.toString()])];
  // If there are no dupes, yyyy will be 4 characters
  if (yyyy.length === 4) {
    /*
    join() the array into a String and return it
    */
    return yyyy.join('');
  }
  /*
  If the lenght of yyyy is less than 4
  recursively call dDY() passing next year through.
  */
  return distinctDigitYear(year);
};

console.log(distinctDigitYear(1987));
console.log(distinctDigitYear(2020));
console.log(distinctDigitYear(1910));

  • Related