第八章第十一题(游戏:九个硬币的正反面)(Game: front and back of nine coins)
-
**8.11(游戏:九个硬币的正反面)一个3x3的矩阵中放置了9个硬币,这些硬币有些面朝上,有些面朝下。可以使用3x3的矩阵中的0(正面)或1(反面)表示硬币的状态。下面是一些例子:
000 101 110 101 100
010 001 100 110 111
000 100 001 100 110
每个状态都可以使用一个二进制数表示。例如,前面的矩阵对应到数字:
000010000 101001100 110100001 101110100 100111110
总共会有512中可能性。所以可以使用十进制数0,1,2,3,…,511来表示这个矩阵的所有状态。编写一个程序,提示用户输入一个在0到511之间的数字,然后显示用字符H和T表示的对应的矩阵。下面是一个运行示例:
Enter a number between 0 and 511:7
H H H
H H H
T T T
**8.11(Game: front and back of nine coins)Game: Nine coins front and back, a 3x3 matrix placed 9 coins, some of these coins face up, some face down. The status of the coin (3x3) can be represented by the positive matrix or the reverse matrix. Here are some examples:
000 101 110 101 100
010 001 100 110 111
000 100 001 100 110
Each state can be represented by a binary number. For example, the preceding matrix corresponds to a number:
000010000 101001100 110100001 101110100 100111110
There will be 512 possibilities. So you can use decimal numbers 0,1,2,3,…, 511 to represent all States of the matrix. Write a program to prompt the user to enter a number between 0 and 511, and then display the corresponding matrix represented by the characters h and t. Here is a running example:
Enter a number between 0 and 511:7
H H H
H H H
T T T -
参考代码:
package chapter08; import java.util.Scanner; public class Code_11 { public static void main(String[] args) { int[][] num = new int[3][3]; for (int i = 0; i < num.length; i++) { for (int j = 0; j < num[i].length; j++) { num[i][j] = (int) (Math.random() * 2); } } Scanner input = new Scanner(System.in); System.out.print("Enter a number between 0 and 511:"); int number = input.nextInt(); String decimalToBinary = Integer.toBinaryString(number); //将十进制数转成字符串,例如n=5 ,s = "101" char[] stringArray = decimalToBinary.toCharArray();//转化为字符数组 char[] hAndT = new char[9]; for (int i = stringArray.length - 1, j = hAndT.length - 1; i >= 0; i--, j--) { hAndT[j] = stringArray[i];//从后往前赋值 if (hAndT[j] == '1') hAndT[j] = 'T'; else if (hAndT[j]=='0') hAndT[j]='H'; } for (int i = 0; i < hAndT.length; i++) { if (hAndT[i] == '\u0000') { hAndT[i] = 'H'; //没有被赋值的地方默认为0 } } for (int i = 0; i < hAndT.length; i++) { System.out.print(hAndT[i] + " "); if ((i+1)%3==0) System.out.print("\n"); } } }
-
结果显示:
Enter a number between 0 and 511:7 H H H H H H T T T Process finished with exit code 0