Other [quiz] Compare signs

Erel

B4X founder
Staff member
Licensed User
Longtime User
We want to check whether the two values are either non-negative or negative.

B4X:
If (Func1 >= 0 And Func2 >= 0) Or (Func1 < 0 And Func2 < 0) Then
 Log("Good!")
Else
 Log("Bad")
End If

Sub Func1 As Int
'...
End Sub
Sub Func2 As int
'...
End Sub

How can we avoid calling each sub twice? Without adding any variable.
 

Star-Dust

Expert
Licensed User
Longtime User
B4X:
If (Func1 * Func2 >= 0) Then
 Log("Good!")
Else
 Log("Bad")
End If

Or
B4X:
If (Func1 / Func2 >= 0) Then
 Log("Good!")
Else
 Log("Bad")
End If
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
my try:

B4X:
If (func1 < 0) = (func2 < 0) Then
       Log("good")
Else
       Log("bad")
End If
That was my solution as well.

B4X:
If (Func1 * Func2 >= 0) Then
 Log("Good!")
Else
 Log("Bad")
End If

Or
B4X:
If (Func1 / Func2 >= 0) Then
 Log("Good!")
Else
 Log("Bad")
End If
This solution is not 100% correct.

It has two problems:
- Not correct when one of the subs returns 0.
- Multiplying two large positive numbers will overflow and result with a negative value.
 
Upvote 0

Guardian17

Active Member
Licensed User
Longtime User
My try, assuming "<>" means "not equal to" (though I'm not at my B4A computer to try it):
B4X:
If (Func1 <> 0 And  Func2 <> 0) Then
 Log("Good!")
Else
 Log("Bad")
End If
 
Upvote 0

RandomCoder

Well-Known Member
Licensed User
Longtime User
I love these quizzes that @Erel presents every now and then. I'd have done Func1 * Func2 as already suggested by @Star-Dust but I see that Erel has found a potential flaw in doing it this way.
So how about just utilising the sign bit....
B4X:
If Bit.Xor(Func1,Func2) >= 0 Then
   Log("Good")
Else
   Log("Bad")
End If
It'll be a first if I have the answer right! ;)
 
Upvote 0

RandomCoder

Well-Known Member
Licensed User
Longtime User
I hate to rain on your parade @RandomCoder, but @JordiCP already offered that in the second post
Damn it I missed the spoiler button :oops:
Ah well at least I'm happy in the knowledge that I've not cheated. :)
I see that Erel has another possible solution that also works for floating point numbers. I'll have to put my thinking cap on again!

EDIT... I have just seen that the solution has already been given.
B4X:
If (func1 < 0) = (func2 < 0) Then
       Log("good")
Else
       Log("bad")
End If
I really should give more time to read posts properly :oops:
 
Last edited:
Upvote 0
Top