function solution(X, Y) {
X=X.split('');
Y=Y.split('');
let answer = [];
for (let i=0; i<Y.length; i++) {
if (X.includes(Y[i])) {
answer.push(Number(...X.splice(X.indexOf(Y[i]), 1)));
}
}
if (answer.length===0) {
return String(-1);
}
else if (answer.reduce((a,b)=>a+b)===0) {
return String(0);
}
else {
return answer.sort((a,b) => b-a).join('');
}
}
console.log(solution("12321", "42531"));
“전체를 도는 게 아니라 개수로 접근하기”
0~9 중에서 겹치는 숫자의 개수를 파악해서 그걸 answer에 넣어주기.
아무것도 없으면 -1 리턴
0 이외에 아무것도 없으면 0 리턴
그 외에는 answer 값을 정렬해서 리턴
function solution(X, Y) {
var answer = "";
X = [...X];
Y = [...Y];
console.log(X, Y);
for (let i = 0; i < 10; i++) {
const X_cnt = X.filter((item) => +item === i).length;
const Y_cnt = Y.filter((item) => +item === i).length;
answer += i.toString().repeat(Math.min(X_cnt, Y_cnt));
}
if (answer === "") {
return "-1";
} else if (answer.match(/[^0]/g) === null) {
return "0";
} else {
return [...answer].sort().reverse().join("");
}
}
console.log(solution("10301", "42501"));
객체로 숫자 카운팅
function solution(X, Y) {
const commonNums = [];
const objX = {};
const objY = {};
for(const el of X) {
objX[el] = (objX[el] || 0) + 1
}
for (const el of Y) {
if (objX[el]) {
commonNums.push(el);
objX[el]--;
}
}
commonNums.sort((a, b) => b - a);
if (commonNums.length === 0) return "-1";
if (commonNums[0] === "0") return "0";
return commonNums.reduce((acc, cur) => acc + cur, "");
}
console.log(solution("10301", "42501"));