Skip to content

Commit

Permalink
Chapter 3: Add Exercise 3-4
Browse files Browse the repository at this point in the history
  • Loading branch information
asankov committed May 9, 2020
1 parent 5789612 commit a153095
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 13 deletions.
24 changes: 12 additions & 12 deletions chapter-3/3.5-java/Markov.java
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,8 @@ public void generate(int words) {
if (suf.equals(NON_WORD))
break;
System.out.print(suf + " ");
prefix.pref.removeElementAt(0);
prefix.pref.addElement(suf);
prefix.pref[0] = prefix.pref[1];
prefix.pref[1] = suf;
}
}

Expand All @@ -67,42 +67,42 @@ public void add(String word) {
statetab.put(prefix.clone(), suf);
}
suf.addElement(word);
prefix.pref.removeElementAt(0);
prefix.pref.addElement(word);
prefix.pref[0] = prefix.pref[1];
prefix.pref[1] = word;
}
}

class Prefix {

private static final int MULTIPLIER = 31;

public Vector<String> pref;
public String[] pref;

public static Prefix from(Integer size, String value) {
Prefix p = new Prefix();
p.pref = new Vector<>();
p.pref = new String[size];
for (int i = 0; i < size; i++)
p.pref.add(value);
p.pref[i] = value;
return p;
}

public Prefix clone() {
Prefix n = new Prefix();
n.pref = (Vector) this.pref.clone();
n.pref = this.pref.clone();
return n;
}

public int hashCode() {
int h = 0;
for (int i = 0; i < pref.size(); i++)
h = MULTIPLIER * h + pref.elementAt(i).hashCode();
for (int i = 0; i < pref.length; i++)
h = MULTIPLIER * h + pref[i].hashCode();
return h;
}

public boolean equals(Object o) {
Prefix p = (Prefix) o;
for (int i = 0; i < pref.size(); i++)
if (!pref.elementAt(i).equals(p.pref.elementAt(i)))
for (int i = 0; i < pref.length; i++)
if (!this.pref[i].equals(p.pref[i]))
return false;
return true;
}
Expand Down
8 changes: 7 additions & 1 deletion chapter-3/3.5-java/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,10 @@
- Remove use of deprecated constructor of `StreamTokenizer`
- Static constructor, instead of constructors with fields that differ from the fields of the class

Changes applied in [this commit](https://github.com/asankov/the-practice-of-programming/commit/793994dae973f3d4d9a14224fb511f9d6fe9de82).
Changes applied in [this commit](https://github.com/asankov/the-practice-of-programming/commit/793994dae973f3d4d9a14224fb511f9d6fe9de82).

#### Exercise 3-4
Revise the Java version of `markov` to use an array instead of a `Vector` for the prefix in the `State` class.

*Answer:* An array makes more sense than `Vector`, because the size is fixed and known when the object is instantiated.
Therefore, we don't need data struct that can grow and shrink dinamically.

0 comments on commit a153095

Please sign in to comment.