o4-mini-2025-04-16· OpenAI
LMArena Human Preference 140K
Write a string reversal algorithm in zig
- User
Write a string reversal algorithm in zig
- Assistant
Here’s a simple Zig example that shows both an in-place reversal (for a mutable buffer) and a “pure” reversal that allocates a new string. Tested on Zig 0.11.0-dev.
const std = @import("std"); // Reverse a mutable []u8 buffer in place. pub fn reverseInPlace(s: []u8) void { var i: usize = 0; var j: usize = s.len - 1; while (i < j) : (i += 1, j -= 1) { const tmp = s[i]; s[i] = s[j]; s[j] = tmp; } } // Allocate and return a new reversed copy of the input string. pub fn reverseNew( allocator: *std.mem.Allocator, input: []const u8, ) ![]u8 { // Allocate a buffer of the same size var out = try allocator.alloc(u8, input.len); // Copy characters from end→start for (input.len) |i| { out[i] = input[input.len - 1 - i]; } return out; } pub fn main() !void { const stdout = std.io.getStdOut().writer(); // Example 1: in-place var buf = std.heap.DirectAllocator(.{}) .create([]u8, "hello, zig!") catch unreachable; stdout.print("Original (in-place): {s}\n", .{buf}) catch {}; reverseInPlace(buf); stdout.print("Reversed (in-place): {s}\n\n", .{buf}) catch {}; // Example 2: allocate new const alloc = std.heap.page_allocator; const original = "String Reverse"; stdout.print("Original (new): {s}\n", .{original}) catch {}; const rev = try reverseNew(alloc, original); defer alloc.free(rev); stdout.print("Reversed (new): {s}\n", .{rev}) catch {}; }Explanation
reverseInPlace(s: []u8)
– Two-pointer approach: one at the start, one at the end, swap until they meet.reverseNew(allocator, input)
– Allocates a fresh buffer via the provided allocator, then fills it by readinginputfrom back to front.main()
– Demonstrates both methods: first mutating a buffer in place, then returning a newly-allocated reversed string.
Feel free to adapt the allocator (e.g. use a
std.heap.GeneralPurposeAllocator) or error-handling style to fit your project!
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.