# lastIndexOf in CJam

For the question Find the highest unique digit , here is my answer :

9A,sqfe=W%X#-


At the end I am essentially trying to achieve a lastIndexOf. I do that by reversing my array, using indexOf, and subtracting from 9. This adds 4 (9 W % -) extra bytes to get from indexOf to lastIndexOf.

Furthermore, if I didn't know my array was length 10 the code would be even longer, and secondly, this code returns 10 when indexOf is -1 which may not be acceptable in many situations.

Any suggestions on a shorter way to do the lastIndexOf operation (generally or just as needed for this challenge)?

• I want to ask the same thing, but in pyth :P Jul 15, 2017 at 14:51
• @EriktheOutgolfer Thanks, I changed it to shorter. And I'm interested in solutions for any of the cases: 1) my challenge 2) variable array length 3) -1 case. Jul 15, 2017 at 19:02
• @geokavel OK, posting mine as an answer for 3) then. :) Jul 15, 2017 at 19:03

Splitting is sometimes a good way to do this. E.g.

e# Stack: ... haystack needle
a/);S*,


With variants, such as removing the a if both needle and haystack are strings.

• Golfed: a/)a*,. Jul 16, 2017 at 14:43
• Note: doesn't handle -1 case. Outputs 0 instead. Jul 16, 2017 at 18:15

# 9 bytes

_,(@@W%#-


Try it online!

You must have ...element list exactly like this in the stack. If W doesn't contain -1 you must replace it with something that does evaluate to -1.

• Note: doesn't handle -1 case. Outputs length of array instead. Jul 16, 2017 at 18:16
• @geokavel Yeah the -1 case is being worked on... Jul 16, 2017 at 18:18
• In the case where the array has a known length, outputting the length could sometimes be usable, since at least it is a unique value that could not be confused with a valid index. Jul 16, 2017 at 18:20