This question already has answers here:
Understanding recursion [closed]
(20 answers)
Closed 7 years ago.
When you use recursion to solve a problem, why does the recursion method need to call itself to solve a smaller version of the original problem?
By definition, a recursive function calls itself.
If you are asking when or why you would use recursion, it is well suited for problems that resemble a fractal. IOW, when small parts of the problem look similar to larger versions of the problem.
The general idea behind solving a problem recursively is to find a way to break the problem down into smaller copies of itself, solve those smaller copies, then combine the results together to solve the overall problem.
So let's suppose that you're trying to write a function solveProblemX that solves a problem X recursively. You break the problem down into smaller copies of problem X, and now you need to solve each of them. How do you do that? Well, you're currently writing a method called solveProblemX that specifically is designed to solve problem X, so one option would be to recursively call solveProblemX on those smaller problem instances. After all - if solveProblemX really is supposed to solve problems of type X, there's nothing wrong with doing this!
What changes from problem to problem is how you break the problem down into smaller copies of itself and how you combine them back together. In each case, though, just keep in mind that the function you're writing is designed solve problems of one type, so there's nothing concerning about calling the method you're writing to solve smaller problems of that type.
I'll try to explain the way that I had it explained to me.
Say you're in a line at a coffee shop. The line is really long, and you're all the way at the back. You want to know how many people are in front of you, but you can't see the front, so you can't count everyone yourself. You instead ask the person in front of you "How many people are in front of you?". He then follows your same logic, and asks the person in front of him. Everyone asks the person in front of them until they get to the person at the register. Once the person in front is asked, they answer with 0. That would be the base case. After the person in front responds, the second person in line responds with 0+1, so 1. That continues all the way back to you until you know how many people are in line.
I'm paraphrasing something from somewhere, but I don't remember where I originally saw it.
Related
I have a load of vecmath Point objects (Point3d FWIM) which I would like to “group” based on the distance between them. I can probably write the code for this from scratch (I’ve done similar tasks in excel), but I like the idea of using existing libraries where possible. The problem is I can’t find any libraries like this.
I haven’t thought through the exact algorithm fully, but I hope I’ve done enough for the question not to be deleted. Please bear with me, I'm still new here at the time of this post.
I imagine the grouping would work as follows:
decide the distanceLimit
loop 1: for each Point, calculate the distance to each other Point
Make a "Set"
loop 2: for each Point
if the next Point is within the distanceLimit of any previously considered Points up to i, add it to current "Set"
Else make a new "Set".
Edit: ah the power of verbalising one's ideas. The above doesn't the capture the situation where points 1 and 2 are between one and two distanceLimits apart and initiate separate "sets", and point 3 crops up halfway between them meaning that all three should be in one set really. Need to think about this some more!
I’m also not sure yet what data structures I should really use for the input and output (ArrayLists? Sets?).
Ideally I am looking for an existing library that does this or similar; if you’re confident there isn’t one, then any suggestions for the algorithm or the actual code would be more than welcome.
After lots more googling, I found that:
what I was trying to do is called clustering;
this did exactly what I was trying to do; I was impressed with how well it worked for me.
So I am working on a word problem, and it goes something like this:
! section removed
I am not posting the exact question or diagram just in case someone cannot stop themselves from posting a direct answer.
I am trying to write a program in Java for this, but I can't really get a grip on how to do this logically. I know I can start of with an array for each square like this:
int square1 = //four sides with each liquid value
but I do not know how to include the unlimited ones (which are diagonal), or how to continue once I figure it out.
Any help with this programming logic is appreciated.
I'd say go through each pipe and record the maximum going through it, which should be the lower of its capacity or the sum of the maxima going into it. The unlimited ones then just take the total going into them (or, at the very beginning, Integer.MAX_VALUE). Or you could use a bool for tracking whether it's infinite. Or, just for fun, Double.POSITIVE_INFINITY.
Note that if there are any cycles in the pipes, you may need to cycle through and update a couple times, until you get a steady answer.
Edit: After looking a bit at the max flow problem linked in a comment and thinking about it, I'm not so sure this is the right way to go, as I don't think it accounts for splitting current between two outgoing pipes. Perhaps some distant relative of Ohm's law, adapted for water?
I'm practicing up for a programming competition, and i'm going over some difficult problems that I wasn't able to answer in the past. One of them was the King's Maze. Essentially you are given an NxN array of numbers -50<x<50 that represent "tokens". You have to start at position 1,1(i assume that's 0,0 in array indexes) and finish at N,N. You have to pick up tokens on cells you visit, and you can't step on a cell with no token (represented by a 0). If you get surrounded by 0's you lose. If there is no solution to a maze you output "No solution". Else, you output the highest possible number you can get from adding up the tokens you pick up.
I have no idea how to solve this problem. I figured you could write a maze algorithm to solve it, but that takes time, and in programming contests you are only given two hours to solve multiple problems. I'm guessing there's some sort of pattern i'm missing. Anyone know how I should approach this?
Also, it might help to mention that this problem is meant for high school students.
This type of problem is typically solved using dynamic programming or memoization.
Basically you formulate a recursive solution, and solve it bottom up while remembering and reusing previously computed results.
The simple approach (i.e. simplest to code) is try all the possible paths - try each first step; for each first step try each second step; for each first step/second step combination try each third step; and so on. However depending on how big the maze is this may take too long to run (or it may not).
Your next step is to think about how you can do this faster. The first step is usually to eliminate moves that you know can't lead to a finish, or can't lead to a finish with higher points than the one you already have. Since this is practice for a competition we'll leave you to do this work yourself.
Think "graph" algorithms: The Algorithm Design Manual
In my Java application both of the following will compile and run, and produce the desired result.
//"Rotate" the list items one place to the left.
myLinkedList.addLast(myLinkedList.removeFirst());
And a "rotation" in the opposite direction
//"Rotate" the list items one place to the right.
myLinkedList.addFirst(myLinkedList.removeLast());
Both "rotations" only require one line of code each, but I'm wondering if this is the right way to go about it? Are there any pitfalls in this approach?
Is there a better, more robust, less error-prone way of doing the same as I have above which would require more than one line of code to achieve, and if so please explain why.
Seems fine to me. If you had a truly circular buffer which was full you could just move the "start/end" index, but I think the linked list approach will work pretty well. In particular it's still O(1).
I suggest using Collections.rotate.
I would implement it exactly as you have.
myLinkedList.addLast(myLinkedList.removeFirst());
The only way I can see this being "bad programming" is if the list is shared between threads and your method rotates an element from one end to the other without holding a lock (I am not aware of any concurrent Queue implementation that can rotate atomically.)
Yes, I know this is nothing new and there are many questions already out there (it even has its own tag), but I'd like to create a Sudoku Solver in Java solely for the purpose of training myself to write code that is more efficient.
Probably the easiest way to do this in a program is have a ton of for loops parse through each column and row, collect the possible values of each cell, then weed out the cells with only one possibility (whether they contain only 1 number, or they're the only cell in their row/column that contains this number) until you have a solved puzzle. Of course, a sheer thought of the action should raise a red flag in every programmer's mind.
What I'm looking for is the methodology to go about solving this sucker in the most efficient way possible (please try not to include too much code - I want to figure that part out, myself).
I want to avoid mathematical algorithms if at all possible - those would be too easy and 100% not my work.
If someone could provide a step-by-step, efficient thought process for solving a Sudoku puzzle (whether by a human or computer), I would be most happy :). I'm looking for something that's vague (so it's a challenge), but informative enough (so I'm not totally lost) to get me started.
Many thanks,
Justian Meyer
EDIT:
Looking at my code, I got to thinking: what would be some of the possibilities for storing these solving states (i.e. the Sudoku grid). 2D Arrays and 3D Arrays come to mind. Which might be best? 2D might be easier to manage from the surface, but 3D Arrays would provide the "box"/"cage" number as well.
EDIT:
Nevermind. I'm gonna go with a 3D array.
It depends on how you define efficient.
You can use a brute force method, which searches through each column and row, collects the possible values of each cell, then weeds out the cells with only one possibility.
If you have cells remaining with more than one possibility, save the puzzle state, pick the cell with the fewest possibilities, pick one of the possibilities, and attempt to solve the puzzle. If the possibility you picked leads to a puzzle contradiction, restore the saved puzzle state, go back to the cell and choose a different possibility. If none of the possibilities in the cell you picked solves the puzzle, pick the next cell with the fewest possibilities. Cycle through the remaining possibilities and cells until you've solved the puzzle.
Attempt to solve the puzzle means searching through each column and row, collecting the possible values of each cell, then weeding out the cells with only one possibility. When all of the cells are weeded out, you've solved the puzzle.
You can use a logical / mathematical method, where your code tries different strategies until the puzzle is solved. Search Google with "sudoku strategies" to see the different strategies. Using logical / mathematical methods, your code can "explain" how the puzzle was solved.
When I made mine, I thought I could solve every board using a set of rules without doing any backtracking. This proved impossible as even puzzles targeting human players potentially require making a few hypothesis.
So I starting with implementing the basic "rules" for solving a puzzle, trying to find the next rule to implement that would allow the resolution of where it stopped last time. In the end, I was forced to add a brute forcing recursive algorithm, but most puzzles are actually solved without using that.
I wrote a blog post about my sudoku solver. Just read through the "The algorithm" section and you'll get a pretty good idea how I went about it.
http://www.byteauthor.com/2010/08/sudoku-solver/
Should anyone need a reference Android implementation, I wrote a solution that uses the algorithm from the post above.
Full open-source code here: https://github.com/bizz84/SudokuSolver
Additionally, this solution loads Sudoku Puzzles in JSON format from a web server and posts back the results.
You should think about reducing the Sudoku Problem to a SATisfiability problem.
This method will avoid you to think too mathematically but more logically about the AI.
The goal step by step is basically :
* Find all the constraints that a Sudoku has. (line, column, box).
* Write these constraints as boolean constraints.
* Put all these constraints in a Boolean Satisfiability Problem.
* Run a SAT solver (or write your own ;) ) on this problem.
* Transform the SAT solution into the solution of the initial Sudoku.
It has been done by Ivor Spence by using SAT4J and you can find the Java Applet of his work here : http://www.cs.qub.ac.uk/~I.Spence/SuDoku/SuDoku.html.
You can also download directly the Java code from SAT4J website, to see how it look like : http://sat4j.org/products.php#sudoku.
And finally, the big advantage of this method is : You can solve N*N Sudokus, and not only the typical 9*9, which is I think, much more challenging for an AI :).