|
| 1 | +==================== |
| 2 | +Exercise: Geometry |
| 3 | +==================== |
| 4 | + |
| 5 | +-------------------- |
| 6 | +Geometry Problem |
| 7 | +-------------------- |
| 8 | + |
| 9 | +We will create a few utility functions for 3-dimensional geometry, |
| 10 | +representing a point as :rust:`[f64;3]`. It is up to you to determine the |
| 11 | +function signatures. |
| 12 | + |
| 13 | +:: |
| 14 | + |
| 15 | + // Calculate the magnitude of a vector by summing the squares of its coordinates |
| 16 | + // and taking the square root. Use the `sqrt()` method to calculate the square |
| 17 | + // root, like `v.sqrt()`. |
| 18 | + |
| 19 | + fn magnitude(...) -> f64 { |
| 20 | + todo!() |
| 21 | + } |
| 22 | + |
| 23 | + // Normalize a vector by calculating its magnitude and dividing all of its |
| 24 | + // coordinates by that magnitude. |
| 25 | + |
| 26 | + fn normalize(...) { |
| 27 | + todo!() |
| 28 | + } |
| 29 | + |
| 30 | + // Use the following `main` to test your work. |
| 31 | + |
| 32 | + fn main() { |
| 33 | + println!("Magnitude of a unit vector: {}", magnitude(&[0.0, 1.0, 0.0])); |
| 34 | + |
| 35 | + let mut v = [1.0, 2.0, 9.0]; |
| 36 | + println!("Magnitude of {v:?}: {}", magnitude(&v)); |
| 37 | + normalize(&mut v); |
| 38 | + println!("Magnitude of {v:?} after normalization: {}", magnitude(&v)); |
| 39 | + } |
| 40 | + |
| 41 | +-------------------- |
| 42 | +Geometry Solution |
| 43 | +-------------------- |
| 44 | + |
| 45 | +.. code:: rust |
| 46 | +
|
| 47 | + /// Calculate the magnitude of the given vector. |
| 48 | + fn magnitude(vector: &[f64; 3]) -> f64 { |
| 49 | + let mut mag_squared = 0.0; |
| 50 | + for coord in vector { |
| 51 | + mag_squared += coord * coord; |
| 52 | + } |
| 53 | + mag_squared.sqrt() |
| 54 | + } |
| 55 | +
|
| 56 | + /// Change the magnitude of the vector to 1.0 without changing its direction. |
| 57 | + fn normalize(vector: &mut [f64; 3]) { |
| 58 | + let mag = magnitude(vector); |
| 59 | + for item in vector { |
| 60 | + *item /= mag; |
| 61 | + } |
| 62 | + } |
| 63 | +
|
| 64 | + fn main() { |
| 65 | + println!("Magnitude of a unit vector: {}", magnitude(&[0.0, 1.0, 0.0])); |
| 66 | +
|
| 67 | + let mut v = [1.0, 2.0, 9.0]; |
| 68 | + println!("Magnitude of {v:?}: {}", magnitude(&v)); |
| 69 | + normalize(&mut v); |
| 70 | + println!("Magnitude of {v:?} after normalization: {}", magnitude(&v)); |
| 71 | + } |
| 72 | +
|
| 73 | +------------------------ |
| 74 | +Additional Information |
| 75 | +------------------------ |
| 76 | + |
| 77 | +Note that in :rust:`normalize` we wrote :rust:`*item /= mag` to modify each element. |
| 78 | + |
| 79 | +This is because we’re iterating using a mutable reference to an array, which causes the :rust:`for` loop to give mutable references to each element. |
0 commit comments