|
1 | 1 | const std = @import("std"); |
2 | 2 |
|
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"); |
15 | 9 | } |
16 | | - printPermutations(a, n - 1); |
17 | 10 | } |
| 11 | + try writer.writeAll("\n"); |
18 | 12 | } |
19 | 13 |
|
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 | + } |
23 | 19 |
|
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); |
27 | 21 |
|
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 | +} |
31 | 29 |
|
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(); |
36 | 33 |
|
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); |
40 | 40 | } |
0 commit comments