From ff29be3b5fa5ce84e6f98e9e3806b14a70f79d92 Mon Sep 17 00:00:00 2001 From: Steven Wilson Date: Sat, 20 Jul 2019 16:41:45 +0100 Subject: add script for task 1 --- challenge-017/steven-wilson/perl5/ch-1.pl | 53 +++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 challenge-017/steven-wilson/perl5/ch-1.pl diff --git a/challenge-017/steven-wilson/perl5/ch-1.pl b/challenge-017/steven-wilson/perl5/ch-1.pl new file mode 100644 index 0000000000..7aa4cdb3c1 --- /dev/null +++ b/challenge-017/steven-wilson/perl5/ch-1.pl @@ -0,0 +1,53 @@ +#!/usr/bin/env perl +# Author: Steven Wilson +# Date: 2019-07-15 +# Week: 017 +# +# Task #1 +# Create a script to demonstrate Ackermann function. The Ackermann +# function is defined as below, m and n are positive number: +# A(m, n) = n + 1 if m = 0 +# A(m, n) = A(m - 1, 1) if m > 0 and n = 0 +# A(m, n) = A(m - 1, A(m, n - 1)) if m > 0 and n > 0 +# Example expansions as shown in wiki page. +# https://en.wikipedia.org/wiki/Ackermann_function +# A(1, 2) = A(0, A(1, 1)) +# = A(0, A(0, A(1, 0))) +# = A(0, A(0, A(0, 1))) +# = A(0, A(0, 2)) +# = A(0, 3) +# = 4 + +use strict; +use warnings; +use Memoize; +no warnings 'recursion'; +use feature qw/ say /; +use Test::More; + +ok( A( 1, 2 ) == 4, 'Test A(1, 2) == 4' ); + +done_testing(); + +# This gets past A(4,1) quicker but A(4,2) takes too long so don't run this script +memoize("A"); + +sub A { + my ( $m, $n ) = @_; + if ( $m == 0 ) { + return $n + 1; + } + elsif ( $m > 0 and $n == 0 ) { + return A( $m - 1, 1 ); + } + elsif ( $m > 0 and $n > 0 ) { + return A( $m - 1, A( $m, $n - 1 ) ); + } +} + +my $number = 4; +for my $n ( 0 .. $number ) { + for my $m ( 0 .. $number ) { + say "A($m, $n) is ". A( $m, $n ); + } +} -- cgit