Java The Game of Nim This is a wellknown game with a number
Solution
Hope this will help -
import java.util.Scanner;
public class P4_22 {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int size_of_pile = (int) (Math.random() * 91) + 10;
int current_turn = (int) (Math.random() * 2);
int smart_or_stupid = (int) (Math.random() * 2);
while (size_of_pile > 0)
{
System.out.println(\"Current number of marlbes in pile: \" + size_of_pile);
int marbles_to_remove = 0;
if (current_turn == 0)
{
if (smart_or_stupid == 1 || (size_of_pile == 1 || size_of_pile == 3
|| size_of_pile == 7 || size_of_pile == 15 || size_of_pile == 31
|| size_of_pile == 63))
{
marbles_to_remove = (int) (Math.random() * (size_of_pile / 2 + 1)) + 1;
}
else
{
if (size_of_pile > 63)
{
marbles_to_remove = size_of_pile - 63;
}
else if (size_of_pile > 31)
{
marbles_to_remove = size_of_pile - 31;
}
else if (size_of_pile > 15)
{
marbles_to_remove = size_of_pile - 15;
}
else if (size_of_pile > 7)
{
marbles_to_remove = size_of_pile - 7;
}
else if (size_of_pile > 3)
{
marbles_to_remove = size_of_pile - 3;
}
else
{
marbles_to_remove = size_of_pile - 1;
}
}
System.out.println(\"Computer removes \" + marbles_to_remove + \" marble\" + ((marbles_to_remove > 1)? \"s\": \"\"));
current_turn = 1;
}
else
{
do
{
System.out.println(\"How many marbles do you want to remove: \");
marbles_to_remove = input.nextInt();
} while ((marbles_to_remove != 1) && (marbles_to_remove <= 0 || marbles_to_remove > size_of_pile / 2));
current_turn = 0;
}
size_of_pile -= marbles_to_remove;
}
input.close();
if (current_turn == 0)
{
System.out.println(\"Human took last marble, computer wins!\");
}
else
{
System.out.println(\"Computer took the last marble, human wins!\");
}
}
}

