From 2529c131d77c28d076fcb6ba33ae78694db3e2b5 Mon Sep 17 00:00:00 2001 From: Avery Winters Date: Sat, 30 Mar 2024 15:10:01 -0500 Subject: [PATCH] Binary search --- rust/binary-search/.exercism/config.json | 34 +++++++ rust/binary-search/.exercism/metadata.json | 1 + rust/binary-search/.gitignore | 8 ++ rust/binary-search/Cargo.toml | 9 ++ rust/binary-search/HELP.md | 86 ++++++++++++++++++ rust/binary-search/HINTS.md | 18 ++++ rust/binary-search/README.md | 101 +++++++++++++++++++++ rust/binary-search/src/lib.rs | 20 ++++ rust/binary-search/tests/binary-search.rs | 100 ++++++++++++++++++++ 9 files changed, 377 insertions(+) create mode 100644 rust/binary-search/.exercism/config.json create mode 100644 rust/binary-search/.exercism/metadata.json create mode 100644 rust/binary-search/.gitignore create mode 100644 rust/binary-search/Cargo.toml create mode 100644 rust/binary-search/HELP.md create mode 100644 rust/binary-search/HINTS.md create mode 100644 rust/binary-search/README.md create mode 100644 rust/binary-search/src/lib.rs create mode 100644 rust/binary-search/tests/binary-search.rs diff --git a/rust/binary-search/.exercism/config.json b/rust/binary-search/.exercism/config.json new file mode 100644 index 0000000..b55dd3e --- /dev/null +++ b/rust/binary-search/.exercism/config.json @@ -0,0 +1,34 @@ +{ + "authors": [ + "shybyte" + ], + "contributors": [ + "Cohen-Carlisle", + "coriolinus", + "cwhakes", + "efx", + "ErikSchierboom", + "lutostag", + "nfiles", + "petertseng", + "rofrol", + "stringparser", + "xakon", + "ZapAnton" + ], + "files": { + "solution": [ + "src/lib.rs", + "Cargo.toml" + ], + "test": [ + "tests/binary-search.rs" + ], + "example": [ + ".meta/example.rs" + ] + }, + "blurb": "Implement a binary search algorithm.", + "source": "Wikipedia", + "source_url": "https://en.wikipedia.org/wiki/Binary_search_algorithm" +} diff --git a/rust/binary-search/.exercism/metadata.json b/rust/binary-search/.exercism/metadata.json new file mode 100644 index 0000000..24865fc --- /dev/null +++ b/rust/binary-search/.exercism/metadata.json @@ -0,0 +1 @@ +{"track":"rust","exercise":"binary-search","id":"c6c7cdae8eb548abacff5a70c196319b","url":"https://exercism.org/tracks/rust/exercises/binary-search","handle":"averywinters","is_requester":true,"auto_approve":false} \ No newline at end of file diff --git a/rust/binary-search/.gitignore b/rust/binary-search/.gitignore new file mode 100644 index 0000000..db7f315 --- /dev/null +++ b/rust/binary-search/.gitignore @@ -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 diff --git a/rust/binary-search/Cargo.toml b/rust/binary-search/Cargo.toml new file mode 100644 index 0000000..6cfecd6 --- /dev/null +++ b/rust/binary-search/Cargo.toml @@ -0,0 +1,9 @@ +[package] +edition = "2021" +name = "binary-search" +version = "1.3.0" + +[dependencies] + +[features] +generic = [] diff --git a/rust/binary-search/HELP.md b/rust/binary-search/HELP.md new file mode 100644 index 0000000..67add76 --- /dev/null +++ b/rust/binary-search/HELP.md @@ -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 \ No newline at end of file diff --git a/rust/binary-search/HINTS.md b/rust/binary-search/HINTS.md new file mode 100644 index 0000000..728d175 --- /dev/null +++ b/rust/binary-search/HINTS.md @@ -0,0 +1,18 @@ +# Hints + +## General + +[Slices](https://doc.rust-lang.org/book/2018-edition/ch04-03-slices.html) have additionally to +the normal element access via indexing (slice[index]) many useful functions like +[split_at](https://doc.rust-lang.org/std/primitive.slice.html#method.split_at) or [getting +subslices](https://doc.rust-lang.org/std/primitive.slice.html#method.get) (slice[start..end]). + +You can solve this exercise by just using boring old element access via indexing, but maybe the +other provided functions can make your code cleaner and safer. + +## For Bonus Points + +- To get your function working with all kind of elements which can be ordered, + have a look at the [Ord Trait](https://doc.rust-lang.org/std/cmp/trait.Ord.html). +- To get your function working directly on Vec and Array, you can use the + [AsRef Trait](https://doc.rust-lang.org/std/convert/trait.AsRef.html) \ No newline at end of file diff --git a/rust/binary-search/README.md b/rust/binary-search/README.md new file mode 100644 index 0000000..32cd0a8 --- /dev/null +++ b/rust/binary-search/README.md @@ -0,0 +1,101 @@ +# Binary Search + +Welcome to Binary Search on Exercism's Rust Track. +If you need help running the tests or submitting your code, check out `HELP.md`. +If you get stuck on the exercise, check out `HINTS.md`, but try and solve it without using those first :) + +## Introduction + +You have stumbled upon a group of mathematicians who are also singer-songwriters. +They have written a song for each of their favorite numbers, and, as you can imagine, they have a lot of favorite numbers (like [0][zero] or [73][seventy-three] or [6174][kaprekars-constant]). + +You are curious to hear the song for your favorite number, but with so many songs to wade through, finding the right song could take a while. +Fortunately, they have organized their songs in a playlist sorted by the title — which is simply the number that the song is about. + +You realize that you can use a binary search algorithm to quickly find a song given the title. + +[zero]: https://en.wikipedia.org/wiki/0 +[seventy-three]: https://en.wikipedia.org/wiki/73_(number) +[kaprekars-constant]: https://en.wikipedia.org/wiki/6174_(number) + +## Instructions + +Your task is to implement a binary search algorithm. + +A binary search algorithm finds an item in a list by repeatedly splitting it in half, only keeping the half which contains the item we're looking for. +It allows us to quickly narrow down the possible locations of our item until we find it, or until we've eliminated all possible locations. + +~~~~exercism/caution +Binary search only works when a list has been sorted. +~~~~ + +The algorithm looks like this: + +- Find the middle element of a _sorted_ list and compare it with the item we're looking for. +- If the middle element is our item, then we're done! +- If the middle element is greater than our item, we can eliminate that element and all the elements **after** it. +- If the middle element is less than our item, we can eliminate that element and all the elements **before** it. +- If every element of the list has been eliminated then the item is not in the list. +- Otherwise, repeat the process on the part of the list that has not been eliminated. + +Here's an example: + +Let's say we're looking for the number 23 in the following sorted list: `[4, 8, 12, 16, 23, 28, 32]`. + +- We start by comparing 23 with the middle element, 16. +- Since 23 is greater than 16, we can eliminate the left half of the list, leaving us with `[23, 28, 32]`. +- We then compare 23 with the new middle element, 28. +- Since 23 is less than 28, we can eliminate the right half of the list: `[23]`. +- We've found our item. + +## Restrictions + +Rust provides in its standard library already a +[binary search function](https://doc.rust-lang.org/std/primitive.slice.html#method.binary_search). +For this exercise you should not use this function but just other basic tools instead. + +## For bonus points + +Did you get the tests passing and the code clean? If you want to, there +are some additional things you could try. + +- Currently your find function will probably only work for slices of numbers, + but the Rust type system is flexible enough to create a find function which + works on all slices which contains elements which can be ordered. +- Additionally this find function can work not only on slices, but at the + same time also on a Vec or an Array. + +To run the bonus tests, remove the `#[ignore]` flag and execute the tests with +the `generic` feature, like this: + +```bash +$ cargo test --features generic +``` + +Then please share your thoughts in a comment on the submission. Did this +experiment make the code better? Worse? Did you learn anything from it? + +## Source + +### Created by + +- @shybyte + +### Contributed to by + +- @Cohen-Carlisle +- @coriolinus +- @cwhakes +- @efx +- @ErikSchierboom +- @lutostag +- @nfiles +- @petertseng +- @rofrol +- @stringparser +- @xakon +- @ZapAnton + +### Based on + +Wikipedia - https://en.wikipedia.org/wiki/Binary_search_algorithm \ No newline at end of file diff --git a/rust/binary-search/src/lib.rs b/rust/binary-search/src/lib.rs new file mode 100644 index 0000000..9c46825 --- /dev/null +++ b/rust/binary-search/src/lib.rs @@ -0,0 +1,20 @@ +pub fn find(array: &[i32], key: i32) -> Option { + let mut idx = 0; + let mut len = array.len(); + while len > 1 { + let half = len / 2; + let x = array[idx + half - 1]; + // For binary search, branching on the comparison would be unpredictable. + // Instead, we can try to convince the compiler to generate a conditional + // move (where available) using a predication trick to compute the addition. + // This trick works great on aarch64 at least, but seems to be broken on x86 + // currently due to [a bug in LLVM's x86 cmov converter pass][0]. Compiling + // with `-C llvm-args=-x86-cmov-converter-threshold=10` appears to be a viable + // workaround until that is fixed. + // + // [0]: https://github.com/llvm/llvm-project/issues/39374 + idx += usize::from(x < key) * half; + len -= half; + } + array.get(idx).is_some_and(|&x| x == key).then_some(idx) +} diff --git a/rust/binary-search/tests/binary-search.rs b/rust/binary-search/tests/binary-search.rs new file mode 100644 index 0000000..3f419af --- /dev/null +++ b/rust/binary-search/tests/binary-search.rs @@ -0,0 +1,100 @@ +// The &[] borrows are required for the base exercise, +// where `find` is not generic. Once `find` is made generic, +// the borrows become needless. Since we want the tests to work +// without clippy warnings for both people who take on the +// additional challenge and people who don't, we disable this lint. +#![allow(clippy::needless_borrows_for_generic_args)] + +use binary_search::find; + +#[test] +fn finds_a_value_in_an_array_with_one_element() { + assert_eq!(find(&[6], 6), Some(0)); +} + +#[test] +fn finds_first_value_in_an_array_with_two_element() { + assert_eq!(find(&[1, 2], 1), Some(0)); +} + +#[test] +fn finds_second_value_in_an_array_with_two_element() { + assert_eq!(find(&[1, 2], 2), Some(1)); +} + +#[test] +fn finds_a_value_in_the_middle_of_an_array() { + assert_eq!(find(&[1, 3, 4, 6, 8, 9, 11], 6), Some(3)); +} + +#[test] +fn finds_a_value_at_the_beginning_of_an_array() { + assert_eq!(find(&[1, 3, 4, 6, 8, 9, 11], 1), Some(0)); +} + +#[test] +fn finds_a_value_at_the_end_of_an_array() { + assert_eq!(find(&[1, 3, 4, 6, 8, 9, 11], 11), Some(6)); +} + +#[test] +fn finds_a_value_in_an_array_of_odd_length() { + assert_eq!( + find(&[1, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 634], 144), + Some(9) + ); +} + +#[test] +fn finds_a_value_in_an_array_of_even_length() { + assert_eq!( + find(&[1, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377], 21), + Some(5) + ); +} + +#[test] +fn identifies_that_a_value_is_not_included_in_the_array() { + assert_eq!(find(&[1, 3, 4, 6, 8, 9, 11], 7), None); +} + +#[test] +fn a_value_smaller_than_the_arrays_smallest_value_is_not_included() { + assert_eq!(find(&[1, 3, 4, 6, 8, 9, 11], 0), None); +} + +#[test] +fn a_value_larger_than_the_arrays_largest_value_is_not_included() { + assert_eq!(find(&[1, 3, 4, 6, 8, 9, 11], 13), None); +} + +#[test] +fn nothing_is_included_in_an_empty_array() { + assert_eq!(find(&[], 1), None); +} + +#[test] +fn nothing_is_found_when_the_left_and_right_bounds_cross() { + assert_eq!(find(&[1, 2], 0), None); +} + +#[test] +#[cfg(feature = "generic")] +fn works_for_arrays() { + assert_eq!(find([6], 6), Some(0)); +} + +#[test] +#[cfg(feature = "generic")] +fn works_for_vec() { + let vector = vec![6]; + assert_eq!(find(&vector, 6), Some(0)); + assert_eq!(find(vector, 6), Some(0)); +} + +#[test] +#[cfg(feature = "generic")] +fn works_for_str_elements() { + assert_eq!(find(["a"], "a"), Some(0)); + assert_eq!(find(["a", "b"], "b"), Some(1)); +}