/** * A program to simulate caching. * * First write a method or function called calculateAnswer() * that takes an integer x as input and calculates (and returns) * the sum 1 + 2 + ... + x. * (Pretend this method is computationally costly!) * * Initially, the cache is empty. Ask the user to input a number * in the range 1..100. If the answer is not in the cache, call * calculateAnswer() and display the resulting sum; also store the * result in the cache. If the answer is in the cache, simply * display the answer. * */ import java.util.Scanner; public class Caching { // Do something computationally intensive public static int calculateAnswer( int x ) { int sum = 0; for ( int y = 1 ; y <= x ; y++ ) { sum += y; } try { Thread.sleep( 3000 ); } catch( InterruptedException ex ) { } return sum; } public static final int cacheSize = 10; public static void main( String[] args ) { Scanner keyboard = new Scanner( System.in ); int[] mapping = new int[ cacheSize ]; int[] results = new int[ cacheSize ]; while ( true ) { System.out.print( "Enter x: " ); int x = keyboard.nextInt(); // Determine the cache index by dividing x by 10 and // using the remainder (which will be 0..9) int index = x % cacheSize; if ( mapping[ index ] != x ) { // CACHE MISS int result = calculateAnswer( x ); System.out.print( "==> " + result ); // Store x and result in the cache, overwriting what // was previously in the cache at the given index mapping[ index ] = x; results[ index ] = result; System.out.println( " (stored in cache at index " + index + ")" ); } else { // CACHE HIT! System.out.println( "==> " + results[ index ] + " (cache hit!)" ); } } } }