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

Tree: Inorder Traversal

In this challenge, you are required to implement inorder traversal of a tree. Complete the inorder function in your editor below, which has 1 parameter: a pointer to the root of a binary tree. It must print the values in the tree's inorder traversal as a single line of space-separated values. Input Format Our hidden tester code passes the root node of a binary tree to your $inOrder* func

View Solution →

Tree: Height of a Binary Tree

The height of a binary tree is the number of edges between the tree's root and its furthest leaf. For example, the following binary tree is of height : image Function Description Complete the getHeight or height function in the editor. It must return the height of a binary tree as an integer. getHeight or height has the following parameter(s): root: a reference to the root of a binary

View Solution →

Tree : Top View

Given a pointer to the root of a binary tree, print the top view of the binary tree. The tree as seen from the top the nodes, is called the top view of the tree. For example : 1 \ 2 \ 5 / \ 3 6 \ 4 Top View : 1 -> 2 -> 5 -> 6 Complete the function topView and print the resulting values on a single line separated by space.

View Solution →

Tree: Level Order Traversal

Given a pointer to the root of a binary tree, you need to print the level order traversal of this tree. In level-order traversal, nodes are visited level by level from left to right. Complete the function levelOrder and print the values in a single line separated by a space. For example: 1 \ 2 \ 5 / \ 3 6 \ 4 F

View Solution →

Binary Search Tree : Insertion

You are given a pointer to the root of a binary search tree and values to be inserted into the tree. Insert the values into their appropriate position in the binary search tree and return the root of the updated binary tree. You just have to complete the function. Input Format You are given a function, Node * insert (Node * root ,int data) { } Constraints No. of nodes in the tree <

View Solution →

Tree: Huffman Decoding

Huffman coding assigns variable length codewords to fixed length input characters based on their frequencies. More frequent characters are assigned shorter codewords and less frequent characters are assigned longer codewords. All edges along the path to a character contain a code digit. If they are on the left side of the tree, they will be a 0 (zero). If on the right, they'll be a 1 (one). Only t

View Solution →