A Padovan string P(n) for a natural number n is defined as: P(0) = ‘X’ P(1) = ‘Y’ P(2) = ‘Z’ P(n) = P(n-2) + P(n-3), n>2 where + denotes string concatenation. For a string of the characters ‘X’ , ‘Y’ and ‘Z’ only, and given value of n, write a program that counts the number of occurrences of the string in the n-th Padovan string P(n). An example is given below. For n = 6 and the string ZY, the program should count the occurrences of ZY in P(6). P(0) = ‘X’ P(1) = ‘Y’ P(2) = ‘Z’ P(n) = P(n-2) + P(n-3), n>2 P(3) = P(1)+P(0) P(3) = YX P(4) = P(2)+P(1) P(4) = ZY P(5) = P(3)+P(2) P(5) = YXZ P(6) = P(4)+P(3) P(6) = ZYYX So, the number of occurrences of the string ZY in P(6) is 1.
program in java
// aakash , suraj , prem sasi kumar kamaraj college
program 1 :
package test.padovanstring;
public class PadovanString {
public int stringOccurrences(int n, String str){
if(n >= 40)
return -1;
if(str.replaceAll("X|Y|Z","").length()>0)
return -1;
String res=pad(n);
return(res.length() - res.replaceAll(str,"").length())/(str.length());
}
public String pad(int n){
if(n == 0) return "X";
if(n == 1) return "Y";
if(n == 2) return "Z";
else return pad(n-2) + pad(n-3);
}
public static void main(String []args)
{
PadovanString p = new PadovanString();
System.out.println(p.stringOccurrences(21,"YZ"));
}
}
Program set 2 :
import java.util.Scanner;
import java.util.ArrayList;
public class PadovanSeries
{
public static void main(String[] arg)
{
Scanner read = new Scanner(System.in);
System.out.println("Enter starting no. : ");
int start = read.nextInt();
System.out.println("Enter ending no. : ");
int end = read.nextInt();
int[] ans = getSeries(start, end);
System.out.println("Padovan series : ");
for (int a : ans)
System.out.print(a + " ");
}
public static int[] getSeries(int s, int e)
{
ArrayList list = new ArrayList();
int i, j = 0;
for (i = s; i <= e; i++, j++)
list.add(getPadovan(i));
int[] ans = new int[j];
for (i = 0; i < j; i++)
ans[i] = list.get(i);
return ans;
}
public static int getPadovan(int p)
{
if (p == 0 || p == 1 || p == 2)
return 1;
return (getPadovan(p - 2) + getPadovan(p - 3));
}
}
Padova