gpt4 book ai didi

用于对字符串中的字符进行计数/格式化的 xquery 递归

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

我正在尝试为 xquery 1.0 中的以下问题找到解决方案。我只需要单独使用递归函数。输入将始终只有 A-Z 之间的字符。

1. AAABBCCD --> A1A2A3-B1B2-C1C2-D1
2. ABBAB --> A1-B1B2-A2-B3

谢谢。到目前为止,我所做的尝试没有任何结果。

最佳答案

首先您可能想将字符串拆分为单个字符,这可以通过多种方式完成(例如使用 fn:substring(...)),我将使用 fn :字符串到代码点($str):

declare function local:to-chars($str) {
for $cp in fn:string-to-codepoints($str)
return fn:codepoints-to-string($cp)
};

示例: local:to-chars('ABC') 产生序列 ('A', 'B', 'C').

对于您的格式化方案,您必须跟踪

  1. 在编号之前您遇到每个字符的频率,以及
  2. 前一个字符是什么(破折号)。

我将跟踪 XQuery 3.0 中每个字符的计数 map并将前一个字符保留在递归函数的单独参数中。现在要做的就是

  • 逐一检查每个字符,
  • 获取并更新其在 map 中的计数,
  • 决定在输出字符串中是否应该在它之前添加破折号,
  • 并递归。

当所有字符都处理完后,我们就完成了。

declare function local:format($chars, $counts, $last, $out) {
if(empty($chars)) then $out
else (
let $c := head($chars), (: current char :)
$new-chars := tail($chars), (: rest of the chars :)
$count := ($counts($c), 1)[1], (: old count if present, `1` otherwise :)
$cc := $c || $count, (: char with count :)
$new-out := if($c eq $last) then $out || $cc (: updated output string :)
else $out || '-' || $cc,
$new-counts := map:put($counts, $c, $count + 1) (: updated map :)
return local:format($new-chars, $new-counts, $c, $new-out)
)
};

我们用空映射调用它,并将序列中的第一个字符称为“前一个”字符,以避免在输出开始时出现破折号。

declare function local:format-string($str) {
let $chars := local:to-chars($str)
return local:format($chars, map{}, head($chars), '')
};

这适用于任意字符:local:format-string('HELLO') 产生 'H1-E1-L1L2-O1'

编辑:

我一定是跳过了 XQuery 1.0 部分,我责怪缺少咖啡因...您也可以将计数保留为 26 个整数的序列而不是映射:

declare function local:format($chars, $counts, $last, $out) {
if(empty($chars)) then $out
else (
let $c := $chars[1],
$new-chars := subsequence($chars, 2),
$pos := string-to-codepoints($c) - 64,
$count := $counts[$pos],
$cc := $c || $count,
$new-out := if($c eq $last) then concat($out, $cc)
else concat($out, '-', $cc),
$new-counts :=
(
subsequence($counts, 1, $pos - 1),
$count + 1,
subsequence($counts, $pos + 1)
)
return local:format($new-chars, $new-counts, $c, $new-out)
)
};

declare function local:format-string($str) {
let $chars := local:to-chars($str),
$counts := for $i in 1 to 26 return 1
return local:format($chars, $counts, head($chars), '')
};

关于用于对字符串中的字符进行计数/格式化的 xquery 递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59510041/

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