Padovan n-step number sequences: Difference between revisions
Line 934: | Line 934: | ||
|- |
|- |
||
|} |
|} |
||
=={{header|Mathematica}}/{{header|Wolfram Language}}== |
|||
<lang Mathematica>ClearAll[Padovan] |
|||
Padovan[2,tmax_]:=Module[{start,a,m}, |
|||
start={1,1,1}; |
|||
start=MapIndexed[a[#2[[1]]]==#1&,start]; |
|||
RecurrenceTable[{a[m]==a[m-2]+a[m-3]}~Join~start,a, {m,tmax}] |
|||
] |
|||
Padovan[n_,tmax_]:=Module[{start,eq,a,m}, |
|||
start=Padovan[n-1,n+1]; |
|||
start=MapIndexed[a[#2[[1]]]==#1&,start]; |
|||
eq=Range[2,n+1]; |
|||
eq=Append[start,a[m]==Total[a[m-#]&/@eq]]; |
|||
RecurrenceTable[eq,a, {m,tmax}] |
|||
] |
|||
Padovan[2,15] |
|||
Padovan[3,15] |
|||
Padovan[4,15] |
|||
Padovan[5,15] |
|||
Padovan[6,15] |
|||
Padovan[7,15] |
|||
Padovan[8,15]</lang> |
|||
{{out}} |
|||
<pre>{1,1,1,2,2,3,4,5,7,9,12,16,21,28,37} |
|||
{1,1,1,2,3,4,6,9,13,19,28,41,60,88,129} |
|||
{1,1,1,2,3,5,7,11,17,26,40,61,94,144,221} |
|||
{1,1,1,2,3,5,8,12,19,30,47,74,116,182,286} |
|||
{1,1,1,2,3,5,8,13,20,32,51,81,129,205,326} |
|||
{1,1,1,2,3,5,8,13,21,33,53,85,136,218,349} |
|||
{1,1,1,2,3,5,8,13,21,34,54,87,140,225,362}</pre> |
|||
=={{header|Nim}}== |
=={{header|Nim}}== |
Revision as of 22:20, 16 August 2021
You are encouraged to solve this task according to the task description, using any language you may know.
As the Fibonacci sequence expands to the Fibonacci n-step number sequences; We similarly expand the Padovan sequence to form these Padovan n-step number sequences.
The Fibonacci-like sequences can be defined like this:
For n == 2: start: 1, 1 Recurrence: R(n, x) = R(n, x-1) + R(n, x-2); for n == 2 For n == N: start: First N terms of R(N-1, x) Recurrence: R(N, x) = sum(R(N, x-1) + R(N, x-2) + ... R(N, x-N))
For this task we similarly define terms of the first 2..n-step Padovan sequences as:
For n == 2: start: 1, 1, 1 Recurrence: R(n, x) = R(n, x-2) + R(n, x-3); for n == 2 For n == N: start: First N + 1 terms of R(N-1, x) Recurrence: R(N, x) = sum(R(N, x-2) + R(N, x-3) + ... R(N, x-N-1))
The initial values of the sequences are:
Padovan -step sequences Values OEIS Entry 2 1,1,1,2,2,3,4,5,7,9,12,16,21,28,37, ... A134816: 'Padovan's spiral numbers' 3 1,1,1,2,3,4,6,9,13,19,28,41,60,88,129, ... A000930: 'Narayana's cows sequence' 4 1,1,1,2,3,5,7,11,17,26,40,61,94,144,221, ... A072465: 'A Fibonacci-like model in which each pair of rabbits dies after the birth of their 4th litter' 5 1,1,1,2,3,5,8,12,19,30,47,74,116,182,286, ... A060961: 'Number of compositions (ordered partitions) of n into 1's, 3's and 5's' 6 1,1,1,2,3,5,8,13,20,32,51,81,129,205,326, ... <not found> 7 1,1,1,2,3,5,8,13,21,33,53,85,136,218,349, ... A117760: 'Expansion of 1/(1 - x - x^3 - x^5 - x^7)' 8 1,1,1,2,3,5,8,13,21,34,54,87,140,225,362, ... <not found>
- Task
- Write a function to generate the first terms, of the first
2..max_n
Padovan -step number sequences as defined above. - Use this to print and show here at least the first
t=15
values of the first2..8
-step sequences.
(The OEIS column in the table above should be omitted).
ALGOL 68
<lang algol68>BEGIN # show some valuies of the Padovan n-step number sequences #
# returns an array with the elements set to the elements of # # the Padovan sequences from 2 to max s & elements 1 to max e # # max s must be >= 2 # PROC padovan sequences = ( INT max s, max e )[,]INT: BEGIN PRIO MIN = 1; OP MIN = ( INT a, b )INT: IF a < b THEN a ELSE b FI; # sequence 2 # [ 2 : max s, 1 : max e ]INT r; FOR x TO max e MIN 3 DO r[ 2, x ] := 1 OD; FOR x FROM 4 TO max e DO r[ 2, x ] := r[ 2, x - 2 ] + r[ 2, x - 3 ] OD; # sequences 3 and above # FOR n FROM 3 TO max s DO FOR x TO max e MIN n + 1 DO r[ n, x ] := r[ n - 1, x ] OD; FOR x FROM n + 2 TO max e DO r[ n, x ] := 0; FOR p FROM x - n - 1 TO x - 2 DO r[ n, x ] +:= r[ n, p ] OD OD OD; r END # padovan sequences # ; # calculate and show the sequences # [,]INT r = padovan sequences( 8, 15 ); print( ( "Padovan n-step sequences:", newline ) ); FOR n FROM 1 LWB r TO 1 UPB r DO print( ( whole( n, 0 ), " |" ) ); FOR x FROM 2 LWB r TO 2 UPB r DO print( ( " ", whole( r[ n, x ], -3 ) ) ) OD; print( ( newline ) ) OD
END</lang>
- Output:
Padovan n-step sequences: 2 | 1 1 1 2 2 3 4 5 7 9 12 16 21 28 37 3 | 1 1 1 2 3 4 6 9 13 19 28 41 60 88 129 4 | 1 1 1 2 3 5 7 11 17 26 40 61 94 144 221 5 | 1 1 1 2 3 5 8 12 19 30 47 74 116 182 286 6 | 1 1 1 2 3 5 8 13 20 32 51 81 129 205 326 7 | 1 1 1 2 3 5 8 13 21 33 53 85 136 218 349 8 | 1 1 1 2 3 5 8 13 21 34 54 87 140 225 362
ALGOL W
<lang algolw>begin % show some valuies of the Padovan n-step number sequences %
% sets R(i,j) to the jth element of the ith padovan sequence % % maxS is the number of sequences to generate and maxE is the % % maximum number of elements for each sequence % % maxS must be >= 2 % procedure PadovanSequences ( integer array R ( *, * ) ; integer value maxS, maxE ) ; begin integer procedure min( integer value a, b ) ; if a < b then a else b; % sequence 2 % for x := 1 until min( maxE, 3 ) do R( 2, x ) := 1; for x := 4 until maxE do R( 2, x ) := R( 2, x - 2 ) + R( 2, x - 3 ); % sequences 3 and above % for N := 3 until maxS do begin for x := 1 until min( maxE, N + 1 ) do R( N, x ) := R( N - 1, x ); for x := N + 2 until maxE do begin R( N, x ) := 0; for p := x - N - 1 until x - 2 do R( N, x ) := R( N, x ) + R( N, p ) end for_x end for_N end PadovanSequences ; integer MAX_SEQUENCES, MAX_ELEMENTS; MAX_SEQUENCES := 8; MAX_ELEMENTS := 15; begin % calculate and show the sequences % % array to hold the Padovan Sequences % integer array R ( 2 :: MAX_SEQUENCES, 1 :: MAX_ELEMENTS ); % construct the sequences % PadovanSequences( R, MAX_SEQUENCES, MAX_ELEMENTS ); % show the sequences % write( "Padovan n-step sequences:" ); for n := 2 until MAX_SEQUENCES do begin write( i_w := 1, s_w := 0, n, " |" ); for x := 1 until MAX_ELEMENTS do writeon( i_w := 3, s_w := 0, " ", R( n, x ) ) end for_n end
end.</lang>
- Output:
Padovan n-step sequences: 2 | 1 1 1 2 2 3 4 5 7 9 12 16 21 28 37 3 | 1 1 1 2 3 4 6 9 13 19 28 41 60 88 129 4 | 1 1 1 2 3 5 7 11 17 26 40 61 94 144 221 5 | 1 1 1 2 3 5 8 12 19 30 47 74 116 182 286 6 | 1 1 1 2 3 5 8 13 20 32 51 81 129 205 326 7 | 1 1 1 2 3 5 8 13 21 33 53 85 136 218 349 8 | 1 1 1 2 3 5 8 13 21 34 54 87 140 225 362
AppleScript
<lang applescript>use AppleScript version "2.4" use framework "Foundation" use scripting additions
PADOVAN N-STEP NUMBERS ----------------
-- padovans :: [Int] on padovans(n)
script recurrence on |λ|(xs) {item 1 of xs, ¬ rest of xs & {sum(take(n, xs)) as integer}} end |λ| end script if 3 > n then set seed to |repeat|(1) else set seed to padovans(n - 1) end if if 0 > n then {} else unfoldr(recurrence, take(1 + n, seed)) end if
end padovans
TEST -------------------------
on run
script nSample on |λ|(n) take(15, padovans(n)) end |λ| end script script justified on |λ|(ns) concatMap(justifyRight(4, space), ns) end |λ| end script fTable("Padovan N-step Series:", str, justified, ¬ nSample, enumFromTo(2, 8))
end run
FORMATTING ----------------------
-- fTable :: String -> (a -> String) -> (b -> String) -> -- (a -> b) -> [a] -> String on fTable(s, xShow, fxShow, f, xs)
set ys to map(xShow, xs) set w to maximum(map(my |length|, ys)) script arrowed on |λ|(a, b) |λ|(a) of justifyRight(w, space) & " ->" & b end |λ| end script s & linefeed & unlines(zipWith(arrowed, ¬ ys, map(compose(fxShow, f), xs)))
end fTable
GENERIC ------------------------
-- compose (<<<) :: (b -> c) -> (a -> b) -> a -> c on compose(f, g)
script property mf : mReturn(f) property mg : mReturn(g) on |λ|(x) mf's |λ|(mg's |λ|(x)) end |λ| end script
end compose
-- concatMap :: (a -> [b]) -> [a] -> [b]
on concatMap(f, xs)
set lng to length of xs set acc to {} tell mReturn(f) repeat with i from 1 to lng set acc to acc & (|λ|(item i of xs, i, xs)) end repeat end tell if {text, string} contains class of xs then acc as text else acc end if
end concatMap
-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m, n)
if m ≤ n then set lst to {} repeat with i from m to n set end of lst to i end repeat lst else {} end if
end enumFromTo
-- intercalate :: String -> [String] -> String
on intercalate(delim, xs)
set {dlm, my text item delimiters} to ¬ {my text item delimiters, delim} set s to xs as text set my text item delimiters to dlm s
end intercalate
-- justifyRight :: Int -> Char -> String -> String
on justifyRight(n, cFiller)
script on |λ|(v) set strText to v as text if n > length of strText then text -n thru -1 of ¬ ((replicate(n, cFiller) as text) & strText) else strText end if end |λ| end script
end justifyRight
-- length :: [a] -> Int
on |length|(xs)
set c to class of xs if list is c or string is c then length of xs else (2 ^ 29 - 1) -- (maxInt - simple proxy for non-finite) end if
end |length|
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
-- The list obtained by applying f -- to each element of xs. tell mReturn(f) set lng to length of xs set lst to {} repeat with i from 1 to lng set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell
end map
-- maximum :: Ord a => [a] -> a
on maximum(xs)
set ca to current application unwrap((ca's NSArray's arrayWithArray:xs)'s ¬ valueForKeyPath:"@max.self")
end maximum
-- min :: Ord a => a -> a -> a
on min(x, y)
if y < x then y else x end if
end min
-- mReturn :: First-class m => (a -> b) -> m (a -> b)
on mReturn(f)
-- 2nd class handler function lifted -- into 1st class script wrapper. if script is class of f then f else script property |λ| : f end script end if
end mReturn
-- repeat :: a -> Generator [a]
on |repeat|(x)
script on |λ|() return x end |λ| end script
end |repeat|
-- Egyptian multiplication - progressively doubling a list, appending
-- stages of doubling to an accumulator where needed for binary
-- assembly of a target length
-- replicate :: Int -> String -> String
on replicate(n, s)
-- Egyptian multiplication - progressively doubling a list, -- appending stages of doubling to an accumulator where needed -- for binary assembly of a target length script p on |λ|({n}) n ≤ 1 end |λ| end script script f on |λ|({n, dbl, out}) if (n mod 2) > 0 then set d to out & dbl else set d to out end if {n div 2, dbl & dbl, d} end |λ| end script set xs to |until|(p, f, {n, s, ""}) item 2 of xs & item 3 of xs
end replicate
-- str :: a -> String
on str(x)
x as string
end str
-- sum :: [Num] -> Num
on sum(xs)
set ca to current application ((ca's NSArray's arrayWithArray:xs)'s ¬ valueForKeyPath:"@sum.self") as real
end sum
-- take :: Int -> [a] -> [a]
-- take :: Int -> String -> String
on take(n, xs)
set c to class of xs if list is c then set lng to length of xs if 0 < n and 0 < lng then items 1 thru min(n, lng) of xs else {} end if else if string is c then if 0 < n then text 1 thru min(n, length of xs) of xs else "" end if else if script is c then set ys to {} repeat with i from 1 to n set v to |λ|() of xs if missing value is v then return ys else set end of ys to v end if end repeat return ys else missing value end if
end take
-- unfoldr :: (b -> Maybe (a, b)) -> b -> [a]
on unfoldr(f, v)
-- A lazy (generator) list unfolded from a seed value -- by repeated application of f to a value until no -- residue remains. Dual to fold/reduce. -- f returns either nothing (missing value), -- or just (value, residue). script property valueResidue : {v, v} property g : mReturn(f) on |λ|() set valueResidue to g's |λ|(item 2 of (valueResidue)) if missing value ≠ valueResidue then item 1 of (valueResidue) else missing value end if end |λ| end script
end unfoldr
-- unlines :: [String] -> String
on unlines(xs)
-- A single string formed by the intercalation -- of a list of strings with the newline character. set {dlm, my text item delimiters} to ¬ {my text item delimiters, linefeed} set s to xs as text set my text item delimiters to dlm s
end unlines
-- until :: (a -> Bool) -> (a -> a) -> a -> a
on |until|(p, f, x)
set v to x set mp to mReturn(p) set mf to mReturn(f) repeat until mp's |λ|(v) set v to mf's |λ|(v) end repeat v
end |until|
-- unwrap :: NSValue -> a
on unwrap(nsValue)
if nsValue is missing value then missing value else set ca to current application item 1 of ((ca's NSArray's arrayWithObject:nsValue) as list) end if
end unwrap
-- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
on zipWith(f, xs, ys)
set lng to min(length of xs, length of ys) set lst to {} if 1 > lng then return {} else tell mReturn(f) repeat with i from 1 to lng set end of lst to |λ|(item i of xs, item i of ys) end repeat return lst end tell end if
end zipWith</lang>
- Output:
Padovan N-step Series: 2 -> 1 1 1 2 2 3 4 5 7 9 12 16 21 28 37 3 -> 1 1 1 2 3 4 6 9 13 19 28 41 60 88 129 4 -> 1 1 1 2 3 5 7 11 17 26 40 61 94 144 221 5 -> 1 1 1 2 3 5 8 12 19 30 47 74 116 182 286 6 -> 1 1 1 2 3 5 8 13 20 32 51 81 129 205 326 7 -> 1 1 1 2 3 5 8 13 21 33 53 85 136 218 349 8 -> 1 1 1 2 3 5 8 13 21 34 54 87 140 225 362
C
<lang c>#include <stdio.h>
void padovanN(int n, size_t t, int *p) {
int i, j; if (n < 2 || t < 3) { for (i = 0; i < t; ++i) p[i] = 1; return; } padovanN(n-1, t, p); for (i = n + 1; i < t; ++i) { p[i] = 0; for (j = i - 2; j >= i - n - 1; --j) p[i] += p[j]; }
}
int main() {
int n, i; const size_t t = 15; int p[t]; printf("First %ld terms of the Padovan n-step number sequences:\n", t); for (n = 2; n <= 8; ++n) { for (i = 0; i < t; ++i) p[i] = 0; padovanN(n, t, p); printf("%d: ", n); for (i = 0; i < t; ++i) printf("%3d ", p[i]); printf("\n"); } return 0;
}</lang>
- Output:
First 15 terms of the Padovan n-step number sequences: 2: 1 1 1 2 2 3 4 5 7 9 12 16 21 28 37 3: 1 1 1 2 3 4 6 9 13 19 28 41 60 88 129 4: 1 1 1 2 3 5 7 11 17 26 40 61 94 144 221 5: 1 1 1 2 3 5 8 12 19 30 47 74 116 182 286 6: 1 1 1 2 3 5 8 13 20 32 51 81 129 205 326 7: 1 1 1 2 3 5 8 13 21 33 53 85 136 218 349 8: 1 1 1 2 3 5 8 13 21 34 54 87 140 225 362
F#
<lang fsharp> // Padovan n-step number sequences. Nigel Galloway: July 28th., 2021 let rec pad=function 2->Seq.unfold(fun(n:int[])->Some(n.[0],Array.append n.[1..2] [|Array.sum n.[0..1]|]))[|1;1;1|]
|g->Seq.unfold(fun(n:int[])->Some(n.[0],Array.append n.[1..g] [|Array.sum n.[0..g-1]|]))(Array.ofSeq(pad(g-1)|>Seq.take(g+1)))
[2..8]|>List.iter(fun n->pad n|>Seq.take 15|>Seq.iter(printf "%d "); printfn "") </lang>
- Output:
1 1 1 2 2 3 4 5 7 9 12 16 21 28 37 1 1 1 2 3 4 6 9 13 19 28 41 60 88 129 1 1 1 2 3 5 7 11 17 26 40 61 94 144 221 1 1 1 2 3 5 8 12 19 30 47 74 116 182 286 1 1 1 2 3 5 8 13 20 32 51 81 129 205 326 1 1 1 2 3 5 8 13 21 33 53 85 136 218 349 1 1 1 2 3 5 8 13 21 34 54 87 140 225 362
Factor
<lang factor>USING: compiler.tree.propagation.call-effect io kernel math math.ranges prettyprint sequences ;
- padn ( m n -- seq )
V{ "|" 1 1 1 } over prefix clone over 2 - [ dup last2 + suffix! ] times rot pick 1 + - [ dup length 1 - pick [ - ] keepd pick <slice> sum suffix! ] times nip ;
"Padovan n-step sequences" print 2 8 [a..b] [ 15 swap padn ] map simple-table.</lang>
- Output:
Padovan n-step sequences 2 | 1 1 1 2 2 3 4 5 7 9 12 16 21 28 37 3 | 1 1 1 2 3 4 6 9 13 19 28 41 60 88 129 4 | 1 1 1 2 3 5 7 11 17 26 40 61 94 144 221 5 | 1 1 1 2 3 5 8 12 19 30 47 74 116 182 286 6 | 1 1 1 2 3 5 8 13 20 32 51 81 129 205 326 7 | 1 1 1 2 3 5 8 13 21 33 53 85 136 218 349 8 | 1 1 1 2 3 5 8 13 21 34 54 87 140 225 362
Go
<lang go>package main
import "fmt"
func padovanN(n, t int) []int {
if n < 2 || t < 3 { ones := make([]int, t) for i := 0; i < t; i++ { ones[i] = 1 } return ones } p := padovanN(n-1, t) for i := n + 1; i < t; i++ { p[i] = 0 for j := i - 2; j >= i-n-1; j-- { p[i] += p[j] } } return p
}
func main() {
t := 15 fmt.Println("First", t, "terms of the Padovan n-step number sequences:") for n := 2; n <= 8; n++ { fmt.Printf("%d: %3d\n", n, padovanN(n, t)) }
}</lang>
- Output:
First 15 terms of the Padovan n-step number sequences: 2: [ 1 1 1 2 2 3 4 5 7 9 12 16 21 28 37] 3: [ 1 1 1 2 3 4 6 9 13 19 28 41 60 88 129] 4: [ 1 1 1 2 3 5 7 11 17 26 40 61 94 144 221] 5: [ 1 1 1 2 3 5 8 12 19 30 47 74 116 182 286] 6: [ 1 1 1 2 3 5 8 13 20 32 51 81 129 205 326] 7: [ 1 1 1 2 3 5 8 13 21 33 53 85 136 218 349] 8: [ 1 1 1 2 3 5 8 13 21 34 54 87 140 225 362]
Haskell
<lang haskell>import Data.Bifunctor (second) import Data.List (transpose, uncons, unfoldr)
PADOVAN N-STEP SERIES -----------------
padovans :: Int -> [Int] padovans n
| 0 > n = [] | otherwise = unfoldr (recurrence n) $ take (succ n) xs where xs | 3 > n = repeat 1 | otherwise = padovans $ pred n
recurrence :: Int -> [Int] -> Maybe (Int, [Int]) recurrence n =
( fmap . second . flip (<>) . pure . sum . take n ) <*> uncons
TEST -------------------------
main :: IO () main =
putStrLn $ "Padovan N-step series:\n\n" <> spacedTable justifyRight ( fmap ( \n -> [show n <> " -> "] <> fmap show (take 15 $ padovans n) ) [2 .. 8] )
FORMATTING ----------------------
spacedTable ::
(Int -> Char -> String -> String) -> String -> String
spacedTable aligned rows =
unlines $ fmap (unwords . zipWith (`aligned` ' ') columnWidths) rows where columnWidths = fmap (maximum . fmap length) (transpose rows)
justifyRight :: Int -> a -> [a] -> [a] justifyRight n c = drop . length <*> (replicate n c <>)</lang>
- Output:
Padovan N-step series: 2 -> 1 1 1 2 2 3 4 5 7 9 12 16 21 28 37 3 -> 1 1 1 2 3 4 6 9 13 19 28 41 60 88 129 4 -> 1 1 1 2 3 5 7 11 17 26 40 61 94 144 221 5 -> 1 1 1 2 3 5 8 12 19 30 47 74 116 182 286 6 -> 1 1 1 2 3 5 8 13 20 32 51 81 129 205 326 7 -> 1 1 1 2 3 5 8 13 21 33 53 85 136 218 349 8 -> 1 1 1 2 3 5 8 13 21 34 54 87 140 225 362
JavaScript
<lang javascript>(() => {
"use strict";
// ---------- PADOVAN N-STEP NUMBER SERIES -----------
// padovans :: Int -> [Int] const padovans = n => { // Padovan number series of step N const recurrence = ns => [ ns[0], ns.slice(1).concat( sum(take(n)(ns)) ) ];
return 0 > n ? ( [] ) : unfoldr(recurrence)( take(1 + n)( 3 > n ? ( repeat(1) ) : padovans(n - 1) ) ); };
// ---------------------- TEST ----------------------- // main :: IO () const main = () => fTable("Padovan N-step series:")(str)( xs => xs.map( compose(justifyRight(4)(" "), str) ) .join("") )( compose(take(15), padovans) )( enumFromTo(2)(8) );
// --------------------- GENERIC ---------------------
// compose (<<<) :: (b -> c) -> (a -> b) -> a -> c const compose = (...fs) => // A function defined by the right-to-left // composition of all the functions in fs. fs.reduce( (f, g) => x => f(g(x)), x => x );
// enumFromTo :: Int -> Int -> [Int] const enumFromTo = m => n => Array.from({ length: 1 + n - m }, (_, i) => m + i);
// repeat :: a -> Generator [a] const repeat = function* (x) { while (true) { yield x; } };
// sum :: [Num] -> Num const sum = xs => // The numeric sum of all values in xs. xs.reduce((a, x) => a + x, 0);
// take :: Int -> [a] -> [a] // take :: Int -> String -> String const take = n => // The first n elements of a list, // string of characters, or stream. xs => "GeneratorFunction" !== xs .constructor.constructor.name ? ( xs.slice(0, n) ) : [].concat(...Array.from({ length: n }, () => { const x = xs.next();
return x.done ? [] : [x.value]; }));
// unfoldr :: (b -> Maybe (a, b)) -> b -> Gen [a] const unfoldr = f => // A lazy (generator) list unfolded from a seed value // by repeated application of f to a value until no // residue remains. Dual to fold/reduce. // f returns either Nothing or Just (value, residue). // For a strict output list, // wrap with `list` or Array.from x => ( function* () { let valueResidue = f(x);
while (null !== valueResidue) { yield valueResidue[0]; valueResidue = f(valueResidue[1]); } }() );
// ------------------- FORMATTING --------------------
// fTable :: String -> (a -> String) -> // (b -> String) -> (a -> b) -> [a] -> String const fTable = s => // Heading -> x display function -> // fx display function -> // f -> values -> tabular string xShow => fxShow => f => xs => { const ys = xs.map(xShow), w = Math.max(...ys.map(y => [...y].length)), table = zipWith( a => b => `${a.padStart(w, " ")} ->${b}` )(ys)( xs.map(x => fxShow(f(x))) ).join("\n");
return `${s}\n${table}`; };
// justifyRight :: Int -> Char -> String -> String const justifyRight = n => // The string s, preceded by enough padding (with // the character c) to reach the string length n. c => s => n > s.length ? ( s.padStart(n, c) ) : s;
// str :: a -> String const str = x => `${x}`;
// zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] const zipWith = f => // A list constructed by zipping with a // custom function, rather than with the // default tuple constructor. xs => ys => take( Math.min(xs.length, ys.length) )( xs.map((x, i) => f(x)(ys[i])) );
// MAIN --- return main();
})();</lang>
- Output:
Padovan N-step series: 2 -> 1 1 1 2 2 3 4 5 7 9 12 16 21 28 37 3 -> 1 1 1 2 3 4 6 9 13 19 28 41 60 88 129 4 -> 1 1 1 2 3 5 7 11 17 26 40 61 94 144 221 5 -> 1 1 1 2 3 5 8 12 19 30 47 74 116 182 286 6 -> 1 1 1 2 3 5 8 13 20 32 51 81 129 205 326 7 -> 1 1 1 2 3 5 8 13 21 33 53 85 136 218 349 8 -> 1 1 1 2 3 5 8 13 21 34 54 87 140 225 362
Julia
<lang julia> """
First nterms terms of the first 2..max_nstep -step Padovan sequences.
""" function nstep_Padovan(max_nstep=8, nterms=15)
start = [[], [1, 1, 1]] # for n=0 and n=1 (hidden). for n in 2:max_nstep this = start[n][1:n+1] # Initialise from last while length(this) < nterms push!(this, sum(this[end - i] for i in 1:n)) end push!(start, this) end return start[3:end]
end
function print_Padovan_seq(p)
println(strip("""
-
"""))
for (n, seq) in enumerate(p)
println("| $n || $(replace(string(seq[2:end]), r"[ a-zA-Z\[\]]+" => "")), ...\n|-")
end
println("|}")
end
print_Padovan_seq(nstep_Padovan())
</lang>
- Output:
Padovan -step sequences Values Padovan -step sequences Values 1 1,1,2,2,3,4,5,7,9,12,16,21,28,37, ... 2 1,1,2,3,4,6,9,13,19,28,41,60,88,129, ... 3 1,1,2,3,5,7,11,17,26,40,61,94,144,221, ... 4 1,1,2,3,5,8,12,19,30,47,74,116,182,286, ... 5 1,1,2,3,5,8,13,20,32,51,81,129,205,326, ... 6 1,1,2,3,5,8,13,21,33,53,85,136,218,349, ... 7 1,1,2,3,5,8,13,21,34,54,87,140,225,362, ...
-
"""))
for (n, seq) in enumerate(p)
println("| $n || $(replace(string(seq[2:end]), r"[ a-zA-Z\[\]]+" => "")), ...\n|-")
end
println("|}")
end
print_Padovan_seq(nstep_Padovan())
</lang>
Mathematica /Wolfram Language
<lang Mathematica>ClearAll[Padovan] Padovan[2,tmax_]:=Module[{start,a,m},
start={1,1,1}; start=MapIndexed[a[#21]==#1&,start]; RecurrenceTable[{a[m]==a[m-2]+a[m-3]}~Join~start,a, {m,tmax}]
] Padovan[n_,tmax_]:=Module[{start,eq,a,m},
start=Padovan[n-1,n+1]; start=MapIndexed[a[#21]==#1&,start]; eq=Range[2,n+1]; eq=Append[start,a[m]==Total[a[m-#]&/@eq]]; RecurrenceTable[eq,a, {m,tmax}]
] Padovan[2,15] Padovan[3,15] Padovan[4,15] Padovan[5,15] Padovan[6,15] Padovan[7,15] Padovan[8,15]</lang>
- Output:
{1,1,1,2,2,3,4,5,7,9,12,16,21,28,37} {1,1,1,2,3,4,6,9,13,19,28,41,60,88,129} {1,1,1,2,3,5,7,11,17,26,40,61,94,144,221} {1,1,1,2,3,5,8,12,19,30,47,74,116,182,286} {1,1,1,2,3,5,8,13,20,32,51,81,129,205,326} {1,1,1,2,3,5,8,13,21,33,53,85,136,218,349} {1,1,1,2,3,5,8,13,21,34,54,87,140,225,362}
Nim
<lang Nim>import math, sequtils, strutils
proc rn(n, k: Positive): seq[int] =
assert k >= 2 result = if n == 2: @[1, 1, 1] else: rn(n - 1, n + 1) while result.len != k: result.add sum(result[^(n + 1)..^2])
for n in 2..8:
echo n, ": ", rn(n, 15).mapIt(($it).align(3)).join(" ")</lang>
- Output:
2: 1 1 1 2 2 3 4 5 7 9 12 16 21 28 37 3: 1 1 1 2 3 4 6 9 13 19 28 41 60 88 129 4: 1 1 1 2 3 5 7 11 17 26 40 61 94 144 221 5: 1 1 1 2 3 5 8 12 19 30 47 74 116 182 286 6: 1 1 1 2 3 5 8 13 20 32 51 81 129 205 326 7: 1 1 1 2 3 5 8 13 21 33 53 85 136 218 349 8: 1 1 1 2 3 5 8 13 21 34 54 87 140 225 362
Perl
<lang perl>use strict; use warnings; use feature <state say>; use List::Util 'sum'; use List::Lazy 'lazy_list';
say 'Padovan N-step sequences; first 25 terms:'; for our $N (2..8) {
my $pad_n = lazy_list { state $n = 2; state @pn = (1, 1, 1); push @pn, sum @pn[ grep { $_ >= 0 } $n-$N .. $n++ - 1 ]; $pn[-4] };
print "N = $N |"; print ' ' . $pad_n->next() for 1..25; print "\n"
}</lang>
- Output:
N = 2 | 1 1 1 2 2 3 4 5 7 9 12 16 21 28 37 49 65 86 114 151 200 265 351 465 616 N = 3 | 1 1 1 2 3 4 6 9 13 19 28 41 60 88 129 189 277 406 595 872 1278 1873 2745 4023 5896 N = 4 | 1 1 1 2 3 5 7 11 17 26 40 61 94 144 221 339 520 798 1224 1878 2881 4420 6781 10403 15960 N = 5 | 1 1 1 2 3 5 8 12 19 30 47 74 116 182 286 449 705 1107 1738 2729 4285 6728 10564 16587 26044 N = 6 | 1 1 1 2 3 5 8 13 20 32 51 81 129 205 326 518 824 1310 2083 3312 5266 8373 13313 21168 33657 N = 7 | 1 1 1 2 3 5 8 13 21 33 53 85 136 218 349 559 895 1433 2295 3675 5885 9424 15091 24166 38698 N = 8 | 1 1 1 2 3 5 8 13 21 34 54 87 140 225 362 582 936 1505 2420 3891 6257 10061 16178 26014 41830
Phix
function padovann(integer n,t) if n<2 or t<3 then return repeat(1,t) end if sequence p = padovann(n-1, t) for i=n+2 to t do p[i] = sum(p[i-n-1..i-2]) end for return p end function constant t = 15, fmt = "%d: %d %d %d %d %d %d %d %2d %2d %2d %2d %2d %3d %3d %3d\n" printf(1,"First %d terms of the Padovan n-step number sequences:\n",t) for n=2 to 8 do printf(1,fmt,n&padovann(n,t)) end for
- Output:
First 15 terms of the Padovan n-step number sequences: 2: 1 1 1 2 2 3 4 5 7 9 12 16 21 28 37 3: 1 1 1 2 3 4 6 9 13 19 28 41 60 88 129 4: 1 1 1 2 3 5 7 11 17 26 40 61 94 144 221 5: 1 1 1 2 3 5 8 12 19 30 47 74 116 182 286 6: 1 1 1 2 3 5 8 13 20 32 51 81 129 205 326 7: 1 1 1 2 3 5 8 13 21 33 53 85 136 218 349 8: 1 1 1 2 3 5 8 13 21 34 54 87 140 225 362
Python
Python: Procedural
Generates a wikitable formatted output <lang python>def pad_like(max_n=8, t=15):
""" First t terms of the first 2..max_n-step Padovan sequences. """ start = [[], [1, 1, 1]] # for n=0 and n=1 (hidden). for n in range(2, max_n+1): this = start[n-1][:n+1] # Initialise from last while len(this) < t: this.append(sum(this[i] for i in range(-2, -n - 2, -1))) start.append(this) return start[2:]
def pr(p):
print(
- .strip())
for n, seq in enumerate(p, 2):
print(f"| {n:2} || {str(seq)[1:-1].replace(' ', )+', ...'}\n|-")
print('|}')
if __name__ == '__main__':
p = pad_like()
pr(p)</lang>
- Output:
Padovan -step sequences Values Padovan -step sequences Values 2 1,1,1,2,2,3,4,5,7,9,12,16,21,28,37, ... 3 1,1,1,2,3,4,6,9,13,19,28,41,60,88,129, ... 4 1,1,1,2,3,5,7,11,17,26,40,61,94,144,221, ... 5 1,1,1,2,3,5,8,12,19,30,47,74,116,182,286, ... 6 1,1,1,2,3,5,8,13,20,32,51,81,129,205,326, ... 7 1,1,1,2,3,5,8,13,21,33,53,85,136,218,349, ... 8 1,1,1,2,3,5,8,13,21,34,54,87,140,225,362, ...
- .strip())
for n, seq in enumerate(p, 2):
print(f"| {n:2} || {str(seq)[1:-1].replace(' ', )+', ...'}\n|-")
print('|}')
if __name__ == '__main__':
p = pad_like()
pr(p)</lang>
Python: Functional
Defined in terms of a generic anamorphism, using the unfold abstraction, which is dual to reduce.
Aims for a legible expression of the Padovan recurrence relation, and a good level of reliability and code reuse, as well as rapid drafting and refactoring.
Functional composition, while widely practiced and written about in the context of Python, is not the dominant Python tradition. The documentation of the Python itertools module does, however, acknowledge its debt to languages like ML and Haskell, both for an algebra of composition, and for a source of function-naming traditions.
This draft is thoroughly linted, for a high degree of compliance with Python language standards and layout.
Patterns of functional composition are constrained more by mathematical necessity than by arbitrary convention, but this still leaves room for alternative idioms of functional coding in Python. It is to be hoped that others will contribute divergent examples, enriching the opportunities for contrastive insight which Rosetta code aims to provide.
<lang python>Padovan n-step number sequences
from itertools import chain, islice, repeat
- nStepPadovan :: Int -> [Int]
def nStepPadovan(n):
Non-finite series of N-step Padovan numbers, defined by a recurrence relation. return unfoldr(recurrence(n))( take(1 + n)( repeat(1) if 3 > n else ( nStepPadovan(n - 1) ) ) )
- recurrence :: Int -> [Int] -> Int
def recurrence(n):
Recurrence relation in Fibonacci, Padovan and Perrin sequences. def go(xs): h, *t = xs return h, t + [sum(take(n)(xs))] return go
- ------------------------- TEST -------------------------
- main :: IO ()
def main():
First 15 terms each nStepPadovan(n) series where n is drawn from [2..8] xs = range(2, 1 + 8) print('Padovan n-step series:\n') print( spacedTable(list(map( lambda k, n: list(chain( [k + ' -> '], ( str(x) for x in take(15)(nStepPadovan(n)) ) )), (str(x) for x in xs), xs ))) )
- ----------------------- GENERIC ------------------------
- take :: Int -> [a] -> [a]
- take :: Int -> String -> String
def take(n):
The prefix of xs of length n, or xs itself if n > length xs. def go(xs): return ( xs[0:n] if isinstance(xs, (list, tuple)) else list(islice(xs, n)) ) return go
- unfoldr :: (b -> Maybe (a, b)) -> b -> [a]
def unfoldr(f):
Generic anamorphism. A lazy (generator) list unfolded from a seed value by repeated application of f until no residue remains. Dual to fold/reduce. f returns either None, or just (value, residue). For a strict output value, wrap in list(). def go(x): valueResidue = f(x) while None is not valueResidue: yield valueResidue[0] valueResidue = f(valueResidue[1]) return go
- ---------------------- FORMATTING ----------------------
- spacedTable :: String -> String
def spacedTable(rows):
A table with right-aligned columns. columnWidths = [ max([len(x) for x in col]) for col in zip(*rows) ] return '\n'.join( ' '.join(map( lambda x, w: x.rjust(w, ' '), row, columnWidths )) for row in rows )
- MAIN ---
if __name__ == '__main__':
main()
</lang>
- Output:
Padovan n-step series: 2 -> 1 1 1 2 2 3 4 5 7 9 12 16 21 28 37 3 -> 1 1 1 2 3 4 6 9 13 19 28 41 60 88 129 4 -> 1 1 1 2 3 5 7 11 17 26 40 61 94 144 221 5 -> 1 1 1 2 3 5 8 12 19 30 47 74 116 182 286 6 -> 1 1 1 2 3 5 8 13 20 32 51 81 129 205 326 7 -> 1 1 1 2 3 5 8 13 21 33 53 85 136 218 349 8 -> 1 1 1 2 3 5 8 13 21 34 54 87 140 225 362
Raku
<lang perl6>say 'Padovan N-step sequences; first 25 terms:';
for 2..8 -> \N {
my @n-step = 1, 1, 1, { state $n = 2; @n-step[ ($n - N .. $n++ - 1).grep: * >= 0 ].sum } … *; put "N = {N} |" ~ @n-step[^25]».fmt: "%5d";
}</lang>
- Output:
Padovan N-step sequences; first 25 terms: N = 2 | 1 1 1 2 2 3 4 5 7 9 12 16 21 28 37 49 65 86 114 151 200 265 351 465 616 N = 3 | 1 1 1 2 3 4 6 9 13 19 28 41 60 88 129 189 277 406 595 872 1278 1873 2745 4023 5896 N = 4 | 1 1 1 2 3 5 7 11 17 26 40 61 94 144 221 339 520 798 1224 1878 2881 4420 6781 10403 15960 N = 5 | 1 1 1 2 3 5 8 12 19 30 47 74 116 182 286 449 705 1107 1738 2729 4285 6728 10564 16587 26044 N = 6 | 1 1 1 2 3 5 8 13 20 32 51 81 129 205 326 518 824 1310 2083 3312 5266 8373 13313 21168 33657 N = 7 | 1 1 1 2 3 5 8 13 21 33 53 85 136 218 349 559 895 1433 2295 3675 5885 9424 15091 24166 38698 N = 8 | 1 1 1 2 3 5 8 13 21 34 54 87 140 225 362 582 936 1505 2420 3891 6257 10061 16178 26014 41830
REXX
Some additional code was added for this REXX version to minimize the width for any particular column. <lang rexx>/*REXX program computes and shows the Padovan sequences for M steps for N numbers. */ parse arg n m . /*obtain optional arguments from the CL*/ if n== | n=="," then n= 15 /*Not specified? Then use the default.*/ if m== | m=="," then m= 8 /* " " " " " " */ w.= 1 /*W.c: the maximum width of a column. */
do #=2 for m-1 @.= 0; @.0= 1; @.1= 1; @.2= 1 /*initialize 3 terms of the Padovan seq*/ $= @.0 /*initials the list with the zeroth #. */ do k=2 for n-1; z= pd(k-1) w.k= max(w.k, length(z)); $= $ z /*find maximum width for a specific col*/ end /*k*/ $.#= $ /*save each unaligned line for later. */ end /*#*/
oW= 1
do col=1 for n; oW= oW + w.col + 1 /*add up the width of each column. */ end /*col*/ iW= length(m) + 2; pad= left(, 20*(n<21)) /*maybe indent.*/
say pad center('M', iW, " ")"│"center('first ' n " Padovan sequence with step M", oW) say pad center(, iW, "─")"┼"center(, oW, "─")
do out=2 for m-1; $= /*align columnar elements for outputs. */ do j=1 for n; $= $ right(word($.out, j), w.j) /*align the columns. */ end /*j*/ say pad center(out,length(m)+2)'│'$ /*display a line of columnar elements. */ end /*out*/
say pad center(, length(m)+2, "─")"┴"center(, oW, "─") exit 0 /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ pd: procedure expose @. #; parse arg x; if @.x\==0 then return @.x /*@.x defined?*/
do k=1 for #; _= x-1-k; @.x= @.x + @._; end; return @.x</lang>
- output when using the default inputs:
M │ first 15 Padovan sequence with step M ───┼────────────────────────────────────────── 2 │ 1 1 1 2 2 3 4 5 7 9 12 16 21 28 37 3 │ 1 1 1 2 3 4 6 9 13 19 28 41 60 88 129 4 │ 1 1 1 2 3 5 7 11 17 26 40 61 94 144 221 5 │ 1 1 1 2 3 5 8 12 19 30 47 74 116 182 286 6 │ 1 1 1 2 3 5 8 13 20 32 51 81 129 205 326 7 │ 1 1 1 2 3 5 8 13 21 33 53 85 136 218 349 8 │ 1 1 1 2 3 5 8 13 21 34 54 87 140 225 362 ───┴──────────────────────────────────────────
Rust
<lang rust> fn padovan(n: u64, x: u64) -> u64 {
if n < 2 { return 0; }
match n { 2 if x <= n + 1 => 1, 2 => padovan(n, x - 2) + padovan(n, x - 3), _ if x <= n + 1 => padovan(n - 1, x), _ => ((x - n - 1)..(x - 1)).fold(0, |acc, value| acc + padovan(n, value)), }
} fn main() {
(2..=8).for_each(|n| { print!("\nN={}: ", n); (1..=15).for_each(|x| print!("{},", padovan(n, x))) });
}
</lang>
- Output:
N=2: 1,1,1,2,2,3,4,5,7,9,12,16,21,28,37, N=3: 1,1,1,2,3,4,6,9,13,19,28,41,60,88,129, N=4: 1,1,1,2,3,5,7,11,17,26,40,61,94,144,221, N=5: 1,1,1,2,3,5,8,12,19,30,47,74,116,182,286, N=6: 1,1,1,2,3,5,8,13,20,32,51,81,129,205,326, N=7: 1,1,1,2,3,5,8,13,21,33,53,85,136,218,349, N=8: 1,1,1,2,3,5,8,13,21,34,54,87,140,225,362,
Sidef
<lang ruby>func padovan(N) {
Enumerator({|callback| var n = 2 var pn = [1, 1, 1] loop { pn << sum(pn[n-N .. (n++-1) -> grep { _ >= 0 }]) callback(pn[-4]) } })
}
for n in (2..8) {
say "n = #{n} | #{padovan(n).first(25).join(' ')}"
}</lang>
- Output:
n = 2 | 1 1 1 2 2 3 4 5 7 9 12 16 21 28 37 49 65 86 114 151 200 265 351 465 616 n = 3 | 1 1 1 2 3 4 6 9 13 19 28 41 60 88 129 189 277 406 595 872 1278 1873 2745 4023 5896 n = 4 | 1 1 1 2 3 5 7 11 17 26 40 61 94 144 221 339 520 798 1224 1878 2881 4420 6781 10403 15960 n = 5 | 1 1 1 2 3 5 8 12 19 30 47 74 116 182 286 449 705 1107 1738 2729 4285 6728 10564 16587 26044 n = 6 | 1 1 1 2 3 5 8 13 20 32 51 81 129 205 326 518 824 1310 2083 3312 5266 8373 13313 21168 33657 n = 7 | 1 1 1 2 3 5 8 13 21 33 53 85 136 218 349 559 895 1433 2295 3675 5885 9424 15091 24166 38698 n = 8 | 1 1 1 2 3 5 8 13 21 34 54 87 140 225 362 582 936 1505 2420 3891 6257 10061 16178 26014 41830
Wren
<lang ecmascript>import "/fmt" for Fmt
var padovanN // recursive padovanN = Fn.new { |n, t|
if (n < 2 || t < 3) return [1] * t var p = padovanN.call(n-1, t) if (n + 1 >= t) return p for (i in n+1...t) { p[i] = 0 for (j in i-2..i-n-1) p[i] = p[i] + p[j] } return p
}
var t = 15 System.print("First %(t) terms of the Padovan n-step number sequences:") for (n in 2..8) Fmt.print("$d: $3d" , n, padovanN.call(n, t))</lang>
- Output:
First 15 terms of the Padovan n-step number sequences: 2: 1 1 1 2 2 3 4 5 7 9 12 16 21 28 37 3: 1 1 1 2 3 4 6 9 13 19 28 41 60 88 129 4: 1 1 1 2 3 5 7 11 17 26 40 61 94 144 221 5: 1 1 1 2 3 5 8 12 19 30 47 74 116 182 286 6: 1 1 1 2 3 5 8 13 20 32 51 81 129 205 326 7: 1 1 1 2 3 5 8 13 21 33 53 85 136 218 349 8: 1 1 1 2 3 5 8 13 21 34 54 87 140 225 362