Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid

comment on

( #3333=superdoc: print w/replies, xml ) Need Help??
If this were homework (but of course it's not), I imagine a teacher would be very impressed if one of their students developed a uniquely Perl solution. Instead of trying to move elements around one at a time, come up with an algorithm to swap at least two elements.

For example, with Perl you could solve this specific problem with the following two statements:

($slots[1], $slots[2]) = ($slots[2], $slots[1]); ($slots[2], $slots[3]) = ($slots[3], $slots[2]);
and, of course, with one statement:
($slots[1], $slots[2], $slots[3]) = ($slots[2], $slots[3], $slots[1]);
Coming up with an algorithm for two in-place swaps shouldn't be too difficult (I've already shown you the Perl idiom), ++ if you can handle more than two elements at a time.


Update: Well, that's the algorithm part I alluded to, your list of moves for the 2-element swap would look like this:

  • swap(1, 2)
  • swap(2, 3)
Granted trying to notate a 3 at-a-time swap would be difficult, if even possible (thus the ++).

If we'd known that you had to use a one-armed robot to begin with, the replies might have been more useful. ;)

In reply to Re: sort with fewest moves by jlongino
in thread sort with fewest moves by axelrose

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 or How to display code and escape characters are good places to start.
Log In?

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

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (3)
As of 2022-05-21 18:19 GMT
Find Nodes?
    Voting Booth?
    Do you prefer to work remotely?

    Results (77 votes). Check out past polls.