In this lockdown a family of N members decided to play a game the rules of which are :-
- All N members are made to sit uniformly in a circle (ie. from 1 to N in clockwise direction).
- The game start with the person sitting at first position.
- A song is played in the background. The lyrics of the song are denoted by a string which consists of only letters 'x' and 'y'. Assume that each lyric of the song is a single letter.
- If the lyric 'x' occurs in the song, the member who is currently holding the Parcel passes it on to the next member. This passing takes place in clockwise direction.
- If the lyric 'y' occurs in the song, the member who is currently holding the Parcel loses his/her chances of winning the game. He/she hands over the parcel to the next member (in clockwise direction) and moves out.
- The game continues until a single member survives in the end. He/she will be the winner of the game.
- Note that the song repeats continuously ie. while the game is going on, if at all the song ends, the stereo system will automatically start playing the song from the start without any delay.
You have to find out the member who wins the game.
Example:
Input: n=3, s="xyz"
Output: 1
Approach
Java
public class LockdownGame {public static void main(String args[]) {int n = 3;String s = "xyz";System.out.println(lockJosehous(n, s, 0));}public static int lockJosehous(int n, String s, int i) {if (n == 1)return 1;if (i == s.length())i = 0;if (s.charAt(i) == 'x')return lockJosehous(n, s, i + 1) % n + 1;elsereturn lockJosehous(n - 1, s, i + 1) % n + 1;}}
No comments:
Post a Comment