Question:: The user will enter the number and the output should contain those many rows printing the Fibonacci (Exactly as shown in the below examples).
Example:
Input :7 (Number of rows)
Output:
1
1+2
3+5+8
13+21+3
4+55+
89+
1
Note: To form a prefect diamond split the numbers of the Fibonacci series to next row and for the last number of the Fibonacci series, discard any remaining digit after the split, to print a prefect diamond shape (In example: "34" was split to place "4" into the next row to form a diamond and "144" is split place "1" in the last row and remaining digit "44" is discarded).
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class FibonacciSeriesInDiamondShape {
// Formula for the n-th Fibonacci number
private static int fibonacci(int n) {
if (n == 1) {
return 1;
}
if (n == 2) {
return 1;
}
return fibonacci(n - 1) + fibonacci(n - 2);
}
// returns a string of all Fibonacci numbers upto the nth Fibonacci number concatenated with "+"
private static String concatFibSeries(int n) {
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= n; i++) {
sb.append(fibonacci(i)).append("+");
}
return sb.toString();
}
// cuts the string returned by the method concatFibSeries(int n) into small
// chunks returns a list of strings with list.size equal to given rows the
// length of the strings beginns by one and increases by two on each step
// till the middle row is reached and decreases by two till the end of rows is reached
private static List chopper(String concatenatedString, int rows) {
List list = new ArrayList<>();
for (int i = 1, j = 1; i <= rows; i++, j = (i <= Math.ceil(rows / 2.)) ? j + 2 : j - 2) {
list.add(concatenatedString.substring(0, j));
concatenatedString = concatenatedString.substring(j);
if (concatenatedString.startsWith("+")) {
concatenatedString = concatenatedString.substring(1);
}
}
return list;
}
// adds the required space before and after each string and prints the string
private static void printDiamond(List list) {
final int listSize = list.size();
for (int i = 0; i < listSize; i++) {
String str = "";
for (int j = 0; j < (Math.abs(list.size() - Math.ceil(list.size() / 2.) - i)); j++) {
str += " ";
}
System.out.println(str + list.get(i) + str);
}
}
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in);) {
System.out.println("Enter number of rows:");
int noOfRows = scanner.nextInt();
String str = concatFibSeries(noOfRows * 2);
List list = chopper(str, noOfRows);
printDiamond(list);
}
}
}
No comments:
Post a Comment