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

Beginning Algorithms (2006)

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

Appendix D

Exercise 3 Solution

package com.wrox.algorithms.maps;

import com.wrox.algorithms.iteration.Iterator; import com.wrox.algorithms.sets.Set;

public class MapSet implements Set {

private static final Object PRESENT = new Object();

private final Map _map;

public MapSet(Map map) {

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

}

public boolean contains(Object value) { return _map.contains(value);

}

public boolean add(Object value) {

return _map.set(value, PRESENT) == null;

}

public boolean delete(Object value) { return _map.delete(value) == PRESENT;

}

public Iterator iterator() {

return new MapKeyIterator(_map.iterator());

}

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

}

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

}

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

}

}

Exercise 4 Solution

package com.wrox.algorithms.maps;

import com.wrox.algorithms.iteration.EmptyIterator;

import com.wrox.algorithms.iteration.Iterator;

public final class EmptyMap implements Map {

534

Answers to Exercises

public static final EmptyMap INSTANCE = new EmptyMap();

private EmptyMap() {

}

public Object get(Object key) { return null;

}

public Object set(Object key, Object value) { throw new UnsupportedOperationException();

}

public Object delete(Object key) {

throw new UnsupportedOperationException();

}

public boolean contains(Object key) {

return false;

}

public void clear() {

}

public int size() { return 0;

}

public boolean isEmpty() { return true;

}

public Iterator iterator() { return EmptyIterator.INSTANCE;

}

}

Chapter 14

Exercise

1.Create an iterative form of search().

Exercise 1 Solution

private Node search(Node node, CharSequence word, int index) { assert word != null : “word can’t be null”;

while (node != null) {

char c = word.charAt(index);

if (c == node.getChar()) {

if (index + 1 < word.length()) { node = node.getChild();

} else { break;

535

Appendix D

}

} else {

node = c < node.getChar() ? node.getSmaller() : node.getLarger();

}

}

return node;

}

Chapter 15

Exercises

1.Re-implement the traverse() method on Node to return the entries in key order.

2.Re-implement the indexOf() method on Node to perform a binary search instead of a linear search.

Exercise 1 Solution

public void traverse(List list) {

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

Iterator children = _children.iterator();

Iterator entries = _entries.iterator();

children.first();

entries.first();

while (!children.isDone() || !entries.isDone()) { if (!children.isDone()) {

((Node) children.current()).inOrderTraversal(list);

children.next();

}

if (!entries.isDone()) {

Entry entry = (Entry) entries.current(); if (!entry.isDeleted()) {

list.add(entry);

}

entries.next();

}

}

}

Exercise 2 Solution

private int indexOf(Object key) { int lowerIndex = 0;

int upperIndex = _entries.size() - 1;

while (lowerIndex <= upperIndex) {

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

int cmp = _comparator.compare(key,

536

Answers to Exercises

((Entry) _entries.get(index)).getKey());

if (cmp == 0) { return index;

}else if (cmp < 0) { upperIndex = index - 1;

}else {

lowerIndex = index + 1;

}

}

return -(lowerIndex + 1);

}

Chapter 18

Exercises

1.Implement a brute-force solution to the closest pair problem.

2.Optimize the plane sweep algorithm so that points too distant in the vertical direction are ignored.

Exercise 1 Solution

package com.wrox.algorithms.geometry;

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

import com.wrox.algorithms.sets.ListSet; import com.wrox.algorithms.sets.Set;

import com.wrox.algorithms.bsearch.ListInserter;

import com.wrox.algorithms.bsearch.IterativeBinaryListSearcher;

public final class BruteForceClosestPairFinder implements ClosestPairFinder { public static final BruteForceClosestPairFinder INSTANCE = new

BruteForceClosestPairFinder();

private BruteForceClosestPairFinder() {

}

public Set findClosestPair(Set points) {

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

if (points.size() < 2) { return null;

}

List list = sortPoints(points);

Point p = null;

537

Appendix D

Point q = null;

double distance = Double.MAX_VALUE;

for (int i = 0; i < list.size(); i++) { Point r = (Point) list.get(i);

for (int j = 0; j < list.size(); j++) { Point s = (Point) list.get(j);

if (r != s && r.distance(s) < distance) { distance = r.distance(s);

p = r; q = s;

}

}

}

return createPointPair(p, q);

}

private static List sortPoints(Set points) {

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

List list = new ArrayList(points.size());

Iterator i = points.iterator();

for (i.first(); !i.isDone(); i.next()) { INSERTER.insert(list, i.current());

}

return list;

}

private Set createPointPair(Point p, Point q) { Set result = new ListSet();

result.add(p);

result.add(q); return result;

}

}

Exercise 2 Solution

package com.wrox.algorithms.geometry;

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

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

import com.wrox.algorithms.lists.List; import com.wrox.algorithms.sets.ListSet; import com.wrox.algorithms.sets.Set;

public final class PlaneSweepOptimizedClosestPairFinder implements ClosestPairFinder {

538

Answers to Exercises

public static final PlaneSweepOptimizedClosestPairFinder INSTANCE = new PlaneSweepOptimizedClosestPairFinder();

private static final ListInserter INSERTER = new ListInserter(

new IterativeBinaryListSearcher(XYPointComparator.INSTANCE));

private PlaneSweepOptimizedClosestPairFinder() {

}

public Set findClosestPair(Set points) {

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

if (points.size() < 2) { return null;

}

List sortedPoints = sortPoints(points);

Point p = (Point) sortedPoints.get(0);

Point q = (Point) sortedPoints.get(1);

return findClosestPair(p, q, sortedPoints);

}

private Set findClosestPair(Point p, Point q, List sortedPoints) { Set result = createPointPair(p, q);

double distance = p.distance(q); int dragPoint = 0;

for (int i = 2; i < sortedPoints.size(); ++i) { Point r = (Point) sortedPoints.get(i); double sweepX = r.getX();

double dragX = sweepX - distance;

while (((Point) sortedPoints.get(dragPoint)).getX() < dragX) { ++dragPoint;

}

for (int j = dragPoint; j < i; ++j) {

Point test = (Point) sortedPoints.get(j);

if (Math.abs(r.getY() - test.getY()) > distance) { continue;

}

double checkDistance = r.distance(test); if (checkDistance < distance) {

distance = checkDistance;

result = createPointPair(r, test);

}

}

}

return result;

}

private static List sortPoints(Set points) {

539

Appendix D

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

List list = new ArrayList(points.size());

Iterator i = points.iterator();

for (i.first(); !i.isDone(); i.next()) { INSERTER.insert(list, i.current());

}

return list;

}

private Set createPointPair(Point p, Point q) { Set result = new ListSet();

result.add(p);

result.add(q); return result;

}

}

540

Index

NUMBERS

0(1) data lookup, achieving with hashing, 265

4-sort example, 146–147

A

abstract test class

creating for generic suite of set tests, 297–299

for FIFO queue, 78–80

AbstractFifoQueueTestCase class, explanation of, 80

AbstractHashtableTestCase class effect of, 274

using with hash tables and bucketing, 283 using with hash tables and linear probing, 277

AbstractListSearcherTestCase using with list searcher, 204

using with recursive binary searcher, 206

AbstractListSorter, testing, 125–126 AbstractListSorterTest, extending for

shellsort, 148–149

AbstractListTestCase class extending, 47

extending for array lists, 59–60 extending for linked lists, 66–67 extending for undo/redo, 109

AbstractMapTest class, extending for list maps, 331

Index

Index

AbstractMapTestCase class creating, 322–325 extending for B-Trees, 382

extending for hash maps, 336 using with tree maps, 342

AbstractPriorityQueue test case, creating, 179–182

AbstractPriorityQueueTestCase extending for sorted list priority queue, 184 extending in unsorted list priority queue, 182

AbstractSetTestCase class using with hash sets, 308 using with list sets, 304 using with set tests, 300 using with tree sets, 314

AbstractStringSearcherTestCase class, extending for brute-force algorithm, 401

accessors for coordinates, providing for Point class, 445

add() method testing for lists, 49

using with array lists, 62 using with hash sets, 308

using with hash tables, 288–290

using with hash tables and bucketing, 285 using with hash tables and linear probing, 279 using with list sets, 305

using with lists, 44 using with set tests, 301

using with ternary search trees, 367, 368