gpt4 book ai didi

xpath - xquery随机选择文件而不重复选择

转载 作者:行者123 更新时间:2023-12-02 02:33:59 24 4
gpt4 key购买 nike

在 Xquery 3.1(在 eXist 4.7 中)中,我有 40 个 XML 文件,我需要随机选择其中 4 个。不过我希望这四个文件是不同的。

我的文件都在同一个集合中 ($data)。我目前对文件进行计数,然后使用随机函数 ( util:random($max as xs:integer) ) 在文件序列中生成 position() 以选择其中四个:

let $filecount := count($data)
for $cnt in 1 to 4
let $pos := util:random($filecount)
return $data[position()=$pos]

但这通常会导致相同的文件被偶然选择多次。

每个文件都有一个不同的@xml:id(在每个文件的根节点中),如果可能的话,它可以允许我将其用作递归中的某种谓词。但我无法确定以某种方式将 @xml:id 累积到累积递归序列中的方法。

感谢您的帮助。

最佳答案

我认为标准化的random-numer-generator函数及其permute函数( https://www.w3.org/TR/xpath-functions/#func-random-number-generator )应该为您提供更好的“随机性”和多样化的结果,例如

let $file-count := count($data)
return $data[position() = random-number-generator(current-dateTime())?permute(1 to $file-count)[position() le 4]]

我还没有尝试过使用您的 db/XQuery 实现,并且您当前使用的函数可能还有其他方法。

对于 eXist-db 我想一种策略是调用random-number函数,直到你得到所需数量值的不同序列,以下返回(至少在一些测试中) eXide)) 每次调用时有四个 1 到 40 之间的不同数字:

declare function local:random-sequence($max as xs:integer, $length as xs:integer) as xs:integer+ {
local:random-sequence((), $max, $length)
};

declare function local:random-sequence($seq as xs:integer*, $max as xs:integer, $length as xs:integer) as xs:integer+ {
if (count($seq) = $length and $seq = distinct-values($seq))
then $seq
else local:random-sequence((distinct-values($seq), util:random($max)), $max, $length)
};

let $file-count := 40
return local:random-sequence($file-count, 4)

在之前的尝试中整合它会导致

let $file-count := count($data)
return $data[position() = local:random-sequence($file-count, 4)]

至于您的评论,我没有注意到现有的 util:random 函数可以返回 0 并排除最大值,因此根据您的评论和进一步的测试,我猜您更想要该函数我在上面发布了要实现的内容

declare function local:random-sequence($seq as xs:integer*, $max as xs:integer, $length as xs:integer) as xs:integer+ {
if (count($seq) = $length)
then $seq
else
let $new-number := util:random($max + 1)
return if ($seq = $new-number or $new-number = 0)
then local:random-sequence($seq, $max, $length)
else local:random-sequence(($seq, $new-number), $max, $length)
};

这样一来,它现在有望返回 1$max 参数之间的 $length 不同值。

关于xpath - xquery随机选择文件而不重复选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58512986/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com