Need help with this problem, I am very bad at recursion. I need to write a method that does this:
The input variable X is an integer between 1 and 50. The function should return as Y the X-th term of a sequence defined recursively by:
f(1) = 1
f(2) = 3
f(X) = 2*f(X-1) – 2*f(X-2) for X = 3,4,5,...
Your function code should use recursion (not a loop)
TBH I dont even know where to get started. Any help would be appreciated. Here is my current code:
package p1parta;
import java.util.Scanner;
public class RecursiveSeq
{
public static void main(String args[])
{
System.out.println("Please enter a number:");
Scanner input = new Scanner(System.in);
int x = input.nextInt();
System.out.println(sequence(x));
}
public static int sequence(int x)
{
if(x == 1){
return 1;
}
if (x == 2){
return 3;
}
return 2 * sequence(x - 1) - 2 * sequence(x - 2);
}
}
I tried to implement the solution shown but the output I get from the program do not match what I am calculating by hand. In fact just testing inputs 3,4,5,and 6 The only one that matches is 5
Your problem is a perfect use case for recursion. In general the recursive pattern is:
func(context)
if simple case
return simple answer
else
call func(simpler context)
and return combined results
Have a go at implementing using this pattern and come back if you have issues.
Related
My assignment is to find a way to display all possible ways of giving back change for a predetermined value, the values being scanned in from a txt file. This must be accomplished by Recursive Backtracking otherwise my solution will not be given credit. I will be honest in saying I am completely lost on how to code in the appropriate algorithm. All I know is that the algorithm works something like this:
start with empty sets.
add a dime to one set.
subtract '10' from my amount.
This is a negative number, so I discard that set: it is invalid.
add a nickel to another (empty) set.
subtract '5' from my amount.
This equals 2; so I'll have to keep working on this set.
Now I'm working with sets that already include one nickel.
add a dime to one set.
subtract '10' from my amount.
This is a negative number, so I discard that set: it is invalid.
repeat this with a nickel; I discard this possibility because (2 - 5) is also negative.
repeat this with a penny; this is valid but I still have 1 left.
repeat this whole process again with a starting set of one nickel and one penny,
again discarding a dime and nickel,
and finally adding a penny to reach an amount of 0: this is a valid set.
Now I go back to empty sets and repeat starting with a nickel, then pennies.
The issue is I haven't the slightest clue on how or where to begin, only that that has to be accomplished, or if any other solutions are apparent.
This is my code thus far:
UPDATED
import java.io.*;
import java.util.*;
import java.lang.*;
public class homework5 {
public static int penny = 1;
public static int nickle = 5;
public static int dime = 10;
public static int quarter = 25;
public static int halfDollar = 50;
public static int dollar = 100;
public static int change;
public static void main(String[] args) throws FileNotFoundException {
ArrayList<Integer> coinTypes = new ArrayList<Integer>();
Integer i;
File f = new File (args[0]);
Scanner input = new Scanner(f);
input.nextLine();
while(input.hasNextInt()) {
i = input.nextInt();
coinTypes.add(i);
}
change = coinTypes.get(coinTypes.size()-1);
coinTypes.remove(coinTypes.size()-1);
System.out.println("Found change"); //used for debugging
System.out.println("Change: " + change);
System.out.println(coinTypes);
}
boolean findChange(int change, List<Integer> coinTypes,
List<Integer> answerCoins) {
if(change == 0) {
return true;
}
if(change < 0) {
return false;
} else {
for(Integer coin : coinTypes) {
if(findChange(change - coin, coinTypes, answerCoins)){
answerCoins.add(coin);
return true;
}
}
List<Integer> answer = new ArrayList<Integer>();
boolean canFindChange = findChange(change, coinTypes, answer);
if(canFindChange) {
System.out.println(answer);
} else { System.out.println("No change found");
}
return false;
}
}
Here is the input file that I scan in
java homework5 hwk5sample1.txt
// Coins available in the USA, given in cents. Change for $1.43?
1 5 10 25 50 100
143
OUTPUT
Found change
Change: 143
[1, 5, 10, 25, 50, 100]
So using the numbers in my coinTypes ArrayList, I need a generic code algorithm to show all possible ways of receiving, for example, 143 ($1.43) back in change using the coins in the file with all pennies being the last way to show it.
Please do not think I want you to write me the algorithm, I am simply wanting help writing one otherwise I will learn nothing. Thank you all for any answers or help you can give it means a lot to me! Please let me know if i missed anything or you need more info
The example that you walk through seems to be mostly correct. The only error is this: again discarding a dime and nickel, which should be again discarding a *penny* and nickel (but I think that's just a typo.)
To write a recursive backtracking algorithm, it is useful to think of the recursive call as solving a subproblem of the original problem. In one possible implementation of the solution, the pseudocode looks like this:
/**
* findChange returns true if it is possible to make *change* cents of change
* using the coins in coinTypes. It adds the solution to answerCoins.
* If it's impossible to make this amount of change, then it returns false.
*/
boolean findChange(int change, List<Integer> coinTypes, List<Integer> answerCoins) {
if change is exactly 0: then we're done making change for 0 cents! return true
if change is negative: we cannot make change for negative cents; return false
otherwise, for each coin in coinTypes {
// we solve the subproblem of finding change for (change - coin) cents
// using the recursive call.
if we can findChange(change - coin, coinTypes, answerCoins) {
// then we have a solution to the subproblem of
// making (change - coins) cents of change, so:
- we add coin to answerCoins, the list of coins that we have used
- we return true // because this is a solution for the original problem
}
}
//if we get to the next line, then we can't find change for any of our subproblems
return false
}
We would call this method with:
List<Integer> answer = new ArrayList<Integer>();
boolean canFindChange = findChange(change, coinTypes, answer);
if(canFindChange) {
System.out.println(answer); // your desired output.
}
else {
System.out.println("Can't find change!");
}
I'm new to java programming, and our teacher taught us the concept of recursion and I found it to be a bit complicated. All I understood that it works like a loop(like the factorial of 4) but I still don't quite get it why it works like that. Can I get a detailed explanation on this topic? Here is the piece of code and a picture my teacher used to explain.
package javaapplication1;
public class JavaApplication1 {
static int factorial(int n){
int t;
if(n == 0){
return 1;
} else {
t = factorial(n - 1);
return n * t;
}
}
public static void main(String[] args) {
System.out.println(factorial(5));
}
}
In the following image, the blue color represents stack winding, and the green is stack unwinding, and again I don't know what stack winding and unwinding is.
http://i.stack.imgur.com/pjqJy.png
A recursive function is a function that calls itself until it reaches a return statement, that stops it from recalling itself. Take your example, the Factorial function.
Factorial is a mathematical function that returns the number multiplied by itself - 1 multiplied by itself - 2, ... multiplied by 1, example: factorial of 5 = 5! = 5x4x3x2x1 = 120.
it is also equal to itself multiplied by the factorial of itself -1, which is: 5! = 5x4!
Take into consideration that 0! = 1.
to represent this in a Java code, you need a loop that multiplies the numbers starting from 1, and going till the number you are calculating its factorial.
Further more, explaining your code, let us calculate Factorial(5):
Factorial() returns an integer.
Initial Call from main(): 5 != 0, then skip the condition (n == 0); t
= Factorial(5-1) = Factorial(4);
Second call from Factorial(4): 4 != 0, then skip the condition (n ==
0); t = Factorial(4-1) = Factorial(3);
Third call from Factorial(3): 3 != 0, then skip the condition (n ==
0); t = Factorial(3-1) = Factorial(2);
Fourth call from Factorial(2): 2 != 0, then skip the condition (n ==
0); t = Factorial(2-1) = Factorial(1);
Fifth call from Factorial(1): 1 != 0, then skip the condition (n ==
0); t = Factorial(1-1) = Factorial(0);
Sixth call from Factorial(0): 0 == 0, then return value 1;
First return, 1, to Fifth call (Factorial(1)): return n*t = return 1*1
= return value 1;
Second return, 1, to Fourth call (Factorial(2)): return n*t = return
2*1 = return value 2;
Third return, 2, to third call (Factorial(3)): return n*t = return 3*2
= return value 6;
Second return, 6, to second call (Factorial(4)): return n*t = return
4*6 = return value 24;
Second return, 24, to First call (Factorial(5)): return n*t = return
5*24 = return value 120;
Second return, 120, to Initial call (from main()): print(120);
Hope this helps you understand recursion.
When a call is made to another method, a stack frame is created to hold the state of the current method and it is pushed onto the stack. This is regardless of a method calling itself or another method.
When the call returns, the stack frame is popped of the stack, the state of the method is restored and execution continues in the calling method.
Recursion is when a method (directly or indirectly) calls itself. The general form of a recursive method is:
If a parameter meets a terminating condition, return (usually a result)
Else adjust parameters for the next iteration and call self
The code your teacher wrote has some style issues. It would be clearer if written like this:
static int factorial(int n) {
if (n == 0) {
return 1;
}
return n * factorial(n - 1);
}
Eradicating the unnecessary variable t and redundant else (there is no "else" when the "if" returns - there is merely continuation of execution)
I would write it like this, eliminating the if altogether:
static int factorial(int n) {
return n == 0 ? 1 : n * factorial(n - 1);
}
When one knows that a task can be broken into similar smaller tasks ,then we use recursion or calling the same method(until we met a certain condition).Recursion not only helps in execution of a problem without having to define or invoke another method,it also helps in visualizing a pattern by which the task is getting executed
Personally, I do not like the factorial problem. I find it hard to understand and I do not think it explains recursion in a clear way. So lets look at a different example. Lets say that we want to print numbers from 1-100. This is a very simple task with a for loop and a counter, but it can also be done with recursion. For example:
public static void main(String[] args) {
numbersAscending(1);
numbersDescending(1);
}
//Prints 1 2 3 ... 100
public void numbersAscending(int x){
System.out.println(x);
if(x < 100){
numbersAscending(x+1);
}
}
//Prints 100 99 98 ... 1
public void numbersDescending(int x){
if(x < 100){
numbersDescending(x+1);
}
System.out.println(x);
}
When a function is called, that call goes on top of the stack. Think of this like a stack of cards. Each one has a number on it (1-100). When a function calls itself, a new card gets added to the stack. When the function finishes, it is taken off of the stack.
So for the example above, every time numbersAscending is called, it prints out the current value for x before calling that function again. This results in the numbers being printed in order from 1-100. As soon as 100 is reached, it stops calling itself and pops each function off of the stack.
On the other hand, every time numbersDescending is called, it calls itself again before printing out the number. In this way, x doesn't start printing until it reaches 100. It then moves back down the stack, printing each number as it goes back to the main method.
/*This program in java will help you to understand all the basics of
recursion:
->how control flows in recursion
->how return is executed in the recursive functions
->how and when the statements after recursive function area executed.*/
public class Understanding_Rec{
public static int rec(int x)
{
if(x<5)
{
System.out.println("-->Smaller than 5");
rec(x+1);
System.out.println("<--After recursion inside x<5");
return x;
}
else if(x<7)
{
System.out.println("-->Smaller than 7");
rec(x+1);
System.out.println("<--After recursion inside x<7");
}
System.out.println("<--No Condition Statement");
return x;
}
public static void main(String[] args)
{
int x=1;
rec(x);
System.out.print(x+"Inside main");
}
}
I am not sure if it explains, but if you had a precalculus class then you should know that factorial can be defined in two waqys.
n!=1*2*...*n
of we define
1!=1
and
n!=n*(n-1)!
Try to see yourself that those definitions are equivalent. Pick let us say, 5!
according to second definition
5!=5*4!
but 4!=4*3! so 5!=5*4*3!
but 3!=3*2! so 5!=5*4*3*2!
and so on. Keep doing it until you hit 1!. But 1!=1 so you stop.
Recursion in programming is the same thing.
TomW
I already searched everywhere for a solution for my problem, but didn't get one. So what I'm trying to do ist use recursion to find out whats a passed integer variable's base to the power of the passed exponent. So for example 3² is 9. My solution really looks like what I found in these forums, but it constantly gives me a stack overflow error. Here is what I have so far.(To make it easier, I tried it with the ints directly not using scanner to test my recursion) Any idea?
public class Power {
public static int exp(int x,int n) {
n = 3;
x = 2;
if (x == 0) {
return 1;
}
else {
return n * exp(n,x-1);
}
}
public static void main(String[] args) {
System.out.println(exp(2,3));
}
}
Well, you've got three problems.
First, inside of the method, you're reassigning x and n. So, regardless of what you pass in, x is always 2, and n is always 3. This is the main cause of your infinite recursion - as far as the method is concerned, those values never update. Remove those assignments from your code.
Next, your base case is incorrect - you want to stop when n == 0. Change your if statement to reflect that.
Third, your recursive step is wrong. You want to call your next method with a reduction to n, not to x. It should read return x * exp(x, n-1); instead.
I'm stuck on an assignment, largely due to an extreme lack of examples or even relevant diagrams from my textbook and class material.
The reason I structured the program the way I did is because I'm required to use 4 methods: a main method that executes all the other methods, a retrieve input method, a check method, and a display method. I love to hear about best practices, but I'm forced to code like this.
My main problem is the abstract classes I have. Any variables I write in one method won't be resolvable in another, I don't know how to make the variables global.
secondly, the code does not compile, the example I've found doesn't have a classic main, i don't really know how to make main implement methods, or make the compiler happy with abstraction.
also no clue on how to take my boolean result and use that to display the results in the display method. yes its asinine, I'd rather just do it in the check method.
all i know for sue is that my "logic" so far works. i think. any help to point me in the right direction would be very much appreciated. if thee is a way to do this without abstract classes i'd love to hear it, i think the abstraction is unnecessary.
well here's my monster so far:
import javax.swing.JOptionPane;
interface Palindrome {
void retrieveInput(String[] args);
boolean Check(String s);
void display();
}
abstract class Sub_Palindrome implements Palindrome {
public void retrieveInput(String[] args)
{
String Uinput;
int number1;
int digit1; // first digit
int digit2; // second digit
int digit3;
int digit4; // fourth digit
int digit5; // fifth digit
Uinput = JOptionPane.showInputDialog("Enter A 5 Digit Integer");
try { //Sanitize user input, make sure input entered is a number
number1 = Integer.parseInt(Uinput);
} catch (NumberFormatException String) {
JOptionPane.showMessageDialog(null, "Input invalid, please enter an integer",
"///-D-A-T-A---E-R-R-O-R-\\\\\\", JOptionPane.ERROR_MESSAGE);
return;
}
if (number1 < 10000 || number1 > 99999) { //Sanitize user input, make sure the given number is between 10000 and 99999
JOptionPane.showMessageDialog(null,
"The number entered must be between 10000 and 99999",
"///-D-A-T-A---E-R-R-O-R-\\\\\\", JOptionPane.ERROR_MESSAGE);
return;
}
}
public boolean Check(String s)
{
digit1 = number / 10000;
digit2 = number / 1000 % 10;
digit3 = number % 1000 / 100 % 10; // is the third digit even necessary?
digit4 = number % 10000 % 1000 % 100 / 10;
digit5 = number % 10000 % 1000 % 100 % 10;
if (digit1 == digit5 && digit2 == digit4)
return true;
else
return false;
}
public void display()
{
//display output text based upon result from IsPalinDrome
//after displaying result, start from the beginning and ask user to input data again
}
}
Move the variables outside methods and put directly in class scope
Writing main method is the first thing you learn in java. Look into your tutorial again
You can use a boolean variable boolean displayCheck = false; and set the same
And one question from my side: If your code doesn't compile what makes you feel that the logic is correct?
New to Java, basically started yesterday.
Okay, so here's the thing.
I'm trying to make an 'averager', if you wanna call it that, that accepts a random amount of numbers. I shouldn't have to define it in the program, it has to be arbitrary. I have to make it work on Console.
But I can't use Console.ReadLine() or Scanner or any of that. I have to input the data through the Console itself. So, when I call it, I'd type into the Console:
java AveragerConsole 1 4 82.4
which calls the program and gives the three arguments: 1, 4 and 82.4
I think that the problem I'm having is, I can't seem to tell it this:
If the next field in the array is empty, calculate the average (check Line 14 in code)
My code's below:
public class AveragerConsole
{
public static void main(String args[])
{
boolean stop = false;
int n = 0;
double x;
double total = 0;
while (stop == false)
{
if (args[n] == "") //Line 14
{
double average = total / (n-1);
System.out.println("Average is equal to: "+average);
stop = true;
}
else
{
x = Double.parseDouble(args[n]);
total = total + x;
n = n + 1;
}
}
}
}
The following error appears:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at AveragerConsole.main(AveragerConsole.java:14)
for(String number : args) {
// do something with one argument, your else branch mostly
}
Also, you don't need n, you already have the number of arguments, it's the args length.
This is the simplest way to do it.
For String value comparisons, you must use the equals() method.
if ("".equals(args[n]))
And next, the max valid index in an array is always array.length - 1. If you try to access the array.length index, it'll give you ArrayIndexOutOfBoundsException.
You've got this probably because your if did not evaluate properly, as you used == for String value comparison.
On a side note, I really doubt if this if condition of yours is ever gonna be evaluated, unless you manually enter a blank string after inputting all the numbers.
Change the condition in your while to this and your program seems to be working all fine for n numbers. (#SilviuBurcea's solution seems to be the best since you don't need to keep track of the n yourself)
while (n < args.length)
You gave 3 inputs and array start couting from 0. The array args as per your input is as follows.
args[0] = 1
args[1] = 4
args[2] = 82.4
and
args[3] = // Index out of bound
Better implementation would be like follows
double sum = 0.0;
// No fault tolerant checking implemented
for(String value: args)
sum += Double.parseDouble(value);
double average = sum/args.length;