第七題
將日期寫成YYYYMMDD的形式,然後轉換成二進制,並逆序排列,然後再轉換成十進制,如果與之前的日期相等則正確。查找1970-01-01到2020-07-24之間正確的日期。
#! perl
#20171108
use Date::Parse;
use strict;
my $startTime = "1 Jan 1970";
my $endTime = "24 Jul 2020";
my $startStamp = str2time($startTime);
my $endStamp = str2time($endTime);
for(my $i = $startStamp; $i <= $endStamp; $i = &nextDay($i)) {
&isRight($i);
}
sub nextDay {
my $date = @_[0];
my $dateNext = $date + 86400;
return $dateNext;
}
sub isRight {
my $date = @_[0];
my($sec,$min,$hour,$day,$mon,$year) = localtime($date);
$mon++;$year += 1900;
my $date_now = sprintf("%04d%02d%02d",$year,$mon,$day);
my $dateBin = sprintf("%b", $date_now);
my $dateBinRev = reverse $dateBin;
my $dateDnow = oct('0b' . $dateBinRev);
if($date_now eq $dateDnow) {
print $date_now, "\n";
}
return 0;
}
第八題
機器人可以前後左右移動,每次移動一步,不可以重複到達同一點。比如連續移動3次,則一共有36中路徑。
求:連續移動12次,有多少種路徑。
#!perl
#20171113
use strict;
# The 4 directions
my %direction = ('up' => '(0,1)',
'down' => '(0,-1)',
'left' => '(-1,0)',
'right' => '(1,0)');
# This method is used to get the total steps of something like a robot has moved,
# the robot can only move forward, backward, left and right with one step a time.
# And one place to go only once.
sub forward {
my $p = @_[0];
my @path = @$p;
my $step = 0;
my $length = @path;
# The robot can only move 12 steps;
if($length == 13) {
return 1;
}
if(@path) {
# direction loop
foreach(values %direction) {
my $temp = $_;
# forward
$temp = &move(@path[-1], $_);
# check the target place whether the robot has been to it
if(! grep {$_ eq $temp} @path) {# if not, move
# record the place
push @path,$temp;
# enter the iteration process
$step += &forward(\@path);
# pop the lastest place when the robot has explored one path
pop @path;
}
}
return $step;
}
}
my @path = qw/(0,0)/;
my $pp = \@path;
my $result = &forward($pp);
print "result $result \n";
# // this method is used to change the location
sub move {
my $src = @_[0];
my $tar = @_[1];
my @srcArr = split /,/, $src;
my $src_x = substr $srcArr[0], 1;
my $src_y = substr $srcArr[1], 0;
my @tarArr = split /,/, $tar;
my $tar_x = substr $tarArr[0], 1;
my $tar_y = substr $tarArr[1], 0;
my $res_x = $src_x + $tar_x;
my $res_y = $src_y + $tar_y;
my $res = "(" . $res_x . "," . $res_y . ")";
$res;
}
這道題用到了深度遍歷算法,該算法的意思就是:一條道走到黑,撞牆之後回到上一個十字路口,換個方向繼續走,一直到走完所有的路或者達到停止條件。
ps: 英文註釋是爲了提高自己的英文寫作和閱讀水平,以後還要多多練習
第九題
沒明白題目…兩組人數均等是什麼意思?男女相等麼?男生20人,女生10人,怎麼分也不會均等啊。可能是我理解有問題。