Skip to content

Commit 8be2948

Browse files
committed
Working Zig permutations
1 parent 0f3a162 commit 8be2948

File tree

1 file changed

+29
-29
lines changed

1 file changed

+29
-29
lines changed

zig/permuations.zig

Lines changed: 29 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,40 @@
11
const std = @import("std");
22

3-
fn printPermutations(a: []u8, n: usize) void {
4-
if (n <= 0) {
5-
std.debug.print("{s}\n", .{a});
6-
} else {
7-
var i: usize = 0;
8-
while (i < n) : (i += 1) {
9-
printPermutations(a, n - 1);
10-
const j = if (n % 2 == 0) 0 else i;
11-
12-
const old_a_j = a[j];
13-
a[j] = a[n];
14-
a[n] = old_a_j;
3+
fn printArray(a: []const []const u8) !void {
4+
var writer = std.io.getStdOut().writer();
5+
for (a, 0..) |item, i| {
6+
try writer.writeAll(item);
7+
if (i < a.len - 1) {
8+
try writer.writeAll("\t");
159
}
16-
printPermutations(a, n - 1);
1710
}
11+
try writer.writeAll("\n");
1812
}
1913

20-
pub fn main() anyerror!void {
21-
const args = try std.process.argsAlloc(std.heap.page_allocator);
22-
defer std.process.argsFree(std.heap.page_allocator, args);
14+
fn printPermutations(a: [][]u8, n: usize) !void {
15+
if (n == 0) {
16+
try printArray(a);
17+
return;
18+
}
2319

24-
// Skip the first argument which is the program's own path
25-
const start_index: usize = 1;
26-
const end_index: usize = args.len;
20+
try printPermutations(a, n - 1);
2721

28-
if (end_index >= start_index) {
29-
var buffer: [100]u8 = undefined;
30-
var a: []u8 = buffer[0 .. end_index - start_index];
22+
var i: usize = 0;
23+
while (i < n) : (i += 1) {
24+
const j: usize = if (n % 2 == 0) 0 else i;
25+
std.mem.swap([]const u8, &a[j], &a[n]);
26+
try printPermutations(a, n - 1);
27+
}
28+
}
3129

32-
// Copy the arguments to the buffer
33-
for (start_index..end_index) |i| {
34-
a[i - start_index] = args[i][0];
35-
}
30+
pub fn main() !void {
31+
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
32+
const allocator = gpa.allocator();
3633

37-
// Calculate and print the permutations
38-
printPermutations(a, a.len - 1);
39-
}
34+
var args = try std.process.argsAlloc(allocator);
35+
defer std.process.argsFree(allocator, args);
36+
const a = try allocator.dupe([]u8, args[1..]);
37+
defer allocator.free(a);
38+
39+
try printPermutations(a, a.len - 1);
4040
}

0 commit comments

Comments
 (0)