2017年2月23日木曜日

開発環境

Think Perl 6: How to Think Like a Computer Scientist (Laurent Rosenfeld(著)、Allen B. Downey(著)、Oreilly & Associates Inc)のChapter 4(Conditionals and recursion)のExercises 4-1、2、3、4、5.を取り組んでみる。

Exercises 4-1、2、3、4、5.

コード(Emacs)

#!/usr/bin/env perl6

# 4-1.
# 1.
sub date($seconds is copy) {
    my $d = $seconds div (60 * 60 * 24);
    $seconds = $seconds % (60 * 60 * 24);
    my $h = $seconds div (60 * 60);
    $seconds = $seconds % (60 * 60);
    my $m = $seconds div 60;
    my $s = $seconds % 60;
    say "days: $d, hours: $h, minutes: $m, seconds: $s";
}

date(0);
date(60);
date(3600);
date(3600 * 24);
date(1000000);

# 2.
date(240000);

# 3.
my $s = prompt "input a number of seconds: ";

date($s.Int);

# 4-2.
# 1.
sub check-fermat($a, $b, $c, $n) {
    if $n > 2 and  $a ** $n + $b ** $n == $c ** $n {
        say 'Holy smokes, Fermat was wrong!';
    } else {
        say "No, that doesn't work.";
    }
}

# 2.
my $a = prompt 'a = ';
my $b = prompt 'b = ';
my $c = prompt 'c = ';
my $n = prompt 'n = ';

check-fermat($a.Int, $b.Int, $c.Int, $n.Int);

# 4-3.
sub is-triangle ($a, $b, $c) {
    if ($a + $b > $c) or ($b + $c > $a) or ($c + $a > $b) {
        say 'Yes';
    } else {
        say 'No';
    }
}

is-triangle(1, 2, 3);
is-triangle(1, 2, 4);
is-triangle(2, 4, 1);
is-triangle(4, 1, 2);
$a = prompt 'a = ';
$b = prompt 'b = ';
$c = prompt 'c = ';

# 2.
is-triangle($a.Int, $b.Int, $c.Int);

# 4-4.
$a = 1;
$b = 1;

say $a;
say $b;
for 3..20 {
    my $t = $a + $b;
    say $t;
    $a = $b;
    $b = $t;
}

# 2.
$n = prompt 'number: ';
if $n <= 2 {
    say 1;
} else {
    my $a = 1;
    my $b = 1;
    my $t;
    for 3..$n.Int {
        $t = $a + $b;
        $a = $b;
        $b = $t;
    }
    say $t;
}

# 4-5.
# 1. infinite recursion
# 2. $n >= 0

入出力結果(Terminal)

$ ./sample1.pl
days: 0, hours: 0, minutes: 0, seconds: 0
days: 0, hours: 0, minutes: 1, seconds: 0
days: 0, hours: 1, minutes: 0, seconds: 0
days: 1, hours: 0, minutes: 0, seconds: 0
days: 11, hours: 13, minutes: 46, seconds: 40
days: 2, hours: 18, minutes: 40, seconds: 0
input a number of seconds: 240000
days: 2, hours: 18, minutes: 40, seconds: 0
a = 3
b = 4
c = 5
n = 3
No, that doesn't work.
Yes
Yes
Yes
Yes
a = 1
b = 1
c = 2
Yes
1
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
1597
2584
4181
6765
number: 20
6765
$

0 コメント:

コメントを投稿