|
| 1 | +// Copyright 2023 Google LLC |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +#![allow(unused_variables, dead_code)] |
| 16 | +//ANCHOR-solution |
| 17 | +use std::collections::HashMap; |
| 18 | +use std::hash::Hash; |
| 19 | + |
| 20 | +/// Counter counts the number of times each value of type T has been seen. |
| 21 | +struct Counter<T> { |
| 22 | + values: HashMap<T, u64>, |
| 23 | +} |
| 24 | + |
| 25 | +impl<T: Eq + Hash> Counter<T> { |
| 26 | + /// Create a new Counter. |
| 27 | + fn new() -> Self { |
| 28 | + Counter { values: HashMap::new() } |
| 29 | + } |
| 30 | + |
| 31 | + /// Count an occurrence of the given value. |
| 32 | + fn count(&mut self, value: T) { |
| 33 | + *self.values.entry(value).or_default() += 1; |
| 34 | + } |
| 35 | + |
| 36 | + /// Return the number of times the given value has been seen. |
| 37 | + fn times_seen(&self, value: T) -> u64 { |
| 38 | + self.values.get(&value).copied().unwrap_or_default() |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | +//ANCHOR-main |
| 43 | +fn main() { |
| 44 | + let mut ctr = Counter::new(); |
| 45 | + ctr.count(13); |
| 46 | + ctr.count(14); |
| 47 | + ctr.count(16); |
| 48 | + ctr.count(14); |
| 49 | + ctr.count(14); |
| 50 | + ctr.count(11); |
| 51 | + |
| 52 | + for i in 10..20 { |
| 53 | + println!("saw {} values equal to {}", ctr.times_seen(i), i); |
| 54 | + } |
| 55 | + |
| 56 | + let mut strctr = Counter::new(); |
| 57 | + strctr.count("apple"); |
| 58 | + strctr.count("orange"); |
| 59 | + strctr.count("apple"); |
| 60 | + println!("got {} apples", strctr.times_seen("apple")); |
| 61 | +} |
0 commit comments