add ex53 slices2

This commit is contained in:
Dave Gauer 2021-03-06 19:16:28 -05:00
parent d1c6993898
commit a8b9d6f2b8
3 changed files with 59 additions and 0 deletions

View file

@ -272,6 +272,10 @@ const exercises = [_]Exercise{
.main_file = "52_slices.zig",
.output = "Hand1: A 4 K 8 Hand2: 5 2 Q J",
},
.{
.main_file = "53_slices2.zig",
.output = "'all your base are belong to us.' 'for great justice.'",
},
};
/// Check the zig version to make sure it can compile the examples properly.

35
exercises/53_slices2.zig Normal file
View file

@ -0,0 +1,35 @@
//
// You are perhaps tempted to try slices on strings? They're arrays of
// u8 characters after all, right? Slices on strings work great.
// There's just one catch: don't forget that Zig string literals are
// immutable (const) values. So we need to change the type of slice
// from:
//
// var foo: []u8 = "foobar"[0..3];
//
// to:
//
// var foo: []const u8 = "foobar"[0..3];
//
// See if you can fix this Zero Wing-inspired phrase descrambler:
const std = @import("std");
pub fn main() void {
const scrambled = "great base for all your justice are belong to us";
const base1: []u8 = scrambled[15..23];
const base2: []u8 = scrambled[6..10];
const base3: []u8 = scrambled[32..];
printPhrase(base1, base2, base3);
const justice1: []u8 = scrambled[11..14];
const justice2: []u8 = scrambled[0..5];
const justice3: []u8 = scrambled[24..31];
printPhrase(justice1, justice2, justice3);
std.debug.print("\n", .{});
}
fn printPhrase(part1: []u8, part2: []u8, part3: []u8) void {
std.debug.print("'{s} {s} {s}.' ", .{part1, part2, part3});
}

View file

@ -0,0 +1,20 @@
20,22c20,22
< const base1: []u8 = scrambled[15..23];
< const base2: []u8 = scrambled[6..10];
< const base3: []u8 = scrambled[32..];
---
> const base1: []const u8 = scrambled[15..23];
> const base2: []const u8 = scrambled[6..10];
> const base3: []const u8 = scrambled[32..];
25,27c25,27
< const justice1: []u8 = scrambled[11..14];
< const justice2: []u8 = scrambled[0..5];
< const justice3: []u8 = scrambled[24..31];
---
> const justice1: []const u8 = scrambled[11..14];
> const justice2: []const u8 = scrambled[0..5];
> const justice3: []const u8 = scrambled[24..31];
33c33
< fn printPhrase(part1: []u8, part2: []u8, part3: []u8) void {
---
> fn printPhrase(part1: []const u8, part2: []const u8, part3: []const u8) void {