Compare commits

..

10 commits

Author SHA1 Message Date
a1afa1e16b sublist 2025-12-04 21:54:00 +03:00
d3bfaf4131 space-age 2025-12-04 17:27:34 +03:00
498f64b5cd anagram 2025-12-04 15:38:26 +03:00
62d1558abe removed zig cpp bash 2025-12-03 16:13:21 +03:00
af89290bbc Parallel Letter Frequency 2025-12-03 16:07:22 +03:00
rorikstr
3ca9867a11 done 2025-05-16 19:00:06 +03:00
rorikstr
3220b697d1 passed 29 tests, 23 remaining 2025-05-15 21:48:06 +03:00
rorikstr
e63c68efe8 some tests passed in clock 2025-05-15 19:40:13 +03:00
rorikstr
0ef500d9ef gitignored 2025-05-06 18:36:59 +03:00
rorikstr
11454b1346 pffff 2025-05-06 16:55:23 +03:00
87 changed files with 4135 additions and 18155 deletions

3
.gitignore vendored
View file

@ -1 +1,2 @@
cpp/hello-world/.exercism/metadata.json
*/*/.exercism/metadata.json

View file

@ -1,23 +0,0 @@
# Билд-артефакты
build/
**/*build*/
*.sln
*.vcxproj*
*.cmake
CMakeCache.txt
CMakeFiles/
Makefile
.cache/
# Бинарники
*.out
*.exe
*.a
*.so
*.dll
# Отладка
*.ilk
*.pdb
*.dSYM/

View file

@ -1,67 +0,0 @@
# Get the exercise name from the current directory
get_filename_component(exercise ${CMAKE_CURRENT_SOURCE_DIR} NAME)
# Basic CMake project
cmake_minimum_required(VERSION 3.5.1)
# Name the project after the exercise
project(${exercise} CXX)
# Get a source filename from the exercise name by replacing -'s with _'s
string(REPLACE "-" "_" file ${exercise})
# Implementation could be only a header
if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/${file}.cpp)
set(exercise_cpp ${file}.cpp)
else()
set(exercise_cpp "")
endif()
# Use the common Catch library?
if(EXERCISM_COMMON_CATCH)
# For Exercism track development only
add_executable(${exercise} ${file}_test.cpp ${exercise_cpp} ${file}.h $<TARGET_OBJECTS:catchlib>)
elseif(EXERCISM_TEST_SUITE)
# The Exercism test suite is being run, the Docker image already
# includes a pre-built version of Catch.
find_package(Catch2 REQUIRED)
add_executable(${exercise} ${file}_test.cpp ${exercise_cpp} ${file}.h)
target_link_libraries(${exercise} PRIVATE Catch2::Catch2WithMain)
# When Catch is installed system wide we need to include a different
# header, we need this define to use the correct one.
target_compile_definitions(${exercise} PRIVATE EXERCISM_TEST_SUITE)
else()
# Build executable from sources and headers
add_executable(${exercise} ${file}_test.cpp ${exercise_cpp} ${file}.h test/tests-main.cpp)
endif()
set_target_properties(${exercise} PROPERTIES
CXX_STANDARD 17
CXX_STANDARD_REQUIRED OFF
CXX_EXTENSIONS OFF
)
set(CMAKE_BUILD_TYPE Debug)
if("${CMAKE_CXX_COMPILER_ID}" MATCHES "(GNU|Clang)")
set_target_properties(${exercise} PROPERTIES
COMPILE_FLAGS "-Wall -Wextra -Wpedantic -Werror"
)
endif()
# Configure to run all the tests?
if(${EXERCISM_RUN_ALL_TESTS})
target_compile_definitions(${exercise} PRIVATE EXERCISM_RUN_ALL_TESTS)
endif()
# Tell MSVC not to warn us about unchecked iterators in debug builds
# Treat warnings as errors
# Treat type conversion warnings C4244 and C4267 as level 4 warnings, i.e. ignore them in level 3
if(${MSVC})
set_target_properties(${exercise} PROPERTIES
COMPILE_DEFINITIONS_DEBUG _SCL_SECURE_NO_WARNINGS
COMPILE_FLAGS "/WX /w44244 /w44267")
endif()
# Run the tests on every build
add_custom_target(test_${exercise} ALL DEPENDS ${exercise} COMMAND ${exercise})

View file

@ -1,61 +0,0 @@
# Help
## Running the tests
Running the tests involves running `cmake -G` and then using the build command appropriate for your platform.
Detailed instructions on how to do this can be found on the [Running the Tests][cpp-tests-instructions] page for C++ on exercism.org.
## Passing the Tests
When you start a new exercise locally, the files are configured so that only the first test is performed.
Get that first test compiling, linking and passing by following the [three rules of test-driven development][three-laws-of-tdd].
Create just enough structure by declaring namespaces, functions, classes, etc., to satisfy any compiler errors and get the test to fail.
Then write just enough code to get the test to pass.
Once you've done that, uncomment the next test by moving the line `if defined(EXERCISM_RUN_ALL_TESTS)` past the next test.
See the example below from the Bob exercise (file `bob_test.cpp`, line 15):
```diff
-#if defined(EXERCISM_RUN_ALL_TESTS)
TEST_CASE("shouting")
{
REQUIRE("Whoa, chill out!" == bob::hey("WATCH OUT!"));
}
+#if defined(EXERCISM_RUN_ALL_TESTS)
```
Moving this line past the next test may result in compile errors as new constructs may be invoked that you haven't yet declared or defined.
Again, fix the compile errors minimally to get a failing test, then change the code minimally to pass the test, refactor your implementation for readability and expressiveness and then go on to the next test.
Try to use standard C++17 facilities in preference to writing your own low-level algorithms or facilities by hand.
[cpp-tests-instructions]: https://exercism.org/docs/tracks/cpp/tests
[three-laws-of-tdd]: http://butunclebob.com/ArticleS.UncleBob.TheThreeRulesOfTdd
## Submitting your solution
You can submit your solution using the `exercism submit hello_world.cpp hello_world.h` 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 [C++ track's documentation](https://exercism.org/docs/tracks/cpp)
- The [C++ track's programming category on the forum](https://forum.exercism.org/c/programming/cpp)
- [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.
To get help if you're having trouble, you can use one of the following resources:
- [`c++-faq` tag on StackOverflow](https://stackoverflow.com/tags/c%2b%2b-faq/info)
- [C++ FAQ from isocpp.com](https://isocpp.org/faq)
- [CppReference](http://en.cppreference.com/) is a wiki reference to the C++ language and standard library
- [C traps and pitfalls](http://www.slideshare.net/LegalizeAdulthood/c-traps-and-pitfalls-for-c-programmers) is useful if you are new to C++, but have programmed in C

View file

@ -1,9 +0,0 @@
#include "hello_world.h"
using namespace std;
namespace hello_world {
string hello() { return "Goodbye, Mars!"; }
} // namespace hello_world

View file

@ -1,22 +0,0 @@
// This is an include guard.
// You could alternatively use '#pragma once'
// See https://en.wikipedia.org/wiki/Include_guard
#if !defined(HELLO_WORLD_H)
#define HELLO_WORLD_H
// Include the string header so that we have access to 'std::string'
#include <string>
// Declare a namespace for the function(s) we are exporting.
// https://en.cppreference.com/w/cpp/language/namespace
namespace hello_world {
// Declare the 'hello()' function, which takes no arguments and returns a
// 'std::string'. The function itself is defined in the hello_world.cpp source
// file. Because it is inside of the 'hello_world' namespace, it's full name is
// 'hello_world::hello()'.
std::string hello();
} // namespace hello_world
#endif

View file

@ -1,15 +0,0 @@
// Include the header file with the definitions of the functions you create.
#include "hello_world.h"
// Include the test framework.
#ifdef EXERCISM_TEST_SUITE
#include <catch2/catch.hpp>
#else
#include "test/catch.hpp"
#endif
// Declares a single test.
TEST_CASE("test_hello") {
// Check if your function returns "Hello, World!".
REQUIRE(hello_world::hello() == "Hello, World!");
}

File diff suppressed because it is too large Load diff

View file

@ -1,2 +0,0 @@
#define CATCH_CONFIG_MAIN
#include "catch.hpp"

View file

@ -0,0 +1,47 @@
{
"authors": [
"EduardoBautista"
],
"contributors": [
"andrewclarkson",
"ashleygwilliams",
"bobahop",
"chancancode",
"ClashTheBunny",
"coriolinus",
"cwhakes",
"Dimkar3000",
"EduardoBautista",
"efx",
"ErikSchierboom",
"gris",
"IanWhitney",
"kytrinyx",
"lutostag",
"mkantor",
"nfiles",
"petertseng",
"pminten",
"quartsize",
"rofrol",
"stevejb71",
"stringparser",
"xakon",
"ZapAnton"
],
"files": {
"solution": [
"src/lib.rs",
"Cargo.toml"
],
"test": [
"tests/anagram.rs"
],
"example": [
".meta/example.rs"
]
},
"blurb": "Given a word and a list of possible anagrams, select the correct sublist.",
"source": "Inspired by the Extreme Startup game",
"source_url": "https://github.com/rchatley/extreme_startup"
}

2
rust/anagram/.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
/target
Cargo.lock

9
rust/anagram/Cargo.toml Normal file
View file

@ -0,0 +1,9 @@
[package]
name = "anagram"
version = "0.1.0"
edition = "2024"
# Not all libraries from crates.io are available in Exercism's test runner.
# The full list of available libraries is here:
# https://github.com/exercism/rust-test-runner/blob/main/local-registry/Cargo.toml
[dependencies]

86
rust/anagram/HELP.md Normal file
View file

@ -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

6
rust/anagram/HINTS.md Normal file
View file

@ -0,0 +1,6 @@
# Hints
## General
The solution is case insensitive, which means `"WOrd"` is the same as `"word"` or `"woRd"`.
It may help to take a peek at the [std library](https://doc.rust-lang.org/std/primitive.char.html) for functions that can convert between them.

74
rust/anagram/README.md Normal file
View file

@ -0,0 +1,74 @@
# Anagram
Welcome to Anagram 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
At a garage sale, you find a lovely vintage typewriter at a bargain price!
Excitedly, you rush home, insert a sheet of paper, and start typing away.
However, your excitement wanes when you examine the output: all words are garbled!
For example, it prints "stop" instead of "post" and "least" instead of "stale."
Carefully, you try again, but now it prints "spot" and "slate."
After some experimentation, you find there is a random delay before each letter is printed, which messes up the order.
You now understand why they sold it for so little money!
You realize this quirk allows you to generate anagrams, which are words formed by rearranging the letters of another word.
Pleased with your finding, you spend the rest of the day generating hundreds of anagrams.
## Instructions
Given a target word and one or more candidate words, your task is to find the candidates that are anagrams of the target.
An anagram is a rearrangement of letters to form a new word: for example `"owns"` is an anagram of `"snow"`.
A word is _not_ its own anagram: for example, `"stop"` is not an anagram of `"stop"`.
The target word and candidate words are made up of one or more ASCII alphabetic characters (`A`-`Z` and `a`-`z`).
Lowercase and uppercase characters are equivalent: for example, `"PoTS"` is an anagram of `"sTOp"`, but `"StoP"` is not an anagram of `"sTOp"`.
The words you need to find should be taken from the candidate words, using the same letter case.
Given the target `"stone"` and the candidate words `"stone"`, `"tones"`, `"banana"`, `"tons"`, `"notes"`, and `"Seton"`, the anagram words you need to find are `"tones"`, `"notes"`, and `"Seton"`.
The Rust track extends the possible letters to be any unicode character, not just ASCII alphabetic ones.
You are going to have to adjust the function signature provided in the stub in order for the lifetimes to work out properly.
This is intentional: what's there demonstrates the basics of lifetime syntax, and what's missing teaches how to interpret lifetime-related compiler errors.
## Source
### Created by
- @EduardoBautista
### Contributed to by
- @andrewclarkson
- @ashleygwilliams
- @bobahop
- @chancancode
- @ClashTheBunny
- @coriolinus
- @cwhakes
- @Dimkar3000
- @EduardoBautista
- @efx
- @ErikSchierboom
- @gris
- @IanWhitney
- @kytrinyx
- @lutostag
- @mkantor
- @nfiles
- @petertseng
- @pminten
- @quartsize
- @rofrol
- @stevejb71
- @stringparser
- @xakon
- @ZapAnton
### Based on
Inspired by the Extreme Startup game - https://github.com/rchatley/extreme_startup

36
rust/anagram/src/lib.rs Normal file
View file

@ -0,0 +1,36 @@
use std::collections::{HashMap, HashSet};
pub trait CharCounter {
fn get_chars_frequency(&self) -> HashMap<char, usize>;
}
pub trait AnagramsFinder<'a> {
fn find_anagrams(&self, pattern_raw: &str) -> HashSet<&'a str>;
}
impl CharCounter for str {
fn get_chars_frequency(&self) -> HashMap<char, usize> {
self.chars().fold(HashMap::new(), |mut acc, c| {
*acc.entry(c).or_insert(0) += 1;
acc
})
}
}
impl<'a> AnagramsFinder<'a> for [&'a str] {
fn find_anagrams(&self, pattern_raw: &str) -> HashSet<&'a str> {
let pattern = pattern_raw.to_lowercase();
let pattern_map: HashMap<char, usize> = pattern.get_chars_frequency();
self.iter()
.copied()
.filter(|word_raw| {
let word = word_raw.to_lowercase();
word != pattern && word.get_chars_frequency() == pattern_map
})
.collect()
}
}
pub fn anagrams_for<'a>(word: &str, possible_anagrams: &[&'a str]) -> HashSet<&'a str> {
possible_anagrams.find_anagrams(word)
}

View file

@ -0,0 +1,171 @@
use anagram::*;
use std::collections::HashSet;
#[test]
fn no_matches() {
let word = "diaper";
let inputs = &["hello", "world", "zombies", "pants"];
let output = anagrams_for(word, inputs);
let expected = HashSet::from_iter([]);
assert_eq!(output, expected);
}
#[test]
fn detects_two_anagrams() {
let word = "solemn";
let inputs = &["lemons", "cherry", "melons"];
let output = anagrams_for(word, inputs);
let expected = HashSet::from_iter(["lemons", "melons"]);
assert_eq!(output, expected);
}
#[test]
fn does_not_detect_anagram_subsets() {
let word = "good";
let inputs = &["dog", "goody"];
let output = anagrams_for(word, inputs);
let expected = HashSet::from_iter([]);
assert_eq!(output, expected);
}
#[test]
fn detects_anagram() {
let word = "listen";
let inputs = &["enlists", "google", "inlets", "banana"];
let output = anagrams_for(word, inputs);
let expected = HashSet::from_iter(["inlets"]);
assert_eq!(output, expected);
}
#[test]
fn detects_three_anagrams() {
let word = "allergy";
let inputs = &[
"gallery",
"ballerina",
"regally",
"clergy",
"largely",
"leading",
];
let output = anagrams_for(word, inputs);
let expected = HashSet::from_iter(["gallery", "regally", "largely"]);
assert_eq!(output, expected);
}
#[test]
fn detects_multiple_anagrams_with_different_case() {
let word = "nose";
let inputs = &["Eons", "ONES"];
let output = anagrams_for(word, inputs);
let expected = HashSet::from_iter(["Eons", "ONES"]);
assert_eq!(output, expected);
}
#[test]
fn does_not_detect_non_anagrams_with_identical_checksum() {
let word = "mass";
let inputs = &["last"];
let output = anagrams_for(word, inputs);
let expected = HashSet::from_iter([]);
assert_eq!(output, expected);
}
#[test]
fn detects_anagrams_case_insensitively() {
let word = "Orchestra";
let inputs = &["cashregister", "Carthorse", "radishes"];
let output = anagrams_for(word, inputs);
let expected = HashSet::from_iter(["Carthorse"]);
assert_eq!(output, expected);
}
#[test]
fn detects_anagrams_using_case_insensitive_subject() {
let word = "Orchestra";
let inputs = &["cashregister", "carthorse", "radishes"];
let output = anagrams_for(word, inputs);
let expected = HashSet::from_iter(["carthorse"]);
assert_eq!(output, expected);
}
#[test]
fn detects_anagrams_using_case_insensitive_possible_matches() {
let word = "orchestra";
let inputs = &["cashregister", "Carthorse", "radishes"];
let output = anagrams_for(word, inputs);
let expected = HashSet::from_iter(["Carthorse"]);
assert_eq!(output, expected);
}
#[test]
fn does_not_detect_an_anagram_if_the_original_word_is_repeated() {
let word = "go";
let inputs = &["goGoGO"];
let output = anagrams_for(word, inputs);
let expected = HashSet::from_iter([]);
assert_eq!(output, expected);
}
#[test]
fn anagrams_must_use_all_letters_exactly_once() {
let word = "tapper";
let inputs = &["patter"];
let output = anagrams_for(word, inputs);
let expected = HashSet::from_iter([]);
assert_eq!(output, expected);
}
#[test]
fn words_are_not_anagrams_of_themselves() {
let word = "BANANA";
let inputs = &["BANANA"];
let output = anagrams_for(word, inputs);
let expected = HashSet::from_iter([]);
assert_eq!(output, expected);
}
#[test]
fn words_are_not_anagrams_of_themselves_even_if_letter_case_is_partially_different() {
let word = "BANANA";
let inputs = &["Banana"];
let output = anagrams_for(word, inputs);
let expected = HashSet::from_iter([]);
assert_eq!(output, expected);
}
#[test]
fn words_are_not_anagrams_of_themselves_even_if_letter_case_is_completely_different() {
let word = "BANANA";
let inputs = &["banana"];
let output = anagrams_for(word, inputs);
let expected = HashSet::from_iter([]);
assert_eq!(output, expected);
}
#[test]
fn words_other_than_themselves_can_be_anagrams() {
let word = "LISTEN";
let inputs = &["LISTEN", "Silent"];
let output = anagrams_for(word, inputs);
let expected = HashSet::from_iter(["Silent"]);
assert_eq!(output, expected);
}
#[test]
fn handles_case_of_greek_letters() {
let word = "ΑΒΓ";
let inputs = &["ΒΓΑ", "ΒΓΔ", "γβα", "αβγ"];
let output = anagrams_for(word, inputs);
let expected = HashSet::from_iter(["ΒΓΑ", "γβα"]);
assert_eq!(output, expected);
}
#[test]
fn different_characters_may_have_the_same_bytes() {
let word = "a⬂";
let inputs = &["€a"];
let output = anagrams_for(word, inputs);
let expected = HashSet::from_iter([]);
assert_eq!(output, expected);
}

View file

@ -0,0 +1,42 @@
{
"authors": [
"sacherjj"
],
"contributors": [
"attilahorvath",
"coriolinus",
"cwhakes",
"danieljl",
"eddyp",
"efx",
"ErikSchierboom",
"felix91gr",
"kunaltyagi",
"lutostag",
"nfiles",
"petertseng",
"rofrol",
"shaaraddalvi",
"stringparser",
"tmccombs",
"xakon",
"ZapAnton"
],
"files": {
"solution": [
"src/lib.rs",
"Cargo.toml"
],
"test": [
"tests/clock.rs"
],
"example": [
".meta/example.rs"
]
},
"blurb": "Implement a clock that handles times without dates.",
"source": "Pairing session with Erin Drummond",
"custom": {
"allowed-to-not-compile": "Stub doesn't compile because there is no to_string() implementation. This exercise is an introduction to derived and self-implemented traits, therefore adding template for a trait would reduce student learning."
}
}

2
rust/clock/.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
/target
Cargo.lock

9
rust/clock/Cargo.toml Normal file
View file

@ -0,0 +1,9 @@
[package]
name = "clock"
version = "0.1.0"
edition = "2024"
# Not all libraries from crates.io are available in Exercism's test runner.
# The full list of available libraries is here:
# https://github.com/exercism/rust-test-runner/blob/main/local-registry/Cargo.toml
[dependencies]

86
rust/clock/HELP.md Normal file
View file

@ -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

60
rust/clock/README.md Normal file
View file

@ -0,0 +1,60 @@
# Clock
Welcome to Clock on Exercism's Rust Track.
If you need help running the tests or submitting your code, check out `HELP.md`.
## Instructions
Implement a clock that handles times without dates.
You should be able to add and subtract minutes to it.
Two clocks that represent the same time should be equal to each other.
## Rust Traits for `.to_string()`
You will also need to implement `.to_string()` for the `Clock` struct.
We will be using this to display the Clock's state.
You can either do it via implementing it directly or using the [Display trait][display-trait].
If so, try implementing the [Display trait][display-trait] for `Clock` instead.
Traits allow for a common way to implement functionality for various types.
For additional learning, consider how you might implement `String::from` for the `Clock` type.
You don't have to actually implement this—it's redundant with `Display`, which is generally the
better choice when the destination type is `String`—but it's useful to have a few type-conversion
traits in your toolkit.
[display-trait]: https://doc.rust-lang.org/std/fmt/trait.Display.html
## Source
### Created by
- @sacherjj
### Contributed to by
- @attilahorvath
- @coriolinus
- @cwhakes
- @danieljl
- @eddyp
- @efx
- @ErikSchierboom
- @felix91gr
- @kunaltyagi
- @lutostag
- @nfiles
- @petertseng
- @rofrol
- @shaaraddalvi
- @stringparser
- @tmccombs
- @xakon
- @ZapAnton
### Based on
Pairing session with Erin Drummond

70
rust/clock/src/lib.rs Normal file
View file

@ -0,0 +1,70 @@
use std::cmp::Ordering::{Less, Equal, Greater};
#[derive(Debug)]
pub struct Clock {
pub hours: i32,
pub minutes: i32,
}
/*
-2, -40 => 21, 20 ()
-47, -20 => { -20 => -48, 40 } (-47/24 => -1; -1*24 + 47 = 23; -20)
*/
impl Clock {
pub fn new(hours: i32, minutes: i32) -> Self {
let total_minutes = hours * 60 + minutes;
let mut total_minutes = total_minutes % 1440;
total_minutes = match total_minutes.cmp(&0) {
Less => total_minutes + 1440,
Equal | Greater => total_minutes,
};
let hours = total_minutes / 60;
let minutes = total_minutes % 60;
Clock { hours, minutes }
}
/*
40 => 0 (0*60 + 40 - 60*0)
60 => 1 (1*60 + 60 - 60*1)
90 => 1 (1*60 + 90 - 60*1)
150 => 150/60 = 2, (2*60 + 150 - 60*2)
23 => 23 (23 - 24 * 0)
26 => 2 (hours - 24 * hours_diff)
49 => 1 (hours - 24 * hours_diff)
*/
pub fn add_minutes(&self, minutes: i32) -> Self {
Clock::new(self.hours, self.minutes + minutes)
}
pub fn to_string(&self) -> String {
let hours = match self.hours.cmp(&10) {
Less => format!("0{}",self.hours),
Equal | Greater => format!("{}", self.hours),
};
let minutes = match self.minutes.cmp(&10) {
Less => format!("0{}",self.minutes),
Equal | Greater => format!("{}", self.minutes),
};
format!("{}:{}", hours, minutes)
}
}
impl PartialEq for Clock {
fn eq(&self, other: &Self) -> bool {
match self.hours.cmp(&other.hours) {
Less | Greater => false,
Equal => {
match self.minutes.cmp(&other.minutes) {
Less | Greater => false,
Equal => true,
}
},
}
}
}

340
rust/clock/tests/clock.rs Normal file
View file

@ -0,0 +1,340 @@
use clock::*;
//
// Clock Creation
//
#[test]
fn on_the_hour() {
assert_eq!(Clock::new(8, 0).to_string(), "08:00");
}
#[test]
#[ignore]
fn past_the_hour() {
assert_eq!(Clock::new(11, 9).to_string(), "11:09");
}
#[test]
#[ignore]
fn midnight_is_zero_hours() {
assert_eq!(Clock::new(24, 0).to_string(), "00:00");
}
#[test]
#[ignore]
fn hour_rolls_over() {
assert_eq!(Clock::new(25, 0).to_string(), "01:00");
}
#[test]
#[ignore]
fn hour_rolls_over_continuously() {
assert_eq!(Clock::new(100, 0).to_string(), "04:00");
}
#[test]
#[ignore]
fn sixty_minutes_is_next_hour() {
assert_eq!(Clock::new(1, 60).to_string(), "02:00");
}
#[test]
#[ignore]
fn minutes_roll_over() {
assert_eq!(Clock::new(0, 160).to_string(), "02:40");
}
#[test]
#[ignore]
fn minutes_roll_over_continuously() {
assert_eq!(Clock::new(0, 1723).to_string(), "04:43");
}
#[test]
#[ignore]
fn hour_and_minutes_roll_over() {
assert_eq!(Clock::new(25, 160).to_string(), "03:40");
}
#[test]
#[ignore]
fn hour_and_minutes_roll_over_continuously() {
assert_eq!(Clock::new(201, 3001).to_string(), "11:01");
}
#[test]
#[ignore]
fn hour_and_minutes_roll_over_to_exactly_midnight() {
assert_eq!(Clock::new(72, 8640).to_string(), "00:00");
}
#[test]
#[ignore]
fn negative_hour() {
assert_eq!(Clock::new(-1, 15).to_string(), "23:15");
}
#[test]
#[ignore]
fn negative_hour_rolls_over() {
assert_eq!(Clock::new(-25, 0).to_string(), "23:00");
}
#[test]
#[ignore]
fn negative_hour_rolls_over_continuously() {
assert_eq!(Clock::new(-91, 0).to_string(), "05:00");
}
#[test]
#[ignore]
fn negative_minutes() {
assert_eq!(Clock::new(1, -40).to_string(), "00:20");
}
#[test]
#[ignore]
fn negative_minutes_roll_over() {
assert_eq!(Clock::new(1, -160).to_string(), "22:20");
}
#[test]
#[ignore]
fn negative_minutes_roll_over_continuously() {
assert_eq!(Clock::new(1, -4820).to_string(), "16:40");
}
#[test]
#[ignore]
fn negative_sixty_minutes_is_previous_hour() {
assert_eq!(Clock::new(2, -60).to_string(), "01:00");
}
#[test]
#[ignore]
fn negative_hour_and_minutes_both_roll_over() {
assert_eq!(Clock::new(-25, -160).to_string(), "20:20");
}
#[test]
#[ignore]
fn negative_hour_and_minutes_both_roll_over_continuously() {
assert_eq!(Clock::new(-121, -5810).to_string(), "22:10");
}
//
// Clock Math
//
#[test]
#[ignore]
fn add_minutes() {
let clock = Clock::new(10, 0).add_minutes(3);
assert_eq!(clock.to_string(), "10:03");
}
#[test]
#[ignore]
fn add_no_minutes() {
let clock = Clock::new(6, 41).add_minutes(0);
assert_eq!(clock.to_string(), "06:41");
}
#[test]
#[ignore]
fn add_to_next_hour() {
let clock = Clock::new(0, 45).add_minutes(40);
assert_eq!(clock.to_string(), "01:25");
}
#[test]
#[ignore]
fn add_more_than_one_hour() {
let clock = Clock::new(10, 0).add_minutes(61);
assert_eq!(clock.to_string(), "11:01");
}
#[test]
#[ignore]
fn add_more_than_two_hours_with_carry() {
let clock = Clock::new(0, 45).add_minutes(160);
assert_eq!(clock.to_string(), "03:25");
}
#[test]
#[ignore]
fn add_across_midnight() {
let clock = Clock::new(23, 59).add_minutes(2);
assert_eq!(clock.to_string(), "00:01");
}
#[test]
#[ignore]
fn add_more_than_one_day_1500_min_25_hrs() {
let clock = Clock::new(5, 32).add_minutes(1500);
assert_eq!(clock.to_string(), "06:32");
}
#[test]
#[ignore]
fn add_more_than_two_days() {
let clock = Clock::new(1, 1).add_minutes(3500);
assert_eq!(clock.to_string(), "11:21");
}
#[test]
#[ignore]
fn subtract_minutes() {
let clock = Clock::new(10, 3).add_minutes(-3);
assert_eq!(clock.to_string(), "10:00");
}
#[test]
#[ignore]
fn subtract_to_previous_hour() {
let clock = Clock::new(10, 3).add_minutes(-30);
assert_eq!(clock.to_string(), "09:33");
}
#[test]
#[ignore]
fn subtract_more_than_an_hour() {
let clock = Clock::new(10, 3).add_minutes(-70);
assert_eq!(clock.to_string(), "08:53");
}
#[test]
#[ignore]
fn subtract_across_midnight() {
let clock = Clock::new(0, 3).add_minutes(-4);
assert_eq!(clock.to_string(), "23:59");
}
#[test]
#[ignore]
fn subtract_more_than_two_hours() {
let clock = Clock::new(0, 0).add_minutes(-160);
assert_eq!(clock.to_string(), "21:20");
}
#[test]
#[ignore]
fn subtract_more_than_two_hours_with_borrow() {
let clock = Clock::new(6, 15).add_minutes(-160);
assert_eq!(clock.to_string(), "03:35");
}
#[test]
#[ignore]
fn subtract_more_than_one_day_1500_min_25_hrs() {
let clock = Clock::new(5, 32).add_minutes(-1500);
assert_eq!(clock.to_string(), "04:32");
}
#[test]
#[ignore]
fn subtract_more_than_two_days() {
let clock = Clock::new(2, 20).add_minutes(-3000);
assert_eq!(clock.to_string(), "00:20");
}
//
// Test Equality
//
#[test]
#[ignore]
fn clocks_with_same_time() {
assert_eq!(Clock::new(15, 37), Clock::new(15, 37));
}
#[test]
#[ignore]
fn clocks_a_minute_apart() {
assert_ne!(Clock::new(15, 36), Clock::new(15, 37));
}
#[test]
#[ignore]
fn clocks_an_hour_apart() {
assert_ne!(Clock::new(14, 37), Clock::new(15, 37));
}
#[test]
#[ignore]
fn clocks_with_hour_overflow() {
assert_eq!(Clock::new(10, 37), Clock::new(34, 37));
}
#[test]
#[ignore]
fn clocks_with_hour_overflow_by_several_days() {
assert_eq!(Clock::new(3, 11), Clock::new(99, 11));
}
#[test]
#[ignore]
fn clocks_with_negative_hour() {
assert_eq!(Clock::new(22, 40), Clock::new(-2, 40));
}
#[test]
#[ignore]
fn clocks_with_negative_hour_that_wraps() {
assert_eq!(Clock::new(17, 3), Clock::new(-31, 3));
}
#[test]
#[ignore]
fn clocks_with_negative_hour_that_wraps_multiple_times() {
assert_eq!(Clock::new(13, 49), Clock::new(-83, 49));
}
#[test]
#[ignore]
fn clocks_with_minute_overflow() {
assert_eq!(Clock::new(0, 1), Clock::new(0, 1441));
}
#[test]
#[ignore]
fn clocks_with_minute_overflow_by_several_days() {
assert_eq!(Clock::new(2, 2), Clock::new(2, 4322));
}
#[test]
#[ignore]
fn clocks_with_negative_minute() {
assert_eq!(Clock::new(2, 40), Clock::new(3, -20));
}
#[test]
#[ignore]
fn clocks_with_negative_minute_that_wraps() {
assert_eq!(Clock::new(4, 10), Clock::new(5, -1490));
}
#[test]
#[ignore]
fn clocks_with_negative_minute_that_wraps_multiple_times() {
assert_eq!(Clock::new(6, 15), Clock::new(6, -4305));
}
#[test]
#[ignore]
fn clocks_with_negative_hours_and_minutes() {
assert_eq!(Clock::new(7, 32), Clock::new(-12, -268));
}
#[test]
#[ignore]
fn clocks_with_negative_hours_and_minutes_that_wrap() {
assert_eq!(Clock::new(18, 7), Clock::new(-54, -11513));
}
#[test]
#[ignore]
fn full_clock_and_zeroed_clock() {
assert_eq!(Clock::new(24, 0), Clock::new(0, 0));
}

View file

@ -0,0 +1,45 @@
{
"authors": [
"IanWhitney"
],
"contributors": [
"andy5995",
"ashleygwilliams",
"cbzehner",
"coriolinus",
"cwhakes",
"EduardoBautista",
"efx",
"ErikSchierboom",
"houhoulis",
"IanWhitney",
"janczer",
"leoyvens",
"lutostag",
"mkantor",
"nfiles",
"NieDzejkob",
"ocstl",
"petertseng",
"rofrol",
"sacherjj",
"stringparser",
"xakon",
"ZapAnton"
],
"files": {
"solution": [
"src/lib.rs",
"Cargo.toml"
],
"test": [
"tests/gigasecond.rs"
],
"example": [
".meta/example.rs"
]
},
"blurb": "Given a moment, determine the moment that would be after a gigasecond has passed.",
"source": "Chapter 9 in Chris Pine's online Learn to Program tutorial.",
"source_url": "https://pine.fm/LearnToProgram/?Chapter=09"
}

2
rust/gigasecond/.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
/target
Cargo.lock

View file

@ -0,0 +1,10 @@
[package]
name = "gigasecond"
version = "0.1.0"
edition = "2024"
# Not all libraries from crates.io are available in Exercism's test runner.
# The full list of available libraries is here:
# https://github.com/exercism/rust-test-runner/blob/main/local-registry/Cargo.toml
[dependencies]
time = "0.3"

86
rust/gigasecond/HELP.md Normal file
View file

@ -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

76
rust/gigasecond/README.md Normal file
View file

@ -0,0 +1,76 @@
# Gigasecond
Welcome to Gigasecond on Exercism's Rust Track.
If you need help running the tests or submitting your code, check out `HELP.md`.
## Introduction
The way we measure time is kind of messy.
We have 60 seconds in a minute, and 60 minutes in an hour.
This comes from ancient Babylon, where they used 60 as the basis for their number system.
We have 24 hours in a day, 7 days in a week, and how many days in a month?
Well, for days in a month it depends not only on which month it is, but also on what type of calendar is used in the country you live in.
What if, instead, we only use seconds to express time intervals?
Then we can use metric system prefixes for writing large numbers of seconds in more easily comprehensible quantities.
- A food recipe might explain that you need to let the brownies cook in the oven for two kiloseconds (that's two thousand seconds).
- Perhaps you and your family would travel to somewhere exotic for two megaseconds (that's two million seconds).
- And if you and your spouse were married for _a thousand million_ seconds, you would celebrate your one gigasecond anniversary.
~~~~exercism/note
If we ever colonize Mars or some other planet, measuring time is going to get even messier.
If someone says "year" do they mean a year on Earth or a year on Mars?
The idea for this exercise came from the science fiction novel ["A Deepness in the Sky"][vinge-novel] by author Vernor Vinge.
In it the author uses the metric system as the basis for time measurements.
[vinge-novel]: https://www.tor.com/2017/08/03/science-fiction-with-something-for-everyone-a-deepness-in-the-sky-by-vernor-vinge/
~~~~
## Instructions
Your task is to determine the date and time one gigasecond after a certain date.
A gigasecond is one thousand million seconds.
That is a one with nine zeros after it.
If you were born on _January 24th, 2015 at 22:00 (10:00:00pm)_, then you would be a gigasecond old on _October 2nd, 2046 at 23:46:40 (11:46:40pm)_.
If you're unsure what operations you can perform on `PrimitiveDateTime` take a look at the [time crate](https://docs.rs/time) which is listed as a dependency in the `Cargo.toml` file for this exercise.
## Source
### Created by
- @IanWhitney
### Contributed to by
- @andy5995
- @ashleygwilliams
- @cbzehner
- @coriolinus
- @cwhakes
- @EduardoBautista
- @efx
- @ErikSchierboom
- @houhoulis
- @IanWhitney
- @janczer
- @leoyvens
- @lutostag
- @mkantor
- @nfiles
- @NieDzejkob
- @ocstl
- @petertseng
- @rofrol
- @sacherjj
- @stringparser
- @xakon
- @ZapAnton
### Based on
Chapter 9 in Chris Pine's online Learn to Program tutorial. - https://pine.fm/LearnToProgram/?Chapter=09

View file

@ -0,0 +1,7 @@
use time::PrimitiveDateTime as DateTime;
use time::Duration;
// Returns a DateTime one billion seconds after start.
pub fn after(start: DateTime) -> DateTime {
start + Duration::seconds(1_000_000_000)
}

View file

@ -0,0 +1,59 @@
#[test]
fn date_only_specification_of_time() {
let start = datetime(2011, 4, 25, 0, 0, 0);
let actual = gigasecond::after(start);
let expected = datetime(2043, 1, 1, 1, 46, 40);
assert_eq!(actual, expected);
}
#[test]
#[ignore]
fn second_test_for_date_only_specification_of_time() {
let start = datetime(1977, 6, 13, 0, 0, 0);
let actual = gigasecond::after(start);
let expected = datetime(2009, 2, 19, 1, 46, 40);
assert_eq!(actual, expected);
}
#[test]
#[ignore]
fn third_test_for_date_only_specification_of_time() {
let start = datetime(1959, 7, 19, 0, 0, 0);
let actual = gigasecond::after(start);
let expected = datetime(1991, 3, 27, 1, 46, 40);
assert_eq!(actual, expected);
}
#[test]
#[ignore]
fn full_time_specified() {
let start = datetime(2015, 1, 24, 22, 0, 0);
let actual = gigasecond::after(start);
let expected = datetime(2046, 10, 2, 23, 46, 40);
assert_eq!(actual, expected);
}
#[test]
#[ignore]
fn full_time_with_day_roll_over() {
let start = datetime(2015, 1, 24, 23, 59, 59);
let actual = gigasecond::after(start);
let expected = datetime(2046, 10, 3, 1, 46, 39);
assert_eq!(actual, expected);
}
fn datetime(
year: i32,
month: u8,
day: u8,
hour: u8,
minute: u8,
second: u8,
) -> time::PrimitiveDateTime {
use time::{Date, PrimitiveDateTime, Time};
PrimitiveDateTime::new(
Date::from_calendar_date(year, month.try_into().unwrap(), day).unwrap(),
Time::from_hms(hour, minute, second).unwrap(),
)
}

View file

@ -0,0 +1,42 @@
{
"authors": [
"EduardoBautista"
],
"contributors": [
"andrewclarkson",
"ashleygwilliams",
"ccouzens",
"ClashTheBunny",
"coriolinus",
"cwhakes",
"EduardoBautista",
"efx",
"ErikSchierboom",
"etrepum",
"glennpratt",
"IanWhitney",
"kytrinyx",
"lutostag",
"mkantor",
"nfiles",
"petertseng",
"rofrol",
"sjwarner-bp",
"stringparser",
"xakon",
"ZapAnton"
],
"files": {
"solution": [
"src/lib.rs",
"Cargo.toml"
],
"test": [
"tests/parallel_letter_frequency.rs"
],
"example": [
".meta/example.rs"
]
},
"blurb": "Count the frequency of letters in texts using parallel computation."
}

View file

@ -0,0 +1,2 @@
/target
Cargo.lock

View file

@ -0,0 +1,9 @@
[package]
name = "parallel_letter_frequency"
version = "0.1.0"
edition = "2024"
# Not all libraries from crates.io are available in Exercism's test runner.
# The full list of available libraries is here:
# https://github.com/exercism/rust-test-runner/blob/main/local-registry/Cargo.toml
[dependencies]

View file

@ -0,0 +1,89 @@
# 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
Head to [the forum](https://forum.exercism.org/c/programming/rust/) and create a post to provide feedback about an exercise or if you want to help implement new exercises.
Members of the rust track team are happy to help!
The GitHub [track repository][github] is the home for all of the Rust exercises.
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

View file

@ -0,0 +1,76 @@
# Parallel Letter Frequency
Welcome to Parallel Letter Frequency on Exercism's Rust Track.
If you need help running the tests or submitting your code, check out `HELP.md`.
## Instructions
Count the frequency of letters in texts using parallel computation.
Parallelism is about doing things in parallel that can also be done sequentially.
A common example is counting the frequency of letters.
Employ parallelism to calculate the total frequency of each letter in a list of texts.
## Parallel Letter Frequency in Rust
Learn more about concurrency in Rust here:
- [Concurrency](https://doc.rust-lang.org/book/ch16-00-concurrency.html)
## Bonus
This exercise also includes a benchmark, with a sequential implementation as a
baseline. You can compare your solution to the benchmark. Observe the
effect different size inputs have on the performance of each. Can you
surpass the benchmark using concurrent programming techniques?
As of this writing, test::Bencher is unstable and only available on
*nightly* Rust. Run the benchmarks with Cargo:
```
cargo bench
```
If you are using rustup.rs:
```
rustup run nightly cargo bench
```
- [Benchmark tests](https://doc.rust-lang.org/stable/unstable-book/library-features/test.html)
Learn more about nightly Rust:
- [Nightly Rust](https://doc.rust-lang.org/book/appendix-07-nightly-rust.html)
- [Installing Rust nightly](https://rust-lang.github.io/rustup/concepts/channels.html#working-with-nightly-rust)
## Source
### Created by
- @EduardoBautista
### Contributed to by
- @andrewclarkson
- @ashleygwilliams
- @ccouzens
- @ClashTheBunny
- @coriolinus
- @cwhakes
- @EduardoBautista
- @efx
- @ErikSchierboom
- @etrepum
- @glennpratt
- @IanWhitney
- @kytrinyx
- @lutostag
- @mkantor
- @nfiles
- @petertseng
- @rofrol
- @sjwarner-bp
- @stringparser
- @xakon
- @ZapAnton

View file

@ -0,0 +1,102 @@
#![feature(test)]
extern crate parallel_letter_frequency;
extern crate test;
use std::collections::HashMap;
use test::Bencher;
#[bench]
fn bench_tiny_parallel(b: &mut Bencher) {
let tiny = &["a"];
b.iter(|| parallel_letter_frequency::frequency(tiny, 3));
}
#[bench]
fn bench_tiny_sequential(b: &mut Bencher) {
let tiny = &["a"];
b.iter(|| frequency(tiny));
}
#[bench]
fn bench_small_parallel(b: &mut Bencher) {
let texts = all_texts(1);
b.iter(|| parallel_letter_frequency::frequency(&texts, 3));
}
#[bench]
fn bench_small_sequential(b: &mut Bencher) {
let texts = all_texts(1);
b.iter(|| frequency(&texts));
}
#[bench]
fn bench_large_parallel(b: &mut Bencher) {
let texts = all_texts(30);
b.iter(|| parallel_letter_frequency::frequency(&texts, 3));
}
#[bench]
fn bench_large_sequential(b: &mut Bencher) {
let texts = all_texts(30);
b.iter(|| frequency(&texts));
}
/// Simple sequential char frequency. Can it be beat?
pub fn frequency(texts: &[&str]) -> HashMap<char, usize> {
let mut map = HashMap::new();
for line in texts {
for chr in line.chars().filter(|c| c.is_alphabetic()) {
if let Some(c) = chr.to_lowercase().next() {
(*map.entry(c).or_insert(0)) += 1;
}
}
}
map
}
fn all_texts(repeat: usize) -> Vec<&'static str> {
[ODE_AN_DIE_FREUDE, WILHELMUS, STAR_SPANGLED_BANNER]
.iter()
.cycle()
.take(3 * repeat)
.flat_map(|anthem| anthem.iter().cloned())
.collect()
}
// Poem by Friedrich Schiller. The corresponding music is the European Anthem.
pub const ODE_AN_DIE_FREUDE: [&str; 8] = [
"Freude schöner Götterfunken",
"Tochter aus Elysium,",
"Wir betreten feuertrunken,",
"Himmlische, dein Heiligtum!",
"Deine Zauber binden wieder",
"Was die Mode streng geteilt;",
"Alle Menschen werden Brüder,",
"Wo dein sanfter Flügel weilt.",
];
// Dutch national anthem
pub const WILHELMUS: [&str; 8] = [
"Wilhelmus van Nassouwe",
"ben ik, van Duitsen bloed,",
"den vaderland getrouwe",
"blijf ik tot in den dood.",
"Een Prinse van Oranje",
"ben ik, vrij, onverveerd,",
"den Koning van Hispanje",
"heb ik altijd geëerd.",
];
// American national anthem
pub const STAR_SPANGLED_BANNER: [&str; 8] = [
"O say can you see by the dawn's early light,",
"What so proudly we hailed at the twilight's last gleaming,",
"Whose broad stripes and bright stars through the perilous fight,",
"O'er the ramparts we watched, were so gallantly streaming?",
"And the rockets' red glare, the bombs bursting in air,",
"Gave proof through the night that our flag was still there;",
"O say does that star-spangled banner yet wave,",
"O'er the land of the free and the home of the brave?",
];

View file

@ -0,0 +1,41 @@
use std::any::Any;
use std::collections::HashMap;
use std::thread;
pub fn frequency(input: &[&str], worker_count: usize) -> HashMap<char, usize> {
if input.is_empty() {
return HashMap::<char, usize>::new();
}
let worker_count = worker_count.max(1);
thread::scope(|s| {
let chunk_size = input.len().div_ceil(worker_count);
let handles: Vec<_> = input
.chunks(chunk_size)
.map(|chunk| {
s.spawn(move || {
let mut proxy_map = HashMap::new();
chunk
.iter()
.flat_map(|line| line.chars())
.filter(|char| char.is_alphabetic())
.flat_map(|char_slice| char_slice.to_lowercase())
.for_each(|char| {
*proxy_map.entry(char).or_insert(0) += 1;
});
proxy_map
})
})
.collect();
handles
.into_iter()
.map(|x| x.join().unwrap())
.fold(HashMap::new(), |mut acc, map| {
for (char, count) in map {
*acc.entry(char).or_insert(0) += count;
}
acc
})
})
}

View file

@ -0,0 +1,347 @@
use std::collections::HashMap;
use parallel_letter_frequency as frequency;
#[test]
fn no_texts() {
assert_eq!(frequency::frequency(&[], 4), HashMap::new());
}
#[test]
fn one_text_with_one_letter() {
let mut hm = HashMap::new();
hm.insert('a', 1);
assert_eq!(frequency::frequency(&["a"], 4), hm);
}
#[test]
fn one_text_with_multiple_letters() {
let mut hm = HashMap::new();
hm.insert('b', 2);
hm.insert('c', 3);
hm.insert('d', 1);
assert_eq!(frequency::frequency(&["bbcccd"], 4), hm);
}
#[test]
fn two_texts_with_one_letter() {
let mut hm = HashMap::new();
hm.insert('e', 1);
hm.insert('f', 1);
assert_eq!(frequency::frequency(&["e", "f"], 4), hm);
}
#[test]
fn two_texts_with_multiple_letters() {
let mut hm = HashMap::new();
hm.insert('g', 2);
hm.insert('h', 3);
hm.insert('i', 1);
assert_eq!(frequency::frequency(&["ggh", "hhi"], 4), hm);
}
#[test]
fn case_insensitivity() {
let mut hm = HashMap::new();
hm.insert('a', 2);
assert_eq!(frequency::frequency(&["aA"], 4), hm);
}
#[test]
fn many_empty_lines() {
let v = vec![""; 1000];
assert_eq!(frequency::frequency(&v[..], 4), HashMap::new());
}
#[test]
fn ignore_whitespace() {
let v = [" ", "\t", "\r\n"];
assert_eq!(frequency::frequency(&v[..], 4), HashMap::new());
}
#[test]
fn many_times_same_text() {
let v = vec!["abc"; 1000];
let mut hm = HashMap::new();
hm.insert('a', 1000);
hm.insert('b', 1000);
hm.insert('c', 1000);
assert_eq!(frequency::frequency(&v[..], 4), hm);
}
#[test]
fn punctuation_doesnt_count() {
assert!(!frequency::frequency(&WILHELMUS, 4).contains_key(&','));
}
#[test]
fn numbers_dont_count() {
assert!(!frequency::frequency(&["Testing, 1, 2, 3"], 4).contains_key(&'1'));
}
#[test]
fn unicode_letters() {
let mut hm = HashMap::new();
hm.insert('本', 1);
hm.insert('φ', 1);
hm.insert('ほ', 1);
hm.insert('ø', 1);
let v = ["", "φ", "", "ø"];
assert_eq!(frequency::frequency(&v, 4), hm);
}
#[test]
fn all_three_anthems_1_worker() {
let mut v = Vec::new();
// These constants can be found under the last test if you wish to see them
for anthem in [ODE_AN_DIE_FREUDE, WILHELMUS, STAR_SPANGLED_BANNER].iter() {
for line in anthem.iter() {
v.push(*line);
}
}
let freqs = frequency::frequency(&v[..], 1);
assert_eq!(freqs.get(&'a'), Some(&49));
assert_eq!(freqs.get(&'t'), Some(&56));
assert_eq!(freqs.get(&'ü'), Some(&2));
}
#[test]
fn all_three_anthems_3_workers() {
let mut v = Vec::new();
for anthem in [ODE_AN_DIE_FREUDE, WILHELMUS, STAR_SPANGLED_BANNER].iter() {
for line in anthem.iter() {
v.push(*line);
}
}
let freqs = frequency::frequency(&v[..], 3);
assert_eq!(freqs.get(&'a'), Some(&49));
assert_eq!(freqs.get(&'t'), Some(&56));
assert_eq!(freqs.get(&'ü'), Some(&2));
}
#[test]
fn non_integer_multiple_of_threads() {
let v = vec!["abc"; 999];
let mut hm = HashMap::new();
hm.insert('a', 999);
hm.insert('b', 999);
hm.insert('c', 999);
assert_eq!(frequency::frequency(&v[..], 4), hm);
}
#[test]
fn large_texts() {
let expected: HashMap<char, usize> = [
('a', 845),
('b', 155),
('c', 278),
('d', 359),
('e', 1143),
('f', 222),
('g', 187),
('h', 507),
('i', 791),
('j', 12),
('k', 67),
('l', 423),
('m', 288),
('n', 833),
('o', 791),
('p', 197),
('q', 8),
('r', 432),
('s', 700),
('t', 1043),
('u', 325),
('v', 111),
('w', 223),
('x', 7),
('y', 251),
]
.into_iter()
.collect();
assert_eq!(frequency::frequency(&DOSTOEVSKY, 4), expected);
}
// Poem by Friedrich Schiller. The corresponding music is the European Anthem.
const ODE_AN_DIE_FREUDE: [&str; 8] = [
"Freude schöner Götterfunken",
"Tochter aus Elysium,",
"Wir betreten feuertrunken,",
"Himmlische, dein Heiligtum!",
"Deine Zauber binden wieder",
"Was die Mode streng geteilt;",
"Alle Menschen werden Brüder,",
"Wo dein sanfter Flügel weilt.",
];
// Dutch national anthem
const WILHELMUS: [&str; 8] = [
"Wilhelmus van Nassouwe",
"ben ik, van Duitsen bloed,",
"den vaderland getrouwe",
"blijf ik tot in den dood.",
"Een Prinse van Oranje",
"ben ik, vrij, onverveerd,",
"den Koning van Hispanje",
"heb ik altijd geëerd.",
];
// American national anthem
const STAR_SPANGLED_BANNER: [&str; 8] = [
"O say can you see by the dawn's early light,",
"What so proudly we hailed at the twilight's last gleaming,",
"Whose broad stripes and bright stars through the perilous fight,",
"O'er the ramparts we watched, were so gallantly streaming?",
"And the rockets' red glare, the bombs bursting in air,",
"Gave proof through the night that our flag was still there;",
"O say does that star-spangled banner yet wave,",
"O'er the land of the free and the home of the brave?",
];
const DOSTOEVSKY: [&str; 4] = [
r#"
I am a sick man.... I am a spiteful man. I am an unattractive man.
I believe my liver is diseased. However, I know nothing at all about my disease, and do not
know for certain what ails me. I don't consult a doctor for it,
and never have, though I have a respect for medicine and doctors.
Besides, I am extremely superstitious, sufficiently so to respect medicine,
anyway (I am well-educated enough not to be superstitious, but I am superstitious).
No, I refuse to consult a doctor from spite.
That you probably will not understand. Well, I understand it, though.
Of course, I can't explain who it is precisely that I am mortifying in this case by my spite:
I am perfectly well aware that I cannot "pay out" the doctors by not consulting them;
I know better than anyone that by all this I am only injuring myself and no one else.
But still, if I don't consult a doctor it is from spite.
My liver is bad, well - let it get worse!
I have been going on like that for a long time - twenty years. Now I am forty.
I used to be in the government service, but am no longer.
I was a spiteful official. I was rude and took pleasure in being so.
I did not take bribes, you see, so I was bound to find a recompense in that, at least.
(A poor jest, but I will not scratch it out. I wrote it thinking it would sound very witty;
but now that I have seen myself that I only wanted to show off in a despicable way -
I will not scratch it out on purpose!) When petitioners used to come for
information to the table at which I sat, I used to grind my teeth at them,
and felt intense enjoyment when I succeeded in making anybody unhappy.
I almost did succeed. For the most part they were all timid people - of course,
they were petitioners. But of the uppish ones there was one officer in particular
I could not endure. He simply would not be humble, and clanked his sword in a disgusting way.
I carried on a feud with him for eighteen months over that sword. At last I got the better of him.
He left off clanking it. That happened in my youth, though. But do you know,
gentlemen, what was the chief point about my spite? Why, the whole point,
the real sting of it lay in the fact that continually, even in the moment of the acutest spleen,
I was inwardly conscious with shame that I was not only not a spiteful but not even an embittered man,
that I was simply scaring sparrows at random and amusing myself by it.
I might foam at the mouth, but bring me a doll to play with, give me a cup of tea with sugar in it,
and maybe I should be appeased. I might even be genuinely touched,
though probably I should grind my teeth at myself afterwards and lie awake at night with shame for
months after. That was my way. I was lying when I said just now that I was a spiteful official.
I was lying from spite. I was simply amusing myself with the petitioners and with the officer,
and in reality I never could become spiteful. I was conscious every moment in myself of many,
very many elements absolutely opposite to that. I felt them positively swarming in me,
these opposite elements. I knew that they had been swarming in me all my life and craving some outlet from me,
but I would not let them, would not let them, purposely would not let them come out.
They tormented me till I was ashamed: they drove me to convulsions and - sickened me, at last,
how they sickened me!
"#,
r#"
Gentlemen, I am joking, and I know myself that my jokes are not brilliant,
but you know one can take everything as a joke. I am, perhaps, jesting against the grain.
Gentlemen, I am tormented by questions; answer them for me. You, for instance, want to cure men of their
old habits and reform their will in accordance with science and good sense.
But how do you know, not only that it is possible, but also that it is
desirable to reform man in that way? And what leads you to the conclusion that man's
inclinations need reforming? In short, how do you know that such a reformation will be a benefit to man?
And to go to the root of the matter, why are you so positively convinced that not to act against
his real normal interests guaranteed by the conclusions of reason and arithmetic is certainly always
advantageous for man and must always be a law for mankind? So far, you know,
this is only your supposition. It may be the law of logic, but not the law of humanity.
You think, gentlemen, perhaps that I am mad? Allow me to defend myself. I agree that man
is pre-eminently a creative animal, predestined to strive consciously for an object and to engage in engineering -
that is, incessantly and eternally to make new roads, wherever
they may lead. But the reason why he wants sometimes to go off at a tangent may just be that he is
predestined to make the road, and perhaps, too, that however stupid the "direct"
practical man may be, the thought sometimes will occur to him that the road almost always does lead
somewhere, and that the destination it leads to is less important than the process
of making it, and that the chief thing is to save the well-conducted child from despising engineering,
and so giving way to the fatal idleness, which, as we all know,
is the mother of all the vices. Man likes to make roads and to create, that is a fact beyond dispute.
But why has he such a passionate love for destruction and chaos also?
Tell me that! But on that point I want to say a couple of words myself. May it not be that he loves
chaos and destruction (there can be no disputing that he does sometimes love it)
because he is instinctively afraid of attaining his object and completing the edifice he is constructing?
Who knows, perhaps he only loves that edifice from a distance, and is by no means
in love with it at close quarters; perhaps he only loves building it and does not want to live in it,
but will leave it, when completed, for the use of les animaux domestiques -
such as the ants, the sheep, and so on. Now the ants have quite a different taste.
They have a marvellous edifice of that pattern which endures for ever - the ant-heap.
With the ant-heap the respectable race of ants began and with the ant-heap they will probably end,
which does the greatest credit to their perseverance and good sense. But man is a frivolous and
incongruous creature, and perhaps, like a chess player, loves the process of the game, not the end of it.
And who knows (there is no saying with certainty), perhaps the only goal on earth
to which mankind is striving lies in this incessant process of attaining, in other words,
in life itself, and not in the thing to be attained, which must always be expressed as a formula,
as positive as twice two makes four, and such positiveness is not life, gentlemen,
but is the beginning of death.
"#,
r#"
But these are all golden dreams. Oh, tell me, who was it first announced,
who was it first proclaimed, that man only does nasty things because he does not know his own interests;
and that if he were enlightened, if his eyes were opened to his real normal interests,
man would at once cease to do nasty things, would at once become good and noble because,
being enlightened and understanding his real advantage, he would see his own advantage in the
good and nothing else, and we all know that not one man can, consciously, act against his own interests,
consequently, so to say, through necessity, he would begin doing good? Oh, the babe! Oh, the pure,
innocent child! Why, in the first place, when in all these thousands of years has there been a time
when man has acted only from his own interest? What is to be done with the millions of facts that bear
witness that men, consciously, that is fully understanding their real interests, have left them in the
background and have rushed headlong on another path, to meet peril and danger,
compelled to this course by nobody and by nothing, but, as it were, simply disliking the beaten track,
and have obstinately, wilfully, struck out another difficult, absurd way, seeking it almost in the darkness.
So, I suppose, this obstinacy and perversity were pleasanter to them than any advantage....
Advantage! What is advantage? And will you take it upon yourself to define with perfect accuracy in what the
advantage of man consists? And what if it so happens that a man's advantage, sometimes, not only may,
but even must, consist in his desiring in certain cases what is harmful to himself and not advantageous.
And if so, if there can be such a case, the whole principle falls into dust. What do you think -
are there such cases? You laugh; laugh away, gentlemen, but only answer me: have man's advantages been
reckoned up with perfect certainty? Are there not some which not only have not been included but cannot
possibly be included under any classification? You see, you gentlemen have, to the best of my knowledge,
taken your whole register of human advantages from the averages of statistical figures and
politico-economical formulas. Your advantages are prosperity, wealth, freedom, peace - and so on, and so on.
So that the man who should, for instance, go openly and knowingly in opposition to all that list would to your thinking,
and indeed mine, too, of course, be an obscurantist or an absolute madman: would not he? But, you know, this is
what is surprising: why does it so happen that all these statisticians, sages and lovers of humanity,
when they reckon up human advantages invariably leave out one? They don't even take it into their reckoning
in the form in which it should be taken, and the whole reckoning depends upon that. It would be no greater matter,
they would simply have to take it, this advantage, and add it to the list. But the trouble is, that this strange
advantage does not fall under any classification and is not in place in any list. I have a friend for instance ...
Ech! gentlemen, but of course he is your friend, too; and indeed there is no one, no one to whom he is not a friend!
"#,
r#"
Yes, but here I come to a stop! Gentlemen, you must excuse me for being over-philosophical;
it's the result of forty years underground! Allow me to indulge my fancy. You see, gentlemen, reason is an excellent thing,
there's no disputing that, but reason is nothing but reason and satisfies only the rational side of man's nature,
while will is a manifestation of the whole life, that is, of the whole human life including reason and all the impulses.
And although our life, in this manifestation of it, is often worthless, yet it is life and not simply extracting square roots.
Here I, for instance, quite naturally want to live, in order to satisfy all my capacities for life, and not simply my capacity
for reasoning, that is, not simply one twentieth of my capacity for life. What does reason know? Reason only knows what it has
succeeded in learning (some things, perhaps, it will never learn; this is a poor comfort, but why not say so frankly?)
and human nature acts as a whole, with everything that is in it, consciously or unconsciously, and, even it if goes wrong, it lives.
I suspect, gentlemen, that you are looking at me with compassion; you tell me again that an enlightened and developed man,
such, in short, as the future man will be, cannot consciously desire anything disadvantageous to himself, that that can be proved mathematically.
I thoroughly agree, it can - by mathematics. But I repeat for the hundredth time, there is one case, one only, when man may consciously, purposely,
desire what is injurious to himself, what is stupid, very stupid - simply in order to have the right to desire for himself even what is very stupid
and not to be bound by an obligation to desire only what is sensible. Of course, this very stupid thing, this caprice of ours, may be in reality,
gentlemen, more advantageous for us than anything else on earth, especially in certain cases. And in particular it may be more advantageous than
any advantage even when it does us obvious harm, and contradicts the soundest conclusions of our reason concerning our advantage -
for in any circumstances it preserves for us what is most precious and most important - that is, our personality, our individuality.
Some, you see, maintain that this really is the most precious thing for mankind; choice can, of course, if it chooses, be in agreement
with reason; and especially if this be not abused but kept within bounds. It is profitable and some- times even praiseworthy.
But very often, and even most often, choice is utterly and stubbornly opposed to reason ... and ... and ... do you know that that,
too, is profitable, sometimes even praiseworthy? Gentlemen, let us suppose that man is not stupid. (Indeed one cannot refuse to suppose that,
if only from the one consideration, that, if man is stupid, then who is wise?) But if he is not stupid, he is monstrously ungrateful!
Phenomenally ungrateful. In fact, I believe that the best definition of man is the ungrateful biped. But that is not all, that is not his worst defect;
his worst defect is his perpetual moral obliquity, perpetual - from the days of the Flood to the Schleswig-Holstein period.
"#,
];

View file

@ -0,0 +1,38 @@
{
"authors": [
"coriolinus"
],
"contributors": [
"cbzehner",
"ccouzens",
"cwhakes",
"efx",
"ErikSchierboom",
"hunger",
"lutostag",
"ocstl",
"PaulT89",
"petertseng",
"rofrol",
"rrredface",
"stringparser",
"TheDarkula",
"xakon",
"ZapAnton"
],
"files": {
"solution": [
"src/lib.rs",
"Cargo.toml"
],
"test": [
"tests/reverse_string.rs"
],
"example": [
".meta/example.rs"
]
},
"blurb": "Reverse a given string.",
"source": "Introductory challenge to reverse an input string",
"source_url": "https://medium.freecodecamp.org/how-to-reverse-a-string-in-javascript-in-3-different-ways-75e4763c68cb"
}

2
rust/reverse-string/.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
/target
Cargo.lock

View file

@ -0,0 +1,12 @@
[package]
name = "reverse_string"
version = "0.1.0"
edition = "2024"
# Not all libraries from crates.io are available in Exercism's test runner.
# The full list of available libraries is here:
# https://github.com/exercism/rust-test-runner/blob/main/local-registry/Cargo.toml
[dependencies]
[features]
grapheme = []

View file

@ -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

View file

@ -0,0 +1,68 @@
# Reverse String
Welcome to Reverse String on Exercism's Rust Track.
If you need help running the tests or submitting your code, check out `HELP.md`.
## Introduction
Reversing strings (reading them from right to left, rather than from left to right) is a surprisingly common task in programming.
For example, in bioinformatics, reversing the sequence of DNA or RNA strings is often important for various analyses, such as finding complementary strands or identifying palindromic sequences that have biological significance.
## Instructions
Your task is to reverse a given string.
Some examples:
- Turn `"stressed"` into `"desserts"`.
- Turn `"strops"` into `"sports"`.
- Turn `"racecar"` into `"racecar"`.
## Bonus
Test your function on this string: `uüu` and see what happens.
Try to write a function that properly reverses this string.
Hint: grapheme clusters
To get the bonus test to run, remove the ignore flag (`#[ignore]`) from the last test, and execute the tests with:
```bash
cargo test --features grapheme
```
You will need to use external libraries (a `crate` in rust lingo) for the bonus task.
A good place to look for those is [crates.io](https://crates.io/), the official repository of crates.
Please remember that only a limited set of crates is supported by our test runner.
The full list is in [this file](https://github.com/exercism/rust-test-runner/blob/main/local-registry/Cargo.toml) under the section `[dependencies]`.
[Check the documentation](https://doc.rust-lang.org/cargo/guide/dependencies.html) for instructions on how to use external crates in your projects.
## Source
### Created by
- @coriolinus
### Contributed to by
- @cbzehner
- @ccouzens
- @cwhakes
- @efx
- @ErikSchierboom
- @hunger
- @lutostag
- @ocstl
- @PaulT89
- @petertseng
- @rofrol
- @rrredface
- @stringparser
- @TheDarkula
- @xakon
- @ZapAnton
### Based on
Introductory challenge to reverse an input string - https://medium.freecodecamp.org/how-to-reverse-a-string-in-javascript-in-3-different-ways-75e4763c68cb

View file

@ -0,0 +1,7 @@
pub fn reverse(input: &str) -> String {
let mut res = String::new();
for ch in input.chars().rev() {
res.push(ch);
}
res
}

View file

@ -0,0 +1,83 @@
use reverse_string::*;
#[test]
fn an_empty_string() {
let input = "";
let output = reverse(input);
let expected = "";
assert_eq!(output, expected);
}
#[test]
// #[ignore]
fn a_word() {
let input = "robot";
let output = reverse(input);
let expected = "tobor";
assert_eq!(output, expected);
}
#[test]
// #[ignore]
fn a_capitalized_word() {
let input = "Ramen";
let output = reverse(input);
let expected = "nemaR";
assert_eq!(output, expected);
}
#[test]
// #[ignore]
fn a_sentence_with_punctuation() {
let input = "I'm hungry!";
let output = reverse(input);
let expected = "!yrgnuh m'I";
assert_eq!(output, expected);
}
#[test]
// #[ignore]
fn a_palindrome() {
let input = "racecar";
let output = reverse(input);
let expected = "racecar";
assert_eq!(output, expected);
}
#[test]
// #[ignore]
fn an_even_sized_word() {
let input = "drawer";
let output = reverse(input);
let expected = "reward";
assert_eq!(output, expected);
}
#[test]
// #[ignore]
fn wide_characters() {
let input = "子猫";
let output = reverse(input);
let expected = "猫子";
assert_eq!(output, expected);
}
#[test]
// #[ignore]
#[cfg(feature = "grapheme")]
fn grapheme_cluster_with_pre_combined_form() {
let input = "Würstchenstand";
let output = reverse(input);
let expected = "dnatsnehctsrüW";
assert_eq!(output, expected);
}
#[test]
// #[ignore]
#[cfg(feature = "grapheme")]
fn grapheme_clusters() {
let input = "ผู้เขียนโปรแกรม";
let output = reverse(input);
let expected = "มรกแรปโนยขีเผู้";
assert_eq!(output, expected);
}

View file

@ -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"
}

2
rust/space-age/.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
/target
Cargo.lock

View file

@ -0,0 +1,9 @@
[package]
name = "space_age"
version = "0.1.0"
edition = "2024"
# Not all libraries from crates.io are available in Exercism's test runner.
# The full list of available libraries is here:
# https://github.com/exercism/rust-test-runner/blob/main/local-registry/Cargo.toml
[dependencies]

89
rust/space-age/HELP.md Normal file
View file

@ -0,0 +1,89 @@
# 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
Head to [the forum](https://forum.exercism.org/c/programming/rust/) and create a post to provide feedback about an exercise or if you want to help implement new exercises.
Members of the rust track team are happy to help!
The GitHub [track repository][github] is the home for all of the Rust exercises.
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
rust/space-age/README.md Normal file
View file

@ -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

71
rust/space-age/src/lib.rs Normal file
View file

@ -0,0 +1,71 @@
// The code below is a stub. Just enough to satisfy the compiler.
// In order to pass the tests you can add-to or change any of this code.
#[derive(Debug)]
pub struct Duration {
seconds: u64,
}
impl From<u64> for Duration {
fn from(s: u64) -> Self {
Self { seconds: s }
}
}
pub trait Planet {
fn years_during(d: &Duration) -> f64 {
(d.seconds as f64 / 60.0 / 60.0 / 24.0) / 365.25 / Self::period()
}
fn period() -> f64;
}
pub struct Mercury;
pub struct Venus;
pub struct Earth;
pub struct Mars;
pub struct Jupiter;
pub struct Saturn;
pub struct Uranus;
pub struct Neptune;
impl Planet for Mercury {
fn period() -> f64 {
0.2408467
}
}
impl Planet for Venus {
fn period() -> f64 {
0.61519726
}
}
impl Planet for Earth {
fn period() -> f64 {
1.0
}
}
impl Planet for Mars {
fn period() -> f64 {
1.8808158
}
}
impl Planet for Jupiter {
fn period() -> f64 {
11.862615
}
}
impl Planet for Saturn {
fn period() -> f64 {
29.447498
}
}
impl Planet for Uranus {
fn period() -> f64 {
84.016846
}
}
impl Planet for Neptune {
fn period() -> f64 {
164.79132
}
}

View file

@ -0,0 +1,81 @@
use space_age::*;
fn assert_in_delta(expected: f64, actual: f64) {
let diff: f64 = (expected - actual).abs();
let delta: f64 = 0.01;
if diff > delta {
panic!("Your result of {actual} should be within {delta} of the expected result {expected}")
}
}
#[test]
fn age_on_earth() {
let seconds = 1_000_000_000;
let duration = Duration::from(seconds);
let output = Earth::years_during(&duration);
let expected = 31.69;
assert_in_delta(expected, output);
}
#[test]
fn age_on_mercury() {
let seconds = 2_134_835_688;
let duration = Duration::from(seconds);
let output = Mercury::years_during(&duration);
let expected = 280.88;
assert_in_delta(expected, output);
}
#[test]
fn age_on_venus() {
let seconds = 189_839_836;
let duration = Duration::from(seconds);
let output = Venus::years_during(&duration);
let expected = 9.78;
assert_in_delta(expected, output);
}
#[test]
fn age_on_mars() {
let seconds = 2_129_871_239;
let duration = Duration::from(seconds);
let output = Mars::years_during(&duration);
let expected = 35.88;
assert_in_delta(expected, output);
}
#[test]
fn age_on_jupiter() {
let seconds = 901_876_382;
let duration = Duration::from(seconds);
let output = Jupiter::years_during(&duration);
let expected = 2.41;
assert_in_delta(expected, output);
}
#[test]
fn age_on_saturn() {
let seconds = 2_000_000_000;
let duration = Duration::from(seconds);
let output = Saturn::years_during(&duration);
let expected = 2.15;
assert_in_delta(expected, output);
}
#[test]
fn age_on_uranus() {
let seconds = 1_210_123_456;
let duration = Duration::from(seconds);
let output = Uranus::years_during(&duration);
let expected = 0.46;
assert_in_delta(expected, output);
}
#[test]
fn age_on_neptune() {
let seconds = 1_821_023_456;
let duration = Duration::from(seconds);
let output = Neptune::years_during(&duration);
let expected = 0.35;
assert_in_delta(expected, output);
}

View file

@ -0,0 +1,37 @@
{
"authors": [
"EduardoBautista"
],
"contributors": [
"ashleygwilliams",
"coriolinus",
"cwhakes",
"eddyp",
"EduardoBautista",
"efx",
"ErikSchierboom",
"IanWhitney",
"kytrinyx",
"lutostag",
"mkantor",
"nfiles",
"petertseng",
"rofrol",
"stringparser",
"xakon",
"ZapAnton"
],
"files": {
"solution": [
"src/lib.rs",
"Cargo.toml"
],
"test": [
"tests/sublist.rs"
],
"example": [
".meta/example.rs"
]
},
"blurb": "Write a function to determine if a list is a sublist of another list."
}

2
rust/sublist/.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
/target
Cargo.lock

9
rust/sublist/Cargo.toml Normal file
View file

@ -0,0 +1,9 @@
[package]
name = "sublist"
version = "0.1.0"
edition = "2024"
# Not all libraries from crates.io are available in Exercism's test runner.
# The full list of available libraries is here:
# https://github.com/exercism/rust-test-runner/blob/main/local-registry/Cargo.toml
[dependencies]

89
rust/sublist/HELP.md Normal file
View file

@ -0,0 +1,89 @@
# 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
Head to [the forum](https://forum.exercism.org/c/programming/rust/) and create a post to provide feedback about an exercise or if you want to help implement new exercises.
Members of the rust track team are happy to help!
The GitHub [track repository][github] is the home for all of the Rust exercises.
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

56
rust/sublist/README.md Normal file
View file

@ -0,0 +1,56 @@
# Sublist
Welcome to Sublist on Exercism's Rust Track.
If you need help running the tests or submitting your code, check out `HELP.md`.
## Instructions
Given any two lists `A` and `B`, determine if:
- List `A` is equal to list `B`; or
- List `A` contains list `B` (`A` is a superlist of `B`); or
- List `A` is contained by list `B` (`A` is a sublist of `B`); or
- None of the above is true, thus lists `A` and `B` are unequal
Specifically, list `A` is equal to list `B` if both lists have the same values in the same order.
List `A` is a superlist of `B` if `A` contains a contiguous sub-sequence of values equal to `B`.
List `A` is a sublist of `B` if `B` contains a contiguous sub-sequence of values equal to `A`.
Examples:
- If `A = []` and `B = []` (both lists are empty), then `A` and `B` are equal
- If `A = [1, 2, 3]` and `B = []`, then `A` is a superlist of `B`
- If `A = []` and `B = [1, 2, 3]`, then `A` is a sublist of `B`
- If `A = [1, 2, 3]` and `B = [1, 2, 3, 4, 5]`, then `A` is a sublist of `B`
- If `A = [3, 4, 5]` and `B = [1, 2, 3, 4, 5]`, then `A` is a sublist of `B`
- If `A = [3, 4]` and `B = [1, 2, 3, 4, 5]`, then `A` is a sublist of `B`
- If `A = [1, 2, 3]` and `B = [1, 2, 3]`, then `A` and `B` are equal
- If `A = [1, 2, 3, 4, 5]` and `B = [2, 3, 4]`, then `A` is a superlist of `B`
- If `A = [1, 2, 4]` and `B = [1, 2, 3, 4, 5]`, then `A` and `B` are unequal
- If `A = [1, 2, 3]` and `B = [1, 3, 2]`, then `A` and `B` are unequal
## Source
### Created by
- @EduardoBautista
### Contributed to by
- @ashleygwilliams
- @coriolinus
- @cwhakes
- @eddyp
- @EduardoBautista
- @efx
- @ErikSchierboom
- @IanWhitney
- @kytrinyx
- @lutostag
- @mkantor
- @nfiles
- @petertseng
- @rofrol
- @stringparser
- @xakon
- @ZapAnton

40
rust/sublist/src/lib.rs Normal file
View file

@ -0,0 +1,40 @@
#[derive(Debug, PartialEq, Eq)]
pub enum Comparison {
Equal,
Sublist,
Superlist,
Unequal,
}
trait SublistSearcher<T> {
fn contains_slice(&self, sublist: &[T]) -> bool;
}
impl<T> SublistSearcher<T> for [T]
where
T: PartialEq,
{
fn contains_slice(&self, sublist: &[T]) -> bool {
self.is_empty() && sublist.is_empty()
|| (!sublist.is_empty() && self.windows(sublist.len()).any(|x| x == sublist))
}
}
pub fn sublist(first_list: &[i32], second_list: &[i32]) -> Comparison {
match (first_list.len(), second_list.len()) {
(len_1, len_2) if len_1 == len_2 && first_list == second_list => Comparison::Equal,
(len_1, len_2)
if second_list.is_empty() && !first_list.is_empty()
|| (len_1 > len_2 && first_list.contains_slice(second_list)) =>
{
Comparison::Superlist
}
(len_1, len_2)
if first_list.is_empty() && !second_list.is_empty()
|| (len_1 < len_2 && second_list.contains_slice(first_list)) =>
{
Comparison::Sublist
}
_ => Comparison::Unequal,
}
}

View file

@ -0,0 +1,163 @@
use sublist::*;
#[test]
fn empty_lists() {
let list_one: &[i32] = &[];
let list_two: &[i32] = &[];
let output = sublist(list_one, list_two);
let expected = Comparison::Equal;
assert_eq!(output, expected);
}
#[test]
fn empty_list_within_non_empty_list() {
let list_one: &[i32] = &[];
let list_two: &[i32] = &[1, 2, 3];
let output = sublist(list_one, list_two);
let expected = Comparison::Sublist;
assert_eq!(output, expected);
}
#[test]
fn non_empty_list_contains_empty_list() {
let list_one: &[i32] = &[1, 2, 3];
let list_two: &[i32] = &[];
let output = sublist(list_one, list_two);
let expected = Comparison::Superlist;
assert_eq!(output, expected);
}
#[test]
fn list_equals_itself() {
let list_one: &[i32] = &[1, 2, 3];
let list_two: &[i32] = &[1, 2, 3];
let output = sublist(list_one, list_two);
let expected = Comparison::Equal;
assert_eq!(output, expected);
}
#[test]
fn different_lists() {
let list_one: &[i32] = &[1, 2, 3];
let list_two: &[i32] = &[2, 3, 4];
let output = sublist(list_one, list_two);
let expected = Comparison::Unequal;
assert_eq!(output, expected);
}
#[test]
fn false_start() {
let list_one: &[i32] = &[1, 2, 5];
let list_two: &[i32] = &[0, 1, 2, 3, 1, 2, 5, 6];
let output = sublist(list_one, list_two);
let expected = Comparison::Sublist;
assert_eq!(output, expected);
}
#[test]
fn consecutive() {
let list_one: &[i32] = &[1, 1, 2];
let list_two: &[i32] = &[0, 1, 1, 1, 2, 1, 2];
let output = sublist(list_one, list_two);
let expected = Comparison::Sublist;
assert_eq!(output, expected);
}
#[test]
fn sublist_at_start() {
let list_one: &[i32] = &[0, 1, 2];
let list_two: &[i32] = &[0, 1, 2, 3, 4, 5];
let output = sublist(list_one, list_two);
let expected = Comparison::Sublist;
assert_eq!(output, expected);
}
#[test]
fn sublist_in_middle() {
let list_one: &[i32] = &[2, 3, 4];
let list_two: &[i32] = &[0, 1, 2, 3, 4, 5];
let output = sublist(list_one, list_two);
let expected = Comparison::Sublist;
assert_eq!(output, expected);
}
#[test]
fn sublist_at_end() {
let list_one: &[i32] = &[3, 4, 5];
let list_two: &[i32] = &[0, 1, 2, 3, 4, 5];
let output = sublist(list_one, list_two);
let expected = Comparison::Sublist;
assert_eq!(output, expected);
}
#[test]
fn at_start_of_superlist() {
let list_one: &[i32] = &[0, 1, 2, 3, 4, 5];
let list_two: &[i32] = &[0, 1, 2];
let output = sublist(list_one, list_two);
let expected = Comparison::Superlist;
assert_eq!(output, expected);
}
#[test]
fn in_middle_of_superlist() {
let list_one: &[i32] = &[0, 1, 2, 3, 4, 5];
let list_two: &[i32] = &[2, 3];
let output = sublist(list_one, list_two);
let expected = Comparison::Superlist;
assert_eq!(output, expected);
}
#[test]
fn at_end_of_superlist() {
let list_one: &[i32] = &[0, 1, 2, 3, 4, 5];
let list_two: &[i32] = &[3, 4, 5];
let output = sublist(list_one, list_two);
let expected = Comparison::Superlist;
assert_eq!(output, expected);
}
#[test]
fn first_list_missing_element_from_second_list() {
let list_one: &[i32] = &[1, 3];
let list_two: &[i32] = &[1, 2, 3];
let output = sublist(list_one, list_two);
let expected = Comparison::Unequal;
assert_eq!(output, expected);
}
#[test]
fn second_list_missing_element_from_first_list() {
let list_one: &[i32] = &[1, 2, 3];
let list_two: &[i32] = &[1, 3];
let output = sublist(list_one, list_two);
let expected = Comparison::Unequal;
assert_eq!(output, expected);
}
#[test]
fn first_list_missing_additional_digits_from_second_list() {
let list_one: &[i32] = &[1, 2];
let list_two: &[i32] = &[1, 22];
let output = sublist(list_one, list_two);
let expected = Comparison::Unequal;
assert_eq!(output, expected);
}
#[test]
fn order_matters_to_a_list() {
let list_one: &[i32] = &[1, 2, 3];
let list_two: &[i32] = &[3, 2, 1];
let output = sublist(list_one, list_two);
let expected = Comparison::Unequal;
assert_eq!(output, expected);
}
#[test]
fn same_digits_but_different_numbers() {
let list_one: &[i32] = &[1, 0, 1];
let list_two: &[i32] = &[10, 1];
let output = sublist(list_one, list_two);
let expected = Comparison::Unequal;
assert_eq!(output, expected);
}

View file

@ -0,0 +1,19 @@
{
"authors": [
"vaeng"
],
"files": {
"solution": [
"hello-world.sql"
],
"test": [
"hello-world_test.sql"
],
"example": [
".meta/example.sql"
]
},
"blurb": "Exercism's classic introductory exercise. Just say \"Hello, World!\".",
"source": "This is an exercise to introduce users to using Exercism",
"source_url": "https://en.wikipedia.org/wiki/%22Hello,_world!%22_program"
}

View file

@ -0,0 +1,40 @@
# Help
## Running the tests
Navigate to the directory containing the appropriate `${slug}_test.sql` file, where `${slug}` is the name of the exercise, using hyphens instead of spaces and all lowercase (e.g. `hello-world_test.sql` for the `Hello World` exercise).
```bash
sqlite3 -bail < ${slug}_test.sql
```
You can use `SELECT` statements for debugging.
The output will be forwarded to `user_output.md` and shown in the web-editor if tests fail.
You can find more information in the [sqlite track docs about testing](https://exercism.org/docs/tracks/sqlite/tests).
## Submitting your solution
You can submit your solution using the `exercism submit hello-world.sql` 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 [SQLite track's documentation](https://exercism.org/docs/tracks/sqlite)
- The [SQLite track's programming category on the forum](https://forum.exercism.org/c/programming/sqlite)
- [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.
If you're stuck on something, it may help to look at some of the [available resources](https://exercism.org/docs/tracks/sqlite/resources) or ask [The Exercism Community on Discord](https://exercism.org/r/discord).
Additionally, [StackOverflow](http://stackoverflow.com/questions/tagged/sqlite) is a good spot to search for your problem/question to see if it has been answered already.
If not, you can always [ask](https://stackoverflow.com/help/how-to-ask) or [answer](https://stackoverflow.com/help/how-to-answer) someone else's question.

View file

@ -0,0 +1,31 @@
# Hello World
Welcome to Hello World on Exercism's SQLite Track.
If you need help running the tests or submitting your code, check out `HELP.md`.
## Instructions
The classical introductory exercise.
Just say "Hello, World!".
["Hello, World!"][hello-world] is the traditional first program for beginning programming in a new language or environment.
The objectives are simple:
- Modify the provided code so that it produces the string "Hello, World!".
- Run the test suite and make sure that it succeeds.
- Submit your solution and check it at the website.
If everything goes well, you will be ready to fetch your first real exercise.
[hello-world]: https://en.wikipedia.org/wiki/%22Hello,_world!%22_program
## Source
### Created by
- @vaeng
### Based on
This is an exercise to introduce users to using Exercism - https://en.wikipedia.org/wiki/%22Hello,_world!%22_program

View file

@ -0,0 +1,3 @@
DROP TABLE IF EXISTS hello_world;
CREATE TABLE hello_world (greeting TEXT);

View file

@ -0,0 +1,4 @@
INSERT INTO
hello_world (greeting)
VALUES
('Hello, World!');

View file

@ -0,0 +1,28 @@
-- Setup test table and read in student solution:
.read ./test_setup.sql
-- Test cases:
INSERT INTO
tests (name, uuid, expected)
VALUES
(
'Say Hi!',
'af9ffe10-dc13-42d8-a742-e7bdafac449d',
'Hello, World!'
);
-- Comparison of user input and the tests updates the status for each test:
UPDATE tests
SET
status = 'pass'
FROM
(
SELECT
greeting
FROM
hello_world
) AS actual
WHERE
actual.greeting = tests.expected;
-- Write results and debug info:
.read ./test_reporter.sql

View file

@ -0,0 +1,37 @@
-- Upadate message for failed tests to give helpful information:
UPDATE tests
SET
message = (
'Greeting' || ' is "' || COALESCE(actual.greeting, 'NULL') || '" but should be "' || tests.expected || '"'
)
FROM
(
SELECT
greeting
FROM
hello_world
) AS actual
WHERE
tests.status = 'fail';
-- Save results to ./output.json (needed by the online test-runner)
.mode json
.once './output.json'
SELECT
name,
status,
message,
output,
test_code,
task_id
FROM
tests;
-- Display test results in readable form for the student:
.mode table
SELECT
name,
status,
message
FROM
tests;

View file

@ -0,0 +1,23 @@
-- Create database:
.read ./create_fixture.sql
-- Read user student solution and save any output as markdown in user_output.md:
.mode markdown
.output user_output.md
.read ./hello-world.sql
.output
-- Create a clean testing environment:
DROP TABLE IF EXISTS main.tests;
CREATE TABLE IF NOT EXISTS main.tests (
-- uuid and name (description) are taken from the test.toml file
uuid TEXT PRIMARY KEY,
name TEXT NOT NULL,
-- The following section is needed by the online test-runner
status TEXT DEFAULT 'fail',
message TEXT,
output TEXT,
test_code TEXT,
task_id INTEGER DEFAULT NULL,
-- Here are columns for the actual tests
expected TEXT NOT NULL
);

View file

@ -0,0 +1,14 @@
{
"root": true,
"extends": "@exercism/eslint-config-javascript",
"env": {
"jest": true
},
"overrides": [
{
"files": [".meta/proof.ci.js", ".meta/exemplar.js", "*.spec.js"],
"excludedFiles": ["custom.spec.js"],
"extends": "@exercism/eslint-config-javascript/maintainers"
}
]
}

View file

@ -0,0 +1,28 @@
{
"authors": [
"bushidocodes"
],
"files": {
"solution": [
"hello-world.wat"
],
"test": [
"hello-world.spec.js"
],
"example": [
".meta/proof.ci.wat"
],
"invalidator": [
"package.json"
]
},
"blurb": "Exercism's classic introductory exercise. Just say \"Hello, World!\".",
"source": "This is an exercise to introduce users to using Exercism",
"source_url": "https://en.wikipedia.org/wiki/%22Hello,_world!%22_program",
"custom": {
"version.tests.compatibility": "jest-27",
"flag.tests.task-per-describe": false,
"flag.tests.may-run-long": false,
"flag.tests.includes-optional": false
}
}

1
wasm/hello-world/.npmrc Normal file
View file

@ -0,0 +1 @@
audit=false

343
wasm/hello-world/HELP.md Normal file
View file

@ -0,0 +1,343 @@
# Help
## Running the tests
## Setup
Go through the setup [instructions for WebAssembly][docs-exercism-wasm] to install the necessary dependencies.
## Requirements
Install assignment dependencies:
```shell
# Using npm
npm install
# Alternatively using yarn
yarn
```
## Making the test suite pass
All exercises come with a test suite to help you validate your solution before submitting.
You can execute these tests by opening a command prompt in the exercise's directory, and then running:
```bash
# Using npm
npm test
# Alternatively using yarn
yarn test
```
In some test suites all tests but the first have been skipped.
Once you get a test passing, you can enable the next one by changing `xtest` to `test`.
## Writing custom tests
If you wish to write additional, custom, tests, create a new file `custom.spec.js`, and submit it with your solution together with the new file:
```shell
exercism submit numbers.wat custom.spec.js
```
[docs-exercism-wasm]: https://exercism.org/docs/tracks/wasm/installation
## Submitting your solution
You can submit your solution using the `exercism submit hello-world.wat` 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 [WebAssembly track's documentation](https://exercism.org/docs/tracks/wasm)
- The [WebAssembly track's programming category on the forum](https://forum.exercism.org/c/programming/wasm)
- [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.
To get help if you're having trouble, you can use one of the following resources:
- [/r/WebAssembly](https://www.reddit.com/r/WebAssembly/) is the WebAssembly subreddit.
- [Github issue tracker](https://github.com/exercism/wasm/issues) is where we track our development and maintenance of Javascript exercises in exercism. But if none of the above links help you, feel free to post an issue here.
## How to Debug
Unlike many languages, WebAssembly code does not automatically have access to global resources such as the console. Such functionality instead must be provided as imports.
In order to provide `console.log` like functionality and a few other niceties, the Exercism WebAssembly track exposes a standard library of functions across all exercises.
These functions must be imported at the top of your WebAssembly module and then can be called from within your WebAssembly code.
The `log_mem_*` functions expect to be able to access the linear memory of your WebAssembly module. By default, this is private state, so to make this accessible, you must export your linear memory under the export name `mem`. This is accomplished as follows:
```wasm
(memory (export "mem") 1)
```
## Logging Locals and Globals
We provide logging functions for each of the primitive WebAssembly types. This is useful for logging global and local variables.
### log_i32_s - Log a 32-bit signed integer to console
```wasm
(module
(import "console" "log_i32_s" (func $log_i32_s (param i32)))
(func $main
;; logs -1
(call $log_i32_s (i32.const -1))
)
)
```
### log_i32_u - Log a 32-bit unsigned integer to console
```wasm
(module
(import "console" "log_i32_u" (func $log_i32_u (param i32)))
(func $main
;; Logs 42 to console
(call $log_i32_u (i32.const 42))
)
)
```
### log_i64_s - Log a 64-bit signed integer to console
```wasm
(module
(import "console" "log_i64_s" (func $log_i64_s (param i64)))
(func $main
;; Logs -99 to console
(call $log_i32_u (i64.const -99))
)
)
```
### log_i64_u - Log a 64-bit unsigned integer to console
```wasm
(module
(import "console" "log_i64_u" (func $log_i64_u (param i64)))
(func $main
;; Logs 42 to console
(call $log_i64_u (i32.const 42))
)
)
```
### log_f32 - Log a 32-bit floating point number to console
```wasm
(module
(import "console" "log_f32" (func $log_f32 (param f32)))
(func $main
;; Logs 3.140000104904175 to console
(call $log_f32 (f32.const 3.14))
)
)
```
### log_f64 - Log a 64-bit floating point number to console
```wasm
(module
(import "console" "log_f64" (func $log_f64 (param f64)))
(func $main
;; Logs 3.14 to console
(call $log_f64 (f64.const 3.14))
)
)
```
## Logging from Linear Memory
WebAssembly Linear Memory is a byte-addressable array of values. This serves as the equivalent of virtual memory for WebAssembly programs
We provide logging functions to interpret a range of addresses within linear memory as static arrays of certain types. This acts similar to the TypedArrays of JavaScript. The length parameters are not measured in bytes. They are measured in the number of consecutive elements of the type associated with the function.
**In order for these functions to work, your WebAssembly module must declare and export its linear memory using the named export "mem"**
```wasm
(memory (export "mem") 1)
```
### log_mem_as_utf8 - Log a sequence of UTF8 characters to console
```wasm
(module
(import "console" "log_mem_as_utf8" (func $log_mem_as_utf8 (param $byteOffset i32) (param $length i32)))
(memory (export "mem") 1)
(data (i32.const 64) "Goodbye, Mars!")
(func $main
;; Logs "Goodbye, Mars!" to console
(call $log_mem_as_utf8 (i32.const 64) (i32.const 14))
)
)
```
### log_mem_as_i8 - Log a sequence of signed 8-bit integers to console
```wasm
(module
(import "console" "log_mem_as_i8" (func $log_mem_as_i8 (param $byteOffset i32) (param $length i32)))
(memory (export "mem") 1)
(func $main
(memory.fill (i32.const 128) (i32.const -42) (i32.const 10))
;; Logs an array of 10x -42 to console
(call $log_mem_as_u8 (i32.const 128) (i32.const 10))
)
)
```
### log_mem_as_u8 - Log a sequence of unsigned 8-bit integers to console
```wasm
(module
(import "console" "log_mem_as_u8" (func $log_mem_as_u8 (param $byteOffset i32) (param $length i32)))
(memory (export "mem") 1)
(func $main
(memory.fill (i32.const 128) (i32.const 42) (i32.const 10))
;; Logs an array of 10x 42 to console
(call $log_mem_as_u8 (i32.const 128) (i32.const 10))
)
)
```
### log_mem_as_i16 - Log a sequence of signed 16-bit integers to console
```wasm
(module
(import "console" "log_mem_as_i16" (func $log_mem_as_i16 (param $byteOffset i32) (param $length i32)))
(memory (export "mem") 1)
(func $main
(i32.store16 (i32.const 128) (i32.const -10000))
(i32.store16 (i32.const 130) (i32.const -10001))
(i32.store16 (i32.const 132) (i32.const -10002))
;; Logs [-10000, -10001, -10002] to console
(call $log_mem_as_i16 (i32.const 128) (i32.const 3))
)
)
```
### log_mem_as_u16 - Log a sequence of unsigned 16-bit integers to console
```wasm
(module
(import "console" "log_mem_as_u16" (func $log_mem_as_u16 (param $byteOffset i32) (param $length i32)))
(memory (export "mem") 1)
(func $main
(i32.store16 (i32.const 128) (i32.const 10000))
(i32.store16 (i32.const 130) (i32.const 10001))
(i32.store16 (i32.const 132) (i32.const 10002))
;; Logs [10000, 10001, 10002] to console
(call $log_mem_as_u16 (i32.const 128) (i32.const 3))
)
)
```
### log_mem_as_i32 - Log a sequence of signed 32-bit integers to console
```wasm
(module
(import "console" "log_mem_as_i32" (func $log_mem_as_i32 (param $byteOffset i32) (param $length i32)))
(memory (export "mem") 1)
(func $main
(i32.store (i32.const 128) (i32.const -10000000))
(i32.store (i32.const 132) (i32.const -10000001))
(i32.store (i32.const 136) (i32.const -10000002))
;; Logs [-10000000, -10000001, -10000002] to console
(call $log_mem_as_i32 (i32.const 128) (i32.const 3))
)
)
```
### log_mem_as_u32 - Log a sequence of unsigned 32-bit integers to console
```wasm
(module
(import "console" "log_mem_as_u32" (func $log_mem_as_u32 (param $byteOffset i32) (param $length i32)))
(memory (export "mem") 1)
(func $main
(i32.store (i32.const 128) (i32.const 100000000))
(i32.store (i32.const 132) (i32.const 100000001))
(i32.store (i32.const 136) (i32.const 100000002))
;; Logs [100000000, 100000001, 100000002] to console
(call $log_mem_as_u32 (i32.const 128) (i32.const 3))
)
)
```
### log_mem_as_i64 - Log a sequence of signed 64-bit integers to console
```wasm
(module
(import "console" "log_mem_as_i64" (func $log_mem_as_i64 (param $byteOffset i32) (param $length i32)))
(memory (export "mem") 1)
(func $main
(i64.store (i32.const 128) (i64.const -10000000000))
(i64.store (i32.const 136) (i64.const -10000000001))
(i64.store (i32.const 144) (i64.const -10000000002))
;; Logs [-10000000000, -10000000001, -10000000002] to console
(call $log_mem_as_i64 (i32.const 128) (i32.const 3))
)
)
```
### log_mem_as_u64 - Log a sequence of unsigned 64-bit integers to console
```wasm
(module
(import "console" "log_mem_as_u64" (func $log_mem_as_u64 (param $byteOffset i32) (param $length i32)))
(memory (export "mem") 1)
(func $main
(i64.store (i32.const 128) (i64.const 10000000000))
(i64.store (i32.const 136) (i64.const 10000000001))
(i64.store (i32.const 144) (i64.const 10000000002))
;; Logs [10000000000, 10000000001, 10000000002] to console
(call $log_mem_as_u64 (i32.const 128) (i32.const 3))
)
)
```
### log_mem_as_u64 - Log a sequence of 32-bit floating point numbers to console
```wasm
(module
(import "console" "log_mem_as_f32" (func $log_mem_as_f32 (param $byteOffset i32) (param $length i32)))
(memory (export "mem") 1)
(func $main
(f32.store (i32.const 128) (f32.const 3.14))
(f32.store (i32.const 132) (f32.const 3.14))
(f32.store (i32.const 136) (f32.const 3.14))
;; Logs [3.140000104904175, 3.140000104904175, 3.140000104904175] to console
(call $log_mem_as_u64 (i32.const 128) (i32.const 3))
)
)
```
### log_mem_as_f64 - Log a sequence of 64-bit floating point numbers to console
```wasm
(module
(import "console" "log_mem_as_f64" (func $log_mem_as_f64 (param $byteOffset i32) (param $length i32)))
(memory (export "mem") 1)
(f64.store (i32.const 128) (f64.const 3.14))
(f64.store (i32.const 136) (f64.const 3.14))
(f64.store (i32.const 144) (f64.const 3.14))
;; Logs [3.14, 3.14, 3.14] to console
(call $log_mem_as_u64 (i32.const 128) (i32.const 3))
)
)
```

21
wasm/hello-world/LICENSE Normal file
View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2021 Exercism
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View file

@ -0,0 +1,31 @@
# Hello World
Welcome to Hello World on Exercism's WebAssembly Track.
If you need help running the tests or submitting your code, check out `HELP.md`.
## Instructions
The classical introductory exercise.
Just say "Hello, World!".
["Hello, World!"][hello-world] is the traditional first program for beginning programming in a new language or environment.
The objectives are simple:
- Modify the provided code so that it produces the string "Hello, World!".
- Run the test suite and make sure that it succeeds.
- Submit your solution and check it at the website.
If everything goes well, you will be ready to fetch your first real exercise.
[hello-world]: https://en.wikipedia.org/wiki/%22Hello,_world!%22_program
## Source
### Created by
- @bushidocodes
### Based on
This is an exercise to introduce users to using Exercism - https://en.wikipedia.org/wiki/%22Hello,_world!%22_program

View file

@ -0,0 +1,4 @@
export default {
presets: ["@exercism/babel-preset-javascript"],
plugins: [],
};

View file

@ -0,0 +1,40 @@
import { compileWat, WasmRunner } from "@exercism/wasm-lib";
let wasmModule;
let currentInstance;
beforeAll(async () => {
try {
const watPath = new URL("./hello-world.wat", import.meta.url);
const { buffer } = await compileWat(watPath);
wasmModule = await WebAssembly.compile(buffer);
} catch (err) {
console.log(`Error compiling *.wat: \n${err}`);
process.exit(1);
}
});
describe("Hello World", () => {
beforeEach(async () => {
currentInstance = null;
if (!wasmModule) {
return Promise.reject();
}
try {
currentInstance = await new WasmRunner(wasmModule);
return Promise.resolve();
} catch (err) {
console.log(`Error instantiating WebAssembly module: ${err}`);
return Promise.reject();
}
});
test("Say Hi!", () => {
expect(currentInstance).toBeTruthy();
const [offset, length] = currentInstance.exports.hello();
expect(length).toBe(13);
const greeting = currentInstance.get_mem_as_utf8(offset, length);
expect(greeting).toBe("Hello, World!");
});
});

View file

@ -0,0 +1,16 @@
(module
(memory (export "mem") 1)
;; Initializes the WebAssembly Linear Memory with a UTF-8 string of 14 characters starting at offset 64
(data (i32.const 64) "Hello, World!")
;;
;; Return a greeting
;;
;; Note: The final number (currently “14”) must match the length of the new string!
;;
;; @returns {(i32, i32)} The offset and length of the greeting
(func (export "hello") (result i32 i32)
(i32.const 64) (i32.const 13)
)
)

View file

@ -0,0 +1,35 @@
{
"name": "@exercism/wasm-hello-world",
"description": "Exercism exercises in WebAssembly.",
"author": "Sean McBride",
"type": "module",
"private": true,
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/exercism/wasm",
"directory": "exercises/practice/hello-world"
},
"jest": {
"maxWorkers": 1
},
"devDependencies": {
"@babel/core": "^7.23.3",
"@exercism/babel-preset-javascript": "^0.4.0",
"@exercism/eslint-config-javascript": "^0.6.0",
"@types/jest": "^29.5.8",
"@types/node": "^20.9.1",
"babel-jest": "^29.7.0",
"core-js": "^3.33.2",
"eslint": "^8.54.0",
"jest": "^29.7.0"
},
"scripts": {
"test": "node --experimental-vm-modules node_modules/jest/bin/jest.js ./*",
"watch": "node --experimental-vm-modules node_modules/jest/bin/jest.js --watch ./*",
"lint": "eslint ."
},
"dependencies": {
"@exercism/wasm-lib": "^0.2.0"
}
}

1
yamlscript/.gitignore vendored Normal file
View file

@ -0,0 +1 @@
/.local/

View file

@ -1,25 +1,20 @@
{
"authors": [
"samsondstl"
"ingydotnet"
],
"contributors": [
"elyashiv",
"jackhughesweb",
"KevinWMatthews",
"patricksjackson",
"sturzl"
"m-dango"
],
"files": {
"solution": [
"hello_world.cpp",
"hello_world.h"
"hello-world.ys"
],
"test": [
"hello_world_test.cpp"
"hello-world-test.ys",
"Makefile"
],
"example": [
".meta/example.cpp",
".meta/example.h"
".meta/hello-world.ys"
]
},
"blurb": "Exercism's classic introductory exercise. Just say \"Hello, World!\".",

View file

@ -0,0 +1,127 @@
#!/env/bin/env bash
set -euo pipefail
intro-prompt() (
cat <<...
--------------------------------------------------------------------------------
This YAMLScript Exercism exercise requires the YAMLScript version $version
interpreter command file to be installed here:
$prefix/bin/ys
You can install it by pressing Enter now, or by running this command:
$make install-ys
This should only take a few seconds and you only need to do this once.
Other exercises will use the same file.
See https://yamlscript.org/doc/install/ for more YAMLScript installation info.
--------------------------------------------------------------------------------
Would you like to install the 'ys' file now?
...
printf "Press Enter to install. Ctl-C to Quit."; read -r
)
main() {
setup "$@"
install-from-local
$auto && intro-prompt
installed || install-from-release || true
installed || install-from-build || true
installed ||
die "Installing '$installed' failed. Giving up." \
"Consider filing an issue at: $gh_issue_url"
echo
echo 'Success!'
echo "$installed is now installed."
echo
}
installed() {
[[ -f $installed ]]
}
install-from-local() {
local path
path=$(command -v "$ysfq") || true
if [[ -f $path ]]; then
mkdir -p "$bin"
cp "$path" "$bin"/
ln -fs "$ysfq" "$bin/ys-0"
ln -fs "$ysfq" "$bin/ys"
(installed && $auto) && exit
true
fi
}
install-from-release() (
set -x
curl -s https://yamlscript.org/install |
BIN=1 VERSION="$version" PREFIX="$prefix" bash
)
install-from-build() (
cat <<...
The binary release installation failed.
We can attempt to build and install $ysfq now.
This can take from 1 to 5 minutes to complete.
...
printf "Press Enter to install. Ctl-C to Quit."; read -r
[[ -d /tmp && -w /tmp ]] ||
die "Can't write to /tmp" \
'Giving up.'
set -x
rm -fr "$yamlscript_clone"
git clone --branch="$version" "$yamlscript_repo" "$yamlscript_clone"
"$make" -C "$yamlscript_clone/ys" install PREFIX="$prefix"
)
setup() {
version=$1
prefix=$2
make=$3
auto=false
[[ ${4-} ]] && auto=true
[[ $version =~ ^0\.1\.[0-9]+$ ]] ||
die "Invalid YS_VERSION '$version'"
bin=$prefix/bin
ysfq=ys-$version
installed=$bin/$ysfq
if installed; then
echo "'$installed' is already installed."
exit
fi
yamlscript_repo=https://github.com/yaml/yamlscript
yamlscript_clone=/tmp/yamlscript-exercism
gh_issue_url=https://github.com/exercism/yamlscript/issues
}
die() {
printf '%s\n' "$@" >&2
exit 1
}
main "$@"

View file

@ -0,0 +1,49 @@
SHELL := bash
BASE := $(shell pwd)
export YS_VERSION := 0.1.96
YS_LOCAL_PREFIX := ../../../.local/v$(YS_VERSION)
ifeq (,$(shell [[ -d "$(YS_LOCAL_PREFIX)" ]] && echo ok))
YS_LOCAL_PREFIX := $(shell cd .. && pwd -P)/.local/v$(YS_VERSION)
endif
YS_LOCAL_BIN := $(YS_LOCAL_PREFIX)/bin
YS_BIN := $(YS_LOCAL_BIN)/ys-$(YS_VERSION)
YS_INSTALLER := .yamlscript/exercism-ys-installer
YS_INSTALLER_CMD := \
bash $(YS_INSTALLER) $(YS_VERSION) $(YS_LOCAL_PREFIX) $(MAKE)
TEST_FILE ?= $(wildcard *-test.ys)
export PATH := $(YS_LOCAL_BIN):$(PATH)
export YSPATH := $(BASE)
#-------------------------------------------------------------------------------
default:
@echo " No default make rule. Try 'make test'."
test: $(YS_BIN)
prove -v $(TEST_FILE)
install-ys:
@$(YS_INSTALLER_CMD)
uninstall-ys:
rm -fr $(YS_LOCAL_PREFIX)
#-------------------------------------------------------------------------------
ifdef EXERCISM_YAMLSCRIPT_GHA
$(YS_BIN):
else ifeq (/mnt/,$(dir $(BASE)))
$(YS_BIN):
else
$(YS_BIN):
@$(YS_INSTALLER_CMD) auto
endif

View file

@ -0,0 +1,87 @@
# Help
## Running the tests
To test your solution simply run:
```bash
make test
```
This will run the test file `<exercise-name>-test.ys` which contains all of the
tests that you will need to pass for your solution to be correct.
You should study the test file to understand exactly what your solution needs
to do.
> Note: The first time you run `make test` it will also make sure that the
> correct version of the `ys` YAMLScript interpreter is installed in the
> correct place.
If you run `make test` before changing any files, all the tests will fail.
This is the proper and expected behavior.
The normal exercise development process is to iteratively improve your
solution, running `make test` after each change, until all the tests pass.
If you want to only run a specific test (while concentrating on that part of the
solution), you can add this key/value pair to that test:
```yaml
ONLY: true
```
If you want to skip particular tests (while working on other parts of the
solution), you can add this key/value pair to those tests:
```yaml
SKIP: true
```
## Testing Prerequisites
YAMLScript currently runs on MacOS and Linux.
Your computer will need to have the following very common commands installed:
* `bash` - You can run the tests under any shell, but `bash` must be available.
* `make` - You must use GNU `make` to run the tests.
In some environments tt might have a different name than `make`.
Possibly `gmake`.
* `prove` - This program is part of any normal Perl installation.
* `curl` - Used to install ys if it is not already installed.
It is extremely likely that you already have all of these programs installed.
## Submitting your solution
You can submit your solution using the `exercism submit hello-world.ys` 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 [YAMLScript track's documentation](https://exercism.org/docs/tracks/yamlscript)
- The [YAMLScript track's programming category on the forum](https://forum.exercism.org/c/programming/yamlscript)
- [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.
If you need help with this YAMLScript exercise, try the following resources:
* [YAMLScript Documentation](https://yamlscript.org/doc/)
* [YAMLScript Examples - Rosetta Code](
https://rosettacode.org/wiki/Category:YAMLScript#mw-pages)
* [YAMLScript Matrix Chat](https://matrix.to/#/#chat-yamlscript:yaml.io)
* [YAMLScript Slack Chat](https://clojurians.slack.com/messages/C05HQFMTURF)
* [YAMLScript IRC Chat](https://web.libera.chat/?channel=yamlscript)
* [YAMLScript GitHub Discussions](
https://github.com/yaml/yamlscript/discussions)
* [YAMLScript on Stack Overflow](
https://stackoverflow.com/questions/tagged/yamlscript)

View file

@ -0,0 +1,8 @@
# This Makefile is a decoy to attempt to detect when a non-GNU make is being
# used and alert the user.
test:
@echo "You appear to be using a non-GNU version of the 'make' program."
@echo "The YAMLScript Exercism track requires you to use GNU make."
@echo "Please try 'make $@' again using GNU make."
@exit 1

View file

@ -1,6 +1,6 @@
# Hello World
Welcome to Hello World on Exercism's C++ Track.
Welcome to Hello World on Exercism's YAMLScript Track.
If you need help running the tests or submitting your code, check out `HELP.md`.
## Instructions
@ -24,15 +24,11 @@ If everything goes well, you will be ready to fetch your first real exercise.
### Created by
- @samsondstl
- @ingydotnet
### Contributed to by
- @elyashiv
- @jackhughesweb
- @KevinWMatthews
- @patricksjackson
- @sturzl
- @m-dango
### Based on

View file

@ -0,0 +1,11 @@
#!/usr/bin/env ys-0
use ys::taptest: :all
load: 'hello-world.ys'
test::
- name: Say Hi!
code: hello()
want: Hello, World!
done: 1

View file

@ -0,0 +1,4 @@
!YS-v0
defn hello():
'Hello, World!'