Finding Heads and Tails of a Number in Java

Problem:

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 (head) and 1 (tail). 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 characters H and T.


Output:

Enter a number between 0 and 511
458


T T T
H H T
H T H


Solution:

  import java.util.Scanner;
public class HeadsAndTails
{
  public static int[] decimalToBinary(int decimal)
  {
  int[] nums = new int[9];
  for (int i = nums.length-1;i>=0 && decimal >0;i--)
  {
    if ( decimal% 2 == 0)
      nums[i] = 0;
    else 
      nums[i] = 1;
    decimal /= 2;
  }
  return nums;
  }

  public static void printHeadsAndTails(int[] nums)
  {
    for (int i =0; i<9;i++)
    {
      if (nums[i] == 0) System.out.print("H ");
      else  System.out.print("T ");
      if ((i+1) % 3 == 0) System.out.println();
      
    }
  }
  public static void main (String[] args)
  {
    Scanner scan = new Scanner (System.in);
    System.out.println("Enter a number between 0 and 511");
    int number = scan.nextInt();
    int[] nums = decimalToBinary(number);
    printHeadsAndTails(nums);
  }
}

4 comments:

  1. Replies
    1. nevermind it does work. lol

      Delete
    2. Sorry but I don't understand the problem from the start.... Where did you get
      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 ?

      I thought it was only a 3x3 matrix?

      Please explain
      Thanks!

      Delete
  2. I'm sorry I forgot to add spaces between the examples. This is how it looks now:

    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.

    Happy Coding :)

    ReplyDelete