Storing binary bits into an integer array? - java

Currently, I just have data store the length of the bits, which isn't what I'm looking for.I would like to store the bits generated by the BinaryNumber constructor into the attribute private int data[]. data would later be used for other methods (for retrieving bit length,conversion to decimal, etc.). I am pretty new to Java programming, so I would very much appreciate if you can help me with this problem that I am facing.
public class BinaryNumber {
private int data[];
private boolean overflow;
/**
* Creates a binary number of length length
* and consisting only of zeros.
*
* #param Length
*
**/
public BinaryNumber(int length){
String binaryNum=" ";
for (int i=0; i<length;i++) {
binaryNum += "0";
}
System.out.println(binaryNum);
data= new int[length];
}
public static void main (String[] args) {
BinaryNumber t1=new BinaryNumber(7);
System.out.println(t1);
}
For example, the test above should generate seven 0s (0000000) and I would like to store those seven bits into the array data instead of what I do in my current code, which is storing it into a String binaryNum.

public BinaryNumber(int length) {
data = new int[length];
for (int i = 0; i < length; i++) {
data[i] = 0;
}
}
The Java spec, however, guarantees that all int values are initialized with 0, so your constructor could be simplified to just:
public BinaryNumber(int length) {
data = new int[length];
}

Related

How to store array values into a new array (JAVA) [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Issue: I've completed steps 1-4 of this assignment. However, I'm currently stuck on steps 5 and 6 of this assignment, so I'm at a loss on how to combine my fizz and buzz String arrays into a separate fizzbuzz String array.
TL;DR I don't know how to do steps five and six.
Assignment:
You can do this all in the main method. This is using a game called
Fizz-Buzz, an ancient programmer’s game.
Start by initializing some variables to set the maximum and minimum value of a random number and for the capacity of an array.
(20/100)
Initialize three new arrays, one for a list of random numbers (as integers) and two for String arrays called ‘fizz’ and
‘buzz’.(20/100)
You’ll also need an integer for counting.
Write a for loop that generates a random number for each position in the array. Remember that the range for this will be set by
the two variables initialized at the beginning of the file. There are
multiple ways to create a random number, just find one that works for
you. (20/100)
Using the count of the arrays, create another array that will store all of the fizzes and buzzes without any extra space leftover in
the array. (20/100)
Use a for each loop to iterate the array and print all of the fizzes and buzzes, with no other output. (20/100)
What I've accomplished thus far:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import java.util.Random;
/**
*
* #author
*/
public class FizzBuzz {
//2a. Initialize one int array for a list of random numbers.
private static int[] anArray;
private static final int size = 10;
//2b. Initialize two String arrays called 'fizz' and 'buzz.'
public static String[] fizz;
public static String[] buzz;
public static String[] fizzbuzz;
public static Random rand = new Random();
//1. Set the maximum and minimum value of a random number.
private static final int min = 0;
private static final int max = 5;
private static int count = 0;
public static int[] list() {
anArray = new int[size];
//3. Make an integer for counting("counter" in the for loop)
//4. Write a for loop that generates a random number for
// each position in the array.
for(count = 0; count < anArray.length; count++) {
anArray[count] = randomFill();
}
return anArray;
}
public static void print() {
for (int i = 0; i < anArray.length; i++) {
System.out.println(anArray[i] + ": " + fizz[i] + buzz[i]);
}
}
public static int randomFill() {
return rand.nextInt((max - min) + 1) + min;
}
public static String[] getF() {
fizz = new String[size];
int x = 0;
int counter;
for(counter = 0; counter < fizz.length; counter++) {
if(anArray[counter] % 3 == 0) {
fizz[counter] = "fizz";
} else {
fizz[counter] = "";
}
}
return fizz;
}
public static String[] getB() {
buzz = new String[size];
int x = 0;
int counter;
for(counter = 0; counter < buzz.length; counter++) {
if(anArray[counter] % 5 == 0) {
buzz[counter] = "buzz";
} else {
buzz[counter] = "";
}
}
return buzz;
}
public static String[] getFB() {
fizzbuzz = new String[size];
return fizzbuzz;
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
list();
getF();
getB();
print();
}
}
First of all:
How Random works
Your implementation of Random won't quite work for simple reason:
If you call the default-constructor, the seed of the PRNG will be the current time, thus you're quite likely starting multiple PRNGs with the same seed and thus receive the same random-value multiple times. Use a single Random-instance instead:
private Random rnd = new Random();
public static int randomFill() {
return rnd.nextInt((max - min) + 1) + min;
}
This should help in understanding the issue better.
General implementation
Try to stick as close to the given task as possible. E.g. the problem explicitly states that you should use a variable to specify the length of the arrays, while you're using a fixed magic-number. The task explicitly states to use two arrays fizz and buzz, you're using one array called fizzbuzz.
Inside GetFizzBuff, you probably meant x = 2; instead of x = x + 2;. Apart from that this part is fine.
Output
As above: try to stick to the given task. It's explicitly stated to only output the fizzes and buzzes, not any integers. Or at least try to print a value and the corresponding fizzes and buzzes in the same line, to produce readable output.

How do I fix this array output?

I'm making a histogram program in which I have one array that generates a random number, another that makes them into an array, and a last one that attempts to use that array and tell how many characters are in each [] of the array. My problem is that I cannot find a way to count how many characters are in each array element and outprint it. I'm trying to use the .length function but it doesn't seem to be working. Is there another way that I could do this?
Here is my code. My problem is with my last method, before my main method.
package arrayhistogram;
/**
*
* #author Dominique
*/
public class ArrayHistogram {
public static int randomInt(int low, int high){
double x =Math.random ()* (high - low)+low;
int x1=(int)x;
return x1;
}
public static int[] randomIntArray(int n){
int[] a = new int[n];
for (int i=0; i<n; i++) {
a[i] = randomInt(-5, 15);
}
return a;
}
public static int[] arrayHist () {
int[] x=randomIntArray(30);
for (int i = 0; i < x.length; i++) {
System.out.println(x[i].length);
}
return x;
}
public static void main(String[] args) {
arrayHist();
}
}
Replace
System.out.println(x[i].length);
with
System.out.println(Integer.toString(x[i]).length());
There is no length property on an int. You can use this to get the number of digits in the int.
String.valueOf(x[i]).length()
This first transforms the int into a String and then returns the length of that String. E.g 123 => "123", whose length is 3.

Storing a 4x4 2D-matrix in RAM using encoding algorithm to achieve minimum RAM-space usage

A board with 16 cells (4x4 matrix) exists of numbers from 1 to 15 (there is such a game). One cell is empty.
How to store the matrix data in RAM using minimum possible space of it?
I have made an example of a class Board which can be stored in RAM as an object consisting of just one long property representing the encoded version of the matrix.
Here is my Board class:
import java.io.Serializable;
public class Board implements Serializable {
private static final long serialVersionUID = 1L;
private long board; // the only property which is stored in RAM
public Board() {
board = 0x123456789abcdef0L; // 0 represents the empty-cell
}
public int[][] getBoardMatrix() { // decoding algorithm
int[][] boardMatrix = new int[BoardController.ROWS][BoardController.COLUMNS];
String boardString = getBoardString();
for (int rowIndex = 0; rowIndex < BoardController.ROWS; rowIndex++) {
for (int colIndex = 0; colIndex < BoardController.COLUMNS; colIndex++) {
boardMatrix[rowIndex][colIndex] = Integer.valueOf(
String.valueOf(boardString.charAt(rowIndex * BoardController.COLUMNS + colIndex)), 16);
}
}
return boardMatrix;
}
public void setBoardByMatrix(int[][] boardMatrix) { // encoding algorithm
StringBuilder sb = new StringBuilder();
for (int[] row : boardMatrix) {
for (int cell : row) {
sb.append(cell);
}
}
board = Integer.valueOf(sb.toString(), 16);
}
private String getBoardString() {
return String.format("%x", board);
}
}
I make also use of a class, representing a kind-of module or controller with some static properties:
public class BoardController {
public static final int ROWS = 4;
public static final int COLUMNS = 4;
}
My concrete question:
Is there a better way of storing this matrix to achieve a minimum-RAM-usage?
Biggest memory waste: references.
Don't store an array of Boards - each entry in the array is not a board, but a pointer to a board. This means that you are immediately wasting almost half of the space you could be using. When you save the board, don't save it as a class, but as a long. When you need to work with a board, convert it back from a long to a Board. This way, you can make an array of longs, but still treat them like objects when you want to.
class Board
{
public static Board fromLong(long value) {
int[] positions = new int[16];
List<Integer> possibilities = new ArrayList<Integer>(16);
for (int i = 15; i >= 0; i--)
possibilities.add(i);
long ignore = 0;
for (int i = 15; i > 0; i--) {
// Rounds towards zero
long index = (value - ignore) / factorial(i);
ignore += index * factorial(i);
positions[i] = possibilities.remove(index);
}
positions[0] = possibilities.get(0);
return new Board(positions);
}
/* Note that while this returns a long, only the lowest 45 bits contain data */
public long toLong() {
List<Integer> possibilities = new ArrayList<Integer>(16);
for (int i = 15; i >= 0; i--)
possibilities.add(i);
long value = 0;
for (int i = 15; i > 0; i--) {
int position = positions[i];
int index = possibilities.indexOf(position);
value += index * factorial(i);
possibilities.remove(index);
}
return value;
}
}
Disclaimer: I have not run this code yet, I'm still at work (Just on SO while I wait for compilation).
You can work out how many different combinations this board can produce. Let's treat the empty space as the number 0.
There are 16 unique values for the first tile. Once you know the value of the first tile, there are only 15 possible values for the next tile, and 14 for the third tile. Follow it all the way down to the last one, and you get
16 * 15 * 14 * 13 ... * 3 * 2 * 1
This is 16 factorial (Written as "16!"). This comes out to a huge number: 2.092279e+13
Now how many bits are required to store a number this big?
log2(2.092279e+13) = 44.2501404699
Of course, you can't work with 0.25 of a bit, so we have to round up to 45. The most efficient storage of your board takes up 45 bits. However, this is java, so you can't just allocate 45 bits.

How to merge arrays in Java Fork-Join multithreaded program?

I built a median filter and basically what it does it grabs an array of elements, filters it and returns a filtered array. Now, the sequential version works perfectly but on trying to make a Fork-Join version, I cannot get any result for arrays greater than my Sequential Threshold and it is also accompanied with ArrayIndexOutOfBounds errors.
Now, I'm not sure where I'm going wrong and after hours of research around Google and S.O, I am giving up and decided to post the question here.
Here's my code snippet that does the filtering Sequentially:
//Filter Algorithm.
private void filter(BigDecimal[] elements, int shoulder) {
//Add boundary values in beginning
for(int i=0; i<shoulder; i++){
filteredElements[i] = elements[i];
}
//Add boundary values at end
for(int i=arraySize-1; i>((arraySize-1) - shoulder); i--){
filteredElements[i] = elements[i];
}
//Add middle values to filteredElements array
for (int i = shoulder; i < elements.length-shoulder; i++) {
BigDecimal[] windowValue = prepareWindow(elements, shoulder, filterSize);
BigDecimal median = getMedian(windowValue);
filteredElements[i] = median;
}
}
/*
* Pre-condition: Get Windowed Array
* Post-Condition: Return Median
*/
private static BigDecimal getMedian(BigDecimal[] windowValue) {
Arrays.sort(windowValue);
return windowValue[(filterSize-1)/2];
}
/*
* Pre-condition: Get elements array, get shoulder value and length of filterSize. Notice that this is given name windowLength.
* Post-Condition: Return Windowed Array
*/
private static BigDecimal[] prepareWindow(BigDecimal[] elements, int shoulder, int windowLength) {
BigDecimal[] out = new BigDecimal[windowLength];
int outCounter = 0;
for(int i = position; i<position+filterSize; i++){
out[outCounter] = elements[i];
outCounter++;
}
position++;
return out;
}
//Return Filtered Array
public BigDecimal[] getFilteredArray(){
return filteredElements;
}
Now, the same sequential code applied in a Fork-Join does not work if the array is larger than the sequential threshold and I would like to know where I'm going wrong here.
Here's a snippet for my Parallel implementation:
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.concurrent.RecursiveTask;
public class Parallel extends RecursiveTask<BigDecimal[]>{
BigDecimal[] elements;
BigDecimal[] filteredElements; //Array that contains the filtered elements
int shoulder;
static int filterSize;
int begin;
int end;
static int position = 0;
static final int SEQUENTIAL_CUTOFF = 4;
public Parallel(BigDecimal[] elements, int filterSize, int begin, int end) {
this.elements = elements;
Parallel.filterSize = filterSize;
this.begin = begin;
this.end = end;
filteredElements = new BigDecimal[elements.length]; //Array that contains the filtered elements
shoulder = (filterSize - 1) / 2;
}
#Override
protected BigDecimal[] compute() {
if (end - begin <= SEQUENTIAL_CUTOFF) {
filter(elements, shoulder); //Run Filter Method
}else{
Parallel curLeft = new Parallel(elements, filterSize, this.begin, ((this.begin+this.end)/2));
Parallel curRight = new Parallel(elements, filterSize, ((this.begin+this.end)/2), this.end);
curLeft.fork();
curRight.compute();
curLeft.join();
}
return filteredElements;
}
//Filter Algorithm.
private void filter(BigDecimal[] elements, int shoulder) {
//Add boundary values in beginning
for(int i=0; i<shoulder; i++){
filteredElements[i] = elements[i];
}
//Add boundary values at end
for(int i=this.elements.length-1; i>((this.elements.length-1) - shoulder); i--){
filteredElements[i] = elements[i];
}
//Add middle values to filteredElements array
for (int i = shoulder; i < elements.length-shoulder; i++) {
BigDecimal[] windowValue = prepareWindow(elements, shoulder, filterSize);
BigDecimal median = getMedian(windowValue);
filteredElements[i] = median;
}
}
/*
* Pre-condition: Get Windowed Array
* Post-Condition: Return Median
*/
private static BigDecimal getMedian(BigDecimal[] windowValue) {
Arrays.sort(windowValue);
return windowValue[(filterSize-1)/2];
}
/*
* Pre-condition: Get elements array, get shoulder value and length of filterSize. Notice that this is given name windowLength.
* Post-Condition: Return Windowed Array
*/
private static BigDecimal[] prepareWindow(BigDecimal[] elements, int shoulder, int windowLength) {
BigDecimal[] out = new BigDecimal[windowLength];
int outCounter = 0;
for(int i = position; i<position+filterSize; i++){
out[outCounter] = elements[i];
outCounter++;
}
position++;
return out;
}
//Return Filtered Array
public BigDecimal[] getFilteredArray(){
return filteredElements;
}
}
Basically the Parallel implementation uses the sequential methods I made but I can't get it to work. Below is a list of errors I'm getting(I added the lines that are causing the errors to make reading easier. Most of the errors are in the sequential methods and I don't understand why):
Caused by: java.lang.ArrayIndexOutOfBoundsException: 8
at Parallel.prepareWindow(Parallel.java:80) > out[outCounter] = elements[i];
at Parallel.filter(Parallel.java:55) > BigDecimal[] windowValue = prepareWindow(elements, shoulder, filterSize);
at Parallel.compute(Parallel.java:29) > filter(elements, shoulder); //Run Filter Method
at Parallel.compute(Parallel.java:34) > curRight.compute();
Would really appreciate if someone could help with a meaningful answer.
Thanks.
We cannot see the whole code, but I see that somehow two compute() are called in parallel and they call prepareWindow() concurrently.
The big problem is that position is a static variable and both thread are incrementing the same reference, pushing it out of bounds.

BitSet and Byte Array value getting SET from opposite direction

I have:
public byte[] bytes = new byte[5]; //BitComp Class
public BitSet bits = new BitSet(40);
and the getters and setters in class named BitComp. The following class sets all the first 8 bits to 1(byte[0]).After that it converts all bytes to BitSet. Now after that when it sets the 2nd bit to true and prints both of them.
import java.util.BitSet;
public class TestBitSet {
public void testBit(){
BitComp comp = new BitComp();
comp.bytes[0] |= 0xFF;
comp.setBits(getBitsFromByte(comp.getBytes()));
System.out.println(toCharArray(comp.getBits()));
BitSet bs = comp.getBits();
bs.set(1,true);
comp.setBits(bs);
System.out.println(toCharArray(comp.getBits()));
}
private BitSet getBitsFromByte(byte[] barray)
{
BitSet bits=new BitSet();
if(barray!=null)
{
for (int i=0; i<barray.length*8; i++)
{
if ((barray[barray.length-i/8-1]&(1<<(i%8)))!= 0)
{
bits.set(i);
}
}
}
return bits;
}
public static char[] toCharArray(final BitSet bs)
{
final int length = bs.length();
final char[] arr = new char[length];
for(int i = 0; i < length; i++)
{
arr[i] = bs.get(i) ? '1' : '0';
}
return arr;
}
public static void main(String args[]){
TestBitSet tbs = new TestBitSet();
tbs.testBit();
}
}
Output:0000000000000000000000000000000011111111 <- 0th
0th-> 0100000000000000000000000000000011111111
There should not ne any change cause byte[0] contains the first 8 elements and I am setting the 2nd element as 1 with BitSet operation.
So BitSet is approaching from LHS and Byte array is stored from RHS. How to approach this problem? Is there a problem in getBitsFromByte method?
Please Suggest.
Thanks
You don't provide the code for BitComp, however it appears to me that you determine how to translate bits into bytes and what order to print the bytes.
Its entirely up to you what order you what things to be set or printed out.
Just add a little math into your Set: ((byteNumber*8)+(7-bitNumber))

Categories

Resources