Advertisement
Guest User

Combos.java

a guest
Jul 30th, 2014
240
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.80 KB | None | 0 0
  1. package crossnum;
  2.  
  3. /**
  4.  * Combos can tell how many combinations of a specified number of digits sums
  5.  * to a particular total. Only the digits one to nine are allowed.
  6.  *
  7.  * Combos implements an optimisation whereby the number of combinations is
  8.  * retrieved from a cache. Combos has to be initialised with the maximum number
  9.  * of digits, and maximum total, that it can handle.
  10.  *
  11.  * @author dub_nerd
  12.  *
  13.  */
  14. public class Combos {
  15.  
  16.     /**
  17.      * The cache from which numbers of combinations are retrieved. The
  18.      * dimensions of the cache are max digits x max total.
  19.      */
  20.     private final int cache[][];
  21.    
  22.     /**
  23.      * Construct the Combos cache.
  24.      * @param maxDigits maximum number of digits to be handled.
  25.      * @param maxTotal maximum total sum that can be requested.
  26.      */
  27.     public Combos(int maxDigits, int maxTotal) {
  28.  
  29.         cache = new int[maxDigits][];
  30.        
  31.         /**
  32.          * We populate the cache by creating a Base9 number of each
  33.          * possible number of digits, incrementing it until it overflows
  34.          * and counting the number of times its digits sum a given value
  35.          * within the specified limits.
  36.          */
  37.         for (int digits = 1; digits <= maxDigits; digits++) {
  38.             cache[digits - 1] = new int[maxTotal];
  39.             DigitCombo d = new Base9(digits);
  40.             while (!d.isOverflow()) {
  41.                 int tot = d.summedDigits();
  42.                 if (tot < maxTotal) {
  43.                     cache[digits - 1][tot]++;
  44.                 }
  45.                 d.increment();
  46.             }
  47.         }
  48.        
  49.     }
  50.    
  51.     /**
  52.      * Gets the number of combinations of digits from 0-9 that sum to a given
  53.      * total.
  54.      *
  55.      * @param digits
  56.      *            the number of digits to be summed.
  57.      * @param total
  58.      *            the total to which the digits must sum.
  59.      * @return the number of combinations that sum to the total.
  60.      */
  61.     int getNumberCombos(int digits, int total) {
  62.         return cache[digits - 1][total];
  63.     }
  64.    
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement