Saturday, 27 July 2013

Chapter 3 Solutions Problem [B][f]

Question-Write a program for a matchstick game being played between the computer and a user. Your program should ensure that the computer always wins. Rules for the game are as follows:
− There are 21 matchsticks.
− The computer asks the player to pick 1, 2, 3, or 4 matchsticks.
− After the person picks, the computer does its picking.
− Whoever is forced to pick up the last matchstick loses the game.
Solution-
Pretty interesting question. i bet you wouldn't wanna miss this one.Here is the solution.

#include<stdio.h>
int main()
{
int n,a,b;
n=21;
while(n>1)
{
printf("Enter numbers of matchsticks you want to pick up\n");
scanf("%d",&a);
n=n-a;
printf("Left matchsticks=%d\n",n);
b=5-a;     /* This is the trick you have to figure out,this will make eventually computer win*/
printf("Computer picks=%d\n",b);
n=n-b;
printf("Left matchsticks=%d\n",n);
}
if(n==1)
printf("You lost,Better luck next time :p\n");
return 0;
}

5 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Not Correct Above Code for MatchStick Game, Right code are given below!

    int n,a,b;
    n=21;
    while(n>1)
    {
    printf("Enter numbers of matchsticks you want to pick up\n");
    scanf("%d",&a);

    if(a > 4 || a < 1)
    {
    printf("Eror!Enter Correct choice between 1 and 5\n");
    continue;
    }

    n=n-a;
    printf("Left MatchStick After Player picks=%d\n",n);
    b=5-a;
    printf("Computer picks=%d\n",b);
    n=n-b;
    printf("Left matchsticks=%d\n",n);
    }
    if(n==1)
    printf("You lost,:(\n");

    ReplyDelete
  3. Good Work Vikas Bro! Keep coming your Solution.Thanks

    ReplyDelete
  4. Thanks man ! i appreciate your work . i will correct my mistake ..

    ReplyDelete