Add solutions

This commit is contained in:
Laurens Miers 2024-09-25 15:26:17 +02:00
parent 7417f01d5d
commit b056b6ad81
96 changed files with 229 additions and 166 deletions

View file

@ -16,6 +16,6 @@
//
const std = @import("std");
fn main() void {
pub fn main() void {
std.debug.print("Hello world!\n", .{});
}

View file

@ -11,7 +11,7 @@
// Please complete the import below:
//
??? = @import("std");
const std = @import("std");
pub fn main() void {
std.debug.print("Standard Library.\n", .{});

View file

@ -34,12 +34,12 @@
const std = @import("std");
pub fn main() void {
const n: u8 = 50;
var n: u8 = 50;
n = n + 5;
const pi: u8 = 314159;
const pi: u32 = 314159;
const negative_eleven: u8 = -11;
const negative_eleven: i8 = -11;
// There are no errors in the next line, just explanation:
// Perhaps you noticed before that the print function takes two

View file

@ -27,7 +27,7 @@ pub fn main() void {
// (Problem 1)
// This "const" is going to cause a problem later - can you see what it is?
// How do we fix it?
const some_primes = [_]u8{ 1, 3, 5, 7, 11, 13, 17, 19 };
var some_primes = [_]u8{ 1, 3, 5, 7, 11, 13, 17, 19 };
// Individual values can be set with '[]' notation.
// Example: This line changes the first prime to 2 (which is correct):
@ -40,11 +40,11 @@ pub fn main() void {
// (Problem 2)
// Looks like we need to complete this expression. Use the example
// above to set "fourth" to the fourth element of the some_primes array:
const fourth = some_primes[???];
const fourth = some_primes[3];
// (Problem 3)
// Use the len property to get the length of the array:
const length = some_primes.???;
const length = some_primes.len;
std.debug.print("First: {}, Fourth: {}, Length: {}\n", .{
first, fourth, length,

View file

@ -25,12 +25,12 @@ pub fn main() void {
// (Problem 1)
// Please set this array concatenating the two arrays above.
// It should result in: 1 3 3 7
const leet = ???;
const leet = le ++ et;
// (Problem 2)
// Please set this array using repetition.
// It should result in: 1 0 0 1 1 0 0 1 1 0 0 1
const bit_pattern = [_]u8{ ??? } ** 3;
const bit_pattern = [_]u8{ 1, 0, 0, 1 } ** 3;
// Okay, that's all of the problems. Let's see the results.
//

View file

@ -24,18 +24,18 @@ pub fn main() void {
// (Problem 1)
// Use array square bracket syntax to get the letter 'd' from
// the string "stardust" above.
const d: u8 = ziggy[???];
const d: u8 = ziggy[4];
// (Problem 2)
// Use the array repeat '**' operator to make "ha ha ha ".
const laugh = "ha " ???;
const laugh = "ha " ** 3;
// (Problem 3)
// Use the array concatenation '++' operator to make "Major Tom".
// (You'll need to add a space as well!)
const major = "Major";
const tom = "Tom";
const major_tom = major ??? tom;
const major_tom = major ++ " " ++ tom;
// That's all the problems. Let's see our results:
std.debug.print("d={u} {s}{s}\n", .{ d, laugh, major_tom });

View file

@ -15,9 +15,9 @@ const std = @import("std");
pub fn main() void {
const lyrics =
Ziggy played guitar
Jamming good with Andrew Kelley
And the Spiders from Mars
\\Ziggy played guitar
\\Jamming good with Andrew Kelley
\\And the Spiders from Mars
;
std.debug.print("{s}\n", .{lyrics});

View file

@ -19,7 +19,7 @@ pub fn main() void {
// the idiomatic type to use for array indexing.
//
// There IS a problem on this line, but 'usize' isn't it.
const x: usize = 1;
var x: usize = 1;
// Note: When you want to declare memory (an array in this
// case) without putting anything in it, you can set it to
@ -33,10 +33,11 @@ pub fn main() void {
lang[0] = letters[x];
x = 3;
lang[???] = letters[x];
lang[1] = letters[x];
x = ???;
lang[2] = letters[???];
// x = letters.len - 1;
x = letters.len - 1;
lang[2] = letters[x];
// We want to "Program in Zig!" of course:
std.debug.print("Program in {s}!\n", .{lang});

View file

@ -21,7 +21,7 @@
const std = @import("std");
pub fn main() void {
const foo = 1;
const foo: bool = true;
// Please fix this condition:
if (foo) {

View file

@ -10,7 +10,7 @@ pub fn main() void {
// Please use an if...else expression to set "price".
// If discount is true, the price should be $17, otherwise $20:
const price: u8 = if ???;
const price: u8 = if (discount) 17 else 20;
std.debug.print("With the discount, the price is ${}.\n", .{price});
}

View file

@ -21,7 +21,7 @@ pub fn main() void {
var n: u32 = 2;
// Please use a condition that is true UNTIL "n" reaches 1024:
while (???) {
while (n < 1024) {
// Print the current number
std.debug.print("{} ", .{n});

View file

@ -25,7 +25,7 @@ pub fn main() void {
// Please set the continue expression so that we get the desired
// results in the print statement below.
while (n < 1000) : ??? {
while (n < 1000) : (n *= 2) {
// Print the current number
std.debug.print("{} ", .{n});
}

View file

@ -24,8 +24,8 @@ pub fn main() void {
while (n <= 20) : (n += 1) {
// The '%' symbol is the "modulo" operator and it
// returns the remainder after division.
if (n % 3 == 0) ???;
if (n % 5 == 0) ???;
if (n % 3 == 0) continue;
if (n % 5 == 0) continue;
std.debug.print("{} ", .{n});
}

View file

@ -18,7 +18,7 @@ pub fn main() void {
// Oh dear! This while loop will go forever?!
// Please fix this so the print statement below gives the desired output.
while (true) : (n += 1) {
if (???) ???;
if (n == 4) break;
}
// Result: we want n=4

View file

@ -15,7 +15,7 @@ pub fn main() void {
std.debug.print("A Dramatic Story: ", .{});
for (???) |???| {
for (story) |scene| {
if (scene == 'h') std.debug.print(":-) ", .{});
if (scene == 's') std.debug.print(":-( ", .{});
if (scene == 'n') std.debug.print(":-| ", .{});

View file

@ -25,7 +25,7 @@ pub fn main() void {
// the value of the place as a power of two for each bit.
//
// See if you can figure out the missing pieces:
for (bits, ???) |bit, ???| {
for (bits, 0..) |bit, i| {
// Note that we convert the usize i to a u32 with
// @intCast(), a builtin function just like @import().
// We'll learn about these properly in a later exercise.

View file

@ -9,18 +9,18 @@
// Let's go from 1 to 16. This has been started for you, but there
// are some problems. :-(
//
const std = import standard library;
const std = @import("std");
function main() void {
pub fn main() void {
var i: u8 = 1;
const stop_at: u8 = 16;
// What kind of loop is this? A 'for' or a 'while'?
??? (i <= stop_at) : (i += 1) {
while (i <= stop_at) : (i += 1) {
if (i % 3 == 0) std.debug.print("Fizz", .{});
if (i % 5 == 0) std.debug.print("Buzz", .{});
if (!(i % 3 == 0) and !(i % 5 == 0)) {
std.debug.print("{}", .{???});
std.debug.print("{}", .{i});
}
std.debug.print(", ", .{});
}

View file

@ -25,6 +25,6 @@ pub fn main() void {
// We're just missing a couple things. One thing we're NOT missing is the
// keyword "pub", which is not needed here. Can you guess why?
//
??? deepThought() ??? {
pub fn deepThought() u8 {
return 42; // Number courtesy Douglas Adams
}

View file

@ -22,7 +22,7 @@ pub fn main() void {
// You'll need to figure out the parameter name and type that we're
// expecting. The output type has already been specified for you.
//
fn twoToThe(???) u32 {
fn twoToThe(comptime my_number: u32) u32 {
return std.math.pow(u32, 2, my_number);
// std.math.pow(type, a, b) takes a numeric type and two
// numbers of that type (or that can coerce to that type) and

View file

@ -21,8 +21,8 @@ pub fn main() void {
//
// This function prints, but does not return anything.
//
fn printPowersOfTwo(numbers: [4]u16) ??? {
loop (numbers) |n| {
fn printPowersOfTwo(numbers: [4]u16) void {
for (numbers) |n| {
std.debug.print("{} ", .{twoToThe(n)});
}
}
@ -31,13 +31,13 @@ fn printPowersOfTwo(numbers: [4]u16) ??? {
// exercise. But don't be fooled! This one does the math without the aid
// of the standard library!
//
fn twoToThe(number: u16) ??? {
fn twoToThe(number: u16) u16 {
var n: u16 = 0;
var total: u16 = 1;
loop (n < number) : (n += 1) {
while (n < number) : (n += 1) {
total *= 2;
}
return ???;
return total;
}

View file

@ -9,7 +9,7 @@
// "TooSmall". Please add it where needed!
const MyNumberError = error{
TooBig,
???,
TooSmall,
TooFour,
};
@ -26,7 +26,7 @@ pub fn main() void {
if (number_error == MyNumberError.TooBig) {
std.debug.print(">4. ", .{});
}
if (???) {
if (number_error == MyNumberError.TooSmall) {
std.debug.print("<4. ", .{});
}
if (number_error == MyNumberError.TooFour) {

View file

@ -19,7 +19,7 @@ const std = @import("std");
const MyNumberError = error{TooSmall};
pub fn main() void {
var my_number: ??? = 5;
var my_number: MyNumberError!u8 = 5;
// Looks like my_number will need to either store a number OR
// an error. Can you set the type correctly above?

View file

@ -12,14 +12,14 @@ const MyNumberError = error{TooSmall};
pub fn main() void {
const a: u32 = addTwenty(44) catch 22;
const b: u32 = addTwenty(4) ??? 22;
const b: u32 = addTwenty(4) catch 22;
std.debug.print("a={}, b={}\n", .{ a, b });
}
// Please provide the return type from this function.
// Hint: it'll be an error union.
fn addTwenty(n: u32) ??? {
fn addTwenty(n: u32) MyNumberError!u32 {
if (n < 5) {
return MyNumberError.TooSmall;
} else {

View file

@ -59,7 +59,10 @@ fn fixTooSmall(n: u32) MyNumberError!u32 {
// If we get a TooSmall error, we should return 10.
// If we get any other error, we should return that error.
// Otherwise, we return the u32 number.
return detectProblems(n) ???;
return detectProblems(n) catch |err| {
if (err == MyNumberError.TooSmall) return 10;
return err;
};
}
fn detectProblems(n: u32) MyNumberError!u32 {

View file

@ -26,7 +26,7 @@ fn addFive(n: u32) MyNumberError!u32 {
// This function needs to return any error which might come back from detect().
// Please use a "try" statement rather than a "catch".
//
var x = detect(n);
var x = try detect(n);
return x + 5;
}

View file

@ -23,5 +23,5 @@ pub fn main() !void {
// to be able to pass it up as a return value of main().
//
// We just learned of a single statement which can accomplish this.
stdout.print("Hello world!\n", .{});
try stdout.print("Hello world!\n", .{});
}

View file

@ -20,6 +20,6 @@ const std = @import("std");
pub fn main() void {
// Without changing anything else, please add a 'defer' statement
// to this code so that our program prints "One Two\n":
std.debug.print("Two\n", .{});
std.debug.print("One ", .{});
defer std.debug.print("Two\n", .{});
defer std.debug.print("One ", .{});
}

View file

@ -18,7 +18,7 @@ pub fn main() void {
fn printAnimal(animal: u8) void {
std.debug.print("(", .{});
std.debug.print(") ", .{}); // <---- how?!
defer std.debug.print(") ", .{}); // <---- how?!
if (animal == 'g') {
std.debug.print("Goat", .{});

View file

@ -32,7 +32,7 @@ fn makeNumber() MyErr!u32 {
// Please make the "failed" message print ONLY if the makeNumber()
// function exits with an error:
std.debug.print("failed!\n", .{});
errdefer std.debug.print("failed!\n", .{});
var num = try getNumber(); // <-- This could fail!

View file

@ -42,6 +42,7 @@ pub fn main() void {
// ... we don't need everything in between ...
25 => std.debug.print("Y", .{}),
26 => std.debug.print("Z", .{}),
else => std.debug.print("?", .{}),
// Switch statements must be "exhaustive" (there must be a
// match for every possible value). Please add an "else"
// to this switch to print a question mark "?" when c is

View file

@ -29,6 +29,7 @@ pub fn main() void {
// ...
25 => 'Y',
26 => 'Z',
else => '!',
// As in the last exercise, please add the 'else' clause
// and this time, have it return an exclamation mark '!'.
};

View file

@ -35,6 +35,7 @@ pub fn main() void {
3 => {
current_value *= current_value;
},
else => unreachable,
}
std.debug.print("{} ", .{current_value});

View file

@ -39,6 +39,7 @@ pub fn main() void {
std.debug.print("={}. ", .{value});
} else |err| switch (err) {
MyNumberError.TooBig => std.debug.print(">4. ", .{}),
MyNumberError.TooSmall => std.debug.print("<4. ", .{}),
// Please add a match for TooSmall here and have it print: "<4. "
}
}

View file

@ -9,10 +9,10 @@ const std = @import("std");
const NumError = error{IllegalNumber};
pub fn main() void {
pub fn main() !void {
const stdout = std.io.getStdOut().writer();
const my_num: u32 = getNumber();
const my_num: u32 = getNumber() catch 42;
try stdout.print("my_num={}\n", .{my_num});
}

View file

@ -20,7 +20,7 @@
const std = @import("std");
// Please complete the enum!
const Ops = enum { ??? };
const Ops = enum { inc, pow, dec };
pub fn main() void {
const operations = [_]Ops{

View file

@ -31,7 +31,7 @@ const std = @import("std");
const Color = enum(u32) {
red = 0xff0000,
green = 0x00ff00,
blue = ???,
blue = 0x0000ff,
};
pub fn main() void {
@ -53,12 +53,12 @@ pub fn main() void {
\\<p>
\\ <span style="color: #{x:0>6}">Red</span>
\\ <span style="color: #{x:0>6}">Green</span>
\\ <span style="color: #{}">Blue</span>
\\ <span style="color: #{x:0>6}">Blue</span>
\\</p>
\\
, .{
@intFromEnum(Color.red),
@intFromEnum(Color.green),
@intFromEnum(???), // Oops! We're missing something!
@intFromEnum(Color.blue), // Oops! We're missing something!
});
}

View file

@ -34,6 +34,7 @@ const Role = enum {
// it a u8 integer type.
const Character = struct {
role: Role,
health: u8,
gold: u32,
experience: u32,
};
@ -44,6 +45,7 @@ pub fn main() void {
.role = Role.wizard,
.gold = 20,
.experience = 10,
.health = 100,
};
// Glorp gains some gold.

View file

@ -33,6 +33,13 @@ pub fn main() void {
.experience = 10,
};
chars[1] = Character{
.role = Role.bard,
.gold = 10,
.health = 100,
.experience = 20,
};
// Please add "Zump the Loud" with the following properties:
//
// role bard

View file

@ -30,7 +30,7 @@ pub fn main() void {
// Please make num2 equal 5 using num1_pointer!
// (See the "cheatsheet" above for ideas.)
num2 = ???;
num2 = num1_pointer.*;
std.debug.print("num1: {}, num2: {}\n", .{ num1, num2 });
}

View file

@ -23,7 +23,7 @@ const std = @import("std");
pub fn main() void {
const a: u8 = 12;
const b: *u8 = &a; // fix this!
const b: *const u8 = &a; // fix this!
std.debug.print("a: {}, b: {}\n", .{ a, b.* });
}

View file

@ -31,7 +31,7 @@ pub fn main() void {
// Please define pointer "p" so that it can point to EITHER foo or
// bar AND change the value it points to!
??? p: ??? = undefined;
var p: *u8 = undefined;
p = &foo;
p.* += 1;

View file

@ -37,5 +37,5 @@ pub fn main() void {
// This function should take a reference to a u8 value and set it
// to 5.
fn makeFive(x: *u8) void {
??? = 5; // fix me!
x.* = 5; // fix me!
}

View file

@ -68,7 +68,7 @@ pub fn main() void {
// FIX ME!
// Please pass Glorp to printCharacter():
printCharacter(???);
printCharacter(&glorp);
}
// Note how this function's "c" parameter is a pointer to a Character struct.

View file

@ -18,12 +18,14 @@ const Elephant = struct {
pub fn main() void {
var elephantA = Elephant{ .letter = 'A' };
var elephantB = Elephant{ .letter = 'B' };
// (Please add Elephant B here!)
var elephantC = Elephant{ .letter = 'C' };
// Link the elephants so that each tail "points" to the next elephant.
// They make a circle: A->B->C->A...
elephantA.tail = &elephantB;
elephantB.tail = &elephantC;
// (Please link Elephant B's tail to Elephant C here!)
elephantC.tail = &elephantA;

View file

@ -29,7 +29,7 @@ pub fn main() void {
// Please threaten the result so that answer is either the
// integer value from deepThought() OR the number 42:
const answer: u8 = result;
const answer: u8 = result orelse 42;
std.debug.print("The Ultimate Answer: {}.\n", .{answer});
}

View file

@ -21,7 +21,7 @@ const std = @import("std");
const Elephant = struct {
letter: u8,
tail: *Elephant = null, // Hmm... tail needs something...
tail: ?*Elephant = null, // Hmm... tail needs something...
visited: bool = false,
};
@ -51,7 +51,7 @@ fn visitElephants(first_elephant: *Elephant) void {
// We should stop once we encounter a tail that
// does NOT point to another element. What can
// we put here to make that happen?
if (e.tail == null) ???;
if (e.tail == null) break;
e = e.tail.?;
}

View file

@ -88,7 +88,7 @@ pub fn main() void {
for (&aliens) |*alien| {
// *** Zap the alien with the heat ray here! ***
???.zap(???);
heat_ray.zap(alien);
// If the alien's health is still above 0, it's still alive.
if (alien.health > 0) aliens_alive += 1;

View file

@ -54,7 +54,7 @@ fn visitElephants(first_elephant: *Elephant) void {
// This gets the next elephant or stops:
// which method do we want here?
e = if (e.hasTail()) e.??? else break;
e = if (e.hasTail()) e.getTail() else break;
}
}

View file

@ -27,7 +27,13 @@ const Elephant = struct {
// Your Elephant trunk methods go here!
// ---------------------------------------------------
???
pub fn getTrunk(me: *Elephant) *Elephant {
return me.trunk.?;
}
pub fn hasTrunk(me: *Elephant) bool {
return me.trunk != null;
}
// ---------------------------------------------------

View file

@ -65,10 +65,10 @@ const std = @import("std");
const Err = error{Cthulhu};
pub fn main() void {
var first_line1: *const [16]u8 = ???;
var first_line1: *const [16]u8 = undefined;
first_line1 = "That is not dead";
var first_line2: Err!*const [21]u8 = ???;
var first_line2: Err!*const [21]u8 = Err.Cthulhu;
first_line2 = "which can eternal lie";
// Note we need the "{!s}" format for the error union string.
@ -77,8 +77,8 @@ pub fn main() void {
printSecondLine();
}
fn printSecondLine() ??? {
var second_line2: ?*const [18]u8 = ???;
fn printSecondLine() void {
var second_line2: ?*const [18]u8 = null;
second_line2 = "even death may die";
std.debug.print("And with strange aeons {s}.\n", .{second_line2.?});

View file

@ -87,7 +87,7 @@ pub fn main() void {
// Let's assign the std.debug.print function to a const named
// "print" so that we can use this new name later!
const print = ???;
const print = std.debug.print;
// Now let's look at assigning and pointing to values in Zig.
//
@ -152,13 +152,13 @@ pub fn main() void {
print("XP before:{}, ", .{glorp.experience});
// Fix 1 of 2 goes here:
levelUp(glorp, reward_xp);
levelUp(&glorp, reward_xp);
print("after:{}.\n", .{glorp.experience});
}
// Fix 2 of 2 goes here:
fn levelUp(character_access: Character, xp: u32) void {
fn levelUp(character_access: *Character, xp: u32) void {
character_access.experience += xp;
}

View file

@ -32,8 +32,8 @@ pub fn main() void {
var cards = [8]u8{ 'A', '4', 'K', '8', '5', '2', 'Q', 'J' };
// Please put the first 4 cards in hand1 and the rest in hand2.
const hand1: []u8 = cards[???];
const hand2: []u8 = cards[???];
const hand1: *[4]u8 = cards[0..4];
const hand2 = cards[4..8];
std.debug.print("Hand1: ", .{});
printHand(hand1);
@ -43,7 +43,7 @@ pub fn main() void {
}
// Please lend this function a hand. A u8 slice hand, that is.
fn printHand(hand: ???) void {
fn printHand(hand: *[4]u8) void {
for (hand) |h| {
std.debug.print("{u} ", .{h});
}

View file

@ -17,19 +17,19 @@ 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..];
const base1: []const u8 = scrambled[15..23];
const base2: []const u8 = scrambled[6..10];
const base3: []const 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];
const justice1: []const u8 = scrambled[11..14];
const justice2: []const u8 = scrambled[0..5];
const justice3: []const u8 = scrambled[24..31];
printPhrase(justice1, justice2, justice3);
std.debug.print("\n", .{});
}
fn printPhrase(part1: []u8, part2: []u8, part3: []u8) void {
fn printPhrase(part1: []const u8, part2: []const u8, part3: []const u8) void {
std.debug.print("'{s} {s} {s}.' ", .{ part1, part2, part3 });
}

View file

@ -32,7 +32,7 @@ pub fn main() void {
// we can CONVERT IT TO A SLICE. (Hint: we do know the length!)
//
// Please fix this line so the print statement below can print it:
const zen12_string: []const u8 = zen_manyptr;
const zen12_string: []const u8 = zen_manyptr[0..21];
// Here's the moment of truth!
std.debug.print("{s}\n", .{zen12_string});

View file

@ -59,8 +59,8 @@ pub fn main() void {
std.debug.print("Insect report! ", .{});
// Oops! We've made a mistake here.
printInsect(ant, AntOrBee.c);
printInsect(bee, AntOrBee.c);
printInsect(ant, AntOrBee.a);
printInsect(bee, AntOrBee.b);
std.debug.print("\n", .{});
}

View file

@ -44,14 +44,14 @@ pub fn main() void {
std.debug.print("Insect report! ", .{});
// Could it really be as simple as just passing the union?
printInsect(???);
printInsect(???);
printInsect(ant);
printInsect(bee);
std.debug.print("\n", .{});
}
fn printInsect(insect: Insect) void {
switch (???) {
switch (insect) {
.still_alive => |a| std.debug.print("Ant alive is: {}. ", .{a}),
.flowers_visited => |f| std.debug.print("Bee visited {} flowers. ", .{f}),
}

View file

@ -15,7 +15,7 @@
//
const std = @import("std");
const Insect = union(InsectStat) {
const Insect = union(enum) {
flowers_visited: u16,
still_alive: bool,
};

View file

@ -192,8 +192,8 @@ const TripItem = union(enum) {
// Oops! The hermit forgot how to capture the union values
// in a switch statement. Please capture both values as
// 'p' so the print statements work!
.place => print("{s}", .{p.name}),
.path => print("--{}->", .{p.dist}),
.place => |p| print("{s}", .{p.name}),
.path => |p| print("--{}->", .{p.dist}),
}
}
};
@ -255,7 +255,7 @@ const HermitsNotebook = struct {
// dereference and optional value "unwrapping" look
// together. Remember that you return the address with the
// "&" operator.
if (place == entry.*.?.place) return entry;
if (place == entry.*.?.place) return &entry.*.?;
// Try to make your answer this long:__________;
}
return null;
@ -309,7 +309,7 @@ const HermitsNotebook = struct {
//
// Looks like the hermit forgot something in the return value of
// this function. What could that be?
fn getTripTo(self: *HermitsNotebook, trip: []?TripItem, dest: *Place) void {
fn getTripTo(self: *HermitsNotebook, trip: []?TripItem, dest: *Place) !void {
// We start at the destination entry.
const destination_entry = self.getEntry(dest);

View file

@ -20,9 +20,9 @@ const print = @import("std").debug.print;
pub fn main() void {
const zig = [_]u8{
0o131, // octal
0b1101000, // binary
0x66, // hex
'Z', // octal
'i', // binary
'g', // hex
};
print("{s} is cool.\n", .{zig});

View file

@ -43,7 +43,7 @@ pub fn main() void {
//
// We'll convert this weight from tons to kilograms at a
// conversion of 907.18kg to the ton.
const shuttle_weight: f16 = 907.18 * 2200;
const shuttle_weight: f32 = 907.18 * 2.200;
// By default, float values are formatted in scientific
// notation. Try experimenting with '{d}' and '{d:.3}' to see

View file

@ -67,7 +67,7 @@ const print = @import("std").debug.print;
pub fn main() void {
var letter: u8 = 'A';
const my_letter: ??? = &letter;
const my_letter: ?*[1]u8 = &letter;
// ^^^^^^^
// Your type here.
// Must coerce from &letter (which is a *u8).

View file

@ -47,7 +47,7 @@ pub fn main() void {
// return it from the for loop.
const current_lang: ?[]const u8 = for (langs) |lang| {
if (lang.len == 3) break lang;
};
} else "NOOP";
if (current_lang) |cl| {
print("Current language: {s}\n", .{cl});

View file

@ -115,21 +115,17 @@ pub fn main() void {
// (Remember that want_it will be the index number of
// the ingredient based on its position in the
// required ingredient list for each food.)
const found = for (wanted_ingredients) |want_it| {
if (required_ingredient == want_it) break true;
} else false;
// We did not find this required ingredient, so we
// can't make this Food. Continue the outer loop.
if (!found) continue :food_loop;
for (wanted_ingredients) |want_it| {
if (required_ingredient == want_it) break;
} else continue :food_loop;
}
// If we get this far, the required ingredients were all
// wanted for this Food.
//
// Please return this Food from the loop.
break;
};
break food;
} else menu[0];
// ^ Oops! We forgot to return Mac & Cheese as the default
// Food when the requested ingredients aren't found.

View file

@ -63,7 +63,7 @@ pub fn main() void {
//
// If there was no overflow at all while adding 5 to a, what value would
// 'my_result' hold? Write the answer in into 'expected_result'.
const expected_result: u8 = ???;
const expected_result: u8 = 0b10010;
print(". Without overflow: {b:0>8}. ", .{expected_result});
print("Furthermore, ", .{});
@ -78,6 +78,6 @@ pub fn main() void {
// Now it's your turn. See if you can fix this attempt to use
// this builtin to reverse the bits of a u8 integer.
const input: u8 = 0b11110000;
const tupni: u8 = @bitReverse(input, tupni);
const tupni: u8 = @bitReverse(input);
print("{b:0>8} backwards is {b:0>8}.\n", .{ input, tupni });
}

View file

@ -58,7 +58,7 @@ pub fn main() void {
// Oops! We cannot leave the 'me' and 'myself' fields
// undefined. Please set them here:
narcissus.me = &narcissus;
narcissus.??? = ???;
narcissus.myself = &narcissus;
// This determines a "peer type" from three separate
// references (they just happen to all be the same object).
@ -70,7 +70,7 @@ pub fn main() void {
//
// The fix for this is very subtle, but it makes a big
// difference!
const Type2 = narcissus.fetchTheMostBeautifulType();
const Type2 = Narcissus.fetchTheMostBeautifulType();
// Now we print a pithy statement about Narcissus.
print("A {s} loves all {s}es. ", .{
@ -109,15 +109,15 @@ pub fn main() void {
// Please complete these 'if' statements so that the field
// name will not be printed if the field is of type 'void'
// (which is a zero-bit type that takes up no space at all!):
if (fields[0].??? != void) {
if (fields[0].type != void) {
print(" {s}", .{@typeInfo(Narcissus).Struct.fields[0].name});
}
if (fields[1].??? != void) {
if (fields[1].type != void) {
print(" {s}", .{@typeInfo(Narcissus).Struct.fields[1].name});
}
if (fields[2].??? != void) {
if (fields[2].type != void) {
print(" {s}", .{@typeInfo(Narcissus).Struct.fields[2].name});
}

View file

@ -62,8 +62,8 @@ pub fn main() void {
// types with specific sizes. The comptime numbers will be
// coerced (if they'll fit!) into your chosen runtime types.
// For this it is necessary to specify a size, e.g. 32 bit.
var var_int = 12345;
var var_float = 987.654;
var var_int: u32 = 12345;
var var_float: f32 = 987.654;
// We can change what is stored at the areas set aside for
// "var_int" and "var_float" in the running compiled program.

View file

@ -35,7 +35,7 @@ pub fn main() void {
// In this contrived example, we've decided to allocate some
// arrays using a variable count! But something's missing...
//
var count = 0;
comptime var count = 0;
count += 1;
var a1: [count]u8 = .{'A'} ** count;

View file

@ -43,7 +43,8 @@ const Schooner = struct {
//
// Please change this so that it sets a 0 scale to 1
// instead.
if (my_scale == 0) @compileError("Scale 1:0 is not valid!");
// if (my_scale == 0) @compileError("Scale 1:0 is not valid!");
if (my_scale == 0) my_scale = 1;
self.scale = my_scale;
self.hull_length /= my_scale;
@ -69,7 +70,7 @@ pub fn main() void {
// Hey, we can't just pass this runtime variable as an
// argument to the scaleMe() method. What would let us do
// that?
var scale: u32 = undefined;
comptime var scale: u32 = undefined;
scale = 32; // 1:32 scale

View file

@ -42,8 +42,8 @@ pub fn main() void {
// 2) Sets the size of the array of type T (which is the
// sequence we're creating and returning).
//
fn makeSequence(comptime T: type, ??? size: usize) [???]T {
var sequence: [???]T = undefined;
fn makeSequence(comptime T: type, comptime size: usize) [size]T {
var sequence: [size]T = undefined;
var i: usize = 0;
while (i < size) : (i += 1) {

View file

@ -123,8 +123,8 @@ fn isADuck(possible_duck: anytype) bool {
// Please make sure MyType has both waddle() and quack()
// methods:
const MyType = @TypeOf(possible_duck);
const walks_like_duck = ???;
const quacks_like_duck = ???;
const walks_like_duck = @hasDecl(MyType, "waddle");
const quacks_like_duck = @hasDecl(MyType, "quack");
const is_duck = walks_like_duck and quacks_like_duck;

View file

@ -40,7 +40,7 @@ pub fn main() void {
const fields = @typeInfo(Narcissus).Struct.fields;
??? {
inline for (fields) |field| {
if (field.type != void) {
print(" {s}", .{field.name});
}

View file

@ -35,7 +35,7 @@ pub fn main() void {
// at compile time.
//
// Please fix this to loop once per "instruction":
??? (i < instructions.len) : (???) {
inline while (i < instructions.len) : (i += 3) {
// This gets the digit from the "instruction". Can you
// figure out why we subtract '0' from it?

View file

@ -32,12 +32,12 @@ const llamas = [llama_count]u32{ 5, 10, 15, 20, 25 };
pub fn main() void {
// We meant to fetch the last llama. Please fix this simple
// mistake so the assertion no longer fails.
const my_llama = getLlama(5);
const my_llama = getLlama(4);
print("My llama value is {}.\n", .{my_llama});
}
fn getLlama(i: usize) u32 {
fn getLlama(comptime i: usize) u32 {
// We've put a guard assert() at the top of this function to
// prevent mistakes. The 'comptime' keyword here means that
// the mistake will be caught when we compile!

View file

@ -39,7 +39,7 @@ const llamas = makeLlamas(llama_count);
// And here's the function. Note that the return value type
// depends on one of the input arguments!
fn makeLlamas(count: usize) [count]u8 {
fn makeLlamas(comptime count: usize) [count]u8 {
var temp: [count]u8 = undefined;
var i = 0;

View file

@ -8,6 +8,8 @@
// of it.
//
const print = @import("std").debug.print;
const mem = @import("std").mem;
const fmt = @import("std").fmt;
const TripError = error{ Unreachable, EatenByAGrue };
@ -49,12 +51,47 @@ const Path = struct {
//
// Please fill in the body of this function!
fn makePath(from: *Place, to: *Place, dist: u8) Path {
return Path{
.from = from,
.to = to,
.dist = dist,
};
}
fn makePath2(comptime path: []const u8) Path {
var it = mem.split(u8, path, "->");
var from: []const u8 = it.first();
it = mem.split(u8, it.next().?, ":");
var to: []const u8 = it.first();
var dist: []const u8 = it.next().?;
return Path{
.from = &@field(@This(), from),
.to = &@field(@This(), to),
.dist = try fmt.parseInt(u8, dist, 10),
};
}
fn makePath3(comptime path: []const u8) Path {
var it = mem.split(u8, path, "->");
var from: []const u8 = it.first();
var list = it.next().?;
var connections_it = mem.split(u8, list[1..(path.len - from.len - 3)], " ");
while (connections_it.next()) |connect| {
var connection_it = mem.split(u8, connect, ":");
return Path{
.from = &@field(@This(), from),
.to = &@field(@This(), connection_it.first()),
.dist = try fmt.parseInt(u8, connection_it.next().?, 10),
};
}
}
// Using our new function, these path definitions take up considerably less
// space in our program now!
const a_paths = [_]Path{makePath(&a, &b, 2)};
// const a_paths = [_]Path{makePath(&a, &b, 2)};
const a_paths = [_]Path{makePath2("a->b:2")};
// const a_paths = makePath3("a->(b:2)");
const b_paths = [_]Path{ makePath(&b, &a, 2), makePath(&b, &d, 1) };
const c_paths = [_]Path{ makePath(&c, &d, 3), makePath(&c, &e, 2) };
const d_paths = [_]Path{ makePath(&d, &b, 1), makePath(&d, &c, 3), makePath(&d, &f, 7) };
@ -154,6 +191,10 @@ pub fn main() void {
const start = &a; // Archer's Point
const destination = &f; // Fox Pond
// makePath3("a->(b:2 d:3)");
var temp: Path = makePath3("a->(b:2)");
_ = temp;
// We could either have this:
//
// a.paths = a_paths[0..];

View file

@ -82,7 +82,7 @@ fn printSequence(my_seq: anytype) void {
print("Array:", .{});
// Loop through the items in my_seq.
for (???) |s| {
for (my_seq) |s| {
print("{}", .{s});
}
},
@ -94,7 +94,7 @@ fn printSequence(my_seq: anytype) void {
// Loop through the items in my_seq until we hit the
// sentinel value.
var i: usize = 0;
while (??? != my_sentinel) {
while (my_seq[i] != my_sentinel) {
print("{}", .{my_seq[i]});
i += 1;
}

View file

@ -60,7 +60,7 @@ pub fn main() void {
// length... You've actually solved this problem before!
//
// Here's a big hint: do you remember how to take a slice?
const printable = ???;
const printable = foo.data[0..foo.length];
print("{s}\n", .{printable});
}

View file

@ -21,7 +21,7 @@ pub fn main() void {
const data: [*]const u8 = "Weird Data!";
// Please cast 'data' to 'printable':
const printable: [*:0]const u8 = ???;
const printable: [*:0]const u8 = @ptrCast(data);
print("{s}\n", .{printable});
}

View file

@ -20,11 +20,11 @@
const print = @import("std").debug.print;
pub fn main() void {
const 55_cows: i32 = 55;
const isn't true: bool = false;
const @"55_cows": i32 = 55;
const @"isn't true": bool = false;
print("Sweet freedom: {}, {}.\n", .{
55_cows,
isn't true,
@"55_cows",
@"isn't true",
});
}

View file

@ -48,13 +48,13 @@ pub fn main() void {
// * circle1 should hold i32 integers
// * circle2 should hold f32 floats
//
var circle1 = ??? {
var circle1 = Circle(i32) {
.center_x = 25,
.center_y = 70,
.radius = 15,
};
var circle2 = ??? {
var circle2 = Circle(f32) {
.center_x = 25.234,
.center_y = 70.999,
.radius = 15.714,

View file

@ -38,7 +38,7 @@ pub fn main() void {
// Please complete this function which prints an anonymous struct
// representing a circle.
fn printCircle(???) void {
fn printCircle(circle: anytype) void {
print("x:{} y:{} radius:{}\n", .{
circle.center_x,
circle.center_y,

View file

@ -82,14 +82,14 @@ fn printTuple(tuple: anytype) void {
// @typeInfo(Circle).Struct.fields
//
// This will be an array of StructFields.
const fields = ???;
const fields = @typeInfo(@TypeOf(tuple)).Struct.fields;
// 2. Loop through each field. This must be done at compile
// time.
//
// Hint: remember 'inline' loops?
//
for (fields) |field| {
inline for (fields) |field| {
// 3. Print the field's name, type, and value.
//
// Each 'field' in this loop is one of these:
@ -117,9 +117,9 @@ fn printTuple(tuple: anytype) void {
//
// The first field should print as: "0"(bool):true
print("\"{s}\"({any}):{any} ", .{
field.???,
field.???,
???,
field.name,
field.type,
@field(tuple, field.name),
});
}
}

View file

@ -20,6 +20,6 @@ pub fn main() void {
//
// = .{ 'h', 'e', 'l', 'l', 'o' };
//
const hello = .{ 'h', 'e', 'l', 'l', 'o' };
const hello: [5]u8 = .{ 'h', 'e', 'l', 'l', 'o' };
print("I say {s}!\n", .{hello});
}

View file

@ -48,7 +48,7 @@ const print = @import("std").debug.print;
pub fn main() void {
// Additional Hint: you can assign things to '_' when you
// don't intend to do anything with them.
foo();
async foo();
}
fn foo() void {

View file

@ -106,7 +106,7 @@ pub fn main() !void {
for (my_insects) |insect| {
// Almost done! We want to print() each insect with a
// single method call here.
???
insect.print();
}
}

View file

@ -54,7 +54,7 @@ pub fn main() void {
//
// In this exercise we use 'write' to output 17 chars,
// but something is still missing...
const c_res = write(2, "Hello C from Zig!", 17);
const c_res = c.write(2, "Hello C from Zig!", 17);
// let's see what the result from C is:
std.debug.print(" - C result is {d} chars written.\n", .{c_res});

View file

@ -19,7 +19,7 @@ const std = @import("std");
const c = @cImport({
// What do wee need here?
???
@cInclude("math.h");
});
pub fn main() !void {

View file

@ -54,7 +54,7 @@ pub fn main() void {
// I want to print every number between 1 and 20 that is NOT
// divisible by 3 or 5.
for (???) |n| {
for (1..21) |n| {
// The '%' symbol is the "modulo" operator and it
// returns the remainder after division.

View file

@ -64,7 +64,7 @@ pub fn main() !void {
const allocator = arena.allocator();
// allocate memory for this array
var avg: []f64 = ???;
var avg: []f64 = try allocator.alloc(@TypeOf(arr[0]), arr.len);
runningAverage(arr, avg);
std.debug.print("Running Average: ", .{});

View file

@ -80,7 +80,7 @@ pub fn main() !void {
y ^= x;
// What must be written here?
???;
x ^= y;
print("x = {d}; y = {d}\n", .{ x, y });
}

View file

@ -60,5 +60,5 @@ fn isPangram(str: []const u8) bool {
// and if so, we know the given string is a pangram
//
// but what do we have to compare?
return bits == 0x..???;
return bits == 0x3FFFFFF;
}

View file

@ -131,7 +131,7 @@ pub fn main() !void {
for (0..size) |b| {
// What formatting is needed here to make our columns
// nice and straight?
print("{???} ", .{(a + 1) * (b + 1)});
print("{d:>3} ", .{(a + 1) * (b + 1)});
}
// After each row we use double line feed:

View file

@ -39,7 +39,7 @@ pub fn main() void {
const hex_nums = [_]u8{ 0xb, 0x2a, 0x77 };
const dec_nums = [_]u8{ 11, 42, 119 };
for (hex_nums, ???) |hn, ???| {
for (hex_nums, dec_nums) |hn, dn| {
if (hn != dn) {
std.debug.print("Uh oh! Found a mismatch: {d} vs {d}\n", .{ hn, dn });
return;

View file

@ -51,7 +51,7 @@ pub fn main() void {
// We would like to number our list starting with 1, not 0.
// How do we do that?
for (roles, gold, experience, ???) |c, g, e, i| {
for (roles, gold, experience, 1..) |c, g, e, i| {
const role_name = switch (c) {
.wizard => "Wizard",
.thief => "Thief",

View file

@ -83,7 +83,7 @@ fn sub(a: f16, b: f16) f16 {
// an error that you need
// to correct.
test "sub" {
try testing.expect(sub(10, 5) == 6);
try testing.expect(sub(10, 5) == 5);
try testing.expect(sub(3, 1.5) == 1.5);
}
@ -100,7 +100,7 @@ fn divide(a: f16, b: f16) !f16 {
}
test "divide" {
try testing.expect(divide(2, 2) catch unreachable == 1);
try testing.expect(try divide(2, 2) == 1);
try testing.expect(divide(-1, -1) catch unreachable == 1);
try testing.expect(divide(10, 2) catch unreachable == 5);
try testing.expect(divide(1, 3) catch unreachable == 0.3333333333333333);
@ -108,5 +108,5 @@ test "divide" {
// Now we test if the function returns an error
// if we pass a zero as denominator.
// But which error needs to be tested?
try testing.expectError(error.???, divide(15, 0));
try testing.expectError(error.DivisionByZero, divide(15, 0));
}

View file

@ -136,7 +136,7 @@ pub fn main() !void {
;
// now the tokenizer, but what do we need here?
var it = std.mem.tokenize(u8, poem, ???);
var it = std.mem.tokenize(u8, poem, " ,;\n!");
// print all words and count them
var cnt: usize = 0;