I thought that rewriting "Mathematical puzzles to train the programmer's brain" with Rust might be just right for preventing blurring.
Although it is not the main point, the subtle part of the setting of this quiz is that "rock-paper-scissors wins and loses" has nothing to do with "majority wins and losses". "If it's Choki 2 and Par 2, Choki wins," he said, confused where it wasn't the main line ...
Ruby
q01_2.rb
N = 100
cnt = 0
0.upto(N) do |left|
left.upto(N) do |right|
all = [left, right - left, N - right]
cnt += 1 if all.count(all.max) == 1
end
end
puts cnt
Rust
main.rs
fn main() {
let mut q01 = Q01{ num_of_people:100,};
let answer = q01.solve();
println!("{}", answer);
}
struct Q01 {
num_of_people:i64,
}
impl Q01 {
pub fn solve(&mut self) -> i64 {
let mut count = 0;
for left in 0..=self.num_of_people {
for right in left..=self.num_of_people {
let all = vec![left, right - left, self.num_of_people - right];
let max_value = all.iter().max().unwrap();
let c = all.iter().filter(|&v| *v == *max_value).count();
if c == 1 {
count += 1;
}
}
}
return count;
}
}
Is it like this? The maximum value and scan for Vec
need to be passed through ʻiter ()` once.
Recommended Posts