Created
April 30, 2014 05:35
-
-
Save YuukiARIA/7a34ae2d73d9e1564895 to your computer and use it in GitHub Desktop.
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
use strict; | |
use warnings; | |
use List::Util qw/sum reduce/; | |
use Test::More; | |
sub sample1 { | |
my ( $a, $b ) = @_; | |
if ( !$a && !$b ) { | |
return "hello"; | |
} | |
else { | |
return "world"; | |
} | |
} | |
# ドモルガンの法則で簡素化せよ | |
sub answer1_1 { | |
my ( $a, $b ) = @_; | |
unless ( $a || $b ) { | |
return "hello"; | |
} | |
else { | |
return "world"; | |
} | |
} | |
sub is_both_zero { | |
my ( $a, $b ) = @_; | |
return !$a && !$b; | |
} | |
# 関数切り出しで簡素化せよ | |
sub answer1_2 { | |
my ( $a, $b ) = @_; | |
if ( is_both_zero($a, $b) ) { | |
return "hello"; | |
} | |
else { | |
return "world"; | |
} | |
} | |
sub sample2 { | |
my ( $a, $b, $c ) = @_; | |
if ( !$c ) { | |
if ( !$a && !$b ) { | |
return "hello"; | |
} | |
else { | |
return "world"; | |
} | |
} | |
return ( $a or $b ); | |
} | |
# ガード節でネストを下げよ | |
sub answer2 { | |
my ( $a, $b, $c ) = @_; | |
return $a or $b if $c; | |
return "hello" unless $a or $b; | |
return "world"; | |
} | |
sub sample3 { | |
my ( $a, $b, $c, $d ) = @_; | |
if ( $a && $b && !$c && !$d) { | |
return "a and b"; | |
} | |
if ( $a && !$b && $c && !$d) { | |
return "a and c"; | |
} | |
if ( $a && !$b && !$c && $d) { | |
return "a and d"; | |
} | |
if ( !$a && $b && $c && !$d) { | |
return "b and c"; | |
} | |
if ( !$a && $b && !$c && $d) { | |
return "b and d"; | |
} | |
if ( !$a && !$b && $c && $d) { | |
return "c and d"; | |
} | |
return $a+$b+$c+$d; | |
} | |
sub bool_to_str { | |
my ($b) = @_; | |
return $b ? '1' : '0'; | |
} | |
sub bits_to_str { | |
return reduce { $a . $b } map { bool_to_str($_) } @_ | |
} | |
# 制御をデータ構造に置き換えて簡素化せよ | |
sub answer3{ | |
my %table = ( | |
"1100" => "a and b", | |
"1010" => "a and c", | |
"1001" => "a and d", | |
"0110" => "b and c", | |
"0101" => "b and d", | |
"0011" => "c and d" | |
); | |
my $result = $table{bits_to_str(@_)}; | |
return $result // sum @_; | |
} | |
sub check_bool_eq { | |
my ( $num, $func_a, $func_b ) = @_; | |
for my $s ( 1 .. 2**$num ) { | |
my @args = map { $s & ( 1 << $_ ) } ( 1 .. $num ); | |
is( $func_a->(@args), $func_b->(@args) ); | |
} | |
} | |
check_bool_eq( 2, \&sample1, \&answer1_1 ); | |
check_bool_eq( 2, \&sample1, \&answer1_2 ); | |
check_bool_eq( 3, \&sample2, \&answer2 ); | |
check_bool_eq( 4, \&sample3, \&answer3 ); | |
::done_testing; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment