Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(exercise/armstrong-numbers): optimize implementation to use custom iterator type #21

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 10 additions & 5 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -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
- id: end-of-file-fixer
- id: trailing-whitespace
42 changes: 36 additions & 6 deletions exercism/rust/armstrong-numbers/src/lib.rs
Original file line number Diff line number Diff line change
@@ -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<u32> {
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<Self::Item> {
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)
}
}