package rebelsky.arrays; /** * An assistant that knows how to do some basic computations * with arrays. * * @author Samuel A. Rebelsky * @version 1.0 of October 2004 */ public class Computer { /** * Sum all the cache in stuff. */ public double sum(double[] stuff) { // Prepare to total the cache double total = 0; // Step through the array, adding each value for(int i = 0; i < stuff.length; i = i + 1) { total = total + stuff[i]; } // Return the total value return total; } // sum /** * Compute the nth Fibonacci number recursively. */ public long fibr(int n) { if (n < 2) return n; else return fibr(n-1) + fibr(n-2); } // fibr(int) /** * Compute the nth Fibonacci number recursively, * using an array. */ public long fibra(int n) { long[] cache = new long[n+1]; cache[0] = 0; cache[1] = 1; for (int i = 2; i <= n; i++) cache[i] = -1; return fibra_helper(n, cache); } // fibra(int) public long fibra_helper(int n, long[] cache) { if (cache[n] == -1) cache[n] = fibra_helper(n-1, cache) + fibra_helper(n-2, cache); return cache[n]; } // fibra_helper } // class Computer