divide and conquer assignment - java

I have to write a java program to simulate a robot to match lids with it's corresponding jar. The robot has two arms, one for the lids and one for the jars. I can't compare lids with lids or jars with jars. The user will enter three lines:
5(n)
9 7 2 5 6(size of lids)
2 6 5 7 9(size of jars)
The output should be:
3 5 4 2 1
The 3rd number in line 2 is equal to the 1st number in line 3 and so on.
We are supposed to use a divide and conquer algorithm and I really have no idea where to start. All I have to go by is it's similar to quicksort. Any help would be greatly appreciated.

Divide and conquer algorithms might be confusing at first. Think about it as if you have some relatively large problem that you can't solve, but if that problem was much, much smaller you could find the answer. Applying it to this situation: suppose instead of having 2 big lists of lid and jar sizes, you instead have 1 lid size and some number of jar sizes. You could easily tell me which jar that lid fits on, right? The idea of solving the problem for 1 lid is essentially breaking the large problem (several lids) into a smaller one (1 lid). Once that makes sense, you can move on the algorithm.
You will likely employ some recursion in order to write your algorithm. Start with the base case and solve the simplest meaningful problem (I like the 1 lid example). Once you can solve that problem, can you recursively solve the same problem for every lid? I'm not attaching any code because I don't want to spoil the learning experience for you (and this is clearly homework).

The whole point of "divide and conquer" is to divide up the work into multiple, smaller problems; then you solve the smaller problems and roll them up until they are combined into a solution. This pretty much implies a recursive solution.
With any recursive function, you always need a "basis case". This will be a simple case that is trivially easy to solve. For example, if you only have one jar and one lid, then you simply return that the jar matches the lid. (Because as part of the problem statement, you always have one matching lid for each jar.)
So one place to start is a trivial program that only works right for a length-1 list of jars/lids. Then add more machinery to make it more capable.
With quicksort, you choose a place to divide up the numbers (the "pivot"), then do a very rough sort (just take numbers that should be on the left of the pivot but are on the right and move them to the left, and vice versa). Then you call quicksort recursively on the sublist. Eventually each of the recursive calls to quicksort hits a basis case (a length-1 sublist); once they all have hit the basis case the quicksort is done. (Note: there are ways to optimize quicksort and make it faster by adding more code, but I'm talking about the simplest implementation of quicksort here.)
Maybe in this case you should start with a length-n list of just the numbers from 1 to n, and and then swap the numbers around until you have a correct list?
Hmm.  With length-2 lists, there are only two possibilities: the lists line up, or not.  If they line up you are done.  If not, you swap the numbers to make them line up, and you are done.  Hmm.  This is similar to sorting in a way, but you can't just compare numbers directly like you can when you are sorting.  (In sorting you always know that 3 sorts below 5, but here it might not be so.) So, now think about a way to break down the list and keep doing it until you have a length-2 or length-1 sublist, then handle those trivial cases.
Sounds like a fun problem. I hope you enjoy working on it.

Related

Where to start on a "generate and test" approach using Java

I am required to solve the "N Queens" problem using a generate and test approach in Java, so basically if N=8 my program must generate the 8^8 possible lists and test each one to return the 92 distinct lists that result in a solution to the problem. I must also use a DFS algorithm with backtracking to enumerate the possibilities.
To provide an example, list (2,4,6,8,3,1,7,5) means that the first queen is column 1 row 2, the second is column 2 row 4, the third is column 3 row 6...and so on.
The two main things preventing me from making headway on this are:
1) I have no idea how to generate every possible list of length N (and integers size N or less) in Java
2) I don't really understand how once I have all these lists, to abstract them to a datatype that can be traversed with a DFS algorithm.
I'm not begging someone to do my homework for me, more I'd like a conceptual walkthrough of how #2 can be thought of and a (somewhat) tangible example of how given an input N I can generate all N^N lists.

Recursive Knapsack in Java

I have read many variations of the Knapsack problem, but the version I am tasked with is a little different and I don't quite understand how to solve it.
I have an array of integers that represent weights (ie. {1,4,6,12,7,2}) and need to find only one solution that adds up to the target weight.
I understand the basic algorithm, but I cannot understand how to implement it.
First, what is my base case? Is it when the array is empty? The target has been reached? The target has been over-reached? Or maybe some combination?
Second, when the target is over-reached, how do I backtrack and try the next item?
Third, what am I supposed to return? Should I be returning ints (in which case, am I supposed to print them out?)? Or do I return arrays and the final return is the solution?
Think carefully about the problem you are trying to solve. To approach this problem, I am
considering the inputs and outputs of the Knapsack algorithm.
Input: A set of integers (the knapsack) and a single integer (the proposed sum)
Output: A set of integers who add up to the proposed sum, or null.
In this way your code might look like this
public int[] knapsackSolve(int[] sack, int prospectiveSum) {
//your algorithm here
}
The recursive algorithm is straightforward. First compute the sum of the sack. If it equals
prospectiveSum then return the sack. Otherwise iterate over sack, and for each item initialise a new knapsack with that item removed. Call knapsackSolve on this. If there is a solution, return it. Otherwise proceed to the next item.
For example if we call knapsackSolve({1,2,3},5) the algorithm tries 1 + 2 + 3 = 5 which is false. So it loops through {1,2,3} and calls knapsackSolve on the sublists {2,3},{1,3} and {1,2}. knapsackSolve({2,3},5) is the one that returns a solution.
This isn't a very efficient algorithm although it illustrates fairly well how complex the Knapsack problem is!
Basically the Knapsack problem is formulated as (from Wikipedia): "Given a set of items, each with a mass and a value, determine the number of each item to include in a collection so that the total weight is less than or equal to a given limit and the total value is as large as possible. For your problem we are interested in weights only. So you can set all values to 1. Additionally we only want to know if the target weight can be reached exactly. I guess you are allowed to use a weight only once and not multiple times?
This problem can be solved nicely with dynamic programming. Are you familiar with that principle? Applying dynamic programming is much more elegant and quicker to program than backtracking. But if you are only allowed to do backtracking use the approach from user2738608 posted above.

Algorithm Complexity (Big-O) of sudoku solver

I'm look for the "how do you find it" because I have no idea how to approach finding the algorithm complexity of my program.
I wrote a sudoku solver using java, without efficiency in mind (I wanted to try to make it work recursively, which i succeeded with!)
Some background:
my strategy employs backtracking to determine, for a given Sudoku puzzle, whether the puzzle only has one unique solution or not. So i basically read in a given puzzle, and solve it. Once i found one solution, i'm not necessarily done, need to continue to explore for further solutions. At the end, one of three possible outcomes happens: the puzzle is not solvable at all, the puzzle has a unique solution, or the puzzle has multiple solutions.
My program reads in the puzzle coordinates from a file that has one line for each given digit, consisting of the row, column, and digit. By my own convention, the upper left square of 7 is written as 007.
Implementation:
I load the values in, from the file, and stored them in a 2-D array
I go down the array until i find a Blank (unfilled value), and set it to 1. And check for any conflicts (whether the value i entered is valid or not).
If yes, I move onto the next value.
If no, I increment the value by 1, until I find a digit that works, or if none of them work (1 through 9), I go back 1 step to the last value that I adjusted and I increment that one (using recursion).
I am done solving when all 81 elements have been filled, without conflicts.
If any solutions are found, I print them to the terminal.
Otherwise, if I try to "go back one step" on the FIRST element that I initially modified, it means that there were no solutions.
How can my programs algorithm complexity? I thought it might be linear [ O(n) ], but I am accessing the array multiple times, so i'm not sure :(
Any help is appreciated
O(n ^ m) where n is the number of possibilities for each square (i.e., 9 in classic Sudoku) and m is the number of spaces that are blank.
This can be seen by working backwards from only a single blank. If there is only one blank, then you have n possibilities that you must work through in the worst case. If there are two blanks, then you must work through n possibilities for the first blank and n possibilities for the second blank for each of the possibilities for the first blank. If there are three blanks, then you must work through n possibilities for the first blank. Each of those possibilities will yield a puzzle with two blanks that has n^2 possibilities.
This algorithm performs a depth-first search through the possible solutions. Each level of the graph represents the choices for a single square. The depth of the graph is the number of squares that need to be filled. With a branching factor of n and a depth of m, finding a solution in the graph has a worst-case performance of O(n ^ m).
In many Sudokus, there will be a few numbers that can be placed directly with a bit of thought. By placing a number in the first empty cell, you give up on a lot of opportunities to reduce the possibilities. If the first ten empty cells have lots of possibilities, you get exponential growth. I'd ask the questions:
Where in the first line can the number 1 go?
Where in the first line can the number 2 go?
...
Where in the last line can the number 9 go?
Same but with nine columns?
Same but with the nine boxes?
Which number can go into the first cell?
Which number can go into the 81st cell?
That's 324 questions. If any question has exactly one answer, you pick that answer. If any question has no answer at all, you backtrack. If every question has two or more answers, you pick a question with the minimal number of answers.
You may get exponential growth, but only for problems that are really hard.

Iterating over Permutations of an Array

I'm working on some java code for some research I'm working on, and need to have a way to iterate over all permutations of an ArrayList. I've looked over some previous questions asked here, but most were not quite what I want to do, and the ones that were close had answers dealing with strings and example code written in Perl, or in the case of the one implementation that seemed like it would work ... do not actually work.
Ideally I'm looking for tips/code snippets to help me write a function permute(list, i) that as i goes from 0 to list.size()! gives me every permutation of my ArrayList.
There is a way of counting from 0 to (n! - 1) that will list off all permutations of a list of n elements. The idea is to rewrite the numbers as you go using the factorial number system and interpreting the number as an encoded way of determining which permutation to use. If you're curious about this, I have a C++ implementation of this algorithm. I also once gave a talk about this, in case you'd like some visuals on the topic.
Hope this helps!
If iterating over all permutations is enough for you, see this answer: Stepping through all permutations one swap at a time .
For a given n the iterator produces all permutations of numbers 0 to (n-1).
You can simply wrap it into another iterator that converts the permutation of numbers into a permutation of your array elements. (Note that you cannot just replace int[] within the iterator with an arbitrary array/list. The algorithm needs to work with numbers.)

Why does this code work for this TopCoder prob?

I've been trying to think since HOURS about this TopCoder problem and couldn't come with a perfectly working solution and found the one given below that is insanely beautifully used!
I'm trying to figure how this solution works for the given probem? And how could I have originally thought of it? After reading the solution I figured it's a variant of Huffman coding but that's as far as I could get. I'm really enthralled and would like to know what line of thought could lead to this solution..
Here's the problem:
http://community.topcoder.com/stat?c=problem_statement&pm=11860&rd=15091
Fox Ciel has lots of homework to do. The homework consists of some
mutually independent tasks. Different tasks may take different amounts
of time to complete. You are given a int[] workCost. For each i, the
i-th task takes workCost[i] seconds to complete. She would like to
attend a party and meet her friends, thus she wants to finish all
tasks as quickly as possible.
The main problem is that all foxes, including Ciel, really hate doing
homework. Each fox is only willing to do one of the tasks. Luckily,
Doraemon, a robotic cat from the 22nd century, gave Fox Ciel a split
hammer: a magic gadget which can split any fox into two foxes.
You are given an int splitCost. Using the split hammer on a fox is
instantaneous. Once a hammer is used on a fox, the fox starts to
split. After splitCost seconds she will turn into two foxes -- the
original fox and another completely new fox. While a fox is splitting,
it is not allowed to use the hammer on her again.
The work on a task cannot be interrupted: once a fox starts working on
a task, she must finish it. It is not allowed for multiple foxes to
cooperate on the same task. A fox cannot work on a task while she is
being split using the hammer. It is possible to split the same fox
multiple times. It is possible to split a fox both before and after
she solves one of the tasks.
Compute and return the smallest amount of time in which the foxes can
solve all the tasks.
And here's the solution I found at this link
import java.util.*;
public class FoxAndDoraemon {
public int minTime(int[] workCost, int splitCost) {
PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
for(int i : workCost) pq.offer(i);
while(pq.size()>=2) {
int i = pq.poll();
int j = pq.poll();
pq.offer(Math.max(i, j) + splitCost);
}
return pq.poll();
}
}
First of all you do realize the reasoning behind `max(i, j) + splitCost'. Don't you? Basically, if you have one fox, you split it into two and perform each task independently. Let us call this process "merging".
Now assume we have three jobs a,b and c such that a>b>c. You can either do merge(merge(a,b),c) or merge(merge(a,c),b) or merge(merge(b,c),a). Do the math and you can prove that merge(merge(b,c),a) is least among these three.
You can now use induction to prove that this solution is valid for any number of jobs (not just 3).
It's building a tree from the ground up.
The algorithm uses one basic fact to work:
If you remove the two smallest elements, the cost of computing the smallest element is always less than the cost of the next smallest plus a split. (See ElKamina's post for a much more thorough proof for this).
So if you only had two elements in your tree (say 4 and 2) and your split cost was 4, the lowest amount of time is always going to be 8 (the next to smallest element plus the cost of splitting.
So, to build our tree: let's say we got the workCost [1,3,4,5,7,8,9,10], and our splitCost is 3.
So, we look at the two smallest elements: 1,3. The 'cost' of computing these is at minimum 6 (the largest number plus the cost of a split. By then reinserting 6 into the queue, you're essentially adding the subtree:
6
1 3
Where the 'height'/'cost' is 6 total. By repeating this process, you will build a tree using the smallest subelements you can (either an existing subtree, or a new unfinished homework).
The solution will eventually look like this: (Where S(X) is the cost of splitting plus solving everything below it)
S(17)
S(13) S(14)
S(10) 9 10 S(11)
S(6) 7 S(8) 8
1 3 4 5
If you trace backwards up this tree, it's easy to see how the formula solved it: the cost of 1 and 3 is S(6), 4 and 5 is S(8), then S(6) and 7 is S(10), 8 and S(8) is S(11), etc.

Categories