Created
March 5, 2013 09:24
-
-
Save khronos227/5089040 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/perl | |
| #たかしくんは栗拾いに出かけました。 | |
| #たかしくんは左上から右下に向かって栗を拾いながら進みます。 | |
| #たかしくんは下、右のいずれかに進むことができます。 | |
| #たかしくんが拾う栗の最大数を算出するプログラムを書いてください。 | |
| # | |
| #入力例:添付ファイル | |
| #各数字が、その場所で拾うことのできる栗の数 | |
| my @data = (); | |
| my @route = (); | |
| sub readData{ | |
| my ($fileName,$data,$route) = @_; | |
| my $length = 0; | |
| open(IN, $fileName) or die("ファイルを開けません"); | |
| while(my $line = <IN>){ | |
| #各改行コード削除 | |
| $line =~ s/\x0D?\x0A?$//; | |
| #前後スペース削除 | |
| $line =~ s/^\s*(.*?)\s*$/$1/; | |
| @array = split(/,/,$line); | |
| $len = @array; | |
| if($len < $length){ | |
| die("栗拾いマップが不正です"); | |
| } | |
| $length = $len; | |
| push(@$data, ([@array])); | |
| push(@$route,([@array])); | |
| } | |
| } | |
| sub calcScore{ | |
| my ($data,$scores) = @_; | |
| for (my $y = 0; $y < @$data+0; $y++){ | |
| my @array = @{$data->[$y]}; | |
| for (my $x = 0; $x < @array+0; $x++){ | |
| # 上の要素取り出し | |
| my $upper = 0; | |
| if($y - 1 >= 0){ | |
| $upper = $data->[$y - 1]->[$x]; | |
| } | |
| # 左の要素取り出し | |
| my $left = 0; | |
| if($x - 1 >= 0){ | |
| $left = $data->[$y]->[$x - 1]; | |
| } | |
| $data->[$y]->[$x] = ($upper >= $left ? $upper : $left) + $data->[$y]->[$x]; | |
| } | |
| } | |
| } | |
| sub getAnswer{ | |
| my ($data) = @_; | |
| return $data->[@$data - 1]->[@{$data->[@$data - 1]} - 1]; | |
| } | |
| sub printRoute{ | |
| my ($data,$route) = @_; | |
| $y = @$data - 1; | |
| $x = @{$data->[@$data - 1]} - 1; | |
| my $current = $route->[$y]->[$x]; | |
| $route->[$y]->[$x] = -1; | |
| while($x > 0 || $y > 0){ | |
| # 上の要素取り出し | |
| my $upper = 0; | |
| if($y - 1 >= 0){ | |
| $upper = $data->[$y - 1]->[$x]; | |
| } | |
| # 左の要素取り出し | |
| my $legt = 0; | |
| if($x - 1 >= 0){ | |
| $left = $data->[$y]->[$x - 1]; | |
| } | |
| if($upper + $current == $data->[$y]->[$x]){ | |
| --$y; | |
| }elsif($left + $current == $data->[$y]->[$x]){ | |
| --$x; | |
| }else{ | |
| die("結果とデータが食い違っているようですな。バグですわ。"); | |
| } | |
| $current = $route->[$y]->[$x]; | |
| $route->[$y]->[$x] = -1; | |
| } | |
| $route->[$y]->[$x] = -1; | |
| foreach my $array (@$route){ | |
| foreach my $value (@$array){ | |
| if($value == -1){ | |
| print "o"; | |
| }else{ | |
| print "x"; | |
| } | |
| } | |
| print "\n"; | |
| } | |
| } | |
| &readData($ARGV[0],\@data,\@route); | |
| &calcScore(\@data); | |
| print "Answer is ".&getAnswer(\@data)."\n"; | |
| print &printRoute(\@data,\@route); | |
| print "\n"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment