Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

I'm trying to keep this in terms that someone in an introductory CS class would be equipped to grasp. Therefore, I'm not using an array, Perl's higher-order functions, etc. And as you requested, I'm using a single loop; no hidden implicit ones, just a single flat loop. The modulus operator should be taught in the first week or two of any intro to CS course.

foreach ( 1 .. 64 ) { print "\n" if ( $_ - 1 ) % 8 == 0; print "$_ "; }

The foreach loop iterates over the numbers 1 through 64, inclusive. On each iteration, the variable "$_" holds the value for a single integer within the range of 1 through 64.

First, we test whether "number minus one, mod eight" is zero. In other words, using integer math, whether the number minus one, divided by eight, has no remainder. If there is no remainder, print a newline character.

Then proceed to print the number itself.

Then iterate again.

Actually the formatting would be a little cleaner if you test for a remainder of 7, and in that case print a newline after the number:

foreach ( 1 .. 64 ) { print "$_ "; print "\n" if ( $_ - 1 ) % 8 == 7; }

For purists, there is a hidden loop, but it's not a part of our algorithm; constructing the range 1 .. 64 to iterate over is done by Perl using an internal loop. If we really wanted to keep it pure, we could use "while", or a C-style for.


Dave


In reply to Re^4: Chess Board Single Loop by davido
in thread Chess Board Single Loop by xantithor

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chanting in the Monastery: (8)
As of 2024-04-18 10:39 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found