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

Join 150,071 Java Programmers for FREE! Get instant access to thousands of Java experts, tutorials, code snippets, and more! There are 1,808 people online right now. Registration is fast and FREE... Join Now!




Challenge

 
Reply to this topicStart new topic

Challenge, A new way of doing pascal's triangle

gl3thr0
13 Jun, 2008 - 04:59 AM
Post #1

D.I.C Head
**

Joined: 27 Oct, 2007
Posts: 209



Thanked: 3 times
My Contributions
PASCAL’S PROBLEM

This is a problem based on the common programming task "Print Pascal’s triangle to the nth degree"

however to make it "challenging" the solution must:
  • Demonstrate Recursion.
  • Be able to handle 1, 2 and 3 digit numbers.
  • Format the numbers in the shape of a triangle.
  • Print as many rows as asked.
  • Code will be commented to explain code to other competitors.
  • Code will be written in java.

sample output
CODE

              1
            1   1
         1   2   1
      1   3    3   1
   1   4    6    4   1
1    5   10   10   5   1

better picture at http://www.lincoln.k12.nv.us/alamo/high/De...al/ptreal1r.gif

There's no real reward tongue.gif its just a challenge.


This is not related in any way to a home work or school assignment. This is not me asking for code, or requesting code to meet some deadline or to get a grade and will in no way be used by me as my own work.
This is simply a challenge


if you have questions PM me
User is offlineProfile CardPM
+Quote Post

pbl
RE: Challenge
13 Jun, 2008 - 08:25 PM
Post #2

D.I.C Lover
Group Icon

Joined: 6 Mar, 2008
Posts: 3,587



Thanked: 233 times
Dream Kudos: 75
My Contributions
I almost faled into your trap smile.gif
The first 3 requirements were challenging but the last 2 ones
QUOTE(gl3thr0 @ 13 Jun, 2008 - 05:59 AM) *
  • Code will be commented to explain code to other competitors.
  • Code will be written in java.


smell a lot a school assigment to me biggrin.gif biggrin.gif

Competitors (anybody competes in this forum ?)
Must be written in Java... yes we are in the Java forum if you want it in C++ go to the C++ forum

Good luck

P.S.
I wouldn't qualified this post as "Intermediate":
You can put all your values into an array values[nbLine][];
then use recursion to build values[i] from values[i-1]

CODE

// generate a row according to the previous one
private static int[] genNextRow(int[] previous) {
    int[] x = new int[previous.length + 1];
    // the first and the last one
    x[0] = x[previous.length] = 1;
    for(int i = 1; i < previous.length; i++)
        x[i] = previous[i-1] + previous[i];
    return x;
}


If you want to do dirty code like getting the last line, figure out the largest number, put that number into a String, get that String.length()
CODE

    // find the largest value
    int largest = value[nbLine-1][nbLine/2];
    // see the size it takes to print it
    String str = "" + largest;
    int strLen = str.length() + 1;   // + a space

(I wouldn't write code like that but you can if you wish)

return back and format every number centered to this "maximum" length it is quite trivial
The only challenge is to format the numbers displayed centered that might worth a 15 minutes of thinking
beside that ....

I am sure that if you Goggle for java format "pascal triangle" you'll get a lot of answers

Edited to correct a typo

This post has been edited by pbl: 13 Jun, 2008 - 10:41 PM
User is online!Profile CardPM
+Quote Post

mensahero
RE: Challenge
13 Jun, 2008 - 10:13 PM
Post #3

c0mput3rz Are Only Human
Group Icon

Joined: 26 May, 2008
Posts: 664



Thanked: 17 times
Dream Kudos: 75
My Contributions
QUOTE

I can cope and can be challenges by the first 3 requirements
But the 2 last ones smell a lot a school assigment to me biggrin.gif biggrin.gif

Competitors ?
Must be written in Java... yes we are in the Java forum

Good luck


I absolutely believe that this is not an assignment.. because this actually originates from the another thread here... biggrin.gif

Someone needs help about pascal triangles.. and some members got interested and try it... then gl3thro came with a nice IDEA to recode our solutions to use recursion.. I planned on doing this but after reading about recursion I got really confused.. lmao.. blink.gif blink.gif and I think it's way out of my league... tongue.gif

It's just a test on how well you could code in java.. But IMO recursion is a bad Idea for n00bs like me.. lmao..

This post has been edited by mensahero: 13 Jun, 2008 - 10:18 PM
User is offlineProfile CardPM
+Quote Post

gl3thr0
RE: Challenge
13 Jun, 2008 - 11:45 PM
Post #4

D.I.C Head
**

Joined: 27 Oct, 2007
Posts: 209



Thanked: 3 times
My Contributions
QUOTE
smell a lot a school assigment to me

to put it simply.
ITS NOT!.. if it makes u feel better ill take off the last 2 requirmens.

QUOTE

Must be written in Java... yes we are in the Java forum if you want it in C++ go to the C++ forum

yes we are in the java forum good job. but that does not mean everyone reading this topic ONLY knows java.seeing as this is a site with programmers that know more then just java i thought that was a fairly reasonable requirement.

QUOTE
P.S.
I wouldn't qualified this post as "Intermediate":

and i put it under intermediate because recursion is considered a higher level aspect by IB. its not something ur average beginner would know.
the only way this even relates to an assigment is, for my computer scienve IA i was hopping to use recusion as a mastery aspect so when i saw the pascal's triangle topic i though.. hmm this could probably be done with recursion lets see how ppl would do it.


and your code, its nice.. but where exactly do you "demonstrate recursion?"

This post has been edited by gl3thr0: 13 Jun, 2008 - 11:49 PM
User is offlineProfile CardPM
+Quote Post

baavgai
RE: Challenge
14 Jun, 2008 - 08:05 AM
Post #5

Dreaming Coder
Group Icon

Joined: 16 Oct, 2007
Posts: 2,282



Thanked: 136 times
Dream Kudos: 475
Expert In: C, C++, Java, C#, ASP.NET, PHP, Perl, Python, Oracle, SQL Server, MySql, HTML, JavaScript, Lua, Cheese

My Contributions
Considering the solution to the triangle is ubiquitous, I don't think there's any harm in offering another. I'll give this one a shot.

Demonstrate Recursion: There is really is no advantage to this that I could tell. Now, if you wanted an upside down triangle, then you'd be on to something. However, since you have to reach the end before you print the first line, it's of dubious value. Fear not, recursion is used, for what it's worth.

Be able to handle 1, 2 and 3 digit numbers: I hate fixed numbers. We'll assume we have infinite width and handle everything. So, yes, 1,2,3 and 4,5,6...

Format the numbers in the shape of a triangle: Given. One reason recursion isn't useful.

Print as many rows as asked: Check.

Code will be commented to explain code to other competitors: Code is its own documentation! However I threw in a couple.

Code will be written in java: This actually made it entertaining. Is there a way to use OOP that will make cleaner code than strictly procedural? I created a couple extra to classes for this. I believe they offered a somewhat cleaner solution than, say, some generic collection of arrays.

Honestly, I'm not sure how much this problem lends itself to innovation. Still, I'd be happy if someone proved me wrong. wink2.gif

java

class PascalRow {
private int [] values;

// default parameter is row 1
public PascalRow() {
this.values = new int[1];
this.values[0] = 1;
}

// given prior row, make next row
public PascalRow(PascalRow priorRow) {
int priorSize = priorRow.values.length;
this.values = new int[priorSize + 1];
this.values[0] = this.values[priorSize] = 1;
for(int i = 1; i < priorSize; i++) {
this.values[i] = priorRow.values[i-1] + priorRow.values[i];
}
}

// largest, and therefore longest string in this row
private int getMaxValue() { return this.values[values.length/2]; }

// all elements to conform to the largest sized element
public int getMaxValueSize() {
int size = String.valueOf(getMaxValue()).length();
// centering is cleaner if the value is always odd
return size + ((size % 2)==0 ? 1 : 0);
}

// centering is a big deal, but only this class need know
private static String getCenteredString(String s, int size) {
int padSize = (size - s.length())/2;
for(int i=0; i<padSize; i++) { s = " " + s; }
for(int i=0; i<size - s.length(); i++) { s += " "; }
return s;
}

private static String getCenteredString(int n, int size) {
return getCenteredString(String.valueOf(n), size);
}


// default is using self values, no centering
public String toString() {
return this.toString(getMaxValueSize());
}

// given a max value size, use that for each of the elements
public String toString(int valueSize) {
String s = "";
for(int i = 0; i < values.length; i++) {
if (i!=0) { s += " "; }
s += getCenteredString(this.values[i], valueSize);
}
return s;
}

// given a max line, use that as a center point
public String toString(int valueSize, int maxLineSize) {
return getCenteredString(this.toString(valueSize), maxLineSize);
}

}

// here we'll hold all the rows, populate them on construction, and off them up as a string
class PascalTriangle {
private PascalRow[] rows;

public PascalTriangle(int rowCount) {
this.rows = new PascalRow[rowCount];
this.rows[0] = new PascalRow();
generate(this.rows, 1);
}

// there is no funcational advantage to recursion
// but, it was requested for some reason
private static void generate(PascalRow[] list, int row) {
if (row<list.length) {
list[row] = new PascalRow(list[row-1]);
generate(list, row + 1);
}
}

public String toString() {
String s = "";
PascalRow lastRow = this.rows[this.rows.length-1];
int valueSize = lastRow.getMaxValueSize();
int maxLineSize = lastRow.toString().length();
for( PascalRow row : this.rows) {
s += row.toString(valueSize, maxLineSize) + "\n";
}
return s;
}

}

public class Main {
public static void main(String[] args) {
System.out.println(new PascalTriangle(10));
}
}


User is offlineProfile CardPM
+Quote Post

mensahero
RE: Challenge
14 Jun, 2008 - 08:27 AM
Post #6

c0mput3rz Are Only Human
Group Icon

Joined: 26 May, 2008
Posts: 664



Thanked: 17 times
Dream Kudos: 75
My Contributions
Now that is awesome. Copied and tested. Great example, it will take some time before I actually understand the process flow.
User is offlineProfile CardPM
+Quote Post

gl3thr0
RE: Challenge
14 Jun, 2008 - 08:43 AM
Post #7

D.I.C Head
**

Joined: 27 Oct, 2007
Posts: 209



Thanked: 3 times
My Contributions
wow... freaking impressive. ill point out though that it wont handle more then 29 rows. after that it starts making negative numbers tongue.gif bt w/e you still meet all the requirments thts freaking sweet . i dont think i ever seen so much code go into pascal's triangle.

oh i was thining maybe to make it more challenging it has to be able to start from any row and keep going for some many rows.. ?

edit
and im not sure how much of difference this makes
this.values[0] = 1;
all it does is change the first value of the triangle..

This post has been edited by gl3thr0: 14 Jun, 2008 - 08:56 AM
User is offlineProfile CardPM
+Quote Post

baavgai
RE: Challenge
14 Jun, 2008 - 09:25 AM
Post #8

Dreaming Coder
Group Icon

Joined: 16 Oct, 2007
Posts: 2,282



Thanked: 136 times
Dream Kudos: 475
Expert In: C, C++, Java, C#, ASP.NET, PHP, Perl, Python, Oracle, SQL Server, MySql, HTML, JavaScript, Lua, Cheese

My Contributions
QUOTE(gl3thr0 @ 14 Jun, 2008 - 12:43 PM) *

ill point out though that it wont handle more then 29 rows. after that it starts making negative numbers


Really? I get to row 34 before my signed ints start flipping, with the max for that row being 1166803110. But, sure, you push your computer numbers hard enough and they're going to roll.

The code I think you're referencing is this?
java

// default parameter is row 1
public PascalRow() {
this.values = new int[1];
this.values[0] = 1;
}


This is required; everyone has to start somewhere. The first row has but one value and it's 1. The second row essentially ignores the one and produces "1 1". We can think of the 1s on the edges as superfluous to the calculations, but in fact the real edge value is zero. we usually just ignore that for expediency.

User is offlineProfile CardPM
+Quote Post

gl3thr0
RE: Challenge
14 Jun, 2008 - 09:32 AM
Post #9

D.I.C Head
**

Joined: 27 Oct, 2007
Posts: 209



Thanked: 3 times
My Contributions
QUOTE(baavgai @ 14 Jun, 2008 - 10:25 AM) *

The code I think you're referencing is this?
java

// default parameter is row 1
public PascalRow() {
this.values = new int[1];
this.values[0] = 1;
}

This is required; everyone has to start somewhere. The first row has but one value and it's 1. The second row essentially ignores the one and produces "1 1". We can think of the 1s on the edges as superfluous to the calculations, but in fact the real edge value is zero. we usually just ignore that for expediency.


ahh okay tongue.gif i thought it might let u start the triangle from w/e value nd build it from there.
but still best code yet (not saying much tongue.gif)
User is offlineProfile CardPM
+Quote Post

pbl
RE: Challenge
14 Jun, 2008 - 08:10 PM
Post #10

D.I.C Lover
Group Icon

Joined: 6 Mar, 2008
Posts: 3,587



Thanked: 233 times
Dream Kudos: 75
My Contributions
QUOTE(baavgai @ 14 Jun, 2008 - 09:05 AM) *

Considering the solution to the triangle is ubiquitous, I don't think there's any harm in offering another.

Demonstrate Recursion: There is really is no advantage to this that I could tell

Honestly, I'm not sure how much this problem lends itself to innovation.


These 3 comments worth a "Thank"

User is online!Profile CardPM
+Quote Post

pbl
RE: Challenge
14 Jun, 2008 - 11:39 PM
Post #11

D.I.C Lover
Group Icon

Joined: 6 Mar, 2008
Posts: 3,587



Thanked: 233 times
Dream Kudos: 75
My Contributions
Ok I apologize, you really want to challenge us
Will see if bavgay, the recursion expert has a solution for you
User is online!Profile CardPM
+Quote Post

Fast ReplyReply to this topicStart new topic
Time is now: 1/8/09 10:58PM

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