gpt4 book ai didi

ruby - 换行位置

转载 作者:数据小太阳 更新时间:2023-10-29 07:06:44 26 4
gpt4 key购买 nike

给定一个字符串,返回字符串中换行符开头的字符位置数组的最有效方法是什么?

text =<<_
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis
nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu
fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
culpa qui officia deserunt mollit anim id est laborum.
_

预期:

find_newlines(text) # => [0, 80, 155, 233, 313, 393]

我发布我自己的答案。我愿意接受最快的方式作为接受的答案。


此处的基准测试结果将在添加新答案时更新

require "fruity"

compare do
padde1 {find_newlines_padde1(text)}
digitalross1 {find_newlines_digitalross1(text)}
sawa1 {find_newlines1(text)}
sawa2 {find_newlines2(text)}
end

# Running each test 512 times. Test will take about 1 second.
# digitalross1 is faster than sawa2 by 5x ± 0.1
# sawa2 is faster than sawa1 by 21.999999999999996% ± 1.0%
# sawa1 is faster than padde1 by 4.0000000000000036% ± 1.0%

最佳答案

def find_newlines text
s = 0
[0] + text.to_a[0..-2].map { |e| s += e.size }
end

如前所述,对 1.9 使用 text.each_line.to_a。调用 each_line 也适用于 1.8.7,但比仅调用 to_a.

慢 20%

关于ruby - 换行位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14941036/

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