CodeWars 코딩 문제 2021/04/12 - Handshake problem

이호현·2021년 4월 12일
0

Algorithm

목록 보기
99/138

[문제]

Johnny is a farmer and he annually holds a beet farmers convention "Drop the beet".

Every year he takes photos of farmers handshaking. Johnny knows that no two farmers handshake more than once. He also knows that some of the possible handshake combinations may not happen.

However, Johnny would like to know the minimal amount of people that participated this year just by counting all the handshakes.

Help Johnny by writing a function, that takes the amount of handshakes and returns the minimal amount of people needed to perform these handshakes (a pair of farmers handshake only once).

(요약) 사람들이 서로 한 번씩만 악수를 할 때 주어진 악수 횟수가 되려면 최소 몇명이 필요한가?

[풀이]

function getParticipants(handshakes){
  if(!handshakes) return 1;

  let answer = 0;
  let sum = 0

  while(handshakes > sum) {
    sum = answer * (answer + 1) / 2;

    answer++;
  }

  return answer;
}

규칙을 찾아보면 사람수가 한 명 늘어날 때마다 계차수열의 형태로 증가한다.

계차수열이란?

등차수열이 각 수열 요쇼의 차가 일정한 것이라면 계차수열은 수열 요소의 차가 등차수열인 것을 말한다.

EX)
등차수열: 0, 1, 2, 3, 4, ...
수열 요소의 차가 1로 일정

계차수열: 0, 1, 3, 6, 10, ...
수열 요소의 차가 1, 2, 3, 4, ...로 등차수열의 성질을 가짐

문제에서 각 요소는 차가 1인 등차수열의 합과 같다.

그렇기에 우선 0일 때는 예시에 있는걸 이용해서 1을 return하고, 1이상 일 때는 등차수열의 합을 이용해 답을 구하면 된다.

profile
평생 개발자로 살고싶습니다

0개의 댓글