Java: multiplying big numbers using linked lists - java

I am supposed to write a function that multiplies two big numbers which are in two linked lists. I need help figuring out an algorithm that does that the same way you would solve it on pen and paper. here is what i'm thinking of:
I would use a nested for loop to iterate through both lists while multiplying each of the elements but i'm not sure how to handle the carrying situation. I've already implemented a function that adds two linked lists of integers. any input would be appreciated.

I would go for recursion (if you haven’t heard about recursion, you can probably ignore this answer; you will get around to learning it sooner or later).
I am taking the multiplication 152 * 463 as an example. My calculator tells me that the expected result is 70376. My idea is to split off the 2 from 152 to get 15 and 2 and then multiply 15 * 463 and 2 * 463:
15 * 463 = 6945. Needs to be multiplied by 10 because the 15 were in the 10s’ position. 6945 * 10? Just add a zero: 69450.
2 * 463 = 926.
Product is 69450 + 926 = 70376.
In your code 15 * 463 is obtained through a recursive call to the multiplication method that you are writing. Multiplication by 10 is easy, just append a zero. 2 * 463 is simpler because we’re multiplying by a 1-digit number. Write a new recursive method for this subtask. The function that you already have that adds two linked lists will finish the job.

Related

Finding LIS in an array of user defined objects based on more than one field

Cracking The Coding Interview(5th ed): Chp 11, Ques 7
Question: A circus is designing a tower routine consisting of people standing atop one another's shoulders. For practical and aesthetic reasons, each person must be both shorter and lighter than the person below him or her. Given the height and weights of each person in the circus, write a method to compute the largest possible number of people in such a tower.
My doubt:
In the solution given in the book it is clearly mentioned in the text
that sorting the elements will make the solution too trivial then why
elements have been sorted initially in the code?
If the elements do not need to stay in the same(relative) order, then
we would simply sort the array. This makes the problem too trivial, so
let's assume that the elements need to stay in the same relative
order.
Here is the code from the book where sorting has been done(First three lines of the code):
ArrayList<HtWt> getIncreasingSequence(ArrayList<HtWt> items)
{
Collections.sort(items);
return longestIncreaingSequence(items);
}
The proposed solution is composed of 2 steps:
sort by weight
find the longest increasing subsequence on the heights
The quoted sentence is not relative to the first step, but to the second step (finding the longest increasing subsequence) and it is explaining that we can't just sort the heights because we can't change their order since they are already sorted by their weights.
Take a look at this example with 5 people:
weights: 4 5 1 7 2
heights: 6 3 5 4 1
Result after step 1 (sorting by weight):
weights: 1 2 4 5 7
heights: 5 1 6 3 4
Now, looking at the heights we can see that the longest increasing subsequence is 1 3 4 which tell us that the solution is composed of 3 people. To obtain that result we can't just sort by heights because since they are already sorted by their weight...
... the elements need to stay in the same relative order.
So we need to use a longest increasing subsequence algorithm instead.

Math twenty four game Java [duplicate]

This question already has answers here:
Building a math game in Java
(3 answers)
Closed 8 years ago.
The 24 Game is an arithmetical game in which the objective is to find a way to manipulate four integers so that the end result is 24. Addition, subtraction, multiplication, or division in any order of the numbers may be used to make the four digits operations from one to nine equal 24.
The rules are simple: you have to use each number only once and only the 4 numbers that were read from the user to find one equation to obtain 24.
For example, for the numbers 4,7,8,8, a possible solution is: (7-(8/8))*4=24.
Most sets of 4 digits can be used in multiple equations that result in 24: for example the input: 2, 2, 4 and 7 can be used in multiple ways to obtain 24:
2+2*(4+7) = 24
2+2*(7+4) = 24
(2+2)*7-4 = 24
(2*2)*7-4 = 24
2*(2*7)-4 = 24
There are also combinations of 4 numbers that cannot result into any equation equal with 24. For example 1,1,1,1. In this case, your program should return that there is no possible equation equal with 24.
Note: Although we will enter 4 integers between 1 and 9, we will use doubles to compute all the operations. For example, the numbers 3,3,8,8 can be combined into the formula: 8/(3-8/3) = 24.
Workflow: Your program should read the 4 numbers from the user and output a formula that results in 24. The algorithm should enumerate all the possible orders of 4 numbers, all the possible combinations and all the possible formulas. There is no required GUI for this project I need help with a method that will shuffle the operators for all 64 possible combos so 4 operators and 3 being used in each equation and also account for parenthesis during the equations . I have no idea where to begin.
If you can generate permutations of a string. You need to do that for all the numbers to get all the permutations possible for those numbers.
Now you just need to plugin permutations of operators (3 at a time).
For that you can generate all the permutations of the operators and store them in an array, as that would remain constant for each case. And out of each permutation generated, just pick the first 3 characters as we are looking at groups of 3 out of the 4 possible.
Once you have that, it's simply a matter of reading a permutation of the numbers and then reading a permutation of operators and evaluating the expression.
For reference, I have made a simple demo of a function that finds permutations of a string in Java. The recursive function looks something like (from a relevant SO Post):
public void permut(String str1,String str2){
if(str2.length() != 0){
char ch = str2.charAt(0);
for(int i = 0; i <= str1.length();i++)
permut(str1.substring(0,i) + ch + str1.substring(i,str1.length()),
str2.substring(1,str2.length()));
}else{
System.out.println(str1);
}
}
If you can successfully generate all permutations of a string, the above exercise should be doable. I hope it gets you started in the right direction.

Programmatically determine whether an array could be the result of a Weighted Quick Union algorithm on a set of 10 items?

I'd like to be able to programmatically examine an array and determine whether or not it could have been the result of a Weighted Quick Union algorithm. For those of us who need a refresher, a java implementation of Weighted Quick Union is here.
The basic idea of the weighted quick union algorithm is that is always connects the smaller tree to the larger one in order to minimize height, thus optimizing any traversal functions.
For example, an array that looks like 8 4 8 8 8 3 8 3 9 7 could not be the result of Weighted Quick Union because it contains a cycle, 9->7->3->8->9
An array like 8 0 9 3 6 6 0 4 8 0 cannot be a weighted quick union because the height of the trees together is 4, which is more than log(N) (where N is 10, the size of the initial array).
However, an array like 0 1 2 8 4 1 1 7 8 9 could have been the result of a weighted quick union.
I'd like to write a Java function like this:
public static boolean canBeResultOfWeightedQuickUnion(int[] id){
//returns whether or not the given array of ints could have been the result of a weighted quick union
}
How could I go about writing a method like this, ideally using the data structure available here?
"An array like *** cannot be a weighted quick union because the height of the trees together is 4, which is more than log(N) (where N is 10, the size of the initial array)."
In fact the maximum height in this case is ceil(log_2(N)), which is 4. To check this, just keep merging trees with the same height from the start
This property remains for all subtrees, and it is a very good answer for your question since you can just check this property.
The question that stills is how can you do this with most efficiency. I suppose that you just received an array and is checking it. So no other info is available. If this is the case, you can just create a auxiliary array for the height. Then you must go throught the id array, find the leafs and in a second step recursively go from the leafs to the roots updating the values of the heights and comparing to the number of elements in the subtree.

Recursion: Behind the Scenes [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
While it is common knowledge that recursion is "a method that calls itself", I am inclined to wonder what is actually happening. Take the classic factorial example:
public static int fact(int n) {
if(n == 0)
return 1;
else
return n * fact(n - 1);
}
fact(5);
I understand that it goes a little something like this: (the equals sign indicates what's happening when the function is called for that value)
http://postimg.org/image/4yjalakcb/
Why does recursion function like this? Which aspect of a computer makes it work through itself backwards like so? What's going on behind the scenes?
As a student I feel like the recursion we are taught is shallow and general. I want the excellent community here to help me understand it on the level of the machine itself. Thank you!
Here's is the brief overview of what happens, whenever you call a method:
A frame for that method is allocated from the stack.
The frame contains, all the local variables, parameters, return values of the method.
That frame is placed over the top of the frame of current method, that invokes this method.
When the method returns, the frame related to that method is popped off the stack, and the calling method comes back into action, taking the return value if any from the previous method.
You can learn more about frames here - JVM Spec - Frames.
In case of recursion, same thing happens. Just for the time being, forget that you are dealing with recursion, and take each recursion call as a call to different method. So, in factorial case, the stack would grow like this:
fact(5)
5 * fact(4)
4 * fact(3)
3 * fact(2)
2 * fact(1)
1 * fact(0) // Base case reached. Stack starts unwinding.
2 * 1 * 1
3 * 2 * 1 * 1
4 * 3 * 2 * 1 * 1
5 * 4 * 3 * 2 * 1 * 1 == Final result
If you trace the function calls, you will see how it works.
E.g.
fact(3) will return 3 * fact(2). So java will call fact(2).
fact(2) will return 2 * fact(1). So java will call fact(1).
fact(1) will return 1 * fact(0). So java will call fact(0).
fact(0) will return 1.
Then fact(1) will return 1 * 1 = 1.
Then fact(2) will return 2 * 1 = 2.
Then fact(3) will return 3 * 2 = 6.
Java calls the recursive method like it would any other method.
You might have heard of something called "The Stack" It's what's used to store method states.
I believe it also stores the calling line, so that the function can go back to it's caller
So suppose you have your call to a recursive function
- int $input = 5
- stack.Push L
- GOTO FOO
- Label L
your recursive function(without a base case) might look similar to the following
- Label FOO
- int in = $input
- input = in - 1
- stack.Push in
- stack.Push L2
- goto FOO
- Label L2
- in = stack.Pop in
- output *= in
- goto stack.POP
Maybe the following will help you understand. The computer does not care whether he calls the same function it is just computing. There is nothing magical about recursion once you understand what it is and why it works with many things, like lists, natural numbers, etc., who are themselves recursive by structure.
Definition: The factorial of 0 is 1
Definition: The factorial of a number n greater than 0 is the product of that number and the factorial of its predecessor.
Hence
5! = 5*4! = 5*4*3! = 5*4*3*2! = 5*4*3*2*1! = 5*4*3*2*1*0! = 5*4*3*2*1*1 = 120
So, if you ever heard of proof by induction, it goes like this:
We proof some property for a base case.
We proof that, if the property is true for n, then it will be true for the successor of n.
We conclude that this is the proof that the property holds for the base case and all successive cases.
Example: Proof by induction that the square of an even number is a multiple of 4!
The square of 0 is 0, and it is a multiple of 4.
Let n be an even number, whose square n² is a multiple of 4. Then (2+n)*(2+n) = 4+2n+2n+n². This is a muliple of 4, because n² was by our assumption, 4 is one and 2n+2n = 4n is also a multiple of 4 and the sum of multiples of 4 is a multiple of 4 by distributive law: 4a + 4b = 4(a+b)
Q.E.D. The property holds for 0 (our base case), and for (2+n), provided it holds for n. Hence it holds for 2, 4, 6, 8 .... and all other even numbers.
(An easier proof woud be to observe that (2a)² = 4*a*a, which is a multiple of 4.)
Writing a recursive program is very similar to doing a proof by induction:
We write the computation for the base case.
For the non base case, we know how we can compute the result (for example, we know that n! = n * (n-1)!, so we write it just down, since the function we need is the one we are just writing!
We can conclude that our program will compute the correct value for the base case and any successor of the base case. If 678! nevertheless does not compute the correct answer, then it has to do with the fact that we used a data type like int that is not suited very well for big numbers (or, to put it differently, computes everything moulo 2^32) and in addition, with a software that insists on interpreting half of the available numbers as negative ones.
The reason this works has nothing to do with the computer hardware or the programming language: it is, as I said before, a consequence of the recursive structure of the items (lists, trees, sets, natural numbers) at hand.
A common error newcomers make is to ignore the base case and get lost in complexity. I always suggest to start with the base case, once you have this you can assume that the function exists, and can just use it in the more complex cases.

Best data structure to store and manipulate my data?

I am writing a simple Java program that will input a text file which will have some numbers representing a (n x n) matrix where numbers are separated by spaces. for ex:
1 2 3 4
5 6 7 8
9 1 2 3
4 5 6 7
I then want to store these numbers in a data structure that I will then use to manipulate the data (which will include, comparing adjecent numbers and also deleting certain numbers based on specific rules.
If a number is deleted, all the other numbers above it fall down the amount of spaces.
For the example above, if say i delete 8 and 9, then the result would be:
() 2 3 ()
1 6 7 4
5 1 2 3
4 5 6 7
so the numbers fall down in their columns.
And lastly, the matrix given will always be square (so always n x n, where n will be always given and will always be positive), therefore, the data structure has to be flexible to virtually accept any n-value.
I was originally implementing it in a 2-d array, but I was wandering if someone had an idea of a better data structure that I could use in order to improve efficiency (something that will allow me to more quickly access all the adjacent numbers in the matrix (rows and columns).
Ultimately, mu program will automatically check adjacent numbers against the rules, I delete numbers, re-format the matrix, and keep going, and in the end i want to be able to create an AI that will remove as many numbers from the matrix as possible in the least amount of moves as possible, for any n x n matrix.
In my opinion, you yo know the length of your array when you start, you are better off using an array. A simple dataType will be easier to navigate (direct access). Then again, using LinkedLists, you will be able to remove a middle value without having to re-arrange the data inside you matrix. This will leave you "top" value as null. in your example :
null 2 3 null
1 6 7 4
5 1 2 3
4 5 6 7
Hope this helps.
You could use one dimensional array with the size n*n.
int []myMatrix = new myMatrix[n * n];
To access element with coordinates (i,j) use myMatrix[i + j * n]. To fall elements use System.arraycopy to move lines.
Use special value (e.g. Integer.MIN_VALUE) as a mark for the () hole.
I expect it would be fastest and most memory efficient solution.
Array access is pretty fast. Accessing adjacent elements is easy, as you just increment the relevant index(s) (being cognizant of boundaries). You could write methods to encapsulate those operations that are well tested. Having elements 'fall down' though might get complicated, but shouldn't be too bad if you modularize it out by writing well tested methods.
All that said, if you don't need the absolute best speed, there are other options.
You also might want to consider a modified circularly linked list. When implementing a sudoku solver, I used the structure outlined here. Looking at the image, you will see that this will allow you to modify your 2d array as you want, since all you need to do is move pointers around.
I'll post a screen shot of relevant picture describing the datastructure here, although I would appreciate it if someone will warn me if I am violating some sort of copy right or other rights of the author, in which case I'll take it down...
Try a Array of LinkedLists.
If you want the numbers to auto-fall, I suggest you to use list for the coloumns.

Categories

Resources