From 782efd032d44d6be90189b7e734476e08a65591e Mon Sep 17 00:00:00 2001 From: Ruan Comelli Date: Thu, 24 Aug 2023 18:58:32 -0300 Subject: [PATCH 1/2] ci: skip Rust checks in pre-commit hooks --- .pre-commit-config.yaml | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 37ec135..c5e4dee 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,7 +1,12 @@ repos: -- repo: https://github.com/doublify/pre-commit-rust - rev: v1.0 +# - repo: https://github.com/doublify/pre-commit-rust +# rev: v1.0 +# hooks: +# - id: fmt +# - id: cargo-check +# - id: clippy +- repo: https://github.com/pre-commit/pre-commit-hooks + rev: v4.4.0 hooks: - - id: fmt - - id: cargo-check - - id: clippy \ No newline at end of file + - id: end-of-file-fixer + - id: trailing-whitespace From 2308a8fc1c54008569fbb63700cf608eb2474b3a Mon Sep 17 00:00:00 2001 From: Ruan Comelli Date: Thu, 24 Aug 2023 18:58:41 -0300 Subject: [PATCH 2/2] refactor(exercise/armstrong-numbers): optimize implementation to use custom iterator type --- exercism/rust/armstrong-numbers/src/lib.rs | 42 ++++++++++++++++++---- 1 file changed, 36 insertions(+), 6 deletions(-) diff --git a/exercism/rust/armstrong-numbers/src/lib.rs b/exercism/rust/armstrong-numbers/src/lib.rs index 88cfc36..1134ddb 100644 --- a/exercism/rust/armstrong-numbers/src/lib.rs +++ b/exercism/rust/armstrong-numbers/src/lib.rs @@ -1,18 +1,48 @@ pub fn is_armstrong_number(num: u32) -> bool { - let digits = digits(num); - let exponent = digits.len() as u32; + let digits = Digits::new(num); + let exponent = digits.num_digits; if exponent >= 10 { + // skip the calculation if the exponent is too large return false; } - num == digits.iter().map(|digit| digit.pow(exponent)).sum() + num == Digits::new(num).map(|digit| digit.pow(exponent)).sum() } -fn digits(num: u32) -> Vec { +struct Digits { + num: u32, + num_digits: u32, +} + +impl Digits { + fn new(num: u32) -> Self { + Digits { + num, + num_digits: number_of_digits(num), + } + } +} + +impl Iterator for Digits { + type Item = u32; + + fn next(&mut self) -> Option { + if self.num_digits == 0 { + None + } else { + let digit = self.num % 10; + self.num /= 10; + self.num_digits -= 1; + Some(digit) + } + } +} + +fn number_of_digits(num: u32) -> u32 { if num < 10 { - vec![num] + 1 } else { - [vec![num % 10], digits(num / 10)].concat() + 1 + number_of_digits(num / 10) } }