| 1 |
#!perl |
| 2 |
# Copyright 2022 Jeffrey Kegler |
| 3 |
# This file is part of Marpa::R2. Marpa::R2 is free software: you can |
| 4 |
# redistribute it and/or modify it under the terms of the GNU Lesser |
| 5 |
# General Public License as published by the Free Software Foundation, |
| 6 |
# either version 3 of the License, or (at your option) any later version. |
| 7 |
# |
| 8 |
# Marpa::R2 is distributed in the hope that it will be useful, |
| 9 |
# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 10 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
| 11 |
# Lesser General Public License for more details. |
| 12 |
# |
| 13 |
# You should have received a copy of the GNU Lesser |
| 14 |
# General Public License along with Marpa::R2. If not, see |
| 15 |
# http://www.gnu.org/licenses/. |
| 16 |
|
| 17 |
use 5.010001; |
| 18 |
|
| 19 |
# Count the ways of parenthesizing N symbols in pairs |
| 20 |
# This generates the Catalan numbers |
| 21 |
|
| 22 |
use strict; |
| 23 |
use warnings; |
| 24 |
|
| 25 |
use Test::More tests => 7; |
| 26 |
use lib 'inc'; |
| 27 |
use Marpa::R2::Test; |
| 28 |
use Marpa::R2; |
| 29 |
|
| 30 |
my $g = Marpa::R2::Grammar->new( |
| 31 |
{ start => 'pair', |
| 32 |
rules => [ |
| 33 |
[ pair => [qw(a a)], '::whatever' ], |
| 34 |
[ pair => [qw(pair a)], '::whatever' ], |
| 35 |
[ pair => [qw(a pair)], '::whatever' ], |
| 36 |
[ pair => [qw(pair pair)], '::whatever' ], |
| 37 |
], |
| 38 |
terminals => ['a'], |
| 39 |
|
| 40 |
} |
| 41 |
); |
| 42 |
$g->precompute(); |
| 43 |
|
| 44 |
sub do_pairings { |
| 45 |
my $n = shift; |
| 46 |
my $parse_count = 0; |
| 47 |
|
| 48 |
my $recce = Marpa::R2::Recognizer->new( { grammar => $g } ); |
| 49 |
|
| 50 |
# An arbitrary maximum is put on the number of parses -- this is for |
| 51 |
# debugging, and infinite loops happen. |
| 52 |
$recce->set( { max_parses => 999, } ); |
| 53 |
|
| 54 |
for my $token_ix ( 0 .. $n - 1 ) { |
| 55 |
$recce->read('a'); |
| 56 |
} |
| 57 |
|
| 58 |
while ( my $value_ref = $recce->value() ) { |
| 59 |
$parse_count++; |
| 60 |
} |
| 61 |
return $parse_count; |
| 62 |
} ## end sub do_pairings |
| 63 |
|
| 64 |
my @catalan_numbers = ( 0, 1, 1, 2, 5, 14, 42, 132, 429 ); |
| 65 |
|
| 66 |
for my $a ( ( 2 .. 8 ) ) { |
| 67 |
|
| 68 |
my $actual_parse_count = do_pairings($a); |
| 69 |
Marpa::R2::Test::is( $actual_parse_count, $catalan_numbers[$a], |
| 70 |
"Catalan number $a matches parse count ($actual_parse_count)" ); |
| 71 |
|
| 72 |
} ## end for my $a ( ( 2 .. 8 ) ) |
| 73 |
|
| 74 |
1; # In case used as "do" file |
| 75 |
|
| 76 |
# Local Variables: |
| 77 |
# mode: cperl |
| 78 |
# cperl-indent-level: 4 |
| 79 |
# fill-column: 100 |
| 80 |
# End: |
| 81 |
# vim: expandtab shiftwidth=4: |