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

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 { 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 iterator() { ... } // Binary strings iterator. private class BinaryStringsIterator implements Iterator { 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

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!