Get maximum from absolute values returning signed value - vb.net

Supposing I have a class
Public Class Foo
Property fooProp1 as Single
Property fooProp2 as Single
Property fooProp3 as Single
End Class
to find the absolut maximum of a property (which contains positive or negative values) in a Collection(Of Foo) I can do:
Collection.Max(Function(x As foo) Math.Abs(x.fooProp1))
and it returns the greater absolute value WITHOUT sign.
The question is how can I do to get the number WITH sign?
Thanks in advance.
RG

Math.Abs will always return an unsigned value (the actual meaning of Absolute).
The get the value of a property you need only to READ it.
To get a MAX or MIN, you MUST compare values, like this:
dim x as integer = foo.property
dim y as integer = last_foo_property (or anything else)
Minimum = Math.Min(x,y)
Maximum = Math.Max(x,y)
But, if are trying to get the lower and upper values of a collection, you may utilize:
MaxValue = Collection.Find(Collection, Function(Z) (Z > BiggerValue))
MinValue = Collection.Find(Collection, Function(Z) (Z < LowerValue))
where these values are gotten before the call.
Another way is to make a SORT and get the first and the last values...

Collection.Select(Function(x) a.fooProp1).Aggregate(Function(a, b)
If(Math.Abs(a) > Math.Abs(b), a, b))

Related

Spyne: Integer Validation how can I set minimum digit limit?

I want to add validation for an Integer, that its minimum digit value is 5 and maximum digit value is 20
For Integer I have set following validations
Integer(min_occurs=1, gt=9999, max_str_len=20, nillable=False)
I just put work around for min_str_len, I do not find any attribute for min_str_len.
Instead of work around is there any default way ?
You can subclass Integer type (or another one that fits best) and implement validate_native method.
Example for prime number check from docs:
from math import sqrt, floor
class Prime(UnsignedInteger):
"""Custom integer type that only accepts primes."""
#staticmethod
def validate_native(cls, value):
return (
UnsignedInteger.validate_native(value) and \
all(a % i for i in xrange(2, floor(sqrt(a))))
)
Source: http://spyne.io/docs/2.10/manual/05-02_validation.html#a-native-validation-example

Need Explanation of VB.Net Code

In the below example code from a tutorial, I understand how the majority of it works. There are a few things I do not understand, though. Please help me to understand the purpose of some of these characters and the purpose of them. I will explain below what I don't understand.
Module paramByref
Sub swap(ByRef x As Integer, ByRef y As Integer)
Dim temp As Integer
temp = x ' save the value of x
x = y ' put y into x
y = temp 'put temp into y
End Sub
Sub Main()
' local variable definition
Dim a As Integer = 100
Dim b As Integer = 200
Console.WriteLine("Before swap, value of a : {0}", a)
Console.WriteLine("Before swap, value of b : {0}", b)
' calling a function to swap the values '
swap(a, b)
Console.WriteLine("After swap, value of a : {0}", a)
Console.WriteLine("After swap, value of b : {0}", b)
Console.ReadLine()
End Sub
End Module
What I don't understand is why the need for x, y, and temp. why not just keep declaration of a and b and swap the values?
Also, on the Console.WriteLine, I understand the {0} is an nth reference or index position, but the comma suggests to output something else. Is it saying to output the value of a in the 0 index? If so, there can only be one zero index, so why does the next line reference the value of the zero index? Or am I all wrong on this? Any explanation would be greatly appreciated...please dumb your answer down for this newbie.
The reason for x, y, and temp is to demonstrate how to do swapping. Your question asks
why not just keep declaration of a and b and swap the values
In this situation where you aren't doing any incrementing, sure you could just afterward say b = 100 and a = 200 but if you were doing this say in a loop and constantly swapping them, if you were to do
a = b
b = a
you would have a=100, b=100 because you set the value of b = a which is 100, then set a as the same value so it is still 100. That's why you need the temp value.
With regards to the console.writeLine, you are absolutely correct that it is indexing the 0th index, so in the first example, it is a, however it can be reused in the next line, because it is a totally separate line of code. Each of those console.writeLines can exist independently, so the values are indexed on a line by line basis
You need a temp to store the value from the first var so that you do not lose it when you overwrite it with the value from the second var. Once the second var's value has been transferred into the first var, the value stored in temp (from the original first var) can be transferred into the second var (overwriting the original value).
This is a common method when creating custom sorting routines that shuffle the values from various positions and ranks in an array around.
a and b are variables that are only visible in method Main(). They cannot be accessed from a different method. On the other hand, x, y, and temp are variables that are only visible in method swap(). More precisely, x and y are the method's parameters. The keyword ByRef means that the parameters are references to variables. I.e. when you call swap(a, b), x becomes a reference to variable a and y becomes a reference to variable b. You can work with references like with other variables. The difference is that when you change x in swap(), a in Main will change accordingly.
The Console.WriteLine() method takes a string parameter and an arbitrary number of additional parameters. The {0} is an index into the list of those additional parameters. E.g. Console.WriteLine("{0} {1} {2}", 100, 200, 300) would output 100 200 300. and Console.WriteLine("{2} {1} {0}", 100, 200, 300) would output 300 200 100.

Pig: Absolute value of an integer

I would like to give back the absolute value of an integer field but does not work.
How i can do it correctly?
y = foreach x generate
ABS(quantity);
thanks
IntAbs is the solution that works for integer also not only for expressions

Algorithm for max and min? (Objective-C)

This is a part of a book I'm reading to learn Objective-C.
The following defines a macro called MAX that gives the maximum of two
values: #define MAX(a,b) ( ((a) > (b)) ? (a) : (b) )
And then there are some exercises in the book that asks the reader to define a macro (MIN) to find the minimum of two values and another that asks to define a macro called MAX3 that gives the maximum of 3 values. I think these two definitions will look similar to MAX, but I don't understand how the MAXformula finds the maximum value. I mean if I just did this
int limits = MAX (4,8)
It'll just assign limits the value of 8. What does that have to do with finding a variable's maximum value?
I think you are confusing value and variable. The macro example you listed expands to a comparison between two values and returns the greater of the two values (i.e. which is greater, a or b). So you are right, int limits = MAX(4,8) just assigns 8 to limits and has nothing to do with finding the maximum value you can store in limits.
The header limits.h defines many values like INT_MAX that will tell you information about the min/max values of variable types on your system.
To break it apart:
The declaration:
#define MAX(a,b)
If a is greater than b, use a else use b:
( ((a) > (b)) ? (a) : (b) )
Then to create a MIN expression, use a similar form:
#define MIN(a,b) ( ((a) < (b)) ? (a) : (b) )
^
Then to create a MAX3 expression, you can combine them:
#define MAX3(a,b,c) ( MAX(a, MAX(b,c)) )
Specifically, this macro's intended to be used with scalars (C builtins) which can be compared using < or >. If you passed an objc variable, it would result in comparison of addresses and MAX would return the one with the higher address (it would be very rare if you actually wanted to compare addresses of objc instances).
Also note that this is the classic example of how macros can bite you. With macros, the preprocessor simply expands (textual copy/paste) the parameters in place, so: int limits = MAX (4,8) literally expands to int limits = (4 > 8 ? 4 : 8). If you write MAX(x,++y), then y will be incremented twice if y is greater than or equal to x because it expands to: int limits = (x > ++y ? x : ++y).
generally, you will use a MAX() or MIN() macro to get whichever is the higher/lower of a pair of variables, or of a variable and a constant, or even a pair of macro constants or other non-literal constant expressions. you generally won't supply 2 literal constants as you have done in your question.
Algorithm for max (Objective-C)
// get max value
- (float)maxValue:(NSArray *)arrValue
{
float maxValue = 0.0;
for (NSString *value in arrValue) {
float compareValue = [value floatValue];
if (compareValue > maxValue) {
maxValue = compareValue;
}
}
return maxValue;
}
NSArray *number=[NSArray arrayWithObjects:[NSNumber numberWithFloat:57.02], [NSNumber numberWithFloat:55.02], [NSNumber numberWithFloat:45.02], nil];
NSLog(#"%f", [self maxValue:number]);
result 57.020000

What is one of the more efficient ways to search for a string in an array and get its index?

Given an enum similar to this:
Friend Enum TestValue As Int32
tstNotSet = -1
tstA = 0
tstB = 1
tstC = 2
tstD = 3
tstE = 4
tstF = 5
tstG = 6
tstH = 7
tstI = 8
tstJ = 9
tstK = 10
tstL = 11
tstM = 12
End Enum
And an Array similar to this:
Dim TestValues() As String = {"A", "B", "C", "D", "E", "F", "G",
"H", "I", "J", "K", "L", "M"}
And a string is fed in as input in some form similar to (assume it is already stored to a variable):
Dim tmpInput As String = "ADFGHJLM"
And a Sub/Method in another arbitrary class that takes in as input an array of one of more of the Enums from TestValue, based on the input string tmpInput. Basically, I want to walk the tmpInput variable, and for each character, map out its equivalent member in the Enum, so that I can pass it to this Sub in the other object. The string array TestValues and the Enum TestValue (yes, the names could be done better, but don't let that bother you too much) are laid out to match each other explicitly.
So I basically want to search the array for the matching letter, and use its index offset to know which Enum I want to map to that letter. My current code uses a large Select Case statement, but that's just ugly (although, performance tests show it to be rather speedy, even in the debug build).
The purpose of this test case is to provide an example of a mechanism I use in a project I'm working on. In this project, objects have a ReadOnly property that returns a string of letters composed from TestValues. It also has a Sub that accepts an array of one or more Enums from TestValue that sets a private member in the object that is used by the aforementioned ReadOnly property. The purpose was to store an array of smaller integer values (the Enums) rather than an array of strings for the object's internal functionality. So I had to create a way to map back and forth between the string array and the enum.
Yes, it's easily doable with the many different collections available in .NET, but I feel those are too heavyweight for my needs, as many of my objects have enums as small as two values, hence, arrays. I borrowed the trick from a similar example used in C to be able to select a string from a const array based on an index offset.
Anyways, as I've discovered, searching arrays in VB.NET is not trivial. There is apparently no simple command like TestValues.GetIndex(tmp(i)), where tmp(i) is a variable holding a single character (String, not Char), that would return say, '8' if tmp(i) was set to 'I'. Instead, methods like Array.FindIndex require using delegates/predicates, something I haven't fully wrapped my head around just yet (they seem like function pointers from C).
So what's the best way, other than constantly looping over the array for every input character, to locate the index offset based on the stored value? Is the method I highlight sane or insane (hint: it's a hold-over from VBA code)? Is there a more efficient way?
Oh, and yes, the ReadOnly property does check that the internal members are NOT set to tstNotSet before attempting to read from the TestValues array. That's why that Enum member exists.
Thanks!
EDIT: Hopefully this doesn't muddle the explanation up too much, but here's an example, as simplified as I can get it, of how the look up currently operates using the array, enum, and input string as defined above:
Dim n As Int32 = 0
Dim Foobar(0 to 12) As TestValue
For Each s As String In tmpInput
Select Case Char.ToUpper(CChar(s))
Case CChar(TestValues(tstA))
Foobar(n) = tstA
n += 1
Case CChar(TestValues(tstB))
Foobar(n) = tstB
n += 1
Case CChar(TestValues(tstC))
Foobar(n) = tstC
n += 1
Case CChar(TestValues(tstD))
Foobar(n) = tstD
n += 1
Case CChar(TestValues(tstE))
Foobar(n) = tstE
n += 1
Case CChar(TestValues(tstF))
Foobar(n) = tstF
n += 1
Case CChar(TestValues(tstG))
Foobar(n) = tstG
n += 1
Case CChar(TestValues(tstH))
Foobar(n) = tstH
n += 1
Case CChar(TestValues(tstI))
Foobar(n) = tstI
n += 1
Case CChar(TestValues(tstJ))
Foobar(n) = tstJ
n += 1
Case CChar(TestValues(tstK))
Foobar(n) = tstK
n += 1
Case CChar(TestValues(tstL))
Foobar(n) = tstL
n += 1
Case CChar(TestValues(tstM))
Foobar(n) = tstM
n += 1
End Select
Next
As noted in my comment to Jon Skeet, this construct, along with the rest of the Object's components, executes 100,000 times in a profiling loop in ~570ms (rough average of 3-5 runs).
Exchanging the above construct out with a smaller Array.IndexOf construct loops 100,000 times in ~630ms (again, 3-5 runs, rough average, the whole Object). The new construct looks like this:
Dim p As Int32
p = Array.IndexOf(TestValues, s)
If p <> tstNotSet Then
Foobar(n) = DirectCast(p, TestValue)
n += 1
End If
I'm afraid I found your question extremely hard to understand, but is Array.IndexOf what you're looking for?
Dim index = Array.IndexOf(TestValues, tmp(i))
I've got trouble tying a rope to this question. But in any kind of lookup scenario, you always want to use a Dictionary. You'll get O(1) time instead of O(n). Something like this:
Dim lookup As New Dictionary(Of Char, TestValue)
lookup.Add("A"c, TestValue.tstA)
lookup.Add("B"c, TestValue.tstB)
'' etc
You can make the initialization cleaner in many ways. Then:
Dim value As TestValue = lookup(letter)
i would say the solution by #Hans Passant is the way to go with this, but since you are dealing with chars, and chars are numbers,there is an alternative where you dont need a Dictionary.
you could store all the TestValue enum values in an array, and do something like testValueResult = testValueArray(charCode - 65),i.e. just map 'A' to index 0,'B' to 1..., or even just a direct cast from the numeric form of the TestValue to its Enum since you do define it as an integer, and include a simple bounds check for tstNotSet too.