Tuesday, July 22, 2014

Nim!

3.11 Project
The game of Nim is played as follows. You have n toothpicks to choose from. Player A can remove 1, 2, or 3 toothpicks. Player B can then remove 1, 2, or 3 toothpicks. This process repeats, alternating between players A and B, until there are no more toothpicks left. The player who removes the last toothpick is the loser. Assume that one of the players is human and the other player is the computer (your program).  Use a random generator to decide who goes first. The player that goes second chooses
the value of n, where n must be bigger than 20 and smaller than 30 (if this is the computer, then use a random generator to determine the value of n). Remember to print the remaining number of toothpicks on the screen after every move. If it is the human’s turn, then ask him or her how many toothpicks he or she wants to remove. After the last toothpick is removed, print “YOU WIN” or “YOU LOSE”.
Example program run (player input in italic) follows.
Welcome to my game of Nim.
This time you are going to go first.
I choose the total number of toothpicks to be 21.
Your Turn. There are 21 toothpicks left. How many toothpicks do you want to remove? 2
My turn. There are 19 toothpicks left. I, the Computer, will remove 3 of them.
Your Turn. There are 16 toothpicks left.
How many toothpicks do you want to remove? 3
My Turn. There are 13 toothpicks left. I, the Computer, will remove 3 of them.
Your Turn. There are 10 toothpicks left. How many toothpicks do you want to remove? 3
My Turn. There are 7 toothpicks left. I, the Computer, will remove 3 of them.
Your Turn. There are 4 toothpicks left. How many toothpicks do you want to remove? 3
My Turn. There is 1 toothpick left. I, the Computer, will remove it.
YOU WIN!
Try to design your program to play as smart as possible.

I vaguely remember doing a similar exercise as a homework assignment in my freshman year of college.  I don't remember how I did it then, or if I even did it correctly.  But today this was fairly easy to program.  In my first version the computer chose numbers randomly.  But then I went back and made it play with a strategy.  So now, if the user is randomly chosen to go first in the beginning, the computer will win no matter what the user inputs.  Which makes it a solved game and not very much fun.

import java.util.*;

public class Arithmetic {
public static void main(String[] args) {
boolean usersTurn;
int numtp, input, x;
Scanner keyboard = new Scanner(System.in);
System.out.println("Welcome to the game of Nim!");
//randomly decide who goes first
Random random = new Random();
   usersTurn = random.nextBoolean();
   
   
   //beginning of game
   if (usersTurn){//if user's turn first
    System.out.println("This time you are going to go first.");
    numtp = 21;//computer chooses number of toothpicks
    System.out.println("I choose the number of toothpicks to be "+numtp+".");
   }
   else{//if computer's turn first
    System.out.println("This time I am going to go first.");
    do{
    System.out.print("Choose how many toothpicks we should start with (21-29): ");
    numtp = keyboard.nextInt();
    }while(!(numtp<30&&numtp>20));//loop if not between 20 and 30
   }
   
   
//middle of game
while(numtp>0){//while there are more toothpicks
if(usersTurn){//if it's the user's turn
do{
System.out.print("Your turn.  There are "+numtp+" toothpicks left.  How many toothpicks do you want to remove?  (1-3): ");
input = keyboard.nextInt();
}while (!(input<=3&&input>=1));//repeat if not 1-3
numtp = numtp - input;//subtract that number from number of toothpicks
usersTurn = false;//next turn
}
else{//if it's the computer's turn
if(numtp==1){//if last toothpick
System.out.println("My turn. There is 1 toothpicks left. I will remove it.");
numtp = 0;
usersTurn = true;
break;//game over
}else if (numtp%4==2)//if 2, 6, 10, 14 etc
x=1;//remove 1
else if (numtp%4==3)//if 3, 7, 11, 15 etc
x=2;//remove 2
else if (numtp%4==0)//if 4, 8, 12, 16 etc
x=3;//remove 3
else//if 5, 9, 13 etc
x = random.nextInt(3)+1;//remove random
System.out.println("My turn. There are "+numtp+" toothpicks left. I will remove "+x+" of them.");
numtp = numtp - x;//subtract toothpicks
usersTurn = true;//next turn
}
}


//end of game
if (usersTurn)//if computer was the last player
System.out.println("You Win!");//user wins
else
System.out.println("I Win!");//user loses
keyboard.close();
}
}



Hangman

3.10 Lab
You will create a two-player version of the Hangman game. The program should first ask for the first player to enter a word and save the word. Next, the second player should be allowed to guess letters. If a letter appears in the word, then they should be told at what position. After 6 guesses, the player has one shot of guessing the word. A possible run of the program follows (user input is in italic).
Player 1 enter word: mississippi
Player 2 enter guess: c
No letter c
Player 2 enter guess: d
no letter d
Player 2 enter guess: e
no letter e
Player 2 enter guess: m
at position: 1
Player 2 enter guess: a
no letter a
Player 2 enter guess: i
at position 2 5 8 11
Enter word: mississippi
This is correct!
Use a for loop to iterate through all the guesses. Use a nested for loop to iterate through
all the characters of the word. When there is a hit (i.e., the user character matches a word
character), report the value of the index of the character in the word. Do not forget to add
one to the result because the characters of a string are counted starting at index 0.

This was pretty easy.  I added a small feature above what the exercise asked for which was to convert all inputs to lower case so that there wouldn't be a false negative due to capitalization.


import java.util.*;

public class Arithmetic {
public static void main(String[] args) {
String word, output;// user input, word to guess, program output
char guess;// letter guessed
Scanner keyboard = new Scanner(System.in);
System.out.print("Player 1 enter a word: ");
word = keyboard.next().toLowerCase();// convert input to lower case
int length = word.length();// get length of word
for (int x = 0; x < 6; x++) {// loop for 6 guesses
System.out.print("Player 2 guess a letter: ");
guess = keyboard.next().toLowerCase().charAt(0);// take first character and make it lower case
output = "at position ";
for (int i = 0; i < (length); i++) {// loop through all characters in the word
if (guess == word.charAt(i))// check if corresponding characters match
output = output + (i + 1) + " ";// add to response line
}
if (output.equals("at position "))// if no matches found
output = "No letter " + guess;
System.out.println(output);
}
System.out.print("Player 2 guess the word: ");// prompt user
if (keyboard.next().toLowerCase().equals(word))// if input converted to lower case equals the word
System.out.println("You won!");
else
System.out.println("Sorry, that is incorrect.");
keyboard.close();
}
}


Palindrome

A palindrome is a string that reads the same forward and backward. Write a program
that reads a string from the keyboard and tells the user if the string is a palindrome.


import java.util.*;

public class Arithmetic {
public static void main(String[] args) {
String input;// user input
int i;// iteration
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a word: ");// prompt user
input = keyboard.next();
int length = input.length();// get length
for (i = 0; i < (length / 2); i++) {// loop through first half of word
if (!(input.charAt(i) == input.charAt(length - 1 - i)))// check if corresponding characters match
{
System.out.println(input + " is not a palindrome.");
break;
}
}
if (i == length / 2)
System.out.println(input + " is a palindrome.");
keyboard.close();
}
}



Factorial!

10. Write a program that reads an integer from the keyboard and prints the factorial of the input. Use a variable of type long to store the result.

In mathematics, the factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n. For example,
5! = 5  *  4  *  3  * 2  *  1 = 120.

import java.util.*;
public class Arithmetic {
public static void main(String[] args) {
int input;// stores user input
int i;// stores interation
Scanner keyboard = new Scanner(System.in);
do {
System.out.print("Enter a positive number: ");// prompt user
input = keyboard.nextInt();
} while (input < 0);// won't continue until a positive number is entered
long factorial = input;
for (i = input - 1; i >= 2; i--) {// loops through from one less than
// the input down to 2.
factorial = factorial * i;// multiple itself to the next interation
}
if (input == 0 || input == 1)// if the input is 0 or 1
factorial = 1;// the factorial is 1
System.out.println(input + "! = " + factorial);// print the result
keyboard.close();
}
}

Is It Prime?

8. Write a program that reads an integer from the keyboard and tells the user if the number is prime. Use a for loop to check if the number is divisible by the numbers from 2 up to the value of the input number minus 1.

import java.util.*;
public class Arithmetic {
public static void main(String[] args) {
int input;
int i;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a positive number: ");
input = keyboard.nextInt();
for (i = input - 1; i >= 2; i--) {
if ((input % i) == 0) {
System.out.println(input + " is not prime.");
break;
}
}
if (i == 1)
System.out.println(input + " is prime.");
keyboard.close();
}
}

Monday, July 21, 2014

Math Test Chapter 3, Exercise 1

Chapter 3 Exercise 1
Improve the multiplication game from the previous chapter. We will randomly ask the player to either add, multiply, or subtract one-digit numbers (we skip division because the result of dividing two numbers is not an integer). The game should ask 10 math questions and record the answers. At the end, the game should tell the player how well they did, that is, how many questions they answered correctly.

import java.util.*;
public class MathTest {
public static void main(String[] args) {
Random randomGenerator = new Random();
int x = 1;// first number in equation
int y = 1;// second number in equation
int z = 1;// determines operation
int answer = 0;// correct answer
int score = 0;// how many user gets right
int result = 0;// user input
String op = "";// string correlating to random operation
Scanner keyboard = new Scanner(System.in);

for (int a = 1; a <= 10; a++) {// do this 10 times
x = randomGenerator.nextInt(10);// get random integer 0-9
y = randomGenerator.nextInt(10);// get random integer 0-9
z = randomGenerator.nextInt(3);// get random integer 0-2
if (z == 0) {// if addition
op = "+";
answer = x + y;
} else if (z == 1) {// if subtraction
op = "-";
answer = x - y;
} else if (z == 2) {// else multiplication
op = "*";
answer = x * y;
}
System.out.print(x + " " + op + " " + y + " = ");// prompt user
result = keyboard.nextInt();// get answer
if (result == answer) {// if answer is correct
System.out.println("correct");// print correct
score++;// increase score
} else {
System.out.println("incorrect");// print incorrect
}
}
keyboard.close();
System.out.println("Your score is " + score + "/10.");// print score
}
}


Tuesday, July 15, 2014

Random Number Diamond

2.12 Lab
Write a program that prints the following diamond.
      1
   2 3 4
1 2 5 7 4
   2 3 5
      4
The printed numbers are random digits between 0 and 9. In Java, Math.random() returns
a random double that is greater than or equal to 0 and smaller than 1. The method is
defined in the library java.math.* (use import java.math.*) . Multiply this number by
something to get a digit between 0 and 9. Use int i = (int) d; to convert a double to
an int.

I had to think about how to go about doing this logically.  I can easily change the size of the diamond with one variable change.

import java.math.*;
public class Diamond{
public static void main(String[] args) {
boolean ascending = true;
int spacers = 2;//spacers per row needed
int numbers = 1;//numbers per row needed
while (numbers > 0) {//while numbers are needed
for (int i = 0; i < spacers; i++) {//loop as many times as spaces are needed
System.out.print("  ");// print spacers
}
for (int i = 0; i < numbers; i++) {//loop as many times as numbers are needed
System.out.print(" " + ((int) (Math.random() * 10)));// print random number 0-9
}
if (numbers == 5)//if reached middle
ascending = false;//stop getting wider
if (ascending) {// if ascending 
spacers--;//subtract spacers in next row
numbers=numbers+2;//add numbers in next row
} else// if descending 
{
spacers++;//add spacers in next row
numbers=numbers-2;//subtract numbers in next row
}
System.out.println();//go to next line
}}}


Lexicographical Order

Exercise 2.12  Write a program that reads two strings from the keyboard and prints the largest
(relative to lexicographical order). Use the compareTo method to compare the strings.

import java.util.*;

public class Lexicographical {
public static void main(String[] args) {
System.out.print("First string: ");
Scanner input = new Scanner(System.in);
String x = input.next();
System.out.print("Second string: ");
String y = input.next();
int i = x.compareTo(y);
input.close();
if (i<0){
System.out.print("The larger string is: "+y);
}
else if (i>0){
System.out.print("The larger string is: "+x);
}
else
{
System.out.print("The strings are equal.");
}
}
}

Hi Bye

Exercise 6:  Write a program that chats with you. If you type Hi, then the program should print Hi and terminate. If you enter Bye, then the program should print Bye and terminate.  If you enter anything else, the program should respond And how do you feel about this? and terminate. Use a switch statement.

import java.util.*;

public class HiBye {
public static void main(String[] args) {
System.out.print(": ");
Scanner input = new Scanner(System.in);
String x = input.nextLine();
switch (x) {
case "Hi":
System.out.println("Hi");
break;
case "Bye":
System.out.println("Bye");
break;
default:
System.out.println("And how do you feel about this?");
}
input.close();
}
}

1-4

Exercise 5:  Write a program that reads an integer. If the integer is between 1 and 4, then the
program should print one, two, three, or four, respectively. If the integer is not
between 1 and 4, then the program should print Number not between one and four.
Use a switch statement.

import java.util.*;

public class Arithmetic {
public static void main(String[] args) {
System.out.print("Enter a number from 1 to 4: ");
Scanner input = new Scanner(System.in);
int x = input.nextInt();
switch(x){
case 1:
System.out.println("One");
break;
case 2:
System.out.println("Two");
break;
case 3:
System.out.println("Three");
break;
case 4:
System.out.println("Four");
break;
default:
System.out.println("That is not a number from 1 to 4");
}
input.close();
}
}

Multiplication Test

Exercise:  Write a program that prints two random integers (smaller than 100 and bigger than
0). The program should ask the user to multiply the numbers and read the result
from the user. If the user has done the multiplication correctly, then the program
should print “Congratulations!” Otherwise, the program should print “Better luck
next time.”

I decided to make the exercise a little more complicated by having it ask 10 questions and then print a score at the end.  Instead of the Math.random() that the book used in the chapter I decided to go with Random().

import java.util.*;
public class Multiplication{
public static void main(String[] args) {
   Random randomGenerator = new Random();
   int x = 1;
   int y = 1;
   int answer = 1;
   int score = 0;
   Scanner keyboard = new Scanner(System.in);
 
for (int a = 1; a<=10; a++){//do this 10 times
x = randomGenerator.nextInt(99)+1;//get random integer 1-99
y = randomGenerator.nextInt(99)+1;
   System.out.print(x + " * " + y + " = ");//prompt user
   answer = keyboard.nextInt();//get answer
   if (answer == x*y){//if answer is correct
    System.out.println("correct");//print correct
    score++;//increase score
   }
   else{
    System.out.println("incorrect");//print incorrect
   }
}
keyboard.close();
System.out.println("Your score is "+score+"/10.");//print score
}
}

Are you 21?

Learning JAVA through Games - Chapter 2 exercise 3

Exercise: Write a program that checks if the user is underage. If they are, then the program
should tell them not to go to the bar. If they are over 21, then the program should
print that they are allowed to go to the bar, but they should drink responsibly.

I went the more complicated route by asking for the users birthday instead of just asking if they were 21, but I learned more this way.  I had to look up how to get the current year, month and day.  I only ask for the month / day of the birthday if it's necessary and if it's their birthday they get a special message.

import java.util.*;
public class Test21 {
public static void main(String[] args) {
String output = "";
int year = Calendar.getInstance().get(Calendar.YEAR);
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter your birth year(ex: 1985): ");
int birthYear = keyboard.nextInt();
if ((year-birthYear) < 21){
output = "Don't go to the bar";
}
else if ((year-birthYear) > 21){
output = "Drink responsibly.";
}
else{
int month = Calendar.getInstance().get(Calendar.MONTH);
System.out.print("Enter your birth month(ex: 10): ");
int birthMonth = keyboard.nextInt();
if (month+1 < birthMonth){
output = "Don't go to the bar";
}
else if (month+1 > birthMonth){
output = "Drink responsibly.";
}
else{
int day = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
System.out.print("Enter your birth day(ex: 30): ");
int birthDay = keyboard.nextInt();
if (day < birthDay){
output = "Don't go to the bar";
}
else if (day > birthDay){
output = "Drink responsibly.";
}
else{
output = "HAPPY 21ST BIRTHDAY!!  Go to the bar.";
}
}
}
System.out.println(output);
}
}