• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

pyramid of numbers

 
Sheriff
Posts: 17652
300
  • Number of slices to send:
    Optional 'thank-you' note:
Next, I want to sort the digits. That's easy, I just add a call to Arrays.sort():

I run the program again and see that the digits are now sorted in ascending order:

Enter a sequence of digits, no spaces in between:
2
3
5
9

Again, I have made another step forward.
 
Junilu Lacar
Sheriff
Posts: 17652
300
  • Number of slices to send:
    Optional 'thank-you' note:
Now I actually need to push the characters out so that they form a pyramid.

I analyze the pattern I need. I use "." to represent a space I need to print:

...2
..3
.5
9

I make a table so I can figure out the math:
i#spacestotal
033
123
213
303

This is when the sequence has 4 characters in it. What if my sequence has 5 characters?

....1
...2
..3
.5
9

i#spacestotal
044
134
224
314
404

So it seems that the numbers of spaces I need to print on each row is (sequence.length - 1 - i), where i is the index in the sequence of the character that I'm printing.

That looks about right but let's try it in code.
 
Junilu Lacar
Sheriff
Posts: 17652
300
  • Number of slices to send:
    Optional 'thank-you' note:
Now, since I need to use the loop index as part of a calculation, I need replace the enhanced for-loop that I initially wrote with the standard for-loop:

I'm going to print a "." for now, just to make it easier for me to eyeball the result, which looks like this now:

Enter a sequence of digits, no spaces in between:
...2
..3
.5
9

Ok, great! I'll change my getUserInput() method again so I can verify that it works with 5 digits:

Enter a sequence of digits, no spaces in between:
....1
...2
..3
.5
9

Cool, so I know this part works. I'll leave the "." in there for now and change it to an actual space as the last step.
 
Junilu Lacar
Sheriff
Posts: 17652
300
  • Number of slices to send:
    Optional 'thank-you' note:
Looks like I'm almost done. I just need to replace that statement to print the right number of digits to fill out the pyramid. Again, I analyze the pattern:

...2
..3 3
.5 5 5
9 9 9 9

Again, I create a table:
i#digits
01
12
23
34

I know for sure that if I have 5 digits, then the next entry would be 4|5.

So, I need print a digit (i + 1) times. That's easy:

I run the program and get this output (remember, I changed my getUserInput() method so I now have a 5-digit sequence as input):

Enter a sequence of digits, no spaces in between:
....1
...2 2
..3 3 3
.5 5 5 5
9 9 9 9 9

Great, now I have a full pyramid. The only thing I have left to do is to change that "." to a space.
 
Junilu Lacar
Sheriff
Posts: 17652
300
  • Number of slices to send:
    Optional 'thank-you' note:
After I change the "." to " " in my printSpaces() method, I also have to restore the getUserInput() method so that I'm using the value that the user has entered in the console. Now I'm done. All in all, this would have taken only about 10 minutes in real time, if that.
 
Junilu Lacar
Sheriff
Posts: 17652
300
  • Number of slices to send:
    Optional 'thank-you' note:
That's it, OP. Any questions?
 
Junilu Lacar
Sheriff
Posts: 17652
300
  • Number of slices to send:
    Optional 'thank-you' note:

sai rama krishna wrote: But how to get pyramid structure ... that is where all the complexity using multiple methods using OOP and OOD principles?


Whatever complexity there was, it was all in your head. If you had emptied your mind and put your thoughts down on paper like we have suggested to you all along, it would have been much easier for you to untangle the string of ideas you had tied into a Gordian Knot in your brain.

There's practically no OOP or OOD involved in solving this problem. It's all pattern analysis and recognition, really. Combine that with some discipline and a step-wise approach, not trying to solve everything all at once but making one small step forward instead, and then refining/adding to your solution. If you do that, you'll eventually get to where you need to get. Small, sure steps forward are the key to success. And always running your program to verify that you haven't messed up anything before you try to make the next small step forward.
 
Ranch Hand
Posts: 953
2
  • Number of slices to send:
    Optional 'thank-you' note:
thank you.I appreciate it. I will try soon and get back with any questions.
 
Junilu Lacar
Sheriff
Posts: 17652
300
  • 2
  • Number of slices to send:
    Optional 'thank-you' note:
Note to OP: Please don't post my entire solution. I have purposely spread the code out over multiple responses so that people just can't conveniently copy the code and pass it off as their own. If they're going to be dishonest and submit my code as their own work, at least they'll have to go through this thread, read my responses and understand it enough to recognize the parts that need to go into the final solution.
 
sai rama krishna
Ranch Hand
Posts: 953
2
  • Number of slices to send:
    Optional 'thank-you' note:
ok got it
 
sai rama krishna
Ranch Hand
Posts: 953
2
  • Number of slices to send:
    Optional 'thank-you' note:


Whatever complexity there was, it was all in your head. If you had emptied your mind and put your thoughts down on paper like we have suggested to you all along, it would have been much easier for you to untangle the string of ideas you had tied into a Gordian Knot in your brain.

There's practically no OOP or OOD involved in solving this problem. It's all pattern analysis and recognition, really. Combine that with some discipline and a step-wise approach, not trying to solve everything all at once but making one small step forward instead, and then refining/adding to your solution. If you do that, you'll eventually get to where you need to get. Small, sure steps forward are the key to success. And always running your program to verify that you haven't messed up anything before you try to make the next small step forward.



i will try to remember this valuable advise and hope not fall in to that gordian mind loop you mentioned
 
Junilu Lacar
Sheriff
Posts: 17652
300
  • Number of slices to send:
    Optional 'thank-you' note:

sai rama krishna wrote:i will try to remember this valuable advise and hope not fall in to that gordian mind loop you mentioned


Good. Did you practice going through the steps I demonstrated? Reading through what I did and actually trying to do it yourself are two vastly different experiences. You can't learn how to swim by reading about it or watching other people do it. For the best results, walk through the coding and thinking process again and again until you can easily come up with the solution. It's fine to take a few peeks at the solution on your first few tries but after that, start from scratch and let your brain actually do some thinking and organizing. That's the only way you'll learn how to swim in the waters of programming.
 
sai rama krishna
Ranch Hand
Posts: 953
2
  • Number of slices to send:
    Optional 'thank-you' note:

public class PyramidPrinter {

   public static void main(String[] args) {
         PyramidPrinter printer = new PyramidPrinter();
         printer.print(getUserInput());
   }
 
   private static final Scanner input = new Scanner();

   private static String getUserInput() {
         System.out.print("Enter a sequence of digits, no spaces: ");
         return input.nextLine();
   }

   private void print(String sequence) {
   }
}

I'll compile this to make sure I have no errors so far. I see that it compiles with no errors, so I continue.



for me above code gives below error
The constructor Scanner() is undefined
please advise.

i am also going throguh other steps further
 
Marshal
Posts: 8880
638
  • Number of slices to send:
    Optional 'thank-you' note:
Don't expect everything to be served on the plate. Go to Java API page and check what constructors Scanner class contain.
I think last year you used Scanner class correctly, so re-use that part from there.
 
Junilu Lacar
Sheriff
Posts: 17652
300
  • Number of slices to send:
    Optional 'thank-you' note:
When I say "walk through the coding and thinking process" I mean you shouldn't just copy/paste the code that I gave you. Think through the problem, draw out those tables that help you recognize the patterns, come up with the formula to represent the patterns, write the code to use those formulas, etc. This is how you practice and run your brain through its paces. If you only read what was given to you but don't do it yourself, you're not going to internalize that learning and will soon forget it; then you're back at square one. Only by replication and repetition can you really learn how to do this and improve as a programmer.

Good luck.
 
Junilu Lacar
Sheriff
Posts: 17652
300
  • Number of slices to send:
    Optional 'thank-you' note:

sai rama krishna wrote:
for me above code gives below error
The constructor Scanner() is undefined
please advise.


My fault, I didn't copy/paste the actual code from my IDE. You have been using the Scanner class long enough to know how to fix that though.
 
sai rama krishna
Ranch Hand
Posts: 953
2
  • Number of slices to send:
    Optional 'thank-you' note:


i commented that line to make compiler happy.

I capturee all your sequence of steps and see all the successfully addition of each brick for this pyramid building.

I think  i missed important connection as above
when i run above code console shows

Enter a sequence of digits, no spaces:

then when i try to enter not displaying and not doing anything with entered number?
please advise
 
Junilu Lacar
Sheriff
Posts: 17652
300
  • Number of slices to send:
    Optional 'thank-you' note:

sai rama krishna wrote:
I think  i missed important connection as above
when i run above code console shows

Enter a sequence of digits, no spaces:

then when i try to enter not displaying and not doing anything with entered number?


Go back to the getUserInput() method and UNDERSTAND what commenting out that code and hard-coding a return value does.
 
sai rama krishna
Ranch Hand
Posts: 953
2
  • Number of slices to send:
    Optional 'thank-you' note:


above gives below
Enter a sequence of digits, no spaces:
391


then nothing happens after i enter 391
please advise
 
Junilu Lacar
Sheriff
Posts: 17652
300
  • 1
  • Number of slices to send:
    Optional 'thank-you' note:
@OP: I have to be honest with you now: You have taxed the patience of multiple moderators to the max in this thread.

Like I said before, this exercise should take no more than a couple of hours for a rank beginner to complete, even if he/she ends up writing code that's not the clearest and most organized. You've managed to stretch the effort out to proportions that are quite frankly, hard to believe.

You seem like a nice guy and you're earnest in wanting to learn this stuff but at some point, you have to ask yourself whether you're really cut out for this kind of thing. It's ok to accept that you might not have the aptitude for this kind of activity; not everyone can be a programmer just as not everyone can be a dancer or a singer. If you can't figure out why the print() method is not printing any output, then I just don't know what to tell you anymore except to stop asking for help all the time, think, and work it out yourself.
 
sai rama krishna
Ranch Hand
Posts: 953
2
  • Number of slices to send:
    Optional 'thank-you' note:

DO NOT POST MY SOLUTION CODE!!!


sorry. i forgot. As i was working through solution based on steps you have given i posted issues i faced. I will check it out further.
 
sai rama krishna
Ranch Hand
Posts: 953
2
  • Number of slices to send:
    Optional 'thank-you' note:
i mising calling below method from print method
displayAsPyramid(digits);

Now i see perfect output.
Enter a sequence of digits, no spaces:
192
 1
9 9
2 2 2

Thanks every one for your help on this challenge where i learned so many things.
 
sai rama krishna
Ranch Hand
Posts: 953
2
  • 1
  • Number of slices to send:
    Optional 'thank-you' note:
one important lesson learned is no need of Iterger etc conversion.

simply get String as input from getUserInput
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
return input;
then call print() by passing above input which further converts that string array to char array
char[] digits = sequence.toCharArray();
then further make call displayAsPyramid by taking above char digits array and then finally call printSpaces for spaces and printRow for the digits
 
sai rama krishna
Ranch Hand
Posts: 953
2
  • Number of slices to send:
    Optional 'thank-you' note:
I forget to include sort method
Arrays.sort(digits); withing print method in my last output. After putting it i got it sorted as well correctly
 
Junilu Lacar
Sheriff
Posts: 17652
300
  • Number of slices to send:
    Optional 'thank-you' note:

sai rama krishna wrote:I forget to include sort method
Arrays.sort(digits); withing print method in my last output. After putting it i got it sorted as well correctly


That suggests to me that you need to practice some more. Don't just memorize the solution and try to regurgitate it. Understand the thought process and incremental nature of finding a full solution by attacking parts of the problem, one at a time. If you forgot to add a call to Arrays.sort() then you didn't plan out your solution that well because you skipped the part about thinking "How do I sort these things?"

Your initial planning should go something like this:

1. Get input string
2. Get individual characters
3. Sort the characters
4. Print the characters as a pyramid
...

If you added the call to Arrays.sort() almost as an afterthought, that means you didn't have a plan like the above laid out before you started writing code. You should always have a plan to start with, even just a simple outline and even if you know the plan is going to have to change as you learn more about what you need to do.
 
Ranch Hand
Posts: 94
3
  • Number of slices to send:
    Optional 'thank-you' note:
The people that have commented on here to help have a lot of patience as you stated Junilu! This thread should not have gotten so long. 5 pages for a program that is not too complex.
I say this as humble as I can be.
For a program like this I don't believe you are a beginner just starting out programming. You must have had exercises involving loops and using methods to distribute the workload and be able to easily debug in case something fails.
But I don't see that in your way of coding.

To be a great programmer you really need to love to program and read carefully each chapter of the book you may be currently studying from (everyone needs to start somewhere), not just reading but analyzing each line and code and trying out several exercises to see for yourself why the code behaves like it does. As you progress you won't need to analyze each line anymore but if you skip this part then as things get complicated you don't have the basics down. Loving to program is  not just sitting down and coding. It's the behind the scenes and what's happening in your brain as you encounter bugs:

But why? Why is it doing this? If its laid down on paper and you have a clear visualization of what it needs to do then what is the part that is missing in the code? Use sysouts, scan.next() or whatever would help to dissect each part of the code and identify the working code until you get to the part that's broken. Junilu posted an excellent bite size approach of each part that you should be doing. Yet instead of digesting that and put effort from your part you posted complaining about the scanner class when his code wouldn't work on your program.
My advice would be as others have already pointed out. Go back to the beginning and look at all the helpful posts they have given you. Although with the last solutions provided should be more than enough!
 
sai rama krishna
Ranch Hand
Posts: 953
2
  • Number of slices to send:
    Optional 'thank-you' note:
Definitely i will reread all the comments again and improve in all the weak areas pointed out. Last but not least can you please provide some light on the unit test you are mentioning and you go about this kind of challenge. Do you consider using junit frameworks like Mockito/powermock/hamcrest etc for this. please advise on how would you approach on that important area as well?
 
Daniel Andres
Ranch Hand
Posts: 94
3
  • 1
  • Number of slices to send:
    Optional 'thank-you' note:
I think you are simply too obsessed with this program that you want to get the solution immediately instead of restarting. Again, go back and read all the helpful comments already posted. Between work and school I have been following this and other threads( as I always do because this ranch has become my second home) and I always learn from just reading the advices from experienced programmers and engraving them in my head for a later use. I have many threads bookmarked/watched and books that have been suggested. As well as links.

Any advice I could give you at this point may have probably already been given to you throughout this thread.
You mentioned earlier, page 2 to be exact, that you have been working for over a month in this. Someone asked if this was a homework assignment and you said no. Are you learning Java on your own then? Have you ever taken a programming class? If not, then it's not impossible to learn but jeez that would be very hard in my opinion. Unless you are James gosling perhaps

Have you at least finished an introductory book? If you're just an 'aficionado' and programming will not be your career then I think that may be the reason why you immediately post code and ask for advice time after time.
 
sai rama krishna
Ranch Hand
Posts: 953
2
  • 1
  • Number of slices to send:
    Optional 'thank-you' note:
sure. i will follow all the great advises here.
 
Junilu Lacar
Sheriff
Posts: 17652
300
  • Number of slices to send:
    Optional 'thank-you' note:

Daniel Andres wrote:Are you learning Java on your own then? Have you ever taken a programming class? If not, then it's not impossible to learn but jeez that would be very hard in my opinion. Unless you are James gosling perhaps


Many of us here are self-taught for the most part. Of course, nobody is truly self taught who comes to the Ranch and learns from the examples and advice of others but anyway, by "self-taught" I mean it wasn't through any formal schooling or instruction. Just reading lots of books and playing around and learning on the job. Necessity is, after all, the mother of not only invention but also re-invention. Many self-taught Java programmers come from different backgrounds and had to pick up Java to stay competitive in the job market. While there are a lot of very smart people around here, you don't have to be a language inventor like Gosling to learn Java on your own.

I've said this a few times and I'll say it again here: Practice, Practice, Practice is how you get to Carnegie Hall. And remember: "Practice only makes habit. Only perfect practice makes perfect," said every music teacher ever.

Full Disclosure: I did take a number of Computer Science courses in college and I had about 12 years of professional programming experience by the time I started learning Java, so there's that, too.
 
sai rama krishna
Ranch Hand
Posts: 953
2
  • Number of slices to send:
    Optional 'thank-you' note:
I am having masters from non IT non computer back ground. Lot of simple things to you guys looks strange to me unless i read them few times and practice
 
Junilu Lacar
Sheriff
Posts: 17652
300
  • Number of slices to send:
    Optional 'thank-you' note:

sai rama krishna wrote:I am having masters from non IT non computer back ground. Lot of simple things to you guys looks strange to me unless i read them few times and practice


I may have already recommended this to you before but a book I think you'll find useful is V. Anton Spraul's book, Think Like a Programmer. It has a lot of advice and examples about problem solving strategies that programmers can use. The second chapter is all about patterns, which is what this problem is about. The only downside for you is that it uses C++ for its code examples. C++ is not very different from Java though so you should be able to follow along for the most part. If you find something that's vastly different from Java that you can't understand, you can always post a question here on in the Languages - C/C++ forum to get clarification. The concepts and techniques taught in that book are widely applicable in any programming language though so I think it would be still worth your while to read it and do the practice exercises.

By the way, the process that I demonstrated in my example is patterned after the examples shown in Spraul's book.
 
sai rama krishna
Ranch Hand
Posts: 953
2
  • Number of slices to send:
    Optional 'thank-you' note:
Thank you for reminding again. I started reading the book now. Hopefully will finish in a week days.
 
Greenhorn
Posts: 3
  • Number of slices to send:
    Optional 'thank-you' note:



Hello i'm new in this forum. I found this topic interesting and so I developed a solution. Can I improve this code ? thank you for your answers ?
 
Marshal
Posts: 79422
377
  • Number of slices to send:
    Optional 'thank-you' note:
Welcome to the Ranch

Afraid I haven't enough time to look at your code properly now, but please post the output so we can see how it works.
 
Sheriff
Posts: 7125
184
  • Number of slices to send:
    Optional 'thank-you' note:
Welcome to the Ranch!  A few noted on your program:

* I like the way you launch the program.

* Always close Sanner except when it's opened to System.in.  The reason is that once System.in is closed, you can't get it open again.

* scanner should probably be an instance field, not a local variable.  It only needs to be opened once per program.

* Nice use of a lambda to convert stringDigits into digits.

* The standard way to write line 30 is this: My reasoning it that i is an index into an array, and indexes start with 0.

Of course, this changes the value of i.  I leave it to you to see what those changes would be like.  I think it simplies the code a bit.
 
sai rama krishna
Ranch Hand
Posts: 953
2
  • Number of slices to send:
    Optional 'thank-you' note:


i wonder why the method returns App like below

public App createArrayOfDigits()


i do not see any output. How to execute this program in eclipse?
 
am gueye
Greenhorn
Posts: 3
  • Number of slices to send:
    Optional 'thank-you' note:
Hello, thanks for your answers. I modified the code according to some of your remarks.



To execute this program, just run it as Java Application in eclipse.

An example of execution is below:
Saisir les chiffres: 123456789
               1
             222
           33333
         4444444
       555555555
     66666666666
   7777777777777
 888888888888888
99999999999999999
 
reply
    Bookmark Topic Watch Topic
  • New Topic
vceplus-200-125    | boson-200-125    | training-cissp    | actualtests-cissp    | techexams-cissp    | gratisexams-300-075    | pearsonitcertification-210-260    | examsboost-210-260    | examsforall-210-260    | dumps4free-210-260    | reddit-210-260    | cisexams-352-001    | itexamfox-352-001    | passguaranteed-352-001    | passeasily-352-001    | freeccnastudyguide-200-120    | gocertify-200-120    | passcerty-200-120    | certifyguide-70-980    | dumpscollection-70-980    | examcollection-70-534    | cbtnuggets-210-065    | examfiles-400-051    | passitdump-400-051    | pearsonitcertification-70-462    | anderseide-70-347    | thomas-70-533    | research-1V0-605    | topix-102-400    | certdepot-EX200    | pearsonit-640-916    | itproguru-70-533    | reddit-100-105    | channel9-70-346    | anderseide-70-346    | theiia-IIA-CIA-PART3    | certificationHP-hp0-s41    | pearsonitcertification-640-916    | anderMicrosoft-70-534    | cathMicrosoft-70-462    | examcollection-cca-500    | techexams-gcih    | mslearn-70-346    | measureup-70-486    | pass4sure-hp0-s41    | iiba-640-916    | itsecurity-sscp    | cbtnuggets-300-320    | blogged-70-486    | pass4sure-IIA-CIA-PART1    | cbtnuggets-100-101    | developerhandbook-70-486    | lpicisco-101    | mylearn-1V0-605    | tomsitpro-cism    | gnosis-101    | channel9Mic-70-534    | ipass-IIA-CIA-PART1    | forcerts-70-417    | tests-sy0-401    | ipasstheciaexam-IIA-CIA-PART3    | mostcisco-300-135    | buildazure-70-533    | cloudera-cca-500    | pdf4cert-2v0-621    | f5cisco-101    | gocertify-1z0-062    | quora-640-916    | micrcosoft-70-480    | brain2pass-70-417    | examcompass-sy0-401    | global-EX200    | iassc-ICGB    | vceplus-300-115    | quizlet-810-403    | cbtnuggets-70-697    | educationOracle-1Z0-434    | channel9-70-534    | officialcerts-400-051    | examsboost-IIA-CIA-PART1    | networktut-300-135    | teststarter-300-206    | pluralsight-70-486    | coding-70-486    | freeccna-100-101    | digitaltut-300-101    | iiba-CBAP    | virtuallymikebrown-640-916    | isaca-cism    | whizlabs-pmp    | techexams-70-980    | ciscopress-300-115    | techtarget-cism    | pearsonitcertification-300-070    | testking-2v0-621    | isacaNew-cism    | simplilearn-pmi-rmp    | simplilearn-pmp    | educationOracle-1z0-809    | education-1z0-809    | teachertube-1Z0-434    | villanovau-CBAP    | quora-300-206    | certifyguide-300-208    | cbtnuggets-100-105    | flydumps-70-417    | gratisexams-1V0-605    | ituonline-1z0-062    | techexams-cas-002    | simplilearn-70-534    | pluralsight-70-697    | theiia-IIA-CIA-PART1    | itexamtips-400-051    | pearsonitcertification-EX200    | pluralsight-70-480    | learn-hp0-s42    | giac-gpen    | mindhub-102-400    | coursesmsu-CBAP    | examsforall-2v0-621    | developerhandbook-70-487    | root-EX200    | coderanch-1z0-809    | getfreedumps-1z0-062    | comptia-cas-002    | quora-1z0-809    | boson-300-135    | killtest-2v0-621    | learncia-IIA-CIA-PART3    | computer-gcih    | universitycloudera-cca-500    | itexamrun-70-410    | certificationHPv2-hp0-s41    | certskills-100-105    | skipitnow-70-417    | gocertify-sy0-401    | prep4sure-70-417    | simplilearn-cisa    |
http://www.pmsas.pr.gov.br/wp-content/    | http://www.pmsas.pr.gov.br/wp-content/    |