Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a program that plays the ancient Chinese game of NIM. Actually, this is a

ID: 3654366 • Letter: W

Question

Write a program that plays the ancient Chinese game of NIM. Actually, this is a simplified version of the game. Each game starts with a certain number of stones in a pile. The user and the computer take turns removing either one or two stones for each of their moves. The player who takes the last stone loses. Your program should have the computer use the optimal playing strategy. The optimal strategy is as follows: Divide the remaining number of stones by three. If the remainder is zero, then two stones are removed, else one stone is removed. For example, if the remaining number of stones is nine or fifteen, then two stones are removed; if the remaining number of stones is eight or ten, then one stone is removed. Your program should allow the user to play additional games of NIM as long as he/she enters a ''y" or "yes" (lowercase or uppercase) in response to a "Do you want to play again?" prompt. See the sample session for required wording.

Explanation / Answer

please rate - thanks error checking can be added but your sample run didn't have any
if any problems message me

import java.util.*;
public class nim
{
public static void main(String[] args)
{int stones,move;
char choice;
int turn=0;   //0=person, 1=computer
Scanner in = new Scanner(System.in);
do
{
System.out.println("T H E G A M E O F N I M");
System.out.print("Enter number of starting stones: ");
stones=in.nextInt();
System.out.print("Would you like to go first? (y/n): ");
choice=in.next().charAt(0);
if(choice=='y')
      turn=0;
else
      turn=1;
while(stones>0)
{
    if(turn==0)
        { System.out.print("How many would you like to remove – 1 or 2? ");
         move=in.nextInt();
           }
    else
       { if(stones%3==0)
            move=2;
        else
            move=1;
        System.out.println("The computer removes "+move+" stones.");
       }
    stones-=move;
   System.out.println("The number of stones left is "+stones);
   if(stones==0)
      if(turn==0)
         System.out.println("The computer wins!");
      else
            System.out.println("The human wins!");
   turn=1-turn;
}  
System.out.print("Do you want to play again?: ");
choice=in.next().charAt(0);
}while(choice=='y');
       
}
}
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote