lastIndexOf in CJam

6

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)?

geokavel

Posted 2017-07-15T14:39:50.903

Reputation: 6 352

I want to ask the same thing, but in [tag:pyth] :P – Mr. Xcoder – 2017-07-15T14:51:28.370

@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. – geokavel – 2017-07-15T19:02:46.187

@geokavel OK, posting mine as an answer for 3) then. :) – Erik the Outgolfer – 2017-07-15T19:03:26.820

Answers

2

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.

Peter Taylor

Posted 2017-07-15T14:39:50.903

Reputation: 41 901

Golfed: a/)a*,. – jimmy23013 – 2017-07-16T14:43:08.210

Note: doesn't handle -1 case. Outputs 0 instead. – geokavel – 2017-07-16T18:15:54.100

0

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.

Erik the Outgolfer

Posted 2017-07-15T14:39:50.903

Reputation: 38 134

Note: doesn't handle -1 case. Outputs length of array instead. – geokavel – 2017-07-16T18:16:46.803

@geokavel Yeah the -1 case is being worked on... – Erik the Outgolfer – 2017-07-16T18:18:49.233

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. – geokavel – 2017-07-16T18:20:53.837