Welcome to Dream.In.Code
Become a Java Expert!

Join 149,767 Java Programmers for FREE! Get instant access to thousands of Java experts, tutorials, code snippets, and more! There are 2,597 people online right now. Registration is fast and FREE... Join Now!




Pascal's Triangle (*So close, need help finishing*)

 
Reply to this topicStart new topic

Pascal's Triangle (*So close, need help finishing*)

prelic
13 Feb, 2007 - 07:54 PM
Post #1

New D.I.C Head
*

Joined: 13 Feb, 2007
Posts: 15


My Contributions
I have to print pascal's triangle given a user-inputted row number.

here are the constraints:
-cannot use 2d array
-cannot use more than 1 array
-cannot use temp values

here is what i have come up with so far:
-initialize all to 1
-need 2 nested for loops

i know its SO close to this, just need a push

CODE

public static void calculate(int[] triangle)
{
    
    for(int x = triangle.length - 1; x>= 1; x--)
    {
        
        for(int y= 1; y < triangle.length; y++)
        {
            triangle[y] = triangle[y] + triangle[y-1];
            printRow(triangle);
        }
        
    }
}

User is offlineProfile CardPM
+Quote Post

msg555
RE: Pascal's Triangle (*So Close, Need Help Finishing*)
14 Feb, 2007 - 07:46 AM
Post #2

D.I.C Head
Group Icon

Joined: 4 May, 2006
Posts: 136



Thanked: 5 times
Dream Kudos: 25
My Contributions
You're close, you want to use dynamic programming to solve this problem. I think recursive calls to printRow is cheating.

dp[j] += dp[j - 1] comes from the relationship that pascal[r][c] = pascal[r - 1][c] + pascal[r - 1][c - 1]

Before computing the new value we can assert that dp[j] == pascal[i - 1][j] and that dp[j - 1] == pascal[i - 1][j] because we are iterating backwards, therefore to calculate the value of pascal[i][j] and put it in the variable dp[j] we simply need to add dp[j - 1]

CODE
public void printPascal(int rows)
{
    int [] dp = new int[rows];

    //Set intial array to {1, 0, 0, ... 0}
    dp[0] = 1;

    //Print first row
    System.out.println(1);

    //Calculate and print each row
    for(int i = 1; i < rows; i++)
    {
        //Calculate new row values
        for(int j = i; j > 0; j--)
        {
            dp[j] += dp[j - 1];
        }
        //Print new row
        for(int j = 0; j <= i; j++)
        {
            System.out.print("" + dp[j] + " ");
        }
        System.out.println();
    }
}


This post has been edited by msg555: 14 Feb, 2007 - 08:00 AM
User is offlineProfile CardPM
+Quote Post

Fast ReplyReply to this topicStart new topic
Time is now: 1/8/09 06:24AM

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter

Live Java Help!

Java Tutorials

Reference Sheets

Java Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month