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:
In reply to Re: CarTalk Puzzler
by radiantmatrix
in thread CarTalk Puzzler
by freddo411
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |