Get the most repeating element in a sequence using XQuery

I have a sequence of values. They may be equal ... or not. So with XQuery, I want to get the most frequent element in a sequence.

let $counter := 0, $index1 := 0 for $value in $sequence if (count(index-of($value, $sequence))) then { $counter := count(index-of($value, $sequence)) $index1 := index-of($value) } else {} 

I cannot do this work, so I believe that I am doing something wrong.

Thanks in advance for any help you could give me.

+6
xquery sequence
source share
2 answers

Using

  for $maxFreq in max(for $val in distinct-values($sequence) return count(index-of($sequence, $val)) ) return distinct-values($sequence)[count(index-of($sequence, .)) eq $maxFreq] 

Update December 2015 :

This is noticeably shorter, but may not be very effective:

 $pSeq[index-of($pSeq,.)[max(for $item in $pSeq return count(index-of($pSeq,$item)))]] 

The shortest expression can be built for XPath 3.1:

enter image description here

And even shorter and more copied - using a one-character name:

 $s[index-of($s,.)[max($s ! count(index-of($s, .)))]] 
+6
source share

You are approaching this problem from an overly peremptory point of view.

In XQuery, you can set the values ​​of variables, but you can never change them.

The correct way to execute iterative type algorithms is a recursive function:

 declare funciton local:most($sequence, $index, $value, $count) { let $current=$sequence[$index] return if (empty($current)) then $value else let $current-count = count(index-of($current, $sequence)) return if ($current-count > $count) then local:most($sequence, $index+1, $current, $current-count) else local:most($sequence, $index+1, $value, $count) } 

but the best way to approach the problem is to describe the problem in an inactive way. In this case, of all the different values ​​in your sequence, you want to specify the one that displays the maximum number of times of any single value.

The previous post translated into XQuery,

 let $max-count := max(for $value1 in distinct-values($sequence) return count(index-of($sequence, $value1))) for $value2 in distinct-values($sequence) where (count(index-of($sequence, $value2)) = $max-count return $value2 
+1
source share

All Articles