Created
April 29, 2014 13:50
-
-
Save hirokidaichi/11400997 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
use strict; | |
use warnings; | |
use Test::More; | |
sub sample1 { | |
my ( $a, $b ) = @_; | |
if ( !$a && !$b ) { | |
return "hello"; | |
} | |
else { | |
return "world"; | |
} | |
} | |
# ドモルガンの法則で簡素化せよ | |
sub answer1_1 { | |
my ( $a, $b ) = @_; | |
if ( !$a && !$b ) { | |
return "hello"; | |
} | |
else { | |
return "world"; | |
} | |
} | |
# 関数切り出しで簡素化せよ | |
sub answer1_2 { | |
my ( $a, $b ) = @_; | |
if ( !$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 ) = @_; | |
if ( !$c ) { | |
if ( !$a && !$b ) { | |
return "hello"; | |
} | |
else { | |
return "world"; | |
} | |
} | |
return ( $a or $b ); | |
} | |
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 answer3{ | |
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 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