0% found this document useful (0 votes)
11 views

Rust

The document reads in numbers from a user, stores them in a vector, and sorts the vector in ascending and descending order. It then separates the numbers into even and odd vectors. It calculates and prints the mean, median, and mode of the original number vector.
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Rust

The document reads in numbers from a user, stores them in a vector, and sorts the vector in ascending and descending order. It then separates the numbers into even and odd vectors. It calculates and prints the mean, median, and mode of the original number vector.
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

use std::io;

use std::collections::HashMap;

fn main() {
println!("Enter the number of elements in the array:");
let mut input = String::new();

io::stdin()
.read_line(&mut input)
.expect("Failed to read input.");

let num_elements: usize = input.trim().parse().expect("Please enter a valid


number.");
let mut array = Vec::new();

for i in 0..num_elements {
println!("Enter element at index {}:", i);
let mut input = String::new();
io::stdin()
.read_line(&mut input)
.expect("Failed to read input.");
let element: i32 = input.trim().parse().expect("Please enter a valid
number.");
array.push(element);
}
println!(" ");
println!("The entered array is: {:?}", array);

array.sort();
println!("The entered array in ascending order is : {:?}", array);

array.sort_by(|a, b| b.cmp(a));
println!("The entered array in descending order is: {:?}", array);

let mut even_numbers = Vec::new();


let mut odd_numbers = Vec::new();

for &num in &array {


if num % 2 == 0 {
even_numbers.push(num);
} else {
odd_numbers.push(num);
}
}

println!("The even numbers in the array: {:?}", even_numbers);


println!("The odd numbers in the array : {:?}", odd_numbers);

let mean = calculate_mean(&array);


let median = calculate_median(&array);
let mode = calculate_mode(&array);

println!("Mean: {}", mean);


println!("Median: {}", median);
println!("Mode: {}", mode);
}

fn calculate_mean(data: &[i32]) -> f64 {


let sum: i32 = data.iter().sum();
sum as f64 / data.len() as f64
}

fn calculate_median(data: &[i32]) -> f64 {


let mut sorted_data = data.to_vec();
sorted_data.sort();

let mid = data.len() / 2;


if data.len() % 2 == 0 {
(sorted_data[mid - 1] + sorted_data[mid]) as f64 / 2.0
} else {
sorted_data[mid] as f64
}
}

fn calculate_mode(data: &[i32]) -> i32 {


let mut frequency_map = HashMap::new();

for &item in data {


*frequency_map.entry(item).or_insert(0) += 1;
}

let mut mode = None;


let mut max_frequency = 0;

for (value, frequency) in frequency_map {


if frequency > max_frequency {
max_frequency = frequency;
mode = Some(value);
}
}

mode.unwrap()
}

You might also like