O'Reilly logo

Beginning Algorithms by James Ross, Simon Harris

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Appendix D. Answers to Exercises

The solutions provided in this appendix are sample answers. Not every chapter had exercises at the end, but it is hoped that the ones provided will give you ample opportunity to put what you've learned into practice. We encourage you to experiment with each chapter's concepts.

Exercises

  1. Create an iterator that only returns the value of every nth element, where n is any integer greater than zero.

  2. Create a predicate that performs a Boolean AND (&&) of two other predicates.

  3. Re-implement PowerCalculator using recursion instead of iteration.

  4. Replace the use of arrays with iterators in the recursive directory tree printer.

  5. Create an iterator that holds only a single value.

  6. Create an empty iterator that is always done.

Exercise 1 Solution

package com.wrox.algorithms.iteration;

public class SkipIterator implements Iterator {
    private final Iterator _iterator;
    private final int _skip;

    public SkipIterator(Iterator iterator, int skip) {
        assert iterator != null : "iterator can't be null";
        assert skip > 0 : "skip can't be < 1";
        _iterator = iterator;
        _skip = skip;
    }

    public void first() {
        _iterator.first();
skipForwards(); } public void last() { _iterator.last(); skipBackwards(); } public boolean isDone() { return _iterator.isDone(); } public void next() { _iterator.next(); skipForwards(); } public void previous() { _iterator.previous(); skipBackwards(); } public Object current() throws IteratorOutOfBoundsException { return _iterator.current(); } private ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required