Return set of numbers in recursion - java

following code searches for one zero point of a polynomial function. It uses recursion technique:
private static double funktion(int[] koef, double x){
return koef[0] * Math.pow(x,4) + koef[1] * Math.pow(x,3) +
koef[2] * Math.pow(x,2) + koef[3]*x + koef[4];
}
private static double nullstelle(double a, double b, int[] koef){
double middle = (a + b)/2;
double result = middle;
if(Math.abs(a-b) > 0.00001){
double sin = funktion(koef, middle);
if(sin == 0){
result = middle;
}else if(Math.signum(funktion(koef, a)) ==
Math.signum(funktion(koef, middle))){
result = nullstelle(middle, b, koef);
}else{
result = nullstelle(a, middle, koef);
}
}
return result;
}
I am wondering how to return all zero points. My ideas is to use an array but I am not sure how to do that. Any ideas?
I am not allowed to use anything else than arrays (e.g. hash tables or sets are not allowed)

I would pass in a Collection such as a HashSet to your functions and put all the numbers you discover into it.
As you say you can only use arrays, then you know the maximum number of zero-points that can be found, presumably, so create an array of that size, assigned NaN to every element, then pass in that array and the maximum current index of it to every function call. You will need to return the new size of the array as the result so that you always know how many numbers have been found.

Here is some explanation as this is homework:
1) We need to create an array of the data type you will be using to store zero points. My guess is double.
2) The array will need some type of starting size, lets say 10 for the sake of discussion
3) In the nullstelle method we will add an element to the array created in step 1
4) If the array has size LIMIT -1 we copy the array to a new array with size equal to LIMIT * 2
5) We now return this array.
If it needs to be sorted we can walk over the list utilizing whatever sort technique is to be decided on.

First of all your solution as it stands suffers from one of the same problems as your previous question in that you can't guarantee that you'll get the zero calculation exactly correct. Unfortunately, this time you can't use the simple solution of checking that a and b have opposite signs because, for an arbitrary polynomial, a zero need not imply the function crosses the y = 0 line e.g. y = x^4.
Anyway, to answer your question:
create an array of size 4 of type Double. Use null to denote that an array slot is empty. As your function is a quartic, there is a maximum of four zeroes.
pass the array as a parameter in your function.
when you have detected a zero, fill in the first free slot left in the array with the value of the zero.
No actual Java provided because this is homework.

Math.pow is a very expensive function. You can avoid it entirely using nested expressions. (And its shorter)
private static double funktion(int[] koef, double x){
return (((koef[0] * x + koef[1]) * x +
koef[2]) * x + koef[3]) * x + koef[4];
}

public double[] returnOnlyZeros(int[] whatever1, double whatever2) {
double[] result = new double[/*put the size here*/];
// your math here
// put the values into the result array
return result;
}

Related

Can't create a method to make visible a words letters randomly

I am trying to create a method to make some of the word's letters visible and other ones *. This is actually a simple word guessing game. I ask the user to choose whether they want to give an answer or request a letter. For example if the answer is "ball" and user decides to request a word, ball should turn into "*a**".
That is the method I have came up with:
public static void showALetter(String correctAnswer) {
int randomLetterIndex = (int) Math.random() % (correctAnswer.length());
for (int i = 0; i < correctAnswer.length(); i++) {
if (i == randomLetterIndex) {
System.out.print(correctAnswer.charAt(randomLetterIndex));
} else {
System.out.print("*");
}
}
}
It only shows the first letter of the correct answer at every single request. What should I do ?
Math.random() returns a double with a value between zero and one (technically [0.0, 1.0) written as a mathematical interval). This is not what you want, so you instead need to use the newer java.util.Random class:
Random random = new Random();
int randomLetterIndex = random.nextInt(correctAnswer.length());
The random.nextInt(int limit) method will return a value from zero (inclusive) to limit (exclusive) which is what you need here for your puproses.
If you're going to use random numbers over and over again, then create your Random instance as a static class member and have your methods refer to that, so that you only create the object once.
Math.random() returns a number from zero to one. So, your randomLetterIndex will always be zero. Use this instead.
(int) (Math.random() * correctAnswer.length())
This will give a random number between 0 and correctAnswer.length() - 1.
Math.random() returns a double higher or equal than 0 and less then 1, (int) Math.random() will always return 0.
Use
(int)(Math.random() * correctAnswer.length())
The modulo is useless here, this way you always hit inside the given string as (int) cast returns the floor value so the result will never be equal or higher than correctAnswer.length().

Finding three numbers whose sum is divisible by a given number

How can I search through an array and find every combination of three values whose sum is divisible by a given number(x) in java.
In other words, every combination where (n1+n2+n3) % x == 0.
I know this would be a simple solution using a triple for loop but I need something with a time complexity of O(N^2).
Any idea's?
1 - Hash every (element % x) in the list.
2 - Sum every pair of elements in the list (lets call the sum y) and do modded_y = y % x.
3 - Check if x - modded_y is in the hash table. If it is and it's not one of the other 2 numbers then you found a possible combination. Keep iterating and hashing the combinations you found so that they don't repeat.
This is called a meet in the middle strategy.
It's complexity is O(n + (n^2 * 1)) = O(n^2)
I will call the given array A1.
1) create two structs
struct pair{
int first;
int second;
bool valid;
}
struct third{
int value;
int index;
}
2) using a nested loop, initialize an array B1 of all possible Pairs.
3) Loop through B1. if (A1[B1[i].first] + A1[B1[i].second])%x==0 then set B1[i].valid to true
4) create an array A3 of Thirds that stores the index and value of every element from A1 that is divisible by x.
5) using a nested loop, go through each element of A3 and each element of B1. If B1.valid = true
print A1[B1[i].first] and A1[B1[i].second] with an element from A1[A3.index].
that should give you all combinations without using any triple loops.

sort array positive negative distance value

I have an array of distances calculated using (distance to) method
which contain both negative and positive values looks like this
float num[] = {-123.81944, 34.56723, -133.40782};
when trying to use
Arrays.sort(num);
the result is
-123.81944
-133.40782
34.56723
which is incorrect since -133.40782 location is closer than -123.81944
how can i sort the array to result like this
-133.40782
-123.81944
34.56723
If you want to use float as data type, then you should declare the array as follows. Otherwise, you can use double as data type to avoid adding a suffix f to the numbers.
float[] num = {-123.81944f, 34.56723f, -133.40782f};
// or, double[] num = {-123.81944, 34.56723, -133.40782};
Arrays.sort(num);
System.out.println(Arrays.toString(num));
Output
[-133.40782, -123.81944, 34.56723]
See a live demo.
Suppose there is an arrayA containing negative numbers, zero and positive numbers. You need to sort them, how would you do it. Ofcourse you would consider the natural ordering and would sort as negative numbers followed by zero followed by positive numbers. This is what Arrays.sort() does.
If you wish to sort the distances from a reference point , I feel your expected result is not correct. If we consider a line, a reference point and then on its left the negative distance and on its riggt the positive distance then sorting should be based on absolute value.
Your business requirement is to do a custom sorting. For any sorting to work you need to have a logic for comparision. For this java provides Comparator. You need to implement your business logic based comparision for sorting. [HINT : while comparing you can just compare the absolute value, Math.abs may help]
Floats end with f so apending f with each of your array elements is better.
For reference you can see another related question
How to sort an array of ints using a custom comparator?
For me, with a standard Java JRE it works like (you) expected, but I had to turn the numbers in float literals. Otherwise it did not compile:
float num[] = new float[] {-123.81944f, 34.56723f, -133.40782f};
Arrays.sort(num);
for (int i = 0; i < num.length; i++) {
System.out.print(" " + num[i]);
}
prints -133.40782 -123.81944 34.56723

Horner's recursive algorithm for fractional part - Java

I am trying to create a recursive method that uses Horner's algorithm to convert a fractional number in base n to base 10. I've searched here and all over but couldn't find anywhere that dealt with the fractional part in detail. As a heads up, I'm pretty weak in recursion as I have not formally learned it in my programming classes yet, but have been assigned it by another class.
I was able to make a method that handles the integer part of the number, just not the fractional part.
I feel like the method I've written is fairly close as it gets me to double the answer for my test figures (maybe because I'm testing base 2).
The first param passed is an int array filled with the coefficients. I'm not too concerned with the order of the coefficients as I'm making all the coefficients the same to test it out.
The second param is the base. The third param is initialized to the number of coefficients minus 1 which I also used for the integer part method. I tried using the number of coefficients, but that steps out of the array.
I tried dividing by the base one more time as that would give me the right answer, but it doesn't work if I do so in the base case return statement or at the end of the final return statement.
So, when I try to convert 0.1111 base 2 to base 10, my method returns 1.875 (double the correct answer of 0.9375).
Any hints would be appreciated!
//TL;DR
coef[0] = 1; coef[1] = 1; coef[2] = 1; coef[3] = 1;
base = 2; it = 3;
//results in 1.875 instead of the correct 0.9375
public static double fracHorner(int[] coef, int base, int it) {
if (it == 0) {
return coef[it];
}
return ((float)1/base * fracHorner(coef, base, it-1)) + coef[it];
}
Observe that fracHorner always returns a value at least equal to coef[it] because it either returns coef[it] or something positive added to coef[it]. Since coef[it] >= 1 in your tests, it will always return a number greater than or equal to one.
It's relatively easy to fix: divide both coef[it] by base:
public static double fracHorner(int[] coef, int base, int it) {
if (it == 0) {
return ((double)coef[it])/base;
}
return (fracHorner(coef, base, it-1) + coef[it])/base;
}

How to alter a float by its smallest increment in Java?

I have a double value d and would like a way to nudge it very slightly larger (or smaller) to get a new value that will be as close as possible to the original but still strictly greater than (or less than) the original.
It doesn't have to be close down to the last bit—it's more important that whatever change I make is guaranteed to produce a different value and not round back to the original.
(This question has been asked and answered for C, C++)
The reason I need this, is that I'm mapping from Double to (something), and I may have multiple items with the save double 'value', but they all need to go individually into the map.
My current code (which does the job) looks like this:
private void putUniqueScoreIntoMap(TreeMap map, Double score,
A entry) {
int exponent = 15;
while (map.containsKey(score)) {
Double newScore = score;
while (newScore.equals(score) && exponent != 0) {
newScore = score + (1.0d / (10 * exponent));
exponent--;
}
if (exponent == 0) {
throw new IllegalArgumentException("Failed to find unique new double value");
}
score = newScore;
}
map.put(score, entry);
}
In Java 1.6 and later, the Math.nextAfter(double, double) method is the cleanest way to get the next double value after a given double value.
The second parameter is the direction that you want. Alternatively you can use Math.nextUp(double) (Java 1.6 and later) to get the next larger number and since Java 1.8 you can also use Math.nextDown(double) to get the next smaller number. These two methods are equivalent to using nextAfter with Positive or Negative infinity as the direction double.
Specifically, Math.nextAfter(score, Double.MAX_VALUE) will give you the answer in this case.
Use Double.doubleToRawLongBits and Double.longBitsToDouble:
double d = // your existing value;
long bits = Double.doubleToLongBits(d);
bits++;
d = Double.longBitsToDouble(bits);
The way IEEE-754 works, that will give you exactly the next viable double, i.e. the smallest amount greater than the existing value.
(Eventually it'll hit NaN and probably stay there, but it should work for sensible values.)
Have you considered using a data structure which would allow multiple values stored under the same key (e.g. a binary tree) instead of trying to hack the key value?
What about using Double.MIN_VALUE?
d += Double.MIN_VALUE
(or -= if you want to take away)
Use Double.MIN_VALUE.
The javadoc for it:
A constant holding the smallest positive nonzero value of type double, 2-1074. It is equal to the hexadecimal floating-point literal 0x0.0000000000001P-1022 and also equal to Double.longBitsToDouble(0x1L).

Categories

Resources