## Sunday, 28 August 2016

### Chapter 8 Exercise 11, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

**8.11 (Game: nine heads and tails) Nine coins are placed in a 3-by-3 matrix with some face up and some face down. You can represent the state of the coins using a 3-by-3 matrix with values 0 (heads) and 1 (tails). Here are some examples:
0 0 0    1 0 1    1 1 0    1 0 1    1 0 0
0 1 0    0 0 1    1 0 0    1 1 0    1 1 1
0 0 0    1 0 0    0 0 1    1 0 0    1 1 0
Each state can also be represented using a binary number. For example, the preceding matrices correspond to the numbers

000010000 101001100 110100001 101110100 100111110

There are a total of 512 possibilities, so you can use decimal numbers 0, 1, 2, 3, . . . , and 511 to represent all states of the matrix. Write a program that prompts the user to enter a number between 0 and 511 and displays the corresponding matrix with the characters H and T. Here is a sample run: Enter a number between 0 and 511: 7
H H H
H H H
T T T
The user entered 7, which corresponds to 000000111. Since 0 stands for H and 1 for T, the output is correct.

import java.util.Scanner;

public class ProgrammingEx8_11 {
// Strategies:
// Use binary number and bitwise operator to shift the bit to the right and
// use masking to extract the last digit
// Also see exercise 5.44
public static void main(String[] args) {

Scanner input = new Scanner(System.in);
System.out.print("Enter a number between 0 and 511: ");
short n = input.nextShort();
int intArray[][] = new int[3][3];

short mask = 0b1; // to extract the last bit after shifting

for (int i = 0; i < 9; i++) {

short bit = (short) (n & mask); // extracting last bit i.e the
// remainder of
// division by 2
intArray[2-i / 3][2-i % 3] = bit;
n = (byte) (n >> 1); // Shifting right is dividing by 2. The last
// bit is the remainder of the next shift.

}

displayArray(intArray);

}

public static void displayArray(int array[][]) {

for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[0].length; j++) {
if (array[i][j] == 1) {
System.out.print("T ");
} else {
System.out.print("H ");
}
}

System.out.println("");
}
}

}