How to find closest to zero number in a pair of numbers? - min

Of course, there is always:
if abs(x) < abs(y) { return x; } else { return y; }
But I wonder if there is more optimal solutions to the problem.

Try with the following
function(a,b) {
return Math.min(a, b)
}

Related

If else on Mono if empty or has value

This is the sample code
repo1.findById( id )
.map( p -> {
if( p == null ){
return repo2.findById( id ).flatMap( g -> {
g.setValue("some value");
return g;
});
}
else{
return repo3.findById( id ).flatMap( h -> {
h.setValue("some value");
return h;
});
}
});
Any better way to do this ?. If else inside flat map does not look neat to me.
The idiomatic approach would be to use the switchIfEmpty() operator.
You would only proceed to use the call to repo3 if repo1 actually returns a result.
If not data matches repo1.findById(id), then this call would return an empty result, not null.
To cover this case, use switchIfEmpty().
public Mono<Data> load(String id){
return repo1.findById(id)
.flatMap(p -> {
return repo3.findById(id)
.flatMap(h -> {
h.setValue("some value");
return h;
});
})
.switchIfEmpty(repo2.findById(id)
.flatMap(g -> {
g.setValue("some value");
return g;
}));
}

Time/Space-Complexity method

I got a question to answer with the best complexity we can think about.
We got one sorted array (int) and X value. All we need to do is to find how many places in the array equals the X value.
This is my solution to this situation, as i don't know much about complexity.
All i know is that better methods are without for loops :X
class Question
{
public static int mount (int [] a, int x)
{
int first=0, last=a.length-1, count=0, pointer=0;
boolean found=false, finish=false;
if (x < a[0] || x > a[a.length-1])
return 0;
while (! found) **//Searching any place in the array that equals to x value;**
{
if ( a[(first+last)/2] > x)
last = (first+last)/2;
else if ( a[(first+last)/2] < x)
first = (first+last)/2;
else
{
pointer = (first+last)/2;
count = 1;
found = true; break;
}
if (Math.abs(last-first) == 1)
{
if (a[first] == x)
{
pointer = first;
count = 1;
found = true;
}
else if (a[last] == x)
{
pointer = last;
count = 1;
found = true;
}
else
return 0;
}
if (first == last)
{
if (a[first] == x)
{
pointer = first;
count = 1;
found = true;
}
else
return 0;
}
}
int backPointer=pointer, forwardPointer=pointer;
boolean stop1=false, stop2= false;
while (!finish) **//Counting the number of places the X value is near our pointer.**
{
if (backPointer-1 >= 0)
if (a[backPointer-1] == x)
{
count++;
backPointer--;
}
else
stop1 = true;
if (forwardPointer+1 <= a.length-1)
if (a[forwardPointer+1] == x)
{
count++;
forwardPointer++;
}
else
stop2 = true;
if (stop1 && stop2)
finish=true;
}
return count;
}
public static void main (String [] args)
{
int [] a = {-25,0,5,11,11,99};
System.out.println(mount(a, 11));
}
}
The print command count it right and prints "2".
I just want to know if anyone can think about better complexity for this method.
Moreover, how can i know what is the time/space-complexity of the method?
All i know about time/space-complexity is that for loop is O(n). I don't know how to calculate my method complexity.
Thank a lot!
Editing:
This is the second while loop after changing:
while (!stop1 || !stop2) //Counting the number of places the X value is near our pointer.
{
if (!stop1)
{
if ( a[last] == x )
{
stop1 = true;
count += (last-pointer);
}
else if ( a[(last+forwardPointer)/2] == x )
{
if (last-forwardPointer == 1)
{
stop1 = true;
count += (forwardPointer-pointer);
}
else
forwardPointer = (last + forwardPointer) / 2;
}
else
last = ((last + forwardPointer) / 2) - 1;
}
if (!stop2)
{
if (a[first] == x)
{
stop2 = true;
count += (pointer - first);
}
else if ( a[(first+backPointer)/2] == x )
{
if (backPointer - first == 1)
{
stop2 = true;
count += (pointer-backPointer);
}
else
backPointer = (first + backPointer) / 2;
}
else
first = ((first + backPointer) / 2) + 1;
}
}
What do you think about the changing? I think it would change the time complexity to O(long(n)).
First let's examine your code:
The code could be heavily refactored and cleaned (which would also result in more efficient implementation, yet without improving time or space complexity), but the algorithm itself is pretty good.
What it does is use standard binary search to find an item with the required value, then scans to the back and to the front to find all other occurrences of the value.
In terms of time complexity, the algorithm is O(N). The worst case is when the entire array is the same value and you end up iterating all of it in the 2nd phase (the binary search will only take 1 iteration). Space complexity is O(1). The memory usage (space) is unaffected by growth in input size.
You could improve the worst case time complexity if you keep using binary search on the 2 sub-arrays (back & front) and increase the "match range" logarithmically this way. The time complexity will become O(log(N)). Space complexity will remain O(1) for the same reason as before.
However, the average complexity for a real-world scenario (where the array contains various values) would be very close and might even lean towards your own version.

What is time complexity of below function?

int sumOfDigits(int n)
{
if(n<=9)
return n;
else
{
int r=0;
while(n!=0)
{
r=r+n%10;
n=n/10;
}
sumOfDigits(r);
}
}
This function finds sum of digits of a number till it becomes less than 10.
e.g.if n=12345
then output=6
as 1+2+3+4+5=15,
again 1+5=6.
I guess what you try to achieve is something like this:
class St2 {
static int sumOfDigits(int n) {
if(n<=9) {
return n;
}
else {
int d = n%10;
return d + sumOfDigits((n-d)/10);
}
}
public static void main(String[] args) {
System.out.println(St2.sumOfDigits(345678));
}
}
This would sum the digits. The complexity is linear in the number of digits thus logarithmic in the scale of the input number.

I am getting an error (variable y might not have been initialised in the if's in the loop. How to solve that?

import java.util.Scanner;
public class RPS
{
public void show()
{
int i;
System.out.println("1 - Rock 2 - Paper 3 - Scissor");
Scanner in = new Scanner(System.in);
i = in.nextInt();
double x = Math.random();
int y;
if(x<=0.33)
{
y=1;
}
else if(x>0.33 && x<0.67)
{
y=2;
}
else if(x>=0.67)
{
y=3;
}
for(;;)
{
if(i==y)
System.out.println("It's a draw!");
else if(i==1 && y==2)
System.out.println("Computer wins!");
else if(i==1 && y==3)
System.out.println("You win!");
else if(i==2 && y==1)
System.out.println("You win!");
else if(i==2 && y==3)
System.out.println("Computer wins!");
else if(i==3 && y==1)
System.out.println("Computer wins!");
else if(i==3 && y==2)
System.out.println("You win!");
else
System.out.println("Error!");
}
}
}
Whats wrong?
It gives an error that variable y might not have been intialised in the if's in the for loop.
I have assigned a value to y in the previous if-else section.
so why isnt it getting intialised?
javac is not smart enough to realize that the way your conditions are constructed, one of them will always be true.
You can rewrite your if-statements to make javac realize one branch will always be triggered:
int y;
if(x<=0.33)
{
y=1;
}
else if(x>0.33 && x<0.67)
{
y=2;
}
else // This only triggers when x >= 0.67, so no need to check
{
y=3;
}
Now javac sees that if the first two don't trigger, the last will, so y will always have a value.
You can alternatively add an else branch with an error, in case someone breaks the conditions:
int y;
if(x<=0.33)
{
y=1;
}
else if(x>0.33 && x<0.67)
{
y=2;
}
else if(x >= 0.67)
{
y=3;
}
else
{
// This should never happen
throw new IllegalArgumentException("Something's gone terribly wrong for " + x);
}
This also compiles, and if someone later decides to skew the numbers and turns the first condition into x <= 0.2 but forgets to update the other condition, you'll get an exception at runtime.

"Nested functions are disabled, use -fnested-functions to re-enable"

I want to use this code (from my last question (thanks Adam)),
bool AllDigitsIdentical(int number)
{
int lastDigit = number % 10;
number /= 10;
while(number > 0)
{
int digit = number % 10;
if(digit != lastDigit)
return false;
number /= 10;
}
return true;
}
but the compiler just says in the second line at } :
Nested functions are disabled, use -fnested-functions to re-enable
What can I do in my case? I have no plan…
Thanks and sorry for my bad English.
You wouldn't happen to have something like:
- (void) someMethod
{
bool AllDigitsIdentical(int number)
{
int lastDigit = number % 10;
number /= 10;
while(number > 0)
{
int digit = number % 10;
if(digit != lastDigit)
return false;
number /= 10;
}
return true;
}
}
That is, you have a function declared within a method's scope of implementation (though the same problem would occur for a function declared within a function).
In short, don't do that. It isn't supported and the means via which GCC implements it is considered to be a bit of a security hole (IIRC).
Move it outside:
bool AllDigitsIdentical(int number)
{
int lastDigit = number % 10;
number /= 10;
while(number > 0)
{
int digit = number % 10;
if(digit != lastDigit)
return false;
number /= 10;
}
return true;
}
- (void) someMethod
{
.... call the function here ....
}
this function looks fine, is it possible you missed a closing } in the code before this function ?
You probably pasted that into a method or into your main function! Make sure that that chuck of code is put OUTSIDE any other blocks of code.
so if you have main here:
int main(int argc, char **argv){
//blah
}
make sure that you put that code above or below it like so:
bool AllDigitsIdentical(int number){
//blah
}
do NOT put it inbetween the { or } of the main function (or any other method)