NOTE: **use Perl;** is on undef hiatus. You can read content, but you can't post it. More info will be forthcoming forthcomingly.

bacek

(email not shown publicly)

(email not shown publicly)

Wednesday December 24, 2008

01:11 AM

Hi.

In response to Pm's "Scripting games in Perl6" I've decided to implement some of them in Perl6.

Let's start with easiest "2008: Beginners Event 1"

Task is to calculate number of different pairs of cards.

sub fact($n) {

$n <= 1 ?? 1 !! $n*fact($n-1);

}

sub calculate_pairs(@pairs) {

my %h;

# Calculate number of distinct cards.

++%h{$_} for @pairs;

# Sum of C^N_2

[+] map { int(fact($^a) / 2) }, %h.values;

};

Trivial mathematical solution: number of different pairs for given amount of cards is C^n_2. So, I group cards, calculate number of combinations in different group and sum them.

Little trick: if number of cards in group equals to 1 than int(...) will return 0.

Update: masak++ for pointing to use.perl.org strange reaction on <=

First post.
More |
Login
| Reply

Stories, comments, journals, and other submissions on use Perl; are Copyright 1998-2006, their respective owners.

## C^n_2 (Score:1)

0 0 1 3 12 60 360 ...

C^n_2 is of course n!/(n-2)!2!, or n(n-1)/2:

0 0 1 3 6 10 15 ...

## Factorial in Perl 6 (Score:1)

It’s just

`[*] 1` .. $n

. It’s not even worth putting into a sub.