0 Replies - 5879 Views - Last Post: 08 December 2012 - 08:12 AM

#1 macosxnerd101   User is offline

  • Games, Graphs, and Auctions
  • member icon




Reputation: 12646
  • View blog
  • Posts: 45,819
  • Joined: 27-December 08

Pascal's Triangle

Posted 08 December 2012 - 08:12 AM

Description: Invoke pascalRow(), and pass it some int value. Examples:
pascalRow(3);
pascalRow(5);Returns the nth row of Pascal's Triangle
    /**
     * 
     * @param row The ith row of the Pascal Triangle
     * @return ArrayList<Integer> A List containing all the binomial coefficients
     *         for the given row
     */   
    public ArrayList<Integer> pascalRow(int row){
        ArrayList<Integer> values = new ArrayList<Integer>();
        
        for(int i = 0; i <= row; i++){
            values.add(choose(row, i));
        }
        
        return values;
    
    }
    
    /**
     * 
     * @param n The number of total elements
     * @param r The number to choose from n
     * @return The binomial coefficient n!/(r! * (n-r)!)
     */
    public int choose(int n, int r){
        return factorial(n)/(factorial(r) * factorial(n-r));
    }
    
    /**
     * 
     * @param n The number of which to take the factorial
     * @return int n!
     */
    public int factorial(int n){
        int x = 1;
        
        for(int i = 2; i <= n; i++){
            x *= i;
        }
        
        return x;
    }
    


Is This A Good Question/Topic? 0
  • +

Page 1 of 1