Created
March 31, 2013 04:00
-
-
Save clicktx/5279496 to your computer and use it in GitHub Desktop.
アルゴリズムを学ぼうP48の問題: 戦略1をperlで書く。コピー回数のカウント用。
This file contains 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/env perl | |
use strict; | |
use warnings; | |
# 戦略1: 10だけ大きくした配列を作る戦略 | |
my $array_ref =[('undef') x 10]; | |
my $count = count(); | |
run($ARGV[0]); | |
sub run { | |
my $case = shift; | |
my $item = 1; | |
for (1 .. $case) { | |
my $index = $_ - 1; | |
$array_ref = insertItem($array_ref, $index, $item); | |
} | |
print "$caseの場合: "; | |
print $count->() -1, "回\n"; | |
} | |
sub count { | |
my $i = 0; | |
return sub{ | |
$i++; | |
return $i; | |
}; | |
} | |
sub insertItem { | |
my $array_ref = shift; | |
my $index = shift; | |
my $item = shift; | |
if (@$array_ref <= $index){ | |
# 新しい配列を作成 | |
my $new_array_ref = [ ('undef') x (@$array_ref + 10) ]; | |
# 新しい配列に全てコピー | |
foreach (0 .. @$array_ref - 1){ | |
$new_array_ref->[$_] = $item; | |
$count->(); | |
} | |
$new_array_ref->[$index] = $item; | |
$count->(); | |
return $new_array_ref; | |
} | |
$array_ref->[$index] = $item; | |
$count->(); | |
return $array_ref; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment