Skip to content

Commit

Permalink
Merge pull request #14 from adnilsson/space-age
Browse files Browse the repository at this point in the history
Space age
  • Loading branch information
adnilsson authored Jun 17, 2024
2 parents 91fa43f + 8a02b15 commit 5d30c5b
Show file tree
Hide file tree
Showing 10 changed files with 447 additions and 0 deletions.
40 changes: 40 additions & 0 deletions space-age/.exercism/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
{
"authors": [
"IanWhitney"
],
"contributors": [
"ashleygwilliams",
"bobahop",
"coriolinus",
"cwhakes",
"durka",
"eddyp",
"efx",
"ErikSchierboom",
"IanWhitney",
"joshgoebel",
"lutostag",
"nfiles",
"ocstl",
"petertseng",
"rofrol",
"stringparser",
"xakon",
"ZapAnton"
],
"files": {
"solution": [
"src/lib.rs",
"Cargo.toml"
],
"test": [
"tests/space-age.rs"
],
"example": [
".meta/example.rs"
]
},
"blurb": "Given an age in seconds, calculate how old someone is in terms of a given planet's solar years.",
"source": "Partially inspired by Chapter 1 in Chris Pine's online Learn to Program tutorial.",
"source_url": "https://pine.fm/LearnToProgram/?Chapter=01"
}
1 change: 1 addition & 0 deletions space-age/.exercism/metadata.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"track":"rust","exercise":"space-age","id":"3dae4658c3ae4a61a8c4c20ae6c63bda","url":"https://exercism.org/tracks/rust/exercises/space-age","handle":"adnilsson","is_requester":true,"auto_approve":false}
8 changes: 8 additions & 0 deletions space-age/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# Generated by Cargo
# will have compiled files and executables
/target/
**/*.rs.bk

# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries
# More information here http://doc.crates.io/guide.html#cargotoml-vs-cargolock
Cargo.lock
7 changes: 7 additions & 0 deletions space-age/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
[package]
edition = "2021"
name = "space-age"
version = "1.2.0"

[dependencies]
planet_macro_derive = { path = "./planet_macro_derive" }
86 changes: 86 additions & 0 deletions space-age/HELP.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
# Help

## Running the tests

Execute the tests with:

```bash
$ cargo test
```

All but the first test have been ignored. After you get the first test to
pass, open the tests source file which is located in the `tests` directory
and remove the `#[ignore]` flag from the next test and get the tests to pass
again. Each separate test is a function with `#[test]` flag above it.
Continue, until you pass every test.

If you wish to run _only ignored_ tests without editing the tests source file, use:

```bash
$ cargo test -- --ignored
```

If you are using Rust 1.51 or later, you can run _all_ tests with

```bash
$ cargo test -- --include-ignored
```

To run a specific test, for example `some_test`, you can use:

```bash
$ cargo test some_test
```

If the specific test is ignored, use:

```bash
$ cargo test some_test -- --ignored
```

To learn more about Rust tests refer to the online [test documentation][rust-tests].

[rust-tests]: https://doc.rust-lang.org/book/ch11-02-running-tests.html

## Submitting your solution

You can submit your solution using the `exercism submit src/lib.rs Cargo.toml` command.
This command will upload your solution to the Exercism website and print the solution page's URL.

It's possible to submit an incomplete solution which allows you to:

- See how others have completed the exercise
- Request help from a mentor

## Need to get help?

If you'd like help solving the exercise, check the following pages:

- The [Rust track's documentation](https://exercism.org/docs/tracks/rust)
- The [Rust track's programming category on the forum](https://forum.exercism.org/c/programming/rust)
- [Exercism's programming category on the forum](https://forum.exercism.org/c/programming/5)
- The [Frequently Asked Questions](https://exercism.org/docs/using/faqs)

Should those resources not suffice, you could submit your (incomplete) solution to request mentoring.

## Rust Installation

Refer to the [exercism help page][help-page] for Rust installation and learning
resources.

## Submitting the solution

Generally you should submit all files in which you implemented your solution (`src/lib.rs` in most cases). If you are using any external crates, please consider submitting the `Cargo.toml` file. This will make the review process faster and clearer.

## Feedback, Issues, Pull Requests

The GitHub [track repository][github] is the home for all of the Rust exercises. If you have feedback about an exercise, or want to help implement new exercises, head over there and create an issue. Members of the rust track team are happy to help!

If you want to know more about Exercism, take a look at the [contribution guide].

## Submitting Incomplete Solutions
It's possible to submit an incomplete solution so you can see how others have completed the exercise.

[help-page]: https://exercism.org/tracks/rust/learning
[github]: https://github.com/exercism/rust
[contribution guide]: https://exercism.org/docs/community/contributors
102 changes: 102 additions & 0 deletions space-age/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
# Space Age

Welcome to Space Age on Exercism's Rust Track.
If you need help running the tests or submitting your code, check out `HELP.md`.

## Introduction

The year is 2525 and you've just embarked on a journey to visit all planets in the Solar System (Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus and Neptune).
The first stop is Mercury, where customs require you to fill out a form (bureaucracy is apparently _not_ Earth-specific).
As you hand over the form to the customs officer, they scrutinize it and frown.
"Do you _really_ expect me to believe you're just 50 years old?
You must be closer to 200 years old!"

Amused, you wait for the customs officer to start laughing, but they appear to be dead serious.
You realize that you've entered your age in _Earth years_, but the officer expected it in _Mercury years_!
As Mercury's orbital period around the sun is significantly shorter than Earth, you're actually a lot older in Mercury years.
After some quick calculations, you're able to provide your age in Mercury Years.
The customs officer smiles, satisfied, and waves you through.
You make a mental note to pre-calculate your planet-specific age _before_ future customs checks, to avoid such mix-ups.

~~~~exercism/note
If you're wondering why Pluto didn't make the cut, go watch [this YouTube video][pluto-video].
[pluto-video]: https://www.youtube.com/watch?v=Z_2gbGXzFbs
~~~~

## Instructions

Given an age in seconds, calculate how old someone would be on a planet in our Solar System.

One Earth year equals 365.25 Earth days, or 31,557,600 seconds.
If you were told someone was 1,000,000,000 seconds old, their age would be 31.69 Earth-years.

For the other planets, you have to account for their orbital period in Earth Years:

| Planet | Orbital period in Earth Years |
| ------- | ----------------------------- |
| Mercury | 0.2408467 |
| Venus | 0.61519726 |
| Earth | 1.0 |
| Mars | 1.8808158 |
| Jupiter | 11.862615 |
| Saturn | 29.447498 |
| Uranus | 84.016846 |
| Neptune | 164.79132 |

~~~~exercism/note
The actual length of one complete orbit of the Earth around the sun is closer to 365.256 days (1 sidereal year).
The Gregorian calendar has, on average, 365.2425 days.
While not entirely accurate, 365.25 is the value used in this exercise.
See [Year on Wikipedia][year] for more ways to measure a year.
[year]: https://en.wikipedia.org/wiki/Year#Summary
~~~~

## Topics

Some Rust topics you may want to read about while solving this problem:

- Traits, both the From trait and [implementing your own traits](https://doc.rust-lang.org/book/ch10-02-traits.html)
- [Default method implementations](https://doc.rust-lang.org/book/ch10-02-traits.html#default-implementations) for traits
- Macros, the use of a macro could reduce boilerplate and increase readability
for this exercise. For instance,
[a macro can implement a trait for multiple types at once](https://stackoverflow.com/questions/39150216/implementing-a-trait-for-multiple-types-at-once),
though it is fine to implement `years_during` in the Planet trait itself. A macro could
define both the structs and their implementations. Info to get started with macros can
be found at:

- [The Macros chapter in The Rust Programming Language](https://doc.rust-lang.org/stable/book/ch19-06-macros.html)
- [an older version of the Macros chapter with helpful detail](https://doc.rust-lang.org/1.30.0/book/first-edition/macros.html)
- [Rust By Example](https://doc.rust-lang.org/stable/rust-by-example/macros.html)

## Source

### Created by

- @IanWhitney

### Contributed to by

- @ashleygwilliams
- @bobahop
- @coriolinus
- @cwhakes
- @durka
- @eddyp
- @efx
- @ErikSchierboom
- @IanWhitney
- @joshgoebel
- @lutostag
- @nfiles
- @ocstl
- @petertseng
- @rofrol
- @stringparser
- @xakon
- @ZapAnton

### Based on

Partially inspired by Chapter 1 in Chris Pine's online Learn to Program tutorial. - https://pine.fm/LearnToProgram/?Chapter=01
11 changes: 11 additions & 0 deletions space-age/planet_macro_derive/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
[package]
name = "planet_macro_derive"
version = "0.1.0"
edition = "2021"

[lib]
proc-macro = true

[dependencies]
syn = "2.0"
quote = "1.0"
56 changes: 56 additions & 0 deletions space-age/planet_macro_derive/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
use proc_macro::TokenStream;
use quote::quote;
use syn::{self};

#[proc_macro_derive(Planet, attributes(orbital_period))]
pub fn planet_macro_derive(input: TokenStream) -> TokenStream {
// Construct a representation of Rust code as a syntax tree
// that we can manipulate
let ast = syn::parse_macro_input!(input as syn::DeriveInput);

// Build the trait implementation
impl_planet_macro(&ast)
}

fn impl_planet_macro(ast: &syn::DeriveInput) -> TokenStream {
let name = &ast.ident;

// Iterate over the attributes and do something with them
let orbital_period_attr = ast
.attrs
.iter()
.find(|&a| a.path().is_ident("orbital_period"))
.expect("missing the 'orbital_period' attribute");

let mut orbital_period: f64 = 0.0;
orbital_period_attr
.parse_nested_meta(|meta| {
if !meta.path.is_ident("years") {
return Err(meta.error("the only supported key is 'years'"));
}
let literal: syn::Lit = meta.value()?.parse()?;

// Try to convert the attribute value expression to a float
orbital_period = literal_to_float(&literal)?;
Ok(())
})
.expect("failed to parse the 'orbital_period' attribute");

let gen = quote! {
impl Planet for #name {
const ORBITAL_PERIOD_IN_EARTH_YEARS: f64 = #orbital_period;
}
};
gen.into()
}

fn literal_to_float(literal: &syn::Lit) -> syn::Result<f64> {
match literal {
syn::Lit::Float(f) => f.base10_parse(),
syn::Lit::Int(i) => i.base10_parse(),
default => Err(syn::Error::new_spanned(
default,
"expected a numerical literal value",
)),
}
}
55 changes: 55 additions & 0 deletions space-age/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
use planet_macro_derive::Planet;

/// A Duration on planet Earth
#[derive(Debug)]
pub struct Duration {
seconds: u64,
}

impl From<u64> for Duration {
fn from(s: u64) -> Self {
Self { seconds: s }
}
}

pub trait Planet {
const EARTH_YEAR_SECONDS: f64 = 31_557_600.0;
const ORBITAL_PERIOD_IN_EARTH_YEARS: f64;

fn years_during(d: &Duration) -> f64 {
let earth_years = d.seconds as f64 / Self::EARTH_YEAR_SECONDS;
earth_years / Self::ORBITAL_PERIOD_IN_EARTH_YEARS
}
}

#[derive(Planet)]
#[orbital_period(years = 0.2408467)]
pub struct Mercury;

#[derive(Planet)]
#[orbital_period(years = 0.61519726)]
pub struct Venus;

#[derive(Planet)]
#[orbital_period(years = 1)]
pub struct Earth;

#[derive(Planet)]
#[orbital_period(years = 1.8808158)]
pub struct Mars;

#[derive(Planet)]
#[orbital_period(years = 11.862615)]
pub struct Jupiter;

#[derive(Planet)]
#[orbital_period(years = 29.447498)]
pub struct Saturn;

#[derive(Planet)]
#[orbital_period(years = 84.016846)]
pub struct Uranus;

#[derive(Planet)]
#[orbital_period(years = 164.79132)]
pub struct Neptune;
Loading

0 comments on commit 5d30c5b

Please sign in to comment.