► JS Algorithm/Programmers
[Programmers] JavaScript 알고리즘 | Lv.0 조건 문자열
다람트리
2024. 8. 18. 11:57
반응형
🔒 문제 설명
문자열에 따라 다음과 같이 두 수의 크기를 비교하려고 합니다.
- 두 수가 n과 m이라면
- ">", "=" : n >= m
- "<", "=" : n <= m
- ">", "!" : n > m
- "<", "!" : n < m
두 문자열 ineq와 eq가 주어집니다. ineq는 "<"와 ">"중 하나고, eq는 "="와 "!"중 하나입니다. 그리고 두 정수 n과 m이 주어질 때, n과 m이 ineq와 eq의 조건에 맞으면 1을 아니면 0을 return하도록 solution 함수를 완성해주세요.
🔒 제한사항
- 1 ≤ n, m ≤ 100
🔒 입출력 예
ineq | eq | n | m | result |
"<" | "=" | 20 | 50 | 1 |
">" | "!" | 41 | 78 | 0 |
🔒 입출력 예 설명
입출력 예 #1
- 20 <= 50은 참이기 때문에 1을 return합니다.
입출력 예 #2
- 41 > 78은 거짓이기 때문에 0을 return합니다.
※ 2023.05.31 테스트 케이스가 수정되었습니다. 기존에 제출한 코드가 통과하지 못할 수도 있습니다.
🔐 solution of mine
Array.prototype.filter()
function solution(ineq, eq, n, m) {
const map = {
">": [{ "=": n >= m }, { "!": n > m }],
"<": [{ "=": n <= m }, { "!": n < m }],
};
return console.log(map[ineq].filter((v) => v[eq]).length);
}
solution("<", "=", 20, 50); // expected output: 1
solution(">", "!", 41, 78); // expected output: 0
🔐 GPT's solution
function solution(ineq, eq, n, m) {
if (ineq === ">" && eq === "=") {
return console.log(n >= m ? 1 : 0);
} else if (ineq === ">" && eq === "!") {
return console.log(n > m ? 1 : 0);
} else if (ineq === "<" && eq === "=") {
return console.log(n <= m ? 1 : 0);
} else if (ineq === "<" && eq === "!") {
return console.log(n < m ? 1 : 0);
}
}
solution("<", "=", 20, 50); // expected output: 1
solution(">", "!", 41, 78); // expected output: 0
🔐 solution of others
const operations = {
">=": (n, m) => n >= m,
"<=": (n, m) => n <= m,
">!": (n, m) => n > m,
"<!": (n, m) => n < m,
};
function solution(ineq, eq, n, m) {
const op = operations[ineq + eq];
return console.log(Number(op(n, m)));
}
solution("<", "=", 20, 50); // expected output: 1
solution(">", "!", 41, 78); // expected output: 0
🔐 solution of others
function solution(ineq, eq, n, m) {
if (eq === "=" && n === m) return console.log(1);
if (ineq === "<" && n < m) return console.log(1);
if (ineq === ">" && n > m) return console.log(1);
return console.log(0);
}
solution("<", "=", 20, 50); // expected output: 1
solution(">", "!", 41, 78); // expected output: 0
🔐 solution of others
String.prototype.replace()
eval()
function solution(ineq, eq, n, m) {
let str = (n + ineq + eq + m).replace("!", "");
return console.log(eval(str) ? 1 : 0);
}
solution("<", "=", 20, 50); // expected output: 1
solution(">", "!", 41, 78); // expected output: 0
🔐 solution of others
eval()
function solution(ineq, eq, n, m) {
return console.log(+eval(n + ineq + (eq === "!" ? "" : eq) + m));
}
solution("<", "=", 20, 50); // expected output: 1
solution(">", "!", 41, 78); // expected output: 0
반응형