Search code examples
xpathfunctional-programmingintegrationxqueryosb

Count consecutive repetitive element in a sequence using XQuery


If the Sequence = [a a b c c c a d d e e e f g h h]

then the Output = [1 2 1 1 2 3 1 1 2 1 2 3 1 1 1 2]

Have tried to use recursion but no luck...Please Help..Thanks in Anticipation

Note: Using XQuery implementation 1.0

One of my failed implementation looks like:

declare function local:test($sequence,$count){

for $counter in (1 to count($sequence))

let $maxIndex := count($sequence)

return

if (matches(subsequence($sequence,1,$maxIndex)[$counter],subsequence($sequence,1,$maxIndex)[$counter + +1])) then let $count := $count + 1 return $count[last()]

else let $count := 1 return $count[last()]


};

Solution

  • I got a working solution for my Question. Credits: odie_63 @ http://odieweblog.wordpress.com/

    declare namespace xf = "http://tempuri.org/OSBTestProject/Resources/XQuery/test/";
    
    declare function local:sequence-group($seq as item()*) as item()*
    {
       let $start-of-group :=
       fn:index-of(
         for $i in 1 to count($seq)
         let $prev := $seq[$i - 1]
         return if ($prev != $seq[$i] or not($prev)) then 1 else 0
       , 1
       )
       return
         for $i in 1 to count($seq)
         return $i - $start-of-group[. le $i][last()] + 1
    };
    
    declare function xf:test($test as xs:string) as xs:integer*
     {
    let $test1 := tokenize($test, ',')
     return  local:sequence-group($test1)
    };
    
    declare variable $test as xs:string external;
    
    xf:test($test)
    

    Input: a,a,b,c,c,c,a,d,d,e,e,e,f,g,h,h

    Output: 1 2 1 1 2 3 1 1 2 1 2 3 1 1 1 2