I’m quite stuck from a problem in the liang introduction to Java book – Here’s the problem:
“Sixteen coins are placed in a 4-by-4 matrix with some face up and some face down. You can represent the state of the coins using a 4-by-4 matrix with values 0 (head) and 1 (tail). Here are some examples:
0000
0100
0000
0010
each state can also be repesented using a binary number (a concatenation of the above). Write a program that prompts the user to enter a number between 0 and 65,536 and displays the corresponding matrix – a balue of 7 would give 00000111.
My question is how would you verify that this was the case for 7 ? I’m not even that sure how to begin prototyping such a method – perhaps int x = (int)Math.rand(1) and assign to each of the rows/cols?
Perhaps someone could give me some hints on where to start?
The problem is essentially converting an integer in the range [0, 65536] to its binary representation. This can be done with
Integer.toBinaryString. For instance,would result in the string
111. Now, we want the total length of the string to be 16, so we need to pad with0s on the left to obtain0000000000000111. We can do something like:which results in the string
0000000000000111.Once you have this, you can simply copy it into a 4×4 int (or boolean) array. Or, you can just print the data right off the bat,
Output:
Of course, you can replace that
7with whatever integer you read form the user, but the idea is the same.