Bowling Pins


Problem Statement :


Bowling is a sport in which a player rolls a bowling ball towards a group of pins, the target being to knock down the pins at the end of a lane.

In this challenge, the rules of the game are slightly modified. Now, there are a given number of pins, and the pins are arranged in a horizontal line instead of a triangular formation. Two players have to play this game, taking alternate turns. Whoever knocks down the last pin(s) will be declared the winner.

You are playing this game with your friend, and both of you have become proficient at it. You can knock down any single pin, or any two adjacent pins at one throw of a bowling ball, however, these are the only moves that you can perform. Some moves have already been played. Suddenly, you realize that it is possible to determine whether this game can be won or not, assuming optimal play. And luckily it's your turn right now.

A configuration is represented by a string consisting of the letters X and I, where:

I represents a position containing a pin.
X represents a position where a pin has been knocked down.
An example of such a configuration is shown in the image below. Here, the number of pins is , and the  pin has already been knocked down.


Its representation will be IXIIIIIIIIIII.

Complete the function isWinning that takes the number of pins and the configuration of the pins as input, and return WIN or LOSE based on whether or not you will win.

Given the current configuration of the pins, if both of you play optimally, determine whether you will win this game or not.

Note

A player has to knock down at least one pin in his turn.
Both players play optimally.
Input Format

The first line contains an integer, , the number of test cases. Then  test cases follow.

For each test case, the first line contains a single integer , denoting the number of pins. The second line contains a string of  letters, where each letter is either I or X.


Output Format

For each test case, print a single line containing WIN if you will win this game, otherwise LOSE.



Solution :



title-img


                            Solution in C :

In  C  :






#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char str[301];
int dp[301],a[4000];

int main(){
  int T,N,c,i,j;
  for(dp[0]=0,i=1;i<301;i++){
    memset(a,0,sizeof(a));
    for(j=0;j<=i-1-j;j++)
      a[dp[j]^dp[i-1-j]]=1;
    for(j=0;j<=i-2-j;j++)
      a[dp[j]^dp[i-2-j]]=1;
    for(j=0;a[j];j++);
    dp[i]=j;
  }
  scanf("%d",&T);
  while(T--){
    scanf("%d%s",&N,str);
    for(i=c=j=0;i<N;i++){
      if(str[i]=='I')
        c++;
      else if(str[i]=='X' && i && str[i-1]=='I'){
        j^=dp[c];
        c=0;
      }
    }
    j^=dp[c];
    if(j)
      printf("WIN\n");
    else
      printf("LOSE\n");
  }
  return 0;
}
                        


                        Solution in C++ :

In  C++  :








#include <cmath>
#include <cstdio>
#include <vector>
#include <set>
#include <iostream>
#include <algorithm>
using namespace std;

const int Maxn = 305;

int nim[Maxn];
int t;
int n;
char str[Maxn];

int main() {
    for (int i = 1; i < Maxn; i++) {
        set <int> S;
        for (int j = 0; j < i; j++)
            S.insert(nim[j] ^ nim[i - 1 - j]);
        for (int j = 0; j + 1 < i; j++)
            S.insert(nim[j] ^ nim[i - 2 - j]);
        while (S.find(nim[i]) != S.end()) nim[i]++;
    }  
    scanf("%d", &t);
    while (t--) {
        scanf("%d", &n);
        scanf("%s", str);
        int res = 0;
        for (int i = 0; i < n; i++) if (str[i] == 'I') {
            int j = i;
            while (j < n && str[j] == 'I') j++;
            res ^= nim[j - i];
            i = j;
        }
        printf("%s\n", res? "WIN": "LOSE");
    }
    return 0;
}
                    


                        Solution in Java :

In  Java :







import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

	static int[] nim = new int[301];

	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		int t = in.nextInt();
		while(t-- > 0) {
			int n = in.nextInt();
			String s = in.next();
			List<Integer> list = new ArrayList<Integer>();
			int count = 0;
			for(int i = 0; i < s.length(); i++) {
				char ch = s.charAt(i);
				if(ch == 'I') {
					count++;
				} else {
					if(count != 0)
						list.add(count);
					count = 0;
				}
			}
			if(count > 0)
				list.add(count);

			int result = 0;
			for(int i = 0; i < list.size(); i++) {
				result ^= grundy(list.get(i));
			}
			if(result <= 0) {
				System.out.println("LOSE");
			} else {
				System.out.println("WIN");
			}
		}
		in.close();
	}

	private static int mex(List<Integer> arr) {
		int mex = 0;
		while(arr.contains(mex))
			mex++;
		return mex;
	}

	private static int grundy(int n) {
		if(nim[n] != 0)
			return nim[n];
		if(n == 0) {
			nim[0] = 0;
			return 0;
		}
		if (n == 1) {
			nim[1] = 1;
	        return (1);
		}
	    if (n == 2) {
			nim[2] = 2;
	        return (2);
	    }

		List<Integer> list = new ArrayList<Integer>();
		for(int i = 1, j = 0, k = 0; i <= n; i++) {
			int x, y;
			if(i <= n / 2) {
				x = grundy(j);
				y = grundy(n - j - 2);
				j++;
			} else {
				x = grundy(k);
				y = grundy(n - k - 1);
				k++;
			}
			list.add(x ^ y);
		}
		nim[n] = mex(list);
		return nim[n];
	}
}
                    


                        Solution in Python : 
                            
In  Python3 :






def game_from(board: str) -> list:
    game = []
    count = 0
    for c in board:
        if c == 'I':
            count += 1
        elif count > 0:
            game.append(count)
            count = 0
    if count > 0:
        game.append(count)
    return game


def moves_for(n: int, hits: [int]) -> [list]:
    moves = []
    for hit in hits:
        left = 0
        right = n - hit
        while left <= right:
            if left == 0 and right == 0:
                continue
            elif right < 1 <= left:
                moves.append([left])
            elif left < 1 <= right:
                moves.append([right])
            else:
                moves.append([left, right])
            left += 1
            right -= 1
    return moves


def mex_of(s: set) -> int:
    mex = 0
    while mex in s:
        mex += 1
    return mex


def g_of(n: int, cache: dict) -> int:
    if n < 3:
        return n
    else:
        result = cache.get(n, None)
        if result is not None:
            return result
        moves = moves_for(n, [1,2])
        s = set()
        for move in moves:
            if len(move) == 1:
                s.add(g_of(move[0], cache))
            else:
                s.add(g_of(move[0], cache) ^ g_of(move[1], cache))
        result = mex_of(s)
        cache[n] = result
        return result


def winner(board: str, cache: dict) -> str:
    game = game_from(board)
    g = 0
    for i in game:
        g ^= g_of(i, cache)
    return 'WIN' if g != 0 else 'LOSE'


n = int(input().strip())
c = {}

for i in range(n):
    input()
    g = list(input().strip())
    print(winner(g, c))
                    


View More Similar Problems

Simple Text Editor

In this challenge, you must implement a simple text editor. Initially, your editor contains an empty string, S. You must perform Q operations of the following 4 types: 1. append(W) - Append W string to the end of S. 2 . delete( k ) - Delete the last k characters of S. 3 .print( k ) - Print the kth character of S. 4 . undo( ) - Undo the last (not previously undone) operation of type 1 or 2,

View Solution →

Poisonous Plants

There are a number of plants in a garden. Each of the plants has been treated with some amount of pesticide. After each day, if any plant has more pesticide than the plant on its left, being weaker than the left one, it dies. You are given the initial values of the pesticide in each of the plants. Determine the number of days after which no plant dies, i.e. the time after which there is no plan

View Solution →

AND xor OR

Given an array of distinct elements. Let and be the smallest and the next smallest element in the interval where . . where , are the bitwise operators , and respectively. Your task is to find the maximum possible value of . Input Format First line contains integer N. Second line contains N integers, representing elements of the array A[] . Output Format Print the value

View Solution →

Waiter

You are a waiter at a party. There is a pile of numbered plates. Create an empty answers array. At each iteration, i, remove each plate from the top of the stack in order. Determine if the number on the plate is evenly divisible ith the prime number. If it is, stack it in pile Bi. Otherwise, stack it in stack Ai. Store the values Bi in from top to bottom in answers. In the next iteration, do the

View Solution →

Queue using Two Stacks

A queue is an abstract data type that maintains the order in which elements were added to it, allowing the oldest elements to be removed from the front and new elements to be added to the rear. This is called a First-In-First-Out (FIFO) data structure because the first element added to the queue (i.e., the one that has been waiting the longest) is always the first one to be removed. A basic que

View Solution →

Castle on the Grid

You are given a square grid with some cells open (.) and some blocked (X). Your playing piece can move along any row or column until it reaches the edge of the grid or a blocked cell. Given a grid, a start and a goal, determine the minmum number of moves to get to the goal. Function Description Complete the minimumMoves function in the editor. minimumMoves has the following parameter(s):

View Solution →