Anyone have some spin code to find largest value in an array? — Parallax Forums

# Anyone have some spin code to find largest value in an array?

Posts: 1,632

A byte array of 16 bytes.

Thanks.

• Posts: 7,579
edited 2021-03-12 23:53

You could make a general-purpose method that will work with any array type of any size:

```pub find_max(p_array, bsize, count) : maxval | check

maxval := negx

repeat count
case bsize
1 :
check := byte[p_array]
p_array += 1

2 :
check := word[p_array]
p_array += 2

4 :
check := long[p_array]
p_array += 4

if (check > maxval)
maxval := check
```

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.

• Posts: 22,981
edited 2021-03-12 22:59

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

• Posts: 1,632

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)

repeat n - 1

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!

• Posts: 1,086

This is my demo

• Posts: 7,579
edited 2021-03-12 23:51

Good point, Phil.

• Posts: 22,981
edited 2021-03-13 00:00

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

• Posts: 7,579
edited 2021-03-13 00:15

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.

```pub get_max(p_array, count) : maxval | check

repeat count
check := byte[p_array++]
if (check > maxval)
maxval := check
```

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...

```pub get_max(p_array, count) : maxval

repeat count
maxval #>= byte[p_array++]
```

... but the infinitesimally small performance gain is not worth the non-obvious code (my opinion, of course). I always strive to write obvious code.