in reply to CarTalk Puzzler
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++; }
|
|---|