Skip to content

Conversation

tiaz0128
Copy link
Contributor

@tiaz0128 tiaz0128 commented Aug 10, 2021

2-1. 큰 수 출력하기

  • Array.filter 를 이용하여 문제를 풀이
  • 첫번째는 무조건 포함이므로 ture 리턴
  • 이후부터는 인덱스값을 이용하여 이전값과 비교

2-2. 보이는 학생

  • Array.filter 를 이용하여 문제를 풀이
  • 자신의 차례에서 이전까지 가장 키가 큰 사람보다 크면 true

2-3. 가위바위보

  • 풀이1. switch case 문으로 풀이
  • 풀이2. switch case 와 동일한 기능을 객체에 함수를 담아서 호출 하는 형태로 변경
  • 상수값을 적극적으로 이용
  • 변수명을 사용해서 오브젝트를 키값으로 쓰기 위해서 [변수명] : 값

2-4. 점수 계산

  • 누적 점수 변수값 score 를 사용하여 1인 경우 계속 증가
  • 0 인 경우는 score 값을 0으로 초기화

2-5. 등수구하기

  • 중첩 반복문을 사용
  • 다른 값들과 비교하여 등수를 체점

2-6. 격자판 최대합

  • 행, 열 의 합을 구하는 반복문
  • 위에서 가장 큰 값을 max 변수에 보관
  • 두 개의 대각선의 합을 구하는 반복문
  • 두 개의 대각선의 합과 행, 열 중에서 가장 큰 합 중에 최종적으로 큰값 리턴

2-7. 봉우리

  • 강사님 풀이가 가장 합리적인 듯 합니다.
  • 다른 방법으로 풀어봤습니다!
let arr=[[5, 3, 7, 2, 3], 
         [3, 7, 1, 6, 1],
         [7, 2, 5, 3, 4],
         [4, 3, 6, 4, 1],
         [8, 7, 3, 5, 2]];

1. 2차원 배열에서 인덱스

  • 2차원 배열의 경우 행에 해당하는 첫번째 인덱스가 범위를 넘어가면 에러 발생
  • 두번쨰 인덱스가 범위를 넘어가면 undefined
arr[-1]  // undefined
arr[-1][0]  // Uncaught TypeError: Cannot read property '0' of undefined
arr[0][5] // undefined

2. 2차원 배열에 시작과 끝에 0으로 채워진 배열 추가

  • 위에서 확인 것처럼 2차원 배열에서 첫번째 인덱스가 범위를 벗어난 경우 에러 발생
  • 이러한 에러를 막기 위해서 0 으로 구성된 배열을 시작과 끝에 추가
const dummy = Array.from({length : len}, () => 0

arr.splice(0, 0, dummy)
arr.push(dummy)

0 0 0 0 0 
5 3 7 2 3 
3 7 1 6 1 
7 2 5 3 4 
4 3 6 4 1 
8 7 3 5 2 
0 0 0 0 0 

3. 두번쨰 인덱스를 벗어나는 경우 undefined

  • 두번째 인덱스가 벗어나면 undefined 를 리턴한다.
  • undefined 는 숫자와 비교연산시 무조건 false 처리 된다.
  • 이것을 방지하기 위해서 undefined 인 경우 0으로 변경
  • || 연산자를 이용하여 처리
const up    = arr[i-1][j] || 0
const down  = arr[i+1][j] || 0
const left  = arr[i][j-1] || 0
const right = arr[i][j+1] || 0

4. 상하좌우 값보다 큰 경우는 카운팅

if(arr[i][j] > up && arr[i][j] > down && arr[i][j] > left && arr[i][j] > right) {
 cnt++
}

@tiaz0128 tiaz0128 self-assigned this Aug 10, 2021
Comment on lines +37 to +40
const up = (arr[i-1] ?? [])[j] ?? 0
const down = (arr[i+1] ?? [])[j] ?? 0
const left = (arr[i] ?? [])[j-1] ?? 0
const right = (arr[i] ?? [])[j+1] ?? 0
Copy link
Contributor Author

@tiaz0128 tiaz0128 Aug 11, 2021

Choose a reason for hiding this comment

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

봉우리 더미 없이 처리하기

  • 표현식을 평가하는 과정을 다시 한번 생각해보고 변경해봤습니다.
  • 더미 없이도 2차원 배열에서 인덱스를 벗어나는 에러를 처리 할 수 있는 방법

2차원 배열의 표현식 평가 순서

arr[0][1]
  1. 위의 표현식에서는 arr[0] 가 먼저 평가 되서 결과가 나옵니다.
  2. 여기서 나오는 값이 1차원 배열이 되는 경우를 생각해봅니다.
  3. 예를 들어 [1,2,3,4,5] 와 같은 배열이 오고 여기서 다시 두번째 인덱스 [1] 가 평가됩니다.
arr[0][1] // arr[0] 을 먼저 평가한다.

[1, 2, 3, 4, 5][1] // arr[0] 을 평가 한 결과 1차원배열에서 1번 인덱스 값을 구한다.

// 만약 첫번째 인덱스의 평가결과가 undefined 인 경우는 
// undefined 에서 인덱스를 구하려고 하니 에러 발생
undefined[j] 
  1. 즉 괄호 안에서 첫번째 인덱스를 벗어난 경우 undefined 가 오는 경우를 ?? 연산자를 통해서 빈 배열로 변경하면 인덱스를 벗어난 에러를 방지 할 수 있습니다.
(arr[i-1] ?? [ ])[j]

(undefined ?? [ ])[j]

[ ][j] // undefined
  1. 최종적으로 undefined 가 나온경우 아래의 if 문에서 숫자와 비교연산이 false 가 되므로 0으로 변환 처리
undefined ?? 0

0

Copy link
Contributor

Choose a reason for hiding this comment

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

Nullish coalescing operator 잘 사용하셨네요!

Copy link
Contributor

@goawmfhfl goawmfhfl left a comment

Choose a reason for hiding this comment

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

  • [Review] up to 2-3

@@ -0,0 +1,8 @@
function solution(arr){
return arr.filter((n, i) => {
Copy link
Contributor

Choose a reason for hiding this comment

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

와 filter를 이렇게 활용하시다니!!! 엄청나네요

첫번째 값은 무조건 보여야하니깐 if조건문을 통해서 return으로 출력하셨고
나머지는 filter의 매개변수 index를 활용해서 for문처럼 순회하고 조건에 맞는 값을 filter에 콜백하셨네요 !!
ㅋㅋㅋ 감사합니다 배워갑니다 👍🏻 ✏️✏️✏️

Copy link
Contributor

Choose a reason for hiding this comment

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

문제풀이

  • filter매서드를 활용
  • if문을 통해서 첫 번째 값 출력
  • else문을 통해서 나머지 값을 순회하며 조건에 일치하는 값을 filter에 저장
  • filter에 저장된 값 arr에 다시 배열로 할당 후 출력

return true
}

}).length
Copy link
Contributor

Choose a reason for hiding this comment

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

마지막에 .length를 통해서 filter에 콜백된 값의 길이를 구할수도있네요 ㅎㅎ 👍🏻👍🏻👍🏻
덕분에 filter에 대해서 복습해보는 시간을 가졌어요 !ㅋㅋㅋㅋ

Copy link
Contributor Author

Choose a reason for hiding this comment

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

코드 리뷰 감사합니다!
재영님 보면서 늘 좋은 동기부여 받아갑니다!
꾸준히 하시면 목표하는 바 꼭 이루실수 있을거에요!

Copy link
Contributor

@goawmfhfl goawmfhfl left a comment

Choose a reason for hiding this comment

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

[0813 Algorithm Study] 문제풀어보기

@@ -0,0 +1,8 @@
function solution(arr){
return arr.filter((n, i) => {
Copy link
Contributor

Choose a reason for hiding this comment

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

문제풀이

  • filter매서드를 활용
  • if문을 통해서 첫 번째 값 출력
  • else문을 통해서 나머지 값을 순회하며 조건에 일치하는 값을 filter에 저장
  • filter에 저장된 값 arr에 다시 배열로 할당 후 출력

}

console.log(solution([2,3,3,1,3],[1,1,2,2,3]))

Copy link
Contributor

Choose a reason for hiding this comment

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

문제풀이

  • 전달받은 인자 a에 map 메서드를 활용 메서드는 배열 내의 모든 요소 각각에 대하여 주어진 함수를 호출한 결과를 모아 새로운 배열을 반환한다.
  • aTu 매개변수에 모든 요소 각각에 대하여 함수를 적용한다
  • currentValue = 처리할 현재요소 (aTu)
  • index = 처리할 현재 요소의 인덱스(i)
  • aTu를 이용하여 A의 값들을 구해옴
  • i를 통하여 B 배열의 인덱스로 접근하여 값들을 구해옴
  • switch의 Case문을 통과한 경우 A가 이긴경우 콜백 그렇지 않을 경우 B 콜백

})
}

console.log(solution2([2,3,3,1,3],[1,1,2,2,3]))
Copy link
Contributor

Choose a reason for hiding this comment

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

아직 이해 못한 부분

  1. isWinner[itemA](itemB)의 값이 리턴되어 isWinner 의 target으로 전달되는 로직이 궁금함
  2. [RPS.SCISSORS] : (target) => {return target === RPS.PAPER ? 'A' : 'B' }
  3. 2번 부분의 로직이 어떻게 평가되고 있는지가 궁금함.

Copy link
Contributor Author

@tiaz0128 tiaz0128 Aug 13, 2021

Choose a reason for hiding this comment

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

1. 함수를 가지고 오는 것과 함수를 호출하는 차이

  • 함수는 호출하기 위해서는 괄호를 사용해야 합니다.
  • 괄호가 있고 없을때 어떻게 나오는지 생각해보시면 될듯합니다.
const arr = [1, 2, 3]

arr.join

arr.join( )

2. 변수값으로 객체의 속성에 접근하기

  • 일반적으로 객체의 속성을 접근할때는 객체.속성 식으로 사용합니다.
  • 이 방법말고 방법이 더 있는데요 객체["속성의 문자열"]
  • 그리고 여기서 사용한 객체[변수] 가 있습니다.
  • 속성 접근 연산자인 . 은 변수와 같이 사용하 못하기 때문에 위와 같이 대괄호를 사용합니다.
const arr = [1, 2, 3]
const key = 'join'

arr.join
arr["join"]

arr.key  // 에러발생! 변수값과 속성 접근 연산자 . 과 같이 사용 불가
arr[key] // [ ] 와 같이 변수는 사용가능

Copy link
Contributor

Choose a reason for hiding this comment

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

지금 다시보니깐 이해가되었어요 ㅎㅎㅎㅎ 친절한 설명 감사합니다 통붕이님 !

Copy link
Contributor

Choose a reason for hiding this comment

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

상수 활용하는 부분 좋은 거 같아요. 그리고 그걸 활용해서 isWinner 객체 만든 것도 좋았습니다. 역시 실무에서오는 짬이 느껴지는거같은데요 ㅎㅎ

})
}

console.log(solution([87,89,92,100,76]))
Copy link
Contributor

Choose a reason for hiding this comment

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

문제풀이

  • map 메서드는 배열 내의 모든 요소 각각에 대하여 주어진 함수를 호출한 결과를 모아 새로운 배열을 반환한다.
  • item : 모든 요소 (item) 각각에 대하여 함수를 적용한 후 콜백
  • idx: arr 배열의 index 값
  • ori: arr 배열의 오리지널 값
  • 0등은 존재하지 않으니 score을 1로 초기화
  • forEach 메서드 내의 조건문을 통해서 score에 값 arr에 콜백
  • 맵 매서드에 의해 forEach문도 총 5번 실행함에 따라 arr에 score로 인하여 카운팅 된 값 할당후 출력

@goawmfhfl goawmfhfl merged commit 7f60d58 into master Sep 3, 2021
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