Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / March 2006

Tip: Looking for answers? Try searching our database.

Is there a better way of getting the following output: ?

Thread view: 
Ivan - 21 Mar 2006 03:47 GMT
I've written the following code:

public class Sand
{
   public static void main( String args[] )
   {
       System.out.println( "*****" );
       System.out.println( " *** " );
       System.out.println( "  *  " );
       System.out.println( " *** " );
       System.out.println( "*****" );
   }
}

What i want to know is.. Is there a better (quicker/more efficient) way
of obtaining the same output?

*****
***
 *
***
*****

Thanks..
america.captain@gmail.com - 21 Mar 2006 04:02 GMT
When is your homework due?
Ivan - 21 Mar 2006 04:10 GMT
Next week.. And i've done it.. As you can see. I only want to know if
there are other ways of doing it..
Roedy Green - 21 Mar 2006 04:13 GMT
>What i want to know is.. Is there a better (quicker/more efficient) way
>of obtaining the same output?
[quoted text clipped - 4 lines]
> ***
>*****
consider these numbers
0 5 0
1 3 1
2 1 2
1 3 1
0 5 0

If you could generate them in a loop you could generate that pattern
ad infinitum. The code would not be as terse or as comphensible as
what you have.
Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

Ivan - 21 Mar 2006 04:55 GMT
hhm.. I don't think I've done loops yet..
And the book I'm following (Deitel's Java how to Program) asks at the
end of the chapter to do something similar, but doesn't provide any
examples of the source code..

i guess spaces will have to do..

Incidentally, out of my own personal interest, would it be too
complicated to create such loop, if my knowledge extends to creating
simple algorythms?
Chris Uppal - 21 Mar 2006 11:50 GMT
> Incidentally, out of my own personal interest, would it be too
> complicated to create such loop, if my knowledge extends to creating
> simple algorythms?

It's conceptually simple, but you might find it a bit tricky in practise.

For one thing you need to be comfortable with loops (and nested loops), and I
gather you haven't reached that stage yet.

For the other, it's a bit fiddly getting the exact numbers right, how many
blanks do you need to print on line n, and so on.  Some programmers find that
kind of thing easy, but others find it fustrating and difficult to get exactly
right[*].

([*] I'm in the latter camp. I just tried programming it myself and it took me
a few attempts to get it working correctly -- which is exactly what I
expected).

   -- chris
Dag Sunde - 21 Mar 2006 08:23 GMT
> I've written the following code:
>
[quoted text clipped - 12 lines]
> What i want to know is.. Is there a better (quicker/more efficient) way
> of obtaining the same output?

Not quicker/more efficient, but different...:

public class Sand
{

static final String hourGlass = "*****\n" +
                                " *** \n" +
                                "  *  \n" +
                                " *** \n" +
                                "*****\n";

  public static void main( String args[] )
  {
      System.out.println( hourGlass  );
  }
}

Signature

Dag.

Oliver Wong - 21 Mar 2006 17:50 GMT
> I've written the following code:
>
[quoted text clipped - 12 lines]
> What i want to know is.. Is there a better (quicker/more efficient) way
> of obtaining the same output?

   When you say "quicker/more efficient", do you mean for the JVM, or for
the programmer? I.e. do you mean "It takes less time for the computer to run
this program", or do you mean "I, as a programmer, have to spend less time
writing down this program"?

   - Oliver
José Urzúa - 21 Mar 2006 22:48 GMT
>> I've written the following code:
>>
[quoted text clipped - 12 lines]
>> What i want to know is.. Is there a better (quicker/more efficient) way
>> of obtaining the same output?

public class Sand
{
   public static void main( String args[] )
   {
       System.out.println( "*****\n *** \n  *  \n *** \n*****" );
   }
}

>    When you say "quicker/more efficient", do you mean for the JVM, or
> for the programmer? I.e. do you mean "It takes less time for the
> computer to run this program", or do you mean "I, as a programmer, have
> to spend less time writing down this program"?
>
>    - Oliver

Signature

José Urzúa Reinoso
http://jose.cl

Ivan - 21 Mar 2006 22:49 GMT
uum.. the having to spend less time writing the program one..

Though I don't mind spending more time writing the program, it just
seems like there might be a better way of writing this particular one
without using such elementary processes..
Ivan - 21 Mar 2006 22:54 GMT
hhm.. okay.. i just read the question again and i do have to use
loops.. or nested loops..
Oliver Wong - 21 Mar 2006 23:50 GMT
> hhm.. okay.. i just read the question again and i do have to use
> loops.. or nested loops..

   Well, if you have to use nested loops, then your original program won't
solve the problem. So you better give it another stab before we start
posting solutions for you.

   - Oliver
Ivan - 22 Mar 2006 00:50 GMT
Yep.. Will post my solutions when I do it..

Thanks to all..
Ivan - 22 Mar 2006 05:36 GMT
hhm..
Okay.. This is what I have so far..

import java.io.*;
import java.math.*;
public class Pattern
{
   public static void main( String args[] )
       throws IOException
   {
       int y=1;
       int x=1;
       int z=1;
       int gap = 4;
       int size=9;

       for (x=1; x<=size; x+=2)
       {
           for (z=1; z<=gap; z++)
           {
               System.out.print(" ");
           }
           for (y=1; (y<=(x)); y++)
           System.out.print("*");
           System.out.println();

           gap--;
       }
   }
}

i've made it this far and it seems as if though I can't get my head
around getting the top half to work..
Oliver Wong - 22 Mar 2006 16:46 GMT
> hhm..
> Okay.. This is what I have so far..
[quoted text clipped - 29 lines]
> i've made it this far and it seems as if though I can't get my head
> around getting the top half to work..

   You've got the right idea. This program only prints the "bottom"
triangle. Consider this strategy: Put this program aside for now, and start
writing a new program; one which only prints the "top" triangle.

   Then, take both programs and try to combine them together, to see if you
can produce the whole figure. You'll probably have 2 sets of nested loops,
e.g.

for (something) {
 for (something) {
   do something;
 }
}
for (something) {
 for (something) {
   do something;
 }
}

   - Oliver
Tom Leylan - 22 Mar 2006 19:50 GMT
Hi Ivan:

Well as you can probably tell you've solved it the quicker more efficient
way but probably not the better way (depending upon one's definition of
better.)  You can imagine how it would be to write an 80-row version or if
having completed it the "boss" says "oh but the user gets to choose the
characters to use did I forget to tell you that?"

I can post the code but you should try it first.  Don't think of this as
asterisks and spaces it's all about a pattern and that requires an
algorithm.  Roedy pointed out the pattern you should be trying to solve.
Notice one thing however that the right digit is always the same as the left
digit.  That means you only need to solve for the number of stars and 1/2
the number of spaces.

I wrote it so a maximum number of rows plus two characters can be set and it
generates the pattern.  The only restriction is that the maximum rows must
be odd which is the only way you can get one star in the middle.  I did use
nested loops but they don't look nested since I put the second loop into
it's own procedure so I didn't have to repeat it 3 times.

I noticed your code earlier and your comment about getting the "top-half" to
work.  Avoid thinking about it as having two parts.  I recommend an
iterative process so make sure you can print <n> rows of <n> stars.  Then
make it print the same <n> rows but printing <n1> spaces (I think you should
use periods though, you can see them better) plus <n2> stars plus <n1>
spaces.

So you would get something like this:

...*****...
...*****...
...*****...
...*****...
...*****...

It will be working but clearly it's just a square.  So now the algorithm
comes down to "how do increase the number of periods and reduce the number
of stars (until there is one star) and then reverse the process"?

Tom

>> hhm..
>> Okay.. This is what I have so far..
[quoted text clipped - 50 lines]
>
>    - Oliver
Ivan - 22 Mar 2006 22:55 GMT
hi..

I think I'm almost there..

It's getting rather frustrating and it feels like I hit another brick
wall..

public class Star
{
   public static void main( String args[] )
   {
       int size = 9;
       int insize = size;

       // Start inverted triangle
       for( int i = 0 ; i<=size ; i++ )
       {
           for( int k = 0 ; k<=i ; k++ )
           {
                System.out.print(".") ;// first print space equal to i
           }
            for ( int j=0 ; j <= insize ; j++ )
           {
               System.out.print("* ") ;// print star space
           }

           insize = insize -1 ;
           System.out.println();
       }
   // end inverted triangle

   // start upright triangle
       int line = 1  ;
       for( int i = size ; i >= 1 ; i-- )
       {
           for( int k = 1 ; k <= i ; k++ )
           {
               System.out.print(".") ;
           }
           for( int j = 0 ; j <= line ; j++ )
           {
               System.out.print("* ");
           }

           line++ ;
           System.out.println() ;
       }
// end upright triangle

   }
}

the pattern I'm getting is as follows

10 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 10

I'm looking for
9 7 5 3 1 3 5 7 9

I hope there's SOMETHING i can do to my code.. And not have to start
again..
jagonzal@gmail.com - 22 Mar 2006 23:04 GMT
> the pattern I'm getting is as follows
>
[quoted text clipped - 5 lines]
> I hope there's SOMETHING i can do to my code.. And not have to start
> again..

Try moving your indexes by twos instead of ones? (for example, use
"k+=2" instead of "++k")
Oliver Wong - 22 Mar 2006 23:07 GMT
> hi..
>
[quoted text clipped - 57 lines]
> I hope there's SOMETHING i can do to my code.. And not have to start
> again..

   You're printing a star, then a space ("* "), my understanding is that
this is NOT what you want, but given the comments present in the source
code, it looks like you were doing this intentionally.

   Anyway, you are almost done. If you change a single character, it will
work.

   - Oliver
Roedy Green - 23 Mar 2006 02:09 GMT
>for( int k = 1 ; k <= i ; k++ )
>            {
[quoted text clipped - 4 lines]
>                System.out.print("* ");
>            }

another sort of trick you can use for this sort of problem looks like
this

for( int i = 1 ; i <= n  ; i++ )
{
System.out.print( ( boolean expression of i ) ? '*' : ' ' );
}
I leave it to you to figure out what the expression looks like.

hint mathmaticians like to write things like this

if ( a _<_šb _<_ c )

which in Java comes out

if ( a <= b && b <= c )

Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

Tom Leylan - 23 Mar 2006 03:35 GMT
Hi Ivan:

You are getting closer.  I think you've recognized a sequence but I don't
think you're seeing the pattern.  It's a formula where the star length
decreases by two at each step until there is one star at which point the
star length increases by two.  At the same time the blank length adjusts by
the same value in the opposite direction.  Interestingly you don't have to
keep track of the number of blanks only the stars because you can calculate
blanks at any time by subtracting stars from total rows.

I originally wrote my version as two procedures in a dummy class but I've
subsequently rewrote it as a static class which can be used as follows:

Stars.ProcessX( "*", ".", 5 );
Stars.ProcessX( "X", ".", 8 );

It even self-corrects in the second example.  I check to see if the number
of rows is odd and if it isn't I add one to it.

One other idea (I know you're learning this) but you want to encapsulate
whatever you can to offer reuse.  You are making a lot of calls to
System.out.print() for instance.  It doesn't matter how many call you make
but that they are scattered throughout the code and that make it difficult
to change if the next thing you want to do is draw graphics instead.  I put
all mine in a private method named StarsOut().  It is using
System.out.print() but the mechanism for all output is there and there
alone.

Seemingly I could add other processes to my Stars class that could output
other shapes as well.  You would end up having to rewrite Main().

One step at a time though :-)

> hi..
>
> I think I'm almost there..
>
> It's getting rather frustrating and it feels like I hit another brick
> wall..

<code snipped>

> the pattern I'm getting is as follows
>
[quoted text clipped - 5 lines]
> I hope there's SOMETHING i can do to my code.. And not have to start
> again..


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.