HR - Save the Prisoner!

Goody·2021년 1월 29일
0

알고리즘

목록 보기
22/122

문제

A jail has a number of prisoners and a number of treats to pass out to them. Their jailer decides the fairest way to divide the treats is to seat the prisoners around a circular table in sequentially numbered chairs. A chair number will be drawn from a hat. Beginning with the prisoner in that chair, one candy will be handed to each prisoner sequentially around the table until all have been distributed.

The jailer is playing a little joke, though. The last piece of candy looks like all the others, but it tastes awful. Determine the chair number occupied by the prisoner who will receive that candy.

  • Example
    n = 4
    m = 6
    s = 2

There are 4 prisoners,6 pieces of candy and distribution starts at chair 2 .
The prisoners arrange themselves in seats numbered 1 to 4.
Prisoners receive candy at positions 2,3,4,1,2,3 .
The prisoner to be warned sits in chair number 3 .

예시

INPUT 1

2
5 2 1
5 2 2

OUTPUT 1

2
3

INPUT 2

2
7 19 2
3 7 3

OUTPUT 2

6
3

풀이

  • 죄수가 n명, 캔디가 m개, 첫 캔디를 먹는s번 죄수가 있을 때, 마지막 캔디를 먹는 죄수번호를 구하는 문제이다.
  • 캔디 개수를 사람 수만큼 나누고 남은 나머지만큼 s를 더하면, 마지막 캔디를 먹는 죄수의 번호를 구할 수 있다.

코드

function saveThePrisoner(n, m, s) {

    let last = s + (m % n) - 1;

    if (last > n) last -= n;
    else if (last === 0) last = n;

    return (last);
}

0개의 댓글