Skip to content

Conversation

@tkddbs587
Copy link
Collaborator

[배열]

  • 간단한 알고리즘에 대한 설명
  • 배열 메서드들 다시 한번 싹 훑는다는 느낌으로 해봤습니다

📌 푼 문제

문제이름 문제링크
배열 자르기 https://school.programmers.co.kr/learn/courses/30/lessons/120833
배열 원소의 길이 https://school.programmers.co.kr/learn/courses/30/lessons/120854
배열 회전시키기 https://school.programmers.co.kr/learn/courses/30/lessons/120844
중복된 숫자 개수 https://school.programmers.co.kr/learn/courses/30/lessons/120583
제일 작은 수 제거하기 https://school.programmers.co.kr/learn/courses/30/lessons/12935
나누어 떨어지는 숫자 배열 https://school.programmers.co.kr/learn/courses/30/lessons/12910
행렬의 덧셈 https://school.programmers.co.kr/learn/courses/30/lessons/12950

📝 간단한 풀이 과정

배열 자르기

  • slice() 메서드로 매개변수로 주어진 인덱스 활용해서 자른 배열 반환

배열 원소의 길이

  • map() 메서드를 아시나요 문제. map()으로 각 string의 length로 이루어진 새 배열 반환

배열 회전시키기

  • 오른쪽 회전이면 pop() 으로 마지막 원소 빼서 맨 앞에 붙이고, 왼쪽 회전이면 shift()로 맨 앞에 원소 빼서 맨 뒤에 붙이고

중복된 숫자 개수

  • filter() 메서드로 엘리먼트 순회하며 el === n 으로 몇개 들었나 확인한 배열의 length 반환

제일 작은 수 제거하기

function solution(arr) {
    let minNum = Math.min(...arr) // 전개 연산자로 제일 작은 수 반환
    for(let i = 0; i < arr.length; i++) { 
        if(arr[i] === minNum) { // 배열 순회하며 제일 작은 수 찾으면
            arr.splice(i, 1) // 작은 수 하나 제거
            if(arr.length === 0) { // 작은 수 제거 후 빈 배열이면 
                arr.push(-1) // -1 반환
            }
        }
    }
    return arr;
}

나누어 떨어지는 숫자 배열

function solution(arr, divisor) {
  let newArr = arr.filter((el) => el % divisor === 0); // 나누어 떨어지는 엘리먼트가 담긴 새 배열 반환

  // 나누어 떨어지는 엘리먼트 없으면 그냥 [-1] 반환
  if (newArr.length === 0) {
    return [-1];
  }

  return newArr.sort((a, b) => a - b); // 오름차순 정렬
}

행렬의 덧셈

  • 중첩 for문으로 맞는 인덱스 접근 후 덧셈 후 push 이용해서 새 배열 만듦
function solution(arr1, arr2) {
    let answer = [];

    for (let i = 0; i < arr1.length; i++) {
        let newRow = [];
        
        for (let j = 0; j < arr1[i].length; j++) {
            newRow.push(arr1[i][j] + arr2[i][j]);
        }
        
        answer.push(newRow);
    }

    return answer; 
}

@tkddbs587 tkddbs587 self-assigned this Jan 2, 2025
Copy link
Collaborator

@oh-chaeyeon oh-chaeyeon left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

전체적으로 가독성 좋은 간결한 코드로 많이 배우고 갑니다~~ 수고하셨습니다😃

Comment on lines +4 to +11
for (let i = 0; i < arr1.length; i++) {
let newRow = [];

for (let j = 0; j < arr1[i].length; j++) {
newRow.push(arr1[i][j] + arr2[i][j]);
}
answer.push(newRow);
}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

지금도 잘 작동하지만, 가독성면에서 조금 떨어지는 이중 for문을 더 간결하게 할수 있는지 생각을 해봤는데, 이렇게 arr1.entries()push메서드를 사용하는 방법은 어떤가 생각해 봤습니다.

 for (const [i, row] of arr1.entries()) {
  answer.push(row.map((value, j) => value + arr2[i][j]));
}

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

와우,, 이렇게까지 해주시다니 코테 왕초보라 모르는 메서드들 너무 많아요 감사합니다 채연님!

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

filter메서드랑 sort메서드 사용해서 간단하게 처리하신것 같습니다👍👍
다만, 더 간결하게 코드를 하고 싶다면, 이런식으로도 하셔도 좋을것 같습니다:)

function solution(arr, divisor) {
  const result = arr.filter((el) => el % divisor === 0).sort((a, b) => a - b);
  return result.length ? result : [-1]; 
}

근데,성능테스트했을때는 딱히 차이는 안나긴 했습니다...

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

오 sort() 까지 한곳에서 해결하고 삼항 연산자로 하니까 훨씬 간결해졌네요! 👍🏻

Comment on lines +3 to +11
for (let i = 0; i < arr.length; i++) {
if (arr[i] === minNum) {
arr.splice(i, 1);
if (arr.length === 0) {
arr.push(-1);
}
}
}
return arr;
Copy link
Collaborator

@oh-chaeyeon oh-chaeyeon Jan 6, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

지금도 좋지만, for문 내부에서 splice메서드를 사용하면 배열의 길이가 변해서 불필요한 계산이 발생할 수 있다고 생각합니다... filter를 사용하면 배열을 다시 생성하면서 최소값만 제외할 수 있어서, 이떄는 filter를 사용하는걸 추천합니다👍

const filteredArr = arr.filter((num) => num !== minNum); 
return filteredArr.length ? filteredArr : [-1]; 

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

for문에서 splice 쓰면 정말 그렇겠네요 이런 방법이! 감사합니다 🤩

@JooKangsan JooKangsan merged commit ac78afe into codingTestStd:main Jan 9, 2025
0 of 3 checks passed
bona1122 pushed a commit to bona1122/AlgorithmStudy that referenced this pull request Jan 9, 2025
* Array slicing / 기초

* Length of array elements / 기초

* Rotate array / 기초

* Divisible number array / 중급

* Remove_smallest_number / 중급

* Matrix addition / 중급
@tkddbs587 tkddbs587 requested review from oh-chaeyeon and removed request for JooKangsan and oh-chaeyeon January 9, 2025 12:55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants