Reputation: 9057
I want an algorithm to do the following: When the input is for example 3 I want every 3-bit number to be produced like the following:
000
001
010
011
100
101
110
111
EDIT: Thank you for all your answers, But I'd prefer an algorithm that treats '1's and '0's as characters and the whole answer as an string so I could extend the answer for characters as well. Like producing every possible combination of a,b,c
with the length of 3.
Upvotes: 0
Views: 286
Reputation: 536
Here is some pseudo code which should help you :
function listNumbers (bits : Int) : List<String> {
l = [];
if (bits == 0) {
l.append("");
} else {
prev = listNumbers(bits-1);
for (number in prev) {
l.append("0" + number);
l.append("1" + number);
}
}
return l;
}
Upvotes: 1
Reputation: 1112
What you want do do is generate combinations the code in the article shouldn't be too hard to generalize for all characters using modular arithmetic. Or alternately you map characters onto numeric values, calculate the permutations and then map back to characters.
Upvotes: 0
Reputation: 5131
Maybe you could use a recursive algorithm. This is written in Java:
public void printBin(String soFar, int iterations) {
if(iterations == 0) {
System.out.println(soFar);
}
else {
printBin(soFar + "0", iterations - 1);
printBin(soFar + "1", iterations - 1);
}
}
You would execute this like this:
printBin("", 3);
That would give you all possible binary numbers with 3 digits.
Note, however, that with really big amounts of digits, you might get overflows.
Hope this helped!
Upvotes: 0
Reputation: 14874
It means every number between zero and 2^n-1 which n is your bit number
Upvotes: 1
Reputation: 258618
A straight-forward algorithm would be:
calculate 2^n-1
; in your case, 7
.
for i = 0 : 7
convert i
to binary form
output binary form
Upvotes: 7