Java: How to output all possible binary combinations (256 different sequences)? - java

I need to create a function that outputs all possible binary combinations (2^8 == 256 different sequences of 8 bits.). I'm really stumped on this. I have to do it with nested loops, and am not sure how to go about it. Below is what I tried so far. I was told that I could write this program using 8 nested loops, each one going from 0 to 1; Also, I could try to do this with bit manipulation operators.
Although what I have below is obviously wrong, I tried my best to show that I at least tried this. I also need to put new line's after each closing bracket, to separate the output.
The output should look like this:
00000000
00000001
00000010
00000011
00000100
...
11111110
11111111
public static void outputBinary(){
int[][][][][][][][] num = new int[2][2][2][2][2][2][2][2];
for (int i = 0; i < 2; i++){
for (int j = 0; j < 2; j++){
for (int k = 0; k < 2; k++){
for (int l = 0; l < 2; l++){
for (int m = 0; m < 2; m++){
for (int n = 0; n < 2; n++){
for (int o = 0; o < 2; o++){
for (int p = 0; p < 2; p++){
System.out.print(num[i][j][k][l][m][n][o][p]);
} }}}}}}}
}
Thanks for looking.

No need for the array. Here is a slight modification to your code that will output all the permutations.
for (int i = 0; i < 2; i++){
for (int j = 0; j < 2; j++){
for (int k = 0; k < 2; k++){
for (int l = 0; l < 2; l++){
for (int m = 0; m < 2; m++){
for (int n = 0; n < 2; n++){
for (int o = 0; o < 2; o++){
for (int p = 0; p < 2; p++){
System.out.println("" + i + j + k + l + m + n + o + p);
}
}
}
}
}
}
}
}
Do you have to use nested loops? Because this is trivially easy when you simply take advantage of the fact that the binary representation of all the numbers from 0 through 255 cover every permutation.
for (int i=0; i<256; i++) {
System.out.println(Integer.toBinaryString(i));
}

Just print the for variables (i...p) without accessing this obscure empty array.

Well, if it's OK to use some built-in classes, you can do this in the following way:
for (int i=0; i<256; i++){
System.out.println(Integer.toBinaryString(i));
}
And the second way (I believe you should use it, because looking by looking at it you can understand what's under the hood instead of "some magic", it uses bit mask):
for (int i=0;i<256;i++){
int mask = 256;
while (mask > 0){
if ((mask & i) == 0){
System.out.print("0");
} else {
System.out.print("1");
}
mask = mask >> 1;
}
System.out.println();
}

Here's my version. It uses recursion to convert base 2 to base 10 through repeated division:
public static void printBin()
{
for (int i = 0; i < 256; i++) {
int binary = decToBin(i, "");
// pad to give length of 8
System.out.println(String.format("%08d", binary));
}
}
public static int decToBin(int dec, String bin)
{
int quot = dec / 2;
int remainder = dec % 2;
if (quot == 0)
return Integer.parseInt("" + remainder + bin);
return decToBin(quot, "" + remainder + bin);
}

Heres another way of generating all the values using bit operations
public static void main(String[] args) {
int numBits = 8;
int val = 0;
int[] values = new int[]{0,1};
values[0] = 0;
values[1] = 1;
for (int i = 1; i < numBits; i++) {
int[] moreValues = new int[values.length * 2];
int start = (int)Math.pow(2, i);
for (int j = 0; j < values.length; j++) {
moreValues[j * 2] = values[j] << 1;
moreValues[j * 2 + 1] = values[j] << 1 | 1;
}
values = moreValues;
}
//print the values
for (int value: values) {
System.out.println(Integer.toBinaryString(value));
}
}
And another way, using bit operations and recursion
private static void generateNumbers(int number, int numBits, int currentBit) {
if (numBits == currentBit) {
Integer.toBinaryString(number);
return;
}
currentBit++;
generateNumbers(number << 1, numBits, currentBit);
generateNumbers(number << 1 | 1, numBits, currentBit);
}
public static void generateNumbers(int numBits) {
generateNumbers(0, 8, 1);
generateNumbers(1, 8, 1);
}
public static void main(String[] args) {
generateNumbers(8);
}

package org.cross.topology;
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
//System.out.println("sushil");
int digits=3;//Provide number of digits for which you want combinations of 0 and 1
int noof0and1=(int) Math.pow(2,digits)/*(2^digits)*/,combinations=(int) Math.pow(2,digits),secondloopcounter=0,temp=0;
String current_char="0";
int startindex=0,lastindex;
ArrayList<String> al=new ArrayList<String>(combinations);
for(int k=0;k<combinations;k++)
{
al.add("");
}
for(int i=1;i<=digits;i++)
{
noof0and1=noof0and1/2;
while(temp!=combinations)
{
temp=temp+noof0and1;
secondloopcounter++;
}
lastindex=noof0and1;
startindex=0;
for(int s=0;s<secondloopcounter;s++)
{
for(int j=startindex;j<lastindex;j++)
{
String temps=al.get(j)+current_char;
al.remove(j);
al.add(j, temps);
}
if(current_char.equals("0"))
{
current_char="1";
}
else
{
current_char="0";
}
startindex=lastindex;
lastindex=lastindex+noof0and1;
}
temp=0;
secondloopcounter=0;
}
for(int l=0;l<al.size();l++)
{
System.out.println(al.get(l));
}
}
}

Below is the solution using Recursion as an approach in java
public class NumberOfBinaryPatterns {
static int[] bitArray = new int[]{0,1};
public static void main(String args[])
{
System.out.println("Below are the patterns\n");
int numberOfBits=4; // It can be any value based on the requirement, In this case we can put this as 8
drawBinaryPattern(numberOfBits,"");
}
private static void drawBinaryPattern(int n,String seed)
{
if(n==0){
System.out.println(seed);
return;
}
for(int j=0;j<bitArray.length;j++)
{
String temp = seed+bitArray[j];
drawBinaryPattern(n-1,temp);
}
}
}

Do in php , very easy
Just convert every count of combinations in binary and add as many 0 as required to complete it in a byte representation.
for($c=1;$c<=pow(2,8);$c++)
{
$bin_str=base_convert($c,10,2); //converting combination number into binary string
$len_str=strlen($bin_str); // Length of string obtained
for($i=1;$i<=8-$len_str;$i++)
$bin_str="0".$bin_str; // adding as many 0 as required to complete in byte format
echo "<br>".$bin_str; //Displaying binary values in byte structure
}

Related

Algorithm for combinations of integer in an array

I am having difficulties for writing an algorithm that will create an array of arrays, from a single array of integers.
Say, I have an
int[] intArray = new int[] {1,2,3,4,5};
What I need from it is an array of an arrays that will look like this:
int[][] array = new int[][]{
{-1,2,3,4,5},
{1,-2,3,4,5},
{1,2,-3,4,5},
{1,2,3,-4,5},
{1,2,3,4,-5};
Thank you in advance!!
EDIT:
The following code works for the case if I want to have only one negative value. How about if I would like to have 2,3,4... negative values? Is there a way to make it more dynamic? For example, from {1,2,3,4,5}; to get: {-1,-2,3,4,5}, {-1,2,-3,4,5}, {-1,2,3,-4,5}, {-1,2,3,4,-5}, {1,-‌​2,-3,4,5},{1,-2,3,-4‌​,5}, {1,-2,3,4,-5}...‌​. or for 3 negative values: {-1,-2,-3,4,5}, {-1,-2,3,-4,5}, {-1,-2,3,4,-5}, {1,-2,-3,-4,5},‌ ​{1,-2,-3,4,-5}, {1,2,‌​-3,-4,-5}...etc I hope you get my point! Thanks again guys!!
You could try this:
int l = intArray.length;
int[][] newArray = new int[l][l];
for (int i = 0; i < l; i++) {
for (int j = 0; j < l; j++) {
newArray[i][j] = j == i ? intArray[j] * -1 : intArray[j];
}
}
newArray will have the values you are expecting.
how about
public class x
{
public static int[][] convert(int in[])
{
int s = in.length;
int out[][] = new int[s][s];
for (int i = 0; i < s; ++i) { // row loop
for (int j = 0; j < s; ++j) {
if (i == j)
out[i][j] = -in[j];
else
out[i][j] = in[i];
}
}
return out;
}
public static void print(int in[][])
{
for (int i = 0; i < in.length; ++i) {
String sep = "";
for (int j = 0; j < in[i].length; ++j) {
System.out.print(sep + in[i][j]);
sep = ", ";
}
System.out.println("");
}
}
public static void main(String argv[])
{
int in[] = { 1, 2, 3, 4, 5 };
int out[][];
out = convert(in);
print(out);
}
}
int[] intArray = new int[] {1,2,3,4,5};
int algoIntArray[][] = new int[intArray.length][intArray.length];
for(int i = 0; i < intArray.length; i++){
for (int j = 0; j < algoIntArray[i].length; j++){
if (i == j){
algoIntArray[i][j] = -intArray[j];
} else {
algoIntArray[i][j] = intArray[j];
}
}
}
This code will work for you!

Where are my arrays are out of bounds?

I have looked at other questions about out of bounds error and understood them, couldn't understand the fault in this code.
Question: A JAVA program that will read a boolean matrix corresponding to a relation R and output whether R is Reflexive, Symmetric, Anti-Symmetric and/or Transitive. Input to the program will be the size n of an n x n boolean matrix followed by the matrix elements.
The program must output a reason in the case that an input relation fails to have a certain property.
Solution: I have provided the code, it throws the "java.lang.ArrayIndexOutOfBoundsException" error at main and line 65. I can't see how my arrays are out of bounds
ERROR: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 at XYZ.BooleanMatrix.main(BooleanMatrix.java:65)
Code:
package XYZ;
import edu.princeton.cs.algs4.*;
public class BooleanMatrix {
// read matrix from standard input
public static boolean[][] read() {
int n = StdIn.readInt();
boolean[][] a = new boolean[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (StdIn.readInt() != 0)
a[i][j] = true;
}
}
return a;
}
// print matrix to standard output
public static void print(boolean[][] a) {
int n = a.length;
StdOut.println(n);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (a[i][j])
StdOut.print("1 ");
else
StdOut.print("0 ");
}
StdOut.println();
}
}
// random n-by-n matrix, where each entry is true with probability p
public static boolean[][] random(int n, double p) {
boolean[][] a = new boolean[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
a[i][j] = StdRandom.bernoulli(p);
}
}
return a;
}
// display the matrix using standard draw
// depending on variable which, plot true or false entries in foreground
// color
public static void show(boolean[][] a, boolean which) {
int n = a.length;
StdDraw.setXscale(0, n - 1);
StdDraw.setYscale(0, n - 1);
double r = 0.5;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (a[i][j] == which) {
StdDraw.filledSquare(j, n - i - 1, r);
}
}
}
}
// test client
public static void main(String[] args) {
int n = Integer.parseInt(args[0]); //LINE 65
double p = Double.parseDouble(args[1]);
boolean[][] a = random(n, p);
print(a);
show(a, true);
}}
I don´t know the exact working of StdDraw.setXscale(0, n - 1); but i think it creates a table with n-1 rows. so if you try to fill it with n rows there will be an out of bounds error. try using this in line 47:
StdDraw.setXscale(0, n);
StdDraw.setYscale(0, n);
As stated in the comments below your post: if you don´t enter any arguments when calling the program you´ll get an out of bounds exception because the program expects arguments in the aray and there aren´t any.
To provide arguments open command line and call /java yourcompiledjavafile arg[0] arg[1]

Radix Sort an array of strings using a queue in Java

I don't completely understand radix sort so that is making this more difficult for me to write this program. I need to sort an array of strings that is read from a .txt file. I was able to read the file and enter the strings into an array. A string can contain letters or special characters. I need help with writing the code for sorting the array. It feels like I'm close to the having the correct code, but I'm stuck and don't know what else to do. It would be greatly appreciated if I could get help and point me in the right direction.
Each string has the same amount of characters. I am also using a stackPackage that contains a queue class. I need to modify the code the my professor gave me to sort strings.
Here is the code I started with:
import queuepackage.*;
public class Radix {
public static void main(String[] args) {
int[] array = {143,934,782,687,555,222,111,213,842,2000};
printArray(array);
radixSort(array, 1000);
printArray(array);
}
public static void printArray(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + ", ");
}
System.out.println();
}
public static void radixSort(int[] array, int maxPowerOf10) {
Queue[] queueArray = new Queue[10];
for (int queueNum = 0; queueNum < 10; queueNum++) {
queueArray[queueNum] = new Queue();
}
for (int powerOf10 = 1; powerOf10 <= maxPowerOf10; powerOf10 = powerOf10 * 10) {
for (int item = 0; item < array.length; item++) {
int digit = getDigit(array[item], powerOf10);
queueArray[digit].enqueue(new Integer(array[item]));
}
int item = 0;
for (int queueNum = 0; queueNum < 10; queueNum++) {
while (!queueArray[queueNum].isEmpty()) {
array[item] = ((Integer) queueArray[queueNum].dequeue()).intValue();
item++;
}
}
}
}
public static int getDigit(int number, int powerOf10) {
return (number/powerOf10)%10;
}
}
This is what I have.
length = length of the array
wordLen = length of a string in the array
Here is my current code of the radixSort method:
public static void radixSort(String[] array, int length, int wordLen) {
Queue[] queueArray = new Queue[256];
for (int queueNum = 0; queueNum < 256; queueNum++) {
queueArray[queueNum] = new Queue();
}
for (int len = 0; len < wordLen; len++) {
for (int item = 0; item < length; item++) {
int letter = array[item].charAt(len);
queueArray[letter].enqueue(new String(array[item]));
}
int item = 0;
for (int queueNum = 0; queueNum < 256; queueNum++) {
while (!queueArray[queueNum].isEmpty()) {
array[item] = ((String) queueArray[queueNum].dequeue()).toString();
item++;
}
}
}
}
It's almost working, you just need to iterate the word backwards, look at the second for loop
public static void radixSort(String[] array, int length, int wordLen) {
Queue[] queueArray = new Queue[256];
for (int queueNum = 0; queueNum < 256; queueNum++) {
queueArray[queueNum] = new Queue();
}
for (int len = wordLen-1; len >= 0; len--) {
for (int item = 0; item < length; item++) {
int letter = array[item].charAt(len);
queueArray[letter].enqueue(new String(array[item]));
}
int item = 0;
for (int queueNum = 0; queueNum < 256; queueNum++) {
while (!queueArray[queueNum].isEmpty()) {
array[item] = ((String) queueArray[queueNum].dequeue()).toString(); // Here you need to swap the
item++;
}
}
}
}
If you iterate it in the regular way you are losing the previous information, so the last characters are the most important
Good luck!
The only mistake in your code that I can see is that in RadixSort you wanna start with sorting by the least significant digit and move up to more significant digits as you go. In this case however you are starting at the left and going right which is the wrong way around for natural order String sorting.
This however can be easily fixed by changing for (int len = 0; len < wordLen; len++) into for (int len = wordLen - 1; len >= 0; len--).
Changing for (int len = 0; len < wordLen; len++) into for (int len = wordLen - 1; len >= 0; len--) worked and makes my program does what it is supposed to

Least Common Subsequence with optimized space (two columns, since it's Markovian)

I'm trying to write LCS of two String objects using bottom-up dynamic programming. I'm able to get it to work properly with O(mn) space. However, as I could see, I don't need all the previous columns. So, I tried to modify it to get it fit in 2 columns so space become O(m). However, it's not working for all inputs (for example, to this: abcabc and abcbcca). What am I missing here? NOT HW, NOT CONTEST nothing. Practicing DP.
public int longestCommonSubsequence(String input) {
char[] firstStr = this.string.toCharArray();
char[] secondStr = input.toCharArray();
int[][] maxLength = new int[firstStr.length+1][2];
for(int i=0; i <= firstStr.length; i++) {
maxLength[i][0] = 0;
}
for(int j=0; j < 2; j++) {
maxLength[0][j] = 0;
}
for(int i=0; i < firstStr.length; i++) {
for(int j=0; j < secondStr.length; j++) {
if(firstStr[i] == secondStr[j]) {
maxLength[i+1][1] = 1 + maxLength[i][0];
}
else {
maxLength[i+1][1] = maxLength[i][1]>maxLength[i+1][0]?maxLength[i][1]:maxLength[i+1][0];
}
}
//Copy second row to first row
for(int l =0; l < firstStr.length; l++) {
maxLength[l][0] = maxLength[l][1];
}
}
return maxLength[firstStr.length -1][0];
}
This has two problems:
if(firstStr[i] == secondStr[j]) {
maxLength[i+1][1] = 1 + maxLength[i][0];
// check here if maxLength[i+1][1] is greather than the last max length
}
else {
maxLength[i+1][1] = maxLength[i][1]>maxLength[i+1][0]?maxLength[i][1]:maxLength[i+1][0];
// absolutely wrong: maxLength[i+1][1] = 0;
}
Here can see the algorithm with micro optimization.
public static int lcs(String s0, String s1) {
int maxLength = 0;
int [][]lengths = new int[2][s1.length()+1];
for (int i = 0; i < s0.length(); i++) {
for (int j = 0; j < s1.length(); j++) {
if (s0.charAt(i) == s1.charAt(j)) {
lengths[0][j+1] = lengths[1][j] + 1;
if (lengths[0][j+1] > maxLength) {
maxLength = lengths[0][j+1];
}
} else {
lengths[0][j+1] = 0;
}
}
int []temp = lengths[0];
lengths[0] = lengths[1];
lengths[1] = temp;
}
return maxLength;
}

enumerating through every five card combination

I have just had a brain block, I have a Deck object and want to get every 5 card combination from it in a iterative manner. Could someone show me how to do this, I would imagine it would be:
for(int i =0; i <52; i++){
for(int j = i + 1 ; j < 52; j++){
for(int k = j + 1; k < 52; k++{
for(int l = k + 1; l < 52; l++){
for(int m = l + 1; m < 52; m++){
}
}
}
}
}
Is this correct?
Thanks
Yes, that works fine. If you want to enumerate all n-card combinations, this doesn't work.
For that, you'd need recursion. Put card 0 in slot 0. Recursively enumerate all n-1 card hands (excluding 0) in the remaining n-1 slots. Repeat, with card 1 in slot 0. Pretty easy.
EDIT: some code:
private static final int NUM_CARDS = 52;
public static void main(String[] args) {
enumerateAllHands(Integer.parseInt(args[0]));
}
private static void enumerateAllHands(int n) {
if (n > NUM_CARDS) {
throw new IllegalArgumentException();
}
int[] cards = new int[n];
BitSet cardsUsed = new BitSet();
enumerate(cards, 0, cardsUsed);
}
private static void enumerate(int[] cards, int from, BitSet cardsUsed) {
if (from == cards.length) {
emit(cards);
} else {
for (int i = 0; i < NUM_CARDS; i++) {
if (!cardsUsed.get(i)) {
cards[from] = i;
cardsUsed.set(i);
enumerate(cards, from + 1, cardsUsed);
cardsUsed.clear(i);
}
}
}
}
private static void emit(int[] cards) {
System.out.println(Arrays.toString(cards));
}

Categories

Resources