Implement an immutable, iterable data type BinaryStrings in BinaryStrings.java t
ID: 3729167 • Letter: I
Question
Implement an immutable, iterable data type BinaryStrings in BinaryStrings.java to systematically iterate over length-n binary strings.
import edu.princeton.cs.algs4.StdOut;
import java.util.Iterator;
// An immutable data type to systematically iterate over length-n binary
// strings.
public class BinaryStrings implements Iterable<String> {
private final int n; // need all binary strings of length n
// Construct an iterable BinaryStrings object given the length of binary
// strings needed.
public BinaryStrings(int n) {
...
}
// A BinaryStringsIterator object.
public Iterator<String> iterator() {
...
}
// Binary strings iterator.
private class BinaryStringsIterator implements Iterator<String> {
private int count = 0; // number of binary strings returned
private int p = 0; // current number
// Are there anymore length-n binary strings left to be iterated?
public boolean hasNext() {
...
}
// The next length-n binary string.
public String next() {
...
}
// Remove is not supported.
public void remove() {
// nothing to do
}
// The n-bit representation of x.
private String binary(int x) {
String s = Integer.toBinaryString(x);
int padding = n - s.length();
for (int i = 1; i <= padding; i++) {
s = "0" + s;
}
return s;
}
}
// Test client. [DO NOt EDIT]
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
for (String s : new BinaryStrings(n)) {
StdOut.println(s);
}
}
$ java BinaryStrings 4
0000
0001
0010
0011
0100
0101
0110
1000
1001
1010
1011
1100
1101
1110
1111
Explanation / Answer
import edu.princeton.cs.algs4.StdOut;
import java.util.Iterator;
public class BinaryStrings implements Iterable<String>
{
private final int n;
public BinaryStrings(int n)
{
this.n = n;
}
public Iterator<String> iterator()
{
return new BinaryStringsIterator();
}
private class BinaryStringsIterator implements Iterator<String>
{
private int count = 0;
private int p = 0;
public boolean hasNext()
{
p = count;
return count < Math.pow(2, n);
}
public String next()
{
count = count + 1;
return binary(p);
}
public void remove()
{
// nothing to do
}
private String binary(int x)
{
String s = Integer.toBinaryString(x);
int padding = n - s.length();
for (int i = 1; i <= padding; i++)
{
s = "0" + s;
}
return s;
}
}
public static void main(String[] args){
int n = Integer.parseInt(args[0]);
for (String s : new BinaryStrings(n))
{
StdOut.println(s);
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.