2017年5月14日日曜日

開発環境

Think Perl 6: How to Think Like a Computer Scientist (Laurent Rosenfeld(著)、Allen B. Downey(著)、Oreilly & Associates Inc)のPart 1(Starting with the basics)、Chapter 9(Arrays and Lists)の Exercise 9-1、2、3、4、5、6、7、8、9.を取り組んでみる。

Exercise 9-1、2、3、4、5、6、7、8、9.

コード(Emacs)

#!/usr/bin/env perl6
# -*- coding: utf-8 -*-

say '1.';
sub nested-sum(@AoA) {
    my $result = 0;
    for @AoA -> @a {
        for @a {
            $result += $_;
        }
    }
    return $result;
}

my @AoA = [[1, 2], [3], [4, 5, 6]];

say nested-sum(@AoA);

say '2.';
sub cumul-sum(@numbers) {
    my @result;
    for 0..@numbers.elems - 1 {
        push @result, @numbers[$_] + $_;
    }
    return @result;
}
my @nums = [1, 2, 3, 4];
say cumul-sum(@nums);

say '3.';
sub middle(@array) {
    @array[1..*-2];
}

# say middle(1, 2, 3, 4); error
say middle (1, 2, 3, 4);

say '4.';
sub crop-it(@array) {
    @array = @array[1..*-2];
    return;
}
say @nums;
crop-it(@nums);
say @nums;

say '5.';
sub is-sorted(@array) {
    my @array1 = sort @array;

    for 0..@array1.elems - 1 {
        return False unless @array1[$_] == @array[$_];
    }
    return True;
}

say is-sorted (1, 2, 2);
say is-sorted (1, 2, 1);

say '6.';
sub is-anagram($s1, $s2) {
    return False unless $s1.chars == $s2.chars;
    my @array1 = $s1.comb.sort;
    my @array2 = $s2.comb.sort;
    for 0..@array1.elems - 1 {
        return False if @array1[$_] ne @array2[$_];
    }
    return True;
}
say is-anagram("perl 6", "6p elr");
say is-anagram("perl 6", "6pelr");
say is-anagram("perl 6", "6pelra");

say '7.';
sub has-duplicates(@array) {
    @array.elems !== @array.unique.elems;
}

my @nums1 = (1, 2, 3, 4, 5);
my @nums2 = (1, 2, 1, 4, 5);
say has-duplicates(@nums1);
say has-duplicates(@nums2);

say '8.';

my $total = 10000;
my $deplicates = 0;
for 1..$total {
    $deplicates++ if has-duplicates(map {365.rand.Int}, 1..23);
}
say $deplicates / $total * 100, '%';

say '9.';

for 1..5 {
    my @words1;
    my @words2;
    my $t = now;
    for 'words.txt'.IO.lines {
        push @words1, $_;
    }
    say "push:    ", now - $t;

    $t = now;
    for 'words.txt'.IO.lines {
        unshift @words2, $_;
    }
    say "unshift: ", now - $t;
}

入出力結果(Terminal, REPL)

$ ./sample1.pl
1.
21
2.
[1 3 5 7]
3.
(2 3)
4.
[1 2 3 4]
[2 3]
5.
True
False
6.
True
False
False
7.
False
True
8.
51.15%
9.
push:    1.2547846
unshift: 1.61254895
push:    1.23710698
unshift: 1.6442248
push:    1.2594857
unshift: 1.6632775
push:    1.269719
unshift: 1.59224313
push:    1.38028078
unshift: 1.5838102
$

0 コメント:

コメントを投稿