Anyone have some spin code to find largest value in an array?
Don M
Posts: 1,652
in Propeller 1
A byte array of 16 bytes.
Thanks.
Comments
I think I found the answer... https://forums.parallax.com/discussion/136846/how-to-get-the-maximum-or-minimum-value-of-an-array
You could make a general-purpose method that will work with any array type of any size:
As Phil points out, all the math done in this method uses longs, so there is not need to check size when setting the initial value of maxval.
Jon,
I think you can do this regardless of bsize:
maxval := negx
since the math is all done in longs anyway. Saves an if.
-Phil
Well I thought I did. Evidently I don't know how to use it.
VAR
byte Buff1[16], MaxResult
In this array I have these numbers stored: $01, $02, $05, $14, $FE, $00, $00, $00, $00, $00, $38, $00, $00, $00, $00, $00
I tried this method from @Kuroneco
pub
MaxResult := maxval2(@Buff1, 16)
term.hex(MaxResult, 2)
pub maxval2(addr, n)
addr := (addr - @addr) >> 2
result := addr[addr++]
repeat n - 1
result #>= addr[addr++]
I'm not sure what it's supposed to give me. The actual largest number ($FE) or the index of the largest number (4). It gives me 0.
Help!
This is my demo
Good point, Phil.
Saving another if:
maxval #>= check
Of course, that might be totally opaque to a lot of people. Reason enough not to use it, I s'pose.
-Phil
Since you only care about bytes, here's a simple version. I tested on a byte array with 25 values and it found the correct maximum.
What you're doing with the array pointer seems convoluted. When using pointer, you need to tell Spin what size value you are taking from that pointer -- in this case, a byte.
You could shorten the code a bit...
... but the infinitesimally small performance gain is not worth the non-obvious code (my opinion, of course). I always strive to write obvious code.