Fall 2023 Rust Exam

Problem 1

Define a function named outside_box that receives three 2-tuples representing xy-positions on a two-dimensional grid. The first is the location of a box's bottom-left corner. The second, the top-right corner. The function returns true if and only if the third point lies outside the box. All coordinates are of type i32. A point on the perimeter is considered inside the box.

Write this as a single expression. Do not write any conditional statements—which does not mean you can't use logical operators. Do not use an explicit return.

Problem 2

Define an enum named Season with variants Spring, Summer, Fall, and Winter. Have it automatically implement the Debug and PartialEq traits to enable printing and comparing.

Give the Season enum an instance method named next that borrows its receiver. It returns the following season. For example: Season::Fall.next()Season::Winter. Do not write an explicit return or if statement.

Problem 3

Define a function named partway that accepts three parameters in the following order: a lower bound of type i32, an upper bound of type i32, and a proportion of type f64. It returns the value between the bounds at the given proportion as an f64. For example partway(10, 20, 0.7)17.0.

Problem 4

Define a main function that expects command-line arguments \(a\), \(b\), and \(c\)—all unsigned integers. The numbers satisfy this relationship:

$$a \lt b \gt c$$

It prints the numbers going up from \(a\) to \(b\) and those going down from \(b\) to \(c\), one number per line. For example, running your program on parameters 1 5 3 yields this output:

1
2
3
4
5
4
3

Problem 5

Define a function named rotate that accepts a borrowed mutable String. It moves the character from the end of the string to the beginning. For example: rotating "idea" yields "aide". Assume the string contains at least one character.

Problem 6

Define a struct named Triangle that has fields base and height, both of type f64.

Define an associated function named new that accepts the base and height as parameters and returns a new instance of the struct.

Define an instance method named area that returns the triangle's area, which is half of the product of its fields. It borrows its receiver.

Problem 7

Define a function named eighties that accepts a borrowed Vec of u32. Each element is a four-digit year. It returns a similar Vec containing only the two-digit forms of the years that occurred in the 1980s. For example: eighties(vec![1983, 1979, 1980, 2005, 2089])vec![83, 80].

Use higher-order functions. Do not write any loops or explicit returns.

Problem 8

Define function closest_pair that accepts a borrowed Vec of u32, which is guaranteed to contain at least two numbers. All elements are unique. It returns as a tuple the two distinct numbers from the vector that are closest together. Assume only one such pair exists. The elements of the pair are ordered by their index. For example, vec![2, 10, 5, 8](10, 8).