Thirsty Crow
Thirsty Crow

Reputation: 1

counting number of words after last occurrence of every word in an array of strings

i am working on text. I want to find the number of words after the last occurrence of a particular word in an array of strings.For instance:

String[] array={cat,rat,cat,bat,cat,cat,bat,fat,mat}

and I want to find the last occurrence of every word in this array and the number of words after the last occurrence . How can I do it???

Upvotes: 0

Views: 489

Answers (3)

Jonas Elfström
Jonas Elfström

Reputation: 31448

In Ruby:

arr = [:cat,:rat,:cat,:bat,:cat,:cat,:bat,:fat,:mat]
hash = {}
arr.reverse.each_with_index {|item, index| hash[item]=index unless hash.has_key?(item)}
hash
=> {:mat=>0, :fat=>1, :bat=>2, :cat=>3, :rat=>7}

Upvotes: 0

Nasenbaer
Nasenbaer

Reputation: 4900

There is a solution with RegEx in DotNet if you will work with strings.

To search in an array here is an short example:

    using System;

class Program
{
    static void Main()
    {
    //
    // Use this array of string references.
    //
    string[] array1 = { "cat", "dog", "carrot", "bird" };
    //
    // Find first element starting with substring.
    //
    string value1 = Array.Find(array1,
        element => element.StartsWith("car", StringComparison.Ordinal));
    //
    // Find first element of three characters length.
    //
    string value2 = Array.Find(array1,
        element => element.Length == 3);
    //
    // Find all elements not greater than four letters long.
    //
    string[] array2 = Array.FindAll(array1,
        element => element.Length <= 4);

    Console.WriteLine(value1);
    Console.WriteLine(value2);
    Console.WriteLine(string.Join(",", array2));
    }
}

Also you can take a look to MSDN Example

Hope that helps Regards

Upvotes: 0

x4u
x4u

Reputation: 14077

Iterate and count the array backwards and every new word that you encounter this way is the last or only instance of this word in the array. You can i.e. put the words in a hash set to check whether you have seen them already. Whenever you detect a new word this way you get the number of words behind it from the counter or by calculating array.length - currentPosition.

Upvotes: 3

Related Questions