I'd like to calculate the height and set the resizeWeight of a JSplitPane that may contain other JSplitPanes and other Components as well. The concept right now looks the following (warning: snippet, not a fully functional code fragment; I only need guidelines for rewriting the recursive invocations with a while-loop using accumulators, not a fully functional solution code).
splitPane.setResizeWeight(calculateComponentHeight(splitPane.getTopComponent()) / calculateNewSplitPaneHeight(splitPane));
...
private double calculateNewSplitPaneHeight(JSplitPane sp) {
return calculateComponentHeight(sp.getTopComponent()) + calculateComponentHeight(sp.getBottomComponent());
}
private double calculateComponentHeight(Component c) {
if (c instanceof JSplitPane) {
return calculateNewSplitPaneHeight((JSplitPane) c);
}
return (double) c.getHeight();
}
As I may not know the level of embeddedness of the split panes, what can be a practical approach towards resolving such recursions?
And yes, I know, splitPane.getPreferredSize().height and splitPane.getTopComponent().getPreferredSize().height give me the answers I need without any recursive invocations. This is question is merely here to work one's brain on recursions and loops.
You can emulate recursion with a stack: How can you emulate recursion with a stack?
I once made a try on emulating a simple Fibonacci-like recursion:
f(n) = f(n-1) + f(n-2) + array[n]
The result is placed on a GitHub and is written according to the explanations in the linked answer. I should admit that it was a more complex task than I first imagined.
Related
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 2 years ago.
Improve this question
so I was wondering if any of you can give me tips regarding this. I've been doing some challenges like (the classical) making a method to calculate the nth number of a Fibonacci sequence using a single recursive call (aka. avoid return fibo(n-1) + fibo(n-2);).
I really scratched my head on that one and ended up looking at the solution that made use of a helper method -
public static int fibonacci(int n) {
if (n < 2) {
return n;
}
return fibonacci_helper(n, 1, 0);
}
public static int fibonacci_helper(int n, int previous, int current) {
if (n < 1) {
return current;
}
return fibonacci_helper(n - 1, current, previous + current);
}
I'm not really sure what approach one takes to solve questions like that quickly (without first solving it iteratively and translating that to a tail recursion, which takes a lot of time).
Would really appreciate some tips, thanks in advance.
You need to first decide if the question needs a recursive solution.Typically a recursion is needed when a present solution is dependent on some previous (already calculated) solution.
To start with , first check on small inputs(call them corner/base cases) . Then build on it (manually by dry running) on small inputs.Once you have done this, you can , in most cases , figure out the recurrence relation(like here in fibonacci).Test its validity , and then using base cases and current recurrence relation , write a recursion.
For example , the given code searches for a node with particular value in a binary tree(check out if you don't know what binary tree is: https://en.wikipedia.org/wiki/Binary_tree)
bool search(Node root,int val){
if(root==null)//base case 1
return false;
if(root.value==val)//base case 2
return true;
return(search(root.left,val)||search(root.right,val));//recursing left and right subtrees for looking out for the value
}
Play with it on paper, and try discover hidden computations that are redone needlessly. Then try to avoid them.
Here you have f(n) = f(n-1) + f(n-2); obviously f(n-1) = f(n-2) + f(n-3) redoes f(n-2) needlessly, etc. etc. etc.. What if you could do the two at once?
Have f2(n) return two values, for n and for (n-1); then you do (in pseudocode)
f(n) = let { (a,b) := f2(n-1) } in (a+b)
Now you have two functions, none is yet defined, what good does it do? Turn this f into f2 as well, so it returns two values, not one, just as we expect it to do:
f2(n) = let { (a,b) := f2(n-1) } in (a+b,a)
And voila, a recursive definition where a is reused.
All that's left is to add some corner/edge/base case(s), and check for the off-by-1 errors.
Or even better, reverse the time arrow, start from the base case, and get your iterative version for free.
Recursion is a tool which is there to help us, to make problem solving easier.
The area you're thinking of is called Dynamic Programming. The way it works is that the solution to the larger problem you're trying to solve is composed of solutions to smaller problems, and the time complexity can be reduced dramatically if you keep those solutions and reuse them, instead of calculating them multiple times. The general approach to take is to consider how the problem can be broken down, and which solutions to the smaller problems you'll need to remember in order to solve it. In this case, you could do it in linear time and linear space by keeping all the results in an array, which should be pretty easy to think of if you're looking for a DP solution. Of course that can be simplified because you don't need to keep all those numbers, but that's a separate problem.
Typically, DP solutions will be iterative rather than recursive, because you need to keep a large number of solutions available to calculate the next larger one. To change it to use recursion, you just need to figure out which solutions you need to pass on, and include those as the parameters.
I don't get why I have to use square() in this code? Why can't I just add n times n to the String s?
static int square(int n){
return n*n;
}
static void ausgabe(int n){
String s;
int i = n;
s = "SquareOf" + i + " = " + square(i);
Sysout(s);
}
my solution would be to miss out the square method and just add like this
s = "SquareOf" + i + " = " + i*i;
I tried and the result is always right. But our book suggests the first way and I would just like to know why they make it more complicated in my eyes.
Thanks in advance.
Well, you are partially right, BUT software is developed better when you split thing according of what they do...
The method Ausgabe have a job: display the result only
The method square have a job: do the math operation only
So the whole point behind soft development is not that the code works
we try to do something else:
it must work
it must be easy to maintain
it must be easy to improve
all those requirements are related to the project's complexity and can be reached based on a single responsibility principle
For something as trivial as i*i you wouldn't need a method. However if instead have to do a more complicated operation which would require quite a few lines of code, then it would be a good idea to put that in its own method in order to keep your code clean and easy to read, understand and maintain. Moreover if you need to do the same operation at multiple points in your program, then a method would be beneficial as you do not have to copy/paste the same code over and over again in different places.
I'm planning on creating a calculator for physics that would run off of a few equations. But, I realized that it would be a lot of code.
With the equation v = x/t (just one of many I want to include) , there's already three possible equations.
v = x/t x = vt t = x/v
What I was planning to have the program do is:
-Ask the user what equation they're going to use
-Ask what variable is missing
-Solve for it with a matching equation
My question is whether or not there is a way I can format the code more efficiently. Without knowing how, it seems like running a lot of very similar code for each variant of an equation.
I'm planning to create this using multiple classes, if it isn't clear.
There's 2 approaches I can think of that would make the most sense.
The first more traditional way would be to make a bunch of classes for each kind of equation you wanted to include.
public class Velocity implements Equation{
public double solveT(double v, double x){
if(v != 0)
return x / v;
else
return 0; //or whatever value is appropriate
}
public double solveX(double v, double t){
return v * t;
}
public double solveV(double t, double x){
if(t != 0)
return x / t;
else
return 0; //or whatever value is appropriate
}
}
This keeps all of your different equations separate, and if you define an empty Equation interface you can substitute different Equation objects as needed. The drawback is that you'd have a lot of classes to keep track of, and you would have to make sure that the Equation object you're trying to call methods on is the correct instance, i.e. trying to call solveX() on a Density instance that doesn't have a solveX() method. However, having each class separate is a nice way to organize and debug.
The other approach is using Java8 lambdas:
interface twoTermEq{
double solve(double a, double b);
}
public class Calculator{
public double solveTwoTermEq(twoTermEq eq, double a, double v){
eq.solve(a, b);
}
}
public static void main(String[] args){
twoTermEq velSolveX = (t, v) -> return t * v;
twoTermEq velSolveT = (x, v) -> v != 0.0 ? return x / v : 0.0;
twoTermEq velSolveV = (x, t) -> t != 0.0 ? return x / t : 0.0;
//define as many equations as needed...
Calculator c = new Calculator();
//select which equation to run, collect user input
....
//do the calculation
double result = c.solveTwoTermEq(velSolveX, t, v);
}
This lets you define your equations all in one place and doesn't need a boatload of classes. You could similarly define interfaces for ThreeTermEq, FourTermEq, etc., as well as solveThreeTermEq(), solveFourTermEq(), etc. methods for the Calculator class. The drawback here is that it might become more difficult to maintain and organize, and I believe there's an upper limit on how big a class file can be; if a class file becomes too big it won't compile, which could happen if you've defined tons of equations.
For me the choice would come down to how I wanted to organize the code; if I wanted to only include a (relatively) small number of (relatively) simple equations, I would probably use lambdas. If I wanted to include every physics equation across as many physics topics as possible, I'd probably use classes.
Either way, there's going to have to be some similar code written for different permutations of an equation - I don't think there's really any way around that. You could try for a novel approach using a bunch of Objects to try to circumvent that, but I think that would be overwrought and not worth the effort; it's not like flipping variables around is hard.
You would probably be best off using some kind of symbolic math toolbox. Maple and MatLab are good languages/environments for working with equations, as they recognize symbolic math and can manipulate equations fairly easily. Java does not have any built in libraries for this, and it is difficult to find any libraries that would support a 'Computer Algebra System' to manipulate the equations for you. You might want to look at JAS (Java Algebra System), but I'm not sure that will do what you're looking to do. Most likey, you will need to solve for each variable by hand and build functions for each individual expression.
If you're sticking with Java, this is how I would go about it. In terms of code formatting, I would just create one Equation class that holds an array of all the variations of a given equation. The variations (i.e. V=I*R, I=V/R, R=V/I) would all be passed into the constructor for the class. A solve method could then be implemented that takes the requested variable to be solved for, the other variables and their values (distinguished by two arrays- one for characters and one for values)
Usage could be as follows:
Equation ohmsLaw = new Equation(new String[] {"V=I*R", "I=V/R", "R=V/I"});
double resistance = ohmsLaw.solve('R', new char[] {'I', 'V'}, new double[] {0.5, 12.0});
You would need to write a little bit of symbolic parsing, but that makes it fun, right?
May or may not have been the answer you were looking for, but hopefully it's some help. Good luck!
In the following line of code:
x = x.times(x).plus(y);
in what order are these expressions going to be executed?
Will it be like:
x = (x + y)*x
or x = (x^2) + y,
or something else and why?
Links to documentation about the specific subject will be highly appreciated as I had no luck with my search. Apparently I don't know where to look at and what to look for.
Thank you.
These are methods; the fact that they are called "plus" and "times" doesn't mean that they'll necessarily follow the behaviour of the built-in + and * operators.
So x.times(x) will be executed first. This will return a reference to an object, on which plus(y) will then be executed. The return value of this will then be assigned to x. It's equivalent to:
tmp = x.times(x);
x = tmp.plus(y);
Here's a link to a documentation which most likely contains the required answer (probably at 15.7). It's highly technical and verbose but not inaccessible to most people (I believe).
However, it seems that you're just starting programming, so you'll be better off reading other answers here, and programming more to get an intuitive feel (not exactly a 'feel', as it's systematic and rigourous) of the order of operations etc...
Don't be afraid to write "throw-away" code (which you can incidentally save too) to find out things you don't know if you don't know where else to look for the answer. You can always google more intensively or dive through the language specs at a latter date. You'll learn faster this way. :)
One simple way to find out is to write something like this:
class Number{
private int number;
public Number(int x){
number = x;
}
public Number times(Number x){
System.Out.PrintLn("times");
return number * x;
}
public Number plus(Number x){
System.Out.PrintLn("plus");
return number + x;
}
}
Method chains get executed from left to right, with each method using the result from the previous method, so it will be x = (x^2) + y.
What you're referring to in the algebraic expressions is operator precedence - evaluating multiplications before addition, for example. The Java compiler knows about these rules for expressions, and will generate code to evaluate them as you expect.
For method calling, there are no "special rules". When given x = x.times(x).plus(y); the compiler only knows that to evaluate x.times(x).plus(y), it first needs to know what x is, so it can call times on it. Likewise, it then needs to know what x.times(x) is so it can call the plus method on that result. Hence, this type of statement is parsed left to right : (x * x) + y.
Some languages allow the creation of functions that are "infix" with user supplied precedence. (such as Haskell : See http://www.haskell.org/tutorial/functions.html, section "Fixity declarations"). Java is, alas, not one of them.
It's going to be executed in left-to-right order, as
x = (x.times(x)).plus(y)
The other way:
x = x.(times(x).plus(y))
doesn't even make sense to me. You would have to rewrite it as
x = x.times(x.plus(y))
to make sense of it, but the fact that the second x is contained within times() while the y is outside it rules out that interpretation.
The reason the documentation doesn't say anything about this is probably that such expressions follow the normal rules for how a statement like a.b().c().d() is evaluated: from left to right. We start with a and call the function b() on it. Then, we call c() on the result of that call, and we call d() on the result of c(). Hence, x.times(x).plus(y) will first perform the multiplication, then the addition.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 6 years ago.
Improve this question
I saw this question, but the answers there are not very relevant.
A friend needs a bank of solved recursion problems to help him study for a test tomorrow.
He learned the issue theoretically, but is having problems grasping how to actually solve recursion problems. Do you know a good source of solved recursion problems (preferably in C, but can be in a C-style language as well) available on the net?
Note - examples in functional languages will not help much here. My friend is in a study race to pass his test tomorrow, and I'm sure switching languages will just confuse him at this point (it might be educational on other, less stressed times).
One of the best ways to learn recursion is to get some experience in a functional programming language such as Haskell or Lisp or Scheme.
So finding recursive problems can be reduced to finding some problems and answers related to functional programming languages. Here's an example 99 lisp problems.
It really only takes 5 minutes to learn Scheme or Lisp so you can get started with examples right away for the test tomorrow you mentioned.
Another great way to learn recursion is to get some practice in mathematical proofs involving induction.
Key concepts relating to recursion:
With recursion you don't need to know how to solve the problem. You just need to know 2 things. 1) how to solve the smallest instance of the problem, and 2) how to break it up into smaller parts.
Equivalently, you just have to keep in mind that you need: 1) a base case and 2) a recursive case.
The base case handles 1 single instance of what you want to do with smallest input.
The recursive case breaks the problem into a subproblem. Eventually this subproblem will reduce to the base case.
Example:
//1+...+n = n*n(+1)/2 = sumAll(n):
int sumAll(int x)
{
if(x == 0) //base case
return 0;
else
return sumAll(x-1) + x; //recursive case
}
It is important to understand that the base case is not hard to figure out. It just has to exist. Here is an equivalent solution for x> 0:
//1+...+n = n*n(+1)/2 = sumAll(n):
int sumAll(int x)
{
if(x == 1) //base case
return 1;
else
return sumAll(x-1) + x; //recursive case
}
This article explains recursion and has some simple C examples for traversing linked list and binary tree
This is going to sound like a very lame answer, but recursion is a paradigm that's often very hard to grasp at the first for beginners. It will take more than a day's meditation on the subject for your friend to firmly grasp the concept.
You may want to have him peruse Project Euler for a potential direction to study.
I think Haskell's syntax is great for thinking recursively, because the pattern matching construct makes the base case and the recursive case so obvious. Translating this into another language is then fairly straightforward.
sumAll [] = 0
sumAll (x:xs) = x + sumAll xs
To understand this, you really only need to know that
[] represents an empty list,
(x:xs) splits a list into a head (x) and a tail (xs)
You don't need to learn all of Haskell (which is, let's face it, hard) - but doing some of the basics certainly helps you think in recursion.
In c /c++ language a function can call itself and this case is called Recursion. Mainly recursion have two cases:
Base case.
recursive case.
and we have some recursive categories like as...
Liner recursion
Binary recursion
Nested recursion
Mutual recursion
Tail recursion
Here take a example to discuss recursion ...
// a recursive program to calculate NcR //
#include <stdio.h>
int ncr(int x,int y)
{
if(y>x)
{
printf("!sorry,the operation can't processed.");
getch();
exit(1);
}
else if(y==0 ||y==x) //base case
{
return(1);
}
else
{
return(ncr(x-1,y-1)+ncr(x-1,y)); //recursive case
}
}
Read SICP(Structure and Interpretation of Computer Programs)
#include<iostream>
using namesspace std;
int E(int x);
int main()
{
int x;
cout << E(x) << endl;
return 0;
}
int E(int x)
{
return x ? (x % 10 + E(x/10)) : 0;
}