space age

This commit is contained in:
Ruidy 2022-02-02 08:33:47 -04:00
parent cef0040dd0
commit 8c66019956
42 changed files with 927 additions and 0 deletions

View file

@ -0,0 +1,31 @@
{
"blurb": "Implement a binary search algorithm.",
"authors": [
"bernardoamc"
],
"contributors": [
"angelikatyborska",
"Cohen-Carlisle",
"devonestes",
"lpil",
"martinsvalin",
"neenjaw",
"parkerl",
"screamingjungle",
"sotojuan",
"waiting-for-dev"
],
"files": {
"solution": [
"lib/binary_search.ex"
],
"test": [
"test/binary_search_test.exs"
],
"example": [
".meta/example.ex"
]
},
"source": "Wikipedia",
"source_url": "http://en.wikipedia.org/wiki/Binary_search_algorithm"
}

View file

@ -0,0 +1 @@
{"track":"elixir","exercise":"binary-search","id":"5e40f287d55a4b898fda154d02e346fe","url":"https://exercism.org/tracks/elixir/exercises/binary-search","handle":"rjNemo","is_requester":true,"auto_approve":false}

View file

@ -0,0 +1,4 @@
# Used by "mix format"
[
inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"]
]

24
binary-search/.gitignore vendored Normal file
View file

@ -0,0 +1,24 @@
# The directory Mix will write compiled artifacts to.
/_build/
# If you run "mix test --cover", coverage assets end up here.
/cover/
# The directory Mix downloads your dependencies sources to.
/deps/
# Where third-party dependencies like ExDoc output generated docs.
/doc/
# Ignore .fetch files in case you like to edit your project deps locally.
/.fetch
# If the VM crashes, it generates a dump, let's ignore it too.
erl_crash.dump
# Also ignore archive artifacts (built via "mix archive.build").
*.ez
# Ignore package tarball (built via "mix hex.build").
binary_search-*.tar

75
binary-search/HELP.md Normal file
View file

@ -0,0 +1,75 @@
# Help
## Running the tests
From the terminal, change to the base directory of the exercise then execute the tests with:
```bashv
$ mix test
```
This will execute the test file found in the `test` subfolder -- a file ending in `_test.exs`
Documentation:
* [`mix test` - Elixir's test execution tool](https://hexdocs.pm/mix/Mix.Tasks.Test.html)
* [`ExUnit` - Elixir's unit test library](https://hexdocs.pm/ex_unit/ExUnit.html)
## Pending tests
In test suites of practice exercises, all but the first test have been tagged to be skipped.
Once you get a test passing, you can unskip the next one by commenting out the relevant `@tag :pending` with a `#` symbol.
For example:
```elixir
# @tag :pending
test "shouting" do
assert Bob.hey("WATCH OUT!") == "Whoa, chill out!"
end
```
If you wish to run all tests at once, you can include all skipped test by using the `--include` flag on the `mix test` command:
```bash
$ mix test --include pending
```
Or, you can enable all the tests by commenting out the `ExUnit.configure` line in the file `test/test_helper.exs`.
```elixir
# ExUnit.configure(exclude: :pending, trace: true)
```
## Useful `mix test` options
* `test/<FILE>.exs:LINENUM` - runs only a single test, the test from `<FILE>.exs` whose definition is on line `LINENUM`
* `--failed` - runs only tests that failed the last time they ran
* `--max-failures` - the suite stops evaluating tests when this number of test failures
is reached
* `--seed 0` - disables randomization so the tests in a single file will always be ran
in the same order they were defined in
## Submitting your solution
You can submit your solution using the `exercism submit lib/binary_search.ex` 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 [Elixir track's documentation](https://exercism.org/docs/tracks/elixir)
- [Exercism's support channel on gitter](https://gitter.im/exercism/support)
- The [Frequently Asked Questions](https://exercism.org/docs/using/faqs)
Should those resources not suffice, you could submit your (incomplete) solution to request mentoring.
If you're stuck on something, it may help to look at some of the [available resources](https://exercism.org/docs/tracks/elixir/resources) out there where answers might be found.
If you can't find what you're looking for in the documentation, feel free to ask help in the Exercism's BEAM [gitter channel](https://gitter.im/exercism/xerlang).

63
binary-search/README.md Normal file
View file

@ -0,0 +1,63 @@
# Binary Search
Welcome to Binary Search on Exercism's Elixir Track.
If you need help running the tests or submitting your code, check out `HELP.md`.
## Instructions
Implement a binary search algorithm.
Searching a sorted collection is a common task. A dictionary is a sorted
list of word definitions. Given a word, one can find its definition. A
telephone book is a sorted list of people's names, addresses, and
telephone numbers. Knowing someone's name allows one to quickly find
their telephone number and address.
If the list to be searched contains more than a few items (a dozen, say)
a binary search will require far fewer comparisons than a linear search,
but it imposes the requirement that the list be sorted.
In computer science, a binary search or half-interval search algorithm
finds the position of a specified input value (the search "key") within
an array sorted by key value.
In each step, the algorithm compares the search key value with the key
value of the middle element of the array.
If the keys match, then a matching element has been found and its index,
or position, is returned.
Otherwise, if the search key is less than the middle element's key, then
the algorithm repeats its action on the sub-array to the left of the
middle element or, if the search key is greater, on the sub-array to the
right.
If the remaining array to be searched is empty, then the key cannot be
found in the array and a special "not found" indication is returned.
A binary search halves the number of items to check with each iteration,
so locating an item (or determining its absence) takes logarithmic time.
A binary search is a dichotomic divide and conquer search algorithm.
## Source
### Created by
- @bernardoamc
### Contributed to by
- @angelikatyborska
- @Cohen-Carlisle
- @devonestes
- @lpil
- @martinsvalin
- @neenjaw
- @parkerl
- @screamingjungle
- @sotojuan
- @waiting-for-dev
### Based on
Wikipedia - http://en.wikipedia.org/wiki/Binary_search_algorithm

View file

@ -0,0 +1,35 @@
defmodule BinarySearch do
@doc """
Searches for a key in the tuple using the binary search algorithm.
It returns :not_found if the key is not in the tuple.
Otherwise returns {:ok, index}.
## Examples
iex> BinarySearch.search({}, 2)
:not_found
iex> BinarySearch.search({1, 3, 5}, 2)
:not_found
iex> BinarySearch.search({1, 3, 5}, 5)
{:ok, 2}
"""
@spec search(tuple, integer) :: {:ok, integer} | :not_found
def search({key}, key), do: {:ok, 0}
def search(numbers, key) do
count = tuple_size(numbers)
mid = div(count, 2)
{left, right} = numbers |> Tuple.to_list() |> Enum.split(mid)
cond do
key > List.last(left) -> search(right, key)
key < hd(right) -> search(left, key)
end
end
# def search(_, _), do: :not_found
end

28
binary-search/mix.exs Normal file
View file

@ -0,0 +1,28 @@
defmodule BinarySearch.MixProject do
use Mix.Project
def project do
[
app: :binary_search,
version: "0.1.0",
# elixir: "~> 1.8",
start_permanent: Mix.env() == :prod,
deps: deps()
]
end
# Run "mix help compile.app" to learn about applications.
def application do
[
extra_applications: [:logger]
]
end
# Run "mix help deps" to learn about dependencies.
defp deps do
[
# {:dep_from_hexpm, "~> 0.3.0"},
# {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"}
]
end
end

View file

@ -0,0 +1,65 @@
defmodule BinarySearchTest do
use ExUnit.Case
test "finds a value in a tuple with one element" do
assert BinarySearch.search({6}, 6) == {:ok, 0}
assert BinarySearch.search({3}, 3) == {:ok, 0}
end
test "finds a value in the middle of a tuple" do
assert BinarySearch.search({1, 2, 3, 4, 5, 6}, 4) == {:ok, 2}
assert BinarySearch.search({1, 3, 4, 6, 8, 9, 11}, 6) == {:ok, 3}
end
test "finds a value at the beginning of a tuple" do
assert BinarySearch.search({1, 2, 4, 5, 6}, 1) == {:ok, 0}
assert BinarySearch.search({1, 3, 4, 5, 8, 9, 11}, 1) == {:ok, 0}
end
@tag :pending
test "finds a value at the end of a tuple" do
assert BinarySearch.search({1, 2, 4, 5, 6}, 6) == {:ok, 4}
assert BinarySearch.search({1, 3, 4, 5, 8, 9, 11}, 11) == {:ok, 6}
end
@tag :pending
test "finds a value in a tuple of odd length" do
tuple = {1, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 634}
assert BinarySearch.search(tuple, 144) == {:ok, 9}
end
@tag :pending
test "finds a value in a tuple of even length" do
tuple = {1, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377}
assert BinarySearch.search(tuple, 21) == {:ok, 5}
assert BinarySearch.search(tuple, 34) == {:ok, 6}
end
@tag :pending
test "identifies that a value is not included in the tuple" do
assert BinarySearch.search({2, 4, 6}, 3) == :not_found
assert BinarySearch.search({1, 3, 4, 6, 8, 9, 11}, 7) == :not_found
end
@tag :pending
test "a value smaller than the tuple's smallest value is not found" do
assert BinarySearch.search({2, 4, 6}, 1) == :not_found
assert BinarySearch.search({1, 3, 4, 6, 8, 9, 11}, 0) == :not_found
end
@tag :pending
test "a value larger than the tuple's largest value is not found" do
assert BinarySearch.search({2, 4, 6}, 9) == :not_found
assert BinarySearch.search({1, 3, 4, 6, 8, 9, 11}, 13) == :not_found
end
@tag :pending
test "nothing is found in an empty tuple" do
assert BinarySearch.search({}, 1) == :not_found
end
@tag :pending
test "nothing is found when the left and right bounds cross" do
assert BinarySearch.search({1, 2}, 0) == :not_found
end
end

View file

@ -0,0 +1,2 @@
ExUnit.start()
ExUnit.configure(exclude: :pending, trace: true)

View file

@ -0,0 +1,18 @@
{
"authors": ["jiegillet"],
"contributors": [],
"files": {
"example": [
".meta/example.ex"
],
"solution": [
"lib/resistor_color_duo.ex"
],
"test": [
"test/resistor_color_duo_test.exs"
]
},
"blurb": "Convert color codes, as used on resistors, to a numeric value.",
"source": "Maud de Vries, Erik Schierboom",
"source_url": "https://github.com/exercism/problem-specifications/issues/1464"
}

View file

@ -0,0 +1,4 @@
# Used by "mix format"
[
inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"]
]

View file

@ -0,0 +1,75 @@
# Help
## Running the tests
From the terminal, change to the base directory of the exercise then execute the tests with:
```bash
$ mix test
```
This will execute the test file found in the `test` subfolder -- a file ending in `_test.exs`
Documentation:
* [`mix test` - Elixir's test execution tool](https://hexdocs.pm/mix/Mix.Tasks.Test.html)
* [`ExUnit` - Elixir's unit test library](https://hexdocs.pm/ex_unit/ExUnit.html)
## Pending tests
In test suites of practice exercises, all but the first test have been tagged to be skipped.
Once you get a test passing, you can unskip the next one by commenting out the relevant `@tag :pending` with a `#` symbol.
For example:
```elixir
# @tag :pending
test "shouting" do
assert Bob.hey("WATCH OUT!") == "Whoa, chill out!"
end
```
If you wish to run all tests at once, you can include all skipped test by using the `--include` flag on the `mix test` command:
```bash
$ mix test --include pending
```
Or, you can enable all the tests by commenting out the `ExUnit.configure` line in the file `test/test_helper.exs`.
```elixir
# ExUnit.configure(exclude: :pending, trace: true)
```
## Useful `mix test` options
* `test/<FILE>.exs:LINENUM` - runs only a single test, the test from `<FILE>.exs` whose definition is on line `LINENUM`
* `--failed` - runs only tests that failed the last time they ran
* `--max-failures` - the suite stops evaluating tests when this number of test failures
is reached
* `--seed 0` - disables randomization so the tests in a single file will always be ran
in the same order they were defined in
## Submitting your solution
You can submit your solution using the `exercism submit lib/resistor_color_duo.ex` 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 [Elixir track's documentation](https://exercism.org/docs/tracks/elixir)
- [Exercism's support channel on gitter](https://gitter.im/exercism/support)
- The [Frequently Asked Questions](https://exercism.org/docs/using/faqs)
Should those resources not suffice, you could submit your (incomplete) solution to request mentoring.
If you're stuck on something, it may help to look at some of the [available resources](https://exercism.org/docs/tracks/elixir/resources) out there where answers might be found.
If you can't find what you're looking for in the documentation, feel free to ask help in the Exercism's BEAM [gitter channel](https://gitter.im/exercism/xerlang).

View file

@ -0,0 +1,48 @@
# Resistor Color Duo
Welcome to Resistor Color Duo on Exercism's Elixir Track.
If you need help running the tests or submitting your code, check out `HELP.md`.
## Instructions
If you want to build something using a Raspberry Pi, you'll probably use _resistors_.
For this exercise, you need to know two things about them:
* Each resistor has a resistance value.
* Resistors are small - so small in fact that if you printed the resistance value on them, it would be hard to read.
To get around this problem, manufacturers print color-coded bands onto the resistors to denote their resistance values.
Each band has a position and a numeric value.
The first 2 bands of a resistor have a simple encoding scheme: each color maps to a single number.
For example, if they printed a brown band (value 1) followed by a green band (value 5), it would translate to the number 15.
In this exercise you are going to create a helpful program so that you don't have to remember the values of the bands.
The program will take color names as input and output a two digit number, even if the input is more than two colors!
The band colors are encoded as follows:
* Black: 0
* Brown: 1
* Red: 2
* Orange: 3
* Yellow: 4
* Green: 5
* Blue: 6
* Violet: 7
* Grey: 8
* White: 9
From the example above:
brown-green should return 15
brown-green-violet should return 15 too, ignoring the third color.
## Source
### Created by
- @jiegillet
### Based on
Maud de Vries, Erik Schierboom - https://github.com/exercism/problem-specifications/issues/1464

View file

@ -0,0 +1,6 @@
{application,resistor_color_duo,
[{applications,[kernel,stdlib,elixir,logger]},
{description,"resistor_color_duo"},
{modules,['Elixir.ResistorColorDuo']},
{registered,[]},
{vsn,"0.1.0"}]}.

View file

@ -0,0 +1,26 @@
defmodule ResistorColorDuo do
@colors %{
black: 0,
brown: 1,
red: 2,
orange: 3,
yellow: 4,
green: 5,
blue: 6,
violet: 7,
grey: 8,
white: 9
}
@doc """
Calculate a resistance value from two colors
"""
@spec value(colors :: [atom]) :: integer
def value(colors),
do:
colors
|> Enum.take(2)
|> Enum.map(&Map.get(@colors, &1))
|> Enum.join()
|> String.to_integer()
end

View file

@ -0,0 +1,28 @@
defmodule ResistorColorDuo.MixProject do
use Mix.Project
def project do
[
app: :resistor_color_duo,
version: "0.1.0",
# elixir: "~> 1.8",
start_permanent: Mix.env() == :prod,
deps: deps()
]
end
# Run "mix help compile.app" to learn about applications.
def application do
[
extra_applications: [:logger]
]
end
# Run "mix help deps" to learn about dependencies.
defp deps do
[
# {:dep_from_hexpm, "~> 0.3.0"},
# {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"}
]
end
end

View file

@ -0,0 +1,60 @@
defmodule ResistorColorDuoTest do
use ExUnit.Case
# @tag :pending
test "Brown and black" do
colors = [:brown, :black]
output = ResistorColorDuo.value(colors)
expected = 10
assert output == expected
end
test "Blue and grey" do
colors = [:blue, :grey]
output = ResistorColorDuo.value(colors)
expected = 68
assert output == expected
end
test "Yellow and violet" do
colors = [:yellow, :violet]
output = ResistorColorDuo.value(colors)
expected = 47
assert output == expected
end
test "White and red" do
colors = [:white, :red]
output = ResistorColorDuo.value(colors)
expected = 92
assert output == expected
end
test "Orange and orange" do
colors = [:orange, :orange]
output = ResistorColorDuo.value(colors)
expected = 33
assert output == expected
end
test "Ignore additional colors" do
colors = [:green, :brown, :orange]
output = ResistorColorDuo.value(colors)
expected = 51
assert output == expected
end
test "Black and brown, one digit" do
colors = [:black, :brown]
output = ResistorColorDuo.value(colors)
expected = 1
assert output == expected
end
end

View file

@ -0,0 +1,2 @@
ExUnit.start()
ExUnit.configure(exclude: :pending, trace: true)

View file

@ -14,6 +14,7 @@ defmodule ResistorColor do
grey: 8,
white: 9
}
@doc """
Return the value of a color band
"""

View file

@ -0,0 +1,36 @@
{
"blurb": "Given an age in seconds, calculate how old someone is in terms of a given planet's solar years.",
"authors": [
"rubysolo"
],
"contributors": [
"angelikatyborska",
"Cohen-Carlisle",
"dalexj",
"devonestes",
"henrik",
"jinyeow",
"koriroys",
"kytrinyx",
"lpil",
"neenjaw",
"parkerl",
"pminten",
"sotojuan",
"Teapane",
"waiting-for-dev"
],
"files": {
"solution": [
"lib/space_age.ex"
],
"test": [
"test/space_age_test.exs"
],
"example": [
".meta/example.ex"
]
},
"source": "Partially inspired by Chapter 1 in Chris Pine's online Learn to Program tutorial.",
"source_url": "http://pine.fm/LearnToProgram/?Chapter=01"
}

View file

@ -0,0 +1 @@
{"track":"elixir","exercise":"space-age","id":"9a81858ebd7c46a4a47952bd1535102e","url":"https://exercism.org/tracks/elixir/exercises/space-age","handle":"rjNemo","is_requester":true,"auto_approve":false}

4
space-age/.formatter.exs Normal file
View file

@ -0,0 +1,4 @@
# Used by "mix format"
[
inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"]
]

24
space-age/.gitignore vendored Normal file
View file

@ -0,0 +1,24 @@
# The directory Mix will write compiled artifacts to.
/_build/
# If you run "mix test --cover", coverage assets end up here.
/cover/
# The directory Mix downloads your dependencies sources to.
/deps/
# Where third-party dependencies like ExDoc output generated docs.
/doc/
# Ignore .fetch files in case you like to edit your project deps locally.
/.fetch
# If the VM crashes, it generates a dump, let's ignore it too.
erl_crash.dump
# Also ignore archive artifacts (built via "mix archive.build").
*.ez
# Ignore package tarball (built via "mix hex.build").
space_age-*.tar

75
space-age/HELP.md Normal file
View file

@ -0,0 +1,75 @@
# Help
## Running the tests
From the terminal, change to the base directory of the exercise then execute the tests with:
```bash
$ mix test
```
This will execute the test file found in the `test` subfolder -- a file ending in `_test.exs`
Documentation:
* [`mix test` - Elixir's test execution tool](https://hexdocs.pm/mix/Mix.Tasks.Test.html)
* [`ExUnit` - Elixir's unit test library](https://hexdocs.pm/ex_unit/ExUnit.html)
## Pending tests
In test suites of practice exercises, all but the first test have been tagged to be skipped.
Once you get a test passing, you can unskip the next one by commenting out the relevant `@tag :pending` with a `#` symbol.
For example:
```elixir
# @tag :pending
test "shouting" do
assert Bob.hey("WATCH OUT!") == "Whoa, chill out!"
end
```
If you wish to run all tests at once, you can include all skipped test by using the `--include` flag on the `mix test` command:
```bash
$ mix test --include pending
```
Or, you can enable all the tests by commenting out the `ExUnit.configure` line in the file `test/test_helper.exs`.
```elixir
# ExUnit.configure(exclude: :pending, trace: true)
```
## Useful `mix test` options
* `test/<FILE>.exs:LINENUM` - runs only a single test, the test from `<FILE>.exs` whose definition is on line `LINENUM`
* `--failed` - runs only tests that failed the last time they ran
* `--max-failures` - the suite stops evaluating tests when this number of test failures
is reached
* `--seed 0` - disables randomization so the tests in a single file will always be ran
in the same order they were defined in
## Submitting your solution
You can submit your solution using the `exercism submit lib/space_age.ex` 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 [Elixir track's documentation](https://exercism.org/docs/tracks/elixir)
- [Exercism's support channel on gitter](https://gitter.im/exercism/support)
- The [Frequently Asked Questions](https://exercism.org/docs/using/faqs)
Should those resources not suffice, you could submit your (incomplete) solution to request mentoring.
If you're stuck on something, it may help to look at some of the [available resources](https://exercism.org/docs/tracks/elixir/resources) out there where answers might be found.
If you can't find what you're looking for in the documentation, feel free to ask help in the Exercism's BEAM [gitter channel](https://gitter.im/exercism/xerlang).

51
space-age/README.md Normal file
View file

@ -0,0 +1,51 @@
# Space Age
Welcome to Space Age on Exercism's Elixir Track.
If you need help running the tests or submitting your code, check out `HELP.md`.
## Instructions
Given an age in seconds, calculate how old someone would be on:
- Mercury: orbital period 0.2408467 Earth years
- Venus: orbital period 0.61519726 Earth years
- Earth: orbital period 1.0 Earth years, 365.25 Earth days, or 31557600 seconds
- Mars: orbital period 1.8808158 Earth years
- Jupiter: orbital period 11.862615 Earth years
- Saturn: orbital period 29.447498 Earth years
- Uranus: orbital period 84.016846 Earth years
- Neptune: orbital period 164.79132 Earth years
So if you were told someone were 1,000,000,000 seconds old, you should
be able to say that they're 31.69 Earth-years old.
If you're wondering why Pluto didn't make the cut, go watch [this
YouTube video](http://www.youtube.com/watch?v=Z_2gbGXzFbs).
## Source
### Created by
- @rubysolo
### Contributed to by
- @angelikatyborska
- @Cohen-Carlisle
- @dalexj
- @devonestes
- @henrik
- @jinyeow
- @koriroys
- @kytrinyx
- @lpil
- @neenjaw
- @parkerl
- @pminten
- @sotojuan
- @Teapane
- @waiting-for-dev
### Based on
Partially inspired by Chapter 1 in Chris Pine's online Learn to Program tutorial. - http://pine.fm/LearnToProgram/?Chapter=01

View file

@ -0,0 +1,40 @@
defmodule SpaceAge do
@type planet ::
:mercury
| :venus
| :earth
| :mars
| :jupiter
| :saturn
| :uranus
| :neptune
@seconds_in_earth_year 31_557_600
@seconds_in_mercury_year 0.2408467 * @seconds_in_earth_year
@seconds_in_venus_year 0.61519726 * @seconds_in_earth_year
@seconds_in_mars_year 1.8808158 * @seconds_in_earth_year
@seconds_in_jupiter_year 11.862615 * @seconds_in_earth_year
@seconds_in_saturn_year 29.447498 * @seconds_in_earth_year
@seconds_in_uranus_year 84.016846 * @seconds_in_earth_year
@seconds_in_neptune_year 164.79132 * @seconds_in_earth_year
@doc """
Return the number of years a person that has lived for 'seconds' seconds is
aged on 'planet', or an error if 'planet' is not a planet.
"""
@spec age_on(planet, pos_integer) :: {:ok, float} | {:error, String.t()}
def age_on(planet, seconds) do
case planet do
:mercury -> {:ok, seconds / @seconds_in_mercury_year}
:venus -> {:ok, seconds / @seconds_in_venus_year}
:earth -> {:ok, seconds / @seconds_in_earth_year}
:mars -> {:ok, seconds / @seconds_in_mars_year}
:jupiter -> {:ok, seconds / @seconds_in_jupiter_year}
:saturn -> {:ok, seconds / @seconds_in_saturn_year}
:uranus -> {:ok, seconds / @seconds_in_uranus_year}
:neptune -> {:ok, seconds / @seconds_in_neptune_year}
# sorry pluto
_ -> {:error, "not a planet"}
end
end
end

28
space-age/mix.exs Normal file
View file

@ -0,0 +1,28 @@
defmodule SpaceAge.MixProject do
use Mix.Project
def project do
[
app: :space_age,
version: "0.1.0",
# elixir: "~> 1.8",
start_permanent: Mix.env() == :prod,
deps: deps()
]
end
# Run "mix help compile.app" to learn about applications.
def application do
[
extra_applications: [:logger]
]
end
# Run "mix help deps" to learn about dependencies.
defp deps do
[
# {:dep_from_hexpm, "~> 0.3.0"},
# {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"}
]
end
end

View file

@ -0,0 +1,70 @@
defmodule SpaceAgeTest do
use ExUnit.Case
test "age on Earth" do
input = 1_000_000_000
{:ok, age} = SpaceAge.age_on(:earth, input)
assert_in_delta 31.69, age, 0.005
end
test "age on Mercury" do
input = 2_134_835_688
{:ok, age} = SpaceAge.age_on(:earth, input)
assert_in_delta 67.65, age, 0.005
{:ok, age} = SpaceAge.age_on(:mercury, input)
assert_in_delta 280.88, age, 0.005
end
test "age on Venus" do
input = 189_839_836
{:ok, age} = SpaceAge.age_on(:earth, input)
assert_in_delta 6.02, age, 0.005
{:ok, age} = SpaceAge.age_on(:venus, input)
assert_in_delta 9.78, age, 0.005
end
test "age on Mars" do
input = 2_129_871_239
{:ok, age} = SpaceAge.age_on(:earth, input)
assert_in_delta 67.49, age, 0.005
{:ok, age} = SpaceAge.age_on(:mars, input)
assert_in_delta 35.88, age, 0.005
end
test "age on Jupiter" do
input = 901_876_382
{:ok, age} = SpaceAge.age_on(:earth, input)
assert_in_delta 28.58, age, 0.005
{:ok, age} = SpaceAge.age_on(:jupiter, input)
assert_in_delta 2.41, age, 0.005
end
test "age on Saturn" do
input = 2_000_000_000
{:ok, age} = SpaceAge.age_on(:earth, input)
assert_in_delta 63.38, age, 0.005
{:ok, age} = SpaceAge.age_on(:saturn, input)
assert_in_delta 2.15, age, 0.005
end
test "age on Uranus" do
input = 1_210_123_456
{:ok, age} = SpaceAge.age_on(:earth, input)
assert_in_delta 38.35, age, 0.005
{:ok, age} = SpaceAge.age_on(:uranus, input)
assert_in_delta 0.46, age, 0.005
end
test "age on Neptune" do
input = 1_821_023_456
{:ok, age} = SpaceAge.age_on(:earth, input)
assert_in_delta 57.70, age, 0.005
{:ok, age} = SpaceAge.age_on(:neptune, input)
assert_in_delta 0.35, age, 0.005
end
test "invalid planet causes error" do
input = 680_804_807
assert SpaceAge.age_on(:sun, input) == {:error, "not a planet"}
end
end

View file

@ -0,0 +1,2 @@
ExUnit.start()
ExUnit.configure(exclude: :pending, trace: true)