fibonacci recursive method with special output - java

I'm looking to generate a specific output with my fibonacci recursive method. I already have the recursive code. However the output should display the fibonacci number(one per line) and also the ratio of the current and previous fibonacci numbers on each line.
(if user enters 5)
Fib#1=0
Fib#2=1
Fib#3=1; 1/1=1
Fib#4=2; 2/1=2
Fib#5=3; 3/2=1
this is the code i have so far:
if(n == 0)
return "0";
else if(n == 1)
return "1";
else
return FibonacciCalc(n - 1) + FibonacciCalc(n - 2);
How do i make that output? Should i return a String or make a different print method? Thanks

The problem with this recursive function is that it would be very inefficient as it has the calculate the whole range every time. Better to do this in a loop.
int beforeLastNumber = 1;
int lastNumber = 1;
System.out.println("0");
System.out.println("1");
for(int number=2; number<max; number++) {
int nextNumber = beforeLastNumber + lastNumber;
beforeLastNumber = lastNumber;
lastNumber = nextNumber;
System.out.println(nextNumber);
}
The above keeps a running total of where we're at, which avoid recalculating a sum of lots of numbers to get the higher ones.

Try this:
public class fib {
public static int FibonnaciCalc(int n) {
if (n == 0)
return 0;
else if (n == 1)
return 1;
else
return FibonnaciCalc(n - 1) + FibonnaciCalc(n - 2);
}
public static void main(String[] args) {
final List<Integer> fibList = new ArrayList<Integer>();
int limit = 5;
for (int i = 0; i < limit; i++)
fibList.add(FibonnaciCalc(i));
int tmp = 0;
for (int i=0;i<fibList.size();i++) {
tmp=i+1;
if (i <2)
System.out.println("Fib#" + tmp + "=" + fibList.get(i));
else
System.out.println("Fib#" + tmp + "=" + fibList.get(i)+"; "+fibList.get(i) +"/"+fibList.get(i-1)+"="+fibList.get(i)/fibList.get(i-1));
}
}
}

Recursive fibonacci output
class FibonacciContext {
int beforePrevious;
int previous;
public FibonacciContext(int beforePrevious, int previous) {
this.beforePrevious = beforePrevious;
this.previous = previous;
}
public int getBeforePrevious() {
return beforePrevious();
}
public int getPrevious() {
return previous;
}
public int getNext() {
return beforePrevious + previous;
}
public FibonnaciContext getNextContext() {
return new FibonnaciContext(previous, getNext());
}
}
public FibonacciContext outputFibonacciNumbers(int maxIndex) {
// 0 and 1 are 0 and 1 - non recursive termination
if (maxIndex<2) {
System.out.println(maxIndex);
return new FibonnaciContext(0, maxIndex);
}
// output all previous numbers before this one
FibonnaciContext context = outputFibonacciNumbers(maxIndex-1);
// print out this one
System.out.println(context.getNext());
// context passed back to the recursive call
return context.getNextContext();
}

Try this one:
public static void main(String[] args) {
new Main().f(5);
}
private void f(final int i) {
if (i > 2) {
f(i - 1);
System.out.println(String.format("Fib#%1$d=%2$d; %2$d/%3$d=%4$d", i, fib(i-1), fib(i-2), fib(i-1)/fib(i-2)));
} else if (i > 0) {
f(i - 1);
System.out.println(String.format("Fib#%1$d=%2$d", i, fib(i-1)));
}
}
private int fib(final int i) {
if (i == 0) {
return 0;
} else if (i == 1) {
return 1;
} else {
return fib(i - 2) + fib(i - 1);
}
}

Related

Trying to find palindrome number

I am trying to find palindrome no but every time it is showing false for every no even for 121
please Help....
public boolean isPalindrome(int x) {
if(x<0 || x%10==0){
return false;
}
int rev = 0;
while(x!=0){
rev=(rev*10)+(x%10);
x/=10;
}
if(x==rev){
return true;
}
else{
return false;
}
}
enter image description here
As an option, you may create something like this:
public boolean isPalindrome(int x) {
StringBuilder sb = new StringBuilder();
sb.append(x);
return sb.toString().equals(sb.reverse().toString());
}
Because after your while loop ends, x will be 0, you have to act on a copy instead
public boolean isPalindrome(int x) {
int num = x;
if(x<0 || x%10==0){
return false;
}
int rev = 0;
while(x!=0){
rev=(rev*10)+(x%10);
x/=10;
}
if(num==rev){
return true;
}
else{
return false;
}
}
All you need to do is build the new number as you reduce the original. Then compare the two.
for (int i : new int[]{121,12321, 123,34543,20012}) {
System.out.printf("%6d - %s%n", i, isPalindrome(i));
}
public static boolean isPalindrome(int numb) {
int n = 0;
for (int b = numb; b > 0;) {
n *= 10;
n += b%10;
b/=10;
}
return n == numb;
}
Prints
121 - true
12321 - true
123 - false
34543 - true
20012 - false
Hope this is useful:
public static boolean palindrome(int n) {
int nPalindrome = 0;
int nCopy = n;
while (n != 0) {
nPalindrome = nPalindrome *10 + n % 10;
n = n / 10;
}
if (nCopy == nPalindrom) {
return true;
} else {
return false;
}
}
You function can be as simple as below
public static void main(String args[]){
int r,sum=0;
int n=454;//It is the number variable to be checked for palindrome
if(isPalindrome(n)) {
System.out.println("palindrome number ");
} else {
System.out.println("not palindrome number ");
}
}
public boolean isPalindrome(int n) {
while(n>0){
r=n%10; //getting remainder
sum=(sum*10)+r;
n=n/10;
}
return n==sum;
}

for-loop Java return value

I am very new to Java, sorry if the question is too simple. I am trying to evaluate whether an array is part of the fibonacci sequence. I do not know how to return "true" value when the whole "for" loop does not break. Any ideas? Thank you in advance! This is what I have for now:
public boolean checkFibb(ArrayList<Integer> array1) {
int i;
int fibb;
if (array1.size() < 3) {
System.out.println("Your array is too short!");
} else {
for (i = 0; i <= array1.size() - 2; i++) {
fibb = array1.get(i + 2) - (array1.get(i + 1) + array1.get(i));
if (fibb != 0) {
System.out.println("Elements are not part of the Fibonacci sequence.");
break;
} else {
System.out.println("Elements are part of the Fibonacci sequence.");
}
}
}
return true;
}
You always return true from the method. You should do something as follows:
public boolean checkFibb(ArrayList<Integer> array1) {
int i;
int fibb;
boolean isFibb = true;
if (array1.size() < 3) {
System.out.println("Your array is too short!");
isFibb = false;
} else {
for (i = 0; i <= array1.size() - 2; i++) {
fibb = array1.get(i + 2) - (array1.get(i + 1) + array1.get(i));
if (fibb != 0) {
System.out.println("Elements are not part of the Fibonacci sequence.");
isFibb = false;
break;
} else {
System.out.println("Elements are part of the Fibonacci sequence.");
}
}
}
return isFibb;
}
What you're doing in your code is you're breaking the current iteration of the loop when you detect that the elements aren't part of a fibonacci sequence. break only stops the current iteration of the loop that you are in. What you want to do is return false from the function at this point. When you detect that the array is indeed a fibonacci sequence you would want to return true at this point.
If you array is too short, it cannot be a fibonacci sequence thus you would return false at this point.
public boolean checkFibb(ArrayList<Integer> array1) {
int i;
int fibb;
if (array1.size() < 3) {
System.out.println("Your array is too short!");
return false;
} else {
for (i = 0; i <= array1.size() - 2; i++) {
fibb = array1.get(i + 2) - (array1.get(i + 1) + array1.get(i));
if (fibb != 0) {
System.out.println("Elements are not part of the Fibonacci sequence.");
return false;
} else {
System.out.println("Elements are part of the Fibonacci sequence.");
return true;
}
}
}
}

NullPointerException even when variables are not null

I'm currently designing a program to simulate an airport. I ran into a problem and I've already tried my best to figure out the problem and posting to this site was my final resort.
It keeps giving me a "Exception in thread "main" java.lang.NullPointerException at AirportApp.main(AirportApp.java:119)" which is under the //Landings section with the code
System.out.println(plane1.getCapacity());
The reason I did the print is to make sure plane1.getCapacity isn't a null. This is because when I tried the code below it
if(plane1.getCapacity() < 300);
it gave me the NullPointerException error. I did the print and it didn't return a null.
What I'm trying to do here is whenever a plane lands, it will be assigned to an empty gate. If the plane has a capacity of 300 or more, it will be assigned to the 4th or 5th gate only. The other planes can be assigned to any gate.
What I noticed was that the error happens only when the capacity is over 300.
I've already looked at my code over and over again making sure all variables were initialized and I still could not find anything wrong. Any help or hints will be greatly appreciated. Apologies for the messy code.
Main class.
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
public class AirportApp {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
Random rn = new Random();
String [] flightNames = {"SQ", "MI", "TZ", "TR", "EK", "MO", "FC"};
int [] flightNum = {8421, 5361, 6342, 6135, 8424, 7424, 5435};
Queue landingRunway = new Queue(10);
Queue takeoffRunway = new Queue(10);
Queue planesQueue = new Queue(100);
Queue gatesQueue = new Queue(100);
ArrayList<Gate> allGates = new ArrayList();
for(int i = 1 ; i < 6 ; i++)
{
allGates.add(new Gate(i, 0, 0, true));
}
int minutes = 0;
int planesMissedTime = 0;
Boolean highWinds = null;
int tookOffPlanes = 0;
int smallCapPlanes = 0;
int largeCapPlanes = 0;
int landedPlanes = 0;
System.out.println("Please key in the number of minutes you want "
+ "the program to run: ");
int desiredMinutes = sc.nextInt();
while(minutes < desiredMinutes)
{
//Randomise wind warnings
int windRandom = rn.nextInt(2) + 1;
if(windRandom == 1)
{
highWinds = true;
}
if(windRandom == 2)
{
highWinds = false;
}
//Empty the gates
for(Gate c : allGates)
{
if(c.getAvailability() == false)
{
c.addMinInQueue(1);
if(c.getMinInQueue() == 15)
{
c.isAvailable();
}
}
}
//Every 2 minutes
if(minutes % 2 == 0)
{
//Randomise flight names and number
int index = rn.nextInt(flightNames.length);
int index1 = rn.nextInt(flightNum.length);
String name = flightNames[index];
int num = flightNum[index1];
//Randomise plane assignment
int planeDirection = rn.nextInt(2) + 1;
int planeCap = rn.nextInt(401) + 100;
//Arrival Planes
if(planeDirection == 1)
{
planesQueue.enqueue(new Plane(num, name, planeCap, 5 , 0 ));
System.out.println("A plane has been generated.");
}
//Departure Planes
if(planeDirection == 2)
{
planesQueue.enqueue(new Plane(num, name, planeCap, 0 , 5 ));
System.out.println("A plane has been generated.");
}
//Take-Offs
if(!takeoffRunway.isEmpty())
{
System.out.println("A plane has departed.");
Plane departPlane = (Plane) takeoffRunway.dequeue();
if (departPlane.getCapacity() < 300)
{
smallCapPlanes++;
}
tookOffPlanes++;
}
}
//Landings
if(minutes % 3 == 0 && !landingRunway.isEmpty())
{
System.out.println("A plane has landed.");
gatesQueue.enqueue(landingRunway.dequeue());
landedPlanes++;
loop1:
for(Gate e : allGates)
{
if(e.getAvailability() == true)
{
Plane plane1 = (Plane) gatesQueue.dequeue();
System.out.println(plane1.getCapacity());
if(plane1.getCapacity() < 300)
{
e.addNumOfPlanes(1);
e.setAvailability(false);
break loop1;
}
if(plane1.getCapacity() > 300)
{
largeCapPlanes++;
if(e.getGateId() == 4 || e.getGateId() == 5)
{
e.addNumOfPlanes(1);
e.setAvailability(false);
break loop1;
}
}
}
}
}
//Plane assigned to takeoff or landing queue
if(minutes % 5 == 0)
{
Plane item = (Plane) planesQueue.peek();
if(item.getArrivalTime() == 5 && landingRunway.isEmpty()
&& highWinds == false)
{
landingRunway.enqueue(planesQueue.dequeue());
System.out.println("A plane has been assigned to "
+ "the landing queue.");
}
else if(item.getDepartureTime() == 5 &&
takeoffRunway.isEmpty() && highWinds == false)
{
takeoffRunway.enqueue(planesQueue.dequeue());
System.out.println("A plane has been assigned to "
+ "the takeoff queue.");
}
else
{
planesMissedTime++;
}
}
minutes++;
}
Class 1
public class Plane
{
private int flightNo;
private String flightName;
private int capacity;
private int timeOfArrival;
private int timeOfDeparture;
private int delayTime;
public Plane(int flightNo, String flightName, int capacity,
int timeOfArrival, int timeOfDeparture)
{
this.flightNo = flightNo;
this.flightName = flightName;
this.capacity = capacity;
this.timeOfArrival = timeOfArrival;
this.timeOfDeparture = timeOfDeparture;
}
public void setFlightNum(int flightNo)
{
this.flightNo = flightNo;
}
public int getFlightNum()
{
return this.flightNo;
}
public void setFlightName(String flightName)
{
this.flightName = flightName;
}
public String getflightName()
{
return this.flightName;
}
public void addCapacity(int capacity)
{
this.capacity = capacity;
}
public int getCapacity()
{
return this.capacity;
}
public void setArrivalTime(int newArrivalTime)
{
this.timeOfArrival = newArrivalTime;
}
public int getArrivalTime()
{
return this.timeOfArrival;
}
public void setDepartureTime(int newDepartureTime)
{
this.timeOfDeparture = newDepartureTime;
}
public int getDepartureTime()
{
return this.timeOfDeparture;
}
}
Class 2
public class Gate
{
private int gateID;
private int numOfPlanes;
private int minInQueue;
private boolean availability;
public Gate(int id, int numPlanes, int minQueue, boolean available)
{
this.gateID = id;
this.numOfPlanes = numPlanes;
this.minInQueue = minQueue;
this.availability = available;
}
public int getGateId()
{
return this.gateID;
}
public void setGateId(int newID)
{
this.gateID = newID;
}
public int getNumOfPlanes()
{
return this.numOfPlanes;
}
public void addNumOfPlanes(int addNum)
{
this.numOfPlanes += addNum;
}
public int getMinInQueue()
{
return this.minInQueue;
}
public void setMinInQueue(int setMin)
{
this.minInQueue = 0;
}
public void addMinInQueue(int addMin)
{
this.minInQueue += addMin;
}
public boolean getAvailability()
{
return this.availability;
}
public void setAvailability(Boolean setAvailability)
{
this.availability = setAvailability;
}
public void isAvailable()
{
this.availability = true;
this.minInQueue = 0;
}
}
Queue class
class Queue
{
private int count;
private int front = 0;
private int rear = 0;
private Object [] items;
public Queue(int maxSize)
{
count = 0;
front = -1;
rear = -1;
items = new Object [maxSize];
}
public boolean enqueue (Object x)
{
if (count == items.length)
{
return false;
}
else
{
rear = (rear + 1) % items.length;
items[rear] = x;
if (count == 0)
{
front = 0;
}
count++;
return true;
}
}
public Object dequeue()
{
if (count == 0)
{
return null;
}
else
{
Object result = items[front];
front = (front + 1) % items.length;
count--;
if (count == 0)
{
front = -1;
rear = -1;
}
return result;
}
}
public int size()
{
return count;
}
public boolean isEmpty()
{
if (count == 0)
{
return true;
}
else
{
return false;
}
}
public Object peek()
{
if (count == 0)
{
return null;
}
else
{
return items[front];
}
}
}
The problem lies in the second if statement
if (plane1.getCapacity() > 300) {
largeCapPlanes++;
if (e.getGateId() == 4 || e.getGateId() == 5) {
e.addNumOfPlanes(1);
e.setAvailability(false);
break loop1;
}
}
You only break your loop if the gate is 4, or 5. So, if it is not gate 4 or 5, then you code will loop back to the next gate, grab another plane from the queue (which is empty and your plane1 is now null) and then try to get the capacity. And there you get your null pointer.
Note: Be careful nesting loops and if statements. This is where bugs enjoy living.
Happy Coding!
I ran the code and didn't get an error until I tried a large number for the time (1000). I'm assuming the error is with the Plane plane1 = (Plane) gatesQueue.dequeue(); section. I would throw some debug statements in there to see if for large n that the Queue is generated properly. if dequeue() returns null then plane1 will also be null
EDIT:
So I debugged it and confirmed that the issue is with your plane object in that loop. You enqueue your gates: gatesQueue.enqueue(landingRunway.dequeue()); then you run a loop: for(Gate e : allGates) and then you dequeue: Plane plane1 = (Plane) gatesQueue.dequeue();
If you dequeue more than what you enqueue you will return null. So you'll either have to change how you do your queue or put a check in that for-loop to check the size of your queue.
The reason you are seeing a number when you do your System.out.println() is because it is displaying that, returning to the top of the loop, and then trying to get the plane object again before you run the print again.

How to Update a Counter for Fibonacci using Recursion?

Here's the deal I want to count the recursive calls for a basic Fibonacci code. I already have it so the values will print out in column format but I don't know how to update the recCounter. I think I have to add recCounter++; Somewhere and I don't know where
public static int recursionFibonacci(int n) {
recCounter = 1;
return fibonacci1(n);
}
public static int fibonacci1(int n) {
if (n == 1 || n == 2) {
return 1;
} else {
return fibonacci1(n-1) + fibonacci1(n-2);
}
}
You should increment the counter every time you call the function:
public static int fibonacci1(int n) {
recCounter++; // <<-- here
if (n == 1 || n == 2) {
return 1;
} else {
return fibonacci1(n-1) + fibonacci1(n-2);
}
}

Java code freezing mid execution

Im running my code, and after it says the first print statement it pauses. It pauses at a point where it calls a function "insert" and simply doesnt respond anything. it prints "adding dog, cat, & horse" but then just stops, doesnt do anything after that.
main function
package assignment2;
public class Main {
public static void main(String[] args) {
OrderedStringList myList = new OrderedStringList(5);
System.out.println("adding dog, cat, & horse");
myList.Insert("dog");
myList.Insert("cat");
myList.Insert("horse");
myList.Display();
System.out.println("Value pig find = "+ myList.Find("pig"));
System.out.println("Value horse find = "+ myList.Find("horse"));
System.out.println("Adding mouse & rat");
myList.Insert("mouse");
myList.Insert("rat");
myList.Display();
System.out.println("myList size: "+ myList.Size());
if (!myList.Insert("chinchilla"))
System.out.println("Could not add chinchilla, full");
System.out.println("Removing dog, adding chinchilla.");
myList.Delete("dog");
myList.Insert("chinchilla");
myList.Display();
}
}
here is my code of functions
package assignment2;
public class OrderedStringList {
int length;
int numUsed;
String[] storage;
boolean ordered;
public OrderedStringList(int size){
length = size;
storage = new String[length];
numUsed = 0;
}
public boolean Insert(String value){
boolean result = false;
int index = 0;
if (numUsed < length) {
while (index < numUsed) {
int compare = storage[index].compareTo(value);
if (compare < 0)
index++;
}
moveItemsDown(index);
storage[index] = value;
numUsed++;
result = true;
}
return result;
}
private void moveItemsDown(int start){
int index;
for (index = numUsed-1; index >=start; index--){
storage[index+1] = storage[index];
}
}
private void moveItemsUp(int start){
int index;
for (index = start; index < numUsed-1; index++){
storage[index] = storage[index+1];
}
}
public boolean Find(String value){
return (FindIndex(value) >= 0);
}
private int FindIndex(String value) {
int result = -1;
int index = 0;
boolean found = false;
while ((index < numUsed) && (!found)) {
found = (value.equals(storage[index]));
if (!found)
index++;
}
if (found)
result = index;
return result;
}
public boolean Delete(String value){
boolean result = false;
int location;
location = FindIndex(value);
if (location >= 0) {
moveItemsUp(location);
numUsed--;
result = true;
}
return result;
}
public void Display() {
int index;
System.out.println("list Contents: ");
for (index = 0; index < numUsed; index++) {
System.out.println(index+" "+storage[index]);
}
System.out.println("-------------");
System.out.println();
}
public void DisplayNoLF() {
int index;
System.out.println("list Contents: ");
for (index = 0; index < numUsed; index++) {
System.out.print(storage[index]+" ");
}
System.out.println("-------------");
System.out.println();
}
public int Size(){
return numUsed;
}
}
You're getting caught in an infinite loop in the while statement of your Insert function. Consider this piece of code:
while (index < numUsed) {
int compare = storage[index].compareTo(value);
if (compare < 0)
index++;
}
What happens if compare >= 0 for index = 0? Index doesn't increment upwards, then the while loop is called again on index = 0, ad infinitum. You need to increment index outside of the if statement and put a different condition in your if statement.
while (index < numUsed && storage[index].compareTo(value) < 0) {
index++;
}
solved my problem by doing this. i simply removed the for loop and added an extra requirement on the while loop.

Categories