const std = @import("std"); const mem = std.mem; const rule1 = [_][]const u8{ "a", "e", "i", "o", "u", "xr", "yt", "ay" }; const vowels = "aeiou"; fn rule_one(res: *std.ArrayList(u8), phrase: []const u8) mem.Allocator.Error!bool { for (rule1) |r| { if (mem.eql(u8, r, &.{phrase[0]}) or mem.eql(u8, r, phrase[0..2])) { try res.appendSlice("ay"); return true; } } return false; } fn rule_two(res: *std.ArrayList(u8), phrase: []const u8) mem.Allocator.Error!bool { for (0..phrase.len - 1) |i| { if (!mem.containsAtLeast(u8, vowels, 1, &[_]u8{phrase[i]})) { try res.appendSlice(&.{res.orderedRemove(mem.indexOf(u8, phrase, &[_]u8{phrase[0]}).?)}); } else { try res.appendSlice("ay"); return true; } } return false; } fn rule_three(res: *std.ArrayList(u8), phrase: []const u8) mem.Allocator.Error!bool { var prev: u8 = 0; for (0..phrase.len - 1) |i| { if ((prev == 'q' and phrase[i] == 'u') or !mem.containsAtLeast(u8, vowels, 1, &[_]u8{phrase[i]})) { try res.appendSlice(&.{res.orderedRemove(mem.indexOf(u8, phrase, &[_]u8{phrase[0]}).?)}); } else { try res.appendSlice("ay"); return true; } prev = phrase[i]; } return false; } // Because Yttrium Oxide ("yttria") comes up all the time in children's games fn rule_four(res: *std.ArrayList(u8), phrase: []const u8) mem.Allocator.Error!bool { var i: usize = 0; while (phrase[i] != 'y' and i < phrase.len) : (i += 1) { try res.appendSlice(&.{res.orderedRemove(mem.indexOf(u8, phrase, &[_]u8{phrase[0]}).?)}); } try res.appendSlice("ay"); return true; } fn translate_single(ar: *std.ArrayList(u8), phrase: []const u8) mem.Allocator.Error!void { try ar.appendSlice(phrase); if (try rule_one(ar, phrase)) return; ar.clearRetainingCapacity(); try ar.appendSlice(phrase); if (try rule_three(ar, phrase)) return; ar.clearRetainingCapacity(); try ar.appendSlice(phrase); if (try rule_two(ar, phrase)) return; ar.clearRetainingCapacity(); try ar.appendSlice(phrase); _ = try rule_four(ar, phrase); } pub fn translate(allocator: mem.Allocator, phrase: []const u8) mem.Allocator.Error![]u8 { var it = mem.splitScalar(u8, phrase, ' '); const first = it.first(); var res = std.ArrayList(u8).init(allocator); try translate_single(&res, first); if (it.peek() == null) { return res.toOwnedSlice(); } var buf: [32]u8 = undefined; var fba = std.heap.FixedBufferAllocator.init(&buf); const fba_allocator = fba.allocator(); try res.appendSlice(" "); while (it.next()) |word| { var tmp = std.ArrayList(u8).init(fba_allocator); try translate_single(&tmp, word); try res.appendSlice(try tmp.toOwnedSlice()); try res.appendSlice(" "); } _ = res.pop(); return res.toOwnedSlice(); }