commit d8afd96c4cec4c8288258f17c62586d57945d29a
parent aad435dd3daf670c1d57b0c99344b8a235cb41cd
Author: Sebastian <sebastian@sebsite.pw>
Date: Tue, 23 Jan 2024 15:57:57 -0500
strings: replace O(n^2) algorithm in rsplitn
Rather than inserting to the beginning of the slice (and shifting
everything by one) for each token, the slice is appended to and then
reversed at the end.
Signed-off-by: Sebastian <sebastian@sebsite.pw>
Diffstat:
1 file changed, 9 insertions(+), 2 deletions(-)
diff --git a/strings/tokenize.ha b/strings/tokenize.ha
@@ -128,7 +128,7 @@ export fn rsplitn(in: str, delim: str, n: size) []str = {
for (let i = 0z; i < n - 1z; i += 1) {
match (next_token(&tok)) {
case let s: str =>
- insert(toks[0], s);
+ append(toks, s);
case void =>
return toks;
};
@@ -136,8 +136,15 @@ export fn rsplitn(in: str, delim: str, n: size) []str = {
match(peek_token(&tok)) {
case void => void;
case let s: str =>
- insert(toks[0], remaining_tokens(&tok));
+ append(toks, remaining_tokens(&tok));
};
+
+ for (let i = 0z; i < len(toks) / 2; i += 1) {
+ const tmp = toks[i];
+ toks[i] = toks[len(toks) - i - 1];
+ toks[len(toks) - i - 1] = tmp;
+ };
+
return toks;
};