Recursive definition solution - java

im studying for my final exam from the text book. I need an answer for this question since i couldn't solve it.
1)Write a recursive definition of the function multiply(int a, int b) that takes two integers and return the result of their multiplication.
I answered:
Multiply(a, b) :
0 - if a or b is equal to zero. (I got -1 here. Reason written: only 1)
a * b - (I didn't know what to write here)
2)
Write a recursive method that takes a linked list of integers and returns the sum of it's elements.
My solution was:
int sumList(Node<Integer> list) {
int temp = list.getInfo();
if(temp == null) {
return 0;
} else {
return temp + sumList(temp.getNext);
}
}
I fixed it, i think:
public int sumList(Node<Integer> list) {
Node<Integer> temp = list;
if(temp == null) {
return 0;
} else {
return temp.getInfo() + sumList(temp.getNext());
}
}
Is the solution for question 2 right?

Since this is for exam preparation, I don't want to give you the code for doing this. Instead I will give you some ideas.
For the question no 1. Since multiplication is repeated summation, you can use that as the base for recursion here.
If you want to find 3 * 4, use recursion to calculate and return 4 + 4 + 4.
In other words, you can see a pattern emerge below.
4 * 3 = 4 + (4 * 2)
4 * 3 = 4 + 4 + (4 * 1)

To get a working recursive solution you need a base case, for example a == 0, and then work yourself down towards the base case by recursively calling yourself.
The solution for question 1 could be something along the lines of this, that decreases the a argument until it reaches 0:
int multiply(int a, int b) {
if (a == 0 || b == 0) {
return 0;
}
return b + multiply(a - 1, b);
}
For example, multiply(2, 5) would become 5 + multiply(1, 5) -> 5 + 5 + multiply(0, 5) -> 5 + 5 + 0.
Note that this particular solution doesn't work for negative numbers, but you get the idea. You should be able to easily add support for that yourself.

A) well, you really need to reread that chapter on recursion.
The mathematical principle is this:
http://en.wikipedia.org/wiki/Mathematical_induction
and the Wikipedia article will step you through a much more complicated task.
B) No, it won't compile at all. There are multiple syntax errors.
Try using a Java compiler for excersising your programming skills.

Related

Java Help: Determining if Digits Can Form a Sequence

I have a quick question on an assignment I'm trying to finish up. I'm writing a boolean method that takes three digit parameters (0-9) and returns true if they can be re arranged to make up a sequence. The hard part, for me at least, is that 0 can make a sequence with 8, 9, or 1,2. The three numbers are assumed to all be different. To be clear, the number 5,7,6 would be true because it can be rearranged to be 5, 6, 7, a sequence. Also 8,0,9 would return true, but 2,4,7 would not. I'm hoping someone can point me in the right direction with this, any help at all would be much appreciated!
You only need to check the validity of two tests:
Are all numbers different?
Is the absolute difference between the extremes 2?
This would give you the following method:
public static boolean isSequence(int a, int b, int c) {
if(a == 0) a = 10;
if(b == 0) b = 10;
if(c == 0) c = 10;
//Add the commented-out lines to make it safe to use with non-different numbers.
//boolean allDifferent = !(a == b) && !(b == c) && !(a == c);
boolean extremesIsTwo = Math.abs(Math.max(Math.max(a, b), c)
- Math.min(Math.min(a, b), c)) == 2;
//return allDifferent && extremesIsTwo;
return extremesIsTwo;
}
When you look at it, it's only a matter of simple logic, and finding the shortest path to the answer. There might be more optimized ways to do this, but this is clear, readable and works just fine.
Now, if you really want to get grinding on a problem of the like, you could either try to optimize this algorithm, or find another way to check that the three numbers are a sequence.
EDIT This version is scalable. And even though your requirements are for three arguments, I would still consider this solution, because it uses OOP to avoid repetition of code. As requested, it also doesn't check for duplicates.
public static boolean isSequenceScalable(List<Integer> list) {
list = list.stream().map(i -> i = (i == 0) ? 10 : i).collect(Collectors.toList());
list.sort(Integer::compareTo);
if (Math.abs(list.get(0) - list.get(list.size() - 1)) == 2) return true;
return false;
}

How do I return multiple integers when the return type is simply int? [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 6 years ago.
Improve this question
I have to implement the following function:
public int solution(int[] A) {
// smth
}
However, this function may have zero or more solutions, I mean no solution (then should return -1), one solution, two solutions, etc. As you see the function just has int as return type (not an array) and I cannot change it. What should I do, if for example this function should return two values (5 and 9) or three values (1, 10, and 7)? How can I return them?
I thought about tuples, but I believe there is a better way to solve it.
Why don't you use crypting? This only works, if your solutions and numbers of solutions are small and you know two upper limits (number of solutions and biggest size of solution), but you can put more information in one int. Here mult is a number greater than the greatest expected solution:
public int solution(int[] A) {
int returnValue = 0;
//solution is an array of your solutions
for(i=0; i<solution.length; i++){
returnValue=returnValue*mult;
returnValue+=solution[i];
}
return returnValue;
}
public List<Integer> retrieveSolutions(int solution){
List<Integer> decryptedSolutions = new ArrayList<>();
while(solution>mult){
decryptedSolutions.add(solution%mult);
solution = (int) solution/mult;
}
return decryptedSolutions;
}
Just beware the case solution=0 is ignored here and you might get bigger values than the max-Value of Integer (hence you have to make sure, your upperBound+1 (=mult) power the biggest number of solutions+1 is smaller than the max-Value of Integer). Also negative solutions would break this (you can avoid this, if you know the lower bound of the solutions). An alternative would be (as mentioned in the comments) to put the solutions in an mutable Object given in the arguments:
Either in the array as Peter stated in his answer (works only, if the argument array has more elements, than your solutions) and now you have the solutions in the given array and the return value tells how many solutions you got:
public int solution(int[] A) {
int numberSolutions = solutions.length;
for(int i=0; i<solutions.length; i++){
A[i]=solutions[i];
}
return numberSolutions;
}
or in an extra "bag"
public int solution(int[] A, NumberBag putTheSolutionsHere) {
// puts solutions in your NumberBag, whatever Object you might want to use here (preferable List implementation)
}
If you cannot change the signature, you only option is to change the input. While that would be the worst possible solution, it might be your only one. You could return the number of solutions. e.g.
// return all the positive numbers
public int solution(int[] array) {
// put all the positive numbers at the start.
return numOfPositives;
}
A better solution would be to return an array of results
public int[] solution(int[] input)
If you can't change the function, overload it - write the same function with different signature.
more on overloading
If you can add one argument to the signature, add any Collection and the method will populate the Collection (trivial).
If you cannot change the signature and cannot change the return type : is it for a good reason? Discuss with the one who asked you to do it.
If there is a good reason for that (or if it is a sort of algorithmic exercise), you can use some bit masking. In java, an int is encoded on 32 bits. If the possible solution are smalls, you can divide those 32 bits in small groups and store each solution in a group.
Here is a solution which shows how you could store up to 8 solutions in [0; 15] by using groups of 4 bits:
public static void main(String[] args) throws Exception {
List<Integer> values = Arrays.asList(5, 7, 3, 8, 9);
String collect = values.stream().map(Object::toString).collect(Collectors.joining(", "));
System.out.println("Values to encode : "+collect);
int _1111 = (2 << 3) - 1;
System.out.println("\nMasks : ");
for (int i = 0; i < values.size(); i++) {
System.out.println(padWith0(Integer.toString(_1111 << 4 * i, 2)));
}
System.out.println("\nEncoding : ");
int result = 0;
for (int i = 0; i< values.size() ; i++) {
int partial = values.get(i) << (4 * i);
System.out.println(values.get(i) +" => " + padWith0(Integer.toString(partial, 2)));
result += partial;
}
System.out.println(" => "+Integer.toString(result, 2));
System.out.println("\nRestitution : ");
for(int i = 0; i< values.size(); i++) {
int mask = _1111 << (4 * i);
int partial = (result & mask) >> (4 * i);
System.out.println(Integer.toString(partial, 2) +" => " + partial);
}
}
public static String padWith0(String s) {
return ("00000000000000000000000000000000" + s).substring(s.length());
}
Output :
Values to encode : 5, 7, 3, 8, 9
Masks :
00000000000000000000000000001111
00000000000000000000000011110000
00000000000000000000111100000000
00000000000000001111000000000000
00000000000011110000000000000000
Encoding :
5 => 00000000000000000000000000000101
7 => 00000000000000000000000001110000
3 => 00000000000000000000001100000000
8 => 00000000000000001000000000000000
9 => 00000000000010010000000000000000
=> 00000000000010011000001101110101
Restitution :
101 => 5
111 => 7
11 => 3
1000 => 8
1001 => 9

Learning Java - Do not fully understand how this sequence is calculated (Fibonacci) in for loop [duplicate]

This question already has answers here:
Java recursive Fibonacci sequence
(37 answers)
Closed 8 years ago.
I am learning Java and I have this code from the internet and running it in Eclipse:
public class Fibonacci {
public static void main (String [] args) {
for (int counter = 0; counter <= 3; counter++){
System.out.printf("Fibonacci of %d is: %d\n", counter, fibonacci(counter));
}
public static long fibonacci(long number) {
if ((number == 0) || (number == 1))
return number;
else
return fibonacci(number - 1) + fibonacci(number - 2);
}
}
I've tried to understand it but cannot get it. So I run through the code and counter gets passed in through the fibonacci method. As counter starts at 0 and this is what gets passed first, then 1 and I understand the method passes back 0 and then 1.
When it reaches 2: it will return 2-1 + 2-2 = 2 and it does return this.
When it reaches 3: it will return 3-1 + 3-2 = 3 but it does not return 3 it returns 2.
Please can someone explain to me why as I cannot figure this out?
Thanks
First, I have to tell you that this recursive version has a dramatic exponential cost. Once you understand how it works, my advice for you would be to learn about tail recursivity, write a tail-recursive solution, an iterative solution, and compare them to your current method for high values of "number".
Then, your function basically uses the mathematical definition of the Fibonacci sequence :
f0 = 1, f1 = 1, fn = fn-1 + fn-2 for all n >= 2
For example if we call fibonacci(3), this will return fibonacci(2) + fibonacci(1). fibonacci(2) will be executed first and will return fibonacci(1) + fibonnacci(0). Then fibonacci(1) will return immediately 1 since it is a terminal case. It happens the same thing with fibonnacci(0), so now we have computed fibonnacci(2) = 1 + 0 = 1. Let's go back to fibonacci(3) which has been partially evaluated at this point : 1 + fibonnacci(1). We just have to compute fibonnacci(1) and we can finally return 1 + 1 = 2.
Even in this little example, you can see that we evaluated twice fibonacci(1), that is why this version is so slow, it computes many times the same values of the sequence, and it gets worth when "number" is high.

Dealing with overflow in Java without using BigInteger

Suppose I have a method to calculate combinations of r items from n items:
public static long combi(int n, int r) {
if ( r == n) return 1;
long numr = 1;
for(int i=n; i > (n-r); i--) {
numr *=i;
}
return numr/fact(r);
}
public static long fact(int n) {
long rs = 1;
if(n <2) return 1;
for (int i=2; i<=n; i++) {
rs *=i;
}
return rs;
}
As you can see it involves factorial which can easily overflow the result. For example if I have fact(200) for the foctorial method I get zero. The question is why do I get zero?
Secondly how do I deal with overflow in above context? The method should return largest possible number to fit in long if the result is too big instead of returning wrong answer.
One approach (but this could be wrong) is that if the result exceed some large number for example 1,400,000,000 then return remainder of result modulo
1,400,000,001. Can you explain what this means and how can I do that in Java?
Note that I do not guarantee that above methods are accurate for calculating factorial and combinations. Extra bonus if you can find errors and correct them.
Note that I can only use int or long and if it is unavoidable, can also use double. Other data types are not allowed.
I am not sure who marked this question as homework. This is NOT homework. I wish it was homework and i was back to future, young student at university. But I am old with more than 10 years working as programmer. I just want to practice developing highly optimized solutions in Java. In our times at university, Internet did not even exist. Today's students are lucky that they can even post their homework on site like SO.
Use the multiplicative formula, instead of the factorial formula.
Since its homework, I won't want to just give you a solution. However a hint I will give is that instead of calculating two large numbers and dividing the result, try calculating both together. e.g. calculate the numerator until its about to over flow, then calculate the denominator. In this last step you can chose the divide the numerator instead of multiplying the denominator. This stops both values from getting really large when the ratio of the two is relatively small.
I got this result before an overflow was detected.
combi(61,30) = 232714176627630544 which is 2.52% of Long.MAX_VALUE
The only "bug" I found in your code is not having any overflow detection, since you know its likely to be a problem. ;)
To answer your first question (why did you get zero), the values of fact() as computed by modular arithmetic were such that you hit a result with all 64 bits zero! Change your fact code to this:
public static long fact(int n) {
long rs = 1;
if( n <2) return 1;
for (int i=2; i<=n; i++) {
rs *=i;
System.out.println(rs);
}
return rs;
}
Take a look at the outputs! They are very interesting.
Now onto the second question....
It looks like you want to give exact integer (er, long) answers for values of n and r that fit, and throw an exception if they do not. This is a fair exercise.
To do this properly you should not use factorial at all. The trick is to recognize that C(n,r) can be computed incrementally by adding terms. This can be done using recursion with memoization, or by the multiplicative formula mentioned by Stefan Kendall.
As you accumulate the results into a long variable that you will use for your answer, check the value after each addition to see if it goes negative. When it does, throw an exception. If it stays positive, you can safely return your accumulated result as your answer.
To see why this works consider Pascal's triangle
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
which is generated like so:
C(0,0) = 1 (base case)
C(1,0) = 1 (base case)
C(1,1) = 1 (base case)
C(2,0) = 1 (base case)
C(2,1) = C(1,0) + C(1,1) = 2
C(2,2) = 1 (base case)
C(3,0) = 1 (base case)
C(3,1) = C(2,0) + C(2,1) = 3
C(3,2) = C(2,1) + C(2,2) = 3
...
When computing the value of C(n,r) using memoization, store the results of recursive invocations as you encounter them in a suitable structure such as an array or hashmap. Each value is the sum of two smaller numbers. The numbers start small and are always positive. Whenever you compute a new value (let's call it a subterm) you are adding smaller positive numbers. Recall from your computer organization class that whenever you add two modular positive numbers, there is an overflow if and only if the sum is negative. It only takes one overflow in the whole process for you to know that the C(n,r) you are looking for is too large.
This line of argument could be turned into a nice inductive proof, but that might be for another assignment, and perhaps another StackExchange site.
ADDENDUM
Here is a complete application you can run. (I haven't figured out how to get Java to run on codepad and ideone).
/**
* A demo showing how to do combinations using recursion and memoization, while detecting
* results that cannot fit in 64 bits.
*/
public class CombinationExample {
/**
* Returns the number of combinatios of r things out of n total.
*/
public static long combi(int n, int r) {
long[][] cache = new long[n + 1][n + 1];
if (n < 0 || r > n) {
throw new IllegalArgumentException("Nonsense args");
}
return c(n, r, cache);
}
/**
* Recursive helper for combi.
*/
private static long c(int n, int r, long[][] cache) {
if (r == 0 || r == n) {
return cache[n][r] = 1;
} else if (cache[n][r] != 0) {
return cache[n][r];
} else {
cache[n][r] = c(n-1, r-1, cache) + c(n-1, r, cache);
if (cache[n][r] < 0) {
throw new RuntimeException("Woops too big");
}
return cache[n][r];
}
}
/**
* Prints out a few example invocations.
*/
public static void main(String[] args) {
String[] data = ("0,0,3,1,4,4,5,2,10,0,10,10,10,4,9,7,70,8,295,100," +
"34,88,-2,7,9,-1,90,0,90,1,90,2,90,3,90,8,90,24").split(",");
for (int i = 0; i < data.length; i += 2) {
int n = Integer.valueOf(data[i]);
int r = Integer.valueOf(data[i + 1]);
System.out.printf("C(%d,%d) = ", n, r);
try {
System.out.println(combi(n, r));
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
}
Hope it is useful. It's just a quick hack so you might want to clean it up a little.... Also note that a good solution would use proper unit testing, although this code does give nice output.
You can use the java.math.BigInteger class to deal with arbitrarily large numbers.
If you make the return type double, it can handle up to fact(170), but you'll lose some precision because of the nature of double (I don't know why you'd need exact precision for such huge numbers).
For input over 170, the result is infinity
Note that java.lang.Long includes constants for the min and max values for a long.
When you add together two signed 2s-complement positive values of a given size, and the result overflows, the result will be negative. Bit-wise, it will be the same bits you would have gotten with a larger representation, only the high-order bit will be truncated away.
Multiplying is a bit more complicated, unfortunately, since you can overflow by more than one bit.
But you can multiply in parts. Basically you break the to multipliers into low and high halves (or more than that, if you already have an "overflowed" value), perform the four possible multiplications between the four halves, then recombine the results. (It's really just like doing decimal multiplication by hand, but each "digit" is, say, 32 bits.)
You can copy the code from java.math.BigInteger to deal with arbitrarily large numbers. Go ahead and plagiarize.

combination of combination java

I need to find combination of combination in JAVA.
I have for instance 6 students in class. Out of them, I need to create combination of 4 people in group, and for each group I can choose an intimate group of 2.
I have to make sure that there are no doubles (order does not matter).! and need to print the 4 people group.
However, this is the hard part:
So defining students with numbers:
If I print out 1234 as one of the combinations, I can't print out1256 as well, since 12 appears both in 1234 and in 1256.
How can I write it in Java?
EDITED
output of ([1,2,3,4,5],3,2) will be:
Combinations without repetition (n=5, r=3)
{1,2,3} {1,2,4} {1,2,5} {1,3,4} {1,3,5} {1,4,5} {2,3,4} {2,3,5} {2,4,5} {3,4,5}
deleting repeating groups of 2 elements, will leave me only:
{1,2,3} {1,4,5} (i deleted groups that have combinations of 12,13,23,45,14,15 since they already appear in the first two that I have found.
Ok, here's the simple emulation of the process you described. But I use binary numbers to present set, it makes manipulations easier. For example, number 19 is 10011 in binary form: it means students 0, 3 and 4 are selected (there're 1's in those positions).
A little helper first.
// return all subsets of 'set', having size 'subsetSize'
Set<Integer> allSubsets(int set, int subsetSize) {
Set<Integer> result = new HashSet<Integer>();
if (subsetSize == 0) {
result.add(0);
return result;
}
if (set == 0) {
return result;
}
// check if 1st element is present
if (set % 2 == 1) {
// use 1st element, one less element to collect
for (Integer i : allSubsets(set / 2, subsetSize - 1)) {
result.add(i * 2 + 1);
}
}
// not use 1st element
for (Integer i : allSubsets(set / 2, subsetSize)) {
result.add(i * 2);
}
return result;
}
And main program. Suggestions are welcome.
int N = 5;
int M = 3;
int Z = 2;
List<Integer> result = new ArrayList<Integer>();
// get all groups of M elements from 'wholeSet'
int wholeSet = (1 << N) - 1;
for (int s : allSubsets(wholeSet, M)) {
// Check all subsets of 'Z' elements from set 's'
boolean valid = true;
for (int t : allSubsets(s, Z)) {
// check if this Z-element subset already was used
for (int past : result) {
// check if 't' is subset of 'past' set
if ((past|t) == past) {
valid = false;
break;
}
}
if (!valid) {
break;
}
}
if (valid) {
// none of Z-element subsets of 's' were used before
result.add(s);
}
}
But it may require improvements (like memoization) for big inputs. But for now, since you don't say what kind of input you expect, I assume this is good enough.
Imagine you have a Student object with an equals comparing their Primarykey. In your example, student 1 will return 1, 2 will return 2 and so on.
Put them all in the set, this will ensure that there will be no double.
Iterate though the set by 4 then by 2 and will return you your desired result.

Categories