Skip to content

Commit 0a47fcb

Browse files
committed
add feature - generate random problem
use "cargo run random" to generate a random problem.
1 parent 154bea6 commit 0a47fcb

File tree

1 file changed

+38
-2
lines changed

1 file changed

+38
-2
lines changed

src/main.rs

Lines changed: 38 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,18 @@ fn main() {
1616
if args.len() < 2 {
1717
panic!("problem id must be provided");
1818
}
19-
let id = &args[1];
20-
let id = id.parse::<u32>().expect(&format!("not a number: {}", id));
19+
let id_arg = &args[1];
20+
let mut id :u32 = 0;
21+
match id_arg.as_ref() {
22+
"random" => {
23+
println!("You select random mode.");
24+
id = get_random_id();
25+
println!("Generate random problem: {}", &id);
26+
},
27+
_ => {
28+
id = id_arg.parse::<u32>().expect(&format!("not a number: {}", id));
29+
}
30+
}
2131

2232
let problem = problem::get_problem(id)
2333
.expect(&format!("problem #{} not found", id));
@@ -58,6 +68,32 @@ fn main() {
5868
writeln!(lib_file, "mod {};", file_name);
5969
}
6070

71+
fn get_random_id() -> u32 {
72+
use std::fs;
73+
let paths = fs::read_dir("./src").unwrap();
74+
let mut solved_ids = Vec::new();
75+
76+
for path in paths {
77+
let path = path.unwrap().path();
78+
let s = path.to_str().unwrap();
79+
if s.chars().next().unwrap() != 'n' {
80+
continue;
81+
}
82+
let id = &s[7..11];
83+
let id = id.parse::<u32>().unwrap();
84+
solved_ids.push(id);
85+
}
86+
use rand::Rng;
87+
let mut rng = rand::thread_rng();
88+
loop {
89+
let res :u32 = rng.gen_range(1, 1106);
90+
if !solved_ids.contains(&res) {
91+
return res;
92+
}
93+
println!("Generate a random num ({}), but it is solved. Regenerate..", res);
94+
}
95+
}
96+
6197
fn parse_extra_use(code: &str) -> String {
6298
let mut extra_use_line = String::new();
6399
// a linked-list problem

0 commit comments

Comments
 (0)