더보기
❓Problem
사진들을 보며 추억에 젖어 있던 루는 사진별로 추억 점수를 매길려고 합니다. 사진 속에 나오는 인물의 그리움 점수를 모두 합산한 값이 해당 사진의 추억 점수가 됩니다. 예를 들어 사진 속 인물의 이름이 ["may", "kein", "kain"]이고 각 인물의 그리움 점수가 [5점, 10점, 1점]일 때 해당 사진의 추억 점수는 16(5 + 10 + 1)점이 됩니다. 다른 사진 속 인물의 이름이 ["kali", "mari", "don", "tony"]이고 ["kali", "mari", "don"]의 그리움 점수가 각각 [11점, 1점, 55점]]이고, "tony"는 그리움 점수가 없을 때, 이 사진의 추억 점수는 3명의 그리움 점수를 합한 67(11 + 1 + 55)점입니다.
그리워하는 사람의 이름을 담은 문자열 배열 name, 각 사람별 그리움 점수를 담은 정수 배열 yearning, 각 사진에 찍힌 인물의 이름을 담은 이차원 문자열 배열 photo가 매개변수로 주어질 때, 사진들의 추억 점수를 photo에 주어진 순서대로 배열에 담아 return하는 solution 함수를 완성해주세요.
🚫Restrictions
3 ≤ name의 길이 = yearning의 길이≤ 100
3 ≤ name의 원소의 길이 ≤ 7
name의 원소들은 알파벳 소문자로만 이루어져 있습니다.
name에는 중복된 값이 들어가지 않습니다.
1 ≤ yearning[i] ≤ 100
yearning[i]는 i번째 사람의 그리움 점수입니다.
3 ≤ photo의 길이 ≤ 100
1 ≤ photo[i]의 길이 ≤ 100
3 ≤ photo[i]의 원소(문자열)의 길이 ≤ 7
photo[i]의 원소들은 알파벳 소문자로만 이루어져 있습니다.
photo[i]의 원소들은 중복된 값이 들어가지 않습니다.
❗Solution
function solution(name, yearning, photo) {
var answer = [];
for(let i = 0; i < photo.length; i++){
let sum = 0;
let num = 0;
for(let j = 0; j < 100; j++){
if(name.includes(photo[i][j]) ){
num = name.indexOf(photo[i][j])
sum += yearning[num];
}
}
answer.push(sum);
}
return answer;
}
/// 1. photo의 배열길이와 제한사항 100으로 이중배열을 돌린다.
/// 2. name 배열 안에 photo안에 동일한 게 있다면
/// 3. name의 indexOf번호를 알아내서
/// 4. sum값에 더해준다.
/// 5. answer값에 넣어준다.
💯Study
Array.prototype.includes()
const array = [1, 2, 3];
console.log(array.includes(2));
// Expected output: true
const animal = ['elephant', 'tiger', 'rabbit'];
console.log(pets.includes('tiger'));
// Expected output: true
console.log(pets.includes('bit'));
// Expected output: false
String.prototype.includes()
const sentence = 'The quick brown fox jumps over the lazy dog.';
const word = 'fox';
console.log(`The word "${word}" ${sentence.includes(word) ? 'is' : 'is not'} in the sentence`);
// Expected output: "The word "fox" is in the sentence"
includes() 메서드는 하나의 문자열이 다른 문자열에 포함되어 있는지를 판별하고, 결과를 true 또는 false 로 반환한다.
대소문자를 구분한다.
includes(searchElement, fromIndex)
'abcdefg'.includes( 'e', 2 )
cdefg가 e를 포함하는지 검사한다. e를 포함하므로 true를 반환한다.
'abcdefg'.includes( 'e', 5 )
fg가 e를 포함하는지 검사한다. e를 포함하지 않으므로 false를 반환한다
Array.prototype.indexOf()
indexOf() 메서드는 배열에서 지정된 요소를 찾을 수 있는 첫 번째 인덱스를 반환하고 존재하지 않으면 -1을 반환한다.
const name = ['karina', 'jamie', 'hana', 'jenny', 'winter'];
console.log(beasts.indexOf('winter'));
// Expected output: 4
// Start from index 2
console.log(beasts.indexOf('jamie', 2));
// Expected output: 4
console.log(beasts.indexOf('wonyeong'));
// Expected output: -1
Reference
'Coding Test > Programmers' 카테고리의 다른 글
[Programmers JavaScript] Lv.1 덧칠하기 (0) | 2023.10.18 |
---|---|
[Programmers JavaScript] Lv.0 배열 조각하기 (0) | 2023.10.05 |
[Programmers JavaScript] Lv.0 옹알이(1) (2) | 2023.09.25 |