Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
sflitman,
I finally have a solution I am happy with. It only loops 206 times as that's how many possible 3x3 magic squares using 1-26 there are. Of course, I spent far more of my time (not to mention tilly and tye) figuring out how to get this solution then it would have taken just to let a naive brute force run. Enjoy. This should scale something close to O(N) where N is the number of names that you want to check.
#!/usr/bin/perl use strict; use warnings; my @possible; for my $x (5 .. 22) { for my $y (grep {$_ != $x} 1 .. int((25 - $x) / 2)) { my $max = 26 - $x - 2 * $y; my $min = $x - 2 * $y - 1; for my $z (grep {$_ != $x && $_ != $y} 1 .. ($min < $max ? $mi +n : $max)) { my @square = ( ($x + $y), ($x + $z), ($x - $y - $z), ($x - 2 * $y - $z), ($x), ($x + 2 * $y + $z), ($x + $y + $z), ($x - $z), ($x - $y) ); push @possible, join '', map chr($_ + 64), @square; } } } NAME: for (qw/PAUL JOHN MARTY SHEILA SMACK SUZY ELSA/) { for my $square (@possible) { my $name = $_; $name =~ s/[$square]//g; if (! length($name)) { print "$_ is contained within $square\n"; next NAME; } } print "No solution for $_\n"; }

Cheers - L~R


In reply to Re: magic squares by Limbic~Region
in thread magic squares by sflitman

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 pondering the Monastery: (7)
As of 2024-04-19 15:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found