/** Static methods to show off multidimensional arrays */
public class MultiDimensional {

    /** Yields: a representation of b
     *  Precondition: b is either
     *  (1) an array of base type int or Object, or
     *  (2) an Object */
    public static String toString(Object b) {
        if (b instanceof int[]) {
            int[] bint= (int[]) b;
            return toString(bint);
        }
        
        if (b instanceof Object[]) {
            Object[] bb= (Object[]) b;
            String res= "[";
            
            //inv: res contains "[" followed by b[0..k-1]
            for (int k= 0; k < bb.length; k= k+1) {
                if (k > 0) res= res + ", ";
                res= res + toString(bb[k]);
            }
            return res + "]";
            
        }
        
        // b is not an array
        return b.toString();
    }
    
    /** Yields: a representation of b, delimited by [ ] and 
     *  elements separated by ", "        */
    private static String toString(int[] b) {
        String res= "[";
        //inv: res contains b[0..k-1], separated by ", "
        for (int k= 0; k < b.length; k= k+1) {
            if (k > 0) res= res + ", ";
            res= res + b[k];
        }
        return res + "]";
    }
    
    /** Yields: ragged array of first n rows of Pascal�s triangle. 
     *  Precondition: 0 � n */ 
    public static int[][] pascalTriangle(int n) { 
        int[][] b= new int[n][];      // First n rows of Pascal's triangle 
        
        // Create and calculate rows 0..n-1
        // inv: rows 0..i-1 have been created and calculated
        for (int i= 0; i < n; i= i+1) {
            // Create row i;
            b[i]= new int[i+1];
            
            // Calculate row i;
            b[i][0]= 1;
            // calculate b[i][1..i-1]
            for (int j= 1; j < i; j= j+1) {
                b[i][j]= b[i-1][j-1] + b[i-1][j];
            }
            
            b[i][i]= 1;   
        }
        
        return b; 
    } 
    
    
    /** Yields: Sum of elements of b.  
     *  Precondition: b is either an Integer or 
     *  an array whose base type is int or Integer. */
    public static int sum(Object b) {
        if (b instanceof Integer) {
            return  (Integer) b;
        }
        
        // b is an array
        if (b instanceof int[]) {
            int[] bint= (int[]) b;
            
            int x= 0;
            // inv: x is sum of bint[0..k-1]
            for (int k= 0; k < bint.length; k= k+1) {
                x= x + bint[k];
            }
            return x;
        }
        
        // b is an Integer array of 1 or more dimensions
        Object[] bobj= (Object[]) b;
        
        int y= 0;
        // y is sum of bobj[0..k-1]
        for (int k= 0; k < bobj.length; k= k+1) {
            y= y + sum(bobj[k]);
        }
        
        return y;
    }
}