Nine coins were placed in a 3x3 matrix with some face up and some face down. You
ID: 3787797 • Letter: N
Question
Nine coins were 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:
000101110
010001100
000100001
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.
Your output must match the sample run exactly, character by character including spaces and punctuation. When a floating point number is displayed, use the printf method to round up the number in the format as indicated in the sample run.
SAMPLE RUN #1 JAVA HEADSANDTAILS
Enter an integer representing the state of the coins:255
HTT
TTT
TTT
SAMPLE RUN #2 JAVA HEADSANDTAILS
Enter an integer representing the state of the coins:107
HTT
THT
TTT
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.