Having trouble filling an array of binary numbers from an integer - java

This is the question we were assigned :
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.
I want the method toBinary() to fill the array binaryNumbers. I realized that this does not fill in 0s to the left. I have to think that through but is that the only thing that is the problem?
//https://www.geeksforgeeks.org/java-program-for-decimal-to-binary-conversion/
import java.util.Scanner;
public class HeadsAndTails {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num = input.nextInt();
int[] binaryNumbers = toBinary(num);
for (int i = 0; i < 9; i++) {
printArr(binaryNumbers);
System.out.print(binaryNumbers[1]);
}
}
public static int[] toBinary(int inputtedNumber) {
int[] binaryNum = new int[9];
int i = 0;
while (inputtedNumber > 0) {
binaryNum[i] = inputtedNumber % 2;
inputtedNumber = inputtedNumber/2;
inputtedNumber++;
} return binaryNum;
}
public static void printArr(int[] arr) {
for (int i = 0; i < 9; i++) {
if (arr[i] == 0) {
System.out.print("H ");
} else {
System.out.print("T ");
}
if (arr[i+1] % 3 == 0) {
System.out.println();
} System.out.print(arr[i]);
}
}
}

Looks like you are incrementing the wrong variable in your while loop:
while (inputtedNumber > 0) {
binaryNum[i] = inputtedNumber % 2;
inputtedNumber = inputtedNumber/2;
i++; // NOT inputtedNumber
} return binaryNum;
Also note, a new int[9] is probably already initialized to 0, but if not, you could just loop 9 times, rather than until the inputtedNumber is 0:
for (int i = 0; i < 9; i++) {
binaryNum[i] = inputtedNumber % 2;
inputtedNumber = inputtedNumber/2;
}
return binaryNum;
Finally, I think your array might be backwards when you're done, so you may need to reverse it or output it in reverse order

I realize this is a homework assignment so you should stick with your current approach. However, sometimes it can be fun to see what can be achieved using the built in features of Java.
The Integer class has a method toBinaryString that's a good starting point:
int n = 23;
String s1 = Integer.toBinaryString(n);
System.out.println(s1);
Output: 10111
But as we can see, this omits leading 0s. We can get these back by making sure our number has a significant digit in the 10th place, using a little bit-twiddling:
String s2 = Integer.toBinaryString(1<<9 | n);
System.out.println(s2);
Output: 1000010111
But now we have a leading 1 that we don't want. We'll strip this off using String.substring, and while we're at it we'll use String.replace to replace 0 with H and 1 with T:
String s3 = Integer.toBinaryString(1<<9 | n).substring(1).replace('0','H').replace('1','T');
System.out.println(s3);
Output: HHHHTHTTT
Now we can print this string in matrix form, again using substring to extract each line and replaceAll to insert the desired spaces:
for(int i=0; i<9; i+=3)
System.out.println(s3.substring(i, i+3).replaceAll("", " ").trim());
Output:
H H H
H T H
T T T
If we're up for a bit of regex wizardry (found here and here) we can do even better:
for(String sl : s3.split("(?<=\\G.{3})"))
System.out.println(sl.replaceAll(".(?=.)", "$0 "));
Putting it all together we get:
int n = 23;
String s3 = Integer.toBinaryString(1<<9 | n).substring(1).replace('0','H').replace('1','T');
for(String s : s3.split("(?<=\\G.{3})"))
System.out.println(s.replaceAll(".(?=.)", "$0 "));

Related

Decreasing number pyramid, nested for loop, user input, java

Write a program to produce the following output for any given integer number between
1 and 9 inclusive.
Enter an integer value [1..9]: 6
1
12
123
1234
12345
123456
666666
66666
6666
666
66
6
I have done the top half but I can not figure out the bottom with the repeating user input.
package lab7;
import java.util.Scanner;
public class problem5 {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
System.out.println("Input an integer between 1 and 9");
int input = scan.nextInt();
while (input <= 9) {
for (int i = 1; i <= input; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(j);
}
System.out.println();
}
break;
}
}
}
Expected result: included at the top; actual result so far (input of 5):
1
12
123
1234
12345
You're pretty close. You have a for loop that covers the first half of the output you want. You can add a second for loop to handle the second half of the output.
This is pretty similar to the first loop, but has a few small differences:
instead of the loop variable starting at 1 and increasing, this one starts at input and decreases each time through (i-- instead of i++)
instead of printing any of the loop variables (i or j), it prints the input value ("6" in your example)
for (int i = input; i > 0; i--) {
for (int j = 1; j <= i; j++) {
System.out.print(input);
}
System.out.println();
}
If I run that code locally – so your for loop, then this for loop, then the break statement – this is the output:
Input an integer between 1 and 9
6
1
12
123
1234
12345
123456
666666
66666
6666
666
66
6
I would prefer a more efficient algorithm, your current approach is O(n2); consider the digits '1' - '9'; if we store them in a String then we can take a simple substring of that String for each line at the top (for example, "123456789".substring(0, 3) -> "123") that can be used to generate the top through successive calls to substring. We can use a similar approach to build the bottom; use an array of all possible rows and iteratively call substring. Finally, don't forget to validate that input is between one and nine inclusive. Something like,
Scanner scan = new Scanner(System.in);
String digits = "123456789";
String[] btm = { "1", "22", "333", "4444", "55555",
"666666", "7777777", "88888888", "999999999" };
System.out.println("Input an integer between 1 and 9");
int input = scan.nextInt();
if (input < 1 || input > 9) {
System.err.printf("Invalid input: %d%n", input);
System.exit(1);
}
for (int i = 0; i < input; i++) {
System.out.println(digits.substring(0, i + 1));
}
for (int i = input - 1; i >= 0; i--) {
System.out.println(btm[input - 1].substring(0, i + 1));
}

Printing a unique triangle of characters in java

I need to print a triangle of characters:
0
1 0
1 0 1
0 1 0 1
The code I have prints it as this:
0
1 0
0 1 0
1 0 1 0
I can print it alternating, but when I try to change from alternating to unique characters I run into issues.
public static void main(String[] args) {
//mod even = 0, mod 1 = odd
int height;
int zero = 0;
int one = 1;
height = 4;
for(int i=1; i<=height; i++) {
for(int j=1; j<=i; j++) {
if ((j % 2) == 1) {
System.out.print((i % 2 == 1) ? zero : one);
} else {
System.out.print((i % 2 == 1) ? one : zero);
}
}
System.out.println();
}
}
I've tried adding in the if statement a scenario such as
if ((j % 2) == 1 && i == height){
System.out.print((i % 2 == 1) ? one : zero);
}
to get the last line to print starting with one, but it gets buggy and affects all lines. Any suggestions?
private static void triangle(int height) {
int valueToPrintNext = 0;
for(int i = 0; i < height; i++)
{
for(int j = -1; j < i; j++)
{
System.out.print(valueToPrintNext + " ");
valueToPrintNext = valueToPrintNext==0 ? 1 : 0;
}
System.out.println();
}
}
Main:
public static void main( String[] args )
{
triangle(6);
}
Output:
0
1 0
1 0 1
0 1 0 1
0 1 0 1 0
1 0 1 0 1 0
First of all: you're a programmer now. Programmers start counting from 0, not 1. PARTICULARLY in our for(){} loops. You're almost certainly a student, so just keep working at it.
What you're printing is basically "1 0 1 0" with newLines sprinkled in... so that's exactly how I'm going to do it.
This shows you that there are at least two different approaches to solving this problem. Bonus credit for anyone who comes up with a 3rd one (no not really).
Lets do a little numeric analysis to figure out the math on the total character count given a particular number of lines...
1 = 2 "1\n"
2 = 6 "1\n0 1\n"
3 = 12 "1\n0 1\n0 1 0\n"
4 = 20
5 = 30
6 = 42
n = n^2 + n
Okay, so now we write that up as a fairly trivial function. Lots of little functions is always easier to write AND TEST than a few big ones. Small functions good. Big functions bad.
private int getEndOfLinePosition(int lines) {
return lines * lines + lines;
}
And here we have the code which handles the aforementioned testing. Unit tests are awesome. Many people encourage you to write your unit tests BEFORE the code your testing. A good idea, but one I have to work at to follow. I like JUnit 5.
// imports go before your class at the top of the file
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
#Test
public void eolTest() {
int correctLengths[] = {2, 6, 12, 20, 30, 42};
for (int i = 0; i < 6; ++i) {
Assertions.assertEquals(correctLengths[i], getEndOfLinePosition(i + 1));
}
}
We'll build two functions, one to build the ones and zeros, and the other two sprinkle in the new lines. And we'll need a 'main' to glue 'em together.
void main() {
int height = 4;
StringBuffer onesAndZeros = buildOnesAndZeros(height);
addNewlines(onesAndZeros, height);
System.out.print(onesAndZeros);
}
There shouldn't be any surprises there... except perhaps that I'm using a StringBuffer rather than a String. String is immutable in Java, StringBuffer is expressly intended to be messed with, and mess with it we shall. Also, using print instead of println: our return will be built into the string.
private StringBuffer buildOnesAndZeroes(int height) {
int stringLength = getEndOfLinePosition(height);
StringBuffer buffer = new StringBuffer(stringLength);
char nextChar = '0';
for (int i = 0; i < stringLength; i += 2) {
buffer.append(nextChar);
buffer.append(' ');
nextChar = i % 2 == 1 ? "1" : "0";
}
return buffer;
}
The expression to determine nextChar might be backwards, but that should be easy to detect and fix. I may have even gotten it backwards on purpose just to leave you a bug to squish.
String addNewLines(StringBuffer onesAndZeros, int height) {
for (int i = 0; i < height; ++i) {
int currentEnd = getEndOfLinePosition(i);
onesAndZeros.setCharAt(curentEnd - 1, '\n');
}
}
Wrap all that in a class, and Bob's your uncle. Where the hell does that expression come from anyway? I mean... England, yeah, but why?!

How to generate a right angle Fibonacci Series pyramid in Java?

I want to generate an output like this :-
0
0 1
0 1 1
0 1 1 2
0 1 1 2 3
0 1 1 2 3 5
However, i am trying in this way to achieve , but some piece of logic is missing which i am unable to decipher.
Here's what i am trying :-
import java.util.Scanner;
class Fibonacci
{
public static void main(String arr[])
{
System.out.println("Enter a no.");
Scanner input=new Scanner(System.in);
int num=input.nextInt();
int x=0,y=1;
for(int i=0;i<=num;i++)
{
for(int j=0;j<i;j++)
{
System.out.print(j);
}
System.out.println("");
}
}
}
And it generates the output like this (consider num=6)
0
0 1
0 1 2
0 1 2 3
0 1 2 3 4
0 1 2 3 4 5
What logic is required to get the desired output ? Would be thankful if anyone can explain me this :)
Thanks in advance !!
You need to change logic of inner loop like this by adding two previous number to current number and swap them like this.
import java.util.Scanner;
class Fibonacci
{
public static void main(String arr[])
{
int x = 0, y = 0, c = 0;
System.out.println("Enter a no.");
Scanner input = new Scanner(System.in);
int num = input.nextInt();
for (int count = 0; count < num; count++) {
System.out.print(0);
x = 0;
y = 1;
c = 0;
for (int i = 1; i <= count; i++) {
c = x + y;
y = x;
x = c;
System.out.print(" " + c);
}
System.out.println();
}
}
}
First two numbers 0 and 1 are given , no need to caculate .
Use a String to save previous line string .
Caculate next numbers , add it into your previous line string .
Here is an example :
int x = 0 , y = 1;
int num = 6;
System.out.println("0");
System.out.println("0 1");
String str = "0 1";
for(int i = 2 ; i < num ; i ++){
int amt = x + y ;
x = y;
y = amt;
str += " " + amt;
System.out.println(str);
}
In a Fibonacci series only the first two numbers are provided which are 0 and 1. The next number of the series are calculated by adding the last two numbers. The series is limited by the user by providing the number of integers it wants in the series.
Logic: The logic behind creating a Fibonacci series is to add the two integers and save them in a new variable z = x+y and then replace the first integer value by the second integer and second integer value by their sum to move one step ahead in the series x=y adn y=z.
In your problem you want the series to be printed in a right angled triangle so you need to save the series that is already printed in a string
int n = 10;
System.out.println("0\n");
System.out.println("0 1\n");
int x = 0, y=1;
int i=2, z=0;
String str = "0 1";
while(i!=10)
{
z = x+y;
str += " " + z;
x=y;
y=z;
i++;
System.out.println(str);
}
Hope this helps

Binary Calculator Assignment

For this lab, you will enter two numbers in base ten and translate
them to binary. You will then add the numbers in binary and print out
the result. All numbers entered will be between 0 and 255, inclusive,
and binary output is limited to 8 bits. This means that the sum of the
two added numbers will also be limited to 8 bits. If the sum of the
two numbers is more than 8 bits, please print the first 8 digits of
the sum and the message "Error: overflow". Your program should
represent binary numbers using integer arrays, with the ones digit
(2^0) stored at index 0, the twos digit (2^1) stored at index 1, all
the way up to the 2^7 digit stored at index 7. Your program should
include the following methods:
int[] convertToBinary(int b) Translates the parameter to a binary value and returns it stored as an array of ints.
void printBin(int b[]) Outputs the binary number stored in the array on one line. Please note, there should be exactly one space
between each output 0 or 1.
int[] addBin(int a[], int b[]) Adds the two binary numbers stored in the arrays, and returns the sum in a new array of ints.
When entering my code into CodeRunner (which tests the code and returns a grade back depending on the results of each test) I cannot seem to pass one of the tests. This is the message that I am getting:
*You had 43 out of 44 tests pass correctly. Your score is 97%.
The tests that failed were: Test: addBin() method Incorrect: Incorrect number returned*
Heres my code:
import java.util.Scanner;
class Main {
public static int[] convertToBinary(int a) {
int[] bin = {0, 0, 0, 0, 0, 0, 0, 0};
for (int i = bin.length - 1; i >= 0; i--) {
bin[i] = a % 2;
a = a / 2;
}
return bin;
}
public static void printBin(int[] b) {
int z;
for (z = 0; z < b.length; z++) {
System.out.print(b[z] + " ");
}
System.out.println();
}
public static int[] addBin(int[] c, int[] d) {
int[] added = new int[8];
int remain = 0;
for (int x = added.length - 1; x >= 0; x--) {
added[x] = (c[x] + d[x] + remain) % 2;
remain = (c[x] + d[x] + remain) / 2;
}
if (added[0] + c[0] + d[0] == 1) {
added[0] = 1;
} else if ((added[0] + c[0] + d[0] == 2) || (added[0] + c[0] + d[0] == 3)) {
System.out.println("Error: overflow");
}
return added;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a base ten number between 0 and 255, inclusive.");
int num1 = scan.nextInt();
System.out.println("Enter a base ten number between 0 and 255, inclusive.");
int num2 = scan.nextInt();
int[] bin;
bin = convertToBinary(num1);
System.out.println("First binary number:");
printBin(bin);
int[] bin1 = bin;
bin = convertToBinary(num2);
System.out.println("Second binary number:");
printBin(bin);
int[] bin2 = bin;
System.out.println("Added:");
{
printBin(addBin(bin1, bin2));
}
}
}
If anyone could take a look at my code above and see if they could tell me what needs to be changed to fix the addbin() method so that it passes all of the tests, that'd be great! Any help is greatly appreciated even if you are not sure it would work! Thanks!
Hi first of all pardon my English but i guess your assignment accepts 1 and 255 too. So i added two of them and get 1 0 0 0 0 0 0 0 in your code. But i think it need to be 0 0 0 0 0 0 0 0 with an overflow error. So i changed your code a little bit.
public static int[] addBin(int[] c, int[] d) {
int[] added = new int[8];
int remain = 0;
for (int x = added.length - 1; x >= 0; x--) {
added[x] = (c[x] + d[x] + remain) % 2;
remain = (c[x] + d[x] + remain) / 2;
}
if (remain!=0) {
System.out.println("Error: overflow");
}
return added;
}
It's my first answer on the site so i hope it works for your test

How to "invert" numbers in Java

Lets say I have a number 1-5, now if I have 2, I want 4 as an output, if I had 3 then have 3 as the output, if I have 1 then 4 as the output. Here is a chart of what I want:
1-10 Chart:
Give 1 return 9
Give 2 return 8
Give 3 return 7
Give 4 return 6
Give 5 return 5
What algorithm do I use for such a thing?
I don't see that you need an algorithm as much. What you have is:
InverseNumber = (myCollection.Length - MySelection);
Thats all you need for even numbers.
With a collection of 1 - 6 for example:
Give 2; 6 - 2 = 4. Also if given 4, 6 - 4 = 2.
You will need a slightly different problem for odds:
1 - 5; with 1 given 1 is at index 0, the opposite is 5, 2 given and the inverse ( 5 - 2) is 3. But if 3 is given, there is no inverse. So you might want to also add a catch for:
if (((myCollection.Length *.5).Round) == mySelection) { //Inverse does not exist!!!}
If you are using just integers, and not arrays of numbers then just replace the myCollection.Length with the upperbound integer.
I think the following code will work for what you need:
int a[] = new a[length_needed];
int counter = length_needed;
for(int c = 0; c < length_needed; c++) {
a[c] = counter;
counter--;
}
int number_inputed;
for(int c = 0; c < length needed; c++) {
if(c == number_inputed) System.out.println(a[c]);
}
Let's say you are giving max number as input. Then you are going to have 0-n numbers. For ex., if 9 is the max number you will have 0-9.
Then you can do something like this:
public static void main(String[] a) {
int max = a[0]; // read values from cmd line args
int forWhichNum = a[1]; //for which number we need its inverse
Sop(max- forWhichNum);
}
Integer value = 2;
Integer maxValue = 6;
Integer reverseCounter = 0;
for (int i = maxValue; i > 0; i--) {
reverseCounter++;
if (i == value) {
return reverseCounter;
}
}

Categories

Resources