As a demonstration of how finding the pattern (perfect squares) is so much better than brute force, a benchmark:

use strict; use warnings; $|=1; sub sol1 { #init; my $lights = 20_000; my @lit = map {1} (1..$lights); my @sol; #flip; for (2..$lights) { my $cnt = $_-1; while ($cnt < $lights) { $lit[$cnt] = !$lit[$cnt]; $cnt+=$_; } } #answer; for (0..$#lit) { push @sol, $_+1 if $lit[$_] } } sub sol2 { my $lights = 20_000; my @sol; for (1..$lights) { my $sqr = sqrt($_); push @sol, $_ if int($sqr) == $sqr; } } use Benchmark ':all'; cmpthese( 100, { sol1 => \&sol1, sol2 => \&sol2, }); __END__ Rate sol1 sol2 sol1 6.58/s -- -93% sol2 98.5/s 1398% --

These two solutions are abstracted to work for any number of lights, and the first is meant to be something someone of average coding skill might come up with (i.e. my crack at the solution ;-) ). Notice how sol2, where we just find all the perfect squares in range, is tremendously faster.

Just goes to show that the best optimization is done by redefining the problem. In this case, redefining from "toggle every nth light for n=2..max" to "find all lights that are perfect squares" resulted in a performance gain of nearly 1700%1400%!

Updates:

<-radiant.matrix->
A collection of thoughts and links from the minds of geeks
The Code that can be seen is not the true Code
"In any sufficiently large group of people, most are idiots" - Kaa's Law

In reply to Re: CarTalk Puzzler by radiantmatrix
in thread CarTalk Puzzler by freddo411

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



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.