Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Beginning Algorithms (2006)

.pdf
Скачиваний:
255
Добавлен:
17.08.2013
Размер:
9.67 Mб
Скачать

Appendix D

return;

}

int index = lowerIndex + (upperIndex - lowerIndex) / 2;

tree.insert(list.get(index)); preOrderInsert(tree, list, lowerIndex, index - 1); preOrderInsert(tree, list, index + 1, upperIndex);

}

Exercise 8 Solution

public int size() { return size(this);

}

private int size(Node node) { if (node == null) {

return 0;

}

return 1 + size(node.getSmaller()) + size(node.getLarger());

}

Exercise 9 Solution

public int height() { return height(this) - 1;

}

private int height(Node node) { if (node == null) {

return 0;

}

return 1 + Math.max(height(node.getSmaller()), height(node.getLarger()));

}

Chapter 11

Exercises

1.Modify BucketingHashtable to always use a prime number of buckets. What effect (if any) does this have on performance?

2.Modify LinearProbingHashtable to maintain the number of values in the table, rather than calculate it every time.

3.Modify BucketingHashtable to maintain the number of values in the table, rather than calculate it every time.

4.Create an iterator that provides access to all of the entries in a BucketingHashtable.

524

Answers to Exercises

Exercise 1 Solution

package com.wrox.algorithms.hashing;

public final class SimplePrimeNumberGenerator {

public static final SimplePrimeNumberGenerator INSTANCE =

new SimplePrimeNumberGenerator();

private SimplePrimeNumberGenerator() {

}

public int generate(int candidate) { int prime = candidate;

while (!isPrime(prime)) { ++prime;

}

return prime;

}

private boolean isPrime(int candidate) {

for (int i = candidate / 2; i >= 2; --i) { if (candidate % i == 0) {

return false;

}

}

return true;

}

}

package com.wrox.algorithms.hashing;

import com.wrox.algorithms.iteration.Iterator; import com.wrox.algorithms.lists.LinkedList; import com.wrox.algorithms.lists.List;

public class BucketingHashtable implements Hashtable {

...

public BucketingHashtable(int initialCapacity, float loadFactor) {

assert initialCapacity > 0 : “initialCapacity can’t be < 1”; assert loadFactor > 0 : “loadFactor can’t be <= 0”;

_loadFactor = loadFactor; _buckets = new Bucket[

SimplePrimeNumberGenerator.INSTANCE.generate(initialCapacity)];

}

...

}

525

Appendix D

Exercise 2 Solution

package com.wrox.algorithms.hashing;

public class LinearProbingHashtable implements Hashtable {

...

private int _size;

public void add(Object value) { ensureCapacityForOneMore();

int index = indexFor(value);

if (_values[index] == null) { _values[index] = value; ++_size;

}

}

public int size() { return _size;

}

}

Exercise 3 Solution

package com.wrox.algorithms.hashing;

import com.wrox.algorithms.iteration.Iterator; import com.wrox.algorithms.lists.LinkedList; import com.wrox.algorithms.lists.List;

public class BucketingHashtable implements Hashtable {

...

private int _size;

public void add(Object value) { List bucket = bucketFor(value);

if (!bucket.contains(value)) { bucket.add(value); ++_size;

maintainLoad();

}

}

public int size() { return _size;

}

}

526

Answers to Exercises

Exercise 4 Solution

package com.wrox.algorithms.hashing;

import com.wrox.algorithms.iteration.EmptyIterator; import com.wrox.algorithms.iteration.Iterable; import com.wrox.algorithms.iteration.Iterator;

import com.wrox.algorithms.iteration.IteratorOutOfBoundsException;

public class HashtableIterator implements Iterator { private final Iterator _buckets;

private Iterator _values = EmptyIterator.INSTANCE;

public HashtableIterator(Iterator buckets) {

assert buckets != null : “buckets can’t be null”; _buckets = buckets;

}

public void first() { _buckets.first();

_values = EmptyIterator.INSTANCE; next();

}

public void last() { _buckets.last();

_values = EmptyIterator.INSTANCE; previous();

}

public boolean isDone() {

return _values.isDone() && _buckets.isDone();

}

public void next() { for (_values.next();

_values.isDone() && !_buckets.isDone(); _buckets.next()) {

Iterable bucket = (Iterable) _buckets.current(); if (bucket != null) {

_values = bucket.iterator(); _values.first();

}

}

}

public void previous() { for (_values.previous();

_values.isDone() && !_buckets.isDone(); _buckets.previous()) {

Iterable bucket = (Iterable) _buckets.current(); if (bucket != null) {

_values = bucket.iterator(); _values.last();

}

527

Appendix D

}

}

public Object current() throws IteratorOutOfBoundsException { if (isDone()) {

throw new IteratorOutOfBoundsException();

}

return _values.current();

}

}

Chapter 12

Exercises

1.Write a method that takes two sets and determines whether they are equal.

2.Write a method that takes two sets and produces a third set containing the union of the first two.

3.Write a method that takes two sets and produces a third set containing the intersection of the first two.

4.Write a method that takes two sets and produces a third set containing the difference between the first two.

5.Update the delete() method in HashSet to free the bucket if it’s empty.

6.Create a set implementation that uses a sorted list.

7.Create a set implementation that is always empty and throws UnsupportedOperationException whenever an attempt is made to modify it.

Exercise 1 Solution

public boolean equals(Set a, Set b) { assert a != null : “a can’t be null”; assert b != null : “b can’t be null”;

Iterator i = a.iterator();

for (i.first(); !i.isDone(); i.next()) { if (!b.contains(i.current())) {

return false;

}

}

return a.size() == b.size();

}

}

Exercise 2 Solution

public Set union(Set a, Set b) {

assert a != null : “a can’t be null”;

528

Answers to Exercises

assert b != null : “b can’t be null”;

Set result = new HashSet();

Iterator i = a.iterator();

for (i.first(); !i.isDone(); i.next()) { result.add(i.current());

}

Iterator j = b.iterator();

for (j.first(); !j.isDone(); j.next()) { result.add(j.current());

}

return result;

}

Exercise 3 Solution

public Set intersection(Set a, Set b) { assert a != null : “a can’t be null”; assert b != null : “b can’t be null”;

Set result = new HashSet();

Iterator i = a.iterator();

for (i.first(); !i.isDone(); i.next()) { if (b.contains(i.current())) { result.add(i.current());

}

}

return result;

}

Exercise 4 Solution

public Set difference(Set a, Set b) { assert a != null : “a can’t be null”; assert b != null : “b can’t be null”;

Set result = new HashSet();

Iterator i = a.iterator();

for (i.first(); !i.isDone(); i.next()) { if (!b.contains(i.current())) { result.add(i.current());

}

}

return result;

}

529

Appendix D

Exercise 5 Solution

public boolean delete(Object value) {

int bucketIndex = bucketIndexFor(value); ListSet bucket = _buckets[bucketIndex];

if (bucket != null && bucket.delete(value)) { --_size;

if (bucket.isEmpty()) { _buckets[bucketIndex] = null;

}

return true;

}

return false;

}

Exercise 6 Solution

package com.wrox.algorithms.sets;

import com.wrox.algorithms.bsearch.IterativeBinaryListSearcher; import com.wrox.algorithms.bsearch.ListSearcher;

import com.wrox.algorithms.iteration.Iterator; import com.wrox.algorithms.lists.ArrayList; import com.wrox.algorithms.lists.List;

import com.wrox.algorithms.sorting.Comparator; import com.wrox.algorithms.sorting.NaturalComparator;

public class SortedListSet implements Set { private final List _values = new ArrayList(); private final ListSearcher _searcher;

public SortedListSet() { this(NaturalComparator.INSTANCE);

}

public SortedListSet(Comparator comparator) {

_searcher = new IterativeBinaryListSearcher(comparator);

}

public boolean contains(Object value) { return indexOf(value) >= 0;

}

public boolean add(Object value) { int index = indexOf(value); if (index < 0) {

_values.insert(-(index + 1), value); return true;

}

_values.set(index, value); return false;

}

public boolean delete(Object value) {

530

Answers to Exercises

int index = indexOf(value); if (index >= 0) {

_values.delete(index); return true;

}

return false;

}

public Iterator iterator() { return _values.iterator();

}

public void clear() { _values.clear();

}

public int size() { return _values.size();

}

public boolean isEmpty() { return _values.isEmpty();

}

private int indexOf(Object value) {

return _searcher.search(_values, value);

}

}

Exercise 7 Solution

package com.wrox.algorithms.sets;

import com.wrox.algorithms.iteration.EmptyIterator; import com.wrox.algorithms.iteration.Iterator;

public final class EmptySet implements Set {

public static final EmptySet INSTANCE = new EmptySet();

private EmptySet() {

}

public boolean contains(Object value) {

return false;

}

public boolean add(Object value) {

throw new UnsupportedOperationException();

}

public boolean delete(Object value) {

throw new UnsupportedOperationException();

}

public void clear() {

531

Appendix D

}

public int size() { return 0;

}

public boolean isEmpty() { return true;

}

public Iterator iterator() { return EmptyIterator.INSTANCE;

}

Chapter 13

Exercises

1.Create an iterator that returns only the keys contained within a map.

2.Create an iterator that returns only the values contained within a map.

3.Create a set implementation that uses a map as the underlying storage mechanism for the values.

4.Create an empty map that throws UnsupportedOperationException anytime an attempt is made to modify it.

Exercise 1 Solution

package com.wrox.algorithms.maps;

import com.wrox.algorithms.iteration.Iterator;

import com.wrox.algorithms.iteration.IteratorOutOfBoundsException;

public class MapKeyIterator implements Iterator { private final Iterator _entries;

public MapKeyIterator(Iterator entries) {

assert entries != null : “entries can’t be null”; _entries = entries;

}

public void first() { _entries.first();

}

public void last() { _entries.last();

}

public boolean isDone() { return _entries.isDone();

532

Answers to Exercises

}

public void next() { _entries.next();

}

public void previous() {

_entries.previous();

}

public Object current() throws IteratorOutOfBoundsException { return ((Map.Entry) _entries.current()).getKey();

}

}

Exercise 2 Solution

package com.wrox.algorithms.maps;

import com.wrox.algorithms.iteration.Iterator;

import com.wrox.algorithms.iteration.IteratorOutOfBoundsException;

public class MapValueIterator implements Iterator { private final Iterator _entries;

public MapValueIterator(Iterator entries) {

assert entries != null : “entries can’t be null”; _entries = entries;

}

public void first() { _entries.first();

}

public void last() { _entries.last();

}

public boolean isDone() { return _entries.isDone();

}

public void next() { _entries.next();

}

public void previous() { _entries.previous();

}

public Object current() throws IteratorOutOfBoundsException { return ((Map.Entry) _entries.current()).getValue();

}

}

533