From 705fc86e897b3947c91a08eb3d6385cf86f704dc Mon Sep 17 00:00:00 2001 From: xblakicex Date: Fri, 13 Jan 2023 19:02:42 +0100 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(worst=5Fbest=5Ftime=5Fcomplexi?= =?UTF-8?q?ty):=20add=20rust=20code?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../worst_best_time_complexity.rs | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 codes/rust/chapter_computational_complexity/worst_best_time_complexity.rs diff --git a/codes/rust/chapter_computational_complexity/worst_best_time_complexity.rs b/codes/rust/chapter_computational_complexity/worst_best_time_complexity.rs new file mode 100644 index 00000000..23c2d646 --- /dev/null +++ b/codes/rust/chapter_computational_complexity/worst_best_time_complexity.rs @@ -0,0 +1,43 @@ +// rand = "0.8.5" +/** + * File: time_complexity.cpp + * Created Time: 2023-01-13 + * Author: xBLACICEx (xBLACKICEx@outlook.com ) + */ + +// to compilse and run this singile file need: +// 1. cargo install cargo-single +// 2. cargo single run worst_best_time_complexity.rs + +use rand::seq::SliceRandom; +use rand::thread_rng; + +/* 生成一个数组,元素为 { 1, 2, ..., n },顺序被打乱 */ +fn random_numbers(n: i32) -> Vec { + // 生成数组 nums = { 1, 2, 3, ..., n } + let mut nums = (1..n + 1).collect::>(); + // 随机打乱数组元素 + nums.shuffle(&mut thread_rng()); + nums +} + +/* 查找数组 nums 中数字 1 所在索引 */ +fn find_one(nums: &[i32]) -> Option { + for i in 0..nums.len() { + if nums[i] == 1 { + return Some(i); + } + } + None +} + +/* Driver Code */ +fn main() { + for _ in 0..10 { + let n = 100; + let nums = random_numbers(n); + let index = find_one(&nums); + println!("\n数组 [ 1, 2, ..., n ] 被打乱后 = {:?}", nums); + println!("数字 1 的索引为 {:?}", index); + } +} \ No newline at end of file