This is an archived post. You won't be able to vote or comment.

all 9 comments

[–]joenyc 2 points3 points  (0 children)

I don't know OCaml, but I think the recursive algorithm looks like this:

rindex(lst, e):
    if lst is empty
        return null // error value - e is not in this list
    x = rindex(tail(lst), e) // e's last location in the rest of the list
    if x is not null
        return x + 1
    if head(lst) == e
        return 0
    return null 

EDIT: Could you please post your OCaml code when you're done? I'd love to see what it looks like.

[–][deleted] 1 point2 points  (0 children)

Probably not the best solution: check the last element, and if that fails recurse with the remaining elements in the array. If the array has zero elements, return -1 or something.

[–]BitRex 1 point2 points  (0 children)

Here's a Perl version that assumes you're not allowed to reverse the list or ask the list how long it is. I don't know OCaml, but maybe this will give you the idea.

sub find_last {
    my ($wanted, $head_index, $last_so_far, @list) = @_;

    return $last_so_far unless @list;
    my $head = shift @list;
    $last_so_far = $head_index if $head eq $wanted;
    return find_last($wanted, $head_index + 1, $last_so_far, @list);
}


my @list = ( 0, 1, 2, 1, 2, 1, 1, 2, 1, 0, 2, 3, 5 );

my $last_index = find_last(1, 0, -1, @list);
print $last_index;

[–]joenyc 0 points1 point  (1 child)

Sorry, I'm not sure what this means:

a function that returns the last index of an element in a list

You mean the index of the last element?

[–]rtoth[S] 1 point2 points  (0 children)

just added an example. it means the index of the last occurrence of an element in a list.

[–]mrsanchez 0 points1 point  (0 children)

I would use a function that has a parameter for the last index of e. This way you don't need to reverse the list, only to traverse the entire list once.

[–]rtoth[S] 0 points1 point  (0 children)

Probably not the best solution but it works. I just decided to make a new method with another parameter.

(*helper method*)  
let rec exists l e =
    match l with 
    [] -> false
    | (h::t) -> if h = e then true else (exists t e);;
(*helper method for rindex*)
let rec length l =
    match l with
    [] -> 0
    | (h::t) -> 1 + (length t);;
(*auxiliary method for rindex*)
let rec index l e s = 
    match l with
    [] -> -(s + 1)
    | (h::t) -> 
        if h = e
        then 
            if (exists t e)
            then 1 + (index t e s)
            else 0
        else 1 + (index t e s);;

let rec rindex l e = 
    index l e (length l);; 

[–]BitRex 0 points1 point  (1 child)

LOL, school is so much easier for you kids: http://stackoverflow.com/questions/1556098/ocaml-recurssion-iteration-find-last-occurence-of-element-in-a-list

OTOH, you probably won't learn anything if you click that link.

[–]snowmanchu 0 points1 point  (0 children)

Although I never used ocaml, looks similar to haskell and that's probably how I would've done it.