문제
다음 숫자 이름 문자열을 가정합니다 -
const str = 'TOWNE';
이 문자열을 재배열하면 2(TWO)와 1(ONE)이라는 두 개의 숫자 이름을 찾을 수 있습니다.
따라서 21의 출력을 기대합니다.
이러한 문자열을 받아서 문자열에 있는 숫자를 반환하는 JavaScript 함수를 작성해야 합니다.
예시
다음은 코드입니다 -
const str = 'TOWNE';
const findNumber = (str = '') => {
function stringPermutations(str) {
const res = [];
if (str.length == 1) return [str];
if (str.length == 2) return [str, str[1]+str[0]];
str.split('').forEach((chr, ind, arr) => {
let sub = [].concat(arr);
sub.splice(ind, 1);
stringPermutations(sub.join('')).forEach(function (perm) {
res.push(chr+perm);
});
});
return res;
}
const legend = {
'ONE': 1, 'TWO': 2, 'THREE': 3, 'FOUR': 4,
'FIVE': 5, 'SIX': 6, 'SEVEN': 7, 'EIGHT': 8,
'NINE': 9, 'ZERO': 0
};
const keys = Object.keys(legend);
const res = {};
const resArr = [];
let result = '';
keys.forEach(key => {
const match = stringPermutations(key).find(el => el.split('').every(char => str.includes(char)));
if(match){
const index = str.indexOf(match[0]);
if(!res.hasOwnProperty(key)){
res[key] = [index];
}else if(!res[key].includes(index)){
res[key].push(index);
};
};
});
Object.keys(res).forEach(word => {
resArr.push([word, ...res[word]]);
});
resArr.sort((a, b) => a[1] - b[1]);
resArr.forEach(sub => {
result = result + String(legend[sub[0]]).repeat(sub.length - 1);
});
return +result;
};
console.log(findNumber(str)); 출력
다음은 콘솔 출력입니다 -
21