-
[알고리즘풀기] 프로그래머스 로그인성공?Algorithm 2023. 3. 30. 01:19728x90
머쓱이는 프로그래머스에 로그인하려고 합니다. 머쓱이가 입력한 아이디와 패스워드가 담긴 배열
id_pw
와 회원들의 정보가 담긴 2차원 배열db
가 주어질 때, 다음과 같이 로그인 성공, 실패에 따른 메시지를 return하도록 solution 함수를 완성해주세요.- 아이디와 비밀번호가 모두 일치하는 회원정보가 있으면 "login"을 return합니다.
- 로그인이 실패했을 때 아이디가 일치하는 회원이 없다면 “fail”를, 아이디는 일치하지만 비밀번호가 일치하는 회원이 없다면 “wrong pw”를 return 합니다.
제한사항
- 회원들의 아이디는 문자열입니다.
- 회원들의 아이디는 알파벳 소문자와 숫자로만 이루어져 있습니다.
- 회원들의 패스워드는 숫자로 구성된 문자열입니다.
- 회원들의 비밀번호는 같을 수 있지만 아이디는 같을 수 없습니다.
id_pw
의 길이는 2입니다.id_pw
와 db의 원소는 [아이디, 패스워드] 형태입니다.- 1 ≤ 아이디의 길이 ≤ 15
- 1 ≤ 비밀번호의 길이 ≤ 6
- 1 ≤
db
의 길이 ≤ 10 db
의 원소의 길이는 2입니다.
...
입출력 예 설명
입출력 예 #1
db
에 같은 정보의 계정이 있으므로 "login"을 return합니다.
입출력 예 #2
db
에 아이디는 같지만 패스워드가 다른 계정이 있으므로 "wrong pw"를 return합니다.
입출력 예 #3
db
에 아이디가 맞는 계정이 없으므로 "fail"을 return합니다.
function solution(id_pw, db) { let answer = "fail"; db.some((e) => { const dbid = e[0]; const dbpw = e[1]; const [inputid, inputpw] = id_pw; if (dbid === inputid) { if (dbpw === inputpw) { answer = "login"; } else { answer = "wrong pw"; } return true; } }); return answer; }
새로 알게된 메서드 some
Array.prototype.some()은 배열 내의 각각의 원소에 대해 주어진 콜백 함수를 호출하면서, 콜백 함수의 반환값이 true가 되는 첫 번째 원소를 찾으면 즉시 반복을 멈추고 true를 반환합니다.
만약 콜백 함수의 반환값이 false인 경우, some() 메소드는 다음 원소를 검사합니다.
즉, some() 메소드는 배열 내에서 조건을 만족하는 원소가 있는지 여부를 판단할 때 유용합니다.
map과 유사하지만, map()은 배열을 변환하고 some()은 조건을 확인할 때 사용됩니다.
some()은 배열의 요소 중 하나라도 주어진 함수를 만족시키면 true를 반환합니다. 만족하는 요소가 없으면 false를 반환합니다. 예를 들어, [1, 2, 3].some(x => x > 2)는 true를 반환합니다. ( [1, 2, 3].map(x => x * 2)는 [2, 4, 6]을 반환합니다)
따라서 some()은 주어진 조건이 하나라도 만족하는지 확인할 때 유용하게 사용됩니다.
728x90'Algorithm' 카테고리의 다른 글
알고리즘 하드코딩 장인 [프로그래머스] 약수의 개수와 덧셈 (코드 간결화) (0) 2023.04.11 HackerRank 문제 해석, 풀이 Plus Minus- Java script (0) 2023.04.06 [알고리즘풀기] 프로그래머스 문자열 나누기 Java script (0) 2023.03.28 10.[Programmers]알고리즘 문제 Java script 2016 요일구하기 (사서 고생하는 사람의 노가다 구경하실래요?) (0) 2022.12.21 9. [Programmers] 알고리즘 문제풀기 Java script 문자열 다루기 기본 (0) 2022.12.20