Win a copy of Machine Learning Systems: Designs that scale this week in the Scala forum
or Xamarin in Action: Creating native cross-platform mobile apps in the Android forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

pyramid of numbers  RSS feed

 
Sheriff
Posts: 12014
196
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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: 12014
196
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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: 12014
196
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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: 12014
196
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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: 12014
196
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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: 12014
196
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's it, OP. Any questions?
 
Junilu Lacar
Sheriff
Posts: 12014
196
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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: 536
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thank you.I appreciate it. I will try soon and get back with any questions.
 
Junilu Lacar
Sheriff
Posts: 12014
196
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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: 536
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ok got it
 
sai rama krishna
Ranch Hand
Posts: 536
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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: 12014
196
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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: 536
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
 
Sheriff
Posts: 5705
393
BSD
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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: 12014
196
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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: 12014
196
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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: 536
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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: 12014
196
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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: 536
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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


then nothing happens after i enter 391
please advise
 
Junilu Lacar
Sheriff
Posts: 12014
196
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
@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: 536
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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: 536
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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: 536
1
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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: 536
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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: 12014
196
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
AngularJS C++ Chrome Eclipse IDE Oracle Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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: 536
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
AngularJS C++ Chrome Eclipse IDE Oracle Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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: 536
1
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
sure. i will follow all the great advises here.
 
Junilu Lacar
Sheriff
Posts: 12014
196
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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: 536
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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: 12014
196
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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: 536
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you for reminding again. I started reading the book now. Hopefully will finish in a week days.
 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator



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: 59115
180
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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: 4866
136
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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: 536
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Mo-om! You're embarassing me! Can you just read a tiny ad like a normal person?
Rocket Oven Kickstarter - from the trailboss
https://coderanch.com/t/695773/Rocket-Oven-Kickstarter-trailboss
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!