Skip to content

Instantly share code, notes, and snippets.

@kikuchy
Created April 30, 2014 05:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kikuchy/a25c08c062345bd5ac6c to your computer and use it in GitHub Desktop.
Save kikuchy/a25c08c062345bd5ac6c to your computer and use it in GitHub Desktop.
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 ) = @_;
unless ( $a || $b ) {
return "hello";
}
else {
return "world";
}
}
# 関数切り出しで簡素化せよ
sub answer1_2 {
my ( $a, $b ) = @_;
if ( is_enable($a, $b) ) {
return "hello";
}
else {
return "world";
}
}
sub is_enable {
my ( $a, $b ) = @_;
return !( $a || $b );
}
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 ) {
return ( $a or $b )
}
unless ( $a or $b ) {
return "hello";
}
else {
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 answer3{
my ( $a, $b, $c, $d ) = @_;
my %table = (
$a => "a",
$b => "b",
$c => "c",
$d => "d"
);
my @trues = grep {$_} @_;
return "$table{$trues[0]} and $table{$trues[1]}" if @trues == 2;
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