不同的数字年份 -Codewars Challenge-
Distinct Digit Year -Codewars Challenge-
我在解决代码战挑战时陷入了死循环。任务是从给定的输入(如 1987 年)中找到下一个只有不同数字的更大整数。在那种情况下,它将是 2013,因为 1988、1998、2000 等没有 4 个不同的数字。我想用一个对象来解决这个任务,看看 Object.keys(obj)
的长度在哪里等于 4.
这是我的尝试
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)
感谢阅读!
详情见下方示例
// 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));
我在解决代码战挑战时陷入了死循环。任务是从给定的输入(如 1987 年)中找到下一个只有不同数字的更大整数。在那种情况下,它将是 2013,因为 1988、1998、2000 等没有 4 个不同的数字。我想用一个对象来解决这个任务,看看 Object.keys(obj)
的长度在哪里等于 4.
这是我的尝试
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)
感谢阅读!
详情见下方示例
// 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));