Nine coins are placed in a 3x3 matrix with some face up and some face down. You
ID: 3565961 • Letter: N
Question
Nine coins are placed in a 3x3 matrix with some face up and some face down. You can represent the state of the coins using a 3x3 matrix with values 0 (heads) and 1 (tails). Here are some examples: 0 0 0 1 0 1 1 1 0 0 1 0 0 0 1 1 0 0 0 0 0 1 0 0 0 0 1 Each state can also be represented using a binary number. For example, the preceding matrices correspond to the numbers: 000010000 101001100 110100001 There are a total of 512 possibilities, so you can use decimal numbers 0, 1, 2, 3,...,511 to represent all the 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.
Explanation / Answer
// HEADSANDTAILS.java
import java.util.Scanner;
public class HEADSANDTAILS
{
public static String toBinary(int n)
{
StringBuilder sb = new StringBuilder();
while (n != 0)
{
sb.append(n & 1);
n = n >> 1;
}
while (sb.length() < 9)
{
sb.insert(0, "0");
}
return sb.toString();
}
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer representing the state of the coins: ");
int n = input.nextInt();
int[][] matrix = new int[3][3];
String binary = toBinary(n);
int idx = 0;
for (int i = 0; i < matrix.length; i++)
{
for (int j = 0; j < matrix[i].length; j++)
{
int side = (binary.charAt(idx++) == '0') ? 0 : 1;
matrix[i][j] = side;
}
}
for (int i = 0; i < matrix.length; i++)
{
for (int j = 0; j < matrix[i].length; j++)
{
char c = (matrix[i][j] == 0) ? 'H' : 'T';
System.out.print(c + " ");
}
System.out.println("");
}
}
}
/*
output:
Enter an integer representing the state of the coins: 255
H T T
T T T
T T T
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.