Skip to content

Commit 9f4d671

Browse files
committed
fixed stacks example / closes #318
1 parent 3b6be69 commit 9f4d671

File tree

3 files changed

+43
-35
lines changed

3 files changed

+43
-35
lines changed

website/versioned_docs/version-0.15.x/02-standard-library/11-stacks.md

Lines changed: 0 additions & 35 deletions
This file was deleted.
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import CodeBlock from "@theme/CodeBlock";
2+
3+
import Stacks from "!!raw-loader!./11.stacks.zig";
4+
5+
# Stacks
6+
7+
[`std.ArrayList`](https://ziglang.org/documentation/master/std/#std.ArrayList)
8+
provides the methods necessary to use it as a stack. Here's an example of
9+
creating a list of matched brackets.
10+
11+
<CodeBlock language="zig">{Stacks}</CodeBlock>
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
// hide-start
2+
const std = @import("std");
3+
const eql = std.mem.eql;
4+
const expect = std.testing.expect;
5+
const test_allocator = std.testing.allocator;
6+
// hide-end
7+
test "stack" {
8+
const string = "(()())";
9+
var stack: std.ArrayList(usize) = .empty;
10+
defer stack.deinit(test_allocator);
11+
12+
const Pair = struct { open: usize, close: usize };
13+
var pairs: std.ArrayList(Pair) = .empty;
14+
defer pairs.deinit(test_allocator);
15+
16+
for (string, 0..) |char, i| {
17+
if (char == '(') try stack.append(test_allocator, i);
18+
if (char == ')')
19+
try pairs.append(test_allocator, .{
20+
.open = stack.pop() orelse
21+
@panic("mismatched brackets"),
22+
.close = i,
23+
});
24+
}
25+
26+
const expected_pairs: []const Pair = &.{
27+
.{ .open = 1, .close = 2 },
28+
.{ .open = 3, .close = 4 },
29+
.{ .open = 0, .close = 5 },
30+
};
31+
try std.testing.expectEqualDeep(expected_pairs, pairs.items);
32+
}

0 commit comments

Comments
 (0)