Recursion java modified Fibonacci - java

public class ModFib
{
public static int modFibonacci(int term)
{
if(term == 1)
{
return 3;
}
else if(term == 2)
{
return 5;
}
else
{
return modFibonacci(term - 1) + modFibonacci(term - 2) + modFibonacci(term - 3);
}
}
}
it works fine at only term - 3 but this gives a stack overflow error.

need to add condition like
if(term == 0)
{
return 0;
}

Related

function to find number of ways u can split n objects using parts up to m

I'm using recursion to solve the problem. On paper my answer should work so I went wrong with the code. However, I can't figure exactly where the problem is.
public class Partition {
public static void main(String[] args) {
System.out.println(part(6,4));
}
public static int part(int n, int m) {
if (n==0) {
return 1;
}
else if(m == 0 || n<0) {
return 0;
}
else {
return part(n-m, m) + part(n, m);
}
}
}
You need to reduce m only for the problem to return 9 as you indicated.
public static int part (int n, int m) {
if (n == 0) {
return 1;
} else if (m == 0 || n < 0) {
return 0;
} else {
return part(n - m, m--) + part(n, m);
}
}
I'm not sure what you're trying to do, but if it is to compute the combination it should look like this :
public static int part(int n, int m) {
if(m>n) { //This prevent a wrong input from the user
return part(m, n);
} else if (m==0 || m==n) { //This is your base case
return 1;
} else if(m < 0 || n<0) { //this should not happened, but you never know
return 0;
} else { //this is where you're making mistake(s)
//I don't know if I'm using the formula you are looking for
//But if not, make sure yours do not use part(n, m) otherwise it will run forever
return part(n-1, m) + part(n-1, m-1);
}
}

More efficient if else block statements [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 6 years ago.
Improve this question
I'm trying to recreate a printer in java,I'm fairly new to programming so I'm using huge if else blocks inside a single function to dictate the logic of the program, I'm noticing this is creating a mass of code inside the same function, I was wondering if there was a more eloquent/efficient way of doing this, printer class below. Logic for the printer isn't too important, but just to show anyway, one is a double sided printer one isn't, and logic is in charge of checking toner levels and making sure pages printed are in line with printer being double sided or not.
package com.company;
public class Printer {
private String name;
private double tonerLevel = 100;
private int ammountOfPaper;
private int numberOfPagesPrinted;
private boolean isDoubleSided;
public Printer(String name, double tonerLevel, int ammountOfPaper, boolean isDoubleSided) {
this.name = name;
if(tonerLevel >= 0 && tonerLevel <= 100) {
this.tonerLevel = tonerLevel;
}
this.ammountOfPaper = ammountOfPaper;
this.isDoubleSided = isDoubleSided;
}
private boolean isOutOfToner(double numberToPrint) {
if((tonerLevel - (numberToPrint / 2) < 0)) {
return true;
}
else {
return false;
}
}
private boolean isOutOfPaper(double numberToPrint) {
if(((ammountOfPaper - numberToPrint) < 0)) {
return true;
}
else {
return false;
}
}
private boolean twoSideNoPaperEven(double numberToPrint) {
if((ammountOfPaper - ((int) numberToPrint / 2)) < 0 ) {
return true;
}
else {
return false;
}
}
private boolean twoSideNoPaperOdd(double numberToPrint) {
if(((ammountOfPaper - ((int) numberToPrint / 2)) - 1) < 0) {
return true;
}
else {
return false;
}
}
public void printPages(double numberToPrint) {
if(isDoubleSided == false) {
if(tonerLevel == 0) {
System.out.println("Out of toner");
}
if(ammountOfPaper == 0) {
System.out.println("Out of Paper");
}
if(isOutOfToner(numberToPrint) && (tonerLevel != 0)) {
double difference = tonerLevel * 2;
numberToPrint = difference;
ammountOfPaper -= numberToPrint;
System.out.println("Will run out of toner after this print, able to print " + (int) numberToPrint +
" pages");
tonerLevel = 0;
}
if(isOutOfPaper(numberToPrint) && (ammountOfPaper != 0)) {
double different = ammountOfPaper - numberToPrint;
numberToPrint = numberToPrint + different;
System.out.println("Will run out of paper after this print, printing " + (int) numberToPrint + " pages");
ammountOfPaper = 0;
}
else if(!isOutOfToner(numberToPrint) && (!isOutOfPaper(numberToPrint))) {
ammountOfPaper -= numberToPrint;
tonerLevel = tonerLevel - (numberToPrint / 2);
showPages(numberToPrint);
}
}
else if(isDoubleSided = true) {
if (numberToPrint % 2 == 0) {
if(tonerLevel == 0) {
System.out.println("Out of Toner");
}
if(ammountOfPaper == 0) {
System.out.println("Out of Paper");
}
if(twoSideNoPaperEven(numberToPrint) && (ammountOfPaper != 0)) {
ammountOfPaper -= numberToPrint / 2;
System.out.println("There is no Paper");
}
else if(!twoSideNoPaperEven(numberToPrint)) {
tonerLevel = tonerLevel - (numberToPrint / 2);
ammountOfPaper -= numberToPrint / 2;
showPages(numberToPrint);
}
} else {
if(tonerLevel == 0) {
System.out.println("Out of Toner");
}
if(ammountOfPaper == 0) {
System.out.println("Out of Paper");
}
if(twoSideNoPaperOdd(numberToPrint) && (ammountOfPaper != 0)) {
System.out.println("There is no paper");
ammountOfPaper = (ammountOfPaper - ((int) numberToPrint / 2)) - 1;
ammountOfPaper = 0;
}
else if(!twoSideNoPaperOdd(numberToPrint)) {
tonerLevel = tonerLevel - (numberToPrint / 2);
ammountOfPaper = (ammountOfPaper - ((int) numberToPrint / 2)) - 1;
showPages(numberToPrint);
}
}
}
}
public void showPages(double numberToPrint) {
System.out.println("Printing " + (int) numberToPrint + " Pages, paper remaining is: " + this.ammountOfPaper
+ " Toner level is: " + this.tonerLevel);
}
public void refillToner() {
tonerLevel = 100;
}
public void refillPaper(int paper) {
if(paper > 50) {
System.out.println("Cannot put in more paper");
}
else {
this.ammountOfPaper += paper;
}
}
public int getAmmountOfPaper() {
return ammountOfPaper;
}
public double getTonerLevel() {
return tonerLevel;
}
public void setTonerLevel(double tonerLevel) {
this.tonerLevel = tonerLevel;
}
public void setAmmountOfPaper(int ammountOfPaper) {
this.ammountOfPaper = ammountOfPaper;
}
Changing the If Statements To as suggested by nicolas:
public void printPages(double numberToPrint) {
if(tonerLevel == 0) {
System.out.println("Out of toner");
return;
}
if(ammountOfPaper == 0) {
System.out.println("Out of Paper");
return;
}
if(isDoubleSided == false) {
Your if-statements are redundant. You can return directly the boolean value. It saves you 12 lines in your code. For example:
private boolean twoSideNoPaperOdd(double numberToPrint) {
return ((ammountOfPaper - ((int) numberToPrint / 2)) - 1) < 0;
}
There are few conditions repeated often with the same result. Again, it shortens the class by 24 lines.
if (tonerLevel == 0) {
System.out.println("Out of toner");
return; // leave the rest of method
}
if (ammountOfPaper == 0) {
System.out.println("Out of Paper");
return
}

Recursive method checking whether a row of integers is descending: return true/false

I have to write a recursive method in Java that returns true if a row is descending and false it does not.
This is what I tried, but it doesn't work properly:
ArrayList<Integer> getallen = new ArrayList();
getallen.add(500);
getallen.add(400);
getallen.add(300);
getallen.add(200);
getallen.add(100);
getallen.add(0);
System.out.println(isDescending(getallen));
}
public static boolean isDescending(ArrayList<Integer> getallen) {
if (getallen.size() >= 2) {
if (getallen.get(0) < getallen.get(1)) {
return false;
} else if (getallen.size() > 0) {
getallen.remove(0);
return isDescending(getallen);
} else {
return true;
}
} else {
return false;
}
}
I think you have unnecessary cases if the size is less than 2 you can only assume true.
Try:
public static boolean isDescending(ArrayList<Integer> getallen) {
if (getallen.size() >= 2) {
if (getallen.get(0) < getallen.get(1)) {
return false;
} else {
getallen.remove(0);
return isDescending(getallen);
}
} else {
return true;
}
}
If I had to grade this, it would get a big fat X for
Having been fraudulently asked on stackoverflow
Being quite inefficient (try running this test on a list of a million elements, then realise that removing element 0 in an ArrayList causes all elements to shift down)
Instead consider:
public static boolean isDescending(List<Integer> getallen) {
return isDescending(getallen, 0);
}
public static boolean isDescending(List<Integer> getallen, int from) {
return from >= getallen.size() - 1
|| getallen.get(from) < getallen.get(from + 1)
&& isDescending(getallen, from + 1);
}
How about little bit more efficient approach with logarithmic recursion depth? Just as an exercise.
public static void main(String[] args) {
List<Integer> getallen = new ArrayList<Integer>();
getallen.add(500);
getallen.add(400);
getallen.add(300);
getallen.add(200);
getallen.add(100);
getallen.add(0);
System.out.println(isDescending(getallen));
}
public static boolean isDescending(List<Integer> getallen) {
return isDescending(getallen, 0, getallen.size());
}
private static boolean isDescending(List<Integer> getallen,
int start, int end) {
if (end - start <= 1)
return true;
if (end - start == 2) {
return getallen.get(start) > getallen.get(start + 1);
}
int middle = (start + end - 1) / 2 + 1;
return (getallen.get(middle - 1) > getallen.get(middle)) &&
isDescending(getallen, start, middle) &&
isDescending(getallen, middle, end);
}

recursive factorial formula

I want to get an output that displays something like 1*2*3*4 but instead I get 4*3*2*1
this is my code:
public static int fact(int n)
{
if(n ==1)
return 1;
else
return n * fact(n-1);
}
public static int factorForm(int n)
{
System.out.print(n);
if (n == 1)
return 1;
else
{
System.out.print("*");
return n + '*' + factorForm(n-1);
}
}
You are calling fact(4)
Then you print
Then you call fact(3)
If you invert that you'll get what you want:
public class fact {
static int f(int n)
{
if (n ==1 )
{
System.out.print(1);
return 1;
}
int ret= (n * f(n-1));
System.out.print("*");
System.out.print(n);
return ret;
}
public static void main(String[] args)
{
int ret=f(4);
System.out.print("=");
System.out.println(ret);
}
}
To reverse the output, n should be printed after making the recursive call:
public static int factorForm(int n)
{
if (n == 1)
{
System.out.print(1);
return 1;
}
else
{
int rest = factorForm(n-1); // prints 1*2*...*n-1
System.out.print("*");
System.out.print(n);
return rest * n;
}
}
The expression n + '*' + factorForm(n-1) performs integer addition, not multiplication or string concatenation. I changed it to perform multiplication. If the intention is to return the string that was printed, the return type and the type of rest should be changed to String, the return value in the base case should be "1", and that expression should be changed to rest + "*" + n.
Return after printing as below, more importantly understand how recursion works:
public static int factorForm(int n)
{
if (n == 1){
System.out.print("1*");
return 1;
}
else
{
int val = n * factorForm(n-1);
System.out.print(n + "*");
return val;
}
}
if you want to get like 1*2*3*4 result. i think you can do this.
this is my code:
public static String fact(int n) {
if (n < 1) {
throw new RuntimeException("n must be int type and up 0");
}
else if (n == 1) {
return "1";
} else {
return n + "*" + fact(n - 1);
}
}
public static String factorForm(String str) {
String [] arr = str.split("\\*");
String [] newArr = new String[arr.length];
String result = "";
if (arr.length > 1) {
for (int i = 0; i < arr.length; i++) {
newArr[arr.length - i - 1] = arr[i];
}
for (int i = 0; i < newArr.length; i++) {
result += newArr[i] + (i != newArr.length - 1 ? "*" : "");
}
return result;
} else {
return str;
}
}
like this. you can get results what you get. may be complicated.

2 returns firing in the same function?

Well been working for hours today so i might be missing something silly, but, at this point I'm kinda blind with this and looking for an explanation for this behaviour
i made an example of the problem I'm having and the solution i found is not quite a solution.
The Problem: to the following function I pass 1 as shotCount and 9 as Countdown
the result when i debug, i see the first if run, and run the return 2, but then also the else decides to run to and finally return -1
public int getNextShot(int shotCount, int Countdown)
{
if ((shotCount == 1) && (Countdown != 10)) return 2;
else if (shotCount == 0) return 1;
else return -1;
}
BUT if i do this (same parameters) it works:
public int getNextShot(int shotCount, int Countdown)
{
int res = -2;
if ((shotCount == 1) && (Countdown != 10)) res = 2;
else if (shotCount == 0) res = 1;
else res = -1;
return res;
}
Am I missing something here?
Thanks :)
I think you are mistaken.
Sometimes the debugger in Eclipse acts like its jumping to the last line of the method call but then does return the correct value.
For example, I just copied and pasted your code and it ran fine for me. The below code prints 2.
public class AA {
public static void main(String[] args) {
System.out.println(getNextShot(1, 9));
}
public static int getNextShot(int shotCount, int Countdown)
{
if ((shotCount == 1) && (Countdown != 10)) return 2;
else if (shotCount == 0) return 1;
else return -1;
}
}
This code is OK. When I run this:
public static int getNextShot1(int shotCount, int Countdown) {
if ((shotCount == 1) && (Countdown != 10)) {
return 2;
} else if (shotCount == 0) {
return 1;
} else {
return -1;
}
}
public static int getNextShot2(int shotCount, int Countdown) {
int res = -2;
if ((shotCount == 1) && !(Countdown == 10)) {
res = 2;
} else if (shotCount == 0) {
res = 1;
} else {
res = -1;
}
return res;
}
public static void main(String[] args) throws KeyStoreException, ParseException {
System.out.println(getNextShot1(1, 9));
System.out.println(getNextShot2(1, 9));
}
I get
2
2
on console :)
Second function could look like this (final keyword):
public static int getNextShot2(int shotCount, int Countdown) {
final int res;
if ((shotCount == 1) && !(Countdown == 10)) {
res = 2;
} else if (shotCount == 0) {
res = 1;
} else {
res = -1;
}
return res;
}

Categories

Resources