Okay here is my hideously slow, unoptimized, but obvious code.

I am actually only mainly posting this because I was puzzled that the this line of code didn't work: $lights{$light} ? $lights{$light} = 0 : $lights{$light} = 1; # turn off if it's on, and vice versa. Ternary if operator didn't work, and I had to do this with normal if operator. If I get around to it I wanted to ask a SOPW about this later on today...

use strict; use warnings; my $num_lights = 2; my %lights; #keep printing results until cancelled by user while ( 1 ) { #lights are all off $lights{$_} = 0 foreach (1..$num_lights); #flip them on and off. foreach my $light ( sort { $a <=> $b }(keys %lights) ){ foreach my $divisor (2..$num_lights ) { if ( $light % $divisor == 0 ) { # if it divides evenly, pu +ll the cord #print "$divisor divides $light evenly\n "; #this doesn't work. #$lights{$light} ? $lights{$light} = 0 : $lights{$ligh +t} = 1; # turn off if it's on, and vice versa. #this works if ( $lights{$light} ) { $lights{$light} = 0; } else { $lights{$light} = 1; } } } } #output is prettier if comment this out #print "on for $num_lights lights: "; #foreach (sort { $a <=> $b }( keys %lights ) ) { # #print "$_ " if $lights{$_}; #} #print "\n"; print "off for $num_lights lights: "; foreach (sort { $a <=> $b }( keys %lights ) ) { print "$_ " unless $lights{$_}; } print "\n"; $num_lights++; }

In reply to Re: CarTalk Puzzler by tphyahoo
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.