I am working on a project involving \"Dynamic Programming\" and am struck on this trivial thing, please help.
Suppose I take 4 as an input, I want to display somethi
I'm a bit lost as to how you'd apply dynamic programming to this. It's just a matter of counting from 0 to one less than the specified maximum value (where the maximum value is 1 shifted left the specified number of bits).
Edit: I should add that there are other possibilities (e.g., gray codes) but absent some reason to do otherwise, simple binary counting is probably the simplest to implement.
int x = 5;
for(int i = 0; i < (1 << x); i++){
System.out.println(Integer.toBinaryString(i));
}
here is the code is to find the combination
/*
* 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.
*/
package rotateimage;
/**
*
* @author ANGEL
*/
public class BinaryPermutaion {
public static void main(String[] args) {
//object creation
BinaryPermutaion binaryDigit=new BinaryPermutaion();
//Recursive call of the function to print the binary string combinations
binaryDigit.printBinary("", 4);
}
/**
*
* @param soFar String to be printed
* @param iterations number of combinations
*/
public void printBinary(String soFar, int iterations) {
if(iterations == 0) {
System.out.println(soFar);
}
else {
printBinary(soFar + "0", iterations - 1);
printBinary(soFar + "1", iterations - 1);
}
}
}
n
i=0
to (2^n) - 1
i
bitmask each bit of i
and display.public void outBinary(int value){
for (int i = 0; i < Math.pow(2, value); i++) {
System.out.println(Integer.toBinaryString(i));
}
}
with leading zeros something like that
for (int i = 0; i < Math.pow(2, value); i++) {
StringBuilder binary = new StringBuilder(Integer.toBinaryString(i));
for(int j = binary.length(); j < value; j++) {
binary.insert( 0, '0' );
}
System.out.println(binary);
}
Either use phoxis's very nice solution, or just iterate them lexicographically (this is really the same solution!): Given a binary string of a given length, get the next lexicographic string by finding the rightmost zero entry, change it to a 1
, and change everything to the right of it back to a 0
, e.g.
0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1