# Wrong counter in hashmap

I have a vector u8, and I try to count the number that occurs the maximum number of times:

``````use std::collections::HashMap;

fn main() {
let v:Vec<u8> = vec![1,2,3,6,7,8,9,4,3,5,4,6,7,8,3,5,6,2,3,4,5,6,7,5,6];
let a = exercise1(v);
println!("average - {}, middle - {}, max_count key - {}",a[0],a[1],a[2])
//println!("vec = {:?}",v);
}

pub fn exercise1(v: Vec<u8>) -> [u8; 3] {
let mut sum: u8 = 0;
let mut i = 0;
let mut map = HashMap::new();
for number in v.iter() {
sum += number;
i += 1;
let count = map.entry(number).or_insert(0);
*count +=1;
}
let average = sum/i as u8;
let j = i/2;
println!("{:?}", map);

let mut max_count: u8 =0;
for (_key, value) in &map {
//println!("{:?}:{:?}",key,value);
if value > &max_count {
max_count = *value;
}
}

println!("max_count = {:?}", max_count);

let mut max_key: u8 = 0;
for (_key, value) in &map {
//println!("{:?}:{:?}",key,value);
if value == &max_count {
max_key = **_key;
}
}

let a: [u8; 3]=[average,v[j],max_key];
return a;
}
``````

If I run the script:

``````eyegor@twdevel:~/devel/rust/study/exercises/exercise1\$ cargo run
Finished dev [unoptimized + debuginfo] target(s) in 0.01s
Running `target/debug/exercise1`
{3: 4, 8: 2, 5: 4, 7: 3, 2: 2, 1: 1, 9: 1, 4: 3, 6: 5}
max_count = 5
average - 5, middle - 7, max_count key - 6
``````

I've see, that max_count is 5 of number 6, but realy number 6 occurs only 4 times. Where is my misstake?

That seems to be wrong. Here's the playground illustrating it.

Realy. Thank You!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.