User:Dora Gustafson/occurences

From Second Life Wiki
Jump to navigation Jump to search

Count Occurrences in a list

Look for and count anything, that can be an element, in a list

This script is an example which include a list: "haystack" and an element: "needle"
Here "haystack" and "needle" are constants and only meant to make up a working script
// count occurrences in list; by Dora Gustafson, Studio Dora 2014
// v1.1 inline code

default
{
    state_entry()
    {
        list haystack = [1,2,1,2,1,2,3,2,4,5,2,6,4,2,3,2,1,8];
        list needle = [2];
        integer i = 0;
        integer j = 0;
        integer k = llListFindList( haystack, needle);
        integer m = llGetListLength( haystack );
        while ( k >= 0 && i < m )
        {
            i += k+1;
            k = llListFindList( llList2List( haystack, i, -1), needle);
            ++j;
        }
        llOwnerSay((string)needle+" occurs "+(string)j+" times in "+llDumpList2String( haystack, ", "));
    }
}

This program is straight, a recursive approach follows

// count occurrences in list; by Dora Gustafson, Studio Dora 2014
// v1.1 inline code
// v1.2 recursive approach

list haystack = [1,2,1,2,1,2,3,2,4,5,2,6,4,2,3,2,1,8];
list needle = [2];
integer j = 0;

tin( list L )
{
    integer k = llListFindList( L, needle);
    if ( k >= 0 )
    {
        ++j;
        if ( k+1 < llGetListLength(L) ) tin( llList2List( L, k+1, -1));
    }
}

default
{
    state_entry()
    {
        tin( haystack);
        llOwnerSay((string)needle+" occurs "+(string)j+" times in "+llDumpList2String( haystack, ", "));
    }
}

The advantage of recursion over straight code is a shorter code(the code is reused)
The disadvantages are longer execution time and more overhead generated at runtime

For these reasons the recursion approach is a bad choice to search a long list in LSL