gpt4 book ai didi

javascript - 在重复模式中查找每隔一个元素

转载 作者:行者123 更新时间:2023-11-30 09:34:05 26 4
gpt4 key购买 nike

重复“i”后跟“i”和/或“t”的数据。

data = ['i','t','t','i','i','t','t','t']

尝试检索模式 ['i','t','t'] 中最后一个 't' 的索引:

[2,6] // ['i','t','t','i','i','t','t','t'] # position of the returned 't's
// _______ ^ _______ ^

我正在寻找仅使用(纯)函数的非递归解决方案,例如使用 ramdajs。

尝试使用reducetransduce,但至今未成功。

最佳答案

一种方法是使用 R.aperture迭代 data 列表的 3 元素滑动窗口,然后跟踪等于模式 ['i', 't', 't'] 的任何子列表的位置

const data = ['i','t','t','i','i','t','t','t']

const isPattern = R.equals(['i', 't', 't'])

const reduceWithIdx = R.addIndex(R.reduce)

const positions = reduceWithIdx((idxs, next, idx) =>
isPattern(next) ? R.append(idx + 2, idxs) : idxs
, [], R.aperture(3, data))

console.log(positions)
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.24.1/ramda.min.js"></script>

这种方法的无点版本可能类似于以下内容,尽管这是否更可取取决于对样式/可读性的偏好。

const data = ['i','t','t','i','i','t','t','t']

const isPattern = R.equals(['i', 't', 't'])

const run = R.pipe(
// create sliding window of 3 elements
R.aperture(3),

// zip sliding window with index
R.chain(R.zip, R.compose(R.range(0), R.length)),

// filter matching pattern
R.filter(R.compose(isPattern, R.nth(1))),

// extract index
R.map(R.compose(R.add(2), R.head))
)

console.log(run(data))
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.24.1/ramda.min.js"></script>

关于javascript - 在重复模式中查找每隔一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44601969/

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