Padovan sequence: Difference between revisions

Added FreeBASIC
(Added FreeBASIC)
(28 intermediate revisions by 15 users not shown)
Line 49:
| L-System Start/Axiom. || A || A
|-
| L-System Rules. || A->B,B->C,C->AB || A->B,B->AAB
|}
 
Line 66:
* [https://www.youtube.com/watch?v=PsGUEj4w9Cc The Plastic Ratio] - Numberphile video.
 
 
=={{header|11l}}==
{{trans|Nim}}
 
<syntaxhighlight lang="11l">V pp = 1.324717957244746025960908854
V ss = 1.0453567932525329623
V Rules = [‘A’ = ‘B’, ‘B’ = ‘C’, ‘C’ = ‘AB’]
 
F padovan1(n)
V r = [1] * min(n, 3)
V (a, b, c) = (1, 1, 1)
V count = 3
L count < n
(a, b, c) = (b, c, a + b)
r [+]= c
count++
R r
 
F padovan2(n)
V r = [1] * (n > 1)
V p = 1.0
V count = 1
L count < n
r [+]= Int(round(p / :ss))
p *= :pp
count++
R r
 
F padovan3(n)
[String] r
V s = ‘A’
V count = 0
L count < n
r [+]= s
V next = ‘’
L(ch) s
next ‘’= Rules[ch]
s = next
count++
R r
 
print(‘First 20 terms of the Padovan sequence:’)
print(padovan1(20).join(‘ ’))
 
V list1 = padovan1(64)
V list2 = padovan2(64)
print(‘The first 64 iterative and calculated values ’(I list1 == list2 {‘are the same.’} E ‘differ.’))
 
print()
print(‘First 10 L-system strings:’)
print(padovan3(10).join(‘ ’))
print()
print(‘Lengths of the 32 first L-system strings:’)
V list3 = padovan3(32).map(x -> x.len)
print(list3.join(‘ ’))
print(‘These lengths are’(I list3 == list1[0.<32] {‘ ’} E ‘ not ’)‘the 32 first terms of the Padovan sequence.’)</syntaxhighlight>
 
{{out}}
<pre>
First 20 terms of the Padovan sequence:
1 1 1 2 2 3 4 5 7 9 12 16 21 28 37 49 65 86 114 151
The first 64 iterative and calculated values are the same.
 
First 10 L-system strings:
A B C AB BC CAB ABBC BCCAB CABABBC ABBCBCCAB
 
Lengths of the 32 first L-system strings:
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 816 1081 1432 1897 2513 3329 4410
These lengths are the 32 first terms of the Padovan sequence.
</pre>
 
=={{header|ALGOL 68}}==
<langsyntaxhighlight lang="algol68">BEGIN # show members of the Padovan Sequence calculated in various ways #
# returns the first n elements of the Padovan sequence by the #
# recurance relation: P(n)=P(n-2)+P(n-3) #
Line 152 ⟶ 222:
)
END
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 165 ⟶ 235:
 
=={{header|AppleScript}}==
<langsyntaxhighlight lang="applescript">--------------------- PADOVAN NUMBERS --------------------
 
-- padovans :: [Int]
Line 432 ⟶ 502:
set my text item delimiters to dlm
s
end unlines</langsyntaxhighlight>
{{Out}}
<pre>First 20 padovans:
Line 451 ⟶ 521:
 
=={{header|C}}==
<langsyntaxhighlight Clang="c">#include <stdio.h>
#include <stdlib.h>
#include <math.h>
Line 548 ⟶ 618:
return 0;
}</langsyntaxhighlight>
 
{{out}}
Line 568 ⟶ 638:
 
The floor- and L-system-based functions match from P_0 to P_31.</pre>
 
 
=={{header|C#}}==
{{trans|Java}}
 
<syntaxhighlight lang="C#">using System;
using System.Collections.Generic;
using System.Linq;
 
public static class Padovan
{
private static readonly List<int> recurrences = new List<int>();
private static readonly List<int> floors = new List<int>();
private const double PP = 1.324717957244746025960908854;
private const double SS = 1.0453567932525329623;
 
public static void Main(string[] args)
{
for (int i = 0; i < 64; i++)
{
recurrences.Add(PadovanRecurrence(i));
floors.Add(PadovanFloor(i));
}
 
Console.WriteLine("The first 20 terms of the Padovan sequence:");
recurrences.GetRange(0, 20).ForEach(term => Console.Write(term + " "));
Console.WriteLine(Environment.NewLine);
 
Console.WriteLine("Recurrence and floor functions agree for first 64 terms? " + recurrences.SequenceEqual(floors));
Console.WriteLine(Environment.NewLine);
 
List<string> words = CreateLSystem();
 
Console.WriteLine("The first 10 terms of the L-system:");
words.GetRange(0, 10).ForEach(term => Console.Write(term + " "));
Console.WriteLine(Environment.NewLine);
 
Console.Write("Length of first 32 terms produced from the L-system match Padovan sequence? ");
List<int> wordLengths = words.Select(s => s.Length).ToList();
Console.WriteLine(wordLengths.SequenceEqual(recurrences.GetRange(0, 32)));
}
 
private static int PadovanRecurrence(int n)
{
if (n <= 2)
return 1;
return recurrences[n - 2] + recurrences[n - 3];
}
 
private static int PadovanFloor(int n)
{
return (int)Math.Floor(Math.Pow(PP, n - 1) / SS + 0.5);
}
 
private static List<string> CreateLSystem()
{
List<string> words = new List<string>();
string text = "A";
 
while (words.Count < 32)
{
words.Add(text);
char[] textChars = text.ToCharArray();
text = "";
foreach (char ch in textChars)
{
text += ch switch
{
'A' => "B",
'B' => "C",
'C' => "AB",
_ => throw new InvalidOperationException("Unexpected character found: " + ch),
};
}
}
 
return words;
}
}</syntaxhighlight>
 
{{out}}
<pre>
The first 20 terms of the Padovan sequence:
1 1 1 2 2 3 4 5 7 9 12 16 21 28 37 49 65 86 114 151
 
Recurrence and floor functions agree for first 64 terms? True
 
 
The first 10 terms of the L-system:
A B C AB BC CAB ABBC BCCAB CABABBC ABBCBCCAB
 
Length of first 32 terms produced from the L-system match Padovan sequence? True
</pre>
 
 
 
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <map>
#include <cmath>
Line 651 ⟶ 817:
"floor- and L-system-based", 32);
return 0;
}</langsyntaxhighlight>
 
{{out}}
Line 671 ⟶ 837:
 
The floor- and L-system-based functions match from P_0 to P_32.</pre>
 
=={{header|Clojure}}==
<syntaxhighlight lang="clojure">(def padovan (map first (iterate (fn [[a b c]] [b c (+ a b)]) [1 1 1])))
 
(def pad-floor
(let [p 1.324717957244746025960908854
s 1.0453567932525329623]
(map (fn [n] (int (Math/floor (+ (/ (Math/pow p (dec n)) s) 0.5)))) (range))))
 
(def pad-l
(iterate (fn f [[c & s]]
(case c
\A (str "B" (f s))
\B (str "C" (f s))
\C (str "AB" (f s))
(str "")))
"A"))
 
(defn comp-seq [n seqa seqb]
(= (take n seqa) (take n seqb)))
 
(defn comp-all [n]
(= (map count (vec (take n pad-l)))
(take n padovan)
(take n pad-floor)))
 
(defn padovan-print [& args]
((print "The first 20 items with recursion relation are: ")
(println (take 20 padovan))
(println)
(println (str
"The recurrence and floor based algorithms "
(if (comp-seq 64 padovan pad-floor) "match" "not match")
" to n=64"))
(println)
(println "The first 10 L-system strings are:")
(println (take 10 pad-l))
(println)
(println (str
"The L-system, recurrence and floor based algorithms "
(if (comp-all 32) "match" "not match")
" to n=32"))))</syntaxhighlight>
 
{{out}}
 
<pre>The first 20 items with recursion relation are: (1 1 1 2 2 3 4 5 7 9 12 16 21 28 37 49 65 86 114 151)
 
The recurrence and floor based algorithms match to n=64
 
The first 10 L-system strings are:
(A B C AB BC CAB ABBC BCCAB CABABBC ABBCBCCAB)
 
The L-system, recurrence and floor based algorithms match to n=32</pre>
 
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
{{libheader| Velthuis.BigDecimals}}
{{libheader| Boost.Generics.Collection}}
{{Trans|C++}}
Thanks Rudy Velthuis for the [https://github.com/rvelthuis/DelphiBigNumbers Velthuis.BigDecimals] library.<br>
Boost.Generics.Collection is part of [https://github.com/MaiconSoft/DelphiBoostLib DelphiBoostLib].
<syntaxhighlight lang="delphi">
program Padovan_sequence;
 
{$APPTYPE CONSOLE}
 
uses
System.SysUtils,
Velthuis.BigDecimals,
Boost.Generics.Collection;
 
type
TpFn = TFunc<Integer, Integer>;
 
var
RecMemo: TDictionary<Integer, Integer>;
lSystemMemo: TDictionary<Integer, string>;
 
function pRec(n: Integer): Integer;
begin
if RecMemo.HasKey(n) then
exit(RecMemo[n]);
 
if (n <= 2) then
RecMemo[n] := 1
else
RecMemo[n] := pRec(n - 2) + pRec(n - 3);
Result := RecMemo[n];
end;
 
function pFloor(n: Integer): Integer;
var
p, s, a: BigDecimal;
begin
p := '1.324717957244746025960908854';
s := '1.0453567932525329623';
a := p.IntPower(n - 1, 64);
Result := Round(BigDecimal.Divide(a, s));
end;
 
function lSystem(n: Integer): string;
begin
if n = 0 then
lSystemMemo[n] := 'A'
else
begin
lSystemMemo[n] := '';
for var ch in lSystemMemo[n - 1] do
begin
case ch of
'A':
lSystemMemo[n] := lSystemMemo[n] + 'B';
'B':
lSystemMemo[n] := lSystemMemo[n] + 'C';
'C':
lSystemMemo[n] := lSystemMemo[n] + 'AB';
end;
end;
end;
Result := lSystemMemo[n];
end;
 
procedure Compare(f1, f2: TpFn; descr: string; stop: Integer);
begin
write('The ', descr, ' functions ');
var i := 0;
while i < stop do
begin
var n1 := f1(i);
var n2 := f2(i);
if n1 <> n2 then
begin
write('do not match at ', i);
writeln(': ', n1, ' != ', n2, '.');
break;
end;
inc(i);
end;
if i = stop then
writeln('match from P_0 to P_', stop, '.');
end;
 
begin
RecMemo := TDictionary<Integer, Integer>.Create([], []);
lSystemMemo := TDictionary<Integer, string>.Create([], []);
 
write('P_0 .. P_19: ');
for var i := 0 to 19 do
write(pRec(i), ' ');
writeln;
 
Compare(pFloor, pRec, 'floor- and recurrence-based', 64);
writeln(#10'The first 10 L-system strings are:');
 
for var i := 0 to 9 do
writeln(lSystem(i));
writeln;
 
Compare(pFloor,
function(n: Integer): Integer
begin
Result := length(lSystem(n));
end, 'floor- and L-system-based', 32);
readln;
end.</syntaxhighlight>
 
=={{header|EasyLang}}==
{{trans|Swift}}
<syntaxhighlight>
p[] = [ 1 1 1 ]
padorn = 1
func padorec .
if padorn <= 3
h = p[padorn]
else
h = p[1] + p[2]
.
p[1] = p[2]
p[2] = p[3]
p[3] = h
padorn += 1
return h
.
pfn = 1
P = 1.32471795724474602596
S = 1.0453567932525329623
#
func padofloor .
p = floor ((pow P (pfn - 2)) / S + 0.5)
pfn += 1
return p
.
str$ = "A"
func$ padolsys .
r$ = str$
for c$ in strchars str$
if c$ = "A"
nxt$ &= "B"
elif c$ = "B"
nxt$ &= "C"
else
nxt$ &= "AB"
.
.
str$ = nxt$
return r$
.
#
print "First 20 terms of the Padovan sequence:"
for i to 64
par[] &= padorec
.
for i to 20
write par[i] & " "
.
print ""
for i to 64
paf[] &= padofloor
.
if par[] = paf[]
print "\nRecurrence and floor functions agree for first 64 terms"
.
for i to 32
pal$[] &= padolsys
.
print "\nFirst 10 strings produced from the L-system:"
for i to 10
write pal$[i] & " "
.
print ""
for i to 32
if len pal$[i] <> par[i]
break 1
.
.
if i > 32
print "\nLength of first 32 strings produced from the L-system = Padovan sequence"
.
</syntaxhighlight>
 
{{out}}
<pre>
First 20 terms of the Padovan sequence:
1 1 1 2 2 3 4 5 7 9 12 16 21 28 37 49 65 86 114 151
 
Recurrence and floor functions agree for first 64 terms
 
First 10 strings produced from the L-system:
A B C AB BC CAB ABBC BCCAB CABABBC ABBCBCCAB
 
Length of first 32 strings produced from the L-system = Padovan sequence
</pre>
 
=={{header|Elixir}}==
{{trans|Ruby}}
<syntaxhighlight lang="Elixir"># Padovan sequence as a Stream
defmodule Padovan do
def stream do
Stream.resource(
fn -> {1, 1, 1} end,
fn {a, b, c} ->
next_value = a + b
{[a], {b, c, next_value}}
end,
fn _ -> :ok end
)
end
end
 
# Padovan floor function
defmodule PadovanFloorFunction do
@p 1.324717957244746025960908854
@s 1.0453567932525329623
 
def padovan_f(n), do: trunc((:math.pow(@p, n - 1) / @s) + 0.5)
end
 
# Calculate and print the first 20 elements of the Padovan sequence and the floor function
padovan_sequence = Padovan.stream() |> Enum.take(20)
padovan_floor_function = Enum.map(0..19, &PadovanFloorFunction.padovan_f(&1))
 
IO.puts("Recurrence Padovan: #{inspect(padovan_sequence)}")
IO.puts("Floor function: #{inspect(padovan_floor_function)}")
 
# Check if the sequences are equal up to n
n = 63
bool = Enum.map(0..(n-1), &PadovanFloorFunction.padovan_f(&1)) == Padovan.stream() |> Enum.take(n)
IO.puts("Recurrence and floor function are equal up to #{n}: #{bool}.")
 
# L-system generator as a Stream
defmodule LSystem do
def stream(axiom \\ "A", rules \\ %{"A" => "B", "B" => "C", "C" => "AB"}) do
Stream.iterate(axiom, fn string ->
string
|> String.graphemes()
|> Enum.map(&Map.get(rules, &1, ""))
|> Enum.join()
end)
end
end
 
# Calculate and print the first 10 elements of the L-system
l_system_sequence = LSystem.stream() |> Enum.take(10)
IO.puts("First 10 elements of L-system: #{l_system_sequence |> Enum.join(", ")}")
 
# Check if the sizes of the L-system strings match the Padovan sequence
n = 32
l_system_sizes = LSystem.stream() |> Enum.take(n) |> Enum.map(&String.length/1)
bool = l_system_sizes == Padovan.stream() |> Enum.take(n)
IO.puts("Sizes of first #{n} L_system strings equal to recurrence Padovan? #{bool}.")</syntaxhighlight>
 
{{out}}
<pre>
Recurrence Padovan: [1, 1, 1, 2, 2, 3, 4, 5, 7, 9, 12, 16, 21, 28, 37, 49, 65, 86, 114, 151]
Floor function: [1, 1, 1, 2, 2, 3, 4, 5, 7, 9, 12, 16, 21, 28, 37, 49, 65, 86, 114, 151]
Recurrence and floor function are equal up to 63: true.
First 10 elements of L-system: A, B, C, AB, BC, CAB, ABBC, BCCAB, CABABBC, ABBCBCCAB
Sizes of first 32 L_system strings equal to recurrence Padovan? true.
</pre>
 
=={{header|Factor}}==
{{works with|Factor|0.99 2021-02-05}}
<langsyntaxhighlight lang="factor">USING: L-system accessors io kernel make math math.functions
memoize prettyprint qw sequences ;
 
Line 704 ⟶ 1,190:
 
32 <iota> [ pfloor ] map 32 plsys [ length ] map assert=
"The L-system, recurrence and floor based algorithms match to n=31." print</langsyntaxhighlight>
{{out}}
<pre>
Line 728 ⟶ 1,214:
The L-system, recurrence and floor based algorithms match to n=31.
</pre>
 
=={{header|FreeBASIC}}==
{{trans|11l}}
<syntaxhighlight lang="vbnet">Const As Double pp = 1.324717957244746025960908854
Const As Double ss = 1.0453567932525329623
 
Function padovan1(Byval n As Integer) As Integer
Dim As Integer a, b, c, d, i
a = 1: b = 1: c = 1
d = 1
For i = 1 To (n - 3)
d = a + b
a = b : b = c : c = d
Next i
Return d
End Function
 
Function padovan2(Byval n As Integer) As Integer
Dim As Double p = 1.0
For i As Integer = 1 To (n - 1)
p *= pp
Next i
Return Fix(p / ss)
End Function
 
Function padovan3(Byval n As Integer) As String
Dim As String sgte, s = "A"
Dim As Integer i, j, c
Dim As String rules(1 To 3) = {"B", "C", "AB"}
For i = 1 To n
sgte = ""
For j = 1 To Len(s)
Select Case Mid(s, j, 1)
Case "A" : c = 1
Case "B" : c = 2
Case "C" : c = 3
End Select
sgte &= rules(c)
Next j
s = sgte
Next i
Return s
End Function
 
Dim As Integer n
Print "First 20 terms of the Padovan sequence:"
For n = 1 To 20
Print padovan1(n); '" ";
Next
 
n = 1
Dim As Boolean areEqual = True
Dim As Integer list1(64), list2(64)
 
Do While n <= 64 And areEqual = False
list1(n) = padovan1(n)
list2(n) = padovan2(n)
If list1(n) <> list2(n) Then areEqual = False
n += 1
Loop
Print !"\nThe first 64 iterative and calculated values ";
Print Iif(areEqual, "are the same.", "differ.")
 
Print !"\nFirst 10 L-system strings:"
For n = 0 To 9
Print padovan3(n); " ";
Next
Print
 
areEqual = True
Dim As Integer list3(31)
 
Print !"\nLengths of the 32 first L-system strings:"
For n = 0 To 31
list3(n) = Len(padovan3(n))
Print list3(n); '" ";
If list3(n) <> list1(n) Then areEqual = False
Next
Print !"\nThese lengths are";
Print Iif(areEqual, " the 32 first terms of the Padovan sequence.", " not the 32 first terms of the Padovan sequence.")
 
Sleep</syntaxhighlight>
{{out}}
<pre>First 20 terms of the Padovan sequence:
1 1 1 2 2 3 4 5 7 9 12 16 21 28 37 49 65 86 114 151
The first 64 iterative and calculated values are the same.
 
First 10 L-system strings:
A B C AB BC CAB ABBC BCCAB CABABBC ABBCBCCAB
 
Lengths of the 32 first L-system strings:
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 816 1081 1432 1897 2513 3329 4410
These lengths are not the 32 first terms of the Padovan sequence.</pre>
 
=={{header|Go}}==
{{trans|Wren}}
<langsyntaxhighlight lang="go">package main
 
import (
Line 837 ⟶ 1,417:
}
fmt.Println("\nThe recurrence and L-system based functions", s, "the same results for 32 terms.")
</syntaxhighlight>
</lang>
 
{{out}}
Line 856 ⟶ 1,436:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">-- list of Padovan numbers using recurrence
pRec = map (\(a,_,_) -> a) $ iterate (\(a,b,c) -> (b,c,a+b)) (1,1,1)
 
Line 896 ⟶ 1,476:
putStr $ if checkN 32 pFloor (map length lSystem)
then "match" else "do not match"
putStr " from P_0 to P_31.\n"</langsyntaxhighlight>
 
{{out}}
Line 911 ⟶ 1,491:
 
and a variant expressed in terms of '''unfoldr''', which allows for a coherent treatment of these three cases – isolating the respects in which they differ – and also lends itself to a simple translation to the N-Step Padovan case, covered in another task.
<langsyntaxhighlight lang="haskell">import Data.List (unfoldr)
 
--------------------- PADOVAN NUMBERS --------------------
Line 919 ⟶ 1,499:
where
f (a, b, c) = Just (a, (b, c, a + b))
 
 
padovanFloor :: [Integer]
Line 924 ⟶ 1,505:
where
f = Just . (((,) . g) <*> succ)
 
g = floor . (0.5 +) . (/ s) . (p **) . fromInteger . pred
p = 1.324717957244746025960908854
s = 1.0453567932525329623
 
g = floor . (0.5 +) . (/ s) . (p **) . fromInteger . pred
 
padovanLSystem :: [String]
Line 932 ⟶ 1,515:
where
f = Just . ((,) <*> concatMap rule)
 
rule 'A' = "B"
rule 'B' = "C"
Line 963 ⟶ 1,547:
 
prefixesMatch :: Eq a => [a] -> [a] -> Int -> Bool
prefixesMatch xs ys n = and (zipWith (==) (take n xs) ys)</langsyntaxhighlight>
{{Out}}
<pre>First 20 padovans:
Line 982 ⟶ 1,566:
 
True</pre>
 
=={{header|J}}==
 
Implementation:
<syntaxhighlight lang="j">
padovanSeq=: (],+/@(_2 _3{]))^:([-3:)&1 1 1
 
NB. or, equivalently:
padovanSeq=: (, [: +/ _2 {. }:)@]^:([ - 2:)&1 1
 
realRoot=. {:@(#~ ]=|)@;@p.
padovanNth=: 0.5 <.@+ (realRoot _23 23 _2 1) %~ (realRoot _1 _1 0 1)^<:
 
padovanL=: rplc&('A';'B'; 'B';'C'; 'C';'AB')@]^:[&'A'
seqLen=. #@(-.&' ')"1
</syntaxhighlight>
 
Typically, inductive sequences based on a function F with an initial value G can be expressed using an expression of the form F@]^:[@G or something similar. Here, [ represents the argument to the derived recurrence function. For padovanSeq, we are generating a sequence, so we want to retain the previous values. So instead of just using f=: +/@(_2 3{]) which adds up the second and third numbers from the end of the sequence, we also retain the previous values using F=: ],f
 
But, also, since our initial value is a sequence with three elements, we can make the argument to the recurrence function be the length of the desired sequence by replacing [ for the repetition count with [-3:
 
Task examples:
 
<syntaxhighlight lang="j">
padovanSeq 20
1 1 1 2 2 3 4 5 7 9 12 16 21 28 37 49 65 86 114 151
(padovanSeq 64) -: padovanNth(i.64)
1
padovanL i.10
A
B
C
AB
BC
CAB
ABBC
BCCAB
CABABBC
ABBCBCCAB
(padovanSeq 32) -: seqLen padovanL i.32
1
</syntaxhighlight>
 
=={{header|Java}}==
<syntaxhighlight lang="java">
import java.util.ArrayList;
import java.util.List;
 
public final class Padovan {
 
public static void main(String[] aArgs) {
for ( int i = 0; i < 64; i++ ) {
recurrences.add(padovanRecurrence(i));
floors.add(padovanFloor(i));
}
System.out.println("The first 20 terms of the Padovan sequence:");
recurrences.subList(0, 20).forEach( term -> System.out.print(term + " ") );
System.out.println(System.lineSeparator());
System.out.print("Recurrence and floor functions agree for first 64 terms? " + recurrences.equals(floors));
System.out.println(System.lineSeparator());
List<String> words = createLSystem();
System.out.println("The first 10 terms of the L-system:");
words.subList(0, 10).forEach( term -> System.out.print(term + " ") );
System.out.println(System.lineSeparator());
System.out.print("Length of first 32 terms produced from the L-system match Padovan sequence? ");
List<Integer> wordLengths = words.stream().map( s -> s.length() ).toList();
System.out.println(wordLengths.equals(recurrences.subList(0, 32)));
}
private static int padovanRecurrence(int aN) {
return ( aN <= 2 ) ? 1 : recurrences.get(aN - 2) + recurrences.get(aN - 3);
}
private static int padovanFloor(int aN) {
return (int) Math.floor(Math.pow(PP, aN - 1) / SS + 0.5);
}
private static List<String> createLSystem() {
List<String> words = new ArrayList<String>();
StringBuilder stringBuilder = new StringBuilder();
String text = "A";
do {
words.add(text);
stringBuilder.setLength(0);
for ( char ch : text.toCharArray() ) {
String entry = switch ( ch ) {
case 'A' -> "B";
case 'B' -> "C";
case 'C' -> "AB";
default -> throw new AssertionError("Unexpected character found: " + ch);
};
stringBuilder.append(entry);
}
text = stringBuilder.toString();
} while ( words.size() < 32 );
return words;
}
private static List<Integer> recurrences = new ArrayList<Integer>();
private static List<Integer> floors = new ArrayList<Integer>();
private static final double PP = 1.324717957244746025960908854;
private static final double SS = 1.0453567932525329623;
 
}
</syntaxhighlight>
{{ out }}
<pre>
The first 20 terms of the Padovan sequence:
1 1 1 2 2 3 4 5 7 9 12 16 21 28 37 49 65 86 114 151
 
Recurrence and floor functions agree for first 64 terms? true
 
The first 10 terms of the L-system:
A B C AB BC CAB ABBC BCCAB CABABBC ABBCBCCAB
 
Length of first 32 terms produced from the L-system match Padovan sequence? true
</pre>
 
=={{header|JavaScript}}==
<langsyntaxhighlight lang="javascript">(() => {
"use strict";
 
Line 1,178 ⟶ 1,889:
// MAIN ---
return main();
})();</langsyntaxhighlight>
{{Out}}
<pre>First 20 padovans:
Line 1,195 ⟶ 1,906:
 
true</pre>
 
=={{header|jq}}==
{{works with|jq}}
'''Works with gojq, the Go implementation of jq'''
 
This entry differs from others in that the L-system is used to define
two functions - `padovanStrings` and `padovanNumbers` - that emit unbounded
streams of the Padovan strings and numbers respectively.
 
<syntaxhighlight lang="jq"># Output: first $n Padovans
def padovanRecur($n):
[range(0;$n) | 1] as $p
| if $n < 3 then $p
else reduce range(3;$n) as $i ($p; .[$i] = .[$i-2] + .[$i-3])
end;
 
# Output: first $n Padovans
def padovanFloor($n):
{ p: 1.324717957244746025960908854,
s: 1.0453567932525329623,
pow: 1 }
| reduce range (1;$n) as $i ( .f = [ ((.pow/.p/.s) + 0.5)|floor];
.f[$i] = (((.pow/.s) + 0.5)|floor)
| .pow *= .p)
| .f ;
# Output: a stream of the L-System Padovan strings
def padovanStrings:
{A: "B", B: "C", C: "AB", "": "A"} as $rules
| $rules[""]
| while(true;
ascii_downcase
| gsub("a"; $rules["A"]) | gsub("b"; $rules["B"]) | gsub("c"; $rules["C"]) ) ;
 
# Output: a stream of the Padovan numbers using the L-System strings
def padovanNumbers:
padovanStrings | length;
 
def task:
def s1($n):
if padovanFloor($n) == padovanRecur($n) then "give" else "do not give" end;
 
def s2($n):
if [limit($n; padovanNumbers)] == padovanRecur($n) then "give" else "do not give" end;
 
"The first 20 members of the Padovan sequence:", padovanRecur(20),
"",
"The recurrence and floor-based functions \(s1(64)) the same results for 64 terms.",
"",
([limit(10; padovanStrings)]
| "First 10 members of the Padovan L-System:", .,
"and their lengths:",
map(length)),
"",
"The recurrence and L-system based functions \(s2(32)) the same results for 32 terms."
;
 
task</syntaxhighlight>
{{out}}
<pre>
The first 20 members of the Padovan sequence:
[1,1,1,2,2,3,4,5,7,9,12,16,21,28,37,49,65,86,114,151]
 
The recurrence and floor-based functions give the same results for 64 terms.
 
First 10 members of the Padovan L-System:
["A","B","C","AB","BC","CAB","ABBC","BCCAB","CABABBC","ABBCBCCAB"]
and their lengths:
[1,1,1,2,2,3,4,5,7,9]
 
The recurrence and L-system based functions give the same results for 32 terms.
</pre>
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">""" Recursive PadowanPadovan """
rPadovan(n) = (n < 4) ? one(n) : rPadovan(n - 3) + rPadovan(n - 2)
 
""" Floor function calculation PadowanPadovan """
function fPadovan(n)::Int
p, s = big"1.324717957244746025960908854", big"1.0453567932525329623"
Line 1,206 ⟶ 1,989:
end
 
""" LSystem PadowanPadovan """
function list_LsysPadowanlist_LsysPadovan(N)
rules = Dict("A" => "B", "B" => "C", "C" => "AB")
seq, lens = ["A"], [1]
Line 1,219 ⟶ 2,002:
 
const lr, lf = [rPadovan(i) for i in 1:64], [fPadovan(i) for i in 1:64]
const sL, lL = list_LsysPadowanlist_LsysPadovan(32)
println("N Recursive Floor LSystem String\n=============================================")
foreach(i -> println(rpad(i, 4), rpad(lr[i], 12), rpad(lf[i], 12),
rpad(i < 33 ? lL[i] : "", 12), (i < 11 ? sL[i] : "")), 1:64)
</langsyntaxhighlight>{{out}}
<pre>
N Recursive Floor LSystem String
Line 1,292 ⟶ 2,075:
64 35676949 35676949
</pre>
 
 
=={{header|Kotlin}}==
<syntaxhighlight lang="Kotlin">import kotlin.math.floor
import kotlin.math.pow
 
object CodeKt{
 
private val recurrences = mutableListOf<Int>()
private val floors = mutableListOf<Int>()
private const val PP = 1.324717957244746025960908854
private const val SS = 1.0453567932525329623
 
@JvmStatic
fun main(args: Array<String>) {
for (i in 0 until 64) {
recurrences.add(padovanRecurrence(i))
floors.add(padovanFloor(i))
}
 
println("The first 20 terms of the Padovan sequence:")
recurrences.subList(0, 20).forEach { term -> print("$term ") }
println("\n")
 
println("Recurrence and floor functions agree for first 64 terms? ${recurrences == floors}\n")
 
val words = createLSystem()
 
println("The first 10 terms of the L-system:")
words.subList(0, 10).forEach { term -> print("$term ") }
println("\n")
 
print("Length of first 32 terms produced from the L-system match Padovan sequence? ")
val wordLengths = words.map { it.length }
println(wordLengths == recurrences.subList(0, 32))
}
 
private fun padovanRecurrence(n: Int): Int =
if (n <= 2) 1 else recurrences[n - 2] + recurrences[n - 3]
 
private fun padovanFloor(n: Int): Int =
floor(PP.pow(n - 1) / SS + 0.5).toInt()
 
private fun createLSystem(): List<String> {
val words = mutableListOf<String>()
var text = "A"
 
while (words.size < 32) {
words.add(text)
text = text.map { ch ->
when (ch) {
'A' -> "B"
'B' -> "C"
'C' -> "AB"
else -> throw AssertionError("Unexpected character found: $ch")
}
}.joinToString("")
}
 
return words
}
}</syntaxhighlight>
 
{{out}}
<pre>
The first 20 terms of the Padovan sequence:
1 1 1 2 2 3 4 5 7 9 12 16 21 28 37 49 65 86 114 151
 
Recurrence and floor functions agree for first 64 terms? true
 
The first 10 terms of the L-system:
A B C AB BC CAB ABBC BCCAB CABABBC ABBCBCCAB
 
Length of first 32 terms produced from the L-system match Padovan sequence? true
</pre>
 
 
 
=={{header|Lua}}==
{{trans|Perl}}
 
<syntaxhighlight lang="Lua">-- Define the constants
local p = 1.32471795724474602596
local s = 1.0453567932525329623
 
 
-- Generator for the Padovan sequence using coroutines
function pad_recur_gen(n)
local co = coroutine.create(function ()
local p = {1, 1, 1, 2}
for i = 1, n do
local next_val = p[2] + p[3]
coroutine.yield(p[1])
table.remove(p, 1)
table.insert(p, next_val)
end
end)
return function () -- iterator
local status, value = coroutine.resume(co)
return value
end
end
 
-- Padovan floor function
function pad_floor(index)
if index < 3 then
return math.floor(1/2 + p)
else
return math.floor(1/2 + p^(index - 2) / s)
end
end
 
local l, m, n = 10, 20, 32
 
local pr = {}
local pad_recur = pad_recur_gen(n)
for i = 1, n do
pr[i] = pad_recur()
end
for i = 1, m do
io.write(pr[i] .. ' ')
end
io.write('\n')
 
local pf = {}
for i = 1, n do
pf[i] = pad_floor(i)
end
for i = 1, m do
io.write(pf[i] .. ' ')
end
io.write('\n')
 
local L = {'A'}
local rules = { A = 'B', B = 'C', C = 'AB' }
for i = 1, n do
local next_str = ''
for char in L[#L]:gmatch('.') do
next_str = next_str .. rules[char]
end
table.insert(L, next_str)
end
for i = 1, l do
io.write(L[i] .. ' ')
end
io.write('\n')
 
for i = 1, n do
assert(pr[i] == pf[i] and pr[i] == #L[i],
"Uh oh, n=" .. i .. ": " .. pr[i] .. " vs " .. pf[i] .. " vs " .. #L[i])
end
 
print('100% agreement among all 3 methods.')</syntaxhighlight>
 
{{out}}
<pre>
1 1 1 2 2 3 4 5 7 9 12 16 21 28 37 49 65 86 114 151
1 1 1 2 2 3 4 5 7 9 12 16 21 28 37 49 65 86 114 151
A B C AB BC CAB ABBC BCCAB CABABBC ABBCBCCAB
100% agreement among all 3 methods.
</pre>
 
 
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">ClearAll[Padovan1,a,p,s]
p=N[Surd[((9+Sqrt[69])/18),3]+Surd[((9-Sqrt[69])/18),3],200];
s=1.0453567932525329623;
Padovan1[nmax_Integer]:=RecurrenceTable[{a[n+1]==a[n-1]+a[n-2],a[0]==1,a[1]==1,a[2]==1},a,{n,0,nmax-1}]
Padovan2[nmax_Integer]:=With[{},Floor[p^Range[-1,nmax-2]/s+1/2]]
Padovan1[20]
Padovan2[20]
Padovan1[64]===Padovan2[64]
SubstitutionSystem[{"A"->"B","B"->"C","C"->"AB"},"A",10]//Column
(StringLength/@SubstitutionSystem[{"A"->"B","B"->"C","C"->"AB"},"A",31])==Padovan2[32]</syntaxhighlight>
{{out}}
<pre>{1,1,1,2,2,3,4,5,7,9,12,16,21,28,37,49,65,86,114,151}
{1,1,1,2,2,3,4,5,7,9,12,16,21,28,37,49,65,86,114,151}
True
A
B
C
AB
BC
CAB
ABBC
BCCAB
CABABBC
ABBCBCCAB
BCCABCABABBC
True</pre>
 
 
=={{header|MATLAB}}==
<syntaxhighlight lang="MATLAB">clear all;close all;clc;
% Calculate the sequences
padovan_sequence_20 = Padovan1(20)
padovan_approx_20 = Padovan2(20)
 
% Check if the sequences are equal for n = 64
are_sequences_equal = isequal(Padovan1(64), Padovan2(64))
 
 
% Generate the substitution system sequence
sequence_32 = createLSystem();
words = sequence_32(1:10)
 
% Check if the length of the substitution system sequence equals the Padovan sequence
are_lengths_equal = all( cellfun(@(ele) length(ele), sequence_32) ...
== Padovan2(32) )
 
function words = createLSystem()
words = {'A'}; % Initialize cell array with one element "A"
text = 'A'; % Current text is "A"
 
while length(words) < 32
newText = ''; % Initialize new text as empty
for i = 1:length(text)
switch text(i)
case 'A'
newText = [newText 'B']; % Append 'B' to new text
case 'B'
newText = [newText 'C']; % Append 'C' to new text
case 'C'
newText = [newText 'AB']; % Append 'AB' to new text
end
end
text = newText; % Update text with the new text
words{end+1} = text; % Append new text to words list
end
end
 
function padovan_sequence = Padovan1(nmax)
padovan_sequence = zeros(1, nmax);
padovan_sequence(1:3) = [1, 1, 1];
for n = 4:nmax
padovan_sequence(n) = padovan_sequence(n-2) + padovan_sequence(n-3);
end
end
 
function padovan_approx = Padovan2(nmax)
p = 1.324717957244746025960908854;
s = 1.0453567932525329623;
padovan_approx = floor(p.^(-1:nmax-2) / s + 0.5);
end</syntaxhighlight>
 
{{out}}
<pre>
padovan_sequence_20 =
 
1 1 1 2 2 3 4 5 7 9 12 16 21 28 37 49 65 86 114 151
 
 
padovan_approx_20 =
 
1 1 1 2 2 3 4 5 7 9 12 16 21 28 37 49 65 86 114 151
 
 
are_sequences_equal =
 
logical
 
1
 
 
words =
 
1×10 cell array
 
{'A'} {'B'} {'C'} {'AB'} {'BC'} {'CAB'} {'ABBC'} {'BCCAB'} {'CABABBC'} {'ABBCBCCAB'}
 
 
are_lengths_equal =
 
logical
 
1
</pre>
 
 
=={{header|Nim}}==
<langsyntaxhighlight Nimlang="nim">import sequtils, strutils, tables
 
const
Line 1,355 ⟶ 2,417:
echo "These lengths are",
if list3 == list1[0..31]: " " else: " not ",
"the 32 first terms of the Padovan sequence."</langsyntaxhighlight>
 
{{out}}
Line 1,371 ⟶ 2,433:
=={{header|Perl}}==
{{trans|Raku}}
<langsyntaxhighlight lang="perl">use strict;
use warnings;
use feature <state say>;
Line 1,395 ⟶ 2,457:
 
$pr[$_] == $pf[$_] and $pr[$_] == length $L[$_] or die "Uh oh, n=$_: $pr[$_] vs $pf[$_] vs " . length $L[$_] for 0 .. $n-1;
say '100% agreement among all 3 methods.';</langsyntaxhighlight>
{{out}}
<pre>1 1 1 2 2 3 4 5 7 9 12 16 21 28 37 49 65 86 114 151
Line 1,404 ⟶ 2,466:
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>sequence padovan = {1,1,1}
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
function padovanr(integer n)
<span style="color: #004080;">sequence</span> <span style="color: #000000;">padovan</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">}</span>
while length(padovan)<n do
<span style="color: #008080;">function</span> <span style="color: #000000;">padovanr</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
padovan &= padovan[$-2]+padovan[$-1]
<span style="color: #008080;">while</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">padovan</span><span style="color: #0000FF;">)<</span><span style="color: #000000;">n</span> <span style="color: #008080;">do</span>
end while
<span style="color: #000000;">padovan</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">padovan</span><span style="color: #0000FF;">[$-</span><span style="color: #000000;">2</span><span style="color: #0000FF;">]+</span><span style="color: #000000;">padovan</span><span style="color: #0000FF;">[$-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span>
return padovan[n]
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
end function
<span style="color: #008080;">return</span> <span style="color: #000000;">padovan</span><span style="color: #0000FF;">[</span><span style="color: #000000;">n</span><span style="color: #0000FF;">]</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
constant p = 1.324717957244746025960908854,
s = 1.0453567932525329623
<span style="color: #008080;">constant</span> <span style="color: #000000;">p</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1.324717957244746025960908854</span><span style="color: #0000FF;">,</span>
function padovana(integer n)
<span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1.0453567932525329623</span>
return floor(power(p,n-2)/s + 0.5)
<span style="color: #008080;">function</span> <span style="color: #000000;">padovana</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
end function
<span style="color: #008080;">return</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">p</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span><span style="color: #0000FF;">-</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)/</span><span style="color: #000000;">s</span> <span style="color: #0000FF;">+</span> <span style="color: #000000;">0.5</span><span style="color: #0000FF;">)</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
constant l = {"B","C","AB"}
function padovanl(string prev)
<span style="color: #008080;">constant</span> <span style="color: #000000;">l</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">"B"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"C"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"AB"</span><span style="color: #0000FF;">}</span>
string res = ""
<span style="color: #008080;">function</span> <span style="color: #000000;">padovanl</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">prev</span><span style="color: #0000FF;">)</span>
for i=1 to length(prev) do
<span style="color: #004080;">string</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">""</span>
res &= l[prev[i]-64]
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">prev</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
end for
<span style="color: #000000;">res</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">l</span><span style="color: #0000FF;">[</span><span style="color: #000000;">prev</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]-</span><span style="color: #000000;">64</span><span style="color: #0000FF;">]</span>
return res
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end function
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
sequence pl = "A", l10 = {}
for n=1 to 64 do
<span style="color: #004080;">sequence</span> <span style="color: #000000;">pl</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"A"</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">l10</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
integer pn = padovanr(n)
<span style="color: #008080;">for</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">64</span> <span style="color: #008080;">do</span>
if padovana(n)!=pn or length(pl)!=pn then crash("oops") end if
<span style="color: #004080;">integer</span> <span style="color: #000000;">pn</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">padovanr</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
if n<=10 then l10 = append(l10,pl) end if
<span style="color: #008080;">if</span> <span style="color: #000000;">padovana</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)!=</span><span style="color: #000000;">pn</span> <span style="color: #008080;">or</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">pl</span><span style="color: #0000FF;">)!=</span><span style="color: #000000;">pn</span> <span style="color: #008080;">then</span> <span style="color: #7060A8;">crash</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"oops"</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
pl = padovanl(pl)
<span style="color: #008080;">if</span> <span style="color: #000000;">n</span><span style="color: #0000FF;"><=</span><span style="color: #000000;">10</span> <span style="color: #008080;">then</span> <span style="color: #000000;">l10</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">l10</span><span style="color: #0000FF;">,</span><span style="color: #000000;">pl</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end for
<span style="color: #000000;">pl</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">padovanl</span><span style="color: #0000FF;">(</span><span style="color: #000000;">pl</span><span style="color: #0000FF;">)</span>
printf(1,"The first 20 terms of the Padovan sequence: %v\n\n",{padovan[1..20]})
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
printf(1,"The first 10 L-system strings: %v\n\n",{l10})
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"The first 20 terms of the Padovan sequence: %v\n\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">padovan</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..</span><span style="color: #000000;">20</span><span style="color: #0000FF;">]})</span>
printf(1,"recursive, algorithmic, and l-system agree to n=64\n")</lang>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"The first 10 L-system strings: %v\n\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">l10</span><span style="color: #0000FF;">})</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"recursive, algorithmic, and l-system agree to n=64\n"</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 1,448 ⟶ 2,513:
=={{Header|Python}}==
===Python: Idiomatic===
<langsyntaxhighlight lang="python">from math import floor
from collections import deque
from typing import Dict, Generator
Line 1,496 ⟶ 2,561:
print("\nThe L-system, recurrence and floor based algorithms match to n=31 .")
else:
print("\nThe L-system, recurrence and floor based algorithms DIFFER!")</langsyntaxhighlight>
 
{{out}}
Line 1,518 ⟶ 2,583:
The L-system, recurrence and floor based algorithms match to n=31 .</pre>
 
===Python: FunctionalExpressed in terms of a generic anamorphism (unfoldr)===
<syntaxhighlight lang="python">'''Padovan series'''
Expressed in terms of a generic anamorphism (unfoldr):
<lang python>'''Padovan series'''
 
from itertools import chain, islice
Line 1,655 ⟶ 2,719:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>First 20 padovans:
Line 1,673 ⟶ 2,737:
 
True</pre>
 
=={{header|Quackery}}==
 
<code>v**</code> is defined at [[Exponentiation operator#Quackery]].
 
<syntaxhighlight lang="quackery">( --------------------- Recurrence -------------------- )
[ dup 0 = iff
[ drop ' [ ] ] done
dup 1 = iff
[ drop ' [ 1 ] ] done
dip [ [] 0 1 1 ]
2 - times
[ dip [ 2dup + ] swap
3 pack dip join
unpack ]
3 times join behead drop ] is padovan1 ( n --> [ )
say "With recurrence: " 20 padovan1 echo cr cr
( ------------------- Floor Function ------------------ )
$ "bigrat.qky" loadfile
[ [ $ "1.324717957244746025960908854"
$->v drop join ] constant
do ] is p ( --> n/d )
[ [ $ "1.0453567932525329623"
$->v drop join ] constant
do ] is s ( --> n/d )
[ 1 -
p rot v** s v/ 1 2 v+ / ] is padovan2 ( n --> n )
say "With floor function: "
[]
20 times [ i^ padovan2 join ]
echo cr cr
( ---------------------- L-System --------------------- )
[ $ "" swap witheach
[ nested quackery join ] ] is expand ( $ --> $ )
[ $ "B" ] is A ( $ --> $ )
[ $ "C" ] is B ( $ --> $ )
[ $ "AB" ] is C ( $ --> $ )
$ "A"
say "First 10 L System strings: "
9 times
[ dup echo$ sp
expand ]
echo$ cr cr
[] $ "A"
31 times
[ dup size
swap dip join
expand ]
size join
32 padovan1 = iff
[ say "The first 32 recurrence terms and L System lengths are the same." ]
else [ say "Oh no! It's all gone pear-shaped!" ]
</syntaxhighlight>
 
{{out}}
 
<pre>With recurrence: [ 1 1 1 2 2 3 4 5 7 9 12 16 21 28 37 49 65 86 114 151 ]
 
With floor function: [ 1 1 1 2 2 3 4 5 7 9 12 16 21 28 37 49 65 86 114 151 ]
 
First 10 L System strings: A B C AB BC CAB ABBC BCCAB CABABBC ABBCBCCAB
 
The first 32 recurrence terms and L System lengths are the same.</pre>
 
 
 
=={{header|R}}==
<syntaxhighlight lang="R" line># Function to calculate Padovan sequence iteratively
padovan_sequence <- function(n) {
recurrences <- numeric(n)
recurrences[1:3] <- c(1, 1, 1)
if (n > 3) {
for (i in 4:n) {
recurrences[i] <- recurrences[i-2] + recurrences[i-3]
}
}
recurrences
}
 
# Function to calculate Padovan floor
padovan_floor <- function(aN) {
PP <- 1.324717957244746025960908854
SS <- 1.0453567932525329623
floor((PP^(aN - 1)) / SS + 0.5)
}
 
# Function to create L-system
create_l_system<- function() {
words <- c("A")
text <- "A"
while (length(words) < 32) {
text <- strsplit(text, "")[[1]] # Split the string into a list of characters
text <- sapply(text, function(char) {
if (char == "A") {
return("B")
} else if (char == "B") {
return("C")
} else if (char == "C") {
return("AB")
}
})
text <- paste(text, collapse = "") # Collapse the list back into a single string
words <- c(words, text) # Append the new word to the list
}
words
}
 
 
# Main script
num_terms <- 64
padovan_seq <- padovan_sequence(num_terms)
floors <- sapply(0:(num_terms-1), padovan_floor)
 
cat("The first 20 terms of the Padovan sequence:\n")
cat(padovan_seq[1:20], sep=" ", end="\n")
cat("\n")
 
cat("Recurrence and floor functions agree for first 64 terms?", all(padovan_seq == floors), "\n\n")
 
words <- create_l_system()
 
cat("The first 10 terms of the L-system:\n")
cat(words[1:10], sep=" ", end="\n")
cat("\n")
 
cat("Length of first 32 terms produced from the L-system match Padovan sequence? ")
word_lengths <- sapply(words, nchar)
cat(all(word_lengths[1:32] == padovan_seq[1:32]))</syntaxhighlight>
{{out}}
<pre>
The first 20 terms of the Padovan sequence:
1 1 1 2 2 3 4 5 7 9 12 16 21 28 37 49 65 86 114 151
 
Recurrence and floor functions agree for first 64 terms? TRUE
 
The first 10 terms of the L-system:
A B C AB BC CAB ABBC BCCAB CABABBC ABBCBCCAB
 
Length of first 32 terms produced from the L-system match Padovan sequence? TRUE
</pre>
 
 
=={{header|Raku}}==
<syntaxhighlight lang="raku" perl6line>constant p = 1.32471795724474602596;
constant s = 1.0453567932525329623;
constant %rules = A => 'B', B => 'C', C => 'AB';
Line 1,690 ⟶ 2,916:
 
say "Recurrence == Floor to N=64" if (@pad-recur Z== @pad-floor).head(64).all;
say "Recurrence == L-len to N=32" if (@pad-recur Z== @pad-L-len).head(32).all;</langsyntaxhighlight>
{{out}}
<pre>
Line 1,700 ⟶ 2,926:
 
=={{header|REXX}}==
<langsyntaxhighlight lang="rexx">/*REXX pgm computes the Padovan seq. (using 2 methods), and also computes the L─strings.*/
numeric digits 40 /*better precision for Plastic ratio. */
parse arg n nF Ln cL . /*obtain optional arguments from the CL*/
Line 1,750 ⟶ 2,976:
end /*j*/
say
if ok then say 'all ' cL what; return</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>
Line 1,761 ⟶ 2,987:
 
all 32 terms match for Padovan terms and lengths of L_sys terms.
</pre>
 
=={{header|RPL}}==
≪ '''IF''' DUP 2 ≤ '''THEN''' DROP 1
'''ELSE''' 1 1 1
3 5 ROLL START OVER + ROT ROT NEXT DROP2
'''END'''
≫ ''''PDVAN1'''' STO
≪ 1.32471795724 SWAP 1 - ^ 1.04535679325 / 0.5 + FLOOR ≫ ''''PDVAN2'''' STO
≪ {{ "" "A" } { "A" "B" } { "B" "C" } { "C" "AB" }}
1 4 '''FOR''' j
DUP j GET
'''IF''' 3 PICK OVER 1 GET == '''THEN''' 2 GET 5 'j' STO '''ELSE''' DROP '''END'''
'''NEXT'''
ROT ROT DROP2
≫ ''''RULE→'''' STO
≪ "" 1 ROT '''START'''
"" 1 3 PICK SIZE '''FOR''' j
OVER j DUP SUB '''RULE→''' + '''NEXT'''
SWAP DROP '''NEXT'''
≫ ''''LSTRN'''' STO
{{in}}
<pre>
≪ {} 0 63 FOR j j PDVAN1 + NEXT ≫ EVAL
≪ 1 CF
0 63 FOR j IF j PDVAN1 j PDVAN2 ≠ THEN 1 SF END NEXT
1 SF? "Different results" "64 same results" IFTE
≫ EVAL
≪ {} 1 32 FOR j j LSTRN + NEXT ≫ EVAL
≪ {} 0 31 FOR j j PDVAN2 + NEXT ≫ EVAL
DUP ==
</pre>
{{out}}
<pre>
4: { 1 1 1 2 2 3 4 5 7 9 12 16 21 28 37 49 65 86 114 151 }
3: "64 same results"
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 816 1081 1432 1897 2513 3329 4410 }
1: 1
</pre>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">padovan = Enumerator.new do |y|
ar = [1, 1, 1]
loop do
Line 1,795 ⟶ 3,062:
bool = l_system.take(n).map(&:size) == padovan.take(n)
puts "Sizes of first #{n} l_system strings equal to recurrence padovan? #{bool}."
</syntaxhighlight>
</lang>
{{out}}
<pre>Recurrence Padovan: [1, 1, 1, 2, 2, 3, 4, 5, 7, 9, 12, 16, 21, 28, 37, 49, 65, 86, 114, 151]
Line 1,804 ⟶ 3,071:
Sizes of first 32 l_system strings equal to recurrence padovan? true.
</pre>
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">fn padovan_recur() -> impl std::iter::Iterator<Item = usize> {
let mut p = vec![1, 1, 1];
let mut n = 0;
Line 1,866 ⟶ 3,134:
.eq(padovan_recur().take(32))
);
}</langsyntaxhighlight>
 
{{out}}
Line 1,880 ⟶ 3,148:
Length of first 32 strings produced from the L-system = Padovan sequence? true
</pre>
 
=={{header|Scala}}==
 
{{trans|Java}}
 
<syntaxhighlight lang="scala">object Padovan extends App {
 
val recurrences = new collection.mutable.ListBuffer[Int]()
val floors = new collection.mutable.ListBuffer[Int]()
val PP = 1.324717957244746025960908854
val SS = 1.0453567932525329623
 
for (i <- 0 until 64) {
recurrences += padovanRecurrence(i)
floors += padovanFloor(i)
}
 
println("The first 20 terms of the Padovan sequence:")
recurrences.slice(0, 20).foreach(term => print(s"${term} "))
println("\n")
 
println(s"Recurrence and floor functions agree for first 64 terms? ${recurrences == floors}")
println("")
 
val words = createLSystem()
 
println("The first 10 terms of the L-system:")
words.slice(0, 10).foreach(term => print(term + " "))
println("\n")
 
print("Length of first 32 terms produced from the L-system match Padovan sequence? ")
val wordLengths = words.map(_.length)
print(wordLengths.slice(0, 32) == recurrences.slice(0, 32))
 
def padovanRecurrence(n: Int): Int = {
if (n <= 2) 1 else recurrences(n - 2) + recurrences(n - 3)
}
 
def padovanFloor(aN: Int): Int = {
scala.math.floor(scala.math.pow(PP, aN - 1) / SS + 0.5).toInt
}
 
def createLSystem(): List[String] = {
var words = List("A")
var text = "A"
 
while (words.length < 32) {
text = text.flatMap {
case 'A' => "B"
case 'B' => "C"
case 'C' => "AB"
}
words = words :+ text
}
 
words
}
 
}</syntaxhighlight>
{{out}}
<pre>
The first 20 terms of the Padovan sequence:
1 1 1 2 2 3 4 5 7 9 12 16 21 28 37 49 65 86 114 151
 
Recurrence and floor functions agree for first 64 terms? true
 
The first 10 terms of the L-system:
A B C AB BC CAB ABBC BCCAB CABABBC ABBCBCCAB
 
Length of first 32 terms produced from the L-system match Padovan sequence? true
</pre>
 
 
=={{header|Swift}}==
<langsyntaxhighlight lang="swift">import Foundation
 
class PadovanRecurrence: Sequence, IteratorProtocol {
Line 1,946 ⟶ 3,286:
b = PadovanLSystem().prefix(32).map{$0.count}
.elementsEqual(PadovanRecurrence().prefix(32))
print("\nLength of first 32 strings produced from the L-system = Padovan sequence? \(b)")</langsyntaxhighlight>
 
{{out}}
Line 1,960 ⟶ 3,300:
Length of first 32 strings produced from the L-system = Padovan sequence? true
</pre>
 
 
 
=={{header|Tcl}}==
{{trans|Perl}}
<syntaxhighlight lang="Tcl">package require Tcl 8.6
 
# Create a coroutine for generating Padovan sequence using lazy evaluation
proc pad_recur {{n 1}} {
set p1 1
set p2 1
set p3 1
set p4 1
for {set i 1} {$i <= $n} {incr i} {
set next [expr {$p2 + $p3}]
yield $p1
set p1 $p2
set p2 $p3
set p3 $p4
set p4 $next
}
}
 
proc pad_floor {n} {
set p 1.32471795724474602596
set s 1.0453567932525329623
if {$n < 3} {
return 1 ;# The first three elements should be 1, so return 1 for n < 3
} else {
return [expr {int(0.5 + pow($p, double($n)-2) / $s)}]
}
}
 
# Main variables
set l 10
set m 20
set n 32
 
# Generating Padovan sequence using recursive coroutine
set pr [list]
set pad_recur_coro [coroutine pad_recur_co pad_recur $n]
for {set i 1} {$i <= $n} {incr i} {
lappend pr [pad_recur_co]
}
puts [join [lrange $pr 0 [expr {$m - 1}]] " "]
 
# Generating Padovan sequence using floor function
set pf [list]
for {set i 1} {$i <= $n} {incr i} {
lappend pf [pad_floor $i]
}
puts [join [lrange $pf 0 [expr {$m - 1}]] " "]
 
# Generating L-system sequence
set L [list "A"]
set rules [dict create A B B C C AB]
for {set i 1} {$i <= $n} {incr i} {
set last [lindex $L end]
set expansion ""
foreach char [split $last ""] {
append expansion [dict get $rules $char]
}
lappend L $expansion
}
puts [join [lrange $L 0 [expr {$l - 1}]] " "]
 
# Comparison of all three methods, adjusting for zero-indexing
for {set i 0} {$i < $m} {incr i} {
set pr_val [lindex $pr $i]
set pf_val [lindex $pf $i]
set L_len [string length [lindex $L $i]]
if { $pr_val != $pf_val || $pr_val != $L_len } {
error "Uh oh, n=$i: $pr_val vs $pf_val vs $L_len"
}
}
 
puts "100% agreement among all 3 methods."</syntaxhighlight>
 
{{out}}
<pre>
1 1 1 2 2 3 4 5 7 9 12 16 21 28 37 49 65 86 114 151
1 1 1 2 2 3 4 5 7 9 12 16 21 28 37 49 65 86 114 151
A B C AB BC CAB ABBC BCCAB CABABBC ABBCBCCAB
100% agreement among all 3 methods.
</pre>
 
 
 
 
 
=={{header|Wren}}==
Line 1,965 ⟶ 3,394:
{{libheader|Wren-dynamic}}
L-System stuff is based on the Julia implementation.
<langsyntaxhighlight ecmascriptlang="wren">import "./big" for BigRat
import "./dynamic" for Struct
 
var padovanRecur = Fn.new { |n|
Line 2,028 ⟶ 3,457:
areSame = (0...32).all { |i| recur[i] == lsyst[i] }
s = areSame ? "give" : "do not give"
System.print("\nThe recurrence and L-system based functions %(s) the same results for 32 terms.")</langsyntaxhighlight>
 
{{out}}
2,130

edits